blob: 464d1a34f5187a66995203d2b794d0e427c8cfba [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"
Chandler Carruth1305dc32014-03-04 11:45:46 +000026#include "llvm/IR/CFG.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000027#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Instructions.h"
29#include "llvm/IR/Type.h"
Torok Edwin56d06592009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
Wei Mie04d0ef2016-07-22 18:04:25 +000031#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +000033#include "llvm/Transforms/Utils/Cloning.h"
34#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattnerdf3c3422004-01-09 06:12:26 +000035using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000036
Chandler Carruth964daaa2014-04-22 02:55:47 +000037#define DEBUG_TYPE "break-crit-edges"
38
Chris Lattner45f966d2006-12-19 22:17:40 +000039STATISTIC(NumBroken, "Number of blocks inserted");
Chris Lattnerb03832d2002-09-24 00:08:39 +000040
Chris Lattner45f966d2006-12-19 22:17:40 +000041namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000042 struct BreakCriticalEdges : public FunctionPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000043 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000044 BreakCriticalEdges() : FunctionPass(ID) {
45 initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
46 }
Devang Patel09f162c2007-05-01 21:15:47 +000047
Kostya Serebryanye5ea4242014-11-19 00:17:31 +000048 bool runOnFunction(Function &F) override {
Chandler Carruth37df2cf2015-01-19 12:09:11 +000049 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
50 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
51 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
52 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
53 unsigned N =
54 SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI));
Kostya Serebryanye5ea4242014-11-19 00:17:31 +000055 NumBroken += N;
56 return N > 0;
57 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000058
Craig Topper3e4c6972014-03-05 09:10:37 +000059 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +000060 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +000061 AU.addPreserved<LoopInfoWrapperPass>();
Chris Lattner72272a72003-10-12 21:52:28 +000062
63 // No loop canonicalization guarantees are broken by this pass.
64 AU.addPreservedID(LoopSimplifyID);
Chris Lattner4bec6652002-09-24 15:43:12 +000065 }
66 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000067}
Chris Lattnerb03832d2002-09-24 00:08:39 +000068
Dan Gohmand78c4002008-05-13 00:00:25 +000069char BreakCriticalEdges::ID = 0;
Owen Andersond31d82d2010-08-23 17:52:01 +000070INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
Owen Andersondf7a4f22010-10-07 22:25:06 +000071 "Break critical edges in CFG", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000072
Chris Lattner0ab5e2c2011-04-15 05:18:47 +000073// Publicly exposed interface to pass...
Owen Andersona7aed182010-08-06 18:33:48 +000074char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
Chris Lattner7471b962004-07-31 10:01:58 +000075FunctionPass *llvm::createBreakCriticalEdgesPass() {
76 return new BreakCriticalEdges();
77}
Chris Lattnerb03832d2002-09-24 00:08:39 +000078
Wei Mie04d0ef2016-07-22 18:04:25 +000079PreservedAnalyses BreakCriticalEdgesPass::run(Function &F,
80 FunctionAnalysisManager &AM) {
81 auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
82 auto *LI = AM.getCachedResult<LoopAnalysis>(F);
83 unsigned N = SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI));
84 NumBroken += N;
85 if (N == 0)
86 return PreservedAnalyses::all();
87 PreservedAnalyses PA;
88 PA.preserve<DominatorTreeAnalysis>();
89 PA.preserve<LoopAnalysis>();
90 return PA;
91}
92
Chris Lattner1e6d3052003-11-10 04:42:42 +000093//===----------------------------------------------------------------------===//
94// Implementation of the external critical edge manipulation functions
95//===----------------------------------------------------------------------===//
Chris Lattner75f80bd2002-09-24 15:51:56 +000096
Sanjay Patel85ce0f12016-04-23 16:31:48 +000097/// When a loop exit edge is split, LCSSA form may require new PHIs in the new
98/// exit block. This function inserts the new PHIs, as needed. Preds is a list
99/// of preds inside the loop, SplitBB is the new loop exit block, and DestBB is
100/// the old loop exit, now the successor of SplitBB.
Bill Wendling325e6cd2012-04-30 10:25:51 +0000101static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
Dan Gohmanec4557f2009-09-09 18:18:18 +0000102 BasicBlock *SplitBB,
103 BasicBlock *DestBB) {
104 // SplitBB shouldn't have anything non-trivial in it yet.
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000105 assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
106 SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
Dan Gohmanec4557f2009-09-09 18:18:18 +0000107
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000108 // For each PHI in the destination block.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000109 for (PHINode &PN : DestBB->phis()) {
110 unsigned Idx = PN.getBasicBlockIndex(SplitBB);
111 Value *V = PN.getIncomingValue(Idx);
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000112
Dan Gohmanec4557f2009-09-09 18:18:18 +0000113 // If the input is a PHI which already satisfies LCSSA, don't create
114 // a new one.
115 if (const PHINode *VP = dyn_cast<PHINode>(V))
116 if (VP->getParent() == SplitBB)
117 continue;
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000118
Dan Gohmanec4557f2009-09-09 18:18:18 +0000119 // Otherwise a new PHI is needed. Create one and populate it.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000120 PHINode *NewPN = PHINode::Create(
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000121 PN.getType(), Preds.size(), "split",
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000122 SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator());
Dan Gohmanec4557f2009-09-09 18:18:18 +0000123 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
124 NewPN->addIncoming(V, Preds[i]);
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000125
Dan Gohmanec4557f2009-09-09 18:18:18 +0000126 // Update the original PHI.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000127 PN.setIncomingValue(Idx, NewPN);
Dan Gohmanec4557f2009-09-09 18:18:18 +0000128 }
129}
130
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000131BasicBlock *
132llvm::SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum,
133 const CriticalEdgeSplittingOptions &Options) {
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000134 if (!isCriticalEdge(TI, SuccNum, Options.MergeIdenticalEdges))
135 return nullptr;
Andrew Trick411842f2011-10-04 03:34:49 +0000136
Chris Lattnerba364b02009-10-31 21:51:10 +0000137 assert(!isa<IndirectBrInst>(TI) &&
138 "Cannot split critical edge from IndirectBrInst");
Andrew Trick411842f2011-10-04 03:34:49 +0000139
Chris Lattner75f80bd2002-09-24 15:51:56 +0000140 BasicBlock *TIBB = TI->getParent();
Chris Lattner12764c82002-10-31 02:44:36 +0000141 BasicBlock *DestBB = TI->getSuccessor(SuccNum);
Chris Lattner75f80bd2002-09-24 15:51:56 +0000142
David Majnemereb518bd2015-08-04 08:21:40 +0000143 // Splitting the critical edge to a pad block is non-trivial. Don't do
Bill Wendling2dfbcc42011-08-17 21:04:05 +0000144 // it in this generic function.
David Majnemereb518bd2015-08-04 08:21:40 +0000145 if (DestBB->isEHPad()) return nullptr;
Bill Wendling2dfbcc42011-08-17 21:04:05 +0000146
Chris Lattner75f80bd2002-09-24 15:51:56 +0000147 // Create a new basic block, linking it into the CFG.
Owen Anderson55f1c092009-08-13 21:58:54 +0000148 BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
149 TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
Chris Lattner72c4dce2010-02-13 04:24:19 +0000150 // Create our unconditional branch.
Devang Patelc23bcbc2011-05-17 19:43:06 +0000151 BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
152 NewBI->setDebugLoc(TI->getDebugLoc());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000153
Chris Lattner80ea2072006-10-28 06:44:56 +0000154 // Branch to the new block, breaking the edge.
Chris Lattner75f80bd2002-09-24 15:51:56 +0000155 TI->setSuccessor(SuccNum, NewBB);
156
157 // Insert the block into the function... right after the block TI lives in.
158 Function &F = *TIBB->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000159 Function::iterator FBBI = TIBB->getIterator();
Chris Lattner233f97a2007-04-17 18:09:47 +0000160 F.getBasicBlockList().insert(++FBBI, NewBB);
Andrew Trick411842f2011-10-04 03:34:49 +0000161
Chris Lattner75f80bd2002-09-24 15:51:56 +0000162 // If there are any PHI nodes in DestBB, we need to update them so that they
163 // merge incoming values from NewBB instead of from TIBB.
Jay Foad61ea0e42011-06-23 09:09:15 +0000164 {
165 unsigned BBIdx = 0;
166 for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
167 // We no longer enter through TIBB, now we come in through NewBB.
168 // Revector exactly one entry in the PHI node that used to come from
169 // TIBB to come from NewBB.
170 PHINode *PN = cast<PHINode>(I);
171
172 // Reuse the previous value of BBIdx if it lines up. In cases where we
173 // have multiple phi nodes with *lots* of predecessors, this is a speed
174 // win because we don't have to scan the PHI looking for TIBB. This
175 // happens because the BB list of PHI nodes are usually in the same
176 // order.
177 if (PN->getIncomingBlock(BBIdx) != TIBB)
Andrew Trick411842f2011-10-04 03:34:49 +0000178 BBIdx = PN->getBasicBlockIndex(TIBB);
Jay Foad61ea0e42011-06-23 09:09:15 +0000179 PN->setIncomingBlock(BBIdx, NewBB);
Chris Lattner5e7f7052010-02-13 05:01:14 +0000180 }
Chris Lattner75f80bd2002-09-24 15:51:56 +0000181 }
Andrew Trick411842f2011-10-04 03:34:49 +0000182
Chris Lattner80ea2072006-10-28 06:44:56 +0000183 // If there are any other edges from TIBB to DestBB, update those to go
184 // through the split block, making those edges non-critical as well (and
185 // reducing the number of phi entries in the DestBB if relevant).
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000186 if (Options.MergeIdenticalEdges) {
Chris Lattner80ea2072006-10-28 06:44:56 +0000187 for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
188 if (TI->getSuccessor(i) != DestBB) continue;
Andrew Trick411842f2011-10-04 03:34:49 +0000189
Chris Lattner80ea2072006-10-28 06:44:56 +0000190 // Remove an entry for TIBB from DestBB phi nodes.
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000191 DestBB->removePredecessor(TIBB, Options.DontDeleteUselessPHIs);
Andrew Trick411842f2011-10-04 03:34:49 +0000192
Chris Lattner80ea2072006-10-28 06:44:56 +0000193 // We found another edge to DestBB, go to NewBB instead.
194 TI->setSuccessor(i, NewBB);
195 }
196 }
Andrew Trick411842f2011-10-04 03:34:49 +0000197
Chris Lattner5e7f7052010-02-13 05:01:14 +0000198 // If we have nothing to update, just return.
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000199 auto *DT = Options.DT;
200 auto *LI = Options.LI;
Craig Topperf40110f2014-04-25 05:29:35 +0000201 if (!DT && !LI)
Chris Lattner5e7f7052010-02-13 05:01:14 +0000202 return NewBB;
Chris Lattner5ac72de2002-10-08 21:06:27 +0000203
Chris Lattner5e7f7052010-02-13 05:01:14 +0000204 if (DT) {
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000205 // Update the DominatorTree.
206 // ---> NewBB -----\
207 // / V
208 // TIBB -------\\------> DestBB
Chris Lattnerbedbd6b2002-09-26 16:18:51 +0000209 //
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000210 // First, inform the DT about the new path from TIBB to DestBB via NewBB,
211 // then delete the old edge from TIBB to DestBB. By doing this in that order
212 // DestBB stays reachable in the DT the whole time and its subtree doesn't
213 // get disconnected.
214 SmallVector<DominatorTree::UpdateType, 3> Updates;
215 Updates.push_back({DominatorTree::Insert, TIBB, NewBB});
216 Updates.push_back({DominatorTree::Insert, NewBB, DestBB});
217 if (llvm::find(successors(TIBB), DestBB) == succ_end(TIBB))
218 Updates.push_back({DominatorTree::Delete, TIBB, DestBB});
Andrew Trick411842f2011-10-04 03:34:49 +0000219
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000220 DT->applyUpdates(Updates);
Chris Lattner75f80bd2002-09-24 15:51:56 +0000221 }
Chris Lattner12764c82002-10-31 02:44:36 +0000222
Chris Lattner89c1dfc2005-08-13 01:38:43 +0000223 // Update LoopInfo if it is around.
Chris Lattner5e7f7052010-02-13 05:01:14 +0000224 if (LI) {
Dan Gohman3ddbc242009-09-08 15:45:00 +0000225 if (Loop *TIL = LI->getLoopFor(TIBB)) {
226 // If one or the other blocks were not in a loop, the new block is not
227 // either, and thus LI doesn't need to be updated.
Chris Lattner89c1dfc2005-08-13 01:38:43 +0000228 if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
229 if (TIL == DestLoop) {
230 // Both in the same loop, the NewBB joins loop.
Chandler Carruth691addc2015-01-18 01:25:51 +0000231 DestLoop->addBasicBlockToLoop(NewBB, *LI);
Dan Gohman18fa5682009-12-18 01:24:09 +0000232 } else if (TIL->contains(DestLoop)) {
Chris Lattner8aca0ee2006-10-03 07:02:02 +0000233 // Edge from an outer loop to an inner loop. Add to the outer loop.
Chandler Carruth691addc2015-01-18 01:25:51 +0000234 TIL->addBasicBlockToLoop(NewBB, *LI);
Dan Gohman18fa5682009-12-18 01:24:09 +0000235 } else if (DestLoop->contains(TIL)) {
Chris Lattner8aca0ee2006-10-03 07:02:02 +0000236 // Edge from an inner loop to an outer loop. Add to the outer loop.
Chandler Carruth691addc2015-01-18 01:25:51 +0000237 DestLoop->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner89c1dfc2005-08-13 01:38:43 +0000238 } else {
239 // Edge from two loops with no containment relation. Because these
240 // are natural loops, we know that the destination block must be the
241 // header of its loop (adding a branch into a loop elsewhere would
242 // create an irreducible loop).
243 assert(DestLoop->getHeader() == DestBB &&
244 "Should not create irreducible loops!");
245 if (Loop *P = DestLoop->getParentLoop())
Chandler Carruth691addc2015-01-18 01:25:51 +0000246 P->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner89c1dfc2005-08-13 01:38:43 +0000247 }
248 }
Chandler Carruthad34d912015-01-19 10:23:00 +0000249
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000250 // If TIBB is in a loop and DestBB is outside of that loop, we may need
251 // to update LoopSimplify form and LCSSA form.
Chandler Carruthad34d912015-01-19 10:23:00 +0000252 if (!TIL->contains(DestBB)) {
Dan Gohmanec4557f2009-09-09 18:18:18 +0000253 assert(!TIL->contains(NewBB) &&
254 "Split point for loop exit is contained in loop!");
255
256 // Update LCSSA form in the newly created exit block.
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000257 if (Options.PreserveLCSSA) {
Bill Wendling325e6cd2012-04-30 10:25:51 +0000258 createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
Chandler Carruthad34d912015-01-19 10:23:00 +0000259 }
Dan Gohmanec4557f2009-09-09 18:18:18 +0000260
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000261 // The only that we can break LoopSimplify form by splitting a critical
262 // edge is if after the split there exists some edge from TIL to DestBB
263 // *and* the only edge into DestBB from outside of TIL is that of
264 // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
265 // is the new exit block and it has no non-loop predecessors. If the
266 // second isn't true, then DestBB was not in LoopSimplify form prior to
267 // the split as it had a non-loop predecessor. In both of these cases,
268 // the predecessor must be directly in TIL, not in a subloop, or again
269 // LoopSimplify doesn't hold.
270 SmallVector<BasicBlock *, 4> LoopPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000271 for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
272 ++I) {
273 BasicBlock *P = *I;
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000274 if (P == NewBB)
275 continue; // The new block is known.
276 if (LI->getLoopFor(P) != TIL) {
277 // No need to re-simplify, it wasn't to start with.
278 LoopPreds.clear();
279 break;
Gabor Greiffd8e7d42010-07-09 16:31:08 +0000280 }
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000281 LoopPreds.push_back(P);
282 }
283 if (!LoopPreds.empty()) {
David Majnemereb518bd2015-08-04 08:21:40 +0000284 assert(!DestBB->isEHPad() && "We don't split edges to EH pads!");
Chandler Carruthb5797b62015-01-18 09:21:15 +0000285 BasicBlock *NewExitBB = SplitBlockPredecessors(
Chandler Carruth96ada252015-07-22 09:52:54 +0000286 DestBB, LoopPreds, "split", DT, LI, Options.PreserveLCSSA);
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000287 if (Options.PreserveLCSSA)
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000288 createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000289 }
290 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000291 }
Chris Lattner89c1dfc2005-08-13 01:38:43 +0000292 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000293
294 return NewBB;
Chris Lattner75f80bd2002-09-24 15:51:56 +0000295}
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000296
297// Return the unique indirectbr predecessor of a block. This may return null
298// even if such a predecessor exists, if it's not useful for splitting.
299// If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
300// predecessors of BB.
301static BasicBlock *
302findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
303 // If the block doesn't have any PHIs, we don't care about it, since there's
304 // no point in splitting it.
305 PHINode *PN = dyn_cast<PHINode>(BB->begin());
306 if (!PN)
307 return nullptr;
308
309 // Verify we have exactly one IBR predecessor.
310 // Conservatively bail out if one of the other predecessors is not a "regular"
311 // terminator (that is, not a switch or a br).
312 BasicBlock *IBB = nullptr;
313 for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
314 BasicBlock *PredBB = PN->getIncomingBlock(Pred);
315 TerminatorInst *PredTerm = PredBB->getTerminator();
316 switch (PredTerm->getOpcode()) {
317 case Instruction::IndirectBr:
318 if (IBB)
319 return nullptr;
320 IBB = PredBB;
321 break;
322 case Instruction::Br:
323 case Instruction::Switch:
324 OtherPreds.push_back(PredBB);
325 continue;
326 default:
327 return nullptr;
328 }
329 }
330
331 return IBB;
332}
333
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000334bool llvm::SplitIndirectBrCriticalEdges(Function &F,
335 BranchProbabilityInfo *BPI,
336 BlockFrequencyInfo *BFI) {
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000337 // Check whether the function has any indirectbrs, and collect which blocks
338 // they may jump to. Since most functions don't have indirect branches,
339 // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
340 SmallSetVector<BasicBlock *, 16> Targets;
341 for (auto &BB : F) {
342 auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
343 if (!IBI)
344 continue;
345
346 for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
347 Targets.insert(IBI->getSuccessor(Succ));
348 }
349
350 if (Targets.empty())
351 return false;
352
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000353 bool ShouldUpdateAnalysis = BPI && BFI;
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000354 bool Changed = false;
355 for (BasicBlock *Target : Targets) {
356 SmallVector<BasicBlock *, 16> OtherPreds;
357 BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
358 // If we did not found an indirectbr, or the indirectbr is the only
359 // incoming edge, this isn't the kind of edge we're looking for.
360 if (!IBRPred || OtherPreds.empty())
361 continue;
362
363 // Don't even think about ehpads/landingpads.
364 Instruction *FirstNonPHI = Target->getFirstNonPHI();
365 if (FirstNonPHI->isEHPad() || Target->isLandingPad())
366 continue;
367
368 BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000369 if (ShouldUpdateAnalysis) {
370 // Copy the BFI/BPI from Target to BodyBlock.
371 for (unsigned I = 0, E = BodyBlock->getTerminator()->getNumSuccessors();
372 I < E; ++I)
373 BPI->setEdgeProbability(BodyBlock, I,
374 BPI->getEdgeProbability(Target, I));
375 BFI->setBlockFreq(BodyBlock, BFI->getBlockFreq(Target).getFrequency());
376 }
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000377 // It's possible Target was its own successor through an indirectbr.
378 // In this case, the indirectbr now comes from BodyBlock.
379 if (IBRPred == Target)
380 IBRPred = BodyBlock;
381
382 // At this point Target only has PHIs, and BodyBlock has the rest of the
383 // block's body. Create a copy of Target that will be used by the "direct"
384 // preds.
385 ValueToValueMapTy VMap;
386 BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
387
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000388 BlockFrequency BlockFreqForDirectSucc;
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000389 for (BasicBlock *Pred : OtherPreds) {
390 // If the target is a loop to itself, then the terminator of the split
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000391 // block (BodyBlock) needs to be updated.
392 BasicBlock *Src = Pred != Target ? Pred : BodyBlock;
393 Src->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
394 if (ShouldUpdateAnalysis)
395 BlockFreqForDirectSucc += BFI->getBlockFreq(Src) *
396 BPI->getEdgeProbability(Src, DirectSucc);
397 }
398 if (ShouldUpdateAnalysis) {
399 BFI->setBlockFreq(DirectSucc, BlockFreqForDirectSucc.getFrequency());
400 BlockFrequency NewBlockFreqForTarget =
401 BFI->getBlockFreq(Target) - BlockFreqForDirectSucc;
402 BFI->setBlockFreq(Target, NewBlockFreqForTarget.getFrequency());
403 BPI->eraseBlock(Target);
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000404 }
405
406 // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
407 // they are clones, so the number of PHIs are the same.
408 // (a) Remove the edge coming from IBRPred from the "Direct" PHI
409 // (b) Leave that as the only edge in the "Indirect" PHI.
410 // (c) Merge the two in the body block.
411 BasicBlock::iterator Indirect = Target->begin(),
412 End = Target->getFirstNonPHI()->getIterator();
413 BasicBlock::iterator Direct = DirectSucc->begin();
414 BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
415
416 assert(&*End == Target->getTerminator() &&
417 "Block was expected to only contain PHIs");
418
419 while (Indirect != End) {
420 PHINode *DirPHI = cast<PHINode>(Direct);
421 PHINode *IndPHI = cast<PHINode>(Indirect);
422
423 // Now, clean up - the direct block shouldn't get the indirect value,
424 // and vice versa.
425 DirPHI->removeIncomingValue(IBRPred);
426 Direct++;
427
428 // Advance the pointer here, to avoid invalidation issues when the old
429 // PHI is erased.
430 Indirect++;
431
432 PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
433 NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
434 IBRPred);
435
436 // Create a PHI in the body block, to merge the direct and indirect
437 // predecessors.
438 PHINode *MergePHI =
439 PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
440 MergePHI->addIncoming(NewIndPHI, Target);
441 MergePHI->addIncoming(DirPHI, DirectSucc);
442
443 IndPHI->replaceAllUsesWith(MergePHI);
444 IndPHI->eraseFromParent();
445 }
446
447 Changed = true;
448 }
449
450 return Changed;
451}