blob: 0d6d1022502c33bd5e701454db260e37ad17ed4a [file] [log] [blame]
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00001//===- BasicBlockUtils.cpp - BasicBlock Utilities --------------------------==//
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 Lattner28537df2002-05-07 18:07:59 +00008//
9// This family of functions perform manipulations on basic blocks, and
10// instructions contained within basic blocks.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000015#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Twine.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000019#include "llvm/Analysis/CFG.h"
Richard Trieu5f436fc2019-02-06 02:52:52 +000020#include "llvm/Analysis/DomTreeUpdater.h"
Chris Lattnerf6ae9042011-01-11 08:13:40 +000021#include "llvm/Analysis/LoopInfo.h"
22#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Alina Sbirleaab6f84f72018-08-21 23:32:03 +000023#include "llvm/Analysis/MemorySSAUpdater.h"
Chijun Sima21a8b602018-08-03 05:08:17 +000024#include "llvm/Analysis/PostDominators.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000025#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/CFG.h"
27#include "llvm/IR/Constants.h"
Adrian Prantld60f34c2017-11-01 20:43:30 +000028#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000029#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Function.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000031#include "llvm/IR/InstrTypes.h"
32#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Instructions.h"
Adrian Prantld60f34c2017-11-01 20:43:30 +000034#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000035#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/Type.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000037#include "llvm/IR/User.h"
38#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000039#include "llvm/IR/ValueHandle.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000040#include "llvm/Support/Casting.h"
Chijun Sima21a8b602018-08-03 05:08:17 +000041#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000042#include <cassert>
43#include <cstdint>
44#include <string>
45#include <utility>
46#include <vector>
47
Chris Lattnerdf3c3422004-01-09 06:12:26 +000048using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000049
Max Kazantsev36b392c2019-02-06 07:56:36 +000050void llvm::DetatchDeadBlocks(
51 ArrayRef<BasicBlock *> BBs,
Max Kazantsev0686d1a2019-02-12 06:14:27 +000052 SmallVectorImpl<DominatorTree::UpdateType> *Updates,
Max Kazantsev20b91892019-02-12 07:09:29 +000053 bool KeepOneInputPHIs) {
Max Kazantsev1f733102019-01-14 10:26:26 +000054 for (auto *BB : BBs) {
55 // Loop through all of our successors and make sure they know that one
56 // of their predecessors is going away.
Max Kazantsev36b392c2019-02-06 07:56:36 +000057 SmallPtrSet<BasicBlock *, 4> UniqueSuccessors;
Max Kazantsev1f733102019-01-14 10:26:26 +000058 for (BasicBlock *Succ : successors(BB)) {
Max Kazantsev20b91892019-02-12 07:09:29 +000059 Succ->removePredecessor(BB, KeepOneInputPHIs);
Max Kazantsev36b392c2019-02-06 07:56:36 +000060 if (Updates && UniqueSuccessors.insert(Succ).second)
61 Updates->push_back({DominatorTree::Delete, BB, Succ});
Max Kazantsev1f733102019-01-14 10:26:26 +000062 }
63
64 // Zap all the instructions in the block.
65 while (!BB->empty()) {
66 Instruction &I = BB->back();
67 // If this instruction is used, replace uses with an arbitrary value.
68 // Because control flow can't get here, we don't care what we replace the
69 // value with. Note that since this block is unreachable, and all values
70 // contained within it must dominate their uses, that all uses will
71 // eventually be removed (they are themselves dead).
72 if (!I.use_empty())
73 I.replaceAllUsesWith(UndefValue::get(I.getType()));
74 BB->getInstList().pop_back();
75 }
76 new UnreachableInst(BB->getContext(), BB);
77 assert(BB->getInstList().size() == 1 &&
78 isa<UnreachableInst>(BB->getTerminator()) &&
79 "The successor list of BB isn't empty before "
80 "applying corresponding DTU updates.");
81 }
Max Kazantsev36b392c2019-02-06 07:56:36 +000082}
83
Max Kazantsev0686d1a2019-02-12 06:14:27 +000084void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU,
Max Kazantsev20b91892019-02-12 07:09:29 +000085 bool KeepOneInputPHIs) {
86 DeleteDeadBlocks({BB}, DTU, KeepOneInputPHIs);
Max Kazantsev36b392c2019-02-06 07:56:36 +000087}
88
Max Kazantsev0686d1a2019-02-12 06:14:27 +000089void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs, DomTreeUpdater *DTU,
Max Kazantsev20b91892019-02-12 07:09:29 +000090 bool KeepOneInputPHIs) {
Max Kazantsev36b392c2019-02-06 07:56:36 +000091#ifndef NDEBUG
92 // Make sure that all predecessors of each dead block is also dead.
93 SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end());
94 assert(Dead.size() == BBs.size() && "Duplicating blocks?");
95 for (auto *BB : Dead)
96 for (BasicBlock *Pred : predecessors(BB))
97 assert(Dead.count(Pred) && "All predecessors must be dead!");
98#endif
99
100 SmallVector<DominatorTree::UpdateType, 4> Updates;
Max Kazantsev20b91892019-02-12 07:09:29 +0000101 DetatchDeadBlocks(BBs, DTU ? &Updates : nullptr, KeepOneInputPHIs);
Max Kazantsev36b392c2019-02-06 07:56:36 +0000102
Chijun Sima21a8b602018-08-03 05:08:17 +0000103 if (DTU)
Chijun Sima21a8b602018-08-03 05:08:17 +0000104 DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
Max Kazantsev1f733102019-01-14 10:26:26 +0000105
106 for (BasicBlock *BB : BBs)
107 if (DTU)
108 DTU->deleteBB(BB);
109 else
110 BB->eraseFromParent();
Chris Lattnerbcc904a2008-12-03 06:37:44 +0000111}
112
Chandler Carruth96ada252015-07-22 09:52:54 +0000113void llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
Chandler Carruth61440d22016-03-10 00:55:30 +0000114 MemoryDependenceResults *MemDep) {
Chris Lattnerf6ae9042011-01-11 08:13:40 +0000115 if (!isa<PHINode>(BB->begin())) return;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000116
Chris Lattnerdc3f6f22008-12-03 19:44:02 +0000117 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
118 if (PN->getIncomingValue(0) != PN)
119 PN->replaceAllUsesWith(PN->getIncomingValue(0));
120 else
Owen Andersonb292b8c2009-07-30 23:03:37 +0000121 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Jakub Staszak190db2f2013-01-14 23:16:36 +0000122
Chris Lattnerf6ae9042011-01-11 08:13:40 +0000123 if (MemDep)
124 MemDep->removeInstruction(PN); // Memdep updates AA itself.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000125
Chris Lattnerdc3f6f22008-12-03 19:44:02 +0000126 PN->eraseFromParent();
127 }
128}
129
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000130bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
Dan Gohmanff089952009-05-02 18:29:22 +0000131 // Recursively deleting a PHI may cause multiple PHIs to be deleted
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000132 // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
133 SmallVector<WeakTrackingVH, 8> PHIs;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000134 for (PHINode &PN : BB->phis())
135 PHIs.push_back(&PN);
Dan Gohmanff089952009-05-02 18:29:22 +0000136
Dan Gohmancb99fe92010-01-05 15:45:31 +0000137 bool Changed = false;
Dan Gohmanff089952009-05-02 18:29:22 +0000138 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
139 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000140 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
Dan Gohmancb99fe92010-01-05 15:45:31 +0000141
142 return Changed;
Dan Gohmanff089952009-05-02 18:29:22 +0000143}
144
Chijun Sima21a8b602018-08-03 05:08:17 +0000145bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000146 LoopInfo *LI, MemorySSAUpdater *MSSAU,
Chijun Sima21a8b602018-08-03 05:08:17 +0000147 MemoryDependenceResults *MemDep) {
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000148 if (BB->hasAddressTaken())
149 return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000150
Dan Gohman941020e2010-08-17 17:07:02 +0000151 // Can't merge if there are multiple predecessors, or no predecessors.
152 BasicBlock *PredBB = BB->getUniquePredecessor();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000153 if (!PredBB) return false;
Dan Gohman941020e2010-08-17 17:07:02 +0000154
Dan Gohman2d02ff82009-10-31 17:33:01 +0000155 // Don't break self-loops.
156 if (PredBB == BB) return false;
David Majnemer654e1302015-07-31 17:58:14 +0000157 // Don't break unwinding instructions.
Chandler Carruth698fbe72018-08-26 08:56:42 +0000158 if (PredBB->getTerminator()->isExceptionalTerminator())
David Majnemer654e1302015-07-31 17:58:14 +0000159 return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000160
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000161 // Can't merge if there are multiple distinct successors.
162 if (PredBB->getUniqueSuccessor() != BB)
163 return false;
Devang Patel0f7a3502008-09-09 01:06:56 +0000164
Dan Gohman2d02ff82009-10-31 17:33:01 +0000165 // Can't merge if there is PHI loop.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000166 for (PHINode &PN : BB->phis())
167 for (Value *IncValue : PN.incoming_values())
168 if (IncValue == &PN)
169 return false;
Dan Gohman2d02ff82009-10-31 17:33:01 +0000170
171 // Begin by getting rid of unneeded PHIs.
Davide Italiano48283ba2018-05-08 23:28:15 +0000172 SmallVector<AssertingVH<Value>, 4> IncomingValues;
Adrian Prantld60f34c2017-11-01 20:43:30 +0000173 if (isa<PHINode>(BB->front())) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000174 for (PHINode &PN : BB->phis())
Davide Italiano48283ba2018-05-08 23:28:15 +0000175 if (!isa<PHINode>(PN.getIncomingValue(0)) ||
176 cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000177 IncomingValues.push_back(PN.getIncomingValue(0));
Chandler Carruth96ada252015-07-22 09:52:54 +0000178 FoldSingleEntryPHINodes(BB, MemDep);
Adrian Prantld60f34c2017-11-01 20:43:30 +0000179 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000180
Chijun Sima21a8b602018-08-03 05:08:17 +0000181 // DTU update: Collect all the edges that exit BB.
182 // These dominator edges will be redirected from Pred.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000183 std::vector<DominatorTree::UpdateType> Updates;
Chijun Sima21a8b602018-08-03 05:08:17 +0000184 if (DTU) {
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000185 Updates.reserve(1 + (2 * succ_size(BB)));
186 Updates.push_back({DominatorTree::Delete, PredBB, BB});
187 for (auto I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
188 Updates.push_back({DominatorTree::Delete, BB, *I});
189 Updates.push_back({DominatorTree::Insert, PredBB, *I});
190 }
191 }
192
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000193 if (MSSAU)
194 MSSAU->moveAllAfterMergeBlocks(BB, PredBB, &*(BB->begin()));
195
Owen Andersonc0623812008-07-17 00:01:40 +0000196 // Delete the unconditional branch from the predecessor...
197 PredBB->getInstList().pop_back();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000198
Owen Andersonc0623812008-07-17 00:01:40 +0000199 // Make all PHI nodes that referred to BB now refer to Pred as their
200 // source...
201 BB->replaceAllUsesWith(PredBB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000202
Jay Foad61ea0e42011-06-23 09:09:15 +0000203 // Move all definitions in the successor to the predecessor...
204 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
Chijun Sima21a8b602018-08-03 05:08:17 +0000205 new UnreachableInst(BB->getContext(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000206
Adrian Prantld60f34c2017-11-01 20:43:30 +0000207 // Eliminate duplicate dbg.values describing the entry PHI node post-splice.
Davide Italiano48283ba2018-05-08 23:28:15 +0000208 for (auto Incoming : IncomingValues) {
209 if (isa<Instruction>(*Incoming)) {
Adrian Prantld60f34c2017-11-01 20:43:30 +0000210 SmallVector<DbgValueInst *, 2> DbgValues;
211 SmallDenseSet<std::pair<DILocalVariable *, DIExpression *>, 2>
212 DbgValueSet;
213 llvm::findDbgValues(DbgValues, Incoming);
214 for (auto &DVI : DbgValues) {
215 auto R = DbgValueSet.insert({DVI->getVariable(), DVI->getExpression()});
216 if (!R.second)
217 DVI->eraseFromParent();
218 }
219 }
220 }
221
Dan Gohman2d02ff82009-10-31 17:33:01 +0000222 // Inherit predecessors name if it exists.
Owen Anderson27405ef2008-07-17 19:42:29 +0000223 if (!PredBB->hasName())
224 PredBB->takeName(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000225
Chandler Carruthb5c11532015-01-18 02:11:23 +0000226 if (LI)
227 LI->removeBlock(BB);
228
229 if (MemDep)
230 MemDep->invalidateCachedPredecessors();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000231
Chijun Sima21a8b602018-08-03 05:08:17 +0000232 // Finally, erase the old block and update dominator info.
233 if (DTU) {
234 assert(BB->getInstList().size() == 1 &&
235 isa<UnreachableInst>(BB->getTerminator()) &&
236 "The successor list of BB isn't empty before "
237 "applying corresponding DTU updates.");
238 DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
239 DTU->deleteBB(BB);
240 }
241
242 else {
243 BB->eraseFromParent(); // Nuke BB if DTU is nullptr.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000244 }
Dan Gohman2d02ff82009-10-31 17:33:01 +0000245 return true;
Owen Andersonc0623812008-07-17 00:01:40 +0000246}
247
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000248void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
249 BasicBlock::iterator &BI, Value *V) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000250 Instruction &I = *BI;
Chris Lattner28537df2002-05-07 18:07:59 +0000251 // Replaces all of the uses of the instruction with uses of the value
Chris Lattnerfda72b12002-06-25 16:12:52 +0000252 I.replaceAllUsesWith(V);
Chris Lattner28537df2002-05-07 18:07:59 +0000253
Chris Lattner8dd4cae2007-02-11 01:37:51 +0000254 // Make sure to propagate a name if there is one already.
255 if (I.hasName() && !V->hasName())
256 V->takeName(&I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000257
Misha Brukman7eb05a12003-08-18 14:43:39 +0000258 // Delete the unnecessary instruction now...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000259 BI = BIL.erase(BI);
Chris Lattner28537df2002-05-07 18:07:59 +0000260}
261
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000262void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
263 BasicBlock::iterator &BI, Instruction *I) {
Craig Toppere73658d2014-04-28 04:05:08 +0000264 assert(I->getParent() == nullptr &&
Chris Lattner28537df2002-05-07 18:07:59 +0000265 "ReplaceInstWithInst: Instruction already inserted into basic block!");
266
Alexey Samsonov19ffcb92015-06-23 21:00:08 +0000267 // Copy debug location to newly added instruction, if it wasn't already set
268 // by the caller.
269 if (!I->getDebugLoc())
270 I->setDebugLoc(BI->getDebugLoc());
271
Chris Lattner28537df2002-05-07 18:07:59 +0000272 // Insert the new instruction into the basic block...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000273 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner28537df2002-05-07 18:07:59 +0000274
275 // Replace all uses of the old instruction, and delete it.
276 ReplaceInstWithValue(BIL, BI, I);
277
278 // Move BI back to point to the newly inserted instruction
Chris Lattnerfda72b12002-06-25 16:12:52 +0000279 BI = New;
Chris Lattner28537df2002-05-07 18:07:59 +0000280}
281
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000282void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000283 BasicBlock::iterator BI(From);
284 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner28537df2002-05-07 18:07:59 +0000285}
Chris Lattnerb17274e2002-07-29 22:32:08 +0000286
Chandler Carruthd4500562015-01-19 12:36:53 +0000287BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000288 LoopInfo *LI, MemorySSAUpdater *MSSAU) {
Bob Wilsonaff96b22010-02-16 21:06:42 +0000289 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000290
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000291 // If this is a critical edge, let SplitCriticalEdge do it.
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000292 Instruction *LatchTerm = BB->getTerminator();
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000293 if (SplitCriticalEdge(
294 LatchTerm, SuccNum,
295 CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA()))
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000296 return LatchTerm->getSuccessor(SuccNum);
Chandler Carruth32c52c72015-01-18 02:39:37 +0000297
Devang Pateld7767cc2007-07-06 21:39:20 +0000298 // If the edge isn't critical, then BB has a single successor or Succ has a
299 // single pred. Split the block.
Devang Pateld7767cc2007-07-06 21:39:20 +0000300 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
301 // If the successor only has a single pred, split the top of the successor
302 // block.
303 assert(SP == BB && "CFG broken");
Craig Topperf40110f2014-04-25 05:29:35 +0000304 SP = nullptr;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000305 return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU);
Devang Pateld7767cc2007-07-06 21:39:20 +0000306 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000307
Chris Lattner30d95f92011-01-08 18:47:43 +0000308 // Otherwise, if BB has a single successor, split it at the bottom of the
309 // block.
310 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
Jakub Staszak190db2f2013-01-14 23:16:36 +0000311 "Should have a single succ!");
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000312 return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU);
Devang Pateld7767cc2007-07-06 21:39:20 +0000313}
314
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000315unsigned
316llvm::SplitAllCriticalEdges(Function &F,
317 const CriticalEdgeSplittingOptions &Options) {
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000318 unsigned NumBroken = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000319 for (BasicBlock &BB : F) {
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000320 Instruction *TI = BB.getTerminator();
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000321 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
322 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000323 if (SplitCriticalEdge(TI, i, Options))
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000324 ++NumBroken;
325 }
326 return NumBroken;
327}
328
Chandler Carruth32c52c72015-01-18 02:39:37 +0000329BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000330 DominatorTree *DT, LoopInfo *LI,
331 MemorySSAUpdater *MSSAU) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000332 BasicBlock::iterator SplitIt = SplitPt->getIterator();
David Majnemer654e1302015-07-31 17:58:14 +0000333 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
Devang Pateld7767cc2007-07-06 21:39:20 +0000334 ++SplitIt;
335 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
336
Dan Gohman3ddbc242009-09-08 15:45:00 +0000337 // The new block lives in whichever loop the old one did. This preserves
338 // LCSSA as well, because we force the split point to be after any PHI nodes.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000339 if (LI)
340 if (Loop *L = LI->getLoopFor(Old))
341 L->addBasicBlockToLoop(New, *LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000342
Chandler Carruth32c52c72015-01-18 02:39:37 +0000343 if (DT)
Gabor Greif2f5f6962010-09-10 22:25:58 +0000344 // Old dominates New. New node dominates all other nodes dominated by Old.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000345 if (DomTreeNode *OldNode = DT->getNode(Old)) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000346 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
Devang Patel186e0d82007-07-19 02:29:24 +0000347
Chandler Carruth32c52c72015-01-18 02:39:37 +0000348 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000349 for (DomTreeNode *I : Children)
350 DT->changeImmediateDominator(I, NewNode);
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000351 }
Devang Pateld7767cc2007-07-06 21:39:20 +0000352
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000353 // Move MemoryAccesses still tracked in Old, but part of New now.
354 // Update accesses in successor blocks accordingly.
355 if (MSSAU)
356 MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
357
Devang Pateld7767cc2007-07-06 21:39:20 +0000358 return New;
359}
Chris Lattnera5b11702008-04-21 01:28:02 +0000360
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000361/// Update DominatorTree, LoopInfo, and LCCSA analysis information.
Bill Wendling60291352011-08-18 17:57:57 +0000362static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
Bill Wendlingec3823d2011-08-18 20:39:32 +0000363 ArrayRef<BasicBlock *> Preds,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000364 DominatorTree *DT, LoopInfo *LI,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000365 MemorySSAUpdater *MSSAU,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000366 bool PreserveLCSSA, bool &HasLoopExit) {
367 // Update dominator tree if available.
Matt Arsenault06dfbb52018-01-31 22:54:37 +0000368 if (DT) {
369 if (OldBB == DT->getRootNode()->getBlock()) {
370 assert(NewBB == &NewBB->getParent()->getEntryBlock());
371 DT->setNewRoot(NewBB);
372 } else {
373 // Split block expects NewBB to have a non-empty set of predecessors.
374 DT->splitBlock(NewBB);
375 }
376 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000377
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000378 // Update MemoryPhis after split if MemorySSA is available
379 if (MSSAU)
380 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
381
Chandler Carruthb5797b62015-01-18 09:21:15 +0000382 // The rest of the logic is only relevant for updating the loop structures.
383 if (!LI)
384 return;
385
Anna Thomas9fca5832018-01-04 17:21:15 +0000386 assert(DT && "DT should be available to update LoopInfo!");
Chandler Carruthb5797b62015-01-18 09:21:15 +0000387 Loop *L = LI->getLoopFor(OldBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000388
389 // If we need to preserve loop analyses, collect some information about how
390 // this split will affect loops.
391 bool IsLoopEntry = !!L;
392 bool SplitMakesNewLoopHeader = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000393 for (BasicBlock *Pred : Preds) {
Anna Thomasbdb94302018-01-02 16:25:50 +0000394 // Preds that are not reachable from entry should not be used to identify if
395 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
396 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
397 // as true and make the NewBB the header of some loop. This breaks LI.
398 if (!DT->isReachableFromEntry(Pred))
399 continue;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000400 // If we need to preserve LCSSA, determine if any of the preds is a loop
401 // exit.
402 if (PreserveLCSSA)
403 if (Loop *PL = LI->getLoopFor(Pred))
404 if (!PL->contains(OldBB))
405 HasLoopExit = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000406
Chandler Carruthb5797b62015-01-18 09:21:15 +0000407 // If we need to preserve LoopInfo, note whether any of the preds crosses
408 // an interesting loop boundary.
409 if (!L)
410 continue;
411 if (L->contains(Pred))
412 IsLoopEntry = false;
413 else
414 SplitMakesNewLoopHeader = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000415 }
416
Chandler Carruthb5797b62015-01-18 09:21:15 +0000417 // Unless we have a loop for OldBB, nothing else to do here.
418 if (!L)
419 return;
Bill Wendling0a693f42011-08-18 05:25:23 +0000420
421 if (IsLoopEntry) {
422 // Add the new block to the nearest enclosing loop (and not an adjacent
423 // loop). To find this, examine each of the predecessors and determine which
424 // loops enclose them, and select the most-nested loop which contains the
425 // loop containing the block being split.
Craig Topperf40110f2014-04-25 05:29:35 +0000426 Loop *InnermostPredLoop = nullptr;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000427 for (BasicBlock *Pred : Preds) {
Bill Wendlingec3823d2011-08-18 20:39:32 +0000428 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
Bill Wendling0a693f42011-08-18 05:25:23 +0000429 // Seek a loop which actually contains the block being split (to avoid
430 // adjacent loops).
431 while (PredLoop && !PredLoop->contains(OldBB))
432 PredLoop = PredLoop->getParentLoop();
433
434 // Select the most-nested of these loops which contains the block.
435 if (PredLoop && PredLoop->contains(OldBB) &&
436 (!InnermostPredLoop ||
437 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
438 InnermostPredLoop = PredLoop;
439 }
Bill Wendlingec3823d2011-08-18 20:39:32 +0000440 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000441
442 if (InnermostPredLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000443 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000444 } else {
Chandler Carruth691addc2015-01-18 01:25:51 +0000445 L->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000446 if (SplitMakesNewLoopHeader)
447 L->moveToHeader(NewBB);
448 }
449}
450
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000451/// Update the PHI nodes in OrigBB to include the values coming from NewBB.
452/// This also updates AliasAnalysis, if available.
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000453static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000454 ArrayRef<BasicBlock *> Preds, BranchInst *BI,
Chandler Carruth96ada252015-07-22 09:52:54 +0000455 bool HasLoopExit) {
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000456 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000457 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000458 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
459 PHINode *PN = cast<PHINode>(I++);
460
461 // Check to see if all of the values coming in are the same. If so, we
462 // don't need to create a new PHI node, unless it's needed for LCSSA.
Craig Topperf40110f2014-04-25 05:29:35 +0000463 Value *InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000464 if (!HasLoopExit) {
465 InVal = PN->getIncomingValueForBlock(Preds[0]);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000466 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
467 if (!PredSet.count(PN->getIncomingBlock(i)))
468 continue;
469 if (!InVal)
470 InVal = PN->getIncomingValue(i);
471 else if (InVal != PN->getIncomingValue(i)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000472 InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000473 break;
474 }
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000475 }
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000476 }
477
478 if (InVal) {
479 // If all incoming values for the new PHI would be the same, just don't
480 // make a new PHI. Instead, just remove the incoming values from the old
481 // PHI.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000482
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000483 // NOTE! This loop walks backwards for a reason! First off, this minimizes
484 // the cost of removal if we end up removing a large number of values, and
485 // second off, this ensures that the indices for the incoming values
486 // aren't invalidated when we remove one.
487 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
488 if (PredSet.count(PN->getIncomingBlock(i)))
489 PN->removeIncomingValue(i, false);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000490
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000491 // Add an incoming value to the PHI node in the loop for the preheader
492 // edge.
493 PN->addIncoming(InVal, NewBB);
494 continue;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000495 }
496
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000497 // If the values coming into the block are not the same, we need a new
498 // PHI.
499 // Create the new PHI node, insert it into NewBB at the end of the block
500 PHINode *NewPHI =
501 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000502
503 // NOTE! This loop walks backwards for a reason! First off, this minimizes
504 // the cost of removal if we end up removing a large number of values, and
505 // second off, this ensures that the indices for the incoming values aren't
506 // invalidated when we remove one.
507 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
508 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
509 if (PredSet.count(IncomingBB)) {
510 Value *V = PN->removeIncomingValue(i, false);
511 NewPHI->addIncoming(V, IncomingBB);
512 }
513 }
514
515 PN->addIncoming(NewPHI, NewBB);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000516 }
517}
518
Jakub Staszak190db2f2013-01-14 23:16:36 +0000519BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000520 ArrayRef<BasicBlock *> Preds,
Chandler Carruth96ada252015-07-22 09:52:54 +0000521 const char *Suffix, DominatorTree *DT,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000522 LoopInfo *LI, MemorySSAUpdater *MSSAU,
523 bool PreserveLCSSA) {
David Majnemer654e1302015-07-31 17:58:14 +0000524 // Do not attempt to split that which cannot be split.
525 if (!BB->canSplitPredecessors())
526 return nullptr;
527
Philip Reames9198b332015-01-28 23:06:47 +0000528 // For the landingpads we need to act a bit differently.
529 // Delegate this work to the SplitLandingPadPredecessors.
530 if (BB->isLandingPad()) {
531 SmallVector<BasicBlock*, 2> NewBBs;
532 std::string NewName = std::string(Suffix) + ".split-lp";
533
Chandler Carruth96ada252015-07-22 09:52:54 +0000534 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000535 LI, MSSAU, PreserveLCSSA);
Philip Reames9198b332015-01-28 23:06:47 +0000536 return NewBBs[0];
537 }
538
Chris Lattnera5b11702008-04-21 01:28:02 +0000539 // Create new basic block, insert right before the original block.
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000540 BasicBlock *NewBB = BasicBlock::Create(
541 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000542
Chris Lattnera5b11702008-04-21 01:28:02 +0000543 // The new block unconditionally branches to the old block.
544 BranchInst *BI = BranchInst::Create(BB, NewBB);
Taewook Oh2e945eb2017-02-14 21:10:40 +0000545 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000546
Chris Lattnera5b11702008-04-21 01:28:02 +0000547 // Move the edges from Preds to point to NewBB instead of BB.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000548 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Dan Gohman00c79382009-11-05 18:25:44 +0000549 // This is slightly more strict than necessary; the minimum requirement
550 // is that there be no more than one indirectbr branching to BB. And
551 // all BlockAddress uses would need to be updated.
552 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
553 "Cannot split an edge from an IndirectBrInst");
Craig Topper784929d2019-02-08 20:48:56 +0000554 assert(!isa<CallBrInst>(Preds[i]->getTerminator()) &&
555 "Cannot split an edge from a CallBrInst");
Chris Lattnera5b11702008-04-21 01:28:02 +0000556 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000557 }
558
Chris Lattnera5b11702008-04-21 01:28:02 +0000559 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
560 // node becomes an incoming value for BB's phi node. However, if the Preds
561 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
562 // account for the newly created predecessor.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000563 if (Preds.empty()) {
Chris Lattnera5b11702008-04-21 01:28:02 +0000564 // Insert dummy values as the incoming value.
565 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000566 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattnera5b11702008-04-21 01:28:02 +0000567 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000568
Bill Wendling0a693f42011-08-18 05:25:23 +0000569 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
570 bool HasLoopExit = false;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000571 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, MSSAU, PreserveLCSSA,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000572 HasLoopExit);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000573
Matt Arsenault06dfbb52018-01-31 22:54:37 +0000574 if (!Preds.empty()) {
575 // Update the PHI nodes in BB with the values coming from NewBB.
576 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
577 }
578
Chris Lattnera5b11702008-04-21 01:28:02 +0000579 return NewBB;
580}
Chris Lattner72f16e72008-11-27 08:10:05 +0000581
Bill Wendlingca7d3092011-08-19 00:05:40 +0000582void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000583 ArrayRef<BasicBlock *> Preds,
Bill Wendlingca7d3092011-08-19 00:05:40 +0000584 const char *Suffix1, const char *Suffix2,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000585 SmallVectorImpl<BasicBlock *> &NewBBs,
Chandler Carruth96ada252015-07-22 09:52:54 +0000586 DominatorTree *DT, LoopInfo *LI,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000587 MemorySSAUpdater *MSSAU,
Chandler Carruth96ada252015-07-22 09:52:54 +0000588 bool PreserveLCSSA) {
Bill Wendlingca7d3092011-08-19 00:05:40 +0000589 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
590
591 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
592 // it right before the original block.
593 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
594 OrigBB->getName() + Suffix1,
595 OrigBB->getParent(), OrigBB);
596 NewBBs.push_back(NewBB1);
597
598 // The new block unconditionally branches to the old block.
599 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000600 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendlingca7d3092011-08-19 00:05:40 +0000601
602 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
603 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
604 // This is slightly more strict than necessary; the minimum requirement
605 // is that there be no more than one indirectbr branching to BB. And
606 // all BlockAddress uses would need to be updated.
607 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
608 "Cannot split an edge from an IndirectBrInst");
609 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
610 }
611
Bill Wendlingca7d3092011-08-19 00:05:40 +0000612 bool HasLoopExit = false;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000613 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, MSSAU, PreserveLCSSA,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000614 HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000615
616 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
Chandler Carruth96ada252015-07-22 09:52:54 +0000617 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000618
Bill Wendlingca7d3092011-08-19 00:05:40 +0000619 // Move the remaining edges from OrigBB to point to NewBB2.
620 SmallVector<BasicBlock*, 8> NewBB2Preds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000621 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
622 i != e; ) {
623 BasicBlock *Pred = *i++;
Bill Wendling38d81302011-08-19 23:46:30 +0000624 if (Pred == NewBB1) continue;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000625 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
626 "Cannot split an edge from an IndirectBrInst");
Bill Wendlingca7d3092011-08-19 00:05:40 +0000627 NewBB2Preds.push_back(Pred);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000628 e = pred_end(OrigBB);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000629 }
630
Craig Topperf40110f2014-04-25 05:29:35 +0000631 BasicBlock *NewBB2 = nullptr;
Bill Wendling38d81302011-08-19 23:46:30 +0000632 if (!NewBB2Preds.empty()) {
633 // Create another basic block for the rest of OrigBB's predecessors.
634 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
635 OrigBB->getName() + Suffix2,
636 OrigBB->getParent(), OrigBB);
637 NewBBs.push_back(NewBB2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000638
Bill Wendling38d81302011-08-19 23:46:30 +0000639 // The new block unconditionally branches to the old block.
640 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000641 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendling38d81302011-08-19 23:46:30 +0000642
643 // Move the remaining edges from OrigBB to point to NewBB2.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000644 for (BasicBlock *NewBB2Pred : NewBB2Preds)
645 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
Bill Wendling38d81302011-08-19 23:46:30 +0000646
647 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
648 HasLoopExit = false;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000649 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI, MSSAU,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000650 PreserveLCSSA, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000651
652 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
Chandler Carruth96ada252015-07-22 09:52:54 +0000653 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000654 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000655
656 LandingPadInst *LPad = OrigBB->getLandingPadInst();
657 Instruction *Clone1 = LPad->clone();
658 Clone1->setName(Twine("lpad") + Suffix1);
659 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
660
Bill Wendling38d81302011-08-19 23:46:30 +0000661 if (NewBB2) {
662 Instruction *Clone2 = LPad->clone();
663 Clone2->setName(Twine("lpad") + Suffix2);
664 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000665
Chen Li78bde832016-01-06 20:32:05 +0000666 // Create a PHI node for the two cloned landingpad instructions only
667 // if the original landingpad instruction has some uses.
668 if (!LPad->use_empty()) {
669 assert(!LPad->getType()->isTokenTy() &&
670 "Split cannot be applied if LPad is token type. Otherwise an "
671 "invalid PHINode of token type would be created.");
672 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
673 PN->addIncoming(Clone1, NewBB1);
674 PN->addIncoming(Clone2, NewBB2);
675 LPad->replaceAllUsesWith(PN);
676 }
Bill Wendling38d81302011-08-19 23:46:30 +0000677 LPad->eraseFromParent();
678 } else {
679 // There is no second clone. Just replace the landing pad with the first
680 // clone.
681 LPad->replaceAllUsesWith(Clone1);
682 LPad->eraseFromParent();
683 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000684}
685
Evan Chengd983eba2011-01-29 04:46:23 +0000686ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
Chijun Sima8b5de482018-08-04 08:13:47 +0000687 BasicBlock *Pred,
688 DomTreeUpdater *DTU) {
Evan Chengd983eba2011-01-29 04:46:23 +0000689 Instruction *UncondBranch = Pred->getTerminator();
690 // Clone the return and add it to the end of the predecessor.
691 Instruction *NewRet = RI->clone();
692 Pred->getInstList().push_back(NewRet);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000693
Evan Chengd983eba2011-01-29 04:46:23 +0000694 // If the return instruction returns a value, and if the value was a
695 // PHI node in "BB", propagate the right value into the return.
696 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
Evan Cheng249716e2012-07-27 21:21:26 +0000697 i != e; ++i) {
698 Value *V = *i;
Craig Topperf40110f2014-04-25 05:29:35 +0000699 Instruction *NewBC = nullptr;
Evan Cheng249716e2012-07-27 21:21:26 +0000700 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
701 // Return value might be bitcasted. Clone and insert it before the
702 // return instruction.
703 V = BCI->getOperand(0);
704 NewBC = BCI->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000705 Pred->getInstList().insert(NewRet->getIterator(), NewBC);
Evan Cheng249716e2012-07-27 21:21:26 +0000706 *i = NewBC;
707 }
708 if (PHINode *PN = dyn_cast<PHINode>(V)) {
709 if (PN->getParent() == BB) {
710 if (NewBC)
711 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
712 else
713 *i = PN->getIncomingValueForBlock(Pred);
714 }
715 }
716 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000717
Evan Chengd983eba2011-01-29 04:46:23 +0000718 // Update any PHI nodes in the returning block to realize that we no
719 // longer branch to them.
720 BB->removePredecessor(Pred);
721 UncondBranch->eraseFromParent();
Chijun Sima8b5de482018-08-04 08:13:47 +0000722
723 if (DTU)
Chijun Simaf131d612019-02-22 05:41:43 +0000724 DTU->applyUpdates({{DominatorTree::Delete, Pred, BB}});
Chijun Sima8b5de482018-08-04 08:13:47 +0000725
Evan Chengd983eba2011-01-29 04:46:23 +0000726 return cast<ReturnInst>(NewRet);
Chris Lattner351134b2009-05-04 02:25:58 +0000727}
Devang Patela8e74112011-04-29 22:28:59 +0000728
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000729Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
730 Instruction *SplitBefore,
731 bool Unreachable,
732 MDNode *BranchWeights,
Max Kazantsev73db5c12019-02-15 08:18:00 +0000733 DominatorTree *DT, LoopInfo *LI,
734 BasicBlock *ThenBlock) {
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000735 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000736 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000737 Instruction *HeadOldTerm = Head->getTerminator();
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000738 LLVMContext &C = Head->getContext();
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000739 Instruction *CheckTerm;
Max Kazantsev73db5c12019-02-15 08:18:00 +0000740 bool CreateThenBlock = (ThenBlock == nullptr);
741 if (CreateThenBlock) {
742 ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
743 if (Unreachable)
744 CheckTerm = new UnreachableInst(C, ThenBlock);
745 else
746 CheckTerm = BranchInst::Create(Tail, ThenBlock);
747 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
748 } else
749 CheckTerm = ThenBlock->getTerminator();
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000750 BranchInst *HeadNewTerm =
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000751 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000752 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
753 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000754
755 if (DT) {
756 if (DomTreeNode *OldNode = DT->getNode(Head)) {
757 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
758
759 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000760 for (DomTreeNode *Child : Children)
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000761 DT->changeImmediateDominator(Child, NewNode);
762
763 // Head dominates ThenBlock.
Max Kazantsev73db5c12019-02-15 08:18:00 +0000764 if (CreateThenBlock)
765 DT->addNewBlock(ThenBlock, Head);
766 else
767 DT->changeImmediateDominator(ThenBlock, Head);
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000768 }
769 }
770
Adam Nemetfdb20592016-03-15 18:06:20 +0000771 if (LI) {
Michael Kruse811de8a2017-03-06 15:33:05 +0000772 if (Loop *L = LI->getLoopFor(Head)) {
773 L->addBasicBlockToLoop(ThenBlock, *LI);
774 L->addBasicBlockToLoop(Tail, *LI);
775 }
Adam Nemetfdb20592016-03-15 18:06:20 +0000776 }
777
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000778 return CheckTerm;
779}
Tom Stellardaa664d92013-08-06 02:43:45 +0000780
Kostya Serebryany530e2072013-12-23 14:15:08 +0000781void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000782 Instruction **ThenTerm,
783 Instruction **ElseTerm,
Kostya Serebryany530e2072013-12-23 14:15:08 +0000784 MDNode *BranchWeights) {
785 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000786 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000787 Instruction *HeadOldTerm = Head->getTerminator();
Kostya Serebryany530e2072013-12-23 14:15:08 +0000788 LLVMContext &C = Head->getContext();
789 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
790 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
791 *ThenTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000792 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000793 *ElseTerm = BranchInst::Create(Tail, ElseBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000794 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000795 BranchInst *HeadNewTerm =
796 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
797 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
798 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
799}
800
Tom Stellardaa664d92013-08-06 02:43:45 +0000801Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
802 BasicBlock *&IfFalse) {
803 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +0000804 BasicBlock *Pred1 = nullptr;
805 BasicBlock *Pred2 = nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000806
807 if (SomePHI) {
808 if (SomePHI->getNumIncomingValues() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +0000809 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000810 Pred1 = SomePHI->getIncomingBlock(0);
811 Pred2 = SomePHI->getIncomingBlock(1);
812 } else {
813 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
814 if (PI == PE) // No predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000815 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000816 Pred1 = *PI++;
817 if (PI == PE) // Only one predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000818 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000819 Pred2 = *PI++;
820 if (PI != PE) // More than two predecessors
Craig Topperf40110f2014-04-25 05:29:35 +0000821 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000822 }
823
824 // We can only handle branches. Other control flow will be lowered to
825 // branches if possible anyway.
826 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
827 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000828 if (!Pred1Br || !Pred2Br)
829 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000830
831 // Eliminate code duplication by ensuring that Pred1Br is conditional if
832 // either are.
833 if (Pred2Br->isConditional()) {
834 // If both branches are conditional, we don't have an "if statement". In
835 // reality, we could transform this case, but since the condition will be
836 // required anyway, we stand no chance of eliminating it, so the xform is
837 // probably not profitable.
838 if (Pred1Br->isConditional())
Craig Topperf40110f2014-04-25 05:29:35 +0000839 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000840
841 std::swap(Pred1, Pred2);
842 std::swap(Pred1Br, Pred2Br);
843 }
844
845 if (Pred1Br->isConditional()) {
846 // The only thing we have to watch out for here is to make sure that Pred2
847 // doesn't have incoming edges from other blocks. If it does, the condition
848 // doesn't dominate BB.
Craig Topperf40110f2014-04-25 05:29:35 +0000849 if (!Pred2->getSinglePredecessor())
850 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000851
852 // If we found a conditional branch predecessor, make sure that it branches
853 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
854 if (Pred1Br->getSuccessor(0) == BB &&
855 Pred1Br->getSuccessor(1) == Pred2) {
856 IfTrue = Pred1;
857 IfFalse = Pred2;
858 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
859 Pred1Br->getSuccessor(1) == BB) {
860 IfTrue = Pred2;
861 IfFalse = Pred1;
862 } else {
863 // We know that one arm of the conditional goes to BB, so the other must
864 // go somewhere unrelated, and this must not be an "if statement".
Craig Topperf40110f2014-04-25 05:29:35 +0000865 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000866 }
867
868 return Pred1Br->getCondition();
869 }
870
871 // Ok, if we got here, both predecessors end with an unconditional branch to
872 // BB. Don't panic! If both blocks only have a single (identical)
873 // predecessor, and THAT is a conditional branch, then we're all ok!
874 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +0000875 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
876 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000877
878 // Otherwise, if this is a conditional branch, then we can use it!
879 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000880 if (!BI) return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000881
882 assert(BI->isConditional() && "Two successors but not conditional?");
883 if (BI->getSuccessor(0) == Pred1) {
884 IfTrue = Pred1;
885 IfFalse = Pred2;
886 } else {
887 IfTrue = Pred2;
888 IfFalse = Pred1;
889 }
890 return BI->getCondition();
891}