blob: 602e8ba55107a073109533d06c3dca0223d76504 [file] [log] [blame]
Chris Lattner28537df2002-05-07 18:07:59 +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"
Chris Lattnera5b11702008-04-21 01:28:02 +000016#include "llvm/Analysis/AliasAnalysis.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000017#include "llvm/Analysis/CFG.h"
Chris Lattnerf6ae9042011-01-11 08:13:40 +000018#include "llvm/Analysis/LoopInfo.h"
19#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/Constant.h"
21#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000022#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Function.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/IntrinsicInst.h"
26#include "llvm/IR/Type.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000027#include "llvm/IR/ValueHandle.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000028#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Transforms/Scalar.h"
30#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28537df2002-05-07 18:07:59 +000031#include <algorithm>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000032using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000033
Chris Lattner7eb270e2008-12-03 06:40:52 +000034/// DeleteDeadBlock - Delete the specified block, which must have no
35/// predecessors.
36void llvm::DeleteDeadBlock(BasicBlock *BB) {
Chris Lattner37e01362008-12-03 07:45:15 +000037 assert((pred_begin(BB) == pred_end(BB) ||
38 // Can delete self loop.
39 BB->getSinglePredecessor() == BB) && "Block is not dead!");
Chris Lattnerbcc904a2008-12-03 06:37:44 +000040 TerminatorInst *BBTerm = BB->getTerminator();
Jakub Staszak190db2f2013-01-14 23:16:36 +000041
Chris Lattnerbcc904a2008-12-03 06:37:44 +000042 // Loop through all of our successors and make sure they know that one
43 // of their predecessors is going away.
44 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
45 BBTerm->getSuccessor(i)->removePredecessor(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +000046
Chris Lattnerbcc904a2008-12-03 06:37:44 +000047 // Zap all the instructions in the block.
48 while (!BB->empty()) {
49 Instruction &I = BB->back();
50 // If this instruction is used, replace uses with an arbitrary value.
51 // Because control flow can't get here, we don't care what we replace the
52 // value with. Note that since this block is unreachable, and all values
53 // contained within it must dominate their uses, that all uses will
54 // eventually be removed (they are themselves dead).
55 if (!I.use_empty())
Owen Andersonb292b8c2009-07-30 23:03:37 +000056 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattnerbcc904a2008-12-03 06:37:44 +000057 BB->getInstList().pop_back();
58 }
Jakub Staszak190db2f2013-01-14 23:16:36 +000059
Chris Lattnerbcc904a2008-12-03 06:37:44 +000060 // Zap the block!
61 BB->eraseFromParent();
Chris Lattnerbcc904a2008-12-03 06:37:44 +000062}
63
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000064/// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are
65/// any single-entry PHI nodes in it, fold them away. This handles the case
66/// when all entries to the PHI nodes in a block are guaranteed equal, such as
67/// when the block has exactly one predecessor.
Chris Lattnerf6ae9042011-01-11 08:13:40 +000068void llvm::FoldSingleEntryPHINodes(BasicBlock *BB, Pass *P) {
69 if (!isa<PHINode>(BB->begin())) return;
Jakub Staszak190db2f2013-01-14 23:16:36 +000070
Craig Topperf40110f2014-04-25 05:29:35 +000071 AliasAnalysis *AA = nullptr;
72 MemoryDependenceAnalysis *MemDep = nullptr;
Chris Lattnerf6ae9042011-01-11 08:13:40 +000073 if (P) {
74 AA = P->getAnalysisIfAvailable<AliasAnalysis>();
75 MemDep = P->getAnalysisIfAvailable<MemoryDependenceAnalysis>();
76 }
Jakub Staszak190db2f2013-01-14 23:16:36 +000077
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000078 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
79 if (PN->getIncomingValue(0) != PN)
80 PN->replaceAllUsesWith(PN->getIncomingValue(0));
81 else
Owen Andersonb292b8c2009-07-30 23:03:37 +000082 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Jakub Staszak190db2f2013-01-14 23:16:36 +000083
Chris Lattnerf6ae9042011-01-11 08:13:40 +000084 if (MemDep)
85 MemDep->removeInstruction(PN); // Memdep updates AA itself.
86 else if (AA && isa<PointerType>(PN->getType()))
87 AA->deleteValue(PN);
Jakub Staszak190db2f2013-01-14 23:16:36 +000088
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000089 PN->eraseFromParent();
90 }
91}
92
93
Dan Gohmanff089952009-05-02 18:29:22 +000094/// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
95/// is dead. Also recursively delete any operands that become dead as
96/// a result. This includes tracing the def-use list from the PHI to see if
Dan Gohman48f82222009-05-04 22:30:44 +000097/// it is ultimately unused or if it reaches an unused cycle.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +000098bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
Dan Gohmanff089952009-05-02 18:29:22 +000099 // Recursively deleting a PHI may cause multiple PHIs to be deleted
100 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
101 SmallVector<WeakVH, 8> PHIs;
102 for (BasicBlock::iterator I = BB->begin();
103 PHINode *PN = dyn_cast<PHINode>(I); ++I)
104 PHIs.push_back(PN);
105
Dan Gohmancb99fe92010-01-05 15:45:31 +0000106 bool Changed = false;
Dan Gohmanff089952009-05-02 18:29:22 +0000107 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
108 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000109 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
Dan Gohmancb99fe92010-01-05 15:45:31 +0000110
111 return Changed;
Dan Gohmanff089952009-05-02 18:29:22 +0000112}
113
Dan Gohman2d02ff82009-10-31 17:33:01 +0000114/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
115/// if possible. The return value indicates success or failure.
Chris Lattnera1dc1012009-11-01 04:57:33 +0000116bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P) {
Dan Gohman941020e2010-08-17 17:07:02 +0000117 // Don't merge away blocks who have their address taken.
118 if (BB->hasAddressTaken()) return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000119
Dan Gohman941020e2010-08-17 17:07:02 +0000120 // Can't merge if there are multiple predecessors, or no predecessors.
121 BasicBlock *PredBB = BB->getUniquePredecessor();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000122 if (!PredBB) return false;
Dan Gohman941020e2010-08-17 17:07:02 +0000123
Dan Gohman2d02ff82009-10-31 17:33:01 +0000124 // Don't break self-loops.
125 if (PredBB == BB) return false;
126 // Don't break invokes.
127 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000128
Dan Gohman2d02ff82009-10-31 17:33:01 +0000129 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
Chris Lattner930b7162011-01-08 19:08:40 +0000130 BasicBlock *OnlySucc = BB;
Dan Gohman2d02ff82009-10-31 17:33:01 +0000131 for (; SI != SE; ++SI)
132 if (*SI != OnlySucc) {
Craig Topperf40110f2014-04-25 05:29:35 +0000133 OnlySucc = nullptr; // There are multiple distinct successors!
Dan Gohman2d02ff82009-10-31 17:33:01 +0000134 break;
135 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000136
Dan Gohman2d02ff82009-10-31 17:33:01 +0000137 // Can't merge if there are multiple successors.
138 if (!OnlySucc) return false;
Devang Patel0f7a3502008-09-09 01:06:56 +0000139
Dan Gohman2d02ff82009-10-31 17:33:01 +0000140 // Can't merge if there is PHI loop.
141 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
142 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
143 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
144 if (PN->getIncomingValue(i) == PN)
145 return false;
146 } else
147 break;
148 }
149
150 // Begin by getting rid of unneeded PHIs.
Chris Lattner930b7162011-01-08 19:08:40 +0000151 if (isa<PHINode>(BB->front()))
Chris Lattnerf6ae9042011-01-11 08:13:40 +0000152 FoldSingleEntryPHINodes(BB, P);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000153
Owen Andersonc0623812008-07-17 00:01:40 +0000154 // Delete the unconditional branch from the predecessor...
155 PredBB->getInstList().pop_back();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000156
Owen Andersonc0623812008-07-17 00:01:40 +0000157 // Make all PHI nodes that referred to BB now refer to Pred as their
158 // source...
159 BB->replaceAllUsesWith(PredBB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000160
Jay Foad61ea0e42011-06-23 09:09:15 +0000161 // Move all definitions in the successor to the predecessor...
162 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000163
Dan Gohman2d02ff82009-10-31 17:33:01 +0000164 // Inherit predecessors name if it exists.
Owen Anderson27405ef2008-07-17 19:42:29 +0000165 if (!PredBB->hasName())
166 PredBB->takeName(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000167
Owen Andersonc0623812008-07-17 00:01:40 +0000168 // Finally, erase the old block and update dominator info.
169 if (P) {
Chandler Carruth73523022014-01-13 13:07:17 +0000170 if (DominatorTreeWrapperPass *DTWP =
171 P->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
172 DominatorTree &DT = DTWP->getDomTree();
173 if (DomTreeNode *DTN = DT.getNode(BB)) {
174 DomTreeNode *PredDTN = DT.getNode(PredBB);
Jakob Stoklund Olesenf2407aa2011-01-11 22:54:38 +0000175 SmallVector<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
Craig Topperaf0dea12013-07-04 01:31:24 +0000176 for (SmallVectorImpl<DomTreeNode *>::iterator DI = Children.begin(),
Owen Andersonc0623812008-07-17 00:01:40 +0000177 DE = Children.end(); DI != DE; ++DI)
Chandler Carruth73523022014-01-13 13:07:17 +0000178 DT.changeImmediateDominator(*DI, PredDTN);
Owen Andersonc0623812008-07-17 00:01:40 +0000179
Chandler Carruth73523022014-01-13 13:07:17 +0000180 DT.eraseNode(BB);
Owen Andersonc0623812008-07-17 00:01:40 +0000181 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000182
Chris Lattner930b7162011-01-08 19:08:40 +0000183 if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
184 LI->removeBlock(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000185
Chris Lattnere2523b22011-01-11 08:16:49 +0000186 if (MemoryDependenceAnalysis *MD =
187 P->getAnalysisIfAvailable<MemoryDependenceAnalysis>())
188 MD->invalidateCachedPredecessors();
Owen Andersonc0623812008-07-17 00:01:40 +0000189 }
190 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000191
Owen Andersonc0623812008-07-17 00:01:40 +0000192 BB->eraseFromParent();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000193 return true;
Owen Andersonc0623812008-07-17 00:01:40 +0000194}
195
Chris Lattner7ceb0812005-04-21 16:04:49 +0000196/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
197/// with a value, then remove and delete the original instruction.
198///
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000199void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
200 BasicBlock::iterator &BI, Value *V) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000201 Instruction &I = *BI;
Chris Lattner28537df2002-05-07 18:07:59 +0000202 // Replaces all of the uses of the instruction with uses of the value
Chris Lattnerfda72b12002-06-25 16:12:52 +0000203 I.replaceAllUsesWith(V);
Chris Lattner28537df2002-05-07 18:07:59 +0000204
Chris Lattner8dd4cae2007-02-11 01:37:51 +0000205 // Make sure to propagate a name if there is one already.
206 if (I.hasName() && !V->hasName())
207 V->takeName(&I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000208
Misha Brukman7eb05a12003-08-18 14:43:39 +0000209 // Delete the unnecessary instruction now...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000210 BI = BIL.erase(BI);
Chris Lattner28537df2002-05-07 18:07:59 +0000211}
212
213
Chris Lattner7ceb0812005-04-21 16:04:49 +0000214/// ReplaceInstWithInst - Replace the instruction specified by BI with the
215/// instruction specified by I. The original instruction is deleted and BI is
216/// updated to point to the new instruction.
217///
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000218void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
219 BasicBlock::iterator &BI, Instruction *I) {
Craig Toppere73658d2014-04-28 04:05:08 +0000220 assert(I->getParent() == nullptr &&
Chris Lattner28537df2002-05-07 18:07:59 +0000221 "ReplaceInstWithInst: Instruction already inserted into basic block!");
222
223 // Insert the new instruction into the basic block...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000224 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner28537df2002-05-07 18:07:59 +0000225
226 // Replace all uses of the old instruction, and delete it.
227 ReplaceInstWithValue(BIL, BI, I);
228
229 // Move BI back to point to the newly inserted instruction
Chris Lattnerfda72b12002-06-25 16:12:52 +0000230 BI = New;
Chris Lattner28537df2002-05-07 18:07:59 +0000231}
232
Chris Lattner7ceb0812005-04-21 16:04:49 +0000233/// ReplaceInstWithInst - Replace the instruction specified by From with the
234/// instruction specified by To.
235///
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000236void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000237 BasicBlock::iterator BI(From);
238 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner28537df2002-05-07 18:07:59 +0000239}
Chris Lattnerb17274e2002-07-29 22:32:08 +0000240
Jakub Staszak190db2f2013-01-14 23:16:36 +0000241/// SplitEdge - Split the edge connecting specified block. Pass P must
242/// not be NULL.
Bob Wilson3de492e2010-02-16 19:49:17 +0000243BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
Bob Wilsonaff96b22010-02-16 21:06:42 +0000244 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000245
Devang Pateld7767cc2007-07-06 21:39:20 +0000246 // If this is a critical edge, let SplitCriticalEdge do it.
Bob Wilson3de492e2010-02-16 19:49:17 +0000247 TerminatorInst *LatchTerm = BB->getTerminator();
248 if (SplitCriticalEdge(LatchTerm, SuccNum, P))
Devang Pateld7767cc2007-07-06 21:39:20 +0000249 return LatchTerm->getSuccessor(SuccNum);
250
251 // If the edge isn't critical, then BB has a single successor or Succ has a
252 // single pred. Split the block.
Devang Pateld7767cc2007-07-06 21:39:20 +0000253 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
254 // If the successor only has a single pred, split the top of the successor
255 // block.
256 assert(SP == BB && "CFG broken");
Craig Topperf40110f2014-04-25 05:29:35 +0000257 SP = nullptr;
Devang Pateld7767cc2007-07-06 21:39:20 +0000258 return SplitBlock(Succ, Succ->begin(), P);
Devang Pateld7767cc2007-07-06 21:39:20 +0000259 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000260
Chris Lattner30d95f92011-01-08 18:47:43 +0000261 // Otherwise, if BB has a single successor, split it at the bottom of the
262 // block.
263 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
Jakub Staszak190db2f2013-01-14 23:16:36 +0000264 "Should have a single succ!");
Chris Lattner30d95f92011-01-08 18:47:43 +0000265 return SplitBlock(BB, BB->getTerminator(), P);
Devang Pateld7767cc2007-07-06 21:39:20 +0000266}
267
268/// SplitBlock - Split the specified block at the specified instruction - every
269/// thing before SplitPt stays in Old and everything starting with SplitPt moves
270/// to a new block. The two blocks are joined by an unconditional branch and
271/// the loop info is updated.
272///
273BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
Devang Pateld7767cc2007-07-06 21:39:20 +0000274 BasicBlock::iterator SplitIt = SplitPt;
Bill Wendling79a68732011-08-17 21:21:31 +0000275 while (isa<PHINode>(SplitIt) || isa<LandingPadInst>(SplitIt))
Devang Pateld7767cc2007-07-06 21:39:20 +0000276 ++SplitIt;
277 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
278
Dan Gohman3ddbc242009-09-08 15:45:00 +0000279 // The new block lives in whichever loop the old one did. This preserves
280 // LCSSA as well, because we force the split point to be after any PHI nodes.
Chris Lattner930b7162011-01-08 19:08:40 +0000281 if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
Owen Andersoncb4f1562008-10-03 06:55:35 +0000282 if (Loop *L = LI->getLoopFor(Old))
283 L->addBasicBlockToLoop(New, LI->getBase());
Devang Pateld7767cc2007-07-06 21:39:20 +0000284
Chandler Carruth73523022014-01-13 13:07:17 +0000285 if (DominatorTreeWrapperPass *DTWP =
286 P->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
287 DominatorTree &DT = DTWP->getDomTree();
Gabor Greif2f5f6962010-09-10 22:25:58 +0000288 // Old dominates New. New node dominates all other nodes dominated by Old.
Chandler Carruth73523022014-01-13 13:07:17 +0000289 if (DomTreeNode *OldNode = DT.getNode(Old)) {
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000290 std::vector<DomTreeNode *> Children;
291 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000292 I != E; ++I)
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000293 Children.push_back(*I);
Devang Patel186e0d82007-07-19 02:29:24 +0000294
Chandler Carruth73523022014-01-13 13:07:17 +0000295 DomTreeNode *NewNode = DT.addNewBlock(New, Old);
Devang Patel186e0d82007-07-19 02:29:24 +0000296 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
Jakub Staszak190db2f2013-01-14 23:16:36 +0000297 E = Children.end(); I != E; ++I)
Chandler Carruth73523022014-01-13 13:07:17 +0000298 DT.changeImmediateDominator(*I, NewNode);
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000299 }
Evan Chengba930442010-04-05 21:16:25 +0000300 }
Devang Pateld7767cc2007-07-06 21:39:20 +0000301
Devang Pateld7767cc2007-07-06 21:39:20 +0000302 return New;
303}
Chris Lattnera5b11702008-04-21 01:28:02 +0000304
Bill Wendling0a693f42011-08-18 05:25:23 +0000305/// UpdateAnalysisInformation - Update DominatorTree, LoopInfo, and LCCSA
306/// 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,
309 Pass *P, bool &HasLoopExit) {
Bill Wendling0a693f42011-08-18 05:25:23 +0000310 if (!P) return;
311
312 LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>();
Craig Topperf40110f2014-04-25 05:29:35 +0000313 Loop *L = LI ? LI->getLoopFor(OldBB) : nullptr;
Bill Wendling0a693f42011-08-18 05:25:23 +0000314
315 // If we need to preserve loop analyses, collect some information about how
316 // this split will affect loops.
317 bool IsLoopEntry = !!L;
318 bool SplitMakesNewLoopHeader = false;
319 if (LI) {
Bill Wendlingca7d3092011-08-19 00:05:40 +0000320 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
Bill Wendlingec3823d2011-08-18 20:39:32 +0000321 for (ArrayRef<BasicBlock*>::iterator
322 i = Preds.begin(), e = Preds.end(); i != e; ++i) {
323 BasicBlock *Pred = *i;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000324
Bill Wendling0a693f42011-08-18 05:25:23 +0000325 // If we need to preserve LCSSA, determine if any of the preds is a loop
326 // exit.
327 if (PreserveLCSSA)
Bill Wendlingec3823d2011-08-18 20:39:32 +0000328 if (Loop *PL = LI->getLoopFor(Pred))
Bill Wendling0a693f42011-08-18 05:25:23 +0000329 if (!PL->contains(OldBB))
330 HasLoopExit = true;
331
332 // If we need to preserve LoopInfo, note whether any of the preds crosses
333 // an interesting loop boundary.
334 if (!L) continue;
Bill Wendlingec3823d2011-08-18 20:39:32 +0000335 if (L->contains(Pred))
Bill Wendling0a693f42011-08-18 05:25:23 +0000336 IsLoopEntry = false;
337 else
338 SplitMakesNewLoopHeader = true;
339 }
340 }
341
342 // Update dominator tree if available.
Chandler Carruth73523022014-01-13 13:07:17 +0000343 if (DominatorTreeWrapperPass *DTWP =
344 P->getAnalysisIfAvailable<DominatorTreeWrapperPass>())
345 DTWP->getDomTree().splitBlock(NewBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000346
347 if (!L) return;
348
349 if (IsLoopEntry) {
350 // Add the new block to the nearest enclosing loop (and not an adjacent
351 // loop). To find this, examine each of the predecessors and determine which
352 // loops enclose them, and select the most-nested loop which contains the
353 // loop containing the block being split.
Craig Topperf40110f2014-04-25 05:29:35 +0000354 Loop *InnermostPredLoop = nullptr;
Bill Wendlingec3823d2011-08-18 20:39:32 +0000355 for (ArrayRef<BasicBlock*>::iterator
356 i = Preds.begin(), e = Preds.end(); i != e; ++i) {
357 BasicBlock *Pred = *i;
358 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
Bill Wendling0a693f42011-08-18 05:25:23 +0000359 // Seek a loop which actually contains the block being split (to avoid
360 // adjacent loops).
361 while (PredLoop && !PredLoop->contains(OldBB))
362 PredLoop = PredLoop->getParentLoop();
363
364 // Select the most-nested of these loops which contains the block.
365 if (PredLoop && PredLoop->contains(OldBB) &&
366 (!InnermostPredLoop ||
367 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
368 InnermostPredLoop = PredLoop;
369 }
Bill Wendlingec3823d2011-08-18 20:39:32 +0000370 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000371
372 if (InnermostPredLoop)
373 InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
374 } else {
375 L->addBasicBlockToLoop(NewBB, LI->getBase());
376 if (SplitMakesNewLoopHeader)
377 L->moveToHeader(NewBB);
378 }
379}
380
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000381/// UpdatePHINodes - Update the PHI nodes in OrigBB to include the values coming
382/// from NewBB. This also updates AliasAnalysis, if available.
383static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
384 ArrayRef<BasicBlock*> Preds, BranchInst *BI,
385 Pass *P, bool HasLoopExit) {
386 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
Craig Topperf40110f2014-04-25 05:29:35 +0000387 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : nullptr;
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000388 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000389 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
390 PHINode *PN = cast<PHINode>(I++);
391
392 // Check to see if all of the values coming in are the same. If so, we
393 // don't need to create a new PHI node, unless it's needed for LCSSA.
Craig Topperf40110f2014-04-25 05:29:35 +0000394 Value *InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000395 if (!HasLoopExit) {
396 InVal = PN->getIncomingValueForBlock(Preds[0]);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000397 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
398 if (!PredSet.count(PN->getIncomingBlock(i)))
399 continue;
400 if (!InVal)
401 InVal = PN->getIncomingValue(i);
402 else if (InVal != PN->getIncomingValue(i)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000403 InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000404 break;
405 }
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000406 }
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000407 }
408
409 if (InVal) {
410 // If all incoming values for the new PHI would be the same, just don't
411 // make a new PHI. Instead, just remove the incoming values from the old
412 // PHI.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000413
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000414 // NOTE! This loop walks backwards for a reason! First off, this minimizes
415 // the cost of removal if we end up removing a large number of values, and
416 // second off, this ensures that the indices for the incoming values
417 // aren't invalidated when we remove one.
418 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
419 if (PredSet.count(PN->getIncomingBlock(i)))
420 PN->removeIncomingValue(i, false);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000421
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000422 // Add an incoming value to the PHI node in the loop for the preheader
423 // edge.
424 PN->addIncoming(InVal, NewBB);
425 continue;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000426 }
427
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000428 // If the values coming into the block are not the same, we need a new
429 // PHI.
430 // Create the new PHI node, insert it into NewBB at the end of the block
431 PHINode *NewPHI =
432 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
433 if (AA)
434 AA->copyValue(PN, NewPHI);
435
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
Chris Lattnera5b11702008-04-21 01:28:02 +0000452/// SplitBlockPredecessors - This method transforms BB by introducing a new
453/// basic block into the function, and moving some of the predecessors of BB to
454/// be predecessors of the new block. The new predecessors are indicated by the
455/// Preds array, which has NumPreds elements in it. The new block is given a
456/// suffix of 'Suffix'.
457///
Dan Gohman3ddbc242009-09-08 15:45:00 +0000458/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
Cameron Zwarichb7036542011-01-18 04:11:31 +0000459/// LoopInfo, and LCCSA but no other analyses. In particular, it does not
460/// preserve LoopSimplify (because it's complicated to handle the case where one
461/// of the edges being split is an exit of a loop with other exits).
Dan Gohman3ddbc242009-09-08 15:45:00 +0000462///
Jakub Staszak190db2f2013-01-14 23:16:36 +0000463BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000464 ArrayRef<BasicBlock*> Preds,
465 const char *Suffix, Pass *P) {
Chris Lattnera5b11702008-04-21 01:28:02 +0000466 // Create new basic block, insert right before the original block.
Owen Anderson55f1c092009-08-13 21:58:54 +0000467 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
468 BB->getParent(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000469
Chris Lattnera5b11702008-04-21 01:28:02 +0000470 // The new block unconditionally branches to the old block.
471 BranchInst *BI = BranchInst::Create(BB, NewBB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000472
Chris Lattnera5b11702008-04-21 01:28:02 +0000473 // Move the edges from Preds to point to NewBB instead of BB.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000474 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Dan Gohman00c79382009-11-05 18:25:44 +0000475 // This is slightly more strict than necessary; the minimum requirement
476 // is that there be no more than one indirectbr branching to BB. And
477 // all BlockAddress uses would need to be updated.
478 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
479 "Cannot split an edge from an IndirectBrInst");
Chris Lattnera5b11702008-04-21 01:28:02 +0000480 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000481 }
482
Chris Lattnera5b11702008-04-21 01:28:02 +0000483 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
484 // node becomes an incoming value for BB's phi node. However, if the Preds
485 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
486 // account for the newly created predecessor.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000487 if (Preds.size() == 0) {
Chris Lattnera5b11702008-04-21 01:28:02 +0000488 // Insert dummy values as the incoming value.
489 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000490 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattnera5b11702008-04-21 01:28:02 +0000491 return NewBB;
492 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000493
Bill Wendling0a693f42011-08-18 05:25:23 +0000494 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
495 bool HasLoopExit = false;
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000496 UpdateAnalysisInformation(BB, NewBB, Preds, P, HasLoopExit);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000497
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000498 // Update the PHI nodes in BB with the values coming from NewBB.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000499 UpdatePHINodes(BB, NewBB, Preds, BI, P, HasLoopExit);
Chris Lattnera5b11702008-04-21 01:28:02 +0000500 return NewBB;
501}
Chris Lattner72f16e72008-11-27 08:10:05 +0000502
Bill Wendlingca7d3092011-08-19 00:05:40 +0000503/// SplitLandingPadPredecessors - This method transforms the landing pad,
504/// OrigBB, by introducing two new basic blocks into the function. One of those
505/// new basic blocks gets the predecessors listed in Preds. The other basic
506/// block gets the remaining predecessors of OrigBB. The landingpad instruction
507/// OrigBB is clone into both of the new basic blocks. The new blocks are given
508/// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000509///
Bill Wendlingca7d3092011-08-19 00:05:40 +0000510/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
511/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular,
512/// it does not preserve LoopSimplify (because it's complicated to handle the
513/// case where one of the edges being split is an exit of a loop with other
514/// exits).
Jakub Staszak190db2f2013-01-14 23:16:36 +0000515///
Bill Wendlingca7d3092011-08-19 00:05:40 +0000516void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
517 ArrayRef<BasicBlock*> Preds,
518 const char *Suffix1, const char *Suffix2,
519 Pass *P,
520 SmallVectorImpl<BasicBlock*> &NewBBs) {
521 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
522
523 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
524 // it right before the original block.
525 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
526 OrigBB->getName() + Suffix1,
527 OrigBB->getParent(), OrigBB);
528 NewBBs.push_back(NewBB1);
529
530 // The new block unconditionally branches to the old block.
531 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
532
533 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
534 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
535 // This is slightly more strict than necessary; the minimum requirement
536 // is that there be no more than one indirectbr branching to BB. And
537 // all BlockAddress uses would need to be updated.
538 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
539 "Cannot split an edge from an IndirectBrInst");
540 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
541 }
542
543 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
544 bool HasLoopExit = false;
545 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, P, HasLoopExit);
546
547 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
548 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, P, HasLoopExit);
549
Bill Wendlingca7d3092011-08-19 00:05:40 +0000550 // Move the remaining edges from OrigBB to point to NewBB2.
551 SmallVector<BasicBlock*, 8> NewBB2Preds;
552 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
553 i != e; ) {
554 BasicBlock *Pred = *i++;
Bill Wendling38d81302011-08-19 23:46:30 +0000555 if (Pred == NewBB1) continue;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000556 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
557 "Cannot split an edge from an IndirectBrInst");
Bill Wendlingca7d3092011-08-19 00:05:40 +0000558 NewBB2Preds.push_back(Pred);
559 e = pred_end(OrigBB);
560 }
561
Craig Topperf40110f2014-04-25 05:29:35 +0000562 BasicBlock *NewBB2 = nullptr;
Bill Wendling38d81302011-08-19 23:46:30 +0000563 if (!NewBB2Preds.empty()) {
564 // Create another basic block for the rest of OrigBB's predecessors.
565 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
566 OrigBB->getName() + Suffix2,
567 OrigBB->getParent(), OrigBB);
568 NewBBs.push_back(NewBB2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000569
Bill Wendling38d81302011-08-19 23:46:30 +0000570 // The new block unconditionally branches to the old block.
571 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
572
573 // Move the remaining edges from OrigBB to point to NewBB2.
574 for (SmallVectorImpl<BasicBlock*>::iterator
575 i = NewBB2Preds.begin(), e = NewBB2Preds.end(); i != e; ++i)
576 (*i)->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
577
578 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
579 HasLoopExit = false;
580 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, P, HasLoopExit);
581
582 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
583 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, P, HasLoopExit);
584 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000585
586 LandingPadInst *LPad = OrigBB->getLandingPadInst();
587 Instruction *Clone1 = LPad->clone();
588 Clone1->setName(Twine("lpad") + Suffix1);
589 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
590
Bill Wendling38d81302011-08-19 23:46:30 +0000591 if (NewBB2) {
592 Instruction *Clone2 = LPad->clone();
593 Clone2->setName(Twine("lpad") + Suffix2);
594 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000595
Bill Wendling38d81302011-08-19 23:46:30 +0000596 // Create a PHI node for the two cloned landingpad instructions.
597 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
598 PN->addIncoming(Clone1, NewBB1);
599 PN->addIncoming(Clone2, NewBB2);
600 LPad->replaceAllUsesWith(PN);
601 LPad->eraseFromParent();
602 } else {
603 // There is no second clone. Just replace the landing pad with the first
604 // clone.
605 LPad->replaceAllUsesWith(Clone1);
606 LPad->eraseFromParent();
607 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000608}
609
Evan Chengd983eba2011-01-29 04:46:23 +0000610/// FoldReturnIntoUncondBranch - This method duplicates the specified return
611/// instruction into a predecessor which ends in an unconditional branch. If
612/// the return instruction returns a value defined by a PHI, propagate the
613/// right value into the return. It returns the new return instruction in the
614/// predecessor.
615ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
616 BasicBlock *Pred) {
617 Instruction *UncondBranch = Pred->getTerminator();
618 // Clone the return and add it to the end of the predecessor.
619 Instruction *NewRet = RI->clone();
620 Pred->getInstList().push_back(NewRet);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000621
Evan Chengd983eba2011-01-29 04:46:23 +0000622 // If the return instruction returns a value, and if the value was a
623 // PHI node in "BB", propagate the right value into the return.
624 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
Evan Cheng249716e2012-07-27 21:21:26 +0000625 i != e; ++i) {
626 Value *V = *i;
Craig Topperf40110f2014-04-25 05:29:35 +0000627 Instruction *NewBC = nullptr;
Evan Cheng249716e2012-07-27 21:21:26 +0000628 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
629 // Return value might be bitcasted. Clone and insert it before the
630 // return instruction.
631 V = BCI->getOperand(0);
632 NewBC = BCI->clone();
633 Pred->getInstList().insert(NewRet, NewBC);
634 *i = NewBC;
635 }
636 if (PHINode *PN = dyn_cast<PHINode>(V)) {
637 if (PN->getParent() == BB) {
638 if (NewBC)
639 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
640 else
641 *i = PN->getIncomingValueForBlock(Pred);
642 }
643 }
644 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000645
Evan Chengd983eba2011-01-29 04:46:23 +0000646 // Update any PHI nodes in the returning block to realize that we no
647 // longer branch to them.
648 BB->removePredecessor(Pred);
649 UncondBranch->eraseFromParent();
650 return cast<ReturnInst>(NewRet);
Chris Lattner351134b2009-05-04 02:25:58 +0000651}
Devang Patela8e74112011-04-29 22:28:59 +0000652
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000653/// SplitBlockAndInsertIfThen - Split the containing block at the
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000654/// specified instruction - everything before and including SplitBefore stays
655/// in the old basic block, and everything after SplitBefore is moved to a
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000656/// new block. The two blocks are connected by a conditional branch
657/// (with value of Cmp being the condition).
658/// Before:
659/// Head
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000660/// SplitBefore
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000661/// Tail
662/// After:
663/// Head
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000664/// if (Cond)
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000665/// ThenBlock
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000666/// SplitBefore
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000667/// Tail
668///
669/// If Unreachable is true, then ThenBlock ends with
670/// UnreachableInst, otherwise it branches to Tail.
671/// Returns the NewBasicBlock's terminator.
672
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000673TerminatorInst *llvm::SplitBlockAndInsertIfThen(Value *Cond,
674 Instruction *SplitBefore,
675 bool Unreachable,
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000676 MDNode *BranchWeights,
677 DominatorTree *DT) {
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000678 BasicBlock *Head = SplitBefore->getParent();
679 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
680 TerminatorInst *HeadOldTerm = Head->getTerminator();
681 LLVMContext &C = Head->getContext();
682 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
683 TerminatorInst *CheckTerm;
684 if (Unreachable)
685 CheckTerm = new UnreachableInst(C, ThenBlock);
686 else
687 CheckTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000688 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000689 BranchInst *HeadNewTerm =
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000690 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000691 HeadNewTerm->setDebugLoc(SplitBefore->getDebugLoc());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000692 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
693 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000694
695 if (DT) {
696 if (DomTreeNode *OldNode = DT->getNode(Head)) {
697 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
698
699 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
700 for (auto Child : Children)
701 DT->changeImmediateDominator(Child, NewNode);
702
703 // Head dominates ThenBlock.
704 DT->addNewBlock(ThenBlock, Head);
705 }
706 }
707
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000708 return CheckTerm;
709}
Tom Stellardaa664d92013-08-06 02:43:45 +0000710
Kostya Serebryany530e2072013-12-23 14:15:08 +0000711/// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
712/// but also creates the ElseBlock.
713/// Before:
714/// Head
715/// SplitBefore
716/// Tail
717/// After:
718/// Head
719/// if (Cond)
720/// ThenBlock
721/// else
722/// ElseBlock
723/// SplitBefore
724/// Tail
725void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
726 TerminatorInst **ThenTerm,
727 TerminatorInst **ElseTerm,
728 MDNode *BranchWeights) {
729 BasicBlock *Head = SplitBefore->getParent();
730 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
731 TerminatorInst *HeadOldTerm = Head->getTerminator();
732 LLVMContext &C = Head->getContext();
733 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
734 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
735 *ThenTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000736 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000737 *ElseTerm = BranchInst::Create(Tail, ElseBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000738 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000739 BranchInst *HeadNewTerm =
740 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000741 HeadNewTerm->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000742 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
743 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
744}
745
746
Tom Stellardaa664d92013-08-06 02:43:45 +0000747/// GetIfCondition - Given a basic block (BB) with two predecessors,
748/// check to see if the merge at this block is due
749/// to an "if condition". If so, return the boolean condition that determines
750/// which entry into BB will be taken. Also, return by references the block
751/// that will be entered from if the condition is true, and the block that will
752/// be entered if the condition is false.
753///
754/// This does no checking to see if the true/false blocks have large or unsavory
755/// instructions in them.
756Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
757 BasicBlock *&IfFalse) {
758 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +0000759 BasicBlock *Pred1 = nullptr;
760 BasicBlock *Pred2 = nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000761
762 if (SomePHI) {
763 if (SomePHI->getNumIncomingValues() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +0000764 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000765 Pred1 = SomePHI->getIncomingBlock(0);
766 Pred2 = SomePHI->getIncomingBlock(1);
767 } else {
768 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
769 if (PI == PE) // No predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000770 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000771 Pred1 = *PI++;
772 if (PI == PE) // Only one predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000773 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000774 Pred2 = *PI++;
775 if (PI != PE) // More than two predecessors
Craig Topperf40110f2014-04-25 05:29:35 +0000776 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000777 }
778
779 // We can only handle branches. Other control flow will be lowered to
780 // branches if possible anyway.
781 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
782 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000783 if (!Pred1Br || !Pred2Br)
784 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000785
786 // Eliminate code duplication by ensuring that Pred1Br is conditional if
787 // either are.
788 if (Pred2Br->isConditional()) {
789 // If both branches are conditional, we don't have an "if statement". In
790 // reality, we could transform this case, but since the condition will be
791 // required anyway, we stand no chance of eliminating it, so the xform is
792 // probably not profitable.
793 if (Pred1Br->isConditional())
Craig Topperf40110f2014-04-25 05:29:35 +0000794 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000795
796 std::swap(Pred1, Pred2);
797 std::swap(Pred1Br, Pred2Br);
798 }
799
800 if (Pred1Br->isConditional()) {
801 // The only thing we have to watch out for here is to make sure that Pred2
802 // doesn't have incoming edges from other blocks. If it does, the condition
803 // doesn't dominate BB.
Craig Topperf40110f2014-04-25 05:29:35 +0000804 if (!Pred2->getSinglePredecessor())
805 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000806
807 // If we found a conditional branch predecessor, make sure that it branches
808 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
809 if (Pred1Br->getSuccessor(0) == BB &&
810 Pred1Br->getSuccessor(1) == Pred2) {
811 IfTrue = Pred1;
812 IfFalse = Pred2;
813 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
814 Pred1Br->getSuccessor(1) == BB) {
815 IfTrue = Pred2;
816 IfFalse = Pred1;
817 } else {
818 // We know that one arm of the conditional goes to BB, so the other must
819 // go somewhere unrelated, and this must not be an "if statement".
Craig Topperf40110f2014-04-25 05:29:35 +0000820 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000821 }
822
823 return Pred1Br->getCondition();
824 }
825
826 // Ok, if we got here, both predecessors end with an unconditional branch to
827 // BB. Don't panic! If both blocks only have a single (identical)
828 // predecessor, and THAT is a conditional branch, then we're all ok!
829 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +0000830 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
831 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000832
833 // Otherwise, if this is a conditional branch, then we can use it!
834 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000835 if (!BI) return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000836
837 assert(BI->isConditional() && "Two successors but not conditional?");
838 if (BI->getSuccessor(0) == Pred1) {
839 IfTrue = Pred1;
840 IfFalse = Pred2;
841 } else {
842 IfTrue = Pred2;
843 IfFalse = Pred1;
844 }
845 return BI->getCondition();
846}