BlockFrequencyInfoImpl.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. //===- BlockFrequencyImplInfo.cpp - Block Frequency Info Implementation ---===//
  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. // Loops should be simplified before this analysis.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
  13. #include "llvm/ADT/APInt.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/SCCIterator.h"
  16. #include "llvm/Config/llvm-config.h"
  17. #include "llvm/IR/Function.h"
  18. #include "llvm/Support/BlockFrequency.h"
  19. #include "llvm/Support/BranchProbability.h"
  20. #include "llvm/Support/Compiler.h"
  21. #include "llvm/Support/Debug.h"
  22. #include "llvm/Support/MathExtras.h"
  23. #include "llvm/Support/ScaledNumber.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include <algorithm>
  26. #include <cassert>
  27. #include <cstddef>
  28. #include <cstdint>
  29. #include <iterator>
  30. #include <list>
  31. #include <numeric>
  32. #include <optional>
  33. #include <utility>
  34. #include <vector>
  35. using namespace llvm;
  36. using namespace llvm::bfi_detail;
  37. #define DEBUG_TYPE "block-freq"
  38. namespace llvm {
  39. cl::opt<bool> CheckBFIUnknownBlockQueries(
  40. "check-bfi-unknown-block-queries",
  41. cl::init(false), cl::Hidden,
  42. cl::desc("Check if block frequency is queried for an unknown block "
  43. "for debugging missed BFI updates"));
  44. cl::opt<bool> UseIterativeBFIInference(
  45. "use-iterative-bfi-inference", cl::Hidden,
  46. cl::desc("Apply an iterative post-processing to infer correct BFI counts"));
  47. cl::opt<unsigned> IterativeBFIMaxIterationsPerBlock(
  48. "iterative-bfi-max-iterations-per-block", cl::init(1000), cl::Hidden,
  49. cl::desc("Iterative inference: maximum number of update iterations "
  50. "per block"));
  51. cl::opt<double> IterativeBFIPrecision(
  52. "iterative-bfi-precision", cl::init(1e-12), cl::Hidden,
  53. cl::desc("Iterative inference: delta convergence precision; smaller values "
  54. "typically lead to better results at the cost of worsen runtime"));
  55. }
  56. ScaledNumber<uint64_t> BlockMass::toScaled() const {
  57. if (isFull())
  58. return ScaledNumber<uint64_t>(1, 0);
  59. return ScaledNumber<uint64_t>(getMass() + 1, -64);
  60. }
  61. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  62. LLVM_DUMP_METHOD void BlockMass::dump() const { print(dbgs()); }
  63. #endif
  64. static char getHexDigit(int N) {
  65. assert(N < 16);
  66. if (N < 10)
  67. return '0' + N;
  68. return 'a' + N - 10;
  69. }
  70. raw_ostream &BlockMass::print(raw_ostream &OS) const {
  71. for (int Digits = 0; Digits < 16; ++Digits)
  72. OS << getHexDigit(Mass >> (60 - Digits * 4) & 0xf);
  73. return OS;
  74. }
  75. namespace {
  76. using BlockNode = BlockFrequencyInfoImplBase::BlockNode;
  77. using Distribution = BlockFrequencyInfoImplBase::Distribution;
  78. using WeightList = BlockFrequencyInfoImplBase::Distribution::WeightList;
  79. using Scaled64 = BlockFrequencyInfoImplBase::Scaled64;
  80. using LoopData = BlockFrequencyInfoImplBase::LoopData;
  81. using Weight = BlockFrequencyInfoImplBase::Weight;
  82. using FrequencyData = BlockFrequencyInfoImplBase::FrequencyData;
  83. /// Dithering mass distributer.
  84. ///
  85. /// This class splits up a single mass into portions by weight, dithering to
  86. /// spread out error. No mass is lost. The dithering precision depends on the
  87. /// precision of the product of \a BlockMass and \a BranchProbability.
  88. ///
  89. /// The distribution algorithm follows.
  90. ///
  91. /// 1. Initialize by saving the sum of the weights in \a RemWeight and the
  92. /// mass to distribute in \a RemMass.
  93. ///
  94. /// 2. For each portion:
  95. ///
  96. /// 1. Construct a branch probability, P, as the portion's weight divided
  97. /// by the current value of \a RemWeight.
  98. /// 2. Calculate the portion's mass as \a RemMass times P.
  99. /// 3. Update \a RemWeight and \a RemMass at each portion by subtracting
  100. /// the current portion's weight and mass.
  101. struct DitheringDistributer {
  102. uint32_t RemWeight;
  103. BlockMass RemMass;
  104. DitheringDistributer(Distribution &Dist, const BlockMass &Mass);
  105. BlockMass takeMass(uint32_t Weight);
  106. };
  107. } // end anonymous namespace
  108. DitheringDistributer::DitheringDistributer(Distribution &Dist,
  109. const BlockMass &Mass) {
  110. Dist.normalize();
  111. RemWeight = Dist.Total;
  112. RemMass = Mass;
  113. }
  114. BlockMass DitheringDistributer::takeMass(uint32_t Weight) {
  115. assert(Weight && "invalid weight");
  116. assert(Weight <= RemWeight);
  117. BlockMass Mass = RemMass * BranchProbability(Weight, RemWeight);
  118. // Decrement totals (dither).
  119. RemWeight -= Weight;
  120. RemMass -= Mass;
  121. return Mass;
  122. }
  123. void Distribution::add(const BlockNode &Node, uint64_t Amount,
  124. Weight::DistType Type) {
  125. assert(Amount && "invalid weight of 0");
  126. uint64_t NewTotal = Total + Amount;
  127. // Check for overflow. It should be impossible to overflow twice.
  128. bool IsOverflow = NewTotal < Total;
  129. assert(!(DidOverflow && IsOverflow) && "unexpected repeated overflow");
  130. DidOverflow |= IsOverflow;
  131. // Update the total.
  132. Total = NewTotal;
  133. // Save the weight.
  134. Weights.push_back(Weight(Type, Node, Amount));
  135. }
  136. static void combineWeight(Weight &W, const Weight &OtherW) {
  137. assert(OtherW.TargetNode.isValid());
  138. if (!W.Amount) {
  139. W = OtherW;
  140. return;
  141. }
  142. assert(W.Type == OtherW.Type);
  143. assert(W.TargetNode == OtherW.TargetNode);
  144. assert(OtherW.Amount && "Expected non-zero weight");
  145. if (W.Amount > W.Amount + OtherW.Amount)
  146. // Saturate on overflow.
  147. W.Amount = UINT64_MAX;
  148. else
  149. W.Amount += OtherW.Amount;
  150. }
  151. static void combineWeightsBySorting(WeightList &Weights) {
  152. // Sort so edges to the same node are adjacent.
  153. llvm::sort(Weights, [](const Weight &L, const Weight &R) {
  154. return L.TargetNode < R.TargetNode;
  155. });
  156. // Combine adjacent edges.
  157. WeightList::iterator O = Weights.begin();
  158. for (WeightList::const_iterator I = O, L = O, E = Weights.end(); I != E;
  159. ++O, (I = L)) {
  160. *O = *I;
  161. // Find the adjacent weights to the same node.
  162. for (++L; L != E && I->TargetNode == L->TargetNode; ++L)
  163. combineWeight(*O, *L);
  164. }
  165. // Erase extra entries.
  166. Weights.erase(O, Weights.end());
  167. }
  168. static void combineWeightsByHashing(WeightList &Weights) {
  169. // Collect weights into a DenseMap.
  170. using HashTable = DenseMap<BlockNode::IndexType, Weight>;
  171. HashTable Combined(NextPowerOf2(2 * Weights.size()));
  172. for (const Weight &W : Weights)
  173. combineWeight(Combined[W.TargetNode.Index], W);
  174. // Check whether anything changed.
  175. if (Weights.size() == Combined.size())
  176. return;
  177. // Fill in the new weights.
  178. Weights.clear();
  179. Weights.reserve(Combined.size());
  180. for (const auto &I : Combined)
  181. Weights.push_back(I.second);
  182. }
  183. static void combineWeights(WeightList &Weights) {
  184. // Use a hash table for many successors to keep this linear.
  185. if (Weights.size() > 128) {
  186. combineWeightsByHashing(Weights);
  187. return;
  188. }
  189. combineWeightsBySorting(Weights);
  190. }
  191. static uint64_t shiftRightAndRound(uint64_t N, int Shift) {
  192. assert(Shift >= 0);
  193. assert(Shift < 64);
  194. if (!Shift)
  195. return N;
  196. return (N >> Shift) + (UINT64_C(1) & N >> (Shift - 1));
  197. }
  198. void Distribution::normalize() {
  199. // Early exit for termination nodes.
  200. if (Weights.empty())
  201. return;
  202. // Only bother if there are multiple successors.
  203. if (Weights.size() > 1)
  204. combineWeights(Weights);
  205. // Early exit when combined into a single successor.
  206. if (Weights.size() == 1) {
  207. Total = 1;
  208. Weights.front().Amount = 1;
  209. return;
  210. }
  211. // Determine how much to shift right so that the total fits into 32-bits.
  212. //
  213. // If we shift at all, shift by 1 extra. Otherwise, the lower limit of 1
  214. // for each weight can cause a 32-bit overflow.
  215. int Shift = 0;
  216. if (DidOverflow)
  217. Shift = 33;
  218. else if (Total > UINT32_MAX)
  219. Shift = 33 - countLeadingZeros(Total);
  220. // Early exit if nothing needs to be scaled.
  221. if (!Shift) {
  222. // If we didn't overflow then combineWeights() shouldn't have changed the
  223. // sum of the weights, but let's double-check.
  224. assert(Total == std::accumulate(Weights.begin(), Weights.end(), UINT64_C(0),
  225. [](uint64_t Sum, const Weight &W) {
  226. return Sum + W.Amount;
  227. }) &&
  228. "Expected total to be correct");
  229. return;
  230. }
  231. // Recompute the total through accumulation (rather than shifting it) so that
  232. // it's accurate after shifting and any changes combineWeights() made above.
  233. Total = 0;
  234. // Sum the weights to each node and shift right if necessary.
  235. for (Weight &W : Weights) {
  236. // Scale down below UINT32_MAX. Since Shift is larger than necessary, we
  237. // can round here without concern about overflow.
  238. assert(W.TargetNode.isValid());
  239. W.Amount = std::max(UINT64_C(1), shiftRightAndRound(W.Amount, Shift));
  240. assert(W.Amount <= UINT32_MAX);
  241. // Update the total.
  242. Total += W.Amount;
  243. }
  244. assert(Total <= UINT32_MAX);
  245. }
  246. void BlockFrequencyInfoImplBase::clear() {
  247. // Swap with a default-constructed std::vector, since std::vector<>::clear()
  248. // does not actually clear heap storage.
  249. std::vector<FrequencyData>().swap(Freqs);
  250. IsIrrLoopHeader.clear();
  251. std::vector<WorkingData>().swap(Working);
  252. Loops.clear();
  253. }
  254. /// Clear all memory not needed downstream.
  255. ///
  256. /// Releases all memory not used downstream. In particular, saves Freqs.
  257. static void cleanup(BlockFrequencyInfoImplBase &BFI) {
  258. std::vector<FrequencyData> SavedFreqs(std::move(BFI.Freqs));
  259. SparseBitVector<> SavedIsIrrLoopHeader(std::move(BFI.IsIrrLoopHeader));
  260. BFI.clear();
  261. BFI.Freqs = std::move(SavedFreqs);
  262. BFI.IsIrrLoopHeader = std::move(SavedIsIrrLoopHeader);
  263. }
  264. bool BlockFrequencyInfoImplBase::addToDist(Distribution &Dist,
  265. const LoopData *OuterLoop,
  266. const BlockNode &Pred,
  267. const BlockNode &Succ,
  268. uint64_t Weight) {
  269. if (!Weight)
  270. Weight = 1;
  271. auto isLoopHeader = [&OuterLoop](const BlockNode &Node) {
  272. return OuterLoop && OuterLoop->isHeader(Node);
  273. };
  274. BlockNode Resolved = Working[Succ.Index].getResolvedNode();
  275. #ifndef NDEBUG
  276. auto debugSuccessor = [&](const char *Type) {
  277. dbgs() << " =>"
  278. << " [" << Type << "] weight = " << Weight;
  279. if (!isLoopHeader(Resolved))
  280. dbgs() << ", succ = " << getBlockName(Succ);
  281. if (Resolved != Succ)
  282. dbgs() << ", resolved = " << getBlockName(Resolved);
  283. dbgs() << "\n";
  284. };
  285. (void)debugSuccessor;
  286. #endif
  287. if (isLoopHeader(Resolved)) {
  288. LLVM_DEBUG(debugSuccessor("backedge"));
  289. Dist.addBackedge(Resolved, Weight);
  290. return true;
  291. }
  292. if (Working[Resolved.Index].getContainingLoop() != OuterLoop) {
  293. LLVM_DEBUG(debugSuccessor(" exit "));
  294. Dist.addExit(Resolved, Weight);
  295. return true;
  296. }
  297. if (Resolved < Pred) {
  298. if (!isLoopHeader(Pred)) {
  299. // If OuterLoop is an irreducible loop, we can't actually handle this.
  300. assert((!OuterLoop || !OuterLoop->isIrreducible()) &&
  301. "unhandled irreducible control flow");
  302. // Irreducible backedge. Abort.
  303. LLVM_DEBUG(debugSuccessor("abort!!!"));
  304. return false;
  305. }
  306. // If "Pred" is a loop header, then this isn't really a backedge; rather,
  307. // OuterLoop must be irreducible. These false backedges can come only from
  308. // secondary loop headers.
  309. assert(OuterLoop && OuterLoop->isIrreducible() && !isLoopHeader(Resolved) &&
  310. "unhandled irreducible control flow");
  311. }
  312. LLVM_DEBUG(debugSuccessor(" local "));
  313. Dist.addLocal(Resolved, Weight);
  314. return true;
  315. }
  316. bool BlockFrequencyInfoImplBase::addLoopSuccessorsToDist(
  317. const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist) {
  318. // Copy the exit map into Dist.
  319. for (const auto &I : Loop.Exits)
  320. if (!addToDist(Dist, OuterLoop, Loop.getHeader(), I.first,
  321. I.second.getMass()))
  322. // Irreducible backedge.
  323. return false;
  324. return true;
  325. }
  326. /// Compute the loop scale for a loop.
  327. void BlockFrequencyInfoImplBase::computeLoopScale(LoopData &Loop) {
  328. // Compute loop scale.
  329. LLVM_DEBUG(dbgs() << "compute-loop-scale: " << getLoopName(Loop) << "\n");
  330. // Infinite loops need special handling. If we give the back edge an infinite
  331. // mass, they may saturate all the other scales in the function down to 1,
  332. // making all the other region temperatures look exactly the same. Choose an
  333. // arbitrary scale to avoid these issues.
  334. //
  335. // FIXME: An alternate way would be to select a symbolic scale which is later
  336. // replaced to be the maximum of all computed scales plus 1. This would
  337. // appropriately describe the loop as having a large scale, without skewing
  338. // the final frequency computation.
  339. const Scaled64 InfiniteLoopScale(1, 12);
  340. // LoopScale == 1 / ExitMass
  341. // ExitMass == HeadMass - BackedgeMass
  342. BlockMass TotalBackedgeMass;
  343. for (auto &Mass : Loop.BackedgeMass)
  344. TotalBackedgeMass += Mass;
  345. BlockMass ExitMass = BlockMass::getFull() - TotalBackedgeMass;
  346. // Block scale stores the inverse of the scale. If this is an infinite loop,
  347. // its exit mass will be zero. In this case, use an arbitrary scale for the
  348. // loop scale.
  349. Loop.Scale =
  350. ExitMass.isEmpty() ? InfiniteLoopScale : ExitMass.toScaled().inverse();
  351. LLVM_DEBUG(dbgs() << " - exit-mass = " << ExitMass << " ("
  352. << BlockMass::getFull() << " - " << TotalBackedgeMass
  353. << ")\n"
  354. << " - scale = " << Loop.Scale << "\n");
  355. }
  356. /// Package up a loop.
  357. void BlockFrequencyInfoImplBase::packageLoop(LoopData &Loop) {
  358. LLVM_DEBUG(dbgs() << "packaging-loop: " << getLoopName(Loop) << "\n");
  359. // Clear the subloop exits to prevent quadratic memory usage.
  360. for (const BlockNode &M : Loop.Nodes) {
  361. if (auto *Loop = Working[M.Index].getPackagedLoop())
  362. Loop->Exits.clear();
  363. LLVM_DEBUG(dbgs() << " - node: " << getBlockName(M.Index) << "\n");
  364. }
  365. Loop.IsPackaged = true;
  366. }
  367. #ifndef NDEBUG
  368. static void debugAssign(const BlockFrequencyInfoImplBase &BFI,
  369. const DitheringDistributer &D, const BlockNode &T,
  370. const BlockMass &M, const char *Desc) {
  371. dbgs() << " => assign " << M << " (" << D.RemMass << ")";
  372. if (Desc)
  373. dbgs() << " [" << Desc << "]";
  374. if (T.isValid())
  375. dbgs() << " to " << BFI.getBlockName(T);
  376. dbgs() << "\n";
  377. }
  378. #endif
  379. void BlockFrequencyInfoImplBase::distributeMass(const BlockNode &Source,
  380. LoopData *OuterLoop,
  381. Distribution &Dist) {
  382. BlockMass Mass = Working[Source.Index].getMass();
  383. LLVM_DEBUG(dbgs() << " => mass: " << Mass << "\n");
  384. // Distribute mass to successors as laid out in Dist.
  385. DitheringDistributer D(Dist, Mass);
  386. for (const Weight &W : Dist.Weights) {
  387. // Check for a local edge (non-backedge and non-exit).
  388. BlockMass Taken = D.takeMass(W.Amount);
  389. if (W.Type == Weight::Local) {
  390. Working[W.TargetNode.Index].getMass() += Taken;
  391. LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
  392. continue;
  393. }
  394. // Backedges and exits only make sense if we're processing a loop.
  395. assert(OuterLoop && "backedge or exit outside of loop");
  396. // Check for a backedge.
  397. if (W.Type == Weight::Backedge) {
  398. OuterLoop->BackedgeMass[OuterLoop->getHeaderIndex(W.TargetNode)] += Taken;
  399. LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "back"));
  400. continue;
  401. }
  402. // This must be an exit.
  403. assert(W.Type == Weight::Exit);
  404. OuterLoop->Exits.push_back(std::make_pair(W.TargetNode, Taken));
  405. LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, "exit"));
  406. }
  407. }
  408. static void convertFloatingToInteger(BlockFrequencyInfoImplBase &BFI,
  409. const Scaled64 &Min, const Scaled64 &Max) {
  410. // Scale the Factor to a size that creates integers. Ideally, integers would
  411. // be scaled so that Max == UINT64_MAX so that they can be best
  412. // differentiated. However, in the presence of large frequency values, small
  413. // frequencies are scaled down to 1, making it impossible to differentiate
  414. // small, unequal numbers. When the spread between Min and Max frequencies
  415. // fits well within MaxBits, we make the scale be at least 8.
  416. const unsigned MaxBits = 64;
  417. const unsigned SpreadBits = (Max / Min).lg();
  418. Scaled64 ScalingFactor;
  419. if (SpreadBits <= MaxBits - 3) {
  420. // If the values are small enough, make the scaling factor at least 8 to
  421. // allow distinguishing small values.
  422. ScalingFactor = Min.inverse();
  423. ScalingFactor <<= 3;
  424. } else {
  425. // If the values need more than MaxBits to be represented, saturate small
  426. // frequency values down to 1 by using a scaling factor that benefits large
  427. // frequency values.
  428. ScalingFactor = Scaled64(1, MaxBits) / Max;
  429. }
  430. // Translate the floats to integers.
  431. LLVM_DEBUG(dbgs() << "float-to-int: min = " << Min << ", max = " << Max
  432. << ", factor = " << ScalingFactor << "\n");
  433. for (size_t Index = 0; Index < BFI.Freqs.size(); ++Index) {
  434. Scaled64 Scaled = BFI.Freqs[Index].Scaled * ScalingFactor;
  435. BFI.Freqs[Index].Integer = std::max(UINT64_C(1), Scaled.toInt<uint64_t>());
  436. LLVM_DEBUG(dbgs() << " - " << BFI.getBlockName(Index) << ": float = "
  437. << BFI.Freqs[Index].Scaled << ", scaled = " << Scaled
  438. << ", int = " << BFI.Freqs[Index].Integer << "\n");
  439. }
  440. }
  441. /// Unwrap a loop package.
  442. ///
  443. /// Visits all the members of a loop, adjusting their BlockData according to
  444. /// the loop's pseudo-node.
  445. static void unwrapLoop(BlockFrequencyInfoImplBase &BFI, LoopData &Loop) {
  446. LLVM_DEBUG(dbgs() << "unwrap-loop-package: " << BFI.getLoopName(Loop)
  447. << ": mass = " << Loop.Mass << ", scale = " << Loop.Scale
  448. << "\n");
  449. Loop.Scale *= Loop.Mass.toScaled();
  450. Loop.IsPackaged = false;
  451. LLVM_DEBUG(dbgs() << " => combined-scale = " << Loop.Scale << "\n");
  452. // Propagate the head scale through the loop. Since members are visited in
  453. // RPO, the head scale will be updated by the loop scale first, and then the
  454. // final head scale will be used for updated the rest of the members.
  455. for (const BlockNode &N : Loop.Nodes) {
  456. const auto &Working = BFI.Working[N.Index];
  457. Scaled64 &F = Working.isAPackage() ? Working.getPackagedLoop()->Scale
  458. : BFI.Freqs[N.Index].Scaled;
  459. Scaled64 New = Loop.Scale * F;
  460. LLVM_DEBUG(dbgs() << " - " << BFI.getBlockName(N) << ": " << F << " => "
  461. << New << "\n");
  462. F = New;
  463. }
  464. }
  465. void BlockFrequencyInfoImplBase::unwrapLoops() {
  466. // Set initial frequencies from loop-local masses.
  467. for (size_t Index = 0; Index < Working.size(); ++Index)
  468. Freqs[Index].Scaled = Working[Index].Mass.toScaled();
  469. for (LoopData &Loop : Loops)
  470. unwrapLoop(*this, Loop);
  471. }
  472. void BlockFrequencyInfoImplBase::finalizeMetrics() {
  473. // Unwrap loop packages in reverse post-order, tracking min and max
  474. // frequencies.
  475. auto Min = Scaled64::getLargest();
  476. auto Max = Scaled64::getZero();
  477. for (size_t Index = 0; Index < Working.size(); ++Index) {
  478. // Update min/max scale.
  479. Min = std::min(Min, Freqs[Index].Scaled);
  480. Max = std::max(Max, Freqs[Index].Scaled);
  481. }
  482. // Convert to integers.
  483. convertFloatingToInteger(*this, Min, Max);
  484. // Clean up data structures.
  485. cleanup(*this);
  486. // Print out the final stats.
  487. LLVM_DEBUG(dump());
  488. }
  489. BlockFrequency
  490. BlockFrequencyInfoImplBase::getBlockFreq(const BlockNode &Node) const {
  491. if (!Node.isValid()) {
  492. #ifndef NDEBUG
  493. if (CheckBFIUnknownBlockQueries) {
  494. SmallString<256> Msg;
  495. raw_svector_ostream OS(Msg);
  496. OS << "*** Detected BFI query for unknown block " << getBlockName(Node);
  497. report_fatal_error(OS.str());
  498. }
  499. #endif
  500. return 0;
  501. }
  502. return Freqs[Node.Index].Integer;
  503. }
  504. std::optional<uint64_t>
  505. BlockFrequencyInfoImplBase::getBlockProfileCount(const Function &F,
  506. const BlockNode &Node,
  507. bool AllowSynthetic) const {
  508. return getProfileCountFromFreq(F, getBlockFreq(Node).getFrequency(),
  509. AllowSynthetic);
  510. }
  511. std::optional<uint64_t>
  512. BlockFrequencyInfoImplBase::getProfileCountFromFreq(const Function &F,
  513. uint64_t Freq,
  514. bool AllowSynthetic) const {
  515. auto EntryCount = F.getEntryCount(AllowSynthetic);
  516. if (!EntryCount)
  517. return std::nullopt;
  518. // Use 128 bit APInt to do the arithmetic to avoid overflow.
  519. APInt BlockCount(128, EntryCount->getCount());
  520. APInt BlockFreq(128, Freq);
  521. APInt EntryFreq(128, getEntryFreq());
  522. BlockCount *= BlockFreq;
  523. // Rounded division of BlockCount by EntryFreq. Since EntryFreq is unsigned
  524. // lshr by 1 gives EntryFreq/2.
  525. BlockCount = (BlockCount + EntryFreq.lshr(1)).udiv(EntryFreq);
  526. return BlockCount.getLimitedValue();
  527. }
  528. bool
  529. BlockFrequencyInfoImplBase::isIrrLoopHeader(const BlockNode &Node) {
  530. if (!Node.isValid())
  531. return false;
  532. return IsIrrLoopHeader.test(Node.Index);
  533. }
  534. Scaled64
  535. BlockFrequencyInfoImplBase::getFloatingBlockFreq(const BlockNode &Node) const {
  536. if (!Node.isValid())
  537. return Scaled64::getZero();
  538. return Freqs[Node.Index].Scaled;
  539. }
  540. void BlockFrequencyInfoImplBase::setBlockFreq(const BlockNode &Node,
  541. uint64_t Freq) {
  542. assert(Node.isValid() && "Expected valid node");
  543. assert(Node.Index < Freqs.size() && "Expected legal index");
  544. Freqs[Node.Index].Integer = Freq;
  545. }
  546. std::string
  547. BlockFrequencyInfoImplBase::getBlockName(const BlockNode &Node) const {
  548. return {};
  549. }
  550. std::string
  551. BlockFrequencyInfoImplBase::getLoopName(const LoopData &Loop) const {
  552. return getBlockName(Loop.getHeader()) + (Loop.isIrreducible() ? "**" : "*");
  553. }
  554. raw_ostream &
  555. BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
  556. const BlockNode &Node) const {
  557. return OS << getFloatingBlockFreq(Node);
  558. }
  559. raw_ostream &
  560. BlockFrequencyInfoImplBase::printBlockFreq(raw_ostream &OS,
  561. const BlockFrequency &Freq) const {
  562. Scaled64 Block(Freq.getFrequency(), 0);
  563. Scaled64 Entry(getEntryFreq(), 0);
  564. return OS << Block / Entry;
  565. }
  566. void IrreducibleGraph::addNodesInLoop(const BFIBase::LoopData &OuterLoop) {
  567. Start = OuterLoop.getHeader();
  568. Nodes.reserve(OuterLoop.Nodes.size());
  569. for (auto N : OuterLoop.Nodes)
  570. addNode(N);
  571. indexNodes();
  572. }
  573. void IrreducibleGraph::addNodesInFunction() {
  574. Start = 0;
  575. for (uint32_t Index = 0; Index < BFI.Working.size(); ++Index)
  576. if (!BFI.Working[Index].isPackaged())
  577. addNode(Index);
  578. indexNodes();
  579. }
  580. void IrreducibleGraph::indexNodes() {
  581. for (auto &I : Nodes)
  582. Lookup[I.Node.Index] = &I;
  583. }
  584. void IrreducibleGraph::addEdge(IrrNode &Irr, const BlockNode &Succ,
  585. const BFIBase::LoopData *OuterLoop) {
  586. if (OuterLoop && OuterLoop->isHeader(Succ))
  587. return;
  588. auto L = Lookup.find(Succ.Index);
  589. if (L == Lookup.end())
  590. return;
  591. IrrNode &SuccIrr = *L->second;
  592. Irr.Edges.push_back(&SuccIrr);
  593. SuccIrr.Edges.push_front(&Irr);
  594. ++SuccIrr.NumIn;
  595. }
  596. namespace llvm {
  597. template <> struct GraphTraits<IrreducibleGraph> {
  598. using GraphT = bfi_detail::IrreducibleGraph;
  599. using NodeRef = const GraphT::IrrNode *;
  600. using ChildIteratorType = GraphT::IrrNode::iterator;
  601. static NodeRef getEntryNode(const GraphT &G) { return G.StartIrr; }
  602. static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
  603. static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
  604. };
  605. } // end namespace llvm
  606. /// Find extra irreducible headers.
  607. ///
  608. /// Find entry blocks and other blocks with backedges, which exist when \c G
  609. /// contains irreducible sub-SCCs.
  610. static void findIrreducibleHeaders(
  611. const BlockFrequencyInfoImplBase &BFI,
  612. const IrreducibleGraph &G,
  613. const std::vector<const IrreducibleGraph::IrrNode *> &SCC,
  614. LoopData::NodeList &Headers, LoopData::NodeList &Others) {
  615. // Map from nodes in the SCC to whether it's an entry block.
  616. SmallDenseMap<const IrreducibleGraph::IrrNode *, bool, 8> InSCC;
  617. // InSCC also acts the set of nodes in the graph. Seed it.
  618. for (const auto *I : SCC)
  619. InSCC[I] = false;
  620. for (auto I = InSCC.begin(), E = InSCC.end(); I != E; ++I) {
  621. auto &Irr = *I->first;
  622. for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
  623. if (InSCC.count(P))
  624. continue;
  625. // This is an entry block.
  626. I->second = true;
  627. Headers.push_back(Irr.Node);
  628. LLVM_DEBUG(dbgs() << " => entry = " << BFI.getBlockName(Irr.Node)
  629. << "\n");
  630. break;
  631. }
  632. }
  633. assert(Headers.size() >= 2 &&
  634. "Expected irreducible CFG; -loop-info is likely invalid");
  635. if (Headers.size() == InSCC.size()) {
  636. // Every block is a header.
  637. llvm::sort(Headers);
  638. return;
  639. }
  640. // Look for extra headers from irreducible sub-SCCs.
  641. for (const auto &I : InSCC) {
  642. // Entry blocks are already headers.
  643. if (I.second)
  644. continue;
  645. auto &Irr = *I.first;
  646. for (const auto *P : make_range(Irr.pred_begin(), Irr.pred_end())) {
  647. // Skip forward edges.
  648. if (P->Node < Irr.Node)
  649. continue;
  650. // Skip predecessors from entry blocks. These can have inverted
  651. // ordering.
  652. if (InSCC.lookup(P))
  653. continue;
  654. // Store the extra header.
  655. Headers.push_back(Irr.Node);
  656. LLVM_DEBUG(dbgs() << " => extra = " << BFI.getBlockName(Irr.Node)
  657. << "\n");
  658. break;
  659. }
  660. if (Headers.back() == Irr.Node)
  661. // Added this as a header.
  662. continue;
  663. // This is not a header.
  664. Others.push_back(Irr.Node);
  665. LLVM_DEBUG(dbgs() << " => other = " << BFI.getBlockName(Irr.Node) << "\n");
  666. }
  667. llvm::sort(Headers);
  668. llvm::sort(Others);
  669. }
  670. static void createIrreducibleLoop(
  671. BlockFrequencyInfoImplBase &BFI, const IrreducibleGraph &G,
  672. LoopData *OuterLoop, std::list<LoopData>::iterator Insert,
  673. const std::vector<const IrreducibleGraph::IrrNode *> &SCC) {
  674. // Translate the SCC into RPO.
  675. LLVM_DEBUG(dbgs() << " - found-scc\n");
  676. LoopData::NodeList Headers;
  677. LoopData::NodeList Others;
  678. findIrreducibleHeaders(BFI, G, SCC, Headers, Others);
  679. auto Loop = BFI.Loops.emplace(Insert, OuterLoop, Headers.begin(),
  680. Headers.end(), Others.begin(), Others.end());
  681. // Update loop hierarchy.
  682. for (const auto &N : Loop->Nodes)
  683. if (BFI.Working[N.Index].isLoopHeader())
  684. BFI.Working[N.Index].Loop->Parent = &*Loop;
  685. else
  686. BFI.Working[N.Index].Loop = &*Loop;
  687. }
  688. iterator_range<std::list<LoopData>::iterator>
  689. BlockFrequencyInfoImplBase::analyzeIrreducible(
  690. const IrreducibleGraph &G, LoopData *OuterLoop,
  691. std::list<LoopData>::iterator Insert) {
  692. assert((OuterLoop == nullptr) == (Insert == Loops.begin()));
  693. auto Prev = OuterLoop ? std::prev(Insert) : Loops.end();
  694. for (auto I = scc_begin(G); !I.isAtEnd(); ++I) {
  695. if (I->size() < 2)
  696. continue;
  697. // Translate the SCC into RPO.
  698. createIrreducibleLoop(*this, G, OuterLoop, Insert, *I);
  699. }
  700. if (OuterLoop)
  701. return make_range(std::next(Prev), Insert);
  702. return make_range(Loops.begin(), Insert);
  703. }
  704. void
  705. BlockFrequencyInfoImplBase::updateLoopWithIrreducible(LoopData &OuterLoop) {
  706. OuterLoop.Exits.clear();
  707. for (auto &Mass : OuterLoop.BackedgeMass)
  708. Mass = BlockMass::getEmpty();
  709. auto O = OuterLoop.Nodes.begin() + 1;
  710. for (auto I = O, E = OuterLoop.Nodes.end(); I != E; ++I)
  711. if (!Working[I->Index].isPackaged())
  712. *O++ = *I;
  713. OuterLoop.Nodes.erase(O, OuterLoop.Nodes.end());
  714. }
  715. void BlockFrequencyInfoImplBase::adjustLoopHeaderMass(LoopData &Loop) {
  716. assert(Loop.isIrreducible() && "this only makes sense on irreducible loops");
  717. // Since the loop has more than one header block, the mass flowing back into
  718. // each header will be different. Adjust the mass in each header loop to
  719. // reflect the masses flowing through back edges.
  720. //
  721. // To do this, we distribute the initial mass using the backedge masses
  722. // as weights for the distribution.
  723. BlockMass LoopMass = BlockMass::getFull();
  724. Distribution Dist;
  725. LLVM_DEBUG(dbgs() << "adjust-loop-header-mass:\n");
  726. for (uint32_t H = 0; H < Loop.NumHeaders; ++H) {
  727. auto &HeaderNode = Loop.Nodes[H];
  728. auto &BackedgeMass = Loop.BackedgeMass[Loop.getHeaderIndex(HeaderNode)];
  729. LLVM_DEBUG(dbgs() << " - Add back edge mass for node "
  730. << getBlockName(HeaderNode) << ": " << BackedgeMass
  731. << "\n");
  732. if (BackedgeMass.getMass() > 0)
  733. Dist.addLocal(HeaderNode, BackedgeMass.getMass());
  734. else
  735. LLVM_DEBUG(dbgs() << " Nothing added. Back edge mass is zero\n");
  736. }
  737. DitheringDistributer D(Dist, LoopMass);
  738. LLVM_DEBUG(dbgs() << " Distribute loop mass " << LoopMass
  739. << " to headers using above weights\n");
  740. for (const Weight &W : Dist.Weights) {
  741. BlockMass Taken = D.takeMass(W.Amount);
  742. assert(W.Type == Weight::Local && "all weights should be local");
  743. Working[W.TargetNode.Index].getMass() = Taken;
  744. LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
  745. }
  746. }
  747. void BlockFrequencyInfoImplBase::distributeIrrLoopHeaderMass(Distribution &Dist) {
  748. BlockMass LoopMass = BlockMass::getFull();
  749. DitheringDistributer D(Dist, LoopMass);
  750. for (const Weight &W : Dist.Weights) {
  751. BlockMass Taken = D.takeMass(W.Amount);
  752. assert(W.Type == Weight::Local && "all weights should be local");
  753. Working[W.TargetNode.Index].getMass() = Taken;
  754. LLVM_DEBUG(debugAssign(*this, D, W.TargetNode, Taken, nullptr));
  755. }
  756. }