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