blob: c3d67087ae7edc54ad211bbfca2a3000a1bc0e07 [file] [log] [blame]
Chris Lattnerb03832d2002-09-24 00:08:39 +00001//===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerb03832d2002-09-24 00:08:39 +00009//
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
Cameron Zwarichb7036542011-01-18 04:11:31 +000014// dominator trees.
Chris Lattnerb03832d2002-09-24 00:08:39 +000015//
16//===----------------------------------------------------------------------===//
17
Wei Mie04d0ef2016-07-22 18:04:25 +000018#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +000019#include "llvm/ADT/SetVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/Statistic.h"
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +000022#include "llvm/Analysis/BlockFrequencyInfo.h"
23#include "llvm/Analysis/BranchProbabilityInfo.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000024#include "llvm/Analysis/CFG.h"
Chris Lattner89c1dfc2005-08-13 01:38:43 +000025#include "llvm/Analysis/LoopInfo.h"
Alina Sbirleaab6f84f72018-08-21 23:32:03 +000026#include "llvm/Analysis/MemorySSAUpdater.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000027#include "llvm/IR/CFG.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Type.h"
Torok Edwin56d06592009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
David Blaikiea373d182018-03-28 17:44:36 +000032#include "llvm/Transforms/Utils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +000034#include "llvm/Transforms/Utils/Cloning.h"
35#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattnerdf3c3422004-01-09 06:12:26 +000036using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000037
Chandler Carruth964daaa2014-04-22 02:55:47 +000038#define DEBUG_TYPE "break-crit-edges"
39
Chris Lattner45f966d2006-12-19 22:17:40 +000040STATISTIC(NumBroken, "Number of blocks inserted");
Chris Lattnerb03832d2002-09-24 00:08:39 +000041
Chris Lattner45f966d2006-12-19 22:17:40 +000042namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000043 struct BreakCriticalEdges : public FunctionPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000044 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000045 BreakCriticalEdges() : FunctionPass(ID) {
46 initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
47 }
Devang Patel09f162c2007-05-01 21:15:47 +000048
Kostya Serebryanye5ea4242014-11-19 00:17:31 +000049 bool runOnFunction(Function &F) override {
Chandler Carruth37df2cf2015-01-19 12:09:11 +000050 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
51 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
52 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
53 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
54 unsigned N =
55 SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI));
Kostya Serebryanye5ea4242014-11-19 00:17:31 +000056 NumBroken += N;
57 return N > 0;
58 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000059
Craig Topper3e4c6972014-03-05 09:10:37 +000060 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +000061 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +000062 AU.addPreserved<LoopInfoWrapperPass>();
Chris Lattner72272a72003-10-12 21:52:28 +000063
64 // No loop canonicalization guarantees are broken by this pass.
65 AU.addPreservedID(LoopSimplifyID);
Chris Lattner4bec6652002-09-24 15:43:12 +000066 }
67 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000068}
Chris Lattnerb03832d2002-09-24 00:08:39 +000069
Dan Gohmand78c4002008-05-13 00:00:25 +000070char BreakCriticalEdges::ID = 0;
Owen Andersond31d82d2010-08-23 17:52:01 +000071INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
Owen Andersondf7a4f22010-10-07 22:25:06 +000072 "Break critical edges in CFG", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000073
Chris Lattner0ab5e2c2011-04-15 05:18:47 +000074// Publicly exposed interface to pass...
Owen Andersona7aed182010-08-06 18:33:48 +000075char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
Chris Lattner7471b962004-07-31 10:01:58 +000076FunctionPass *llvm::createBreakCriticalEdgesPass() {
77 return new BreakCriticalEdges();
78}
Chris Lattnerb03832d2002-09-24 00:08:39 +000079
Wei Mie04d0ef2016-07-22 18:04:25 +000080PreservedAnalyses 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));
85 NumBroken += N;
86 if (N == 0)
87 return PreservedAnalyses::all();
88 PreservedAnalyses PA;
89 PA.preserve<DominatorTreeAnalysis>();
90 PA.preserve<LoopAnalysis>();
91 return PA;
92}
93
Chris Lattner1e6d3052003-11-10 04:42:42 +000094//===----------------------------------------------------------------------===//
95// Implementation of the external critical edge manipulation functions
96//===----------------------------------------------------------------------===//
Chris Lattner75f80bd2002-09-24 15:51:56 +000097
Sanjay Patel85ce0f12016-04-23 16:31:48 +000098/// 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.
Bill Wendling325e6cd2012-04-30 10:25:51 +0000102static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
Dan Gohmanec4557f2009-09-09 18:18:18 +0000103 BasicBlock *SplitBB,
104 BasicBlock *DestBB) {
105 // SplitBB shouldn't have anything non-trivial in it yet.
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000106 assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
107 SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
Dan Gohmanec4557f2009-09-09 18:18:18 +0000108
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000109 // For each PHI in the destination block.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000110 for (PHINode &PN : DestBB->phis()) {
111 unsigned Idx = PN.getBasicBlockIndex(SplitBB);
112 Value *V = PN.getIncomingValue(Idx);
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000113
Dan Gohmanec4557f2009-09-09 18:18:18 +0000114 // If the input is a PHI which already satisfies LCSSA, don't create
115 // a new one.
116 if (const PHINode *VP = dyn_cast<PHINode>(V))
117 if (VP->getParent() == SplitBB)
118 continue;
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000119
Dan Gohmanec4557f2009-09-09 18:18:18 +0000120 // Otherwise a new PHI is needed. Create one and populate it.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000121 PHINode *NewPN = PHINode::Create(
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000122 PN.getType(), Preds.size(), "split",
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000123 SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator());
Dan Gohmanec4557f2009-09-09 18:18:18 +0000124 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
125 NewPN->addIncoming(V, Preds[i]);
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000126
Dan Gohmanec4557f2009-09-09 18:18:18 +0000127 // Update the original PHI.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000128 PN.setIncomingValue(Idx, NewPN);
Dan Gohmanec4557f2009-09-09 18:18:18 +0000129 }
130}
131
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000132BasicBlock *
Chandler Carruthb99a24682018-10-15 09:17:09 +0000133llvm::SplitCriticalEdge(Instruction *TI, unsigned SuccNum,
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000134 const CriticalEdgeSplittingOptions &Options) {
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000135 if (!isCriticalEdge(TI, SuccNum, Options.MergeIdenticalEdges))
136 return nullptr;
Andrew Trick411842f2011-10-04 03:34:49 +0000137
Chris Lattnerba364b02009-10-31 21:51:10 +0000138 assert(!isa<IndirectBrInst>(TI) &&
139 "Cannot split critical edge from IndirectBrInst");
Andrew Trick411842f2011-10-04 03:34:49 +0000140
Chris Lattner75f80bd2002-09-24 15:51:56 +0000141 BasicBlock *TIBB = TI->getParent();
Chris Lattner12764c82002-10-31 02:44:36 +0000142 BasicBlock *DestBB = TI->getSuccessor(SuccNum);
Chris Lattner75f80bd2002-09-24 15:51:56 +0000143
David Majnemereb518bd2015-08-04 08:21:40 +0000144 // Splitting the critical edge to a pad block is non-trivial. Don't do
Bill Wendling2dfbcc42011-08-17 21:04:05 +0000145 // it in this generic function.
David Majnemereb518bd2015-08-04 08:21:40 +0000146 if (DestBB->isEHPad()) return nullptr;
Bill Wendling2dfbcc42011-08-17 21:04:05 +0000147
Chris Lattner75f80bd2002-09-24 15:51:56 +0000148 // Create a new basic block, linking it into the CFG.
Owen Anderson55f1c092009-08-13 21:58:54 +0000149 BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
150 TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
Chris Lattner72c4dce2010-02-13 04:24:19 +0000151 // Create our unconditional branch.
Devang Patelc23bcbc2011-05-17 19:43:06 +0000152 BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
153 NewBI->setDebugLoc(TI->getDebugLoc());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000154
Chris Lattner80ea2072006-10-28 06:44:56 +0000155 // Branch to the new block, breaking the edge.
Chris Lattner75f80bd2002-09-24 15:51:56 +0000156 TI->setSuccessor(SuccNum, NewBB);
157
158 // Insert the block into the function... right after the block TI lives in.
159 Function &F = *TIBB->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000160 Function::iterator FBBI = TIBB->getIterator();
Chris Lattner233f97a2007-04-17 18:09:47 +0000161 F.getBasicBlockList().insert(++FBBI, NewBB);
Andrew Trick411842f2011-10-04 03:34:49 +0000162
Chris Lattner75f80bd2002-09-24 15:51:56 +0000163 // 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.
Jay Foad61ea0e42011-06-23 09:09:15 +0000165 {
166 unsigned BBIdx = 0;
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);
172
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
177 // order.
178 if (PN->getIncomingBlock(BBIdx) != TIBB)
Andrew Trick411842f2011-10-04 03:34:49 +0000179 BBIdx = PN->getBasicBlockIndex(TIBB);
Jay Foad61ea0e42011-06-23 09:09:15 +0000180 PN->setIncomingBlock(BBIdx, NewBB);
Chris Lattner5e7f7052010-02-13 05:01:14 +0000181 }
Chris Lattner75f80bd2002-09-24 15:51:56 +0000182 }
Andrew Trick411842f2011-10-04 03:34:49 +0000183
Chris Lattner80ea2072006-10-28 06:44:56 +0000184 // 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).
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000187 if (Options.MergeIdenticalEdges) {
Chris Lattner80ea2072006-10-28 06:44:56 +0000188 for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
189 if (TI->getSuccessor(i) != DestBB) continue;
Andrew Trick411842f2011-10-04 03:34:49 +0000190
Chris Lattner80ea2072006-10-28 06:44:56 +0000191 // Remove an entry for TIBB from DestBB phi nodes.
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000192 DestBB->removePredecessor(TIBB, Options.DontDeleteUselessPHIs);
Andrew Trick411842f2011-10-04 03:34:49 +0000193
Chris Lattner80ea2072006-10-28 06:44:56 +0000194 // We found another edge to DestBB, go to NewBB instead.
195 TI->setSuccessor(i, NewBB);
196 }
197 }
Andrew Trick411842f2011-10-04 03:34:49 +0000198
Chris Lattner5e7f7052010-02-13 05:01:14 +0000199 // If we have nothing to update, just return.
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000200 auto *DT = Options.DT;
201 auto *LI = Options.LI;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000202 auto *MSSAU = Options.MSSAU;
203 if (MSSAU)
Alina Sbirleaf98c2c52018-09-07 21:14:48 +0000204 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(
205 DestBB, NewBB, {TIBB}, Options.MergeIdenticalEdges);
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000206
Craig Topperf40110f2014-04-25 05:29:35 +0000207 if (!DT && !LI)
Chris Lattner5e7f7052010-02-13 05:01:14 +0000208 return NewBB;
Chris Lattner5ac72de2002-10-08 21:06:27 +0000209
Chris Lattner5e7f7052010-02-13 05:01:14 +0000210 if (DT) {
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000211 // Update the DominatorTree.
212 // ---> NewBB -----\
213 // / V
214 // TIBB -------\\------> DestBB
Chris Lattnerbedbd6b2002-09-26 16:18:51 +0000215 //
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000216 // 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
219 // get disconnected.
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});
Andrew Trick411842f2011-10-04 03:34:49 +0000225
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000226 DT->applyUpdates(Updates);
Chris Lattner75f80bd2002-09-24 15:51:56 +0000227 }
Chris Lattner12764c82002-10-31 02:44:36 +0000228
Chris Lattner89c1dfc2005-08-13 01:38:43 +0000229 // Update LoopInfo if it is around.
Chris Lattner5e7f7052010-02-13 05:01:14 +0000230 if (LI) {
Dan Gohman3ddbc242009-09-08 15:45:00 +0000231 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.
Chris Lattner89c1dfc2005-08-13 01:38:43 +0000234 if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
235 if (TIL == DestLoop) {
236 // Both in the same loop, the NewBB joins loop.
Chandler Carruth691addc2015-01-18 01:25:51 +0000237 DestLoop->addBasicBlockToLoop(NewBB, *LI);
Dan Gohman18fa5682009-12-18 01:24:09 +0000238 } else if (TIL->contains(DestLoop)) {
Chris Lattner8aca0ee2006-10-03 07:02:02 +0000239 // Edge from an outer loop to an inner loop. Add to the outer loop.
Chandler Carruth691addc2015-01-18 01:25:51 +0000240 TIL->addBasicBlockToLoop(NewBB, *LI);
Dan Gohman18fa5682009-12-18 01:24:09 +0000241 } else if (DestLoop->contains(TIL)) {
Chris Lattner8aca0ee2006-10-03 07:02:02 +0000242 // Edge from an inner loop to an outer loop. Add to the outer loop.
Chandler Carruth691addc2015-01-18 01:25:51 +0000243 DestLoop->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner89c1dfc2005-08-13 01:38:43 +0000244 } else {
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())
Chandler Carruth691addc2015-01-18 01:25:51 +0000252 P->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner89c1dfc2005-08-13 01:38:43 +0000253 }
254 }
Chandler Carruthad34d912015-01-19 10:23:00 +0000255
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000256 // If TIBB is in a loop and DestBB is outside of that loop, we may need
257 // to update LoopSimplify form and LCSSA form.
Chandler Carruthad34d912015-01-19 10:23:00 +0000258 if (!TIL->contains(DestBB)) {
Dan Gohmanec4557f2009-09-09 18:18:18 +0000259 assert(!TIL->contains(NewBB) &&
260 "Split point for loop exit is contained in loop!");
261
262 // Update LCSSA form in the newly created exit block.
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000263 if (Options.PreserveLCSSA) {
Bill Wendling325e6cd2012-04-30 10:25:51 +0000264 createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
Chandler Carruthad34d912015-01-19 10:23:00 +0000265 }
Dan Gohmanec4557f2009-09-09 18:18:18 +0000266
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000267 // 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;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000277 for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
278 ++I) {
279 BasicBlock *P = *I;
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000280 if (P == NewBB)
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.
284 LoopPreds.clear();
285 break;
Gabor Greiffd8e7d42010-07-09 16:31:08 +0000286 }
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000287 LoopPreds.push_back(P);
288 }
289 if (!LoopPreds.empty()) {
David Majnemereb518bd2015-08-04 08:21:40 +0000290 assert(!DestBB->isEHPad() && "We don't split edges to EH pads!");
Chandler Carruthb5797b62015-01-18 09:21:15 +0000291 BasicBlock *NewExitBB = SplitBlockPredecessors(
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000292 DestBB, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000293 if (Options.PreserveLCSSA)
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000294 createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000295 }
296 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000297 }
Chris Lattner89c1dfc2005-08-13 01:38:43 +0000298 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000299
300 return NewBB;
Chris Lattner75f80bd2002-09-24 15:51:56 +0000301}
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000302
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.
307static BasicBlock *
308findIBRPredecessor(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());
312 if (!PN)
313 return nullptr;
314
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 TerminatorInst *PredTerm = PredBB->getTerminator();
322 switch (PredTerm->getOpcode()) {
323 case Instruction::IndirectBr:
324 if (IBB)
325 return nullptr;
326 IBB = PredBB;
327 break;
328 case Instruction::Br:
329 case Instruction::Switch:
330 OtherPreds.push_back(PredBB);
331 continue;
332 default:
333 return nullptr;
334 }
335 }
336
337 return IBB;
338}
339
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000340bool llvm::SplitIndirectBrCriticalEdges(Function &F,
341 BranchProbabilityInfo *BPI,
342 BlockFrequencyInfo *BFI) {
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000343 // 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;
347 for (auto &BB : F) {
348 auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
349 if (!IBI)
350 continue;
351
352 for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
353 Targets.insert(IBI->getSuccessor(Succ));
354 }
355
356 if (Targets.empty())
357 return false;
358
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000359 bool ShouldUpdateAnalysis = BPI && BFI;
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000360 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())
367 continue;
368
369 // Don't even think about ehpads/landingpads.
370 Instruction *FirstNonPHI = Target->getFirstNonPHI();
371 if (FirstNonPHI->isEHPad() || Target->isLandingPad())
372 continue;
373
374 BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000375 if (ShouldUpdateAnalysis) {
376 // Copy the BFI/BPI from Target to BodyBlock.
377 for (unsigned I = 0, E = BodyBlock->getTerminator()->getNumSuccessors();
378 I < E; ++I)
379 BPI->setEdgeProbability(BodyBlock, I,
380 BPI->getEdgeProbability(Target, I));
381 BFI->setBlockFreq(BodyBlock, BFI->getBlockFreq(Target).getFrequency());
382 }
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000383 // 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)
386 IBRPred = BodyBlock;
387
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"
390 // preds.
391 ValueToValueMapTy VMap;
392 BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
393
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000394 BlockFrequency BlockFreqForDirectSucc;
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000395 for (BasicBlock *Pred : OtherPreds) {
396 // If the target is a loop to itself, then the terminator of the split
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000397 // 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);
403 }
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);
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000410 }
411
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();
421
422 assert(&*End == Target->getTerminator() &&
423 "Block was expected to only contain PHIs");
424
425 while (Indirect != End) {
426 PHINode *DirPHI = cast<PHINode>(Direct);
427 PHINode *IndPHI = cast<PHINode>(Indirect);
428
429 // Now, clean up - the direct block shouldn't get the indirect value,
430 // and vice versa.
431 DirPHI->removeIncomingValue(IBRPred);
432 Direct++;
433
434 // Advance the pointer here, to avoid invalidation issues when the old
435 // PHI is erased.
436 Indirect++;
437
438 PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
439 NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
440 IBRPred);
441
442 // Create a PHI in the body block, to merge the direct and indirect
443 // predecessors.
444 PHINode *MergePHI =
445 PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
446 MergePHI->addIncoming(NewIndPHI, Target);
447 MergePHI->addIncoming(DirPHI, DirectSucc);
448
449 IndPHI->replaceAllUsesWith(MergePHI);
450 IndPHI->eraseFromParent();
451 }
452
453 Changed = true;
454 }
455
456 return Changed;
457}