LLVM 24.0.0git
PGOCtxProfLowering.cpp
Go to the documentation of this file.
1//===- PGOCtxProfLowering.cpp - Contextual PGO Instr. Lowering ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/Analysis/CFG.h"
14#include "llvm/IR/Analysis.h"
15#include "llvm/IR/Constants.h"
17#include "llvm/IR/GlobalValue.h"
18#include "llvm/IR/IRBuilder.h"
19#include "llvm/IR/InstrTypes.h"
22#include "llvm/IR/Module.h"
23#include "llvm/IR/PassManager.h"
27#include <utility>
28
29using namespace llvm;
30
31#define DEBUG_TYPE "ctx-instr-lower"
32
34 "profile-context-root", cl::Hidden,
36 "A function name, assumed to be global, which will be treated as the "
37 "root of an interesting graph, which will be profiled independently "
38 "from other similar graphs."));
39
43
44// the names of symbols we expect in compiler-rt. Using a namespace for
45// readability.
47static auto StartCtx = "__llvm_ctx_profile_start_context";
48static auto ReleaseCtx = "__llvm_ctx_profile_release_context";
49static auto GetCtx = "__llvm_ctx_profile_get_context";
50static auto ExpectedCalleeTLS = "__llvm_ctx_profile_expected_callee";
51static auto CallsiteTLS = "__llvm_ctx_profile_callsite";
52} // namespace CompilerRtAPINames
53
54namespace {
55// The lowering logic and state.
56class CtxInstrumentationLowerer final {
57 Module &M;
59 Type *ContextNodeTy = nullptr;
60 StructType *FunctionDataTy = nullptr;
61
62 DenseSet<const Function *> ContextRootSet;
63 Function *StartCtx = nullptr;
64 Function *GetCtx = nullptr;
65 Function *ReleaseCtx = nullptr;
66 GlobalVariable *ExpectedCalleeTLS = nullptr;
67 GlobalVariable *CallsiteInfoTLS = nullptr;
68 Constant *CannotBeRootInitializer = nullptr;
69
70public:
71 CtxInstrumentationLowerer(Module &M, ModuleAnalysisManager &MAM);
72 // return true if lowering happened (i.e. a change was made)
73 bool lowerFunction(Function &F);
74};
75
76// llvm.instrprof.increment[.step] captures the total number of counters as one
77// of its parameters, and llvm.instrprof.callsite captures the total number of
78// callsites. Those values are the same for instances of those intrinsics in
79// this function. Find the first instance of each and return them.
80std::pair<uint32_t, uint32_t> getNumCountersAndCallsites(const Function &F) {
81 uint32_t NumCounters = 0;
82 uint32_t NumCallsites = 0;
83 for (const auto &BB : F) {
84 for (const auto &I : BB) {
85 if (const auto *Incr = dyn_cast<InstrProfIncrementInst>(&I)) {
86 uint32_t V =
87 static_cast<uint32_t>(Incr->getNumCounters()->getZExtValue());
88 assert((!NumCounters || V == NumCounters) &&
89 "expected all llvm.instrprof.increment[.step] intrinsics to "
90 "have the same total nr of counters parameter");
91 NumCounters = V;
92 } else if (const auto *CSIntr = dyn_cast<InstrProfCallsite>(&I)) {
93 uint32_t V =
94 static_cast<uint32_t>(CSIntr->getNumCounters()->getZExtValue());
95 assert((!NumCallsites || V == NumCallsites) &&
96 "expected all llvm.instrprof.callsite intrinsics to have the "
97 "same total nr of callsites parameter");
98 NumCallsites = V;
99 }
100#ifdef NDEBUG
101 if (NumCounters && NumCallsites)
102 return std::make_pair(NumCounters, NumCallsites);
103#endif
104 }
105 }
106 return {NumCounters, NumCallsites};
107}
108
109void emitUnsupportedRootError(const Function &F, StringRef Reason) {
110 F.getContext().emitError("[ctxprof] The function " + F.getName() +
111 " was indicated as context root but " + Reason +
112 ", which is not supported.");
113}
114} // namespace
115
116// set up tie-in with compiler-rt.
117// NOTE!!!
118// These have to match compiler-rt/lib/ctx_profile/CtxInstrProfiling.h
119CtxInstrumentationLowerer::CtxInstrumentationLowerer(Module &M,
121 : M(M), MAM(MAM) {
122 auto *PointerTy = PointerType::get(M.getContext(), 0);
123 auto *SanitizerMutexType = Type::getInt8Ty(M.getContext());
124 auto *I32Ty = Type::getInt32Ty(M.getContext());
125 auto *I64Ty = Type::getInt64Ty(M.getContext());
126
127#define _PTRDECL(_, __) PointerTy,
128#define _VOLATILE_PTRDECL(_, __) PointerTy,
129#define _CONTEXT_ROOT PointerTy,
130#define _MUTEXDECL(_) SanitizerMutexType,
131
132 FunctionDataTy = StructType::get(
133 M.getContext(), {CTXPROF_FUNCTION_DATA(_PTRDECL, _CONTEXT_ROOT,
134 _VOLATILE_PTRDECL, _MUTEXDECL)});
135#undef _PTRDECL
136#undef _CONTEXT_ROOT
137#undef _VOLATILE_PTRDECL
138#undef _MUTEXDECL
139
140#define _PTRDECL(_, __) Constant::getNullValue(PointerTy),
141#define _VOLATILE_PTRDECL(_, __) _PTRDECL(_, __)
142#define _MUTEXDECL(_) Constant::getNullValue(SanitizerMutexType),
143#define _CONTEXT_ROOT \
144 Constant::getIntegerValue( \
145 PointerTy, \
146 APInt(M.getDataLayout().getPointerTypeSizeInBits(PointerTy), 1U)),
147 CannotBeRootInitializer = ConstantStruct::get(
150#undef _PTRDECL
151#undef _CONTEXT_ROOT
152#undef _VOLATILE_PTRDECL
153#undef _MUTEXDECL
154
155 // The Context header.
156 ContextNodeTy = StructType::get(M.getContext(), {
157 I64Ty, /*Guid*/
158 PointerTy, /*Next*/
159 I32Ty, /*NumCounters*/
160 I32Ty, /*NumCallsites*/
161 });
162
163 // Define a global for each entrypoint. We'll reuse the entrypoint's name
164 // as prefix. We assume the entrypoint names to be unique.
165 for (const auto &Fname : ContextRoots) {
166 if (const auto *F = M.getFunction(Fname)) {
167 if (F->isDeclaration())
168 continue;
169 ContextRootSet.insert(F);
170 for (const auto &BB : *F)
171 for (const auto &I : BB)
172 if (const auto *CB = dyn_cast<CallBase>(&I))
173 if (CB->isMustTailCall())
174 emitUnsupportedRootError(*F, "it features musttail calls");
175 }
176 }
177
178 // Declare the functions we will call.
180 M.getOrInsertFunction(
182 FunctionType::get(PointerTy,
183 {PointerTy, /*FunctionData*/
184 I64Ty, /*Guid*/ I32Ty,
185 /*NumCounters*/ I32Ty /*NumCallsites*/},
186 false))
187 .getCallee());
189 M.getOrInsertFunction(CompilerRtAPINames::GetCtx,
190 FunctionType::get(PointerTy,
191 {PointerTy, /*FunctionData*/
192 PointerTy, /*Callee*/
193 I64Ty, /*Guid*/
194 I32Ty, /*NumCounters*/
195 I32Ty}, /*NumCallsites*/
196 false))
197 .getCallee());
199 M.getOrInsertFunction(CompilerRtAPINames::ReleaseCtx,
200 FunctionType::get(Type::getVoidTy(M.getContext()),
201 {
202 PointerTy, /*FunctionData*/
203 },
204 false))
205 .getCallee());
206
207 // Declare the TLSes we will need to use.
208 CallsiteInfoTLS =
209 new GlobalVariable(M, PointerTy, false, GlobalValue::ExternalLinkage,
211 CallsiteInfoTLS->setThreadLocal(true);
212 CallsiteInfoTLS->setVisibility(llvm::GlobalValue::HiddenVisibility);
214 new GlobalVariable(M, PointerTy, false, GlobalValue::ExternalLinkage,
216 ExpectedCalleeTLS->setThreadLocal(true);
218}
219
222 CtxInstrumentationLowerer Lowerer(M, MAM);
223 bool Changed = false;
224 for (auto &F : M)
225 Changed |= Lowerer.lowerFunction(F);
227}
228
229bool CtxInstrumentationLowerer::lowerFunction(Function &F) {
230 if (F.isDeclaration())
231 return false;
232
233 // Probably pointless to try to do anything here, unlikely to be
234 // performance-affecting.
235 if (!llvm::canReturn(F)) {
236 for (auto &BB : F)
237 for (auto &I : make_early_inc_range(BB))
239 I.eraseFromParent();
240 if (ContextRootSet.contains(&F))
241 emitUnsupportedRootError(F, "it does not return");
242 return true;
243 }
244
245 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
246 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
247
248 Value *Guid = nullptr;
249 auto [NumCounters, NumCallsites] = getNumCountersAndCallsites(F);
250
251 Value *Context = nullptr;
252 Value *RealContext = nullptr;
253
254 StructType *ThisContextType = nullptr;
255 Value *TheRootFunctionData = nullptr;
256 Value *ExpectedCalleeTLSAddr = nullptr;
257 Value *CallsiteInfoTLSAddr = nullptr;
258 const bool HasMusttail = [&F]() {
259 for (auto &BB : F)
260 for (auto &I : BB)
261 if (auto *CB = dyn_cast<CallBase>(&I))
262 if (CB->isMustTailCall())
263 return true;
264 return false;
265 }();
266
267 if (HasMusttail && ContextRootSet.contains(&F)) {
268 F.getContext().emitError(
269 "[ctx_prof] A function with musttail calls was explicitly requested as "
270 "root. That is not supported because we cannot instrument a return "
271 "instruction to release the context: " +
272 F.getName());
273 return false;
274 }
275 auto &Head = F.getEntryBlock();
276 for (auto &I : Head) {
277 // Find the increment intrinsic in the entry basic block.
278 if (auto *Mark = dyn_cast<InstrProfIncrementInst>(&I)) {
279 assert(Mark->getIndex()->isZero());
280
281 IRBuilder<> Builder(Mark);
282 Guid = Builder.getInt64(cast<Function>(*Mark->getNameValue()).getGUID());
283 // The type of the context of this function is now knowable since we have
284 // NumCallsites and NumCounters. We declare it here because it's more
285 // convenient - we have the Builder.
286 ThisContextType = StructType::get(
287 F.getContext(),
288 {ContextNodeTy, ArrayType::get(Builder.getInt64Ty(), NumCounters),
289 ArrayType::get(Builder.getPtrTy(), NumCallsites)});
290 // Figure out which way we obtain the context object for this function -
291 // if it's an entrypoint, then we call StartCtx, otherwise GetCtx. In the
292 // former case, we also set TheRootFunctionData since we need to release
293 // it at the end (plus it can be used to know if we have an entrypoint or
294 // a regular function). Don't set a name, they end up taking a lot of
295 // space and we don't need them.
296
297 // Zero-initialize the FunctionData, except for functions that have
298 // musttail calls. There, we set the CtxRoot field to 1, which will be
299 // treated as a "can't be set as root".
300 TheRootFunctionData = new GlobalVariable(
301 M, FunctionDataTy, false, GlobalVariable::InternalLinkage,
302 HasMusttail ? CannotBeRootInitializer
303 : Constant::getNullValue(FunctionDataTy));
304
305 if (ContextRootSet.contains(&F)) {
306 Context = Builder.CreateCall(
307 StartCtx, {TheRootFunctionData, Guid, Builder.getInt32(NumCounters),
308 Builder.getInt32(NumCallsites)});
309 ORE.emit(
310 [&] { return OptimizationRemark(DEBUG_TYPE, "Entrypoint", &F); });
311 } else {
312 Context = Builder.CreateCall(GetCtx, {TheRootFunctionData, &F, Guid,
313 Builder.getInt32(NumCounters),
314 Builder.getInt32(NumCallsites)});
315 ORE.emit([&] {
316 return OptimizationRemark(DEBUG_TYPE, "RegularFunction", &F);
317 });
318 }
319 // The context could be scratch.
320 auto *CtxAsInt = Builder.CreatePtrToInt(Context, Builder.getInt64Ty());
321 if (NumCallsites > 0) {
322 // Figure out which index of the TLS 2-element buffers to use.
323 // Scratch context => we use index == 1. Real contexts => index == 0.
324 auto *Index = Builder.CreateAnd(CtxAsInt, Builder.getInt64(1));
325 // The GEPs corresponding to that index, in the respective TLS.
326 ExpectedCalleeTLSAddr = Builder.CreateGEP(
327 PointerType::getUnqual(F.getContext()),
328 Builder.CreateThreadLocalAddress(ExpectedCalleeTLS), {Index});
329 CallsiteInfoTLSAddr = Builder.CreateGEP(
330 Builder.getInt32Ty(),
331 Builder.CreateThreadLocalAddress(CallsiteInfoTLS), {Index});
332 }
333 // Because the context pointer may have LSB set (to indicate scratch),
334 // clear it for the value we use as base address for the counter vector.
335 // This way, if later we want to have "real" (not clobbered) buffers
336 // acting as scratch, the lowering (at least this part of it that deals
337 // with counters) stays the same.
338 RealContext = Builder.CreateIntToPtr(
339 Builder.CreateAnd(CtxAsInt, Builder.getInt64(-2)),
340 PointerType::getUnqual(F.getContext()));
341 I.eraseFromParent();
342 break;
343 }
344 }
345 if (!Context) {
346 ORE.emit([&] {
347 return OptimizationRemarkMissed(DEBUG_TYPE, "Skip", &F)
348 << "Function doesn't have instrumentation, skipping";
349 });
350 return false;
351 }
352
353 bool ContextWasReleased = false;
354 for (auto &BB : F) {
355 for (auto &I : llvm::make_early_inc_range(BB)) {
356 if (auto *Instr = dyn_cast<InstrProfCntrInstBase>(&I)) {
357 IRBuilder<> Builder(Instr);
358 switch (Instr->getIntrinsicID()) {
359 case llvm::Intrinsic::instrprof_increment:
360 case llvm::Intrinsic::instrprof_increment_step: {
361 // Increments (or increment-steps) are just a typical load - increment
362 // - store in the RealContext.
363 auto *AsStep = cast<InstrProfIncrementInst>(Instr);
364 auto *GEP = Builder.CreateGEP(
365 ThisContextType, RealContext,
366 {Builder.getInt32(0), Builder.getInt32(1), AsStep->getIndex()});
367 Builder.CreateStore(
368 Builder.CreateAdd(Builder.CreateLoad(Builder.getInt64Ty(), GEP),
369 AsStep->getStep()),
370 GEP);
371 } break;
372 case llvm::Intrinsic::instrprof_callsite:
373 // callsite lowering: write the called value in the expected callee
374 // TLS we treat the TLS as volatile because of signal handlers and to
375 // avoid these being moved away from the callsite they decorate.
376 auto *CSIntrinsic = dyn_cast<InstrProfCallsite>(Instr);
377 Builder.CreateStore(CSIntrinsic->getCallee(), ExpectedCalleeTLSAddr,
378 true);
379 // write the GEP of the slot in the sub-contexts portion of the
380 // context in TLS. Now, here, we use the actual Context value - as
381 // returned from compiler-rt - which may have the LSB set if the
382 // Context was scratch. Since the header of the context object and
383 // then the values are all 8-aligned (or, really, insofar as we care,
384 // they are even) - if the context is scratch (meaning, an odd value),
385 // so will the GEP. This is important because this is then visible to
386 // compiler-rt which will produce scratch contexts for callers that
387 // have a scratch context.
388 Builder.CreateStore(
389 Builder.CreateGEP(ThisContextType, Context,
390 {Builder.getInt32(0), Builder.getInt32(2),
391 CSIntrinsic->getIndex()}),
392 CallsiteInfoTLSAddr, true);
393 break;
394 }
395 I.eraseFromParent();
396 } else if (!HasMusttail && isa<ReturnInst>(I)) {
397 // Remember to release the context if we are an entrypoint.
398 IRBuilder<> Builder(&I);
399 Builder.CreateCall(ReleaseCtx, {TheRootFunctionData});
400 ContextWasReleased = true;
401 }
402 }
403 }
404 if (!HasMusttail && !ContextWasReleased)
406 "[ctx_prof] A function that doesn't have musttail calls was "
407 "instrumented but it has no `ret` "
408 "instructions above which to release the context: " +
409 F.getName());
410 return true;
411}
412
415 bool Changed = false;
416 for (auto &F : M) {
417 if (F.isDeclaration())
418 continue;
419 if (F.hasFnAttribute(Attribute::NoInline))
420 continue;
421 if (!F.isWeakForLinker())
422 continue;
423
424 if (F.hasFnAttribute(Attribute::AlwaysInline))
425 F.removeFnAttr(Attribute::AlwaysInline);
426
427 F.addFnAttr(Attribute::NoInline);
428 Changed = true;
429 }
430 if (Changed)
432 return PreservedAnalyses::all();
433}
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.
#define DEBUG_TYPE
Hexagon Common GEP
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define _MUTEXDECL(_)
#define _VOLATILE_PTRDECL(_, __)
#define _PTRDECL(_, __)
#define _CONTEXT_ROOT
static cl::list< std::string > ContextRoots("profile-context-root", cl::Hidden, cl::desc("A function name, assumed to be global, which will be treated as the " "root of an interesting graph, which will be profiled independently " "from other similar graphs."))
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
This file contains some templates that are useful if you are working with the STL at all.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2903
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.
Definition Module.h:67
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
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.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
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.
Definition Type.cpp:477
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
Changed
Pass manager infrastructure for declaring and invalidating analyses.
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
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.
Definition Casting.h:643
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...
Definition STLExtras.h:633
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
void * PointerTy
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...
Definition Casting.h:547
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
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.
Definition CFG.cpp:405