LLVM API Documentation

BreakCriticalEdges.cpp
Go to the documentation of this file.
00001 //===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // BreakCriticalEdges pass - Break all of the critical edges in the CFG by
00011 // inserting a dummy basic block.  This pass may be "required" by passes that
00012 // cannot deal with critical edges.  For this usage, the structure type is
00013 // forward declared.  This pass obviously invalidates the CFG, but can update
00014 // dominator trees.
00015 //
00016 //===----------------------------------------------------------------------===//
00017 
00018 #include "llvm/Transforms/Scalar.h"
00019 #include "llvm/ADT/SmallVector.h"
00020 #include "llvm/ADT/Statistic.h"
00021 #include "llvm/Analysis/CFG.h"
00022 #include "llvm/Analysis/LoopInfo.h"
00023 #include "llvm/IR/CFG.h"
00024 #include "llvm/IR/Dominators.h"
00025 #include "llvm/IR/Function.h"
00026 #include "llvm/IR/Instructions.h"
00027 #include "llvm/IR/Type.h"
00028 #include "llvm/Support/ErrorHandling.h"
00029 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00030 using namespace llvm;
00031 
00032 #define DEBUG_TYPE "break-crit-edges"
00033 
00034 STATISTIC(NumBroken, "Number of blocks inserted");
00035 
00036 namespace {
00037   struct BreakCriticalEdges : public FunctionPass {
00038     static char ID; // Pass identification, replacement for typeid
00039     BreakCriticalEdges() : FunctionPass(ID) {
00040       initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
00041     }
00042 
00043     bool runOnFunction(Function &F) override;
00044 
00045     void getAnalysisUsage(AnalysisUsage &AU) const override {
00046       AU.addPreserved<DominatorTreeWrapperPass>();
00047       AU.addPreserved<LoopInfo>();
00048 
00049       // No loop canonicalization guarantees are broken by this pass.
00050       AU.addPreservedID(LoopSimplifyID);
00051     }
00052   };
00053 }
00054 
00055 char BreakCriticalEdges::ID = 0;
00056 INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
00057                 "Break critical edges in CFG", false, false)
00058 
00059 // Publicly exposed interface to pass...
00060 char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
00061 FunctionPass *llvm::createBreakCriticalEdgesPass() {
00062   return new BreakCriticalEdges();
00063 }
00064 
00065 // runOnFunction - Loop over all of the edges in the CFG, breaking critical
00066 // edges as they are found.
00067 //
00068 bool BreakCriticalEdges::runOnFunction(Function &F) {
00069   bool Changed = false;
00070   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
00071     TerminatorInst *TI = I->getTerminator();
00072     if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
00073       for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
00074         if (SplitCriticalEdge(TI, i, this)) {
00075           ++NumBroken;
00076           Changed = true;
00077         }
00078   }
00079 
00080   return Changed;
00081 }
00082 
00083 //===----------------------------------------------------------------------===//
00084 //    Implementation of the external critical edge manipulation functions
00085 //===----------------------------------------------------------------------===//
00086 
00087 /// createPHIsForSplitLoopExit - When a loop exit edge is split, LCSSA form
00088 /// may require new PHIs in the new exit block. This function inserts the
00089 /// new PHIs, as needed. Preds is a list of preds inside the loop, SplitBB
00090 /// is the new loop exit block, and DestBB is the old loop exit, now the
00091 /// successor of SplitBB.
00092 static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
00093                                        BasicBlock *SplitBB,
00094                                        BasicBlock *DestBB) {
00095   // SplitBB shouldn't have anything non-trivial in it yet.
00096   assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
00097           SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
00098 
00099   // For each PHI in the destination block.
00100   for (BasicBlock::iterator I = DestBB->begin();
00101        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
00102     unsigned Idx = PN->getBasicBlockIndex(SplitBB);
00103     Value *V = PN->getIncomingValue(Idx);
00104 
00105     // If the input is a PHI which already satisfies LCSSA, don't create
00106     // a new one.
00107     if (const PHINode *VP = dyn_cast<PHINode>(V))
00108       if (VP->getParent() == SplitBB)
00109         continue;
00110 
00111     // Otherwise a new PHI is needed. Create one and populate it.
00112     PHINode *NewPN =
00113       PHINode::Create(PN->getType(), Preds.size(), "split",
00114                       SplitBB->isLandingPad() ?
00115                       SplitBB->begin() : SplitBB->getTerminator());
00116     for (unsigned i = 0, e = Preds.size(); i != e; ++i)
00117       NewPN->addIncoming(V, Preds[i]);
00118 
00119     // Update the original PHI.
00120     PN->setIncomingValue(Idx, NewPN);
00121   }
00122 }
00123 
00124 /// SplitCriticalEdge - If this edge is a critical edge, insert a new node to
00125 /// split the critical edge.  This will update DominatorTree information if it
00126 /// is available, thus calling this pass will not invalidate either of them.
00127 /// This returns the new block if the edge was split, null otherwise.
00128 ///
00129 /// If MergeIdenticalEdges is true (not the default), *all* edges from TI to the
00130 /// specified successor will be merged into the same critical edge block.
00131 /// This is most commonly interesting with switch instructions, which may
00132 /// have many edges to any one destination.  This ensures that all edges to that
00133 /// dest go to one block instead of each going to a different block, but isn't
00134 /// the standard definition of a "critical edge".
00135 ///
00136 /// It is invalid to call this function on a critical edge that starts at an
00137 /// IndirectBrInst.  Splitting these edges will almost always create an invalid
00138 /// program because the address of the new block won't be the one that is jumped
00139 /// to.
00140 ///
00141 BasicBlock *llvm::SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum,
00142                                     Pass *P, bool MergeIdenticalEdges,
00143                                     bool DontDeleteUselessPhis,
00144                                     bool SplitLandingPads) {
00145   if (!isCriticalEdge(TI, SuccNum, MergeIdenticalEdges)) return nullptr;
00146 
00147   assert(!isa<IndirectBrInst>(TI) &&
00148          "Cannot split critical edge from IndirectBrInst");
00149 
00150   BasicBlock *TIBB = TI->getParent();
00151   BasicBlock *DestBB = TI->getSuccessor(SuccNum);
00152 
00153   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
00154   // it in this generic function.
00155   if (DestBB->isLandingPad()) return nullptr;
00156 
00157   // Create a new basic block, linking it into the CFG.
00158   BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
00159                       TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
00160   // Create our unconditional branch.
00161   BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
00162   NewBI->setDebugLoc(TI->getDebugLoc());
00163 
00164   // Branch to the new block, breaking the edge.
00165   TI->setSuccessor(SuccNum, NewBB);
00166 
00167   // Insert the block into the function... right after the block TI lives in.
00168   Function &F = *TIBB->getParent();
00169   Function::iterator FBBI = TIBB;
00170   F.getBasicBlockList().insert(++FBBI, NewBB);
00171 
00172   // If there are any PHI nodes in DestBB, we need to update them so that they
00173   // merge incoming values from NewBB instead of from TIBB.
00174   {
00175     unsigned BBIdx = 0;
00176     for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
00177       // We no longer enter through TIBB, now we come in through NewBB.
00178       // Revector exactly one entry in the PHI node that used to come from
00179       // TIBB to come from NewBB.
00180       PHINode *PN = cast<PHINode>(I);
00181 
00182       // Reuse the previous value of BBIdx if it lines up.  In cases where we
00183       // have multiple phi nodes with *lots* of predecessors, this is a speed
00184       // win because we don't have to scan the PHI looking for TIBB.  This
00185       // happens because the BB list of PHI nodes are usually in the same
00186       // order.
00187       if (PN->getIncomingBlock(BBIdx) != TIBB)
00188         BBIdx = PN->getBasicBlockIndex(TIBB);
00189       PN->setIncomingBlock(BBIdx, NewBB);
00190     }
00191   }
00192 
00193   // If there are any other edges from TIBB to DestBB, update those to go
00194   // through the split block, making those edges non-critical as well (and
00195   // reducing the number of phi entries in the DestBB if relevant).
00196   if (MergeIdenticalEdges) {
00197     for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
00198       if (TI->getSuccessor(i) != DestBB) continue;
00199 
00200       // Remove an entry for TIBB from DestBB phi nodes.
00201       DestBB->removePredecessor(TIBB, DontDeleteUselessPhis);
00202 
00203       // We found another edge to DestBB, go to NewBB instead.
00204       TI->setSuccessor(i, NewBB);
00205     }
00206   }
00207 
00208 
00209 
00210   // If we don't have a pass object, we can't update anything...
00211   if (!P) return NewBB;
00212 
00213   DominatorTreeWrapperPass *DTWP =
00214       P->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
00215   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
00216   LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>();
00217 
00218   // If we have nothing to update, just return.
00219   if (!DT && !LI)
00220     return NewBB;
00221 
00222   // Now update analysis information.  Since the only predecessor of NewBB is
00223   // the TIBB, TIBB clearly dominates NewBB.  TIBB usually doesn't dominate
00224   // anything, as there are other successors of DestBB.  However, if all other
00225   // predecessors of DestBB are already dominated by DestBB (e.g. DestBB is a
00226   // loop header) then NewBB dominates DestBB.
00227   SmallVector<BasicBlock*, 8> OtherPreds;
00228 
00229   // If there is a PHI in the block, loop over predecessors with it, which is
00230   // faster than iterating pred_begin/end.
00231   if (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
00232     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00233       if (PN->getIncomingBlock(i) != NewBB)
00234         OtherPreds.push_back(PN->getIncomingBlock(i));
00235   } else {
00236     for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB);
00237          I != E; ++I) {
00238       BasicBlock *P = *I;
00239       if (P != NewBB)
00240         OtherPreds.push_back(P);
00241     }
00242   }
00243 
00244   bool NewBBDominatesDestBB = true;
00245 
00246   // Should we update DominatorTree information?
00247   if (DT) {
00248     DomTreeNode *TINode = DT->getNode(TIBB);
00249 
00250     // The new block is not the immediate dominator for any other nodes, but
00251     // TINode is the immediate dominator for the new node.
00252     //
00253     if (TINode) {       // Don't break unreachable code!
00254       DomTreeNode *NewBBNode = DT->addNewBlock(NewBB, TIBB);
00255       DomTreeNode *DestBBNode = nullptr;
00256 
00257       // If NewBBDominatesDestBB hasn't been computed yet, do so with DT.
00258       if (!OtherPreds.empty()) {
00259         DestBBNode = DT->getNode(DestBB);
00260         while (!OtherPreds.empty() && NewBBDominatesDestBB) {
00261           if (DomTreeNode *OPNode = DT->getNode(OtherPreds.back()))
00262             NewBBDominatesDestBB = DT->dominates(DestBBNode, OPNode);
00263           OtherPreds.pop_back();
00264         }
00265         OtherPreds.clear();
00266       }
00267 
00268       // If NewBBDominatesDestBB, then NewBB dominates DestBB, otherwise it
00269       // doesn't dominate anything.
00270       if (NewBBDominatesDestBB) {
00271         if (!DestBBNode) DestBBNode = DT->getNode(DestBB);
00272         DT->changeImmediateDominator(DestBBNode, NewBBNode);
00273       }
00274     }
00275   }
00276 
00277   // Update LoopInfo if it is around.
00278   if (LI) {
00279     if (Loop *TIL = LI->getLoopFor(TIBB)) {
00280       // If one or the other blocks were not in a loop, the new block is not
00281       // either, and thus LI doesn't need to be updated.
00282       if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
00283         if (TIL == DestLoop) {
00284           // Both in the same loop, the NewBB joins loop.
00285           DestLoop->addBasicBlockToLoop(NewBB, LI->getBase());
00286         } else if (TIL->contains(DestLoop)) {
00287           // Edge from an outer loop to an inner loop.  Add to the outer loop.
00288           TIL->addBasicBlockToLoop(NewBB, LI->getBase());
00289         } else if (DestLoop->contains(TIL)) {
00290           // Edge from an inner loop to an outer loop.  Add to the outer loop.
00291           DestLoop->addBasicBlockToLoop(NewBB, LI->getBase());
00292         } else {
00293           // Edge from two loops with no containment relation.  Because these
00294           // are natural loops, we know that the destination block must be the
00295           // header of its loop (adding a branch into a loop elsewhere would
00296           // create an irreducible loop).
00297           assert(DestLoop->getHeader() == DestBB &&
00298                  "Should not create irreducible loops!");
00299           if (Loop *P = DestLoop->getParentLoop())
00300             P->addBasicBlockToLoop(NewBB, LI->getBase());
00301         }
00302       }
00303       // If TIBB is in a loop and DestBB is outside of that loop, we may need
00304       // to update LoopSimplify form and LCSSA form.
00305       if (!TIL->contains(DestBB) &&
00306           P->mustPreserveAnalysisID(LoopSimplifyID)) {
00307         assert(!TIL->contains(NewBB) &&
00308                "Split point for loop exit is contained in loop!");
00309 
00310         // Update LCSSA form in the newly created exit block.
00311         if (P->mustPreserveAnalysisID(LCSSAID))
00312           createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
00313 
00314         // The only that we can break LoopSimplify form by splitting a critical
00315         // edge is if after the split there exists some edge from TIL to DestBB
00316         // *and* the only edge into DestBB from outside of TIL is that of
00317         // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
00318         // is the new exit block and it has no non-loop predecessors. If the
00319         // second isn't true, then DestBB was not in LoopSimplify form prior to
00320         // the split as it had a non-loop predecessor. In both of these cases,
00321         // the predecessor must be directly in TIL, not in a subloop, or again
00322         // LoopSimplify doesn't hold.
00323         SmallVector<BasicBlock *, 4> LoopPreds;
00324         for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
00325              ++I) {
00326           BasicBlock *P = *I;
00327           if (P == NewBB)
00328             continue; // The new block is known.
00329           if (LI->getLoopFor(P) != TIL) {
00330             // No need to re-simplify, it wasn't to start with.
00331             LoopPreds.clear();
00332             break;
00333           }
00334           LoopPreds.push_back(P);
00335         }
00336         if (!LoopPreds.empty()) {
00337           assert(!DestBB->isLandingPad() &&
00338                  "We don't split edges to landing pads!");
00339           BasicBlock *NewExitBB =
00340               SplitBlockPredecessors(DestBB, LoopPreds, "split", P);
00341           if (P->mustPreserveAnalysisID(LCSSAID))
00342             createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
00343         }
00344       }
00345       // LCSSA form was updated above for the case where LoopSimplify is
00346       // available, which means that all predecessors of loop exit blocks
00347       // are within the loop. Without LoopSimplify form, it would be
00348       // necessary to insert a new phi.
00349       assert((!P->mustPreserveAnalysisID(LCSSAID) ||
00350               P->mustPreserveAnalysisID(LoopSimplifyID)) &&
00351              "SplitCriticalEdge doesn't know how to update LCCSA form "
00352              "without LoopSimplify!");
00353     }
00354   }
00355 
00356   return NewBB;
00357 }