1 //===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
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 // 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
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/BlockFrequencyInfo.h"
23 #include "llvm/Analysis/BranchProbabilityInfo.h"
24 #include "llvm/Analysis/CFG.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/MemorySSAUpdater.h"
27 #include "llvm/IR/CFG.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Transforms/Utils.h"
33 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34 #include "llvm/Transforms/Utils/Cloning.h"
35 #include "llvm/Transforms/Utils/ValueMapper.h"
38 #define DEBUG_TYPE "break-crit-edges"
40 STATISTIC(NumBroken, "Number of blocks inserted");
43 struct BreakCriticalEdges : public FunctionPass {
44 static char ID; // Pass identification, replacement for typeid
45 BreakCriticalEdges() : FunctionPass(ID) {
46 initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
49 bool runOnFunction(Function &F) override {
50 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
51 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
52 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
53 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
55 SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI));
60 void getAnalysisUsage(AnalysisUsage &AU) const override {
61 AU.addPreserved<DominatorTreeWrapperPass>();
62 AU.addPreserved<LoopInfoWrapperPass>();
64 // No loop canonicalization guarantees are broken by this pass.
65 AU.addPreservedID(LoopSimplifyID);
70 char BreakCriticalEdges::ID = 0;
71 INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
72 "Break critical edges in CFG", false, false)
74 // Publicly exposed interface to pass...
75 char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
76 FunctionPass *llvm::createBreakCriticalEdgesPass() {
77 return new BreakCriticalEdges();
80 PreservedAnalyses BreakCriticalEdgesPass::run(Function &F,
81 FunctionAnalysisManager &AM) {
82 auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
83 auto *LI = AM.getCachedResult<LoopAnalysis>(F);
84 unsigned N = SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI));
87 return PreservedAnalyses::all();
89 PA.preserve<DominatorTreeAnalysis>();
90 PA.preserve<LoopAnalysis>();
94 //===----------------------------------------------------------------------===//
95 // Implementation of the external critical edge manipulation functions
96 //===----------------------------------------------------------------------===//
98 /// When a loop exit edge is split, LCSSA form may require new PHIs in the new
99 /// exit block. This function inserts the new PHIs, as needed. Preds is a list
100 /// of preds inside the loop, SplitBB is the new loop exit block, and DestBB is
101 /// the old loop exit, now the successor of SplitBB.
102 static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
104 BasicBlock *DestBB) {
105 // SplitBB shouldn't have anything non-trivial in it yet.
106 assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
107 SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
109 // For each PHI in the destination block.
110 for (PHINode &PN : DestBB->phis()) {
111 unsigned Idx = PN.getBasicBlockIndex(SplitBB);
112 Value *V = PN.getIncomingValue(Idx);
114 // If the input is a PHI which already satisfies LCSSA, don't create
116 if (const PHINode *VP = dyn_cast<PHINode>(V))
117 if (VP->getParent() == SplitBB)
120 // Otherwise a new PHI is needed. Create one and populate it.
121 PHINode *NewPN = PHINode::Create(
122 PN.getType(), Preds.size(), "split",
123 SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator());
124 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
125 NewPN->addIncoming(V, Preds[i]);
127 // Update the original PHI.
128 PN.setIncomingValue(Idx, NewPN);
133 llvm::SplitCriticalEdge(Instruction *TI, unsigned SuccNum,
134 const CriticalEdgeSplittingOptions &Options) {
135 if (!isCriticalEdge(TI, SuccNum, Options.MergeIdenticalEdges))
138 assert(!isa<IndirectBrInst>(TI) &&
139 "Cannot split critical edge from IndirectBrInst");
141 BasicBlock *TIBB = TI->getParent();
142 BasicBlock *DestBB = TI->getSuccessor(SuccNum);
144 // Splitting the critical edge to a pad block is non-trivial. Don't do
145 // it in this generic function.
146 if (DestBB->isEHPad()) return nullptr;
148 // Create a new basic block, linking it into the CFG.
149 BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
150 TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
151 // Create our unconditional branch.
152 BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
153 NewBI->setDebugLoc(TI->getDebugLoc());
155 // Branch to the new block, breaking the edge.
156 TI->setSuccessor(SuccNum, NewBB);
158 // Insert the block into the function... right after the block TI lives in.
159 Function &F = *TIBB->getParent();
160 Function::iterator FBBI = TIBB->getIterator();
161 F.getBasicBlockList().insert(++FBBI, NewBB);
163 // If there are any PHI nodes in DestBB, we need to update them so that they
164 // merge incoming values from NewBB instead of from TIBB.
167 for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
168 // We no longer enter through TIBB, now we come in through NewBB.
169 // Revector exactly one entry in the PHI node that used to come from
170 // TIBB to come from NewBB.
171 PHINode *PN = cast<PHINode>(I);
173 // Reuse the previous value of BBIdx if it lines up. In cases where we
174 // have multiple phi nodes with *lots* of predecessors, this is a speed
175 // win because we don't have to scan the PHI looking for TIBB. This
176 // happens because the BB list of PHI nodes are usually in the same
178 if (PN->getIncomingBlock(BBIdx) != TIBB)
179 BBIdx = PN->getBasicBlockIndex(TIBB);
180 PN->setIncomingBlock(BBIdx, NewBB);
184 // If there are any other edges from TIBB to DestBB, update those to go
185 // through the split block, making those edges non-critical as well (and
186 // reducing the number of phi entries in the DestBB if relevant).
187 if (Options.MergeIdenticalEdges) {
188 for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
189 if (TI->getSuccessor(i) != DestBB) continue;
191 // Remove an entry for TIBB from DestBB phi nodes.
192 DestBB->removePredecessor(TIBB, Options.DontDeleteUselessPHIs);
194 // We found another edge to DestBB, go to NewBB instead.
195 TI->setSuccessor(i, NewBB);
199 // If we have nothing to update, just return.
200 auto *DT = Options.DT;
201 auto *LI = Options.LI;
202 auto *MSSAU = Options.MSSAU;
204 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(
205 DestBB, NewBB, {TIBB}, Options.MergeIdenticalEdges);
211 // Update the DominatorTree.
214 // TIBB -------\\------> DestBB
216 // First, inform the DT about the new path from TIBB to DestBB via NewBB,
217 // then delete the old edge from TIBB to DestBB. By doing this in that order
218 // DestBB stays reachable in the DT the whole time and its subtree doesn't
220 SmallVector<DominatorTree::UpdateType, 3> Updates;
221 Updates.push_back({DominatorTree::Insert, TIBB, NewBB});
222 Updates.push_back({DominatorTree::Insert, NewBB, DestBB});
223 if (llvm::find(successors(TIBB), DestBB) == succ_end(TIBB))
224 Updates.push_back({DominatorTree::Delete, TIBB, DestBB});
226 DT->applyUpdates(Updates);
229 // Update LoopInfo if it is around.
231 if (Loop *TIL = LI->getLoopFor(TIBB)) {
232 // If one or the other blocks were not in a loop, the new block is not
233 // either, and thus LI doesn't need to be updated.
234 if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
235 if (TIL == DestLoop) {
236 // Both in the same loop, the NewBB joins loop.
237 DestLoop->addBasicBlockToLoop(NewBB, *LI);
238 } else if (TIL->contains(DestLoop)) {
239 // Edge from an outer loop to an inner loop. Add to the outer loop.
240 TIL->addBasicBlockToLoop(NewBB, *LI);
241 } else if (DestLoop->contains(TIL)) {
242 // Edge from an inner loop to an outer loop. Add to the outer loop.
243 DestLoop->addBasicBlockToLoop(NewBB, *LI);
245 // Edge from two loops with no containment relation. Because these
246 // are natural loops, we know that the destination block must be the
247 // header of its loop (adding a branch into a loop elsewhere would
248 // create an irreducible loop).
249 assert(DestLoop->getHeader() == DestBB &&
250 "Should not create irreducible loops!");
251 if (Loop *P = DestLoop->getParentLoop())
252 P->addBasicBlockToLoop(NewBB, *LI);
256 // If TIBB is in a loop and DestBB is outside of that loop, we may need
257 // to update LoopSimplify form and LCSSA form.
258 if (!TIL->contains(DestBB)) {
259 assert(!TIL->contains(NewBB) &&
260 "Split point for loop exit is contained in loop!");
262 // Update LCSSA form in the newly created exit block.
263 if (Options.PreserveLCSSA) {
264 createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
267 // The only that we can break LoopSimplify form by splitting a critical
268 // edge is if after the split there exists some edge from TIL to DestBB
269 // *and* the only edge into DestBB from outside of TIL is that of
270 // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
271 // is the new exit block and it has no non-loop predecessors. If the
272 // second isn't true, then DestBB was not in LoopSimplify form prior to
273 // the split as it had a non-loop predecessor. In both of these cases,
274 // the predecessor must be directly in TIL, not in a subloop, or again
275 // LoopSimplify doesn't hold.
276 SmallVector<BasicBlock *, 4> LoopPreds;
277 for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
281 continue; // The new block is known.
282 if (LI->getLoopFor(P) != TIL) {
283 // No need to re-simplify, it wasn't to start with.
287 LoopPreds.push_back(P);
289 if (!LoopPreds.empty()) {
290 assert(!DestBB->isEHPad() && "We don't split edges to EH pads!");
291 BasicBlock *NewExitBB = SplitBlockPredecessors(
292 DestBB, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
293 if (Options.PreserveLCSSA)
294 createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
303 // Return the unique indirectbr predecessor of a block. This may return null
304 // even if such a predecessor exists, if it's not useful for splitting.
305 // If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
306 // predecessors of BB.
308 findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
309 // If the block doesn't have any PHIs, we don't care about it, since there's
310 // no point in splitting it.
311 PHINode *PN = dyn_cast<PHINode>(BB->begin());
315 // Verify we have exactly one IBR predecessor.
316 // Conservatively bail out if one of the other predecessors is not a "regular"
317 // terminator (that is, not a switch or a br).
318 BasicBlock *IBB = nullptr;
319 for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
320 BasicBlock *PredBB = PN->getIncomingBlock(Pred);
321 Instruction *PredTerm = PredBB->getTerminator();
322 switch (PredTerm->getOpcode()) {
323 case Instruction::IndirectBr:
328 case Instruction::Br:
329 case Instruction::Switch:
330 OtherPreds.push_back(PredBB);
340 bool llvm::SplitIndirectBrCriticalEdges(Function &F,
341 BranchProbabilityInfo *BPI,
342 BlockFrequencyInfo *BFI) {
343 // Check whether the function has any indirectbrs, and collect which blocks
344 // they may jump to. Since most functions don't have indirect branches,
345 // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
346 SmallSetVector<BasicBlock *, 16> Targets;
348 auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
352 for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
353 Targets.insert(IBI->getSuccessor(Succ));
359 bool ShouldUpdateAnalysis = BPI && BFI;
360 bool Changed = false;
361 for (BasicBlock *Target : Targets) {
362 SmallVector<BasicBlock *, 16> OtherPreds;
363 BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
364 // If we did not found an indirectbr, or the indirectbr is the only
365 // incoming edge, this isn't the kind of edge we're looking for.
366 if (!IBRPred || OtherPreds.empty())
369 // Don't even think about ehpads/landingpads.
370 Instruction *FirstNonPHI = Target->getFirstNonPHI();
371 if (FirstNonPHI->isEHPad() || Target->isLandingPad())
374 BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
375 if (ShouldUpdateAnalysis) {
376 // Copy the BFI/BPI from Target to BodyBlock.
377 for (unsigned I = 0, E = BodyBlock->getTerminator()->getNumSuccessors();
379 BPI->setEdgeProbability(BodyBlock, I,
380 BPI->getEdgeProbability(Target, I));
381 BFI->setBlockFreq(BodyBlock, BFI->getBlockFreq(Target).getFrequency());
383 // It's possible Target was its own successor through an indirectbr.
384 // In this case, the indirectbr now comes from BodyBlock.
385 if (IBRPred == Target)
388 // At this point Target only has PHIs, and BodyBlock has the rest of the
389 // block's body. Create a copy of Target that will be used by the "direct"
391 ValueToValueMapTy VMap;
392 BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
394 BlockFrequency BlockFreqForDirectSucc;
395 for (BasicBlock *Pred : OtherPreds) {
396 // If the target is a loop to itself, then the terminator of the split
397 // block (BodyBlock) needs to be updated.
398 BasicBlock *Src = Pred != Target ? Pred : BodyBlock;
399 Src->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
400 if (ShouldUpdateAnalysis)
401 BlockFreqForDirectSucc += BFI->getBlockFreq(Src) *
402 BPI->getEdgeProbability(Src, DirectSucc);
404 if (ShouldUpdateAnalysis) {
405 BFI->setBlockFreq(DirectSucc, BlockFreqForDirectSucc.getFrequency());
406 BlockFrequency NewBlockFreqForTarget =
407 BFI->getBlockFreq(Target) - BlockFreqForDirectSucc;
408 BFI->setBlockFreq(Target, NewBlockFreqForTarget.getFrequency());
409 BPI->eraseBlock(Target);
412 // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
413 // they are clones, so the number of PHIs are the same.
414 // (a) Remove the edge coming from IBRPred from the "Direct" PHI
415 // (b) Leave that as the only edge in the "Indirect" PHI.
416 // (c) Merge the two in the body block.
417 BasicBlock::iterator Indirect = Target->begin(),
418 End = Target->getFirstNonPHI()->getIterator();
419 BasicBlock::iterator Direct = DirectSucc->begin();
420 BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
422 assert(&*End == Target->getTerminator() &&
423 "Block was expected to only contain PHIs");
425 while (Indirect != End) {
426 PHINode *DirPHI = cast<PHINode>(Direct);
427 PHINode *IndPHI = cast<PHINode>(Indirect);
429 // Now, clean up - the direct block shouldn't get the indirect value,
431 DirPHI->removeIncomingValue(IBRPred);
434 // Advance the pointer here, to avoid invalidation issues when the old
438 PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
439 NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
442 // Create a PHI in the body block, to merge the direct and indirect
445 PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
446 MergePHI->addIncoming(NewIndPHI, Target);
447 MergePHI->addIncoming(DirPHI, DirectSucc);
449 IndPHI->replaceAllUsesWith(MergePHI);
450 IndPHI->eraseFromParent();