blob: 463f5185c2a77b963feacd52085dc5feaff9e993 [file] [log] [blame]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001//===- XRayInstrumentation.cpp - Adds XRay instrumentation to functions. --===//
Dean Michael Berris52735fc2016-07-14 04:06:33 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Dean Michael Berris52735fc2016-07-14 04:06:33 +00006//
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
Eugene Zelenkofb69e662017-06-06 22:22:41 +000016#include "llvm/ADT/STLExtras.h"
Dean Michael Berris711dec22017-09-08 01:47:56 +000017#include "llvm/ADT/SmallVector.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000018#include "llvm/ADT/Triple.h"
19#include "llvm/CodeGen/MachineBasicBlock.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000020#include "llvm/CodeGen/MachineDominators.h"
Dean Michael Berris52735fc2016-07-14 04:06:33 +000021#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
Dean Michael Berris22f2bcf2017-05-04 01:24:26 +000024#include "llvm/CodeGen/MachineLoopInfo.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000025#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000026#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000027#include "llvm/IR/Attributes.h"
28#include "llvm/IR/Function.h"
29#include "llvm/Pass.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000030#include "llvm/Target/TargetMachine.h"
Dean Michael Berris52735fc2016-07-14 04:06:33 +000031
32using namespace llvm;
33
34namespace {
Eugene Zelenkofb69e662017-06-06 22:22:41 +000035
Tim Shencee75362017-09-22 18:30:02 +000036struct InstrumentationOptions {
37 // Whether to emit PATCHABLE_TAIL_CALL.
38 bool HandleTailcall;
39
40 // Whether to emit PATCHABLE_RET/PATCHABLE_FUNCTION_EXIT for all forms of
41 // return, e.g. conditional return.
42 bool HandleAllReturns;
43};
44
Dean Michael Berris52735fc2016-07-14 04:06:33 +000045struct XRayInstrumentation : public MachineFunctionPass {
46 static char ID;
47
48 XRayInstrumentation() : MachineFunctionPass(ID) {
49 initializeXRayInstrumentationPass(*PassRegistry::getPassRegistry());
50 }
51
Dean Michael Berris22f2bcf2017-05-04 01:24:26 +000052 void getAnalysisUsage(AnalysisUsage &AU) const override {
53 AU.setPreservesCFG();
Dean Michael Berris22f2bcf2017-05-04 01:24:26 +000054 AU.addPreserved<MachineLoopInfo>();
55 AU.addPreserved<MachineDominatorTree>();
56 MachineFunctionPass::getAnalysisUsage(AU);
57 }
58
Dean Michael Berris52735fc2016-07-14 04:06:33 +000059 bool runOnMachineFunction(MachineFunction &MF) override;
Dean Michael Berris464015442016-09-19 00:54:35 +000060
61private:
62 // Replace the original RET instruction with the exit sled code ("patchable
63 // ret" pseudo-instruction), so that at runtime XRay can replace the sled
64 // with a code jumping to XRay trampoline, which calls the tracing handler
65 // and, in the end, issues the RET instruction.
66 // This is the approach to go on CPUs which have a single RET instruction,
67 // like x86/x86_64.
68 void replaceRetWithPatchableRet(MachineFunction &MF,
Tim Shencee75362017-09-22 18:30:02 +000069 const TargetInstrInfo *TII,
70 InstrumentationOptions);
Serge Rogatcha3311332016-11-24 18:51:47 +000071
Dean Michael Berris464015442016-09-19 00:54:35 +000072 // Prepend the original return instruction with the exit sled code ("patchable
73 // function exit" pseudo-instruction), preserving the original return
74 // instruction just after the exit sled code.
75 // This is the approach to go on CPUs which have multiple options for the
76 // return instruction, like ARM. For such CPUs we can't just jump into the
77 // XRay trampoline and issue a single return instruction there. We rather
78 // have to call the trampoline and return from it to the original return
79 // instruction of the function being instrumented.
80 void prependRetWithPatchableExit(MachineFunction &MF,
Tim Shencee75362017-09-22 18:30:02 +000081 const TargetInstrInfo *TII,
82 InstrumentationOptions);
Dean Michael Berris52735fc2016-07-14 04:06:33 +000083};
Eugene Zelenkofb69e662017-06-06 22:22:41 +000084
85} // end anonymous namespace
Dean Michael Berris52735fc2016-07-14 04:06:33 +000086
Dean Michael Berris22f2bcf2017-05-04 01:24:26 +000087void XRayInstrumentation::replaceRetWithPatchableRet(
Tim Shencee75362017-09-22 18:30:02 +000088 MachineFunction &MF, const TargetInstrInfo *TII,
89 InstrumentationOptions op) {
Dean Michael Berris464015442016-09-19 00:54:35 +000090 // We look for *all* terminators and returns, then replace those with
Dean Michael Berris52735fc2016-07-14 04:06:33 +000091 // PATCHABLE_RET instructions.
92 SmallVector<MachineInstr *, 4> Terminators;
93 for (auto &MBB : MF) {
94 for (auto &T : MBB.terminators()) {
Dean Michael Berrise8ae5ba2016-09-01 01:29:13 +000095 unsigned Opc = 0;
Tim Shencee75362017-09-22 18:30:02 +000096 if (T.isReturn() &&
97 (op.HandleAllReturns || T.getOpcode() == TII->getReturnOpcode())) {
Dean Michael Berris52735fc2016-07-14 04:06:33 +000098 // Replace return instructions with:
99 // PATCHABLE_RET <Opcode>, <Operand>...
Dean Michael Berrise8ae5ba2016-09-01 01:29:13 +0000100 Opc = TargetOpcode::PATCHABLE_RET;
101 }
Tim Shencee75362017-09-22 18:30:02 +0000102 if (TII->isTailCall(T) && op.HandleTailcall) {
Dean Michael Berrise8ae5ba2016-09-01 01:29:13 +0000103 // Treat the tail call as a return instruction, which has a
104 // different-looking sled than the normal return case.
105 Opc = TargetOpcode::PATCHABLE_TAIL_CALL;
106 }
107 if (Opc != 0) {
108 auto MIB = BuildMI(MBB, T, T.getDebugLoc(), TII->get(Opc))
Dean Michael Berris52735fc2016-07-14 04:06:33 +0000109 .addImm(T.getOpcode());
110 for (auto &MO : T.operands())
Diana Picus116bbab2017-01-13 09:58:52 +0000111 MIB.add(MO);
Dean Michael Berris52735fc2016-07-14 04:06:33 +0000112 Terminators.push_back(&T);
Dean Michael Berris52735fc2016-07-14 04:06:33 +0000113 }
114 }
115 }
116
117 for (auto &I : Terminators)
118 I->eraseFromParent();
Dean Michael Berris464015442016-09-19 00:54:35 +0000119}
Dean Michael Berris52735fc2016-07-14 04:06:33 +0000120
Dean Michael Berris22f2bcf2017-05-04 01:24:26 +0000121void XRayInstrumentation::prependRetWithPatchableExit(
Tim Shencee75362017-09-22 18:30:02 +0000122 MachineFunction &MF, const TargetInstrInfo *TII,
123 InstrumentationOptions op) {
Dean Michael Berris711dec22017-09-08 01:47:56 +0000124 for (auto &MBB : MF)
Tim Shencee75362017-09-22 18:30:02 +0000125 for (auto &T : MBB.terminators()) {
126 unsigned Opc = 0;
127 if (T.isReturn() &&
128 (op.HandleAllReturns || T.getOpcode() == TII->getReturnOpcode())) {
129 Opc = TargetOpcode::PATCHABLE_FUNCTION_EXIT;
Dean Michael Berris156f6ca2016-10-18 05:54:15 +0000130 }
Tim Shencee75362017-09-22 18:30:02 +0000131 if (TII->isTailCall(T) && op.HandleTailcall) {
132 Opc = TargetOpcode::PATCHABLE_TAIL_CALL;
133 }
134 if (Opc != 0) {
135 // Prepend the return instruction with PATCHABLE_FUNCTION_EXIT or
136 // PATCHABLE_TAIL_CALL .
137 BuildMI(MBB, T, T.getDebugLoc(), TII->get(Opc));
138 }
139 }
Dean Michael Berris464015442016-09-19 00:54:35 +0000140}
141
142bool XRayInstrumentation::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000143 auto &F = MF.getFunction();
Dean Michael Berris464015442016-09-19 00:54:35 +0000144 auto InstrAttr = F.getFnAttribute("function-instrument");
145 bool AlwaysInstrument = !InstrAttr.hasAttribute(Attribute::None) &&
146 InstrAttr.isStringAttribute() &&
147 InstrAttr.getValueAsString() == "xray-always";
148 Attribute Attr = F.getFnAttribute("xray-instruction-threshold");
149 unsigned XRayThreshold = 0;
150 if (!AlwaysInstrument) {
151 if (Attr.hasAttribute(Attribute::None) || !Attr.isStringAttribute())
152 return false; // XRay threshold attribute not found.
153 if (Attr.getValueAsString().getAsInteger(10, XRayThreshold))
154 return false; // Invalid value for threshold.
Dean Michael Berris22f2bcf2017-05-04 01:24:26 +0000155
Serge Rogatch85427c02017-06-09 13:23:23 +0000156 // Count the number of MachineInstr`s in MachineFunction
Dimitry Andrice4b97452017-07-14 21:14:58 +0000157 int64_t MICount = 0;
Dean Michael Berris711dec22017-09-08 01:47:56 +0000158 for (const auto &MBB : MF)
Dimitry Andrice4b97452017-07-14 21:14:58 +0000159 MICount += MBB.size();
Serge Rogatch85427c02017-06-09 13:23:23 +0000160
Michael Zolotukhinfb3f5092018-03-20 17:02:29 +0000161 // Get MachineDominatorTree or compute it on the fly if it's unavailable
162 auto *MDT = getAnalysisIfAvailable<MachineDominatorTree>();
163 MachineDominatorTree ComputedMDT;
164 if (!MDT) {
165 ComputedMDT.getBase().recalculate(MF);
166 MDT = &ComputedMDT;
167 }
168
169 // Get MachineLoopInfo or compute it on the fly if it's unavailable
170 auto *MLI = getAnalysisIfAvailable<MachineLoopInfo>();
171 MachineLoopInfo ComputedMLI;
172 if (!MLI) {
173 ComputedMLI.getBase().analyze(MDT->getBase());
174 MLI = &ComputedMLI;
175 }
176
Dean Michael Berris22f2bcf2017-05-04 01:24:26 +0000177 // Check if we have a loop.
178 // FIXME: Maybe make this smarter, and see whether the loops are dependent
179 // on inputs or side-effects?
Michael Zolotukhinfb3f5092018-03-20 17:02:29 +0000180 if (MLI->empty() && MICount < XRayThreshold)
Dean Michael Berris22f2bcf2017-05-04 01:24:26 +0000181 return false; // Function is too small and has no loops.
Dean Michael Berris464015442016-09-19 00:54:35 +0000182 }
183
Dean Michael Berris03b8be52016-12-19 09:20:38 +0000184 // We look for the first non-empty MachineBasicBlock, so that we can insert
185 // the function instrumentation in the appropriate place.
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000186 auto MBI = llvm::find_if(
187 MF, [&](const MachineBasicBlock &MBB) { return !MBB.empty(); });
Dean Michael Berris03b8be52016-12-19 09:20:38 +0000188 if (MBI == MF.end())
189 return false; // The function is empty.
190
191 auto *TII = MF.getSubtarget().getInstrInfo();
192 auto &FirstMBB = *MBI;
Dean Michael Berris464015442016-09-19 00:54:35 +0000193 auto &FirstMI = *FirstMBB.begin();
194
195 if (!MF.getSubtarget().isXRaySupported()) {
196 FirstMI.emitError("An attempt to perform XRay instrumentation for an"
Dean Michael Berris22f2bcf2017-05-04 01:24:26 +0000197 " unsupported target.");
Dean Michael Berris464015442016-09-19 00:54:35 +0000198 return false;
199 }
200
Dean Michael Berris464015442016-09-19 00:54:35 +0000201 // First, insert an PATCHABLE_FUNCTION_ENTER as the first instruction of the
202 // MachineFunction.
Dean Michael Berris464015442016-09-19 00:54:35 +0000203 BuildMI(FirstMBB, FirstMI, FirstMI.getDebugLoc(),
204 TII->get(TargetOpcode::PATCHABLE_FUNCTION_ENTER));
205
206 switch (MF.getTarget().getTargetTriple().getArch()) {
207 case Triple::ArchType::arm:
208 case Triple::ArchType::thumb:
Dean Michael Berris3234d3a2016-11-17 05:15:37 +0000209 case Triple::ArchType::aarch64:
Sagar Thakurec657922017-02-15 10:48:11 +0000210 case Triple::ArchType::mips:
211 case Triple::ArchType::mipsel:
212 case Triple::ArchType::mips64:
Tim Shencee75362017-09-22 18:30:02 +0000213 case Triple::ArchType::mips64el: {
Dean Michael Berris464015442016-09-19 00:54:35 +0000214 // For the architectures which don't have a single return instruction
Tim Shencee75362017-09-22 18:30:02 +0000215 InstrumentationOptions op;
216 op.HandleTailcall = false;
217 op.HandleAllReturns = true;
218 prependRetWithPatchableExit(MF, TII, op);
Dean Michael Berris464015442016-09-19 00:54:35 +0000219 break;
Tim Shencee75362017-09-22 18:30:02 +0000220 }
221 case Triple::ArchType::ppc64le: {
222 // PPC has conditional returns. Turn them into branch and plain returns.
223 InstrumentationOptions op;
224 op.HandleTailcall = false;
225 op.HandleAllReturns = true;
226 replaceRetWithPatchableRet(MF, TII, op);
227 break;
228 }
229 default: {
Dean Michael Berris464015442016-09-19 00:54:35 +0000230 // For the architectures that have a single return instruction (such as
231 // RETQ on x86_64).
Tim Shencee75362017-09-22 18:30:02 +0000232 InstrumentationOptions op;
233 op.HandleTailcall = true;
234 op.HandleAllReturns = false;
235 replaceRetWithPatchableRet(MF, TII, op);
Dean Michael Berris464015442016-09-19 00:54:35 +0000236 break;
237 }
Tim Shencee75362017-09-22 18:30:02 +0000238 }
Dean Michael Berris52735fc2016-07-14 04:06:33 +0000239 return true;
240}
241
242char XRayInstrumentation::ID = 0;
243char &llvm::XRayInstrumentationID = XRayInstrumentation::ID;
Dean Michael Berris22f2bcf2017-05-04 01:24:26 +0000244INITIALIZE_PASS_BEGIN(XRayInstrumentation, "xray-instrumentation",
245 "Insert XRay ops", false, false)
246INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
247INITIALIZE_PASS_END(XRayInstrumentation, "xray-instrumentation",
248 "Insert XRay ops", false, false)