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/DIBuilder.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalValue.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/IRBuilder.h"
37 #include "llvm/IR/Instruction.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/InitializePasses.h"
43 #include "llvm/Pass.h"
44 #include "llvm/ProfileData/InstrProf.h"
45 #include "llvm/ProfileData/InstrProfCorrelator.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Error.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Transforms/Utils/ModuleUtils.h"
51 #include "llvm/Transforms/Utils/SSAUpdater.h"
52 #include <algorithm>
53 #include <cassert>
54 #include <cstddef>
55 #include <cstdint>
56 #include <string>
57 
58 using namespace llvm;
59 
60 #define DEBUG_TYPE "instrprof"
61 
62 namespace llvm {
63 cl::opt<bool>
64     DebugInfoCorrelate("debug-info-correlate", cl::ZeroOrMore,
65                        cl::desc("Use debug info to correlate profiles."),
66                        cl::init(false));
67 } // namespace llvm
68 
69 namespace {
70 
71 cl::opt<bool> DoHashBasedCounterSplit(
72     "hash-based-counter-split",
73     cl::desc("Rename counter variable of a comdat function based on cfg hash"),
74     cl::init(true));
75 
76 cl::opt<bool>
77     RuntimeCounterRelocation("runtime-counter-relocation",
78                              cl::desc("Enable relocating counters at runtime."),
79                              cl::init(false));
80 
81 cl::opt<bool> ValueProfileStaticAlloc(
82     "vp-static-alloc",
83     cl::desc("Do static counter allocation for value profiler"),
84     cl::init(true));
85 
86 cl::opt<double> NumCountersPerValueSite(
87     "vp-counters-per-site",
88     cl::desc("The average number of profile counters allocated "
89              "per value profiling site."),
90     // This is set to a very small value because in real programs, only
91     // a very small percentage of value sites have non-zero targets, e.g, 1/30.
92     // For those sites with non-zero profile, the average number of targets
93     // is usually smaller than 2.
94     cl::init(1.0));
95 
96 cl::opt<bool> AtomicCounterUpdateAll(
97     "instrprof-atomic-counter-update-all", cl::ZeroOrMore,
98     cl::desc("Make all profile counter updates atomic (for testing only)"),
99     cl::init(false));
100 
101 cl::opt<bool> AtomicCounterUpdatePromoted(
102     "atomic-counter-update-promoted", cl::ZeroOrMore,
103     cl::desc("Do counter update using atomic fetch add "
104              " for promoted counters only"),
105     cl::init(false));
106 
107 cl::opt<bool> AtomicFirstCounter(
108     "atomic-first-counter", cl::ZeroOrMore,
109     cl::desc("Use atomic fetch add for first counter in a function (usually "
110              "the entry counter)"),
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 cl::opt<bool> SkipRetExitBlock(
148     cl::ZeroOrMore, "skip-ret-exit-block", cl::init(true),
149     cl::desc("Suppress counter promotion if exit blocks contain ret."));
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     initializeInstrProfilingLegacyPassPass(*PassRegistry::getPassRegistry());
161   }
162 
163   StringRef getPassName() const override {
164     return "Frontend instrumentation-based coverage lowering";
165   }
166 
167   bool runOnModule(Module &M) override {
168     auto GetTLI = [this](Function &F) -> TargetLibraryInfo & {
169       return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
170     };
171     return InstrProf.run(M, GetTLI);
172   }
173 
174   void getAnalysisUsage(AnalysisUsage &AU) const override {
175     AU.setPreservesCFG();
176     AU.addRequired<TargetLibraryInfoWrapperPass>();
177   }
178 };
179 
180 ///
181 /// A helper class to promote one counter RMW operation in the loop
182 /// into register update.
183 ///
184 /// RWM update for the counter will be sinked out of the loop after
185 /// the transformation.
186 ///
187 class PGOCounterPromoterHelper : public LoadAndStorePromoter {
188 public:
189   PGOCounterPromoterHelper(
190       Instruction *L, Instruction *S, SSAUpdater &SSA, Value *Init,
191       BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
192       ArrayRef<Instruction *> InsertPts,
193       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
194       LoopInfo &LI)
195       : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
196         InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
197     assert(isa<LoadInst>(L));
198     assert(isa<StoreInst>(S));
199     SSA.AddAvailableValue(PH, Init);
200   }
201 
202   void doExtraRewritesBeforeFinalDeletion() override {
203     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
204       BasicBlock *ExitBlock = ExitBlocks[i];
205       Instruction *InsertPos = InsertPts[i];
206       // Get LiveIn value into the ExitBlock. If there are multiple
207       // predecessors, the value is defined by a PHI node in this
208       // block.
209       Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
210       Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
211       Type *Ty = LiveInValue->getType();
212       IRBuilder<> Builder(InsertPos);
213       if (AtomicCounterUpdatePromoted)
214         // automic update currently can only be promoted across the current
215         // loop, not the whole loop nest.
216         Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
217                                 MaybeAlign(),
218                                 AtomicOrdering::SequentiallyConsistent);
219       else {
220         LoadInst *OldVal = Builder.CreateLoad(Ty, Addr, "pgocount.promoted");
221         auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
222         auto *NewStore = Builder.CreateStore(NewVal, Addr);
223 
224         // Now update the parent loop's candidate list:
225         if (IterativeCounterPromotion) {
226           auto *TargetLoop = LI.getLoopFor(ExitBlock);
227           if (TargetLoop)
228             LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
229         }
230       }
231     }
232   }
233 
234 private:
235   Instruction *Store;
236   ArrayRef<BasicBlock *> ExitBlocks;
237   ArrayRef<Instruction *> InsertPts;
238   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
239   LoopInfo &LI;
240 };
241 
242 /// A helper class to do register promotion for all profile counter
243 /// updates in a loop.
244 ///
245 class PGOCounterPromoter {
246 public:
247   PGOCounterPromoter(
248       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
249       Loop &CurLoop, LoopInfo &LI, BlockFrequencyInfo *BFI)
250       : LoopToCandidates(LoopToCands), L(CurLoop), LI(LI), BFI(BFI) {
251 
252     // Skip collection of ExitBlocks and InsertPts for loops that will not be
253     // able to have counters promoted.
254     SmallVector<BasicBlock *, 8> LoopExitBlocks;
255     SmallPtrSet<BasicBlock *, 8> BlockSet;
256 
257     L.getExitBlocks(LoopExitBlocks);
258     if (!isPromotionPossible(&L, LoopExitBlocks))
259       return;
260 
261     for (BasicBlock *ExitBlock : LoopExitBlocks) {
262       if (BlockSet.insert(ExitBlock).second) {
263         ExitBlocks.push_back(ExitBlock);
264         InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
265       }
266     }
267   }
268 
269   bool run(int64_t *NumPromoted) {
270     // Skip 'infinite' loops:
271     if (ExitBlocks.size() == 0)
272       return false;
273 
274     // Skip if any of the ExitBlocks contains a ret instruction.
275     // This is to prevent dumping of incomplete profile -- if the
276     // the loop is a long running loop and dump is called in the middle
277     // of the loop, the result profile is incomplete.
278     // FIXME: add other heuristics to detect long running loops.
279     if (SkipRetExitBlock) {
280       for (auto BB : ExitBlocks)
281         if (isa<ReturnInst>(BB->getTerminator()))
282           return false;
283     }
284 
285     unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
286     if (MaxProm == 0)
287       return false;
288 
289     unsigned Promoted = 0;
290     for (auto &Cand : LoopToCandidates[&L]) {
291 
292       SmallVector<PHINode *, 4> NewPHIs;
293       SSAUpdater SSA(&NewPHIs);
294       Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
295 
296       // If BFI is set, we will use it to guide the promotions.
297       if (BFI) {
298         auto *BB = Cand.first->getParent();
299         auto InstrCount = BFI->getBlockProfileCount(BB);
300         if (!InstrCount)
301           continue;
302         auto PreheaderCount = BFI->getBlockProfileCount(L.getLoopPreheader());
303         // If the average loop trip count is not greater than 1.5, we skip
304         // promotion.
305         if (PreheaderCount &&
306             (PreheaderCount.getValue() * 3) >= (InstrCount.getValue() * 2))
307           continue;
308       }
309 
310       PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
311                                         L.getLoopPreheader(), ExitBlocks,
312                                         InsertPts, LoopToCandidates, LI);
313       Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
314       Promoted++;
315       if (Promoted >= MaxProm)
316         break;
317 
318       (*NumPromoted)++;
319       if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
320         break;
321     }
322 
323     LLVM_DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
324                       << L.getLoopDepth() << ")\n");
325     return Promoted != 0;
326   }
327 
328 private:
329   bool allowSpeculativeCounterPromotion(Loop *LP) {
330     SmallVector<BasicBlock *, 8> ExitingBlocks;
331     L.getExitingBlocks(ExitingBlocks);
332     // Not considierered speculative.
333     if (ExitingBlocks.size() == 1)
334       return true;
335     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
336       return false;
337     return true;
338   }
339 
340   // Check whether the loop satisfies the basic conditions needed to perform
341   // Counter Promotions.
342   bool
343   isPromotionPossible(Loop *LP,
344                       const SmallVectorImpl<BasicBlock *> &LoopExitBlocks) {
345     // We can't insert into a catchswitch.
346     if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
347           return isa<CatchSwitchInst>(Exit->getTerminator());
348         }))
349       return false;
350 
351     if (!LP->hasDedicatedExits())
352       return false;
353 
354     BasicBlock *PH = LP->getLoopPreheader();
355     if (!PH)
356       return false;
357 
358     return true;
359   }
360 
361   // Returns the max number of Counter Promotions for LP.
362   unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
363     SmallVector<BasicBlock *, 8> LoopExitBlocks;
364     LP->getExitBlocks(LoopExitBlocks);
365     if (!isPromotionPossible(LP, LoopExitBlocks))
366       return 0;
367 
368     SmallVector<BasicBlock *, 8> ExitingBlocks;
369     LP->getExitingBlocks(ExitingBlocks);
370 
371     // If BFI is set, we do more aggressive promotions based on BFI.
372     if (BFI)
373       return (unsigned)-1;
374 
375     // Not considierered speculative.
376     if (ExitingBlocks.size() == 1)
377       return MaxNumOfPromotionsPerLoop;
378 
379     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
380       return 0;
381 
382     // Whether the target block is in a loop does not matter:
383     if (SpeculativeCounterPromotionToLoop)
384       return MaxNumOfPromotionsPerLoop;
385 
386     // Now check the target block:
387     unsigned MaxProm = MaxNumOfPromotionsPerLoop;
388     for (auto *TargetBlock : LoopExitBlocks) {
389       auto *TargetLoop = LI.getLoopFor(TargetBlock);
390       if (!TargetLoop)
391         continue;
392       unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
393       unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
394       MaxProm =
395           std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
396                                 PendingCandsInTarget);
397     }
398     return MaxProm;
399   }
400 
401   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
402   SmallVector<BasicBlock *, 8> ExitBlocks;
403   SmallVector<Instruction *, 8> InsertPts;
404   Loop &L;
405   LoopInfo &LI;
406   BlockFrequencyInfo *BFI;
407 };
408 
409 enum class ValueProfilingCallType {
410   // Individual values are tracked. Currently used for indiret call target
411   // profiling.
412   Default,
413 
414   // MemOp: the memop size value profiling.
415   MemOp
416 };
417 
418 } // end anonymous namespace
419 
420 PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
421   FunctionAnalysisManager &FAM =
422       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
423   auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
424     return FAM.getResult<TargetLibraryAnalysis>(F);
425   };
426   if (!run(M, GetTLI))
427     return PreservedAnalyses::all();
428 
429   return PreservedAnalyses::none();
430 }
431 
432 char InstrProfilingLegacyPass::ID = 0;
433 INITIALIZE_PASS_BEGIN(InstrProfilingLegacyPass, "instrprof",
434                       "Frontend instrumentation-based coverage lowering.",
435                       false, false)
436 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
437 INITIALIZE_PASS_END(InstrProfilingLegacyPass, "instrprof",
438                     "Frontend instrumentation-based coverage lowering.", false,
439                     false)
440 
441 ModulePass *
442 llvm::createInstrProfilingLegacyPass(const InstrProfOptions &Options,
443                                      bool IsCS) {
444   return new InstrProfilingLegacyPass(Options, IsCS);
445 }
446 
447 bool InstrProfiling::lowerIntrinsics(Function *F) {
448   bool MadeChange = false;
449   PromotionCandidates.clear();
450   for (BasicBlock &BB : *F) {
451     for (Instruction &Instr : llvm::make_early_inc_range(BB)) {
452       if (auto *IPIS = dyn_cast<InstrProfIncrementInstStep>(&Instr)) {
453         lowerIncrement(IPIS);
454         MadeChange = true;
455       } else if (auto *IPI = dyn_cast<InstrProfIncrementInst>(&Instr)) {
456         lowerIncrement(IPI);
457         MadeChange = true;
458       } else if (auto *IPC = dyn_cast<InstrProfCoverInst>(&Instr)) {
459         lowerCover(IPC);
460         MadeChange = true;
461       } else if (auto *IPVP = dyn_cast<InstrProfValueProfileInst>(&Instr)) {
462         lowerValueProfileInst(IPVP);
463         MadeChange = true;
464       }
465     }
466   }
467 
468   if (!MadeChange)
469     return false;
470 
471   promoteCounterLoadStores(F);
472   return true;
473 }
474 
475 bool InstrProfiling::isRuntimeCounterRelocationEnabled() const {
476   // Mach-O don't support weak external references.
477   if (TT.isOSBinFormatMachO())
478     return false;
479 
480   if (RuntimeCounterRelocation.getNumOccurrences() > 0)
481     return RuntimeCounterRelocation;
482 
483   // Fuchsia uses runtime counter relocation by default.
484   return TT.isOSFuchsia();
485 }
486 
487 bool InstrProfiling::isCounterPromotionEnabled() const {
488   if (DoCounterPromotion.getNumOccurrences() > 0)
489     return DoCounterPromotion;
490 
491   return Options.DoCounterPromotion;
492 }
493 
494 void InstrProfiling::promoteCounterLoadStores(Function *F) {
495   if (!isCounterPromotionEnabled())
496     return;
497 
498   DominatorTree DT(*F);
499   LoopInfo LI(DT);
500   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
501 
502   std::unique_ptr<BlockFrequencyInfo> BFI;
503   if (Options.UseBFIInPromotion) {
504     std::unique_ptr<BranchProbabilityInfo> BPI;
505     BPI.reset(new BranchProbabilityInfo(*F, LI, &GetTLI(*F)));
506     BFI.reset(new BlockFrequencyInfo(*F, *BPI, LI));
507   }
508 
509   for (const auto &LoadStore : PromotionCandidates) {
510     auto *CounterLoad = LoadStore.first;
511     auto *CounterStore = LoadStore.second;
512     BasicBlock *BB = CounterLoad->getParent();
513     Loop *ParentLoop = LI.getLoopFor(BB);
514     if (!ParentLoop)
515       continue;
516     LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
517   }
518 
519   SmallVector<Loop *, 4> Loops = LI.getLoopsInPreorder();
520 
521   // Do a post-order traversal of the loops so that counter updates can be
522   // iteratively hoisted outside the loop nest.
523   for (auto *Loop : llvm::reverse(Loops)) {
524     PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI, BFI.get());
525     Promoter.run(&TotalCountersPromoted);
526   }
527 }
528 
529 static bool needsRuntimeHookUnconditionally(const Triple &TT) {
530   // On Fuchsia, we only need runtime hook if any counters are present.
531   if (TT.isOSFuchsia())
532     return false;
533 
534   return true;
535 }
536 
537 /// Check if the module contains uses of any profiling intrinsics.
538 static bool containsProfilingIntrinsics(Module &M) {
539   auto containsIntrinsic = [&](int ID) {
540     if (auto *F = M.getFunction(Intrinsic::getName(ID)))
541       return !F->use_empty();
542     return false;
543   };
544   return containsIntrinsic(llvm::Intrinsic::instrprof_cover) ||
545          containsIntrinsic(llvm::Intrinsic::instrprof_increment) ||
546          containsIntrinsic(llvm::Intrinsic::instrprof_increment_step) ||
547          containsIntrinsic(llvm::Intrinsic::instrprof_value_profile);
548 }
549 
550 bool InstrProfiling::run(
551     Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI) {
552   this->M = &M;
553   this->GetTLI = std::move(GetTLI);
554   NamesVar = nullptr;
555   NamesSize = 0;
556   ProfileDataMap.clear();
557   CompilerUsedVars.clear();
558   UsedVars.clear();
559   TT = Triple(M.getTargetTriple());
560 
561   bool MadeChange = false;
562 
563   // Emit the runtime hook even if no counters are present.
564   if (needsRuntimeHookUnconditionally(TT))
565     MadeChange = emitRuntimeHook();
566 
567   // Improve compile time by avoiding linear scans when there is no work.
568   GlobalVariable *CoverageNamesVar =
569       M.getNamedGlobal(getCoverageUnusedNamesVarName());
570   if (!containsProfilingIntrinsics(M) && !CoverageNamesVar)
571     return MadeChange;
572 
573   // We did not know how many value sites there would be inside
574   // the instrumented function. This is counting the number of instrumented
575   // target value sites to enter it as field in the profile data variable.
576   for (Function &F : M) {
577     InstrProfIncrementInst *FirstProfIncInst = nullptr;
578     for (BasicBlock &BB : F)
579       for (auto I = BB.begin(), E = BB.end(); I != E; I++)
580         if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
581           computeNumValueSiteCounts(Ind);
582         else if (FirstProfIncInst == nullptr)
583           FirstProfIncInst = dyn_cast<InstrProfIncrementInst>(I);
584 
585     // Value profiling intrinsic lowering requires per-function profile data
586     // variable to be created first.
587     if (FirstProfIncInst != nullptr)
588       static_cast<void>(getOrCreateRegionCounters(FirstProfIncInst));
589   }
590 
591   for (Function &F : M)
592     MadeChange |= lowerIntrinsics(&F);
593 
594   if (CoverageNamesVar) {
595     lowerCoverageData(CoverageNamesVar);
596     MadeChange = true;
597   }
598 
599   if (!MadeChange)
600     return false;
601 
602   emitVNodes();
603   emitNameData();
604   emitRuntimeHook();
605   emitRegistration();
606   emitUses();
607   emitInitialization();
608   return true;
609 }
610 
611 static FunctionCallee getOrInsertValueProfilingCall(
612     Module &M, const TargetLibraryInfo &TLI,
613     ValueProfilingCallType CallType = ValueProfilingCallType::Default) {
614   LLVMContext &Ctx = M.getContext();
615   auto *ReturnTy = Type::getVoidTy(M.getContext());
616 
617   AttributeList AL;
618   if (auto AK = TLI.getExtAttrForI32Param(false))
619     AL = AL.addParamAttribute(M.getContext(), 2, AK);
620 
621   assert((CallType == ValueProfilingCallType::Default ||
622           CallType == ValueProfilingCallType::MemOp) &&
623          "Must be Default or MemOp");
624   Type *ParamTypes[] = {
625 #define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
626 #include "llvm/ProfileData/InstrProfData.inc"
627   };
628   auto *ValueProfilingCallTy =
629       FunctionType::get(ReturnTy, makeArrayRef(ParamTypes), false);
630   StringRef FuncName = CallType == ValueProfilingCallType::Default
631                            ? getInstrProfValueProfFuncName()
632                            : getInstrProfValueProfMemOpFuncName();
633   return M.getOrInsertFunction(FuncName, ValueProfilingCallTy, AL);
634 }
635 
636 void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
637   GlobalVariable *Name = Ind->getName();
638   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
639   uint64_t Index = Ind->getIndex()->getZExtValue();
640   auto &PD = ProfileDataMap[Name];
641   PD.NumValueSites[ValueKind] =
642       std::max(PD.NumValueSites[ValueKind], (uint32_t)(Index + 1));
643 }
644 
645 void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
646   // TODO: Value profiling heavily depends on the data section which is omitted
647   // in lightweight mode. We need to move the value profile pointer to the
648   // Counter struct to get this working.
649   assert(
650       !DebugInfoCorrelate &&
651       "Value profiling is not yet supported with lightweight instrumentation");
652   GlobalVariable *Name = Ind->getName();
653   auto It = ProfileDataMap.find(Name);
654   assert(It != ProfileDataMap.end() && It->second.DataVar &&
655          "value profiling detected in function with no counter incerement");
656 
657   GlobalVariable *DataVar = It->second.DataVar;
658   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
659   uint64_t Index = Ind->getIndex()->getZExtValue();
660   for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
661     Index += It->second.NumValueSites[Kind];
662 
663   IRBuilder<> Builder(Ind);
664   bool IsMemOpSize = (Ind->getValueKind()->getZExtValue() ==
665                       llvm::InstrProfValueKind::IPVK_MemOPSize);
666   CallInst *Call = nullptr;
667   auto *TLI = &GetTLI(*Ind->getFunction());
668 
669   // To support value profiling calls within Windows exception handlers, funclet
670   // information contained within operand bundles needs to be copied over to
671   // the library call. This is required for the IR to be processed by the
672   // WinEHPrepare pass.
673   SmallVector<OperandBundleDef, 1> OpBundles;
674   Ind->getOperandBundlesAsDefs(OpBundles);
675   if (!IsMemOpSize) {
676     Value *Args[3] = {Ind->getTargetValue(),
677                       Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
678                       Builder.getInt32(Index)};
679     Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args,
680                               OpBundles);
681   } else {
682     Value *Args[3] = {Ind->getTargetValue(),
683                       Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
684                       Builder.getInt32(Index)};
685     Call = Builder.CreateCall(
686         getOrInsertValueProfilingCall(*M, *TLI, ValueProfilingCallType::MemOp),
687         Args, OpBundles);
688   }
689   if (auto AK = TLI->getExtAttrForI32Param(false))
690     Call->addParamAttr(2, AK);
691   Ind->replaceAllUsesWith(Call);
692   Ind->eraseFromParent();
693 }
694 
695 Value *InstrProfiling::getCounterAddress(InstrProfInstBase *I) {
696   auto *Counters = getOrCreateRegionCounters(I);
697   IRBuilder<> Builder(I);
698 
699   auto *Addr = Builder.CreateConstInBoundsGEP2_32(
700       Counters->getValueType(), Counters, 0, I->getIndex()->getZExtValue());
701 
702   if (!isRuntimeCounterRelocationEnabled())
703     return Addr;
704 
705   Type *Int64Ty = Type::getInt64Ty(M->getContext());
706   Function *Fn = I->getParent()->getParent();
707   Instruction &EntryI = Fn->getEntryBlock().front();
708   LoadInst *LI = dyn_cast<LoadInst>(&EntryI);
709   if (!LI) {
710     IRBuilder<> EntryBuilder(&EntryI);
711     auto *Bias = M->getGlobalVariable(getInstrProfCounterBiasVarName());
712     if (!Bias) {
713       // Compiler must define this variable when runtime counter relocation
714       // is being used. Runtime has a weak external reference that is used
715       // to check whether that's the case or not.
716       Bias = new GlobalVariable(
717           *M, Int64Ty, false, GlobalValue::LinkOnceODRLinkage,
718           Constant::getNullValue(Int64Ty), getInstrProfCounterBiasVarName());
719       Bias->setVisibility(GlobalVariable::HiddenVisibility);
720       // A definition that's weak (linkonce_odr) without being in a COMDAT
721       // section wouldn't lead to link errors, but it would lead to a dead
722       // data word from every TU but one. Putting it in COMDAT ensures there
723       // will be exactly one data slot in the link.
724       if (TT.supportsCOMDAT())
725         Bias->setComdat(M->getOrInsertComdat(Bias->getName()));
726     }
727     LI = EntryBuilder.CreateLoad(Int64Ty, Bias);
728   }
729   auto *Add = Builder.CreateAdd(Builder.CreatePtrToInt(Addr, Int64Ty), LI);
730   return Builder.CreateIntToPtr(Add, Addr->getType());
731 }
732 
733 void InstrProfiling::lowerCover(InstrProfCoverInst *CoverInstruction) {
734   auto *Addr = getCounterAddress(CoverInstruction);
735   IRBuilder<> Builder(CoverInstruction);
736   // We store zero to represent that this block is covered.
737   Builder.CreateStore(Builder.getInt8(0), Addr);
738   CoverInstruction->eraseFromParent();
739 }
740 
741 void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
742   auto *Addr = getCounterAddress(Inc);
743 
744   IRBuilder<> Builder(Inc);
745   if (Options.Atomic || AtomicCounterUpdateAll ||
746       (Inc->getIndex()->isZeroValue() && AtomicFirstCounter)) {
747     Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, Inc->getStep(),
748                             MaybeAlign(), AtomicOrdering::Monotonic);
749   } else {
750     Value *IncStep = Inc->getStep();
751     Value *Load = Builder.CreateLoad(IncStep->getType(), Addr, "pgocount");
752     auto *Count = Builder.CreateAdd(Load, Inc->getStep());
753     auto *Store = Builder.CreateStore(Count, Addr);
754     if (isCounterPromotionEnabled())
755       PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
756   }
757   Inc->eraseFromParent();
758 }
759 
760 void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
761   ConstantArray *Names =
762       cast<ConstantArray>(CoverageNamesVar->getInitializer());
763   for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
764     Constant *NC = Names->getOperand(I);
765     Value *V = NC->stripPointerCasts();
766     assert(isa<GlobalVariable>(V) && "Missing reference to function name");
767     GlobalVariable *Name = cast<GlobalVariable>(V);
768 
769     Name->setLinkage(GlobalValue::PrivateLinkage);
770     ReferencedNames.push_back(Name);
771     NC->dropAllReferences();
772   }
773   CoverageNamesVar->eraseFromParent();
774 }
775 
776 /// Get the name of a profiling variable for a particular function.
777 static std::string getVarName(InstrProfInstBase *Inc, StringRef Prefix,
778                               bool &Renamed) {
779   StringRef NamePrefix = getInstrProfNameVarPrefix();
780   StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
781   Function *F = Inc->getParent()->getParent();
782   Module *M = F->getParent();
783   if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
784       !canRenameComdatFunc(*F)) {
785     Renamed = false;
786     return (Prefix + Name).str();
787   }
788   Renamed = true;
789   uint64_t FuncHash = Inc->getHash()->getZExtValue();
790   SmallVector<char, 24> HashPostfix;
791   if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
792     return (Prefix + Name).str();
793   return (Prefix + Name + "." + Twine(FuncHash)).str();
794 }
795 
796 static uint64_t getIntModuleFlagOrZero(const Module &M, StringRef Flag) {
797   auto *MD = dyn_cast_or_null<ConstantAsMetadata>(M.getModuleFlag(Flag));
798   if (!MD)
799     return 0;
800 
801   // If the flag is a ConstantAsMetadata, it should be an integer representable
802   // in 64-bits.
803   return cast<ConstantInt>(MD->getValue())->getZExtValue();
804 }
805 
806 static bool enablesValueProfiling(const Module &M) {
807   return isIRPGOFlagSet(&M) ||
808          getIntModuleFlagOrZero(M, "EnableValueProfiling") != 0;
809 }
810 
811 // Conservatively returns true if data variables may be referenced by code.
812 static bool profDataReferencedByCode(const Module &M) {
813   return enablesValueProfiling(M);
814 }
815 
816 static inline bool shouldRecordFunctionAddr(Function *F) {
817   // Only record function addresses if IR PGO is enabled or if clang value
818   // profiling is enabled. Recording function addresses greatly increases object
819   // file size, because it prevents the inliner from deleting functions that
820   // have been inlined everywhere.
821   if (!profDataReferencedByCode(*F->getParent()))
822     return false;
823 
824   // Check the linkage
825   bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
826   if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
827       !HasAvailableExternallyLinkage)
828     return true;
829 
830   // A function marked 'alwaysinline' with available_externally linkage can't
831   // have its address taken. Doing so would create an undefined external ref to
832   // the function, which would fail to link.
833   if (HasAvailableExternallyLinkage &&
834       F->hasFnAttribute(Attribute::AlwaysInline))
835     return false;
836 
837   // Prohibit function address recording if the function is both internal and
838   // COMDAT. This avoids the profile data variable referencing internal symbols
839   // in COMDAT.
840   if (F->hasLocalLinkage() && F->hasComdat())
841     return false;
842 
843   // Check uses of this function for other than direct calls or invokes to it.
844   // Inline virtual functions have linkeOnceODR linkage. When a key method
845   // exists, the vtable will only be emitted in the TU where the key method
846   // is defined. In a TU where vtable is not available, the function won't
847   // be 'addresstaken'. If its address is not recorded here, the profile data
848   // with missing address may be picked by the linker leading  to missing
849   // indirect call target info.
850   return F->hasAddressTaken() || F->hasLinkOnceLinkage();
851 }
852 
853 static bool needsRuntimeRegistrationOfSectionRange(const Triple &TT) {
854   // Don't do this for Darwin.  compiler-rt uses linker magic.
855   if (TT.isOSDarwin())
856     return false;
857   // Use linker script magic to get data/cnts/name start/end.
858   if (TT.isOSLinux() || TT.isOSFreeBSD() || TT.isOSNetBSD() ||
859       TT.isOSSolaris() || TT.isOSFuchsia() || TT.isPS4() || TT.isOSWindows())
860     return false;
861 
862   return true;
863 }
864 
865 GlobalVariable *
866 InstrProfiling::createRegionCounters(InstrProfInstBase *Inc, StringRef Name,
867                                      GlobalValue::LinkageTypes Linkage) {
868   uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
869   auto &Ctx = M->getContext();
870   GlobalVariable *GV;
871   if (isa<InstrProfCoverInst>(Inc)) {
872     auto *CounterTy = Type::getInt8Ty(Ctx);
873     auto *CounterArrTy = ArrayType::get(CounterTy, NumCounters);
874     // TODO: `Constant::getAllOnesValue()` does not yet accept an array type.
875     std::vector<Constant *> InitialValues(NumCounters,
876                                           Constant::getAllOnesValue(CounterTy));
877     GV = new GlobalVariable(*M, CounterArrTy, false, Linkage,
878                             ConstantArray::get(CounterArrTy, InitialValues),
879                             Name);
880     GV->setAlignment(Align(1));
881   } else {
882     auto *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
883     GV = new GlobalVariable(*M, CounterTy, false, Linkage,
884                             Constant::getNullValue(CounterTy), Name);
885     GV->setAlignment(Align(8));
886   }
887   return GV;
888 }
889 
890 GlobalVariable *
891 InstrProfiling::getOrCreateRegionCounters(InstrProfInstBase *Inc) {
892   GlobalVariable *NamePtr = Inc->getName();
893   auto &PD = ProfileDataMap[NamePtr];
894   if (PD.RegionCounters)
895     return PD.RegionCounters;
896 
897   // Match the linkage and visibility of the name global.
898   Function *Fn = Inc->getParent()->getParent();
899   GlobalValue::LinkageTypes Linkage = NamePtr->getLinkage();
900   GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
901 
902   // Use internal rather than private linkage so the counter variable shows up
903   // in the symbol table when using debug info for correlation.
904   if (DebugInfoCorrelate && TT.isOSBinFormatMachO() &&
905       Linkage == GlobalValue::PrivateLinkage)
906     Linkage = GlobalValue::InternalLinkage;
907 
908   // Due to the limitation of binder as of 2021/09/28, the duplicate weak
909   // symbols in the same csect won't be discarded. When there are duplicate weak
910   // symbols, we can NOT guarantee that the relocations get resolved to the
911   // intended weak symbol, so we can not ensure the correctness of the relative
912   // CounterPtr, so we have to use private linkage for counter and data symbols.
913   if (TT.isOSBinFormatXCOFF()) {
914     Linkage = GlobalValue::PrivateLinkage;
915     Visibility = GlobalValue::DefaultVisibility;
916   }
917   // Move the name variable to the right section. Place them in a COMDAT group
918   // if the associated function is a COMDAT. This will make sure that only one
919   // copy of counters of the COMDAT function will be emitted after linking. Keep
920   // in mind that this pass may run before the inliner, so we need to create a
921   // new comdat group for the counters and profiling data. If we use the comdat
922   // of the parent function, that will result in relocations against discarded
923   // sections.
924   //
925   // If the data variable is referenced by code,  counters and data have to be
926   // in different comdats for COFF because the Visual C++ linker will report
927   // duplicate symbol errors if there are multiple external symbols with the
928   // same name marked IMAGE_COMDAT_SELECT_ASSOCIATIVE.
929   //
930   // For ELF, when not using COMDAT, put counters, data and values into a
931   // nodeduplicate COMDAT which is lowered to a zero-flag section group. This
932   // allows -z start-stop-gc to discard the entire group when the function is
933   // discarded.
934   bool DataReferencedByCode = profDataReferencedByCode(*M);
935   bool NeedComdat = needsComdatForCounter(*Fn, *M);
936   bool Renamed;
937   std::string CntsVarName =
938       getVarName(Inc, getInstrProfCountersVarPrefix(), Renamed);
939   std::string DataVarName =
940       getVarName(Inc, getInstrProfDataVarPrefix(), Renamed);
941   auto MaybeSetComdat = [&](GlobalVariable *GV) {
942     bool UseComdat = (NeedComdat || TT.isOSBinFormatELF());
943     if (UseComdat) {
944       StringRef GroupName = TT.isOSBinFormatCOFF() && DataReferencedByCode
945                                 ? GV->getName()
946                                 : CntsVarName;
947       Comdat *C = M->getOrInsertComdat(GroupName);
948       if (!NeedComdat)
949         C->setSelectionKind(Comdat::NoDeduplicate);
950       GV->setComdat(C);
951     }
952   };
953 
954   uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
955   LLVMContext &Ctx = M->getContext();
956 
957   auto *CounterPtr = createRegionCounters(Inc, CntsVarName, Linkage);
958   CounterPtr->setVisibility(Visibility);
959   CounterPtr->setSection(
960       getInstrProfSectionName(IPSK_cnts, TT.getObjectFormat()));
961   MaybeSetComdat(CounterPtr);
962   CounterPtr->setLinkage(Linkage);
963   PD.RegionCounters = CounterPtr;
964   if (DebugInfoCorrelate) {
965     if (auto *SP = Fn->getSubprogram()) {
966       DIBuilder DB(*M, true, SP->getUnit());
967       Metadata *FunctionNameAnnotation[] = {
968           MDString::get(Ctx, InstrProfCorrelator::FunctionNameAttributeName),
969           MDString::get(Ctx, getPGOFuncNameVarInitializer(NamePtr)),
970       };
971       Metadata *CFGHashAnnotation[] = {
972           MDString::get(Ctx, InstrProfCorrelator::CFGHashAttributeName),
973           ConstantAsMetadata::get(Inc->getHash()),
974       };
975       Metadata *NumCountersAnnotation[] = {
976           MDString::get(Ctx, InstrProfCorrelator::NumCountersAttributeName),
977           ConstantAsMetadata::get(Inc->getNumCounters()),
978       };
979       auto Annotations = DB.getOrCreateArray({
980           MDNode::get(Ctx, FunctionNameAnnotation),
981           MDNode::get(Ctx, CFGHashAnnotation),
982           MDNode::get(Ctx, NumCountersAnnotation),
983       });
984       auto *DICounter = DB.createGlobalVariableExpression(
985           SP, CounterPtr->getName(), /*LinkageName=*/StringRef(), SP->getFile(),
986           /*LineNo=*/0, DB.createUnspecifiedType("Profile Data Type"),
987           CounterPtr->hasLocalLinkage(), /*IsDefined=*/true, /*Expr=*/nullptr,
988           /*Decl=*/nullptr, /*TemplateParams=*/nullptr, /*AlignInBits=*/0,
989           Annotations);
990       CounterPtr->addDebugInfo(DICounter);
991       DB.finalize();
992     } else {
993       std::string Msg = ("Missing debug info for function " + Fn->getName() +
994                          "; required for profile correlation.")
995                             .str();
996       Ctx.diagnose(
997           DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
998     }
999   }
1000 
1001   auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
1002   // Allocate statically the array of pointers to value profile nodes for
1003   // the current function.
1004   Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
1005   uint64_t NS = 0;
1006   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1007     NS += PD.NumValueSites[Kind];
1008   if (NS > 0 && ValueProfileStaticAlloc &&
1009       !needsRuntimeRegistrationOfSectionRange(TT)) {
1010     ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
1011     auto *ValuesVar = new GlobalVariable(
1012         *M, ValuesTy, false, Linkage, Constant::getNullValue(ValuesTy),
1013         getVarName(Inc, getInstrProfValuesVarPrefix(), Renamed));
1014     ValuesVar->setVisibility(Visibility);
1015     ValuesVar->setSection(
1016         getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
1017     ValuesVar->setAlignment(Align(8));
1018     MaybeSetComdat(ValuesVar);
1019     ValuesPtrExpr =
1020         ConstantExpr::getBitCast(ValuesVar, Type::getInt8PtrTy(Ctx));
1021   }
1022 
1023   if (DebugInfoCorrelate) {
1024     // Mark the counter variable as used so that it isn't optimized out.
1025     CompilerUsedVars.push_back(PD.RegionCounters);
1026     return PD.RegionCounters;
1027   }
1028 
1029   // Create data variable.
1030   auto *IntPtrTy = M->getDataLayout().getIntPtrType(M->getContext());
1031   auto *Int16Ty = Type::getInt16Ty(Ctx);
1032   auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
1033   Type *DataTypes[] = {
1034 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
1035 #include "llvm/ProfileData/InstrProfData.inc"
1036   };
1037   auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
1038 
1039   Constant *FunctionAddr = shouldRecordFunctionAddr(Fn)
1040                                ? ConstantExpr::getBitCast(Fn, Int8PtrTy)
1041                                : ConstantPointerNull::get(Int8PtrTy);
1042 
1043   Constant *Int16ArrayVals[IPVK_Last + 1];
1044   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1045     Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
1046 
1047   // If the data variable is not referenced by code (if we don't emit
1048   // @llvm.instrprof.value.profile, NS will be 0), and the counter keeps the
1049   // data variable live under linker GC, the data variable can be private. This
1050   // optimization applies to ELF.
1051   //
1052   // On COFF, a comdat leader cannot be local so we require DataReferencedByCode
1053   // to be false.
1054   //
1055   // If profd is in a deduplicate comdat, NS==0 with a hash suffix guarantees
1056   // that other copies must have the same CFG and cannot have value profiling.
1057   // If no hash suffix, other profd copies may be referenced by code.
1058   if (NS == 0 && !(DataReferencedByCode && NeedComdat && !Renamed) &&
1059       (TT.isOSBinFormatELF() ||
1060        (!DataReferencedByCode && TT.isOSBinFormatCOFF()))) {
1061     Linkage = GlobalValue::PrivateLinkage;
1062     Visibility = GlobalValue::DefaultVisibility;
1063   }
1064   auto *Data =
1065       new GlobalVariable(*M, DataTy, false, Linkage, nullptr, DataVarName);
1066   // Reference the counter variable with a label difference (link-time
1067   // constant).
1068   auto *RelativeCounterPtr =
1069       ConstantExpr::getSub(ConstantExpr::getPtrToInt(CounterPtr, IntPtrTy),
1070                            ConstantExpr::getPtrToInt(Data, IntPtrTy));
1071 
1072   Constant *DataVals[] = {
1073 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
1074 #include "llvm/ProfileData/InstrProfData.inc"
1075   };
1076   Data->setInitializer(ConstantStruct::get(DataTy, DataVals));
1077 
1078   Data->setVisibility(Visibility);
1079   Data->setSection(getInstrProfSectionName(IPSK_data, TT.getObjectFormat()));
1080   Data->setAlignment(Align(INSTR_PROF_DATA_ALIGNMENT));
1081   MaybeSetComdat(Data);
1082   Data->setLinkage(Linkage);
1083 
1084   PD.DataVar = Data;
1085 
1086   // Mark the data variable as used so that it isn't stripped out.
1087   CompilerUsedVars.push_back(Data);
1088   // Now that the linkage set by the FE has been passed to the data and counter
1089   // variables, reset Name variable's linkage and visibility to private so that
1090   // it can be removed later by the compiler.
1091   NamePtr->setLinkage(GlobalValue::PrivateLinkage);
1092   // Collect the referenced names to be used by emitNameData.
1093   ReferencedNames.push_back(NamePtr);
1094 
1095   return PD.RegionCounters;
1096 }
1097 
1098 void InstrProfiling::emitVNodes() {
1099   if (!ValueProfileStaticAlloc)
1100     return;
1101 
1102   // For now only support this on platforms that do
1103   // not require runtime registration to discover
1104   // named section start/end.
1105   if (needsRuntimeRegistrationOfSectionRange(TT))
1106     return;
1107 
1108   size_t TotalNS = 0;
1109   for (auto &PD : ProfileDataMap) {
1110     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1111       TotalNS += PD.second.NumValueSites[Kind];
1112   }
1113 
1114   if (!TotalNS)
1115     return;
1116 
1117   uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
1118 // Heuristic for small programs with very few total value sites.
1119 // The default value of vp-counters-per-site is chosen based on
1120 // the observation that large apps usually have a low percentage
1121 // of value sites that actually have any profile data, and thus
1122 // the average number of counters per site is low. For small
1123 // apps with very few sites, this may not be true. Bump up the
1124 // number of counters in this case.
1125 #define INSTR_PROF_MIN_VAL_COUNTS 10
1126   if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
1127     NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
1128 
1129   auto &Ctx = M->getContext();
1130   Type *VNodeTypes[] = {
1131 #define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
1132 #include "llvm/ProfileData/InstrProfData.inc"
1133   };
1134   auto *VNodeTy = StructType::get(Ctx, makeArrayRef(VNodeTypes));
1135 
1136   ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
1137   auto *VNodesVar = new GlobalVariable(
1138       *M, VNodesTy, false, GlobalValue::PrivateLinkage,
1139       Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
1140   VNodesVar->setSection(
1141       getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
1142   // VNodesVar is used by runtime but not referenced via relocation by other
1143   // sections. Conservatively make it linker retained.
1144   UsedVars.push_back(VNodesVar);
1145 }
1146 
1147 void InstrProfiling::emitNameData() {
1148   std::string UncompressedData;
1149 
1150   if (ReferencedNames.empty())
1151     return;
1152 
1153   std::string CompressedNameStr;
1154   if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
1155                                           DoInstrProfNameCompression)) {
1156     report_fatal_error(Twine(toString(std::move(E))), false);
1157   }
1158 
1159   auto &Ctx = M->getContext();
1160   auto *NamesVal =
1161       ConstantDataArray::getString(Ctx, StringRef(CompressedNameStr), false);
1162   NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
1163                                 GlobalValue::PrivateLinkage, NamesVal,
1164                                 getInstrProfNamesVarName());
1165   NamesSize = CompressedNameStr.size();
1166   NamesVar->setSection(
1167       getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
1168   // On COFF, it's important to reduce the alignment down to 1 to prevent the
1169   // linker from inserting padding before the start of the names section or
1170   // between names entries.
1171   NamesVar->setAlignment(Align(1));
1172   // NamesVar is used by runtime but not referenced via relocation by other
1173   // sections. Conservatively make it linker retained.
1174   UsedVars.push_back(NamesVar);
1175 
1176   for (auto *NamePtr : ReferencedNames)
1177     NamePtr->eraseFromParent();
1178 }
1179 
1180 void InstrProfiling::emitRegistration() {
1181   if (!needsRuntimeRegistrationOfSectionRange(TT))
1182     return;
1183 
1184   // Construct the function.
1185   auto *VoidTy = Type::getVoidTy(M->getContext());
1186   auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
1187   auto *Int64Ty = Type::getInt64Ty(M->getContext());
1188   auto *RegisterFTy = FunctionType::get(VoidTy, false);
1189   auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
1190                                      getInstrProfRegFuncsName(), M);
1191   RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1192   if (Options.NoRedZone)
1193     RegisterF->addFnAttr(Attribute::NoRedZone);
1194 
1195   auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
1196   auto *RuntimeRegisterF =
1197       Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
1198                        getInstrProfRegFuncName(), M);
1199 
1200   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
1201   for (Value *Data : CompilerUsedVars)
1202     if (!isa<Function>(Data))
1203       IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
1204   for (Value *Data : UsedVars)
1205     if (Data != NamesVar && !isa<Function>(Data))
1206       IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
1207 
1208   if (NamesVar) {
1209     Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
1210     auto *NamesRegisterTy =
1211         FunctionType::get(VoidTy, makeArrayRef(ParamTypes), false);
1212     auto *NamesRegisterF =
1213         Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
1214                          getInstrProfNamesRegFuncName(), M);
1215     IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
1216                                     IRB.getInt64(NamesSize)});
1217   }
1218 
1219   IRB.CreateRetVoid();
1220 }
1221 
1222 bool InstrProfiling::emitRuntimeHook() {
1223   // We expect the linker to be invoked with -u<hook_var> flag for Linux
1224   // in which case there is no need to emit the external variable.
1225   if (TT.isOSLinux())
1226     return false;
1227 
1228   // If the module's provided its own runtime, we don't need to do anything.
1229   if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
1230     return false;
1231 
1232   // Declare an external variable that will pull in the runtime initialization.
1233   auto *Int32Ty = Type::getInt32Ty(M->getContext());
1234   auto *Var =
1235       new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
1236                          nullptr, getInstrProfRuntimeHookVarName());
1237 
1238   if (TT.isOSBinFormatELF()) {
1239     // Mark the user variable as used so that it isn't stripped out.
1240     CompilerUsedVars.push_back(Var);
1241   } else {
1242     // Make a function that uses it.
1243     auto *User = Function::Create(FunctionType::get(Int32Ty, false),
1244                                   GlobalValue::LinkOnceODRLinkage,
1245                                   getInstrProfRuntimeHookVarUseFuncName(), M);
1246     User->addFnAttr(Attribute::NoInline);
1247     if (Options.NoRedZone)
1248       User->addFnAttr(Attribute::NoRedZone);
1249     User->setVisibility(GlobalValue::HiddenVisibility);
1250     if (TT.supportsCOMDAT())
1251       User->setComdat(M->getOrInsertComdat(User->getName()));
1252 
1253     IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
1254     auto *Load = IRB.CreateLoad(Int32Ty, Var);
1255     IRB.CreateRet(Load);
1256 
1257     // Mark the function as used so that it isn't stripped out.
1258     CompilerUsedVars.push_back(User);
1259   }
1260   return true;
1261 }
1262 
1263 void InstrProfiling::emitUses() {
1264   // The metadata sections are parallel arrays. Optimizers (e.g.
1265   // GlobalOpt/ConstantMerge) may not discard associated sections as a unit, so
1266   // we conservatively retain all unconditionally in the compiler.
1267   //
1268   // On ELF and Mach-O, the linker can guarantee the associated sections will be
1269   // retained or discarded as a unit, so llvm.compiler.used is sufficient.
1270   // Similarly on COFF, if prof data is not referenced by code we use one comdat
1271   // and ensure this GC property as well. Otherwise, we have to conservatively
1272   // make all of the sections retained by the linker.
1273   if (TT.isOSBinFormatELF() || TT.isOSBinFormatMachO() ||
1274       (TT.isOSBinFormatCOFF() && !profDataReferencedByCode(*M)))
1275     appendToCompilerUsed(*M, CompilerUsedVars);
1276   else
1277     appendToUsed(*M, CompilerUsedVars);
1278 
1279   // We do not add proper references from used metadata sections to NamesVar and
1280   // VNodesVar, so we have to be conservative and place them in llvm.used
1281   // regardless of the target,
1282   appendToUsed(*M, UsedVars);
1283 }
1284 
1285 void InstrProfiling::emitInitialization() {
1286   // Create ProfileFileName variable. Don't don't this for the
1287   // context-sensitive instrumentation lowering: This lowering is after
1288   // LTO/ThinLTO linking. Pass PGOInstrumentationGenCreateVar should
1289   // have already create the variable before LTO/ThinLTO linking.
1290   if (!IsCS)
1291     createProfileFileNameVar(*M, Options.InstrProfileOutput);
1292   Function *RegisterF = M->getFunction(getInstrProfRegFuncsName());
1293   if (!RegisterF)
1294     return;
1295 
1296   // Create the initialization function.
1297   auto *VoidTy = Type::getVoidTy(M->getContext());
1298   auto *F = Function::Create(FunctionType::get(VoidTy, false),
1299                              GlobalValue::InternalLinkage,
1300                              getInstrProfInitFuncName(), M);
1301   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1302   F->addFnAttr(Attribute::NoInline);
1303   if (Options.NoRedZone)
1304     F->addFnAttr(Attribute::NoRedZone);
1305 
1306   // Add the basic block and the necessary calls.
1307   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
1308   IRB.CreateCall(RegisterF, {});
1309   IRB.CreateRetVoid();
1310 
1311   appendToGlobalCtors(*M, F, 0);
1312 }
1313