blob: e8833f209267534dd3691a75abf2fc521f2c2458 [file] [log] [blame]
Chris Lattner4d1e46e2002-05-07 18:07:59 +00001//===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner4d1e46e2002-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 Lattner54b9c3b2008-04-21 01:28:02 +000016#include "llvm/Analysis/AliasAnalysis.h"
Cameron Zwarich30127872011-01-18 04:11:31 +000017#include "llvm/Analysis/Dominators.h"
Chris Lattnerb5b79972011-01-11 08:13:40 +000018#include "llvm/Analysis/LoopInfo.h"
19#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000020#include "llvm/Constant.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000021#include "llvm/DataLayout.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000022#include "llvm/Function.h"
23#include "llvm/Instructions.h"
24#include "llvm/IntrinsicInst.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000025#include "llvm/Support/ErrorHandling.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000026#include "llvm/Support/ValueHandle.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/Transforms/Scalar.h"
28#include "llvm/Transforms/Utils/Local.h"
29#include "llvm/Type.h"
Chris Lattner4d1e46e2002-05-07 18:07:59 +000030#include <algorithm>
Chris Lattnerf7703df2004-01-09 06:12:26 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Chris Lattner71af9b02008-12-03 06:40:52 +000033/// DeleteDeadBlock - Delete the specified block, which must have no
34/// predecessors.
35void llvm::DeleteDeadBlock(BasicBlock *BB) {
Chris Lattner2973a252008-12-03 07:45:15 +000036 assert((pred_begin(BB) == pred_end(BB) ||
37 // Can delete self loop.
38 BB->getSinglePredecessor() == BB) && "Block is not dead!");
Chris Lattner2b1ba242008-12-03 06:37:44 +000039 TerminatorInst *BBTerm = BB->getTerminator();
Devang Patel5622f072009-02-24 00:05:16 +000040
Chris Lattner2b1ba242008-12-03 06:37:44 +000041 // Loop through all of our successors and make sure they know that one
42 // of their predecessors is going away.
43 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
44 BBTerm->getSuccessor(i)->removePredecessor(BB);
45
46 // Zap all the instructions in the block.
47 while (!BB->empty()) {
48 Instruction &I = BB->back();
49 // If this instruction is used, replace uses with an arbitrary value.
50 // Because control flow can't get here, we don't care what we replace the
51 // value with. Note that since this block is unreachable, and all values
52 // contained within it must dominate their uses, that all uses will
53 // eventually be removed (they are themselves dead).
54 if (!I.use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000055 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner2b1ba242008-12-03 06:37:44 +000056 BB->getInstList().pop_back();
57 }
Devang Patel5622f072009-02-24 00:05:16 +000058
Chris Lattner2b1ba242008-12-03 06:37:44 +000059 // Zap the block!
60 BB->eraseFromParent();
Chris Lattner2b1ba242008-12-03 06:37:44 +000061}
62
Chris Lattner29874e02008-12-03 19:44:02 +000063/// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are
64/// any single-entry PHI nodes in it, fold them away. This handles the case
65/// when all entries to the PHI nodes in a block are guaranteed equal, such as
66/// when the block has exactly one predecessor.
Chris Lattnerb5b79972011-01-11 08:13:40 +000067void llvm::FoldSingleEntryPHINodes(BasicBlock *BB, Pass *P) {
68 if (!isa<PHINode>(BB->begin())) return;
69
70 AliasAnalysis *AA = 0;
71 MemoryDependenceAnalysis *MemDep = 0;
72 if (P) {
73 AA = P->getAnalysisIfAvailable<AliasAnalysis>();
74 MemDep = P->getAnalysisIfAvailable<MemoryDependenceAnalysis>();
75 }
76
Chris Lattner29874e02008-12-03 19:44:02 +000077 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
78 if (PN->getIncomingValue(0) != PN)
79 PN->replaceAllUsesWith(PN->getIncomingValue(0));
80 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000081 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattnerb5b79972011-01-11 08:13:40 +000082
83 if (MemDep)
84 MemDep->removeInstruction(PN); // Memdep updates AA itself.
85 else if (AA && isa<PointerType>(PN->getType()))
86 AA->deleteValue(PN);
87
Chris Lattner29874e02008-12-03 19:44:02 +000088 PN->eraseFromParent();
89 }
90}
91
92
Dan Gohmanafc36a92009-05-02 18:29:22 +000093/// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
94/// is dead. Also recursively delete any operands that become dead as
95/// a result. This includes tracing the def-use list from the PHI to see if
Dan Gohman35738ac2009-05-04 22:30:44 +000096/// it is ultimately unused or if it reaches an unused cycle.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +000097bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
Dan Gohmanafc36a92009-05-02 18:29:22 +000098 // Recursively deleting a PHI may cause multiple PHIs to be deleted
99 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
100 SmallVector<WeakVH, 8> PHIs;
101 for (BasicBlock::iterator I = BB->begin();
102 PHINode *PN = dyn_cast<PHINode>(I); ++I)
103 PHIs.push_back(PN);
104
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000105 bool Changed = false;
Dan Gohmanafc36a92009-05-02 18:29:22 +0000106 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
107 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000108 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
Dan Gohman90fe0bd2010-01-05 15:45:31 +0000109
110 return Changed;
Dan Gohmanafc36a92009-05-02 18:29:22 +0000111}
112
Dan Gohman438b5832009-10-31 17:33:01 +0000113/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
114/// if possible. The return value indicates success or failure.
Chris Lattner88202922009-11-01 04:57:33 +0000115bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P) {
Dan Gohman1c034dc2010-08-17 17:07:02 +0000116 // Don't merge away blocks who have their address taken.
117 if (BB->hasAddressTaken()) return false;
Owen Anderson11f2ec82008-07-17 19:42:29 +0000118
Dan Gohman1c034dc2010-08-17 17:07:02 +0000119 // Can't merge if there are multiple predecessors, or no predecessors.
120 BasicBlock *PredBB = BB->getUniquePredecessor();
Dan Gohman438b5832009-10-31 17:33:01 +0000121 if (!PredBB) return false;
Dan Gohman1c034dc2010-08-17 17:07:02 +0000122
Dan Gohman438b5832009-10-31 17:33:01 +0000123 // Don't break self-loops.
124 if (PredBB == BB) return false;
125 // Don't break invokes.
126 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
127
128 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
Chris Lattnerdc85f8a2011-01-08 19:08:40 +0000129 BasicBlock *OnlySucc = BB;
Dan Gohman438b5832009-10-31 17:33:01 +0000130 for (; SI != SE; ++SI)
131 if (*SI != OnlySucc) {
132 OnlySucc = 0; // There are multiple distinct successors!
133 break;
134 }
135
136 // Can't merge if there are multiple successors.
137 if (!OnlySucc) return false;
Devang Patele435a5d2008-09-09 01:06:56 +0000138
Dan Gohman438b5832009-10-31 17:33:01 +0000139 // Can't merge if there is PHI loop.
140 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
141 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
142 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
143 if (PN->getIncomingValue(i) == PN)
144 return false;
145 } else
146 break;
147 }
148
149 // Begin by getting rid of unneeded PHIs.
Chris Lattnerdc85f8a2011-01-08 19:08:40 +0000150 if (isa<PHINode>(BB->front()))
Chris Lattnerb5b79972011-01-11 08:13:40 +0000151 FoldSingleEntryPHINodes(BB, P);
Dan Gohman438b5832009-10-31 17:33:01 +0000152
Owen Andersonb31b06d2008-07-17 00:01:40 +0000153 // Delete the unconditional branch from the predecessor...
154 PredBB->getInstList().pop_back();
155
Owen Andersonb31b06d2008-07-17 00:01:40 +0000156 // Make all PHI nodes that referred to BB now refer to Pred as their
157 // source...
158 BB->replaceAllUsesWith(PredBB);
159
Jay Foad95c3e482011-06-23 09:09:15 +0000160 // Move all definitions in the successor to the predecessor...
161 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
162
Dan Gohman438b5832009-10-31 17:33:01 +0000163 // Inherit predecessors name if it exists.
Owen Anderson11f2ec82008-07-17 19:42:29 +0000164 if (!PredBB->hasName())
165 PredBB->takeName(BB);
166
Owen Andersonb31b06d2008-07-17 00:01:40 +0000167 // Finally, erase the old block and update dominator info.
168 if (P) {
Chris Lattnerdc85f8a2011-01-08 19:08:40 +0000169 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>()) {
170 if (DomTreeNode *DTN = DT->getNode(BB)) {
171 DomTreeNode *PredDTN = DT->getNode(PredBB);
Jakob Stoklund Olesenfbbd4ab2011-01-11 22:54:38 +0000172 SmallVector<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
173 for (SmallVector<DomTreeNode*, 8>::iterator DI = Children.begin(),
Owen Andersonb31b06d2008-07-17 00:01:40 +0000174 DE = Children.end(); DI != DE; ++DI)
175 DT->changeImmediateDominator(*DI, PredDTN);
176
177 DT->eraseNode(BB);
178 }
Chris Lattnerdc85f8a2011-01-08 19:08:40 +0000179
180 if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
181 LI->removeBlock(BB);
Chris Lattnerb6810992011-01-11 08:16:49 +0000182
183 if (MemoryDependenceAnalysis *MD =
184 P->getAnalysisIfAvailable<MemoryDependenceAnalysis>())
185 MD->invalidateCachedPredecessors();
Owen Andersonb31b06d2008-07-17 00:01:40 +0000186 }
187 }
188
189 BB->eraseFromParent();
Dan Gohman438b5832009-10-31 17:33:01 +0000190 return true;
Owen Andersonb31b06d2008-07-17 00:01:40 +0000191}
192
Chris Lattner0f67dd62005-04-21 16:04:49 +0000193/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
194/// with a value, then remove and delete the original instruction.
195///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000196void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
197 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000198 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000199 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000200 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000201
Chris Lattner86cc4232007-02-11 01:37:51 +0000202 // Make sure to propagate a name if there is one already.
203 if (I.hasName() && !V->hasName())
204 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000205
Misha Brukman5560c9d2003-08-18 14:43:39 +0000206 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000207 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000208}
209
210
Chris Lattner0f67dd62005-04-21 16:04:49 +0000211/// ReplaceInstWithInst - Replace the instruction specified by BI with the
212/// instruction specified by I. The original instruction is deleted and BI is
213/// updated to point to the new instruction.
214///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000215void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
216 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000217 assert(I->getParent() == 0 &&
218 "ReplaceInstWithInst: Instruction already inserted into basic block!");
219
220 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000221 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-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 Lattner18961502002-06-25 16:12:52 +0000227 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000228}
229
Chris Lattner0f67dd62005-04-21 16:04:49 +0000230/// ReplaceInstWithInst - Replace the instruction specified by From with the
231/// instruction specified by To.
232///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000233void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000234 BasicBlock::iterator BI(From);
235 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000236}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000237
Bob Wilsonae23daf2010-02-16 21:06:42 +0000238/// GetSuccessorNumber - Search for the specified successor of basic block BB
239/// and return its position in the terminator instruction's list of
240/// successors. It is an error to call this with a block that is not a
241/// successor.
242unsigned llvm::GetSuccessorNumber(BasicBlock *BB, BasicBlock *Succ) {
Bob Wilsonadb6f222010-02-16 19:49:17 +0000243 TerminatorInst *Term = BB->getTerminator();
Devang Patel8a88a142008-11-03 23:14:09 +0000244#ifndef NDEBUG
Bob Wilsonadb6f222010-02-16 19:49:17 +0000245 unsigned e = Term->getNumSuccessors();
Devang Patel8a88a142008-11-03 23:14:09 +0000246#endif
247 for (unsigned i = 0; ; ++i) {
Devang Patel80198932007-07-06 21:39:20 +0000248 assert(i != e && "Didn't find edge?");
Bob Wilsonadb6f222010-02-16 19:49:17 +0000249 if (Term->getSuccessor(i) == Succ)
250 return i;
Devang Patel80198932007-07-06 21:39:20 +0000251 }
Bob Wilsonadb6f222010-02-16 19:49:17 +0000252}
253
254/// SplitEdge - Split the edge connecting specified block. Pass P must
255/// not be NULL.
256BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
Bob Wilsonae23daf2010-02-16 21:06:42 +0000257 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Devang Patel80198932007-07-06 21:39:20 +0000258
259 // If this is a critical edge, let SplitCriticalEdge do it.
Bob Wilsonadb6f222010-02-16 19:49:17 +0000260 TerminatorInst *LatchTerm = BB->getTerminator();
261 if (SplitCriticalEdge(LatchTerm, SuccNum, P))
Devang Patel80198932007-07-06 21:39:20 +0000262 return LatchTerm->getSuccessor(SuccNum);
263
264 // If the edge isn't critical, then BB has a single successor or Succ has a
265 // single pred. Split the block.
266 BasicBlock::iterator SplitPoint;
267 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
268 // If the successor only has a single pred, split the top of the successor
269 // block.
270 assert(SP == BB && "CFG broken");
Devang Patel8a88a142008-11-03 23:14:09 +0000271 SP = NULL;
Devang Patel80198932007-07-06 21:39:20 +0000272 return SplitBlock(Succ, Succ->begin(), P);
Devang Patel80198932007-07-06 21:39:20 +0000273 }
Chris Lattnerb0433d42011-01-08 18:47:43 +0000274
275 // Otherwise, if BB has a single successor, split it at the bottom of the
276 // block.
277 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
278 "Should have a single succ!");
279 return SplitBlock(BB, BB->getTerminator(), P);
Devang Patel80198932007-07-06 21:39:20 +0000280}
281
282/// SplitBlock - Split the specified block at the specified instruction - every
283/// thing before SplitPt stays in Old and everything starting with SplitPt moves
284/// to a new block. The two blocks are joined by an unconditional branch and
285/// the loop info is updated.
286///
287BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
Devang Patel80198932007-07-06 21:39:20 +0000288 BasicBlock::iterator SplitIt = SplitPt;
Bill Wendlingab82fd92011-08-17 21:21:31 +0000289 while (isa<PHINode>(SplitIt) || isa<LandingPadInst>(SplitIt))
Devang Patel80198932007-07-06 21:39:20 +0000290 ++SplitIt;
291 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
292
Dan Gohman5c89b522009-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.
Chris Lattnerdc85f8a2011-01-08 19:08:40 +0000295 if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
Owen Andersona90793b2008-10-03 06:55:35 +0000296 if (Loop *L = LI->getLoopFor(Old))
297 L->addBasicBlockToLoop(New, LI->getBase());
Devang Patel80198932007-07-06 21:39:20 +0000298
Evan Cheng0f1666b2010-04-05 21:16:25 +0000299 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>()) {
Gabor Greife2d50042010-09-10 22:25:58 +0000300 // Old dominates New. New node dominates all other nodes dominated by Old.
Rafael Espindola605e2b52011-08-24 18:07:01 +0000301 if (DomTreeNode *OldNode = DT->getNode(Old)) {
302 std::vector<DomTreeNode *> Children;
303 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
304 I != E; ++I)
305 Children.push_back(*I);
Devang Patela8a8a362007-07-19 02:29:24 +0000306
Evan Cheng0f1666b2010-04-05 21:16:25 +0000307 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
Devang Patela8a8a362007-07-19 02:29:24 +0000308 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
309 E = Children.end(); I != E; ++I)
310 DT->changeImmediateDominator(*I, NewNode);
Rafael Espindola605e2b52011-08-24 18:07:01 +0000311 }
Evan Cheng0f1666b2010-04-05 21:16:25 +0000312 }
Devang Patel80198932007-07-06 21:39:20 +0000313
Devang Patel80198932007-07-06 21:39:20 +0000314 return New;
315}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000316
Bill Wendlinga644b332011-08-18 05:25:23 +0000317/// UpdateAnalysisInformation - Update DominatorTree, LoopInfo, and LCCSA
318/// analysis information.
Bill Wendlingd4770142011-08-18 17:57:57 +0000319static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
Bill Wendling9210e842011-08-18 20:39:32 +0000320 ArrayRef<BasicBlock *> Preds,
321 Pass *P, bool &HasLoopExit) {
Bill Wendlinga644b332011-08-18 05:25:23 +0000322 if (!P) return;
323
324 LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>();
325 Loop *L = LI ? LI->getLoopFor(OldBB) : 0;
Bill Wendlinga644b332011-08-18 05:25:23 +0000326
327 // If we need to preserve loop analyses, collect some information about how
328 // this split will affect loops.
329 bool IsLoopEntry = !!L;
330 bool SplitMakesNewLoopHeader = false;
331 if (LI) {
Bill Wendling7e8840c2011-08-19 00:05:40 +0000332 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
Bill Wendling9210e842011-08-18 20:39:32 +0000333 for (ArrayRef<BasicBlock*>::iterator
334 i = Preds.begin(), e = Preds.end(); i != e; ++i) {
335 BasicBlock *Pred = *i;
Bill Wendling7e8840c2011-08-19 00:05:40 +0000336
Bill Wendlinga644b332011-08-18 05:25:23 +0000337 // If we need to preserve LCSSA, determine if any of the preds is a loop
338 // exit.
339 if (PreserveLCSSA)
Bill Wendling9210e842011-08-18 20:39:32 +0000340 if (Loop *PL = LI->getLoopFor(Pred))
Bill Wendlinga644b332011-08-18 05:25:23 +0000341 if (!PL->contains(OldBB))
342 HasLoopExit = true;
343
344 // If we need to preserve LoopInfo, note whether any of the preds crosses
345 // an interesting loop boundary.
346 if (!L) continue;
Bill Wendling9210e842011-08-18 20:39:32 +0000347 if (L->contains(Pred))
Bill Wendlinga644b332011-08-18 05:25:23 +0000348 IsLoopEntry = false;
349 else
350 SplitMakesNewLoopHeader = true;
351 }
352 }
353
354 // Update dominator tree if available.
355 DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
356 if (DT)
357 DT->splitBlock(NewBB);
358
359 if (!L) return;
360
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.
366 Loop *InnermostPredLoop = 0;
Bill Wendling9210e842011-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 Wendlinga644b332011-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 Wendling9210e842011-08-18 20:39:32 +0000382 }
Bill Wendlinga644b332011-08-18 05:25:23 +0000383
384 if (InnermostPredLoop)
385 InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
386 } else {
387 L->addBasicBlockToLoop(NewBB, LI->getBase());
388 if (SplitMakesNewLoopHeader)
389 L->moveToHeader(NewBB);
390 }
391}
392
Bill Wendling1c44d862011-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,
396 ArrayRef<BasicBlock*> Preds, BranchInst *BI,
397 Pass *P, bool HasLoopExit) {
398 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
399 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
400 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.
405 Value *InVal = 0;
406 if (!HasLoopExit) {
407 InVal = PN->getIncomingValueForBlock(Preds[0]);
408 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
409 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
410 InVal = 0;
411 break;
412 }
413 }
414
415 if (InVal) {
416 // If all incoming values for the new PHI would be the same, just don't
417 // make a new PHI. Instead, just remove the incoming values from the old
418 // PHI.
419 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
420 PN->removeIncomingValue(Preds[i], false);
421 } else {
422 // If the values coming into the block are not the same, we need a PHI.
423 // Create the new PHI node, insert it into NewBB at the end of the block
424 PHINode *NewPHI =
425 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
426 if (AA) AA->copyValue(PN, NewPHI);
427
428 // Move all of the PHI values for 'Preds' to the new PHI.
429 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
430 Value *V = PN->removeIncomingValue(Preds[i], false);
431 NewPHI->addIncoming(V, Preds[i]);
432 }
433
434 InVal = NewPHI;
435 }
436
437 // Add an incoming value to the PHI node in the loop for the preheader
438 // edge.
439 PN->addIncoming(InVal, NewBB);
440 }
441}
442
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000443/// SplitBlockPredecessors - This method transforms BB by introducing a new
444/// basic block into the function, and moving some of the predecessors of BB to
445/// be predecessors of the new block. The new predecessors are indicated by the
446/// Preds array, which has NumPreds elements in it. The new block is given a
447/// suffix of 'Suffix'.
448///
Dan Gohman5c89b522009-09-08 15:45:00 +0000449/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
Cameron Zwarich30127872011-01-18 04:11:31 +0000450/// LoopInfo, and LCCSA but no other analyses. In particular, it does not
451/// preserve LoopSimplify (because it's complicated to handle the case where one
452/// of the edges being split is an exit of a loop with other exits).
Dan Gohman5c89b522009-09-08 15:45:00 +0000453///
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000454BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
Jakub Staszak2fac1d52011-12-09 21:19:53 +0000455 ArrayRef<BasicBlock*> Preds,
456 const char *Suffix, Pass *P) {
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000457 // Create new basic block, insert right before the original block.
Owen Anderson1d0be152009-08-13 21:58:54 +0000458 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
459 BB->getParent(), BB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000460
461 // The new block unconditionally branches to the old block.
462 BranchInst *BI = BranchInst::Create(BB, NewBB);
463
464 // Move the edges from Preds to point to NewBB instead of BB.
Jakub Staszak2fac1d52011-12-09 21:19:53 +0000465 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Dan Gohmanb8eb17c2009-11-05 18:25:44 +0000466 // This is slightly more strict than necessary; the minimum requirement
467 // is that there be no more than one indirectbr branching to BB. And
468 // all BlockAddress uses would need to be updated.
469 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
470 "Cannot split an edge from an IndirectBrInst");
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000471 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000472 }
473
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000474 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
475 // node becomes an incoming value for BB's phi node. However, if the Preds
476 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
477 // account for the newly created predecessor.
Jakub Staszak2fac1d52011-12-09 21:19:53 +0000478 if (Preds.size() == 0) {
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000479 // Insert dummy values as the incoming value.
480 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000481 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000482 return NewBB;
483 }
Dan Gohman5c89b522009-09-08 15:45:00 +0000484
Bill Wendlinga644b332011-08-18 05:25:23 +0000485 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
486 bool HasLoopExit = false;
Jakub Staszak2fac1d52011-12-09 21:19:53 +0000487 UpdateAnalysisInformation(BB, NewBB, Preds, P, HasLoopExit);
Dan Gohman5c89b522009-09-08 15:45:00 +0000488
Bill Wendling1c44d862011-08-18 20:51:04 +0000489 // Update the PHI nodes in BB with the values coming from NewBB.
Jakub Staszak2fac1d52011-12-09 21:19:53 +0000490 UpdatePHINodes(BB, NewBB, Preds, BI, P, HasLoopExit);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000491 return NewBB;
492}
Chris Lattner52c95852008-11-27 08:10:05 +0000493
Bill Wendling7e8840c2011-08-19 00:05:40 +0000494/// SplitLandingPadPredecessors - This method transforms the landing pad,
495/// OrigBB, by introducing two new basic blocks into the function. One of those
496/// new basic blocks gets the predecessors listed in Preds. The other basic
497/// block gets the remaining predecessors of OrigBB. The landingpad instruction
498/// OrigBB is clone into both of the new basic blocks. The new blocks are given
499/// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
500///
501/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
502/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular,
503/// it does not preserve LoopSimplify (because it's complicated to handle the
504/// case where one of the edges being split is an exit of a loop with other
505/// exits).
506///
507void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
508 ArrayRef<BasicBlock*> Preds,
509 const char *Suffix1, const char *Suffix2,
510 Pass *P,
511 SmallVectorImpl<BasicBlock*> &NewBBs) {
512 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
513
514 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
515 // it right before the original block.
516 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
517 OrigBB->getName() + Suffix1,
518 OrigBB->getParent(), OrigBB);
519 NewBBs.push_back(NewBB1);
520
521 // The new block unconditionally branches to the old block.
522 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
523
524 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
525 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
526 // This is slightly more strict than necessary; the minimum requirement
527 // is that there be no more than one indirectbr branching to BB. And
528 // all BlockAddress uses would need to be updated.
529 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
530 "Cannot split an edge from an IndirectBrInst");
531 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
532 }
533
534 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
535 bool HasLoopExit = false;
536 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, P, HasLoopExit);
537
538 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
539 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, P, HasLoopExit);
540
Bill Wendling7e8840c2011-08-19 00:05:40 +0000541 // Move the remaining edges from OrigBB to point to NewBB2.
542 SmallVector<BasicBlock*, 8> NewBB2Preds;
543 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
544 i != e; ) {
545 BasicBlock *Pred = *i++;
Bill Wendling94657b92011-08-19 23:46:30 +0000546 if (Pred == NewBB1) continue;
Bill Wendling7e8840c2011-08-19 00:05:40 +0000547 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
548 "Cannot split an edge from an IndirectBrInst");
Bill Wendling7e8840c2011-08-19 00:05:40 +0000549 NewBB2Preds.push_back(Pred);
550 e = pred_end(OrigBB);
551 }
552
Bill Wendling94657b92011-08-19 23:46:30 +0000553 BasicBlock *NewBB2 = 0;
554 if (!NewBB2Preds.empty()) {
555 // Create another basic block for the rest of OrigBB's predecessors.
556 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
557 OrigBB->getName() + Suffix2,
558 OrigBB->getParent(), OrigBB);
559 NewBBs.push_back(NewBB2);
Bill Wendling7e8840c2011-08-19 00:05:40 +0000560
Bill Wendling94657b92011-08-19 23:46:30 +0000561 // The new block unconditionally branches to the old block.
562 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
563
564 // Move the remaining edges from OrigBB to point to NewBB2.
565 for (SmallVectorImpl<BasicBlock*>::iterator
566 i = NewBB2Preds.begin(), e = NewBB2Preds.end(); i != e; ++i)
567 (*i)->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
568
569 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
570 HasLoopExit = false;
571 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, P, HasLoopExit);
572
573 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
574 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, P, HasLoopExit);
575 }
Bill Wendling7e8840c2011-08-19 00:05:40 +0000576
577 LandingPadInst *LPad = OrigBB->getLandingPadInst();
578 Instruction *Clone1 = LPad->clone();
579 Clone1->setName(Twine("lpad") + Suffix1);
580 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
581
Bill Wendling94657b92011-08-19 23:46:30 +0000582 if (NewBB2) {
583 Instruction *Clone2 = LPad->clone();
584 Clone2->setName(Twine("lpad") + Suffix2);
585 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
Bill Wendling7e8840c2011-08-19 00:05:40 +0000586
Bill Wendling94657b92011-08-19 23:46:30 +0000587 // Create a PHI node for the two cloned landingpad instructions.
588 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
589 PN->addIncoming(Clone1, NewBB1);
590 PN->addIncoming(Clone2, NewBB2);
591 LPad->replaceAllUsesWith(PN);
592 LPad->eraseFromParent();
593 } else {
594 // There is no second clone. Just replace the landing pad with the first
595 // clone.
596 LPad->replaceAllUsesWith(Clone1);
597 LPad->eraseFromParent();
598 }
Bill Wendling7e8840c2011-08-19 00:05:40 +0000599}
600
Mike Stumpfe095f32009-05-04 18:40:41 +0000601/// FindFunctionBackedges - Analyze the specified function to find all of the
602/// loop backedges in the function and return them. This is a relatively cheap
603/// (compared to computing dominators and loop info) analysis.
604///
605/// The output is added to Result, as pairs of <from,to> edge info.
606void llvm::FindFunctionBackedges(const Function &F,
607 SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
608 const BasicBlock *BB = &F.getEntryBlock();
609 if (succ_begin(BB) == succ_end(BB))
610 return;
611
612 SmallPtrSet<const BasicBlock*, 8> Visited;
613 SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
614 SmallPtrSet<const BasicBlock*, 8> InStack;
615
616 Visited.insert(BB);
617 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
618 InStack.insert(BB);
619 do {
620 std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
621 const BasicBlock *ParentBB = Top.first;
622 succ_const_iterator &I = Top.second;
623
624 bool FoundNew = false;
625 while (I != succ_end(ParentBB)) {
626 BB = *I++;
627 if (Visited.insert(BB)) {
628 FoundNew = true;
629 break;
630 }
631 // Successor is in VisitStack, it's a back edge.
632 if (InStack.count(BB))
633 Result.push_back(std::make_pair(ParentBB, BB));
634 }
635
636 if (FoundNew) {
637 // Go down one level if there is a unvisited successor.
638 InStack.insert(BB);
639 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
640 } else {
641 // Go up one level.
642 InStack.erase(VisitStack.pop_back_val().first);
643 }
Evan Chengc3f507f2011-01-29 04:46:23 +0000644 } while (!VisitStack.empty());
645}
646
647/// FoldReturnIntoUncondBranch - This method duplicates the specified return
648/// instruction into a predecessor which ends in an unconditional branch. If
649/// the return instruction returns a value defined by a PHI, propagate the
650/// right value into the return. It returns the new return instruction in the
651/// predecessor.
652ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
653 BasicBlock *Pred) {
654 Instruction *UncondBranch = Pred->getTerminator();
655 // Clone the return and add it to the end of the predecessor.
656 Instruction *NewRet = RI->clone();
657 Pred->getInstList().push_back(NewRet);
658
659 // If the return instruction returns a value, and if the value was a
660 // PHI node in "BB", propagate the right value into the return.
661 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
Evan Cheng9c777a42012-07-27 21:21:26 +0000662 i != e; ++i) {
663 Value *V = *i;
664 Instruction *NewBC = 0;
665 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
666 // Return value might be bitcasted. Clone and insert it before the
667 // return instruction.
668 V = BCI->getOperand(0);
669 NewBC = BCI->clone();
670 Pred->getInstList().insert(NewRet, NewBC);
671 *i = NewBC;
672 }
673 if (PHINode *PN = dyn_cast<PHINode>(V)) {
674 if (PN->getParent() == BB) {
675 if (NewBC)
676 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
677 else
678 *i = PN->getIncomingValueForBlock(Pred);
679 }
680 }
681 }
Evan Chengc3f507f2011-01-29 04:46:23 +0000682
683 // Update any PHI nodes in the returning block to realize that we no
684 // longer branch to them.
685 BB->removePredecessor(Pred);
686 UncondBranch->eraseFromParent();
687 return cast<ReturnInst>(NewRet);
Mike Stumpfe095f32009-05-04 18:40:41 +0000688}
Devang Patel40348e82011-04-29 22:28:59 +0000689
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000690/// SplitBlockAndInsertIfThen - Split the containing block at the
691/// specified instruction - everything before and including Cmp stays
692/// in the old basic block, and everything after Cmp is moved to a
693/// new block. The two blocks are connected by a conditional branch
694/// (with value of Cmp being the condition).
695/// Before:
696/// Head
697/// Cmp
698/// Tail
699/// After:
700/// Head
701/// Cmp
702/// if (Cmp)
703/// ThenBlock
704/// Tail
705///
706/// If Unreachable is true, then ThenBlock ends with
707/// UnreachableInst, otherwise it branches to Tail.
708/// Returns the NewBasicBlock's terminator.
709
710TerminatorInst *llvm::SplitBlockAndInsertIfThen(Instruction *Cmp,
711 bool Unreachable, MDNode *BranchWeights) {
712 Instruction *SplitBefore = Cmp->getNextNode();
713 BasicBlock *Head = SplitBefore->getParent();
714 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
715 TerminatorInst *HeadOldTerm = Head->getTerminator();
716 LLVMContext &C = Head->getContext();
717 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
718 TerminatorInst *CheckTerm;
719 if (Unreachable)
720 CheckTerm = new UnreachableInst(C, ThenBlock);
721 else
722 CheckTerm = BranchInst::Create(Tail, ThenBlock);
723 BranchInst *HeadNewTerm =
724 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cmp);
725 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
726 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
727 return CheckTerm;
728}