blob: 2b3d1cc28b89c5cb7efb8ad83b4c2b49ac2baa4c [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
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 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
110bool InstrProfiling::run(Module &M) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000111 bool MadeChange = false;
112
113 this->M = &M;
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000114 NamesVar = nullptr;
115 NamesSize = 0;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000116 ProfileDataMap.clear();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000117 UsedVars.clear();
118
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000119 // We did not know how many value sites there would be inside
120 // the instrumented function. This is counting the number of instrumented
121 // target value sites to enter it as field in the profile data variable.
Rong Xu294572f2016-01-19 18:29:54 +0000122 for (Function &F : M) {
123 InstrProfIncrementInst *FirstProfIncInst = nullptr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000124 for (BasicBlock &BB : F)
Rong Xu294572f2016-01-19 18:29:54 +0000125 for (auto I = BB.begin(), E = BB.end(); I != E; I++)
126 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000127 computeNumValueSiteCounts(Ind);
Rong Xu294572f2016-01-19 18:29:54 +0000128 else if (FirstProfIncInst == nullptr)
129 FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
130
131 // Value profiling intrinsic lowering requires per-function profile data
132 // variable to be created first.
133 if (FirstProfIncInst != nullptr)
134 static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
135 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000136
137 for (Function &F : M)
138 for (BasicBlock &BB : F)
139 for (auto I = BB.begin(), E = BB.end(); I != E;) {
140 auto Instr = I++;
141 if (auto *Inc = dyn_cast<InstrProfIncrementInst>(Instr)) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000142 lowerIncrement(Inc);
143 MadeChange = true;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000144 } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
145 lowerValueProfileInst(Ind);
146 MadeChange = true;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000147 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000148 }
149
Xinliang David Li81056072016-01-07 20:05:49 +0000150 if (GlobalVariable *CoverageNamesVar =
Xinliang David Li440cd702016-01-20 00:24:36 +0000151 M.getNamedGlobal(getCoverageUnusedNamesVarName())) {
Xinliang David Li81056072016-01-07 20:05:49 +0000152 lowerCoverageData(CoverageNamesVar);
Justin Bognerd24e1852015-02-11 02:52:44 +0000153 MadeChange = true;
154 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000155
Justin Bogner61ba2e32014-12-08 18:02:35 +0000156 if (!MadeChange)
157 return false;
158
Xinliang David Lib628dd32016-05-21 22:55:34 +0000159 emitVNodes();
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000160 emitNameData();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000161 emitRegistration();
162 emitRuntimeHook();
163 emitUses();
164 emitInitialization();
165 return true;
166}
167
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000168static Constant *getOrInsertValueProfilingCall(Module &M) {
Xinliang David Lic7673232015-11-22 00:22:07 +0000169 LLVMContext &Ctx = M.getContext();
170 auto *ReturnTy = Type::getVoidTy(M.getContext());
171 Type *ParamTypes[] = {
172#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
173#include "llvm/ProfileData/InstrProfData.inc"
174 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000175 auto *ValueProfilingCallTy =
Xinliang David Lic7673232015-11-22 00:22:07 +0000176 FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
Xinliang David Li924e0582015-11-22 05:42:31 +0000177 return M.getOrInsertFunction(getInstrProfValueProfFuncName(),
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000178 ValueProfilingCallTy);
179}
180
181void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
182
183 GlobalVariable *Name = Ind->getName();
184 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
185 uint64_t Index = Ind->getIndex()->getZExtValue();
186 auto It = ProfileDataMap.find(Name);
187 if (It == ProfileDataMap.end()) {
188 PerFunctionProfileData PD;
189 PD.NumValueSites[ValueKind] = Index + 1;
190 ProfileDataMap[Name] = PD;
191 } else if (It->second.NumValueSites[ValueKind] <= Index)
192 It->second.NumValueSites[ValueKind] = Index + 1;
193}
194
195void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
196
197 GlobalVariable *Name = Ind->getName();
198 auto It = ProfileDataMap.find(Name);
199 assert(It != ProfileDataMap.end() && It->second.DataVar &&
Xinliang David Li69a00f02016-06-21 02:39:08 +0000200 "value profiling detected in function with no counter incerement");
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000201
202 GlobalVariable *DataVar = It->second.DataVar;
203 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
204 uint64_t Index = Ind->getIndex()->getZExtValue();
205 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
206 Index += It->second.NumValueSites[Kind];
207
208 IRBuilder<> Builder(Ind);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000209 Value *Args[3] = {Ind->getTargetValue(),
210 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
211 Builder.getInt32(Index)};
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000212 Ind->replaceAllUsesWith(
213 Builder.CreateCall(getOrInsertValueProfilingCall(*M), Args));
214 Ind->eraseFromParent();
215}
216
Justin Bogner61ba2e32014-12-08 18:02:35 +0000217void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
218 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
219
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000220 IRBuilder<> Builder(Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000221 uint64_t Index = Inc->getIndex()->getZExtValue();
Diego Novillob3029d22015-06-04 11:45:32 +0000222 Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
223 Value *Count = Builder.CreateLoad(Addr, "pgocount");
Justin Bogner61ba2e32014-12-08 18:02:35 +0000224 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
225 Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
226 Inc->eraseFromParent();
227}
228
Xinliang David Li81056072016-01-07 20:05:49 +0000229void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
Justin Bognerd24e1852015-02-11 02:52:44 +0000230
Xinliang David Li81056072016-01-07 20:05:49 +0000231 ConstantArray *Names =
232 cast<ConstantArray>(CoverageNamesVar->getInitializer());
233 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
234 Constant *NC = Names->getOperand(I);
235 Value *V = NC->stripPointerCasts();
Justin Bognerd24e1852015-02-11 02:52:44 +0000236 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
237 GlobalVariable *Name = cast<GlobalVariable>(V);
238
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000239 Name->setLinkage(GlobalValue::PrivateLinkage);
240 ReferencedNames.push_back(Name);
Justin Bognerd24e1852015-02-11 02:52:44 +0000241 }
242}
243
Justin Bogner61ba2e32014-12-08 18:02:35 +0000244/// Get the name of a profiling variable for a particular function.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000245static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000246 StringRef NamePrefix = getInstrProfNameVarPrefix();
247 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
Xinliang David Li83bc4222015-10-22 20:32:12 +0000248 return (Prefix + Name).str();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000249}
250
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000251static inline bool shouldRecordFunctionAddr(Function *F) {
252 // Check the linkage
253 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
254 !F->hasAvailableExternallyLinkage())
255 return true;
Rong Xuaf5aeba2016-04-27 21:17:30 +0000256 // Prohibit function address recording if the function is both internal and
257 // COMDAT. This avoids the profile data variable referencing internal symbols
258 // in COMDAT.
259 if (F->hasLocalLinkage() && F->hasComdat())
260 return false;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000261 // Check uses of this function for other than direct calls or invokes to it.
Xinliang David Li7008ce32016-06-02 16:33:41 +0000262 // Inline virtual functions have linkeOnceODR linkage. When a key method
263 // exists, the vtable will only be emitted in the TU where the key method
264 // is defined. In a TU where vtable is not available, the function won't
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000265 // be 'addresstaken'. If its address is not recorded here, the profile data
Xinliang David Li69a00f02016-06-21 02:39:08 +0000266 // with missing address may be picked by the linker leading to missing
Xinliang David Li6c44e9e2016-06-03 23:02:28 +0000267 // indirect call target info.
268 return F->hasAddressTaken() || F->hasLinkOnceLinkage();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000269}
270
Xinliang David Li985ff202016-02-27 23:11:30 +0000271static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F,
Xinliang David Liab361ef2015-12-21 21:52:27 +0000272 InstrProfIncrementInst *Inc) {
Xinliang David Li985ff202016-02-27 23:11:30 +0000273 if (!needsComdatForCounter(F, M))
274 return nullptr;
275
Xinliang David Liab361ef2015-12-21 21:52:27 +0000276 // COFF format requires a COMDAT section to have a key symbol with the same
Vedant Kumar2d5b5d32016-02-03 23:22:43 +0000277 // name. The linker targeting COFF also requires that the COMDAT
Xinliang David Li5fe04552015-12-22 00:11:15 +0000278 // a section is associated to must precede the associating section. For this
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000279 // reason, we must choose the counter var's name as the name of the comdat.
Xinliang David Liab361ef2015-12-21 21:52:27 +0000280 StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF()
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000281 ? getInstrProfCountersVarPrefix()
Xinliang David Liab361ef2015-12-21 21:52:27 +0000282 : getInstrProfComdatPrefix());
283 return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix)));
284}
285
Xinliang David Lib628dd32016-05-21 22:55:34 +0000286static bool needsRuntimeRegistrationOfSectionRange(const Module &M) {
287 // Don't do this for Darwin. compiler-rt uses linker magic.
288 if (Triple(M.getTargetTriple()).isOSDarwin())
289 return false;
290
291 // Use linker script magic to get data/cnts/name start/end.
292 if (Triple(M.getTargetTriple()).isOSLinux() ||
293 Triple(M.getTargetTriple()).isOSFreeBSD() ||
294 Triple(M.getTargetTriple()).isPS4CPU())
295 return false;
296
297 return true;
298}
299
Justin Bogner61ba2e32014-12-08 18:02:35 +0000300GlobalVariable *
301InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
Xinliang David Li192c7482015-11-05 00:47:26 +0000302 GlobalVariable *NamePtr = Inc->getName();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000303 auto It = ProfileDataMap.find(NamePtr);
304 PerFunctionProfileData PD;
305 if (It != ProfileDataMap.end()) {
306 if (It->second.RegionCounters)
307 return It->second.RegionCounters;
308 PD = It->second;
309 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000310
Wei Mi3cc92042015-09-23 22:40:45 +0000311 // Move the name variable to the right section. Place them in a COMDAT group
312 // if the associated function is a COMDAT. This will make sure that
313 // only one copy of counters of the COMDAT function will be emitted after
314 // linking.
Diego Novillodf4837b2015-05-27 19:34:01 +0000315 Function *Fn = Inc->getParent()->getParent();
Wei Mi3cc92042015-09-23 22:40:45 +0000316 Comdat *ProfileVarsComdat = nullptr;
Xinliang David Li985ff202016-02-27 23:11:30 +0000317 ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000318
319 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
320 LLVMContext &Ctx = M->getContext();
321 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
322
323 // Create the counters variable.
Xinliang David Li192c7482015-11-05 00:47:26 +0000324 auto *CounterPtr =
325 new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000326 Constant::getNullValue(CounterTy),
327 getVarName(Inc, getInstrProfCountersVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000328 CounterPtr->setVisibility(NamePtr->getVisibility());
329 CounterPtr->setSection(getCountersSection());
330 CounterPtr->setAlignment(8);
331 CounterPtr->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000332
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000333 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000334 // Allocate statically the array of pointers to value profile nodes for
335 // the current function.
336 Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
337 if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(*M)) {
338
339 uint64_t NS = 0;
340 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
341 NS += PD.NumValueSites[Kind];
342 if (NS) {
343 ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
344
345 auto *ValuesVar =
346 new GlobalVariable(*M, ValuesTy, false, NamePtr->getLinkage(),
347 Constant::getNullValue(ValuesTy),
348 getVarName(Inc, getInstrProfValuesVarPrefix()));
349 ValuesVar->setVisibility(NamePtr->getVisibility());
350 ValuesVar->setSection(getInstrProfValuesSectionName(isMachO()));
351 ValuesVar->setAlignment(8);
352 ValuesVar->setComdat(ProfileVarsComdat);
353 ValuesPtrExpr =
354 ConstantExpr::getBitCast(ValuesVar, llvm::Type::getInt8PtrTy(Ctx));
355 }
356 }
357
358 // Create data variable.
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000359 auto *Int16Ty = Type::getInt16Ty(Ctx);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000360 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
Xinliang David Li192c7482015-11-05 00:47:26 +0000361 Type *DataTypes[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000362#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
363#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000364 };
Justin Bogner61ba2e32014-12-08 18:02:35 +0000365 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
Xinliang David Li192c7482015-11-05 00:47:26 +0000366
Xinliang David Li69a00f02016-06-21 02:39:08 +0000367 Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
368 ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
369 : ConstantPointerNull::get(Int8PtrTy);
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000370
Xinliang David Li69a00f02016-06-21 02:39:08 +0000371 Constant *Int16ArrayVals[IPVK_Last + 1];
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000372 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
373 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
374
Justin Bogner61ba2e32014-12-08 18:02:35 +0000375 Constant *DataVals[] = {
Xinliang David Li69a00f02016-06-21 02:39:08 +0000376#define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
377#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Li192c7482015-11-05 00:47:26 +0000378 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000379 auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
Justin Bogner61ba2e32014-12-08 18:02:35 +0000380 ConstantStruct::get(DataTy, DataVals),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000381 getVarName(Inc, getInstrProfDataVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000382 Data->setVisibility(NamePtr->getVisibility());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000383 Data->setSection(getDataSection());
Xinliang David Lic7c1f852015-11-23 18:02:59 +0000384 Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
Wei Mi3cc92042015-09-23 22:40:45 +0000385 Data->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000386
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000387 PD.RegionCounters = CounterPtr;
388 PD.DataVar = Data;
389 ProfileDataMap[NamePtr] = PD;
390
Justin Bogner61ba2e32014-12-08 18:02:35 +0000391 // Mark the data variable as used so that it isn't stripped out.
392 UsedVars.push_back(Data);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000393 // Now that the linkage set by the FE has been passed to the data and counter
394 // variables, reset Name variable's linkage and visibility to private so that
395 // it can be removed later by the compiler.
396 NamePtr->setLinkage(GlobalValue::PrivateLinkage);
397 // Collect the referenced names to be used by emitNameData.
398 ReferencedNames.push_back(NamePtr);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000399
Xinliang David Li192c7482015-11-05 00:47:26 +0000400 return CounterPtr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000401}
402
Xinliang David Lib628dd32016-05-21 22:55:34 +0000403void InstrProfiling::emitVNodes() {
404 if (!ValueProfileStaticAlloc)
405 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000406
Xinliang David Lib628dd32016-05-21 22:55:34 +0000407 // For now only support this on platforms that do
408 // not require runtime registration to discover
409 // named section start/end.
410 if (needsRuntimeRegistrationOfSectionRange(*M))
411 return;
Xinliang David Li8da773b2016-05-17 20:19:03 +0000412
Xinliang David Lib628dd32016-05-21 22:55:34 +0000413 size_t TotalNS = 0;
414 for (auto &PD : ProfileDataMap) {
415 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
416 TotalNS += PD.second.NumValueSites[Kind];
417 }
418
419 if (!TotalNS)
420 return;
421
422 uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
Xinliang David Li69a00f02016-06-21 02:39:08 +0000423// Heuristic for small programs with very few total value sites.
424// The default value of vp-counters-per-site is chosen based on
425// the observation that large apps usually have a low percentage
426// of value sites that actually have any profile data, and thus
427// the average number of counters per site is low. For small
428// apps with very few sites, this may not be true. Bump up the
429// number of counters in this case.
Xinliang David Lie4520762016-05-23 19:29:26 +0000430#define INSTR_PROF_MIN_VAL_COUNTS 10
431 if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000432 NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
Xinliang David Lib628dd32016-05-21 22:55:34 +0000433
434 auto &Ctx = M->getContext();
435 Type *VNodeTypes[] = {
436#define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
437#include "llvm/ProfileData/InstrProfData.inc"
438 };
439 auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
440
441 ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
442 auto *VNodesVar = new GlobalVariable(
443 *M, VNodesTy, false, llvm::GlobalValue::PrivateLinkage,
444 Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
445 VNodesVar->setSection(getInstrProfVNodesSectionName(isMachO()));
446 UsedVars.push_back(VNodesVar);
Xinliang David Li8da773b2016-05-17 20:19:03 +0000447}
448
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000449void InstrProfiling::emitNameData() {
450 std::string UncompressedData;
451
452 if (ReferencedNames.empty())
453 return;
454
455 std::string CompressedNameStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000456 if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
Vedant Kumar43cba732016-05-03 16:53:17 +0000457 DoNameCompression)) {
Vedant Kumar9152fd12016-05-19 03:54:45 +0000458 llvm::report_fatal_error(toString(std::move(E)), false);
Vedant Kumar43cba732016-05-03 16:53:17 +0000459 }
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000460
461 auto &Ctx = M->getContext();
462 auto *NamesVal = llvm::ConstantDataArray::getString(
463 Ctx, StringRef(CompressedNameStr), false);
464 NamesVar = new llvm::GlobalVariable(*M, NamesVal->getType(), true,
465 llvm::GlobalValue::PrivateLinkage,
466 NamesVal, getInstrProfNamesVarName());
467 NamesSize = CompressedNameStr.size();
468 NamesVar->setSection(getNameSection());
469 UsedVars.push_back(NamesVar);
470}
471
Justin Bogner61ba2e32014-12-08 18:02:35 +0000472void InstrProfiling::emitRegistration() {
Xinliang David Li8da773b2016-05-17 20:19:03 +0000473 if (!needsRuntimeRegistrationOfSectionRange(*M))
Xinliang David Liaa0592c2015-10-19 04:17:10 +0000474 return;
Xinliang David Li3dd88172015-10-13 18:39:48 +0000475
Justin Bogner61ba2e32014-12-08 18:02:35 +0000476 // Construct the function.
477 auto *VoidTy = Type::getVoidTy(M->getContext());
478 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000479 auto *Int64Ty = Type::getInt64Ty(M->getContext());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000480 auto *RegisterFTy = FunctionType::get(VoidTy, false);
481 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000482 getInstrProfRegFuncsName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000483 RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000484 if (Options.NoRedZone)
485 RegisterF->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000486
Diego Novillob3029d22015-06-04 11:45:32 +0000487 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000488 auto *RuntimeRegisterF =
489 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000490 getInstrProfRegFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000491
492 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
493 for (Value *Data : UsedVars)
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000494 if (Data != NamesVar)
495 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
496
497 if (NamesVar) {
498 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
499 auto *NamesRegisterTy =
500 FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
501 auto *NamesRegisterF =
502 Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
503 getInstrProfNamesRegFuncName(), M);
504 IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
505 IRB.getInt64(NamesSize)});
506 }
507
Justin Bogner61ba2e32014-12-08 18:02:35 +0000508 IRB.CreateRetVoid();
509}
510
511void InstrProfiling::emitRuntimeHook() {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000512
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000513 // We expect the linker to be invoked with -u<hook_var> flag for linux,
514 // for which case there is no need to emit the user function.
515 if (Triple(M->getTargetTriple()).isOSLinux())
516 return;
517
Justin Bogner61ba2e32014-12-08 18:02:35 +0000518 // If the module's provided its own runtime, we don't need to do anything.
Xinliang David Li69a00f02016-06-21 02:39:08 +0000519 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
520 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000521
522 // Declare an external variable that will pull in the runtime initialization.
523 auto *Int32Ty = Type::getInt32Ty(M->getContext());
524 auto *Var =
525 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000526 nullptr, getInstrProfRuntimeHookVarName());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000527
528 // Make a function that uses it.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000529 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
530 GlobalValue::LinkOnceODRLinkage,
531 getInstrProfRuntimeHookVarUseFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000532 User->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000533 if (Options.NoRedZone)
534 User->addFnAttr(Attribute::NoRedZone);
Justin Bogner2e427d42015-02-25 22:52:20 +0000535 User->setVisibility(GlobalValue::HiddenVisibility);
Xinliang David Lia2286082016-05-25 17:17:51 +0000536 if (Triple(M->getTargetTriple()).supportsCOMDAT())
Xinliang David Lif4edae62016-05-24 18:47:38 +0000537 User->setComdat(M->getOrInsertComdat(User->getName()));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000538
539 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
540 auto *Load = IRB.CreateLoad(Var);
541 IRB.CreateRet(Load);
542
543 // Mark the user variable as used so that it isn't stripped out.
544 UsedVars.push_back(User);
545}
546
547void InstrProfiling::emitUses() {
548 if (UsedVars.empty())
549 return;
550
551 GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used");
Diego Novillob3029d22015-06-04 11:45:32 +0000552 std::vector<Constant *> MergedVars;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000553 if (LLVMUsed) {
554 // Collect the existing members of llvm.used.
555 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
556 for (unsigned I = 0, E = Inits->getNumOperands(); I != E; ++I)
557 MergedVars.push_back(Inits->getOperand(I));
558 LLVMUsed->eraseFromParent();
559 }
560
561 Type *i8PTy = Type::getInt8PtrTy(M->getContext());
562 // Add uses for our data.
563 for (auto *Value : UsedVars)
564 MergedVars.push_back(
Diego Novillob3029d22015-06-04 11:45:32 +0000565 ConstantExpr::getBitCast(cast<Constant>(Value), i8PTy));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000566
567 // Recreate llvm.used.
568 ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size());
Diego Novillob3029d22015-06-04 11:45:32 +0000569 LLVMUsed =
570 new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage,
571 ConstantArray::get(ATy, MergedVars), "llvm.used");
Justin Bogner61ba2e32014-12-08 18:02:35 +0000572 LLVMUsed->setSection("llvm.metadata");
573}
574
575void InstrProfiling::emitInitialization() {
Vedant Kumarcd32eba2016-07-21 17:50:07 +0000576 StringRef InstrProfileOutput = Options.InstrProfileOutput;
Justin Bognerba1900c2015-04-30 23:49:23 +0000577
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000578 if (!InstrProfileOutput.empty()) {
579 // Create variable for profile name.
580 Constant *ProfileNameConst =
581 ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
582 GlobalVariable *ProfileNameVar = new GlobalVariable(
583 *M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
584 ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
585 Triple TT(M->getTargetTriple());
586 if (TT.supportsCOMDAT()) {
587 ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
588 ProfileNameVar->setComdat(M->getOrInsertComdat(
589 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
590 }
591 }
592
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000593 Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
Xinliang David Li6f8c5042016-07-21 23:19:10 +0000594 if (!RegisterF)
Xinliang David Li69a00f02016-06-21 02:39:08 +0000595 return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000596
597 // Create the initialization function.
598 auto *VoidTy = Type::getVoidTy(M->getContext());
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000599 auto *F = Function::Create(FunctionType::get(VoidTy, false),
600 GlobalValue::InternalLinkage,
601 getInstrProfInitFuncName(), M);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000602 F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000603 F->addFnAttr(Attribute::NoInline);
Xinliang David Li69a00f02016-06-21 02:39:08 +0000604 if (Options.NoRedZone)
605 F->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000606
607 // Add the basic block and the necessary calls.
608 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
Justin Bognerba1900c2015-04-30 23:49:23 +0000609 if (RegisterF)
David Blaikieff6409d2015-05-18 22:13:54 +0000610 IRB.CreateCall(RegisterF, {});
Justin Bogner61ba2e32014-12-08 18:02:35 +0000611 IRB.CreateRetVoid();
612
613 appendToGlobalCtors(*M, F, 0);
614}