blob: f5e4b53f6d97d1a76bf8fb41b4f0f3f168febff2 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Misha Brukmanb1c93172005-04-21 23:48:37 +00006//
John Criswell482202a2003-10-20 19:43:21 +00007//===----------------------------------------------------------------------===//
Chris Lattnerb03832d2002-09-24 00:08:39 +00008//
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
Cameron Zwarichb7036542011-01-18 04:11:31 +000013// dominator trees.
Chris Lattnerb03832d2002-09-24 00:08:39 +000014//
15//===----------------------------------------------------------------------===//
16
Wei Mie04d0ef2016-07-22 18:04:25 +000017#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +000018#include "llvm/ADT/SetVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/Statistic.h"
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +000021#include "llvm/Analysis/BlockFrequencyInfo.h"
22#include "llvm/Analysis/BranchProbabilityInfo.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000023#include "llvm/Analysis/CFG.h"
Chris Lattner89c1dfc2005-08-13 01:38:43 +000024#include "llvm/Analysis/LoopInfo.h"
Alina Sbirleaab6f84f72018-08-21 23:32:03 +000025#include "llvm/Analysis/MemorySSAUpdater.h"
Matt Arsenault65b4ab92019-02-22 15:01:41 +000026#include "llvm/Analysis/PostDominators.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;
Matt Arsenault65b4ab92019-02-22 15:01:41 +000052
53 auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
54 auto *PDT = PDTWP ? &PDTWP->getPostDomTree() : nullptr;
55
Chandler Carruth37df2cf2015-01-19 12:09:11 +000056 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
57 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
58 unsigned N =
Matt Arsenault65b4ab92019-02-22 15:01:41 +000059 SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI, nullptr, PDT));
Kostya Serebryanye5ea4242014-11-19 00:17:31 +000060 NumBroken += N;
61 return N > 0;
62 }
Misha Brukmanb1c93172005-04-21 23:48:37 +000063
Craig Topper3e4c6972014-03-05 09:10:37 +000064 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +000065 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +000066 AU.addPreserved<LoopInfoWrapperPass>();
Chris Lattner72272a72003-10-12 21:52:28 +000067
68 // No loop canonicalization guarantees are broken by this pass.
69 AU.addPreservedID(LoopSimplifyID);
Chris Lattner4bec6652002-09-24 15:43:12 +000070 }
71 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000072}
Chris Lattnerb03832d2002-09-24 00:08:39 +000073
Dan Gohmand78c4002008-05-13 00:00:25 +000074char BreakCriticalEdges::ID = 0;
Owen Andersond31d82d2010-08-23 17:52:01 +000075INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
Owen Andersondf7a4f22010-10-07 22:25:06 +000076 "Break critical edges in CFG", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000077
Chris Lattner0ab5e2c2011-04-15 05:18:47 +000078// Publicly exposed interface to pass...
Owen Andersona7aed182010-08-06 18:33:48 +000079char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
Chris Lattner7471b962004-07-31 10:01:58 +000080FunctionPass *llvm::createBreakCriticalEdgesPass() {
81 return new BreakCriticalEdges();
82}
Chris Lattnerb03832d2002-09-24 00:08:39 +000083
Wei Mie04d0ef2016-07-22 18:04:25 +000084PreservedAnalyses 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
Chris Lattner1e6d3052003-11-10 04:42:42 +000098//===----------------------------------------------------------------------===//
99// Implementation of the external critical edge manipulation functions
100//===----------------------------------------------------------------------===//
Chris Lattner75f80bd2002-09-24 15:51:56 +0000101
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000102/// 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.
Bill Wendling325e6cd2012-04-30 10:25:51 +0000106static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
Dan Gohmanec4557f2009-09-09 18:18:18 +0000107 BasicBlock *SplitBB,
108 BasicBlock *DestBB) {
109 // SplitBB shouldn't have anything non-trivial in it yet.
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000110 assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
111 SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
Dan Gohmanec4557f2009-09-09 18:18:18 +0000112
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000113 // For each PHI in the destination block.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000114 for (PHINode &PN : DestBB->phis()) {
115 unsigned Idx = PN.getBasicBlockIndex(SplitBB);
116 Value *V = PN.getIncomingValue(Idx);
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000117
Dan Gohmanec4557f2009-09-09 18:18:18 +0000118 // 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;
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000123
Dan Gohmanec4557f2009-09-09 18:18:18 +0000124 // Otherwise a new PHI is needed. Create one and populate it.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000125 PHINode *NewPN = PHINode::Create(
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000126 PN.getType(), Preds.size(), "split",
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000127 SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator());
Dan Gohmanec4557f2009-09-09 18:18:18 +0000128 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
129 NewPN->addIncoming(V, Preds[i]);
Bill Wendlingbf4b9af2012-04-30 10:44:54 +0000130
Dan Gohmanec4557f2009-09-09 18:18:18 +0000131 // Update the original PHI.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000132 PN.setIncomingValue(Idx, NewPN);
Dan Gohmanec4557f2009-09-09 18:18:18 +0000133 }
134}
135
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000136BasicBlock *
Chandler Carruthb99a24682018-10-15 09:17:09 +0000137llvm::SplitCriticalEdge(Instruction *TI, unsigned SuccNum,
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000138 const CriticalEdgeSplittingOptions &Options) {
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000139 if (!isCriticalEdge(TI, SuccNum, Options.MergeIdenticalEdges))
140 return nullptr;
Andrew Trick411842f2011-10-04 03:34:49 +0000141
Chris Lattnerba364b02009-10-31 21:51:10 +0000142 assert(!isa<IndirectBrInst>(TI) &&
143 "Cannot split critical edge from IndirectBrInst");
Andrew Trick411842f2011-10-04 03:34:49 +0000144
Chris Lattner75f80bd2002-09-24 15:51:56 +0000145 BasicBlock *TIBB = TI->getParent();
Chris Lattner12764c82002-10-31 02:44:36 +0000146 BasicBlock *DestBB = TI->getSuccessor(SuccNum);
Chris Lattner75f80bd2002-09-24 15:51:56 +0000147
David Majnemereb518bd2015-08-04 08:21:40 +0000148 // Splitting the critical edge to a pad block is non-trivial. Don't do
Bill Wendling2dfbcc42011-08-17 21:04:05 +0000149 // it in this generic function.
David Majnemereb518bd2015-08-04 08:21:40 +0000150 if (DestBB->isEHPad()) return nullptr;
Bill Wendling2dfbcc42011-08-17 21:04:05 +0000151
Craig Topper784929d2019-02-08 20:48:56 +0000152 // Don't split the non-fallthrough edge from a callbr.
153 if (isa<CallBrInst>(TI) && SuccNum > 0)
154 return nullptr;
155
Craig Topper03e93f52019-03-12 18:20:25 +0000156 if (Options.IgnoreUnreachableDests &&
157 isa<UnreachableInst>(DestBB->getFirstNonPHIOrDbgOrLifetime()))
158 return nullptr;
159
Chris Lattner75f80bd2002-09-24 15:51:56 +0000160 // Create a new basic block, linking it into the CFG.
Owen Anderson55f1c092009-08-13 21:58:54 +0000161 BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
162 TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
Chris Lattner72c4dce2010-02-13 04:24:19 +0000163 // Create our unconditional branch.
Devang Patelc23bcbc2011-05-17 19:43:06 +0000164 BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
165 NewBI->setDebugLoc(TI->getDebugLoc());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000166
Chris Lattner80ea2072006-10-28 06:44:56 +0000167 // Branch to the new block, breaking the edge.
Chris Lattner75f80bd2002-09-24 15:51:56 +0000168 TI->setSuccessor(SuccNum, NewBB);
169
170 // Insert the block into the function... right after the block TI lives in.
171 Function &F = *TIBB->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000172 Function::iterator FBBI = TIBB->getIterator();
Chris Lattner233f97a2007-04-17 18:09:47 +0000173 F.getBasicBlockList().insert(++FBBI, NewBB);
Andrew Trick411842f2011-10-04 03:34:49 +0000174
Chris Lattner75f80bd2002-09-24 15:51:56 +0000175 // If there are any PHI nodes in DestBB, we need to update them so that they
176 // merge incoming values from NewBB instead of from TIBB.
Jay Foad61ea0e42011-06-23 09:09:15 +0000177 {
178 unsigned BBIdx = 0;
179 for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
180 // We no longer enter through TIBB, now we come in through NewBB.
181 // Revector exactly one entry in the PHI node that used to come from
182 // TIBB to come from NewBB.
183 PHINode *PN = cast<PHINode>(I);
184
185 // Reuse the previous value of BBIdx if it lines up. In cases where we
186 // have multiple phi nodes with *lots* of predecessors, this is a speed
187 // win because we don't have to scan the PHI looking for TIBB. This
188 // happens because the BB list of PHI nodes are usually in the same
189 // order.
190 if (PN->getIncomingBlock(BBIdx) != TIBB)
Andrew Trick411842f2011-10-04 03:34:49 +0000191 BBIdx = PN->getBasicBlockIndex(TIBB);
Jay Foad61ea0e42011-06-23 09:09:15 +0000192 PN->setIncomingBlock(BBIdx, NewBB);
Chris Lattner5e7f7052010-02-13 05:01:14 +0000193 }
Chris Lattner75f80bd2002-09-24 15:51:56 +0000194 }
Andrew Trick411842f2011-10-04 03:34:49 +0000195
Chris Lattner80ea2072006-10-28 06:44:56 +0000196 // If there are any other edges from TIBB to DestBB, update those to go
197 // through the split block, making those edges non-critical as well (and
198 // reducing the number of phi entries in the DestBB if relevant).
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000199 if (Options.MergeIdenticalEdges) {
Chris Lattner80ea2072006-10-28 06:44:56 +0000200 for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
201 if (TI->getSuccessor(i) != DestBB) continue;
Andrew Trick411842f2011-10-04 03:34:49 +0000202
Chris Lattner80ea2072006-10-28 06:44:56 +0000203 // Remove an entry for TIBB from DestBB phi nodes.
Max Kazantsev20b91892019-02-12 07:09:29 +0000204 DestBB->removePredecessor(TIBB, Options.KeepOneInputPHIs);
Andrew Trick411842f2011-10-04 03:34:49 +0000205
Chris Lattner80ea2072006-10-28 06:44:56 +0000206 // We found another edge to DestBB, go to NewBB instead.
207 TI->setSuccessor(i, NewBB);
208 }
209 }
Andrew Trick411842f2011-10-04 03:34:49 +0000210
Chris Lattner5e7f7052010-02-13 05:01:14 +0000211 // If we have nothing to update, just return.
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000212 auto *DT = Options.DT;
Matt Arsenault65b4ab92019-02-22 15:01:41 +0000213 auto *PDT = Options.PDT;
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000214 auto *LI = Options.LI;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000215 auto *MSSAU = Options.MSSAU;
216 if (MSSAU)
Alina Sbirleaf98c2c52018-09-07 21:14:48 +0000217 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(
218 DestBB, NewBB, {TIBB}, Options.MergeIdenticalEdges);
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000219
Matt Arsenault65b4ab92019-02-22 15:01:41 +0000220 if (!DT && !PDT && !LI)
Chris Lattner5e7f7052010-02-13 05:01:14 +0000221 return NewBB;
Chris Lattner5ac72de2002-10-08 21:06:27 +0000222
Matt Arsenault65b4ab92019-02-22 15:01:41 +0000223 if (DT || PDT) {
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000224 // Update the DominatorTree.
225 // ---> NewBB -----\
226 // / V
227 // TIBB -------\\------> DestBB
Chris Lattnerbedbd6b2002-09-26 16:18:51 +0000228 //
Jakub Kuderskie35a4492017-08-17 16:45:35 +0000229 // First, inform the DT about the new path from TIBB to DestBB via NewBB,
230 // then delete the old edge from TIBB to DestBB. By doing this in that order
231 // DestBB stays reachable in the DT the whole time and its subtree doesn't
232 // get disconnected.
233 SmallVector<DominatorTree::UpdateType, 3> Updates;
234 Updates.push_back({DominatorTree::Insert, TIBB, NewBB});
235 Updates.push_back({DominatorTree::Insert, NewBB, DestBB});
236 if (llvm::find(successors(TIBB), DestBB) == succ_end(TIBB))
237 Updates.push_back({DominatorTree::Delete, TIBB, DestBB});
Andrew Trick411842f2011-10-04 03:34:49 +0000238
Matt Arsenault65b4ab92019-02-22 15:01:41 +0000239 if (DT)
240 DT->applyUpdates(Updates);
241 if (PDT)
242 PDT->applyUpdates(Updates);
Chris Lattner75f80bd2002-09-24 15:51:56 +0000243 }
Chris Lattner12764c82002-10-31 02:44:36 +0000244
Chris Lattner89c1dfc2005-08-13 01:38:43 +0000245 // Update LoopInfo if it is around.
Chris Lattner5e7f7052010-02-13 05:01:14 +0000246 if (LI) {
Dan Gohman3ddbc242009-09-08 15:45:00 +0000247 if (Loop *TIL = LI->getLoopFor(TIBB)) {
248 // If one or the other blocks were not in a loop, the new block is not
249 // either, and thus LI doesn't need to be updated.
Chris Lattner89c1dfc2005-08-13 01:38:43 +0000250 if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
251 if (TIL == DestLoop) {
252 // Both in the same loop, the NewBB joins loop.
Chandler Carruth691addc2015-01-18 01:25:51 +0000253 DestLoop->addBasicBlockToLoop(NewBB, *LI);
Dan Gohman18fa5682009-12-18 01:24:09 +0000254 } else if (TIL->contains(DestLoop)) {
Chris Lattner8aca0ee2006-10-03 07:02:02 +0000255 // Edge from an outer loop to an inner loop. Add to the outer loop.
Chandler Carruth691addc2015-01-18 01:25:51 +0000256 TIL->addBasicBlockToLoop(NewBB, *LI);
Dan Gohman18fa5682009-12-18 01:24:09 +0000257 } else if (DestLoop->contains(TIL)) {
Chris Lattner8aca0ee2006-10-03 07:02:02 +0000258 // Edge from an inner loop to an outer loop. Add to the outer loop.
Chandler Carruth691addc2015-01-18 01:25:51 +0000259 DestLoop->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner89c1dfc2005-08-13 01:38:43 +0000260 } else {
261 // Edge from two loops with no containment relation. Because these
262 // are natural loops, we know that the destination block must be the
263 // header of its loop (adding a branch into a loop elsewhere would
264 // create an irreducible loop).
265 assert(DestLoop->getHeader() == DestBB &&
266 "Should not create irreducible loops!");
267 if (Loop *P = DestLoop->getParentLoop())
Chandler Carruth691addc2015-01-18 01:25:51 +0000268 P->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner89c1dfc2005-08-13 01:38:43 +0000269 }
270 }
Chandler Carruthad34d912015-01-19 10:23:00 +0000271
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000272 // If TIBB is in a loop and DestBB is outside of that loop, we may need
273 // to update LoopSimplify form and LCSSA form.
Chandler Carruthad34d912015-01-19 10:23:00 +0000274 if (!TIL->contains(DestBB)) {
Dan Gohmanec4557f2009-09-09 18:18:18 +0000275 assert(!TIL->contains(NewBB) &&
276 "Split point for loop exit is contained in loop!");
277
278 // Update LCSSA form in the newly created exit block.
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000279 if (Options.PreserveLCSSA) {
Bill Wendling325e6cd2012-04-30 10:25:51 +0000280 createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
Chandler Carruthad34d912015-01-19 10:23:00 +0000281 }
Dan Gohmanec4557f2009-09-09 18:18:18 +0000282
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000283 // The only that we can break LoopSimplify form by splitting a critical
284 // edge is if after the split there exists some edge from TIL to DestBB
285 // *and* the only edge into DestBB from outside of TIL is that of
286 // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
287 // is the new exit block and it has no non-loop predecessors. If the
288 // second isn't true, then DestBB was not in LoopSimplify form prior to
289 // the split as it had a non-loop predecessor. In both of these cases,
290 // the predecessor must be directly in TIL, not in a subloop, or again
291 // LoopSimplify doesn't hold.
292 SmallVector<BasicBlock *, 4> LoopPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000293 for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
294 ++I) {
295 BasicBlock *P = *I;
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000296 if (P == NewBB)
297 continue; // The new block is known.
298 if (LI->getLoopFor(P) != TIL) {
299 // No need to re-simplify, it wasn't to start with.
300 LoopPreds.clear();
301 break;
Gabor Greiffd8e7d42010-07-09 16:31:08 +0000302 }
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000303 LoopPreds.push_back(P);
304 }
305 if (!LoopPreds.empty()) {
David Majnemereb518bd2015-08-04 08:21:40 +0000306 assert(!DestBB->isEHPad() && "We don't split edges to EH pads!");
Chandler Carruthb5797b62015-01-18 09:21:15 +0000307 BasicBlock *NewExitBB = SplitBlockPredecessors(
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000308 DestBB, LoopPreds, "split", DT, LI, MSSAU, Options.PreserveLCSSA);
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000309 if (Options.PreserveLCSSA)
Chandler Carruthd4be9dc2014-01-29 13:16:53 +0000310 createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000311 }
312 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000313 }
Chris Lattner89c1dfc2005-08-13 01:38:43 +0000314 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000315
316 return NewBB;
Chris Lattner75f80bd2002-09-24 15:51:56 +0000317}
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000318
319// Return the unique indirectbr predecessor of a block. This may return null
320// even if such a predecessor exists, if it's not useful for splitting.
321// If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
322// predecessors of BB.
323static BasicBlock *
324findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
325 // If the block doesn't have any PHIs, we don't care about it, since there's
326 // no point in splitting it.
327 PHINode *PN = dyn_cast<PHINode>(BB->begin());
328 if (!PN)
329 return nullptr;
330
331 // Verify we have exactly one IBR predecessor.
332 // Conservatively bail out if one of the other predecessors is not a "regular"
333 // terminator (that is, not a switch or a br).
334 BasicBlock *IBB = nullptr;
335 for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
336 BasicBlock *PredBB = PN->getIncomingBlock(Pred);
Chandler Carruthedb12a82018-10-15 10:04:59 +0000337 Instruction *PredTerm = PredBB->getTerminator();
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000338 switch (PredTerm->getOpcode()) {
339 case Instruction::IndirectBr:
340 if (IBB)
341 return nullptr;
342 IBB = PredBB;
343 break;
344 case Instruction::Br:
345 case Instruction::Switch:
346 OtherPreds.push_back(PredBB);
347 continue;
348 default:
349 return nullptr;
350 }
351 }
352
353 return IBB;
354}
355
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000356bool llvm::SplitIndirectBrCriticalEdges(Function &F,
357 BranchProbabilityInfo *BPI,
358 BlockFrequencyInfo *BFI) {
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000359 // Check whether the function has any indirectbrs, and collect which blocks
360 // they may jump to. Since most functions don't have indirect branches,
361 // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
362 SmallSetVector<BasicBlock *, 16> Targets;
363 for (auto &BB : F) {
364 auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
365 if (!IBI)
366 continue;
367
368 for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
369 Targets.insert(IBI->getSuccessor(Succ));
370 }
371
372 if (Targets.empty())
373 return false;
374
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000375 bool ShouldUpdateAnalysis = BPI && BFI;
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000376 bool Changed = false;
377 for (BasicBlock *Target : Targets) {
378 SmallVector<BasicBlock *, 16> OtherPreds;
379 BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
380 // If we did not found an indirectbr, or the indirectbr is the only
381 // incoming edge, this isn't the kind of edge we're looking for.
382 if (!IBRPred || OtherPreds.empty())
383 continue;
384
385 // Don't even think about ehpads/landingpads.
386 Instruction *FirstNonPHI = Target->getFirstNonPHI();
387 if (FirstNonPHI->isEHPad() || Target->isLandingPad())
388 continue;
389
390 BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000391 if (ShouldUpdateAnalysis) {
392 // Copy the BFI/BPI from Target to BodyBlock.
393 for (unsigned I = 0, E = BodyBlock->getTerminator()->getNumSuccessors();
394 I < E; ++I)
395 BPI->setEdgeProbability(BodyBlock, I,
396 BPI->getEdgeProbability(Target, I));
397 BFI->setBlockFreq(BodyBlock, BFI->getBlockFreq(Target).getFrequency());
398 }
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000399 // It's possible Target was its own successor through an indirectbr.
400 // In this case, the indirectbr now comes from BodyBlock.
401 if (IBRPred == Target)
402 IBRPred = BodyBlock;
403
404 // At this point Target only has PHIs, and BodyBlock has the rest of the
405 // block's body. Create a copy of Target that will be used by the "direct"
406 // preds.
407 ValueToValueMapTy VMap;
408 BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
409
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000410 BlockFrequency BlockFreqForDirectSucc;
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000411 for (BasicBlock *Pred : OtherPreds) {
412 // If the target is a loop to itself, then the terminator of the split
Hiroshi Yamauchif3bda1d2017-12-12 19:07:43 +0000413 // block (BodyBlock) needs to be updated.
414 BasicBlock *Src = Pred != Target ? Pred : BodyBlock;
415 Src->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
416 if (ShouldUpdateAnalysis)
417 BlockFreqForDirectSucc += BFI->getBlockFreq(Src) *
418 BPI->getEdgeProbability(Src, DirectSucc);
419 }
420 if (ShouldUpdateAnalysis) {
421 BFI->setBlockFreq(DirectSucc, BlockFreqForDirectSucc.getFrequency());
422 BlockFrequency NewBlockFreqForTarget =
423 BFI->getBlockFreq(Target) - BlockFreqForDirectSucc;
424 BFI->setBlockFreq(Target, NewBlockFreqForTarget.getFrequency());
425 BPI->eraseBlock(Target);
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000426 }
427
428 // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
429 // they are clones, so the number of PHIs are the same.
430 // (a) Remove the edge coming from IBRPred from the "Direct" PHI
431 // (b) Leave that as the only edge in the "Indirect" PHI.
432 // (c) Merge the two in the body block.
433 BasicBlock::iterator Indirect = Target->begin(),
434 End = Target->getFirstNonPHI()->getIterator();
435 BasicBlock::iterator Direct = DirectSucc->begin();
436 BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
437
438 assert(&*End == Target->getTerminator() &&
439 "Block was expected to only contain PHIs");
440
441 while (Indirect != End) {
442 PHINode *DirPHI = cast<PHINode>(Direct);
443 PHINode *IndPHI = cast<PHINode>(Indirect);
444
445 // Now, clean up - the direct block shouldn't get the indirect value,
446 // and vice versa.
447 DirPHI->removeIncomingValue(IBRPred);
448 Direct++;
449
450 // Advance the pointer here, to avoid invalidation issues when the old
451 // PHI is erased.
452 Indirect++;
453
454 PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
455 NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
456 IBRPred);
457
458 // Create a PHI in the body block, to merge the direct and indirect
459 // predecessors.
460 PHINode *MergePHI =
461 PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
462 MergePHI->addIncoming(NewIndPHI, Target);
463 MergePHI->addIncoming(DirPHI, DirectSucc);
464
465 IndPHI->replaceAllUsesWith(MergePHI);
466 IndPHI->eraseFromParent();
467 }
468
469 Changed = true;
470 }
471
472 return Changed;
473}