1 //===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // BreakCriticalEdges pass - Break all of the critical edges in the CFG by
10 // inserting a dummy basic block. This pass may be "required" by passes that
11 // cannot deal with critical edges. For this usage, the structure type is
12 // forward declared. This pass obviously invalidates the CFG, but can update
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/BlockFrequencyInfo.h"
22 #include "llvm/Analysis/BranchProbabilityInfo.h"
23 #include "llvm/Analysis/CFG.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/MemorySSAUpdater.h"
26 #include "llvm/Analysis/PostDominators.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/InitializePasses.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Transforms/Utils.h"
34 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
35 #include "llvm/Transforms/Utils/Cloning.h"
36 #include "llvm/Transforms/Utils/ValueMapper.h"
39 #define DEBUG_TYPE "break-crit-edges"
41 STATISTIC(NumBroken, "Number of blocks inserted");
44 struct BreakCriticalEdges : public FunctionPass {
45 static char ID; // Pass identification, replacement for typeid
46 BreakCriticalEdges() : FunctionPass(ID) {
47 initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
50 bool runOnFunction(Function &F) override {
51 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
52 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
54 auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
55 auto *PDT = PDTWP ? &PDTWP->getPostDomTree() : nullptr;
57 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
58 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
60 SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI, nullptr, PDT));
65 void getAnalysisUsage(AnalysisUsage &AU) const override {
66 AU.addPreserved<DominatorTreeWrapperPass>();
67 AU.addPreserved<LoopInfoWrapperPass>();
69 // No loop canonicalization guarantees are broken by this pass.
70 AU.addPreservedID(LoopSimplifyID);
75 char BreakCriticalEdges::ID = 0;
76 INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
77 "Break critical edges in CFG", false, false)
79 // Publicly exposed interface to pass...
80 char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
81 FunctionPass *llvm::createBreakCriticalEdgesPass() {
82 return new BreakCriticalEdges();
85 PreservedAnalyses BreakCriticalEdgesPass::run(Function &F,
86 FunctionAnalysisManager &AM) {
87 auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
88 auto *LI = AM.getCachedResult<LoopAnalysis>(F);
89 unsigned N = SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI));
92 return PreservedAnalyses::all();
94 PA.preserve<DominatorTreeAnalysis>();
95 PA.preserve<LoopAnalysis>();
99 //===----------------------------------------------------------------------===//
100 // Implementation of the external critical edge manipulation functions
101 //===----------------------------------------------------------------------===//
103 /// When a loop exit edge is split, LCSSA form may require new PHIs in the new
104 /// exit block. This function inserts the new PHIs, as needed. Preds is a list
105 /// of preds inside the loop, SplitBB is the new loop exit block, and DestBB is
106 /// the old loop exit, now the successor of SplitBB.
107 static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
109 BasicBlock *DestBB) {
110 // SplitBB shouldn't have anything non-trivial in it yet.
111 assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
112 SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
114 // For each PHI in the destination block.
115 for (PHINode &PN : DestBB->phis()) {
116 unsigned Idx = PN.getBasicBlockIndex(SplitBB);
117 Value *V = PN.getIncomingValue(Idx);
119 // If the input is a PHI which already satisfies LCSSA, don't create
121 if (const PHINode *VP = dyn_cast<PHINode>(V))
122 if (VP->getParent() == SplitBB)
125 // Otherwise a new PHI is needed. Create one and populate it.
126 PHINode *NewPN = PHINode::Create(
127 PN.getType(), Preds.size(), "split",
128 SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator());
129 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
130 NewPN->addIncoming(V, Preds[i]);
132 // Update the original PHI.
133 PN.setIncomingValue(Idx, NewPN);
138 llvm::SplitCriticalEdge(Instruction *TI, unsigned SuccNum,
139 const CriticalEdgeSplittingOptions &Options) {
140 if (!isCriticalEdge(TI, SuccNum, Options.MergeIdenticalEdges))
143 assert(!isa<IndirectBrInst>(TI) &&
144 "Cannot split critical edge from IndirectBrInst");
146 BasicBlock *TIBB = TI->getParent();
147 BasicBlock *DestBB = TI->getSuccessor(SuccNum);
149 // Splitting the critical edge to a pad block is non-trivial. Don't do
150 // it in this generic function.
151 if (DestBB->isEHPad()) return nullptr;
153 // Don't split the non-fallthrough edge from a callbr.
154 if (isa<CallBrInst>(TI) && SuccNum > 0)
157 if (Options.IgnoreUnreachableDests &&
158 isa<UnreachableInst>(DestBB->getFirstNonPHIOrDbgOrLifetime()))
161 // Create a new basic block, linking it into the CFG.
162 BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
163 TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
164 // Create our unconditional branch.
165 BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
166 NewBI->setDebugLoc(TI->getDebugLoc());
168 // Branch to the new block, breaking the edge.
169 TI->setSuccessor(SuccNum, NewBB);
171 // Insert the block into the function... right after the block TI lives in.
172 Function &F = *TIBB->getParent();
173 Function::iterator FBBI = TIBB->getIterator();
174 F.getBasicBlockList().insert(++FBBI, NewBB);
176 // If there are any PHI nodes in DestBB, we need to update them so that they
177 // merge incoming values from NewBB instead of from TIBB.
180 for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
181 // We no longer enter through TIBB, now we come in through NewBB.
182 // Revector exactly one entry in the PHI node that used to come from
183 // TIBB to come from NewBB.
184 PHINode *PN = cast<PHINode>(I);
186 // Reuse the previous value of BBIdx if it lines up. In cases where we
187 // have multiple phi nodes with *lots* of predecessors, this is a speed
188 // win because we don't have to scan the PHI looking for TIBB. This
189 // happens because the BB list of PHI nodes are usually in the same
191 if (PN->getIncomingBlock(BBIdx) != TIBB)
192 BBIdx = PN->getBasicBlockIndex(TIBB);
193 PN->setIncomingBlock(BBIdx, NewBB);
197 // If there are any other edges from TIBB to DestBB, update those to go
198 // through the split block, making those edges non-critical as well (and
199 // reducing the number of phi entries in the DestBB if relevant).
200 if (Options.MergeIdenticalEdges) {
201 for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
202 if (TI->getSuccessor(i) != DestBB) continue;
204 // Remove an entry for TIBB from DestBB phi nodes.
205 DestBB->removePredecessor(TIBB, Options.KeepOneInputPHIs);
207 // We found another edge to DestBB, go to NewBB instead.
208 TI->setSuccessor(i, NewBB);
212 // If we have nothing to update, just return.
213 auto *DT = Options.DT;
214 auto *PDT = Options.PDT;
215 auto *LI = Options.LI;
216 auto *MSSAU = Options.MSSAU;
218 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(
219 DestBB, NewBB, {TIBB}, Options.MergeIdenticalEdges);
221 if (!DT && !PDT && !LI)
225 // Update the DominatorTree.
228 // TIBB -------\\------> DestBB
230 // First, inform the DT about the new path from TIBB to DestBB via NewBB,
231 // then delete the old edge from TIBB to DestBB. By doing this in that order
232 // DestBB stays reachable in the DT the whole time and its subtree doesn't
234 SmallVector<DominatorTree::UpdateType, 3> Updates;
235 Updates.push_back({DominatorTree::Insert, TIBB, NewBB});
236 Updates.push_back({DominatorTree::Insert, NewBB, DestBB});
237 if (llvm::find(successors(TIBB), DestBB) == succ_end(TIBB))
238 Updates.push_back({DominatorTree::Delete, TIBB, DestBB});
241 DT->applyUpdates(Updates);
243 PDT->applyUpdates(Updates);
246 // Update LoopInfo if it is around.
248 if (Loop *TIL = LI->getLoopFor(TIBB)) {
249 // If one or the other blocks were not in a loop, the new block is not
250 // either, and thus LI doesn't need to be updated.
251 if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
252 if (TIL == DestLoop) {
253 // Both in the same loop, the NewBB joins loop.
254 DestLoop->addBasicBlockToLoop(NewBB, *LI);
255 } else if (TIL->contains(DestLoop)) {
256 // Edge from an outer loop to an inner loop. Add to the outer loop.
257 TIL->addBasicBlockToLoop(NewBB, *LI);
258 } else if (DestLoop->contains(TIL)) {
259 // Edge from an inner loop to an outer loop. Add to the outer loop.
260 DestLoop->addBasicBlockToLoop(NewBB, *LI);
262 // Edge from two loops with no containment relation. Because these
263 // are natural loops, we know that the destination block must be the
264 // header of its loop (adding a branch into a loop elsewhere would
265 // create an irreducible loop).
266 assert(DestLoop->getHeader() == DestBB &&
267 "Should not create irreducible loops!");
268 if (Loop *P = DestLoop->getParentLoop())
269 P->addBasicBlockToLoop(NewBB, *LI);
273 // If TIBB is in a loop and DestBB is outside of that loop, we may need
274 // to update LoopSimplify form and LCSSA form.
275 if (!TIL->contains(DestBB)) {
276 assert(!TIL->contains(NewBB) &&
277 "Split point for loop exit is contained in loop!");
279 // Update LCSSA form in the newly created exit block.
280 if (Options.PreserveLCSSA) {
281 createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
284 // The only that we can break LoopSimplify form by splitting a critical
285 // edge is if after the split there exists some edge from TIL to DestBB
286 // *and* the only edge into DestBB from outside of TIL is that of
287 // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
288 // is the new exit block and it has no non-loop predecessors. If the
289 // second isn't true, then DestBB was not in LoopSimplify form prior to
290 // the split as it had a non-loop predecessor. In both of these cases,
291 // the predecessor must be directly in TIL, not in a subloop, or again
292 // LoopSimplify doesn't hold.
293 SmallVector<BasicBlock *, 4> LoopPreds;
294 for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
298 continue; // The new block is known.
299 if (LI->getLoopFor(P) != TIL) {
300 // No need to re-simplify, it wasn't to start with.
304 LoopPreds.push_back(P);
306 if (!LoopPreds.empty()) {
307 assert(!DestBB->isEHPad() && "We don't split edges to EH pads!");
308 BasicBlock *NewExitBB = SplitBlockPredecessors(
309 DestBB, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
310 if (Options.PreserveLCSSA)
311 createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
320 // Return the unique indirectbr predecessor of a block. This may return null
321 // even if such a predecessor exists, if it's not useful for splitting.
322 // If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
323 // predecessors of BB.
325 findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
326 // If the block doesn't have any PHIs, we don't care about it, since there's
327 // no point in splitting it.
328 PHINode *PN = dyn_cast<PHINode>(BB->begin());
332 // Verify we have exactly one IBR predecessor.
333 // Conservatively bail out if one of the other predecessors is not a "regular"
334 // terminator (that is, not a switch or a br).
335 BasicBlock *IBB = nullptr;
336 for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
337 BasicBlock *PredBB = PN->getIncomingBlock(Pred);
338 Instruction *PredTerm = PredBB->getTerminator();
339 switch (PredTerm->getOpcode()) {
340 case Instruction::IndirectBr:
345 case Instruction::Br:
346 case Instruction::Switch:
347 OtherPreds.push_back(PredBB);
357 bool llvm::SplitIndirectBrCriticalEdges(Function &F,
358 BranchProbabilityInfo *BPI,
359 BlockFrequencyInfo *BFI) {
360 // Check whether the function has any indirectbrs, and collect which blocks
361 // they may jump to. Since most functions don't have indirect branches,
362 // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
363 SmallSetVector<BasicBlock *, 16> Targets;
365 auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
369 for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
370 Targets.insert(IBI->getSuccessor(Succ));
376 bool ShouldUpdateAnalysis = BPI && BFI;
377 bool Changed = false;
378 for (BasicBlock *Target : Targets) {
379 SmallVector<BasicBlock *, 16> OtherPreds;
380 BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
381 // If we did not found an indirectbr, or the indirectbr is the only
382 // incoming edge, this isn't the kind of edge we're looking for.
383 if (!IBRPred || OtherPreds.empty())
386 // Don't even think about ehpads/landingpads.
387 Instruction *FirstNonPHI = Target->getFirstNonPHI();
388 if (FirstNonPHI->isEHPad() || Target->isLandingPad())
391 BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
392 if (ShouldUpdateAnalysis) {
393 // Copy the BFI/BPI from Target to BodyBlock.
394 for (unsigned I = 0, E = BodyBlock->getTerminator()->getNumSuccessors();
396 BPI->setEdgeProbability(BodyBlock, I,
397 BPI->getEdgeProbability(Target, I));
398 BFI->setBlockFreq(BodyBlock, BFI->getBlockFreq(Target).getFrequency());
400 // It's possible Target was its own successor through an indirectbr.
401 // In this case, the indirectbr now comes from BodyBlock.
402 if (IBRPred == Target)
405 // At this point Target only has PHIs, and BodyBlock has the rest of the
406 // block's body. Create a copy of Target that will be used by the "direct"
408 ValueToValueMapTy VMap;
409 BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
411 BlockFrequency BlockFreqForDirectSucc;
412 for (BasicBlock *Pred : OtherPreds) {
413 // If the target is a loop to itself, then the terminator of the split
414 // block (BodyBlock) needs to be updated.
415 BasicBlock *Src = Pred != Target ? Pred : BodyBlock;
416 Src->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
417 if (ShouldUpdateAnalysis)
418 BlockFreqForDirectSucc += BFI->getBlockFreq(Src) *
419 BPI->getEdgeProbability(Src, DirectSucc);
421 if (ShouldUpdateAnalysis) {
422 BFI->setBlockFreq(DirectSucc, BlockFreqForDirectSucc.getFrequency());
423 BlockFrequency NewBlockFreqForTarget =
424 BFI->getBlockFreq(Target) - BlockFreqForDirectSucc;
425 BFI->setBlockFreq(Target, NewBlockFreqForTarget.getFrequency());
426 BPI->eraseBlock(Target);
429 // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
430 // they are clones, so the number of PHIs are the same.
431 // (a) Remove the edge coming from IBRPred from the "Direct" PHI
432 // (b) Leave that as the only edge in the "Indirect" PHI.
433 // (c) Merge the two in the body block.
434 BasicBlock::iterator Indirect = Target->begin(),
435 End = Target->getFirstNonPHI()->getIterator();
436 BasicBlock::iterator Direct = DirectSucc->begin();
437 BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
439 assert(&*End == Target->getTerminator() &&
440 "Block was expected to only contain PHIs");
442 while (Indirect != End) {
443 PHINode *DirPHI = cast<PHINode>(Direct);
444 PHINode *IndPHI = cast<PHINode>(Indirect);
446 // Now, clean up - the direct block shouldn't get the indirect value,
448 DirPHI->removeIncomingValue(IBRPred);
451 // Advance the pointer here, to avoid invalidation issues when the old
455 PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
456 NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
459 // Create a PHI in the body block, to merge the direct and indirect
462 PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
463 MergePHI->addIncoming(NewIndPHI, Target);
464 MergePHI->addIncoming(DirPHI, DirectSucc);
466 IndPHI->replaceAllUsesWith(MergePHI);
467 IndPHI->eraseFromParent();