MachineBlockPlacement.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  1. //===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
  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. // This file implements basic block placement transformations using the CFG
  11. // structure and branch probability estimates.
  12. //
  13. // The pass strives to preserve the structure of the CFG (that is, retain
  14. // a topological ordering of basic blocks) in the absence of a *strong* signal
  15. // to the contrary from probabilities. However, within the CFG structure, it
  16. // attempts to choose an ordering which favors placing more likely sequences of
  17. // blocks adjacent to each other.
  18. //
  19. // The algorithm works from the inner-most loop within a function outward, and
  20. // at each stage walks through the basic blocks, trying to coalesce them into
  21. // sequential chains where allowed by the CFG (or demanded by heavy
  22. // probabilities). Finally, it walks the blocks in topological order, and the
  23. // first time it reaches a chain of basic blocks, it schedules them in the
  24. // function in-order.
  25. //
  26. //===----------------------------------------------------------------------===//
  27. #include "llvm/CodeGen/Passes.h"
  28. #include "llvm/ADT/DenseMap.h"
  29. #include "llvm/ADT/SmallPtrSet.h"
  30. #include "llvm/ADT/SmallVector.h"
  31. #include "llvm/ADT/Statistic.h"
  32. #include "llvm/CodeGen/MachineBasicBlock.h"
  33. #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
  34. #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
  35. #include "llvm/CodeGen/MachineFunction.h"
  36. #include "llvm/CodeGen/MachineFunctionPass.h"
  37. #include "llvm/CodeGen/MachineLoopInfo.h"
  38. #include "llvm/CodeGen/MachineModuleInfo.h"
  39. #include "llvm/Support/Allocator.h"
  40. #include "llvm/Support/CommandLine.h"
  41. #include "llvm/Support/Debug.h"
  42. #include "llvm/Target/TargetInstrInfo.h"
  43. #include "llvm/Target/TargetLowering.h"
  44. #include "llvm/Target/TargetSubtargetInfo.h"
  45. #include <algorithm>
  46. using namespace llvm;
  47. #define DEBUG_TYPE "block-placement2"
  48. STATISTIC(NumCondBranches, "Number of conditional branches");
  49. STATISTIC(NumUncondBranches, "Number of uncondittional branches");
  50. STATISTIC(CondBranchTakenFreq,
  51. "Potential frequency of taking conditional branches");
  52. STATISTIC(UncondBranchTakenFreq,
  53. "Potential frequency of taking unconditional branches");
  54. static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
  55. cl::desc("Force the alignment of all "
  56. "blocks in the function."),
  57. cl::init(0), cl::Hidden);
  58. // FIXME: Find a good default for this flag and remove the flag.
  59. static cl::opt<unsigned>
  60. ExitBlockBias("block-placement-exit-block-bias",
  61. cl::desc("Block frequency percentage a loop exit block needs "
  62. "over the original exit to be considered the new exit."),
  63. cl::init(0), cl::Hidden);
  64. namespace {
  65. class BlockChain;
  66. /// \brief Type for our function-wide basic block -> block chain mapping.
  67. typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
  68. }
  69. namespace {
  70. /// \brief A chain of blocks which will be laid out contiguously.
  71. ///
  72. /// This is the datastructure representing a chain of consecutive blocks that
  73. /// are profitable to layout together in order to maximize fallthrough
  74. /// probabilities and code locality. We also can use a block chain to represent
  75. /// a sequence of basic blocks which have some external (correctness)
  76. /// requirement for sequential layout.
  77. ///
  78. /// Chains can be built around a single basic block and can be merged to grow
  79. /// them. They participate in a block-to-chain mapping, which is updated
  80. /// automatically as chains are merged together.
  81. class BlockChain {
  82. /// \brief The sequence of blocks belonging to this chain.
  83. ///
  84. /// This is the sequence of blocks for a particular chain. These will be laid
  85. /// out in-order within the function.
  86. SmallVector<MachineBasicBlock *, 4> Blocks;
  87. /// \brief A handle to the function-wide basic block to block chain mapping.
  88. ///
  89. /// This is retained in each block chain to simplify the computation of child
  90. /// block chains for SCC-formation and iteration. We store the edges to child
  91. /// basic blocks, and map them back to their associated chains using this
  92. /// structure.
  93. BlockToChainMapType &BlockToChain;
  94. public:
  95. /// \brief Construct a new BlockChain.
  96. ///
  97. /// This builds a new block chain representing a single basic block in the
  98. /// function. It also registers itself as the chain that block participates
  99. /// in with the BlockToChain mapping.
  100. BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
  101. : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
  102. assert(BB && "Cannot create a chain with a null basic block");
  103. BlockToChain[BB] = this;
  104. }
  105. /// \brief Iterator over blocks within the chain.
  106. typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
  107. /// \brief Beginning of blocks within the chain.
  108. iterator begin() { return Blocks.begin(); }
  109. /// \brief End of blocks within the chain.
  110. iterator end() { return Blocks.end(); }
  111. /// \brief Merge a block chain into this one.
  112. ///
  113. /// This routine merges a block chain into this one. It takes care of forming
  114. /// a contiguous sequence of basic blocks, updating the edge list, and
  115. /// updating the block -> chain mapping. It does not free or tear down the
  116. /// old chain, but the old chain's block list is no longer valid.
  117. void merge(MachineBasicBlock *BB, BlockChain *Chain) {
  118. assert(BB);
  119. assert(!Blocks.empty());
  120. // Fast path in case we don't have a chain already.
  121. if (!Chain) {
  122. assert(!BlockToChain[BB]);
  123. Blocks.push_back(BB);
  124. BlockToChain[BB] = this;
  125. return;
  126. }
  127. assert(BB == *Chain->begin());
  128. assert(Chain->begin() != Chain->end());
  129. // Update the incoming blocks to point to this chain, and add them to the
  130. // chain structure.
  131. for (BlockChain::iterator BI = Chain->begin(), BE = Chain->end();
  132. BI != BE; ++BI) {
  133. Blocks.push_back(*BI);
  134. assert(BlockToChain[*BI] == Chain && "Incoming blocks not in chain");
  135. BlockToChain[*BI] = this;
  136. }
  137. }
  138. #ifndef NDEBUG
  139. /// \brief Dump the blocks in this chain.
  140. LLVM_DUMP_METHOD void dump() {
  141. for (iterator I = begin(), E = end(); I != E; ++I)
  142. (*I)->dump();
  143. }
  144. #endif // NDEBUG
  145. /// \brief Count of predecessors within the loop currently being processed.
  146. ///
  147. /// This count is updated at each loop we process to represent the number of
  148. /// in-loop predecessors of this chain.
  149. unsigned LoopPredecessors;
  150. };
  151. }
  152. namespace {
  153. class MachineBlockPlacement : public MachineFunctionPass {
  154. /// \brief A typedef for a block filter set.
  155. typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
  156. /// \brief A handle to the branch probability pass.
  157. const MachineBranchProbabilityInfo *MBPI;
  158. /// \brief A handle to the function-wide block frequency pass.
  159. const MachineBlockFrequencyInfo *MBFI;
  160. /// \brief A handle to the loop info.
  161. const MachineLoopInfo *MLI;
  162. /// \brief A handle to the target's instruction info.
  163. const TargetInstrInfo *TII;
  164. /// \brief A handle to the target's lowering info.
  165. const TargetLoweringBase *TLI;
  166. /// \brief Allocator and owner of BlockChain structures.
  167. ///
  168. /// We build BlockChains lazily while processing the loop structure of
  169. /// a function. To reduce malloc traffic, we allocate them using this
  170. /// slab-like allocator, and destroy them after the pass completes. An
  171. /// important guarantee is that this allocator produces stable pointers to
  172. /// the chains.
  173. SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
  174. /// \brief Function wide BasicBlock to BlockChain mapping.
  175. ///
  176. /// This mapping allows efficiently moving from any given basic block to the
  177. /// BlockChain it participates in, if any. We use it to, among other things,
  178. /// allow implicitly defining edges between chains as the existing edges
  179. /// between basic blocks.
  180. DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
  181. void markChainSuccessors(BlockChain &Chain,
  182. MachineBasicBlock *LoopHeaderBB,
  183. SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
  184. const BlockFilterSet *BlockFilter = nullptr);
  185. MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
  186. BlockChain &Chain,
  187. const BlockFilterSet *BlockFilter);
  188. MachineBasicBlock *selectBestCandidateBlock(
  189. BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
  190. const BlockFilterSet *BlockFilter);
  191. MachineBasicBlock *getFirstUnplacedBlock(
  192. MachineFunction &F,
  193. const BlockChain &PlacedChain,
  194. MachineFunction::iterator &PrevUnplacedBlockIt,
  195. const BlockFilterSet *BlockFilter);
  196. void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
  197. SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
  198. const BlockFilterSet *BlockFilter = nullptr);
  199. MachineBasicBlock *findBestLoopTop(MachineLoop &L,
  200. const BlockFilterSet &LoopBlockSet);
  201. MachineBasicBlock *findBestLoopExit(MachineFunction &F,
  202. MachineLoop &L,
  203. const BlockFilterSet &LoopBlockSet);
  204. void buildLoopChains(MachineFunction &F, MachineLoop &L);
  205. void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
  206. const BlockFilterSet &LoopBlockSet);
  207. void buildCFGChains(MachineFunction &F);
  208. public:
  209. static char ID; // Pass identification, replacement for typeid
  210. MachineBlockPlacement() : MachineFunctionPass(ID) {
  211. initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
  212. }
  213. bool runOnMachineFunction(MachineFunction &F) override;
  214. void getAnalysisUsage(AnalysisUsage &AU) const override {
  215. AU.addRequired<MachineBranchProbabilityInfo>();
  216. AU.addRequired<MachineBlockFrequencyInfo>();
  217. AU.addRequired<MachineLoopInfo>();
  218. MachineFunctionPass::getAnalysisUsage(AU);
  219. }
  220. };
  221. }
  222. char MachineBlockPlacement::ID = 0;
  223. char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
  224. INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement2",
  225. "Branch Probability Basic Block Placement", false, false)
  226. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  227. INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
  228. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  229. INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement2",
  230. "Branch Probability Basic Block Placement", false, false)
  231. #ifndef NDEBUG
  232. /// \brief Helper to print the name of a MBB.
  233. ///
  234. /// Only used by debug logging.
  235. static std::string getBlockName(MachineBasicBlock *BB) {
  236. std::string Result;
  237. raw_string_ostream OS(Result);
  238. OS << "BB#" << BB->getNumber()
  239. << " (derived from LLVM BB '" << BB->getName() << "')";
  240. OS.flush();
  241. return Result;
  242. }
  243. /// \brief Helper to print the number of a MBB.
  244. ///
  245. /// Only used by debug logging.
  246. static std::string getBlockNum(MachineBasicBlock *BB) {
  247. std::string Result;
  248. raw_string_ostream OS(Result);
  249. OS << "BB#" << BB->getNumber();
  250. OS.flush();
  251. return Result;
  252. }
  253. #endif
  254. /// \brief Mark a chain's successors as having one fewer preds.
  255. ///
  256. /// When a chain is being merged into the "placed" chain, this routine will
  257. /// quickly walk the successors of each block in the chain and mark them as
  258. /// having one fewer active predecessor. It also adds any successors of this
  259. /// chain which reach the zero-predecessor state to the worklist passed in.
  260. void MachineBlockPlacement::markChainSuccessors(
  261. BlockChain &Chain,
  262. MachineBasicBlock *LoopHeaderBB,
  263. SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
  264. const BlockFilterSet *BlockFilter) {
  265. // Walk all the blocks in this chain, marking their successors as having
  266. // a predecessor placed.
  267. for (BlockChain::iterator CBI = Chain.begin(), CBE = Chain.end();
  268. CBI != CBE; ++CBI) {
  269. // Add any successors for which this is the only un-placed in-loop
  270. // predecessor to the worklist as a viable candidate for CFG-neutral
  271. // placement. No subsequent placement of this block will violate the CFG
  272. // shape, so we get to use heuristics to choose a favorable placement.
  273. for (MachineBasicBlock::succ_iterator SI = (*CBI)->succ_begin(),
  274. SE = (*CBI)->succ_end();
  275. SI != SE; ++SI) {
  276. if (BlockFilter && !BlockFilter->count(*SI))
  277. continue;
  278. BlockChain &SuccChain = *BlockToChain[*SI];
  279. // Disregard edges within a fixed chain, or edges to the loop header.
  280. if (&Chain == &SuccChain || *SI == LoopHeaderBB)
  281. continue;
  282. // This is a cross-chain edge that is within the loop, so decrement the
  283. // loop predecessor count of the destination chain.
  284. if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
  285. BlockWorkList.push_back(*SuccChain.begin());
  286. }
  287. }
  288. }
  289. /// \brief Select the best successor for a block.
  290. ///
  291. /// This looks across all successors of a particular block and attempts to
  292. /// select the "best" one to be the layout successor. It only considers direct
  293. /// successors which also pass the block filter. It will attempt to avoid
  294. /// breaking CFG structure, but cave and break such structures in the case of
  295. /// very hot successor edges.
  296. ///
  297. /// \returns The best successor block found, or null if none are viable.
  298. MachineBasicBlock *MachineBlockPlacement::selectBestSuccessor(
  299. MachineBasicBlock *BB, BlockChain &Chain,
  300. const BlockFilterSet *BlockFilter) {
  301. const BranchProbability HotProb(4, 5); // 80%
  302. MachineBasicBlock *BestSucc = nullptr;
  303. // FIXME: Due to the performance of the probability and weight routines in
  304. // the MBPI analysis, we manually compute probabilities using the edge
  305. // weights. This is suboptimal as it means that the somewhat subtle
  306. // definition of edge weight semantics is encoded here as well. We should
  307. // improve the MBPI interface to efficiently support query patterns such as
  308. // this.
  309. uint32_t BestWeight = 0;
  310. uint32_t WeightScale = 0;
  311. uint32_t SumWeight = MBPI->getSumForBlock(BB, WeightScale);
  312. DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
  313. for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
  314. SE = BB->succ_end();
  315. SI != SE; ++SI) {
  316. if (BlockFilter && !BlockFilter->count(*SI))
  317. continue;
  318. BlockChain &SuccChain = *BlockToChain[*SI];
  319. if (&SuccChain == &Chain) {
  320. DEBUG(dbgs() << " " << getBlockName(*SI) << " -> Already merged!\n");
  321. continue;
  322. }
  323. if (*SI != *SuccChain.begin()) {
  324. DEBUG(dbgs() << " " << getBlockName(*SI) << " -> Mid chain!\n");
  325. continue;
  326. }
  327. uint32_t SuccWeight = MBPI->getEdgeWeight(BB, *SI);
  328. BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
  329. // Only consider successors which are either "hot", or wouldn't violate
  330. // any CFG constraints.
  331. if (SuccChain.LoopPredecessors != 0) {
  332. if (SuccProb < HotProb) {
  333. DEBUG(dbgs() << " " << getBlockName(*SI) << " -> " << SuccProb
  334. << " (prob) (CFG conflict)\n");
  335. continue;
  336. }
  337. // Make sure that a hot successor doesn't have a globally more important
  338. // predecessor.
  339. BlockFrequency CandidateEdgeFreq
  340. = MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl();
  341. bool BadCFGConflict = false;
  342. for (MachineBasicBlock::pred_iterator PI = (*SI)->pred_begin(),
  343. PE = (*SI)->pred_end();
  344. PI != PE; ++PI) {
  345. if (*PI == *SI || (BlockFilter && !BlockFilter->count(*PI)) ||
  346. BlockToChain[*PI] == &Chain)
  347. continue;
  348. BlockFrequency PredEdgeFreq
  349. = MBFI->getBlockFreq(*PI) * MBPI->getEdgeProbability(*PI, *SI);
  350. if (PredEdgeFreq >= CandidateEdgeFreq) {
  351. BadCFGConflict = true;
  352. break;
  353. }
  354. }
  355. if (BadCFGConflict) {
  356. DEBUG(dbgs() << " " << getBlockName(*SI) << " -> " << SuccProb
  357. << " (prob) (non-cold CFG conflict)\n");
  358. continue;
  359. }
  360. }
  361. DEBUG(dbgs() << " " << getBlockName(*SI) << " -> " << SuccProb
  362. << " (prob)"
  363. << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
  364. << "\n");
  365. if (BestSucc && BestWeight >= SuccWeight)
  366. continue;
  367. BestSucc = *SI;
  368. BestWeight = SuccWeight;
  369. }
  370. return BestSucc;
  371. }
  372. /// \brief Select the best block from a worklist.
  373. ///
  374. /// This looks through the provided worklist as a list of candidate basic
  375. /// blocks and select the most profitable one to place. The definition of
  376. /// profitable only really makes sense in the context of a loop. This returns
  377. /// the most frequently visited block in the worklist, which in the case of
  378. /// a loop, is the one most desirable to be physically close to the rest of the
  379. /// loop body in order to improve icache behavior.
  380. ///
  381. /// \returns The best block found, or null if none are viable.
  382. MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
  383. BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
  384. const BlockFilterSet *BlockFilter) {
  385. // Once we need to walk the worklist looking for a candidate, cleanup the
  386. // worklist of already placed entries.
  387. // FIXME: If this shows up on profiles, it could be folded (at the cost of
  388. // some code complexity) into the loop below.
  389. WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
  390. [&](MachineBasicBlock *BB) {
  391. return BlockToChain.lookup(BB) == &Chain;
  392. }),
  393. WorkList.end());
  394. MachineBasicBlock *BestBlock = nullptr;
  395. BlockFrequency BestFreq;
  396. for (SmallVectorImpl<MachineBasicBlock *>::iterator WBI = WorkList.begin(),
  397. WBE = WorkList.end();
  398. WBI != WBE; ++WBI) {
  399. BlockChain &SuccChain = *BlockToChain[*WBI];
  400. if (&SuccChain == &Chain) {
  401. DEBUG(dbgs() << " " << getBlockName(*WBI)
  402. << " -> Already merged!\n");
  403. continue;
  404. }
  405. assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
  406. BlockFrequency CandidateFreq = MBFI->getBlockFreq(*WBI);
  407. DEBUG(dbgs() << " " << getBlockName(*WBI) << " -> ";
  408. MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
  409. if (BestBlock && BestFreq >= CandidateFreq)
  410. continue;
  411. BestBlock = *WBI;
  412. BestFreq = CandidateFreq;
  413. }
  414. return BestBlock;
  415. }
  416. /// \brief Retrieve the first unplaced basic block.
  417. ///
  418. /// This routine is called when we are unable to use the CFG to walk through
  419. /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
  420. /// We walk through the function's blocks in order, starting from the
  421. /// LastUnplacedBlockIt. We update this iterator on each call to avoid
  422. /// re-scanning the entire sequence on repeated calls to this routine.
  423. MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
  424. MachineFunction &F, const BlockChain &PlacedChain,
  425. MachineFunction::iterator &PrevUnplacedBlockIt,
  426. const BlockFilterSet *BlockFilter) {
  427. for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
  428. ++I) {
  429. if (BlockFilter && !BlockFilter->count(I))
  430. continue;
  431. if (BlockToChain[I] != &PlacedChain) {
  432. PrevUnplacedBlockIt = I;
  433. // Now select the head of the chain to which the unplaced block belongs
  434. // as the block to place. This will force the entire chain to be placed,
  435. // and satisfies the requirements of merging chains.
  436. return *BlockToChain[I]->begin();
  437. }
  438. }
  439. return nullptr;
  440. }
  441. void MachineBlockPlacement::buildChain(
  442. MachineBasicBlock *BB,
  443. BlockChain &Chain,
  444. SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
  445. const BlockFilterSet *BlockFilter) {
  446. assert(BB);
  447. assert(BlockToChain[BB] == &Chain);
  448. MachineFunction &F = *BB->getParent();
  449. MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
  450. MachineBasicBlock *LoopHeaderBB = BB;
  451. markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
  452. BB = *std::prev(Chain.end());
  453. for (;;) {
  454. assert(BB);
  455. assert(BlockToChain[BB] == &Chain);
  456. assert(*std::prev(Chain.end()) == BB);
  457. // Look for the best viable successor if there is one to place immediately
  458. // after this block.
  459. MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
  460. // If an immediate successor isn't available, look for the best viable
  461. // block among those we've identified as not violating the loop's CFG at
  462. // this point. This won't be a fallthrough, but it will increase locality.
  463. if (!BestSucc)
  464. BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
  465. if (!BestSucc) {
  466. BestSucc = getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt,
  467. BlockFilter);
  468. if (!BestSucc)
  469. break;
  470. DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
  471. "layout successor until the CFG reduces\n");
  472. }
  473. // Place this block, updating the datastructures to reflect its placement.
  474. BlockChain &SuccChain = *BlockToChain[BestSucc];
  475. // Zero out LoopPredecessors for the successor we're about to merge in case
  476. // we selected a successor that didn't fit naturally into the CFG.
  477. SuccChain.LoopPredecessors = 0;
  478. DEBUG(dbgs() << "Merging from " << getBlockNum(BB)
  479. << " to " << getBlockNum(BestSucc) << "\n");
  480. markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
  481. Chain.merge(BestSucc, &SuccChain);
  482. BB = *std::prev(Chain.end());
  483. }
  484. DEBUG(dbgs() << "Finished forming chain for header block "
  485. << getBlockNum(*Chain.begin()) << "\n");
  486. }
  487. /// \brief Find the best loop top block for layout.
  488. ///
  489. /// Look for a block which is strictly better than the loop header for laying
  490. /// out at the top of the loop. This looks for one and only one pattern:
  491. /// a latch block with no conditional exit. This block will cause a conditional
  492. /// jump around it or will be the bottom of the loop if we lay it out in place,
  493. /// but if it it doesn't end up at the bottom of the loop for any reason,
  494. /// rotation alone won't fix it. Because such a block will always result in an
  495. /// unconditional jump (for the backedge) rotating it in front of the loop
  496. /// header is always profitable.
  497. MachineBasicBlock *
  498. MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
  499. const BlockFilterSet &LoopBlockSet) {
  500. // Check that the header hasn't been fused with a preheader block due to
  501. // crazy branches. If it has, we need to start with the header at the top to
  502. // prevent pulling the preheader into the loop body.
  503. BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
  504. if (!LoopBlockSet.count(*HeaderChain.begin()))
  505. return L.getHeader();
  506. DEBUG(dbgs() << "Finding best loop top for: "
  507. << getBlockName(L.getHeader()) << "\n");
  508. BlockFrequency BestPredFreq;
  509. MachineBasicBlock *BestPred = nullptr;
  510. for (MachineBasicBlock::pred_iterator PI = L.getHeader()->pred_begin(),
  511. PE = L.getHeader()->pred_end();
  512. PI != PE; ++PI) {
  513. MachineBasicBlock *Pred = *PI;
  514. if (!LoopBlockSet.count(Pred))
  515. continue;
  516. DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
  517. << Pred->succ_size() << " successors, ";
  518. MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
  519. if (Pred->succ_size() > 1)
  520. continue;
  521. BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
  522. if (!BestPred || PredFreq > BestPredFreq ||
  523. (!(PredFreq < BestPredFreq) &&
  524. Pred->isLayoutSuccessor(L.getHeader()))) {
  525. BestPred = Pred;
  526. BestPredFreq = PredFreq;
  527. }
  528. }
  529. // If no direct predecessor is fine, just use the loop header.
  530. if (!BestPred)
  531. return L.getHeader();
  532. // Walk backwards through any straight line of predecessors.
  533. while (BestPred->pred_size() == 1 &&
  534. (*BestPred->pred_begin())->succ_size() == 1 &&
  535. *BestPred->pred_begin() != L.getHeader())
  536. BestPred = *BestPred->pred_begin();
  537. DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
  538. return BestPred;
  539. }
  540. /// \brief Find the best loop exiting block for layout.
  541. ///
  542. /// This routine implements the logic to analyze the loop looking for the best
  543. /// block to layout at the top of the loop. Typically this is done to maximize
  544. /// fallthrough opportunities.
  545. MachineBasicBlock *
  546. MachineBlockPlacement::findBestLoopExit(MachineFunction &F,
  547. MachineLoop &L,
  548. const BlockFilterSet &LoopBlockSet) {
  549. // We don't want to layout the loop linearly in all cases. If the loop header
  550. // is just a normal basic block in the loop, we want to look for what block
  551. // within the loop is the best one to layout at the top. However, if the loop
  552. // header has be pre-merged into a chain due to predecessors not having
  553. // analyzable branches, *and* the predecessor it is merged with is *not* part
  554. // of the loop, rotating the header into the middle of the loop will create
  555. // a non-contiguous range of blocks which is Very Bad. So start with the
  556. // header and only rotate if safe.
  557. BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
  558. if (!LoopBlockSet.count(*HeaderChain.begin()))
  559. return nullptr;
  560. BlockFrequency BestExitEdgeFreq;
  561. unsigned BestExitLoopDepth = 0;
  562. MachineBasicBlock *ExitingBB = nullptr;
  563. // If there are exits to outer loops, loop rotation can severely limit
  564. // fallthrough opportunites unless it selects such an exit. Keep a set of
  565. // blocks where rotating to exit with that block will reach an outer loop.
  566. SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
  567. DEBUG(dbgs() << "Finding best loop exit for: "
  568. << getBlockName(L.getHeader()) << "\n");
  569. for (MachineLoop::block_iterator I = L.block_begin(),
  570. E = L.block_end();
  571. I != E; ++I) {
  572. BlockChain &Chain = *BlockToChain[*I];
  573. // Ensure that this block is at the end of a chain; otherwise it could be
  574. // mid-way through an inner loop or a successor of an analyzable branch.
  575. if (*I != *std::prev(Chain.end()))
  576. continue;
  577. // Now walk the successors. We need to establish whether this has a viable
  578. // exiting successor and whether it has a viable non-exiting successor.
  579. // We store the old exiting state and restore it if a viable looping
  580. // successor isn't found.
  581. MachineBasicBlock *OldExitingBB = ExitingBB;
  582. BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
  583. bool HasLoopingSucc = false;
  584. // FIXME: Due to the performance of the probability and weight routines in
  585. // the MBPI analysis, we use the internal weights and manually compute the
  586. // probabilities to avoid quadratic behavior.
  587. uint32_t WeightScale = 0;
  588. uint32_t SumWeight = MBPI->getSumForBlock(*I, WeightScale);
  589. for (MachineBasicBlock::succ_iterator SI = (*I)->succ_begin(),
  590. SE = (*I)->succ_end();
  591. SI != SE; ++SI) {
  592. if ((*SI)->isLandingPad())
  593. continue;
  594. if (*SI == *I)
  595. continue;
  596. BlockChain &SuccChain = *BlockToChain[*SI];
  597. // Don't split chains, either this chain or the successor's chain.
  598. if (&Chain == &SuccChain) {
  599. DEBUG(dbgs() << " exiting: " << getBlockName(*I) << " -> "
  600. << getBlockName(*SI) << " (chain conflict)\n");
  601. continue;
  602. }
  603. uint32_t SuccWeight = MBPI->getEdgeWeight(*I, *SI);
  604. if (LoopBlockSet.count(*SI)) {
  605. DEBUG(dbgs() << " looping: " << getBlockName(*I) << " -> "
  606. << getBlockName(*SI) << " (" << SuccWeight << ")\n");
  607. HasLoopingSucc = true;
  608. continue;
  609. }
  610. unsigned SuccLoopDepth = 0;
  611. if (MachineLoop *ExitLoop = MLI->getLoopFor(*SI)) {
  612. SuccLoopDepth = ExitLoop->getLoopDepth();
  613. if (ExitLoop->contains(&L))
  614. BlocksExitingToOuterLoop.insert(*I);
  615. }
  616. BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
  617. BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(*I) * SuccProb;
  618. DEBUG(dbgs() << " exiting: " << getBlockName(*I) << " -> "
  619. << getBlockName(*SI) << " [L:" << SuccLoopDepth
  620. << "] (";
  621. MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
  622. // Note that we bias this toward an existing layout successor to retain
  623. // incoming order in the absence of better information. The exit must have
  624. // a frequency higher than the current exit before we consider breaking
  625. // the layout.
  626. BranchProbability Bias(100 - ExitBlockBias, 100);
  627. if (!ExitingBB || BestExitLoopDepth < SuccLoopDepth ||
  628. ExitEdgeFreq > BestExitEdgeFreq ||
  629. ((*I)->isLayoutSuccessor(*SI) &&
  630. !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
  631. BestExitEdgeFreq = ExitEdgeFreq;
  632. ExitingBB = *I;
  633. }
  634. }
  635. // Restore the old exiting state, no viable looping successor was found.
  636. if (!HasLoopingSucc) {
  637. ExitingBB = OldExitingBB;
  638. BestExitEdgeFreq = OldBestExitEdgeFreq;
  639. continue;
  640. }
  641. }
  642. // Without a candidate exiting block or with only a single block in the
  643. // loop, just use the loop header to layout the loop.
  644. if (!ExitingBB || L.getNumBlocks() == 1)
  645. return nullptr;
  646. // Also, if we have exit blocks which lead to outer loops but didn't select
  647. // one of them as the exiting block we are rotating toward, disable loop
  648. // rotation altogether.
  649. if (!BlocksExitingToOuterLoop.empty() &&
  650. !BlocksExitingToOuterLoop.count(ExitingBB))
  651. return nullptr;
  652. DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
  653. return ExitingBB;
  654. }
  655. /// \brief Attempt to rotate an exiting block to the bottom of the loop.
  656. ///
  657. /// Once we have built a chain, try to rotate it to line up the hot exit block
  658. /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
  659. /// branches. For example, if the loop has fallthrough into its header and out
  660. /// of its bottom already, don't rotate it.
  661. void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
  662. MachineBasicBlock *ExitingBB,
  663. const BlockFilterSet &LoopBlockSet) {
  664. if (!ExitingBB)
  665. return;
  666. MachineBasicBlock *Top = *LoopChain.begin();
  667. bool ViableTopFallthrough = false;
  668. for (MachineBasicBlock::pred_iterator PI = Top->pred_begin(),
  669. PE = Top->pred_end();
  670. PI != PE; ++PI) {
  671. BlockChain *PredChain = BlockToChain[*PI];
  672. if (!LoopBlockSet.count(*PI) &&
  673. (!PredChain || *PI == *std::prev(PredChain->end()))) {
  674. ViableTopFallthrough = true;
  675. break;
  676. }
  677. }
  678. // If the header has viable fallthrough, check whether the current loop
  679. // bottom is a viable exiting block. If so, bail out as rotating will
  680. // introduce an unnecessary branch.
  681. if (ViableTopFallthrough) {
  682. MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
  683. for (MachineBasicBlock::succ_iterator SI = Bottom->succ_begin(),
  684. SE = Bottom->succ_end();
  685. SI != SE; ++SI) {
  686. BlockChain *SuccChain = BlockToChain[*SI];
  687. if (!LoopBlockSet.count(*SI) &&
  688. (!SuccChain || *SI == *SuccChain->begin()))
  689. return;
  690. }
  691. }
  692. BlockChain::iterator ExitIt = std::find(LoopChain.begin(), LoopChain.end(),
  693. ExitingBB);
  694. if (ExitIt == LoopChain.end())
  695. return;
  696. std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
  697. }
  698. /// \brief Forms basic block chains from the natural loop structures.
  699. ///
  700. /// These chains are designed to preserve the existing *structure* of the code
  701. /// as much as possible. We can then stitch the chains together in a way which
  702. /// both preserves the topological structure and minimizes taken conditional
  703. /// branches.
  704. void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
  705. MachineLoop &L) {
  706. // First recurse through any nested loops, building chains for those inner
  707. // loops.
  708. for (MachineLoop::iterator LI = L.begin(), LE = L.end(); LI != LE; ++LI)
  709. buildLoopChains(F, **LI);
  710. SmallVector<MachineBasicBlock *, 16> BlockWorkList;
  711. BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end());
  712. // First check to see if there is an obviously preferable top block for the
  713. // loop. This will default to the header, but may end up as one of the
  714. // predecessors to the header if there is one which will result in strictly
  715. // fewer branches in the loop body.
  716. MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
  717. // If we selected just the header for the loop top, look for a potentially
  718. // profitable exit block in the event that rotating the loop can eliminate
  719. // branches by placing an exit edge at the bottom.
  720. MachineBasicBlock *ExitingBB = nullptr;
  721. if (LoopTop == L.getHeader())
  722. ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
  723. BlockChain &LoopChain = *BlockToChain[LoopTop];
  724. // FIXME: This is a really lame way of walking the chains in the loop: we
  725. // walk the blocks, and use a set to prevent visiting a particular chain
  726. // twice.
  727. SmallPtrSet<BlockChain *, 4> UpdatedPreds;
  728. assert(LoopChain.LoopPredecessors == 0);
  729. UpdatedPreds.insert(&LoopChain);
  730. for (MachineLoop::block_iterator BI = L.block_begin(),
  731. BE = L.block_end();
  732. BI != BE; ++BI) {
  733. BlockChain &Chain = *BlockToChain[*BI];
  734. if (!UpdatedPreds.insert(&Chain))
  735. continue;
  736. assert(Chain.LoopPredecessors == 0);
  737. for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
  738. BCI != BCE; ++BCI) {
  739. assert(BlockToChain[*BCI] == &Chain);
  740. for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
  741. PE = (*BCI)->pred_end();
  742. PI != PE; ++PI) {
  743. if (BlockToChain[*PI] == &Chain || !LoopBlockSet.count(*PI))
  744. continue;
  745. ++Chain.LoopPredecessors;
  746. }
  747. }
  748. if (Chain.LoopPredecessors == 0)
  749. BlockWorkList.push_back(*Chain.begin());
  750. }
  751. buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
  752. rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
  753. DEBUG({
  754. // Crash at the end so we get all of the debugging output first.
  755. bool BadLoop = false;
  756. if (LoopChain.LoopPredecessors) {
  757. BadLoop = true;
  758. dbgs() << "Loop chain contains a block without its preds placed!\n"
  759. << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
  760. << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
  761. }
  762. for (BlockChain::iterator BCI = LoopChain.begin(), BCE = LoopChain.end();
  763. BCI != BCE; ++BCI) {
  764. dbgs() << " ... " << getBlockName(*BCI) << "\n";
  765. if (!LoopBlockSet.erase(*BCI)) {
  766. // We don't mark the loop as bad here because there are real situations
  767. // where this can occur. For example, with an unanalyzable fallthrough
  768. // from a loop block to a non-loop block or vice versa.
  769. dbgs() << "Loop chain contains a block not contained by the loop!\n"
  770. << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
  771. << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
  772. << " Bad block: " << getBlockName(*BCI) << "\n";
  773. }
  774. }
  775. if (!LoopBlockSet.empty()) {
  776. BadLoop = true;
  777. for (BlockFilterSet::iterator LBI = LoopBlockSet.begin(),
  778. LBE = LoopBlockSet.end();
  779. LBI != LBE; ++LBI)
  780. dbgs() << "Loop contains blocks never placed into a chain!\n"
  781. << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
  782. << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
  783. << " Bad block: " << getBlockName(*LBI) << "\n";
  784. }
  785. assert(!BadLoop && "Detected problems with the placement of this loop.");
  786. });
  787. }
  788. void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
  789. // Ensure that every BB in the function has an associated chain to simplify
  790. // the assumptions of the remaining algorithm.
  791. SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
  792. for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
  793. MachineBasicBlock *BB = FI;
  794. BlockChain *Chain
  795. = new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
  796. // Also, merge any blocks which we cannot reason about and must preserve
  797. // the exact fallthrough behavior for.
  798. for (;;) {
  799. Cond.clear();
  800. MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
  801. if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
  802. break;
  803. MachineFunction::iterator NextFI(std::next(FI));
  804. MachineBasicBlock *NextBB = NextFI;
  805. // Ensure that the layout successor is a viable block, as we know that
  806. // fallthrough is a possibility.
  807. assert(NextFI != FE && "Can't fallthrough past the last block.");
  808. DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
  809. << getBlockName(BB) << " -> " << getBlockName(NextBB)
  810. << "\n");
  811. Chain->merge(NextBB, nullptr);
  812. FI = NextFI;
  813. BB = NextBB;
  814. }
  815. }
  816. // Build any loop-based chains.
  817. for (MachineLoopInfo::iterator LI = MLI->begin(), LE = MLI->end(); LI != LE;
  818. ++LI)
  819. buildLoopChains(F, **LI);
  820. SmallVector<MachineBasicBlock *, 16> BlockWorkList;
  821. SmallPtrSet<BlockChain *, 4> UpdatedPreds;
  822. for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
  823. MachineBasicBlock *BB = &*FI;
  824. BlockChain &Chain = *BlockToChain[BB];
  825. if (!UpdatedPreds.insert(&Chain))
  826. continue;
  827. assert(Chain.LoopPredecessors == 0);
  828. for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
  829. BCI != BCE; ++BCI) {
  830. assert(BlockToChain[*BCI] == &Chain);
  831. for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
  832. PE = (*BCI)->pred_end();
  833. PI != PE; ++PI) {
  834. if (BlockToChain[*PI] == &Chain)
  835. continue;
  836. ++Chain.LoopPredecessors;
  837. }
  838. }
  839. if (Chain.LoopPredecessors == 0)
  840. BlockWorkList.push_back(*Chain.begin());
  841. }
  842. BlockChain &FunctionChain = *BlockToChain[&F.front()];
  843. buildChain(&F.front(), FunctionChain, BlockWorkList);
  844. #ifndef NDEBUG
  845. typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
  846. #endif
  847. DEBUG({
  848. // Crash at the end so we get all of the debugging output first.
  849. bool BadFunc = false;
  850. FunctionBlockSetType FunctionBlockSet;
  851. for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
  852. FunctionBlockSet.insert(FI);
  853. for (BlockChain::iterator BCI = FunctionChain.begin(),
  854. BCE = FunctionChain.end();
  855. BCI != BCE; ++BCI)
  856. if (!FunctionBlockSet.erase(*BCI)) {
  857. BadFunc = true;
  858. dbgs() << "Function chain contains a block not in the function!\n"
  859. << " Bad block: " << getBlockName(*BCI) << "\n";
  860. }
  861. if (!FunctionBlockSet.empty()) {
  862. BadFunc = true;
  863. for (FunctionBlockSetType::iterator FBI = FunctionBlockSet.begin(),
  864. FBE = FunctionBlockSet.end();
  865. FBI != FBE; ++FBI)
  866. dbgs() << "Function contains blocks never placed into a chain!\n"
  867. << " Bad block: " << getBlockName(*FBI) << "\n";
  868. }
  869. assert(!BadFunc && "Detected problems with the block placement.");
  870. });
  871. // Splice the blocks into place.
  872. MachineFunction::iterator InsertPos = F.begin();
  873. for (BlockChain::iterator BI = FunctionChain.begin(),
  874. BE = FunctionChain.end();
  875. BI != BE; ++BI) {
  876. DEBUG(dbgs() << (BI == FunctionChain.begin() ? "Placing chain "
  877. : " ... ")
  878. << getBlockName(*BI) << "\n");
  879. if (InsertPos != MachineFunction::iterator(*BI))
  880. F.splice(InsertPos, *BI);
  881. else
  882. ++InsertPos;
  883. // Update the terminator of the previous block.
  884. if (BI == FunctionChain.begin())
  885. continue;
  886. MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(*BI));
  887. // FIXME: It would be awesome of updateTerminator would just return rather
  888. // than assert when the branch cannot be analyzed in order to remove this
  889. // boiler plate.
  890. Cond.clear();
  891. MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
  892. if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
  893. // The "PrevBB" is not yet updated to reflect current code layout, so,
  894. // o. it may fall-through to a block without explict "goto" instruction
  895. // before layout, and no longer fall-through it after layout; or
  896. // o. just opposite.
  897. //
  898. // AnalyzeBranch() may return erroneous value for FBB when these two
  899. // situations take place. For the first scenario FBB is mistakenly set
  900. // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
  901. // is mistakenly pointing to "*BI".
  902. //
  903. bool needUpdateBr = true;
  904. if (!Cond.empty() && (!FBB || FBB == *BI)) {
  905. PrevBB->updateTerminator();
  906. needUpdateBr = false;
  907. Cond.clear();
  908. TBB = FBB = nullptr;
  909. if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
  910. // FIXME: This should never take place.
  911. TBB = FBB = nullptr;
  912. }
  913. }
  914. // If PrevBB has a two-way branch, try to re-order the branches
  915. // such that we branch to the successor with higher weight first.
  916. if (TBB && !Cond.empty() && FBB &&
  917. MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) &&
  918. !TII->ReverseBranchCondition(Cond)) {
  919. DEBUG(dbgs() << "Reverse order of the two branches: "
  920. << getBlockName(PrevBB) << "\n");
  921. DEBUG(dbgs() << " Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB)
  922. << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n");
  923. DebugLoc dl; // FIXME: this is nowhere
  924. TII->RemoveBranch(*PrevBB);
  925. TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
  926. needUpdateBr = true;
  927. }
  928. if (needUpdateBr)
  929. PrevBB->updateTerminator();
  930. }
  931. }
  932. // Fixup the last block.
  933. Cond.clear();
  934. MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
  935. if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
  936. F.back().updateTerminator();
  937. // Walk through the backedges of the function now that we have fully laid out
  938. // the basic blocks and align the destination of each backedge. We don't rely
  939. // exclusively on the loop info here so that we can align backedges in
  940. // unnatural CFGs and backedges that were introduced purely because of the
  941. // loop rotations done during this layout pass.
  942. if (F.getFunction()->getAttributes().
  943. hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize))
  944. return;
  945. unsigned Align = TLI->getPrefLoopAlignment();
  946. if (!Align)
  947. return; // Don't care about loop alignment.
  948. if (FunctionChain.begin() == FunctionChain.end())
  949. return; // Empty chain.
  950. const BranchProbability ColdProb(1, 5); // 20%
  951. BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
  952. BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
  953. for (BlockChain::iterator BI = std::next(FunctionChain.begin()),
  954. BE = FunctionChain.end();
  955. BI != BE; ++BI) {
  956. // Don't align non-looping basic blocks. These are unlikely to execute
  957. // enough times to matter in practice. Note that we'll still handle
  958. // unnatural CFGs inside of a natural outer loop (the common case) and
  959. // rotated loops.
  960. MachineLoop *L = MLI->getLoopFor(*BI);
  961. if (!L)
  962. continue;
  963. // If the block is cold relative to the function entry don't waste space
  964. // aligning it.
  965. BlockFrequency Freq = MBFI->getBlockFreq(*BI);
  966. if (Freq < WeightedEntryFreq)
  967. continue;
  968. // If the block is cold relative to its loop header, don't align it
  969. // regardless of what edges into the block exist.
  970. MachineBasicBlock *LoopHeader = L->getHeader();
  971. BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
  972. if (Freq < (LoopHeaderFreq * ColdProb))
  973. continue;
  974. // Check for the existence of a non-layout predecessor which would benefit
  975. // from aligning this block.
  976. MachineBasicBlock *LayoutPred = *std::prev(BI);
  977. // Force alignment if all the predecessors are jumps. We already checked
  978. // that the block isn't cold above.
  979. if (!LayoutPred->isSuccessor(*BI)) {
  980. (*BI)->setAlignment(Align);
  981. continue;
  982. }
  983. // Align this block if the layout predecessor's edge into this block is
  984. // cold relative to the block. When this is true, other predecessors make up
  985. // all of the hot entries into the block and thus alignment is likely to be
  986. // important.
  987. BranchProbability LayoutProb = MBPI->getEdgeProbability(LayoutPred, *BI);
  988. BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
  989. if (LayoutEdgeFreq <= (Freq * ColdProb))
  990. (*BI)->setAlignment(Align);
  991. }
  992. }
  993. bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
  994. // Check for single-block functions and skip them.
  995. if (std::next(F.begin()) == F.end())
  996. return false;
  997. if (skipOptnoneFunction(*F.getFunction()))
  998. return false;
  999. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  1000. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  1001. MLI = &getAnalysis<MachineLoopInfo>();
  1002. TII = F.getTarget().getSubtargetImpl()->getInstrInfo();
  1003. TLI = F.getTarget().getSubtargetImpl()->getTargetLowering();
  1004. assert(BlockToChain.empty());
  1005. buildCFGChains(F);
  1006. BlockToChain.clear();
  1007. ChainAllocator.DestroyAll();
  1008. if (AlignAllBlock)
  1009. // Align all of the blocks in the function to a specific alignment.
  1010. for (MachineFunction::iterator FI = F.begin(), FE = F.end();
  1011. FI != FE; ++FI)
  1012. FI->setAlignment(AlignAllBlock);
  1013. // We always return true as we have no way to track whether the final order
  1014. // differs from the original order.
  1015. return true;
  1016. }
  1017. namespace {
  1018. /// \brief A pass to compute block placement statistics.
  1019. ///
  1020. /// A separate pass to compute interesting statistics for evaluating block
  1021. /// placement. This is separate from the actual placement pass so that they can
  1022. /// be computed in the absence of any placement transformations or when using
  1023. /// alternative placement strategies.
  1024. class MachineBlockPlacementStats : public MachineFunctionPass {
  1025. /// \brief A handle to the branch probability pass.
  1026. const MachineBranchProbabilityInfo *MBPI;
  1027. /// \brief A handle to the function-wide block frequency pass.
  1028. const MachineBlockFrequencyInfo *MBFI;
  1029. public:
  1030. static char ID; // Pass identification, replacement for typeid
  1031. MachineBlockPlacementStats() : MachineFunctionPass(ID) {
  1032. initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
  1033. }
  1034. bool runOnMachineFunction(MachineFunction &F) override;
  1035. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1036. AU.addRequired<MachineBranchProbabilityInfo>();
  1037. AU.addRequired<MachineBlockFrequencyInfo>();
  1038. AU.setPreservesAll();
  1039. MachineFunctionPass::getAnalysisUsage(AU);
  1040. }
  1041. };
  1042. }
  1043. char MachineBlockPlacementStats::ID = 0;
  1044. char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
  1045. INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
  1046. "Basic Block Placement Stats", false, false)
  1047. INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
  1048. INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
  1049. INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
  1050. "Basic Block Placement Stats", false, false)
  1051. bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
  1052. // Check for single-block functions and skip them.
  1053. if (std::next(F.begin()) == F.end())
  1054. return false;
  1055. MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
  1056. MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
  1057. for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
  1058. BlockFrequency BlockFreq = MBFI->getBlockFreq(I);
  1059. Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches
  1060. : NumUncondBranches;
  1061. Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq
  1062. : UncondBranchTakenFreq;
  1063. for (MachineBasicBlock::succ_iterator SI = I->succ_begin(),
  1064. SE = I->succ_end();
  1065. SI != SE; ++SI) {
  1066. // Skip if this successor is a fallthrough.
  1067. if (I->isLayoutSuccessor(*SI))
  1068. continue;
  1069. BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI);
  1070. ++NumBranches;
  1071. BranchTakenFreq += EdgeFreq.getFrequency();
  1072. }
  1073. }
  1074. return false;
  1075. }