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/Support/ErrorHandling.h"
40 #include "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/PostOrderIterator.h"
42 #include "llvm/ADT/SCCIterator.h"
43 #include "llvm/ADT/SmallPtrSet.h"
44 #include "llvm/ADT/SmallVector.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/Target/TargetInstrInfo.h"
47 #include "llvm/Target/TargetLowering.h"
51 STATISTIC(NumCondBranches, "Number of conditional branches");
52 STATISTIC(NumUncondBranches, "Number of uncondittional branches");
53 STATISTIC(CondBranchTakenFreq,
54 "Potential frequency of taking conditional branches");
55 STATISTIC(UncondBranchTakenFreq,
56 "Potential frequency of taking unconditional branches");
59 /// \brief A structure for storing a weighted edge.
61 /// This stores an edge and its weight, computed as the product of the
62 /// frequency that the starting block is entered with the probability of
63 /// a particular exit block.
65 BlockFrequency EdgeFrequency;
66 MachineBasicBlock *From, *To;
68 bool operator<(const WeightedEdge &RHS) const {
69 return EdgeFrequency < RHS.EdgeFrequency;
76 /// \brief Type for our function-wide basic block -> block chain mapping.
77 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
81 /// \brief A chain of blocks which will be laid out contiguously.
83 /// This is the datastructure representing a chain of consecutive blocks that
84 /// are profitable to layout together in order to maximize fallthrough
85 /// probabilities. We also can use a block chain to represent a sequence of
86 /// basic blocks which have some external (correctness) requirement for
87 /// sequential layout.
89 /// Eventually, the block chains will form a directed graph over the function.
90 /// We provide an SCC-supporting-iterator in order to quicky build and walk the
91 /// SCCs of block chains within a function.
93 /// The block chains also have support for calculating and caching probability
94 /// information related to the chain itself versus other chains. This is used
95 /// for ranking during the final layout of block chains.
97 /// \brief The sequence of blocks belonging to this chain.
99 /// This is the sequence of blocks for a particular chain. These will be laid
100 /// out in-order within the function.
101 SmallVector<MachineBasicBlock *, 4> Blocks;
103 /// \brief A handle to the function-wide basic block to block chain mapping.
105 /// This is retained in each block chain to simplify the computation of child
106 /// block chains for SCC-formation and iteration. We store the edges to child
107 /// basic blocks, and map them back to their associated chains using this
109 BlockToChainMapType &BlockToChain;
112 /// \brief Construct a new BlockChain.
114 /// This builds a new block chain representing a single basic block in the
115 /// function. It also registers itself as the chain that block participates
116 /// in with the BlockToChain mapping.
117 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
118 : Blocks(1, BB), BlockToChain(BlockToChain) {
119 assert(BB && "Cannot create a chain with a null basic block");
120 BlockToChain[BB] = this;
123 /// \brief Iterator over blocks within the chain.
124 typedef SmallVectorImpl<MachineBasicBlock *>::const_iterator iterator;
126 /// \brief Beginning of blocks within the chain.
127 iterator begin() const { return Blocks.begin(); }
129 /// \brief End of blocks within the chain.
130 iterator end() const { return Blocks.end(); }
132 /// \brief Merge a block chain into this one.
134 /// This routine merges a block chain into this one. It takes care of forming
135 /// a contiguous sequence of basic blocks, updating the edge list, and
136 /// updating the block -> chain mapping. It does not free or tear down the
137 /// old chain, but the old chain's block list is no longer valid.
138 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
140 assert(!Blocks.empty());
141 assert(Blocks.back()->isSuccessor(BB));
143 // Fast path in case we don't have a chain already.
145 assert(!BlockToChain[BB]);
146 Blocks.push_back(BB);
147 BlockToChain[BB] = this;
151 assert(BB == *Chain->begin());
152 assert(Chain->begin() != Chain->end());
154 // Update the incoming blocks to point to this chain, and add them to the
156 for (BlockChain::iterator BI = Chain->begin(), BE = Chain->end();
158 Blocks.push_back(*BI);
159 assert(BlockToChain[*BI] == Chain && "Incoming blocks not in chain");
160 BlockToChain[*BI] = this;
167 class MachineBlockPlacement : public MachineFunctionPass {
168 /// \brief A typedef for a block filter set.
169 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
171 /// \brief A handle to the branch probability pass.
172 const MachineBranchProbabilityInfo *MBPI;
174 /// \brief A handle to the function-wide block frequency pass.
175 const MachineBlockFrequencyInfo *MBFI;
177 /// \brief A handle to the loop info.
178 const MachineLoopInfo *MLI;
180 /// \brief A handle to the target's instruction info.
181 const TargetInstrInfo *TII;
183 /// \brief A handle to the target's lowering info.
184 const TargetLowering *TLI;
186 /// \brief Allocator and owner of BlockChain structures.
188 /// We build BlockChains lazily by merging together high probability BB
189 /// sequences acording to the "Algo2" in the paper mentioned at the top of
190 /// the file. To reduce malloc traffic, we allocate them using this slab-like
191 /// allocator, and destroy them after the pass completes.
192 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
194 /// \brief Function wide BasicBlock to BlockChain mapping.
196 /// This mapping allows efficiently moving from any given basic block to the
197 /// BlockChain it participates in, if any. We use it to, among other things,
198 /// allow implicitly defining edges between chains as the existing edges
199 /// between basic blocks.
200 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
202 BlockChain *CreateChain(MachineBasicBlock *BB);
203 void mergeSuccessor(MachineBasicBlock *BB, BlockChain *Chain,
204 BlockFilterSet *Filter = 0);
205 void buildLoopChains(MachineFunction &F, MachineLoop &L);
206 void buildCFGChains(MachineFunction &F);
207 void placeChainsTopologically(MachineFunction &F);
208 void AlignLoops(MachineFunction &F);
211 static char ID; // Pass identification, replacement for typeid
212 MachineBlockPlacement() : MachineFunctionPass(ID) {
213 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
216 bool runOnMachineFunction(MachineFunction &F);
218 void getAnalysisUsage(AnalysisUsage &AU) const {
219 AU.addRequired<MachineBranchProbabilityInfo>();
220 AU.addRequired<MachineBlockFrequencyInfo>();
221 AU.addRequired<MachineLoopInfo>();
222 MachineFunctionPass::getAnalysisUsage(AU);
225 const char *getPassName() const { return "Block Placement"; }
229 char MachineBlockPlacement::ID = 0;
230 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement2",
231 "Branch Probability Basic Block Placement", false, false)
232 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
233 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
234 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
235 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement2",
236 "Branch Probability Basic Block Placement", false, false)
238 FunctionPass *llvm::createMachineBlockPlacementPass() {
239 return new MachineBlockPlacement();
243 /// \brief Helper to print the name of a MBB.
245 /// Only used by debug logging.
246 static std::string getBlockName(MachineBasicBlock *BB) {
248 raw_string_ostream OS(Result);
249 OS << "BB#" << BB->getNumber()
250 << " (derived from LLVM BB '" << BB->getName() << "')";
255 /// \brief Helper to print the number of a MBB.
257 /// Only used by debug logging.
258 static std::string getBlockNum(MachineBasicBlock *BB) {
260 raw_string_ostream OS(Result);
261 OS << "BB#" << BB->getNumber();
267 /// \brief Helper to create a new chain for a single BB.
269 /// Takes care of growing the Chains, setting up the BlockChain object, and any
270 /// debug checking logic.
271 /// \returns A pointer to the new BlockChain.
272 BlockChain *MachineBlockPlacement::CreateChain(MachineBasicBlock *BB) {
274 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
278 /// \brief Merge a chain with any viable successor.
280 /// This routine walks the predecessors of the current block, looking for
281 /// viable merge candidates. It has strict rules it uses to determine when
282 /// a predecessor can be merged with the current block, which center around
283 /// preserving the CFG structure. It performs the merge if any viable candidate
285 void MachineBlockPlacement::mergeSuccessor(MachineBasicBlock *BB,
287 BlockFilterSet *Filter) {
291 // If this block is not at the end of its chain, it cannot merge with any
293 if (Chain && *llvm::prior(Chain->end()) != BB)
296 // Walk through the successors looking for the highest probability edge.
297 MachineBasicBlock *Successor = 0;
298 BranchProbability BestProb = BranchProbability::getZero();
299 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
300 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
303 if (BB == *SI || (Filter && !Filter->count(*SI)))
306 BranchProbability SuccProb = MBPI->getEdgeProbability(BB, *SI);
307 DEBUG(dbgs() << " " << getBlockName(*SI) << " -> " << SuccProb << "\n");
308 if (!Successor || SuccProb > BestProb || (!(SuccProb < BestProb) &&
309 BB->isLayoutSuccessor(*SI))) {
317 // Grab a chain if it exists already for this successor and make sure the
318 // successor is at the start of the chain as we can't merge mid-chain. Also,
319 // if the successor chain is the same as our chain, we're already merged.
320 BlockChain *SuccChain = BlockToChain[Successor];
321 if (SuccChain && (SuccChain == Chain || Successor != *SuccChain->begin()))
324 // We only merge chains across a CFG merge when the desired merge path is
325 // significantly hotter than the incoming edge. We define a hot edge more
326 // strictly than the BranchProbabilityInfo does, as the two predecessor
327 // blocks may have dramatically different incoming probabilities we need to
328 // account for. Therefor we use the "global" edge weight which is the
329 // branch's probability times the block frequency of the predecessor.
330 BlockFrequency MergeWeight = MBFI->getBlockFreq(BB);
331 MergeWeight *= MBPI->getEdgeProbability(BB, Successor);
332 // We only want to consider breaking the CFG when the merge weight is much
333 // higher (80% vs. 20%), so multiply it by 1/4. This will require the merged
334 // edge to be 4x more likely before we disrupt the CFG. This number matches
335 // the definition of "hot" in BranchProbabilityAnalysis (80% vs. 20%).
336 MergeWeight *= BranchProbability(1, 4);
337 for (MachineBasicBlock::pred_iterator PI = Successor->pred_begin(),
338 PE = Successor->pred_end();
340 if (BB == *PI || Successor == *PI) continue;
341 BlockFrequency PredWeight = MBFI->getBlockFreq(*PI);
342 PredWeight *= MBPI->getEdgeProbability(*PI, Successor);
344 // Return on the first predecessor we find which outstrips our merge weight.
345 if (MergeWeight < PredWeight)
347 DEBUG(dbgs() << "Breaking CFG edge!\n"
348 << " Edge from " << getBlockNum(BB) << " to "
349 << getBlockNum(Successor) << ": " << MergeWeight << "\n"
350 << " vs. " << getBlockNum(BB) << " to "
351 << getBlockNum(*PI) << ": " << PredWeight << "\n");
354 DEBUG(dbgs() << "Merging from " << getBlockNum(BB) << " to "
355 << getBlockNum(Successor) << "\n");
356 Chain->merge(Successor, SuccChain);
359 /// \brief Forms basic block chains from the natural loop structures.
361 /// These chains are designed to preserve the existing *structure* of the code
362 /// as much as possible. We can then stitch the chains together in a way which
363 /// both preserves the topological structure and minimizes taken conditional
365 void MachineBlockPlacement::buildLoopChains(MachineFunction &F, MachineLoop &L) {
366 // First recurse through any nested loops, building chains for those inner
368 for (MachineLoop::iterator LI = L.begin(), LE = L.end(); LI != LE; ++LI)
369 buildLoopChains(F, **LI);
371 SmallPtrSet<MachineBasicBlock *, 16> LoopBlockSet(L.block_begin(),
374 // Begin building up a set of chains of blocks within this loop which should
375 // remain contiguous. Some of the blocks already belong to a chain which
376 // represents an inner loop.
377 for (MachineLoop::block_iterator BI = L.block_begin(), BE = L.block_end();
379 MachineBasicBlock *BB = *BI;
380 BlockChain *Chain = BlockToChain[BB];
381 if (!Chain) Chain = CreateChain(BB);
382 mergeSuccessor(BB, Chain, &LoopBlockSet);
386 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
387 // First build any loop-based chains.
388 for (MachineLoopInfo::iterator LI = MLI->begin(), LE = MLI->end(); LI != LE;
390 buildLoopChains(F, **LI);
392 // Now walk the blocks of the function forming chains where they don't
393 // violate any CFG structure.
394 for (MachineFunction::iterator BI = F.begin(), BE = F.end();
396 MachineBasicBlock *BB = BI;
397 BlockChain *Chain = BlockToChain[BB];
398 if (!Chain) Chain = CreateChain(BB);
399 mergeSuccessor(BB, Chain);
403 void MachineBlockPlacement::placeChainsTopologically(MachineFunction &F) {
404 MachineBasicBlock *EntryB = &F.front();
405 assert(BlockToChain[EntryB] && "Missing chain for entry block");
406 assert(*BlockToChain[EntryB]->begin() == EntryB &&
407 "Entry block is not the head of the entry block chain");
409 // Walk the blocks in RPO, and insert each block for a chain in order the
410 // first time we see that chain.
411 MachineFunction::iterator InsertPos = F.begin();
412 SmallPtrSet<BlockChain *, 16> VisitedChains;
413 ReversePostOrderTraversal<MachineBasicBlock *> RPOT(EntryB);
414 typedef ReversePostOrderTraversal<MachineBasicBlock *>::rpo_iterator
416 for (rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
417 BlockChain *Chain = BlockToChain[*I];
419 if(!VisitedChains.insert(Chain))
421 for (BlockChain::iterator BI = Chain->begin(), BE = Chain->end(); BI != BE;
423 DEBUG(dbgs() << (BI == Chain->begin() ? "Placing chain "
425 << getBlockName(*BI) << "\n");
426 if (InsertPos != MachineFunction::iterator(*BI))
427 F.splice(InsertPos, *BI);
433 // Now that every block is in its final position, update all of the
435 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
436 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
437 // FIXME: It would be awesome of updateTerminator would just return rather
438 // than assert when the branch cannot be analyzed in order to remove this
441 MachineBasicBlock *TBB = 0, *FBB = 0; // For AnalyzeBranch.
442 if (!TII->AnalyzeBranch(*FI, TBB, FBB, Cond))
443 FI->updateTerminator();
447 /// \brief Recursive helper to align a loop and any nested loops.
448 static void AlignLoop(MachineFunction &F, MachineLoop *L, unsigned Align) {
449 // Recurse through nested loops.
450 for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
451 AlignLoop(F, *I, Align);
453 L->getTopBlock()->setAlignment(Align);
456 /// \brief Align loop headers to target preferred alignments.
457 void MachineBlockPlacement::AlignLoops(MachineFunction &F) {
458 if (F.getFunction()->hasFnAttr(Attribute::OptimizeForSize))
461 unsigned Align = TLI->getPrefLoopAlignment();
463 return; // Don't care about loop alignment.
465 for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end(); I != E; ++I)
466 AlignLoop(F, *I, Align);
469 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
470 // Check for single-block functions and skip them.
471 if (llvm::next(F.begin()) == F.end())
474 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
475 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
476 MLI = &getAnalysis<MachineLoopInfo>();
477 TII = F.getTarget().getInstrInfo();
478 TLI = F.getTarget().getTargetLowering();
479 assert(BlockToChain.empty());
482 placeChainsTopologically(F);
485 BlockToChain.clear();
487 // We always return true as we have no way to track whether the final order
488 // differs from the original order.
493 /// \brief A pass to compute block placement statistics.
495 /// A separate pass to compute interesting statistics for evaluating block
496 /// placement. This is separate from the actual placement pass so that they can
497 /// be computed in the absense of any placement transformations or when using
498 /// alternative placement strategies.
499 class MachineBlockPlacementStats : public MachineFunctionPass {
500 /// \brief A handle to the branch probability pass.
501 const MachineBranchProbabilityInfo *MBPI;
503 /// \brief A handle to the function-wide block frequency pass.
504 const MachineBlockFrequencyInfo *MBFI;
507 static char ID; // Pass identification, replacement for typeid
508 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
509 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
512 bool runOnMachineFunction(MachineFunction &F);
514 void getAnalysisUsage(AnalysisUsage &AU) const {
515 AU.addRequired<MachineBranchProbabilityInfo>();
516 AU.addRequired<MachineBlockFrequencyInfo>();
517 AU.setPreservesAll();
518 MachineFunctionPass::getAnalysisUsage(AU);
521 const char *getPassName() const { return "Block Placement Stats"; }
525 char MachineBlockPlacementStats::ID = 0;
526 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
527 "Basic Block Placement Stats", false, false)
528 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
529 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
530 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
531 "Basic Block Placement Stats", false, false)
533 FunctionPass *llvm::createMachineBlockPlacementStatsPass() {
534 return new MachineBlockPlacementStats();
537 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
538 // Check for single-block functions and skip them.
539 if (llvm::next(F.begin()) == F.end())
542 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
543 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
545 for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
546 BlockFrequency BlockFreq = MBFI->getBlockFreq(I);
547 Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches
549 Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq
550 : UncondBranchTakenFreq;
551 for (MachineBasicBlock::succ_iterator SI = I->succ_begin(),
554 // Skip if this successor is a fallthrough.
555 if (I->isLayoutSuccessor(*SI))
558 BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI);
560 BranchTakenFreq += EdgeFreq.getFrequency();