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