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> DoNameCompression("enable-name-compression",
78                                 cl::desc("Enable name string compression"),
79                                 cl::init(true));
80 
81 cl::opt<bool> DoHashBasedCounterSplit(
82     "hash-based-counter-split",
83     cl::desc("Rename counter variable of a comdat function based on cfg hash"),
84     cl::init(true));
85 
86 cl::opt<bool> RuntimeCounterRelocation(
87     "runtime-counter-relocation",
88     cl::desc("Enable relocating counters at runtime."),
89     cl::init(false));
90 
91 cl::opt<bool> ValueProfileStaticAlloc(
92     "vp-static-alloc",
93     cl::desc("Do static counter allocation for value profiler"),
94     cl::init(true));
95 
96 cl::opt<double> NumCountersPerValueSite(
97     "vp-counters-per-site",
98     cl::desc("The average number of profile counters allocated "
99              "per value profiling site."),
100     // This is set to a very small value because in real programs, only
101     // a very small percentage of value sites have non-zero targets, e.g, 1/30.
102     // For those sites with non-zero profile, the average number of targets
103     // is usually smaller than 2.
104     cl::init(1.0));
105 
106 cl::opt<bool> AtomicCounterUpdateAll(
107     "instrprof-atomic-counter-update-all", cl::ZeroOrMore,
108     cl::desc("Make all profile counter updates atomic (for testing only)"),
109     cl::init(false));
110 
111 cl::opt<bool> AtomicCounterUpdatePromoted(
112     "atomic-counter-update-promoted", cl::ZeroOrMore,
113     cl::desc("Do counter update using atomic fetch add "
114              " for promoted counters only"),
115     cl::init(false));
116 
117 // If the option is not specified, the default behavior about whether
118 // counter promotion is done depends on how instrumentaiton lowering
119 // pipeline is setup, i.e., the default value of true of this option
120 // does not mean the promotion will be done by default. Explicitly
121 // setting this option can override the default behavior.
122 cl::opt<bool> DoCounterPromotion("do-counter-promotion", cl::ZeroOrMore,
123                                  cl::desc("Do counter register promotion"),
124                                  cl::init(false));
125 cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
126     cl::ZeroOrMore, "max-counter-promotions-per-loop", cl::init(20),
127     cl::desc("Max number counter promotions per loop to avoid"
128              " increasing register pressure too much"));
129 
130 // A debug option
131 cl::opt<int>
132     MaxNumOfPromotions(cl::ZeroOrMore, "max-counter-promotions", cl::init(-1),
133                        cl::desc("Max number of allowed counter promotions"));
134 
135 cl::opt<unsigned> SpeculativeCounterPromotionMaxExiting(
136     cl::ZeroOrMore, "speculative-counter-promotion-max-exiting", cl::init(3),
137     cl::desc("The max number of exiting blocks of a loop to allow "
138              " speculative counter promotion"));
139 
140 cl::opt<bool> SpeculativeCounterPromotionToLoop(
141     cl::ZeroOrMore, "speculative-counter-promotion-to-loop", cl::init(false),
142     cl::desc("When the option is false, if the target block is in a loop, "
143              "the promotion will be disallowed unless the promoted counter "
144              " update can be further/iteratively promoted into an acyclic "
145              " region."));
146 
147 cl::opt<bool> IterativeCounterPromotion(
148     cl::ZeroOrMore, "iterative-counter-promotion", cl::init(true),
149     cl::desc("Allow counter promotion across the whole loop nest."));
150 
151 class InstrProfilingLegacyPass : public ModulePass {
152   InstrProfiling InstrProf;
153 
154 public:
155   static char ID;
156 
157   InstrProfilingLegacyPass() : ModulePass(ID) {}
158   InstrProfilingLegacyPass(const InstrProfOptions &Options, bool IsCS = false)
159       : ModulePass(ID), InstrProf(Options, IsCS) {}
160 
161   StringRef getPassName() const override {
162     return "Frontend instrumentation-based coverage lowering";
163   }
164 
165   bool runOnModule(Module &M) override {
166     auto GetTLI = [this](Function &F) -> TargetLibraryInfo & {
167       return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
168     };
169     return InstrProf.run(M, GetTLI);
170   }
171 
172   void getAnalysisUsage(AnalysisUsage &AU) const override {
173     AU.setPreservesCFG();
174     AU.addRequired<TargetLibraryInfoWrapperPass>();
175   }
176 };
177 
178 ///
179 /// A helper class to promote one counter RMW operation in the loop
180 /// into register update.
181 ///
182 /// RWM update for the counter will be sinked out of the loop after
183 /// the transformation.
184 ///
185 class PGOCounterPromoterHelper : public LoadAndStorePromoter {
186 public:
187   PGOCounterPromoterHelper(
188       Instruction *L, Instruction *S, SSAUpdater &SSA, Value *Init,
189       BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
190       ArrayRef<Instruction *> InsertPts,
191       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
192       LoopInfo &LI)
193       : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
194         InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
195     assert(isa<LoadInst>(L));
196     assert(isa<StoreInst>(S));
197     SSA.AddAvailableValue(PH, Init);
198   }
199 
200   void doExtraRewritesBeforeFinalDeletion() override {
201     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
202       BasicBlock *ExitBlock = ExitBlocks[i];
203       Instruction *InsertPos = InsertPts[i];
204       // Get LiveIn value into the ExitBlock. If there are multiple
205       // predecessors, the value is defined by a PHI node in this
206       // block.
207       Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
208       Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
209       Type *Ty = LiveInValue->getType();
210       IRBuilder<> Builder(InsertPos);
211       if (AtomicCounterUpdatePromoted)
212         // automic update currently can only be promoted across the current
213         // loop, not the whole loop nest.
214         Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
215                                 AtomicOrdering::SequentiallyConsistent);
216       else {
217         LoadInst *OldVal = Builder.CreateLoad(Ty, Addr, "pgocount.promoted");
218         auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
219         auto *NewStore = Builder.CreateStore(NewVal, Addr);
220 
221         // Now update the parent loop's candidate list:
222         if (IterativeCounterPromotion) {
223           auto *TargetLoop = LI.getLoopFor(ExitBlock);
224           if (TargetLoop)
225             LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
226         }
227       }
228     }
229   }
230 
231 private:
232   Instruction *Store;
233   ArrayRef<BasicBlock *> ExitBlocks;
234   ArrayRef<Instruction *> InsertPts;
235   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
236   LoopInfo &LI;
237 };
238 
239 /// A helper class to do register promotion for all profile counter
240 /// updates in a loop.
241 ///
242 class PGOCounterPromoter {
243 public:
244   PGOCounterPromoter(
245       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
246       Loop &CurLoop, LoopInfo &LI, BlockFrequencyInfo *BFI)
247       : LoopToCandidates(LoopToCands), ExitBlocks(), InsertPts(), L(CurLoop),
248         LI(LI), BFI(BFI) {
249 
250     // Skip collection of ExitBlocks and InsertPts for loops that will not be
251     // able to have counters promoted.
252     SmallVector<BasicBlock *, 8> LoopExitBlocks;
253     SmallPtrSet<BasicBlock *, 8> BlockSet;
254 
255     L.getExitBlocks(LoopExitBlocks);
256     if (!isPromotionPossible(&L, LoopExitBlocks))
257       return;
258 
259     for (BasicBlock *ExitBlock : LoopExitBlocks) {
260       if (BlockSet.insert(ExitBlock).second) {
261         ExitBlocks.push_back(ExitBlock);
262         InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
263       }
264     }
265   }
266 
267   bool run(int64_t *NumPromoted) {
268     // Skip 'infinite' loops:
269     if (ExitBlocks.size() == 0)
270       return false;
271     unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
272     if (MaxProm == 0)
273       return false;
274 
275     unsigned Promoted = 0;
276     for (auto &Cand : LoopToCandidates[&L]) {
277 
278       SmallVector<PHINode *, 4> NewPHIs;
279       SSAUpdater SSA(&NewPHIs);
280       Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
281 
282       // If BFI is set, we will use it to guide the promotions.
283       if (BFI) {
284         auto *BB = Cand.first->getParent();
285         auto InstrCount = BFI->getBlockProfileCount(BB);
286         if (!InstrCount)
287           continue;
288         auto PreheaderCount = BFI->getBlockProfileCount(L.getLoopPreheader());
289         // If the average loop trip count is not greater than 1.5, we skip
290         // promotion.
291         if (PreheaderCount &&
292             (PreheaderCount.getValue() * 3) >= (InstrCount.getValue() * 2))
293           continue;
294       }
295 
296       PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
297                                         L.getLoopPreheader(), ExitBlocks,
298                                         InsertPts, LoopToCandidates, LI);
299       Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
300       Promoted++;
301       if (Promoted >= MaxProm)
302         break;
303 
304       (*NumPromoted)++;
305       if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
306         break;
307     }
308 
309     LLVM_DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
310                       << L.getLoopDepth() << ")\n");
311     return Promoted != 0;
312   }
313 
314 private:
315   bool allowSpeculativeCounterPromotion(Loop *LP) {
316     SmallVector<BasicBlock *, 8> ExitingBlocks;
317     L.getExitingBlocks(ExitingBlocks);
318     // Not considierered speculative.
319     if (ExitingBlocks.size() == 1)
320       return true;
321     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
322       return false;
323     return true;
324   }
325 
326   // Check whether the loop satisfies the basic conditions needed to perform
327   // Counter Promotions.
328   bool isPromotionPossible(Loop *LP,
329                            const SmallVectorImpl<BasicBlock *> &LoopExitBlocks) {
330     // We can't insert into a catchswitch.
331     if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
332           return isa<CatchSwitchInst>(Exit->getTerminator());
333         }))
334       return false;
335 
336     if (!LP->hasDedicatedExits())
337       return false;
338 
339     BasicBlock *PH = LP->getLoopPreheader();
340     if (!PH)
341       return false;
342 
343     return true;
344   }
345 
346   // Returns the max number of Counter Promotions for LP.
347   unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
348     SmallVector<BasicBlock *, 8> LoopExitBlocks;
349     LP->getExitBlocks(LoopExitBlocks);
350     if (!isPromotionPossible(LP, LoopExitBlocks))
351       return 0;
352 
353     SmallVector<BasicBlock *, 8> ExitingBlocks;
354     LP->getExitingBlocks(ExitingBlocks);
355 
356     // If BFI is set, we do more aggressive promotions based on BFI.
357     if (BFI)
358       return (unsigned)-1;
359 
360     // Not considierered speculative.
361     if (ExitingBlocks.size() == 1)
362       return MaxNumOfPromotionsPerLoop;
363 
364     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
365       return 0;
366 
367     // Whether the target block is in a loop does not matter:
368     if (SpeculativeCounterPromotionToLoop)
369       return MaxNumOfPromotionsPerLoop;
370 
371     // Now check the target block:
372     unsigned MaxProm = MaxNumOfPromotionsPerLoop;
373     for (auto *TargetBlock : LoopExitBlocks) {
374       auto *TargetLoop = LI.getLoopFor(TargetBlock);
375       if (!TargetLoop)
376         continue;
377       unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
378       unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
379       MaxProm =
380           std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
381                                 PendingCandsInTarget);
382     }
383     return MaxProm;
384   }
385 
386   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
387   SmallVector<BasicBlock *, 8> ExitBlocks;
388   SmallVector<Instruction *, 8> InsertPts;
389   Loop &L;
390   LoopInfo &LI;
391   BlockFrequencyInfo *BFI;
392 };
393 
394 } // end anonymous namespace
395 
396 PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
397   FunctionAnalysisManager &FAM =
398       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
399   auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
400     return FAM.getResult<TargetLibraryAnalysis>(F);
401   };
402   if (!run(M, GetTLI))
403     return PreservedAnalyses::all();
404 
405   return PreservedAnalyses::none();
406 }
407 
408 char InstrProfilingLegacyPass::ID = 0;
409 INITIALIZE_PASS_BEGIN(
410     InstrProfilingLegacyPass, "instrprof",
411     "Frontend instrumentation-based coverage lowering.", false, false)
412 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
413 INITIALIZE_PASS_END(
414     InstrProfilingLegacyPass, "instrprof",
415     "Frontend instrumentation-based coverage lowering.", false, false)
416 
417 ModulePass *
418 llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options,
419                                      bool IsCS) {
420   return new InstrProfilingLegacyPass(Options, IsCS);
421 }
422 
423 static InstrProfIncrementInst *castToIncrementInst(Instruction *Instr) {
424   InstrProfIncrementInst *Inc = dyn_cast<InstrProfIncrementInstStep>(Instr);
425   if (Inc)
426     return Inc;
427   return dyn_cast<InstrProfIncrementInst>(Instr);
428 }
429 
430 bool InstrProfiling::lowerIntrinsics(Function *F) {
431   bool MadeChange = false;
432   PromotionCandidates.clear();
433   for (BasicBlock &BB : *F) {
434     for (auto I = BB.begin(), E = BB.end(); I != E;) {
435       auto Instr = I++;
436       InstrProfIncrementInst *Inc = castToIncrementInst(&*Instr);
437       if (Inc) {
438         lowerIncrement(Inc);
439         MadeChange = true;
440       } else if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(Instr)) {
441         lowerValueProfileInst(Ind);
442         MadeChange = true;
443       }
444     }
445   }
446 
447   if (!MadeChange)
448     return false;
449 
450   promoteCounterLoadStores(F);
451   return true;
452 }
453 
454 bool InstrProfiling::isRuntimeCounterRelocationEnabled() const {
455   if (RuntimeCounterRelocation.getNumOccurrences() > 0)
456     return RuntimeCounterRelocation;
457 
458   return TT.isOSFuchsia();
459 }
460 
461 bool InstrProfiling::isCounterPromotionEnabled() const {
462   if (DoCounterPromotion.getNumOccurrences() > 0)
463     return DoCounterPromotion;
464 
465   return Options.DoCounterPromotion;
466 }
467 
468 void InstrProfiling::promoteCounterLoadStores(Function *F) {
469   if (!isCounterPromotionEnabled())
470     return;
471 
472   DominatorTree DT(*F);
473   LoopInfo LI(DT);
474   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
475 
476   std::unique_ptr<BlockFrequencyInfo> BFI;
477   if (Options.UseBFIInPromotion) {
478     std::unique_ptr<BranchProbabilityInfo> BPI;
479     BPI.reset(new BranchProbabilityInfo(*F, LI, &GetTLI(*F)));
480     BFI.reset(new BlockFrequencyInfo(*F, *BPI, LI));
481   }
482 
483   for (const auto &LoadStore : PromotionCandidates) {
484     auto *CounterLoad = LoadStore.first;
485     auto *CounterStore = LoadStore.second;
486     BasicBlock *BB = CounterLoad->getParent();
487     Loop *ParentLoop = LI.getLoopFor(BB);
488     if (!ParentLoop)
489       continue;
490     LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
491   }
492 
493   SmallVector<Loop *, 4> Loops = LI.getLoopsInPreorder();
494 
495   // Do a post-order traversal of the loops so that counter updates can be
496   // iteratively hoisted outside the loop nest.
497   for (auto *Loop : llvm::reverse(Loops)) {
498     PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI, BFI.get());
499     Promoter.run(&TotalCountersPromoted);
500   }
501 }
502 
503 /// Check if the module contains uses of any profiling intrinsics.
504 static bool containsProfilingIntrinsics(Module &M) {
505   if (auto *F = M.getFunction(
506           Intrinsic::getName(llvm::Intrinsic::instrprof_increment)))
507     if (!F->use_empty())
508       return true;
509   if (auto *F = M.getFunction(
510           Intrinsic::getName(llvm::Intrinsic::instrprof_increment_step)))
511     if (!F->use_empty())
512       return true;
513   if (auto *F = M.getFunction(
514           Intrinsic::getName(llvm::Intrinsic::instrprof_value_profile)))
515     if (!F->use_empty())
516       return true;
517   return false;
518 }
519 
520 bool InstrProfiling::run(
521     Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI) {
522   this->M = &M;
523   this->GetTLI = std::move(GetTLI);
524   NamesVar = nullptr;
525   NamesSize = 0;
526   ProfileDataMap.clear();
527   UsedVars.clear();
528   getMemOPSizeRangeFromOption(MemOPSizeRange, MemOPSizeRangeStart,
529                               MemOPSizeRangeLast);
530   TT = Triple(M.getTargetTriple());
531 
532   // Emit the runtime hook even if no counters are present.
533   bool MadeChange = emitRuntimeHook();
534 
535   // Improve compile time by avoiding linear scans when there is no work.
536   GlobalVariable *CoverageNamesVar =
537       M.getNamedGlobal(getCoverageUnusedNamesVarName());
538   if (!containsProfilingIntrinsics(M) && !CoverageNamesVar)
539     return MadeChange;
540 
541   // We did not know how many value sites there would be inside
542   // the instrumented function. This is counting the number of instrumented
543   // target value sites to enter it as field in the profile data variable.
544   for (Function &F : M) {
545     InstrProfIncrementInst *FirstProfIncInst = nullptr;
546     for (BasicBlock &BB : F)
547       for (auto I = BB.begin(), E = BB.end(); I != E; I++)
548         if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
549           computeNumValueSiteCounts(Ind);
550         else if (FirstProfIncInst == nullptr)
551           FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
552 
553     // Value profiling intrinsic lowering requires per-function profile data
554     // variable to be created first.
555     if (FirstProfIncInst != nullptr)
556       static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
557   }
558 
559   for (Function &F : M)
560     MadeChange |= lowerIntrinsics(&F);
561 
562   if (CoverageNamesVar) {
563     lowerCoverageData(CoverageNamesVar);
564     MadeChange = true;
565   }
566 
567   if (!MadeChange)
568     return false;
569 
570   emitVNodes();
571   emitNameData();
572   emitRegistration();
573   emitUses();
574   emitInitialization();
575   return true;
576 }
577 
578 static FunctionCallee
579 getOrInsertValueProfilingCall(Module &M, const TargetLibraryInfo &TLI,
580                               bool IsRange = false) {
581   LLVMContext &Ctx = M.getContext();
582   auto *ReturnTy = Type::getVoidTy(M.getContext());
583 
584   AttributeList AL;
585   if (auto AK = TLI.getExtAttrForI32Param(false))
586     AL = AL.addParamAttribute(M.getContext(), 2, AK);
587 
588   if (!IsRange) {
589     Type *ParamTypes[] = {
590 #define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
591 #include "llvm/ProfileData/InstrProfData.inc"
592     };
593     auto *ValueProfilingCallTy =
594         FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
595     return M.getOrInsertFunction(getInstrProfValueProfFuncName(),
596                                  ValueProfilingCallTy, AL);
597   } else {
598     Type *RangeParamTypes[] = {
599 #define VALUE_RANGE_PROF 1
600 #define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
601 #include "llvm/ProfileData/InstrProfData.inc"
602 #undef VALUE_RANGE_PROF
603     };
604     auto *ValueRangeProfilingCallTy =
605         FunctionType::get(ReturnTy, makeArrayRef(RangeParamTypes), false);
606     return M.getOrInsertFunction(getInstrProfValueRangeProfFuncName(),
607                                  ValueRangeProfilingCallTy, AL);
608   }
609 }
610 
611 void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
612   GlobalVariable *Name = Ind->getName();
613   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
614   uint64_t Index = Ind->getIndex()->getZExtValue();
615   auto It = ProfileDataMap.find(Name);
616   if (It == ProfileDataMap.end()) {
617     PerFunctionProfileData PD;
618     PD.NumValueSites[ValueKind] = Index + 1;
619     ProfileDataMap[Name] = PD;
620   } else if (It->second.NumValueSites[ValueKind] <= Index)
621     It->second.NumValueSites[ValueKind] = Index + 1;
622 }
623 
624 void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
625   GlobalVariable *Name = Ind->getName();
626   auto It = ProfileDataMap.find(Name);
627   assert(It != ProfileDataMap.end() && It->second.DataVar &&
628          "value profiling detected in function with no counter incerement");
629 
630   GlobalVariable *DataVar = It->second.DataVar;
631   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
632   uint64_t Index = Ind->getIndex()->getZExtValue();
633   for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
634     Index += It->second.NumValueSites[Kind];
635 
636   IRBuilder<> Builder(Ind);
637   bool IsRange = (Ind->getValueKind()->getZExtValue() ==
638                   llvm::InstrProfValueKind::IPVK_MemOPSize);
639   CallInst *Call = nullptr;
640   auto *TLI = &GetTLI(*Ind->getFunction());
641 
642   // To support value profiling calls within Windows exception handlers, funclet
643   // information contained within operand bundles needs to be copied over to
644   // the library call. This is required for the IR to be processed by the
645   // WinEHPrepare pass.
646   SmallVector<OperandBundleDef, 1> OpBundles;
647   Ind->getOperandBundlesAsDefs(OpBundles);
648   if (!IsRange) {
649     Value *Args[3] = {Ind->getTargetValue(),
650                       Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
651                       Builder.getInt32(Index)};
652     Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args,
653                               OpBundles);
654   } else {
655     Value *Args[6] = {
656         Ind->getTargetValue(),
657         Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
658         Builder.getInt32(Index),
659         Builder.getInt64(MemOPSizeRangeStart),
660         Builder.getInt64(MemOPSizeRangeLast),
661         Builder.getInt64(MemOPSizeLarge == 0 ? INT64_MIN : MemOPSizeLarge)};
662     Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI, true),
663                               Args, OpBundles);
664   }
665   if (auto AK = TLI->getExtAttrForI32Param(false))
666     Call->addParamAttr(2, AK);
667   Ind->replaceAllUsesWith(Call);
668   Ind->eraseFromParent();
669 }
670 
671 void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
672   GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
673 
674   IRBuilder<> Builder(Inc);
675   uint64_t Index = Inc->getIndex()->getZExtValue();
676   Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters->getValueType(),
677                                                    Counters, 0, Index);
678 
679   if (isRuntimeCounterRelocationEnabled()) {
680     Type *Int64Ty = Type::getInt64Ty(M->getContext());
681     Type *Int64PtrTy = Type::getInt64PtrTy(M->getContext());
682     Function *Fn = Inc->getParent()->getParent();
683     Instruction &I = Fn->getEntryBlock().front();
684     LoadInst *LI = dyn_cast<LoadInst>(&I);
685     if (!LI) {
686       IRBuilder<> Builder(&I);
687       Type *Int64Ty = Type::getInt64Ty(M->getContext());
688       GlobalVariable *Bias = M->getGlobalVariable(getInstrProfCounterBiasVarName());
689       if (!Bias)
690         Bias = new GlobalVariable(*M, Int64Ty, false, GlobalValue::LinkOnceODRLinkage,
691                                   Constant::getNullValue(Int64Ty),
692                                   getInstrProfCounterBiasVarName());
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                                           DoNameCompression)) {
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