blob: 41ad4fefe1f38d34d963160a76538564f881ea74 [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,
52 SmallVectorImpl<DominatorTree::UpdateType> *Updates) {
Max Kazantsev1f733102019-01-14 10:26:26 +000053 for (auto *BB : BBs) {
54 // Loop through all of our successors and make sure they know that one
55 // of their predecessors is going away.
Max Kazantsev36b392c2019-02-06 07:56:36 +000056 SmallPtrSet<BasicBlock *, 4> UniqueSuccessors;
Max Kazantsev1f733102019-01-14 10:26:26 +000057 for (BasicBlock *Succ : successors(BB)) {
58 Succ->removePredecessor(BB);
Max Kazantsev36b392c2019-02-06 07:56:36 +000059 if (Updates && UniqueSuccessors.insert(Succ).second)
60 Updates->push_back({DominatorTree::Delete, BB, Succ});
Max Kazantsev1f733102019-01-14 10:26:26 +000061 }
62
63 // Zap all the instructions in the block.
64 while (!BB->empty()) {
65 Instruction &I = BB->back();
66 // If this instruction is used, replace uses with an arbitrary value.
67 // Because control flow can't get here, we don't care what we replace the
68 // value with. Note that since this block is unreachable, and all values
69 // contained within it must dominate their uses, that all uses will
70 // eventually be removed (they are themselves dead).
71 if (!I.use_empty())
72 I.replaceAllUsesWith(UndefValue::get(I.getType()));
73 BB->getInstList().pop_back();
74 }
75 new UnreachableInst(BB->getContext(), BB);
76 assert(BB->getInstList().size() == 1 &&
77 isa<UnreachableInst>(BB->getTerminator()) &&
78 "The successor list of BB isn't empty before "
79 "applying corresponding DTU updates.");
80 }
Max Kazantsev36b392c2019-02-06 07:56:36 +000081}
82
83void llvm::DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU) {
84 DeleteDeadBlocks({BB}, DTU);
85}
86
87void llvm::DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs,
88 DomTreeUpdater *DTU) {
89#ifndef NDEBUG
90 // Make sure that all predecessors of each dead block is also dead.
91 SmallPtrSet<BasicBlock *, 4> Dead(BBs.begin(), BBs.end());
92 assert(Dead.size() == BBs.size() && "Duplicating blocks?");
93 for (auto *BB : Dead)
94 for (BasicBlock *Pred : predecessors(BB))
95 assert(Dead.count(Pred) && "All predecessors must be dead!");
96#endif
97
98 SmallVector<DominatorTree::UpdateType, 4> Updates;
99 DetatchDeadBlocks(BBs, DTU ? &Updates : nullptr);
100
Chijun Sima21a8b602018-08-03 05:08:17 +0000101 if (DTU)
Chijun Sima21a8b602018-08-03 05:08:17 +0000102 DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
Max Kazantsev1f733102019-01-14 10:26:26 +0000103
104 for (BasicBlock *BB : BBs)
105 if (DTU)
106 DTU->deleteBB(BB);
107 else
108 BB->eraseFromParent();
Chris Lattnerbcc904a2008-12-03 06:37:44 +0000109}
110
Chandler Carruth96ada252015-07-22 09:52:54 +0000111void llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
Chandler Carruth61440d22016-03-10 00:55:30 +0000112 MemoryDependenceResults *MemDep) {
Chris Lattnerf6ae9042011-01-11 08:13:40 +0000113 if (!isa<PHINode>(BB->begin())) return;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000114
Chris Lattnerdc3f6f22008-12-03 19:44:02 +0000115 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
116 if (PN->getIncomingValue(0) != PN)
117 PN->replaceAllUsesWith(PN->getIncomingValue(0));
118 else
Owen Andersonb292b8c2009-07-30 23:03:37 +0000119 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Jakub Staszak190db2f2013-01-14 23:16:36 +0000120
Chris Lattnerf6ae9042011-01-11 08:13:40 +0000121 if (MemDep)
122 MemDep->removeInstruction(PN); // Memdep updates AA itself.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000123
Chris Lattnerdc3f6f22008-12-03 19:44:02 +0000124 PN->eraseFromParent();
125 }
126}
127
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000128bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
Dan Gohmanff089952009-05-02 18:29:22 +0000129 // Recursively deleting a PHI may cause multiple PHIs to be deleted
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000130 // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
131 SmallVector<WeakTrackingVH, 8> PHIs;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000132 for (PHINode &PN : BB->phis())
133 PHIs.push_back(&PN);
Dan Gohmanff089952009-05-02 18:29:22 +0000134
Dan Gohmancb99fe92010-01-05 15:45:31 +0000135 bool Changed = false;
Dan Gohmanff089952009-05-02 18:29:22 +0000136 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
137 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000138 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
Dan Gohmancb99fe92010-01-05 15:45:31 +0000139
140 return Changed;
Dan Gohmanff089952009-05-02 18:29:22 +0000141}
142
Chijun Sima21a8b602018-08-03 05:08:17 +0000143bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000144 LoopInfo *LI, MemorySSAUpdater *MSSAU,
Chijun Sima21a8b602018-08-03 05:08:17 +0000145 MemoryDependenceResults *MemDep) {
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000146 if (BB->hasAddressTaken())
147 return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000148
Dan Gohman941020e2010-08-17 17:07:02 +0000149 // Can't merge if there are multiple predecessors, or no predecessors.
150 BasicBlock *PredBB = BB->getUniquePredecessor();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000151 if (!PredBB) return false;
Dan Gohman941020e2010-08-17 17:07:02 +0000152
Dan Gohman2d02ff82009-10-31 17:33:01 +0000153 // Don't break self-loops.
154 if (PredBB == BB) return false;
David Majnemer654e1302015-07-31 17:58:14 +0000155 // Don't break unwinding instructions.
Chandler Carruth698fbe72018-08-26 08:56:42 +0000156 if (PredBB->getTerminator()->isExceptionalTerminator())
David Majnemer654e1302015-07-31 17:58:14 +0000157 return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000158
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000159 // Can't merge if there are multiple distinct successors.
160 if (PredBB->getUniqueSuccessor() != BB)
161 return false;
Devang Patel0f7a3502008-09-09 01:06:56 +0000162
Dan Gohman2d02ff82009-10-31 17:33:01 +0000163 // Can't merge if there is PHI loop.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000164 for (PHINode &PN : BB->phis())
165 for (Value *IncValue : PN.incoming_values())
166 if (IncValue == &PN)
167 return false;
Dan Gohman2d02ff82009-10-31 17:33:01 +0000168
169 // Begin by getting rid of unneeded PHIs.
Davide Italiano48283ba2018-05-08 23:28:15 +0000170 SmallVector<AssertingVH<Value>, 4> IncomingValues;
Adrian Prantld60f34c2017-11-01 20:43:30 +0000171 if (isa<PHINode>(BB->front())) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000172 for (PHINode &PN : BB->phis())
Davide Italiano48283ba2018-05-08 23:28:15 +0000173 if (!isa<PHINode>(PN.getIncomingValue(0)) ||
174 cast<PHINode>(PN.getIncomingValue(0))->getParent() != BB)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000175 IncomingValues.push_back(PN.getIncomingValue(0));
Chandler Carruth96ada252015-07-22 09:52:54 +0000176 FoldSingleEntryPHINodes(BB, MemDep);
Adrian Prantld60f34c2017-11-01 20:43:30 +0000177 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000178
Chijun Sima21a8b602018-08-03 05:08:17 +0000179 // DTU update: Collect all the edges that exit BB.
180 // These dominator edges will be redirected from Pred.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000181 std::vector<DominatorTree::UpdateType> Updates;
Chijun Sima21a8b602018-08-03 05:08:17 +0000182 if (DTU) {
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000183 Updates.reserve(1 + (2 * succ_size(BB)));
184 Updates.push_back({DominatorTree::Delete, PredBB, BB});
185 for (auto I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
186 Updates.push_back({DominatorTree::Delete, BB, *I});
187 Updates.push_back({DominatorTree::Insert, PredBB, *I});
188 }
189 }
190
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000191 if (MSSAU)
192 MSSAU->moveAllAfterMergeBlocks(BB, PredBB, &*(BB->begin()));
193
Owen Andersonc0623812008-07-17 00:01:40 +0000194 // Delete the unconditional branch from the predecessor...
195 PredBB->getInstList().pop_back();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000196
Owen Andersonc0623812008-07-17 00:01:40 +0000197 // Make all PHI nodes that referred to BB now refer to Pred as their
198 // source...
199 BB->replaceAllUsesWith(PredBB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000200
Jay Foad61ea0e42011-06-23 09:09:15 +0000201 // Move all definitions in the successor to the predecessor...
202 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
Chijun Sima21a8b602018-08-03 05:08:17 +0000203 new UnreachableInst(BB->getContext(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000204
Adrian Prantld60f34c2017-11-01 20:43:30 +0000205 // Eliminate duplicate dbg.values describing the entry PHI node post-splice.
Davide Italiano48283ba2018-05-08 23:28:15 +0000206 for (auto Incoming : IncomingValues) {
207 if (isa<Instruction>(*Incoming)) {
Adrian Prantld60f34c2017-11-01 20:43:30 +0000208 SmallVector<DbgValueInst *, 2> DbgValues;
209 SmallDenseSet<std::pair<DILocalVariable *, DIExpression *>, 2>
210 DbgValueSet;
211 llvm::findDbgValues(DbgValues, Incoming);
212 for (auto &DVI : DbgValues) {
213 auto R = DbgValueSet.insert({DVI->getVariable(), DVI->getExpression()});
214 if (!R.second)
215 DVI->eraseFromParent();
216 }
217 }
218 }
219
Dan Gohman2d02ff82009-10-31 17:33:01 +0000220 // Inherit predecessors name if it exists.
Owen Anderson27405ef2008-07-17 19:42:29 +0000221 if (!PredBB->hasName())
222 PredBB->takeName(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000223
Chandler Carruthb5c11532015-01-18 02:11:23 +0000224 if (LI)
225 LI->removeBlock(BB);
226
227 if (MemDep)
228 MemDep->invalidateCachedPredecessors();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000229
Chijun Sima21a8b602018-08-03 05:08:17 +0000230 // Finally, erase the old block and update dominator info.
231 if (DTU) {
232 assert(BB->getInstList().size() == 1 &&
233 isa<UnreachableInst>(BB->getTerminator()) &&
234 "The successor list of BB isn't empty before "
235 "applying corresponding DTU updates.");
236 DTU->applyUpdates(Updates, /*ForceRemoveDuplicates*/ true);
237 DTU->deleteBB(BB);
238 }
239
240 else {
241 BB->eraseFromParent(); // Nuke BB if DTU is nullptr.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000242 }
Dan Gohman2d02ff82009-10-31 17:33:01 +0000243 return true;
Owen Andersonc0623812008-07-17 00:01:40 +0000244}
245
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000246void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
247 BasicBlock::iterator &BI, Value *V) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000248 Instruction &I = *BI;
Chris Lattner28537df2002-05-07 18:07:59 +0000249 // Replaces all of the uses of the instruction with uses of the value
Chris Lattnerfda72b12002-06-25 16:12:52 +0000250 I.replaceAllUsesWith(V);
Chris Lattner28537df2002-05-07 18:07:59 +0000251
Chris Lattner8dd4cae2007-02-11 01:37:51 +0000252 // Make sure to propagate a name if there is one already.
253 if (I.hasName() && !V->hasName())
254 V->takeName(&I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000255
Misha Brukman7eb05a12003-08-18 14:43:39 +0000256 // Delete the unnecessary instruction now...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000257 BI = BIL.erase(BI);
Chris Lattner28537df2002-05-07 18:07:59 +0000258}
259
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000260void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
261 BasicBlock::iterator &BI, Instruction *I) {
Craig Toppere73658d2014-04-28 04:05:08 +0000262 assert(I->getParent() == nullptr &&
Chris Lattner28537df2002-05-07 18:07:59 +0000263 "ReplaceInstWithInst: Instruction already inserted into basic block!");
264
Alexey Samsonov19ffcb92015-06-23 21:00:08 +0000265 // Copy debug location to newly added instruction, if it wasn't already set
266 // by the caller.
267 if (!I->getDebugLoc())
268 I->setDebugLoc(BI->getDebugLoc());
269
Chris Lattner28537df2002-05-07 18:07:59 +0000270 // Insert the new instruction into the basic block...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000271 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner28537df2002-05-07 18:07:59 +0000272
273 // Replace all uses of the old instruction, and delete it.
274 ReplaceInstWithValue(BIL, BI, I);
275
276 // Move BI back to point to the newly inserted instruction
Chris Lattnerfda72b12002-06-25 16:12:52 +0000277 BI = New;
Chris Lattner28537df2002-05-07 18:07:59 +0000278}
279
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000280void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000281 BasicBlock::iterator BI(From);
282 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner28537df2002-05-07 18:07:59 +0000283}
Chris Lattnerb17274e2002-07-29 22:32:08 +0000284
Chandler Carruthd4500562015-01-19 12:36:53 +0000285BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000286 LoopInfo *LI, MemorySSAUpdater *MSSAU) {
Bob Wilsonaff96b22010-02-16 21:06:42 +0000287 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000288
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000289 // If this is a critical edge, let SplitCriticalEdge do it.
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000290 Instruction *LatchTerm = BB->getTerminator();
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000291 if (SplitCriticalEdge(
292 LatchTerm, SuccNum,
293 CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA()))
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000294 return LatchTerm->getSuccessor(SuccNum);
Chandler Carruth32c52c72015-01-18 02:39:37 +0000295
Devang Pateld7767cc2007-07-06 21:39:20 +0000296 // If the edge isn't critical, then BB has a single successor or Succ has a
297 // single pred. Split the block.
Devang Pateld7767cc2007-07-06 21:39:20 +0000298 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
299 // If the successor only has a single pred, split the top of the successor
300 // block.
301 assert(SP == BB && "CFG broken");
Craig Topperf40110f2014-04-25 05:29:35 +0000302 SP = nullptr;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000303 return SplitBlock(Succ, &Succ->front(), DT, LI, MSSAU);
Devang Pateld7767cc2007-07-06 21:39:20 +0000304 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000305
Chris Lattner30d95f92011-01-08 18:47:43 +0000306 // Otherwise, if BB has a single successor, split it at the bottom of the
307 // block.
308 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
Jakub Staszak190db2f2013-01-14 23:16:36 +0000309 "Should have a single succ!");
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000310 return SplitBlock(BB, BB->getTerminator(), DT, LI, MSSAU);
Devang Pateld7767cc2007-07-06 21:39:20 +0000311}
312
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000313unsigned
314llvm::SplitAllCriticalEdges(Function &F,
315 const CriticalEdgeSplittingOptions &Options) {
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000316 unsigned NumBroken = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000317 for (BasicBlock &BB : F) {
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000318 Instruction *TI = BB.getTerminator();
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000319 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
320 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000321 if (SplitCriticalEdge(TI, i, Options))
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000322 ++NumBroken;
323 }
324 return NumBroken;
325}
326
Chandler Carruth32c52c72015-01-18 02:39:37 +0000327BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000328 DominatorTree *DT, LoopInfo *LI,
329 MemorySSAUpdater *MSSAU) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000330 BasicBlock::iterator SplitIt = SplitPt->getIterator();
David Majnemer654e1302015-07-31 17:58:14 +0000331 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
Devang Pateld7767cc2007-07-06 21:39:20 +0000332 ++SplitIt;
333 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
334
Dan Gohman3ddbc242009-09-08 15:45:00 +0000335 // The new block lives in whichever loop the old one did. This preserves
336 // LCSSA as well, because we force the split point to be after any PHI nodes.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000337 if (LI)
338 if (Loop *L = LI->getLoopFor(Old))
339 L->addBasicBlockToLoop(New, *LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000340
Chandler Carruth32c52c72015-01-18 02:39:37 +0000341 if (DT)
Gabor Greif2f5f6962010-09-10 22:25:58 +0000342 // Old dominates New. New node dominates all other nodes dominated by Old.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000343 if (DomTreeNode *OldNode = DT->getNode(Old)) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000344 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
Devang Patel186e0d82007-07-19 02:29:24 +0000345
Chandler Carruth32c52c72015-01-18 02:39:37 +0000346 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000347 for (DomTreeNode *I : Children)
348 DT->changeImmediateDominator(I, NewNode);
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000349 }
Devang Pateld7767cc2007-07-06 21:39:20 +0000350
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000351 // Move MemoryAccesses still tracked in Old, but part of New now.
352 // Update accesses in successor blocks accordingly.
353 if (MSSAU)
354 MSSAU->moveAllAfterSpliceBlocks(Old, New, &*(New->begin()));
355
Devang Pateld7767cc2007-07-06 21:39:20 +0000356 return New;
357}
Chris Lattnera5b11702008-04-21 01:28:02 +0000358
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000359/// Update DominatorTree, LoopInfo, and LCCSA analysis information.
Bill Wendling60291352011-08-18 17:57:57 +0000360static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
Bill Wendlingec3823d2011-08-18 20:39:32 +0000361 ArrayRef<BasicBlock *> Preds,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000362 DominatorTree *DT, LoopInfo *LI,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000363 MemorySSAUpdater *MSSAU,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000364 bool PreserveLCSSA, bool &HasLoopExit) {
365 // Update dominator tree if available.
Matt Arsenault06dfbb52018-01-31 22:54:37 +0000366 if (DT) {
367 if (OldBB == DT->getRootNode()->getBlock()) {
368 assert(NewBB == &NewBB->getParent()->getEntryBlock());
369 DT->setNewRoot(NewBB);
370 } else {
371 // Split block expects NewBB to have a non-empty set of predecessors.
372 DT->splitBlock(NewBB);
373 }
374 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000375
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000376 // Update MemoryPhis after split if MemorySSA is available
377 if (MSSAU)
378 MSSAU->wireOldPredecessorsToNewImmediatePredecessor(OldBB, NewBB, Preds);
379
Chandler Carruthb5797b62015-01-18 09:21:15 +0000380 // The rest of the logic is only relevant for updating the loop structures.
381 if (!LI)
382 return;
383
Anna Thomas9fca5832018-01-04 17:21:15 +0000384 assert(DT && "DT should be available to update LoopInfo!");
Chandler Carruthb5797b62015-01-18 09:21:15 +0000385 Loop *L = LI->getLoopFor(OldBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000386
387 // If we need to preserve loop analyses, collect some information about how
388 // this split will affect loops.
389 bool IsLoopEntry = !!L;
390 bool SplitMakesNewLoopHeader = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000391 for (BasicBlock *Pred : Preds) {
Anna Thomasbdb94302018-01-02 16:25:50 +0000392 // Preds that are not reachable from entry should not be used to identify if
393 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
394 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
395 // as true and make the NewBB the header of some loop. This breaks LI.
396 if (!DT->isReachableFromEntry(Pred))
397 continue;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000398 // If we need to preserve LCSSA, determine if any of the preds is a loop
399 // exit.
400 if (PreserveLCSSA)
401 if (Loop *PL = LI->getLoopFor(Pred))
402 if (!PL->contains(OldBB))
403 HasLoopExit = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000404
Chandler Carruthb5797b62015-01-18 09:21:15 +0000405 // If we need to preserve LoopInfo, note whether any of the preds crosses
406 // an interesting loop boundary.
407 if (!L)
408 continue;
409 if (L->contains(Pred))
410 IsLoopEntry = false;
411 else
412 SplitMakesNewLoopHeader = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000413 }
414
Chandler Carruthb5797b62015-01-18 09:21:15 +0000415 // Unless we have a loop for OldBB, nothing else to do here.
416 if (!L)
417 return;
Bill Wendling0a693f42011-08-18 05:25:23 +0000418
419 if (IsLoopEntry) {
420 // Add the new block to the nearest enclosing loop (and not an adjacent
421 // loop). To find this, examine each of the predecessors and determine which
422 // loops enclose them, and select the most-nested loop which contains the
423 // loop containing the block being split.
Craig Topperf40110f2014-04-25 05:29:35 +0000424 Loop *InnermostPredLoop = nullptr;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000425 for (BasicBlock *Pred : Preds) {
Bill Wendlingec3823d2011-08-18 20:39:32 +0000426 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
Bill Wendling0a693f42011-08-18 05:25:23 +0000427 // Seek a loop which actually contains the block being split (to avoid
428 // adjacent loops).
429 while (PredLoop && !PredLoop->contains(OldBB))
430 PredLoop = PredLoop->getParentLoop();
431
432 // Select the most-nested of these loops which contains the block.
433 if (PredLoop && PredLoop->contains(OldBB) &&
434 (!InnermostPredLoop ||
435 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
436 InnermostPredLoop = PredLoop;
437 }
Bill Wendlingec3823d2011-08-18 20:39:32 +0000438 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000439
440 if (InnermostPredLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000441 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000442 } else {
Chandler Carruth691addc2015-01-18 01:25:51 +0000443 L->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000444 if (SplitMakesNewLoopHeader)
445 L->moveToHeader(NewBB);
446 }
447}
448
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000449/// Update the PHI nodes in OrigBB to include the values coming from NewBB.
450/// This also updates AliasAnalysis, if available.
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000451static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000452 ArrayRef<BasicBlock *> Preds, BranchInst *BI,
Chandler Carruth96ada252015-07-22 09:52:54 +0000453 bool HasLoopExit) {
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000454 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000455 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000456 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
457 PHINode *PN = cast<PHINode>(I++);
458
459 // Check to see if all of the values coming in are the same. If so, we
460 // don't need to create a new PHI node, unless it's needed for LCSSA.
Craig Topperf40110f2014-04-25 05:29:35 +0000461 Value *InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000462 if (!HasLoopExit) {
463 InVal = PN->getIncomingValueForBlock(Preds[0]);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000464 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
465 if (!PredSet.count(PN->getIncomingBlock(i)))
466 continue;
467 if (!InVal)
468 InVal = PN->getIncomingValue(i);
469 else if (InVal != PN->getIncomingValue(i)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000470 InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000471 break;
472 }
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000473 }
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000474 }
475
476 if (InVal) {
477 // If all incoming values for the new PHI would be the same, just don't
478 // make a new PHI. Instead, just remove the incoming values from the old
479 // PHI.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000480
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000481 // NOTE! This loop walks backwards for a reason! First off, this minimizes
482 // the cost of removal if we end up removing a large number of values, and
483 // second off, this ensures that the indices for the incoming values
484 // aren't invalidated when we remove one.
485 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
486 if (PredSet.count(PN->getIncomingBlock(i)))
487 PN->removeIncomingValue(i, false);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000488
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000489 // Add an incoming value to the PHI node in the loop for the preheader
490 // edge.
491 PN->addIncoming(InVal, NewBB);
492 continue;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000493 }
494
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000495 // If the values coming into the block are not the same, we need a new
496 // PHI.
497 // Create the new PHI node, insert it into NewBB at the end of the block
498 PHINode *NewPHI =
499 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000500
501 // NOTE! This loop walks backwards for a reason! First off, this minimizes
502 // the cost of removal if we end up removing a large number of values, and
503 // second off, this ensures that the indices for the incoming values aren't
504 // invalidated when we remove one.
505 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
506 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
507 if (PredSet.count(IncomingBB)) {
508 Value *V = PN->removeIncomingValue(i, false);
509 NewPHI->addIncoming(V, IncomingBB);
510 }
511 }
512
513 PN->addIncoming(NewPHI, NewBB);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000514 }
515}
516
Jakub Staszak190db2f2013-01-14 23:16:36 +0000517BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000518 ArrayRef<BasicBlock *> Preds,
Chandler Carruth96ada252015-07-22 09:52:54 +0000519 const char *Suffix, DominatorTree *DT,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000520 LoopInfo *LI, MemorySSAUpdater *MSSAU,
521 bool PreserveLCSSA) {
David Majnemer654e1302015-07-31 17:58:14 +0000522 // Do not attempt to split that which cannot be split.
523 if (!BB->canSplitPredecessors())
524 return nullptr;
525
Philip Reames9198b332015-01-28 23:06:47 +0000526 // For the landingpads we need to act a bit differently.
527 // Delegate this work to the SplitLandingPadPredecessors.
528 if (BB->isLandingPad()) {
529 SmallVector<BasicBlock*, 2> NewBBs;
530 std::string NewName = std::string(Suffix) + ".split-lp";
531
Chandler Carruth96ada252015-07-22 09:52:54 +0000532 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000533 LI, MSSAU, PreserveLCSSA);
Philip Reames9198b332015-01-28 23:06:47 +0000534 return NewBBs[0];
535 }
536
Chris Lattnera5b11702008-04-21 01:28:02 +0000537 // Create new basic block, insert right before the original block.
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000538 BasicBlock *NewBB = BasicBlock::Create(
539 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000540
Chris Lattnera5b11702008-04-21 01:28:02 +0000541 // The new block unconditionally branches to the old block.
542 BranchInst *BI = BranchInst::Create(BB, NewBB);
Taewook Oh2e945eb2017-02-14 21:10:40 +0000543 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000544
Chris Lattnera5b11702008-04-21 01:28:02 +0000545 // Move the edges from Preds to point to NewBB instead of BB.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000546 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Dan Gohman00c79382009-11-05 18:25:44 +0000547 // This is slightly more strict than necessary; the minimum requirement
548 // is that there be no more than one indirectbr branching to BB. And
549 // all BlockAddress uses would need to be updated.
550 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
551 "Cannot split an edge from an IndirectBrInst");
Chris Lattnera5b11702008-04-21 01:28:02 +0000552 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000553 }
554
Chris Lattnera5b11702008-04-21 01:28:02 +0000555 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
556 // node becomes an incoming value for BB's phi node. However, if the Preds
557 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
558 // account for the newly created predecessor.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000559 if (Preds.empty()) {
Chris Lattnera5b11702008-04-21 01:28:02 +0000560 // Insert dummy values as the incoming value.
561 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000562 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattnera5b11702008-04-21 01:28:02 +0000563 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000564
Bill Wendling0a693f42011-08-18 05:25:23 +0000565 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
566 bool HasLoopExit = false;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000567 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, MSSAU, PreserveLCSSA,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000568 HasLoopExit);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000569
Matt Arsenault06dfbb52018-01-31 22:54:37 +0000570 if (!Preds.empty()) {
571 // Update the PHI nodes in BB with the values coming from NewBB.
572 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
573 }
574
Chris Lattnera5b11702008-04-21 01:28:02 +0000575 return NewBB;
576}
Chris Lattner72f16e72008-11-27 08:10:05 +0000577
Bill Wendlingca7d3092011-08-19 00:05:40 +0000578void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000579 ArrayRef<BasicBlock *> Preds,
Bill Wendlingca7d3092011-08-19 00:05:40 +0000580 const char *Suffix1, const char *Suffix2,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000581 SmallVectorImpl<BasicBlock *> &NewBBs,
Chandler Carruth96ada252015-07-22 09:52:54 +0000582 DominatorTree *DT, LoopInfo *LI,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000583 MemorySSAUpdater *MSSAU,
Chandler Carruth96ada252015-07-22 09:52:54 +0000584 bool PreserveLCSSA) {
Bill Wendlingca7d3092011-08-19 00:05:40 +0000585 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
586
587 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
588 // it right before the original block.
589 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
590 OrigBB->getName() + Suffix1,
591 OrigBB->getParent(), OrigBB);
592 NewBBs.push_back(NewBB1);
593
594 // The new block unconditionally branches to the old block.
595 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000596 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendlingca7d3092011-08-19 00:05:40 +0000597
598 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
599 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
600 // This is slightly more strict than necessary; the minimum requirement
601 // is that there be no more than one indirectbr branching to BB. And
602 // all BlockAddress uses would need to be updated.
603 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
604 "Cannot split an edge from an IndirectBrInst");
605 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
606 }
607
Bill Wendlingca7d3092011-08-19 00:05:40 +0000608 bool HasLoopExit = false;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000609 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, MSSAU, PreserveLCSSA,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000610 HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000611
612 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
Chandler Carruth96ada252015-07-22 09:52:54 +0000613 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000614
Bill Wendlingca7d3092011-08-19 00:05:40 +0000615 // Move the remaining edges from OrigBB to point to NewBB2.
616 SmallVector<BasicBlock*, 8> NewBB2Preds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000617 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
618 i != e; ) {
619 BasicBlock *Pred = *i++;
Bill Wendling38d81302011-08-19 23:46:30 +0000620 if (Pred == NewBB1) continue;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000621 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
622 "Cannot split an edge from an IndirectBrInst");
Bill Wendlingca7d3092011-08-19 00:05:40 +0000623 NewBB2Preds.push_back(Pred);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000624 e = pred_end(OrigBB);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000625 }
626
Craig Topperf40110f2014-04-25 05:29:35 +0000627 BasicBlock *NewBB2 = nullptr;
Bill Wendling38d81302011-08-19 23:46:30 +0000628 if (!NewBB2Preds.empty()) {
629 // Create another basic block for the rest of OrigBB's predecessors.
630 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
631 OrigBB->getName() + Suffix2,
632 OrigBB->getParent(), OrigBB);
633 NewBBs.push_back(NewBB2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000634
Bill Wendling38d81302011-08-19 23:46:30 +0000635 // The new block unconditionally branches to the old block.
636 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000637 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendling38d81302011-08-19 23:46:30 +0000638
639 // Move the remaining edges from OrigBB to point to NewBB2.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000640 for (BasicBlock *NewBB2Pred : NewBB2Preds)
641 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
Bill Wendling38d81302011-08-19 23:46:30 +0000642
643 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
644 HasLoopExit = false;
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000645 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI, MSSAU,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000646 PreserveLCSSA, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000647
648 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
Chandler Carruth96ada252015-07-22 09:52:54 +0000649 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000650 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000651
652 LandingPadInst *LPad = OrigBB->getLandingPadInst();
653 Instruction *Clone1 = LPad->clone();
654 Clone1->setName(Twine("lpad") + Suffix1);
655 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
656
Bill Wendling38d81302011-08-19 23:46:30 +0000657 if (NewBB2) {
658 Instruction *Clone2 = LPad->clone();
659 Clone2->setName(Twine("lpad") + Suffix2);
660 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000661
Chen Li78bde832016-01-06 20:32:05 +0000662 // Create a PHI node for the two cloned landingpad instructions only
663 // if the original landingpad instruction has some uses.
664 if (!LPad->use_empty()) {
665 assert(!LPad->getType()->isTokenTy() &&
666 "Split cannot be applied if LPad is token type. Otherwise an "
667 "invalid PHINode of token type would be created.");
668 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
669 PN->addIncoming(Clone1, NewBB1);
670 PN->addIncoming(Clone2, NewBB2);
671 LPad->replaceAllUsesWith(PN);
672 }
Bill Wendling38d81302011-08-19 23:46:30 +0000673 LPad->eraseFromParent();
674 } else {
675 // There is no second clone. Just replace the landing pad with the first
676 // clone.
677 LPad->replaceAllUsesWith(Clone1);
678 LPad->eraseFromParent();
679 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000680}
681
Evan Chengd983eba2011-01-29 04:46:23 +0000682ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
Chijun Sima8b5de482018-08-04 08:13:47 +0000683 BasicBlock *Pred,
684 DomTreeUpdater *DTU) {
Evan Chengd983eba2011-01-29 04:46:23 +0000685 Instruction *UncondBranch = Pred->getTerminator();
686 // Clone the return and add it to the end of the predecessor.
687 Instruction *NewRet = RI->clone();
688 Pred->getInstList().push_back(NewRet);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000689
Evan Chengd983eba2011-01-29 04:46:23 +0000690 // If the return instruction returns a value, and if the value was a
691 // PHI node in "BB", propagate the right value into the return.
692 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
Evan Cheng249716e2012-07-27 21:21:26 +0000693 i != e; ++i) {
694 Value *V = *i;
Craig Topperf40110f2014-04-25 05:29:35 +0000695 Instruction *NewBC = nullptr;
Evan Cheng249716e2012-07-27 21:21:26 +0000696 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
697 // Return value might be bitcasted. Clone and insert it before the
698 // return instruction.
699 V = BCI->getOperand(0);
700 NewBC = BCI->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000701 Pred->getInstList().insert(NewRet->getIterator(), NewBC);
Evan Cheng249716e2012-07-27 21:21:26 +0000702 *i = NewBC;
703 }
704 if (PHINode *PN = dyn_cast<PHINode>(V)) {
705 if (PN->getParent() == BB) {
706 if (NewBC)
707 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
708 else
709 *i = PN->getIncomingValueForBlock(Pred);
710 }
711 }
712 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000713
Evan Chengd983eba2011-01-29 04:46:23 +0000714 // Update any PHI nodes in the returning block to realize that we no
715 // longer branch to them.
716 BB->removePredecessor(Pred);
717 UncondBranch->eraseFromParent();
Chijun Sima8b5de482018-08-04 08:13:47 +0000718
719 if (DTU)
720 DTU->deleteEdge(Pred, BB);
721
Evan Chengd983eba2011-01-29 04:46:23 +0000722 return cast<ReturnInst>(NewRet);
Chris Lattner351134b2009-05-04 02:25:58 +0000723}
Devang Patela8e74112011-04-29 22:28:59 +0000724
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000725Instruction *llvm::SplitBlockAndInsertIfThen(Value *Cond,
726 Instruction *SplitBefore,
727 bool Unreachable,
728 MDNode *BranchWeights,
729 DominatorTree *DT, LoopInfo *LI) {
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000730 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000731 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000732 Instruction *HeadOldTerm = Head->getTerminator();
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000733 LLVMContext &C = Head->getContext();
734 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000735 Instruction *CheckTerm;
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000736 if (Unreachable)
737 CheckTerm = new UnreachableInst(C, ThenBlock);
738 else
739 CheckTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000740 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000741 BranchInst *HeadNewTerm =
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000742 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000743 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
744 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000745
746 if (DT) {
747 if (DomTreeNode *OldNode = DT->getNode(Head)) {
748 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
749
750 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000751 for (DomTreeNode *Child : Children)
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000752 DT->changeImmediateDominator(Child, NewNode);
753
754 // Head dominates ThenBlock.
755 DT->addNewBlock(ThenBlock, Head);
756 }
757 }
758
Adam Nemetfdb20592016-03-15 18:06:20 +0000759 if (LI) {
Michael Kruse811de8a2017-03-06 15:33:05 +0000760 if (Loop *L = LI->getLoopFor(Head)) {
761 L->addBasicBlockToLoop(ThenBlock, *LI);
762 L->addBasicBlockToLoop(Tail, *LI);
763 }
Adam Nemetfdb20592016-03-15 18:06:20 +0000764 }
765
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000766 return CheckTerm;
767}
Tom Stellardaa664d92013-08-06 02:43:45 +0000768
Kostya Serebryany530e2072013-12-23 14:15:08 +0000769void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000770 Instruction **ThenTerm,
771 Instruction **ElseTerm,
Kostya Serebryany530e2072013-12-23 14:15:08 +0000772 MDNode *BranchWeights) {
773 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000774 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Chandler Carruth4a2d58e2018-10-15 09:34:05 +0000775 Instruction *HeadOldTerm = Head->getTerminator();
Kostya Serebryany530e2072013-12-23 14:15:08 +0000776 LLVMContext &C = Head->getContext();
777 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
778 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
779 *ThenTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000780 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000781 *ElseTerm = BranchInst::Create(Tail, ElseBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000782 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000783 BranchInst *HeadNewTerm =
784 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
785 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
786 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
787}
788
Tom Stellardaa664d92013-08-06 02:43:45 +0000789Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
790 BasicBlock *&IfFalse) {
791 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +0000792 BasicBlock *Pred1 = nullptr;
793 BasicBlock *Pred2 = nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000794
795 if (SomePHI) {
796 if (SomePHI->getNumIncomingValues() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +0000797 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000798 Pred1 = SomePHI->getIncomingBlock(0);
799 Pred2 = SomePHI->getIncomingBlock(1);
800 } else {
801 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
802 if (PI == PE) // No predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000803 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000804 Pred1 = *PI++;
805 if (PI == PE) // Only one predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000806 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000807 Pred2 = *PI++;
808 if (PI != PE) // More than two predecessors
Craig Topperf40110f2014-04-25 05:29:35 +0000809 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000810 }
811
812 // We can only handle branches. Other control flow will be lowered to
813 // branches if possible anyway.
814 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
815 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000816 if (!Pred1Br || !Pred2Br)
817 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000818
819 // Eliminate code duplication by ensuring that Pred1Br is conditional if
820 // either are.
821 if (Pred2Br->isConditional()) {
822 // If both branches are conditional, we don't have an "if statement". In
823 // reality, we could transform this case, but since the condition will be
824 // required anyway, we stand no chance of eliminating it, so the xform is
825 // probably not profitable.
826 if (Pred1Br->isConditional())
Craig Topperf40110f2014-04-25 05:29:35 +0000827 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000828
829 std::swap(Pred1, Pred2);
830 std::swap(Pred1Br, Pred2Br);
831 }
832
833 if (Pred1Br->isConditional()) {
834 // The only thing we have to watch out for here is to make sure that Pred2
835 // doesn't have incoming edges from other blocks. If it does, the condition
836 // doesn't dominate BB.
Craig Topperf40110f2014-04-25 05:29:35 +0000837 if (!Pred2->getSinglePredecessor())
838 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000839
840 // If we found a conditional branch predecessor, make sure that it branches
841 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
842 if (Pred1Br->getSuccessor(0) == BB &&
843 Pred1Br->getSuccessor(1) == Pred2) {
844 IfTrue = Pred1;
845 IfFalse = Pred2;
846 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
847 Pred1Br->getSuccessor(1) == BB) {
848 IfTrue = Pred2;
849 IfFalse = Pred1;
850 } else {
851 // We know that one arm of the conditional goes to BB, so the other must
852 // go somewhere unrelated, and this must not be an "if statement".
Craig Topperf40110f2014-04-25 05:29:35 +0000853 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000854 }
855
856 return Pred1Br->getCondition();
857 }
858
859 // Ok, if we got here, both predecessors end with an unconditional branch to
860 // BB. Don't panic! If both blocks only have a single (identical)
861 // predecessor, and THAT is a conditional branch, then we're all ok!
862 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +0000863 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
864 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000865
866 // Otherwise, if this is a conditional branch, then we can use it!
867 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000868 if (!BI) return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000869
870 assert(BI->isConditional() && "Two successors but not conditional?");
871 if (BI->getSuccessor(0) == Pred1) {
872 IfTrue = Pred1;
873 IfFalse = Pred2;
874 } else {
875 IfTrue = Pred2;
876 IfFalse = Pred1;
877 }
878 return BI->getCondition();
879}