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