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
12#include "llvm/ADT/STLExtras.h"
13#include "llvm/Analysis/CFG.h"
15#include "llvm/IR/Analysis.h"
16#include "llvm/IR/Constants.h"
18#include "llvm/IR/GlobalValue.h"
19#include "llvm/IR/IRBuilder.h"
20#include "llvm/IR/InstrTypes.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IR/PassManager.h"
27#include <utility>
28
29using namespace llvm;
30
31#define DEBUG_TYPE "ctx-instr-lower"
32
34 return !InstrumentationOptions::Global.profile_context_root.empty();
35}
36
37// the names of symbols we expect in compiler-rt. Using a namespace for
38// readability.
40static auto StartCtx = "__llvm_ctx_profile_start_context";
41static auto ReleaseCtx = "__llvm_ctx_profile_release_context";
42static auto GetCtx = "__llvm_ctx_profile_get_context";
43static auto ExpectedCalleeTLS = "__llvm_ctx_profile_expected_callee";
44static auto CallsiteTLS = "__llvm_ctx_profile_callsite";
45} // namespace CompilerRtAPINames
46
47namespace {
48// The lowering logic and state.
49class CtxInstrumentationLowerer final {
50 Module &M;
52 Type *ContextNodeTy = nullptr;
53 StructType *FunctionDataTy = nullptr;
54
55 DenseSet<const Function *> ContextRootSet;
56 Function *StartCtx = nullptr;
57 Function *GetCtx = nullptr;
58 Function *ReleaseCtx = nullptr;
59 GlobalVariable *ExpectedCalleeTLS = nullptr;
60 GlobalVariable *CallsiteInfoTLS = nullptr;
61 Constant *CannotBeRootInitializer = nullptr;
62
63public:
64 CtxInstrumentationLowerer(Module &M, ModuleAnalysisManager &MAM);
65 // return true if lowering happened (i.e. a change was made)
66 bool lowerFunction(Function &F);
67};
68
69// llvm.instrprof.increment[.step] captures the total number of counters as one
70// of its parameters, and llvm.instrprof.callsite captures the total number of
71// callsites. Those values are the same for instances of those intrinsics in
72// this function. Find the first instance of each and return them.
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) {
78 if (const auto *Incr = dyn_cast<InstrProfIncrementInst>(&I)) {
79 uint32_t V =
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");
84 NumCounters = V;
85 } else if (const auto *CSIntr = dyn_cast<InstrProfCallsite>(&I)) {
86 uint32_t V =
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");
91 NumCallsites = V;
92 }
93#ifdef NDEBUG
94 if (NumCounters && NumCallsites)
95 return std::make_pair(NumCounters, NumCallsites);
96#endif
97 }
98 }
99 return {NumCounters, NumCallsites};
100}
101
102void emitUnsupportedRootError(const Function &F, StringRef Reason) {
103 F.getContext().emitError("[ctxprof] The function " + F.getName() +
104 " was indicated as context root but " + Reason +
105 ", which is not supported.");
106}
107} // namespace
108
109// set up tie-in with compiler-rt.
110// NOTE!!!
111// These have to match compiler-rt/lib/ctx_profile/CtxInstrProfiling.h
112CtxInstrumentationLowerer::CtxInstrumentationLowerer(Module &M,
114 : M(M), MAM(MAM) {
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());
119
120#define _PTRDECL(_, __) PointerTy,
121#define _VOLATILE_PTRDECL(_, __) PointerTy,
122#define _CONTEXT_ROOT PointerTy,
123#define _MUTEXDECL(_) SanitizerMutexType,
124
125 FunctionDataTy = StructType::get(
126 M.getContext(), {CTXPROF_FUNCTION_DATA(_PTRDECL, _CONTEXT_ROOT,
127 _VOLATILE_PTRDECL, _MUTEXDECL)});
128#undef _PTRDECL
129#undef _CONTEXT_ROOT
130#undef _VOLATILE_PTRDECL
131#undef _MUTEXDECL
132
133#define _PTRDECL(_, __) Constant::getNullValue(PointerTy),
134#define _VOLATILE_PTRDECL(_, __) _PTRDECL(_, __)
135#define _MUTEXDECL(_) Constant::getNullValue(SanitizerMutexType),
136#define _CONTEXT_ROOT \
137 Constant::getIntegerValue( \
138 PointerTy, \
139 APInt(M.getDataLayout().getPointerTypeSizeInBits(PointerTy), 1U)),
140 CannotBeRootInitializer = ConstantStruct::get(
143#undef _PTRDECL
144#undef _CONTEXT_ROOT
145#undef _VOLATILE_PTRDECL
146#undef _MUTEXDECL
147
148 // The Context header.
149 ContextNodeTy = StructType::get(M.getContext(), {
150 I64Ty, /*Guid*/
151 PointerTy, /*Next*/
152 I32Ty, /*NumCounters*/
153 I32Ty, /*NumCallsites*/
154 });
155
156 // Define a global for each entrypoint. We'll reuse the entrypoint's name
157 // as prefix. We assume the entrypoint names to be unique.
158 for (StringRef Fname : InstrumentationOptions::Global.profile_context_root) {
159 if (const auto *F = M.getFunction(Fname)) {
160 if (F->isDeclaration())
161 continue;
162 ContextRootSet.insert(F);
163 for (const auto &BB : *F)
164 for (const auto &I : BB)
165 if (const auto *CB = dyn_cast<CallBase>(&I))
166 if (CB->isMustTailCall())
167 emitUnsupportedRootError(*F, "it features musttail calls");
168 }
169 }
170
171 // Declare the functions we will call.
173 M.getOrInsertFunction(
175 FunctionType::get(PointerTy,
176 {PointerTy, /*FunctionData*/
177 I64Ty, /*Guid*/ I32Ty,
178 /*NumCounters*/ I32Ty /*NumCallsites*/},
179 false))
180 .getCallee());
182 M.getOrInsertFunction(CompilerRtAPINames::GetCtx,
183 FunctionType::get(PointerTy,
184 {PointerTy, /*FunctionData*/
185 PointerTy, /*Callee*/
186 I64Ty, /*Guid*/
187 I32Ty, /*NumCounters*/
188 I32Ty}, /*NumCallsites*/
189 false))
190 .getCallee());
192 M.getOrInsertFunction(CompilerRtAPINames::ReleaseCtx,
193 FunctionType::get(Type::getVoidTy(M.getContext()),
194 {
195 PointerTy, /*FunctionData*/
196 },
197 false))
198 .getCallee());
199
200 // Declare the TLSes we will need to use.
201 CallsiteInfoTLS =
202 new GlobalVariable(M, PointerTy, false, GlobalValue::ExternalLinkage,
204 CallsiteInfoTLS->setThreadLocal(true);
205 CallsiteInfoTLS->setVisibility(llvm::GlobalValue::HiddenVisibility);
207 new GlobalVariable(M, PointerTy, false, GlobalValue::ExternalLinkage,
209 ExpectedCalleeTLS->setThreadLocal(true);
211}
212
215 CtxInstrumentationLowerer Lowerer(M, MAM);
216 bool Changed = false;
217 for (auto &F : M)
218 Changed |= Lowerer.lowerFunction(F);
220}
221
222bool CtxInstrumentationLowerer::lowerFunction(Function &F) {
223 if (F.isDeclaration())
224 return false;
225
226 // Probably pointless to try to do anything here, unlikely to be
227 // performance-affecting.
228 if (!llvm::canReturn(F)) {
229 for (auto &BB : F)
230 for (auto &I : make_early_inc_range(BB))
232 I.eraseFromParent();
233 if (ContextRootSet.contains(&F))
234 emitUnsupportedRootError(F, "it does not return");
235 return true;
236 }
237
238 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
239 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
240
241 Value *Guid = nullptr;
242 auto [NumCounters, NumCallsites] = getNumCountersAndCallsites(F);
243
244 Value *Context = nullptr;
245 Value *RealContext = nullptr;
246
247 StructType *ThisContextType = nullptr;
248 Value *TheRootFunctionData = nullptr;
249 Value *ExpectedCalleeTLSAddr = nullptr;
250 Value *CallsiteInfoTLSAddr = nullptr;
251 const bool HasMusttail = [&F]() {
252 for (auto &BB : F)
253 for (auto &I : BB)
254 if (auto *CB = dyn_cast<CallBase>(&I))
255 if (CB->isMustTailCall())
256 return true;
257 return false;
258 }();
259
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: " +
265 F.getName());
266 return false;
267 }
268 auto &Head = F.getEntryBlock();
269 for (auto &I : Head) {
270 // Find the increment intrinsic in the entry basic block.
271 if (auto *Mark = dyn_cast<InstrProfIncrementInst>(&I)) {
272 assert(Mark->getIndex()->isZero());
273
274 IRBuilder<> Builder(Mark);
275 Guid = Builder.getInt64(cast<Function>(*Mark->getNameValue()).getGUID());
276 // The type of the context of this function is now knowable since we have
277 // NumCallsites and NumCounters. We declare it here because it's more
278 // convenient - we have the Builder.
279 ThisContextType = StructType::get(
280 F.getContext(),
281 {ContextNodeTy, ArrayType::get(Builder.getInt64Ty(), NumCounters),
282 ArrayType::get(Builder.getPtrTy(), NumCallsites)});
283 // Figure out which way we obtain the context object for this function -
284 // if it's an entrypoint, then we call StartCtx, otherwise GetCtx. In the
285 // former case, we also set TheRootFunctionData since we need to release
286 // it at the end (plus it can be used to know if we have an entrypoint or
287 // a regular function). Don't set a name, they end up taking a lot of
288 // space and we don't need them.
289
290 // Zero-initialize the FunctionData, except for functions that have
291 // musttail calls. There, we set the CtxRoot field to 1, which will be
292 // treated as a "can't be set as root".
293 TheRootFunctionData = new GlobalVariable(
294 M, FunctionDataTy, false, GlobalVariable::InternalLinkage,
295 HasMusttail ? CannotBeRootInitializer
296 : Constant::getNullValue(FunctionDataTy));
297
298 if (ContextRootSet.contains(&F)) {
299 Context = Builder.CreateCall(
300 StartCtx, {TheRootFunctionData, Guid, Builder.getInt32(NumCounters),
301 Builder.getInt32(NumCallsites)});
302 ORE.emit(
303 [&] { return OptimizationRemark(DEBUG_TYPE, "Entrypoint", &F); });
304 } else {
305 Context = Builder.CreateCall(GetCtx, {TheRootFunctionData, &F, Guid,
306 Builder.getInt32(NumCounters),
307 Builder.getInt32(NumCallsites)});
308 ORE.emit([&] {
309 return OptimizationRemark(DEBUG_TYPE, "RegularFunction", &F);
310 });
311 }
312 // The context could be scratch.
313 auto *CtxAsInt = Builder.CreatePtrToInt(Context, Builder.getInt64Ty());
314 if (NumCallsites > 0) {
315 // Figure out which index of the TLS 2-element buffers to use.
316 // Scratch context => we use index == 1. Real contexts => index == 0.
317 auto *Index = Builder.CreateAnd(CtxAsInt, Builder.getInt64(1));
318 // The GEPs corresponding to that index, in the respective TLS.
319 ExpectedCalleeTLSAddr = Builder.CreateGEP(
320 PointerType::getUnqual(F.getContext()),
321 Builder.CreateThreadLocalAddress(ExpectedCalleeTLS), {Index});
322 CallsiteInfoTLSAddr = Builder.CreateGEP(
323 Builder.getInt32Ty(),
324 Builder.CreateThreadLocalAddress(CallsiteInfoTLS), {Index});
325 }
326 // Because the context pointer may have LSB set (to indicate scratch),
327 // clear it for the value we use as base address for the counter vector.
328 // This way, if later we want to have "real" (not clobbered) buffers
329 // acting as scratch, the lowering (at least this part of it that deals
330 // with counters) stays the same.
331 RealContext = Builder.CreateIntToPtr(
332 Builder.CreateAnd(CtxAsInt, Builder.getInt64(-2)),
333 PointerType::getUnqual(F.getContext()));
334 I.eraseFromParent();
335 break;
336 }
337 }
338 if (!Context) {
339 ORE.emit([&] {
340 return OptimizationRemarkMissed(DEBUG_TYPE, "Skip", &F)
341 << "Function doesn't have instrumentation, skipping";
342 });
343 return false;
344 }
345
346 bool ContextWasReleased = false;
347 for (auto &BB : F) {
348 for (auto &I : llvm::make_early_inc_range(BB)) {
349 if (auto *Instr = dyn_cast<InstrProfCntrInstBase>(&I)) {
350 IRBuilder<> Builder(Instr);
351 switch (Instr->getIntrinsicID()) {
352 case llvm::Intrinsic::instrprof_increment:
353 case llvm::Intrinsic::instrprof_increment_step: {
354 // Increments (or increment-steps) are just a typical load - increment
355 // - store in the RealContext.
356 auto *AsStep = cast<InstrProfIncrementInst>(Instr);
357 auto *GEP = Builder.CreateGEP(
358 ThisContextType, RealContext,
359 {Builder.getInt32(0), Builder.getInt32(1), AsStep->getIndex()});
360 Builder.CreateStore(
361 Builder.CreateAdd(Builder.CreateLoad(Builder.getInt64Ty(), GEP),
362 AsStep->getStep()),
363 GEP);
364 } break;
365 case llvm::Intrinsic::instrprof_callsite:
366 // callsite lowering: write the called value in the expected callee
367 // TLS we treat the TLS as volatile because of signal handlers and to
368 // avoid these being moved away from the callsite they decorate.
369 auto *CSIntrinsic = dyn_cast<InstrProfCallsite>(Instr);
370 Builder.CreateStore(CSIntrinsic->getCallee(), ExpectedCalleeTLSAddr,
371 true);
372 // write the GEP of the slot in the sub-contexts portion of the
373 // context in TLS. Now, here, we use the actual Context value - as
374 // returned from compiler-rt - which may have the LSB set if the
375 // Context was scratch. Since the header of the context object and
376 // then the values are all 8-aligned (or, really, insofar as we care,
377 // they are even) - if the context is scratch (meaning, an odd value),
378 // so will the GEP. This is important because this is then visible to
379 // compiler-rt which will produce scratch contexts for callers that
380 // have a scratch context.
381 Builder.CreateStore(
382 Builder.CreateGEP(ThisContextType, Context,
383 {Builder.getInt32(0), Builder.getInt32(2),
384 CSIntrinsic->getIndex()}),
385 CallsiteInfoTLSAddr, true);
386 break;
387 }
388 I.eraseFromParent();
389 } else if (!HasMusttail && isa<ReturnInst>(I)) {
390 // Remember to release the context if we are an entrypoint.
391 IRBuilder<> Builder(&I);
392 Builder.CreateCall(ReleaseCtx, {TheRootFunctionData});
393 ContextWasReleased = true;
394 }
395 }
396 }
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: " +
402 F.getName());
403 return true;
404}
405
408 bool Changed = false;
409 for (auto &F : M) {
410 if (F.isDeclaration())
411 continue;
412 if (F.hasFnAttribute(Attribute::NoInline))
413 continue;
414 if (!F.isWeakForLinker())
415 continue;
416
417 if (F.hasFnAttribute(Attribute::AlwaysInline))
418 F.removeFnAttr(Attribute::AlwaysInline);
419
420 F.addFnAttr(Attribute::NoInline);
421 Changed = true;
422 }
423 if (Changed)
425 return PreservedAnalyses::all();
426}
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
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:2918
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:68
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:467
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:260
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:649
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