blob: 45cfe8f181fa56ea7bbdd8422de60acc848ed843 [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"
Chris Lattnerb0f0ef82002-07-29 22:32:08 +000018#include "llvm/Constant.h"
19#include "llvm/Type.h"
Chris Lattner54b9c3b2008-04-21 01:28:02 +000020#include "llvm/Analysis/AliasAnalysis.h"
Devang Patel80198932007-07-06 21:39:20 +000021#include "llvm/Analysis/LoopInfo.h"
22#include "llvm/Analysis/Dominators.h"
Chris Lattneree6e10b2008-11-27 08:18:12 +000023#include "llvm/Target/TargetData.h"
Chris Lattner4d1e46e2002-05-07 18:07:59 +000024#include <algorithm>
Chris Lattnerf7703df2004-01-09 06:12:26 +000025using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000026
Chris Lattner71af9b02008-12-03 06:40:52 +000027/// DeleteDeadBlock - Delete the specified block, which must have no
28/// predecessors.
29void llvm::DeleteDeadBlock(BasicBlock *BB) {
Chris Lattner2973a252008-12-03 07:45:15 +000030 assert((pred_begin(BB) == pred_end(BB) ||
31 // Can delete self loop.
32 BB->getSinglePredecessor() == BB) && "Block is not dead!");
Chris Lattner2b1ba242008-12-03 06:37:44 +000033 TerminatorInst *BBTerm = BB->getTerminator();
34
35 // Loop through all of our successors and make sure they know that one
36 // of their predecessors is going away.
37 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
38 BBTerm->getSuccessor(i)->removePredecessor(BB);
39
40 // Zap all the instructions in the block.
41 while (!BB->empty()) {
42 Instruction &I = BB->back();
43 // If this instruction is used, replace uses with an arbitrary value.
44 // Because control flow can't get here, we don't care what we replace the
45 // value with. Note that since this block is unreachable, and all values
46 // contained within it must dominate their uses, that all uses will
47 // eventually be removed (they are themselves dead).
48 if (!I.use_empty())
49 I.replaceAllUsesWith(UndefValue::get(I.getType()));
50 BB->getInstList().pop_back();
51 }
52
53 // Zap the block!
54 BB->eraseFromParent();
Chris Lattner2b1ba242008-12-03 06:37:44 +000055}
56
Owen Andersonb31b06d2008-07-17 00:01:40 +000057/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
58/// if possible. The return value indicates success or failure.
59bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
Owen Anderson11f2ec82008-07-17 19:42:29 +000060 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
Owen Andersonb31b06d2008-07-17 00:01:40 +000061 // Can't merge the entry block.
62 if (pred_begin(BB) == pred_end(BB)) return false;
Owen Andersonb31b06d2008-07-17 00:01:40 +000063
Owen Anderson11f2ec82008-07-17 19:42:29 +000064 BasicBlock *PredBB = *PI++;
65 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
66 if (*PI != PredBB) {
67 PredBB = 0; // There are multiple different predecessors...
68 break;
69 }
Owen Andersonb31b06d2008-07-17 00:01:40 +000070
Owen Anderson11f2ec82008-07-17 19:42:29 +000071 // Can't merge if there are multiple predecessors.
72 if (!PredBB) return false;
Owen Anderson3ecaf1b2008-07-18 17:46:41 +000073 // Don't break self-loops.
74 if (PredBB == BB) return false;
75 // Don't break invokes.
76 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
Owen Anderson11f2ec82008-07-17 19:42:29 +000077
78 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
79 BasicBlock* OnlySucc = BB;
80 for (; SI != SE; ++SI)
81 if (*SI != OnlySucc) {
82 OnlySucc = 0; // There are multiple distinct successors!
83 break;
84 }
85
86 // Can't merge if there are multiple successors.
87 if (!OnlySucc) return false;
Devang Patele435a5d2008-09-09 01:06:56 +000088
89 // Can't merge if there is PHI loop.
90 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
91 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
92 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
93 if (PN->getIncomingValue(i) == PN)
94 return false;
95 } else
96 break;
97 }
98
Owen Andersonb31b06d2008-07-17 00:01:40 +000099 // Begin by getting rid of unneeded PHIs.
100 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
101 PN->replaceAllUsesWith(PN->getIncomingValue(0));
102 BB->getInstList().pop_front(); // Delete the phi node...
103 }
104
105 // Delete the unconditional branch from the predecessor...
106 PredBB->getInstList().pop_back();
107
108 // Move all definitions in the successor to the predecessor...
109 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
110
111 // Make all PHI nodes that referred to BB now refer to Pred as their
112 // source...
113 BB->replaceAllUsesWith(PredBB);
114
Owen Anderson11f2ec82008-07-17 19:42:29 +0000115 // Inherit predecessors name if it exists.
116 if (!PredBB->hasName())
117 PredBB->takeName(BB);
118
Owen Andersonb31b06d2008-07-17 00:01:40 +0000119 // Finally, erase the old block and update dominator info.
120 if (P) {
121 if (DominatorTree* DT = P->getAnalysisToUpdate<DominatorTree>()) {
122 DomTreeNode* DTN = DT->getNode(BB);
123 DomTreeNode* PredDTN = DT->getNode(PredBB);
124
125 if (DTN) {
126 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
127 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
128 DE = Children.end(); DI != DE; ++DI)
129 DT->changeImmediateDominator(*DI, PredDTN);
130
131 DT->eraseNode(BB);
132 }
133 }
134 }
135
136 BB->eraseFromParent();
137
138
139 return true;
140}
141
Chris Lattner0f67dd62005-04-21 16:04:49 +0000142/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
143/// with a value, then remove and delete the original instruction.
144///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000145void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
146 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000147 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000148 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000149 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000150
Chris Lattner86cc4232007-02-11 01:37:51 +0000151 // Make sure to propagate a name if there is one already.
152 if (I.hasName() && !V->hasName())
153 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000154
Misha Brukman5560c9d2003-08-18 14:43:39 +0000155 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000156 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000157}
158
159
Chris Lattner0f67dd62005-04-21 16:04:49 +0000160/// ReplaceInstWithInst - Replace the instruction specified by BI with the
161/// instruction specified by I. The original instruction is deleted and BI is
162/// updated to point to the new instruction.
163///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000164void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
165 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000166 assert(I->getParent() == 0 &&
167 "ReplaceInstWithInst: Instruction already inserted into basic block!");
168
169 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000170 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000171
172 // Replace all uses of the old instruction, and delete it.
173 ReplaceInstWithValue(BIL, BI, I);
174
175 // Move BI back to point to the newly inserted instruction
Chris Lattner18961502002-06-25 16:12:52 +0000176 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000177}
178
Chris Lattner0f67dd62005-04-21 16:04:49 +0000179/// ReplaceInstWithInst - Replace the instruction specified by From with the
180/// instruction specified by To.
181///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000182void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000183 BasicBlock::iterator BI(From);
184 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000185}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000186
Chris Lattner0f67dd62005-04-21 16:04:49 +0000187/// RemoveSuccessor - Change the specified terminator instruction such that its
Reid Spencerbc2eba12006-05-19 19:09:46 +0000188/// successor SuccNum no longer exists. Because this reduces the outgoing
Chris Lattner0f67dd62005-04-21 16:04:49 +0000189/// degree of the current basic block, the actual terminator instruction itself
Reid Spencerbc2eba12006-05-19 19:09:46 +0000190/// may have to be changed. In the case where the last successor of the block
191/// is deleted, a return instruction is inserted in its place which can cause a
Chris Lattner0f67dd62005-04-21 16:04:49 +0000192/// surprising change in program behavior if it is not expected.
193///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000194void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000195 assert(SuccNum < TI->getNumSuccessors() &&
196 "Trying to remove a nonexistant successor!");
197
198 // If our old successor block contains any PHI nodes, remove the entry in the
199 // PHI nodes that comes from this branch...
200 //
201 BasicBlock *BB = TI->getParent();
202 TI->getSuccessor(SuccNum)->removePredecessor(BB);
203
204 TerminatorInst *NewTI = 0;
205 switch (TI->getOpcode()) {
206 case Instruction::Br:
207 // If this is a conditional branch... convert to unconditional branch.
208 if (TI->getNumSuccessors() == 2) {
209 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
210 } else { // Otherwise convert to a return instruction...
211 Value *RetVal = 0;
Misha Brukmanfd939082005-04-21 23:48:37 +0000212
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000213 // Create a value to return... if the function doesn't return null...
214 if (BB->getParent()->getReturnType() != Type::VoidTy)
215 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
216
217 // Create the return...
Gabor Greif051a9502008-04-06 20:25:17 +0000218 NewTI = ReturnInst::Create(RetVal);
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000219 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000220 break;
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000221
222 case Instruction::Invoke: // Should convert to call
223 case Instruction::Switch: // Should remove entry
224 default:
225 case Instruction::Ret: // Cannot happen, has no successors!
226 assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
227 abort();
228 }
229
230 if (NewTI) // If it's a different instruction, replace.
231 ReplaceInstWithInst(TI, NewTI);
232}
Brian Gaeked0fde302003-11-11 22:41:34 +0000233
Devang Patel80198932007-07-06 21:39:20 +0000234/// SplitEdge - Split the edge connecting specified block. Pass P must
235/// not be NULL.
236BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
237 TerminatorInst *LatchTerm = BB->getTerminator();
238 unsigned SuccNum = 0;
Devang Patel8a88a142008-11-03 23:14:09 +0000239#ifndef NDEBUG
240 unsigned e = LatchTerm->getNumSuccessors();
241#endif
242 for (unsigned i = 0; ; ++i) {
Devang Patel80198932007-07-06 21:39:20 +0000243 assert(i != e && "Didn't find edge?");
244 if (LatchTerm->getSuccessor(i) == Succ) {
245 SuccNum = i;
246 break;
247 }
248 }
249
250 // If this is a critical edge, let SplitCriticalEdge do it.
251 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
252 return LatchTerm->getSuccessor(SuccNum);
253
254 // If the edge isn't critical, then BB has a single successor or Succ has a
255 // single pred. Split the block.
256 BasicBlock::iterator SplitPoint;
257 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
258 // If the successor only has a single pred, split the top of the successor
259 // block.
260 assert(SP == BB && "CFG broken");
Devang Patel8a88a142008-11-03 23:14:09 +0000261 SP = NULL;
Devang Patel80198932007-07-06 21:39:20 +0000262 return SplitBlock(Succ, Succ->begin(), P);
263 } else {
264 // Otherwise, if BB has a single successor, split it at the bottom of the
265 // block.
266 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
267 "Should have a single succ!");
268 return SplitBlock(BB, BB->getTerminator(), P);
269 }
270}
271
272/// SplitBlock - Split the specified block at the specified instruction - every
273/// thing before SplitPt stays in Old and everything starting with SplitPt moves
274/// to a new block. The two blocks are joined by an unconditional branch and
275/// the loop info is updated.
276///
277BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
Devang Patel80198932007-07-06 21:39:20 +0000278 BasicBlock::iterator SplitIt = SplitPt;
279 while (isa<PHINode>(SplitIt))
280 ++SplitIt;
281 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
282
283 // The new block lives in whichever loop the old one did.
Owen Andersona90793b2008-10-03 06:55:35 +0000284 if (LoopInfo* LI = P->getAnalysisToUpdate<LoopInfo>())
285 if (Loop *L = LI->getLoopFor(Old))
286 L->addBasicBlockToLoop(New, LI->getBase());
Devang Patel80198932007-07-06 21:39:20 +0000287
Devang Patela8a8a362007-07-19 02:29:24 +0000288 if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>())
289 {
290 // Old dominates New. New node domiantes all other nodes dominated by Old.
291 DomTreeNode *OldNode = DT->getNode(Old);
292 std::vector<DomTreeNode *> Children;
293 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
294 I != E; ++I)
295 Children.push_back(*I);
296
297 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
298
299 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
300 E = Children.end(); I != E; ++I)
301 DT->changeImmediateDominator(*I, NewNode);
302 }
Devang Patel80198932007-07-06 21:39:20 +0000303
304 if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>())
305 DF->splitBlock(Old);
306
307 return New;
308}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000309
310
311/// SplitBlockPredecessors - This method transforms BB by introducing a new
312/// basic block into the function, and moving some of the predecessors of BB to
313/// be predecessors of the new block. The new predecessors are indicated by the
314/// Preds array, which has NumPreds elements in it. The new block is given a
315/// suffix of 'Suffix'.
316///
317/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
318/// DominanceFrontier, but no other analyses.
319BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
320 BasicBlock *const *Preds,
321 unsigned NumPreds, const char *Suffix,
322 Pass *P) {
323 // Create new basic block, insert right before the original block.
324 BasicBlock *NewBB =
325 BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
326
327 // The new block unconditionally branches to the old block.
328 BranchInst *BI = BranchInst::Create(BB, NewBB);
329
330 // Move the edges from Preds to point to NewBB instead of BB.
Nick Lewycky280a6e62008-04-25 16:53:59 +0000331 for (unsigned i = 0; i != NumPreds; ++i)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000332 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000333
334 // Update dominator tree and dominator frontier if available.
335 DominatorTree *DT = P ? P->getAnalysisToUpdate<DominatorTree>() : 0;
336 if (DT)
337 DT->splitBlock(NewBB);
338 if (DominanceFrontier *DF = P ? P->getAnalysisToUpdate<DominanceFrontier>():0)
339 DF->splitBlock(NewBB);
340 AliasAnalysis *AA = P ? P->getAnalysisToUpdate<AliasAnalysis>() : 0;
341
342
343 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
344 // node becomes an incoming value for BB's phi node. However, if the Preds
345 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
346 // account for the newly created predecessor.
347 if (NumPreds == 0) {
348 // Insert dummy values as the incoming value.
349 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
350 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
351 return NewBB;
352 }
353
354 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
355 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
356 PHINode *PN = cast<PHINode>(I++);
357
358 // Check to see if all of the values coming in are the same. If so, we
359 // don't need to create a new PHI node.
360 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
361 for (unsigned i = 1; i != NumPreds; ++i)
362 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
363 InVal = 0;
364 break;
365 }
366
367 if (InVal) {
368 // If all incoming values for the new PHI would be the same, just don't
369 // make a new PHI. Instead, just remove the incoming values from the old
370 // PHI.
371 for (unsigned i = 0; i != NumPreds; ++i)
372 PN->removeIncomingValue(Preds[i], false);
373 } else {
374 // If the values coming into the block are not the same, we need a PHI.
375 // Create the new PHI node, insert it into NewBB at the end of the block
376 PHINode *NewPHI =
377 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
378 if (AA) AA->copyValue(PN, NewPHI);
379
380 // Move all of the PHI values for 'Preds' to the new PHI.
381 for (unsigned i = 0; i != NumPreds; ++i) {
382 Value *V = PN->removeIncomingValue(Preds[i], false);
383 NewPHI->addIncoming(V, Preds[i]);
384 }
385 InVal = NewPHI;
386 }
387
388 // Add an incoming value to the PHI node in the loop for the preheader
389 // edge.
390 PN->addIncoming(InVal, NewBB);
391
392 // Check to see if we can eliminate this phi node.
393 if (Value *V = PN->hasConstantValue(DT != 0)) {
394 Instruction *I = dyn_cast<Instruction>(V);
395 if (!I || DT == 0 || DT->dominates(I, PN)) {
396 PN->replaceAllUsesWith(V);
397 if (AA) AA->deleteValue(PN);
398 PN->eraseFromParent();
399 }
400 }
401 }
402
403 return NewBB;
404}
Chris Lattner52c95852008-11-27 08:10:05 +0000405
Chris Lattner4aebaee2008-11-27 08:56:30 +0000406/// AreEquivalentAddressValues - Test if A and B will obviously have the same
407/// value. This includes recognizing that %t0 and %t1 will have the same
408/// value in code like this:
409/// %t0 = getelementptr @a, 0, 3
410/// store i32 0, i32* %t0
411/// %t1 = getelementptr @a, 0, 3
412/// %t2 = load i32* %t1
413///
414static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
415 // Test if the values are trivially equivalent.
416 if (A == B) return true;
417
418 // Test if the values come form identical arithmetic instructions.
419 if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
420 isa<PHINode>(A) || isa<GetElementPtrInst>(A))
421 if (const Instruction *BI = dyn_cast<Instruction>(B))
422 if (cast<Instruction>(A)->isIdenticalTo(BI))
423 return true;
424
425 // Otherwise they may not be equivalent.
426 return false;
427}
428
Chris Lattner52c95852008-11-27 08:10:05 +0000429/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
430/// instruction before ScanFrom) checking to see if we have the value at the
431/// memory address *Ptr locally available within a small number of instructions.
432/// If the value is available, return it.
433///
434/// If not, return the iterator for the last validated instruction that the
435/// value would be live through. If we scanned the entire block and didn't find
436/// something that invalidates *Ptr or provides it, ScanFrom would be left at
437/// begin() and this returns null. ScanFrom could also be left
438///
439/// MaxInstsToScan specifies the maximum instructions to scan in the block. If
440/// it is set to 0, it will scan the whole block. You can also optionally
441/// specify an alias analysis implementation, which makes this more precise.
442Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
443 BasicBlock::iterator &ScanFrom,
444 unsigned MaxInstsToScan,
445 AliasAnalysis *AA) {
446 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
Chris Lattneree6e10b2008-11-27 08:18:12 +0000447
448 // If we're using alias analysis to disambiguate get the size of *Ptr.
449 unsigned AccessSize = 0;
450 if (AA) {
451 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
452 AccessSize = AA->getTargetData().getTypeStoreSizeInBits(AccessTy);
453 }
Chris Lattner52c95852008-11-27 08:10:05 +0000454
455 while (ScanFrom != ScanBB->begin()) {
456 // Don't scan huge blocks.
457 if (MaxInstsToScan-- == 0) return 0;
458
459 Instruction *Inst = --ScanFrom;
460
461 // If this is a load of Ptr, the loaded value is available.
462 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000463 if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000464 return LI;
465
466 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
467 // If this is a store through Ptr, the value is available!
Chris Lattner4aebaee2008-11-27 08:56:30 +0000468 if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000469 return SI->getOperand(0);
470
471 // If Ptr is an alloca and this is a store to a different alloca, ignore
472 // the store. This is a trivial form of alias analysis that is important
473 // for reg2mem'd code.
474 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
475 (isa<AllocaInst>(SI->getOperand(1)) ||
476 isa<GlobalVariable>(SI->getOperand(1))))
477 continue;
478
Chris Lattneree6e10b2008-11-27 08:18:12 +0000479 // If we have alias analysis and it says the store won't modify the loaded
480 // value, ignore the store.
481 if (AA &&
482 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
483 continue;
484
Chris Lattner52c95852008-11-27 08:10:05 +0000485 // Otherwise the store that may or may not alias the pointer, bail out.
486 ++ScanFrom;
487 return 0;
488 }
489
Chris Lattner52c95852008-11-27 08:10:05 +0000490 // If this is some other instruction that may clobber Ptr, bail out.
491 if (Inst->mayWriteToMemory()) {
Chris Lattneree6e10b2008-11-27 08:18:12 +0000492 // If alias analysis claims that it really won't modify the load,
493 // ignore it.
494 if (AA &&
495 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
496 continue;
497
Chris Lattner52c95852008-11-27 08:10:05 +0000498 // May modify the pointer, bail out.
499 ++ScanFrom;
500 return 0;
501 }
502 }
503
504 // Got to the start of the block, we didn't find it, but are done for this
505 // block.
506 return 0;
507}