blob: 056753f7ddb883ba6ce29c3cd2bbf156af3ad3ae [file] [log] [blame]
Eugene Zelenko57bd5a02017-10-27 01:09:08 +00001//===- BasicBlockUtils.cpp - BasicBlock Utilities --------------------------==//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner28537df2002-05-07 18:07:59 +00009//
10// This family of functions perform manipulations on basic blocks, and
11// instructions contained within basic blocks.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000016#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/SmallPtrSet.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Twine.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000020#include "llvm/Analysis/CFG.h"
Chris Lattnerf6ae9042011-01-11 08:13:40 +000021#include "llvm/Analysis/LoopInfo.h"
22#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000023#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/CFG.h"
25#include "llvm/IR/Constants.h"
Adrian Prantld60f34c2017-11-01 20:43:30 +000026#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000027#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Function.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000029#include "llvm/IR/InstrTypes.h"
30#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Instructions.h"
Adrian Prantld60f34c2017-11-01 20:43:30 +000032#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000033#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Type.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000035#include "llvm/IR/User.h"
36#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000037#include "llvm/IR/ValueHandle.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000038#include "llvm/Support/Casting.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000039#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko57bd5a02017-10-27 01:09:08 +000040#include <cassert>
41#include <cstdint>
42#include <string>
43#include <utility>
44#include <vector>
45
Chris Lattnerdf3c3422004-01-09 06:12:26 +000046using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000047
Brian M. Rzycki580bc3c2017-12-13 22:01:17 +000048void llvm::DeleteDeadBlock(BasicBlock *BB) {
Chris Lattner37e01362008-12-03 07:45:15 +000049 assert((pred_begin(BB) == pred_end(BB) ||
50 // Can delete self loop.
51 BB->getSinglePredecessor() == BB) && "Block is not dead!");
Chris Lattnerbcc904a2008-12-03 06:37:44 +000052 TerminatorInst *BBTerm = BB->getTerminator();
Jakub Staszak190db2f2013-01-14 23:16:36 +000053
Chris Lattnerbcc904a2008-12-03 06:37:44 +000054 // Loop through all of our successors and make sure they know that one
55 // of their predecessors is going away.
Brian M. Rzycki580bc3c2017-12-13 22:01:17 +000056 for (BasicBlock *Succ : BBTerm->successors())
Pete Cooperebcd7482015-08-06 20:22:46 +000057 Succ->removePredecessor(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +000058
Chris Lattnerbcc904a2008-12-03 06:37:44 +000059 // Zap all the instructions in the block.
60 while (!BB->empty()) {
61 Instruction &I = BB->back();
62 // If this instruction is used, replace uses with an arbitrary value.
63 // Because control flow can't get here, we don't care what we replace the
64 // value with. Note that since this block is unreachable, and all values
65 // contained within it must dominate their uses, that all uses will
66 // eventually be removed (they are themselves dead).
67 if (!I.use_empty())
Owen Andersonb292b8c2009-07-30 23:03:37 +000068 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattnerbcc904a2008-12-03 06:37:44 +000069 BB->getInstList().pop_back();
70 }
Jakub Staszak190db2f2013-01-14 23:16:36 +000071
Brian M. Rzycki580bc3c2017-12-13 22:01:17 +000072 // Zap the block!
73 BB->eraseFromParent();
Chris Lattnerbcc904a2008-12-03 06:37:44 +000074}
75
Chandler Carruth96ada252015-07-22 09:52:54 +000076void llvm::FoldSingleEntryPHINodes(BasicBlock *BB,
Chandler Carruth61440d22016-03-10 00:55:30 +000077 MemoryDependenceResults *MemDep) {
Chris Lattnerf6ae9042011-01-11 08:13:40 +000078 if (!isa<PHINode>(BB->begin())) return;
Jakub Staszak190db2f2013-01-14 23:16:36 +000079
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000080 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
81 if (PN->getIncomingValue(0) != PN)
82 PN->replaceAllUsesWith(PN->getIncomingValue(0));
83 else
Owen Andersonb292b8c2009-07-30 23:03:37 +000084 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Jakub Staszak190db2f2013-01-14 23:16:36 +000085
Chris Lattnerf6ae9042011-01-11 08:13:40 +000086 if (MemDep)
87 MemDep->removeInstruction(PN); // Memdep updates AA itself.
Jakub Staszak190db2f2013-01-14 23:16:36 +000088
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000089 PN->eraseFromParent();
90 }
91}
92
Benjamin Kramer8bcc9712012-08-29 15:32:21 +000093bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
Dan Gohmanff089952009-05-02 18:29:22 +000094 // Recursively deleting a PHI may cause multiple PHIs to be deleted
Sanjoy Dase6bca0e2017-05-01 17:07:49 +000095 // or RAUW'd undef, so use an array of WeakTrackingVH for the PHIs to delete.
96 SmallVector<WeakTrackingVH, 8> PHIs;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000097 for (PHINode &PN : BB->phis())
98 PHIs.push_back(&PN);
Dan Gohmanff089952009-05-02 18:29:22 +000099
Dan Gohmancb99fe92010-01-05 15:45:31 +0000100 bool Changed = false;
Dan Gohmanff089952009-05-02 18:29:22 +0000101 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
102 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000103 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
Dan Gohmancb99fe92010-01-05 15:45:31 +0000104
105 return Changed;
Dan Gohmanff089952009-05-02 18:29:22 +0000106}
107
Chandler Carruthb5c11532015-01-18 02:11:23 +0000108bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT,
Chandler Carruth96ada252015-07-22 09:52:54 +0000109 LoopInfo *LI,
Chandler Carruth61440d22016-03-10 00:55:30 +0000110 MemoryDependenceResults *MemDep) {
Dan Gohman941020e2010-08-17 17:07:02 +0000111 // Don't merge away blocks who have their address taken.
112 if (BB->hasAddressTaken()) return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000113
Dan Gohman941020e2010-08-17 17:07:02 +0000114 // Can't merge if there are multiple predecessors, or no predecessors.
115 BasicBlock *PredBB = BB->getUniquePredecessor();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000116 if (!PredBB) return false;
Dan Gohman941020e2010-08-17 17:07:02 +0000117
Dan Gohman2d02ff82009-10-31 17:33:01 +0000118 // Don't break self-loops.
119 if (PredBB == BB) return false;
David Majnemer654e1302015-07-31 17:58:14 +0000120 // Don't break unwinding instructions.
121 if (PredBB->getTerminator()->isExceptional())
122 return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000123
Dan Gohman2d02ff82009-10-31 17:33:01 +0000124 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
Chris Lattner930b7162011-01-08 19:08:40 +0000125 BasicBlock *OnlySucc = BB;
Dan Gohman2d02ff82009-10-31 17:33:01 +0000126 for (; SI != SE; ++SI)
127 if (*SI != OnlySucc) {
Craig Topperf40110f2014-04-25 05:29:35 +0000128 OnlySucc = nullptr; // There are multiple distinct successors!
Dan Gohman2d02ff82009-10-31 17:33:01 +0000129 break;
130 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000131
Dan Gohman2d02ff82009-10-31 17:33:01 +0000132 // Can't merge if there are multiple successors.
133 if (!OnlySucc) return false;
Devang Patel0f7a3502008-09-09 01:06:56 +0000134
Dan Gohman2d02ff82009-10-31 17:33:01 +0000135 // Can't merge if there is PHI loop.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000136 for (PHINode &PN : BB->phis())
137 for (Value *IncValue : PN.incoming_values())
138 if (IncValue == &PN)
139 return false;
Dan Gohman2d02ff82009-10-31 17:33:01 +0000140
141 // Begin by getting rid of unneeded PHIs.
Adrian Prantld60f34c2017-11-01 20:43:30 +0000142 SmallVector<Value *, 4> IncomingValues;
143 if (isa<PHINode>(BB->front())) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000144 for (PHINode &PN : BB->phis())
145 if (PN.getIncomingValue(0) != &PN)
146 IncomingValues.push_back(PN.getIncomingValue(0));
Chandler Carruth96ada252015-07-22 09:52:54 +0000147 FoldSingleEntryPHINodes(BB, MemDep);
Adrian Prantld60f34c2017-11-01 20:43:30 +0000148 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000149
Owen Andersonc0623812008-07-17 00:01:40 +0000150 // Delete the unconditional branch from the predecessor...
151 PredBB->getInstList().pop_back();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000152
Owen Andersonc0623812008-07-17 00:01:40 +0000153 // Make all PHI nodes that referred to BB now refer to Pred as their
154 // source...
155 BB->replaceAllUsesWith(PredBB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000156
Jay Foad61ea0e42011-06-23 09:09:15 +0000157 // Move all definitions in the successor to the predecessor...
158 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000159
Adrian Prantld60f34c2017-11-01 20:43:30 +0000160 // Eliminate duplicate dbg.values describing the entry PHI node post-splice.
161 for (auto *Incoming : IncomingValues) {
162 if (isa<Instruction>(Incoming)) {
163 SmallVector<DbgValueInst *, 2> DbgValues;
164 SmallDenseSet<std::pair<DILocalVariable *, DIExpression *>, 2>
165 DbgValueSet;
166 llvm::findDbgValues(DbgValues, Incoming);
167 for (auto &DVI : DbgValues) {
168 auto R = DbgValueSet.insert({DVI->getVariable(), DVI->getExpression()});
169 if (!R.second)
170 DVI->eraseFromParent();
171 }
172 }
173 }
174
Dan Gohman2d02ff82009-10-31 17:33:01 +0000175 // Inherit predecessors name if it exists.
Owen Anderson27405ef2008-07-17 19:42:29 +0000176 if (!PredBB->hasName())
177 PredBB->takeName(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000178
Owen Andersonc0623812008-07-17 00:01:40 +0000179 // Finally, erase the old block and update dominator info.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000180 if (DT)
181 if (DomTreeNode *DTN = DT->getNode(BB)) {
182 DomTreeNode *PredDTN = DT->getNode(PredBB);
183 SmallVector<DomTreeNode *, 8> Children(DTN->begin(), DTN->end());
Benjamin Kramer135f7352016-06-26 12:28:59 +0000184 for (DomTreeNode *DI : Children)
185 DT->changeImmediateDominator(DI, PredDTN);
Owen Andersonc0623812008-07-17 00:01:40 +0000186
Chandler Carruthb5c11532015-01-18 02:11:23 +0000187 DT->eraseNode(BB);
Owen Andersonc0623812008-07-17 00:01:40 +0000188 }
Chandler Carruthb5c11532015-01-18 02:11:23 +0000189
190 if (LI)
191 LI->removeBlock(BB);
192
193 if (MemDep)
194 MemDep->invalidateCachedPredecessors();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000195
Owen Andersonc0623812008-07-17 00:01:40 +0000196 BB->eraseFromParent();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000197 return true;
Owen Andersonc0623812008-07-17 00:01:40 +0000198}
199
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000200void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
201 BasicBlock::iterator &BI, Value *V) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000202 Instruction &I = *BI;
Chris Lattner28537df2002-05-07 18:07:59 +0000203 // Replaces all of the uses of the instruction with uses of the value
Chris Lattnerfda72b12002-06-25 16:12:52 +0000204 I.replaceAllUsesWith(V);
Chris Lattner28537df2002-05-07 18:07:59 +0000205
Chris Lattner8dd4cae2007-02-11 01:37:51 +0000206 // Make sure to propagate a name if there is one already.
207 if (I.hasName() && !V->hasName())
208 V->takeName(&I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000209
Misha Brukman7eb05a12003-08-18 14:43:39 +0000210 // Delete the unnecessary instruction now...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000211 BI = BIL.erase(BI);
Chris Lattner28537df2002-05-07 18:07:59 +0000212}
213
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000214void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
215 BasicBlock::iterator &BI, Instruction *I) {
Craig Toppere73658d2014-04-28 04:05:08 +0000216 assert(I->getParent() == nullptr &&
Chris Lattner28537df2002-05-07 18:07:59 +0000217 "ReplaceInstWithInst: Instruction already inserted into basic block!");
218
Alexey Samsonov19ffcb92015-06-23 21:00:08 +0000219 // Copy debug location to newly added instruction, if it wasn't already set
220 // by the caller.
221 if (!I->getDebugLoc())
222 I->setDebugLoc(BI->getDebugLoc());
223
Chris Lattner28537df2002-05-07 18:07:59 +0000224 // Insert the new instruction into the basic block...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000225 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner28537df2002-05-07 18:07:59 +0000226
227 // Replace all uses of the old instruction, and delete it.
228 ReplaceInstWithValue(BIL, BI, I);
229
230 // Move BI back to point to the newly inserted instruction
Chris Lattnerfda72b12002-06-25 16:12:52 +0000231 BI = New;
Chris Lattner28537df2002-05-07 18:07:59 +0000232}
233
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000234void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000235 BasicBlock::iterator BI(From);
236 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner28537df2002-05-07 18:07:59 +0000237}
Chris Lattnerb17274e2002-07-29 22:32:08 +0000238
Chandler Carruthd4500562015-01-19 12:36:53 +0000239BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
240 LoopInfo *LI) {
Bob Wilsonaff96b22010-02-16 21:06:42 +0000241 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000242
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000243 // If this is a critical edge, let SplitCriticalEdge do it.
244 TerminatorInst *LatchTerm = BB->getTerminator();
Chandler Carruthd4500562015-01-19 12:36:53 +0000245 if (SplitCriticalEdge(LatchTerm, SuccNum, CriticalEdgeSplittingOptions(DT, LI)
246 .setPreserveLCSSA()))
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000247 return LatchTerm->getSuccessor(SuccNum);
Chandler Carruth32c52c72015-01-18 02:39:37 +0000248
Devang Pateld7767cc2007-07-06 21:39:20 +0000249 // If the edge isn't critical, then BB has a single successor or Succ has a
250 // single pred. Split the block.
Devang Pateld7767cc2007-07-06 21:39:20 +0000251 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
252 // If the successor only has a single pred, split the top of the successor
253 // block.
254 assert(SP == BB && "CFG broken");
Craig Topperf40110f2014-04-25 05:29:35 +0000255 SP = nullptr;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000256 return SplitBlock(Succ, &Succ->front(), DT, LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000257 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000258
Chris Lattner30d95f92011-01-08 18:47:43 +0000259 // Otherwise, if BB has a single successor, split it at the bottom of the
260 // block.
261 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
Jakub Staszak190db2f2013-01-14 23:16:36 +0000262 "Should have a single succ!");
Chandler Carruth32c52c72015-01-18 02:39:37 +0000263 return SplitBlock(BB, BB->getTerminator(), DT, LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000264}
265
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000266unsigned
267llvm::SplitAllCriticalEdges(Function &F,
268 const CriticalEdgeSplittingOptions &Options) {
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000269 unsigned NumBroken = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000270 for (BasicBlock &BB : F) {
271 TerminatorInst *TI = BB.getTerminator();
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000272 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
273 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000274 if (SplitCriticalEdge(TI, i, Options))
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000275 ++NumBroken;
276 }
277 return NumBroken;
278}
279
Chandler Carruth32c52c72015-01-18 02:39:37 +0000280BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
281 DominatorTree *DT, LoopInfo *LI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000282 BasicBlock::iterator SplitIt = SplitPt->getIterator();
David Majnemer654e1302015-07-31 17:58:14 +0000283 while (isa<PHINode>(SplitIt) || SplitIt->isEHPad())
Devang Pateld7767cc2007-07-06 21:39:20 +0000284 ++SplitIt;
285 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
286
Dan Gohman3ddbc242009-09-08 15:45:00 +0000287 // The new block lives in whichever loop the old one did. This preserves
288 // LCSSA as well, because we force the split point to be after any PHI nodes.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000289 if (LI)
290 if (Loop *L = LI->getLoopFor(Old))
291 L->addBasicBlockToLoop(New, *LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000292
Chandler Carruth32c52c72015-01-18 02:39:37 +0000293 if (DT)
Gabor Greif2f5f6962010-09-10 22:25:58 +0000294 // Old dominates New. New node dominates all other nodes dominated by Old.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000295 if (DomTreeNode *OldNode = DT->getNode(Old)) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000296 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
Devang Patel186e0d82007-07-19 02:29:24 +0000297
Chandler Carruth32c52c72015-01-18 02:39:37 +0000298 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000299 for (DomTreeNode *I : Children)
300 DT->changeImmediateDominator(I, NewNode);
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000301 }
Devang Pateld7767cc2007-07-06 21:39:20 +0000302
Devang Pateld7767cc2007-07-06 21:39:20 +0000303 return New;
304}
Chris Lattnera5b11702008-04-21 01:28:02 +0000305
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000306/// Update DominatorTree, LoopInfo, and LCCSA analysis information.
Bill Wendling60291352011-08-18 17:57:57 +0000307static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
Bill Wendlingec3823d2011-08-18 20:39:32 +0000308 ArrayRef<BasicBlock *> Preds,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000309 DominatorTree *DT, LoopInfo *LI,
310 bool PreserveLCSSA, bool &HasLoopExit) {
311 // Update dominator tree if available.
312 if (DT)
313 DT->splitBlock(NewBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000314
Chandler Carruthb5797b62015-01-18 09:21:15 +0000315 // The rest of the logic is only relevant for updating the loop structures.
316 if (!LI)
317 return;
318
Anna Thomas9fca5832018-01-04 17:21:15 +0000319 assert(DT && "DT should be available to update LoopInfo!");
Chandler Carruthb5797b62015-01-18 09:21:15 +0000320 Loop *L = LI->getLoopFor(OldBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000321
322 // If we need to preserve loop analyses, collect some information about how
323 // this split will affect loops.
324 bool IsLoopEntry = !!L;
325 bool SplitMakesNewLoopHeader = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000326 for (BasicBlock *Pred : Preds) {
Anna Thomasbdb94302018-01-02 16:25:50 +0000327 // Preds that are not reachable from entry should not be used to identify if
328 // OldBB is a loop entry or if SplitMakesNewLoopHeader. Unreachable blocks
329 // are not within any loops, so we incorrectly mark SplitMakesNewLoopHeader
330 // as true and make the NewBB the header of some loop. This breaks LI.
331 if (!DT->isReachableFromEntry(Pred))
332 continue;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000333 // If we need to preserve LCSSA, determine if any of the preds is a loop
334 // exit.
335 if (PreserveLCSSA)
336 if (Loop *PL = LI->getLoopFor(Pred))
337 if (!PL->contains(OldBB))
338 HasLoopExit = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000339
Chandler Carruthb5797b62015-01-18 09:21:15 +0000340 // If we need to preserve LoopInfo, note whether any of the preds crosses
341 // an interesting loop boundary.
342 if (!L)
343 continue;
344 if (L->contains(Pred))
345 IsLoopEntry = false;
346 else
347 SplitMakesNewLoopHeader = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000348 }
349
Chandler Carruthb5797b62015-01-18 09:21:15 +0000350 // Unless we have a loop for OldBB, nothing else to do here.
351 if (!L)
352 return;
Bill Wendling0a693f42011-08-18 05:25:23 +0000353
354 if (IsLoopEntry) {
355 // Add the new block to the nearest enclosing loop (and not an adjacent
356 // loop). To find this, examine each of the predecessors and determine which
357 // loops enclose them, and select the most-nested loop which contains the
358 // loop containing the block being split.
Craig Topperf40110f2014-04-25 05:29:35 +0000359 Loop *InnermostPredLoop = nullptr;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000360 for (BasicBlock *Pred : Preds) {
Bill Wendlingec3823d2011-08-18 20:39:32 +0000361 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
Bill Wendling0a693f42011-08-18 05:25:23 +0000362 // Seek a loop which actually contains the block being split (to avoid
363 // adjacent loops).
364 while (PredLoop && !PredLoop->contains(OldBB))
365 PredLoop = PredLoop->getParentLoop();
366
367 // Select the most-nested of these loops which contains the block.
368 if (PredLoop && PredLoop->contains(OldBB) &&
369 (!InnermostPredLoop ||
370 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
371 InnermostPredLoop = PredLoop;
372 }
Bill Wendlingec3823d2011-08-18 20:39:32 +0000373 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000374
375 if (InnermostPredLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000376 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000377 } else {
Chandler Carruth691addc2015-01-18 01:25:51 +0000378 L->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000379 if (SplitMakesNewLoopHeader)
380 L->moveToHeader(NewBB);
381 }
382}
383
Sanjay Patel85ce0f12016-04-23 16:31:48 +0000384/// Update the PHI nodes in OrigBB to include the values coming from NewBB.
385/// This also updates AliasAnalysis, if available.
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000386static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000387 ArrayRef<BasicBlock *> Preds, BranchInst *BI,
Chandler Carruth96ada252015-07-22 09:52:54 +0000388 bool HasLoopExit) {
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000389 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000390 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000391 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
392 PHINode *PN = cast<PHINode>(I++);
393
394 // Check to see if all of the values coming in are the same. If so, we
395 // don't need to create a new PHI node, unless it's needed for LCSSA.
Craig Topperf40110f2014-04-25 05:29:35 +0000396 Value *InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000397 if (!HasLoopExit) {
398 InVal = PN->getIncomingValueForBlock(Preds[0]);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000399 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
400 if (!PredSet.count(PN->getIncomingBlock(i)))
401 continue;
402 if (!InVal)
403 InVal = PN->getIncomingValue(i);
404 else if (InVal != PN->getIncomingValue(i)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000405 InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000406 break;
407 }
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000408 }
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000409 }
410
411 if (InVal) {
412 // If all incoming values for the new PHI would be the same, just don't
413 // make a new PHI. Instead, just remove the incoming values from the old
414 // PHI.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000415
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000416 // NOTE! This loop walks backwards for a reason! First off, this minimizes
417 // the cost of removal if we end up removing a large number of values, and
418 // second off, this ensures that the indices for the incoming values
419 // aren't invalidated when we remove one.
420 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
421 if (PredSet.count(PN->getIncomingBlock(i)))
422 PN->removeIncomingValue(i, false);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000423
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000424 // Add an incoming value to the PHI node in the loop for the preheader
425 // edge.
426 PN->addIncoming(InVal, NewBB);
427 continue;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000428 }
429
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000430 // If the values coming into the block are not the same, we need a new
431 // PHI.
432 // Create the new PHI node, insert it into NewBB at the end of the block
433 PHINode *NewPHI =
434 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000435
436 // NOTE! This loop walks backwards for a reason! First off, this minimizes
437 // the cost of removal if we end up removing a large number of values, and
438 // second off, this ensures that the indices for the incoming values aren't
439 // invalidated when we remove one.
440 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
441 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
442 if (PredSet.count(IncomingBB)) {
443 Value *V = PN->removeIncomingValue(i, false);
444 NewPHI->addIncoming(V, IncomingBB);
445 }
446 }
447
448 PN->addIncoming(NewPHI, NewBB);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000449 }
450}
451
Jakub Staszak190db2f2013-01-14 23:16:36 +0000452BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000453 ArrayRef<BasicBlock *> Preds,
Chandler Carruth96ada252015-07-22 09:52:54 +0000454 const char *Suffix, DominatorTree *DT,
455 LoopInfo *LI, bool PreserveLCSSA) {
David Majnemer654e1302015-07-31 17:58:14 +0000456 // Do not attempt to split that which cannot be split.
457 if (!BB->canSplitPredecessors())
458 return nullptr;
459
Philip Reames9198b332015-01-28 23:06:47 +0000460 // For the landingpads we need to act a bit differently.
461 // Delegate this work to the SplitLandingPadPredecessors.
462 if (BB->isLandingPad()) {
463 SmallVector<BasicBlock*, 2> NewBBs;
464 std::string NewName = std::string(Suffix) + ".split-lp";
465
Chandler Carruth96ada252015-07-22 09:52:54 +0000466 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs, DT,
467 LI, PreserveLCSSA);
Philip Reames9198b332015-01-28 23:06:47 +0000468 return NewBBs[0];
469 }
470
Chris Lattnera5b11702008-04-21 01:28:02 +0000471 // Create new basic block, insert right before the original block.
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000472 BasicBlock *NewBB = BasicBlock::Create(
473 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000474
Chris Lattnera5b11702008-04-21 01:28:02 +0000475 // The new block unconditionally branches to the old block.
476 BranchInst *BI = BranchInst::Create(BB, NewBB);
Taewook Oh2e945eb2017-02-14 21:10:40 +0000477 BI->setDebugLoc(BB->getFirstNonPHIOrDbg()->getDebugLoc());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000478
Chris Lattnera5b11702008-04-21 01:28:02 +0000479 // Move the edges from Preds to point to NewBB instead of BB.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000480 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Dan Gohman00c79382009-11-05 18:25:44 +0000481 // This is slightly more strict than necessary; the minimum requirement
482 // is that there be no more than one indirectbr branching to BB. And
483 // all BlockAddress uses would need to be updated.
484 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
485 "Cannot split an edge from an IndirectBrInst");
Chris Lattnera5b11702008-04-21 01:28:02 +0000486 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000487 }
488
Chris Lattnera5b11702008-04-21 01:28:02 +0000489 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
490 // node becomes an incoming value for BB's phi node. However, if the Preds
491 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
492 // account for the newly created predecessor.
Eugene Zelenko57bd5a02017-10-27 01:09:08 +0000493 if (Preds.empty()) {
Chris Lattnera5b11702008-04-21 01:28:02 +0000494 // Insert dummy values as the incoming value.
495 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000496 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattnera5b11702008-04-21 01:28:02 +0000497 return NewBB;
498 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000499
Bill Wendling0a693f42011-08-18 05:25:23 +0000500 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
501 bool HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000502 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, PreserveLCSSA,
503 HasLoopExit);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000504
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000505 // Update the PHI nodes in BB with the values coming from NewBB.
Chandler Carruth96ada252015-07-22 09:52:54 +0000506 UpdatePHINodes(BB, NewBB, Preds, BI, HasLoopExit);
Chris Lattnera5b11702008-04-21 01:28:02 +0000507 return NewBB;
508}
Chris Lattner72f16e72008-11-27 08:10:05 +0000509
Bill Wendlingca7d3092011-08-19 00:05:40 +0000510void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000511 ArrayRef<BasicBlock *> Preds,
Bill Wendlingca7d3092011-08-19 00:05:40 +0000512 const char *Suffix1, const char *Suffix2,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000513 SmallVectorImpl<BasicBlock *> &NewBBs,
Chandler Carruth96ada252015-07-22 09:52:54 +0000514 DominatorTree *DT, LoopInfo *LI,
515 bool PreserveLCSSA) {
Bill Wendlingca7d3092011-08-19 00:05:40 +0000516 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
517
518 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
519 // it right before the original block.
520 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
521 OrigBB->getName() + Suffix1,
522 OrigBB->getParent(), OrigBB);
523 NewBBs.push_back(NewBB1);
524
525 // The new block unconditionally branches to the old block.
526 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000527 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendlingca7d3092011-08-19 00:05:40 +0000528
529 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
530 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
531 // This is slightly more strict than necessary; the minimum requirement
532 // is that there be no more than one indirectbr branching to BB. And
533 // all BlockAddress uses would need to be updated.
534 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
535 "Cannot split an edge from an IndirectBrInst");
536 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
537 }
538
Bill Wendlingca7d3092011-08-19 00:05:40 +0000539 bool HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000540 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, PreserveLCSSA,
541 HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000542
543 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
Chandler Carruth96ada252015-07-22 09:52:54 +0000544 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000545
Bill Wendlingca7d3092011-08-19 00:05:40 +0000546 // Move the remaining edges from OrigBB to point to NewBB2.
547 SmallVector<BasicBlock*, 8> NewBB2Preds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000548 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
549 i != e; ) {
550 BasicBlock *Pred = *i++;
Bill Wendling38d81302011-08-19 23:46:30 +0000551 if (Pred == NewBB1) continue;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000552 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
553 "Cannot split an edge from an IndirectBrInst");
Bill Wendlingca7d3092011-08-19 00:05:40 +0000554 NewBB2Preds.push_back(Pred);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000555 e = pred_end(OrigBB);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000556 }
557
Craig Topperf40110f2014-04-25 05:29:35 +0000558 BasicBlock *NewBB2 = nullptr;
Bill Wendling38d81302011-08-19 23:46:30 +0000559 if (!NewBB2Preds.empty()) {
560 // Create another basic block for the rest of OrigBB's predecessors.
561 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
562 OrigBB->getName() + Suffix2,
563 OrigBB->getParent(), OrigBB);
564 NewBBs.push_back(NewBB2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000565
Bill Wendling38d81302011-08-19 23:46:30 +0000566 // The new block unconditionally branches to the old block.
567 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000568 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendling38d81302011-08-19 23:46:30 +0000569
570 // Move the remaining edges from OrigBB to point to NewBB2.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000571 for (BasicBlock *NewBB2Pred : NewBB2Preds)
572 NewBB2Pred->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
Bill Wendling38d81302011-08-19 23:46:30 +0000573
574 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
575 HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000576 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI,
577 PreserveLCSSA, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000578
579 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
Chandler Carruth96ada252015-07-22 09:52:54 +0000580 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000581 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000582
583 LandingPadInst *LPad = OrigBB->getLandingPadInst();
584 Instruction *Clone1 = LPad->clone();
585 Clone1->setName(Twine("lpad") + Suffix1);
586 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
587
Bill Wendling38d81302011-08-19 23:46:30 +0000588 if (NewBB2) {
589 Instruction *Clone2 = LPad->clone();
590 Clone2->setName(Twine("lpad") + Suffix2);
591 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000592
Chen Li78bde832016-01-06 20:32:05 +0000593 // Create a PHI node for the two cloned landingpad instructions only
594 // if the original landingpad instruction has some uses.
595 if (!LPad->use_empty()) {
596 assert(!LPad->getType()->isTokenTy() &&
597 "Split cannot be applied if LPad is token type. Otherwise an "
598 "invalid PHINode of token type would be created.");
599 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
600 PN->addIncoming(Clone1, NewBB1);
601 PN->addIncoming(Clone2, NewBB2);
602 LPad->replaceAllUsesWith(PN);
603 }
Bill Wendling38d81302011-08-19 23:46:30 +0000604 LPad->eraseFromParent();
605 } else {
606 // There is no second clone. Just replace the landing pad with the first
607 // clone.
608 LPad->replaceAllUsesWith(Clone1);
609 LPad->eraseFromParent();
610 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000611}
612
Evan Chengd983eba2011-01-29 04:46:23 +0000613ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
614 BasicBlock *Pred) {
615 Instruction *UncondBranch = Pred->getTerminator();
616 // Clone the return and add it to the end of the predecessor.
617 Instruction *NewRet = RI->clone();
618 Pred->getInstList().push_back(NewRet);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000619
Evan Chengd983eba2011-01-29 04:46:23 +0000620 // If the return instruction returns a value, and if the value was a
621 // PHI node in "BB", propagate the right value into the return.
622 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
Evan Cheng249716e2012-07-27 21:21:26 +0000623 i != e; ++i) {
624 Value *V = *i;
Craig Topperf40110f2014-04-25 05:29:35 +0000625 Instruction *NewBC = nullptr;
Evan Cheng249716e2012-07-27 21:21:26 +0000626 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
627 // Return value might be bitcasted. Clone and insert it before the
628 // return instruction.
629 V = BCI->getOperand(0);
630 NewBC = BCI->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000631 Pred->getInstList().insert(NewRet->getIterator(), NewBC);
Evan Cheng249716e2012-07-27 21:21:26 +0000632 *i = NewBC;
633 }
634 if (PHINode *PN = dyn_cast<PHINode>(V)) {
635 if (PN->getParent() == BB) {
636 if (NewBC)
637 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
638 else
639 *i = PN->getIncomingValueForBlock(Pred);
640 }
641 }
642 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000643
Evan Chengd983eba2011-01-29 04:46:23 +0000644 // Update any PHI nodes in the returning block to realize that we no
645 // longer branch to them.
646 BB->removePredecessor(Pred);
647 UncondBranch->eraseFromParent();
648 return cast<ReturnInst>(NewRet);
Chris Lattner351134b2009-05-04 02:25:58 +0000649}
Devang Patela8e74112011-04-29 22:28:59 +0000650
Adam Nemetfdb20592016-03-15 18:06:20 +0000651TerminatorInst *
652llvm::SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
653 bool Unreachable, MDNode *BranchWeights,
654 DominatorTree *DT, LoopInfo *LI) {
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000655 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000656 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000657 TerminatorInst *HeadOldTerm = Head->getTerminator();
658 LLVMContext &C = Head->getContext();
659 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
660 TerminatorInst *CheckTerm;
661 if (Unreachable)
662 CheckTerm = new UnreachableInst(C, ThenBlock);
663 else
664 CheckTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000665 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000666 BranchInst *HeadNewTerm =
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000667 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000668 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
669 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000670
671 if (DT) {
672 if (DomTreeNode *OldNode = DT->getNode(Head)) {
673 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
674
675 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
Benjamin Kramer135f7352016-06-26 12:28:59 +0000676 for (DomTreeNode *Child : Children)
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000677 DT->changeImmediateDominator(Child, NewNode);
678
679 // Head dominates ThenBlock.
680 DT->addNewBlock(ThenBlock, Head);
681 }
682 }
683
Adam Nemetfdb20592016-03-15 18:06:20 +0000684 if (LI) {
Michael Kruse811de8a2017-03-06 15:33:05 +0000685 if (Loop *L = LI->getLoopFor(Head)) {
686 L->addBasicBlockToLoop(ThenBlock, *LI);
687 L->addBasicBlockToLoop(Tail, *LI);
688 }
Adam Nemetfdb20592016-03-15 18:06:20 +0000689 }
690
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000691 return CheckTerm;
692}
Tom Stellardaa664d92013-08-06 02:43:45 +0000693
Kostya Serebryany530e2072013-12-23 14:15:08 +0000694void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
695 TerminatorInst **ThenTerm,
696 TerminatorInst **ElseTerm,
697 MDNode *BranchWeights) {
698 BasicBlock *Head = SplitBefore->getParent();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000699 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore->getIterator());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000700 TerminatorInst *HeadOldTerm = Head->getTerminator();
701 LLVMContext &C = Head->getContext();
702 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
703 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
704 *ThenTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000705 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000706 *ElseTerm = BranchInst::Create(Tail, ElseBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000707 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000708 BranchInst *HeadNewTerm =
709 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
710 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
711 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
712}
713
Tom Stellardaa664d92013-08-06 02:43:45 +0000714Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
715 BasicBlock *&IfFalse) {
716 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +0000717 BasicBlock *Pred1 = nullptr;
718 BasicBlock *Pred2 = nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000719
720 if (SomePHI) {
721 if (SomePHI->getNumIncomingValues() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +0000722 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000723 Pred1 = SomePHI->getIncomingBlock(0);
724 Pred2 = SomePHI->getIncomingBlock(1);
725 } else {
726 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
727 if (PI == PE) // No predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000728 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000729 Pred1 = *PI++;
730 if (PI == PE) // Only one predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000731 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000732 Pred2 = *PI++;
733 if (PI != PE) // More than two predecessors
Craig Topperf40110f2014-04-25 05:29:35 +0000734 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000735 }
736
737 // We can only handle branches. Other control flow will be lowered to
738 // branches if possible anyway.
739 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
740 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000741 if (!Pred1Br || !Pred2Br)
742 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000743
744 // Eliminate code duplication by ensuring that Pred1Br is conditional if
745 // either are.
746 if (Pred2Br->isConditional()) {
747 // If both branches are conditional, we don't have an "if statement". In
748 // reality, we could transform this case, but since the condition will be
749 // required anyway, we stand no chance of eliminating it, so the xform is
750 // probably not profitable.
751 if (Pred1Br->isConditional())
Craig Topperf40110f2014-04-25 05:29:35 +0000752 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000753
754 std::swap(Pred1, Pred2);
755 std::swap(Pred1Br, Pred2Br);
756 }
757
758 if (Pred1Br->isConditional()) {
759 // The only thing we have to watch out for here is to make sure that Pred2
760 // doesn't have incoming edges from other blocks. If it does, the condition
761 // doesn't dominate BB.
Craig Topperf40110f2014-04-25 05:29:35 +0000762 if (!Pred2->getSinglePredecessor())
763 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000764
765 // If we found a conditional branch predecessor, make sure that it branches
766 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
767 if (Pred1Br->getSuccessor(0) == BB &&
768 Pred1Br->getSuccessor(1) == Pred2) {
769 IfTrue = Pred1;
770 IfFalse = Pred2;
771 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
772 Pred1Br->getSuccessor(1) == BB) {
773 IfTrue = Pred2;
774 IfFalse = Pred1;
775 } else {
776 // We know that one arm of the conditional goes to BB, so the other must
777 // go somewhere unrelated, and this must not be an "if statement".
Craig Topperf40110f2014-04-25 05:29:35 +0000778 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000779 }
780
781 return Pred1Br->getCondition();
782 }
783
784 // Ok, if we got here, both predecessors end with an unconditional branch to
785 // BB. Don't panic! If both blocks only have a single (identical)
786 // predecessor, and THAT is a conditional branch, then we're all ok!
787 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +0000788 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
789 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000790
791 // Otherwise, if this is a conditional branch, then we can use it!
792 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000793 if (!BI) return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000794
795 assert(BI->isConditional() && "Two successors but not conditional?");
796 if (BI->getSuccessor(0) == Pred1) {
797 IfTrue = Pred1;
798 IfFalse = Pred2;
799 } else {
800 IfTrue = Pred2;
801 IfFalse = Pred1;
802 }
803 return BI->getCondition();
804}