31#define DEBUG_TYPE "ctx-instr-lower"
35 return !LibraryOptions.
get<InstrumentationOptions>()
36 .profile_context_root.empty();
42static auto StartCtx =
"__llvm_ctx_profile_start_context";
43static auto ReleaseCtx =
"__llvm_ctx_profile_release_context";
44static auto GetCtx =
"__llvm_ctx_profile_get_context";
51class CtxInstrumentationLowerer final {
54 Type *ContextNodeTy =
nullptr;
63 Constant *CannotBeRootInitializer =
nullptr;
75std::pair<uint32_t, uint32_t> getNumCountersAndCallsites(
const Function &
F) {
76 uint32_t NumCounters = 0;
77 uint32_t NumCallsites = 0;
78 for (
const auto &BB :
F) {
79 for (
const auto &
I : BB) {
82 static_cast<uint32_t
>(Incr->getNumCounters()->getZExtValue());
83 assert((!NumCounters ||
V == NumCounters) &&
84 "expected all llvm.instrprof.increment[.step] intrinsics to "
85 "have the same total nr of counters parameter");
89 static_cast<uint32_t
>(CSIntr->getNumCounters()->getZExtValue());
90 assert((!NumCallsites ||
V == NumCallsites) &&
91 "expected all llvm.instrprof.callsite intrinsics to have the "
92 "same total nr of callsites parameter");
96 if (NumCounters && NumCallsites)
97 return std::make_pair(NumCounters, NumCallsites);
101 return {NumCounters, NumCallsites};
105 F.getContext().emitError(
"[ctxprof] The function " +
F.getName() +
106 " was indicated as context root but " + Reason +
107 ", which is not supported.");
114CtxInstrumentationLowerer::CtxInstrumentationLowerer(
Module &M,
117 auto *
PointerTy = PointerType::get(
M.getContext(), 0);
118 auto *SanitizerMutexType = Type::getInt8Ty(
M.getContext());
119 auto *I32Ty = Type::getInt32Ty(
M.getContext());
120 auto *I64Ty = Type::getInt64Ty(
M.getContext());
122#define _PTRDECL(_, __) PointerTy,
123#define _VOLATILE_PTRDECL(_, __) PointerTy,
124#define _CONTEXT_ROOT PointerTy,
125#define _MUTEXDECL(_) SanitizerMutexType,
128 M.getContext(), {CTXPROF_FUNCTION_DATA(_PTRDECL, _CONTEXT_ROOT,
129 _VOLATILE_PTRDECL, _MUTEXDECL)});
132#undef _VOLATILE_PTRDECL
135#define _PTRDECL(_, __) Constant::getNullValue(PointerTy),
136#define _VOLATILE_PTRDECL(_, __) _PTRDECL(_, __)
137#define _MUTEXDECL(_) Constant::getNullValue(SanitizerMutexType),
138#define _CONTEXT_ROOT \
139 Constant::getIntegerValue( \
141 APInt(M.getDataLayout().getPointerTypeSizeInBits(PointerTy), 1U)),
147#undef _VOLATILE_PTRDECL
161 for (StringRef Fname : Opts.profile_context_root) {
162 if (
const auto *
F =
M.getFunction(Fname)) {
163 if (
F->isDeclaration())
165 ContextRootSet.insert(
F);
166 for (
const auto &BB : *
F)
167 for (
const auto &
I : BB)
169 if (CB->isMustTailCall())
170 emitUnsupportedRootError(*
F,
"it features musttail calls");
176 M.getOrInsertFunction(
196 FunctionType::get(Type::getVoidTy(
M.getContext()),
207 CallsiteInfoTLS->setThreadLocal(
true);
218 CtxInstrumentationLowerer Lowerer(M,
MAM);
221 Changed |= Lowerer.lowerFunction(
F);
225bool CtxInstrumentationLowerer::lowerFunction(
Function &
F) {
226 if (
F.isDeclaration())
236 if (ContextRootSet.contains(&
F))
237 emitUnsupportedRootError(
F,
"it does not return");
245 auto [NumCounters, NumCallsites] = getNumCountersAndCallsites(
F);
247 Value *Context =
nullptr;
248 Value *RealContext =
nullptr;
251 Value *TheRootFunctionData =
nullptr;
252 Value *ExpectedCalleeTLSAddr =
nullptr;
253 Value *CallsiteInfoTLSAddr =
nullptr;
254 const bool HasMusttail = [&
F]() {
258 if (CB->isMustTailCall())
263 if (HasMusttail && ContextRootSet.contains(&
F)) {
264 F.getContext().emitError(
265 "[ctx_prof] A function with musttail calls was explicitly requested as "
266 "root. That is not supported because we cannot instrument a return "
267 "instruction to release the context: " +
271 auto &Head =
F.getEntryBlock();
272 for (
auto &
I : Head) {
275 assert(Mark->getIndex()->isZero());
278 Builder.disableGEPCanonicalization();
285 {ContextNodeTy, ArrayType::get(Builder.getInt64Ty(), NumCounters),
286 ArrayType::get(Builder.getPtrTy(), NumCallsites)});
299 HasMusttail ? CannotBeRootInitializer
302 if (ContextRootSet.contains(&
F)) {
304 StartCtx, {TheRootFunctionData,
Guid, Builder.getInt32(NumCounters),
305 Builder.getInt32(NumCallsites)});
309 Context = Builder.CreateCall(GetCtx, {TheRootFunctionData, &
F,
Guid,
310 Builder.getInt32(NumCounters),
311 Builder.getInt32(NumCallsites)});
317 auto *CtxAsInt = Builder.CreatePtrToInt(
Context, Builder.getInt64Ty());
318 if (NumCallsites > 0) {
321 auto *
Index = Builder.CreateAnd(CtxAsInt, Builder.getInt64(1));
323 ExpectedCalleeTLSAddr = Builder.CreateGEP(
325 Builder.CreateThreadLocalAddress(ExpectedCalleeTLS), {Index});
326 CallsiteInfoTLSAddr = Builder.CreateGEP(
327 Builder.getInt32Ty(),
328 Builder.CreateThreadLocalAddress(CallsiteInfoTLS), {Index});
335 RealContext = Builder.CreateIntToPtr(
336 Builder.CreateAnd(CtxAsInt, Builder.getInt64(-2)),
345 <<
"Function doesn't have instrumentation, skipping";
350 bool ContextWasReleased =
false;
355 Builder.disableGEPCanonicalization();
356 switch (
Instr->getIntrinsicID()) {
357 case llvm::Intrinsic::instrprof_increment:
358 case llvm::Intrinsic::instrprof_increment_step: {
362 auto *
GEP = Builder.CreateGEP(
363 ThisContextType, RealContext,
364 {Builder.getInt32(0), Builder.getInt32(1), AsStep->getIndex()});
366 Builder.CreateAdd(Builder.CreateLoad(Builder.getInt64Ty(),
GEP),
370 case llvm::Intrinsic::instrprof_callsite:
375 Builder.CreateStore(CSIntrinsic->getCallee(), ExpectedCalleeTLSAddr,
387 Builder.CreateGEP(ThisContextType,
Context,
388 {Builder.getInt32(0), Builder.getInt32(2),
389 CSIntrinsic->getIndex()}),
390 CallsiteInfoTLSAddr,
true);
397 Builder.CreateCall(ReleaseCtx, {TheRootFunctionData});
398 ContextWasReleased =
true;
402 if (!HasMusttail && !ContextWasReleased)
404 "[ctx_prof] A function that doesn't have musttail calls was "
405 "instrumented but it has no `ret` "
406 "instructions above which to release the context: " +
415 if (
F.isDeclaration())
419 if (!
F.isWeakForLinker())
422 if (
F.hasFnAttribute(Attribute::AlwaysInline))
423 F.removeFnAttr(Attribute::AlwaysInline);
425 F.addFnAttr(Attribute::NoInline);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define CTXPROF_FUNCTION_DATA(PTRDECL, CONTEXT_PTR, VOLATILE_PTRDECL, MUTEXDECL)
The internal structure of FunctionData.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define _VOLATILE_PTRDECL(_, __)
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
This is an important base class in LLVM.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Implements a dense probed hash-table based set.
@ HiddenVisibility
The GV is hidden.
@ InternalLinkage
Rename collisions when linking (static functions).
@ ExternalLinkage
Externally visible function.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
A Module instance is used to store all the information related to an LLVM module.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
static LLVM_ABI bool isCtxIRPGOInstrEnabled(const cl::LibraryOptionsContext &LibraryOptions)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Represent a constant reference to a string, i.e.
Class to represent struct types.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM Value Representation.
LLVMContext & getContext() const
All values hold a context through their type.
Pass manager infrastructure for declaring and invalidating analyses.
static auto ExpectedCalleeTLS
NodeAddr< InstrNode * > Instr
This is an optimization pass for GlobalISel generic memory operations.
const InstrumentationOptions & getInstrumentationOptions(const LLVMContext &C)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
LLVM_ABI bool canReturn(const Function &F)
Return true if there is at least a path through which F can return, false if there is no such path.