1 //===-- InstrProfiling.cpp - Frontend instrumentation based profiling -----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass lowers instrprof_* intrinsics emitted by a frontend for profiling.
10 // It also builds the data structures and initialization code needed for
11 // updating execution counts and emitting the profile at runtime.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Analysis/BlockFrequencyInfo.h"
22 #include "llvm/Analysis/BranchProbabilityInfo.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/TargetLibraryInfo.h"
25 #include "llvm/IR/Attributes.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/Constant.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalValue.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/IRBuilder.h"
35 #include "llvm/IR/Instruction.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/InitializePasses.h"
41 #include "llvm/Pass.h"
42 #include "llvm/ProfileData/InstrProf.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Error.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/ModuleUtils.h"
49 #include "llvm/Transforms/Utils/SSAUpdater.h"
50 #include <algorithm>
51 #include <cassert>
52 #include <cstddef>
53 #include <cstdint>
54 #include <string>
55 
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "instrprof"
59 
60 // The start and end values of precise value profile range for memory
61 // intrinsic sizes
62 cl::opt<std::string> MemOPSizeRange(
63     "memop-size-range",
64     cl::desc("Set the range of size in memory intrinsic calls to be profiled "
65              "precisely, in a format of <start_val>:<end_val>"),
66     cl::init(""));
67 
68 // The value that considered to be large value in  memory intrinsic.
69 cl::opt<unsigned> MemOPSizeLarge(
70     "memop-size-large",
71     cl::desc("Set large value thresthold in memory intrinsic size profiling. "
72              "Value of 0 disables the large value profiling."),
73     cl::init(8192));
74 
75 namespace {
76 
77 cl::opt<bool> DoHashBasedCounterSplit(
78     "hash-based-counter-split",
79     cl::desc("Rename counter variable of a comdat function based on cfg hash"),
80     cl::init(true));
81 
82 cl::opt<bool> RuntimeCounterRelocation(
83     "runtime-counter-relocation",
84     cl::desc("Enable relocating counters at runtime."),
85     cl::init(false));
86 
87 cl::opt<bool> ValueProfileStaticAlloc(
88     "vp-static-alloc",
89     cl::desc("Do static counter allocation for value profiler"),
90     cl::init(true));
91 
92 cl::opt<double> NumCountersPerValueSite(
93     "vp-counters-per-site",
94     cl::desc("The average number of profile counters allocated "
95              "per value profiling site."),
96     // This is set to a very small value because in real programs, only
97     // a very small percentage of value sites have non-zero targets, e.g, 1/30.
98     // For those sites with non-zero profile, the average number of targets
99     // is usually smaller than 2.
100     cl::init(1.0));
101 
102 cl::opt<bool> AtomicCounterUpdateAll(
103     "instrprof-atomic-counter-update-all", cl::ZeroOrMore,
104     cl::desc("Make all profile counter updates atomic (for testing only)"),
105     cl::init(false));
106 
107 cl::opt<bool> AtomicCounterUpdatePromoted(
108     "atomic-counter-update-promoted", cl::ZeroOrMore,
109     cl::desc("Do counter update using atomic fetch add "
110              " for promoted counters only"),
111     cl::init(false));
112 
113 // If the option is not specified, the default behavior about whether
114 // counter promotion is done depends on how instrumentaiton lowering
115 // pipeline is setup, i.e., the default value of true of this option
116 // does not mean the promotion will be done by default. Explicitly
117 // setting this option can override the default behavior.
118 cl::opt<bool> DoCounterPromotion("do-counter-promotion", cl::ZeroOrMore,
119                                  cl::desc("Do counter register promotion"),
120                                  cl::init(false));
121 cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
122     cl::ZeroOrMore, "max-counter-promotions-per-loop", cl::init(20),
123     cl::desc("Max number counter promotions per loop to avoid"
124              " increasing register pressure too much"));
125 
126 // A debug option
127 cl::opt<int>
128     MaxNumOfPromotions(cl::ZeroOrMore, "max-counter-promotions", cl::init(-1),
129                        cl::desc("Max number of allowed counter promotions"));
130 
131 cl::opt<unsigned> SpeculativeCounterPromotionMaxExiting(
132     cl::ZeroOrMore, "speculative-counter-promotion-max-exiting", cl::init(3),
133     cl::desc("The max number of exiting blocks of a loop to allow "
134              " speculative counter promotion"));
135 
136 cl::opt<bool> SpeculativeCounterPromotionToLoop(
137     cl::ZeroOrMore, "speculative-counter-promotion-to-loop", cl::init(false),
138     cl::desc("When the option is false, if the target block is in a loop, "
139              "the promotion will be disallowed unless the promoted counter "
140              " update can be further/iteratively promoted into an acyclic "
141              " region."));
142 
143 cl::opt<bool> IterativeCounterPromotion(
144     cl::ZeroOrMore, "iterative-counter-promotion", cl::init(true),
145     cl::desc("Allow counter promotion across the whole loop nest."));
146 
147 class InstrProfilingLegacyPass : public ModulePass {
148   InstrProfiling InstrProf;
149 
150 public:
151   static char ID;
152 
153   InstrProfilingLegacyPass() : ModulePass(ID) {}
154   InstrProfilingLegacyPass(const InstrProfOptions &Options, bool IsCS = false)
155       : ModulePass(ID), InstrProf(Options, IsCS) {
156     initializeInstrProfilingLegacyPassPass(*PassRegistry::getPassRegistry());
157   }
158 
159   StringRef getPassName() const override {
160     return "Frontend instrumentation-based coverage lowering";
161   }
162 
163   bool runOnModule(Module &M) override {
164     auto GetTLI = [this](Function &F) -> TargetLibraryInfo & {
165       return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
166     };
167     return InstrProf.run(M, GetTLI);
168   }
169 
170   void getAnalysisUsage(AnalysisUsage &AU) const override {
171     AU.setPreservesCFG();
172     AU.addRequired<TargetLibraryInfoWrapperPass>();
173   }
174 };
175 
176 ///
177 /// A helper class to promote one counter RMW operation in the loop
178 /// into register update.
179 ///
180 /// RWM update for the counter will be sinked out of the loop after
181 /// the transformation.
182 ///
183 class PGOCounterPromoterHelper : public LoadAndStorePromoter {
184 public:
185   PGOCounterPromoterHelper(
186       Instruction *L, Instruction *S, SSAUpdater &SSA, Value *Init,
187       BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
188       ArrayRef<Instruction *> InsertPts,
189       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
190       LoopInfo &LI)
191       : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
192         InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
193     assert(isa<LoadInst>(L));
194     assert(isa<StoreInst>(S));
195     SSA.AddAvailableValue(PH, Init);
196   }
197 
198   void doExtraRewritesBeforeFinalDeletion() override {
199     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
200       BasicBlock *ExitBlock = ExitBlocks[i];
201       Instruction *InsertPos = InsertPts[i];
202       // Get LiveIn value into the ExitBlock. If there are multiple
203       // predecessors, the value is defined by a PHI node in this
204       // block.
205       Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
206       Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
207       Type *Ty = LiveInValue->getType();
208       IRBuilder<> Builder(InsertPos);
209       if (AtomicCounterUpdatePromoted)
210         // automic update currently can only be promoted across the current
211         // loop, not the whole loop nest.
212         Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
213                                 AtomicOrdering::SequentiallyConsistent);
214       else {
215         LoadInst *OldVal = Builder.CreateLoad(Ty, Addr, "pgocount.promoted");
216         auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
217         auto *NewStore = Builder.CreateStore(NewVal, Addr);
218 
219         // Now update the parent loop's candidate list:
220         if (IterativeCounterPromotion) {
221           auto *TargetLoop = LI.getLoopFor(ExitBlock);
222           if (TargetLoop)
223             LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
224         }
225       }
226     }
227   }
228 
229 private:
230   Instruction *Store;
231   ArrayRef<BasicBlock *> ExitBlocks;
232   ArrayRef<Instruction *> InsertPts;
233   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
234   LoopInfo &LI;
235 };
236 
237 /// A helper class to do register promotion for all profile counter
238 /// updates in a loop.
239 ///
240 class PGOCounterPromoter {
241 public:
242   PGOCounterPromoter(
243       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
244       Loop &CurLoop, LoopInfo &LI, BlockFrequencyInfo *BFI)
245       : LoopToCandidates(LoopToCands), ExitBlocks(), InsertPts(), L(CurLoop),
246         LI(LI), BFI(BFI) {
247 
248     // Skip collection of ExitBlocks and InsertPts for loops that will not be
249     // able to have counters promoted.
250     SmallVector<BasicBlock *, 8> LoopExitBlocks;
251     SmallPtrSet<BasicBlock *, 8> BlockSet;
252 
253     L.getExitBlocks(LoopExitBlocks);
254     if (!isPromotionPossible(&L, LoopExitBlocks))
255       return;
256 
257     for (BasicBlock *ExitBlock : LoopExitBlocks) {
258       if (BlockSet.insert(ExitBlock).second) {
259         ExitBlocks.push_back(ExitBlock);
260         InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
261       }
262     }
263   }
264 
265   bool run(int64_t *NumPromoted) {
266     // Skip 'infinite' loops:
267     if (ExitBlocks.size() == 0)
268       return false;
269     unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
270     if (MaxProm == 0)
271       return false;
272 
273     unsigned Promoted = 0;
274     for (auto &Cand : LoopToCandidates[&L]) {
275 
276       SmallVector<PHINode *, 4> NewPHIs;
277       SSAUpdater SSA(&NewPHIs);
278       Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
279 
280       // If BFI is set, we will use it to guide the promotions.
281       if (BFI) {
282         auto *BB = Cand.first->getParent();
283         auto InstrCount = BFI->getBlockProfileCount(BB);
284         if (!InstrCount)
285           continue;
286         auto PreheaderCount = BFI->getBlockProfileCount(L.getLoopPreheader());
287         // If the average loop trip count is not greater than 1.5, we skip
288         // promotion.
289         if (PreheaderCount &&
290             (PreheaderCount.getValue() * 3) >= (InstrCount.getValue() * 2))
291           continue;
292       }
293 
294       PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
295                                         L.getLoopPreheader(), ExitBlocks,
296                                         InsertPts, LoopToCandidates, LI);
297       Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
298       Promoted++;
299       if (Promoted >= MaxProm)
300         break;
301 
302       (*NumPromoted)++;
303       if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
304         break;
305     }
306 
307     LLVM_DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
308                       << L.getLoopDepth() << ")\n");
309     return Promoted != 0;
310   }
311 
312 private:
313   bool allowSpeculativeCounterPromotion(Loop *LP) {
314     SmallVector<BasicBlock *, 8> ExitingBlocks;
315     L.getExitingBlocks(ExitingBlocks);
316     // Not considierered speculative.
317     if (ExitingBlocks.size() == 1)
318       return true;
319     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
320       return false;
321     return true;
322   }
323 
324   // Check whether the loop satisfies the basic conditions needed to perform
325   // Counter Promotions.
326   bool isPromotionPossible(Loop *LP,
327                            const SmallVectorImpl<BasicBlock *> &LoopExitBlocks) {
328     // We can't insert into a catchswitch.
329     if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
330           return isa<CatchSwitchInst>(Exit->getTerminator());
331         }))
332       return false;
333 
334     if (!LP->hasDedicatedExits())
335       return false;
336 
337     BasicBlock *PH = LP->getLoopPreheader();
338     if (!PH)
339       return false;
340 
341     return true;
342   }
343 
344   // Returns the max number of Counter Promotions for LP.
345   unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
346     SmallVector<BasicBlock *, 8> LoopExitBlocks;
347     LP->getExitBlocks(LoopExitBlocks);
348     if (!isPromotionPossible(LP, LoopExitBlocks))
349       return 0;
350 
351     SmallVector<BasicBlock *, 8> ExitingBlocks;
352     LP->getExitingBlocks(ExitingBlocks);
353 
354     // If BFI is set, we do more aggressive promotions based on BFI.
355     if (BFI)
356       return (unsigned)-1;
357 
358     // Not considierered speculative.
359     if (ExitingBlocks.size() == 1)
360       return MaxNumOfPromotionsPerLoop;
361 
362     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
363       return 0;
364 
365     // Whether the target block is in a loop does not matter:
366     if (SpeculativeCounterPromotionToLoop)
367       return MaxNumOfPromotionsPerLoop;
368 
369     // Now check the target block:
370     unsigned MaxProm = MaxNumOfPromotionsPerLoop;
371     for (auto *TargetBlock : LoopExitBlocks) {
372       auto *TargetLoop = LI.getLoopFor(TargetBlock);
373       if (!TargetLoop)
374         continue;
375       unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
376       unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
377       MaxProm =
378           std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
379                                 PendingCandsInTarget);
380     }
381     return MaxProm;
382   }
383 
384   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
385   SmallVector<BasicBlock *, 8> ExitBlocks;
386   SmallVector<Instruction *, 8> InsertPts;
387   Loop &L;
388   LoopInfo &LI;
389   BlockFrequencyInfo *BFI;
390 };
391 
392 } // end anonymous namespace
393 
394 PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
395   FunctionAnalysisManager &FAM =
396       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
397   auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
398     return FAM.getResult<TargetLibraryAnalysis>(F);
399   };
400   if (!run(M, GetTLI))
401     return PreservedAnalyses::all();
402 
403   return PreservedAnalyses::none();
404 }
405 
406 char InstrProfilingLegacyPass::ID = 0;
407 INITIALIZE_PASS_BEGIN(
408     InstrProfilingLegacyPass, "instrprof",
409     "Frontend instrumentation-based coverage lowering.", false, false)
410 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
411 INITIALIZE_PASS_END(
412     InstrProfilingLegacyPass, "instrprof",
413     "Frontend instrumentation-based coverage lowering.", false, false)
414 
415 ModulePass *
416 llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options,
417                                      bool IsCS) {
418   return new InstrProfilingLegacyPass(Options, IsCS);
419 }
420 
421 static InstrProfIncrementInst *castToIncrementInst(Instruction *Instr) {
422   InstrProfIncrementInst *Inc = dyn_cast<InstrProfIncrementInstStep>(Instr);
423   if (Inc)
424     return Inc;
425   return dyn_cast<InstrProfIncrementInst>(Instr);
426 }
427 
428 bool InstrProfiling::lowerIntrinsics(Function *F) {
429   bool MadeChange = false;
430   PromotionCandidates.clear();
431   for (BasicBlock &BB : *F) {
432     for (auto I = BB.begin(), E = BB.end(); I != E;) {
433       auto Instr = I++;
434       InstrProfIncrementInst *Inc = castToIncrementInst(&*Instr);
435       if (Inc) {
436         lowerIncrement(Inc);
437         MadeChange = true;
438       } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
439         lowerValueProfileInst(Ind);
440         MadeChange = true;
441       }
442     }
443   }
444 
445   if (!MadeChange)
446     return false;
447 
448   promoteCounterLoadStores(F);
449   return true;
450 }
451 
452 bool InstrProfiling::isRuntimeCounterRelocationEnabled() const {
453   if (RuntimeCounterRelocation.getNumOccurrences() > 0)
454     return RuntimeCounterRelocation;
455 
456   return TT.isOSFuchsia();
457 }
458 
459 bool InstrProfiling::isCounterPromotionEnabled() const {
460   if (DoCounterPromotion.getNumOccurrences() > 0)
461     return DoCounterPromotion;
462 
463   return Options.DoCounterPromotion;
464 }
465 
466 void InstrProfiling::promoteCounterLoadStores(Function *F) {
467   if (!isCounterPromotionEnabled())
468     return;
469 
470   DominatorTree DT(*F);
471   LoopInfo LI(DT);
472   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
473 
474   std::unique_ptr<BlockFrequencyInfo> BFI;
475   if (Options.UseBFIInPromotion) {
476     std::unique_ptr<BranchProbabilityInfo> BPI;
477     BPI.reset(new BranchProbabilityInfo(*F, LI, &GetTLI(*F)));
478     BFI.reset(new BlockFrequencyInfo(*F, *BPI, LI));
479   }
480 
481   for (const auto &LoadStore : PromotionCandidates) {
482     auto *CounterLoad = LoadStore.first;
483     auto *CounterStore = LoadStore.second;
484     BasicBlock *BB = CounterLoad->getParent();
485     Loop *ParentLoop = LI.getLoopFor(BB);
486     if (!ParentLoop)
487       continue;
488     LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
489   }
490 
491   SmallVector<Loop *, 4> Loops = LI.getLoopsInPreorder();
492 
493   // Do a post-order traversal of the loops so that counter updates can be
494   // iteratively hoisted outside the loop nest.
495   for (auto *Loop : llvm::reverse(Loops)) {
496     PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI, BFI.get());
497     Promoter.run(&TotalCountersPromoted);
498   }
499 }
500 
501 /// Check if the module contains uses of any profiling intrinsics.
502 static bool containsProfilingIntrinsics(Module &M) {
503   if (auto *F = M.getFunction(
504           Intrinsic::getName(llvm::Intrinsic::instrprof_increment)))
505     if (!F->use_empty())
506       return true;
507   if (auto *F = M.getFunction(
508           Intrinsic::getName(llvm::Intrinsic::instrprof_increment_step)))
509     if (!F->use_empty())
510       return true;
511   if (auto *F = M.getFunction(
512           Intrinsic::getName(llvm::Intrinsic::instrprof_value_profile)))
513     if (!F->use_empty())
514       return true;
515   return false;
516 }
517 
518 bool InstrProfiling::run(
519     Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI) {
520   this->M = &M;
521   this->GetTLI = std::move(GetTLI);
522   NamesVar = nullptr;
523   NamesSize = 0;
524   ProfileDataMap.clear();
525   UsedVars.clear();
526   getMemOPSizeRangeFromOption(MemOPSizeRange, MemOPSizeRangeStart,
527                               MemOPSizeRangeLast);
528   TT = Triple(M.getTargetTriple());
529 
530   // Emit the runtime hook even if no counters are present.
531   bool MadeChange = emitRuntimeHook();
532 
533   // Improve compile time by avoiding linear scans when there is no work.
534   GlobalVariable *CoverageNamesVar =
535       M.getNamedGlobal(getCoverageUnusedNamesVarName());
536   if (!containsProfilingIntrinsics(M) && !CoverageNamesVar)
537     return MadeChange;
538 
539   // We did not know how many value sites there would be inside
540   // the instrumented function. This is counting the number of instrumented
541   // target value sites to enter it as field in the profile data variable.
542   for (Function &F : M) {
543     InstrProfIncrementInst *FirstProfIncInst = nullptr;
544     for (BasicBlock &BB : F)
545       for (auto I = BB.begin(), E = BB.end(); I != E; I++)
546         if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
547           computeNumValueSiteCounts(Ind);
548         else if (FirstProfIncInst == nullptr)
549           FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
550 
551     // Value profiling intrinsic lowering requires per-function profile data
552     // variable to be created first.
553     if (FirstProfIncInst != nullptr)
554       static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
555   }
556 
557   for (Function &F : M)
558     MadeChange |= lowerIntrinsics(&F);
559 
560   if (CoverageNamesVar) {
561     lowerCoverageData(CoverageNamesVar);
562     MadeChange = true;
563   }
564 
565   if (!MadeChange)
566     return false;
567 
568   emitVNodes();
569   emitNameData();
570   emitRegistration();
571   emitUses();
572   emitInitialization();
573   return true;
574 }
575 
576 static FunctionCallee
577 getOrInsertValueProfilingCall(Module &M, const TargetLibraryInfo &TLI,
578                               bool IsRange = false) {
579   LLVMContext &Ctx = M.getContext();
580   auto *ReturnTy = Type::getVoidTy(M.getContext());
581 
582   AttributeList AL;
583   if (auto AK = TLI.getExtAttrForI32Param(false))
584     AL = AL.addParamAttribute(M.getContext(), 2, AK);
585 
586   if (!IsRange) {
587     Type *ParamTypes[] = {
588 #define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
589 #include "llvm/ProfileData/InstrProfData.inc"
590     };
591     auto *ValueProfilingCallTy =
592         FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
593     return M.getOrInsertFunction(getInstrProfValueProfFuncName(),
594                                  ValueProfilingCallTy, AL);
595   } else {
596     Type *RangeParamTypes[] = {
597 #define VALUE_RANGE_PROF 1
598 #define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
599 #include "llvm/ProfileData/InstrProfData.inc"
600 #undef VALUE_RANGE_PROF
601     };
602     auto *ValueRangeProfilingCallTy =
603         FunctionType::get(ReturnTy, makeArrayRef(RangeParamTypes), false);
604     return M.getOrInsertFunction(getInstrProfValueRangeProfFuncName(),
605                                  ValueRangeProfilingCallTy, AL);
606   }
607 }
608 
609 void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
610   GlobalVariable *Name = Ind->getName();
611   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
612   uint64_t Index = Ind->getIndex()->getZExtValue();
613   auto It = ProfileDataMap.find(Name);
614   if (It == ProfileDataMap.end()) {
615     PerFunctionProfileData PD;
616     PD.NumValueSites[ValueKind] = Index + 1;
617     ProfileDataMap[Name] = PD;
618   } else if (It->second.NumValueSites[ValueKind] <= Index)
619     It->second.NumValueSites[ValueKind] = Index + 1;
620 }
621 
622 void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
623   GlobalVariable *Name = Ind->getName();
624   auto It = ProfileDataMap.find(Name);
625   assert(It != ProfileDataMap.end() && It->second.DataVar &&
626          "value profiling detected in function with no counter incerement");
627 
628   GlobalVariable *DataVar = It->second.DataVar;
629   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
630   uint64_t Index = Ind->getIndex()->getZExtValue();
631   for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
632     Index += It->second.NumValueSites[Kind];
633 
634   IRBuilder<> Builder(Ind);
635   bool IsRange = (Ind->getValueKind()->getZExtValue() ==
636                   llvm::InstrProfValueKind::IPVK_MemOPSize);
637   CallInst *Call = nullptr;
638   auto *TLI = &GetTLI(*Ind->getFunction());
639 
640   // To support value profiling calls within Windows exception handlers, funclet
641   // information contained within operand bundles needs to be copied over to
642   // the library call. This is required for the IR to be processed by the
643   // WinEHPrepare pass.
644   SmallVector<OperandBundleDef, 1> OpBundles;
645   Ind->getOperandBundlesAsDefs(OpBundles);
646   if (!IsRange) {
647     Value *Args[3] = {Ind->getTargetValue(),
648                       Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
649                       Builder.getInt32(Index)};
650     Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args,
651                               OpBundles);
652   } else {
653     Value *Args[6] = {
654         Ind->getTargetValue(),
655         Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
656         Builder.getInt32(Index),
657         Builder.getInt64(MemOPSizeRangeStart),
658         Builder.getInt64(MemOPSizeRangeLast),
659         Builder.getInt64(MemOPSizeLarge == 0 ? INT64_MIN : MemOPSizeLarge)};
660     Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI, true),
661                               Args, OpBundles);
662   }
663   if (auto AK = TLI->getExtAttrForI32Param(false))
664     Call->addParamAttr(2, AK);
665   Ind->replaceAllUsesWith(Call);
666   Ind->eraseFromParent();
667 }
668 
669 void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
670   GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
671 
672   IRBuilder<> Builder(Inc);
673   uint64_t Index = Inc->getIndex()->getZExtValue();
674   Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters->getValueType(),
675                                                    Counters, 0, Index);
676 
677   if (isRuntimeCounterRelocationEnabled()) {
678     Type *Int64Ty = Type::getInt64Ty(M->getContext());
679     Type *Int64PtrTy = Type::getInt64PtrTy(M->getContext());
680     Function *Fn = Inc->getParent()->getParent();
681     Instruction &I = Fn->getEntryBlock().front();
682     LoadInst *LI = dyn_cast<LoadInst>(&I);
683     if (!LI) {
684       IRBuilder<> Builder(&I);
685       Type *Int64Ty = Type::getInt64Ty(M->getContext());
686       GlobalVariable *Bias = M->getGlobalVariable(getInstrProfCounterBiasVarName());
687       if (!Bias) {
688         Bias = new GlobalVariable(*M, Int64Ty, false, GlobalValue::LinkOnceODRLinkage,
689                                   Constant::getNullValue(Int64Ty),
690                                   getInstrProfCounterBiasVarName());
691         Bias->setVisibility(GlobalVariable::HiddenVisibility);
692       }
693       LI = Builder.CreateLoad(Int64Ty, Bias);
694     }
695     auto *Add = Builder.CreateAdd(Builder.CreatePtrToInt(Addr, Int64Ty), LI);
696     Addr = Builder.CreateIntToPtr(Add, Int64PtrTy);
697   }
698 
699   if (Options.Atomic || AtomicCounterUpdateAll) {
700     Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, Inc->getStep(),
701                             AtomicOrdering::Monotonic);
702   } else {
703     Value *IncStep = Inc->getStep();
704     Value *Load = Builder.CreateLoad(IncStep->getType(), Addr, "pgocount");
705     auto *Count = Builder.CreateAdd(Load, Inc->getStep());
706     auto *Store = Builder.CreateStore(Count, Addr);
707     if (isCounterPromotionEnabled())
708       PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
709   }
710   Inc->eraseFromParent();
711 }
712 
713 void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
714   ConstantArray *Names =
715       cast<ConstantArray>(CoverageNamesVar->getInitializer());
716   for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
717     Constant *NC = Names->getOperand(I);
718     Value *V = NC->stripPointerCasts();
719     assert(isa<GlobalVariable>(V) && "Missing reference to function name");
720     GlobalVariable *Name = cast<GlobalVariable>(V);
721 
722     Name->setLinkage(GlobalValue::PrivateLinkage);
723     ReferencedNames.push_back(Name);
724     NC->dropAllReferences();
725   }
726   CoverageNamesVar->eraseFromParent();
727 }
728 
729 /// Get the name of a profiling variable for a particular function.
730 static std::string getVarName(InstrProfIncrementInst *Inc, StringRef Prefix) {
731   StringRef NamePrefix = getInstrProfNameVarPrefix();
732   StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
733   Function *F = Inc->getParent()->getParent();
734   Module *M = F->getParent();
735   if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
736       !canRenameComdatFunc(*F))
737     return (Prefix + Name).str();
738   uint64_t FuncHash = Inc->getHash()->getZExtValue();
739   SmallVector<char, 24> HashPostfix;
740   if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
741     return (Prefix + Name).str();
742   return (Prefix + Name + "." + Twine(FuncHash)).str();
743 }
744 
745 static inline bool shouldRecordFunctionAddr(Function *F) {
746   // Check the linkage
747   bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
748   if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
749       !HasAvailableExternallyLinkage)
750     return true;
751 
752   // A function marked 'alwaysinline' with available_externally linkage can't
753   // have its address taken. Doing so would create an undefined external ref to
754   // the function, which would fail to link.
755   if (HasAvailableExternallyLinkage &&
756       F->hasFnAttribute(Attribute::AlwaysInline))
757     return false;
758 
759   // Prohibit function address recording if the function is both internal and
760   // COMDAT. This avoids the profile data variable referencing internal symbols
761   // in COMDAT.
762   if (F->hasLocalLinkage() && F->hasComdat())
763     return false;
764 
765   // Check uses of this function for other than direct calls or invokes to it.
766   // Inline virtual functions have linkeOnceODR linkage. When a key method
767   // exists, the vtable will only be emitted in the TU where the key method
768   // is defined. In a TU where vtable is not available, the function won't
769   // be 'addresstaken'. If its address is not recorded here, the profile data
770   // with missing address may be picked by the linker leading  to missing
771   // indirect call target info.
772   return F->hasAddressTaken() || F->hasLinkOnceLinkage();
773 }
774 
775 static bool needsRuntimeRegistrationOfSectionRange(const Triple &TT) {
776   // Don't do this for Darwin.  compiler-rt uses linker magic.
777   if (TT.isOSDarwin())
778     return false;
779   // Use linker script magic to get data/cnts/name start/end.
780   if (TT.isOSLinux() || TT.isOSFreeBSD() || TT.isOSNetBSD() ||
781       TT.isOSSolaris() || TT.isOSFuchsia() || TT.isPS4CPU() ||
782       TT.isOSWindows())
783     return false;
784 
785   return true;
786 }
787 
788 GlobalVariable *
789 InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
790   GlobalVariable *NamePtr = Inc->getName();
791   auto It = ProfileDataMap.find(NamePtr);
792   PerFunctionProfileData PD;
793   if (It != ProfileDataMap.end()) {
794     if (It->second.RegionCounters)
795       return It->second.RegionCounters;
796     PD = It->second;
797   }
798 
799   // Match the linkage and visibility of the name global. COFF supports using
800   // comdats with internal symbols, so do that if we can.
801   Function *Fn = Inc->getParent()->getParent();
802   GlobalValue::LinkageTypes Linkage = NamePtr->getLinkage();
803   GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
804   if (TT.isOSBinFormatCOFF()) {
805     Linkage = GlobalValue::InternalLinkage;
806     Visibility = GlobalValue::DefaultVisibility;
807   }
808 
809   // Move the name variable to the right section. Place them in a COMDAT group
810   // if the associated function is a COMDAT. This will make sure that only one
811   // copy of counters of the COMDAT function will be emitted after linking. Keep
812   // in mind that this pass may run before the inliner, so we need to create a
813   // new comdat group for the counters and profiling data. If we use the comdat
814   // of the parent function, that will result in relocations against discarded
815   // sections.
816   bool NeedComdat = needsComdatForCounter(*Fn, *M);
817   if (NeedComdat) {
818     if (TT.isOSBinFormatCOFF()) {
819       // For COFF, put the counters, data, and values each into their own
820       // comdats. We can't use a group because the Visual C++ linker will
821       // report duplicate symbol errors if there are multiple external symbols
822       // with the same name marked IMAGE_COMDAT_SELECT_ASSOCIATIVE.
823       Linkage = GlobalValue::LinkOnceODRLinkage;
824       Visibility = GlobalValue::HiddenVisibility;
825     }
826   }
827   auto MaybeSetComdat = [=](GlobalVariable *GV) {
828     if (NeedComdat)
829       GV->setComdat(M->getOrInsertComdat(GV->getName()));
830   };
831 
832   uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
833   LLVMContext &Ctx = M->getContext();
834   ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
835 
836   // Create the counters variable.
837   auto *CounterPtr =
838       new GlobalVariable(*M, CounterTy, false, Linkage,
839                          Constant::getNullValue(CounterTy),
840                          getVarName(Inc, getInstrProfCountersVarPrefix()));
841   CounterPtr->setVisibility(Visibility);
842   CounterPtr->setSection(
843       getInstrProfSectionName(IPSK_cnts, TT.getObjectFormat()));
844   CounterPtr->setAlignment(Align(8));
845   MaybeSetComdat(CounterPtr);
846   CounterPtr->setLinkage(Linkage);
847 
848   auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
849   // Allocate statically the array of pointers to value profile nodes for
850   // the current function.
851   Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
852   if (ValueProfileStaticAlloc && !needsRuntimeRegistrationOfSectionRange(TT)) {
853     uint64_t NS = 0;
854     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
855       NS += PD.NumValueSites[Kind];
856     if (NS) {
857       ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
858 
859       auto *ValuesVar =
860           new GlobalVariable(*M, ValuesTy, false, Linkage,
861                              Constant::getNullValue(ValuesTy),
862                              getVarName(Inc, getInstrProfValuesVarPrefix()));
863       ValuesVar->setVisibility(Visibility);
864       ValuesVar->setSection(
865           getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
866       ValuesVar->setAlignment(Align(8));
867       MaybeSetComdat(ValuesVar);
868       ValuesPtrExpr =
869           ConstantExpr::getBitCast(ValuesVar, Type::getInt8PtrTy(Ctx));
870     }
871   }
872 
873   // Create data variable.
874   auto *Int16Ty = Type::getInt16Ty(Ctx);
875   auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
876   Type *DataTypes[] = {
877 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
878 #include "llvm/ProfileData/InstrProfData.inc"
879   };
880   auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
881 
882   Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
883                                ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
884                                : ConstantPointerNull::get(Int8PtrTy);
885 
886   Constant *Int16ArrayVals[IPVK_Last + 1];
887   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
888     Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
889 
890   Constant *DataVals[] = {
891 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
892 #include "llvm/ProfileData/InstrProfData.inc"
893   };
894   auto *Data = new GlobalVariable(*M, DataTy, false, Linkage,
895                                   ConstantStruct::get(DataTy, DataVals),
896                                   getVarName(Inc, getInstrProfDataVarPrefix()));
897   Data->setVisibility(Visibility);
898   Data->setSection(getInstrProfSectionName(IPSK_data, TT.getObjectFormat()));
899   Data->setAlignment(Align(INSTR_PROF_DATA_ALIGNMENT));
900   MaybeSetComdat(Data);
901   Data->setLinkage(Linkage);
902 
903   PD.RegionCounters = CounterPtr;
904   PD.DataVar = Data;
905   ProfileDataMap[NamePtr] = PD;
906 
907   // Mark the data variable as used so that it isn't stripped out.
908   UsedVars.push_back(Data);
909   // Now that the linkage set by the FE has been passed to the data and counter
910   // variables, reset Name variable's linkage and visibility to private so that
911   // it can be removed later by the compiler.
912   NamePtr->setLinkage(GlobalValue::PrivateLinkage);
913   // Collect the referenced names to be used by emitNameData.
914   ReferencedNames.push_back(NamePtr);
915 
916   return CounterPtr;
917 }
918 
919 void InstrProfiling::emitVNodes() {
920   if (!ValueProfileStaticAlloc)
921     return;
922 
923   // For now only support this on platforms that do
924   // not require runtime registration to discover
925   // named section start/end.
926   if (needsRuntimeRegistrationOfSectionRange(TT))
927     return;
928 
929   size_t TotalNS = 0;
930   for (auto &PD : ProfileDataMap) {
931     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
932       TotalNS += PD.second.NumValueSites[Kind];
933   }
934 
935   if (!TotalNS)
936     return;
937 
938   uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
939 // Heuristic for small programs with very few total value sites.
940 // The default value of vp-counters-per-site is chosen based on
941 // the observation that large apps usually have a low percentage
942 // of value sites that actually have any profile data, and thus
943 // the average number of counters per site is low. For small
944 // apps with very few sites, this may not be true. Bump up the
945 // number of counters in this case.
946 #define INSTR_PROF_MIN_VAL_COUNTS 10
947   if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
948     NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
949 
950   auto &Ctx = M->getContext();
951   Type *VNodeTypes[] = {
952 #define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
953 #include "llvm/ProfileData/InstrProfData.inc"
954   };
955   auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
956 
957   ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
958   auto *VNodesVar = new GlobalVariable(
959       *M, VNodesTy, false, GlobalValue::PrivateLinkage,
960       Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
961   VNodesVar->setSection(
962       getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
963   UsedVars.push_back(VNodesVar);
964 }
965 
966 void InstrProfiling::emitNameData() {
967   std::string UncompressedData;
968 
969   if (ReferencedNames.empty())
970     return;
971 
972   std::string CompressedNameStr;
973   if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
974                                           DoInstrProfNameCompression)) {
975     report_fatal_error(toString(std::move(E)), false);
976   }
977 
978   auto &Ctx = M->getContext();
979   auto *NamesVal = ConstantDataArray::getString(
980       Ctx, StringRef(CompressedNameStr), false);
981   NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
982                                 GlobalValue::PrivateLinkage, NamesVal,
983                                 getInstrProfNamesVarName());
984   NamesSize = CompressedNameStr.size();
985   NamesVar->setSection(
986       getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
987   // On COFF, it's important to reduce the alignment down to 1 to prevent the
988   // linker from inserting padding before the start of the names section or
989   // between names entries.
990   NamesVar->setAlignment(Align(1));
991   UsedVars.push_back(NamesVar);
992 
993   for (auto *NamePtr : ReferencedNames)
994     NamePtr->eraseFromParent();
995 }
996 
997 void InstrProfiling::emitRegistration() {
998   if (!needsRuntimeRegistrationOfSectionRange(TT))
999     return;
1000 
1001   // Construct the function.
1002   auto *VoidTy = Type::getVoidTy(M->getContext());
1003   auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
1004   auto *Int64Ty = Type::getInt64Ty(M->getContext());
1005   auto *RegisterFTy = FunctionType::get(VoidTy, false);
1006   auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
1007                                      getInstrProfRegFuncsName(), M);
1008   RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1009   if (Options.NoRedZone)
1010     RegisterF->addFnAttr(Attribute::NoRedZone);
1011 
1012   auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
1013   auto *RuntimeRegisterF =
1014       Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
1015                        getInstrProfRegFuncName(), M);
1016 
1017   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
1018   for (Value *Data : UsedVars)
1019     if (Data != NamesVar && !isa<Function>(Data))
1020       IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
1021 
1022   if (NamesVar) {
1023     Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
1024     auto *NamesRegisterTy =
1025         FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
1026     auto *NamesRegisterF =
1027         Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
1028                          getInstrProfNamesRegFuncName(), M);
1029     IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
1030                                     IRB.getInt64(NamesSize)});
1031   }
1032 
1033   IRB.CreateRetVoid();
1034 }
1035 
1036 bool InstrProfiling::emitRuntimeHook() {
1037   // We expect the linker to be invoked with -u<hook_var> flag for linux,
1038   // for which case there is no need to emit the user function.
1039   if (TT.isOSLinux())
1040     return false;
1041 
1042   // If the module's provided its own runtime, we don't need to do anything.
1043   if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
1044     return false;
1045 
1046   // Declare an external variable that will pull in the runtime initialization.
1047   auto *Int32Ty = Type::getInt32Ty(M->getContext());
1048   auto *Var =
1049       new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
1050                          nullptr, getInstrProfRuntimeHookVarName());
1051 
1052   // Make a function that uses it.
1053   auto *User = Function::Create(FunctionType::get(Int32Ty, false),
1054                                 GlobalValue::LinkOnceODRLinkage,
1055                                 getInstrProfRuntimeHookVarUseFuncName(), M);
1056   User->addFnAttr(Attribute::NoInline);
1057   if (Options.NoRedZone)
1058     User->addFnAttr(Attribute::NoRedZone);
1059   User->setVisibility(GlobalValue::HiddenVisibility);
1060   if (TT.supportsCOMDAT())
1061     User->setComdat(M->getOrInsertComdat(User->getName()));
1062 
1063   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
1064   auto *Load = IRB.CreateLoad(Int32Ty, Var);
1065   IRB.CreateRet(Load);
1066 
1067   // Mark the user variable as used so that it isn't stripped out.
1068   UsedVars.push_back(User);
1069   return true;
1070 }
1071 
1072 void InstrProfiling::emitUses() {
1073   if (!UsedVars.empty())
1074     appendToUsed(*M, UsedVars);
1075 }
1076 
1077 void InstrProfiling::emitInitialization() {
1078   // Create ProfileFileName variable. Don't don't this for the
1079   // context-sensitive instrumentation lowering: This lowering is after
1080   // LTO/ThinLTO linking. Pass PGOInstrumentationGenCreateVar should
1081   // have already create the variable before LTO/ThinLTO linking.
1082   if (!IsCS)
1083     createProfileFileNameVar(*M, Options.InstrProfileOutput);
1084   Function *RegisterF = M->getFunction(getInstrProfRegFuncsName());
1085   if (!RegisterF)
1086     return;
1087 
1088   // Create the initialization function.
1089   auto *VoidTy = Type::getVoidTy(M->getContext());
1090   auto *F = Function::Create(FunctionType::get(VoidTy, false),
1091                              GlobalValue::InternalLinkage,
1092                              getInstrProfInitFuncName(), M);
1093   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1094   F->addFnAttr(Attribute::NoInline);
1095   if (Options.NoRedZone)
1096     F->addFnAttr(Attribute::NoRedZone);
1097 
1098   // Add the basic block and the necessary calls.
1099   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
1100   IRB.CreateCall(RegisterF, {});
1101   IRB.CreateRetVoid();
1102 
1103   appendToGlobalCtors(*M, F, 0);
1104 }
1105