blob: c728c0bd5f1cdc29f85db3e3ab95429ce5833167 [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.
Chris Lattner88202922009-11-01 04:57:33 +000097bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P) {
Dan Gohman438b5832009-10-31 17:33:01 +000098 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
Chris Lattner88202922009-11-01 04:57:33 +000099 // Can't merge the entry block. Don't merge away blocks who have their
100 // address taken: this is a bug if the predecessor block is the entry node
101 // (because we'd end up taking the address of the entry) and undesirable in
102 // any case.
103 if (pred_begin(BB) == pred_end(BB) ||
104 BB->hasAddressTaken()) return false;
Owen Anderson11f2ec82008-07-17 19:42:29 +0000105
Dan Gohman438b5832009-10-31 17:33:01 +0000106 BasicBlock *PredBB = *PI++;
107 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
108 if (*PI != PredBB) {
109 PredBB = 0; // There are multiple different predecessors...
110 break;
111 }
112
113 // Can't merge if there are multiple predecessors.
114 if (!PredBB) return false;
115 // Don't break self-loops.
116 if (PredBB == BB) return false;
117 // Don't break invokes.
118 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
119
120 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
121 BasicBlock* OnlySucc = BB;
122 for (; SI != SE; ++SI)
123 if (*SI != OnlySucc) {
124 OnlySucc = 0; // There are multiple distinct successors!
125 break;
126 }
127
128 // Can't merge if there are multiple successors.
129 if (!OnlySucc) return false;
Devang Patele435a5d2008-09-09 01:06:56 +0000130
Dan Gohman438b5832009-10-31 17:33:01 +0000131 // Can't merge if there is PHI loop.
132 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
133 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
134 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
135 if (PN->getIncomingValue(i) == PN)
136 return false;
137 } else
138 break;
139 }
140
141 // Begin by getting rid of unneeded PHIs.
142 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
143 PN->replaceAllUsesWith(PN->getIncomingValue(0));
144 BB->getInstList().pop_front(); // Delete the phi node...
145 }
146
Owen Andersonb31b06d2008-07-17 00:01:40 +0000147 // Delete the unconditional branch from the predecessor...
148 PredBB->getInstList().pop_back();
149
150 // Move all definitions in the successor to the predecessor...
151 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
152
153 // Make all PHI nodes that referred to BB now refer to Pred as their
154 // source...
155 BB->replaceAllUsesWith(PredBB);
156
Dan Gohman438b5832009-10-31 17:33:01 +0000157 // Inherit predecessors name if it exists.
Owen Anderson11f2ec82008-07-17 19:42:29 +0000158 if (!PredBB->hasName())
159 PredBB->takeName(BB);
160
Owen Andersonb31b06d2008-07-17 00:01:40 +0000161 // Finally, erase the old block and update dominator info.
162 if (P) {
Duncan Sands1465d612009-01-28 13:14:17 +0000163 if (DominatorTree* DT = P->getAnalysisIfAvailable<DominatorTree>()) {
Owen Andersonb31b06d2008-07-17 00:01:40 +0000164 DomTreeNode* DTN = DT->getNode(BB);
165 DomTreeNode* PredDTN = DT->getNode(PredBB);
166
167 if (DTN) {
168 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
169 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
170 DE = Children.end(); DI != DE; ++DI)
171 DT->changeImmediateDominator(*DI, PredDTN);
172
173 DT->eraseNode(BB);
174 }
175 }
176 }
177
178 BB->eraseFromParent();
179
Dan Gohman438b5832009-10-31 17:33:01 +0000180
181 return true;
Owen Andersonb31b06d2008-07-17 00:01:40 +0000182}
183
Chris Lattner0f67dd62005-04-21 16:04:49 +0000184/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
185/// with a value, then remove and delete the original instruction.
186///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000187void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
188 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000189 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000190 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000191 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000192
Chris Lattner86cc4232007-02-11 01:37:51 +0000193 // Make sure to propagate a name if there is one already.
194 if (I.hasName() && !V->hasName())
195 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000196
Misha Brukman5560c9d2003-08-18 14:43:39 +0000197 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000198 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000199}
200
201
Chris Lattner0f67dd62005-04-21 16:04:49 +0000202/// ReplaceInstWithInst - Replace the instruction specified by BI with the
203/// instruction specified by I. The original instruction is deleted and BI is
204/// updated to point to the new instruction.
205///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000206void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
207 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000208 assert(I->getParent() == 0 &&
209 "ReplaceInstWithInst: Instruction already inserted into basic block!");
210
211 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000212 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000213
214 // Replace all uses of the old instruction, and delete it.
215 ReplaceInstWithValue(BIL, BI, I);
216
217 // Move BI back to point to the newly inserted instruction
Chris Lattner18961502002-06-25 16:12:52 +0000218 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000219}
220
Chris Lattner0f67dd62005-04-21 16:04:49 +0000221/// ReplaceInstWithInst - Replace the instruction specified by From with the
222/// instruction specified by To.
223///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000224void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000225 BasicBlock::iterator BI(From);
226 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000227}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000228
Chris Lattner0f67dd62005-04-21 16:04:49 +0000229/// RemoveSuccessor - Change the specified terminator instruction such that its
Reid Spencerbc2eba12006-05-19 19:09:46 +0000230/// successor SuccNum no longer exists. Because this reduces the outgoing
Chris Lattner0f67dd62005-04-21 16:04:49 +0000231/// degree of the current basic block, the actual terminator instruction itself
Reid Spencerbc2eba12006-05-19 19:09:46 +0000232/// may have to be changed. In the case where the last successor of the block
233/// is deleted, a return instruction is inserted in its place which can cause a
Chris Lattner0f67dd62005-04-21 16:04:49 +0000234/// surprising change in program behavior if it is not expected.
235///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000236void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000237 assert(SuccNum < TI->getNumSuccessors() &&
238 "Trying to remove a nonexistant successor!");
239
240 // If our old successor block contains any PHI nodes, remove the entry in the
241 // PHI nodes that comes from this branch...
242 //
243 BasicBlock *BB = TI->getParent();
244 TI->getSuccessor(SuccNum)->removePredecessor(BB);
245
246 TerminatorInst *NewTI = 0;
247 switch (TI->getOpcode()) {
248 case Instruction::Br:
249 // If this is a conditional branch... convert to unconditional branch.
250 if (TI->getNumSuccessors() == 2) {
251 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
252 } else { // Otherwise convert to a return instruction...
253 Value *RetVal = 0;
Misha Brukmanfd939082005-04-21 23:48:37 +0000254
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000255 // Create a value to return... if the function doesn't return null...
Owen Anderson1d0be152009-08-13 21:58:54 +0000256 if (BB->getParent()->getReturnType() != Type::getVoidTy(TI->getContext()))
Owen Andersona7235ea2009-07-31 20:28:14 +0000257 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000258
259 // Create the return...
Owen Anderson1d0be152009-08-13 21:58:54 +0000260 NewTI = ReturnInst::Create(TI->getContext(), RetVal);
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000261 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000262 break;
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000263
264 case Instruction::Invoke: // Should convert to call
265 case Instruction::Switch: // Should remove entry
266 default:
267 case Instruction::Ret: // Cannot happen, has no successors!
Torok Edwinc23197a2009-07-14 16:55:14 +0000268 llvm_unreachable("Unhandled terminator instruction type in RemoveSuccessor!");
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000269 }
270
271 if (NewTI) // If it's a different instruction, replace.
272 ReplaceInstWithInst(TI, NewTI);
273}
Brian Gaeked0fde302003-11-11 22:41:34 +0000274
Devang Patel80198932007-07-06 21:39:20 +0000275/// SplitEdge - Split the edge connecting specified block. Pass P must
276/// not be NULL.
277BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
Chris Lattnera4b04212009-10-31 22:04:43 +0000278 assert(!isa<IndirectBrInst>(BB->getTerminator()) &&
279 "Cannot split an edge from an IndirectBrInst");
Devang Patel80198932007-07-06 21:39:20 +0000280 TerminatorInst *LatchTerm = BB->getTerminator();
281 unsigned SuccNum = 0;
Devang Patel8a88a142008-11-03 23:14:09 +0000282#ifndef NDEBUG
283 unsigned e = LatchTerm->getNumSuccessors();
284#endif
285 for (unsigned i = 0; ; ++i) {
Devang Patel80198932007-07-06 21:39:20 +0000286 assert(i != e && "Didn't find edge?");
287 if (LatchTerm->getSuccessor(i) == Succ) {
288 SuccNum = i;
289 break;
290 }
291 }
292
293 // If this is a critical edge, let SplitCriticalEdge do it.
294 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
295 return LatchTerm->getSuccessor(SuccNum);
296
297 // If the edge isn't critical, then BB has a single successor or Succ has a
298 // single pred. Split the block.
299 BasicBlock::iterator SplitPoint;
300 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
301 // If the successor only has a single pred, split the top of the successor
302 // block.
303 assert(SP == BB && "CFG broken");
Devang Patel8a88a142008-11-03 23:14:09 +0000304 SP = NULL;
Devang Patel80198932007-07-06 21:39:20 +0000305 return SplitBlock(Succ, Succ->begin(), P);
306 } else {
307 // Otherwise, if BB has a single successor, split it at the bottom of the
308 // block.
309 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
310 "Should have a single succ!");
311 return SplitBlock(BB, BB->getTerminator(), P);
312 }
313}
314
315/// SplitBlock - Split the specified block at the specified instruction - every
316/// thing before SplitPt stays in Old and everything starting with SplitPt moves
317/// to a new block. The two blocks are joined by an unconditional branch and
318/// the loop info is updated.
319///
320BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
Devang Patel80198932007-07-06 21:39:20 +0000321 BasicBlock::iterator SplitIt = SplitPt;
322 while (isa<PHINode>(SplitIt))
323 ++SplitIt;
324 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
325
Dan Gohman5c89b522009-09-08 15:45:00 +0000326 // The new block lives in whichever loop the old one did. This preserves
327 // LCSSA as well, because we force the split point to be after any PHI nodes.
Duncan Sands1465d612009-01-28 13:14:17 +0000328 if (LoopInfo* LI = P->getAnalysisIfAvailable<LoopInfo>())
Owen Andersona90793b2008-10-03 06:55:35 +0000329 if (Loop *L = LI->getLoopFor(Old))
330 L->addBasicBlockToLoop(New, LI->getBase());
Devang Patel80198932007-07-06 21:39:20 +0000331
Duncan Sands1465d612009-01-28 13:14:17 +0000332 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>())
Devang Patela8a8a362007-07-19 02:29:24 +0000333 {
334 // Old dominates New. New node domiantes all other nodes dominated by Old.
335 DomTreeNode *OldNode = DT->getNode(Old);
336 std::vector<DomTreeNode *> Children;
337 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
338 I != E; ++I)
339 Children.push_back(*I);
340
341 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
342
343 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
344 E = Children.end(); I != E; ++I)
345 DT->changeImmediateDominator(*I, NewNode);
346 }
Devang Patel80198932007-07-06 21:39:20 +0000347
Duncan Sands1465d612009-01-28 13:14:17 +0000348 if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
Devang Patel80198932007-07-06 21:39:20 +0000349 DF->splitBlock(Old);
350
351 return New;
352}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000353
354
355/// SplitBlockPredecessors - This method transforms BB by introducing a new
356/// basic block into the function, and moving some of the predecessors of BB to
357/// be predecessors of the new block. The new predecessors are indicated by the
358/// Preds array, which has NumPreds elements in it. The new block is given a
359/// suffix of 'Suffix'.
360///
Dan Gohman5c89b522009-09-08 15:45:00 +0000361/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
362/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses.
363/// In particular, it does not preserve LoopSimplify (because it's
364/// complicated to handle the case where one of the edges being split
365/// is an exit of a loop with other exits).
366///
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000367BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
368 BasicBlock *const *Preds,
369 unsigned NumPreds, const char *Suffix,
370 Pass *P) {
371 // Create new basic block, insert right before the original block.
Owen Anderson1d0be152009-08-13 21:58:54 +0000372 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
373 BB->getParent(), BB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000374
375 // The new block unconditionally branches to the old block.
376 BranchInst *BI = BranchInst::Create(BB, NewBB);
377
Dan Gohman5c89b522009-09-08 15:45:00 +0000378 LoopInfo *LI = P ? P->getAnalysisIfAvailable<LoopInfo>() : 0;
379 Loop *L = LI ? LI->getLoopFor(BB) : 0;
380 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
381
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000382 // Move the edges from Preds to point to NewBB instead of BB.
Dan Gohman5c89b522009-09-08 15:45:00 +0000383 // While here, if we need to preserve loop analyses, collect
384 // some information about how this split will affect loops.
385 bool HasLoopExit = false;
386 bool IsLoopEntry = !!L;
387 bool SplitMakesNewLoopHeader = false;
388 for (unsigned i = 0; i != NumPreds; ++i) {
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000389 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000390
391 if (LI) {
392 // If we need to preserve LCSSA, determine if any of
393 // the preds is a loop exit.
394 if (PreserveLCSSA)
395 if (Loop *PL = LI->getLoopFor(Preds[i]))
396 if (!PL->contains(BB))
397 HasLoopExit = true;
398 // If we need to preserve LoopInfo, note whether any of the
399 // preds crosses an interesting loop boundary.
400 if (L) {
401 if (L->contains(Preds[i]))
402 IsLoopEntry = false;
403 else
404 SplitMakesNewLoopHeader = true;
405 }
406 }
407 }
408
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000409 // Update dominator tree and dominator frontier if available.
Duncan Sands1465d612009-01-28 13:14:17 +0000410 DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000411 if (DT)
412 DT->splitBlock(NewBB);
Duncan Sands1465d612009-01-28 13:14:17 +0000413 if (DominanceFrontier *DF = P ? P->getAnalysisIfAvailable<DominanceFrontier>():0)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000414 DF->splitBlock(NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000415
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000416 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
417 // node becomes an incoming value for BB's phi node. However, if the Preds
418 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
419 // account for the newly created predecessor.
420 if (NumPreds == 0) {
421 // Insert dummy values as the incoming value.
422 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000423 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000424 return NewBB;
425 }
Dan Gohman5c89b522009-09-08 15:45:00 +0000426
427 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
428
429 if (L) {
430 if (IsLoopEntry) {
Dan Gohman841a1472009-10-19 16:04:50 +0000431 // Add the new block to the nearest enclosing loop (and not an
432 // adjacent loop). To find this, examine each of the predecessors and
433 // determine which loops enclose them, and select the most-nested loop
434 // which contains the loop containing the block being split.
435 Loop *InnermostPredLoop = 0;
436 for (unsigned i = 0; i != NumPreds; ++i)
437 if (Loop *PredLoop = LI->getLoopFor(Preds[i])) {
438 // Seek a loop which actually contains the block being split (to
439 // avoid adjacent loops).
440 while (PredLoop && !PredLoop->contains(BB))
441 PredLoop = PredLoop->getParentLoop();
442 // Select the most-nested of these loops which contains the block.
443 if (PredLoop &&
444 PredLoop->contains(BB) &&
445 (!InnermostPredLoop ||
446 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
447 InnermostPredLoop = PredLoop;
448 }
449 if (InnermostPredLoop)
450 InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
Dan Gohman5c89b522009-09-08 15:45:00 +0000451 } else {
452 L->addBasicBlockToLoop(NewBB, LI->getBase());
453 if (SplitMakesNewLoopHeader)
454 L->moveToHeader(NewBB);
455 }
456 }
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000457
458 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
459 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
460 PHINode *PN = cast<PHINode>(I++);
461
462 // Check to see if all of the values coming in are the same. If so, we
Dan Gohman5c89b522009-09-08 15:45:00 +0000463 // don't need to create a new PHI node, unless it's needed for LCSSA.
464 Value *InVal = 0;
465 if (!HasLoopExit) {
466 InVal = PN->getIncomingValueForBlock(Preds[0]);
467 for (unsigned i = 1; i != NumPreds; ++i)
468 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
469 InVal = 0;
470 break;
471 }
472 }
473
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000474 if (InVal) {
475 // If all incoming values for the new PHI would be the same, just don't
476 // make a new PHI. Instead, just remove the incoming values from the old
477 // PHI.
478 for (unsigned i = 0; i != NumPreds; ++i)
479 PN->removeIncomingValue(Preds[i], false);
480 } else {
481 // If the values coming into the block are not the same, we need a PHI.
482 // Create the new PHI node, insert it into NewBB at the end of the block
483 PHINode *NewPHI =
484 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
485 if (AA) AA->copyValue(PN, NewPHI);
486
487 // Move all of the PHI values for 'Preds' to the new PHI.
488 for (unsigned i = 0; i != NumPreds; ++i) {
489 Value *V = PN->removeIncomingValue(Preds[i], false);
490 NewPHI->addIncoming(V, Preds[i]);
491 }
492 InVal = NewPHI;
493 }
494
495 // Add an incoming value to the PHI node in the loop for the preheader
496 // edge.
497 PN->addIncoming(InVal, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000498 }
499
500 return NewBB;
501}
Chris Lattner52c95852008-11-27 08:10:05 +0000502
Mike Stumpfe095f32009-05-04 18:40:41 +0000503/// FindFunctionBackedges - Analyze the specified function to find all of the
504/// loop backedges in the function and return them. This is a relatively cheap
505/// (compared to computing dominators and loop info) analysis.
506///
507/// The output is added to Result, as pairs of <from,to> edge info.
508void llvm::FindFunctionBackedges(const Function &F,
509 SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
510 const BasicBlock *BB = &F.getEntryBlock();
511 if (succ_begin(BB) == succ_end(BB))
512 return;
513
514 SmallPtrSet<const BasicBlock*, 8> Visited;
515 SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
516 SmallPtrSet<const BasicBlock*, 8> InStack;
517
518 Visited.insert(BB);
519 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
520 InStack.insert(BB);
521 do {
522 std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
523 const BasicBlock *ParentBB = Top.first;
524 succ_const_iterator &I = Top.second;
525
526 bool FoundNew = false;
527 while (I != succ_end(ParentBB)) {
528 BB = *I++;
529 if (Visited.insert(BB)) {
530 FoundNew = true;
531 break;
532 }
533 // Successor is in VisitStack, it's a back edge.
534 if (InStack.count(BB))
535 Result.push_back(std::make_pair(ParentBB, BB));
536 }
537
538 if (FoundNew) {
539 // Go down one level if there is a unvisited successor.
540 InStack.insert(BB);
541 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
542 } else {
543 // Go up one level.
544 InStack.erase(VisitStack.pop_back_val().first);
545 }
546 } while (!VisitStack.empty());
547
548
549}
550
551
552
Chris Lattner4aebaee2008-11-27 08:56:30 +0000553/// AreEquivalentAddressValues - Test if A and B will obviously have the same
554/// value. This includes recognizing that %t0 and %t1 will have the same
555/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000556/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000557/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000558/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000559/// %t2 = load i32* %t1
560///
561static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
562 // Test if the values are trivially equivalent.
563 if (A == B) return true;
564
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000565 // Test if the values come from identical arithmetic instructions.
566 // Use isIdenticalToWhenDefined instead of isIdenticalTo because
567 // this function is only used when one address use dominates the
568 // other, which means that they'll always either have the same
569 // value or one of them will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +0000570 if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
571 isa<PHINode>(A) || isa<GetElementPtrInst>(A))
572 if (const Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000573 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000574 return true;
575
576 // Otherwise they may not be equivalent.
577 return false;
578}
579
Chris Lattner52c95852008-11-27 08:10:05 +0000580/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
581/// instruction before ScanFrom) checking to see if we have the value at the
582/// memory address *Ptr locally available within a small number of instructions.
583/// If the value is available, return it.
584///
585/// If not, return the iterator for the last validated instruction that the
586/// value would be live through. If we scanned the entire block and didn't find
587/// something that invalidates *Ptr or provides it, ScanFrom would be left at
588/// begin() and this returns null. ScanFrom could also be left
589///
590/// MaxInstsToScan specifies the maximum instructions to scan in the block. If
591/// it is set to 0, it will scan the whole block. You can also optionally
592/// specify an alias analysis implementation, which makes this more precise.
593Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
594 BasicBlock::iterator &ScanFrom,
595 unsigned MaxInstsToScan,
596 AliasAnalysis *AA) {
597 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
Chris Lattneree6e10b2008-11-27 08:18:12 +0000598
599 // If we're using alias analysis to disambiguate get the size of *Ptr.
600 unsigned AccessSize = 0;
601 if (AA) {
602 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +0000603 AccessSize = AA->getTypeStoreSize(AccessTy);
Chris Lattneree6e10b2008-11-27 08:18:12 +0000604 }
Chris Lattner52c95852008-11-27 08:10:05 +0000605
606 while (ScanFrom != ScanBB->begin()) {
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000607 // We must ignore debug info directives when counting (otherwise they
608 // would affect codegen).
609 Instruction *Inst = --ScanFrom;
610 if (isa<DbgInfoIntrinsic>(Inst))
611 continue;
Dale Johannesend9c05d72009-03-04 02:06:53 +0000612 // We skip pointer-to-pointer bitcasts, which are NOPs.
613 // It is necessary for correctness to skip those that feed into a
614 // llvm.dbg.declare, as these are not present when debugging is off.
615 if (isa<BitCastInst>(Inst) && isa<PointerType>(Inst->getType()))
Dale Johannesen4ded40a2009-03-03 22:36:47 +0000616 continue;
617
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000618 // Restore ScanFrom to expected value in case next test succeeds
619 ScanFrom++;
620
Chris Lattner52c95852008-11-27 08:10:05 +0000621 // Don't scan huge blocks.
622 if (MaxInstsToScan-- == 0) return 0;
623
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000624 --ScanFrom;
Chris Lattner52c95852008-11-27 08:10:05 +0000625 // If this is a load of Ptr, the loaded value is available.
626 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000627 if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000628 return LI;
629
630 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
631 // If this is a store through Ptr, the value is available!
Chris Lattner4aebaee2008-11-27 08:56:30 +0000632 if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000633 return SI->getOperand(0);
634
635 // If Ptr is an alloca and this is a store to a different alloca, ignore
636 // the store. This is a trivial form of alias analysis that is important
637 // for reg2mem'd code.
638 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
639 (isa<AllocaInst>(SI->getOperand(1)) ||
640 isa<GlobalVariable>(SI->getOperand(1))))
641 continue;
642
Chris Lattneree6e10b2008-11-27 08:18:12 +0000643 // If we have alias analysis and it says the store won't modify the loaded
644 // value, ignore the store.
645 if (AA &&
646 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
647 continue;
648
Chris Lattner52c95852008-11-27 08:10:05 +0000649 // Otherwise the store that may or may not alias the pointer, bail out.
650 ++ScanFrom;
651 return 0;
652 }
653
Chris Lattner52c95852008-11-27 08:10:05 +0000654 // If this is some other instruction that may clobber Ptr, bail out.
655 if (Inst->mayWriteToMemory()) {
Chris Lattneree6e10b2008-11-27 08:18:12 +0000656 // If alias analysis claims that it really won't modify the load,
657 // ignore it.
658 if (AA &&
659 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
660 continue;
661
Chris Lattner52c95852008-11-27 08:10:05 +0000662 // May modify the pointer, bail out.
663 ++ScanFrom;
664 return 0;
665 }
666 }
667
668 // Got to the start of the block, we didn't find it, but are done for this
669 // block.
670 return 0;
671}
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000672
673/// CopyPrecedingStopPoint - If I is immediately preceded by a StopPoint,
674/// make a copy of the stoppoint before InsertPos (presumably before copying
675/// or moving I).
676void llvm::CopyPrecedingStopPoint(Instruction *I,
677 BasicBlock::iterator InsertPos) {
678 if (I != I->getParent()->begin()) {
679 BasicBlock::iterator BBI = I; --BBI;
680 if (DbgStopPointInst *DSPI = dyn_cast<DbgStopPointInst>(BBI)) {
Devang Patel50b6e332009-10-27 22:16:29 +0000681 CallInst *newDSPI = cast<CallInst>(DSPI->clone());
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000682 newDSPI->insertBefore(InsertPos);
683 }
684 }
685}