1 //===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements basic block placement transformations using the CFG
11 // structure and branch probability estimates.
13 // The pass strives to preserve the structure of the CFG (that is, retain
14 // a topological ordering of basic blocks) in the absense 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.
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
26 //===----------------------------------------------------------------------===//
28 #define DEBUG_TYPE "block-placement2"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
31 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/Passes.h"
37 #include "llvm/Support/Allocator.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/ADT/DenseMap.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetLowering.h"
48 STATISTIC(NumCondBranches, "Number of conditional branches");
49 STATISTIC(NumUncondBranches, "Number of uncondittional branches");
50 STATISTIC(CondBranchTakenFreq,
51 "Potential frequency of taking conditional branches");
52 STATISTIC(UncondBranchTakenFreq,
53 "Potential frequency of taking unconditional branches");
57 /// \brief Type for our function-wide basic block -> block chain mapping.
58 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
62 /// \brief A chain of blocks which will be laid out contiguously.
64 /// This is the datastructure representing a chain of consecutive blocks that
65 /// are profitable to layout together in order to maximize fallthrough
66 /// probabilities. We also can use a block chain to represent a sequence of
67 /// basic blocks which have some external (correctness) requirement for
68 /// sequential layout.
70 /// Eventually, the block chains will form a directed graph over the function.
71 /// We provide an SCC-supporting-iterator in order to quicky build and walk the
72 /// SCCs of block chains within a function.
74 /// The block chains also have support for calculating and caching probability
75 /// information related to the chain itself versus other chains. This is used
76 /// for ranking during the final layout of block chains.
78 /// \brief The sequence of blocks belonging to this chain.
80 /// This is the sequence of blocks for a particular chain. These will be laid
81 /// out in-order within the function.
82 SmallVector<MachineBasicBlock *, 4> Blocks;
84 /// \brief A handle to the function-wide basic block to block chain mapping.
86 /// This is retained in each block chain to simplify the computation of child
87 /// block chains for SCC-formation and iteration. We store the edges to child
88 /// basic blocks, and map them back to their associated chains using this
90 BlockToChainMapType &BlockToChain;
93 /// \brief Construct a new BlockChain.
95 /// This builds a new block chain representing a single basic block in the
96 /// function. It also registers itself as the chain that block participates
97 /// in with the BlockToChain mapping.
98 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
99 : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
100 assert(BB && "Cannot create a chain with a null basic block");
101 BlockToChain[BB] = this;
104 /// \brief Iterator over blocks within the chain.
105 typedef SmallVectorImpl<MachineBasicBlock *>::const_iterator iterator;
107 /// \brief Beginning of blocks within the chain.
108 iterator begin() const { return Blocks.begin(); }
110 /// \brief End of blocks within the chain.
111 iterator end() const { return Blocks.end(); }
113 /// \brief Merge a block chain into this one.
115 /// This routine merges a block chain into this one. It takes care of forming
116 /// a contiguous sequence of basic blocks, updating the edge list, and
117 /// updating the block -> chain mapping. It does not free or tear down the
118 /// old chain, but the old chain's block list is no longer valid.
119 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
121 assert(!Blocks.empty());
123 // Fast path in case we don't have a chain already.
125 assert(!BlockToChain[BB]);
126 Blocks.push_back(BB);
127 BlockToChain[BB] = this;
131 assert(BB == *Chain->begin());
132 assert(Chain->begin() != Chain->end());
134 // Update the incoming blocks to point to this chain, and add them to the
136 for (BlockChain::iterator BI = Chain->begin(), BE = Chain->end();
138 Blocks.push_back(*BI);
139 assert(BlockToChain[*BI] == Chain && "Incoming blocks not in chain");
140 BlockToChain[*BI] = this;
144 /// \brief Count of predecessors within the loop currently being processed.
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;
153 class MachineBlockPlacement : public MachineFunctionPass {
154 /// \brief A typedef for a block filter set.
155 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
157 /// \brief A handle to the branch probability pass.
158 const MachineBranchProbabilityInfo *MBPI;
160 /// \brief A handle to the function-wide block frequency pass.
161 const MachineBlockFrequencyInfo *MBFI;
163 /// \brief A handle to the loop info.
164 const MachineLoopInfo *MLI;
166 /// \brief A handle to the target's instruction info.
167 const TargetInstrInfo *TII;
169 /// \brief A handle to the target's lowering info.
170 const TargetLowering *TLI;
172 /// \brief Allocator and owner of BlockChain structures.
174 /// We build BlockChains lazily by merging together high probability BB
175 /// sequences acording to the "Algo2" in the paper mentioned at the top of
176 /// the file. To reduce malloc traffic, we allocate them using this slab-like
177 /// allocator, and destroy them after the pass completes.
178 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
180 /// \brief Function wide BasicBlock to BlockChain mapping.
182 /// This mapping allows efficiently moving from any given basic block to the
183 /// BlockChain it participates in, if any. We use it to, among other things,
184 /// allow implicitly defining edges between chains as the existing edges
185 /// between basic blocks.
186 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
188 void markChainSuccessors(BlockChain &Chain,
189 MachineBasicBlock *LoopHeaderBB,
190 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
191 const BlockFilterSet *BlockFilter = 0);
192 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
194 const BlockFilterSet *BlockFilter);
195 MachineBasicBlock *selectBestCandidateBlock(
196 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
197 const BlockFilterSet *BlockFilter);
198 MachineBasicBlock *getFirstUnplacedBlock(
200 const BlockChain &PlacedChain,
201 MachineFunction::iterator &PrevUnplacedBlockIt,
202 const BlockFilterSet *BlockFilter);
203 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
204 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
205 const BlockFilterSet *BlockFilter = 0);
206 MachineBasicBlock *findBestLoopTop(MachineFunction &F,
208 const BlockFilterSet &LoopBlockSet);
209 void buildLoopChains(MachineFunction &F, MachineLoop &L);
210 void buildCFGChains(MachineFunction &F);
211 void AlignLoops(MachineFunction &F);
214 static char ID; // Pass identification, replacement for typeid
215 MachineBlockPlacement() : MachineFunctionPass(ID) {
216 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
219 bool runOnMachineFunction(MachineFunction &F);
221 void getAnalysisUsage(AnalysisUsage &AU) const {
222 AU.addRequired<MachineBranchProbabilityInfo>();
223 AU.addRequired<MachineBlockFrequencyInfo>();
224 AU.addRequired<MachineLoopInfo>();
225 MachineFunctionPass::getAnalysisUsage(AU);
230 char MachineBlockPlacement::ID = 0;
231 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
232 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement2",
233 "Branch Probability Basic Block Placement", false, false)
234 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
235 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
236 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
237 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement2",
238 "Branch Probability Basic Block Placement", false, false)
241 /// \brief Helper to print the name of a MBB.
243 /// Only used by debug logging.
244 static std::string getBlockName(MachineBasicBlock *BB) {
246 raw_string_ostream OS(Result);
247 OS << "BB#" << BB->getNumber()
248 << " (derived from LLVM BB '" << BB->getName() << "')";
253 /// \brief Helper to print the number of a MBB.
255 /// Only used by debug logging.
256 static std::string getBlockNum(MachineBasicBlock *BB) {
258 raw_string_ostream OS(Result);
259 OS << "BB#" << BB->getNumber();
265 /// \brief Mark a chain's successors as having one fewer preds.
267 /// When a chain is being merged into the "placed" chain, this routine will
268 /// quickly walk the successors of each block in the chain and mark them as
269 /// having one fewer active predecessor. It also adds any successors of this
270 /// chain which reach the zero-predecessor state to the worklist passed in.
271 void MachineBlockPlacement::markChainSuccessors(
273 MachineBasicBlock *LoopHeaderBB,
274 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
275 const BlockFilterSet *BlockFilter) {
276 // Walk all the blocks in this chain, marking their successors as having
277 // a predecessor placed.
278 for (BlockChain::iterator CBI = Chain.begin(), CBE = Chain.end();
280 // Add any successors for which this is the only un-placed in-loop
281 // predecessor to the worklist as a viable candidate for CFG-neutral
282 // placement. No subsequent placement of this block will violate the CFG
283 // shape, so we get to use heuristics to choose a favorable placement.
284 for (MachineBasicBlock::succ_iterator SI = (*CBI)->succ_begin(),
285 SE = (*CBI)->succ_end();
287 if (BlockFilter && !BlockFilter->count(*SI))
289 BlockChain &SuccChain = *BlockToChain[*SI];
290 // Disregard edges within a fixed chain, or edges to the loop header.
291 if (&Chain == &SuccChain || *SI == LoopHeaderBB)
294 // This is a cross-chain edge that is within the loop, so decrement the
295 // loop predecessor count of the destination chain.
296 if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
297 BlockWorkList.push_back(*SuccChain.begin());
302 /// \brief Select the best successor for a block.
304 /// This looks across all successors of a particular block and attempts to
305 /// select the "best" one to be the layout successor. It only considers direct
306 /// successors which also pass the block filter. It will attempt to avoid
307 /// breaking CFG structure, but cave and break such structures in the case of
308 /// very hot successor edges.
310 /// \returns The best successor block found, or null if none are viable.
311 MachineBasicBlock *MachineBlockPlacement::selectBestSuccessor(
312 MachineBasicBlock *BB, BlockChain &Chain,
313 const BlockFilterSet *BlockFilter) {
314 const BranchProbability HotProb(4, 5); // 80%
316 MachineBasicBlock *BestSucc = 0;
317 // FIXME: Due to the performance of the probability and weight routines in
318 // the MBPI analysis, we manually compute probabilities using the edge
319 // weights. This is suboptimal as it means that the somewhat subtle
320 // definition of edge weight semantics is encoded here as well. We should
321 // improve the MBPI interface to effeciently support query patterns such as
323 uint32_t BestWeight = 0;
324 uint32_t WeightScale = 0;
325 uint32_t SumWeight = MBPI->getSumForBlock(BB, WeightScale);
326 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
327 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
330 if (BlockFilter && !BlockFilter->count(*SI))
332 BlockChain &SuccChain = *BlockToChain[*SI];
333 if (&SuccChain == &Chain) {
334 DEBUG(dbgs() << " " << getBlockName(*SI) << " -> Already merged!\n");
337 if (*SI != *SuccChain.begin()) {
338 DEBUG(dbgs() << " " << getBlockName(*SI) << " -> Mid chain!\n");
342 uint32_t SuccWeight = MBPI->getEdgeWeight(BB, *SI);
343 BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
345 // Only consider successors which are either "hot", or wouldn't violate
346 // any CFG constraints.
347 if (SuccChain.LoopPredecessors != 0) {
348 if (SuccProb < HotProb) {
349 DEBUG(dbgs() << " " << getBlockName(*SI) << " -> CFG conflict\n");
353 // Make sure that a hot successor doesn't have a globally more important
355 BlockFrequency CandidateEdgeFreq
356 = MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl();
357 bool BadCFGConflict = false;
358 for (MachineBasicBlock::pred_iterator PI = (*SI)->pred_begin(),
359 PE = (*SI)->pred_end();
361 if (*PI == *SI || (BlockFilter && !BlockFilter->count(*PI)) ||
362 BlockToChain[*PI] == &Chain)
364 BlockFrequency PredEdgeFreq
365 = MBFI->getBlockFreq(*PI) * MBPI->getEdgeProbability(*PI, *SI);
366 if (PredEdgeFreq >= CandidateEdgeFreq) {
367 BadCFGConflict = true;
371 if (BadCFGConflict) {
372 DEBUG(dbgs() << " " << getBlockName(*SI)
373 << " -> non-cold CFG conflict\n");
378 DEBUG(dbgs() << " " << getBlockName(*SI) << " -> " << SuccProb
380 << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
382 if (BestSucc && BestWeight >= SuccWeight)
385 BestWeight = SuccWeight;
391 /// \brief Predicate struct to detect blocks already placed.
392 class IsBlockPlaced {
393 const BlockChain &PlacedChain;
394 const BlockToChainMapType &BlockToChain;
397 IsBlockPlaced(const BlockChain &PlacedChain,
398 const BlockToChainMapType &BlockToChain)
399 : PlacedChain(PlacedChain), BlockToChain(BlockToChain) {}
401 bool operator()(MachineBasicBlock *BB) const {
402 return BlockToChain.lookup(BB) == &PlacedChain;
407 /// \brief Select the best block from a worklist.
409 /// This looks through the provided worklist as a list of candidate basic
410 /// blocks and select the most profitable one to place. The definition of
411 /// profitable only really makes sense in the context of a loop. This returns
412 /// the most frequently visited block in the worklist, which in the case of
413 /// a loop, is the one most desirable to be physically close to the rest of the
414 /// loop body in order to improve icache behavior.
416 /// \returns The best block found, or null if none are viable.
417 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
418 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
419 const BlockFilterSet *BlockFilter) {
420 // Once we need to walk the worklist looking for a candidate, cleanup the
421 // worklist of already placed entries.
422 // FIXME: If this shows up on profiles, it could be folded (at the cost of
423 // some code complexity) into the loop below.
424 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
425 IsBlockPlaced(Chain, BlockToChain)),
428 MachineBasicBlock *BestBlock = 0;
429 BlockFrequency BestFreq;
430 for (SmallVectorImpl<MachineBasicBlock *>::iterator WBI = WorkList.begin(),
431 WBE = WorkList.end();
433 assert(!BlockFilter || BlockFilter->count(*WBI));
434 BlockChain &SuccChain = *BlockToChain[*WBI];
435 if (&SuccChain == &Chain) {
436 DEBUG(dbgs() << " " << getBlockName(*WBI)
437 << " -> Already merged!\n");
440 assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
442 BlockFrequency CandidateFreq = MBFI->getBlockFreq(*WBI);
443 DEBUG(dbgs() << " " << getBlockName(*WBI) << " -> " << CandidateFreq
445 if (BestBlock && BestFreq >= CandidateFreq)
448 BestFreq = CandidateFreq;
453 /// \brief Retrieve the first unplaced basic block.
455 /// This routine is called when we are unable to use the CFG to walk through
456 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
457 /// We walk through the function's blocks in order, starting from the
458 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
459 /// re-scanning the entire sequence on repeated calls to this routine.
460 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
461 MachineFunction &F, const BlockChain &PlacedChain,
462 MachineFunction::iterator &PrevUnplacedBlockIt,
463 const BlockFilterSet *BlockFilter) {
464 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
466 if (BlockFilter && !BlockFilter->count(I))
468 if (BlockToChain[I] != &PlacedChain) {
469 PrevUnplacedBlockIt = I;
470 // Now select the head of the chain to which the unplaced block belongs
471 // as the block to place. This will force the entire chain to be placed,
472 // and satisfies the requirements of merging chains.
473 return *BlockToChain[I]->begin();
479 void MachineBlockPlacement::buildChain(
480 MachineBasicBlock *BB,
482 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
483 const BlockFilterSet *BlockFilter) {
485 assert(BlockToChain[BB] == &Chain);
486 MachineFunction &F = *BB->getParent();
487 MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
489 MachineBasicBlock *LoopHeaderBB = BB;
490 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
491 BB = *llvm::prior(Chain.end());
494 assert(BlockToChain[BB] == &Chain);
495 assert(*llvm::prior(Chain.end()) == BB);
496 MachineBasicBlock *BestSucc = 0;
498 // Look for the best viable successor if there is one to place immediately
500 BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
502 // If an immediate successor isn't available, look for the best viable
503 // block among those we've identified as not violating the loop's CFG at
504 // this point. This won't be a fallthrough, but it will increase locality.
506 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
509 BestSucc = getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt,
514 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
515 "layout successor until the CFG reduces\n");
518 // Place this block, updating the datastructures to reflect its placement.
519 BlockChain &SuccChain = *BlockToChain[BestSucc];
520 // Zero out LoopPredecessors for the successor we're about to merge in case
521 // we selected a successor that didn't fit naturally into the CFG.
522 SuccChain.LoopPredecessors = 0;
523 DEBUG(dbgs() << "Merging from " << getBlockNum(BB)
524 << " to " << getBlockNum(BestSucc) << "\n");
525 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
526 Chain.merge(BestSucc, &SuccChain);
527 BB = *llvm::prior(Chain.end());
530 DEBUG(dbgs() << "Finished forming chain for header block "
531 << getBlockNum(*Chain.begin()) << "\n");
534 /// \brief Find the best loop top block for layout.
536 /// This routine implements the logic to analyze the loop looking for the best
537 /// block to layout at the top of the loop. Typically this is done to maximize
538 /// fallthrough opportunities.
540 MachineBlockPlacement::findBestLoopTop(MachineFunction &F,
542 const BlockFilterSet &LoopBlockSet) {
543 BlockFrequency BestExitEdgeFreq;
544 MachineBasicBlock *ExitingBB = 0;
545 MachineBasicBlock *LoopingBB = 0;
546 // If there are exits to outer loops, loop rotation can severely limit
547 // fallthrough opportunites unless it selects such an exit. Keep a set of
548 // blocks where rotating to exit with that block will reach an outer loop.
549 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
551 DEBUG(dbgs() << "Finding best loop exit for: "
552 << getBlockName(L.getHeader()) << "\n");
553 for (MachineLoop::block_iterator I = L.block_begin(),
556 BlockChain &Chain = *BlockToChain[*I];
557 // Ensure that this block is at the end of a chain; otherwise it could be
558 // mid-way through an inner loop or a successor of an analyzable branch.
559 if (*I != *llvm::prior(Chain.end()))
562 // Now walk the successors. We need to establish whether this has a viable
563 // exiting successor and whether it has a viable non-exiting successor.
564 // We store the old exiting state and restore it if a viable looping
565 // successor isn't found.
566 MachineBasicBlock *OldExitingBB = ExitingBB;
567 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
568 // We also compute and store the best looping successor for use in layout.
569 MachineBasicBlock *BestLoopSucc = 0;
570 // FIXME: Due to the performance of the probability and weight routines in
571 // the MBPI analysis, we use the internal weights. This is only valid
572 // because it is purely a ranking function, we don't care about anything
573 // but the relative values.
574 uint32_t BestLoopSuccWeight = 0;
575 // FIXME: We also manually compute the probabilities to avoid quadratic
577 uint32_t WeightScale = 0;
578 uint32_t SumWeight = MBPI->getSumForBlock(*I, WeightScale);
579 for (MachineBasicBlock::succ_iterator SI = (*I)->succ_begin(),
580 SE = (*I)->succ_end();
582 if ((*SI)->isLandingPad())
586 BlockChain &SuccChain = *BlockToChain[*SI];
587 // Don't split chains, either this chain or the successor's chain.
588 if (&Chain == &SuccChain || *SI != *SuccChain.begin()) {
589 DEBUG(dbgs() << " " << (LoopBlockSet.count(*SI) ? "looping: "
591 << getBlockName(*I) << " -> "
592 << getBlockName(*SI) << " (chain conflict)\n");
596 uint32_t SuccWeight = MBPI->getEdgeWeight(*I, *SI);
597 if (LoopBlockSet.count(*SI)) {
598 DEBUG(dbgs() << " looping: " << getBlockName(*I) << " -> "
599 << getBlockName(*SI) << " (" << SuccWeight << ")\n");
600 if (BestLoopSucc && BestLoopSuccWeight >= SuccWeight)
604 BestLoopSuccWeight = SuccWeight;
608 BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
609 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(*I) * SuccProb;
610 DEBUG(dbgs() << " exiting: " << getBlockName(*I) << " -> "
611 << getBlockName(*SI) << " (" << ExitEdgeFreq << ")\n");
612 // Note that we slightly bias this toward an existing layout successor to
613 // retain incoming order in the absence of better information.
614 // FIXME: Should we bias this more strongly? It's pretty weak.
615 if (!ExitingBB || ExitEdgeFreq > BestExitEdgeFreq ||
616 ((*I)->isLayoutSuccessor(*SI) &&
617 !(ExitEdgeFreq < BestExitEdgeFreq))) {
618 BestExitEdgeFreq = ExitEdgeFreq;
622 if (MachineLoop *ExitLoop = MLI->getLoopFor(*SI))
623 if (ExitLoop->contains(&L))
624 BlocksExitingToOuterLoop.insert(*I);
627 // Restore the old exiting state, no viable looping successor was found.
629 ExitingBB = OldExitingBB;
630 BestExitEdgeFreq = OldBestExitEdgeFreq;
634 // If this was best exiting block thus far, also record the looping block.
636 LoopingBB = BestLoopSucc;
638 // Without a candidate exitting 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 L.getHeader();
643 // Also, if we have exit blocks which lead to outer loops but didn't select
644 // one of them as the exiting block we are rotating toward, disable loop
645 // rotation altogether.
646 if (!BlocksExitingToOuterLoop.empty() &&
647 !BlocksExitingToOuterLoop.count(ExitingBB))
648 return L.getHeader();
650 assert(LoopingBB && "All successors of a loop block are exit blocks!");
651 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
652 DEBUG(dbgs() << " Best top block: " << getBlockName(LoopingBB) << "\n");
656 /// \brief Forms basic block chains from the natural loop structures.
658 /// These chains are designed to preserve the existing *structure* of the code
659 /// as much as possible. We can then stitch the chains together in a way which
660 /// both preserves the topological structure and minimizes taken conditional
662 void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
664 // First recurse through any nested loops, building chains for those inner
666 for (MachineLoop::iterator LI = L.begin(), LE = L.end(); LI != LE; ++LI)
667 buildLoopChains(F, **LI);
669 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
670 BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end());
672 MachineBasicBlock *LayoutTop = findBestLoopTop(F, L, LoopBlockSet);
673 BlockChain &LoopChain = *BlockToChain[LayoutTop];
675 // FIXME: This is a really lame way of walking the chains in the loop: we
676 // walk the blocks, and use a set to prevent visiting a particular chain
678 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
679 assert(LoopChain.LoopPredecessors == 0);
680 UpdatedPreds.insert(&LoopChain);
681 for (MachineLoop::block_iterator BI = L.block_begin(),
684 BlockChain &Chain = *BlockToChain[*BI];
685 if (!UpdatedPreds.insert(&Chain))
688 assert(Chain.LoopPredecessors == 0);
689 for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
691 assert(BlockToChain[*BCI] == &Chain);
692 for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
693 PE = (*BCI)->pred_end();
695 if (BlockToChain[*PI] == &Chain || !LoopBlockSet.count(*PI))
697 ++Chain.LoopPredecessors;
701 if (Chain.LoopPredecessors == 0)
702 BlockWorkList.push_back(*Chain.begin());
705 buildChain(LayoutTop, LoopChain, BlockWorkList, &LoopBlockSet);
708 // Crash at the end so we get all of the debugging output first.
709 bool BadLoop = false;
710 if (LoopChain.LoopPredecessors) {
712 dbgs() << "Loop chain contains a block without its preds placed!\n"
713 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
714 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
716 for (BlockChain::iterator BCI = LoopChain.begin(), BCE = LoopChain.end();
718 if (!LoopBlockSet.erase(*BCI)) {
719 // We don't mark the loop as bad here because there are real situations
720 // where this can occur. For example, with an unanalyzable fallthrough
721 // from a loop block to a non-loop block or vice versa.
722 dbgs() << "Loop chain contains a block not contained by the loop!\n"
723 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
724 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
725 << " Bad block: " << getBlockName(*BCI) << "\n";
728 if (!LoopBlockSet.empty()) {
730 for (BlockFilterSet::iterator LBI = LoopBlockSet.begin(),
731 LBE = LoopBlockSet.end();
733 dbgs() << "Loop contains blocks never placed into a chain!\n"
734 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
735 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
736 << " Bad block: " << getBlockName(*LBI) << "\n";
738 assert(!BadLoop && "Detected problems with the placement of this loop.");
742 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
743 // Ensure that every BB in the function has an associated chain to simplify
744 // the assumptions of the remaining algorithm.
745 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
746 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
747 MachineBasicBlock *BB = FI;
749 = new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
750 // Also, merge any blocks which we cannot reason about and must preserve
751 // the exact fallthrough behavior for.
754 MachineBasicBlock *TBB = 0, *FBB = 0; // For AnalyzeBranch.
755 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
758 MachineFunction::iterator NextFI(llvm::next(FI));
759 MachineBasicBlock *NextBB = NextFI;
760 // Ensure that the layout successor is a viable block, as we know that
761 // fallthrough is a possibility.
762 assert(NextFI != FE && "Can't fallthrough past the last block.");
763 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
764 << getBlockName(BB) << " -> " << getBlockName(NextBB)
766 Chain->merge(NextBB, 0);
772 // Build any loop-based chains.
773 for (MachineLoopInfo::iterator LI = MLI->begin(), LE = MLI->end(); LI != LE;
775 buildLoopChains(F, **LI);
777 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
779 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
780 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
781 MachineBasicBlock *BB = &*FI;
782 BlockChain &Chain = *BlockToChain[BB];
783 if (!UpdatedPreds.insert(&Chain))
786 assert(Chain.LoopPredecessors == 0);
787 for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
789 assert(BlockToChain[*BCI] == &Chain);
790 for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
791 PE = (*BCI)->pred_end();
793 if (BlockToChain[*PI] == &Chain)
795 ++Chain.LoopPredecessors;
799 if (Chain.LoopPredecessors == 0)
800 BlockWorkList.push_back(*Chain.begin());
803 BlockChain &FunctionChain = *BlockToChain[&F.front()];
804 buildChain(&F.front(), FunctionChain, BlockWorkList);
806 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
808 // Crash at the end so we get all of the debugging output first.
809 bool BadFunc = false;
810 FunctionBlockSetType FunctionBlockSet;
811 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
812 FunctionBlockSet.insert(FI);
814 for (BlockChain::iterator BCI = FunctionChain.begin(),
815 BCE = FunctionChain.end();
817 if (!FunctionBlockSet.erase(*BCI)) {
819 dbgs() << "Function chain contains a block not in the function!\n"
820 << " Bad block: " << getBlockName(*BCI) << "\n";
823 if (!FunctionBlockSet.empty()) {
825 for (FunctionBlockSetType::iterator FBI = FunctionBlockSet.begin(),
826 FBE = FunctionBlockSet.end();
828 dbgs() << "Function contains blocks never placed into a chain!\n"
829 << " Bad block: " << getBlockName(*FBI) << "\n";
831 assert(!BadFunc && "Detected problems with the block placement.");
834 // Splice the blocks into place.
835 MachineFunction::iterator InsertPos = F.begin();
836 for (BlockChain::iterator BI = FunctionChain.begin(),
837 BE = FunctionChain.end();
839 DEBUG(dbgs() << (BI == FunctionChain.begin() ? "Placing chain "
841 << getBlockName(*BI) << "\n");
842 if (InsertPos != MachineFunction::iterator(*BI))
843 F.splice(InsertPos, *BI);
847 // Update the terminator of the previous block.
848 if (BI == FunctionChain.begin())
850 MachineBasicBlock *PrevBB = llvm::prior(MachineFunction::iterator(*BI));
852 // FIXME: It would be awesome of updateTerminator would just return rather
853 // than assert when the branch cannot be analyzed in order to remove this
856 MachineBasicBlock *TBB = 0, *FBB = 0; // For AnalyzeBranch.
857 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond))
858 PrevBB->updateTerminator();
861 // Fixup the last block.
863 MachineBasicBlock *TBB = 0, *FBB = 0; // For AnalyzeBranch.
864 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
865 F.back().updateTerminator();
868 /// \brief Recursive helper to align a loop and any nested loops.
869 static void AlignLoop(MachineFunction &F, MachineLoop *L, unsigned Align) {
870 // Recurse through nested loops.
871 for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
872 AlignLoop(F, *I, Align);
874 L->getTopBlock()->setAlignment(Align);
877 /// \brief Align loop headers to target preferred alignments.
878 void MachineBlockPlacement::AlignLoops(MachineFunction &F) {
879 if (F.getFunction()->hasFnAttr(Attribute::OptimizeForSize))
882 unsigned Align = TLI->getPrefLoopAlignment();
884 return; // Don't care about loop alignment.
886 for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end(); I != E; ++I)
887 AlignLoop(F, *I, Align);
890 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
891 // Check for single-block functions and skip them.
892 if (llvm::next(F.begin()) == F.end())
895 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
896 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
897 MLI = &getAnalysis<MachineLoopInfo>();
898 TII = F.getTarget().getInstrInfo();
899 TLI = F.getTarget().getTargetLowering();
900 assert(BlockToChain.empty());
905 BlockToChain.clear();
906 ChainAllocator.DestroyAll();
908 // We always return true as we have no way to track whether the final order
909 // differs from the original order.
914 /// \brief A pass to compute block placement statistics.
916 /// A separate pass to compute interesting statistics for evaluating block
917 /// placement. This is separate from the actual placement pass so that they can
918 /// be computed in the absense of any placement transformations or when using
919 /// alternative placement strategies.
920 class MachineBlockPlacementStats : public MachineFunctionPass {
921 /// \brief A handle to the branch probability pass.
922 const MachineBranchProbabilityInfo *MBPI;
924 /// \brief A handle to the function-wide block frequency pass.
925 const MachineBlockFrequencyInfo *MBFI;
928 static char ID; // Pass identification, replacement for typeid
929 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
930 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
933 bool runOnMachineFunction(MachineFunction &F);
935 void getAnalysisUsage(AnalysisUsage &AU) const {
936 AU.addRequired<MachineBranchProbabilityInfo>();
937 AU.addRequired<MachineBlockFrequencyInfo>();
938 AU.setPreservesAll();
939 MachineFunctionPass::getAnalysisUsage(AU);
944 char MachineBlockPlacementStats::ID = 0;
945 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
946 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
947 "Basic Block Placement Stats", false, false)
948 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
949 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
950 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
951 "Basic Block Placement Stats", false, false)
953 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
954 // Check for single-block functions and skip them.
955 if (llvm::next(F.begin()) == F.end())
958 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
959 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
961 for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
962 BlockFrequency BlockFreq = MBFI->getBlockFreq(I);
963 Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches
965 Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq
966 : UncondBranchTakenFreq;
967 for (MachineBasicBlock::succ_iterator SI = I->succ_begin(),
970 // Skip if this successor is a fallthrough.
971 if (I->isLayoutSuccessor(*SI))
974 BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI);
976 BranchTakenFreq += EdgeFreq.getFrequency();