blob: a3fc16c9a9f73310f3fbe06b8e5950cca94036ac [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//
Betul Buyukkurt6fac1742015-11-18 18:14:55 +000010// This pass lowers instrprof_* intrinsics emitted by a frontend for profiling.
11// It also builds the data structures and initialization code needed for
12// updating execution counts and emitting the profile at runtime.
Justin Bogner61ba2e32014-12-08 18:02:35 +000013//
14//===----------------------------------------------------------------------===//
15
Justin Bogner61ba2e32014-12-08 18:02:35 +000016#include "llvm/ADT/Triple.h"
17#include "llvm/IR/IRBuilder.h"
18#include "llvm/IR/IntrinsicInst.h"
19#include "llvm/IR/Module.h"
Betul Buyukkurt6fac1742015-11-18 18:14:55 +000020#include "llvm/ProfileData/InstrProf.h"
Xinliang David Lie6b89292016-04-18 17:47:38 +000021#include "llvm/Transforms/InstrProfiling.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000022#include "llvm/Transforms/Utils/ModuleUtils.h"
23
24using namespace llvm;
25
26#define DEBUG_TYPE "instrprof"
27
28namespace {
29
Xinliang David Lia82d6c02016-02-08 18:13:49 +000030cl::opt<bool> DoNameCompression("enable-name-compression",
31 cl::desc("Enable name string compression"),
32 cl::init(true));
33
Xinliang David Lib628dd32016-05-21 22:55:34 +000034cl::opt<bool> ValueProfileStaticAlloc(
35 "vp-static-alloc",
36 cl::desc("Do static counter allocation for value profiler"),
37 cl::init(true));
38cl::opt<double> NumCountersPerValueSite(
39 "vp-counters-per-site",
40 cl::desc("The average number of profile counters allocated "
41 "per value profiling site."),
42 // This is set to a very small value because in real programs, only
43 // a very small percentage of value sites have non-zero targets, e.g, 1/30.
44 // For those sites with non-zero profile, the average number of targets
45 // is usually smaller than 2.
46 cl::init(1.0));
47
Xinliang David Lie6b89292016-04-18 17:47:38 +000048class InstrProfilingLegacyPass : public ModulePass {
49 InstrProfiling InstrProf;
50
Justin Bogner61ba2e32014-12-08 18:02:35 +000051public:
52 static char ID;
Xinliang David Lie6b89292016-04-18 17:47:38 +000053 InstrProfilingLegacyPass() : ModulePass(ID), InstrProf() {}
54 InstrProfilingLegacyPass(const InstrProfOptions &Options)
55 : ModulePass(ID), InstrProf(Options) {}
Justin Bogner61ba2e32014-12-08 18:02:35 +000056 const char *getPassName() const override {
57 return "Frontend instrumentation-based coverage lowering";
58 }
59
Xinliang David Lie6b89292016-04-18 17:47:38 +000060 bool runOnModule(Module &M) override { return InstrProf.run(M); }
Justin Bogner61ba2e32014-12-08 18:02:35 +000061
62 void getAnalysisUsage(AnalysisUsage &AU) const override {
63 AU.setPreservesCFG();
64 }
Justin Bogner61ba2e32014-12-08 18:02:35 +000065};
66
67} // anonymous namespace
68
Xinliang David Lie6b89292016-04-18 17:47:38 +000069PreservedAnalyses InstrProfiling::run(Module &M, AnalysisManager<Module> &AM) {
70 if (!run(M))
71 return PreservedAnalyses::all();
72
73 return PreservedAnalyses::none();
74}
75
76char InstrProfilingLegacyPass::ID = 0;
77INITIALIZE_PASS(InstrProfilingLegacyPass, "instrprof",
Justin Bogner61ba2e32014-12-08 18:02:35 +000078 "Frontend instrumentation-based coverage lowering.", false,
79 false)
80
Xinliang David Lie6b89292016-04-18 17:47:38 +000081ModulePass *llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options) {
82 return new InstrProfilingLegacyPass(Options);
Justin Bogner61ba2e32014-12-08 18:02:35 +000083}
84
Xinliang David Lie6b89292016-04-18 17:47:38 +000085bool InstrProfiling::isMachO() const {
86 return Triple(M->getTargetTriple()).isOSBinFormatMachO();
87}
88
89/// Get the section name for the counter variables.
90StringRef InstrProfiling::getCountersSection() const {
91 return getInstrProfCountersSectionName(isMachO());
92}
93
94/// Get the section name for the name variables.
95StringRef InstrProfiling::getNameSection() const {
96 return getInstrProfNameSectionName(isMachO());
97}
98
99/// Get the section name for the profile data variables.
100StringRef InstrProfiling::getDataSection() const {
101 return getInstrProfDataSectionName(isMachO());
102}
103
104/// Get the section name for the coverage mapping data.
105StringRef InstrProfiling::getCoverageSection() const {
106 return getInstrProfCoverageSectionName(isMachO());
107}
108
109bool InstrProfiling::run(Module &M) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000110 bool MadeChange = false;
111
112 this->M = &M;
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000113 NamesVar = nullptr;
114 NamesSize = 0;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000115 ProfileDataMap.clear();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000116 UsedVars.clear();
117
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000118 // We did not know how many value sites there would be inside
119 // the instrumented function. This is counting the number of instrumented
120 // target value sites to enter it as field in the profile data variable.
Rong Xu294572f2016-01-19 18:29:54 +0000121 for (Function &F : M) {
122 InstrProfIncrementInst *FirstProfIncInst = nullptr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000123 for (BasicBlock &BB : F)
Rong Xu294572f2016-01-19 18:29:54 +0000124 for (auto I = BB.begin(), E = BB.end(); I != E; I++)
125 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000126 computeNumValueSiteCounts(Ind);
Rong Xu294572f2016-01-19 18:29:54 +0000127 else if (FirstProfIncInst == nullptr)
128 FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
129
130 // Value profiling intrinsic lowering requires per-function profile data
131 // variable to be created first.
132 if (FirstProfIncInst != nullptr)
133 static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
134 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000135
136 for (Function &F : M)
137 for (BasicBlock &BB : F)
138 for (auto I = BB.begin(), E = BB.end(); I != E;) {
139 auto Instr = I++;
140 if (auto *Inc = dyn_cast<InstrProfIncrementInst>(Instr)) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000141 lowerIncrement(Inc);
142 MadeChange = true;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000143 } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
144 lowerValueProfileInst(Ind);
145 MadeChange = true;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000146 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000147 }
148
Xinliang David Li81056072016-01-07 20:05:49 +0000149 if (GlobalVariable *CoverageNamesVar =
Xinliang David Li440cd702016-01-20 00:24:36 +0000150 M.getNamedGlobal(getCoverageUnusedNamesVarName())) {
Xinliang David Li81056072016-01-07 20:05:49 +0000151 lowerCoverageData(CoverageNamesVar);
Justin Bognerd24e1852015-02-11 02:52:44 +0000152 MadeChange = true;
153 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000154
Justin Bogner61ba2e32014-12-08 18:02:35 +0000155 if (!MadeChange)
156 return false;
157
Xinliang David Lib628dd32016-05-21 22:55:34 +0000158 emitVNodes();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000159 emitNameData();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000160 emitRegistration();
161 emitRuntimeHook();
162 emitUses();
163 emitInitialization();
164 return true;
165}
166
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000167static Constant *getOrInsertValueProfilingCall(Module &M) {
Xinliang David Lic7673232015-11-22 00:22:07 +0000168 LLVMContext &Ctx = M.getContext();
169 auto *ReturnTy = Type::getVoidTy(M.getContext());
170 Type *ParamTypes[] = {
171#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
172#include "llvm/ProfileData/InstrProfData.inc"
173 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000174 auto *ValueProfilingCallTy =
Xinliang David Lic7673232015-11-22 00:22:07 +0000175 FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
Xinliang David Li924e0582015-11-22 05:42:31 +0000176 return M.getOrInsertFunction(getInstrProfValueProfFuncName(),
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000177 ValueProfilingCallTy);
178}
179
180void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
181
182 GlobalVariable *Name = Ind->getName();
183 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
184 uint64_t Index = Ind->getIndex()->getZExtValue();
185 auto It = ProfileDataMap.find(Name);
186 if (It == ProfileDataMap.end()) {
187 PerFunctionProfileData PD;
188 PD.NumValueSites[ValueKind] = Index + 1;
189 ProfileDataMap[Name] = PD;
190 } else if (It->second.NumValueSites[ValueKind] <= Index)
191 It->second.NumValueSites[ValueKind] = Index + 1;
192}
193
194void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
195
196 GlobalVariable *Name = Ind->getName();
197 auto It = ProfileDataMap.find(Name);
198 assert(It != ProfileDataMap.end() && It->second.DataVar &&
199 "value profiling detected in function with no counter incerement");
200
201 GlobalVariable *DataVar = It->second.DataVar;
202 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
203 uint64_t Index = Ind->getIndex()->getZExtValue();
204 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
205 Index += It->second.NumValueSites[Kind];
206
207 IRBuilder<> Builder(Ind);
208 Value* Args[3] = {Ind->getTargetValue(),
209 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
210 Builder.getInt32(Index)};
211 Ind->replaceAllUsesWith(
212 Builder.CreateCall(getOrInsertValueProfilingCall(*M), Args));
213 Ind->eraseFromParent();
214}
215
Justin Bogner61ba2e32014-12-08 18:02:35 +0000216void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
217 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
218
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000219 IRBuilder<> Builder(Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000220 uint64_t Index = Inc->getIndex()->getZExtValue();
Diego Novillob3029d22015-06-04 11:45:32 +0000221 Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
222 Value *Count = Builder.CreateLoad(Addr, "pgocount");
Justin Bogner61ba2e32014-12-08 18:02:35 +0000223 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
224 Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
225 Inc->eraseFromParent();
226}
227
Xinliang David Li81056072016-01-07 20:05:49 +0000228void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
Justin Bognerd24e1852015-02-11 02:52:44 +0000229
Xinliang David Li81056072016-01-07 20:05:49 +0000230 ConstantArray *Names =
231 cast<ConstantArray>(CoverageNamesVar->getInitializer());
232 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
233 Constant *NC = Names->getOperand(I);
234 Value *V = NC->stripPointerCasts();
Justin Bognerd24e1852015-02-11 02:52:44 +0000235 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
236 GlobalVariable *Name = cast<GlobalVariable>(V);
237
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000238 Name->setLinkage(GlobalValue::PrivateLinkage);
239 ReferencedNames.push_back(Name);
Justin Bognerd24e1852015-02-11 02:52:44 +0000240 }
241}
242
Justin Bogner61ba2e32014-12-08 18:02:35 +0000243/// Get the name of a profiling variable for a particular function.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000244static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000245 StringRef NamePrefix = getInstrProfNameVarPrefix();
246 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
Xinliang David Li83bc4222015-10-22 20:32:12 +0000247 return (Prefix + Name).str();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000248}
249
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000250static inline bool shouldRecordFunctionAddr(Function *F) {
251 // Check the linkage
252 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
253 !F->hasAvailableExternallyLinkage())
254 return true;
Rong Xuaf5aeba2016-04-27 21:17:30 +0000255 // Prohibit function address recording if the function is both internal and
256 // COMDAT. This avoids the profile data variable referencing internal symbols
257 // in COMDAT.
258 if (F->hasLocalLinkage() && F->hasComdat())
259 return false;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000260 // Check uses of this function for other than direct calls or invokes to it.
Xinliang David Li7008ce32016-06-02 16:33:41 +0000261 // Inline virtual functions have linkeOnceODR linkage. When a key method
262 // exists, the vtable will only be emitted in the TU where the key method
263 // is defined. In a TU where vtable is not available, the function won't
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000264 // be 'addresstaken'. If its address is not recorded here, the profile data
265 // with missing address may be picked by the linker leading to missing
266 // indirect call target info.
267 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000268}
269
Xinliang David Li985ff202016-02-27 23:11:30 +0000270static inline bool needsComdatForCounter(Function &F, Module &M) {
271
272 if (F.hasComdat())
273 return true;
274
275 Triple TT(M.getTargetTriple());
276 if (!TT.isOSBinFormatELF())
277 return false;
278
279 // See createPGOFuncNameVar for more details. To avoid link errors, profile
280 // counters for function with available_externally linkage needs to be changed
281 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
282 // created. Without using comdat, duplicate entries won't be removed by the
283 // linker leading to increased data segement size and raw profile size. Even
284 // worse, since the referenced counter from profile per-function data object
285 // will be resolved to the common strong definition, the profile counts for
286 // available_externally functions will end up being duplicated in raw profile
287 // data. This can result in distorted profile as the counts of those dups
288 // will be accumulated by the profile merger.
289 GlobalValue::LinkageTypes Linkage = F.getLinkage();
290 if (Linkage != GlobalValue::ExternalWeakLinkage &&
291 Linkage != GlobalValue::AvailableExternallyLinkage)
292 return false;
293
294 return true;
295}
296
297static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F,
Xinliang David Liab361ef2015-12-21 21:52:27 +0000298 InstrProfIncrementInst *Inc) {
Xinliang David Li985ff202016-02-27 23:11:30 +0000299 if (!needsComdatForCounter(F, M))
300 return nullptr;
301
Xinliang David Liab361ef2015-12-21 21:52:27 +0000302 // COFF format requires a COMDAT section to have a key symbol with the same
Vedant Kumar2d5b5d32016-02-03 23:22:43 +0000303 // name. The linker targeting COFF also requires that the COMDAT
Xinliang David Li5fe04552015-12-22 00:11:15 +0000304 // a section is associated to must precede the associating section. For this
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000305 // reason, we must choose the counter var's name as the name of the comdat.
Xinliang David Liab361ef2015-12-21 21:52:27 +0000306 StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF()
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000307 ? getInstrProfCountersVarPrefix()
Xinliang David Liab361ef2015-12-21 21:52:27 +0000308 : getInstrProfComdatPrefix());
309 return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix)));
310}
311
Xinliang David Lib628dd32016-05-21 22:55:34 +0000312static bool needsRuntimeRegistrationOfSectionRange(const Module &M) {
313 // Don't do this for Darwin. compiler-rt uses linker magic.
314 if (Triple(M.getTargetTriple()).isOSDarwin())
315 return false;
316
317 // Use linker script magic to get data/cnts/name start/end.
318 if (Triple(M.getTargetTriple()).isOSLinux() ||
319 Triple(M.getTargetTriple()).isOSFreeBSD() ||
320 Triple(M.getTargetTriple()).isPS4CPU())
321 return false;
322
323 return true;
324}
325
Justin Bogner61ba2e32014-12-08 18:02:35 +0000326GlobalVariable *
327InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
Xinliang David Li192c7482015-11-05 00:47:26 +0000328 GlobalVariable *NamePtr = Inc->getName();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000329 auto It = ProfileDataMap.find(NamePtr);
330 PerFunctionProfileData PD;
331 if (It != ProfileDataMap.end()) {
332 if (It->second.RegionCounters)
333 return It->second.RegionCounters;
334 PD = It->second;
335 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000336
Wei Mi3cc92042015-09-23 22:40:45 +0000337 // Move the name variable to the right section. Place them in a COMDAT group
338 // if the associated function is a COMDAT. This will make sure that
339 // only one copy of counters of the COMDAT function will be emitted after
340 // linking.
Diego Novillodf4837b2015-05-27 19:34:01 +0000341 Function *Fn = Inc->getParent()->getParent();
Wei Mi3cc92042015-09-23 22:40:45 +0000342 Comdat *ProfileVarsComdat = nullptr;
Xinliang David Li985ff202016-02-27 23:11:30 +0000343 ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000344
345 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
346 LLVMContext &Ctx = M->getContext();
347 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
348
349 // Create the counters variable.
Xinliang David Li192c7482015-11-05 00:47:26 +0000350 auto *CounterPtr =
351 new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000352 Constant::getNullValue(CounterTy),
353 getVarName(Inc, getInstrProfCountersVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000354 CounterPtr->setVisibility(NamePtr->getVisibility());
355 CounterPtr->setSection(getCountersSection());
356 CounterPtr->setAlignment(8);
357 CounterPtr->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000358
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000359 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000360 // Allocate statically the array of pointers to value profile nodes for
361 // the current function.
362 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
363 if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(*M)) {
364
365 uint64_t NS = 0;
366 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
367 NS += PD.NumValueSites[Kind];
368 if (NS) {
369 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
370
371 auto *ValuesVar =
372 new GlobalVariable(*M, ValuesTy, false, NamePtr->getLinkage(),
373 Constant::getNullValue(ValuesTy),
374 getVarName(Inc, getInstrProfValuesVarPrefix()));
375 ValuesVar->setVisibility(NamePtr->getVisibility());
376 ValuesVar->setSection(getInstrProfValuesSectionName(isMachO()));
377 ValuesVar->setAlignment(8);
378 ValuesVar->setComdat(ProfileVarsComdat);
379 ValuesPtrExpr =
380 ConstantExpr::getBitCast(ValuesVar, llvm::Type::getInt8PtrTy(Ctx));
381 }
382 }
383
384 // Create data variable.
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000385 auto *Int16Ty = Type::getInt16Ty(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000386 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
Xinliang David Li192c7482015-11-05 00:47:26 +0000387 Type *DataTypes[] = {
388 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
389 #include "llvm/ProfileData/InstrProfData.inc"
390 };
Justin Bogner61ba2e32014-12-08 18:02:35 +0000391 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
Xinliang David Li192c7482015-11-05 00:47:26 +0000392
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000393 Constant *FunctionAddr = shouldRecordFunctionAddr(Fn) ?
394 ConstantExpr::getBitCast(Fn, Int8PtrTy) :
395 ConstantPointerNull::get(Int8PtrTy);
396
397 Constant *Int16ArrayVals[IPVK_Last+1];
398 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
399 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
400
Justin Bogner61ba2e32014-12-08 18:02:35 +0000401 Constant *DataVals[] = {
Xinliang David Li192c7482015-11-05 00:47:26 +0000402 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
403 #include "llvm/ProfileData/InstrProfData.inc"
404 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000405 auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
Justin Bogner61ba2e32014-12-08 18:02:35 +0000406 ConstantStruct::get(DataTy, DataVals),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000407 getVarName(Inc, getInstrProfDataVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000408 Data->setVisibility(NamePtr->getVisibility());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000409 Data->setSection(getDataSection());
Xinliang David Lic7c1f852015-11-23 18:02:59 +0000410 Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
Wei Mi3cc92042015-09-23 22:40:45 +0000411 Data->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000412
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000413 PD.RegionCounters = CounterPtr;
414 PD.DataVar = Data;
415 ProfileDataMap[NamePtr] = PD;
416
Justin Bogner61ba2e32014-12-08 18:02:35 +0000417 // Mark the data variable as used so that it isn't stripped out.
418 UsedVars.push_back(Data);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000419 // Now that the linkage set by the FE has been passed to the data and counter
420 // variables, reset Name variable's linkage and visibility to private so that
421 // it can be removed later by the compiler.
422 NamePtr->setLinkage(GlobalValue::PrivateLinkage);
423 // Collect the referenced names to be used by emitNameData.
424 ReferencedNames.push_back(NamePtr);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000425
Xinliang David Li192c7482015-11-05 00:47:26 +0000426 return CounterPtr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000427}
428
Xinliang David Lib628dd32016-05-21 22:55:34 +0000429void InstrProfiling::emitVNodes() {
430 if (!ValueProfileStaticAlloc)
431 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000432
Xinliang David Lib628dd32016-05-21 22:55:34 +0000433 // For now only support this on platforms that do
434 // not require runtime registration to discover
435 // named section start/end.
436 if (needsRuntimeRegistrationOfSectionRange(*M))
437 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000438
Xinliang David Lib628dd32016-05-21 22:55:34 +0000439 size_t TotalNS = 0;
440 for (auto &PD : ProfileDataMap) {
441 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
442 TotalNS += PD.second.NumValueSites[Kind];
443 }
444
445 if (!TotalNS)
446 return;
447
448 uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
449 // Heuristic for small programs with very few total value sites.
450 // The default value of vp-counters-per-site is chosen based on
451 // the observation that large apps usually have a low percentage
452 // of value sites that actually have any profile data, and thus
453 // the average number of counters per site is low. For small
454 // apps with very few sites, this may not be true. Bump up the
455 // number of counters in this case.
Xinliang David Lie4520762016-05-23 19:29:26 +0000456#define INSTR_PROF_MIN_VAL_COUNTS 10
457 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
458 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int) NumCounters * 2);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000459
460 auto &Ctx = M->getContext();
461 Type *VNodeTypes[] = {
462#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
463#include "llvm/ProfileData/InstrProfData.inc"
464 };
465 auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
466
467 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
468 auto *VNodesVar = new GlobalVariable(
469 *M, VNodesTy, false, llvm::GlobalValue::PrivateLinkage,
470 Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
471 VNodesVar->setSection(getInstrProfVNodesSectionName(isMachO()));
472 UsedVars.push_back(VNodesVar);
Xinliang David Li8da773b2016-05-17 20:19:03 +0000473}
474
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000475void InstrProfiling::emitNameData() {
476 std::string UncompressedData;
477
478 if (ReferencedNames.empty())
479 return;
480
481 std::string CompressedNameStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000482 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
Vedant Kumar43cba732016-05-03 16:53:17 +0000483 DoNameCompression)) {
Vedant Kumar9152fd12016-05-19 03:54:45 +0000484 llvm::report_fatal_error(toString(std::move(E)), false);
Vedant Kumar43cba732016-05-03 16:53:17 +0000485 }
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000486
487 auto &Ctx = M->getContext();
488 auto *NamesVal = llvm::ConstantDataArray::getString(
489 Ctx, StringRef(CompressedNameStr), false);
490 NamesVar = new llvm::GlobalVariable(*M, NamesVal->getType(), true,
491 llvm::GlobalValue::PrivateLinkage,
492 NamesVal, getInstrProfNamesVarName());
493 NamesSize = CompressedNameStr.size();
494 NamesVar->setSection(getNameSection());
495 UsedVars.push_back(NamesVar);
496}
497
Justin Bogner61ba2e32014-12-08 18:02:35 +0000498void InstrProfiling::emitRegistration() {
Xinliang David Li8da773b2016-05-17 20:19:03 +0000499 if (!needsRuntimeRegistrationOfSectionRange(*M))
Xinliang David Liaa0592c2015-10-19 04:17:10 +0000500 return;
Xinliang David Li3dd88172015-10-13 18:39:48 +0000501
Justin Bogner61ba2e32014-12-08 18:02:35 +0000502 // Construct the function.
503 auto *VoidTy = Type::getVoidTy(M->getContext());
504 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000505 auto *Int64Ty = Type::getInt64Ty(M->getContext());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000506 auto *RegisterFTy = FunctionType::get(VoidTy, false);
507 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000508 getInstrProfRegFuncsName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000509 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000510 if (Options.NoRedZone) RegisterF->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000511
Diego Novillob3029d22015-06-04 11:45:32 +0000512 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000513 auto *RuntimeRegisterF =
514 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000515 getInstrProfRegFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000516
517 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
518 for (Value *Data : UsedVars)
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000519 if (Data != NamesVar)
520 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
521
522 if (NamesVar) {
523 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
524 auto *NamesRegisterTy =
525 FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
526 auto *NamesRegisterF =
527 Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
528 getInstrProfNamesRegFuncName(), M);
529 IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
530 IRB.getInt64(NamesSize)});
531 }
532
Justin Bogner61ba2e32014-12-08 18:02:35 +0000533 IRB.CreateRetVoid();
534}
535
536void InstrProfiling::emitRuntimeHook() {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000537
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000538 // We expect the linker to be invoked with -u<hook_var> flag for linux,
539 // for which case there is no need to emit the user function.
540 if (Triple(M->getTargetTriple()).isOSLinux())
541 return;
542
Justin Bogner61ba2e32014-12-08 18:02:35 +0000543 // If the module's provided its own runtime, we don't need to do anything.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000544 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName())) return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000545
546 // Declare an external variable that will pull in the runtime initialization.
547 auto *Int32Ty = Type::getInt32Ty(M->getContext());
548 auto *Var =
549 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000550 nullptr, getInstrProfRuntimeHookVarName());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000551
552 // Make a function that uses it.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000553 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
554 GlobalValue::LinkOnceODRLinkage,
555 getInstrProfRuntimeHookVarUseFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000556 User->addFnAttr(Attribute::NoInline);
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000557 if (Options.NoRedZone) User->addFnAttr(Attribute::NoRedZone);
Justin Bogner2e427d42015-02-25 22:52:20 +0000558 User->setVisibility(GlobalValue::HiddenVisibility);
Xinliang David Lia2286082016-05-25 17:17:51 +0000559 if (Triple(M->getTargetTriple()).supportsCOMDAT())
Xinliang David Lif4edae62016-05-24 18:47:38 +0000560 User->setComdat(M->getOrInsertComdat(User->getName()));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000561
562 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
563 auto *Load = IRB.CreateLoad(Var);
564 IRB.CreateRet(Load);
565
566 // Mark the user variable as used so that it isn't stripped out.
567 UsedVars.push_back(User);
568}
569
570void InstrProfiling::emitUses() {
571 if (UsedVars.empty())
572 return;
573
574 GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used");
Diego Novillob3029d22015-06-04 11:45:32 +0000575 std::vector<Constant *> MergedVars;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000576 if (LLVMUsed) {
577 // Collect the existing members of llvm.used.
578 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
579 for (unsigned I = 0, E = Inits->getNumOperands(); I != E; ++I)
580 MergedVars.push_back(Inits->getOperand(I));
581 LLVMUsed->eraseFromParent();
582 }
583
584 Type *i8PTy = Type::getInt8PtrTy(M->getContext());
585 // Add uses for our data.
586 for (auto *Value : UsedVars)
587 MergedVars.push_back(
Diego Novillob3029d22015-06-04 11:45:32 +0000588 ConstantExpr::getBitCast(cast<Constant>(Value), i8PTy));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000589
590 // Recreate llvm.used.
591 ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size());
Diego Novillob3029d22015-06-04 11:45:32 +0000592 LLVMUsed =
593 new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage,
594 ConstantArray::get(ATy, MergedVars), "llvm.used");
Justin Bogner61ba2e32014-12-08 18:02:35 +0000595 LLVMUsed->setSection("llvm.metadata");
596}
597
598void InstrProfiling::emitInitialization() {
Justin Bognerba1900c2015-04-30 23:49:23 +0000599 std::string InstrProfileOutput = Options.InstrProfileOutput;
600
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000601 Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
602 if (!RegisterF && InstrProfileOutput.empty()) return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000603
604 // Create the initialization function.
605 auto *VoidTy = Type::getVoidTy(M->getContext());
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000606 auto *F = Function::Create(FunctionType::get(VoidTy, false),
607 GlobalValue::InternalLinkage,
608 getInstrProfInitFuncName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000609 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000610 F->addFnAttr(Attribute::NoInline);
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000611 if (Options.NoRedZone) F->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000612
613 // Add the basic block and the necessary calls.
614 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
Justin Bognerba1900c2015-04-30 23:49:23 +0000615 if (RegisterF)
David Blaikieff6409d2015-05-18 22:13:54 +0000616 IRB.CreateCall(RegisterF, {});
Justin Bognerba1900c2015-04-30 23:49:23 +0000617 if (!InstrProfileOutput.empty()) {
618 auto *Int8PtrTy = Type::getInt8PtrTy(M->getContext());
619 auto *SetNameTy = FunctionType::get(VoidTy, Int8PtrTy, false);
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000620 auto *SetNameF = Function::Create(SetNameTy, GlobalValue::ExternalLinkage,
621 getInstrProfFileOverriderFuncName(), M);
Justin Bognerba1900c2015-04-30 23:49:23 +0000622
Diego Novillob0257c82015-06-29 20:03:46 +0000623 // Create variable for profile name.
Justin Bognerba1900c2015-04-30 23:49:23 +0000624 Constant *ProfileNameConst =
625 ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
626 GlobalVariable *ProfileName =
627 new GlobalVariable(*M, ProfileNameConst->getType(), true,
628 GlobalValue::PrivateLinkage, ProfileNameConst);
629
630 IRB.CreateCall(SetNameF, IRB.CreatePointerCast(ProfileName, Int8PtrTy));
631 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000632 IRB.CreateRetVoid();
633
634 appendToGlobalCtors(*M, F, 0);
635}