blob: 1f9a2031f3b524feb95c203675027c8c5313a7da [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"
16#include "llvm/Function.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000017#include "llvm/Instructions.h"
Dale Johannesenbd8e6502009-03-03 01:09:07 +000018#include "llvm/IntrinsicInst.h"
Owen Anderson0a205a42009-07-05 22:41:43 +000019#include "llvm/LLVMContext.h"
Chris Lattnerb0f0ef82002-07-29 22:32:08 +000020#include "llvm/Constant.h"
21#include "llvm/Type.h"
Chris Lattner54b9c3b2008-04-21 01:28:02 +000022#include "llvm/Analysis/AliasAnalysis.h"
Devang Patel80198932007-07-06 21:39:20 +000023#include "llvm/Analysis/LoopInfo.h"
24#include "llvm/Analysis/Dominators.h"
Chris Lattneree6e10b2008-11-27 08:18:12 +000025#include "llvm/Target/TargetData.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000026#include "llvm/Transforms/Utils/Local.h"
Dan Gohman5c89b522009-09-08 15:45:00 +000027#include "llvm/Transforms/Scalar.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000028#include "llvm/Support/ErrorHandling.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000029#include "llvm/Support/ValueHandle.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.
67void llvm::FoldSingleEntryPHINodes(BasicBlock *BB) {
Chris Lattner29874e02008-12-03 19:44:02 +000068 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
69 if (PN->getIncomingValue(0) != PN)
70 PN->replaceAllUsesWith(PN->getIncomingValue(0));
71 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000072 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner29874e02008-12-03 19:44:02 +000073 PN->eraseFromParent();
74 }
75}
76
77
Dan Gohmanafc36a92009-05-02 18:29:22 +000078/// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
79/// is dead. Also recursively delete any operands that become dead as
80/// a result. This includes tracing the def-use list from the PHI to see if
Dan Gohman35738ac2009-05-04 22:30:44 +000081/// it is ultimately unused or if it reaches an unused cycle.
82void llvm::DeleteDeadPHIs(BasicBlock *BB) {
Dan Gohmanafc36a92009-05-02 18:29:22 +000083 // Recursively deleting a PHI may cause multiple PHIs to be deleted
84 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
85 SmallVector<WeakVH, 8> PHIs;
86 for (BasicBlock::iterator I = BB->begin();
87 PHINode *PN = dyn_cast<PHINode>(I); ++I)
88 PHIs.push_back(PN);
89
90 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
91 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Dan Gohman35738ac2009-05-04 22:30:44 +000092 RecursivelyDeleteDeadPHINode(PN);
Dan Gohmanafc36a92009-05-02 18:29:22 +000093}
94
Dan Gohman438b5832009-10-31 17:33:01 +000095/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
96/// if possible. The return value indicates success or failure.
97bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
98 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
99 // Can't merge the entry block.
100 if (pred_begin(BB) == pred_end(BB)) return false;
Owen Anderson11f2ec82008-07-17 19:42:29 +0000101
Dan Gohman438b5832009-10-31 17:33:01 +0000102 BasicBlock *PredBB = *PI++;
103 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
104 if (*PI != PredBB) {
105 PredBB = 0; // There are multiple different predecessors...
106 break;
107 }
108
109 // Can't merge if there are multiple predecessors.
110 if (!PredBB) return false;
111 // Don't break self-loops.
112 if (PredBB == BB) return false;
113 // Don't break invokes.
114 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
115
116 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
117 BasicBlock* OnlySucc = BB;
118 for (; SI != SE; ++SI)
119 if (*SI != OnlySucc) {
120 OnlySucc = 0; // There are multiple distinct successors!
121 break;
122 }
123
124 // Can't merge if there are multiple successors.
125 if (!OnlySucc) return false;
Devang Patele435a5d2008-09-09 01:06:56 +0000126
Dan Gohman438b5832009-10-31 17:33:01 +0000127 // Can't merge if there is PHI loop.
128 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
129 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
130 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
131 if (PN->getIncomingValue(i) == PN)
132 return false;
133 } else
134 break;
135 }
136
137 // Begin by getting rid of unneeded PHIs.
138 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
139 PN->replaceAllUsesWith(PN->getIncomingValue(0));
140 BB->getInstList().pop_front(); // Delete the phi node...
141 }
142
Owen Andersonb31b06d2008-07-17 00:01:40 +0000143 // Delete the unconditional branch from the predecessor...
144 PredBB->getInstList().pop_back();
145
146 // Move all definitions in the successor to the predecessor...
147 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
148
149 // Make all PHI nodes that referred to BB now refer to Pred as their
150 // source...
151 BB->replaceAllUsesWith(PredBB);
152
Dan Gohman438b5832009-10-31 17:33:01 +0000153 // Inherit predecessors name if it exists.
Owen Anderson11f2ec82008-07-17 19:42:29 +0000154 if (!PredBB->hasName())
155 PredBB->takeName(BB);
156
Owen Andersonb31b06d2008-07-17 00:01:40 +0000157 // Finally, erase the old block and update dominator info.
158 if (P) {
Duncan Sands1465d612009-01-28 13:14:17 +0000159 if (DominatorTree* DT = P->getAnalysisIfAvailable<DominatorTree>()) {
Owen Andersonb31b06d2008-07-17 00:01:40 +0000160 DomTreeNode* DTN = DT->getNode(BB);
161 DomTreeNode* PredDTN = DT->getNode(PredBB);
162
163 if (DTN) {
164 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
165 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
166 DE = Children.end(); DI != DE; ++DI)
167 DT->changeImmediateDominator(*DI, PredDTN);
168
169 DT->eraseNode(BB);
170 }
171 }
172 }
173
174 BB->eraseFromParent();
175
Dan Gohman438b5832009-10-31 17:33:01 +0000176
177 return true;
Owen Andersonb31b06d2008-07-17 00:01:40 +0000178}
179
Chris Lattner0f67dd62005-04-21 16:04:49 +0000180/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
181/// with a value, then remove and delete the original instruction.
182///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000183void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
184 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000185 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000186 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000187 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000188
Chris Lattner86cc4232007-02-11 01:37:51 +0000189 // Make sure to propagate a name if there is one already.
190 if (I.hasName() && !V->hasName())
191 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000192
Misha Brukman5560c9d2003-08-18 14:43:39 +0000193 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000194 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000195}
196
197
Chris Lattner0f67dd62005-04-21 16:04:49 +0000198/// ReplaceInstWithInst - Replace the instruction specified by BI with the
199/// instruction specified by I. The original instruction is deleted and BI is
200/// updated to point to the new instruction.
201///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000202void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
203 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000204 assert(I->getParent() == 0 &&
205 "ReplaceInstWithInst: Instruction already inserted into basic block!");
206
207 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000208 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000209
210 // Replace all uses of the old instruction, and delete it.
211 ReplaceInstWithValue(BIL, BI, I);
212
213 // Move BI back to point to the newly inserted instruction
Chris Lattner18961502002-06-25 16:12:52 +0000214 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000215}
216
Chris Lattner0f67dd62005-04-21 16:04:49 +0000217/// ReplaceInstWithInst - Replace the instruction specified by From with the
218/// instruction specified by To.
219///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000220void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000221 BasicBlock::iterator BI(From);
222 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000223}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000224
Chris Lattner0f67dd62005-04-21 16:04:49 +0000225/// RemoveSuccessor - Change the specified terminator instruction such that its
Reid Spencerbc2eba12006-05-19 19:09:46 +0000226/// successor SuccNum no longer exists. Because this reduces the outgoing
Chris Lattner0f67dd62005-04-21 16:04:49 +0000227/// degree of the current basic block, the actual terminator instruction itself
Reid Spencerbc2eba12006-05-19 19:09:46 +0000228/// may have to be changed. In the case where the last successor of the block
229/// is deleted, a return instruction is inserted in its place which can cause a
Chris Lattner0f67dd62005-04-21 16:04:49 +0000230/// surprising change in program behavior if it is not expected.
231///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000232void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000233 assert(SuccNum < TI->getNumSuccessors() &&
234 "Trying to remove a nonexistant successor!");
235
236 // If our old successor block contains any PHI nodes, remove the entry in the
237 // PHI nodes that comes from this branch...
238 //
239 BasicBlock *BB = TI->getParent();
240 TI->getSuccessor(SuccNum)->removePredecessor(BB);
241
242 TerminatorInst *NewTI = 0;
243 switch (TI->getOpcode()) {
244 case Instruction::Br:
245 // If this is a conditional branch... convert to unconditional branch.
246 if (TI->getNumSuccessors() == 2) {
247 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
248 } else { // Otherwise convert to a return instruction...
249 Value *RetVal = 0;
Misha Brukmanfd939082005-04-21 23:48:37 +0000250
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000251 // Create a value to return... if the function doesn't return null...
Owen Anderson1d0be152009-08-13 21:58:54 +0000252 if (BB->getParent()->getReturnType() != Type::getVoidTy(TI->getContext()))
Owen Andersona7235ea2009-07-31 20:28:14 +0000253 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000254
255 // Create the return...
Owen Anderson1d0be152009-08-13 21:58:54 +0000256 NewTI = ReturnInst::Create(TI->getContext(), RetVal);
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000257 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000258 break;
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000259
260 case Instruction::Invoke: // Should convert to call
261 case Instruction::Switch: // Should remove entry
262 default:
263 case Instruction::Ret: // Cannot happen, has no successors!
Torok Edwinc23197a2009-07-14 16:55:14 +0000264 llvm_unreachable("Unhandled terminator instruction type in RemoveSuccessor!");
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000265 }
266
267 if (NewTI) // If it's a different instruction, replace.
268 ReplaceInstWithInst(TI, NewTI);
269}
Brian Gaeked0fde302003-11-11 22:41:34 +0000270
Devang Patel80198932007-07-06 21:39:20 +0000271/// SplitEdge - Split the edge connecting specified block. Pass P must
272/// not be NULL.
273BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
Chris Lattnera4b04212009-10-31 22:04:43 +0000274 assert(!isa<IndirectBrInst>(BB->getTerminator()) &&
275 "Cannot split an edge from an IndirectBrInst");
Devang Patel80198932007-07-06 21:39:20 +0000276 TerminatorInst *LatchTerm = BB->getTerminator();
277 unsigned SuccNum = 0;
Devang Patel8a88a142008-11-03 23:14:09 +0000278#ifndef NDEBUG
279 unsigned e = LatchTerm->getNumSuccessors();
280#endif
281 for (unsigned i = 0; ; ++i) {
Devang Patel80198932007-07-06 21:39:20 +0000282 assert(i != e && "Didn't find edge?");
283 if (LatchTerm->getSuccessor(i) == Succ) {
284 SuccNum = i;
285 break;
286 }
287 }
288
289 // If this is a critical edge, let SplitCriticalEdge do it.
290 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
291 return LatchTerm->getSuccessor(SuccNum);
292
293 // If the edge isn't critical, then BB has a single successor or Succ has a
294 // single pred. Split the block.
295 BasicBlock::iterator SplitPoint;
296 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
297 // If the successor only has a single pred, split the top of the successor
298 // block.
299 assert(SP == BB && "CFG broken");
Devang Patel8a88a142008-11-03 23:14:09 +0000300 SP = NULL;
Devang Patel80198932007-07-06 21:39:20 +0000301 return SplitBlock(Succ, Succ->begin(), P);
302 } else {
303 // Otherwise, if BB has a single successor, split it at the bottom of the
304 // block.
305 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
306 "Should have a single succ!");
307 return SplitBlock(BB, BB->getTerminator(), P);
308 }
309}
310
311/// SplitBlock - Split the specified block at the specified instruction - every
312/// thing before SplitPt stays in Old and everything starting with SplitPt moves
313/// to a new block. The two blocks are joined by an unconditional branch and
314/// the loop info is updated.
315///
316BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
Devang Patel80198932007-07-06 21:39:20 +0000317 BasicBlock::iterator SplitIt = SplitPt;
318 while (isa<PHINode>(SplitIt))
319 ++SplitIt;
320 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
321
Dan Gohman5c89b522009-09-08 15:45:00 +0000322 // The new block lives in whichever loop the old one did. This preserves
323 // LCSSA as well, because we force the split point to be after any PHI nodes.
Duncan Sands1465d612009-01-28 13:14:17 +0000324 if (LoopInfo* LI = P->getAnalysisIfAvailable<LoopInfo>())
Owen Andersona90793b2008-10-03 06:55:35 +0000325 if (Loop *L = LI->getLoopFor(Old))
326 L->addBasicBlockToLoop(New, LI->getBase());
Devang Patel80198932007-07-06 21:39:20 +0000327
Duncan Sands1465d612009-01-28 13:14:17 +0000328 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>())
Devang Patela8a8a362007-07-19 02:29:24 +0000329 {
330 // Old dominates New. New node domiantes all other nodes dominated by Old.
331 DomTreeNode *OldNode = DT->getNode(Old);
332 std::vector<DomTreeNode *> Children;
333 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
334 I != E; ++I)
335 Children.push_back(*I);
336
337 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
338
339 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
340 E = Children.end(); I != E; ++I)
341 DT->changeImmediateDominator(*I, NewNode);
342 }
Devang Patel80198932007-07-06 21:39:20 +0000343
Duncan Sands1465d612009-01-28 13:14:17 +0000344 if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
Devang Patel80198932007-07-06 21:39:20 +0000345 DF->splitBlock(Old);
346
347 return New;
348}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000349
350
351/// SplitBlockPredecessors - This method transforms BB by introducing a new
352/// basic block into the function, and moving some of the predecessors of BB to
353/// be predecessors of the new block. The new predecessors are indicated by the
354/// Preds array, which has NumPreds elements in it. The new block is given a
355/// suffix of 'Suffix'.
356///
Dan Gohman5c89b522009-09-08 15:45:00 +0000357/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
358/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses.
359/// In particular, it does not preserve LoopSimplify (because it's
360/// complicated to handle the case where one of the edges being split
361/// is an exit of a loop with other exits).
362///
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000363BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
364 BasicBlock *const *Preds,
365 unsigned NumPreds, const char *Suffix,
366 Pass *P) {
367 // Create new basic block, insert right before the original block.
Owen Anderson1d0be152009-08-13 21:58:54 +0000368 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
369 BB->getParent(), BB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000370
371 // The new block unconditionally branches to the old block.
372 BranchInst *BI = BranchInst::Create(BB, NewBB);
373
Dan Gohman5c89b522009-09-08 15:45:00 +0000374 LoopInfo *LI = P ? P->getAnalysisIfAvailable<LoopInfo>() : 0;
375 Loop *L = LI ? LI->getLoopFor(BB) : 0;
376 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
377
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000378 // Move the edges from Preds to point to NewBB instead of BB.
Dan Gohman5c89b522009-09-08 15:45:00 +0000379 // While here, if we need to preserve loop analyses, collect
380 // some information about how this split will affect loops.
381 bool HasLoopExit = false;
382 bool IsLoopEntry = !!L;
383 bool SplitMakesNewLoopHeader = false;
384 for (unsigned i = 0; i != NumPreds; ++i) {
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000385 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000386
387 if (LI) {
388 // If we need to preserve LCSSA, determine if any of
389 // the preds is a loop exit.
390 if (PreserveLCSSA)
391 if (Loop *PL = LI->getLoopFor(Preds[i]))
392 if (!PL->contains(BB))
393 HasLoopExit = true;
394 // If we need to preserve LoopInfo, note whether any of the
395 // preds crosses an interesting loop boundary.
396 if (L) {
397 if (L->contains(Preds[i]))
398 IsLoopEntry = false;
399 else
400 SplitMakesNewLoopHeader = true;
401 }
402 }
403 }
404
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000405 // Update dominator tree and dominator frontier if available.
Duncan Sands1465d612009-01-28 13:14:17 +0000406 DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000407 if (DT)
408 DT->splitBlock(NewBB);
Duncan Sands1465d612009-01-28 13:14:17 +0000409 if (DominanceFrontier *DF = P ? P->getAnalysisIfAvailable<DominanceFrontier>():0)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000410 DF->splitBlock(NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000411
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000412 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
413 // node becomes an incoming value for BB's phi node. However, if the Preds
414 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
415 // account for the newly created predecessor.
416 if (NumPreds == 0) {
417 // Insert dummy values as the incoming value.
418 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000419 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000420 return NewBB;
421 }
Dan Gohman5c89b522009-09-08 15:45:00 +0000422
423 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
424
425 if (L) {
426 if (IsLoopEntry) {
Dan Gohman841a1472009-10-19 16:04:50 +0000427 // Add the new block to the nearest enclosing loop (and not an
428 // adjacent loop). To find this, examine each of the predecessors and
429 // determine which loops enclose them, and select the most-nested loop
430 // which contains the loop containing the block being split.
431 Loop *InnermostPredLoop = 0;
432 for (unsigned i = 0; i != NumPreds; ++i)
433 if (Loop *PredLoop = LI->getLoopFor(Preds[i])) {
434 // Seek a loop which actually contains the block being split (to
435 // avoid adjacent loops).
436 while (PredLoop && !PredLoop->contains(BB))
437 PredLoop = PredLoop->getParentLoop();
438 // Select the most-nested of these loops which contains the block.
439 if (PredLoop &&
440 PredLoop->contains(BB) &&
441 (!InnermostPredLoop ||
442 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
443 InnermostPredLoop = PredLoop;
444 }
445 if (InnermostPredLoop)
446 InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
Dan Gohman5c89b522009-09-08 15:45:00 +0000447 } else {
448 L->addBasicBlockToLoop(NewBB, LI->getBase());
449 if (SplitMakesNewLoopHeader)
450 L->moveToHeader(NewBB);
451 }
452 }
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000453
454 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
455 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
456 PHINode *PN = cast<PHINode>(I++);
457
458 // Check to see if all of the values coming in are the same. If so, we
Dan Gohman5c89b522009-09-08 15:45:00 +0000459 // don't need to create a new PHI node, unless it's needed for LCSSA.
460 Value *InVal = 0;
461 if (!HasLoopExit) {
462 InVal = PN->getIncomingValueForBlock(Preds[0]);
463 for (unsigned i = 1; i != NumPreds; ++i)
464 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
465 InVal = 0;
466 break;
467 }
468 }
469
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000470 if (InVal) {
471 // If all incoming values for the new PHI would be the same, just don't
472 // make a new PHI. Instead, just remove the incoming values from the old
473 // PHI.
474 for (unsigned i = 0; i != NumPreds; ++i)
475 PN->removeIncomingValue(Preds[i], false);
476 } else {
477 // If the values coming into the block are not the same, we need a PHI.
478 // Create the new PHI node, insert it into NewBB at the end of the block
479 PHINode *NewPHI =
480 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
481 if (AA) AA->copyValue(PN, NewPHI);
482
483 // Move all of the PHI values for 'Preds' to the new PHI.
484 for (unsigned i = 0; i != NumPreds; ++i) {
485 Value *V = PN->removeIncomingValue(Preds[i], false);
486 NewPHI->addIncoming(V, Preds[i]);
487 }
488 InVal = NewPHI;
489 }
490
491 // Add an incoming value to the PHI node in the loop for the preheader
492 // edge.
493 PN->addIncoming(InVal, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000494 }
495
496 return NewBB;
497}
Chris Lattner52c95852008-11-27 08:10:05 +0000498
Mike Stumpfe095f32009-05-04 18:40:41 +0000499/// FindFunctionBackedges - Analyze the specified function to find all of the
500/// loop backedges in the function and return them. This is a relatively cheap
501/// (compared to computing dominators and loop info) analysis.
502///
503/// The output is added to Result, as pairs of <from,to> edge info.
504void llvm::FindFunctionBackedges(const Function &F,
505 SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
506 const BasicBlock *BB = &F.getEntryBlock();
507 if (succ_begin(BB) == succ_end(BB))
508 return;
509
510 SmallPtrSet<const BasicBlock*, 8> Visited;
511 SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
512 SmallPtrSet<const BasicBlock*, 8> InStack;
513
514 Visited.insert(BB);
515 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
516 InStack.insert(BB);
517 do {
518 std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
519 const BasicBlock *ParentBB = Top.first;
520 succ_const_iterator &I = Top.second;
521
522 bool FoundNew = false;
523 while (I != succ_end(ParentBB)) {
524 BB = *I++;
525 if (Visited.insert(BB)) {
526 FoundNew = true;
527 break;
528 }
529 // Successor is in VisitStack, it's a back edge.
530 if (InStack.count(BB))
531 Result.push_back(std::make_pair(ParentBB, BB));
532 }
533
534 if (FoundNew) {
535 // Go down one level if there is a unvisited successor.
536 InStack.insert(BB);
537 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
538 } else {
539 // Go up one level.
540 InStack.erase(VisitStack.pop_back_val().first);
541 }
542 } while (!VisitStack.empty());
543
544
545}
546
547
548
Chris Lattner4aebaee2008-11-27 08:56:30 +0000549/// AreEquivalentAddressValues - Test if A and B will obviously have the same
550/// value. This includes recognizing that %t0 and %t1 will have the same
551/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000552/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000553/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000554/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000555/// %t2 = load i32* %t1
556///
557static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
558 // Test if the values are trivially equivalent.
559 if (A == B) return true;
560
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000561 // Test if the values come from identical arithmetic instructions.
562 // Use isIdenticalToWhenDefined instead of isIdenticalTo because
563 // this function is only used when one address use dominates the
564 // other, which means that they'll always either have the same
565 // value or one of them will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +0000566 if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
567 isa<PHINode>(A) || isa<GetElementPtrInst>(A))
568 if (const Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000569 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000570 return true;
571
572 // Otherwise they may not be equivalent.
573 return false;
574}
575
Chris Lattner52c95852008-11-27 08:10:05 +0000576/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
577/// instruction before ScanFrom) checking to see if we have the value at the
578/// memory address *Ptr locally available within a small number of instructions.
579/// If the value is available, return it.
580///
581/// If not, return the iterator for the last validated instruction that the
582/// value would be live through. If we scanned the entire block and didn't find
583/// something that invalidates *Ptr or provides it, ScanFrom would be left at
584/// begin() and this returns null. ScanFrom could also be left
585///
586/// MaxInstsToScan specifies the maximum instructions to scan in the block. If
587/// it is set to 0, it will scan the whole block. You can also optionally
588/// specify an alias analysis implementation, which makes this more precise.
589Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
590 BasicBlock::iterator &ScanFrom,
591 unsigned MaxInstsToScan,
592 AliasAnalysis *AA) {
593 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
Chris Lattneree6e10b2008-11-27 08:18:12 +0000594
595 // If we're using alias analysis to disambiguate get the size of *Ptr.
596 unsigned AccessSize = 0;
597 if (AA) {
598 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +0000599 AccessSize = AA->getTypeStoreSize(AccessTy);
Chris Lattneree6e10b2008-11-27 08:18:12 +0000600 }
Chris Lattner52c95852008-11-27 08:10:05 +0000601
602 while (ScanFrom != ScanBB->begin()) {
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000603 // We must ignore debug info directives when counting (otherwise they
604 // would affect codegen).
605 Instruction *Inst = --ScanFrom;
606 if (isa<DbgInfoIntrinsic>(Inst))
607 continue;
Dale Johannesend9c05d72009-03-04 02:06:53 +0000608 // We skip pointer-to-pointer bitcasts, which are NOPs.
609 // It is necessary for correctness to skip those that feed into a
610 // llvm.dbg.declare, as these are not present when debugging is off.
611 if (isa<BitCastInst>(Inst) && isa<PointerType>(Inst->getType()))
Dale Johannesen4ded40a2009-03-03 22:36:47 +0000612 continue;
613
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000614 // Restore ScanFrom to expected value in case next test succeeds
615 ScanFrom++;
616
Chris Lattner52c95852008-11-27 08:10:05 +0000617 // Don't scan huge blocks.
618 if (MaxInstsToScan-- == 0) return 0;
619
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000620 --ScanFrom;
Chris Lattner52c95852008-11-27 08:10:05 +0000621 // If this is a load of Ptr, the loaded value is available.
622 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000623 if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000624 return LI;
625
626 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
627 // If this is a store through Ptr, the value is available!
Chris Lattner4aebaee2008-11-27 08:56:30 +0000628 if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000629 return SI->getOperand(0);
630
631 // If Ptr is an alloca and this is a store to a different alloca, ignore
632 // the store. This is a trivial form of alias analysis that is important
633 // for reg2mem'd code.
634 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
635 (isa<AllocaInst>(SI->getOperand(1)) ||
636 isa<GlobalVariable>(SI->getOperand(1))))
637 continue;
638
Chris Lattneree6e10b2008-11-27 08:18:12 +0000639 // If we have alias analysis and it says the store won't modify the loaded
640 // value, ignore the store.
641 if (AA &&
642 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
643 continue;
644
Chris Lattner52c95852008-11-27 08:10:05 +0000645 // Otherwise the store that may or may not alias the pointer, bail out.
646 ++ScanFrom;
647 return 0;
648 }
649
Chris Lattner52c95852008-11-27 08:10:05 +0000650 // If this is some other instruction that may clobber Ptr, bail out.
651 if (Inst->mayWriteToMemory()) {
Chris Lattneree6e10b2008-11-27 08:18:12 +0000652 // If alias analysis claims that it really won't modify the load,
653 // ignore it.
654 if (AA &&
655 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
656 continue;
657
Chris Lattner52c95852008-11-27 08:10:05 +0000658 // May modify the pointer, bail out.
659 ++ScanFrom;
660 return 0;
661 }
662 }
663
664 // Got to the start of the block, we didn't find it, but are done for this
665 // block.
666 return 0;
667}
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000668
669/// CopyPrecedingStopPoint - If I is immediately preceded by a StopPoint,
670/// make a copy of the stoppoint before InsertPos (presumably before copying
671/// or moving I).
672void llvm::CopyPrecedingStopPoint(Instruction *I,
673 BasicBlock::iterator InsertPos) {
674 if (I != I->getParent()->begin()) {
675 BasicBlock::iterator BBI = I; --BBI;
676 if (DbgStopPointInst *DSPI = dyn_cast<DbgStopPointInst>(BBI)) {
Devang Patel50b6e332009-10-27 22:16:29 +0000677 CallInst *newDSPI = cast<CallInst>(DSPI->clone());
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000678 newDSPI->insertBefore(InsertPos);
679 }
680 }
681}