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