LLVM 24.0.0git
XRayInstrumentation.cpp
Go to the documentation of this file.
1//===- XRayInstrumentation.cpp - Adds XRay instrumentation to functions. --===//
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// This file implements a MachineFunctionPass that inserts the appropriate
10// XRay instrumentation instructions. We look for XRay-specific attributes
11// on the function to determine whether we should insert the replacement
12// operations.
13//
14//===---------------------------------------------------------------------===//
15
17#include "llvm/ADT/STLExtras.h"
30#include "llvm/IR/Attributes.h"
32#include "llvm/IR/Function.h"
34#include "llvm/Pass.h"
37
38using namespace llvm;
39
40namespace {
41
42struct InstrumentationOptions {
43 // Whether to emit PATCHABLE_TAIL_CALL.
44 bool HandleTailcall;
45
46 // Whether to emit PATCHABLE_RET/PATCHABLE_FUNCTION_EXIT for all forms of
47 // return, e.g. conditional return.
48 bool HandleAllReturns;
49};
50
51struct XRayInstrumentationLegacy : public MachineFunctionPass {
52 static char ID;
53
54 XRayInstrumentationLegacy() : MachineFunctionPass(ID) {}
55
56 void getAnalysisUsage(AnalysisUsage &AU) const override {
57 AU.setPreservesCFG();
59 }
60
61 bool runOnMachineFunction(MachineFunction &MF) override;
62};
63
64struct XRayInstrumentation {
65 XRayInstrumentation(MachineDominatorTree *MDT, MachineLoopInfo *MLI)
66 : MDT(MDT), MLI(MLI) {}
67
68 bool run(MachineFunction &MF);
69
70 // Methods for use in the NPM and legacy passes, can be removed once migration
71 // is complete.
72 static bool alwaysInstrument(Function &F) {
73 auto InstrAttr = F.getFnAttribute("function-instrument");
74 return InstrAttr.isStringAttribute() &&
75 InstrAttr.getValueAsString() == "xray-always";
76 }
77
78 static bool needMDTAndMLIAnalyses(Function &F) {
79 auto IgnoreLoopsAttr = F.getFnAttribute("xray-ignore-loops");
80 auto AlwaysInstrument = XRayInstrumentation::alwaysInstrument(F);
81 return !AlwaysInstrument && !IgnoreLoopsAttr.isValid();
82 }
83
84private:
85 // Replace the original RET instruction with the exit sled code ("patchable
86 // ret" pseudo-instruction), so that at runtime XRay can replace the sled
87 // with a code jumping to XRay trampoline, which calls the tracing handler
88 // and, in the end, issues the RET instruction.
89 // This is the approach to go on CPUs which have a single RET instruction,
90 // like x86/x86_64.
91 void replaceRetWithPatchableRet(MachineFunction &MF,
92 const TargetInstrInfo *TII,
93 InstrumentationOptions);
94
95 // Prepend the original return instruction with the exit sled code ("patchable
96 // function exit" pseudo-instruction), preserving the original return
97 // instruction just after the exit sled code.
98 // This is the approach to go on CPUs which have multiple options for the
99 // return instruction, like ARM. For such CPUs we can't just jump into the
100 // XRay trampoline and issue a single return instruction there. We rather
101 // have to call the trampoline and return from it to the original return
102 // instruction of the function being instrumented.
103 void prependRetWithPatchableExit(MachineFunction &MF,
104 const TargetInstrInfo *TII,
105 InstrumentationOptions);
106
107 MachineDominatorTree *MDT;
108 MachineLoopInfo *MLI;
109};
110
111} // end anonymous namespace
112
113void XRayInstrumentation::replaceRetWithPatchableRet(
115 InstrumentationOptions op) {
116 // We look for *all* terminators and returns, then replace those with
117 // PATCHABLE_RET instructions.
118 SmallVector<MachineInstr *, 4> Terminators;
119 for (auto &MBB : MF) {
120 for (auto &T : MBB.terminators()) {
121 unsigned Opc = 0;
122 if (T.isReturn() &&
123 (op.HandleAllReturns || T.getOpcode() == TII->getReturnOpcode())) {
124 // Replace return instructions with:
125 // PATCHABLE_RET <Opcode>, <Operand>...
126 Opc = TargetOpcode::PATCHABLE_RET;
127 }
128 if (TII->isTailCall(T) && op.HandleTailcall) {
129 // Treat the tail call as a return instruction, which has a
130 // different-looking sled than the normal return case.
131 Opc = TargetOpcode::PATCHABLE_TAIL_CALL;
132 }
133 if (Opc != 0) {
134 auto MIB = BuildMI(MBB, T, T.getDebugLoc(), TII->get(Opc))
135 .addImm(T.getOpcode());
136 for (auto &MO : T.operands())
137 MIB.add(MO);
138 Terminators.push_back(&T);
139 if (T.shouldUpdateAdditionalCallInfo())
140 MF.eraseAdditionalCallInfo(&T);
141 }
142 }
143 }
144
145 for (auto &I : Terminators)
146 I->eraseFromParent();
147}
148
149void XRayInstrumentation::prependRetWithPatchableExit(
150 MachineFunction &MF, const TargetInstrInfo *TII,
151 InstrumentationOptions op) {
152 for (auto &MBB : MF)
153 for (auto &T : MBB.terminators()) {
154 unsigned Opc = 0;
155 if (T.isReturn() &&
156 (op.HandleAllReturns || T.getOpcode() == TII->getReturnOpcode())) {
157 Opc = TargetOpcode::PATCHABLE_FUNCTION_EXIT;
158 }
159 if (TII->isTailCall(T) && op.HandleTailcall) {
160 Opc = TargetOpcode::PATCHABLE_TAIL_CALL;
161 }
162 if (Opc != 0) {
163 // Prepend the return instruction with PATCHABLE_FUNCTION_EXIT or
164 // PATCHABLE_TAIL_CALL .
165 BuildMI(MBB, T, T.getDebugLoc(), TII->get(Opc));
166 }
167 }
168}
169
170PreservedAnalyses
173 MachineDominatorTree *MDT = nullptr;
174 MachineLoopInfo *MLI = nullptr;
175
176 if (XRayInstrumentation::needMDTAndMLIAnalyses(MF.getFunction())) {
178 MLI = MFAM.getCachedResult<MachineLoopAnalysis>(MF);
179 }
180
181 if (!XRayInstrumentation(MDT, MLI).run(MF))
182 return PreservedAnalyses::all();
183
185 PA.preserveSet<CFGAnalyses>();
186 return PA;
187}
188
189bool XRayInstrumentationLegacy::runOnMachineFunction(MachineFunction &MF) {
190 MachineDominatorTree *MDT = nullptr;
191 MachineLoopInfo *MLI = nullptr;
192 if (XRayInstrumentation::needMDTAndMLIAnalyses(MF.getFunction())) {
193 auto *MDTWrapper =
194 getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
195 MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
196 auto *MLIWrapper = getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
197 MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
198 }
199 return XRayInstrumentation(MDT, MLI).run(MF);
200}
201
202bool XRayInstrumentation::run(MachineFunction &MF) {
203 auto &F = MF.getFunction();
204 auto InstrAttr = F.getFnAttribute("function-instrument");
205 bool AlwaysInstrument = alwaysInstrument(F);
206 bool NeverInstrument = InstrAttr.isStringAttribute() &&
207 InstrAttr.getValueAsString() == "xray-never";
208 if (NeverInstrument && !AlwaysInstrument)
209 return false;
210 auto IgnoreLoopsAttr = F.getFnAttribute("xray-ignore-loops");
211
212 uint64_t XRayThreshold = 0;
213 if (!AlwaysInstrument) {
214 bool IgnoreLoops = IgnoreLoopsAttr.isValid();
215 XRayThreshold = F.getFnAttributeAsParsedInteger(
216 "xray-instruction-threshold", std::numeric_limits<uint64_t>::max());
217 if (XRayThreshold == std::numeric_limits<uint64_t>::max())
218 return false;
219
220 // Count the number of MachineInstr`s in MachineFunction
221 uint64_t MICount = 0;
222 for (const auto &MBB : MF)
223 MICount += MBB.size();
224
225 bool TooFewInstrs = MICount < XRayThreshold;
226
227 if (!IgnoreLoops) {
228 // Get MachineLoopInfo or compute it on the fly if it's unavailable,
229 // which needs a MachineDominatorTree only for an irreducible CFG.
230 MachineDominatorTree ComputedMDT;
231 MachineLoopInfo ComputedMLI;
232 if (!MLI) {
233 ComputedMLI.calculate(MF, [&]() -> const MachineDominatorTree & {
234 if (!MDT) {
235 ComputedMDT.recalculate(MF);
236 MDT = &ComputedMDT;
237 }
238 return *MDT;
239 });
240 MLI = &ComputedMLI;
241 }
242
243 // Check if we have a loop.
244 // FIXME: Maybe make this smarter, and see whether the loops are dependent
245 // on inputs or side-effects?
246 if (MLI->empty() && TooFewInstrs)
247 return false; // Function is too small and has no loops.
248 } else if (TooFewInstrs) {
249 // Function is too small
250 return false;
251 }
252 }
253
254 // We look for the first non-empty MachineBasicBlock, so that we can insert
255 // the function instrumentation in the appropriate place.
256 auto MBI = llvm::find_if(
257 MF, [&](const MachineBasicBlock &MBB) { return !MBB.empty(); });
258 if (MBI == MF.end())
259 return false; // The function is empty.
260
261 auto *TII = MF.getSubtarget().getInstrInfo();
262 auto &FirstMBB = *MBI;
263 auto &FirstMI = *FirstMBB.begin();
264
265 if (!MF.getSubtarget().isXRaySupported()) {
266
267 const Function &Fn = FirstMBB.getParent()->getFunction();
268 Fn.getContext().diagnose(DiagnosticInfoUnsupported(
269 Fn, "An attempt to perform XRay instrumentation for an"
270 " unsupported target."));
271
272 return false;
273 }
274
275 if (!F.hasFnAttribute("xray-skip-entry")) {
276 // First, insert an PATCHABLE_FUNCTION_ENTER as the first instruction of the
277 // MachineFunction.
278 BuildMI(FirstMBB, FirstMI, FirstMI.getDebugLoc(),
279 TII->get(TargetOpcode::PATCHABLE_FUNCTION_ENTER));
280 }
281
282 if (!F.hasFnAttribute("xray-skip-exit")) {
283 switch (MF.getTarget().getTargetTriple().getArch()) {
284 case Triple::ArchType::arm:
285 case Triple::ArchType::thumb:
286 case Triple::ArchType::aarch64:
287 case Triple::ArchType::hexagon:
288 case Triple::ArchType::loongarch64:
289 case Triple::ArchType::mips:
290 case Triple::ArchType::mipsel:
291 case Triple::ArchType::mips64:
292 case Triple::ArchType::mips64el:
293 case Triple::ArchType::riscv32:
294 case Triple::ArchType::riscv64: {
295 // For the architectures which don't have a single return instruction
296 InstrumentationOptions op;
297 // AArch64 and RISC-V support patching tail calls.
298 op.HandleTailcall = MF.getTarget().getTargetTriple().isAArch64() ||
299 MF.getTarget().getTargetTriple().isRISCV();
300 op.HandleAllReturns = true;
301 prependRetWithPatchableExit(MF, TII, op);
302 break;
303 }
304 case Triple::ArchType::ppc64le:
305 case Triple::ArchType::systemz: {
306 // PPC has conditional returns. Turn them into branch and plain returns.
307 InstrumentationOptions op;
308 op.HandleTailcall = false;
309 op.HandleAllReturns = true;
310 replaceRetWithPatchableRet(MF, TII, op);
311 break;
312 }
313 default: {
314 // For the architectures that have a single return instruction (such as
315 // RETQ on x86_64).
316 InstrumentationOptions op;
317 op.HandleTailcall = true;
318 op.HandleAllReturns = false;
319 replaceRetWithPatchableRet(MF, TII, op);
320 break;
321 }
322 }
323 }
324 return true;
325}
326
327char XRayInstrumentationLegacy::ID = 0;
328char &llvm::XRayInstrumentationID = XRayInstrumentationLegacy::ID;
329INITIALIZE_PASS_BEGIN(XRayInstrumentationLegacy, "xray-instrumentation",
330 "Insert XRay ops", false, false)
332INITIALIZE_PASS_END(XRayInstrumentationLegacy, "xray-instrumentation",
333 "Insert XRay ops", false, false)
MachineBasicBlock & MBB
This file contains the simple types necessary to represent the attributes associated with functions a...
#define op(i)
const HexagonInstrInfo * TII
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#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
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:275
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:762
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:353
bool isTailCall(const MachineInstr &MI) const override
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
iterator_range< iterator > terminators()
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
Analysis pass that exposes the MachineLoopInfo for a machine function.
LLVM_ABI void calculate(MachineDominatorTree &MDT)
Calculate the natural loop information.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
void push_back(const T &Elt)
TargetInstrInfo - Interface to description of machine instruction set.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
DXILDebugInfoMap run(Module &M)
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI char & XRayInstrumentationID
This pass inserts the XRay instrumentation sleds if they are supported by the target platform.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1772