blob: 493c70e8fd6cd017bfb9922636e5c87baf3cde60 [file] [log] [blame]
Justin Bogner61ba2e32014-12-08 18:02:35 +00001//===-- InstrProfiling.cpp - Frontend instrumentation based profiling -----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass lowers instrprof_increment intrinsics emitted by a frontend for
11// profiling. It also builds the data structures and initialization code needed
12// for updating execution counts and emitting the profile at runtime.
13//
14//===----------------------------------------------------------------------===//
15
Xinliang David Li83bc4222015-10-22 20:32:12 +000016#include "llvm/ProfileData/InstrProf.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000017#include "llvm/Transforms/Instrumentation.h"
18
19#include "llvm/ADT/Triple.h"
20#include "llvm/IR/IRBuilder.h"
21#include "llvm/IR/IntrinsicInst.h"
22#include "llvm/IR/Module.h"
23#include "llvm/Transforms/Utils/ModuleUtils.h"
24
25using namespace llvm;
26
27#define DEBUG_TYPE "instrprof"
28
29namespace {
30
31class InstrProfiling : public ModulePass {
32public:
33 static char ID;
34
35 InstrProfiling() : ModulePass(ID) {}
36
37 InstrProfiling(const InstrProfOptions &Options)
38 : ModulePass(ID), Options(Options) {}
39
40 const char *getPassName() const override {
41 return "Frontend instrumentation-based coverage lowering";
42 }
43
44 bool runOnModule(Module &M) override;
45
46 void getAnalysisUsage(AnalysisUsage &AU) const override {
47 AU.setPreservesCFG();
48 }
49
50private:
51 InstrProfOptions Options;
52 Module *M;
53 DenseMap<GlobalVariable *, GlobalVariable *> RegionCounters;
54 std::vector<Value *> UsedVars;
55
56 bool isMachO() const {
57 return Triple(M->getTargetTriple()).isOSBinFormatMachO();
58 }
59
60 /// Get the section name for the counter variables.
61 StringRef getCountersSection() const {
Xinliang David Li83bc4222015-10-22 20:32:12 +000062 return getInstrProfCountersSectionName(isMachO());
Justin Bogner61ba2e32014-12-08 18:02:35 +000063 }
64
65 /// Get the section name for the name variables.
66 StringRef getNameSection() const {
Xinliang David Li83bc4222015-10-22 20:32:12 +000067 return getInstrProfNameSectionName(isMachO());
Justin Bogner61ba2e32014-12-08 18:02:35 +000068 }
69
70 /// Get the section name for the profile data variables.
71 StringRef getDataSection() const {
Xinliang David Li83bc4222015-10-22 20:32:12 +000072 return getInstrProfDataSectionName(isMachO());
Justin Bogner61ba2e32014-12-08 18:02:35 +000073 }
74
Justin Bognerd24e1852015-02-11 02:52:44 +000075 /// Get the section name for the coverage mapping data.
76 StringRef getCoverageSection() const {
Xinliang David Li83bc4222015-10-22 20:32:12 +000077 return getInstrProfCoverageSectionName(isMachO());
Justin Bognerd24e1852015-02-11 02:52:44 +000078 }
79
Justin Bogner61ba2e32014-12-08 18:02:35 +000080 /// Replace instrprof_increment with an increment of the appropriate value.
81 void lowerIncrement(InstrProfIncrementInst *Inc);
82
Justin Bognerd24e1852015-02-11 02:52:44 +000083 /// Set up the section and uses for coverage data and its references.
84 void lowerCoverageData(GlobalVariable *CoverageData);
85
Justin Bogner61ba2e32014-12-08 18:02:35 +000086 /// Get the region counters for an increment, creating them if necessary.
87 ///
88 /// If the counter array doesn't yet exist, the profile data variables
89 /// referring to them will also be created.
90 GlobalVariable *getOrCreateRegionCounters(InstrProfIncrementInst *Inc);
91
92 /// Emit runtime registration functions for each profile data variable.
93 void emitRegistration();
94
95 /// Emit the necessary plumbing to pull in the runtime initialization.
96 void emitRuntimeHook();
97
98 /// Add uses of our data variables and runtime hook.
99 void emitUses();
100
Justin Bognerba1900c2015-04-30 23:49:23 +0000101 /// Create a static initializer for our data, on platforms that need it,
102 /// and for any profile output file that was specified.
Justin Bogner61ba2e32014-12-08 18:02:35 +0000103 void emitInitialization();
104};
105
106} // anonymous namespace
107
108char InstrProfiling::ID = 0;
109INITIALIZE_PASS(InstrProfiling, "instrprof",
110 "Frontend instrumentation-based coverage lowering.", false,
111 false)
112
113ModulePass *llvm::createInstrProfilingPass(const InstrProfOptions &Options) {
114 return new InstrProfiling(Options);
115}
116
117bool InstrProfiling::runOnModule(Module &M) {
118 bool MadeChange = false;
119
120 this->M = &M;
121 RegionCounters.clear();
122 UsedVars.clear();
123
124 for (Function &F : M)
125 for (BasicBlock &BB : F)
126 for (auto I = BB.begin(), E = BB.end(); I != E;)
127 if (auto *Inc = dyn_cast<InstrProfIncrementInst>(I++)) {
128 lowerIncrement(Inc);
129 MadeChange = true;
130 }
Xinliang David Li83bc4222015-10-22 20:32:12 +0000131 if (GlobalVariable *Coverage =
132 M.getNamedGlobal(getCoverageMappingVarName())) {
Justin Bognerd24e1852015-02-11 02:52:44 +0000133 lowerCoverageData(Coverage);
134 MadeChange = true;
135 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000136 if (!MadeChange)
137 return false;
138
139 emitRegistration();
140 emitRuntimeHook();
141 emitUses();
142 emitInitialization();
143 return true;
144}
145
146void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
147 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
148
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000149 IRBuilder<> Builder(Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000150 uint64_t Index = Inc->getIndex()->getZExtValue();
Diego Novillob3029d22015-06-04 11:45:32 +0000151 Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
152 Value *Count = Builder.CreateLoad(Addr, "pgocount");
Justin Bogner61ba2e32014-12-08 18:02:35 +0000153 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
154 Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
155 Inc->eraseFromParent();
156}
157
Justin Bognerd24e1852015-02-11 02:52:44 +0000158void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageData) {
159 CoverageData->setSection(getCoverageSection());
160 CoverageData->setAlignment(8);
161
162 Constant *Init = CoverageData->getInitializer();
163 // We're expecting { i32, i32, i32, i32, [n x { i8*, i32, i32 }], [m x i8] }
164 // for some C. If not, the frontend's given us something broken.
165 assert(Init->getNumOperands() == 6 && "bad number of fields in coverage map");
166 assert(isa<ConstantArray>(Init->getAggregateElement(4)) &&
167 "invalid function list in coverage map");
168 ConstantArray *Records = cast<ConstantArray>(Init->getAggregateElement(4));
169 for (unsigned I = 0, E = Records->getNumOperands(); I < E; ++I) {
170 Constant *Record = Records->getOperand(I);
171 Value *V = const_cast<Value *>(Record->getOperand(0))->stripPointerCasts();
172
173 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
174 GlobalVariable *Name = cast<GlobalVariable>(V);
175
176 // If we have region counters for this name, we've already handled it.
177 auto It = RegionCounters.find(Name);
178 if (It != RegionCounters.end())
179 continue;
180
181 // Move the name variable to the right section.
182 Name->setSection(getNameSection());
183 Name->setAlignment(1);
184 }
185}
186
Justin Bogner61ba2e32014-12-08 18:02:35 +0000187/// Get the name of a profiling variable for a particular function.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000188static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000189 auto *Arr = cast<ConstantDataArray>(Inc->getName()->getInitializer());
190 StringRef Name = Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
Xinliang David Li83bc4222015-10-22 20:32:12 +0000191 return (Prefix + Name).str();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000192}
193
194GlobalVariable *
195InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
196 GlobalVariable *Name = Inc->getName();
197 auto It = RegionCounters.find(Name);
198 if (It != RegionCounters.end())
199 return It->second;
200
Wei Mi3cc92042015-09-23 22:40:45 +0000201 // Move the name variable to the right section. Place them in a COMDAT group
202 // if the associated function is a COMDAT. This will make sure that
203 // only one copy of counters of the COMDAT function will be emitted after
204 // linking.
Diego Novillodf4837b2015-05-27 19:34:01 +0000205 Function *Fn = Inc->getParent()->getParent();
Wei Mi3cc92042015-09-23 22:40:45 +0000206 Comdat *ProfileVarsComdat = nullptr;
207 if (Fn->hasComdat())
Xinliang David Li83bc4222015-10-22 20:32:12 +0000208 ProfileVarsComdat = M->getOrInsertComdat(
209 StringRef(getVarName(Inc, getInstrProfComdatPrefix())));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000210 Name->setSection(getNameSection());
211 Name->setAlignment(1);
Wei Mi3cc92042015-09-23 22:40:45 +0000212 Name->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000213
214 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
215 LLVMContext &Ctx = M->getContext();
216 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
217
218 // Create the counters variable.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000219 auto *Counters =
220 new GlobalVariable(*M, CounterTy, false, Name->getLinkage(),
221 Constant::getNullValue(CounterTy),
222 getVarName(Inc, getInstrProfCountersVarPrefix()));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000223 Counters->setVisibility(Name->getVisibility());
224 Counters->setSection(getCountersSection());
225 Counters->setAlignment(8);
Wei Mi3cc92042015-09-23 22:40:45 +0000226 Counters->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000227
228 RegionCounters[Inc->getName()] = Counters;
229
230 // Create data variable.
231 auto *NameArrayTy = Name->getType()->getPointerElementType();
232 auto *Int32Ty = Type::getInt32Ty(Ctx);
233 auto *Int64Ty = Type::getInt64Ty(Ctx);
234 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
235 auto *Int64PtrTy = Type::getInt64PtrTy(Ctx);
236
237 Type *DataTypes[] = {Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int64PtrTy};
238 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
239 Constant *DataVals[] = {
240 ConstantInt::get(Int32Ty, NameArrayTy->getArrayNumElements()),
241 ConstantInt::get(Int32Ty, NumCounters),
242 ConstantInt::get(Int64Ty, Inc->getHash()->getZExtValue()),
243 ConstantExpr::getBitCast(Name, Int8PtrTy),
244 ConstantExpr::getBitCast(Counters, Int64PtrTy)};
245 auto *Data = new GlobalVariable(*M, DataTy, true, Name->getLinkage(),
246 ConstantStruct::get(DataTy, DataVals),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000247 getVarName(Inc, getInstrProfDataVarPrefix()));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000248 Data->setVisibility(Name->getVisibility());
249 Data->setSection(getDataSection());
250 Data->setAlignment(8);
Wei Mi3cc92042015-09-23 22:40:45 +0000251 Data->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000252
253 // Mark the data variable as used so that it isn't stripped out.
254 UsedVars.push_back(Data);
255
256 return Counters;
257}
258
259void InstrProfiling::emitRegistration() {
260 // Don't do this for Darwin. compiler-rt uses linker magic.
261 if (Triple(M->getTargetTriple()).isOSDarwin())
262 return;
263
Xinliang David Li3dd88172015-10-13 18:39:48 +0000264 // Use linker script magic to get data/cnts/name start/end.
Xinliang David Liaa0592c2015-10-19 04:17:10 +0000265 if (Triple(M->getTargetTriple()).isOSLinux() ||
266 Triple(M->getTargetTriple()).isOSFreeBSD())
267 return;
Xinliang David Li3dd88172015-10-13 18:39:48 +0000268
Justin Bogner61ba2e32014-12-08 18:02:35 +0000269 // Construct the function.
270 auto *VoidTy = Type::getVoidTy(M->getContext());
271 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
272 auto *RegisterFTy = FunctionType::get(VoidTy, false);
273 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000274 getInstrProfRegFuncsName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000275 RegisterF->setUnnamedAddr(true);
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000276 if (Options.NoRedZone) RegisterF->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000277
Diego Novillob3029d22015-06-04 11:45:32 +0000278 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000279 auto *RuntimeRegisterF =
280 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000281 getInstrProfRegFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000282
283 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
284 for (Value *Data : UsedVars)
285 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
286 IRB.CreateRetVoid();
287}
288
289void InstrProfiling::emitRuntimeHook() {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000290
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000291 // We expect the linker to be invoked with -u<hook_var> flag for linux,
292 // for which case there is no need to emit the user function.
293 if (Triple(M->getTargetTriple()).isOSLinux())
294 return;
295
Justin Bogner61ba2e32014-12-08 18:02:35 +0000296 // If the module's provided its own runtime, we don't need to do anything.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000297 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName())) return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000298
299 // Declare an external variable that will pull in the runtime initialization.
300 auto *Int32Ty = Type::getInt32Ty(M->getContext());
301 auto *Var =
302 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000303 nullptr, getInstrProfRuntimeHookVarName());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000304
305 // Make a function that uses it.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000306 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
307 GlobalValue::LinkOnceODRLinkage,
308 getInstrProfRuntimeHookVarUseFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000309 User->addFnAttr(Attribute::NoInline);
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000310 if (Options.NoRedZone) User->addFnAttr(Attribute::NoRedZone);
Justin Bogner2e427d42015-02-25 22:52:20 +0000311 User->setVisibility(GlobalValue::HiddenVisibility);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000312
313 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
314 auto *Load = IRB.CreateLoad(Var);
315 IRB.CreateRet(Load);
316
317 // Mark the user variable as used so that it isn't stripped out.
318 UsedVars.push_back(User);
319}
320
321void InstrProfiling::emitUses() {
322 if (UsedVars.empty())
323 return;
324
325 GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used");
Diego Novillob3029d22015-06-04 11:45:32 +0000326 std::vector<Constant *> MergedVars;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000327 if (LLVMUsed) {
328 // Collect the existing members of llvm.used.
329 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
330 for (unsigned I = 0, E = Inits->getNumOperands(); I != E; ++I)
331 MergedVars.push_back(Inits->getOperand(I));
332 LLVMUsed->eraseFromParent();
333 }
334
335 Type *i8PTy = Type::getInt8PtrTy(M->getContext());
336 // Add uses for our data.
337 for (auto *Value : UsedVars)
338 MergedVars.push_back(
Diego Novillob3029d22015-06-04 11:45:32 +0000339 ConstantExpr::getBitCast(cast<Constant>(Value), i8PTy));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000340
341 // Recreate llvm.used.
342 ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size());
Diego Novillob3029d22015-06-04 11:45:32 +0000343 LLVMUsed =
344 new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage,
345 ConstantArray::get(ATy, MergedVars), "llvm.used");
Justin Bogner61ba2e32014-12-08 18:02:35 +0000346
347 LLVMUsed->setSection("llvm.metadata");
348}
349
350void InstrProfiling::emitInitialization() {
Justin Bognerba1900c2015-04-30 23:49:23 +0000351 std::string InstrProfileOutput = Options.InstrProfileOutput;
352
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000353 Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
354 if (!RegisterF && InstrProfileOutput.empty()) return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000355
356 // Create the initialization function.
357 auto *VoidTy = Type::getVoidTy(M->getContext());
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000358 auto *F = Function::Create(FunctionType::get(VoidTy, false),
359 GlobalValue::InternalLinkage,
360 getInstrProfInitFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000361 F->setUnnamedAddr(true);
362 F->addFnAttr(Attribute::NoInline);
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000363 if (Options.NoRedZone) F->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000364
365 // Add the basic block and the necessary calls.
366 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
Justin Bognerba1900c2015-04-30 23:49:23 +0000367 if (RegisterF)
David Blaikieff6409d2015-05-18 22:13:54 +0000368 IRB.CreateCall(RegisterF, {});
Justin Bognerba1900c2015-04-30 23:49:23 +0000369 if (!InstrProfileOutput.empty()) {
370 auto *Int8PtrTy = Type::getInt8PtrTy(M->getContext());
371 auto *SetNameTy = FunctionType::get(VoidTy, Int8PtrTy, false);
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000372 auto *SetNameF = Function::Create(SetNameTy, GlobalValue::ExternalLinkage,
373 getInstrProfFileOverriderFuncName(), M);
Justin Bognerba1900c2015-04-30 23:49:23 +0000374
Diego Novillob0257c82015-06-29 20:03:46 +0000375 // Create variable for profile name.
Justin Bognerba1900c2015-04-30 23:49:23 +0000376 Constant *ProfileNameConst =
377 ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
378 GlobalVariable *ProfileName =
379 new GlobalVariable(*M, ProfileNameConst->getType(), true,
380 GlobalValue::PrivateLinkage, ProfileNameConst);
381
382 IRB.CreateCall(SetNameF, IRB.CreatePointerCast(ProfileName, Int8PtrTy));
383 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000384 IRB.CreateRetVoid();
385
386 appendToGlobalCtors(*M, F, 0);
387}