MachineBlockPlacement.cpp 47 KB

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