10b57cec5SDimitry Andric //===-- InstrProfiling.cpp - Frontend instrumentation based profiling -----===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This pass lowers instrprof_* intrinsics emitted by a frontend for profiling.
100b57cec5SDimitry Andric // It also builds the data structures and initialization code needed for
110b57cec5SDimitry Andric // updating execution counts and emitting the profile at runtime.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
160b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
170b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
180b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
190b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfo.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
230b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
240b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
250b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
260b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
270b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
280eae32dcSDimitry Andric #include "llvm/IR/DIBuilder.h"
290b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
300eae32dcSDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
310b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
320b57cec5SDimitry Andric #include "llvm/IR/Function.h"
330b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
340b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
350b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
360b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
370b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
380b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
390b57cec5SDimitry Andric #include "llvm/IR/Module.h"
400b57cec5SDimitry Andric #include "llvm/IR/Type.h"
41480093f4SDimitry Andric #include "llvm/InitializePasses.h"
420b57cec5SDimitry Andric #include "llvm/Pass.h"
430b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProf.h"
440eae32dcSDimitry Andric #include "llvm/ProfileData/InstrProfCorrelator.h"
450b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
460b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
470b57cec5SDimitry Andric #include "llvm/Support/Error.h"
480b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
49*fe013be4SDimitry Andric #include "llvm/TargetParser/Triple.h"
500b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ModuleUtils.h"
510b57cec5SDimitry Andric #include "llvm/Transforms/Utils/SSAUpdater.h"
520b57cec5SDimitry Andric #include <algorithm>
530b57cec5SDimitry Andric #include <cassert>
540b57cec5SDimitry Andric #include <cstdint>
550b57cec5SDimitry Andric #include <string>
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric using namespace llvm;
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric #define DEBUG_TYPE "instrprof"
600b57cec5SDimitry Andric 
610eae32dcSDimitry Andric namespace llvm {
620eae32dcSDimitry Andric cl::opt<bool>
6381ad6265SDimitry Andric     DebugInfoCorrelate("debug-info-correlate",
640eae32dcSDimitry Andric                        cl::desc("Use debug info to correlate profiles."),
650eae32dcSDimitry Andric                        cl::init(false));
660eae32dcSDimitry Andric } // namespace llvm
670eae32dcSDimitry Andric 
680b57cec5SDimitry Andric namespace {
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric cl::opt<bool> DoHashBasedCounterSplit(
710b57cec5SDimitry Andric     "hash-based-counter-split",
720b57cec5SDimitry Andric     cl::desc("Rename counter variable of a comdat function based on cfg hash"),
730b57cec5SDimitry Andric     cl::init(true));
740b57cec5SDimitry Andric 
754824e7fdSDimitry Andric cl::opt<bool>
764824e7fdSDimitry Andric     RuntimeCounterRelocation("runtime-counter-relocation",
775ffd83dbSDimitry Andric                              cl::desc("Enable relocating counters at runtime."),
785ffd83dbSDimitry Andric                              cl::init(false));
795ffd83dbSDimitry Andric 
800b57cec5SDimitry Andric cl::opt<bool> ValueProfileStaticAlloc(
810b57cec5SDimitry Andric     "vp-static-alloc",
820b57cec5SDimitry Andric     cl::desc("Do static counter allocation for value profiler"),
830b57cec5SDimitry Andric     cl::init(true));
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric cl::opt<double> NumCountersPerValueSite(
860b57cec5SDimitry Andric     "vp-counters-per-site",
870b57cec5SDimitry Andric     cl::desc("The average number of profile counters allocated "
880b57cec5SDimitry Andric              "per value profiling site."),
890b57cec5SDimitry Andric     // This is set to a very small value because in real programs, only
900b57cec5SDimitry Andric     // a very small percentage of value sites have non-zero targets, e.g, 1/30.
910b57cec5SDimitry Andric     // For those sites with non-zero profile, the average number of targets
920b57cec5SDimitry Andric     // is usually smaller than 2.
930b57cec5SDimitry Andric     cl::init(1.0));
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric cl::opt<bool> AtomicCounterUpdateAll(
9681ad6265SDimitry Andric     "instrprof-atomic-counter-update-all",
970b57cec5SDimitry Andric     cl::desc("Make all profile counter updates atomic (for testing only)"),
980b57cec5SDimitry Andric     cl::init(false));
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric cl::opt<bool> AtomicCounterUpdatePromoted(
10181ad6265SDimitry Andric     "atomic-counter-update-promoted",
1020b57cec5SDimitry Andric     cl::desc("Do counter update using atomic fetch add "
1030b57cec5SDimitry Andric              " for promoted counters only"),
1040b57cec5SDimitry Andric     cl::init(false));
1050b57cec5SDimitry Andric 
1065ffd83dbSDimitry Andric cl::opt<bool> AtomicFirstCounter(
10781ad6265SDimitry Andric     "atomic-first-counter",
1085ffd83dbSDimitry Andric     cl::desc("Use atomic fetch add for first counter in a function (usually "
1095ffd83dbSDimitry Andric              "the entry counter)"),
1105ffd83dbSDimitry Andric     cl::init(false));
1115ffd83dbSDimitry Andric 
1120b57cec5SDimitry Andric // If the option is not specified, the default behavior about whether
1130b57cec5SDimitry Andric // counter promotion is done depends on how instrumentaiton lowering
1140b57cec5SDimitry Andric // pipeline is setup, i.e., the default value of true of this option
1150b57cec5SDimitry Andric // does not mean the promotion will be done by default. Explicitly
1160b57cec5SDimitry Andric // setting this option can override the default behavior.
11781ad6265SDimitry Andric cl::opt<bool> DoCounterPromotion("do-counter-promotion",
1180b57cec5SDimitry Andric                                  cl::desc("Do counter register promotion"),
1190b57cec5SDimitry Andric                                  cl::init(false));
1200b57cec5SDimitry Andric cl::opt<unsigned> MaxNumOfPromotionsPerLoop(
12181ad6265SDimitry Andric     "max-counter-promotions-per-loop", cl::init(20),
1220b57cec5SDimitry Andric     cl::desc("Max number counter promotions per loop to avoid"
1230b57cec5SDimitry Andric              " increasing register pressure too much"));
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric // A debug option
1260b57cec5SDimitry Andric cl::opt<int>
12781ad6265SDimitry Andric     MaxNumOfPromotions("max-counter-promotions", cl::init(-1),
1280b57cec5SDimitry Andric                        cl::desc("Max number of allowed counter promotions"));
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric cl::opt<unsigned> SpeculativeCounterPromotionMaxExiting(
13181ad6265SDimitry Andric     "speculative-counter-promotion-max-exiting", cl::init(3),
1320b57cec5SDimitry Andric     cl::desc("The max number of exiting blocks of a loop to allow "
1330b57cec5SDimitry Andric              " speculative counter promotion"));
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric cl::opt<bool> SpeculativeCounterPromotionToLoop(
13681ad6265SDimitry Andric     "speculative-counter-promotion-to-loop",
1370b57cec5SDimitry Andric     cl::desc("When the option is false, if the target block is in a loop, "
1380b57cec5SDimitry Andric              "the promotion will be disallowed unless the promoted counter "
1390b57cec5SDimitry Andric              " update can be further/iteratively promoted into an acyclic "
1400b57cec5SDimitry Andric              " region."));
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric cl::opt<bool> IterativeCounterPromotion(
14381ad6265SDimitry Andric     "iterative-counter-promotion", cl::init(true),
1440b57cec5SDimitry Andric     cl::desc("Allow counter promotion across the whole loop nest."));
1450b57cec5SDimitry Andric 
146e8d8bef9SDimitry Andric cl::opt<bool> SkipRetExitBlock(
14781ad6265SDimitry Andric     "skip-ret-exit-block", cl::init(true),
148e8d8bef9SDimitry Andric     cl::desc("Suppress counter promotion if exit blocks contain ret."));
149e8d8bef9SDimitry Andric 
1500b57cec5SDimitry Andric ///
1510b57cec5SDimitry Andric /// A helper class to promote one counter RMW operation in the loop
1520b57cec5SDimitry Andric /// into register update.
1530b57cec5SDimitry Andric ///
1540b57cec5SDimitry Andric /// RWM update for the counter will be sinked out of the loop after
1550b57cec5SDimitry Andric /// the transformation.
1560b57cec5SDimitry Andric ///
1570b57cec5SDimitry Andric class PGOCounterPromoterHelper : public LoadAndStorePromoter {
1580b57cec5SDimitry Andric public:
1590b57cec5SDimitry Andric   PGOCounterPromoterHelper(
1600b57cec5SDimitry Andric       Instruction *L, Instruction *S, SSAUpdater &SSA, Value *Init,
1610b57cec5SDimitry Andric       BasicBlock *PH, ArrayRef<BasicBlock *> ExitBlocks,
1620b57cec5SDimitry Andric       ArrayRef<Instruction *> InsertPts,
1630b57cec5SDimitry Andric       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
1640b57cec5SDimitry Andric       LoopInfo &LI)
1650b57cec5SDimitry Andric       : LoadAndStorePromoter({L, S}, SSA), Store(S), ExitBlocks(ExitBlocks),
1660b57cec5SDimitry Andric         InsertPts(InsertPts), LoopToCandidates(LoopToCands), LI(LI) {
1670b57cec5SDimitry Andric     assert(isa<LoadInst>(L));
1680b57cec5SDimitry Andric     assert(isa<StoreInst>(S));
1690b57cec5SDimitry Andric     SSA.AddAvailableValue(PH, Init);
1700b57cec5SDimitry Andric   }
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric   void doExtraRewritesBeforeFinalDeletion() override {
1730b57cec5SDimitry Andric     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
1740b57cec5SDimitry Andric       BasicBlock *ExitBlock = ExitBlocks[i];
1750b57cec5SDimitry Andric       Instruction *InsertPos = InsertPts[i];
1760b57cec5SDimitry Andric       // Get LiveIn value into the ExitBlock. If there are multiple
1770b57cec5SDimitry Andric       // predecessors, the value is defined by a PHI node in this
1780b57cec5SDimitry Andric       // block.
1790b57cec5SDimitry Andric       Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1800b57cec5SDimitry Andric       Value *Addr = cast<StoreInst>(Store)->getPointerOperand();
1810b57cec5SDimitry Andric       Type *Ty = LiveInValue->getType();
1820b57cec5SDimitry Andric       IRBuilder<> Builder(InsertPos);
18381ad6265SDimitry Andric       if (auto *AddrInst = dyn_cast_or_null<IntToPtrInst>(Addr)) {
18481ad6265SDimitry Andric         // If isRuntimeCounterRelocationEnabled() is true then the address of
18581ad6265SDimitry Andric         // the store instruction is computed with two instructions in
18681ad6265SDimitry Andric         // InstrProfiling::getCounterAddress(). We need to copy those
18781ad6265SDimitry Andric         // instructions to this block to compute Addr correctly.
18881ad6265SDimitry Andric         // %BiasAdd = add i64 ptrtoint <__profc_>, <__llvm_profile_counter_bias>
18981ad6265SDimitry Andric         // %Addr = inttoptr i64 %BiasAdd to i64*
19081ad6265SDimitry Andric         auto *OrigBiasInst = dyn_cast<BinaryOperator>(AddrInst->getOperand(0));
19181ad6265SDimitry Andric         assert(OrigBiasInst->getOpcode() == Instruction::BinaryOps::Add);
19281ad6265SDimitry Andric         Value *BiasInst = Builder.Insert(OrigBiasInst->clone());
19381ad6265SDimitry Andric         Addr = Builder.CreateIntToPtr(BiasInst, Ty->getPointerTo());
19481ad6265SDimitry Andric       }
1950b57cec5SDimitry Andric       if (AtomicCounterUpdatePromoted)
1960b57cec5SDimitry Andric         // automic update currently can only be promoted across the current
1970b57cec5SDimitry Andric         // loop, not the whole loop nest.
1980b57cec5SDimitry Andric         Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, LiveInValue,
199fe6060f1SDimitry Andric                                 MaybeAlign(),
2000b57cec5SDimitry Andric                                 AtomicOrdering::SequentiallyConsistent);
2010b57cec5SDimitry Andric       else {
2020b57cec5SDimitry Andric         LoadInst *OldVal = Builder.CreateLoad(Ty, Addr, "pgocount.promoted");
2030b57cec5SDimitry Andric         auto *NewVal = Builder.CreateAdd(OldVal, LiveInValue);
2040b57cec5SDimitry Andric         auto *NewStore = Builder.CreateStore(NewVal, Addr);
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric         // Now update the parent loop's candidate list:
2070b57cec5SDimitry Andric         if (IterativeCounterPromotion) {
2080b57cec5SDimitry Andric           auto *TargetLoop = LI.getLoopFor(ExitBlock);
2090b57cec5SDimitry Andric           if (TargetLoop)
2100b57cec5SDimitry Andric             LoopToCandidates[TargetLoop].emplace_back(OldVal, NewStore);
2110b57cec5SDimitry Andric         }
2120b57cec5SDimitry Andric       }
2130b57cec5SDimitry Andric     }
2140b57cec5SDimitry Andric   }
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric private:
2170b57cec5SDimitry Andric   Instruction *Store;
2180b57cec5SDimitry Andric   ArrayRef<BasicBlock *> ExitBlocks;
2190b57cec5SDimitry Andric   ArrayRef<Instruction *> InsertPts;
2200b57cec5SDimitry Andric   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
2210b57cec5SDimitry Andric   LoopInfo &LI;
2220b57cec5SDimitry Andric };
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric /// A helper class to do register promotion for all profile counter
2250b57cec5SDimitry Andric /// updates in a loop.
2260b57cec5SDimitry Andric ///
2270b57cec5SDimitry Andric class PGOCounterPromoter {
2280b57cec5SDimitry Andric public:
2290b57cec5SDimitry Andric   PGOCounterPromoter(
2300b57cec5SDimitry Andric       DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCands,
2310b57cec5SDimitry Andric       Loop &CurLoop, LoopInfo &LI, BlockFrequencyInfo *BFI)
23204eeddc0SDimitry Andric       : LoopToCandidates(LoopToCands), L(CurLoop), LI(LI), BFI(BFI) {
2330b57cec5SDimitry Andric 
2345ffd83dbSDimitry Andric     // Skip collection of ExitBlocks and InsertPts for loops that will not be
2355ffd83dbSDimitry Andric     // able to have counters promoted.
2360b57cec5SDimitry Andric     SmallVector<BasicBlock *, 8> LoopExitBlocks;
2370b57cec5SDimitry Andric     SmallPtrSet<BasicBlock *, 8> BlockSet;
2385ffd83dbSDimitry Andric 
2390b57cec5SDimitry Andric     L.getExitBlocks(LoopExitBlocks);
2405ffd83dbSDimitry Andric     if (!isPromotionPossible(&L, LoopExitBlocks))
2415ffd83dbSDimitry Andric       return;
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric     for (BasicBlock *ExitBlock : LoopExitBlocks) {
2440b57cec5SDimitry Andric       if (BlockSet.insert(ExitBlock).second) {
2450b57cec5SDimitry Andric         ExitBlocks.push_back(ExitBlock);
2460b57cec5SDimitry Andric         InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
2470b57cec5SDimitry Andric       }
2480b57cec5SDimitry Andric     }
2490b57cec5SDimitry Andric   }
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric   bool run(int64_t *NumPromoted) {
2520b57cec5SDimitry Andric     // Skip 'infinite' loops:
2530b57cec5SDimitry Andric     if (ExitBlocks.size() == 0)
2540b57cec5SDimitry Andric       return false;
255e8d8bef9SDimitry Andric 
256e8d8bef9SDimitry Andric     // Skip if any of the ExitBlocks contains a ret instruction.
257e8d8bef9SDimitry Andric     // This is to prevent dumping of incomplete profile -- if the
258e8d8bef9SDimitry Andric     // the loop is a long running loop and dump is called in the middle
259e8d8bef9SDimitry Andric     // of the loop, the result profile is incomplete.
260e8d8bef9SDimitry Andric     // FIXME: add other heuristics to detect long running loops.
261e8d8bef9SDimitry Andric     if (SkipRetExitBlock) {
262bdd1243dSDimitry Andric       for (auto *BB : ExitBlocks)
263e8d8bef9SDimitry Andric         if (isa<ReturnInst>(BB->getTerminator()))
264e8d8bef9SDimitry Andric           return false;
265e8d8bef9SDimitry Andric     }
266e8d8bef9SDimitry Andric 
2670b57cec5SDimitry Andric     unsigned MaxProm = getMaxNumOfPromotionsInLoop(&L);
2680b57cec5SDimitry Andric     if (MaxProm == 0)
2690b57cec5SDimitry Andric       return false;
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric     unsigned Promoted = 0;
2720b57cec5SDimitry Andric     for (auto &Cand : LoopToCandidates[&L]) {
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric       SmallVector<PHINode *, 4> NewPHIs;
2750b57cec5SDimitry Andric       SSAUpdater SSA(&NewPHIs);
2760b57cec5SDimitry Andric       Value *InitVal = ConstantInt::get(Cand.first->getType(), 0);
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric       // If BFI is set, we will use it to guide the promotions.
2790b57cec5SDimitry Andric       if (BFI) {
2800b57cec5SDimitry Andric         auto *BB = Cand.first->getParent();
2810b57cec5SDimitry Andric         auto InstrCount = BFI->getBlockProfileCount(BB);
2820b57cec5SDimitry Andric         if (!InstrCount)
2830b57cec5SDimitry Andric           continue;
2840b57cec5SDimitry Andric         auto PreheaderCount = BFI->getBlockProfileCount(L.getLoopPreheader());
2850b57cec5SDimitry Andric         // If the average loop trip count is not greater than 1.5, we skip
2860b57cec5SDimitry Andric         // promotion.
28781ad6265SDimitry Andric         if (PreheaderCount && (*PreheaderCount * 3) >= (*InstrCount * 2))
2880b57cec5SDimitry Andric           continue;
2890b57cec5SDimitry Andric       }
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric       PGOCounterPromoterHelper Promoter(Cand.first, Cand.second, SSA, InitVal,
2920b57cec5SDimitry Andric                                         L.getLoopPreheader(), ExitBlocks,
2930b57cec5SDimitry Andric                                         InsertPts, LoopToCandidates, LI);
2940b57cec5SDimitry Andric       Promoter.run(SmallVector<Instruction *, 2>({Cand.first, Cand.second}));
2950b57cec5SDimitry Andric       Promoted++;
2960b57cec5SDimitry Andric       if (Promoted >= MaxProm)
2970b57cec5SDimitry Andric         break;
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric       (*NumPromoted)++;
3000b57cec5SDimitry Andric       if (MaxNumOfPromotions != -1 && *NumPromoted >= MaxNumOfPromotions)
3010b57cec5SDimitry Andric         break;
3020b57cec5SDimitry Andric     }
3030b57cec5SDimitry Andric 
3040b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << Promoted << " counters promoted for loop (depth="
3050b57cec5SDimitry Andric                       << L.getLoopDepth() << ")\n");
3060b57cec5SDimitry Andric     return Promoted != 0;
3070b57cec5SDimitry Andric   }
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric private:
3100b57cec5SDimitry Andric   bool allowSpeculativeCounterPromotion(Loop *LP) {
3110b57cec5SDimitry Andric     SmallVector<BasicBlock *, 8> ExitingBlocks;
3120b57cec5SDimitry Andric     L.getExitingBlocks(ExitingBlocks);
3130b57cec5SDimitry Andric     // Not considierered speculative.
3140b57cec5SDimitry Andric     if (ExitingBlocks.size() == 1)
3150b57cec5SDimitry Andric       return true;
3160b57cec5SDimitry Andric     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
3170b57cec5SDimitry Andric       return false;
3180b57cec5SDimitry Andric     return true;
3190b57cec5SDimitry Andric   }
3200b57cec5SDimitry Andric 
3215ffd83dbSDimitry Andric   // Check whether the loop satisfies the basic conditions needed to perform
3225ffd83dbSDimitry Andric   // Counter Promotions.
3234824e7fdSDimitry Andric   bool
3244824e7fdSDimitry Andric   isPromotionPossible(Loop *LP,
3255ffd83dbSDimitry Andric                       const SmallVectorImpl<BasicBlock *> &LoopExitBlocks) {
3260b57cec5SDimitry Andric     // We can't insert into a catchswitch.
3270b57cec5SDimitry Andric     if (llvm::any_of(LoopExitBlocks, [](BasicBlock *Exit) {
3280b57cec5SDimitry Andric           return isa<CatchSwitchInst>(Exit->getTerminator());
3290b57cec5SDimitry Andric         }))
3305ffd83dbSDimitry Andric       return false;
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric     if (!LP->hasDedicatedExits())
3335ffd83dbSDimitry Andric       return false;
3340b57cec5SDimitry Andric 
3350b57cec5SDimitry Andric     BasicBlock *PH = LP->getLoopPreheader();
3360b57cec5SDimitry Andric     if (!PH)
3375ffd83dbSDimitry Andric       return false;
3385ffd83dbSDimitry Andric 
3395ffd83dbSDimitry Andric     return true;
3405ffd83dbSDimitry Andric   }
3415ffd83dbSDimitry Andric 
3425ffd83dbSDimitry Andric   // Returns the max number of Counter Promotions for LP.
3435ffd83dbSDimitry Andric   unsigned getMaxNumOfPromotionsInLoop(Loop *LP) {
3445ffd83dbSDimitry Andric     SmallVector<BasicBlock *, 8> LoopExitBlocks;
3455ffd83dbSDimitry Andric     LP->getExitBlocks(LoopExitBlocks);
3465ffd83dbSDimitry Andric     if (!isPromotionPossible(LP, LoopExitBlocks))
3470b57cec5SDimitry Andric       return 0;
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric     SmallVector<BasicBlock *, 8> ExitingBlocks;
3500b57cec5SDimitry Andric     LP->getExitingBlocks(ExitingBlocks);
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric     // If BFI is set, we do more aggressive promotions based on BFI.
3530b57cec5SDimitry Andric     if (BFI)
3540b57cec5SDimitry Andric       return (unsigned)-1;
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric     // Not considierered speculative.
3570b57cec5SDimitry Andric     if (ExitingBlocks.size() == 1)
3580b57cec5SDimitry Andric       return MaxNumOfPromotionsPerLoop;
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric     if (ExitingBlocks.size() > SpeculativeCounterPromotionMaxExiting)
3610b57cec5SDimitry Andric       return 0;
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric     // Whether the target block is in a loop does not matter:
3640b57cec5SDimitry Andric     if (SpeculativeCounterPromotionToLoop)
3650b57cec5SDimitry Andric       return MaxNumOfPromotionsPerLoop;
3660b57cec5SDimitry Andric 
3670b57cec5SDimitry Andric     // Now check the target block:
3680b57cec5SDimitry Andric     unsigned MaxProm = MaxNumOfPromotionsPerLoop;
3690b57cec5SDimitry Andric     for (auto *TargetBlock : LoopExitBlocks) {
3700b57cec5SDimitry Andric       auto *TargetLoop = LI.getLoopFor(TargetBlock);
3710b57cec5SDimitry Andric       if (!TargetLoop)
3720b57cec5SDimitry Andric         continue;
3730b57cec5SDimitry Andric       unsigned MaxPromForTarget = getMaxNumOfPromotionsInLoop(TargetLoop);
3740b57cec5SDimitry Andric       unsigned PendingCandsInTarget = LoopToCandidates[TargetLoop].size();
3750b57cec5SDimitry Andric       MaxProm =
3760b57cec5SDimitry Andric           std::min(MaxProm, std::max(MaxPromForTarget, PendingCandsInTarget) -
3770b57cec5SDimitry Andric                                 PendingCandsInTarget);
3780b57cec5SDimitry Andric     }
3790b57cec5SDimitry Andric     return MaxProm;
3800b57cec5SDimitry Andric   }
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> &LoopToCandidates;
3830b57cec5SDimitry Andric   SmallVector<BasicBlock *, 8> ExitBlocks;
3840b57cec5SDimitry Andric   SmallVector<Instruction *, 8> InsertPts;
3850b57cec5SDimitry Andric   Loop &L;
3860b57cec5SDimitry Andric   LoopInfo &LI;
3870b57cec5SDimitry Andric   BlockFrequencyInfo *BFI;
3880b57cec5SDimitry Andric };
3890b57cec5SDimitry Andric 
390e8d8bef9SDimitry Andric enum class ValueProfilingCallType {
391e8d8bef9SDimitry Andric   // Individual values are tracked. Currently used for indiret call target
392e8d8bef9SDimitry Andric   // profiling.
393e8d8bef9SDimitry Andric   Default,
394e8d8bef9SDimitry Andric 
395e8d8bef9SDimitry Andric   // MemOp: the memop size value profiling.
396e8d8bef9SDimitry Andric   MemOp
397e8d8bef9SDimitry Andric };
398e8d8bef9SDimitry Andric 
3990b57cec5SDimitry Andric } // end anonymous namespace
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric PreservedAnalyses InstrProfiling::run(Module &M, ModuleAnalysisManager &AM) {
4028bcb0991SDimitry Andric   FunctionAnalysisManager &FAM =
4038bcb0991SDimitry Andric       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
4048bcb0991SDimitry Andric   auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
4058bcb0991SDimitry Andric     return FAM.getResult<TargetLibraryAnalysis>(F);
4068bcb0991SDimitry Andric   };
4078bcb0991SDimitry Andric   if (!run(M, GetTLI))
4080b57cec5SDimitry Andric     return PreservedAnalyses::all();
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric   return PreservedAnalyses::none();
4110b57cec5SDimitry Andric }
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric bool InstrProfiling::lowerIntrinsics(Function *F) {
4140b57cec5SDimitry Andric   bool MadeChange = false;
4150b57cec5SDimitry Andric   PromotionCandidates.clear();
4160b57cec5SDimitry Andric   for (BasicBlock &BB : *F) {
417349cc55cSDimitry Andric     for (Instruction &Instr : llvm::make_early_inc_range(BB)) {
41804eeddc0SDimitry Andric       if (auto *IPIS = dyn_cast<InstrProfIncrementInstStep>(&Instr)) {
41904eeddc0SDimitry Andric         lowerIncrement(IPIS);
4200b57cec5SDimitry Andric         MadeChange = true;
42104eeddc0SDimitry Andric       } else if (auto *IPI = dyn_cast<InstrProfIncrementInst>(&Instr)) {
42204eeddc0SDimitry Andric         lowerIncrement(IPI);
42304eeddc0SDimitry Andric         MadeChange = true;
424*fe013be4SDimitry Andric       } else if (auto *IPC = dyn_cast<InstrProfTimestampInst>(&Instr)) {
425*fe013be4SDimitry Andric         lowerTimestamp(IPC);
426*fe013be4SDimitry Andric         MadeChange = true;
4271fd87a68SDimitry Andric       } else if (auto *IPC = dyn_cast<InstrProfCoverInst>(&Instr)) {
4281fd87a68SDimitry Andric         lowerCover(IPC);
4291fd87a68SDimitry Andric         MadeChange = true;
43004eeddc0SDimitry Andric       } else if (auto *IPVP = dyn_cast<InstrProfValueProfileInst>(&Instr)) {
43104eeddc0SDimitry Andric         lowerValueProfileInst(IPVP);
4320b57cec5SDimitry Andric         MadeChange = true;
4330b57cec5SDimitry Andric       }
4340b57cec5SDimitry Andric     }
4350b57cec5SDimitry Andric   }
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric   if (!MadeChange)
4380b57cec5SDimitry Andric     return false;
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric   promoteCounterLoadStores(F);
4410b57cec5SDimitry Andric   return true;
4420b57cec5SDimitry Andric }
4430b57cec5SDimitry Andric 
4445ffd83dbSDimitry Andric bool InstrProfiling::isRuntimeCounterRelocationEnabled() const {
445fe6060f1SDimitry Andric   // Mach-O don't support weak external references.
446fe6060f1SDimitry Andric   if (TT.isOSBinFormatMachO())
447fe6060f1SDimitry Andric     return false;
448fe6060f1SDimitry Andric 
4495ffd83dbSDimitry Andric   if (RuntimeCounterRelocation.getNumOccurrences() > 0)
4505ffd83dbSDimitry Andric     return RuntimeCounterRelocation;
4515ffd83dbSDimitry Andric 
452fe6060f1SDimitry Andric   // Fuchsia uses runtime counter relocation by default.
4535ffd83dbSDimitry Andric   return TT.isOSFuchsia();
4545ffd83dbSDimitry Andric }
4555ffd83dbSDimitry Andric 
4560b57cec5SDimitry Andric bool InstrProfiling::isCounterPromotionEnabled() const {
4570b57cec5SDimitry Andric   if (DoCounterPromotion.getNumOccurrences() > 0)
4580b57cec5SDimitry Andric     return DoCounterPromotion;
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric   return Options.DoCounterPromotion;
4610b57cec5SDimitry Andric }
4620b57cec5SDimitry Andric 
4630b57cec5SDimitry Andric void InstrProfiling::promoteCounterLoadStores(Function *F) {
4640b57cec5SDimitry Andric   if (!isCounterPromotionEnabled())
4650b57cec5SDimitry Andric     return;
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric   DominatorTree DT(*F);
4680b57cec5SDimitry Andric   LoopInfo LI(DT);
4690b57cec5SDimitry Andric   DenseMap<Loop *, SmallVector<LoadStorePair, 8>> LoopPromotionCandidates;
4700b57cec5SDimitry Andric 
4710b57cec5SDimitry Andric   std::unique_ptr<BlockFrequencyInfo> BFI;
4720b57cec5SDimitry Andric   if (Options.UseBFIInPromotion) {
4730b57cec5SDimitry Andric     std::unique_ptr<BranchProbabilityInfo> BPI;
4748bcb0991SDimitry Andric     BPI.reset(new BranchProbabilityInfo(*F, LI, &GetTLI(*F)));
4750b57cec5SDimitry Andric     BFI.reset(new BlockFrequencyInfo(*F, *BPI, LI));
4760b57cec5SDimitry Andric   }
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   for (const auto &LoadStore : PromotionCandidates) {
4790b57cec5SDimitry Andric     auto *CounterLoad = LoadStore.first;
4800b57cec5SDimitry Andric     auto *CounterStore = LoadStore.second;
4810b57cec5SDimitry Andric     BasicBlock *BB = CounterLoad->getParent();
4820b57cec5SDimitry Andric     Loop *ParentLoop = LI.getLoopFor(BB);
4830b57cec5SDimitry Andric     if (!ParentLoop)
4840b57cec5SDimitry Andric       continue;
4850b57cec5SDimitry Andric     LoopPromotionCandidates[ParentLoop].emplace_back(CounterLoad, CounterStore);
4860b57cec5SDimitry Andric   }
4870b57cec5SDimitry Andric 
4880b57cec5SDimitry Andric   SmallVector<Loop *, 4> Loops = LI.getLoopsInPreorder();
4890b57cec5SDimitry Andric 
4900b57cec5SDimitry Andric   // Do a post-order traversal of the loops so that counter updates can be
4910b57cec5SDimitry Andric   // iteratively hoisted outside the loop nest.
4920b57cec5SDimitry Andric   for (auto *Loop : llvm::reverse(Loops)) {
4930b57cec5SDimitry Andric     PGOCounterPromoter Promoter(LoopPromotionCandidates, *Loop, LI, BFI.get());
4940b57cec5SDimitry Andric     Promoter.run(&TotalCountersPromoted);
4950b57cec5SDimitry Andric   }
4960b57cec5SDimitry Andric }
4970b57cec5SDimitry Andric 
498349cc55cSDimitry Andric static bool needsRuntimeHookUnconditionally(const Triple &TT) {
499349cc55cSDimitry Andric   // On Fuchsia, we only need runtime hook if any counters are present.
500349cc55cSDimitry Andric   if (TT.isOSFuchsia())
501349cc55cSDimitry Andric     return false;
502349cc55cSDimitry Andric 
503349cc55cSDimitry Andric   return true;
504349cc55cSDimitry Andric }
505349cc55cSDimitry Andric 
5060b57cec5SDimitry Andric /// Check if the module contains uses of any profiling intrinsics.
5070b57cec5SDimitry Andric static bool containsProfilingIntrinsics(Module &M) {
50804eeddc0SDimitry Andric   auto containsIntrinsic = [&](int ID) {
50904eeddc0SDimitry Andric     if (auto *F = M.getFunction(Intrinsic::getName(ID)))
51004eeddc0SDimitry Andric       return !F->use_empty();
5110b57cec5SDimitry Andric     return false;
51204eeddc0SDimitry Andric   };
5131fd87a68SDimitry Andric   return containsIntrinsic(llvm::Intrinsic::instrprof_cover) ||
5141fd87a68SDimitry Andric          containsIntrinsic(llvm::Intrinsic::instrprof_increment) ||
51504eeddc0SDimitry Andric          containsIntrinsic(llvm::Intrinsic::instrprof_increment_step) ||
516*fe013be4SDimitry Andric          containsIntrinsic(llvm::Intrinsic::instrprof_timestamp) ||
51704eeddc0SDimitry Andric          containsIntrinsic(llvm::Intrinsic::instrprof_value_profile);
5180b57cec5SDimitry Andric }
5190b57cec5SDimitry Andric 
5208bcb0991SDimitry Andric bool InstrProfiling::run(
5218bcb0991SDimitry Andric     Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI) {
5220b57cec5SDimitry Andric   this->M = &M;
5238bcb0991SDimitry Andric   this->GetTLI = std::move(GetTLI);
5240b57cec5SDimitry Andric   NamesVar = nullptr;
5250b57cec5SDimitry Andric   NamesSize = 0;
5260b57cec5SDimitry Andric   ProfileDataMap.clear();
527fe6060f1SDimitry Andric   CompilerUsedVars.clear();
5280b57cec5SDimitry Andric   UsedVars.clear();
5290b57cec5SDimitry Andric   TT = Triple(M.getTargetTriple());
5300b57cec5SDimitry Andric 
531349cc55cSDimitry Andric   bool MadeChange = false;
532bdd1243dSDimitry Andric   bool NeedsRuntimeHook = needsRuntimeHookUnconditionally(TT);
533bdd1243dSDimitry Andric   if (NeedsRuntimeHook)
534349cc55cSDimitry Andric     MadeChange = emitRuntimeHook();
5350b57cec5SDimitry Andric 
536bdd1243dSDimitry Andric   bool ContainsProfiling = containsProfilingIntrinsics(M);
5370b57cec5SDimitry Andric   GlobalVariable *CoverageNamesVar =
5380b57cec5SDimitry Andric       M.getNamedGlobal(getCoverageUnusedNamesVarName());
539bdd1243dSDimitry Andric   // Improve compile time by avoiding linear scans when there is no work.
540bdd1243dSDimitry Andric   if (!ContainsProfiling && !CoverageNamesVar)
5410b57cec5SDimitry Andric     return MadeChange;
5420b57cec5SDimitry Andric 
5430b57cec5SDimitry Andric   // We did not know how many value sites there would be inside
5440b57cec5SDimitry Andric   // the instrumented function. This is counting the number of instrumented
5450b57cec5SDimitry Andric   // target value sites to enter it as field in the profile data variable.
5460b57cec5SDimitry Andric   for (Function &F : M) {
547*fe013be4SDimitry Andric     InstrProfInstBase *FirstProfInst = nullptr;
5480b57cec5SDimitry Andric     for (BasicBlock &BB : F)
5490b57cec5SDimitry Andric       for (auto I = BB.begin(), E = BB.end(); I != E; I++)
5500b57cec5SDimitry Andric         if (auto *Ind = dyn_cast<InstrProfValueProfileInst>(I))
5510b57cec5SDimitry Andric           computeNumValueSiteCounts(Ind);
552*fe013be4SDimitry Andric         else if (FirstProfInst == nullptr &&
553*fe013be4SDimitry Andric                  (isa<InstrProfIncrementInst>(I) || isa<InstrProfCoverInst>(I)))
554*fe013be4SDimitry Andric           FirstProfInst = dyn_cast<InstrProfInstBase>(I);
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric     // Value profiling intrinsic lowering requires per-function profile data
5570b57cec5SDimitry Andric     // variable to be created first.
558*fe013be4SDimitry Andric     if (FirstProfInst != nullptr)
559*fe013be4SDimitry Andric       static_cast<void>(getOrCreateRegionCounters(FirstProfInst));
5600b57cec5SDimitry Andric   }
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric   for (Function &F : M)
5630b57cec5SDimitry Andric     MadeChange |= lowerIntrinsics(&F);
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric   if (CoverageNamesVar) {
5660b57cec5SDimitry Andric     lowerCoverageData(CoverageNamesVar);
5670b57cec5SDimitry Andric     MadeChange = true;
5680b57cec5SDimitry Andric   }
5690b57cec5SDimitry Andric 
5700b57cec5SDimitry Andric   if (!MadeChange)
5710b57cec5SDimitry Andric     return false;
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric   emitVNodes();
5740b57cec5SDimitry Andric   emitNameData();
575bdd1243dSDimitry Andric 
576bdd1243dSDimitry Andric   // Emit runtime hook for the cases where the target does not unconditionally
577bdd1243dSDimitry Andric   // require pulling in profile runtime, and coverage is enabled on code that is
578bdd1243dSDimitry Andric   // not eliminated by the front-end, e.g. unused functions with internal
579bdd1243dSDimitry Andric   // linkage.
580bdd1243dSDimitry Andric   if (!NeedsRuntimeHook && ContainsProfiling)
581349cc55cSDimitry Andric     emitRuntimeHook();
582bdd1243dSDimitry Andric 
5830b57cec5SDimitry Andric   emitRegistration();
5840b57cec5SDimitry Andric   emitUses();
5850b57cec5SDimitry Andric   emitInitialization();
5860b57cec5SDimitry Andric   return true;
5870b57cec5SDimitry Andric }
5880b57cec5SDimitry Andric 
589e8d8bef9SDimitry Andric static FunctionCallee getOrInsertValueProfilingCall(
590e8d8bef9SDimitry Andric     Module &M, const TargetLibraryInfo &TLI,
591e8d8bef9SDimitry Andric     ValueProfilingCallType CallType = ValueProfilingCallType::Default) {
5920b57cec5SDimitry Andric   LLVMContext &Ctx = M.getContext();
5930b57cec5SDimitry Andric   auto *ReturnTy = Type::getVoidTy(M.getContext());
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric   AttributeList AL;
5960b57cec5SDimitry Andric   if (auto AK = TLI.getExtAttrForI32Param(false))
5970b57cec5SDimitry Andric     AL = AL.addParamAttribute(M.getContext(), 2, AK);
5980b57cec5SDimitry Andric 
599e8d8bef9SDimitry Andric   assert((CallType == ValueProfilingCallType::Default ||
600e8d8bef9SDimitry Andric           CallType == ValueProfilingCallType::MemOp) &&
601e8d8bef9SDimitry Andric          "Must be Default or MemOp");
6020b57cec5SDimitry Andric   Type *ParamTypes[] = {
6030b57cec5SDimitry Andric #define VALUE_PROF_FUNC_PARAM(ParamType, ParamName, ParamLLVMType) ParamLLVMType
6040b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
6050b57cec5SDimitry Andric   };
6060b57cec5SDimitry Andric   auto *ValueProfilingCallTy =
607bdd1243dSDimitry Andric       FunctionType::get(ReturnTy, ArrayRef(ParamTypes), false);
608e8d8bef9SDimitry Andric   StringRef FuncName = CallType == ValueProfilingCallType::Default
609e8d8bef9SDimitry Andric                            ? getInstrProfValueProfFuncName()
610e8d8bef9SDimitry Andric                            : getInstrProfValueProfMemOpFuncName();
611e8d8bef9SDimitry Andric   return M.getOrInsertFunction(FuncName, ValueProfilingCallTy, AL);
6120b57cec5SDimitry Andric }
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric void InstrProfiling::computeNumValueSiteCounts(InstrProfValueProfileInst *Ind) {
6150b57cec5SDimitry Andric   GlobalVariable *Name = Ind->getName();
6160b57cec5SDimitry Andric   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
6170b57cec5SDimitry Andric   uint64_t Index = Ind->getIndex()->getZExtValue();
6184824e7fdSDimitry Andric   auto &PD = ProfileDataMap[Name];
6194824e7fdSDimitry Andric   PD.NumValueSites[ValueKind] =
6204824e7fdSDimitry Andric       std::max(PD.NumValueSites[ValueKind], (uint32_t)(Index + 1));
6210b57cec5SDimitry Andric }
6220b57cec5SDimitry Andric 
6230b57cec5SDimitry Andric void InstrProfiling::lowerValueProfileInst(InstrProfValueProfileInst *Ind) {
6240eae32dcSDimitry Andric   // TODO: Value profiling heavily depends on the data section which is omitted
6250eae32dcSDimitry Andric   // in lightweight mode. We need to move the value profile pointer to the
6260eae32dcSDimitry Andric   // Counter struct to get this working.
6270eae32dcSDimitry Andric   assert(
6280eae32dcSDimitry Andric       !DebugInfoCorrelate &&
6290eae32dcSDimitry Andric       "Value profiling is not yet supported with lightweight instrumentation");
6300b57cec5SDimitry Andric   GlobalVariable *Name = Ind->getName();
6310b57cec5SDimitry Andric   auto It = ProfileDataMap.find(Name);
6320b57cec5SDimitry Andric   assert(It != ProfileDataMap.end() && It->second.DataVar &&
6330b57cec5SDimitry Andric          "value profiling detected in function with no counter incerement");
6340b57cec5SDimitry Andric 
6350b57cec5SDimitry Andric   GlobalVariable *DataVar = It->second.DataVar;
6360b57cec5SDimitry Andric   uint64_t ValueKind = Ind->getValueKind()->getZExtValue();
6370b57cec5SDimitry Andric   uint64_t Index = Ind->getIndex()->getZExtValue();
6380b57cec5SDimitry Andric   for (uint32_t Kind = IPVK_First; Kind < ValueKind; ++Kind)
6390b57cec5SDimitry Andric     Index += It->second.NumValueSites[Kind];
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   IRBuilder<> Builder(Ind);
642e8d8bef9SDimitry Andric   bool IsMemOpSize = (Ind->getValueKind()->getZExtValue() ==
6430b57cec5SDimitry Andric                       llvm::InstrProfValueKind::IPVK_MemOPSize);
6440b57cec5SDimitry Andric   CallInst *Call = nullptr;
6458bcb0991SDimitry Andric   auto *TLI = &GetTLI(*Ind->getFunction());
6465ffd83dbSDimitry Andric 
6475ffd83dbSDimitry Andric   // To support value profiling calls within Windows exception handlers, funclet
6485ffd83dbSDimitry Andric   // information contained within operand bundles needs to be copied over to
6495ffd83dbSDimitry Andric   // the library call. This is required for the IR to be processed by the
6505ffd83dbSDimitry Andric   // WinEHPrepare pass.
6515ffd83dbSDimitry Andric   SmallVector<OperandBundleDef, 1> OpBundles;
6525ffd83dbSDimitry Andric   Ind->getOperandBundlesAsDefs(OpBundles);
653e8d8bef9SDimitry Andric   if (!IsMemOpSize) {
6540b57cec5SDimitry Andric     Value *Args[3] = {Ind->getTargetValue(),
6550b57cec5SDimitry Andric                       Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
6560b57cec5SDimitry Andric                       Builder.getInt32(Index)};
6575ffd83dbSDimitry Andric     Call = Builder.CreateCall(getOrInsertValueProfilingCall(*M, *TLI), Args,
6585ffd83dbSDimitry Andric                               OpBundles);
6590b57cec5SDimitry Andric   } else {
660e8d8bef9SDimitry Andric     Value *Args[3] = {Ind->getTargetValue(),
6610b57cec5SDimitry Andric                       Builder.CreateBitCast(DataVar, Builder.getInt8PtrTy()),
662e8d8bef9SDimitry Andric                       Builder.getInt32(Index)};
663e8d8bef9SDimitry Andric     Call = Builder.CreateCall(
664e8d8bef9SDimitry Andric         getOrInsertValueProfilingCall(*M, *TLI, ValueProfilingCallType::MemOp),
6655ffd83dbSDimitry Andric         Args, OpBundles);
6660b57cec5SDimitry Andric   }
6670b57cec5SDimitry Andric   if (auto AK = TLI->getExtAttrForI32Param(false))
6680b57cec5SDimitry Andric     Call->addParamAttr(2, AK);
6690b57cec5SDimitry Andric   Ind->replaceAllUsesWith(Call);
6700b57cec5SDimitry Andric   Ind->eraseFromParent();
6710b57cec5SDimitry Andric }
6720b57cec5SDimitry Andric 
6731fd87a68SDimitry Andric Value *InstrProfiling::getCounterAddress(InstrProfInstBase *I) {
6741fd87a68SDimitry Andric   auto *Counters = getOrCreateRegionCounters(I);
6751fd87a68SDimitry Andric   IRBuilder<> Builder(I);
6760b57cec5SDimitry Andric 
677*fe013be4SDimitry Andric   if (isa<InstrProfTimestampInst>(I))
678*fe013be4SDimitry Andric     Counters->setAlignment(Align(8));
679*fe013be4SDimitry Andric 
6801fd87a68SDimitry Andric   auto *Addr = Builder.CreateConstInBoundsGEP2_32(
6811fd87a68SDimitry Andric       Counters->getValueType(), Counters, 0, I->getIndex()->getZExtValue());
6820b57cec5SDimitry Andric 
6831fd87a68SDimitry Andric   if (!isRuntimeCounterRelocationEnabled())
6841fd87a68SDimitry Andric     return Addr;
6851fd87a68SDimitry Andric 
6865ffd83dbSDimitry Andric   Type *Int64Ty = Type::getInt64Ty(M->getContext());
6871fd87a68SDimitry Andric   Function *Fn = I->getParent()->getParent();
68881ad6265SDimitry Andric   LoadInst *&BiasLI = FunctionToProfileBiasMap[Fn];
68981ad6265SDimitry Andric   if (!BiasLI) {
69081ad6265SDimitry Andric     IRBuilder<> EntryBuilder(&Fn->getEntryBlock().front());
6911fd87a68SDimitry Andric     auto *Bias = M->getGlobalVariable(getInstrProfCounterBiasVarName());
6925ffd83dbSDimitry Andric     if (!Bias) {
693fe6060f1SDimitry Andric       // Compiler must define this variable when runtime counter relocation
694fe6060f1SDimitry Andric       // is being used. Runtime has a weak external reference that is used
695fe6060f1SDimitry Andric       // to check whether that's the case or not.
6964824e7fdSDimitry Andric       Bias = new GlobalVariable(
6974824e7fdSDimitry Andric           *M, Int64Ty, false, GlobalValue::LinkOnceODRLinkage,
6984824e7fdSDimitry Andric           Constant::getNullValue(Int64Ty), getInstrProfCounterBiasVarName());
6995ffd83dbSDimitry Andric       Bias->setVisibility(GlobalVariable::HiddenVisibility);
700fe6060f1SDimitry Andric       // A definition that's weak (linkonce_odr) without being in a COMDAT
701fe6060f1SDimitry Andric       // section wouldn't lead to link errors, but it would lead to a dead
702fe6060f1SDimitry Andric       // data word from every TU but one. Putting it in COMDAT ensures there
703fe6060f1SDimitry Andric       // will be exactly one data slot in the link.
704fe6060f1SDimitry Andric       if (TT.supportsCOMDAT())
705fe6060f1SDimitry Andric         Bias->setComdat(M->getOrInsertComdat(Bias->getName()));
7065ffd83dbSDimitry Andric     }
70781ad6265SDimitry Andric     BiasLI = EntryBuilder.CreateLoad(Int64Ty, Bias);
7085ffd83dbSDimitry Andric   }
70981ad6265SDimitry Andric   auto *Add = Builder.CreateAdd(Builder.CreatePtrToInt(Addr, Int64Ty), BiasLI);
7101fd87a68SDimitry Andric   return Builder.CreateIntToPtr(Add, Addr->getType());
7115ffd83dbSDimitry Andric }
7125ffd83dbSDimitry Andric 
7131fd87a68SDimitry Andric void InstrProfiling::lowerCover(InstrProfCoverInst *CoverInstruction) {
7141fd87a68SDimitry Andric   auto *Addr = getCounterAddress(CoverInstruction);
7151fd87a68SDimitry Andric   IRBuilder<> Builder(CoverInstruction);
7161fd87a68SDimitry Andric   // We store zero to represent that this block is covered.
7171fd87a68SDimitry Andric   Builder.CreateStore(Builder.getInt8(0), Addr);
7181fd87a68SDimitry Andric   CoverInstruction->eraseFromParent();
7191fd87a68SDimitry Andric }
7201fd87a68SDimitry Andric 
721*fe013be4SDimitry Andric void InstrProfiling::lowerTimestamp(
722*fe013be4SDimitry Andric     InstrProfTimestampInst *TimestampInstruction) {
723*fe013be4SDimitry Andric   assert(TimestampInstruction->getIndex()->isZeroValue() &&
724*fe013be4SDimitry Andric          "timestamp probes are always the first probe for a function");
725*fe013be4SDimitry Andric   auto &Ctx = M->getContext();
726*fe013be4SDimitry Andric   auto *TimestampAddr = getCounterAddress(TimestampInstruction);
727*fe013be4SDimitry Andric   IRBuilder<> Builder(TimestampInstruction);
728*fe013be4SDimitry Andric   auto *CalleeTy =
729*fe013be4SDimitry Andric       FunctionType::get(Type::getVoidTy(Ctx), TimestampAddr->getType(), false);
730*fe013be4SDimitry Andric   auto Callee = M->getOrInsertFunction(
731*fe013be4SDimitry Andric       INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_SET_TIMESTAMP), CalleeTy);
732*fe013be4SDimitry Andric   Builder.CreateCall(Callee, {TimestampAddr});
733*fe013be4SDimitry Andric   TimestampInstruction->eraseFromParent();
734*fe013be4SDimitry Andric }
735*fe013be4SDimitry Andric 
7361fd87a68SDimitry Andric void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
7371fd87a68SDimitry Andric   auto *Addr = getCounterAddress(Inc);
7381fd87a68SDimitry Andric 
7391fd87a68SDimitry Andric   IRBuilder<> Builder(Inc);
7405ffd83dbSDimitry Andric   if (Options.Atomic || AtomicCounterUpdateAll ||
7411fd87a68SDimitry Andric       (Inc->getIndex()->isZeroValue() && AtomicFirstCounter)) {
7420b57cec5SDimitry Andric     Builder.CreateAtomicRMW(AtomicRMWInst::Add, Addr, Inc->getStep(),
743fe6060f1SDimitry Andric                             MaybeAlign(), AtomicOrdering::Monotonic);
7440b57cec5SDimitry Andric   } else {
7450b57cec5SDimitry Andric     Value *IncStep = Inc->getStep();
7460b57cec5SDimitry Andric     Value *Load = Builder.CreateLoad(IncStep->getType(), Addr, "pgocount");
7470b57cec5SDimitry Andric     auto *Count = Builder.CreateAdd(Load, Inc->getStep());
7480b57cec5SDimitry Andric     auto *Store = Builder.CreateStore(Count, Addr);
7490b57cec5SDimitry Andric     if (isCounterPromotionEnabled())
7500b57cec5SDimitry Andric       PromotionCandidates.emplace_back(cast<Instruction>(Load), Store);
7510b57cec5SDimitry Andric   }
7520b57cec5SDimitry Andric   Inc->eraseFromParent();
7530b57cec5SDimitry Andric }
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageNamesVar) {
7560b57cec5SDimitry Andric   ConstantArray *Names =
7570b57cec5SDimitry Andric       cast<ConstantArray>(CoverageNamesVar->getInitializer());
7580b57cec5SDimitry Andric   for (unsigned I = 0, E = Names->getNumOperands(); I < E; ++I) {
7590b57cec5SDimitry Andric     Constant *NC = Names->getOperand(I);
7600b57cec5SDimitry Andric     Value *V = NC->stripPointerCasts();
7610b57cec5SDimitry Andric     assert(isa<GlobalVariable>(V) && "Missing reference to function name");
7620b57cec5SDimitry Andric     GlobalVariable *Name = cast<GlobalVariable>(V);
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric     Name->setLinkage(GlobalValue::PrivateLinkage);
7650b57cec5SDimitry Andric     ReferencedNames.push_back(Name);
76681ad6265SDimitry Andric     if (isa<ConstantExpr>(NC))
7670b57cec5SDimitry Andric       NC->dropAllReferences();
7680b57cec5SDimitry Andric   }
7690b57cec5SDimitry Andric   CoverageNamesVar->eraseFromParent();
7700b57cec5SDimitry Andric }
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric /// Get the name of a profiling variable for a particular function.
77304eeddc0SDimitry Andric static std::string getVarName(InstrProfInstBase *Inc, StringRef Prefix,
774349cc55cSDimitry Andric                               bool &Renamed) {
7750b57cec5SDimitry Andric   StringRef NamePrefix = getInstrProfNameVarPrefix();
7760b57cec5SDimitry Andric   StringRef Name = Inc->getName()->getName().substr(NamePrefix.size());
7770b57cec5SDimitry Andric   Function *F = Inc->getParent()->getParent();
7780b57cec5SDimitry Andric   Module *M = F->getParent();
7790b57cec5SDimitry Andric   if (!DoHashBasedCounterSplit || !isIRPGOFlagSet(M) ||
780349cc55cSDimitry Andric       !canRenameComdatFunc(*F)) {
781349cc55cSDimitry Andric     Renamed = false;
7820b57cec5SDimitry Andric     return (Prefix + Name).str();
783349cc55cSDimitry Andric   }
784349cc55cSDimitry Andric   Renamed = true;
7850b57cec5SDimitry Andric   uint64_t FuncHash = Inc->getHash()->getZExtValue();
7860b57cec5SDimitry Andric   SmallVector<char, 24> HashPostfix;
7870b57cec5SDimitry Andric   if (Name.endswith((Twine(".") + Twine(FuncHash)).toStringRef(HashPostfix)))
7880b57cec5SDimitry Andric     return (Prefix + Name).str();
7890b57cec5SDimitry Andric   return (Prefix + Name + "." + Twine(FuncHash)).str();
7900b57cec5SDimitry Andric }
7910b57cec5SDimitry Andric 
792fe6060f1SDimitry Andric static uint64_t getIntModuleFlagOrZero(const Module &M, StringRef Flag) {
793fe6060f1SDimitry Andric   auto *MD = dyn_cast_or_null<ConstantAsMetadata>(M.getModuleFlag(Flag));
794fe6060f1SDimitry Andric   if (!MD)
795fe6060f1SDimitry Andric     return 0;
796fe6060f1SDimitry Andric 
797fe6060f1SDimitry Andric   // If the flag is a ConstantAsMetadata, it should be an integer representable
798fe6060f1SDimitry Andric   // in 64-bits.
799fe6060f1SDimitry Andric   return cast<ConstantInt>(MD->getValue())->getZExtValue();
800fe6060f1SDimitry Andric }
801fe6060f1SDimitry Andric 
802fe6060f1SDimitry Andric static bool enablesValueProfiling(const Module &M) {
803fe6060f1SDimitry Andric   return isIRPGOFlagSet(&M) ||
804fe6060f1SDimitry Andric          getIntModuleFlagOrZero(M, "EnableValueProfiling") != 0;
805fe6060f1SDimitry Andric }
806fe6060f1SDimitry Andric 
807fe6060f1SDimitry Andric // Conservatively returns true if data variables may be referenced by code.
808fe6060f1SDimitry Andric static bool profDataReferencedByCode(const Module &M) {
809fe6060f1SDimitry Andric   return enablesValueProfiling(M);
810fe6060f1SDimitry Andric }
811fe6060f1SDimitry Andric 
8120b57cec5SDimitry Andric static inline bool shouldRecordFunctionAddr(Function *F) {
813fe6060f1SDimitry Andric   // Only record function addresses if IR PGO is enabled or if clang value
814fe6060f1SDimitry Andric   // profiling is enabled. Recording function addresses greatly increases object
815fe6060f1SDimitry Andric   // file size, because it prevents the inliner from deleting functions that
816fe6060f1SDimitry Andric   // have been inlined everywhere.
817fe6060f1SDimitry Andric   if (!profDataReferencedByCode(*F->getParent()))
818fe6060f1SDimitry Andric     return false;
819fe6060f1SDimitry Andric 
8200b57cec5SDimitry Andric   // Check the linkage
8210b57cec5SDimitry Andric   bool HasAvailableExternallyLinkage = F->hasAvailableExternallyLinkage();
8220b57cec5SDimitry Andric   if (!F->hasLinkOnceLinkage() && !F->hasLocalLinkage() &&
8230b57cec5SDimitry Andric       !HasAvailableExternallyLinkage)
8240b57cec5SDimitry Andric     return true;
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric   // A function marked 'alwaysinline' with available_externally linkage can't
8270b57cec5SDimitry Andric   // have its address taken. Doing so would create an undefined external ref to
8280b57cec5SDimitry Andric   // the function, which would fail to link.
8290b57cec5SDimitry Andric   if (HasAvailableExternallyLinkage &&
8300b57cec5SDimitry Andric       F->hasFnAttribute(Attribute::AlwaysInline))
8310b57cec5SDimitry Andric     return false;
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric   // Prohibit function address recording if the function is both internal and
8340b57cec5SDimitry Andric   // COMDAT. This avoids the profile data variable referencing internal symbols
8350b57cec5SDimitry Andric   // in COMDAT.
8360b57cec5SDimitry Andric   if (F->hasLocalLinkage() && F->hasComdat())
8370b57cec5SDimitry Andric     return false;
8380b57cec5SDimitry Andric 
8390b57cec5SDimitry Andric   // Check uses of this function for other than direct calls or invokes to it.
8400b57cec5SDimitry Andric   // Inline virtual functions have linkeOnceODR linkage. When a key method
8410b57cec5SDimitry Andric   // exists, the vtable will only be emitted in the TU where the key method
8420b57cec5SDimitry Andric   // is defined. In a TU where vtable is not available, the function won't
8430b57cec5SDimitry Andric   // be 'addresstaken'. If its address is not recorded here, the profile data
8440b57cec5SDimitry Andric   // with missing address may be picked by the linker leading  to missing
8450b57cec5SDimitry Andric   // indirect call target info.
8460b57cec5SDimitry Andric   return F->hasAddressTaken() || F->hasLinkOnceLinkage();
8470b57cec5SDimitry Andric }
8480b57cec5SDimitry Andric 
849*fe013be4SDimitry Andric static inline bool shouldUsePublicSymbol(Function *Fn) {
850*fe013be4SDimitry Andric   // It isn't legal to make an alias of this function at all
851*fe013be4SDimitry Andric   if (Fn->isDeclarationForLinker())
852*fe013be4SDimitry Andric     return true;
853*fe013be4SDimitry Andric 
854*fe013be4SDimitry Andric   // Symbols with local linkage can just use the symbol directly without
855*fe013be4SDimitry Andric   // introducing relocations
856*fe013be4SDimitry Andric   if (Fn->hasLocalLinkage())
857*fe013be4SDimitry Andric     return true;
858*fe013be4SDimitry Andric 
859*fe013be4SDimitry Andric   // PGO + ThinLTO + CFI cause duplicate symbols to be introduced due to some
860*fe013be4SDimitry Andric   // unfavorable interaction between the new alias and the alias renaming done
861*fe013be4SDimitry Andric   // in LowerTypeTests under ThinLTO. For comdat functions that would normally
862*fe013be4SDimitry Andric   // be deduplicated, but the renaming scheme ends up preventing renaming, since
863*fe013be4SDimitry Andric   // it creates unique names for each alias, resulting in duplicated symbols. In
864*fe013be4SDimitry Andric   // the future, we should update the CFI related passes to migrate these
865*fe013be4SDimitry Andric   // aliases to the same module as the jump-table they refer to will be defined.
866*fe013be4SDimitry Andric   if (Fn->hasMetadata(LLVMContext::MD_type))
867*fe013be4SDimitry Andric     return true;
868*fe013be4SDimitry Andric 
869*fe013be4SDimitry Andric   // For comdat functions, an alias would need the same linkage as the original
870*fe013be4SDimitry Andric   // function and hidden visibility. There is no point in adding an alias with
871*fe013be4SDimitry Andric   // identical linkage an visibility to avoid introducing symbolic relocations.
872*fe013be4SDimitry Andric   if (Fn->hasComdat() &&
873*fe013be4SDimitry Andric       (Fn->getVisibility() == GlobalValue::VisibilityTypes::HiddenVisibility))
874*fe013be4SDimitry Andric     return true;
875*fe013be4SDimitry Andric 
876*fe013be4SDimitry Andric   // its OK to use an alias
877*fe013be4SDimitry Andric   return false;
878*fe013be4SDimitry Andric }
879*fe013be4SDimitry Andric 
880*fe013be4SDimitry Andric static inline Constant *getFuncAddrForProfData(Function *Fn) {
881*fe013be4SDimitry Andric   auto *Int8PtrTy = Type::getInt8PtrTy(Fn->getContext());
882*fe013be4SDimitry Andric   // Store a nullptr in __llvm_profd, if we shouldn't use a real address
883*fe013be4SDimitry Andric   if (!shouldRecordFunctionAddr(Fn))
884*fe013be4SDimitry Andric     return ConstantPointerNull::get(Int8PtrTy);
885*fe013be4SDimitry Andric 
886*fe013be4SDimitry Andric   // If we can't use an alias, we must use the public symbol, even though this
887*fe013be4SDimitry Andric   // may require a symbolic relocation.
888*fe013be4SDimitry Andric   if (shouldUsePublicSymbol(Fn))
889*fe013be4SDimitry Andric     return ConstantExpr::getBitCast(Fn, Int8PtrTy);
890*fe013be4SDimitry Andric 
891*fe013be4SDimitry Andric   // When possible use a private alias to avoid symbolic relocations.
892*fe013be4SDimitry Andric   auto *GA = GlobalAlias::create(GlobalValue::LinkageTypes::PrivateLinkage,
893*fe013be4SDimitry Andric                                  Fn->getName() + ".local", Fn);
894*fe013be4SDimitry Andric 
895*fe013be4SDimitry Andric   // When the instrumented function is a COMDAT function, we cannot use a
896*fe013be4SDimitry Andric   // private alias. If we did, we would create reference to a local label in
897*fe013be4SDimitry Andric   // this function's section. If this version of the function isn't selected by
898*fe013be4SDimitry Andric   // the linker, then the metadata would introduce a reference to a discarded
899*fe013be4SDimitry Andric   // section. So, for COMDAT functions, we need to adjust the linkage of the
900*fe013be4SDimitry Andric   // alias. Using hidden visibility avoids a dynamic relocation and an entry in
901*fe013be4SDimitry Andric   // the dynamic symbol table.
902*fe013be4SDimitry Andric   //
903*fe013be4SDimitry Andric   // Note that this handles COMDAT functions with visibility other than Hidden,
904*fe013be4SDimitry Andric   // since that case is covered in shouldUsePublicSymbol()
905*fe013be4SDimitry Andric   if (Fn->hasComdat()) {
906*fe013be4SDimitry Andric     GA->setLinkage(Fn->getLinkage());
907*fe013be4SDimitry Andric     GA->setVisibility(GlobalValue::VisibilityTypes::HiddenVisibility);
908*fe013be4SDimitry Andric   }
909*fe013be4SDimitry Andric 
910*fe013be4SDimitry Andric   // appendToCompilerUsed(*Fn->getParent(), {GA});
911*fe013be4SDimitry Andric 
912*fe013be4SDimitry Andric   return ConstantExpr::getBitCast(GA, Int8PtrTy);
913*fe013be4SDimitry Andric }
914*fe013be4SDimitry Andric 
9150b57cec5SDimitry Andric static bool needsRuntimeRegistrationOfSectionRange(const Triple &TT) {
9160b57cec5SDimitry Andric   // Don't do this for Darwin.  compiler-rt uses linker magic.
9170b57cec5SDimitry Andric   if (TT.isOSDarwin())
9180b57cec5SDimitry Andric     return false;
9190b57cec5SDimitry Andric   // Use linker script magic to get data/cnts/name start/end.
92081ad6265SDimitry Andric   if (TT.isOSAIX() || TT.isOSLinux() || TT.isOSFreeBSD() || TT.isOSNetBSD() ||
92181ad6265SDimitry Andric       TT.isOSSolaris() || TT.isOSFuchsia() || TT.isPS() || TT.isOSWindows())
9220b57cec5SDimitry Andric     return false;
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric   return true;
9250b57cec5SDimitry Andric }
9260b57cec5SDimitry Andric 
9270b57cec5SDimitry Andric GlobalVariable *
9281fd87a68SDimitry Andric InstrProfiling::createRegionCounters(InstrProfInstBase *Inc, StringRef Name,
9291fd87a68SDimitry Andric                                      GlobalValue::LinkageTypes Linkage) {
9301fd87a68SDimitry Andric   uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
9311fd87a68SDimitry Andric   auto &Ctx = M->getContext();
9321fd87a68SDimitry Andric   GlobalVariable *GV;
9331fd87a68SDimitry Andric   if (isa<InstrProfCoverInst>(Inc)) {
9341fd87a68SDimitry Andric     auto *CounterTy = Type::getInt8Ty(Ctx);
9351fd87a68SDimitry Andric     auto *CounterArrTy = ArrayType::get(CounterTy, NumCounters);
9361fd87a68SDimitry Andric     // TODO: `Constant::getAllOnesValue()` does not yet accept an array type.
9371fd87a68SDimitry Andric     std::vector<Constant *> InitialValues(NumCounters,
9381fd87a68SDimitry Andric                                           Constant::getAllOnesValue(CounterTy));
9391fd87a68SDimitry Andric     GV = new GlobalVariable(*M, CounterArrTy, false, Linkage,
9401fd87a68SDimitry Andric                             ConstantArray::get(CounterArrTy, InitialValues),
9411fd87a68SDimitry Andric                             Name);
9421fd87a68SDimitry Andric     GV->setAlignment(Align(1));
9431fd87a68SDimitry Andric   } else {
9441fd87a68SDimitry Andric     auto *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
9451fd87a68SDimitry Andric     GV = new GlobalVariable(*M, CounterTy, false, Linkage,
9461fd87a68SDimitry Andric                             Constant::getNullValue(CounterTy), Name);
9471fd87a68SDimitry Andric     GV->setAlignment(Align(8));
9481fd87a68SDimitry Andric   }
9491fd87a68SDimitry Andric   return GV;
9501fd87a68SDimitry Andric }
9511fd87a68SDimitry Andric 
9521fd87a68SDimitry Andric GlobalVariable *
95304eeddc0SDimitry Andric InstrProfiling::getOrCreateRegionCounters(InstrProfInstBase *Inc) {
9540b57cec5SDimitry Andric   GlobalVariable *NamePtr = Inc->getName();
9554824e7fdSDimitry Andric   auto &PD = ProfileDataMap[NamePtr];
9564824e7fdSDimitry Andric   if (PD.RegionCounters)
9574824e7fdSDimitry Andric     return PD.RegionCounters;
9580b57cec5SDimitry Andric 
959fe6060f1SDimitry Andric   // Match the linkage and visibility of the name global.
9600b57cec5SDimitry Andric   Function *Fn = Inc->getParent()->getParent();
9610b57cec5SDimitry Andric   GlobalValue::LinkageTypes Linkage = NamePtr->getLinkage();
9620b57cec5SDimitry Andric   GlobalValue::VisibilityTypes Visibility = NamePtr->getVisibility();
9630b57cec5SDimitry Andric 
9640eae32dcSDimitry Andric   // Use internal rather than private linkage so the counter variable shows up
9650eae32dcSDimitry Andric   // in the symbol table when using debug info for correlation.
9660eae32dcSDimitry Andric   if (DebugInfoCorrelate && TT.isOSBinFormatMachO() &&
9670eae32dcSDimitry Andric       Linkage == GlobalValue::PrivateLinkage)
9680eae32dcSDimitry Andric     Linkage = GlobalValue::InternalLinkage;
9690eae32dcSDimitry Andric 
970349cc55cSDimitry Andric   // Due to the limitation of binder as of 2021/09/28, the duplicate weak
971349cc55cSDimitry Andric   // symbols in the same csect won't be discarded. When there are duplicate weak
972349cc55cSDimitry Andric   // symbols, we can NOT guarantee that the relocations get resolved to the
973349cc55cSDimitry Andric   // intended weak symbol, so we can not ensure the correctness of the relative
974349cc55cSDimitry Andric   // CounterPtr, so we have to use private linkage for counter and data symbols.
975349cc55cSDimitry Andric   if (TT.isOSBinFormatXCOFF()) {
976349cc55cSDimitry Andric     Linkage = GlobalValue::PrivateLinkage;
977349cc55cSDimitry Andric     Visibility = GlobalValue::DefaultVisibility;
978349cc55cSDimitry Andric   }
9790b57cec5SDimitry Andric   // Move the name variable to the right section. Place them in a COMDAT group
9800b57cec5SDimitry Andric   // if the associated function is a COMDAT. This will make sure that only one
9810b57cec5SDimitry Andric   // copy of counters of the COMDAT function will be emitted after linking. Keep
9820b57cec5SDimitry Andric   // in mind that this pass may run before the inliner, so we need to create a
9830b57cec5SDimitry Andric   // new comdat group for the counters and profiling data. If we use the comdat
9840b57cec5SDimitry Andric   // of the parent function, that will result in relocations against discarded
9850b57cec5SDimitry Andric   // sections.
986fe6060f1SDimitry Andric   //
987fe6060f1SDimitry Andric   // If the data variable is referenced by code,  counters and data have to be
988fe6060f1SDimitry Andric   // in different comdats for COFF because the Visual C++ linker will report
989fe6060f1SDimitry Andric   // duplicate symbol errors if there are multiple external symbols with the
990fe6060f1SDimitry Andric   // same name marked IMAGE_COMDAT_SELECT_ASSOCIATIVE.
991fe6060f1SDimitry Andric   //
992fe6060f1SDimitry Andric   // For ELF, when not using COMDAT, put counters, data and values into a
993fe6060f1SDimitry Andric   // nodeduplicate COMDAT which is lowered to a zero-flag section group. This
994fe6060f1SDimitry Andric   // allows -z start-stop-gc to discard the entire group when the function is
995fe6060f1SDimitry Andric   // discarded.
996fe6060f1SDimitry Andric   bool DataReferencedByCode = profDataReferencedByCode(*M);
997c14a5a88SDimitry Andric   bool NeedComdat = needsComdatForCounter(*Fn, *M);
998349cc55cSDimitry Andric   bool Renamed;
999349cc55cSDimitry Andric   std::string CntsVarName =
1000349cc55cSDimitry Andric       getVarName(Inc, getInstrProfCountersVarPrefix(), Renamed);
1001349cc55cSDimitry Andric   std::string DataVarName =
1002349cc55cSDimitry Andric       getVarName(Inc, getInstrProfDataVarPrefix(), Renamed);
1003fe6060f1SDimitry Andric   auto MaybeSetComdat = [&](GlobalVariable *GV) {
1004fe6060f1SDimitry Andric     bool UseComdat = (NeedComdat || TT.isOSBinFormatELF());
1005fe6060f1SDimitry Andric     if (UseComdat) {
1006fe6060f1SDimitry Andric       StringRef GroupName = TT.isOSBinFormatCOFF() && DataReferencedByCode
1007fe6060f1SDimitry Andric                                 ? GV->getName()
1008fe6060f1SDimitry Andric                                 : CntsVarName;
1009fe6060f1SDimitry Andric       Comdat *C = M->getOrInsertComdat(GroupName);
1010fe6060f1SDimitry Andric       if (!NeedComdat)
1011fe6060f1SDimitry Andric         C->setSelectionKind(Comdat::NoDeduplicate);
1012fe6060f1SDimitry Andric       GV->setComdat(C);
1013bdd1243dSDimitry Andric       // COFF doesn't allow the comdat group leader to have private linkage, so
1014bdd1243dSDimitry Andric       // upgrade private linkage to internal linkage to produce a symbol table
1015bdd1243dSDimitry Andric       // entry.
1016bdd1243dSDimitry Andric       if (TT.isOSBinFormatCOFF() && GV->hasPrivateLinkage())
1017bdd1243dSDimitry Andric         GV->setLinkage(GlobalValue::InternalLinkage);
1018fe6060f1SDimitry Andric     }
1019c14a5a88SDimitry Andric   };
10200b57cec5SDimitry Andric 
10210b57cec5SDimitry Andric   uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
10220b57cec5SDimitry Andric   LLVMContext &Ctx = M->getContext();
10230b57cec5SDimitry Andric 
10241fd87a68SDimitry Andric   auto *CounterPtr = createRegionCounters(Inc, CntsVarName, Linkage);
10250b57cec5SDimitry Andric   CounterPtr->setVisibility(Visibility);
10260b57cec5SDimitry Andric   CounterPtr->setSection(
10270b57cec5SDimitry Andric       getInstrProfSectionName(IPSK_cnts, TT.getObjectFormat()));
1028c14a5a88SDimitry Andric   CounterPtr->setLinkage(Linkage);
1029bdd1243dSDimitry Andric   MaybeSetComdat(CounterPtr);
10304824e7fdSDimitry Andric   PD.RegionCounters = CounterPtr;
10310eae32dcSDimitry Andric   if (DebugInfoCorrelate) {
10320eae32dcSDimitry Andric     if (auto *SP = Fn->getSubprogram()) {
10330eae32dcSDimitry Andric       DIBuilder DB(*M, true, SP->getUnit());
10340eae32dcSDimitry Andric       Metadata *FunctionNameAnnotation[] = {
10350eae32dcSDimitry Andric           MDString::get(Ctx, InstrProfCorrelator::FunctionNameAttributeName),
10360eae32dcSDimitry Andric           MDString::get(Ctx, getPGOFuncNameVarInitializer(NamePtr)),
10370eae32dcSDimitry Andric       };
10380eae32dcSDimitry Andric       Metadata *CFGHashAnnotation[] = {
10390eae32dcSDimitry Andric           MDString::get(Ctx, InstrProfCorrelator::CFGHashAttributeName),
10400eae32dcSDimitry Andric           ConstantAsMetadata::get(Inc->getHash()),
10410eae32dcSDimitry Andric       };
10420eae32dcSDimitry Andric       Metadata *NumCountersAnnotation[] = {
10430eae32dcSDimitry Andric           MDString::get(Ctx, InstrProfCorrelator::NumCountersAttributeName),
10440eae32dcSDimitry Andric           ConstantAsMetadata::get(Inc->getNumCounters()),
10450eae32dcSDimitry Andric       };
10460eae32dcSDimitry Andric       auto Annotations = DB.getOrCreateArray({
10470eae32dcSDimitry Andric           MDNode::get(Ctx, FunctionNameAnnotation),
10480eae32dcSDimitry Andric           MDNode::get(Ctx, CFGHashAnnotation),
10490eae32dcSDimitry Andric           MDNode::get(Ctx, NumCountersAnnotation),
10500eae32dcSDimitry Andric       });
10510eae32dcSDimitry Andric       auto *DICounter = DB.createGlobalVariableExpression(
10520eae32dcSDimitry Andric           SP, CounterPtr->getName(), /*LinkageName=*/StringRef(), SP->getFile(),
10530eae32dcSDimitry Andric           /*LineNo=*/0, DB.createUnspecifiedType("Profile Data Type"),
10540eae32dcSDimitry Andric           CounterPtr->hasLocalLinkage(), /*IsDefined=*/true, /*Expr=*/nullptr,
10550eae32dcSDimitry Andric           /*Decl=*/nullptr, /*TemplateParams=*/nullptr, /*AlignInBits=*/0,
10560eae32dcSDimitry Andric           Annotations);
10570eae32dcSDimitry Andric       CounterPtr->addDebugInfo(DICounter);
10580eae32dcSDimitry Andric       DB.finalize();
10590eae32dcSDimitry Andric     } else {
10600eae32dcSDimitry Andric       std::string Msg = ("Missing debug info for function " + Fn->getName() +
10610eae32dcSDimitry Andric                          "; required for profile correlation.")
10620eae32dcSDimitry Andric                             .str();
10630eae32dcSDimitry Andric       Ctx.diagnose(
10640eae32dcSDimitry Andric           DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
10650eae32dcSDimitry Andric     }
10660eae32dcSDimitry Andric   }
10670b57cec5SDimitry Andric 
10680b57cec5SDimitry Andric   auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
10690b57cec5SDimitry Andric   // Allocate statically the array of pointers to value profile nodes for
10700b57cec5SDimitry Andric   // the current function.
10710b57cec5SDimitry Andric   Constant *ValuesPtrExpr = ConstantPointerNull::get(Int8PtrTy);
10720b57cec5SDimitry Andric   uint64_t NS = 0;
10730b57cec5SDimitry Andric   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
10740b57cec5SDimitry Andric     NS += PD.NumValueSites[Kind];
1075fe6060f1SDimitry Andric   if (NS > 0 && ValueProfileStaticAlloc &&
1076fe6060f1SDimitry Andric       !needsRuntimeRegistrationOfSectionRange(TT)) {
10770b57cec5SDimitry Andric     ArrayType *ValuesTy = ArrayType::get(Type::getInt64Ty(Ctx), NS);
1078fe6060f1SDimitry Andric     auto *ValuesVar = new GlobalVariable(
1079fe6060f1SDimitry Andric         *M, ValuesTy, false, Linkage, Constant::getNullValue(ValuesTy),
1080349cc55cSDimitry Andric         getVarName(Inc, getInstrProfValuesVarPrefix(), Renamed));
10810b57cec5SDimitry Andric     ValuesVar->setVisibility(Visibility);
10820b57cec5SDimitry Andric     ValuesVar->setSection(
10830b57cec5SDimitry Andric         getInstrProfSectionName(IPSK_vals, TT.getObjectFormat()));
10848bcb0991SDimitry Andric     ValuesVar->setAlignment(Align(8));
1085c14a5a88SDimitry Andric     MaybeSetComdat(ValuesVar);
10860b57cec5SDimitry Andric     ValuesPtrExpr =
10870b57cec5SDimitry Andric         ConstantExpr::getBitCast(ValuesVar, Type::getInt8PtrTy(Ctx));
10880b57cec5SDimitry Andric   }
10890b57cec5SDimitry Andric 
109004eeddc0SDimitry Andric   if (DebugInfoCorrelate) {
109104eeddc0SDimitry Andric     // Mark the counter variable as used so that it isn't optimized out.
109204eeddc0SDimitry Andric     CompilerUsedVars.push_back(PD.RegionCounters);
10930eae32dcSDimitry Andric     return PD.RegionCounters;
109404eeddc0SDimitry Andric   }
10950eae32dcSDimitry Andric 
10960b57cec5SDimitry Andric   // Create data variable.
1097349cc55cSDimitry Andric   auto *IntPtrTy = M->getDataLayout().getIntPtrType(M->getContext());
10980b57cec5SDimitry Andric   auto *Int16Ty = Type::getInt16Ty(Ctx);
10990b57cec5SDimitry Andric   auto *Int16ArrayTy = ArrayType::get(Int16Ty, IPVK_Last + 1);
11000b57cec5SDimitry Andric   Type *DataTypes[] = {
11010b57cec5SDimitry Andric #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) LLVMType,
11020b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
11030b57cec5SDimitry Andric   };
1104bdd1243dSDimitry Andric   auto *DataTy = StructType::get(Ctx, ArrayRef(DataTypes));
11050b57cec5SDimitry Andric 
1106*fe013be4SDimitry Andric   Constant *FunctionAddr = getFuncAddrForProfData(Fn);
11070b57cec5SDimitry Andric 
11080b57cec5SDimitry Andric   Constant *Int16ArrayVals[IPVK_Last + 1];
11090b57cec5SDimitry Andric   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
11100b57cec5SDimitry Andric     Int16ArrayVals[Kind] = ConstantInt::get(Int16Ty, PD.NumValueSites[Kind]);
11110b57cec5SDimitry Andric 
1112fe6060f1SDimitry Andric   // If the data variable is not referenced by code (if we don't emit
1113fe6060f1SDimitry Andric   // @llvm.instrprof.value.profile, NS will be 0), and the counter keeps the
1114fe6060f1SDimitry Andric   // data variable live under linker GC, the data variable can be private. This
1115fe6060f1SDimitry Andric   // optimization applies to ELF.
1116fe6060f1SDimitry Andric   //
1117fe6060f1SDimitry Andric   // On COFF, a comdat leader cannot be local so we require DataReferencedByCode
1118fe6060f1SDimitry Andric   // to be false.
1119349cc55cSDimitry Andric   //
1120349cc55cSDimitry Andric   // If profd is in a deduplicate comdat, NS==0 with a hash suffix guarantees
1121349cc55cSDimitry Andric   // that other copies must have the same CFG and cannot have value profiling.
1122349cc55cSDimitry Andric   // If no hash suffix, other profd copies may be referenced by code.
1123349cc55cSDimitry Andric   if (NS == 0 && !(DataReferencedByCode && NeedComdat && !Renamed) &&
1124349cc55cSDimitry Andric       (TT.isOSBinFormatELF() ||
1125fe6060f1SDimitry Andric        (!DataReferencedByCode && TT.isOSBinFormatCOFF()))) {
1126fe6060f1SDimitry Andric     Linkage = GlobalValue::PrivateLinkage;
1127fe6060f1SDimitry Andric     Visibility = GlobalValue::DefaultVisibility;
1128fe6060f1SDimitry Andric   }
1129e8d8bef9SDimitry Andric   auto *Data =
1130349cc55cSDimitry Andric       new GlobalVariable(*M, DataTy, false, Linkage, nullptr, DataVarName);
1131349cc55cSDimitry Andric   // Reference the counter variable with a label difference (link-time
1132349cc55cSDimitry Andric   // constant).
1133349cc55cSDimitry Andric   auto *RelativeCounterPtr =
1134349cc55cSDimitry Andric       ConstantExpr::getSub(ConstantExpr::getPtrToInt(CounterPtr, IntPtrTy),
1135349cc55cSDimitry Andric                            ConstantExpr::getPtrToInt(Data, IntPtrTy));
1136349cc55cSDimitry Andric 
1137349cc55cSDimitry Andric   Constant *DataVals[] = {
1138349cc55cSDimitry Andric #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Init,
1139349cc55cSDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
1140349cc55cSDimitry Andric   };
1141349cc55cSDimitry Andric   Data->setInitializer(ConstantStruct::get(DataTy, DataVals));
1142349cc55cSDimitry Andric 
11430b57cec5SDimitry Andric   Data->setVisibility(Visibility);
11440b57cec5SDimitry Andric   Data->setSection(getInstrProfSectionName(IPSK_data, TT.getObjectFormat()));
11458bcb0991SDimitry Andric   Data->setAlignment(Align(INSTR_PROF_DATA_ALIGNMENT));
1146c14a5a88SDimitry Andric   MaybeSetComdat(Data);
11470b57cec5SDimitry Andric 
11480b57cec5SDimitry Andric   PD.DataVar = Data;
11490b57cec5SDimitry Andric 
11500b57cec5SDimitry Andric   // Mark the data variable as used so that it isn't stripped out.
1151fe6060f1SDimitry Andric   CompilerUsedVars.push_back(Data);
11520b57cec5SDimitry Andric   // Now that the linkage set by the FE has been passed to the data and counter
11530b57cec5SDimitry Andric   // variables, reset Name variable's linkage and visibility to private so that
11540b57cec5SDimitry Andric   // it can be removed later by the compiler.
11550b57cec5SDimitry Andric   NamePtr->setLinkage(GlobalValue::PrivateLinkage);
11560b57cec5SDimitry Andric   // Collect the referenced names to be used by emitNameData.
11570b57cec5SDimitry Andric   ReferencedNames.push_back(NamePtr);
11580b57cec5SDimitry Andric 
11594824e7fdSDimitry Andric   return PD.RegionCounters;
11600b57cec5SDimitry Andric }
11610b57cec5SDimitry Andric 
11620b57cec5SDimitry Andric void InstrProfiling::emitVNodes() {
11630b57cec5SDimitry Andric   if (!ValueProfileStaticAlloc)
11640b57cec5SDimitry Andric     return;
11650b57cec5SDimitry Andric 
11660b57cec5SDimitry Andric   // For now only support this on platforms that do
11670b57cec5SDimitry Andric   // not require runtime registration to discover
11680b57cec5SDimitry Andric   // named section start/end.
11690b57cec5SDimitry Andric   if (needsRuntimeRegistrationOfSectionRange(TT))
11700b57cec5SDimitry Andric     return;
11710b57cec5SDimitry Andric 
11720b57cec5SDimitry Andric   size_t TotalNS = 0;
11730b57cec5SDimitry Andric   for (auto &PD : ProfileDataMap) {
11740b57cec5SDimitry Andric     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
11750b57cec5SDimitry Andric       TotalNS += PD.second.NumValueSites[Kind];
11760b57cec5SDimitry Andric   }
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric   if (!TotalNS)
11790b57cec5SDimitry Andric     return;
11800b57cec5SDimitry Andric 
11810b57cec5SDimitry Andric   uint64_t NumCounters = TotalNS * NumCountersPerValueSite;
11820b57cec5SDimitry Andric // Heuristic for small programs with very few total value sites.
11830b57cec5SDimitry Andric // The default value of vp-counters-per-site is chosen based on
11840b57cec5SDimitry Andric // the observation that large apps usually have a low percentage
11850b57cec5SDimitry Andric // of value sites that actually have any profile data, and thus
11860b57cec5SDimitry Andric // the average number of counters per site is low. For small
11870b57cec5SDimitry Andric // apps with very few sites, this may not be true. Bump up the
11880b57cec5SDimitry Andric // number of counters in this case.
11890b57cec5SDimitry Andric #define INSTR_PROF_MIN_VAL_COUNTS 10
11900b57cec5SDimitry Andric   if (NumCounters < INSTR_PROF_MIN_VAL_COUNTS)
11910b57cec5SDimitry Andric     NumCounters = std::max(INSTR_PROF_MIN_VAL_COUNTS, (int)NumCounters * 2);
11920b57cec5SDimitry Andric 
11930b57cec5SDimitry Andric   auto &Ctx = M->getContext();
11940b57cec5SDimitry Andric   Type *VNodeTypes[] = {
11950b57cec5SDimitry Andric #define INSTR_PROF_VALUE_NODE(Type, LLVMType, Name, Init) LLVMType,
11960b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfData.inc"
11970b57cec5SDimitry Andric   };
1198bdd1243dSDimitry Andric   auto *VNodeTy = StructType::get(Ctx, ArrayRef(VNodeTypes));
11990b57cec5SDimitry Andric 
12000b57cec5SDimitry Andric   ArrayType *VNodesTy = ArrayType::get(VNodeTy, NumCounters);
12010b57cec5SDimitry Andric   auto *VNodesVar = new GlobalVariable(
12020b57cec5SDimitry Andric       *M, VNodesTy, false, GlobalValue::PrivateLinkage,
12030b57cec5SDimitry Andric       Constant::getNullValue(VNodesTy), getInstrProfVNodesVarName());
12040b57cec5SDimitry Andric   VNodesVar->setSection(
12050b57cec5SDimitry Andric       getInstrProfSectionName(IPSK_vnodes, TT.getObjectFormat()));
1206*fe013be4SDimitry Andric   VNodesVar->setAlignment(M->getDataLayout().getABITypeAlign(VNodesTy));
1207fe6060f1SDimitry Andric   // VNodesVar is used by runtime but not referenced via relocation by other
1208fe6060f1SDimitry Andric   // sections. Conservatively make it linker retained.
12090b57cec5SDimitry Andric   UsedVars.push_back(VNodesVar);
12100b57cec5SDimitry Andric }
12110b57cec5SDimitry Andric 
12120b57cec5SDimitry Andric void InstrProfiling::emitNameData() {
12130b57cec5SDimitry Andric   std::string UncompressedData;
12140b57cec5SDimitry Andric 
12150b57cec5SDimitry Andric   if (ReferencedNames.empty())
12160b57cec5SDimitry Andric     return;
12170b57cec5SDimitry Andric 
12180b57cec5SDimitry Andric   std::string CompressedNameStr;
12190b57cec5SDimitry Andric   if (Error E = collectPGOFuncNameStrings(ReferencedNames, CompressedNameStr,
12205ffd83dbSDimitry Andric                                           DoInstrProfNameCompression)) {
1221349cc55cSDimitry Andric     report_fatal_error(Twine(toString(std::move(E))), false);
12220b57cec5SDimitry Andric   }
12230b57cec5SDimitry Andric 
12240b57cec5SDimitry Andric   auto &Ctx = M->getContext();
12254824e7fdSDimitry Andric   auto *NamesVal =
12264824e7fdSDimitry Andric       ConstantDataArray::getString(Ctx, StringRef(CompressedNameStr), false);
12270b57cec5SDimitry Andric   NamesVar = new GlobalVariable(*M, NamesVal->getType(), true,
12280b57cec5SDimitry Andric                                 GlobalValue::PrivateLinkage, NamesVal,
12290b57cec5SDimitry Andric                                 getInstrProfNamesVarName());
12300b57cec5SDimitry Andric   NamesSize = CompressedNameStr.size();
12310b57cec5SDimitry Andric   NamesVar->setSection(
12320b57cec5SDimitry Andric       getInstrProfSectionName(IPSK_name, TT.getObjectFormat()));
12330b57cec5SDimitry Andric   // On COFF, it's important to reduce the alignment down to 1 to prevent the
12340b57cec5SDimitry Andric   // linker from inserting padding before the start of the names section or
12350b57cec5SDimitry Andric   // between names entries.
12365ffd83dbSDimitry Andric   NamesVar->setAlignment(Align(1));
1237fe6060f1SDimitry Andric   // NamesVar is used by runtime but not referenced via relocation by other
1238fe6060f1SDimitry Andric   // sections. Conservatively make it linker retained.
12390b57cec5SDimitry Andric   UsedVars.push_back(NamesVar);
12400b57cec5SDimitry Andric 
12410b57cec5SDimitry Andric   for (auto *NamePtr : ReferencedNames)
12420b57cec5SDimitry Andric     NamePtr->eraseFromParent();
12430b57cec5SDimitry Andric }
12440b57cec5SDimitry Andric 
12450b57cec5SDimitry Andric void InstrProfiling::emitRegistration() {
12460b57cec5SDimitry Andric   if (!needsRuntimeRegistrationOfSectionRange(TT))
12470b57cec5SDimitry Andric     return;
12480b57cec5SDimitry Andric 
12490b57cec5SDimitry Andric   // Construct the function.
12500b57cec5SDimitry Andric   auto *VoidTy = Type::getVoidTy(M->getContext());
12510b57cec5SDimitry Andric   auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
12520b57cec5SDimitry Andric   auto *Int64Ty = Type::getInt64Ty(M->getContext());
12530b57cec5SDimitry Andric   auto *RegisterFTy = FunctionType::get(VoidTy, false);
12540b57cec5SDimitry Andric   auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
12550b57cec5SDimitry Andric                                      getInstrProfRegFuncsName(), M);
12560b57cec5SDimitry Andric   RegisterF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
12570b57cec5SDimitry Andric   if (Options.NoRedZone)
12580b57cec5SDimitry Andric     RegisterF->addFnAttr(Attribute::NoRedZone);
12590b57cec5SDimitry Andric 
12600b57cec5SDimitry Andric   auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
12610b57cec5SDimitry Andric   auto *RuntimeRegisterF =
12620b57cec5SDimitry Andric       Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
12630b57cec5SDimitry Andric                        getInstrProfRegFuncName(), M);
12640b57cec5SDimitry Andric 
12650b57cec5SDimitry Andric   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
1266fe6060f1SDimitry Andric   for (Value *Data : CompilerUsedVars)
1267fe6060f1SDimitry Andric     if (!isa<Function>(Data))
1268fe6060f1SDimitry Andric       IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
12690b57cec5SDimitry Andric   for (Value *Data : UsedVars)
12700b57cec5SDimitry Andric     if (Data != NamesVar && !isa<Function>(Data))
12710b57cec5SDimitry Andric       IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
12720b57cec5SDimitry Andric 
12730b57cec5SDimitry Andric   if (NamesVar) {
12740b57cec5SDimitry Andric     Type *ParamTypes[] = {VoidPtrTy, Int64Ty};
12750b57cec5SDimitry Andric     auto *NamesRegisterTy =
1276bdd1243dSDimitry Andric         FunctionType::get(VoidTy, ArrayRef(ParamTypes), false);
12770b57cec5SDimitry Andric     auto *NamesRegisterF =
12780b57cec5SDimitry Andric         Function::Create(NamesRegisterTy, GlobalVariable::ExternalLinkage,
12790b57cec5SDimitry Andric                          getInstrProfNamesRegFuncName(), M);
12800b57cec5SDimitry Andric     IRB.CreateCall(NamesRegisterF, {IRB.CreateBitCast(NamesVar, VoidPtrTy),
12810b57cec5SDimitry Andric                                     IRB.getInt64(NamesSize)});
12820b57cec5SDimitry Andric   }
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric   IRB.CreateRetVoid();
12850b57cec5SDimitry Andric }
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric bool InstrProfiling::emitRuntimeHook() {
1288349cc55cSDimitry Andric   // We expect the linker to be invoked with -u<hook_var> flag for Linux
1289349cc55cSDimitry Andric   // in which case there is no need to emit the external variable.
1290bdd1243dSDimitry Andric   if (TT.isOSLinux() || TT.isOSAIX())
12910b57cec5SDimitry Andric     return false;
12920b57cec5SDimitry Andric 
12930b57cec5SDimitry Andric   // If the module's provided its own runtime, we don't need to do anything.
12940b57cec5SDimitry Andric   if (M->getGlobalVariable(getInstrProfRuntimeHookVarName()))
12950b57cec5SDimitry Andric     return false;
12960b57cec5SDimitry Andric 
12970b57cec5SDimitry Andric   // Declare an external variable that will pull in the runtime initialization.
12980b57cec5SDimitry Andric   auto *Int32Ty = Type::getInt32Ty(M->getContext());
12990b57cec5SDimitry Andric   auto *Var =
13000b57cec5SDimitry Andric       new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
13010b57cec5SDimitry Andric                          nullptr, getInstrProfRuntimeHookVarName());
1302753f127fSDimitry Andric   Var->setVisibility(GlobalValue::HiddenVisibility);
13030b57cec5SDimitry Andric 
130481ad6265SDimitry Andric   if (TT.isOSBinFormatELF() && !TT.isPS()) {
1305349cc55cSDimitry Andric     // Mark the user variable as used so that it isn't stripped out.
1306349cc55cSDimitry Andric     CompilerUsedVars.push_back(Var);
1307349cc55cSDimitry Andric   } else {
13080b57cec5SDimitry Andric     // Make a function that uses it.
13090b57cec5SDimitry Andric     auto *User = Function::Create(FunctionType::get(Int32Ty, false),
13100b57cec5SDimitry Andric                                   GlobalValue::LinkOnceODRLinkage,
13110b57cec5SDimitry Andric                                   getInstrProfRuntimeHookVarUseFuncName(), M);
13120b57cec5SDimitry Andric     User->addFnAttr(Attribute::NoInline);
13130b57cec5SDimitry Andric     if (Options.NoRedZone)
13140b57cec5SDimitry Andric       User->addFnAttr(Attribute::NoRedZone);
13150b57cec5SDimitry Andric     User->setVisibility(GlobalValue::HiddenVisibility);
13160b57cec5SDimitry Andric     if (TT.supportsCOMDAT())
13170b57cec5SDimitry Andric       User->setComdat(M->getOrInsertComdat(User->getName()));
13180b57cec5SDimitry Andric 
13190b57cec5SDimitry Andric     IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
13200b57cec5SDimitry Andric     auto *Load = IRB.CreateLoad(Int32Ty, Var);
13210b57cec5SDimitry Andric     IRB.CreateRet(Load);
13220b57cec5SDimitry Andric 
1323349cc55cSDimitry Andric     // Mark the function as used so that it isn't stripped out.
1324fe6060f1SDimitry Andric     CompilerUsedVars.push_back(User);
1325349cc55cSDimitry Andric   }
13260b57cec5SDimitry Andric   return true;
13270b57cec5SDimitry Andric }
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric void InstrProfiling::emitUses() {
1330fe6060f1SDimitry Andric   // The metadata sections are parallel arrays. Optimizers (e.g.
1331fe6060f1SDimitry Andric   // GlobalOpt/ConstantMerge) may not discard associated sections as a unit, so
1332fe6060f1SDimitry Andric   // we conservatively retain all unconditionally in the compiler.
1333fe6060f1SDimitry Andric   //
1334349cc55cSDimitry Andric   // On ELF and Mach-O, the linker can guarantee the associated sections will be
1335349cc55cSDimitry Andric   // retained or discarded as a unit, so llvm.compiler.used is sufficient.
1336349cc55cSDimitry Andric   // Similarly on COFF, if prof data is not referenced by code we use one comdat
1337349cc55cSDimitry Andric   // and ensure this GC property as well. Otherwise, we have to conservatively
1338349cc55cSDimitry Andric   // make all of the sections retained by the linker.
1339349cc55cSDimitry Andric   if (TT.isOSBinFormatELF() || TT.isOSBinFormatMachO() ||
1340fe6060f1SDimitry Andric       (TT.isOSBinFormatCOFF() && !profDataReferencedByCode(*M)))
1341fe6060f1SDimitry Andric     appendToCompilerUsed(*M, CompilerUsedVars);
1342fe6060f1SDimitry Andric   else
1343fe6060f1SDimitry Andric     appendToUsed(*M, CompilerUsedVars);
1344fe6060f1SDimitry Andric 
1345fe6060f1SDimitry Andric   // We do not add proper references from used metadata sections to NamesVar and
1346fe6060f1SDimitry Andric   // VNodesVar, so we have to be conservative and place them in llvm.used
1347fe6060f1SDimitry Andric   // regardless of the target,
13480b57cec5SDimitry Andric   appendToUsed(*M, UsedVars);
13490b57cec5SDimitry Andric }
13500b57cec5SDimitry Andric 
13510b57cec5SDimitry Andric void InstrProfiling::emitInitialization() {
13520b57cec5SDimitry Andric   // Create ProfileFileName variable. Don't don't this for the
13530b57cec5SDimitry Andric   // context-sensitive instrumentation lowering: This lowering is after
13540b57cec5SDimitry Andric   // LTO/ThinLTO linking. Pass PGOInstrumentationGenCreateVar should
13550b57cec5SDimitry Andric   // have already create the variable before LTO/ThinLTO linking.
13560b57cec5SDimitry Andric   if (!IsCS)
13570b57cec5SDimitry Andric     createProfileFileNameVar(*M, Options.InstrProfileOutput);
13580b57cec5SDimitry Andric   Function *RegisterF = M->getFunction(getInstrProfRegFuncsName());
13590b57cec5SDimitry Andric   if (!RegisterF)
13600b57cec5SDimitry Andric     return;
13610b57cec5SDimitry Andric 
13620b57cec5SDimitry Andric   // Create the initialization function.
13630b57cec5SDimitry Andric   auto *VoidTy = Type::getVoidTy(M->getContext());
13640b57cec5SDimitry Andric   auto *F = Function::Create(FunctionType::get(VoidTy, false),
13650b57cec5SDimitry Andric                              GlobalValue::InternalLinkage,
13660b57cec5SDimitry Andric                              getInstrProfInitFuncName(), M);
13670b57cec5SDimitry Andric   F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
13680b57cec5SDimitry Andric   F->addFnAttr(Attribute::NoInline);
13690b57cec5SDimitry Andric   if (Options.NoRedZone)
13700b57cec5SDimitry Andric     F->addFnAttr(Attribute::NoRedZone);
13710b57cec5SDimitry Andric 
13720b57cec5SDimitry Andric   // Add the basic block and the necessary calls.
13730b57cec5SDimitry Andric   IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
13740b57cec5SDimitry Andric   IRB.CreateCall(RegisterF, {});
13750b57cec5SDimitry Andric   IRB.CreateRetVoid();
13760b57cec5SDimitry Andric 
13770b57cec5SDimitry Andric   appendToGlobalCtors(*M, F, 0);
13780b57cec5SDimitry Andric }
1379