blob: 0718ddcb6ec75dfde2c0af3c4b4975ebb8c084f6 [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
16#include "llvm/Transforms/Instrumentation.h"
17
18#include "llvm/ADT/Triple.h"
19#include "llvm/IR/IRBuilder.h"
20#include "llvm/IR/IntrinsicInst.h"
21#include "llvm/IR/Module.h"
22#include "llvm/Transforms/Utils/ModuleUtils.h"
23
24using namespace llvm;
25
26#define DEBUG_TYPE "instrprof"
27
28namespace {
29
30class InstrProfiling : public ModulePass {
31public:
32 static char ID;
33
34 InstrProfiling() : ModulePass(ID) {}
35
36 InstrProfiling(const InstrProfOptions &Options)
37 : ModulePass(ID), Options(Options) {}
38
39 const char *getPassName() const override {
40 return "Frontend instrumentation-based coverage lowering";
41 }
42
43 bool runOnModule(Module &M) override;
44
45 void getAnalysisUsage(AnalysisUsage &AU) const override {
46 AU.setPreservesCFG();
47 }
48
49private:
50 InstrProfOptions Options;
51 Module *M;
52 DenseMap<GlobalVariable *, GlobalVariable *> RegionCounters;
53 std::vector<Value *> UsedVars;
54
55 bool isMachO() const {
56 return Triple(M->getTargetTriple()).isOSBinFormatMachO();
57 }
58
59 /// Get the section name for the counter variables.
60 StringRef getCountersSection() const {
61 return isMachO() ? "__DATA,__llvm_prf_cnts" : "__llvm_prf_cnts";
62 }
63
64 /// Get the section name for the name variables.
65 StringRef getNameSection() const {
66 return isMachO() ? "__DATA,__llvm_prf_names" : "__llvm_prf_names";
67 }
68
69 /// Get the section name for the profile data variables.
70 StringRef getDataSection() const {
71 return isMachO() ? "__DATA,__llvm_prf_data" : "__llvm_prf_data";
72 }
73
Justin Bognerd24e1852015-02-11 02:52:44 +000074 /// Get the section name for the coverage mapping data.
75 StringRef getCoverageSection() const {
76 return isMachO() ? "__DATA,__llvm_covmap" : "__llvm_covmap";
77 }
78
Justin Bogner61ba2e32014-12-08 18:02:35 +000079 /// Replace instrprof_increment with an increment of the appropriate value.
80 void lowerIncrement(InstrProfIncrementInst *Inc);
81
Justin Bognerd24e1852015-02-11 02:52:44 +000082 /// Set up the section and uses for coverage data and its references.
83 void lowerCoverageData(GlobalVariable *CoverageData);
84
Justin Bogner61ba2e32014-12-08 18:02:35 +000085 /// Get the region counters for an increment, creating them if necessary.
86 ///
87 /// If the counter array doesn't yet exist, the profile data variables
88 /// referring to them will also be created.
89 GlobalVariable *getOrCreateRegionCounters(InstrProfIncrementInst *Inc);
90
91 /// Emit runtime registration functions for each profile data variable.
92 void emitRegistration();
93
94 /// Emit the necessary plumbing to pull in the runtime initialization.
95 void emitRuntimeHook();
96
97 /// Add uses of our data variables and runtime hook.
98 void emitUses();
99
Justin Bognerba1900c2015-04-30 23:49:23 +0000100 /// Create a static initializer for our data, on platforms that need it,
101 /// and for any profile output file that was specified.
Justin Bogner61ba2e32014-12-08 18:02:35 +0000102 void emitInitialization();
103};
104
105} // anonymous namespace
106
107char InstrProfiling::ID = 0;
108INITIALIZE_PASS(InstrProfiling, "instrprof",
109 "Frontend instrumentation-based coverage lowering.", false,
110 false)
111
112ModulePass *llvm::createInstrProfilingPass(const InstrProfOptions &Options) {
113 return new InstrProfiling(Options);
114}
115
116bool InstrProfiling::runOnModule(Module &M) {
117 bool MadeChange = false;
118
119 this->M = &M;
120 RegionCounters.clear();
121 UsedVars.clear();
122
123 for (Function &F : M)
124 for (BasicBlock &BB : F)
125 for (auto I = BB.begin(), E = BB.end(); I != E;)
126 if (auto *Inc = dyn_cast<InstrProfIncrementInst>(I++)) {
127 lowerIncrement(Inc);
128 MadeChange = true;
129 }
Justin Bognerd24e1852015-02-11 02:52:44 +0000130 if (GlobalVariable *Coverage = M.getNamedGlobal("__llvm_coverage_mapping")) {
131 lowerCoverageData(Coverage);
132 MadeChange = true;
133 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000134 if (!MadeChange)
135 return false;
136
137 emitRegistration();
138 emitRuntimeHook();
139 emitUses();
140 emitInitialization();
141 return true;
142}
143
144void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
145 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
146
147 IRBuilder<> Builder(Inc->getParent(), *Inc);
148 uint64_t Index = Inc->getIndex()->getZExtValue();
149 llvm::Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
150 llvm::Value *Count = Builder.CreateLoad(Addr, "pgocount");
151 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
152 Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
153 Inc->eraseFromParent();
154}
155
Justin Bognerd24e1852015-02-11 02:52:44 +0000156void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageData) {
157 CoverageData->setSection(getCoverageSection());
158 CoverageData->setAlignment(8);
159
160 Constant *Init = CoverageData->getInitializer();
161 // We're expecting { i32, i32, i32, i32, [n x { i8*, i32, i32 }], [m x i8] }
162 // for some C. If not, the frontend's given us something broken.
163 assert(Init->getNumOperands() == 6 && "bad number of fields in coverage map");
164 assert(isa<ConstantArray>(Init->getAggregateElement(4)) &&
165 "invalid function list in coverage map");
166 ConstantArray *Records = cast<ConstantArray>(Init->getAggregateElement(4));
167 for (unsigned I = 0, E = Records->getNumOperands(); I < E; ++I) {
168 Constant *Record = Records->getOperand(I);
169 Value *V = const_cast<Value *>(Record->getOperand(0))->stripPointerCasts();
170
171 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
172 GlobalVariable *Name = cast<GlobalVariable>(V);
173
174 // If we have region counters for this name, we've already handled it.
175 auto It = RegionCounters.find(Name);
176 if (It != RegionCounters.end())
177 continue;
178
179 // Move the name variable to the right section.
180 Name->setSection(getNameSection());
181 Name->setAlignment(1);
182 }
183}
184
Justin Bogner61ba2e32014-12-08 18:02:35 +0000185/// Get the name of a profiling variable for a particular function.
186static std::string getVarName(InstrProfIncrementInst *Inc, StringRef VarName) {
187 auto *Arr = cast<ConstantDataArray>(Inc->getName()->getInitializer());
188 StringRef Name = Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
189 return ("__llvm_profile_" + VarName + "_" + Name).str();
190}
191
192GlobalVariable *
193InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
194 GlobalVariable *Name = Inc->getName();
195 auto It = RegionCounters.find(Name);
196 if (It != RegionCounters.end())
197 return It->second;
198
199 // Move the name variable to the right section.
200 Name->setSection(getNameSection());
201 Name->setAlignment(1);
202
203 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
204 LLVMContext &Ctx = M->getContext();
205 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
206
207 // Create the counters variable.
208 auto *Counters = new GlobalVariable(*M, CounterTy, false, Name->getLinkage(),
209 Constant::getNullValue(CounterTy),
210 getVarName(Inc, "counters"));
211 Counters->setVisibility(Name->getVisibility());
212 Counters->setSection(getCountersSection());
213 Counters->setAlignment(8);
214
215 RegionCounters[Inc->getName()] = Counters;
216
217 // Create data variable.
218 auto *NameArrayTy = Name->getType()->getPointerElementType();
219 auto *Int32Ty = Type::getInt32Ty(Ctx);
220 auto *Int64Ty = Type::getInt64Ty(Ctx);
221 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
222 auto *Int64PtrTy = Type::getInt64PtrTy(Ctx);
223
224 Type *DataTypes[] = {Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int64PtrTy};
225 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
226 Constant *DataVals[] = {
227 ConstantInt::get(Int32Ty, NameArrayTy->getArrayNumElements()),
228 ConstantInt::get(Int32Ty, NumCounters),
229 ConstantInt::get(Int64Ty, Inc->getHash()->getZExtValue()),
230 ConstantExpr::getBitCast(Name, Int8PtrTy),
231 ConstantExpr::getBitCast(Counters, Int64PtrTy)};
232 auto *Data = new GlobalVariable(*M, DataTy, true, Name->getLinkage(),
233 ConstantStruct::get(DataTy, DataVals),
234 getVarName(Inc, "data"));
235 Data->setVisibility(Name->getVisibility());
236 Data->setSection(getDataSection());
237 Data->setAlignment(8);
238
239 // Mark the data variable as used so that it isn't stripped out.
240 UsedVars.push_back(Data);
241
242 return Counters;
243}
244
245void InstrProfiling::emitRegistration() {
246 // Don't do this for Darwin. compiler-rt uses linker magic.
247 if (Triple(M->getTargetTriple()).isOSDarwin())
248 return;
249
250 // Construct the function.
251 auto *VoidTy = Type::getVoidTy(M->getContext());
252 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
253 auto *RegisterFTy = FunctionType::get(VoidTy, false);
254 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
255 "__llvm_profile_register_functions", M);
256 RegisterF->setUnnamedAddr(true);
257 if (Options.NoRedZone)
258 RegisterF->addFnAttr(Attribute::NoRedZone);
259
260 auto *RuntimeRegisterTy = llvm::FunctionType::get(VoidTy, VoidPtrTy, false);
261 auto *RuntimeRegisterF =
262 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
263 "__llvm_profile_register_function", M);
264
265 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
266 for (Value *Data : UsedVars)
267 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
268 IRB.CreateRetVoid();
269}
270
271void InstrProfiling::emitRuntimeHook() {
272 const char *const RuntimeVarName = "__llvm_profile_runtime";
273 const char *const RuntimeUserName = "__llvm_profile_runtime_user";
274
275 // If the module's provided its own runtime, we don't need to do anything.
276 if (M->getGlobalVariable(RuntimeVarName))
277 return;
278
279 // Declare an external variable that will pull in the runtime initialization.
280 auto *Int32Ty = Type::getInt32Ty(M->getContext());
281 auto *Var =
282 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
283 nullptr, RuntimeVarName);
284
285 // Make a function that uses it.
286 auto *User =
287 Function::Create(FunctionType::get(Int32Ty, false),
288 GlobalValue::LinkOnceODRLinkage, RuntimeUserName, M);
289 User->addFnAttr(Attribute::NoInline);
290 if (Options.NoRedZone)
291 User->addFnAttr(Attribute::NoRedZone);
Justin Bogner2e427d42015-02-25 22:52:20 +0000292 User->setVisibility(GlobalValue::HiddenVisibility);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000293
294 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
295 auto *Load = IRB.CreateLoad(Var);
296 IRB.CreateRet(Load);
297
298 // Mark the user variable as used so that it isn't stripped out.
299 UsedVars.push_back(User);
300}
301
302void InstrProfiling::emitUses() {
303 if (UsedVars.empty())
304 return;
305
306 GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used");
307 std::vector<Constant*> MergedVars;
308 if (LLVMUsed) {
309 // Collect the existing members of llvm.used.
310 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
311 for (unsigned I = 0, E = Inits->getNumOperands(); I != E; ++I)
312 MergedVars.push_back(Inits->getOperand(I));
313 LLVMUsed->eraseFromParent();
314 }
315
316 Type *i8PTy = Type::getInt8PtrTy(M->getContext());
317 // Add uses for our data.
318 for (auto *Value : UsedVars)
319 MergedVars.push_back(
320 ConstantExpr::getBitCast(cast<llvm::Constant>(Value), i8PTy));
321
322 // Recreate llvm.used.
323 ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size());
324 LLVMUsed = new llvm::GlobalVariable(
325 *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
326 llvm::ConstantArray::get(ATy, MergedVars), "llvm.used");
327
328 LLVMUsed->setSection("llvm.metadata");
329}
330
331void InstrProfiling::emitInitialization() {
Justin Bognerba1900c2015-04-30 23:49:23 +0000332 std::string InstrProfileOutput = Options.InstrProfileOutput;
333
Justin Bogner61ba2e32014-12-08 18:02:35 +0000334 Constant *RegisterF = M->getFunction("__llvm_profile_register_functions");
Justin Bognerba1900c2015-04-30 23:49:23 +0000335 if (!RegisterF && InstrProfileOutput.empty())
Justin Bogner61ba2e32014-12-08 18:02:35 +0000336 return;
337
338 // Create the initialization function.
339 auto *VoidTy = Type::getVoidTy(M->getContext());
340 auto *F =
341 Function::Create(FunctionType::get(VoidTy, false),
342 GlobalValue::InternalLinkage, "__llvm_profile_init", M);
343 F->setUnnamedAddr(true);
344 F->addFnAttr(Attribute::NoInline);
345 if (Options.NoRedZone)
346 F->addFnAttr(Attribute::NoRedZone);
347
348 // Add the basic block and the necessary calls.
349 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
Justin Bognerba1900c2015-04-30 23:49:23 +0000350 if (RegisterF)
David Blaikieff6409d2015-05-18 22:13:54 +0000351 IRB.CreateCall(RegisterF, {});
Justin Bognerba1900c2015-04-30 23:49:23 +0000352 if (!InstrProfileOutput.empty()) {
353 auto *Int8PtrTy = Type::getInt8PtrTy(M->getContext());
354 auto *SetNameTy = FunctionType::get(VoidTy, Int8PtrTy, false);
355 auto *SetNameF =
356 Function::Create(SetNameTy, GlobalValue::ExternalLinkage,
Justin Bogner03038a52015-05-12 21:23:09 +0000357 "__llvm_profile_override_default_filename", M);
Justin Bognerba1900c2015-04-30 23:49:23 +0000358
359 // Create variable for profile name
360 Constant *ProfileNameConst =
361 ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
362 GlobalVariable *ProfileName =
363 new GlobalVariable(*M, ProfileNameConst->getType(), true,
364 GlobalValue::PrivateLinkage, ProfileNameConst);
365
366 IRB.CreateCall(SetNameF, IRB.CreatePointerCast(ProfileName, Int8PtrTy));
367 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000368 IRB.CreateRetVoid();
369
370 appendToGlobalCtors(*M, F, 0);
371}