blob: c761934162da4298e85c477bc335d855db4697e0 [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.
Chandler Carruth5eee8952015-01-18 01:45:07 +000068void llvm::FoldSingleEntryPHINodes(BasicBlock *BB, AliasAnalysis *AA,
69 MemoryDependenceAnalysis *MemDep) {
Chris Lattnerf6ae9042011-01-11 08:13:40 +000070 if (!isa<PHINode>(BB->begin())) return;
Jakub Staszak190db2f2013-01-14 23:16:36 +000071
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000072 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
73 if (PN->getIncomingValue(0) != PN)
74 PN->replaceAllUsesWith(PN->getIncomingValue(0));
75 else
Owen Andersonb292b8c2009-07-30 23:03:37 +000076 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Jakub Staszak190db2f2013-01-14 23:16:36 +000077
Chris Lattnerf6ae9042011-01-11 08:13:40 +000078 if (MemDep)
79 MemDep->removeInstruction(PN); // Memdep updates AA itself.
80 else if (AA && isa<PointerType>(PN->getType()))
81 AA->deleteValue(PN);
Jakub Staszak190db2f2013-01-14 23:16:36 +000082
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000083 PN->eraseFromParent();
84 }
85}
86
87
Dan Gohmanff089952009-05-02 18:29:22 +000088/// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
89/// is dead. Also recursively delete any operands that become dead as
90/// a result. This includes tracing the def-use list from the PHI to see if
Dan Gohman48f82222009-05-04 22:30:44 +000091/// it is ultimately unused or if it reaches an unused cycle.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +000092bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
Dan Gohmanff089952009-05-02 18:29:22 +000093 // Recursively deleting a PHI may cause multiple PHIs to be deleted
94 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
95 SmallVector<WeakVH, 8> PHIs;
96 for (BasicBlock::iterator I = BB->begin();
97 PHINode *PN = dyn_cast<PHINode>(I); ++I)
98 PHIs.push_back(PN);
99
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
Dan Gohman2d02ff82009-10-31 17:33:01 +0000108/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
109/// if possible. The return value indicates success or failure.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000110bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT,
111 LoopInfo *LI, AliasAnalysis *AA,
112 MemoryDependenceAnalysis *MemDep) {
Dan Gohman941020e2010-08-17 17:07:02 +0000113 // Don't merge away blocks who have their address taken.
114 if (BB->hasAddressTaken()) return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000115
Dan Gohman941020e2010-08-17 17:07:02 +0000116 // Can't merge if there are multiple predecessors, or no predecessors.
117 BasicBlock *PredBB = BB->getUniquePredecessor();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000118 if (!PredBB) return false;
Dan Gohman941020e2010-08-17 17:07:02 +0000119
Dan Gohman2d02ff82009-10-31 17:33:01 +0000120 // Don't break self-loops.
121 if (PredBB == BB) return false;
David Majnemerae2ffc82015-07-10 07:00:44 +0000122 // Don't break unwinding instructions.
123 if (PredBB->getTerminator()->isExceptional())
124 return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000125
Dan Gohman2d02ff82009-10-31 17:33:01 +0000126 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
Chris Lattner930b7162011-01-08 19:08:40 +0000127 BasicBlock *OnlySucc = BB;
Dan Gohman2d02ff82009-10-31 17:33:01 +0000128 for (; SI != SE; ++SI)
129 if (*SI != OnlySucc) {
Craig Topperf40110f2014-04-25 05:29:35 +0000130 OnlySucc = nullptr; // There are multiple distinct successors!
Dan Gohman2d02ff82009-10-31 17:33:01 +0000131 break;
132 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000133
Dan Gohman2d02ff82009-10-31 17:33:01 +0000134 // Can't merge if there are multiple successors.
135 if (!OnlySucc) return false;
Devang Patel0f7a3502008-09-09 01:06:56 +0000136
Dan Gohman2d02ff82009-10-31 17:33:01 +0000137 // Can't merge if there is PHI loop.
138 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
139 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000140 for (Value *IncValue : PN->incoming_values())
141 if (IncValue == PN)
Dan Gohman2d02ff82009-10-31 17:33:01 +0000142 return false;
143 } else
144 break;
145 }
146
147 // Begin by getting rid of unneeded PHIs.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000148 if (isa<PHINode>(BB->front()))
Chandler Carruth5eee8952015-01-18 01:45:07 +0000149 FoldSingleEntryPHINodes(BB, AA, MemDep);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000150
Owen Andersonc0623812008-07-17 00:01:40 +0000151 // Delete the unconditional branch from the predecessor...
152 PredBB->getInstList().pop_back();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000153
Owen Andersonc0623812008-07-17 00:01:40 +0000154 // Make all PHI nodes that referred to BB now refer to Pred as their
155 // source...
156 BB->replaceAllUsesWith(PredBB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000157
Jay Foad61ea0e42011-06-23 09:09:15 +0000158 // Move all definitions in the successor to the predecessor...
159 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000160
Dan Gohman2d02ff82009-10-31 17:33:01 +0000161 // Inherit predecessors name if it exists.
Owen Anderson27405ef2008-07-17 19:42:29 +0000162 if (!PredBB->hasName())
163 PredBB->takeName(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000164
Owen Andersonc0623812008-07-17 00:01:40 +0000165 // Finally, erase the old block and update dominator info.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000166 if (DT)
167 if (DomTreeNode *DTN = DT->getNode(BB)) {
168 DomTreeNode *PredDTN = DT->getNode(PredBB);
169 SmallVector<DomTreeNode *, 8> Children(DTN->begin(), DTN->end());
170 for (SmallVectorImpl<DomTreeNode *>::iterator DI = Children.begin(),
171 DE = Children.end();
172 DI != DE; ++DI)
173 DT->changeImmediateDominator(*DI, PredDTN);
Owen Andersonc0623812008-07-17 00:01:40 +0000174
Chandler Carruthb5c11532015-01-18 02:11:23 +0000175 DT->eraseNode(BB);
Owen Andersonc0623812008-07-17 00:01:40 +0000176 }
Chandler Carruthb5c11532015-01-18 02:11:23 +0000177
178 if (LI)
179 LI->removeBlock(BB);
180
181 if (MemDep)
182 MemDep->invalidateCachedPredecessors();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000183
Owen Andersonc0623812008-07-17 00:01:40 +0000184 BB->eraseFromParent();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000185 return true;
Owen Andersonc0623812008-07-17 00:01:40 +0000186}
187
Chris Lattner7ceb0812005-04-21 16:04:49 +0000188/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
189/// with a value, then remove and delete the original instruction.
190///
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000191void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
192 BasicBlock::iterator &BI, Value *V) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000193 Instruction &I = *BI;
Chris Lattner28537df2002-05-07 18:07:59 +0000194 // Replaces all of the uses of the instruction with uses of the value
Chris Lattnerfda72b12002-06-25 16:12:52 +0000195 I.replaceAllUsesWith(V);
Chris Lattner28537df2002-05-07 18:07:59 +0000196
Chris Lattner8dd4cae2007-02-11 01:37:51 +0000197 // Make sure to propagate a name if there is one already.
198 if (I.hasName() && !V->hasName())
199 V->takeName(&I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000200
Misha Brukman7eb05a12003-08-18 14:43:39 +0000201 // Delete the unnecessary instruction now...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000202 BI = BIL.erase(BI);
Chris Lattner28537df2002-05-07 18:07:59 +0000203}
204
205
Chris Lattner7ceb0812005-04-21 16:04:49 +0000206/// ReplaceInstWithInst - Replace the instruction specified by BI with the
207/// instruction specified by I. The original instruction is deleted and BI is
208/// updated to point to the new instruction.
209///
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000210void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
211 BasicBlock::iterator &BI, Instruction *I) {
Craig Toppere73658d2014-04-28 04:05:08 +0000212 assert(I->getParent() == nullptr &&
Chris Lattner28537df2002-05-07 18:07:59 +0000213 "ReplaceInstWithInst: Instruction already inserted into basic block!");
214
Alexey Samsonov19ffcb92015-06-23 21:00:08 +0000215 // Copy debug location to newly added instruction, if it wasn't already set
216 // by the caller.
217 if (!I->getDebugLoc())
218 I->setDebugLoc(BI->getDebugLoc());
219
Chris Lattner28537df2002-05-07 18:07:59 +0000220 // Insert the new instruction into the basic block...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000221 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner28537df2002-05-07 18:07:59 +0000222
223 // Replace all uses of the old instruction, and delete it.
224 ReplaceInstWithValue(BIL, BI, I);
225
226 // Move BI back to point to the newly inserted instruction
Chris Lattnerfda72b12002-06-25 16:12:52 +0000227 BI = New;
Chris Lattner28537df2002-05-07 18:07:59 +0000228}
229
Chris Lattner7ceb0812005-04-21 16:04:49 +0000230/// ReplaceInstWithInst - Replace the instruction specified by From with the
231/// instruction specified by To.
232///
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000233void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000234 BasicBlock::iterator BI(From);
235 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner28537df2002-05-07 18:07:59 +0000236}
Chris Lattnerb17274e2002-07-29 22:32:08 +0000237
Jakub Staszak190db2f2013-01-14 23:16:36 +0000238/// SplitEdge - Split the edge connecting specified block. Pass P must
239/// not be NULL.
Chandler Carruthd4500562015-01-19 12:36:53 +0000240BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
241 LoopInfo *LI) {
Bob Wilsonaff96b22010-02-16 21:06:42 +0000242 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000243
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000244 // If this is a critical edge, let SplitCriticalEdge do it.
245 TerminatorInst *LatchTerm = BB->getTerminator();
Chandler Carruthd4500562015-01-19 12:36:53 +0000246 if (SplitCriticalEdge(LatchTerm, SuccNum, CriticalEdgeSplittingOptions(DT, LI)
247 .setPreserveLCSSA()))
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000248 return LatchTerm->getSuccessor(SuccNum);
Chandler Carruth32c52c72015-01-18 02:39:37 +0000249
Devang Pateld7767cc2007-07-06 21:39:20 +0000250 // If the edge isn't critical, then BB has a single successor or Succ has a
251 // single pred. Split the block.
Devang Pateld7767cc2007-07-06 21:39:20 +0000252 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
253 // If the successor only has a single pred, split the top of the successor
254 // block.
255 assert(SP == BB && "CFG broken");
Craig Topperf40110f2014-04-25 05:29:35 +0000256 SP = nullptr;
Chandler Carruth32c52c72015-01-18 02:39:37 +0000257 return SplitBlock(Succ, Succ->begin(), DT, LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000258 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000259
Chris Lattner30d95f92011-01-08 18:47:43 +0000260 // Otherwise, if BB has a single successor, split it at the bottom of the
261 // block.
262 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
Jakub Staszak190db2f2013-01-14 23:16:36 +0000263 "Should have a single succ!");
Chandler Carruth32c52c72015-01-18 02:39:37 +0000264 return SplitBlock(BB, BB->getTerminator(), DT, LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000265}
266
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000267unsigned
268llvm::SplitAllCriticalEdges(Function &F,
269 const CriticalEdgeSplittingOptions &Options) {
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000270 unsigned NumBroken = 0;
271 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
272 TerminatorInst *TI = I->getTerminator();
273 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
274 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000275 if (SplitCriticalEdge(TI, i, Options))
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000276 ++NumBroken;
277 }
278 return NumBroken;
279}
280
Devang Pateld7767cc2007-07-06 21:39:20 +0000281/// SplitBlock - Split the specified block at the specified instruction - every
282/// thing before SplitPt stays in Old and everything starting with SplitPt moves
283/// to a new block. The two blocks are joined by an unconditional branch and
284/// the loop info is updated.
285///
Chandler Carruth32c52c72015-01-18 02:39:37 +0000286BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
287 DominatorTree *DT, LoopInfo *LI) {
Devang Pateld7767cc2007-07-06 21:39:20 +0000288 BasicBlock::iterator SplitIt = SplitPt;
Bill Wendling79a68732011-08-17 21:21:31 +0000289 while (isa<PHINode>(SplitIt) || isa<LandingPadInst>(SplitIt))
Devang Pateld7767cc2007-07-06 21:39:20 +0000290 ++SplitIt;
291 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
292
Dan Gohman3ddbc242009-09-08 15:45:00 +0000293 // The new block lives in whichever loop the old one did. This preserves
294 // LCSSA as well, because we force the split point to be after any PHI nodes.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000295 if (LI)
296 if (Loop *L = LI->getLoopFor(Old))
297 L->addBasicBlockToLoop(New, *LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000298
Chandler Carruth32c52c72015-01-18 02:39:37 +0000299 if (DT)
Gabor Greif2f5f6962010-09-10 22:25:58 +0000300 // Old dominates New. New node dominates all other nodes dominated by Old.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000301 if (DomTreeNode *OldNode = DT->getNode(Old)) {
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000302 std::vector<DomTreeNode *> Children;
303 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000304 I != E; ++I)
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000305 Children.push_back(*I);
Devang Patel186e0d82007-07-19 02:29:24 +0000306
Chandler Carruth32c52c72015-01-18 02:39:37 +0000307 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
Devang Patel186e0d82007-07-19 02:29:24 +0000308 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
Jakub Staszak190db2f2013-01-14 23:16:36 +0000309 E = Children.end(); I != E; ++I)
Chandler Carruth32c52c72015-01-18 02:39:37 +0000310 DT->changeImmediateDominator(*I, NewNode);
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000311 }
Devang Pateld7767cc2007-07-06 21:39:20 +0000312
Devang Pateld7767cc2007-07-06 21:39:20 +0000313 return New;
314}
Chris Lattnera5b11702008-04-21 01:28:02 +0000315
Bill Wendling0a693f42011-08-18 05:25:23 +0000316/// UpdateAnalysisInformation - Update DominatorTree, LoopInfo, and LCCSA
317/// analysis information.
Bill Wendling60291352011-08-18 17:57:57 +0000318static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
Bill Wendlingec3823d2011-08-18 20:39:32 +0000319 ArrayRef<BasicBlock *> Preds,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000320 DominatorTree *DT, LoopInfo *LI,
321 bool PreserveLCSSA, bool &HasLoopExit) {
322 // Update dominator tree if available.
323 if (DT)
324 DT->splitBlock(NewBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000325
Chandler Carruthb5797b62015-01-18 09:21:15 +0000326 // The rest of the logic is only relevant for updating the loop structures.
327 if (!LI)
328 return;
329
330 Loop *L = LI->getLoopFor(OldBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000331
332 // If we need to preserve loop analyses, collect some information about how
333 // this split will affect loops.
334 bool IsLoopEntry = !!L;
335 bool SplitMakesNewLoopHeader = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000336 for (ArrayRef<BasicBlock *>::iterator i = Preds.begin(), e = Preds.end();
337 i != e; ++i) {
338 BasicBlock *Pred = *i;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000339
Chandler Carruthb5797b62015-01-18 09:21:15 +0000340 // If we need to preserve LCSSA, determine if any of the preds is a loop
341 // exit.
342 if (PreserveLCSSA)
343 if (Loop *PL = LI->getLoopFor(Pred))
344 if (!PL->contains(OldBB))
345 HasLoopExit = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000346
Chandler Carruthb5797b62015-01-18 09:21:15 +0000347 // If we need to preserve LoopInfo, note whether any of the preds crosses
348 // an interesting loop boundary.
349 if (!L)
350 continue;
351 if (L->contains(Pred))
352 IsLoopEntry = false;
353 else
354 SplitMakesNewLoopHeader = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000355 }
356
Chandler Carruthb5797b62015-01-18 09:21:15 +0000357 // Unless we have a loop for OldBB, nothing else to do here.
358 if (!L)
359 return;
Bill Wendling0a693f42011-08-18 05:25:23 +0000360
361 if (IsLoopEntry) {
362 // Add the new block to the nearest enclosing loop (and not an adjacent
363 // loop). To find this, examine each of the predecessors and determine which
364 // loops enclose them, and select the most-nested loop which contains the
365 // loop containing the block being split.
Craig Topperf40110f2014-04-25 05:29:35 +0000366 Loop *InnermostPredLoop = nullptr;
Bill Wendlingec3823d2011-08-18 20:39:32 +0000367 for (ArrayRef<BasicBlock*>::iterator
368 i = Preds.begin(), e = Preds.end(); i != e; ++i) {
369 BasicBlock *Pred = *i;
370 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
Bill Wendling0a693f42011-08-18 05:25:23 +0000371 // Seek a loop which actually contains the block being split (to avoid
372 // adjacent loops).
373 while (PredLoop && !PredLoop->contains(OldBB))
374 PredLoop = PredLoop->getParentLoop();
375
376 // Select the most-nested of these loops which contains the block.
377 if (PredLoop && PredLoop->contains(OldBB) &&
378 (!InnermostPredLoop ||
379 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
380 InnermostPredLoop = PredLoop;
381 }
Bill Wendlingec3823d2011-08-18 20:39:32 +0000382 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000383
384 if (InnermostPredLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000385 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000386 } else {
Chandler Carruth691addc2015-01-18 01:25:51 +0000387 L->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000388 if (SplitMakesNewLoopHeader)
389 L->moveToHeader(NewBB);
390 }
391}
392
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000393/// UpdatePHINodes - Update the PHI nodes in OrigBB to include the values coming
394/// from NewBB. This also updates AliasAnalysis, if available.
395static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000396 ArrayRef<BasicBlock *> Preds, BranchInst *BI,
397 AliasAnalysis *AA, bool HasLoopExit) {
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000398 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000399 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000400 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
401 PHINode *PN = cast<PHINode>(I++);
402
403 // Check to see if all of the values coming in are the same. If so, we
404 // don't need to create a new PHI node, unless it's needed for LCSSA.
Craig Topperf40110f2014-04-25 05:29:35 +0000405 Value *InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000406 if (!HasLoopExit) {
407 InVal = PN->getIncomingValueForBlock(Preds[0]);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000408 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
409 if (!PredSet.count(PN->getIncomingBlock(i)))
410 continue;
411 if (!InVal)
412 InVal = PN->getIncomingValue(i);
413 else if (InVal != PN->getIncomingValue(i)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000414 InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000415 break;
416 }
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000417 }
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000418 }
419
420 if (InVal) {
421 // If all incoming values for the new PHI would be the same, just don't
422 // make a new PHI. Instead, just remove the incoming values from the old
423 // PHI.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000424
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000425 // NOTE! This loop walks backwards for a reason! First off, this minimizes
426 // the cost of removal if we end up removing a large number of values, and
427 // second off, this ensures that the indices for the incoming values
428 // aren't invalidated when we remove one.
429 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
430 if (PredSet.count(PN->getIncomingBlock(i)))
431 PN->removeIncomingValue(i, false);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000432
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000433 // Add an incoming value to the PHI node in the loop for the preheader
434 // edge.
435 PN->addIncoming(InVal, NewBB);
436 continue;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000437 }
438
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000439 // If the values coming into the block are not the same, we need a new
440 // PHI.
441 // Create the new PHI node, insert it into NewBB at the end of the block
442 PHINode *NewPHI =
443 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
444 if (AA)
445 AA->copyValue(PN, NewPHI);
446
447 // NOTE! This loop walks backwards for a reason! First off, this minimizes
448 // the cost of removal if we end up removing a large number of values, and
449 // second off, this ensures that the indices for the incoming values aren't
450 // invalidated when we remove one.
451 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
452 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
453 if (PredSet.count(IncomingBB)) {
454 Value *V = PN->removeIncomingValue(i, false);
455 NewPHI->addIncoming(V, IncomingBB);
456 }
457 }
458
459 PN->addIncoming(NewPHI, NewBB);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000460 }
461}
462
Philip Reames9198b332015-01-28 23:06:47 +0000463/// SplitBlockPredecessors - This method introduces at least one new basic block
464/// into the function and moves some of the predecessors of BB to be
465/// predecessors of the new block. The new predecessors are indicated by the
466/// Preds array. The new block is given a suffix of 'Suffix'. Returns new basic
467/// block to which predecessors from Preds are now pointing.
468///
469/// If BB is a landingpad block then additional basicblock might be introduced.
470/// It will have suffix of 'Suffix'+".split_lp".
471/// See SplitLandingPadPredecessors for more details on this case.
Chris Lattnera5b11702008-04-21 01:28:02 +0000472///
Dan Gohman3ddbc242009-09-08 15:45:00 +0000473/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
Cameron Zwarichb7036542011-01-18 04:11:31 +0000474/// LoopInfo, and LCCSA but no other analyses. In particular, it does not
475/// preserve LoopSimplify (because it's complicated to handle the case where one
476/// of the edges being split is an exit of a loop with other exits).
Dan Gohman3ddbc242009-09-08 15:45:00 +0000477///
Jakub Staszak190db2f2013-01-14 23:16:36 +0000478BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000479 ArrayRef<BasicBlock *> Preds,
480 const char *Suffix, AliasAnalysis *AA,
481 DominatorTree *DT, LoopInfo *LI,
482 bool PreserveLCSSA) {
Philip Reames9198b332015-01-28 23:06:47 +0000483 // For the landingpads we need to act a bit differently.
484 // Delegate this work to the SplitLandingPadPredecessors.
485 if (BB->isLandingPad()) {
486 SmallVector<BasicBlock*, 2> NewBBs;
487 std::string NewName = std::string(Suffix) + ".split-lp";
488
489 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(),
490 NewBBs, AA, DT, LI, PreserveLCSSA);
491 return NewBBs[0];
492 }
493
Chris Lattnera5b11702008-04-21 01:28:02 +0000494 // Create new basic block, insert right before the original block.
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000495 BasicBlock *NewBB = BasicBlock::Create(
496 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000497
Chris Lattnera5b11702008-04-21 01:28:02 +0000498 // The new block unconditionally branches to the old block.
499 BranchInst *BI = BranchInst::Create(BB, NewBB);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000500 BI->setDebugLoc(BB->getFirstNonPHI()->getDebugLoc());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000501
Chris Lattnera5b11702008-04-21 01:28:02 +0000502 // Move the edges from Preds to point to NewBB instead of BB.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000503 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Dan Gohman00c79382009-11-05 18:25:44 +0000504 // This is slightly more strict than necessary; the minimum requirement
505 // is that there be no more than one indirectbr branching to BB. And
506 // all BlockAddress uses would need to be updated.
507 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
508 "Cannot split an edge from an IndirectBrInst");
Chris Lattnera5b11702008-04-21 01:28:02 +0000509 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000510 }
511
Chris Lattnera5b11702008-04-21 01:28:02 +0000512 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
513 // node becomes an incoming value for BB's phi node. However, if the Preds
514 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
515 // account for the newly created predecessor.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000516 if (Preds.size() == 0) {
Chris Lattnera5b11702008-04-21 01:28:02 +0000517 // Insert dummy values as the incoming value.
518 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000519 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattnera5b11702008-04-21 01:28:02 +0000520 return NewBB;
521 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000522
Bill Wendling0a693f42011-08-18 05:25:23 +0000523 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
524 bool HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000525 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, PreserveLCSSA,
526 HasLoopExit);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000527
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000528 // Update the PHI nodes in BB with the values coming from NewBB.
Chandler Carruthb5797b62015-01-18 09:21:15 +0000529 UpdatePHINodes(BB, NewBB, Preds, BI, AA, HasLoopExit);
Chris Lattnera5b11702008-04-21 01:28:02 +0000530 return NewBB;
531}
Chris Lattner72f16e72008-11-27 08:10:05 +0000532
Bill Wendlingca7d3092011-08-19 00:05:40 +0000533/// SplitLandingPadPredecessors - This method transforms the landing pad,
534/// OrigBB, by introducing two new basic blocks into the function. One of those
535/// new basic blocks gets the predecessors listed in Preds. The other basic
536/// block gets the remaining predecessors of OrigBB. The landingpad instruction
537/// OrigBB is clone into both of the new basic blocks. The new blocks are given
538/// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000539///
Bill Wendlingca7d3092011-08-19 00:05:40 +0000540/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
541/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular,
542/// it does not preserve LoopSimplify (because it's complicated to handle the
543/// case where one of the edges being split is an exit of a loop with other
544/// exits).
Jakub Staszak190db2f2013-01-14 23:16:36 +0000545///
Bill Wendlingca7d3092011-08-19 00:05:40 +0000546void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000547 ArrayRef<BasicBlock *> Preds,
Bill Wendlingca7d3092011-08-19 00:05:40 +0000548 const char *Suffix1, const char *Suffix2,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000549 SmallVectorImpl<BasicBlock *> &NewBBs,
550 AliasAnalysis *AA, DominatorTree *DT,
551 LoopInfo *LI, bool PreserveLCSSA) {
Bill Wendlingca7d3092011-08-19 00:05:40 +0000552 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
553
554 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
555 // it right before the original block.
556 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
557 OrigBB->getName() + Suffix1,
558 OrigBB->getParent(), OrigBB);
559 NewBBs.push_back(NewBB1);
560
561 // The new block unconditionally branches to the old block.
562 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000563 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendlingca7d3092011-08-19 00:05:40 +0000564
565 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
566 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
567 // This is slightly more strict than necessary; the minimum requirement
568 // is that there be no more than one indirectbr branching to BB. And
569 // all BlockAddress uses would need to be updated.
570 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
571 "Cannot split an edge from an IndirectBrInst");
572 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
573 }
574
Bill Wendlingca7d3092011-08-19 00:05:40 +0000575 bool HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000576 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, PreserveLCSSA,
577 HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000578
579 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
Chandler Carruthb5797b62015-01-18 09:21:15 +0000580 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, AA, HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000581
Bill Wendlingca7d3092011-08-19 00:05:40 +0000582 // Move the remaining edges from OrigBB to point to NewBB2.
583 SmallVector<BasicBlock*, 8> NewBB2Preds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000584 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
585 i != e; ) {
586 BasicBlock *Pred = *i++;
Bill Wendling38d81302011-08-19 23:46:30 +0000587 if (Pred == NewBB1) continue;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000588 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
589 "Cannot split an edge from an IndirectBrInst");
Bill Wendlingca7d3092011-08-19 00:05:40 +0000590 NewBB2Preds.push_back(Pred);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000591 e = pred_end(OrigBB);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000592 }
593
Craig Topperf40110f2014-04-25 05:29:35 +0000594 BasicBlock *NewBB2 = nullptr;
Bill Wendling38d81302011-08-19 23:46:30 +0000595 if (!NewBB2Preds.empty()) {
596 // Create another basic block for the rest of OrigBB's predecessors.
597 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
598 OrigBB->getName() + Suffix2,
599 OrigBB->getParent(), OrigBB);
600 NewBBs.push_back(NewBB2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000601
Bill Wendling38d81302011-08-19 23:46:30 +0000602 // The new block unconditionally branches to the old block.
603 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
Alexey Samsonovb7f02d32015-06-09 22:10:29 +0000604 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
Bill Wendling38d81302011-08-19 23:46:30 +0000605
606 // Move the remaining edges from OrigBB to point to NewBB2.
607 for (SmallVectorImpl<BasicBlock*>::iterator
608 i = NewBB2Preds.begin(), e = NewBB2Preds.end(); i != e; ++i)
609 (*i)->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
610
611 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
612 HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000613 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI,
614 PreserveLCSSA, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000615
616 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
Chandler Carruthb5797b62015-01-18 09:21:15 +0000617 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, AA, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000618 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000619
620 LandingPadInst *LPad = OrigBB->getLandingPadInst();
621 Instruction *Clone1 = LPad->clone();
622 Clone1->setName(Twine("lpad") + Suffix1);
623 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
624
Bill Wendling38d81302011-08-19 23:46:30 +0000625 if (NewBB2) {
626 Instruction *Clone2 = LPad->clone();
627 Clone2->setName(Twine("lpad") + Suffix2);
628 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000629
Bill Wendling38d81302011-08-19 23:46:30 +0000630 // Create a PHI node for the two cloned landingpad instructions.
631 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
632 PN->addIncoming(Clone1, NewBB1);
633 PN->addIncoming(Clone2, NewBB2);
634 LPad->replaceAllUsesWith(PN);
635 LPad->eraseFromParent();
636 } else {
637 // There is no second clone. Just replace the landing pad with the first
638 // clone.
639 LPad->replaceAllUsesWith(Clone1);
640 LPad->eraseFromParent();
641 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000642}
643
Evan Chengd983eba2011-01-29 04:46:23 +0000644/// FoldReturnIntoUncondBranch - This method duplicates the specified return
645/// instruction into a predecessor which ends in an unconditional branch. If
646/// the return instruction returns a value defined by a PHI, propagate the
647/// right value into the return. It returns the new return instruction in the
648/// predecessor.
649ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
650 BasicBlock *Pred) {
651 Instruction *UncondBranch = Pred->getTerminator();
652 // Clone the return and add it to the end of the predecessor.
653 Instruction *NewRet = RI->clone();
654 Pred->getInstList().push_back(NewRet);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000655
Evan Chengd983eba2011-01-29 04:46:23 +0000656 // If the return instruction returns a value, and if the value was a
657 // PHI node in "BB", propagate the right value into the return.
658 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
Evan Cheng249716e2012-07-27 21:21:26 +0000659 i != e; ++i) {
660 Value *V = *i;
Craig Topperf40110f2014-04-25 05:29:35 +0000661 Instruction *NewBC = nullptr;
Evan Cheng249716e2012-07-27 21:21:26 +0000662 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
663 // Return value might be bitcasted. Clone and insert it before the
664 // return instruction.
665 V = BCI->getOperand(0);
666 NewBC = BCI->clone();
667 Pred->getInstList().insert(NewRet, NewBC);
668 *i = NewBC;
669 }
670 if (PHINode *PN = dyn_cast<PHINode>(V)) {
671 if (PN->getParent() == BB) {
672 if (NewBC)
673 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
674 else
675 *i = PN->getIncomingValueForBlock(Pred);
676 }
677 }
678 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000679
Evan Chengd983eba2011-01-29 04:46:23 +0000680 // Update any PHI nodes in the returning block to realize that we no
681 // longer branch to them.
682 BB->removePredecessor(Pred);
683 UncondBranch->eraseFromParent();
684 return cast<ReturnInst>(NewRet);
Chris Lattner351134b2009-05-04 02:25:58 +0000685}
Devang Patela8e74112011-04-29 22:28:59 +0000686
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000687/// SplitBlockAndInsertIfThen - Split the containing block at the
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000688/// specified instruction - everything before and including SplitBefore stays
689/// in the old basic block, and everything after SplitBefore is moved to a
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000690/// new block. The two blocks are connected by a conditional branch
691/// (with value of Cmp being the condition).
692/// Before:
693/// Head
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000694/// SplitBefore
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000695/// Tail
696/// After:
697/// Head
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000698/// if (Cond)
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000699/// ThenBlock
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000700/// SplitBefore
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000701/// Tail
702///
703/// If Unreachable is true, then ThenBlock ends with
704/// UnreachableInst, otherwise it branches to Tail.
705/// Returns the NewBasicBlock's terminator.
706
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000707TerminatorInst *llvm::SplitBlockAndInsertIfThen(Value *Cond,
708 Instruction *SplitBefore,
709 bool Unreachable,
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000710 MDNode *BranchWeights,
711 DominatorTree *DT) {
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000712 BasicBlock *Head = SplitBefore->getParent();
713 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
714 TerminatorInst *HeadOldTerm = Head->getTerminator();
715 LLVMContext &C = Head->getContext();
716 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
717 TerminatorInst *CheckTerm;
718 if (Unreachable)
719 CheckTerm = new UnreachableInst(C, ThenBlock);
720 else
721 CheckTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000722 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000723 BranchInst *HeadNewTerm =
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000724 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000725 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
726 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000727
728 if (DT) {
729 if (DomTreeNode *OldNode = DT->getNode(Head)) {
730 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
731
732 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
733 for (auto Child : Children)
734 DT->changeImmediateDominator(Child, NewNode);
735
736 // Head dominates ThenBlock.
737 DT->addNewBlock(ThenBlock, Head);
738 }
739 }
740
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000741 return CheckTerm;
742}
Tom Stellardaa664d92013-08-06 02:43:45 +0000743
Kostya Serebryany530e2072013-12-23 14:15:08 +0000744/// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
745/// but also creates the ElseBlock.
746/// Before:
747/// Head
748/// SplitBefore
749/// Tail
750/// After:
751/// Head
752/// if (Cond)
753/// ThenBlock
754/// else
755/// ElseBlock
756/// SplitBefore
757/// Tail
758void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
759 TerminatorInst **ThenTerm,
760 TerminatorInst **ElseTerm,
761 MDNode *BranchWeights) {
762 BasicBlock *Head = SplitBefore->getParent();
763 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
764 TerminatorInst *HeadOldTerm = Head->getTerminator();
765 LLVMContext &C = Head->getContext();
766 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
767 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
768 *ThenTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000769 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000770 *ElseTerm = BranchInst::Create(Tail, ElseBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000771 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000772 BranchInst *HeadNewTerm =
773 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
774 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
775 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
776}
777
778
Tom Stellardaa664d92013-08-06 02:43:45 +0000779/// GetIfCondition - Given a basic block (BB) with two predecessors,
780/// check to see if the merge at this block is due
781/// to an "if condition". If so, return the boolean condition that determines
782/// which entry into BB will be taken. Also, return by references the block
783/// that will be entered from if the condition is true, and the block that will
784/// be entered if the condition is false.
785///
786/// This does no checking to see if the true/false blocks have large or unsavory
787/// instructions in them.
788Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
789 BasicBlock *&IfFalse) {
790 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +0000791 BasicBlock *Pred1 = nullptr;
792 BasicBlock *Pred2 = nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000793
794 if (SomePHI) {
795 if (SomePHI->getNumIncomingValues() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +0000796 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000797 Pred1 = SomePHI->getIncomingBlock(0);
798 Pred2 = SomePHI->getIncomingBlock(1);
799 } else {
800 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
801 if (PI == PE) // No predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000802 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000803 Pred1 = *PI++;
804 if (PI == PE) // Only one predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000805 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000806 Pred2 = *PI++;
807 if (PI != PE) // More than two predecessors
Craig Topperf40110f2014-04-25 05:29:35 +0000808 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000809 }
810
811 // We can only handle branches. Other control flow will be lowered to
812 // branches if possible anyway.
813 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
814 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000815 if (!Pred1Br || !Pred2Br)
816 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000817
818 // Eliminate code duplication by ensuring that Pred1Br is conditional if
819 // either are.
820 if (Pred2Br->isConditional()) {
821 // If both branches are conditional, we don't have an "if statement". In
822 // reality, we could transform this case, but since the condition will be
823 // required anyway, we stand no chance of eliminating it, so the xform is
824 // probably not profitable.
825 if (Pred1Br->isConditional())
Craig Topperf40110f2014-04-25 05:29:35 +0000826 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000827
828 std::swap(Pred1, Pred2);
829 std::swap(Pred1Br, Pred2Br);
830 }
831
832 if (Pred1Br->isConditional()) {
833 // The only thing we have to watch out for here is to make sure that Pred2
834 // doesn't have incoming edges from other blocks. If it does, the condition
835 // doesn't dominate BB.
Craig Topperf40110f2014-04-25 05:29:35 +0000836 if (!Pred2->getSinglePredecessor())
837 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000838
839 // If we found a conditional branch predecessor, make sure that it branches
840 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
841 if (Pred1Br->getSuccessor(0) == BB &&
842 Pred1Br->getSuccessor(1) == Pred2) {
843 IfTrue = Pred1;
844 IfFalse = Pred2;
845 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
846 Pred1Br->getSuccessor(1) == BB) {
847 IfTrue = Pred2;
848 IfFalse = Pred1;
849 } else {
850 // We know that one arm of the conditional goes to BB, so the other must
851 // go somewhere unrelated, and this must not be an "if statement".
Craig Topperf40110f2014-04-25 05:29:35 +0000852 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000853 }
854
855 return Pred1Br->getCondition();
856 }
857
858 // Ok, if we got here, both predecessors end with an unconditional branch to
859 // BB. Don't panic! If both blocks only have a single (identical)
860 // predecessor, and THAT is a conditional branch, then we're all ok!
861 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +0000862 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
863 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000864
865 // Otherwise, if this is a conditional branch, then we can use it!
866 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000867 if (!BI) return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000868
869 assert(BI->isConditional() && "Two successors but not conditional?");
870 if (BI->getSuccessor(0) == Pred1) {
871 IfTrue = Pred1;
872 IfFalse = Pred2;
873 } else {
874 IfTrue = Pred2;
875 IfFalse = Pred1;
876 }
877 return BI->getCondition();
878}