Home | History | Annotate | Download | only in Utils
      1 //===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
      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 // BreakCriticalEdges pass - Break all of the critical edges in the CFG by
     11 // inserting a dummy basic block.  This pass may be "required" by passes that
     12 // cannot deal with critical edges.  For this usage, the structure type is
     13 // forward declared.  This pass obviously invalidates the CFG, but can update
     14 // dominator trees.
     15 //
     16 //===----------------------------------------------------------------------===//
     17 
     18 #define DEBUG_TYPE "break-crit-edges"
     19 #include "llvm/Transforms/Scalar.h"
     20 #include "llvm/ADT/SmallVector.h"
     21 #include "llvm/ADT/Statistic.h"
     22 #include "llvm/Analysis/CFG.h"
     23 #include "llvm/Analysis/Dominators.h"
     24 #include "llvm/Analysis/LoopInfo.h"
     25 #include "llvm/Analysis/ProfileInfo.h"
     26 #include "llvm/IR/Function.h"
     27 #include "llvm/IR/Instructions.h"
     28 #include "llvm/IR/Type.h"
     29 #include "llvm/Support/CFG.h"
     30 #include "llvm/Support/ErrorHandling.h"
     31 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
     32 using namespace llvm;
     33 
     34 STATISTIC(NumBroken, "Number of blocks inserted");
     35 
     36 namespace {
     37   struct BreakCriticalEdges : public FunctionPass {
     38     static char ID; // Pass identification, replacement for typeid
     39     BreakCriticalEdges() : FunctionPass(ID) {
     40       initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
     41     }
     42 
     43     virtual bool runOnFunction(Function &F);
     44 
     45     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
     46       AU.addPreserved<DominatorTree>();
     47       AU.addPreserved<LoopInfo>();
     48       AU.addPreserved<ProfileInfo>();
     49 
     50       // No loop canonicalization guarantees are broken by this pass.
     51       AU.addPreservedID(LoopSimplifyID);
     52     }
     53   };
     54 }
     55 
     56 char BreakCriticalEdges::ID = 0;
     57 INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
     58                 "Break critical edges in CFG", false, false)
     59 
     60 // Publicly exposed interface to pass...
     61 char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
     62 FunctionPass *llvm::createBreakCriticalEdgesPass() {
     63   return new BreakCriticalEdges();
     64 }
     65 
     66 // runOnFunction - Loop over all of the edges in the CFG, breaking critical
     67 // edges as they are found.
     68 //
     69 bool BreakCriticalEdges::runOnFunction(Function &F) {
     70   bool Changed = false;
     71   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
     72     TerminatorInst *TI = I->getTerminator();
     73     if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
     74       for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
     75         if (SplitCriticalEdge(TI, i, this)) {
     76           ++NumBroken;
     77           Changed = true;
     78         }
     79   }
     80 
     81   return Changed;
     82 }
     83 
     84 //===----------------------------------------------------------------------===//
     85 //    Implementation of the external critical edge manipulation functions
     86 //===----------------------------------------------------------------------===//
     87 
     88 /// createPHIsForSplitLoopExit - When a loop exit edge is split, LCSSA form
     89 /// may require new PHIs in the new exit block. This function inserts the
     90 /// new PHIs, as needed. Preds is a list of preds inside the loop, SplitBB
     91 /// is the new loop exit block, and DestBB is the old loop exit, now the
     92 /// successor of SplitBB.
     93 static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
     94                                        BasicBlock *SplitBB,
     95                                        BasicBlock *DestBB) {
     96   // SplitBB shouldn't have anything non-trivial in it yet.
     97   assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
     98           SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
     99 
    100   // For each PHI in the destination block.
    101   for (BasicBlock::iterator I = DestBB->begin();
    102        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
    103     unsigned Idx = PN->getBasicBlockIndex(SplitBB);
    104     Value *V = PN->getIncomingValue(Idx);
    105 
    106     // If the input is a PHI which already satisfies LCSSA, don't create
    107     // a new one.
    108     if (const PHINode *VP = dyn_cast<PHINode>(V))
    109       if (VP->getParent() == SplitBB)
    110         continue;
    111 
    112     // Otherwise a new PHI is needed. Create one and populate it.
    113     PHINode *NewPN =
    114       PHINode::Create(PN->getType(), Preds.size(), "split",
    115                       SplitBB->isLandingPad() ?
    116                       SplitBB->begin() : SplitBB->getTerminator());
    117     for (unsigned i = 0, e = Preds.size(); i != e; ++i)
    118       NewPN->addIncoming(V, Preds[i]);
    119 
    120     // Update the original PHI.
    121     PN->setIncomingValue(Idx, NewPN);
    122   }
    123 }
    124 
    125 /// SplitCriticalEdge - If this edge is a critical edge, insert a new node to
    126 /// split the critical edge.  This will update DominatorTree information if it
    127 /// is available, thus calling this pass will not invalidate either of them.
    128 /// This returns the new block if the edge was split, null otherwise.
    129 ///
    130 /// If MergeIdenticalEdges is true (not the default), *all* edges from TI to the
    131 /// specified successor will be merged into the same critical edge block.
    132 /// This is most commonly interesting with switch instructions, which may
    133 /// have many edges to any one destination.  This ensures that all edges to that
    134 /// dest go to one block instead of each going to a different block, but isn't
    135 /// the standard definition of a "critical edge".
    136 ///
    137 /// It is invalid to call this function on a critical edge that starts at an
    138 /// IndirectBrInst.  Splitting these edges will almost always create an invalid
    139 /// program because the address of the new block won't be the one that is jumped
    140 /// to.
    141 ///
    142 BasicBlock *llvm::SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum,
    143                                     Pass *P, bool MergeIdenticalEdges,
    144                                     bool DontDeleteUselessPhis,
    145                                     bool SplitLandingPads) {
    146   if (!isCriticalEdge(TI, SuccNum, MergeIdenticalEdges)) return 0;
    147 
    148   assert(!isa<IndirectBrInst>(TI) &&
    149          "Cannot split critical edge from IndirectBrInst");
    150 
    151   BasicBlock *TIBB = TI->getParent();
    152   BasicBlock *DestBB = TI->getSuccessor(SuccNum);
    153 
    154   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
    155   // it in this generic function.
    156   if (DestBB->isLandingPad()) return 0;
    157 
    158   // Create a new basic block, linking it into the CFG.
    159   BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
    160                       TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
    161   // Create our unconditional branch.
    162   BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
    163   NewBI->setDebugLoc(TI->getDebugLoc());
    164 
    165   // Branch to the new block, breaking the edge.
    166   TI->setSuccessor(SuccNum, NewBB);
    167 
    168   // Insert the block into the function... right after the block TI lives in.
    169   Function &F = *TIBB->getParent();
    170   Function::iterator FBBI = TIBB;
    171   F.getBasicBlockList().insert(++FBBI, NewBB);
    172 
    173   // If there are any PHI nodes in DestBB, we need to update them so that they
    174   // merge incoming values from NewBB instead of from TIBB.
    175   {
    176     unsigned BBIdx = 0;
    177     for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
    178       // We no longer enter through TIBB, now we come in through NewBB.
    179       // Revector exactly one entry in the PHI node that used to come from
    180       // TIBB to come from NewBB.
    181       PHINode *PN = cast<PHINode>(I);
    182 
    183       // Reuse the previous value of BBIdx if it lines up.  In cases where we
    184       // have multiple phi nodes with *lots* of predecessors, this is a speed
    185       // win because we don't have to scan the PHI looking for TIBB.  This
    186       // happens because the BB list of PHI nodes are usually in the same
    187       // order.
    188       if (PN->getIncomingBlock(BBIdx) != TIBB)
    189         BBIdx = PN->getBasicBlockIndex(TIBB);
    190       PN->setIncomingBlock(BBIdx, NewBB);
    191     }
    192   }
    193 
    194   // If there are any other edges from TIBB to DestBB, update those to go
    195   // through the split block, making those edges non-critical as well (and
    196   // reducing the number of phi entries in the DestBB if relevant).
    197   if (MergeIdenticalEdges) {
    198     for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
    199       if (TI->getSuccessor(i) != DestBB) continue;
    200 
    201       // Remove an entry for TIBB from DestBB phi nodes.
    202       DestBB->removePredecessor(TIBB, DontDeleteUselessPhis);
    203 
    204       // We found another edge to DestBB, go to NewBB instead.
    205       TI->setSuccessor(i, NewBB);
    206     }
    207   }
    208 
    209 
    210 
    211   // If we don't have a pass object, we can't update anything...
    212   if (P == 0) return NewBB;
    213 
    214   DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
    215   LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>();
    216   ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
    217 
    218   // If we have nothing to update, just return.
    219   if (DT == 0 && LI == 0 && PI == 0)
    220     return NewBB;
    221 
    222   // Now update analysis information.  Since the only predecessor of NewBB is
    223   // the TIBB, TIBB clearly dominates NewBB.  TIBB usually doesn't dominate
    224   // anything, as there are other successors of DestBB.  However, if all other
    225   // predecessors of DestBB are already dominated by DestBB (e.g. DestBB is a
    226   // loop header) then NewBB dominates DestBB.
    227   SmallVector<BasicBlock*, 8> OtherPreds;
    228 
    229   // If there is a PHI in the block, loop over predecessors with it, which is
    230   // faster than iterating pred_begin/end.
    231   if (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
    232     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
    233       if (PN->getIncomingBlock(i) != NewBB)
    234         OtherPreds.push_back(PN->getIncomingBlock(i));
    235   } else {
    236     for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB);
    237          I != E; ++I) {
    238       BasicBlock *P = *I;
    239       if (P != NewBB)
    240         OtherPreds.push_back(P);
    241     }
    242   }
    243 
    244   bool NewBBDominatesDestBB = true;
    245 
    246   // Should we update DominatorTree information?
    247   if (DT) {
    248     DomTreeNode *TINode = DT->getNode(TIBB);
    249 
    250     // The new block is not the immediate dominator for any other nodes, but
    251     // TINode is the immediate dominator for the new node.
    252     //
    253     if (TINode) {       // Don't break unreachable code!
    254       DomTreeNode *NewBBNode = DT->addNewBlock(NewBB, TIBB);
    255       DomTreeNode *DestBBNode = 0;
    256 
    257       // If NewBBDominatesDestBB hasn't been computed yet, do so with DT.
    258       if (!OtherPreds.empty()) {
    259         DestBBNode = DT->getNode(DestBB);
    260         while (!OtherPreds.empty() && NewBBDominatesDestBB) {
    261           if (DomTreeNode *OPNode = DT->getNode(OtherPreds.back()))
    262             NewBBDominatesDestBB = DT->dominates(DestBBNode, OPNode);
    263           OtherPreds.pop_back();
    264         }
    265         OtherPreds.clear();
    266       }
    267 
    268       // If NewBBDominatesDestBB, then NewBB dominates DestBB, otherwise it
    269       // doesn't dominate anything.
    270       if (NewBBDominatesDestBB) {
    271         if (!DestBBNode) DestBBNode = DT->getNode(DestBB);
    272         DT->changeImmediateDominator(DestBBNode, NewBBNode);
    273       }
    274     }
    275   }
    276 
    277   // Update LoopInfo if it is around.
    278   if (LI) {
    279     if (Loop *TIL = LI->getLoopFor(TIBB)) {
    280       // If one or the other blocks were not in a loop, the new block is not
    281       // either, and thus LI doesn't need to be updated.
    282       if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
    283         if (TIL == DestLoop) {
    284           // Both in the same loop, the NewBB joins loop.
    285           DestLoop->addBasicBlockToLoop(NewBB, LI->getBase());
    286         } else if (TIL->contains(DestLoop)) {
    287           // Edge from an outer loop to an inner loop.  Add to the outer loop.
    288           TIL->addBasicBlockToLoop(NewBB, LI->getBase());
    289         } else if (DestLoop->contains(TIL)) {
    290           // Edge from an inner loop to an outer loop.  Add to the outer loop.
    291           DestLoop->addBasicBlockToLoop(NewBB, LI->getBase());
    292         } else {
    293           // Edge from two loops with no containment relation.  Because these
    294           // are natural loops, we know that the destination block must be the
    295           // header of its loop (adding a branch into a loop elsewhere would
    296           // create an irreducible loop).
    297           assert(DestLoop->getHeader() == DestBB &&
    298                  "Should not create irreducible loops!");
    299           if (Loop *P = DestLoop->getParentLoop())
    300             P->addBasicBlockToLoop(NewBB, LI->getBase());
    301         }
    302       }
    303       // If TIBB is in a loop and DestBB is outside of that loop, split the
    304       // other exit blocks of the loop that also have predecessors outside
    305       // the loop, to maintain a LoopSimplify guarantee.
    306       if (!TIL->contains(DestBB) &&
    307           P->mustPreserveAnalysisID(LoopSimplifyID)) {
    308         assert(!TIL->contains(NewBB) &&
    309                "Split point for loop exit is contained in loop!");
    310 
    311         // Update LCSSA form in the newly created exit block.
    312         if (P->mustPreserveAnalysisID(LCSSAID))
    313           createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
    314 
    315         // For each unique exit block...
    316         // FIXME: This code is functionally equivalent to the corresponding
    317         // loop in LoopSimplify.
    318         SmallVector<BasicBlock *, 4> ExitBlocks;
    319         TIL->getExitBlocks(ExitBlocks);
    320         for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
    321           // Collect all the preds that are inside the loop, and note
    322           // whether there are any preds outside the loop.
    323           SmallVector<BasicBlock *, 4> Preds;
    324           bool HasPredOutsideOfLoop = false;
    325           BasicBlock *Exit = ExitBlocks[i];
    326           for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit);
    327                I != E; ++I) {
    328             BasicBlock *P = *I;
    329             if (TIL->contains(P)) {
    330               if (isa<IndirectBrInst>(P->getTerminator())) {
    331                 Preds.clear();
    332                 break;
    333               }
    334               Preds.push_back(P);
    335             } else {
    336               HasPredOutsideOfLoop = true;
    337             }
    338           }
    339           // If there are any preds not in the loop, we'll need to split
    340           // the edges. The Preds.empty() check is needed because a block
    341           // may appear multiple times in the list. We can't use
    342           // getUniqueExitBlocks above because that depends on LoopSimplify
    343           // form, which we're in the process of restoring!
    344           if (!Preds.empty() && HasPredOutsideOfLoop) {
    345             if (!Exit->isLandingPad()) {
    346               BasicBlock *NewExitBB =
    347                 SplitBlockPredecessors(Exit, Preds, "split", P);
    348               if (P->mustPreserveAnalysisID(LCSSAID))
    349                 createPHIsForSplitLoopExit(Preds, NewExitBB, Exit);
    350             } else if (SplitLandingPads) {
    351               SmallVector<BasicBlock*, 8> NewBBs;
    352               SplitLandingPadPredecessors(Exit, Preds,
    353                                           ".split1", ".split2",
    354                                           P, NewBBs);
    355               if (P->mustPreserveAnalysisID(LCSSAID))
    356                 createPHIsForSplitLoopExit(Preds, NewBBs[0], Exit);
    357             }
    358           }
    359         }
    360       }
    361       // LCSSA form was updated above for the case where LoopSimplify is
    362       // available, which means that all predecessors of loop exit blocks
    363       // are within the loop. Without LoopSimplify form, it would be
    364       // necessary to insert a new phi.
    365       assert((!P->mustPreserveAnalysisID(LCSSAID) ||
    366               P->mustPreserveAnalysisID(LoopSimplifyID)) &&
    367              "SplitCriticalEdge doesn't know how to update LCCSA form "
    368              "without LoopSimplify!");
    369     }
    370   }
    371 
    372   // Update ProfileInfo if it is around.
    373   if (PI)
    374     PI->splitEdge(TIBB, DestBB, NewBB, MergeIdenticalEdges);
    375 
    376   return NewBB;
    377 }
    378