31#define DEBUG_TYPE "ctx-instr-lower"
34 return !InstrumentationOptions::Global.profile_context_root.empty();
40static auto StartCtx =
"__llvm_ctx_profile_start_context";
41static auto ReleaseCtx =
"__llvm_ctx_profile_release_context";
42static auto GetCtx =
"__llvm_ctx_profile_get_context";
49class CtxInstrumentationLowerer final {
52 Type *ContextNodeTy =
nullptr;
61 Constant *CannotBeRootInitializer =
nullptr;
73std::pair<uint32_t, uint32_t> getNumCountersAndCallsites(
const Function &
F) {
74 uint32_t NumCounters = 0;
75 uint32_t NumCallsites = 0;
76 for (
const auto &BB :
F) {
77 for (
const auto &
I : BB) {
80 static_cast<uint32_t
>(Incr->getNumCounters()->getZExtValue());
81 assert((!NumCounters || V == NumCounters) &&
82 "expected all llvm.instrprof.increment[.step] intrinsics to "
83 "have the same total nr of counters parameter");
87 static_cast<uint32_t
>(CSIntr->getNumCounters()->getZExtValue());
88 assert((!NumCallsites || V == NumCallsites) &&
89 "expected all llvm.instrprof.callsite intrinsics to have the "
90 "same total nr of callsites parameter");
94 if (NumCounters && NumCallsites)
95 return std::make_pair(NumCounters, NumCallsites);
99 return {NumCounters, NumCallsites};
103 F.getContext().emitError(
"[ctxprof] The function " +
F.getName() +
104 " was indicated as context root but " + Reason +
105 ", which is not supported.");
112CtxInstrumentationLowerer::CtxInstrumentationLowerer(
Module &M,
115 auto *
PointerTy = PointerType::get(
M.getContext(), 0);
116 auto *SanitizerMutexType = Type::getInt8Ty(
M.getContext());
117 auto *I32Ty = Type::getInt32Ty(
M.getContext());
118 auto *I64Ty = Type::getInt64Ty(
M.getContext());
120#define _PTRDECL(_, __) PointerTy,
121#define _VOLATILE_PTRDECL(_, __) PointerTy,
122#define _CONTEXT_ROOT PointerTy,
123#define _MUTEXDECL(_) SanitizerMutexType,
126 M.getContext(), {CTXPROF_FUNCTION_DATA(_PTRDECL, _CONTEXT_ROOT,
127 _VOLATILE_PTRDECL, _MUTEXDECL)});
130#undef _VOLATILE_PTRDECL
133#define _PTRDECL(_, __) Constant::getNullValue(PointerTy),
134#define _VOLATILE_PTRDECL(_, __) _PTRDECL(_, __)
135#define _MUTEXDECL(_) Constant::getNullValue(SanitizerMutexType),
136#define _CONTEXT_ROOT \
137 Constant::getIntegerValue( \
139 APInt(M.getDataLayout().getPointerTypeSizeInBits(PointerTy), 1U)),
145#undef _VOLATILE_PTRDECL
158 for (StringRef Fname : InstrumentationOptions::Global.profile_context_root) {
159 if (
const auto *
F =
M.getFunction(Fname)) {
160 if (
F->isDeclaration())
162 ContextRootSet.insert(
F);
163 for (
const auto &BB : *
F)
164 for (
const auto &
I : BB)
166 if (CB->isMustTailCall())
167 emitUnsupportedRootError(*
F,
"it features musttail calls");
173 M.getOrInsertFunction(
193 FunctionType::get(Type::getVoidTy(
M.getContext()),
204 CallsiteInfoTLS->setThreadLocal(
true);
215 CtxInstrumentationLowerer Lowerer(M,
MAM);
218 Changed |= Lowerer.lowerFunction(
F);
222bool CtxInstrumentationLowerer::lowerFunction(
Function &
F) {
223 if (
F.isDeclaration())
233 if (ContextRootSet.contains(&
F))
234 emitUnsupportedRootError(
F,
"it does not return");
242 auto [NumCounters, NumCallsites] = getNumCountersAndCallsites(
F);
244 Value *Context =
nullptr;
245 Value *RealContext =
nullptr;
248 Value *TheRootFunctionData =
nullptr;
249 Value *ExpectedCalleeTLSAddr =
nullptr;
250 Value *CallsiteInfoTLSAddr =
nullptr;
251 const bool HasMusttail = [&
F]() {
255 if (CB->isMustTailCall())
260 if (HasMusttail && ContextRootSet.contains(&
F)) {
261 F.getContext().emitError(
262 "[ctx_prof] A function with musttail calls was explicitly requested as "
263 "root. That is not supported because we cannot instrument a return "
264 "instruction to release the context: " +
268 auto &Head =
F.getEntryBlock();
269 for (
auto &
I : Head) {
272 assert(Mark->getIndex()->isZero());
281 {ContextNodeTy, ArrayType::get(Builder.getInt64Ty(), NumCounters),
282 ArrayType::get(Builder.getPtrTy(), NumCallsites)});
295 HasMusttail ? CannotBeRootInitializer
298 if (ContextRootSet.contains(&
F)) {
300 StartCtx, {TheRootFunctionData,
Guid, Builder.getInt32(NumCounters),
301 Builder.getInt32(NumCallsites)});
305 Context = Builder.CreateCall(GetCtx, {TheRootFunctionData, &
F,
Guid,
306 Builder.getInt32(NumCounters),
307 Builder.getInt32(NumCallsites)});
313 auto *CtxAsInt = Builder.CreatePtrToInt(
Context, Builder.getInt64Ty());
314 if (NumCallsites > 0) {
317 auto *
Index = Builder.CreateAnd(CtxAsInt, Builder.getInt64(1));
319 ExpectedCalleeTLSAddr = Builder.CreateGEP(
321 Builder.CreateThreadLocalAddress(ExpectedCalleeTLS), {Index});
322 CallsiteInfoTLSAddr = Builder.CreateGEP(
323 Builder.getInt32Ty(),
324 Builder.CreateThreadLocalAddress(CallsiteInfoTLS), {Index});
331 RealContext = Builder.CreateIntToPtr(
332 Builder.CreateAnd(CtxAsInt, Builder.getInt64(-2)),
341 <<
"Function doesn't have instrumentation, skipping";
346 bool ContextWasReleased =
false;
351 switch (
Instr->getIntrinsicID()) {
352 case llvm::Intrinsic::instrprof_increment:
353 case llvm::Intrinsic::instrprof_increment_step: {
357 auto *
GEP = Builder.CreateGEP(
358 ThisContextType, RealContext,
359 {Builder.getInt32(0), Builder.getInt32(1), AsStep->getIndex()});
361 Builder.CreateAdd(Builder.CreateLoad(Builder.getInt64Ty(),
GEP),
365 case llvm::Intrinsic::instrprof_callsite:
370 Builder.CreateStore(CSIntrinsic->getCallee(), ExpectedCalleeTLSAddr,
382 Builder.CreateGEP(ThisContextType,
Context,
383 {Builder.getInt32(0), Builder.getInt32(2),
384 CSIntrinsic->getIndex()}),
385 CallsiteInfoTLSAddr,
true);
392 Builder.CreateCall(ReleaseCtx, {TheRootFunctionData});
393 ContextWasReleased =
true;
397 if (!HasMusttail && !ContextWasReleased)
399 "[ctx_prof] A function that doesn't have musttail calls was "
400 "instrumented but it has no `ret` "
401 "instructions above which to release the context: " +
410 if (
F.isDeclaration())
412 if (
F.hasFnAttribute(Attribute::NoInline))
414 if (!
F.isWeakForLinker())
417 if (
F.hasFnAttribute(Attribute::AlwaysInline))
418 F.removeFnAttr(Attribute::AlwaysInline);
420 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)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
static LLVM_ABI bool isCtxIRPGOInstrEnabled()
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.
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.