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