2
0

BlockFrequencyInfoImpl.cpp 25 KB

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