LLVM 23.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,
48 /*isVarArg=*/false)),
49 {GV}, "", InsertionPt);
50 Call->setDebugLoc(DL);
51 } else if (TargetTriple.isRISCV() || TargetTriple.isAArch64() ||
52 TargetTriple.isLoongArch()) {
53 // On RISC-V, AArch64, and LoongArch, the `_mcount` function takes
54 // `__builtin_return_address(0)` as an argument since
55 // `__builtin_return_address(1)` is not available on these platforms.
56 auto ProgASPtr =
57 PointerType::get(C, M.getDataLayout().getProgramAddressSpace());
59 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::returnaddress,
60 {ProgASPtr}),
61 ConstantInt::get(Type::getInt32Ty(C), 0), "", InsertionPt);
62 RetAddr->setDebugLoc(DL);
63
64 FunctionCallee Fn = M.getOrInsertFunction(
66 false));
67 CallInst *Call = CallInst::Create(Fn, RetAddr, "", InsertionPt);
68 Call->setDebugLoc(DL);
69 } else if (TargetTriple.isSystemZ()) {
70 // skip insertion for `mcount` on SystemZ. This will be handled later in
71 // `emitPrologue`. Add custom attribute to denote this.
72 CurFn.addFnAttr(
73 llvm::Attribute::get(C, "systemz-instrument-function-entry", Func));
74 } else {
75 FunctionCallee Fn = M.getOrInsertFunction(Func, Type::getVoidTy(C));
76 CallInst *Call = CallInst::Create(Fn, "", InsertionPt);
77 Call->setDebugLoc(DL);
78 }
79 return;
80 }
81
82 if (Func == "__cyg_profile_func_enter" || Func == "__cyg_profile_func_exit") {
83 auto ProgASPtr =
84 PointerType::get(C, M.getDataLayout().getProgramAddressSpace());
85 Type *ArgTypes[] = {ProgASPtr, ProgASPtr};
86
87 FunctionCallee Fn = M.getOrInsertFunction(
88 Func, FunctionType::get(Type::getVoidTy(C), ArgTypes, false));
89
91 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::returnaddress,
92 {ProgASPtr}),
93 ArrayRef<Value *>(ConstantInt::get(Type::getInt32Ty(C), 0)), "",
94 InsertionPt);
95 RetAddr->setDebugLoc(DL);
96
97 Value *Args[] = {&CurFn, RetAddr};
98 CallInst *Call =
99 CallInst::Create(Fn, ArrayRef<Value *>(Args), "", InsertionPt);
100 Call->setDebugLoc(DL);
101 return;
102 }
103
104 // We only know how to call a fixed set of instrumentation functions, because
105 // they all expect different arguments, etc.
106 report_fatal_error(Twine("Unknown instrumentation function: '") + Func + "'");
107}
108
109static bool runOnFunction(Function &F, bool PostInlining) {
110 // The asm in a naked function may reasonably expect the argument registers
111 // and the return address register (if present) to be live. An inserted
112 // function call will clobber these registers. Simply skip naked functions for
113 // all targets.
114 if (F.hasFnAttribute(Attribute::Naked))
115 return false;
116
117 // available_externally functions may not have definitions external to the
118 // module (e.g. gnu::always_inline). Instrumenting them might lead to linker
119 // errors if they are optimized out. Skip them like GCC.
120 if (F.hasAvailableExternallyLinkage())
121 return false;
122
123 StringRef EntryAttr = PostInlining ? "instrument-function-entry-inlined"
124 : "instrument-function-entry";
125
126 StringRef ExitAttr = PostInlining ? "instrument-function-exit-inlined"
127 : "instrument-function-exit";
128
129 StringRef EntryFunc = F.getFnAttribute(EntryAttr).getValueAsString();
130 StringRef ExitFunc = F.getFnAttribute(ExitAttr).getValueAsString();
131
132 bool Changed = false;
133
134 // If the attribute is specified, insert instrumentation and then "consume"
135 // the attribute so that it's not inserted again if the pass should happen to
136 // run later for some reason.
137
138 if (!EntryFunc.empty()) {
139 DebugLoc DL;
140 if (auto SP = F.getSubprogram())
141 DL = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
142
143 insertCall(F, EntryFunc, F.begin()->getFirstInsertionPt(), DL);
144 Changed = true;
145 F.removeFnAttr(EntryAttr);
146 }
147
148 if (!ExitFunc.empty()) {
149 for (BasicBlock &BB : F) {
150 Instruction *T = BB.getTerminator();
151 if (!isa<ReturnInst>(T))
152 continue;
153
154 // If T is preceded by a musttail call, that's the real terminator.
155 if (CallInst *CI = BB.getTerminatingMustTailCall())
156 T = CI;
157
158 DebugLoc DL;
159 if (DebugLoc TerminatorDL = T->getDebugLoc())
160 DL = TerminatorDL;
161 else if (auto SP = F.getSubprogram())
162 DL = DILocation::get(SP->getContext(), 0, 0, SP);
163
164 insertCall(F, ExitFunc, T->getIterator(), DL);
165 Changed = true;
166 }
167 F.removeFnAttr(ExitAttr);
168 }
169
170 return Changed;
171}
172
173namespace {
174struct PostInlineEntryExitInstrumenter : public FunctionPass {
175 static char ID;
176 PostInlineEntryExitInstrumenter() : FunctionPass(ID) {
179 }
180 void getAnalysisUsage(AnalysisUsage &AU) const override {
181 AU.addPreserved<GlobalsAAWrapperPass>();
182 AU.setPreservesCFG();
183 }
184 bool runOnFunction(Function &F) override { return ::runOnFunction(F, true); }
185};
186char PostInlineEntryExitInstrumenter::ID = 0;
187}
188
190 PostInlineEntryExitInstrumenter, "post-inline-ee-instrument",
191 "Instrument function entry/exit with calls to e.g. mcount() "
192 "(post inlining)",
193 false, false)
196 PostInlineEntryExitInstrumenter, "post-inline-ee-instrument",
197 "Instrument function entry/exit with calls to e.g. mcount() "
198 "(post inlining)",
200
202 return new PostInlineEntryExitInstrumenter();
203}
204
213
215 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
217 ->printPipeline(OS, MapClassName2PassName);
218 OS << '<';
219 if (PostInlining)
220 OS << "post-inline";
221 OS << '>';
222}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool runOnFunction(Function &F, bool PostInlining)
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.
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define T
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:270
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
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:123
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:316
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition Function.cpp:638
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1572
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
bool isRISCV() const
Tests whether the target is RISC-V (32- and 64-bit).
Definition Triple.h:1142
bool isOSAIX() const
Tests whether the OS is AIX.
Definition Triple.h:798
bool isAArch64() const
Tests whether the target is AArch64 (little and big endian).
Definition Triple.h:1055
bool isSystemZ() const
Tests whether the target is SystemZ.
Definition Triple.h:1156
bool isLoongArch() const
Tests whether the target is LoongArch (32- and 64-bit).
Definition Triple.h:1081
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:313
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:286
LLVM Value Representation.
Definition Value.h:75
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:53
CallInst * Call
Changed
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI FunctionPass * createPostInlineEntryExitInstrumenterPass()
LLVM_ABI void initializePostInlineEntryExitInstrumenterPass(PassRegistry &)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
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
ArrayRef(const T &OneElt) -> ArrayRef< T >
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
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:70