InstrProfiling.cpp 50 KB

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