blob: 4f71261a1abcee5057232ac7abd7d6daa296e86c [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
Xinliang David Li69a00f02016-06-21 02:39:08 +000016#include "llvm/Transforms/InstrProfiling.h"
Justin Bogner61ba2e32014-12-08 18:02:35 +000017#include "llvm/ADT/Triple.h"
18#include "llvm/IR/IRBuilder.h"
19#include "llvm/IR/IntrinsicInst.h"
20#include "llvm/IR/Module.h"
Betul Buyukkurt6fac1742015-11-18 18:14:55 +000021#include "llvm/ProfileData/InstrProf.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
Sean Silvafd03ac62016-08-09 00:28:38 +000069PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
Xinliang David Lie6b89292016-04-18 17:47:38 +000070 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 Li69a00f02016-06-21 02:39:08 +000081ModulePass *
82llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options) {
Xinliang David Lie6b89292016-04-18 17:47:38 +000083 return new InstrProfilingLegacyPass(Options);
Justin Bogner61ba2e32014-12-08 18:02:35 +000084}
85
Xinliang David Lie6b89292016-04-18 17:47:38 +000086bool InstrProfiling::isMachO() const {
87 return Triple(M->getTargetTriple()).isOSBinFormatMachO();
88}
89
90/// Get the section name for the counter variables.
91StringRef InstrProfiling::getCountersSection() const {
92 return getInstrProfCountersSectionName(isMachO());
93}
94
95/// Get the section name for the name variables.
96StringRef InstrProfiling::getNameSection() const {
97 return getInstrProfNameSectionName(isMachO());
98}
99
100/// Get the section name for the profile data variables.
101StringRef InstrProfiling::getDataSection() const {
102 return getInstrProfDataSectionName(isMachO());
103}
104
105/// Get the section name for the coverage mapping data.
106StringRef InstrProfiling::getCoverageSection() const {
107 return getInstrProfCoverageSectionName(isMachO());
108}
109
Xinliang David Li4ca17332016-09-18 18:34:07 +0000110static InstrProfIncrementInst *castToIncrementInst(Instruction *Instr) {
111 InstrProfIncrementInst *Inc = dyn_cast<InstrProfIncrementInstStep>(Instr);
112 if (Inc)
113 return Inc;
114 return dyn_cast<InstrProfIncrementInst>(Instr);
115}
116
Xinliang David Lie6b89292016-04-18 17:47:38 +0000117bool InstrProfiling::run(Module &M) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000118 bool MadeChange = false;
119
120 this->M = &M;
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000121 NamesVar = nullptr;
122 NamesSize = 0;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000123 ProfileDataMap.clear();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000124 UsedVars.clear();
125
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000126 // We did not know how many value sites there would be inside
127 // the instrumented function. This is counting the number of instrumented
128 // target value sites to enter it as field in the profile data variable.
Rong Xu294572f2016-01-19 18:29:54 +0000129 for (Function &F : M) {
130 InstrProfIncrementInst *FirstProfIncInst = nullptr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000131 for (BasicBlock &BB : F)
Rong Xu294572f2016-01-19 18:29:54 +0000132 for (auto I = BB.begin(), E = BB.end(); I != E; I++)
133 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000134 computeNumValueSiteCounts(Ind);
Rong Xu294572f2016-01-19 18:29:54 +0000135 else if (FirstProfIncInst == nullptr)
136 FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
137
138 // Value profiling intrinsic lowering requires per-function profile data
139 // variable to be created first.
140 if (FirstProfIncInst != nullptr)
141 static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
142 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000143
144 for (Function &F : M)
145 for (BasicBlock &BB : F)
146 for (auto I = BB.begin(), E = BB.end(); I != E;) {
147 auto Instr = I++;
Xinliang David Li4ca17332016-09-18 18:34:07 +0000148 InstrProfIncrementInst *Inc = castToIncrementInst(&*Instr);
149 if (Inc) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000150 lowerIncrement(Inc);
151 MadeChange = true;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000152 } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
153 lowerValueProfileInst(Ind);
154 MadeChange = true;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000155 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000156 }
157
Xinliang David Li81056072016-01-07 20:05:49 +0000158 if (GlobalVariable *CoverageNamesVar =
Xinliang David Li440cd702016-01-20 00:24:36 +0000159 M.getNamedGlobal(getCoverageUnusedNamesVarName())) {
Xinliang David Li81056072016-01-07 20:05:49 +0000160 lowerCoverageData(CoverageNamesVar);
Justin Bognerd24e1852015-02-11 02:52:44 +0000161 MadeChange = true;
162 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000163
Justin Bogner61ba2e32014-12-08 18:02:35 +0000164 if (!MadeChange)
165 return false;
166
Xinliang David Lib628dd32016-05-21 22:55:34 +0000167 emitVNodes();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000168 emitNameData();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000169 emitRegistration();
170 emitRuntimeHook();
171 emitUses();
172 emitInitialization();
173 return true;
174}
175
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000176static Constant *getOrInsertValueProfilingCall(Module &M) {
Xinliang David Lic7673232015-11-22 00:22:07 +0000177 LLVMContext &Ctx = M.getContext();
178 auto *ReturnTy = Type::getVoidTy(M.getContext());
179 Type *ParamTypes[] = {
180#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
181#include "llvm/ProfileData/InstrProfData.inc"
182 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000183 auto *ValueProfilingCallTy =
Xinliang David Lic7673232015-11-22 00:22:07 +0000184 FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
Xinliang David Li924e0582015-11-22 05:42:31 +0000185 return M.getOrInsertFunction(getInstrProfValueProfFuncName(),
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000186 ValueProfilingCallTy);
187}
188
189void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
190
191 GlobalVariable *Name = Ind->getName();
192 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
193 uint64_t Index = Ind->getIndex()->getZExtValue();
194 auto It = ProfileDataMap.find(Name);
195 if (It == ProfileDataMap.end()) {
196 PerFunctionProfileData PD;
197 PD.NumValueSites[ValueKind] = Index + 1;
198 ProfileDataMap[Name] = PD;
199 } else if (It->second.NumValueSites[ValueKind] <= Index)
200 It->second.NumValueSites[ValueKind] = Index + 1;
201}
202
203void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
204
205 GlobalVariable *Name = Ind->getName();
206 auto It = ProfileDataMap.find(Name);
207 assert(It != ProfileDataMap.end() && It->second.DataVar &&
Xinliang David Li69a00f02016-06-21 02:39:08 +0000208 "value profiling detected in function with no counter incerement");
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000209
210 GlobalVariable *DataVar = It->second.DataVar;
211 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
212 uint64_t Index = Ind->getIndex()->getZExtValue();
213 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
214 Index += It->second.NumValueSites[Kind];
215
216 IRBuilder<> Builder(Ind);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000217 Value *Args[3] = {Ind->getTargetValue(),
218 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
219 Builder.getInt32(Index)};
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000220 Ind->replaceAllUsesWith(
221 Builder.CreateCall(getOrInsertValueProfilingCall(*M), Args));
222 Ind->eraseFromParent();
223}
224
Xinliang David Li4ca17332016-09-18 18:34:07 +0000225static Value *getIncrementStep(InstrProfIncrementInst *Inc,
226 IRBuilder<> &Builder) {
227 auto *IncWithStep = dyn_cast<InstrProfIncrementInstStep>(Inc);
228 if (IncWithStep)
229 return IncWithStep->getStep();
230 return Builder.getInt64(1);
231}
232
Justin Bogner61ba2e32014-12-08 18:02:35 +0000233void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
234 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
235
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000236 IRBuilder<> Builder(Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000237 uint64_t Index = Inc->getIndex()->getZExtValue();
Diego Novillob3029d22015-06-04 11:45:32 +0000238 Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
239 Value *Count = Builder.CreateLoad(Addr, "pgocount");
Xinliang David Li4ca17332016-09-18 18:34:07 +0000240 Count = Builder.CreateAdd(Count, getIncrementStep(Inc, Builder));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000241 Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
242 Inc->eraseFromParent();
243}
244
Xinliang David Li81056072016-01-07 20:05:49 +0000245void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
Justin Bognerd24e1852015-02-11 02:52:44 +0000246
Xinliang David Li81056072016-01-07 20:05:49 +0000247 ConstantArray *Names =
248 cast<ConstantArray>(CoverageNamesVar->getInitializer());
249 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
250 Constant *NC = Names->getOperand(I);
251 Value *V = NC->stripPointerCasts();
Justin Bognerd24e1852015-02-11 02:52:44 +0000252 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
253 GlobalVariable *Name = cast<GlobalVariable>(V);
254
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000255 Name->setLinkage(GlobalValue::PrivateLinkage);
256 ReferencedNames.push_back(Name);
Justin Bognerd24e1852015-02-11 02:52:44 +0000257 }
258}
259
Justin Bogner61ba2e32014-12-08 18:02:35 +0000260/// Get the name of a profiling variable for a particular function.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000261static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000262 StringRef NamePrefix = getInstrProfNameVarPrefix();
263 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
Xinliang David Li83bc4222015-10-22 20:32:12 +0000264 return (Prefix + Name).str();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000265}
266
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000267static inline bool shouldRecordFunctionAddr(Function *F) {
268 // Check the linkage
269 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
270 !F->hasAvailableExternallyLinkage())
271 return true;
Rong Xuaf5aeba2016-04-27 21:17:30 +0000272 // Prohibit function address recording if the function is both internal and
273 // COMDAT. This avoids the profile data variable referencing internal symbols
274 // in COMDAT.
275 if (F->hasLocalLinkage() && F->hasComdat())
276 return false;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000277 // Check uses of this function for other than direct calls or invokes to it.
Xinliang David Li7008ce32016-06-02 16:33:41 +0000278 // Inline virtual functions have linkeOnceODR linkage. When a key method
279 // exists, the vtable will only be emitted in the TU where the key method
280 // is defined. In a TU where vtable is not available, the function won't
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000281 // be 'addresstaken'. If its address is not recorded here, the profile data
Xinliang David Li69a00f02016-06-21 02:39:08 +0000282 // with missing address may be picked by the linker leading to missing
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000283 // indirect call target info.
284 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000285}
286
Xinliang David Li985ff202016-02-27 23:11:30 +0000287static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F,
Xinliang David Liab361ef2015-12-21 21:52:27 +0000288 InstrProfIncrementInst *Inc) {
Xinliang David Li985ff202016-02-27 23:11:30 +0000289 if (!needsComdatForCounter(F, M))
290 return nullptr;
291
Xinliang David Liab361ef2015-12-21 21:52:27 +0000292 // COFF format requires a COMDAT section to have a key symbol with the same
Vedant Kumar2d5b5d32016-02-03 23:22:43 +0000293 // name. The linker targeting COFF also requires that the COMDAT
Xinliang David Li5fe04552015-12-22 00:11:15 +0000294 // a section is associated to must precede the associating section. For this
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000295 // reason, we must choose the counter var's name as the name of the comdat.
Xinliang David Liab361ef2015-12-21 21:52:27 +0000296 StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF()
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000297 ? getInstrProfCountersVarPrefix()
Xinliang David Liab361ef2015-12-21 21:52:27 +0000298 : getInstrProfComdatPrefix());
299 return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix)));
300}
301
Xinliang David Lib628dd32016-05-21 22:55:34 +0000302static bool needsRuntimeRegistrationOfSectionRange(const Module &M) {
303 // Don't do this for Darwin. compiler-rt uses linker magic.
304 if (Triple(M.getTargetTriple()).isOSDarwin())
305 return false;
306
307 // Use linker script magic to get data/cnts/name start/end.
308 if (Triple(M.getTargetTriple()).isOSLinux() ||
309 Triple(M.getTargetTriple()).isOSFreeBSD() ||
310 Triple(M.getTargetTriple()).isPS4CPU())
311 return false;
312
313 return true;
314}
315
Justin Bogner61ba2e32014-12-08 18:02:35 +0000316GlobalVariable *
317InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
Xinliang David Li192c7482015-11-05 00:47:26 +0000318 GlobalVariable *NamePtr = Inc->getName();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000319 auto It = ProfileDataMap.find(NamePtr);
320 PerFunctionProfileData PD;
321 if (It != ProfileDataMap.end()) {
322 if (It->second.RegionCounters)
323 return It->second.RegionCounters;
324 PD = It->second;
325 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000326
Wei Mi3cc92042015-09-23 22:40:45 +0000327 // Move the name variable to the right section. Place them in a COMDAT group
328 // if the associated function is a COMDAT. This will make sure that
329 // only one copy of counters of the COMDAT function will be emitted after
330 // linking.
Diego Novillodf4837b2015-05-27 19:34:01 +0000331 Function *Fn = Inc->getParent()->getParent();
Wei Mi3cc92042015-09-23 22:40:45 +0000332 Comdat *ProfileVarsComdat = nullptr;
Xinliang David Li985ff202016-02-27 23:11:30 +0000333 ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000334
335 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
336 LLVMContext &Ctx = M->getContext();
337 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
338
339 // Create the counters variable.
Xinliang David Li192c7482015-11-05 00:47:26 +0000340 auto *CounterPtr =
341 new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000342 Constant::getNullValue(CounterTy),
343 getVarName(Inc, getInstrProfCountersVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000344 CounterPtr->setVisibility(NamePtr->getVisibility());
345 CounterPtr->setSection(getCountersSection());
346 CounterPtr->setAlignment(8);
347 CounterPtr->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000348
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000349 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000350 // Allocate statically the array of pointers to value profile nodes for
351 // the current function.
352 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
353 if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(*M)) {
354
355 uint64_t NS = 0;
356 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
357 NS += PD.NumValueSites[Kind];
358 if (NS) {
359 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
360
361 auto *ValuesVar =
362 new GlobalVariable(*M, ValuesTy, false, NamePtr->getLinkage(),
363 Constant::getNullValue(ValuesTy),
364 getVarName(Inc, getInstrProfValuesVarPrefix()));
365 ValuesVar->setVisibility(NamePtr->getVisibility());
366 ValuesVar->setSection(getInstrProfValuesSectionName(isMachO()));
367 ValuesVar->setAlignment(8);
368 ValuesVar->setComdat(ProfileVarsComdat);
369 ValuesPtrExpr =
370 ConstantExpr::getBitCast(ValuesVar, llvm::Type::getInt8PtrTy(Ctx));
371 }
372 }
373
374 // Create data variable.
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000375 auto *Int16Ty = Type::getInt16Ty(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000376 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
Xinliang David Li192c7482015-11-05 00:47:26 +0000377 Type *DataTypes[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000378#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
379#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000380 };
Justin Bogner61ba2e32014-12-08 18:02:35 +0000381 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
Xinliang David Li192c7482015-11-05 00:47:26 +0000382
Xinliang David Li69a00f02016-06-21 02:39:08 +0000383 Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
384 ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
385 : ConstantPointerNull::get(Int8PtrTy);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000386
Xinliang David Li69a00f02016-06-21 02:39:08 +0000387 Constant *Int16ArrayVals[IPVK_Last + 1];
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000388 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
389 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
390
Justin Bogner61ba2e32014-12-08 18:02:35 +0000391 Constant *DataVals[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000392#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
393#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000394 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000395 auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
Justin Bogner61ba2e32014-12-08 18:02:35 +0000396 ConstantStruct::get(DataTy, DataVals),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000397 getVarName(Inc, getInstrProfDataVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000398 Data->setVisibility(NamePtr->getVisibility());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000399 Data->setSection(getDataSection());
Xinliang David Lic7c1f852015-11-23 18:02:59 +0000400 Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
Wei Mi3cc92042015-09-23 22:40:45 +0000401 Data->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000402
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000403 PD.RegionCounters = CounterPtr;
404 PD.DataVar = Data;
405 ProfileDataMap[NamePtr] = PD;
406
Justin Bogner61ba2e32014-12-08 18:02:35 +0000407 // Mark the data variable as used so that it isn't stripped out.
408 UsedVars.push_back(Data);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000409 // Now that the linkage set by the FE has been passed to the data and counter
410 // variables, reset Name variable's linkage and visibility to private so that
411 // it can be removed later by the compiler.
412 NamePtr->setLinkage(GlobalValue::PrivateLinkage);
413 // Collect the referenced names to be used by emitNameData.
414 ReferencedNames.push_back(NamePtr);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000415
Xinliang David Li192c7482015-11-05 00:47:26 +0000416 return CounterPtr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000417}
418
Xinliang David Lib628dd32016-05-21 22:55:34 +0000419void InstrProfiling::emitVNodes() {
420 if (!ValueProfileStaticAlloc)
421 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000422
Xinliang David Lib628dd32016-05-21 22:55:34 +0000423 // For now only support this on platforms that do
424 // not require runtime registration to discover
425 // named section start/end.
426 if (needsRuntimeRegistrationOfSectionRange(*M))
427 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000428
Xinliang David Lib628dd32016-05-21 22:55:34 +0000429 size_t TotalNS = 0;
430 for (auto &PD : ProfileDataMap) {
431 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
432 TotalNS += PD.second.NumValueSites[Kind];
433 }
434
435 if (!TotalNS)
436 return;
437
438 uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
Xinliang David Li69a00f02016-06-21 02:39:08 +0000439// Heuristic for small programs with very few total value sites.
440// The default value of vp-counters-per-site is chosen based on
441// the observation that large apps usually have a low percentage
442// of value sites that actually have any profile data, and thus
443// the average number of counters per site is low. For small
444// apps with very few sites, this may not be true. Bump up the
445// number of counters in this case.
Xinliang David Lie4520762016-05-23 19:29:26 +0000446#define INSTR_PROF_MIN_VAL_COUNTS 10
447 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000448 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000449
450 auto &Ctx = M->getContext();
451 Type *VNodeTypes[] = {
452#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
453#include "llvm/ProfileData/InstrProfData.inc"
454 };
455 auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
456
457 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
458 auto *VNodesVar = new GlobalVariable(
459 *M, VNodesTy, false, llvm::GlobalValue::PrivateLinkage,
460 Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
461 VNodesVar->setSection(getInstrProfVNodesSectionName(isMachO()));
462 UsedVars.push_back(VNodesVar);
Xinliang David Li8da773b2016-05-17 20:19:03 +0000463}
464
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000465void InstrProfiling::emitNameData() {
466 std::string UncompressedData;
467
468 if (ReferencedNames.empty())
469 return;
470
471 std::string CompressedNameStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000472 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
Vedant Kumar43cba732016-05-03 16:53:17 +0000473 DoNameCompression)) {
Vedant Kumar9152fd12016-05-19 03:54:45 +0000474 llvm::report_fatal_error(toString(std::move(E)), false);
Vedant Kumar43cba732016-05-03 16:53:17 +0000475 }
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000476
477 auto &Ctx = M->getContext();
478 auto *NamesVal = llvm::ConstantDataArray::getString(
479 Ctx, StringRef(CompressedNameStr), false);
480 NamesVar = new llvm::GlobalVariable(*M, NamesVal->getType(), true,
481 llvm::GlobalValue::PrivateLinkage,
482 NamesVal, getInstrProfNamesVarName());
483 NamesSize = CompressedNameStr.size();
484 NamesVar->setSection(getNameSection());
485 UsedVars.push_back(NamesVar);
486}
487
Justin Bogner61ba2e32014-12-08 18:02:35 +0000488void InstrProfiling::emitRegistration() {
Xinliang David Li8da773b2016-05-17 20:19:03 +0000489 if (!needsRuntimeRegistrationOfSectionRange(*M))
Xinliang David Liaa0592c2015-10-19 04:17:10 +0000490 return;
Xinliang David Li3dd88172015-10-13 18:39:48 +0000491
Justin Bogner61ba2e32014-12-08 18:02:35 +0000492 // Construct the function.
493 auto *VoidTy = Type::getVoidTy(M->getContext());
494 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000495 auto *Int64Ty = Type::getInt64Ty(M->getContext());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000496 auto *RegisterFTy = FunctionType::get(VoidTy, false);
497 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000498 getInstrProfRegFuncsName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000499 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000500 if (Options.NoRedZone)
501 RegisterF->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000502
Diego Novillob3029d22015-06-04 11:45:32 +0000503 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000504 auto *RuntimeRegisterF =
505 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000506 getInstrProfRegFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000507
508 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
509 for (Value *Data : UsedVars)
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000510 if (Data != NamesVar)
511 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
512
513 if (NamesVar) {
514 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
515 auto *NamesRegisterTy =
516 FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
517 auto *NamesRegisterF =
518 Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
519 getInstrProfNamesRegFuncName(), M);
520 IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
521 IRB.getInt64(NamesSize)});
522 }
523
Justin Bogner61ba2e32014-12-08 18:02:35 +0000524 IRB.CreateRetVoid();
525}
526
527void InstrProfiling::emitRuntimeHook() {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000528
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000529 // We expect the linker to be invoked with -u<hook_var> flag for linux,
530 // for which case there is no need to emit the user function.
531 if (Triple(M->getTargetTriple()).isOSLinux())
532 return;
533
Justin Bogner61ba2e32014-12-08 18:02:35 +0000534 // If the module's provided its own runtime, we don't need to do anything.
Xinliang David Li69a00f02016-06-21 02:39:08 +0000535 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
536 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000537
538 // Declare an external variable that will pull in the runtime initialization.
539 auto *Int32Ty = Type::getInt32Ty(M->getContext());
540 auto *Var =
541 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000542 nullptr, getInstrProfRuntimeHookVarName());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000543
544 // Make a function that uses it.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000545 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
546 GlobalValue::LinkOnceODRLinkage,
547 getInstrProfRuntimeHookVarUseFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000548 User->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000549 if (Options.NoRedZone)
550 User->addFnAttr(Attribute::NoRedZone);
Justin Bogner2e427d42015-02-25 22:52:20 +0000551 User->setVisibility(GlobalValue::HiddenVisibility);
Xinliang David Lia2286082016-05-25 17:17:51 +0000552 if (Triple(M->getTargetTriple()).supportsCOMDAT())
Xinliang David Lif4edae62016-05-24 18:47:38 +0000553 User->setComdat(M->getOrInsertComdat(User->getName()));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000554
555 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
556 auto *Load = IRB.CreateLoad(Var);
557 IRB.CreateRet(Load);
558
559 // Mark the user variable as used so that it isn't stripped out.
560 UsedVars.push_back(User);
561}
562
563void InstrProfiling::emitUses() {
564 if (UsedVars.empty())
565 return;
566
567 GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used");
Diego Novillob3029d22015-06-04 11:45:32 +0000568 std::vector<Constant *> MergedVars;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000569 if (LLVMUsed) {
570 // Collect the existing members of llvm.used.
571 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
572 for (unsigned I = 0, E = Inits->getNumOperands(); I != E; ++I)
573 MergedVars.push_back(Inits->getOperand(I));
574 LLVMUsed->eraseFromParent();
575 }
576
577 Type *i8PTy = Type::getInt8PtrTy(M->getContext());
578 // Add uses for our data.
579 for (auto *Value : UsedVars)
580 MergedVars.push_back(
Diego Novillob3029d22015-06-04 11:45:32 +0000581 ConstantExpr::getBitCast(cast<Constant>(Value), i8PTy));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000582
583 // Recreate llvm.used.
584 ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size());
Diego Novillob3029d22015-06-04 11:45:32 +0000585 LLVMUsed =
586 new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage,
587 ConstantArray::get(ATy, MergedVars), "llvm.used");
Justin Bogner61ba2e32014-12-08 18:02:35 +0000588 LLVMUsed->setSection("llvm.metadata");
589}
590
591void InstrProfiling::emitInitialization() {
Vedant Kumarcd32eba2016-07-21 17:50:07 +0000592 StringRef InstrProfileOutput = Options.InstrProfileOutput;
Justin Bognerba1900c2015-04-30 23:49:23 +0000593
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000594 if (!InstrProfileOutput.empty()) {
595 // Create variable for profile name.
596 Constant *ProfileNameConst =
597 ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
598 GlobalVariable *ProfileNameVar = new GlobalVariable(
599 *M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
600 ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
601 Triple TT(M->getTargetTriple());
602 if (TT.supportsCOMDAT()) {
603 ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
604 ProfileNameVar->setComdat(M->getOrInsertComdat(
605 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
606 }
607 }
608
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000609 Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000610 if (!RegisterF)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000611 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000612
613 // Create the initialization function.
614 auto *VoidTy = Type::getVoidTy(M->getContext());
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000615 auto *F = Function::Create(FunctionType::get(VoidTy, false),
616 GlobalValue::InternalLinkage,
617 getInstrProfInitFuncName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000618 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000619 F->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000620 if (Options.NoRedZone)
621 F->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000622
623 // Add the basic block and the necessary calls.
624 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
Justin Bognerba1900c2015-04-30 23:49:23 +0000625 if (RegisterF)
David Blaikieff6409d2015-05-18 22:13:54 +0000626 IRB.CreateCall(RegisterF, {});
Justin Bogner61ba2e32014-12-08 18:02:35 +0000627 IRB.CreateRetVoid();
628
629 appendToGlobalCtors(*M, F, 0);
630}