1 //===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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
13 // dominator trees.
14 //
15 //===----------------------------------------------------------------------===//
16 
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/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"
36 using namespace llvm;
37 
38 #define DEBUG_TYPE "break-crit-edges"
39 
40 STATISTIC(NumBroken, "Number of blocks inserted");
41 
42 namespace {
43   struct BreakCriticalEdges : public FunctionPass {
44     static char ID; // Pass identification, replacement for typeid
45     BreakCriticalEdges() : FunctionPass(ID) {
46       initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
47     }
48 
49     bool runOnFunction(Function &F) override {
50       auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
51       auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
52 
53       auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
54       auto *PDT = PDTWP ? &PDTWP->getPostDomTree() : nullptr;
55 
56       auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
57       auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
58       unsigned N =
59           SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI, nullptr, PDT));
60       NumBroken += N;
61       return N > 0;
62     }
63 
64     void getAnalysisUsage(AnalysisUsage &AU) const override {
65       AU.addPreserved<DominatorTreeWrapperPass>();
66       AU.addPreserved<LoopInfoWrapperPass>();
67 
68       // No loop canonicalization guarantees are broken by this pass.
69       AU.addPreservedID(LoopSimplifyID);
70     }
71   };
72 }
73 
74 char BreakCriticalEdges::ID = 0;
75 INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
76                 "Break critical edges in CFG", false, false)
77 
78 // Publicly exposed interface to pass...
79 char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
80 FunctionPass *llvm::createBreakCriticalEdgesPass() {
81   return new BreakCriticalEdges();
82 }
83 
84 PreservedAnalyses BreakCriticalEdgesPass::run(Function &F,
85                                               FunctionAnalysisManager &AM) {
86   auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
87   auto *LI = AM.getCachedResult<LoopAnalysis>(F);
88   unsigned N = SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI));
89   NumBroken += N;
90   if (N == 0)
91     return PreservedAnalyses::all();
92   PreservedAnalyses PA;
93   PA.preserve<DominatorTreeAnalysis>();
94   PA.preserve<LoopAnalysis>();
95   return PA;
96 }
97 
98 //===----------------------------------------------------------------------===//
99 //    Implementation of the external critical edge manipulation functions
100 //===----------------------------------------------------------------------===//
101 
102 /// When a loop exit edge is split, LCSSA form may require new PHIs in the new
103 /// exit block. This function inserts the new PHIs, as needed. Preds is a list
104 /// of preds inside the loop, SplitBB is the new loop exit block, and DestBB is
105 /// the old loop exit, now the successor of SplitBB.
106 static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
107                                        BasicBlock *SplitBB,
108                                        BasicBlock *DestBB) {
109   // SplitBB shouldn't have anything non-trivial in it yet.
110   assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
111           SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
112 
113   // For each PHI in the destination block.
114   for (PHINode &PN : DestBB->phis()) {
115     unsigned Idx = PN.getBasicBlockIndex(SplitBB);
116     Value *V = PN.getIncomingValue(Idx);
117 
118     // If the input is a PHI which already satisfies LCSSA, don't create
119     // a new one.
120     if (const PHINode *VP = dyn_cast<PHINode>(V))
121       if (VP->getParent() == SplitBB)
122         continue;
123 
124     // Otherwise a new PHI is needed. Create one and populate it.
125     PHINode *NewPN = PHINode::Create(
126         PN.getType(), Preds.size(), "split",
127         SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator());
128     for (unsigned i = 0, e = Preds.size(); i != e; ++i)
129       NewPN->addIncoming(V, Preds[i]);
130 
131     // Update the original PHI.
132     PN.setIncomingValue(Idx, NewPN);
133   }
134 }
135 
136 BasicBlock *
137 llvm::SplitCriticalEdge(Instruction *TI, unsigned SuccNum,
138                         const CriticalEdgeSplittingOptions &Options) {
139   if (!isCriticalEdge(TI, SuccNum, Options.MergeIdenticalEdges))
140     return nullptr;
141 
142   assert(!isa<IndirectBrInst>(TI) &&
143          "Cannot split critical edge from IndirectBrInst");
144 
145   BasicBlock *TIBB = TI->getParent();
146   BasicBlock *DestBB = TI->getSuccessor(SuccNum);
147 
148   // Splitting the critical edge to a pad block is non-trivial. Don't do
149   // it in this generic function.
150   if (DestBB->isEHPad()) return nullptr;
151 
152   // Don't split the non-fallthrough edge from a callbr.
153   if (isa<CallBrInst>(TI) && SuccNum > 0)
154     return nullptr;
155 
156   // Create a new basic block, linking it into the CFG.
157   BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
158                       TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
159   // Create our unconditional branch.
160   BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
161   NewBI->setDebugLoc(TI->getDebugLoc());
162 
163   // Branch to the new block, breaking the edge.
164   TI->setSuccessor(SuccNum, NewBB);
165 
166   // Insert the block into the function... right after the block TI lives in.
167   Function &F = *TIBB->getParent();
168   Function::iterator FBBI = TIBB->getIterator();
169   F.getBasicBlockList().insert(++FBBI, NewBB);
170 
171   // If there are any PHI nodes in DestBB, we need to update them so that they
172   // merge incoming values from NewBB instead of from TIBB.
173   {
174     unsigned BBIdx = 0;
175     for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
176       // We no longer enter through TIBB, now we come in through NewBB.
177       // Revector exactly one entry in the PHI node that used to come from
178       // TIBB to come from NewBB.
179       PHINode *PN = cast<PHINode>(I);
180 
181       // Reuse the previous value of BBIdx if it lines up.  In cases where we
182       // have multiple phi nodes with *lots* of predecessors, this is a speed
183       // win because we don't have to scan the PHI looking for TIBB.  This
184       // happens because the BB list of PHI nodes are usually in the same
185       // order.
186       if (PN->getIncomingBlock(BBIdx) != TIBB)
187         BBIdx = PN->getBasicBlockIndex(TIBB);
188       PN->setIncomingBlock(BBIdx, NewBB);
189     }
190   }
191 
192   // If there are any other edges from TIBB to DestBB, update those to go
193   // through the split block, making those edges non-critical as well (and
194   // reducing the number of phi entries in the DestBB if relevant).
195   if (Options.MergeIdenticalEdges) {
196     for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
197       if (TI->getSuccessor(i) != DestBB) continue;
198 
199       // Remove an entry for TIBB from DestBB phi nodes.
200       DestBB->removePredecessor(TIBB, Options.KeepOneInputPHIs);
201 
202       // We found another edge to DestBB, go to NewBB instead.
203       TI->setSuccessor(i, NewBB);
204     }
205   }
206 
207   // If we have nothing to update, just return.
208   auto *DT = Options.DT;
209   auto *PDT = Options.PDT;
210   auto *LI = Options.LI;
211   auto *MSSAU = Options.MSSAU;
212   if (MSSAU)
213     MSSAU->wireOldPredecessorsToNewImmediatePredecessor(
214         DestBB, NewBB, {TIBB}, Options.MergeIdenticalEdges);
215 
216   if (!DT && !PDT && !LI)
217     return NewBB;
218 
219   if (DT || PDT) {
220     // Update the DominatorTree.
221     //       ---> NewBB -----\
222     //      /                 V
223     //  TIBB -------\\------> DestBB
224     //
225     // First, inform the DT about the new path from TIBB to DestBB via NewBB,
226     // then delete the old edge from TIBB to DestBB. By doing this in that order
227     // DestBB stays reachable in the DT the whole time and its subtree doesn't
228     // get disconnected.
229     SmallVector<DominatorTree::UpdateType, 3> Updates;
230     Updates.push_back({DominatorTree::Insert, TIBB, NewBB});
231     Updates.push_back({DominatorTree::Insert, NewBB, DestBB});
232     if (llvm::find(successors(TIBB), DestBB) == succ_end(TIBB))
233       Updates.push_back({DominatorTree::Delete, TIBB, DestBB});
234 
235     if (DT)
236       DT->applyUpdates(Updates);
237     if (PDT)
238       PDT->applyUpdates(Updates);
239   }
240 
241   // Update LoopInfo if it is around.
242   if (LI) {
243     if (Loop *TIL = LI->getLoopFor(TIBB)) {
244       // If one or the other blocks were not in a loop, the new block is not
245       // either, and thus LI doesn't need to be updated.
246       if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
247         if (TIL == DestLoop) {
248           // Both in the same loop, the NewBB joins loop.
249           DestLoop->addBasicBlockToLoop(NewBB, *LI);
250         } else if (TIL->contains(DestLoop)) {
251           // Edge from an outer loop to an inner loop.  Add to the outer loop.
252           TIL->addBasicBlockToLoop(NewBB, *LI);
253         } else if (DestLoop->contains(TIL)) {
254           // Edge from an inner loop to an outer loop.  Add to the outer loop.
255           DestLoop->addBasicBlockToLoop(NewBB, *LI);
256         } else {
257           // Edge from two loops with no containment relation.  Because these
258           // are natural loops, we know that the destination block must be the
259           // header of its loop (adding a branch into a loop elsewhere would
260           // create an irreducible loop).
261           assert(DestLoop->getHeader() == DestBB &&
262                  "Should not create irreducible loops!");
263           if (Loop *P = DestLoop->getParentLoop())
264             P->addBasicBlockToLoop(NewBB, *LI);
265         }
266       }
267 
268       // If TIBB is in a loop and DestBB is outside of that loop, we may need
269       // to update LoopSimplify form and LCSSA form.
270       if (!TIL->contains(DestBB)) {
271         assert(!TIL->contains(NewBB) &&
272                "Split point for loop exit is contained in loop!");
273 
274         // Update LCSSA form in the newly created exit block.
275         if (Options.PreserveLCSSA) {
276           createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
277         }
278 
279         // The only that we can break LoopSimplify form by splitting a critical
280         // edge is if after the split there exists some edge from TIL to DestBB
281         // *and* the only edge into DestBB from outside of TIL is that of
282         // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
283         // is the new exit block and it has no non-loop predecessors. If the
284         // second isn't true, then DestBB was not in LoopSimplify form prior to
285         // the split as it had a non-loop predecessor. In both of these cases,
286         // the predecessor must be directly in TIL, not in a subloop, or again
287         // LoopSimplify doesn't hold.
288         SmallVector<BasicBlock *, 4> LoopPreds;
289         for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
290              ++I) {
291           BasicBlock *P = *I;
292           if (P == NewBB)
293             continue; // The new block is known.
294           if (LI->getLoopFor(P) != TIL) {
295             // No need to re-simplify, it wasn't to start with.
296             LoopPreds.clear();
297             break;
298           }
299           LoopPreds.push_back(P);
300         }
301         if (!LoopPreds.empty()) {
302           assert(!DestBB->isEHPad() && "We don't split edges to EH pads!");
303           BasicBlock *NewExitBB = SplitBlockPredecessors(
304               DestBB, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
305           if (Options.PreserveLCSSA)
306             createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
307         }
308       }
309     }
310   }
311 
312   return NewBB;
313 }
314 
315 // Return the unique indirectbr predecessor of a block. This may return null
316 // even if such a predecessor exists, if it's not useful for splitting.
317 // If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
318 // predecessors of BB.
319 static BasicBlock *
320 findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
321   // If the block doesn't have any PHIs, we don't care about it, since there's
322   // no point in splitting it.
323   PHINode *PN = dyn_cast<PHINode>(BB->begin());
324   if (!PN)
325     return nullptr;
326 
327   // Verify we have exactly one IBR predecessor.
328   // Conservatively bail out if one of the other predecessors is not a "regular"
329   // terminator (that is, not a switch or a br).
330   BasicBlock *IBB = nullptr;
331   for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
332     BasicBlock *PredBB = PN->getIncomingBlock(Pred);
333     Instruction *PredTerm = PredBB->getTerminator();
334     switch (PredTerm->getOpcode()) {
335     case Instruction::IndirectBr:
336       if (IBB)
337         return nullptr;
338       IBB = PredBB;
339       break;
340     case Instruction::Br:
341     case Instruction::Switch:
342       OtherPreds.push_back(PredBB);
343       continue;
344     default:
345       return nullptr;
346     }
347   }
348 
349   return IBB;
350 }
351 
352 bool llvm::SplitIndirectBrCriticalEdges(Function &F,
353                                         BranchProbabilityInfo *BPI,
354                                         BlockFrequencyInfo *BFI) {
355   // Check whether the function has any indirectbrs, and collect which blocks
356   // they may jump to. Since most functions don't have indirect branches,
357   // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
358   SmallSetVector<BasicBlock *, 16> Targets;
359   for (auto &BB : F) {
360     auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
361     if (!IBI)
362       continue;
363 
364     for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
365       Targets.insert(IBI->getSuccessor(Succ));
366   }
367 
368   if (Targets.empty())
369     return false;
370 
371   bool ShouldUpdateAnalysis = BPI && BFI;
372   bool Changed = false;
373   for (BasicBlock *Target : Targets) {
374     SmallVector<BasicBlock *, 16> OtherPreds;
375     BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
376     // If we did not found an indirectbr, or the indirectbr is the only
377     // incoming edge, this isn't the kind of edge we're looking for.
378     if (!IBRPred || OtherPreds.empty())
379       continue;
380 
381     // Don't even think about ehpads/landingpads.
382     Instruction *FirstNonPHI = Target->getFirstNonPHI();
383     if (FirstNonPHI->isEHPad() || Target->isLandingPad())
384       continue;
385 
386     BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
387     if (ShouldUpdateAnalysis) {
388       // Copy the BFI/BPI from Target to BodyBlock.
389       for (unsigned I = 0, E = BodyBlock->getTerminator()->getNumSuccessors();
390            I < E; ++I)
391         BPI->setEdgeProbability(BodyBlock, I,
392                                 BPI->getEdgeProbability(Target, I));
393       BFI->setBlockFreq(BodyBlock, BFI->getBlockFreq(Target).getFrequency());
394     }
395     // It's possible Target was its own successor through an indirectbr.
396     // In this case, the indirectbr now comes from BodyBlock.
397     if (IBRPred == Target)
398       IBRPred = BodyBlock;
399 
400     // At this point Target only has PHIs, and BodyBlock has the rest of the
401     // block's body. Create a copy of Target that will be used by the "direct"
402     // preds.
403     ValueToValueMapTy VMap;
404     BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
405 
406     BlockFrequency BlockFreqForDirectSucc;
407     for (BasicBlock *Pred : OtherPreds) {
408       // If the target is a loop to itself, then the terminator of the split
409       // block (BodyBlock) needs to be updated.
410       BasicBlock *Src = Pred != Target ? Pred : BodyBlock;
411       Src->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
412       if (ShouldUpdateAnalysis)
413         BlockFreqForDirectSucc += BFI->getBlockFreq(Src) *
414             BPI->getEdgeProbability(Src, DirectSucc);
415     }
416     if (ShouldUpdateAnalysis) {
417       BFI->setBlockFreq(DirectSucc, BlockFreqForDirectSucc.getFrequency());
418       BlockFrequency NewBlockFreqForTarget =
419           BFI->getBlockFreq(Target) - BlockFreqForDirectSucc;
420       BFI->setBlockFreq(Target, NewBlockFreqForTarget.getFrequency());
421       BPI->eraseBlock(Target);
422     }
423 
424     // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
425     // they are clones, so the number of PHIs are the same.
426     // (a) Remove the edge coming from IBRPred from the "Direct" PHI
427     // (b) Leave that as the only edge in the "Indirect" PHI.
428     // (c) Merge the two in the body block.
429     BasicBlock::iterator Indirect = Target->begin(),
430                          End = Target->getFirstNonPHI()->getIterator();
431     BasicBlock::iterator Direct = DirectSucc->begin();
432     BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
433 
434     assert(&*End == Target->getTerminator() &&
435            "Block was expected to only contain PHIs");
436 
437     while (Indirect != End) {
438       PHINode *DirPHI = cast<PHINode>(Direct);
439       PHINode *IndPHI = cast<PHINode>(Indirect);
440 
441       // Now, clean up - the direct block shouldn't get the indirect value,
442       // and vice versa.
443       DirPHI->removeIncomingValue(IBRPred);
444       Direct++;
445 
446       // Advance the pointer here, to avoid invalidation issues when the old
447       // PHI is erased.
448       Indirect++;
449 
450       PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
451       NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
452                              IBRPred);
453 
454       // Create a PHI in the body block, to merge the direct and indirect
455       // predecessors.
456       PHINode *MergePHI =
457           PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
458       MergePHI->addIncoming(NewIndPHI, Target);
459       MergePHI->addIncoming(DirPHI, DirectSucc);
460 
461       IndPHI->replaceAllUsesWith(MergePHI);
462       IndPHI->eraseFromParent();
463     }
464 
465     Changed = true;
466   }
467 
468   return Changed;
469 }
470