MachineBlockPlacement.cpp 48 KB

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