blob: e6522749bccfc6562630c55cb34a9be60eac21b8 [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"
Torok Edwin7d696d82009-07-11 13:10:19 +000027#include "llvm/Support/ErrorHandling.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000028#include "llvm/Support/ValueHandle.h"
Chris Lattner4d1e46e2002-05-07 18:07:59 +000029#include <algorithm>
Chris Lattnerf7703df2004-01-09 06:12:26 +000030using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000031
Chris Lattner71af9b02008-12-03 06:40:52 +000032/// DeleteDeadBlock - Delete the specified block, which must have no
33/// predecessors.
34void llvm::DeleteDeadBlock(BasicBlock *BB) {
Chris Lattner2973a252008-12-03 07:45:15 +000035 assert((pred_begin(BB) == pred_end(BB) ||
36 // Can delete self loop.
37 BB->getSinglePredecessor() == BB) && "Block is not dead!");
Chris Lattner2b1ba242008-12-03 06:37:44 +000038 TerminatorInst *BBTerm = BB->getTerminator();
Devang Patel5622f072009-02-24 00:05:16 +000039
Chris Lattner2b1ba242008-12-03 06:37:44 +000040 // Loop through all of our successors and make sure they know that one
41 // of their predecessors is going away.
42 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
43 BBTerm->getSuccessor(i)->removePredecessor(BB);
44
45 // Zap all the instructions in the block.
46 while (!BB->empty()) {
47 Instruction &I = BB->back();
48 // If this instruction is used, replace uses with an arbitrary value.
49 // Because control flow can't get here, we don't care what we replace the
50 // value with. Note that since this block is unreachable, and all values
51 // contained within it must dominate their uses, that all uses will
52 // eventually be removed (they are themselves dead).
53 if (!I.use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000054 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner2b1ba242008-12-03 06:37:44 +000055 BB->getInstList().pop_back();
56 }
Devang Patel5622f072009-02-24 00:05:16 +000057
Chris Lattner2b1ba242008-12-03 06:37:44 +000058 // Zap the block!
59 BB->eraseFromParent();
Chris Lattner2b1ba242008-12-03 06:37:44 +000060}
61
Chris Lattner29874e02008-12-03 19:44:02 +000062/// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are
63/// any single-entry PHI nodes in it, fold them away. This handles the case
64/// when all entries to the PHI nodes in a block are guaranteed equal, such as
65/// when the block has exactly one predecessor.
66void llvm::FoldSingleEntryPHINodes(BasicBlock *BB) {
67 if (!isa<PHINode>(BB->begin()))
68 return;
69
70 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
71 if (PN->getIncomingValue(0) != PN)
72 PN->replaceAllUsesWith(PN->getIncomingValue(0));
73 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000074 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner29874e02008-12-03 19:44:02 +000075 PN->eraseFromParent();
76 }
77}
78
79
Dan Gohmanafc36a92009-05-02 18:29:22 +000080/// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
81/// is dead. Also recursively delete any operands that become dead as
82/// a result. This includes tracing the def-use list from the PHI to see if
Dan Gohman35738ac2009-05-04 22:30:44 +000083/// it is ultimately unused or if it reaches an unused cycle.
84void llvm::DeleteDeadPHIs(BasicBlock *BB) {
Dan Gohmanafc36a92009-05-02 18:29:22 +000085 // Recursively deleting a PHI may cause multiple PHIs to be deleted
86 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
87 SmallVector<WeakVH, 8> PHIs;
88 for (BasicBlock::iterator I = BB->begin();
89 PHINode *PN = dyn_cast<PHINode>(I); ++I)
90 PHIs.push_back(PN);
91
92 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
93 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Dan Gohman35738ac2009-05-04 22:30:44 +000094 RecursivelyDeleteDeadPHINode(PN);
Dan Gohmanafc36a92009-05-02 18:29:22 +000095}
96
Owen Andersonb31b06d2008-07-17 00:01:40 +000097/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
98/// if possible. The return value indicates success or failure.
99bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
Owen Anderson11f2ec82008-07-17 19:42:29 +0000100 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
Owen Andersonb31b06d2008-07-17 00:01:40 +0000101 // Can't merge the entry block.
102 if (pred_begin(BB) == pred_end(BB)) return false;
Owen Andersonb31b06d2008-07-17 00:01:40 +0000103
Owen Anderson11f2ec82008-07-17 19:42:29 +0000104 BasicBlock *PredBB = *PI++;
105 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
106 if (*PI != PredBB) {
107 PredBB = 0; // There are multiple different predecessors...
108 break;
109 }
Owen Andersonb31b06d2008-07-17 00:01:40 +0000110
Owen Anderson11f2ec82008-07-17 19:42:29 +0000111 // Can't merge if there are multiple predecessors.
112 if (!PredBB) return false;
Owen Anderson3ecaf1b2008-07-18 17:46:41 +0000113 // Don't break self-loops.
114 if (PredBB == BB) return false;
115 // Don't break invokes.
116 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
Owen Anderson11f2ec82008-07-17 19:42:29 +0000117
118 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
119 BasicBlock* OnlySucc = BB;
120 for (; SI != SE; ++SI)
121 if (*SI != OnlySucc) {
122 OnlySucc = 0; // There are multiple distinct successors!
123 break;
124 }
125
126 // Can't merge if there are multiple successors.
127 if (!OnlySucc) return false;
Devang Patele435a5d2008-09-09 01:06:56 +0000128
129 // Can't merge if there is PHI loop.
130 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
131 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
132 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
133 if (PN->getIncomingValue(i) == PN)
134 return false;
135 } else
136 break;
137 }
138
Owen Andersonb31b06d2008-07-17 00:01:40 +0000139 // Begin by getting rid of unneeded PHIs.
140 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
141 PN->replaceAllUsesWith(PN->getIncomingValue(0));
142 BB->getInstList().pop_front(); // Delete the phi node...
143 }
144
145 // Delete the unconditional branch from the predecessor...
146 PredBB->getInstList().pop_back();
147
148 // Move all definitions in the successor to the predecessor...
149 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
150
151 // Make all PHI nodes that referred to BB now refer to Pred as their
152 // source...
153 BB->replaceAllUsesWith(PredBB);
154
Owen Anderson11f2ec82008-07-17 19:42:29 +0000155 // Inherit predecessors name if it exists.
156 if (!PredBB->hasName())
157 PredBB->takeName(BB);
158
Owen Andersonb31b06d2008-07-17 00:01:40 +0000159 // Finally, erase the old block and update dominator info.
160 if (P) {
Duncan Sands1465d612009-01-28 13:14:17 +0000161 if (DominatorTree* DT = P->getAnalysisIfAvailable<DominatorTree>()) {
Owen Andersonb31b06d2008-07-17 00:01:40 +0000162 DomTreeNode* DTN = DT->getNode(BB);
163 DomTreeNode* PredDTN = DT->getNode(PredBB);
164
165 if (DTN) {
166 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
167 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
168 DE = Children.end(); DI != DE; ++DI)
169 DT->changeImmediateDominator(*DI, PredDTN);
170
171 DT->eraseNode(BB);
172 }
173 }
174 }
175
176 BB->eraseFromParent();
177
178
179 return true;
180}
181
Chris Lattner0f67dd62005-04-21 16:04:49 +0000182/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
183/// with a value, then remove and delete the original instruction.
184///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000185void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
186 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000187 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000188 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000189 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000190
Chris Lattner86cc4232007-02-11 01:37:51 +0000191 // Make sure to propagate a name if there is one already.
192 if (I.hasName() && !V->hasName())
193 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000194
Misha Brukman5560c9d2003-08-18 14:43:39 +0000195 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000196 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000197}
198
199
Chris Lattner0f67dd62005-04-21 16:04:49 +0000200/// ReplaceInstWithInst - Replace the instruction specified by BI with the
201/// instruction specified by I. The original instruction is deleted and BI is
202/// updated to point to the new instruction.
203///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000204void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
205 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000206 assert(I->getParent() == 0 &&
207 "ReplaceInstWithInst: Instruction already inserted into basic block!");
208
209 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000210 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000211
212 // Replace all uses of the old instruction, and delete it.
213 ReplaceInstWithValue(BIL, BI, I);
214
215 // Move BI back to point to the newly inserted instruction
Chris Lattner18961502002-06-25 16:12:52 +0000216 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000217}
218
Chris Lattner0f67dd62005-04-21 16:04:49 +0000219/// ReplaceInstWithInst - Replace the instruction specified by From with the
220/// instruction specified by To.
221///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000222void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000223 BasicBlock::iterator BI(From);
224 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000225}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000226
Chris Lattner0f67dd62005-04-21 16:04:49 +0000227/// RemoveSuccessor - Change the specified terminator instruction such that its
Reid Spencerbc2eba12006-05-19 19:09:46 +0000228/// successor SuccNum no longer exists. Because this reduces the outgoing
Chris Lattner0f67dd62005-04-21 16:04:49 +0000229/// degree of the current basic block, the actual terminator instruction itself
Reid Spencerbc2eba12006-05-19 19:09:46 +0000230/// may have to be changed. In the case where the last successor of the block
231/// is deleted, a return instruction is inserted in its place which can cause a
Chris Lattner0f67dd62005-04-21 16:04:49 +0000232/// surprising change in program behavior if it is not expected.
233///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000234void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000235 assert(SuccNum < TI->getNumSuccessors() &&
236 "Trying to remove a nonexistant successor!");
237
238 // If our old successor block contains any PHI nodes, remove the entry in the
239 // PHI nodes that comes from this branch...
240 //
241 BasicBlock *BB = TI->getParent();
242 TI->getSuccessor(SuccNum)->removePredecessor(BB);
243
244 TerminatorInst *NewTI = 0;
245 switch (TI->getOpcode()) {
246 case Instruction::Br:
247 // If this is a conditional branch... convert to unconditional branch.
248 if (TI->getNumSuccessors() == 2) {
249 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
250 } else { // Otherwise convert to a return instruction...
251 Value *RetVal = 0;
Misha Brukmanfd939082005-04-21 23:48:37 +0000252
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000253 // Create a value to return... if the function doesn't return null...
254 if (BB->getParent()->getReturnType() != Type::VoidTy)
Owen Andersone922c022009-07-22 00:24:57 +0000255 RetVal = TI->getContext().getNullValue(
Owen Anderson0a205a42009-07-05 22:41:43 +0000256 BB->getParent()->getReturnType());
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000257
258 // Create the return...
Gabor Greif051a9502008-04-06 20:25:17 +0000259 NewTI = ReturnInst::Create(RetVal);
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000260 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000261 break;
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000262
263 case Instruction::Invoke: // Should convert to call
264 case Instruction::Switch: // Should remove entry
265 default:
266 case Instruction::Ret: // Cannot happen, has no successors!
Torok Edwinc23197a2009-07-14 16:55:14 +0000267 llvm_unreachable("Unhandled terminator instruction type in RemoveSuccessor!");
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000268 }
269
270 if (NewTI) // If it's a different instruction, replace.
271 ReplaceInstWithInst(TI, NewTI);
272}
Brian Gaeked0fde302003-11-11 22:41:34 +0000273
Devang Patel80198932007-07-06 21:39:20 +0000274/// SplitEdge - Split the edge connecting specified block. Pass P must
275/// not be NULL.
276BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
277 TerminatorInst *LatchTerm = BB->getTerminator();
278 unsigned SuccNum = 0;
Devang Patel8a88a142008-11-03 23:14:09 +0000279#ifndef NDEBUG
280 unsigned e = LatchTerm->getNumSuccessors();
281#endif
282 for (unsigned i = 0; ; ++i) {
Devang Patel80198932007-07-06 21:39:20 +0000283 assert(i != e && "Didn't find edge?");
284 if (LatchTerm->getSuccessor(i) == Succ) {
285 SuccNum = i;
286 break;
287 }
288 }
289
290 // If this is a critical edge, let SplitCriticalEdge do it.
291 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
292 return LatchTerm->getSuccessor(SuccNum);
293
294 // If the edge isn't critical, then BB has a single successor or Succ has a
295 // single pred. Split the block.
296 BasicBlock::iterator SplitPoint;
297 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
298 // If the successor only has a single pred, split the top of the successor
299 // block.
300 assert(SP == BB && "CFG broken");
Devang Patel8a88a142008-11-03 23:14:09 +0000301 SP = NULL;
Devang Patel80198932007-07-06 21:39:20 +0000302 return SplitBlock(Succ, Succ->begin(), P);
303 } else {
304 // Otherwise, if BB has a single successor, split it at the bottom of the
305 // block.
306 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
307 "Should have a single succ!");
308 return SplitBlock(BB, BB->getTerminator(), P);
309 }
310}
311
312/// SplitBlock - Split the specified block at the specified instruction - every
313/// thing before SplitPt stays in Old and everything starting with SplitPt moves
314/// to a new block. The two blocks are joined by an unconditional branch and
315/// the loop info is updated.
316///
317BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
Devang Patel80198932007-07-06 21:39:20 +0000318 BasicBlock::iterator SplitIt = SplitPt;
319 while (isa<PHINode>(SplitIt))
320 ++SplitIt;
321 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
322
323 // The new block lives in whichever loop the old one did.
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///
357/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
358/// DominanceFrontier, but no other analyses.
359BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
360 BasicBlock *const *Preds,
361 unsigned NumPreds, const char *Suffix,
362 Pass *P) {
363 // Create new basic block, insert right before the original block.
364 BasicBlock *NewBB =
365 BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
366
367 // The new block unconditionally branches to the old block.
368 BranchInst *BI = BranchInst::Create(BB, NewBB);
369
370 // Move the edges from Preds to point to NewBB instead of BB.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000371 for (unsigned i = 0; i != NumPreds; ++i)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000372 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000373
374 // Update dominator tree and dominator frontier if available.
Duncan Sands1465d612009-01-28 13:14:17 +0000375 DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000376 if (DT)
377 DT->splitBlock(NewBB);
Duncan Sands1465d612009-01-28 13:14:17 +0000378 if (DominanceFrontier *DF = P ? P->getAnalysisIfAvailable<DominanceFrontier>():0)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000379 DF->splitBlock(NewBB);
Duncan Sands1465d612009-01-28 13:14:17 +0000380 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000381
382
383 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
384 // node becomes an incoming value for BB's phi node. However, if the Preds
385 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
386 // account for the newly created predecessor.
387 if (NumPreds == 0) {
388 // Insert dummy values as the incoming value.
389 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000390 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000391 return NewBB;
392 }
393
394 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
395 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
396 PHINode *PN = cast<PHINode>(I++);
397
398 // Check to see if all of the values coming in are the same. If so, we
399 // don't need to create a new PHI node.
400 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
401 for (unsigned i = 1; i != NumPreds; ++i)
402 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
403 InVal = 0;
404 break;
405 }
406
407 if (InVal) {
408 // If all incoming values for the new PHI would be the same, just don't
409 // make a new PHI. Instead, just remove the incoming values from the old
410 // PHI.
411 for (unsigned i = 0; i != NumPreds; ++i)
412 PN->removeIncomingValue(Preds[i], false);
413 } else {
414 // If the values coming into the block are not the same, we need a PHI.
415 // Create the new PHI node, insert it into NewBB at the end of the block
416 PHINode *NewPHI =
417 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
418 if (AA) AA->copyValue(PN, NewPHI);
419
420 // Move all of the PHI values for 'Preds' to the new PHI.
421 for (unsigned i = 0; i != NumPreds; ++i) {
422 Value *V = PN->removeIncomingValue(Preds[i], false);
423 NewPHI->addIncoming(V, Preds[i]);
424 }
425 InVal = NewPHI;
426 }
427
428 // Add an incoming value to the PHI node in the loop for the preheader
429 // edge.
430 PN->addIncoming(InVal, NewBB);
431
432 // Check to see if we can eliminate this phi node.
433 if (Value *V = PN->hasConstantValue(DT != 0)) {
434 Instruction *I = dyn_cast<Instruction>(V);
435 if (!I || DT == 0 || DT->dominates(I, PN)) {
436 PN->replaceAllUsesWith(V);
437 if (AA) AA->deleteValue(PN);
438 PN->eraseFromParent();
439 }
440 }
441 }
442
443 return NewBB;
444}
Chris Lattner52c95852008-11-27 08:10:05 +0000445
Mike Stumpfe095f32009-05-04 18:40:41 +0000446/// FindFunctionBackedges - Analyze the specified function to find all of the
447/// loop backedges in the function and return them. This is a relatively cheap
448/// (compared to computing dominators and loop info) analysis.
449///
450/// The output is added to Result, as pairs of <from,to> edge info.
451void llvm::FindFunctionBackedges(const Function &F,
452 SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
453 const BasicBlock *BB = &F.getEntryBlock();
454 if (succ_begin(BB) == succ_end(BB))
455 return;
456
457 SmallPtrSet<const BasicBlock*, 8> Visited;
458 SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
459 SmallPtrSet<const BasicBlock*, 8> InStack;
460
461 Visited.insert(BB);
462 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
463 InStack.insert(BB);
464 do {
465 std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
466 const BasicBlock *ParentBB = Top.first;
467 succ_const_iterator &I = Top.second;
468
469 bool FoundNew = false;
470 while (I != succ_end(ParentBB)) {
471 BB = *I++;
472 if (Visited.insert(BB)) {
473 FoundNew = true;
474 break;
475 }
476 // Successor is in VisitStack, it's a back edge.
477 if (InStack.count(BB))
478 Result.push_back(std::make_pair(ParentBB, BB));
479 }
480
481 if (FoundNew) {
482 // Go down one level if there is a unvisited successor.
483 InStack.insert(BB);
484 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
485 } else {
486 // Go up one level.
487 InStack.erase(VisitStack.pop_back_val().first);
488 }
489 } while (!VisitStack.empty());
490
491
492}
493
494
495
Chris Lattner4aebaee2008-11-27 08:56:30 +0000496/// AreEquivalentAddressValues - Test if A and B will obviously have the same
497/// value. This includes recognizing that %t0 and %t1 will have the same
498/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000499/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000500/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000501/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000502/// %t2 = load i32* %t1
503///
504static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
505 // Test if the values are trivially equivalent.
506 if (A == B) return true;
507
508 // Test if the values come form identical arithmetic instructions.
509 if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
510 isa<PHINode>(A) || isa<GetElementPtrInst>(A))
511 if (const Instruction *BI = dyn_cast<Instruction>(B))
512 if (cast<Instruction>(A)->isIdenticalTo(BI))
513 return true;
514
515 // Otherwise they may not be equivalent.
516 return false;
517}
518
Chris Lattner52c95852008-11-27 08:10:05 +0000519/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
520/// instruction before ScanFrom) checking to see if we have the value at the
521/// memory address *Ptr locally available within a small number of instructions.
522/// If the value is available, return it.
523///
524/// If not, return the iterator for the last validated instruction that the
525/// value would be live through. If we scanned the entire block and didn't find
526/// something that invalidates *Ptr or provides it, ScanFrom would be left at
527/// begin() and this returns null. ScanFrom could also be left
528///
529/// MaxInstsToScan specifies the maximum instructions to scan in the block. If
530/// it is set to 0, it will scan the whole block. You can also optionally
531/// specify an alias analysis implementation, which makes this more precise.
532Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
533 BasicBlock::iterator &ScanFrom,
534 unsigned MaxInstsToScan,
535 AliasAnalysis *AA) {
536 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
Chris Lattneree6e10b2008-11-27 08:18:12 +0000537
538 // If we're using alias analysis to disambiguate get the size of *Ptr.
539 unsigned AccessSize = 0;
540 if (AA) {
541 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +0000542 AccessSize = AA->getTypeStoreSize(AccessTy);
Chris Lattneree6e10b2008-11-27 08:18:12 +0000543 }
Chris Lattner52c95852008-11-27 08:10:05 +0000544
545 while (ScanFrom != ScanBB->begin()) {
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000546 // We must ignore debug info directives when counting (otherwise they
547 // would affect codegen).
548 Instruction *Inst = --ScanFrom;
549 if (isa<DbgInfoIntrinsic>(Inst))
550 continue;
Dale Johannesend9c05d72009-03-04 02:06:53 +0000551 // We skip pointer-to-pointer bitcasts, which are NOPs.
552 // It is necessary for correctness to skip those that feed into a
553 // llvm.dbg.declare, as these are not present when debugging is off.
554 if (isa<BitCastInst>(Inst) && isa<PointerType>(Inst->getType()))
Dale Johannesen4ded40a2009-03-03 22:36:47 +0000555 continue;
556
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000557 // Restore ScanFrom to expected value in case next test succeeds
558 ScanFrom++;
559
Chris Lattner52c95852008-11-27 08:10:05 +0000560 // Don't scan huge blocks.
561 if (MaxInstsToScan-- == 0) return 0;
562
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000563 --ScanFrom;
Chris Lattner52c95852008-11-27 08:10:05 +0000564 // If this is a load of Ptr, the loaded value is available.
565 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000566 if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000567 return LI;
568
569 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
570 // If this is a store through Ptr, the value is available!
Chris Lattner4aebaee2008-11-27 08:56:30 +0000571 if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000572 return SI->getOperand(0);
573
574 // If Ptr is an alloca and this is a store to a different alloca, ignore
575 // the store. This is a trivial form of alias analysis that is important
576 // for reg2mem'd code.
577 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
578 (isa<AllocaInst>(SI->getOperand(1)) ||
579 isa<GlobalVariable>(SI->getOperand(1))))
580 continue;
581
Chris Lattneree6e10b2008-11-27 08:18:12 +0000582 // If we have alias analysis and it says the store won't modify the loaded
583 // value, ignore the store.
584 if (AA &&
585 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
586 continue;
587
Chris Lattner52c95852008-11-27 08:10:05 +0000588 // Otherwise the store that may or may not alias the pointer, bail out.
589 ++ScanFrom;
590 return 0;
591 }
592
Chris Lattner52c95852008-11-27 08:10:05 +0000593 // If this is some other instruction that may clobber Ptr, bail out.
594 if (Inst->mayWriteToMemory()) {
Chris Lattneree6e10b2008-11-27 08:18:12 +0000595 // If alias analysis claims that it really won't modify the load,
596 // ignore it.
597 if (AA &&
598 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
599 continue;
600
Chris Lattner52c95852008-11-27 08:10:05 +0000601 // May modify the pointer, bail out.
602 ++ScanFrom;
603 return 0;
604 }
605 }
606
607 // Got to the start of the block, we didn't find it, but are done for this
608 // block.
609 return 0;
610}
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000611
612/// CopyPrecedingStopPoint - If I is immediately preceded by a StopPoint,
613/// make a copy of the stoppoint before InsertPos (presumably before copying
614/// or moving I).
615void llvm::CopyPrecedingStopPoint(Instruction *I,
616 BasicBlock::iterator InsertPos) {
617 if (I != I->getParent()->begin()) {
618 BasicBlock::iterator BBI = I; --BBI;
619 if (DbgStopPointInst *DSPI = dyn_cast<DbgStopPointInst>(BBI)) {
Owen Andersone922c022009-07-22 00:24:57 +0000620 CallInst *newDSPI = DSPI->clone(I->getContext());
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000621 newDSPI->insertBefore(InsertPos);
622 }
623 }
624}