LLVM 20.0.0git
EntryExitInstrumenter.cpp
Go to the documentation of this file.
1//===- EntryExitInstrumenter.cpp - Function Entry/Exit Instrumentation ----===//
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
12#include "llvm/IR/Dominators.h"
13#include "llvm/IR/Function.h"
15#include "llvm/IR/Intrinsics.h"
16#include "llvm/IR/Module.h"
17#include "llvm/IR/Type.h"
20#include "llvm/Pass.h"
22
23using namespace llvm;
24
25static void insertCall(Function &CurFn, StringRef Func,
26 BasicBlock::iterator InsertionPt, DebugLoc DL) {
27 Module &M = *InsertionPt->getParent()->getParent()->getParent();
28 LLVMContext &C = InsertionPt->getParent()->getContext();
29
30 if (Func == "mcount" ||
31 Func == ".mcount" ||
32 Func == "llvm.arm.gnu.eabi.mcount" ||
33 Func == "\01_mcount" ||
34 Func == "\01mcount" ||
35 Func == "__mcount" ||
36 Func == "_mcount" ||
37 Func == "__cyg_profile_func_enter_bare") {
38 Triple TargetTriple(M.getTargetTriple());
39 if (TargetTriple.isOSAIX() && Func == "__mcount") {
40 Type *SizeTy = M.getDataLayout().getIntPtrType(C);
41 Type *SizePtrTy = PointerType::getUnqual(C);
42 GlobalVariable *GV = new GlobalVariable(M, SizeTy, /*isConstant=*/false,
44 ConstantInt::get(SizeTy, 0));
46 M.getOrInsertFunction(Func,
47 FunctionType::get(Type::getVoidTy(C), {SizePtrTy},
48 /*isVarArg=*/false)),
49 {GV}, "", InsertionPt);
50 Call->setDebugLoc(DL);
51 } else {
52 FunctionCallee Fn = M.getOrInsertFunction(Func, Type::getVoidTy(C));
53 CallInst *Call = CallInst::Create(Fn, "", InsertionPt);
54 Call->setDebugLoc(DL);
55 }
56 return;
57 }
58
59 if (Func == "__cyg_profile_func_enter" || Func == "__cyg_profile_func_exit") {
60 Type *ArgTypes[] = {PointerType::getUnqual(C), PointerType::getUnqual(C)};
61
62 FunctionCallee Fn = M.getOrInsertFunction(
63 Func, FunctionType::get(Type::getVoidTy(C), ArgTypes, false));
64
66 Intrinsic::getDeclaration(&M, Intrinsic::returnaddress),
67 ArrayRef<Value *>(ConstantInt::get(Type::getInt32Ty(C), 0)), "",
68 InsertionPt);
69 RetAddr->setDebugLoc(DL);
70
71 Value *Args[] = {&CurFn, RetAddr};
72 CallInst *Call =
73 CallInst::Create(Fn, ArrayRef<Value *>(Args), "", InsertionPt);
74 Call->setDebugLoc(DL);
75 return;
76 }
77
78 // We only know how to call a fixed set of instrumentation functions, because
79 // they all expect different arguments, etc.
80 report_fatal_error(Twine("Unknown instrumentation function: '") + Func + "'");
81}
82
83static bool runOnFunction(Function &F, bool PostInlining) {
84 // The asm in a naked function may reasonably expect the argument registers
85 // and the return address register (if present) to be live. An inserted
86 // function call will clobber these registers. Simply skip naked functions for
87 // all targets.
88 if (F.hasFnAttribute(Attribute::Naked))
89 return false;
90
91 StringRef EntryAttr = PostInlining ? "instrument-function-entry-inlined"
92 : "instrument-function-entry";
93
94 StringRef ExitAttr = PostInlining ? "instrument-function-exit-inlined"
95 : "instrument-function-exit";
96
97 StringRef EntryFunc = F.getFnAttribute(EntryAttr).getValueAsString();
98 StringRef ExitFunc = F.getFnAttribute(ExitAttr).getValueAsString();
99
100 bool Changed = false;
101
102 // If the attribute is specified, insert instrumentation and then "consume"
103 // the attribute so that it's not inserted again if the pass should happen to
104 // run later for some reason.
105
106 if (!EntryFunc.empty()) {
107 DebugLoc DL;
108 if (auto SP = F.getSubprogram())
109 DL = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
110
111 insertCall(F, EntryFunc, F.begin()->getFirstInsertionPt(), DL);
112 Changed = true;
113 F.removeFnAttr(EntryAttr);
114 }
115
116 if (!ExitFunc.empty()) {
117 for (BasicBlock &BB : F) {
118 Instruction *T = BB.getTerminator();
119 if (!isa<ReturnInst>(T))
120 continue;
121
122 // If T is preceded by a musttail call, that's the real terminator.
123 if (CallInst *CI = BB.getTerminatingMustTailCall())
124 T = CI;
125
126 DebugLoc DL;
127 if (DebugLoc TerminatorDL = T->getDebugLoc())
128 DL = TerminatorDL;
129 else if (auto SP = F.getSubprogram())
130 DL = DILocation::get(SP->getContext(), 0, 0, SP);
131
132 insertCall(F, ExitFunc, T->getIterator(), DL);
133 Changed = true;
134 }
135 F.removeFnAttr(ExitAttr);
136 }
137
138 return Changed;
139}
140
141namespace {
142struct PostInlineEntryExitInstrumenter : public FunctionPass {
143 static char ID;
144 PostInlineEntryExitInstrumenter() : FunctionPass(ID) {
147 }
148 void getAnalysisUsage(AnalysisUsage &AU) const override {
151 }
152 bool runOnFunction(Function &F) override { return ::runOnFunction(F, true); }
153};
154char PostInlineEntryExitInstrumenter::ID = 0;
155}
156
158 PostInlineEntryExitInstrumenter, "post-inline-ee-instrument",
159 "Instrument function entry/exit with calls to e.g. mcount() "
160 "(post inlining)",
161 false, false)
164 PostInlineEntryExitInstrumenter, "post-inline-ee-instrument",
165 "Instrument function entry/exit with calls to e.g. mcount() "
166 "(post inlining)",
168
170 return new PostInlineEntryExitInstrumenter();
171}
172
176 return PreservedAnalyses::all();
179 return PA;
180}
181
183 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
185 ->printPipeline(OS, MapClassName2PassName);
186 OS << '<';
187 if (PostInlining)
188 OS << "post-inline";
189 OS << '>';
190}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
always inline
Performs the initial survey of the specified function
post inline ee instrument
static bool runOnFunction(Function &F, bool PostInlining)
post inline ee Instrument function entry exit with calls to e g mcount() " "(post inlining)"
static void insertCall(Function &CurFn, StringRef Func, BasicBlock::iterator InsertionPt, DebugLoc DL)
This is the interface for a simple mod/ref and alias analysis over globals.
#define F(x, y, z)
Definition: MD5.cpp:55
Module.h This file contains the declarations for the Module class.
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:57
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
raw_pwrite_stream & OS
INLINE void g(uint32_t *state, size_t a, size_t b, size_t c, size_t d, uint32_t x, uint32_t y)
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
Represent the analysis usage information of a pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:177
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:72
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
A debug info location.
Definition: DebugLoc.h:33
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:317
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:168
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
Legacy wrapper pass to provide the GlobalsAAResult object.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:463
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:98
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
void preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:146
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool isOSAIX() const
Tests whether the OS is AIX.
Definition: Triple.h:710
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static Type * getVoidTy(LLVMContext &C)
static IntegerType * getInt32Ty(LLVMContext &C)
LLVM Value Representation.
Definition: Value.h:74
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1539
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
FunctionPass * createPostInlineEntryExitInstrumenterPass()
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
void initializePostInlineEntryExitInstrumenterPass(PassRegistry &)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:69