• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- InstrProfiling.cpp - Frontend instrumentation based profiling -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass lowers instrprof_* 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.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Transforms/InstrProfiling.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/IR/IRBuilder.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/ProfileData/InstrProf.h"
22 #include "llvm/Transforms/Utils/ModuleUtils.h"
23 
24 using namespace llvm;
25 
26 #define DEBUG_TYPE "instrprof"
27 
28 namespace {
29 
30 cl::opt<bool> DoNameCompression("enable-name-compression",
31                                 cl::desc("Enable name string compression"),
32                                 cl::init(true));
33 
34 cl::opt<bool> ValueProfileStaticAlloc(
35     "vp-static-alloc",
36     cl::desc("Do static counter allocation for value profiler"),
37     cl::init(true));
38 cl::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 
48 class InstrProfilingLegacyPass : public ModulePass {
49   InstrProfiling InstrProf;
50 
51 public:
52   static char ID;
InstrProfilingLegacyPass()53   InstrProfilingLegacyPass() : ModulePass(ID), InstrProf() {}
InstrProfilingLegacyPass(const InstrProfOptions & Options)54   InstrProfilingLegacyPass(const InstrProfOptions &Options)
55       : ModulePass(ID), InstrProf(Options) {}
getPassName() const56   const char *getPassName() const override {
57     return "Frontend instrumentation-based coverage lowering";
58   }
59 
runOnModule(Module & M)60   bool runOnModule(Module &M) override { return InstrProf.run(M); }
61 
getAnalysisUsage(AnalysisUsage & AU) const62   void getAnalysisUsage(AnalysisUsage &AU) const override {
63     AU.setPreservesCFG();
64   }
65 };
66 
67 } // anonymous namespace
68 
run(Module & M,AnalysisManager<Module> & AM)69 PreservedAnalyses InstrProfiling::run(Module &M, AnalysisManager<Module> &AM) {
70   if (!run(M))
71     return PreservedAnalyses::all();
72 
73   return PreservedAnalyses::none();
74 }
75 
76 char InstrProfilingLegacyPass::ID = 0;
77 INITIALIZE_PASS(InstrProfilingLegacyPass, "instrprof",
78                 "Frontend instrumentation-based coverage lowering.", false,
79                 false)
80 
81 ModulePass *
createInstrProfilingLegacyPass(const InstrProfOptions & Options)82 llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options) {
83   return new InstrProfilingLegacyPass(Options);
84 }
85 
isMachO() const86 bool InstrProfiling::isMachO() const {
87   return Triple(M->getTargetTriple()).isOSBinFormatMachO();
88 }
89 
90 /// Get the section name for the counter variables.
getCountersSection() const91 StringRef InstrProfiling::getCountersSection() const {
92   return getInstrProfCountersSectionName(isMachO());
93 }
94 
95 /// Get the section name for the name variables.
getNameSection() const96 StringRef InstrProfiling::getNameSection() const {
97   return getInstrProfNameSectionName(isMachO());
98 }
99 
100 /// Get the section name for the profile data variables.
getDataSection() const101 StringRef InstrProfiling::getDataSection() const {
102   return getInstrProfDataSectionName(isMachO());
103 }
104 
105 /// Get the section name for the coverage mapping data.
getCoverageSection() const106 StringRef InstrProfiling::getCoverageSection() const {
107   return getInstrProfCoverageSectionName(isMachO());
108 }
109 
run(Module & M)110 bool InstrProfiling::run(Module &M) {
111   bool MadeChange = false;
112 
113   this->M = &M;
114   NamesVar = nullptr;
115   NamesSize = 0;
116   ProfileDataMap.clear();
117   UsedVars.clear();
118 
119   // 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.
122   for (Function &F : M) {
123     InstrProfIncrementInst *FirstProfIncInst = nullptr;
124     for (BasicBlock &BB : F)
125       for (auto I = BB.begin(), E = BB.end(); I != E; I++)
126         if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
127           computeNumValueSiteCounts(Ind);
128         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   }
136 
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)) {
142           lowerIncrement(Inc);
143           MadeChange = true;
144         } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
145           lowerValueProfileInst(Ind);
146           MadeChange = true;
147         }
148       }
149 
150   if (GlobalVariable *CoverageNamesVar =
151           M.getNamedGlobal(getCoverageUnusedNamesVarName())) {
152     lowerCoverageData(CoverageNamesVar);
153     MadeChange = true;
154   }
155 
156   if (!MadeChange)
157     return false;
158 
159   emitVNodes();
160   emitNameData();
161   emitRegistration();
162   emitRuntimeHook();
163   emitUses();
164   emitInitialization();
165   return true;
166 }
167 
getOrInsertValueProfilingCall(Module & M)168 static Constant *getOrInsertValueProfilingCall(Module &M) {
169   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   };
175   auto *ValueProfilingCallTy =
176       FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
177   return M.getOrInsertFunction(getInstrProfValueProfFuncName(),
178                                ValueProfilingCallTy);
179 }
180 
computeNumValueSiteCounts(InstrProfValueProfileInst * Ind)181 void 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 
lowerValueProfileInst(InstrProfValueProfileInst * Ind)195 void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
196 
197   GlobalVariable *Name = Ind->getName();
198   auto It = ProfileDataMap.find(Name);
199   assert(It != ProfileDataMap.end() && It->second.DataVar &&
200          "value profiling detected in function with no counter incerement");
201 
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);
209   Value *Args[3] = {Ind->getTargetValue(),
210                     Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
211                     Builder.getInt32(Index)};
212   Ind->replaceAllUsesWith(
213       Builder.CreateCall(getOrInsertValueProfilingCall(*M), Args));
214   Ind->eraseFromParent();
215 }
216 
lowerIncrement(InstrProfIncrementInst * Inc)217 void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
218   GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
219 
220   IRBuilder<> Builder(Inc);
221   uint64_t Index = Inc->getIndex()->getZExtValue();
222   Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
223   Value *Count = Builder.CreateLoad(Addr, "pgocount");
224   Count = Builder.CreateAdd(Count, Builder.getInt64(1));
225   Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
226   Inc->eraseFromParent();
227 }
228 
lowerCoverageData(GlobalVariable * CoverageNamesVar)229 void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
230 
231   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();
236     assert(isa<GlobalVariable>(V) && "Missing reference to function name");
237     GlobalVariable *Name = cast<GlobalVariable>(V);
238 
239     Name->setLinkage(GlobalValue::PrivateLinkage);
240     ReferencedNames.push_back(Name);
241   }
242 }
243 
244 /// Get the name of a profiling variable for a particular function.
getVarName(InstrProfIncrementInst * Inc,StringRef Prefix)245 static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
246   StringRef NamePrefix = getInstrProfNameVarPrefix();
247   StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
248   return (Prefix + Name).str();
249 }
250 
shouldRecordFunctionAddr(Function * F)251 static inline bool shouldRecordFunctionAddr(Function *F) {
252   // Check the linkage
253   if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
254       !F->hasAvailableExternallyLinkage())
255     return true;
256   // 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;
261   // Check uses of this function for other than direct calls or invokes to it.
262   // 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
265   // be 'addresstaken'. If its address is not recorded here, the profile data
266   // with missing address may be picked by the linker leading  to missing
267   // indirect call target info.
268   return F->hasAddressTaken() || F->hasLinkOnceLinkage();
269 }
270 
needsComdatForCounter(Function & F,Module & M)271 static inline bool needsComdatForCounter(Function &F, Module &M) {
272 
273   if (F.hasComdat())
274     return true;
275 
276   Triple TT(M.getTargetTriple());
277   if (!TT.isOSBinFormatELF())
278     return false;
279 
280   // See createPGOFuncNameVar for more details. To avoid link errors, profile
281   // counters for function with available_externally linkage needs to be changed
282   // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
283   // created. Without using comdat, duplicate entries won't be removed by the
284   // linker leading to increased data segement size and raw profile size. Even
285   // worse, since the referenced counter from profile per-function data object
286   // will be resolved to the common strong definition, the profile counts for
287   // available_externally functions will end up being duplicated in raw profile
288   // data. This can result in distorted profile as the counts of those dups
289   // will be accumulated by the profile merger.
290   GlobalValue::LinkageTypes Linkage = F.getLinkage();
291   if (Linkage != GlobalValue::ExternalWeakLinkage &&
292       Linkage != GlobalValue::AvailableExternallyLinkage)
293     return false;
294 
295   return true;
296 }
297 
getOrCreateProfileComdat(Module & M,Function & F,InstrProfIncrementInst * Inc)298 static inline Comdat *getOrCreateProfileComdat(Module &M, Function &F,
299                                                InstrProfIncrementInst *Inc) {
300   if (!needsComdatForCounter(F, M))
301     return nullptr;
302 
303   // COFF format requires a COMDAT section to have a key symbol with the same
304   // name. The linker targeting COFF also requires that the COMDAT
305   // a section is associated to must precede the associating section. For this
306   // reason, we must choose the counter var's name as the name of the comdat.
307   StringRef ComdatPrefix = (Triple(M.getTargetTriple()).isOSBinFormatCOFF()
308                                 ? getInstrProfCountersVarPrefix()
309                                 : getInstrProfComdatPrefix());
310   return M.getOrInsertComdat(StringRef(getVarName(Inc, ComdatPrefix)));
311 }
312 
needsRuntimeRegistrationOfSectionRange(const Module & M)313 static bool needsRuntimeRegistrationOfSectionRange(const Module &M) {
314   // Don't do this for Darwin.  compiler-rt uses linker magic.
315   if (Triple(M.getTargetTriple()).isOSDarwin())
316     return false;
317 
318   // Use linker script magic to get data/cnts/name start/end.
319   if (Triple(M.getTargetTriple()).isOSLinux() ||
320       Triple(M.getTargetTriple()).isOSFreeBSD() ||
321       Triple(M.getTargetTriple()).isPS4CPU())
322     return false;
323 
324   return true;
325 }
326 
327 GlobalVariable *
getOrCreateRegionCounters(InstrProfIncrementInst * Inc)328 InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
329   GlobalVariable *NamePtr = Inc->getName();
330   auto It = ProfileDataMap.find(NamePtr);
331   PerFunctionProfileData PD;
332   if (It != ProfileDataMap.end()) {
333     if (It->second.RegionCounters)
334       return It->second.RegionCounters;
335     PD = It->second;
336   }
337 
338   // Move the name variable to the right section. Place them in a COMDAT group
339   // if the associated function is a COMDAT. This will make sure that
340   // only one copy of counters of the COMDAT function will be emitted after
341   // linking.
342   Function *Fn = Inc->getParent()->getParent();
343   Comdat *ProfileVarsComdat = nullptr;
344   ProfileVarsComdat = getOrCreateProfileComdat(*M, *Fn, Inc);
345 
346   uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
347   LLVMContext &Ctx = M->getContext();
348   ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
349 
350   // Create the counters variable.
351   auto *CounterPtr =
352       new GlobalVariable(*M, CounterTy, false, NamePtr->getLinkage(),
353                          Constant::getNullValue(CounterTy),
354                          getVarName(Inc, getInstrProfCountersVarPrefix()));
355   CounterPtr->setVisibility(NamePtr->getVisibility());
356   CounterPtr->setSection(getCountersSection());
357   CounterPtr->setAlignment(8);
358   CounterPtr->setComdat(ProfileVarsComdat);
359 
360   auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
361   // Allocate statically the array of pointers to value profile nodes for
362   // the current function.
363   Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
364   if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(*M)) {
365 
366     uint64_t NS = 0;
367     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
368       NS += PD.NumValueSites[Kind];
369     if (NS) {
370       ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
371 
372       auto *ValuesVar =
373           new GlobalVariable(*M, ValuesTy, false, NamePtr->getLinkage(),
374                              Constant::getNullValue(ValuesTy),
375                              getVarName(Inc, getInstrProfValuesVarPrefix()));
376       ValuesVar->setVisibility(NamePtr->getVisibility());
377       ValuesVar->setSection(getInstrProfValuesSectionName(isMachO()));
378       ValuesVar->setAlignment(8);
379       ValuesVar->setComdat(ProfileVarsComdat);
380       ValuesPtrExpr =
381           ConstantExpr::getBitCast(ValuesVar, llvm::Type::getInt8PtrTy(Ctx));
382     }
383   }
384 
385   // Create data variable.
386   auto *Int16Ty = Type::getInt16Ty(Ctx);
387   auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
388   Type *DataTypes[] = {
389 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
390 #include "llvm/ProfileData/InstrProfData.inc"
391   };
392   auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
393 
394   Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
395                                ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
396                                : ConstantPointerNull::get(Int8PtrTy);
397 
398   Constant *Int16ArrayVals[IPVK_Last + 1];
399   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
400     Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
401 
402   Constant *DataVals[] = {
403 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
404 #include "llvm/ProfileData/InstrProfData.inc"
405   };
406   auto *Data = new GlobalVariable(*M, DataTy, false, NamePtr->getLinkage(),
407                                   ConstantStruct::get(DataTy, DataVals),
408                                   getVarName(Inc, getInstrProfDataVarPrefix()));
409   Data->setVisibility(NamePtr->getVisibility());
410   Data->setSection(getDataSection());
411   Data->setAlignment(INSTR_PROF_DATA_ALIGNMENT);
412   Data->setComdat(ProfileVarsComdat);
413 
414   PD.RegionCounters = CounterPtr;
415   PD.DataVar = Data;
416   ProfileDataMap[NamePtr] = PD;
417 
418   // Mark the data variable as used so that it isn't stripped out.
419   UsedVars.push_back(Data);
420   // Now that the linkage set by the FE has been passed to the data and counter
421   // variables, reset Name variable's linkage and visibility to private so that
422   // it can be removed later by the compiler.
423   NamePtr->setLinkage(GlobalValue::PrivateLinkage);
424   // Collect the referenced names to be used by emitNameData.
425   ReferencedNames.push_back(NamePtr);
426 
427   return CounterPtr;
428 }
429 
emitVNodes()430 void InstrProfiling::emitVNodes() {
431   if (!ValueProfileStaticAlloc)
432     return;
433 
434   // For now only support this on platforms that do
435   // not require runtime registration to discover
436   // named section start/end.
437   if (needsRuntimeRegistrationOfSectionRange(*M))
438     return;
439 
440   size_t TotalNS = 0;
441   for (auto &PD : ProfileDataMap) {
442     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
443       TotalNS += PD.second.NumValueSites[Kind];
444   }
445 
446   if (!TotalNS)
447     return;
448 
449   uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
450 // Heuristic for small programs with very few total value sites.
451 // The default value of vp-counters-per-site is chosen based on
452 // the observation that large apps usually have a low percentage
453 // of value sites that actually have any profile data, and thus
454 // the average number of counters per site is low. For small
455 // apps with very few sites, this may not be true. Bump up the
456 // number of counters in this case.
457 #define INSTR_PROF_MIN_VAL_COUNTS 10
458   if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
459     NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
460 
461   auto &Ctx = M->getContext();
462   Type *VNodeTypes[] = {
463 #define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
464 #include "llvm/ProfileData/InstrProfData.inc"
465   };
466   auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
467 
468   ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
469   auto *VNodesVar = new GlobalVariable(
470       *M, VNodesTy, false, llvm::GlobalValue::PrivateLinkage,
471       Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
472   VNodesVar->setSection(getInstrProfVNodesSectionName(isMachO()));
473   UsedVars.push_back(VNodesVar);
474 }
475 
emitNameData()476 void InstrProfiling::emitNameData() {
477   std::string UncompressedData;
478 
479   if (ReferencedNames.empty())
480     return;
481 
482   std::string CompressedNameStr;
483   if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
484                                           DoNameCompression)) {
485     llvm::report_fatal_error(toString(std::move(E)), false);
486   }
487 
488   auto &Ctx = M->getContext();
489   auto *NamesVal = llvm::ConstantDataArray::getString(
490       Ctx, StringRef(CompressedNameStr), false);
491   NamesVar = new llvm::GlobalVariable(*M, NamesVal->getType(), true,
492                                       llvm::GlobalValue::PrivateLinkage,
493                                       NamesVal, getInstrProfNamesVarName());
494   NamesSize = CompressedNameStr.size();
495   NamesVar->setSection(getNameSection());
496   UsedVars.push_back(NamesVar);
497 }
498 
emitRegistration()499 void InstrProfiling::emitRegistration() {
500   if (!needsRuntimeRegistrationOfSectionRange(*M))
501     return;
502 
503   // Construct the function.
504   auto *VoidTy = Type::getVoidTy(M->getContext());
505   auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
506   auto *Int64Ty = Type::getInt64Ty(M->getContext());
507   auto *RegisterFTy = FunctionType::get(VoidTy, false);
508   auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
509                                      getInstrProfRegFuncsName(), M);
510   RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
511   if (Options.NoRedZone)
512     RegisterF->addFnAttr(Attribute::NoRedZone);
513 
514   auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
515   auto *RuntimeRegisterF =
516       Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
517                        getInstrProfRegFuncName(), M);
518 
519   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
520   for (Value *Data : UsedVars)
521     if (Data != NamesVar)
522       IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
523 
524   if (NamesVar) {
525     Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
526     auto *NamesRegisterTy =
527         FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
528     auto *NamesRegisterF =
529         Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
530                          getInstrProfNamesRegFuncName(), M);
531     IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
532                                     IRB.getInt64(NamesSize)});
533   }
534 
535   IRB.CreateRetVoid();
536 }
537 
emitRuntimeHook()538 void InstrProfiling::emitRuntimeHook() {
539 
540   // We expect the linker to be invoked with -u<hook_var> flag for linux,
541   // for which case there is no need to emit the user function.
542   if (Triple(M->getTargetTriple()).isOSLinux())
543     return;
544 
545   // If the module's provided its own runtime, we don't need to do anything.
546   if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
547     return;
548 
549   // Declare an external variable that will pull in the runtime initialization.
550   auto *Int32Ty = Type::getInt32Ty(M->getContext());
551   auto *Var =
552       new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
553                          nullptr, getInstrProfRuntimeHookVarName());
554 
555   // Make a function that uses it.
556   auto *User = Function::Create(FunctionType::get(Int32Ty, false),
557                                 GlobalValue::LinkOnceODRLinkage,
558                                 getInstrProfRuntimeHookVarUseFuncName(), M);
559   User->addFnAttr(Attribute::NoInline);
560   if (Options.NoRedZone)
561     User->addFnAttr(Attribute::NoRedZone);
562   User->setVisibility(GlobalValue::HiddenVisibility);
563   if (Triple(M->getTargetTriple()).supportsCOMDAT())
564     User->setComdat(M->getOrInsertComdat(User->getName()));
565 
566   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
567   auto *Load = IRB.CreateLoad(Var);
568   IRB.CreateRet(Load);
569 
570   // Mark the user variable as used so that it isn't stripped out.
571   UsedVars.push_back(User);
572 }
573 
emitUses()574 void InstrProfiling::emitUses() {
575   if (UsedVars.empty())
576     return;
577 
578   GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used");
579   std::vector<Constant *> MergedVars;
580   if (LLVMUsed) {
581     // Collect the existing members of llvm.used.
582     ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
583     for (unsigned I = 0, E = Inits->getNumOperands(); I != E; ++I)
584       MergedVars.push_back(Inits->getOperand(I));
585     LLVMUsed->eraseFromParent();
586   }
587 
588   Type *i8PTy = Type::getInt8PtrTy(M->getContext());
589   // Add uses for our data.
590   for (auto *Value : UsedVars)
591     MergedVars.push_back(
592         ConstantExpr::getBitCast(cast<Constant>(Value), i8PTy));
593 
594   // Recreate llvm.used.
595   ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size());
596   LLVMUsed =
597       new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage,
598                          ConstantArray::get(ATy, MergedVars), "llvm.used");
599   LLVMUsed->setSection("llvm.metadata");
600 }
601 
emitInitialization()602 void InstrProfiling::emitInitialization() {
603   std::string InstrProfileOutput = Options.InstrProfileOutput;
604 
605   Constant *RegisterF = M->getFunction(getInstrProfRegFuncsName());
606   if (!RegisterF && InstrProfileOutput.empty())
607     return;
608 
609   // Create the initialization function.
610   auto *VoidTy = Type::getVoidTy(M->getContext());
611   auto *F = Function::Create(FunctionType::get(VoidTy, false),
612                              GlobalValue::InternalLinkage,
613                              getInstrProfInitFuncName(), M);
614   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
615   F->addFnAttr(Attribute::NoInline);
616   if (Options.NoRedZone)
617     F->addFnAttr(Attribute::NoRedZone);
618 
619   // Add the basic block and the necessary calls.
620   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
621   if (RegisterF)
622     IRB.CreateCall(RegisterF, {});
623   if (!InstrProfileOutput.empty()) {
624     auto *Int8PtrTy = Type::getInt8PtrTy(M->getContext());
625     auto *SetNameTy = FunctionType::get(VoidTy, Int8PtrTy, false);
626     auto *SetNameF = Function::Create(SetNameTy, GlobalValue::ExternalLinkage,
627                                       getInstrProfFileOverriderFuncName(), M);
628 
629     // Create variable for profile name.
630     Constant *ProfileNameConst =
631         ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
632     GlobalVariable *ProfileName =
633         new GlobalVariable(*M, ProfileNameConst->getType(), true,
634                            GlobalValue::PrivateLinkage, ProfileNameConst);
635 
636     IRB.CreateCall(SetNameF, IRB.CreatePointerCast(ProfileName, Int8PtrTy));
637   }
638   IRB.CreateRetVoid();
639 
640   appendToGlobalCtors(*M, F, 0);
641 }
642