SampleProfileLoaderBaseImpl.h 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. ////===- SampleProfileLoadBaseImpl.h - Profile loader base impl --*- C++-*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. /// \file
  15. /// This file provides the interface for the sampled PGO profile loader base
  16. /// implementation.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_TRANSFORMS_UTILS_SAMPLEPROFILELOADERBASEIMPL_H
  20. #define LLVM_TRANSFORMS_UTILS_SAMPLEPROFILELOADERBASEIMPL_H
  21. #include "llvm/ADT/ArrayRef.h"
  22. #include "llvm/ADT/DenseMap.h"
  23. #include "llvm/ADT/DenseSet.h"
  24. #include "llvm/ADT/SmallPtrSet.h"
  25. #include "llvm/ADT/SmallSet.h"
  26. #include "llvm/ADT/SmallVector.h"
  27. #include "llvm/Analysis/LoopInfo.h"
  28. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  29. #include "llvm/Analysis/PostDominators.h"
  30. #include "llvm/IR/BasicBlock.h"
  31. #include "llvm/IR/CFG.h"
  32. #include "llvm/IR/DebugInfoMetadata.h"
  33. #include "llvm/IR/DebugLoc.h"
  34. #include "llvm/IR/Dominators.h"
  35. #include "llvm/IR/Function.h"
  36. #include "llvm/IR/Instruction.h"
  37. #include "llvm/IR/Instructions.h"
  38. #include "llvm/IR/Module.h"
  39. #include "llvm/ProfileData/SampleProf.h"
  40. #include "llvm/ProfileData/SampleProfReader.h"
  41. #include "llvm/Support/CommandLine.h"
  42. #include "llvm/Support/GenericDomTree.h"
  43. #include "llvm/Support/raw_ostream.h"
  44. #include "llvm/Transforms/Utils/SampleProfileInference.h"
  45. #include "llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h"
  46. namespace llvm {
  47. using namespace sampleprof;
  48. using namespace sampleprofutil;
  49. using ProfileCount = Function::ProfileCount;
  50. #define DEBUG_TYPE "sample-profile-impl"
  51. namespace afdo_detail {
  52. template <typename BlockT> struct IRTraits;
  53. template <> struct IRTraits<BasicBlock> {
  54. using InstructionT = Instruction;
  55. using BasicBlockT = BasicBlock;
  56. using FunctionT = Function;
  57. using BlockFrequencyInfoT = BlockFrequencyInfo;
  58. using LoopT = Loop;
  59. using LoopInfoPtrT = std::unique_ptr<LoopInfo>;
  60. using DominatorTreePtrT = std::unique_ptr<DominatorTree>;
  61. using PostDominatorTreeT = PostDominatorTree;
  62. using PostDominatorTreePtrT = std::unique_ptr<PostDominatorTree>;
  63. using OptRemarkEmitterT = OptimizationRemarkEmitter;
  64. using OptRemarkAnalysisT = OptimizationRemarkAnalysis;
  65. using PredRangeT = pred_range;
  66. using SuccRangeT = succ_range;
  67. static Function &getFunction(Function &F) { return F; }
  68. static const BasicBlock *getEntryBB(const Function *F) {
  69. return &F->getEntryBlock();
  70. }
  71. static pred_range getPredecessors(BasicBlock *BB) { return predecessors(BB); }
  72. static succ_range getSuccessors(BasicBlock *BB) { return successors(BB); }
  73. };
  74. } // end namespace afdo_detail
  75. extern cl::opt<bool> SampleProfileUseProfi;
  76. template <typename BT> class SampleProfileLoaderBaseImpl {
  77. public:
  78. SampleProfileLoaderBaseImpl(std::string Name, std::string RemapName)
  79. : Filename(Name), RemappingFilename(RemapName) {}
  80. void dump() { Reader->dump(); }
  81. using InstructionT = typename afdo_detail::IRTraits<BT>::InstructionT;
  82. using BasicBlockT = typename afdo_detail::IRTraits<BT>::BasicBlockT;
  83. using BlockFrequencyInfoT =
  84. typename afdo_detail::IRTraits<BT>::BlockFrequencyInfoT;
  85. using FunctionT = typename afdo_detail::IRTraits<BT>::FunctionT;
  86. using LoopT = typename afdo_detail::IRTraits<BT>::LoopT;
  87. using LoopInfoPtrT = typename afdo_detail::IRTraits<BT>::LoopInfoPtrT;
  88. using DominatorTreePtrT =
  89. typename afdo_detail::IRTraits<BT>::DominatorTreePtrT;
  90. using PostDominatorTreePtrT =
  91. typename afdo_detail::IRTraits<BT>::PostDominatorTreePtrT;
  92. using PostDominatorTreeT =
  93. typename afdo_detail::IRTraits<BT>::PostDominatorTreeT;
  94. using OptRemarkEmitterT =
  95. typename afdo_detail::IRTraits<BT>::OptRemarkEmitterT;
  96. using OptRemarkAnalysisT =
  97. typename afdo_detail::IRTraits<BT>::OptRemarkAnalysisT;
  98. using PredRangeT = typename afdo_detail::IRTraits<BT>::PredRangeT;
  99. using SuccRangeT = typename afdo_detail::IRTraits<BT>::SuccRangeT;
  100. using BlockWeightMap = DenseMap<const BasicBlockT *, uint64_t>;
  101. using EquivalenceClassMap =
  102. DenseMap<const BasicBlockT *, const BasicBlockT *>;
  103. using Edge = std::pair<const BasicBlockT *, const BasicBlockT *>;
  104. using EdgeWeightMap = DenseMap<Edge, uint64_t>;
  105. using BlockEdgeMap =
  106. DenseMap<const BasicBlockT *, SmallVector<const BasicBlockT *, 8>>;
  107. protected:
  108. ~SampleProfileLoaderBaseImpl() = default;
  109. friend class SampleCoverageTracker;
  110. Function &getFunction(FunctionT &F) {
  111. return afdo_detail::IRTraits<BT>::getFunction(F);
  112. }
  113. const BasicBlockT *getEntryBB(const FunctionT *F) {
  114. return afdo_detail::IRTraits<BT>::getEntryBB(F);
  115. }
  116. PredRangeT getPredecessors(BasicBlockT *BB) {
  117. return afdo_detail::IRTraits<BT>::getPredecessors(BB);
  118. }
  119. SuccRangeT getSuccessors(BasicBlockT *BB) {
  120. return afdo_detail::IRTraits<BT>::getSuccessors(BB);
  121. }
  122. unsigned getFunctionLoc(FunctionT &Func);
  123. virtual ErrorOr<uint64_t> getInstWeight(const InstructionT &Inst);
  124. ErrorOr<uint64_t> getInstWeightImpl(const InstructionT &Inst);
  125. ErrorOr<uint64_t> getBlockWeight(const BasicBlockT *BB);
  126. mutable DenseMap<const DILocation *, const FunctionSamples *>
  127. DILocation2SampleMap;
  128. virtual const FunctionSamples *
  129. findFunctionSamples(const InstructionT &I) const;
  130. void printEdgeWeight(raw_ostream &OS, Edge E);
  131. void printBlockWeight(raw_ostream &OS, const BasicBlockT *BB) const;
  132. void printBlockEquivalence(raw_ostream &OS, const BasicBlockT *BB);
  133. bool computeBlockWeights(FunctionT &F);
  134. void findEquivalenceClasses(FunctionT &F);
  135. void findEquivalencesFor(BasicBlockT *BB1,
  136. ArrayRef<BasicBlockT *> Descendants,
  137. PostDominatorTreeT *DomTree);
  138. void propagateWeights(FunctionT &F);
  139. void applyProfi(FunctionT &F, BlockEdgeMap &Successors,
  140. BlockWeightMap &SampleBlockWeights,
  141. BlockWeightMap &BlockWeights, EdgeWeightMap &EdgeWeights);
  142. uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
  143. void buildEdges(FunctionT &F);
  144. bool propagateThroughEdges(FunctionT &F, bool UpdateBlockCount);
  145. void clearFunctionData(bool ResetDT = true);
  146. void computeDominanceAndLoopInfo(FunctionT &F);
  147. bool
  148. computeAndPropagateWeights(FunctionT &F,
  149. const DenseSet<GlobalValue::GUID> &InlinedGUIDs);
  150. void initWeightPropagation(FunctionT &F,
  151. const DenseSet<GlobalValue::GUID> &InlinedGUIDs);
  152. void
  153. finalizeWeightPropagation(FunctionT &F,
  154. const DenseSet<GlobalValue::GUID> &InlinedGUIDs);
  155. void emitCoverageRemarks(FunctionT &F);
  156. /// Map basic blocks to their computed weights.
  157. ///
  158. /// The weight of a basic block is defined to be the maximum
  159. /// of all the instruction weights in that block.
  160. BlockWeightMap BlockWeights;
  161. /// Map edges to their computed weights.
  162. ///
  163. /// Edge weights are computed by propagating basic block weights in
  164. /// SampleProfile::propagateWeights.
  165. EdgeWeightMap EdgeWeights;
  166. /// Set of visited blocks during propagation.
  167. SmallPtrSet<const BasicBlockT *, 32> VisitedBlocks;
  168. /// Set of visited edges during propagation.
  169. SmallSet<Edge, 32> VisitedEdges;
  170. /// Equivalence classes for block weights.
  171. ///
  172. /// Two blocks BB1 and BB2 are in the same equivalence class if they
  173. /// dominate and post-dominate each other, and they are in the same loop
  174. /// nest. When this happens, the two blocks are guaranteed to execute
  175. /// the same number of times.
  176. EquivalenceClassMap EquivalenceClass;
  177. /// Dominance, post-dominance and loop information.
  178. DominatorTreePtrT DT;
  179. PostDominatorTreePtrT PDT;
  180. LoopInfoPtrT LI;
  181. /// Predecessors for each basic block in the CFG.
  182. BlockEdgeMap Predecessors;
  183. /// Successors for each basic block in the CFG.
  184. BlockEdgeMap Successors;
  185. /// Profile coverage tracker.
  186. SampleCoverageTracker CoverageTracker;
  187. /// Profile reader object.
  188. std::unique_ptr<SampleProfileReader> Reader;
  189. /// Samples collected for the body of this function.
  190. FunctionSamples *Samples = nullptr;
  191. /// Name of the profile file to load.
  192. std::string Filename;
  193. /// Name of the profile remapping file to load.
  194. std::string RemappingFilename;
  195. /// Profile Summary Info computed from sample profile.
  196. ProfileSummaryInfo *PSI = nullptr;
  197. /// Optimization Remark Emitter used to emit diagnostic remarks.
  198. OptRemarkEmitterT *ORE = nullptr;
  199. };
  200. /// Clear all the per-function data used to load samples and propagate weights.
  201. template <typename BT>
  202. void SampleProfileLoaderBaseImpl<BT>::clearFunctionData(bool ResetDT) {
  203. BlockWeights.clear();
  204. EdgeWeights.clear();
  205. VisitedBlocks.clear();
  206. VisitedEdges.clear();
  207. EquivalenceClass.clear();
  208. if (ResetDT) {
  209. DT = nullptr;
  210. PDT = nullptr;
  211. LI = nullptr;
  212. }
  213. Predecessors.clear();
  214. Successors.clear();
  215. CoverageTracker.clear();
  216. }
  217. #ifndef NDEBUG
  218. /// Print the weight of edge \p E on stream \p OS.
  219. ///
  220. /// \param OS Stream to emit the output to.
  221. /// \param E Edge to print.
  222. template <typename BT>
  223. void SampleProfileLoaderBaseImpl<BT>::printEdgeWeight(raw_ostream &OS, Edge E) {
  224. OS << "weight[" << E.first->getName() << "->" << E.second->getName()
  225. << "]: " << EdgeWeights[E] << "\n";
  226. }
  227. /// Print the equivalence class of block \p BB on stream \p OS.
  228. ///
  229. /// \param OS Stream to emit the output to.
  230. /// \param BB Block to print.
  231. template <typename BT>
  232. void SampleProfileLoaderBaseImpl<BT>::printBlockEquivalence(
  233. raw_ostream &OS, const BasicBlockT *BB) {
  234. const BasicBlockT *Equiv = EquivalenceClass[BB];
  235. OS << "equivalence[" << BB->getName()
  236. << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
  237. }
  238. /// Print the weight of block \p BB on stream \p OS.
  239. ///
  240. /// \param OS Stream to emit the output to.
  241. /// \param BB Block to print.
  242. template <typename BT>
  243. void SampleProfileLoaderBaseImpl<BT>::printBlockWeight(
  244. raw_ostream &OS, const BasicBlockT *BB) const {
  245. const auto &I = BlockWeights.find(BB);
  246. uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
  247. OS << "weight[" << BB->getName() << "]: " << W << "\n";
  248. }
  249. #endif
  250. /// Get the weight for an instruction.
  251. ///
  252. /// The "weight" of an instruction \p Inst is the number of samples
  253. /// collected on that instruction at runtime. To retrieve it, we
  254. /// need to compute the line number of \p Inst relative to the start of its
  255. /// function. We use HeaderLineno to compute the offset. We then
  256. /// look up the samples collected for \p Inst using BodySamples.
  257. ///
  258. /// \param Inst Instruction to query.
  259. ///
  260. /// \returns the weight of \p Inst.
  261. template <typename BT>
  262. ErrorOr<uint64_t>
  263. SampleProfileLoaderBaseImpl<BT>::getInstWeight(const InstructionT &Inst) {
  264. return getInstWeightImpl(Inst);
  265. }
  266. template <typename BT>
  267. ErrorOr<uint64_t>
  268. SampleProfileLoaderBaseImpl<BT>::getInstWeightImpl(const InstructionT &Inst) {
  269. const FunctionSamples *FS = findFunctionSamples(Inst);
  270. if (!FS)
  271. return std::error_code();
  272. const DebugLoc &DLoc = Inst.getDebugLoc();
  273. if (!DLoc)
  274. return std::error_code();
  275. const DILocation *DIL = DLoc;
  276. uint32_t LineOffset = FunctionSamples::getOffset(DIL);
  277. uint32_t Discriminator;
  278. if (EnableFSDiscriminator)
  279. Discriminator = DIL->getDiscriminator();
  280. else
  281. Discriminator = DIL->getBaseDiscriminator();
  282. ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
  283. if (R) {
  284. bool FirstMark =
  285. CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
  286. if (FirstMark) {
  287. ORE->emit([&]() {
  288. OptRemarkAnalysisT Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
  289. Remark << "Applied " << ore::NV("NumSamples", *R);
  290. Remark << " samples from profile (offset: ";
  291. Remark << ore::NV("LineOffset", LineOffset);
  292. if (Discriminator) {
  293. Remark << ".";
  294. Remark << ore::NV("Discriminator", Discriminator);
  295. }
  296. Remark << ")";
  297. return Remark;
  298. });
  299. }
  300. LLVM_DEBUG(dbgs() << " " << DLoc.getLine() << "." << Discriminator << ":"
  301. << Inst << " (line offset: " << LineOffset << "."
  302. << Discriminator << " - weight: " << R.get() << ")\n");
  303. }
  304. return R;
  305. }
  306. /// Compute the weight of a basic block.
  307. ///
  308. /// The weight of basic block \p BB is the maximum weight of all the
  309. /// instructions in BB.
  310. ///
  311. /// \param BB The basic block to query.
  312. ///
  313. /// \returns the weight for \p BB.
  314. template <typename BT>
  315. ErrorOr<uint64_t>
  316. SampleProfileLoaderBaseImpl<BT>::getBlockWeight(const BasicBlockT *BB) {
  317. uint64_t Max = 0;
  318. bool HasWeight = false;
  319. for (auto &I : *BB) {
  320. const ErrorOr<uint64_t> &R = getInstWeight(I);
  321. if (R) {
  322. Max = std::max(Max, R.get());
  323. HasWeight = true;
  324. }
  325. }
  326. return HasWeight ? ErrorOr<uint64_t>(Max) : std::error_code();
  327. }
  328. /// Compute and store the weights of every basic block.
  329. ///
  330. /// This populates the BlockWeights map by computing
  331. /// the weights of every basic block in the CFG.
  332. ///
  333. /// \param F The function to query.
  334. template <typename BT>
  335. bool SampleProfileLoaderBaseImpl<BT>::computeBlockWeights(FunctionT &F) {
  336. bool Changed = false;
  337. LLVM_DEBUG(dbgs() << "Block weights\n");
  338. for (const auto &BB : F) {
  339. ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
  340. if (Weight) {
  341. BlockWeights[&BB] = Weight.get();
  342. VisitedBlocks.insert(&BB);
  343. Changed = true;
  344. }
  345. LLVM_DEBUG(printBlockWeight(dbgs(), &BB));
  346. }
  347. return Changed;
  348. }
  349. /// Get the FunctionSamples for an instruction.
  350. ///
  351. /// The FunctionSamples of an instruction \p Inst is the inlined instance
  352. /// in which that instruction is coming from. We traverse the inline stack
  353. /// of that instruction, and match it with the tree nodes in the profile.
  354. ///
  355. /// \param Inst Instruction to query.
  356. ///
  357. /// \returns the FunctionSamples pointer to the inlined instance.
  358. template <typename BT>
  359. const FunctionSamples *SampleProfileLoaderBaseImpl<BT>::findFunctionSamples(
  360. const InstructionT &Inst) const {
  361. const DILocation *DIL = Inst.getDebugLoc();
  362. if (!DIL)
  363. return Samples;
  364. auto it = DILocation2SampleMap.try_emplace(DIL, nullptr);
  365. if (it.second) {
  366. it.first->second = Samples->findFunctionSamples(DIL, Reader->getRemapper());
  367. }
  368. return it.first->second;
  369. }
  370. /// Find equivalence classes for the given block.
  371. ///
  372. /// This finds all the blocks that are guaranteed to execute the same
  373. /// number of times as \p BB1. To do this, it traverses all the
  374. /// descendants of \p BB1 in the dominator or post-dominator tree.
  375. ///
  376. /// A block BB2 will be in the same equivalence class as \p BB1 if
  377. /// the following holds:
  378. ///
  379. /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
  380. /// is a descendant of \p BB1 in the dominator tree, then BB2 should
  381. /// dominate BB1 in the post-dominator tree.
  382. ///
  383. /// 2- Both BB2 and \p BB1 must be in the same loop.
  384. ///
  385. /// For every block BB2 that meets those two requirements, we set BB2's
  386. /// equivalence class to \p BB1.
  387. ///
  388. /// \param BB1 Block to check.
  389. /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
  390. /// \param DomTree Opposite dominator tree. If \p Descendants is filled
  391. /// with blocks from \p BB1's dominator tree, then
  392. /// this is the post-dominator tree, and vice versa.
  393. template <typename BT>
  394. void SampleProfileLoaderBaseImpl<BT>::findEquivalencesFor(
  395. BasicBlockT *BB1, ArrayRef<BasicBlockT *> Descendants,
  396. PostDominatorTreeT *DomTree) {
  397. const BasicBlockT *EC = EquivalenceClass[BB1];
  398. uint64_t Weight = BlockWeights[EC];
  399. for (const auto *BB2 : Descendants) {
  400. bool IsDomParent = DomTree->dominates(BB2, BB1);
  401. bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
  402. if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
  403. EquivalenceClass[BB2] = EC;
  404. // If BB2 is visited, then the entire EC should be marked as visited.
  405. if (VisitedBlocks.count(BB2)) {
  406. VisitedBlocks.insert(EC);
  407. }
  408. // If BB2 is heavier than BB1, make BB2 have the same weight
  409. // as BB1.
  410. //
  411. // Note that we don't worry about the opposite situation here
  412. // (when BB2 is lighter than BB1). We will deal with this
  413. // during the propagation phase. Right now, we just want to
  414. // make sure that BB1 has the largest weight of all the
  415. // members of its equivalence set.
  416. Weight = std::max(Weight, BlockWeights[BB2]);
  417. }
  418. }
  419. const BasicBlockT *EntryBB = getEntryBB(EC->getParent());
  420. if (EC == EntryBB) {
  421. BlockWeights[EC] = Samples->getHeadSamples() + 1;
  422. } else {
  423. BlockWeights[EC] = Weight;
  424. }
  425. }
  426. /// Find equivalence classes.
  427. ///
  428. /// Since samples may be missing from blocks, we can fill in the gaps by setting
  429. /// the weights of all the blocks in the same equivalence class to the same
  430. /// weight. To compute the concept of equivalence, we use dominance and loop
  431. /// information. Two blocks B1 and B2 are in the same equivalence class if B1
  432. /// dominates B2, B2 post-dominates B1 and both are in the same loop.
  433. ///
  434. /// \param F The function to query.
  435. template <typename BT>
  436. void SampleProfileLoaderBaseImpl<BT>::findEquivalenceClasses(FunctionT &F) {
  437. SmallVector<BasicBlockT *, 8> DominatedBBs;
  438. LLVM_DEBUG(dbgs() << "\nBlock equivalence classes\n");
  439. // Find equivalence sets based on dominance and post-dominance information.
  440. for (auto &BB : F) {
  441. BasicBlockT *BB1 = &BB;
  442. // Compute BB1's equivalence class once.
  443. if (EquivalenceClass.count(BB1)) {
  444. LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
  445. continue;
  446. }
  447. // By default, blocks are in their own equivalence class.
  448. EquivalenceClass[BB1] = BB1;
  449. // Traverse all the blocks dominated by BB1. We are looking for
  450. // every basic block BB2 such that:
  451. //
  452. // 1- BB1 dominates BB2.
  453. // 2- BB2 post-dominates BB1.
  454. // 3- BB1 and BB2 are in the same loop nest.
  455. //
  456. // If all those conditions hold, it means that BB2 is executed
  457. // as many times as BB1, so they are placed in the same equivalence
  458. // class by making BB2's equivalence class be BB1.
  459. DominatedBBs.clear();
  460. DT->getDescendants(BB1, DominatedBBs);
  461. findEquivalencesFor(BB1, DominatedBBs, &*PDT);
  462. LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
  463. }
  464. // Assign weights to equivalence classes.
  465. //
  466. // All the basic blocks in the same equivalence class will execute
  467. // the same number of times. Since we know that the head block in
  468. // each equivalence class has the largest weight, assign that weight
  469. // to all the blocks in that equivalence class.
  470. LLVM_DEBUG(
  471. dbgs() << "\nAssign the same weight to all blocks in the same class\n");
  472. for (auto &BI : F) {
  473. const BasicBlockT *BB = &BI;
  474. const BasicBlockT *EquivBB = EquivalenceClass[BB];
  475. if (BB != EquivBB)
  476. BlockWeights[BB] = BlockWeights[EquivBB];
  477. LLVM_DEBUG(printBlockWeight(dbgs(), BB));
  478. }
  479. }
  480. /// Visit the given edge to decide if it has a valid weight.
  481. ///
  482. /// If \p E has not been visited before, we copy to \p UnknownEdge
  483. /// and increment the count of unknown edges.
  484. ///
  485. /// \param E Edge to visit.
  486. /// \param NumUnknownEdges Current number of unknown edges.
  487. /// \param UnknownEdge Set if E has not been visited before.
  488. ///
  489. /// \returns E's weight, if known. Otherwise, return 0.
  490. template <typename BT>
  491. uint64_t SampleProfileLoaderBaseImpl<BT>::visitEdge(Edge E,
  492. unsigned *NumUnknownEdges,
  493. Edge *UnknownEdge) {
  494. if (!VisitedEdges.count(E)) {
  495. (*NumUnknownEdges)++;
  496. *UnknownEdge = E;
  497. return 0;
  498. }
  499. return EdgeWeights[E];
  500. }
  501. /// Propagate weights through incoming/outgoing edges.
  502. ///
  503. /// If the weight of a basic block is known, and there is only one edge
  504. /// with an unknown weight, we can calculate the weight of that edge.
  505. ///
  506. /// Similarly, if all the edges have a known count, we can calculate the
  507. /// count of the basic block, if needed.
  508. ///
  509. /// \param F Function to process.
  510. /// \param UpdateBlockCount Whether we should update basic block counts that
  511. /// has already been annotated.
  512. ///
  513. /// \returns True if new weights were assigned to edges or blocks.
  514. template <typename BT>
  515. bool SampleProfileLoaderBaseImpl<BT>::propagateThroughEdges(
  516. FunctionT &F, bool UpdateBlockCount) {
  517. bool Changed = false;
  518. LLVM_DEBUG(dbgs() << "\nPropagation through edges\n");
  519. for (const auto &BI : F) {
  520. const BasicBlockT *BB = &BI;
  521. const BasicBlockT *EC = EquivalenceClass[BB];
  522. // Visit all the predecessor and successor edges to determine
  523. // which ones have a weight assigned already. Note that it doesn't
  524. // matter that we only keep track of a single unknown edge. The
  525. // only case we are interested in handling is when only a single
  526. // edge is unknown (see setEdgeOrBlockWeight).
  527. for (unsigned i = 0; i < 2; i++) {
  528. uint64_t TotalWeight = 0;
  529. unsigned NumUnknownEdges = 0, NumTotalEdges = 0;
  530. Edge UnknownEdge, SelfReferentialEdge, SingleEdge;
  531. if (i == 0) {
  532. // First, visit all predecessor edges.
  533. NumTotalEdges = Predecessors[BB].size();
  534. for (auto *Pred : Predecessors[BB]) {
  535. Edge E = std::make_pair(Pred, BB);
  536. TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
  537. if (E.first == E.second)
  538. SelfReferentialEdge = E;
  539. }
  540. if (NumTotalEdges == 1) {
  541. SingleEdge = std::make_pair(Predecessors[BB][0], BB);
  542. }
  543. } else {
  544. // On the second round, visit all successor edges.
  545. NumTotalEdges = Successors[BB].size();
  546. for (auto *Succ : Successors[BB]) {
  547. Edge E = std::make_pair(BB, Succ);
  548. TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
  549. }
  550. if (NumTotalEdges == 1) {
  551. SingleEdge = std::make_pair(BB, Successors[BB][0]);
  552. }
  553. }
  554. // After visiting all the edges, there are three cases that we
  555. // can handle immediately:
  556. //
  557. // - All the edge weights are known (i.e., NumUnknownEdges == 0).
  558. // In this case, we simply check that the sum of all the edges
  559. // is the same as BB's weight. If not, we change BB's weight
  560. // to match. Additionally, if BB had not been visited before,
  561. // we mark it visited.
  562. //
  563. // - Only one edge is unknown and BB has already been visited.
  564. // In this case, we can compute the weight of the edge by
  565. // subtracting the total block weight from all the known
  566. // edge weights. If the edges weight more than BB, then the
  567. // edge of the last remaining edge is set to zero.
  568. //
  569. // - There exists a self-referential edge and the weight of BB is
  570. // known. In this case, this edge can be based on BB's weight.
  571. // We add up all the other known edges and set the weight on
  572. // the self-referential edge as we did in the previous case.
  573. //
  574. // In any other case, we must continue iterating. Eventually,
  575. // all edges will get a weight, or iteration will stop when
  576. // it reaches SampleProfileMaxPropagateIterations.
  577. if (NumUnknownEdges <= 1) {
  578. uint64_t &BBWeight = BlockWeights[EC];
  579. if (NumUnknownEdges == 0) {
  580. if (!VisitedBlocks.count(EC)) {
  581. // If we already know the weight of all edges, the weight of the
  582. // basic block can be computed. It should be no larger than the sum
  583. // of all edge weights.
  584. if (TotalWeight > BBWeight) {
  585. BBWeight = TotalWeight;
  586. Changed = true;
  587. LLVM_DEBUG(dbgs() << "All edge weights for " << BB->getName()
  588. << " known. Set weight for block: ";
  589. printBlockWeight(dbgs(), BB););
  590. }
  591. } else if (NumTotalEdges == 1 &&
  592. EdgeWeights[SingleEdge] < BlockWeights[EC]) {
  593. // If there is only one edge for the visited basic block, use the
  594. // block weight to adjust edge weight if edge weight is smaller.
  595. EdgeWeights[SingleEdge] = BlockWeights[EC];
  596. Changed = true;
  597. }
  598. } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
  599. // If there is a single unknown edge and the block has been
  600. // visited, then we can compute E's weight.
  601. if (BBWeight >= TotalWeight)
  602. EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
  603. else
  604. EdgeWeights[UnknownEdge] = 0;
  605. const BasicBlockT *OtherEC;
  606. if (i == 0)
  607. OtherEC = EquivalenceClass[UnknownEdge.first];
  608. else
  609. OtherEC = EquivalenceClass[UnknownEdge.second];
  610. // Edge weights should never exceed the BB weights it connects.
  611. if (VisitedBlocks.count(OtherEC) &&
  612. EdgeWeights[UnknownEdge] > BlockWeights[OtherEC])
  613. EdgeWeights[UnknownEdge] = BlockWeights[OtherEC];
  614. VisitedEdges.insert(UnknownEdge);
  615. Changed = true;
  616. LLVM_DEBUG(dbgs() << "Set weight for edge: ";
  617. printEdgeWeight(dbgs(), UnknownEdge));
  618. }
  619. } else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) {
  620. // If a block Weights 0, all its in/out edges should weight 0.
  621. if (i == 0) {
  622. for (auto *Pred : Predecessors[BB]) {
  623. Edge E = std::make_pair(Pred, BB);
  624. EdgeWeights[E] = 0;
  625. VisitedEdges.insert(E);
  626. }
  627. } else {
  628. for (auto *Succ : Successors[BB]) {
  629. Edge E = std::make_pair(BB, Succ);
  630. EdgeWeights[E] = 0;
  631. VisitedEdges.insert(E);
  632. }
  633. }
  634. } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
  635. uint64_t &BBWeight = BlockWeights[BB];
  636. // We have a self-referential edge and the weight of BB is known.
  637. if (BBWeight >= TotalWeight)
  638. EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
  639. else
  640. EdgeWeights[SelfReferentialEdge] = 0;
  641. VisitedEdges.insert(SelfReferentialEdge);
  642. Changed = true;
  643. LLVM_DEBUG(dbgs() << "Set self-referential edge weight to: ";
  644. printEdgeWeight(dbgs(), SelfReferentialEdge));
  645. }
  646. if (UpdateBlockCount && !VisitedBlocks.count(EC) && TotalWeight > 0) {
  647. BlockWeights[EC] = TotalWeight;
  648. VisitedBlocks.insert(EC);
  649. Changed = true;
  650. }
  651. }
  652. }
  653. return Changed;
  654. }
  655. /// Build in/out edge lists for each basic block in the CFG.
  656. ///
  657. /// We are interested in unique edges. If a block B1 has multiple
  658. /// edges to another block B2, we only add a single B1->B2 edge.
  659. template <typename BT>
  660. void SampleProfileLoaderBaseImpl<BT>::buildEdges(FunctionT &F) {
  661. for (auto &BI : F) {
  662. BasicBlockT *B1 = &BI;
  663. // Add predecessors for B1.
  664. SmallPtrSet<BasicBlockT *, 16> Visited;
  665. if (!Predecessors[B1].empty())
  666. llvm_unreachable("Found a stale predecessors list in a basic block.");
  667. for (auto *B2 : getPredecessors(B1))
  668. if (Visited.insert(B2).second)
  669. Predecessors[B1].push_back(B2);
  670. // Add successors for B1.
  671. Visited.clear();
  672. if (!Successors[B1].empty())
  673. llvm_unreachable("Found a stale successors list in a basic block.");
  674. for (auto *B2 : getSuccessors(B1))
  675. if (Visited.insert(B2).second)
  676. Successors[B1].push_back(B2);
  677. }
  678. }
  679. /// Propagate weights into edges
  680. ///
  681. /// The following rules are applied to every block BB in the CFG:
  682. ///
  683. /// - If BB has a single predecessor/successor, then the weight
  684. /// of that edge is the weight of the block.
  685. ///
  686. /// - If all incoming or outgoing edges are known except one, and the
  687. /// weight of the block is already known, the weight of the unknown
  688. /// edge will be the weight of the block minus the sum of all the known
  689. /// edges. If the sum of all the known edges is larger than BB's weight,
  690. /// we set the unknown edge weight to zero.
  691. ///
  692. /// - If there is a self-referential edge, and the weight of the block is
  693. /// known, the weight for that edge is set to the weight of the block
  694. /// minus the weight of the other incoming edges to that block (if
  695. /// known).
  696. template <typename BT>
  697. void SampleProfileLoaderBaseImpl<BT>::propagateWeights(FunctionT &F) {
  698. // Flow-based profile inference is only usable with BasicBlock instantiation
  699. // of SampleProfileLoaderBaseImpl.
  700. if (SampleProfileUseProfi) {
  701. // Prepare block sample counts for inference.
  702. BlockWeightMap SampleBlockWeights;
  703. for (const auto &BI : F) {
  704. ErrorOr<uint64_t> Weight = getBlockWeight(&BI);
  705. if (Weight)
  706. SampleBlockWeights[&BI] = Weight.get();
  707. }
  708. // Fill in BlockWeights and EdgeWeights using an inference algorithm.
  709. applyProfi(F, Successors, SampleBlockWeights, BlockWeights, EdgeWeights);
  710. } else {
  711. bool Changed = true;
  712. unsigned I = 0;
  713. // If BB weight is larger than its corresponding loop's header BB weight,
  714. // use the BB weight to replace the loop header BB weight.
  715. for (auto &BI : F) {
  716. BasicBlockT *BB = &BI;
  717. LoopT *L = LI->getLoopFor(BB);
  718. if (!L) {
  719. continue;
  720. }
  721. BasicBlockT *Header = L->getHeader();
  722. if (Header && BlockWeights[BB] > BlockWeights[Header]) {
  723. BlockWeights[Header] = BlockWeights[BB];
  724. }
  725. }
  726. // Propagate until we converge or we go past the iteration limit.
  727. while (Changed && I++ < SampleProfileMaxPropagateIterations) {
  728. Changed = propagateThroughEdges(F, false);
  729. }
  730. // The first propagation propagates BB counts from annotated BBs to unknown
  731. // BBs. The 2nd propagation pass resets edges weights, and use all BB
  732. // weights to propagate edge weights.
  733. VisitedEdges.clear();
  734. Changed = true;
  735. while (Changed && I++ < SampleProfileMaxPropagateIterations) {
  736. Changed = propagateThroughEdges(F, false);
  737. }
  738. // The 3rd propagation pass allows adjust annotated BB weights that are
  739. // obviously wrong.
  740. Changed = true;
  741. while (Changed && I++ < SampleProfileMaxPropagateIterations) {
  742. Changed = propagateThroughEdges(F, true);
  743. }
  744. }
  745. }
  746. template <typename BT>
  747. void SampleProfileLoaderBaseImpl<BT>::applyProfi(
  748. FunctionT &F, BlockEdgeMap &Successors, BlockWeightMap &SampleBlockWeights,
  749. BlockWeightMap &BlockWeights, EdgeWeightMap &EdgeWeights) {
  750. auto Infer = SampleProfileInference<BT>(F, Successors, SampleBlockWeights);
  751. Infer.apply(BlockWeights, EdgeWeights);
  752. }
  753. /// Generate branch weight metadata for all branches in \p F.
  754. ///
  755. /// Branch weights are computed out of instruction samples using a
  756. /// propagation heuristic. Propagation proceeds in 3 phases:
  757. ///
  758. /// 1- Assignment of block weights. All the basic blocks in the function
  759. /// are initial assigned the same weight as their most frequently
  760. /// executed instruction.
  761. ///
  762. /// 2- Creation of equivalence classes. Since samples may be missing from
  763. /// blocks, we can fill in the gaps by setting the weights of all the
  764. /// blocks in the same equivalence class to the same weight. To compute
  765. /// the concept of equivalence, we use dominance and loop information.
  766. /// Two blocks B1 and B2 are in the same equivalence class if B1
  767. /// dominates B2, B2 post-dominates B1 and both are in the same loop.
  768. ///
  769. /// 3- Propagation of block weights into edges. This uses a simple
  770. /// propagation heuristic. The following rules are applied to every
  771. /// block BB in the CFG:
  772. ///
  773. /// - If BB has a single predecessor/successor, then the weight
  774. /// of that edge is the weight of the block.
  775. ///
  776. /// - If all the edges are known except one, and the weight of the
  777. /// block is already known, the weight of the unknown edge will
  778. /// be the weight of the block minus the sum of all the known
  779. /// edges. If the sum of all the known edges is larger than BB's weight,
  780. /// we set the unknown edge weight to zero.
  781. ///
  782. /// - If there is a self-referential edge, and the weight of the block is
  783. /// known, the weight for that edge is set to the weight of the block
  784. /// minus the weight of the other incoming edges to that block (if
  785. /// known).
  786. ///
  787. /// Since this propagation is not guaranteed to finalize for every CFG, we
  788. /// only allow it to proceed for a limited number of iterations (controlled
  789. /// by -sample-profile-max-propagate-iterations).
  790. ///
  791. /// FIXME: Try to replace this propagation heuristic with a scheme
  792. /// that is guaranteed to finalize. A work-list approach similar to
  793. /// the standard value propagation algorithm used by SSA-CCP might
  794. /// work here.
  795. ///
  796. /// \param F The function to query.
  797. ///
  798. /// \returns true if \p F was modified. Returns false, otherwise.
  799. template <typename BT>
  800. bool SampleProfileLoaderBaseImpl<BT>::computeAndPropagateWeights(
  801. FunctionT &F, const DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
  802. bool Changed = (InlinedGUIDs.size() != 0);
  803. // Compute basic block weights.
  804. Changed |= computeBlockWeights(F);
  805. if (Changed) {
  806. // Initialize propagation.
  807. initWeightPropagation(F, InlinedGUIDs);
  808. // Propagate weights to all edges.
  809. propagateWeights(F);
  810. // Post-process propagated weights.
  811. finalizeWeightPropagation(F, InlinedGUIDs);
  812. }
  813. return Changed;
  814. }
  815. template <typename BT>
  816. void SampleProfileLoaderBaseImpl<BT>::initWeightPropagation(
  817. FunctionT &F, const DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
  818. // Add an entry count to the function using the samples gathered at the
  819. // function entry.
  820. // Sets the GUIDs that are inlined in the profiled binary. This is used
  821. // for ThinLink to make correct liveness analysis, and also make the IR
  822. // match the profiled binary before annotation.
  823. getFunction(F).setEntryCount(
  824. ProfileCount(Samples->getHeadSamples() + 1, Function::PCT_Real),
  825. &InlinedGUIDs);
  826. if (!SampleProfileUseProfi) {
  827. // Compute dominance and loop info needed for propagation.
  828. computeDominanceAndLoopInfo(F);
  829. // Find equivalence classes.
  830. findEquivalenceClasses(F);
  831. }
  832. // Before propagation starts, build, for each block, a list of
  833. // unique predecessors and successors. This is necessary to handle
  834. // identical edges in multiway branches. Since we visit all blocks and all
  835. // edges of the CFG, it is cleaner to build these lists once at the start
  836. // of the pass.
  837. buildEdges(F);
  838. }
  839. template <typename BT>
  840. void SampleProfileLoaderBaseImpl<BT>::finalizeWeightPropagation(
  841. FunctionT &F, const DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
  842. // If we utilize a flow-based count inference, then we trust the computed
  843. // counts and set the entry count as computed by the algorithm. This is
  844. // primarily done to sync the counts produced by profi and BFI inference,
  845. // which uses the entry count for mass propagation.
  846. // If profi produces a zero-value for the entry count, we fallback to
  847. // Samples->getHeadSamples() + 1 to avoid functions with zero count.
  848. if (SampleProfileUseProfi) {
  849. const BasicBlockT *EntryBB = getEntryBB(&F);
  850. if (BlockWeights[EntryBB] > 0) {
  851. getFunction(F).setEntryCount(
  852. ProfileCount(BlockWeights[EntryBB], Function::PCT_Real),
  853. &InlinedGUIDs);
  854. }
  855. }
  856. }
  857. template <typename BT>
  858. void SampleProfileLoaderBaseImpl<BT>::emitCoverageRemarks(FunctionT &F) {
  859. // If coverage checking was requested, compute it now.
  860. const Function &Func = getFunction(F);
  861. if (SampleProfileRecordCoverage) {
  862. unsigned Used = CoverageTracker.countUsedRecords(Samples, PSI);
  863. unsigned Total = CoverageTracker.countBodyRecords(Samples, PSI);
  864. unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
  865. if (Coverage < SampleProfileRecordCoverage) {
  866. Func.getContext().diagnose(DiagnosticInfoSampleProfile(
  867. Func.getSubprogram()->getFilename(), getFunctionLoc(F),
  868. Twine(Used) + " of " + Twine(Total) + " available profile records (" +
  869. Twine(Coverage) + "%) were applied",
  870. DS_Warning));
  871. }
  872. }
  873. if (SampleProfileSampleCoverage) {
  874. uint64_t Used = CoverageTracker.getTotalUsedSamples();
  875. uint64_t Total = CoverageTracker.countBodySamples(Samples, PSI);
  876. unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
  877. if (Coverage < SampleProfileSampleCoverage) {
  878. Func.getContext().diagnose(DiagnosticInfoSampleProfile(
  879. Func.getSubprogram()->getFilename(), getFunctionLoc(F),
  880. Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
  881. Twine(Coverage) + "%) were applied",
  882. DS_Warning));
  883. }
  884. }
  885. }
  886. /// Get the line number for the function header.
  887. ///
  888. /// This looks up function \p F in the current compilation unit and
  889. /// retrieves the line number where the function is defined. This is
  890. /// line 0 for all the samples read from the profile file. Every line
  891. /// number is relative to this line.
  892. ///
  893. /// \param F Function object to query.
  894. ///
  895. /// \returns the line number where \p F is defined. If it returns 0,
  896. /// it means that there is no debug information available for \p F.
  897. template <typename BT>
  898. unsigned SampleProfileLoaderBaseImpl<BT>::getFunctionLoc(FunctionT &F) {
  899. const Function &Func = getFunction(F);
  900. if (DISubprogram *S = Func.getSubprogram())
  901. return S->getLine();
  902. if (NoWarnSampleUnused)
  903. return 0;
  904. // If the start of \p F is missing, emit a diagnostic to inform the user
  905. // about the missed opportunity.
  906. Func.getContext().diagnose(DiagnosticInfoSampleProfile(
  907. "No debug information found in function " + Func.getName() +
  908. ": Function profile not used",
  909. DS_Warning));
  910. return 0;
  911. }
  912. template <typename BT>
  913. void SampleProfileLoaderBaseImpl<BT>::computeDominanceAndLoopInfo(
  914. FunctionT &F) {
  915. DT.reset(new DominatorTree);
  916. DT->recalculate(F);
  917. PDT.reset(new PostDominatorTree(F));
  918. LI.reset(new LoopInfo);
  919. LI->analyze(*DT);
  920. }
  921. #undef DEBUG_TYPE
  922. } // namespace llvm
  923. #endif // LLVM_TRANSFORMS_UTILS_SAMPLEPROFILELOADERBASEIMPL_H
  924. #ifdef __GNUC__
  925. #pragma GCC diagnostic pop
  926. #endif