blob: 397e64b410e1b95b53698032e0545367d57190d1 [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 Lie6b89292016-04-18 17:47:38 +000034class InstrProfilingLegacyPass : public ModulePass {
35 InstrProfiling InstrProf;
36
Justin Bogner61ba2e32014-12-08 18:02:35 +000037public:
38 static char ID;
Xinliang David Lie6b89292016-04-18 17:47:38 +000039 InstrProfilingLegacyPass() : ModulePass(ID), InstrProf() {}
40 InstrProfilingLegacyPass(const InstrProfOptions &Options)
41 : ModulePass(ID), InstrProf(Options) {}
Justin Bogner61ba2e32014-12-08 18:02:35 +000042 const char *getPassName() const override {
43 return "Frontend instrumentation-based coverage lowering";
44 }
45
Xinliang David Lie6b89292016-04-18 17:47:38 +000046 bool runOnModule(Module &M) override { return InstrProf.run(M); }
Justin Bogner61ba2e32014-12-08 18:02:35 +000047
48 void getAnalysisUsage(AnalysisUsage &AU) const override {
49 AU.setPreservesCFG();
50 }
Justin Bogner61ba2e32014-12-08 18:02:35 +000051};
52
53} // anonymous namespace
54
Xinliang David Lie6b89292016-04-18 17:47:38 +000055PreservedAnalyses InstrProfiling::run(Module &M, AnalysisManager<Module> &AM) {
56 if (!run(M))
57 return PreservedAnalyses::all();
58
59 return PreservedAnalyses::none();
60}
61
62char InstrProfilingLegacyPass::ID = 0;
63INITIALIZE_PASS(InstrProfilingLegacyPass, "instrprof",
Justin Bogner61ba2e32014-12-08 18:02:35 +000064 "Frontend instrumentation-based coverage lowering.", false,
65 false)
66
Xinliang David Lie6b89292016-04-18 17:47:38 +000067ModulePass *llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options) {
68 return new InstrProfilingLegacyPass(Options);
Justin Bogner61ba2e32014-12-08 18:02:35 +000069}
70
Xinliang David Lie6b89292016-04-18 17:47:38 +000071bool InstrProfiling::isMachO() const {
72 return Triple(M->getTargetTriple()).isOSBinFormatMachO();
73}
74
75/// Get the section name for the counter variables.
76StringRef InstrProfiling::getCountersSection() const {
77 return getInstrProfCountersSectionName(isMachO());
78}
79
80/// Get the section name for the name variables.
81StringRef InstrProfiling::getNameSection() const {
82 return getInstrProfNameSectionName(isMachO());
83}
84
85/// Get the section name for the profile data variables.
86StringRef InstrProfiling::getDataSection() const {
87 return getInstrProfDataSectionName(isMachO());
88}
89
90/// Get the section name for the coverage mapping data.
91StringRef InstrProfiling::getCoverageSection() const {
92 return getInstrProfCoverageSectionName(isMachO());
93}
94
95bool InstrProfiling::run(Module &M) {
Justin Bogner61ba2e32014-12-08 18:02:35 +000096 bool MadeChange = false;
97
98 this->M = &M;
Xinliang David Lia82d6c02016-02-08 18:13:49 +000099 NamesVar = nullptr;
100 NamesSize = 0;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000101 ProfileDataMap.clear();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000102 UsedVars.clear();
103
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000104 // We did not know how many value sites there would be inside
105 // the instrumented function. This is counting the number of instrumented
106 // target value sites to enter it as field in the profile data variable.
Rong Xu294572f2016-01-19 18:29:54 +0000107 for (Function &F : M) {
108 InstrProfIncrementInst *FirstProfIncInst = nullptr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000109 for (BasicBlock &BB : F)
Rong Xu294572f2016-01-19 18:29:54 +0000110 for (auto I = BB.begin(), E = BB.end(); I != E; I++)
111 if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000112 computeNumValueSiteCounts(Ind);
Rong Xu294572f2016-01-19 18:29:54 +0000113 else if (FirstProfIncInst == nullptr)
114 FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
115
116 // Value profiling intrinsic lowering requires per-function profile data
117 // variable to be created first.
118 if (FirstProfIncInst != nullptr)
119 static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
120 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000121
122 for (Function &F : M)
123 for (BasicBlock &BB : F)
124 for (auto I = BB.begin(), E = BB.end(); I != E;) {
125 auto Instr = I++;
126 if (auto *Inc = dyn_cast<InstrProfIncrementInst>(Instr)) {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000127 lowerIncrement(Inc);
128 MadeChange = true;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000129 } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
130 lowerValueProfileInst(Ind);
131 MadeChange = true;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000132 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000133 }
134
Xinliang David Li81056072016-01-07 20:05:49 +0000135 if (GlobalVariable *CoverageNamesVar =
Xinliang David Li440cd702016-01-20 00:24:36 +0000136 M.getNamedGlobal(getCoverageUnusedNamesVarName())) {
Xinliang David Li81056072016-01-07 20:05:49 +0000137 lowerCoverageData(CoverageNamesVar);
Justin Bognerd24e1852015-02-11 02:52:44 +0000138 MadeChange = true;
139 }
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000140
Justin Bogner61ba2e32014-12-08 18:02:35 +0000141 if (!MadeChange)
142 return false;
143
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000144 emitNameData();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000145 emitRegistration();
146 emitRuntimeHook();
147 emitUses();
148 emitInitialization();
149 return true;
150}
151
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000152static Constant *getOrInsertValueProfilingCall(Module &M) {
Xinliang David Lic7673232015-11-22 00:22:07 +0000153 LLVMContext &Ctx = M.getContext();
154 auto *ReturnTy = Type::getVoidTy(M.getContext());
155 Type *ParamTypes[] = {
156#define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
157#include "llvm/ProfileData/InstrProfData.inc"
158 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000159 auto *ValueProfilingCallTy =
Xinliang David Lic7673232015-11-22 00:22:07 +0000160 FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
Xinliang David Li924e0582015-11-22 05:42:31 +0000161 return M.getOrInsertFunction(getInstrProfValueProfFuncName(),
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000162 ValueProfilingCallTy);
163}
164
165void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
166
167 GlobalVariable *Name = Ind->getName();
168 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
169 uint64_t Index = Ind->getIndex()->getZExtValue();
170 auto It = ProfileDataMap.find(Name);
171 if (It == ProfileDataMap.end()) {
172 PerFunctionProfileData PD;
173 PD.NumValueSites[ValueKind] = Index + 1;
174 ProfileDataMap[Name] = PD;
175 } else if (It->second.NumValueSites[ValueKind] <= Index)
176 It->second.NumValueSites[ValueKind] = Index + 1;
177}
178
179void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
180
181 GlobalVariable *Name = Ind->getName();
182 auto It = ProfileDataMap.find(Name);
183 assert(It != ProfileDataMap.end() && It->second.DataVar &&
184 "value profiling detected in function with no counter incerement");
185
186 GlobalVariable *DataVar = It->second.DataVar;
187 uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
188 uint64_t Index = Ind->getIndex()->getZExtValue();
189 for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
190 Index += It->second.NumValueSites[Kind];
191
192 IRBuilder<> Builder(Ind);
193 Value* Args[3] = {Ind->getTargetValue(),
194 Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
195 Builder.getInt32(Index)};
196 Ind->replaceAllUsesWith(
197 Builder.CreateCall(getOrInsertValueProfilingCall(*M), Args));
198 Ind->eraseFromParent();
199}
200
Justin Bogner61ba2e32014-12-08 18:02:35 +0000201void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
202 GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
203
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000204 IRBuilder<> Builder(Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000205 uint64_t Index = Inc->getIndex()->getZExtValue();
Diego Novillob3029d22015-06-04 11:45:32 +0000206 Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
207 Value *Count = Builder.CreateLoad(Addr, "pgocount");
Justin Bogner61ba2e32014-12-08 18:02:35 +0000208 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
209 Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
210 Inc->eraseFromParent();
211}
212
Xinliang David Li81056072016-01-07 20:05:49 +0000213void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
Justin Bognerd24e1852015-02-11 02:52:44 +0000214
Xinliang David Li81056072016-01-07 20:05:49 +0000215 ConstantArray *Names =
216 cast<ConstantArray>(CoverageNamesVar->getInitializer());
217 for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
218 Constant *NC = Names->getOperand(I);
219 Value *V = NC->stripPointerCasts();
Justin Bognerd24e1852015-02-11 02:52:44 +0000220 assert(isa<GlobalVariable>(V) && "Missing reference to function name");
221 GlobalVariable *Name = cast<GlobalVariable>(V);
222
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000223 Name->setLinkage(GlobalValue::PrivateLinkage);
224 ReferencedNames.push_back(Name);
Justin Bognerd24e1852015-02-11 02:52:44 +0000225 }
226}
227
Justin Bogner61ba2e32014-12-08 18:02:35 +0000228/// Get the name of a profiling variable for a particular function.
Xinliang David Li83bc4222015-10-22 20:32:12 +0000229static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000230 StringRef NamePrefix = getInstrProfNameVarPrefix();
231 StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
Xinliang David Li83bc4222015-10-22 20:32:12 +0000232 return (Prefix + Name).str();
Justin Bogner61ba2e32014-12-08 18:02:35 +0000233}
234
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000235static inline bool shouldRecordFunctionAddr(Function *F) {
236 // Check the linkage
237 if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
238 !F->hasAvailableExternallyLinkage())
239 return true;
Rong Xuaf5aeba2016-04-27 21:17:30 +0000240 // Prohibit function address recording if the function is both internal and
241 // COMDAT. This avoids the profile data variable referencing internal symbols
242 // in COMDAT.
243 if (F->hasLocalLinkage() && F->hasComdat())
244 return false;
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000245 // Check uses of this function for other than direct calls or invokes to it.
246 return F->hasAddressTaken();
247}
248
Xinliang David Li985ff202016-02-27 23:11:30 +0000249static inline bool needsComdatForCounter(Function &F, Module &M) {
250
251 if (F.hasComdat())
252 return true;
253
254 Triple TT(M.getTargetTriple());
255 if (!TT.isOSBinFormatELF())
256 return false;
257
258 // See createPGOFuncNameVar for more details. To avoid link errors, profile
259 // counters for function with available_externally linkage needs to be changed
260 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
261 // created. Without using comdat, duplicate entries won't be removed by the
262 // linker leading to increased data segement size and raw profile size. Even
263 // worse, since the referenced counter from profile per-function data object
264 // will be resolved to the common strong definition, the profile counts for
265 // available_externally functions will end up being duplicated in raw profile
266 // data. This can result in distorted profile as the counts of those dups
267 // will be accumulated by the profile merger.
268 GlobalValue::LinkageTypes Linkage = F.getLinkage();
269 if (Linkage != GlobalValue::ExternalWeakLinkage &&
270 Linkage != GlobalValue::AvailableExternallyLinkage)
271 return false;
272
273 return true;
274}
275
276static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F,
Xinliang David Liab361ef2015-12-21 21:52:27 +0000277 InstrProfIncrementInst *Inc) {
Xinliang David Li985ff202016-02-27 23:11:30 +0000278 if (!needsComdatForCounter(F, M))
279 return nullptr;
280
Xinliang David Liab361ef2015-12-21 21:52:27 +0000281 // COFF format requires a COMDAT section to have a key symbol with the same
Vedant Kumar2d5b5d32016-02-03 23:22:43 +0000282 // name. The linker targeting COFF also requires that the COMDAT
Xinliang David Li5fe04552015-12-22 00:11:15 +0000283 // a section is associated to must precede the associating section. For this
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000284 // reason, we must choose the counter var's name as the name of the comdat.
Xinliang David Liab361ef2015-12-21 21:52:27 +0000285 StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF()
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000286 ? getInstrProfCountersVarPrefix()
Xinliang David Liab361ef2015-12-21 21:52:27 +0000287 : getInstrProfComdatPrefix());
288 return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix)));
289}
290
Justin Bogner61ba2e32014-12-08 18:02:35 +0000291GlobalVariable *
292InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
Xinliang David Li192c7482015-11-05 00:47:26 +0000293 GlobalVariable *NamePtr = Inc->getName();
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000294 auto It = ProfileDataMap.find(NamePtr);
295 PerFunctionProfileData PD;
296 if (It != ProfileDataMap.end()) {
297 if (It->second.RegionCounters)
298 return It->second.RegionCounters;
299 PD = It->second;
300 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000301
Wei Mi3cc92042015-09-23 22:40:45 +0000302 // Move the name variable to the right section. Place them in a COMDAT group
303 // if the associated function is a COMDAT. This will make sure that
304 // only one copy of counters of the COMDAT function will be emitted after
305 // linking.
Diego Novillodf4837b2015-05-27 19:34:01 +0000306 Function *Fn = Inc->getParent()->getParent();
Wei Mi3cc92042015-09-23 22:40:45 +0000307 Comdat *ProfileVarsComdat = nullptr;
Xinliang David Li985ff202016-02-27 23:11:30 +0000308 ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000309
310 uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
311 LLVMContext &Ctx = M->getContext();
312 ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
313
314 // Create the counters variable.
Xinliang David Li192c7482015-11-05 00:47:26 +0000315 auto *CounterPtr =
316 new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000317 Constant::getNullValue(CounterTy),
318 getVarName(Inc, getInstrProfCountersVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000319 CounterPtr->setVisibility(NamePtr->getVisibility());
320 CounterPtr->setSection(getCountersSection());
321 CounterPtr->setAlignment(8);
322 CounterPtr->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000323
Justin Bogner61ba2e32014-12-08 18:02:35 +0000324 // Create data variable.
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000325 auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
326 auto *Int16Ty = Type::getInt16Ty(Ctx);
327 auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last+1);
Xinliang David Li192c7482015-11-05 00:47:26 +0000328 Type *DataTypes[] = {
329 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
330 #include "llvm/ProfileData/InstrProfData.inc"
331 };
Justin Bogner61ba2e32014-12-08 18:02:35 +0000332 auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
Xinliang David Li192c7482015-11-05 00:47:26 +0000333
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000334 Constant *FunctionAddr = shouldRecordFunctionAddr(Fn) ?
335 ConstantExpr::getBitCast(Fn, Int8PtrTy) :
336 ConstantPointerNull::get(Int8PtrTy);
337
338 Constant *Int16ArrayVals[IPVK_Last+1];
339 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
340 Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
341
Justin Bogner61ba2e32014-12-08 18:02:35 +0000342 Constant *DataVals[] = {
Xinliang David Li192c7482015-11-05 00:47:26 +0000343 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
344 #include "llvm/ProfileData/InstrProfData.inc"
345 };
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000346 auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
Justin Bogner61ba2e32014-12-08 18:02:35 +0000347 ConstantStruct::get(DataTy, DataVals),
Xinliang David Li83bc4222015-10-22 20:32:12 +0000348 getVarName(Inc, getInstrProfDataVarPrefix()));
Xinliang David Li192c7482015-11-05 00:47:26 +0000349 Data->setVisibility(NamePtr->getVisibility());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000350 Data->setSection(getDataSection());
Xinliang David Lic7c1f852015-11-23 18:02:59 +0000351 Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
Wei Mi3cc92042015-09-23 22:40:45 +0000352 Data->setComdat(ProfileVarsComdat);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000353
Betul Buyukkurt6fac1742015-11-18 18:14:55 +0000354 PD.RegionCounters = CounterPtr;
355 PD.DataVar = Data;
356 ProfileDataMap[NamePtr] = PD;
357
Justin Bogner61ba2e32014-12-08 18:02:35 +0000358 // Mark the data variable as used so that it isn't stripped out.
359 UsedVars.push_back(Data);
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000360 // Now that the linkage set by the FE has been passed to the data and counter
361 // variables, reset Name variable's linkage and visibility to private so that
362 // it can be removed later by the compiler.
363 NamePtr->setLinkage(GlobalValue::PrivateLinkage);
364 // Collect the referenced names to be used by emitNameData.
365 ReferencedNames.push_back(NamePtr);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000366
Xinliang David Li192c7482015-11-05 00:47:26 +0000367 return CounterPtr;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000368}
369
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000370void InstrProfiling::emitNameData() {
371 std::string UncompressedData;
372
373 if (ReferencedNames.empty())
374 return;
375
376 std::string CompressedNameStr;
377 collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
378 DoNameCompression);
379
380 auto &Ctx = M->getContext();
381 auto *NamesVal = llvm::ConstantDataArray::getString(
382 Ctx, StringRef(CompressedNameStr), false);
383 NamesVar = new llvm::GlobalVariable(*M, NamesVal->getType(), true,
384 llvm::GlobalValue::PrivateLinkage,
385 NamesVal, getInstrProfNamesVarName());
386 NamesSize = CompressedNameStr.size();
387 NamesVar->setSection(getNameSection());
388 UsedVars.push_back(NamesVar);
389}
390
Justin Bogner61ba2e32014-12-08 18:02:35 +0000391void InstrProfiling::emitRegistration() {
392 // Don't do this for Darwin. compiler-rt uses linker magic.
393 if (Triple(M->getTargetTriple()).isOSDarwin())
394 return;
395
Xinliang David Li3dd88172015-10-13 18:39:48 +0000396 // Use linker script magic to get data/cnts/name start/end.
Xinliang David Liaa0592c2015-10-19 04:17:10 +0000397 if (Triple(M->getTargetTriple()).isOSLinux() ||
Sean Silvaea399f02016-02-27 06:01:26 +0000398 Triple(M->getTargetTriple()).isOSFreeBSD() ||
399 Triple(M->getTargetTriple()).isPS4CPU())
Xinliang David Liaa0592c2015-10-19 04:17:10 +0000400 return;
Xinliang David Li3dd88172015-10-13 18:39:48 +0000401
Justin Bogner61ba2e32014-12-08 18:02:35 +0000402 // Construct the function.
403 auto *VoidTy = Type::getVoidTy(M->getContext());
404 auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000405 auto *Int64Ty = Type::getInt64Ty(M->getContext());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000406 auto *RegisterFTy = FunctionType::get(VoidTy, false);
407 auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000408 getInstrProfRegFuncsName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000409 RegisterF->setUnnamedAddr(true);
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000410 if (Options.NoRedZone) RegisterF->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000411
Diego Novillob3029d22015-06-04 11:45:32 +0000412 auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000413 auto *RuntimeRegisterF =
414 Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000415 getInstrProfRegFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000416
417 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
418 for (Value *Data : UsedVars)
Xinliang David Lia82d6c02016-02-08 18:13:49 +0000419 if (Data != NamesVar)
420 IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
421
422 if (NamesVar) {
423 Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
424 auto *NamesRegisterTy =
425 FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
426 auto *NamesRegisterF =
427 Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
428 getInstrProfNamesRegFuncName(), M);
429 IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
430 IRB.getInt64(NamesSize)});
431 }
432
Justin Bogner61ba2e32014-12-08 18:02:35 +0000433 IRB.CreateRetVoid();
434}
435
436void InstrProfiling::emitRuntimeHook() {
Justin Bogner61ba2e32014-12-08 18:02:35 +0000437
Xinliang David Li7a88ad62015-10-29 04:08:31 +0000438 // We expect the linker to be invoked with -u<hook_var> flag for linux,
439 // for which case there is no need to emit the user function.
440 if (Triple(M->getTargetTriple()).isOSLinux())
441 return;
442
Justin Bogner61ba2e32014-12-08 18:02:35 +0000443 // If the module's provided its own runtime, we don't need to do anything.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000444 if (M->getGlobalVariable(getInstrProfRuntimeHookVarName())) return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000445
446 // Declare an external variable that will pull in the runtime initialization.
447 auto *Int32Ty = Type::getInt32Ty(M->getContext());
448 auto *Var =
449 new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000450 nullptr, getInstrProfRuntimeHookVarName());
Justin Bogner61ba2e32014-12-08 18:02:35 +0000451
452 // Make a function that uses it.
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000453 auto *User = Function::Create(FunctionType::get(Int32Ty, false),
454 GlobalValue::LinkOnceODRLinkage,
455 getInstrProfRuntimeHookVarUseFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000456 User->addFnAttr(Attribute::NoInline);
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000457 if (Options.NoRedZone) User->addFnAttr(Attribute::NoRedZone);
Justin Bogner2e427d42015-02-25 22:52:20 +0000458 User->setVisibility(GlobalValue::HiddenVisibility);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000459
460 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
461 auto *Load = IRB.CreateLoad(Var);
462 IRB.CreateRet(Load);
463
464 // Mark the user variable as used so that it isn't stripped out.
465 UsedVars.push_back(User);
466}
467
468void InstrProfiling::emitUses() {
469 if (UsedVars.empty())
470 return;
471
472 GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used");
Diego Novillob3029d22015-06-04 11:45:32 +0000473 std::vector<Constant *> MergedVars;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000474 if (LLVMUsed) {
475 // Collect the existing members of llvm.used.
476 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
477 for (unsigned I = 0, E = Inits->getNumOperands(); I != E; ++I)
478 MergedVars.push_back(Inits->getOperand(I));
479 LLVMUsed->eraseFromParent();
480 }
481
482 Type *i8PTy = Type::getInt8PtrTy(M->getContext());
483 // Add uses for our data.
484 for (auto *Value : UsedVars)
485 MergedVars.push_back(
Diego Novillob3029d22015-06-04 11:45:32 +0000486 ConstantExpr::getBitCast(cast<Constant>(Value), i8PTy));
Justin Bogner61ba2e32014-12-08 18:02:35 +0000487
488 // Recreate llvm.used.
489 ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size());
Diego Novillob3029d22015-06-04 11:45:32 +0000490 LLVMUsed =
491 new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage,
492 ConstantArray::get(ATy, MergedVars), "llvm.used");
Justin Bogner61ba2e32014-12-08 18:02:35 +0000493 LLVMUsed->setSection("llvm.metadata");
494}
495
496void InstrProfiling::emitInitialization() {
Justin Bognerba1900c2015-04-30 23:49:23 +0000497 std::string InstrProfileOutput = Options.InstrProfileOutput;
498
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000499 Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
500 if (!RegisterF && InstrProfileOutput.empty()) return;
Justin Bogner61ba2e32014-12-08 18:02:35 +0000501
502 // Create the initialization function.
503 auto *VoidTy = Type::getVoidTy(M->getContext());
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000504 auto *F = Function::Create(FunctionType::get(VoidTy, false),
505 GlobalValue::InternalLinkage,
506 getInstrProfInitFuncName(), M);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000507 F->setUnnamedAddr(true);
508 F->addFnAttr(Attribute::NoInline);
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000509 if (Options.NoRedZone) F->addFnAttr(Attribute::NoRedZone);
Justin Bogner61ba2e32014-12-08 18:02:35 +0000510
511 // Add the basic block and the necessary calls.
512 IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
Justin Bognerba1900c2015-04-30 23:49:23 +0000513 if (RegisterF)
David Blaikieff6409d2015-05-18 22:13:54 +0000514 IRB.CreateCall(RegisterF, {});
Justin Bognerba1900c2015-04-30 23:49:23 +0000515 if (!InstrProfileOutput.empty()) {
516 auto *Int8PtrTy = Type::getInt8PtrTy(M->getContext());
517 auto *SetNameTy = FunctionType::get(VoidTy, Int8PtrTy, false);
Xinliang David Li8ee08b02015-10-23 04:22:58 +0000518 auto *SetNameF = Function::Create(SetNameTy, GlobalValue::ExternalLinkage,
519 getInstrProfFileOverriderFuncName(), M);
Justin Bognerba1900c2015-04-30 23:49:23 +0000520
Diego Novillob0257c82015-06-29 20:03:46 +0000521 // Create variable for profile name.
Justin Bognerba1900c2015-04-30 23:49:23 +0000522 Constant *ProfileNameConst =
523 ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
524 GlobalVariable *ProfileName =
525 new GlobalVariable(*M, ProfileNameConst->getType(), true,
526 GlobalValue::PrivateLinkage, ProfileNameConst);
527
528 IRB.CreateCall(SetNameF, IRB.CreatePointerCast(ProfileName, Int8PtrTy));
529 }
Justin Bogner61ba2e32014-12-08 18:02:35 +0000530 IRB.CreateRetVoid();
531
532 appendToGlobalCtors(*M, F, 0);
533}