Use Use::set rather than finding the operand number of the use
[oota-llvm.git] / lib / Transforms / Scalar / GVN.cpp
1 //===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs global value numbering to eliminate fully redundant
11 // instructions.  It also performs simple dead load elimination.
12 //
13 // Note that this pass does the value numbering itself; it does not use the
14 // ValueNumbering analysis passes.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #define DEBUG_TYPE "gvn"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/GlobalVariable.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/ConstantFolding.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm/Analysis/InstructionSimplify.h"
27 #include "llvm/Analysis/Loads.h"
28 #include "llvm/Analysis/MemoryBuiltins.h"
29 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
30 #include "llvm/Analysis/PHITransAddr.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/Assembly/Writer.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetLibraryInfo.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/SSAUpdater.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/DepthFirstIterator.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/Support/Allocator.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/IRBuilder.h"
45 #include "llvm/Support/PatternMatch.h"
46 using namespace llvm;
47 using namespace PatternMatch;
48
49 STATISTIC(NumGVNInstr,  "Number of instructions deleted");
50 STATISTIC(NumGVNLoad,   "Number of loads deleted");
51 STATISTIC(NumGVNPRE,    "Number of instructions PRE'd");
52 STATISTIC(NumGVNBlocks, "Number of blocks merged");
53 STATISTIC(NumGVNSimpl,  "Number of instructions simplified");
54 STATISTIC(NumGVNEqProp, "Number of equalities propagated");
55 STATISTIC(NumPRELoad,   "Number of loads PRE'd");
56
57 static cl::opt<bool> EnablePRE("enable-pre",
58                                cl::init(true), cl::Hidden);
59 static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
60
61 //===----------------------------------------------------------------------===//
62 //                         ValueTable Class
63 //===----------------------------------------------------------------------===//
64
65 /// This class holds the mapping between values and value numbers.  It is used
66 /// as an efficient mechanism to determine the expression-wise equivalence of
67 /// two values.
68 namespace {
69   struct Expression {
70     uint32_t opcode;
71     Type *type;
72     SmallVector<uint32_t, 4> varargs;
73
74     Expression(uint32_t o = ~2U) : opcode(o) { }
75
76     bool operator==(const Expression &other) const {
77       if (opcode != other.opcode)
78         return false;
79       if (opcode == ~0U || opcode == ~1U)
80         return true;
81       if (type != other.type)
82         return false;
83       if (varargs != other.varargs)
84         return false;
85       return true;
86     }
87   };
88
89   class ValueTable {
90     DenseMap<Value*, uint32_t> valueNumbering;
91     DenseMap<Expression, uint32_t> expressionNumbering;
92     AliasAnalysis *AA;
93     MemoryDependenceAnalysis *MD;
94     DominatorTree *DT;
95
96     uint32_t nextValueNumber;
97
98     Expression create_expression(Instruction* I);
99     Expression create_extractvalue_expression(ExtractValueInst* EI);
100     uint32_t lookup_or_add_call(CallInst* C);
101   public:
102     ValueTable() : nextValueNumber(1) { }
103     uint32_t lookup_or_add(Value *V);
104     uint32_t lookup(Value *V) const;
105     void add(Value *V, uint32_t num);
106     void clear();
107     void erase(Value *v);
108     void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
109     AliasAnalysis *getAliasAnalysis() const { return AA; }
110     void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
111     void setDomTree(DominatorTree* D) { DT = D; }
112     uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
113     void verifyRemoved(const Value *) const;
114   };
115 }
116
117 namespace llvm {
118 template <> struct DenseMapInfo<Expression> {
119   static inline Expression getEmptyKey() {
120     return ~0U;
121   }
122
123   static inline Expression getTombstoneKey() {
124     return ~1U;
125   }
126
127   static unsigned getHashValue(const Expression e) {
128     unsigned hash = e.opcode;
129
130     hash = ((unsigned)((uintptr_t)e.type >> 4) ^
131             (unsigned)((uintptr_t)e.type >> 9));
132
133     for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
134          E = e.varargs.end(); I != E; ++I)
135       hash = *I + hash * 37;
136     
137     return hash;
138   }
139   static bool isEqual(const Expression &LHS, const Expression &RHS) {
140     return LHS == RHS;
141   }
142 };
143
144 }
145
146 //===----------------------------------------------------------------------===//
147 //                     ValueTable Internal Functions
148 //===----------------------------------------------------------------------===//
149
150 Expression ValueTable::create_expression(Instruction *I) {
151   Expression e;
152   e.type = I->getType();
153   e.opcode = I->getOpcode();
154   for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
155        OI != OE; ++OI)
156     e.varargs.push_back(lookup_or_add(*OI));
157   
158   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
159     e.opcode = (C->getOpcode() << 8) | C->getPredicate();
160   } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
161     for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
162          II != IE; ++II)
163       e.varargs.push_back(*II);
164   }
165   
166   return e;
167 }
168
169 Expression ValueTable::create_extractvalue_expression(ExtractValueInst *EI) {
170   assert(EI != 0 && "Not an ExtractValueInst?");
171   Expression e;
172   e.type = EI->getType();
173   e.opcode = 0;
174
175   IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
176   if (I != 0 && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
177     // EI might be an extract from one of our recognised intrinsics. If it
178     // is we'll synthesize a semantically equivalent expression instead on
179     // an extract value expression.
180     switch (I->getIntrinsicID()) {
181       case Intrinsic::sadd_with_overflow:
182       case Intrinsic::uadd_with_overflow:
183         e.opcode = Instruction::Add;
184         break;
185       case Intrinsic::ssub_with_overflow:
186       case Intrinsic::usub_with_overflow:
187         e.opcode = Instruction::Sub;
188         break;
189       case Intrinsic::smul_with_overflow:
190       case Intrinsic::umul_with_overflow:
191         e.opcode = Instruction::Mul;
192         break;
193       default:
194         break;
195     }
196
197     if (e.opcode != 0) {
198       // Intrinsic recognized. Grab its args to finish building the expression.
199       assert(I->getNumArgOperands() == 2 &&
200              "Expect two args for recognised intrinsics.");
201       e.varargs.push_back(lookup_or_add(I->getArgOperand(0)));
202       e.varargs.push_back(lookup_or_add(I->getArgOperand(1)));
203       return e;
204     }
205   }
206
207   // Not a recognised intrinsic. Fall back to producing an extract value
208   // expression.
209   e.opcode = EI->getOpcode();
210   for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
211        OI != OE; ++OI)
212     e.varargs.push_back(lookup_or_add(*OI));
213
214   for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
215          II != IE; ++II)
216     e.varargs.push_back(*II);
217
218   return e;
219 }
220
221 //===----------------------------------------------------------------------===//
222 //                     ValueTable External Functions
223 //===----------------------------------------------------------------------===//
224
225 /// add - Insert a value into the table with a specified value number.
226 void ValueTable::add(Value *V, uint32_t num) {
227   valueNumbering.insert(std::make_pair(V, num));
228 }
229
230 uint32_t ValueTable::lookup_or_add_call(CallInst* C) {
231   if (AA->doesNotAccessMemory(C)) {
232     Expression exp = create_expression(C);
233     uint32_t& e = expressionNumbering[exp];
234     if (!e) e = nextValueNumber++;
235     valueNumbering[C] = e;
236     return e;
237   } else if (AA->onlyReadsMemory(C)) {
238     Expression exp = create_expression(C);
239     uint32_t& e = expressionNumbering[exp];
240     if (!e) {
241       e = nextValueNumber++;
242       valueNumbering[C] = e;
243       return e;
244     }
245     if (!MD) {
246       e = nextValueNumber++;
247       valueNumbering[C] = e;
248       return e;
249     }
250
251     MemDepResult local_dep = MD->getDependency(C);
252
253     if (!local_dep.isDef() && !local_dep.isNonLocal()) {
254       valueNumbering[C] =  nextValueNumber;
255       return nextValueNumber++;
256     }
257
258     if (local_dep.isDef()) {
259       CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
260
261       if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
262         valueNumbering[C] = nextValueNumber;
263         return nextValueNumber++;
264       }
265
266       for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
267         uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
268         uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
269         if (c_vn != cd_vn) {
270           valueNumbering[C] = nextValueNumber;
271           return nextValueNumber++;
272         }
273       }
274
275       uint32_t v = lookup_or_add(local_cdep);
276       valueNumbering[C] = v;
277       return v;
278     }
279
280     // Non-local case.
281     const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
282       MD->getNonLocalCallDependency(CallSite(C));
283     // FIXME: Move the checking logic to MemDep!
284     CallInst* cdep = 0;
285
286     // Check to see if we have a single dominating call instruction that is
287     // identical to C.
288     for (unsigned i = 0, e = deps.size(); i != e; ++i) {
289       const NonLocalDepEntry *I = &deps[i];
290       if (I->getResult().isNonLocal())
291         continue;
292
293       // We don't handle non-definitions.  If we already have a call, reject
294       // instruction dependencies.
295       if (!I->getResult().isDef() || cdep != 0) {
296         cdep = 0;
297         break;
298       }
299
300       CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
301       // FIXME: All duplicated with non-local case.
302       if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
303         cdep = NonLocalDepCall;
304         continue;
305       }
306
307       cdep = 0;
308       break;
309     }
310
311     if (!cdep) {
312       valueNumbering[C] = nextValueNumber;
313       return nextValueNumber++;
314     }
315
316     if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
317       valueNumbering[C] = nextValueNumber;
318       return nextValueNumber++;
319     }
320     for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
321       uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
322       uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
323       if (c_vn != cd_vn) {
324         valueNumbering[C] = nextValueNumber;
325         return nextValueNumber++;
326       }
327     }
328
329     uint32_t v = lookup_or_add(cdep);
330     valueNumbering[C] = v;
331     return v;
332
333   } else {
334     valueNumbering[C] = nextValueNumber;
335     return nextValueNumber++;
336   }
337 }
338
339 /// lookup_or_add - Returns the value number for the specified value, assigning
340 /// it a new number if it did not have one before.
341 uint32_t ValueTable::lookup_or_add(Value *V) {
342   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
343   if (VI != valueNumbering.end())
344     return VI->second;
345
346   if (!isa<Instruction>(V)) {
347     valueNumbering[V] = nextValueNumber;
348     return nextValueNumber++;
349   }
350   
351   Instruction* I = cast<Instruction>(V);
352   Expression exp;
353   switch (I->getOpcode()) {
354     case Instruction::Call:
355       return lookup_or_add_call(cast<CallInst>(I));
356     case Instruction::Add:
357     case Instruction::FAdd:
358     case Instruction::Sub:
359     case Instruction::FSub:
360     case Instruction::Mul:
361     case Instruction::FMul:
362     case Instruction::UDiv:
363     case Instruction::SDiv:
364     case Instruction::FDiv:
365     case Instruction::URem:
366     case Instruction::SRem:
367     case Instruction::FRem:
368     case Instruction::Shl:
369     case Instruction::LShr:
370     case Instruction::AShr:
371     case Instruction::And:
372     case Instruction::Or :
373     case Instruction::Xor:
374     case Instruction::ICmp:
375     case Instruction::FCmp:
376     case Instruction::Trunc:
377     case Instruction::ZExt:
378     case Instruction::SExt:
379     case Instruction::FPToUI:
380     case Instruction::FPToSI:
381     case Instruction::UIToFP:
382     case Instruction::SIToFP:
383     case Instruction::FPTrunc:
384     case Instruction::FPExt:
385     case Instruction::PtrToInt:
386     case Instruction::IntToPtr:
387     case Instruction::BitCast:
388     case Instruction::Select:
389     case Instruction::ExtractElement:
390     case Instruction::InsertElement:
391     case Instruction::ShuffleVector:
392     case Instruction::InsertValue:
393     case Instruction::GetElementPtr:
394       exp = create_expression(I);
395       break;
396     case Instruction::ExtractValue:
397       exp = create_extractvalue_expression(cast<ExtractValueInst>(I));
398       break;
399     default:
400       valueNumbering[V] = nextValueNumber;
401       return nextValueNumber++;
402   }
403
404   uint32_t& e = expressionNumbering[exp];
405   if (!e) e = nextValueNumber++;
406   valueNumbering[V] = e;
407   return e;
408 }
409
410 /// lookup - Returns the value number of the specified value. Fails if
411 /// the value has not yet been numbered.
412 uint32_t ValueTable::lookup(Value *V) const {
413   DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
414   assert(VI != valueNumbering.end() && "Value not numbered?");
415   return VI->second;
416 }
417
418 /// clear - Remove all entries from the ValueTable.
419 void ValueTable::clear() {
420   valueNumbering.clear();
421   expressionNumbering.clear();
422   nextValueNumber = 1;
423 }
424
425 /// erase - Remove a value from the value numbering.
426 void ValueTable::erase(Value *V) {
427   valueNumbering.erase(V);
428 }
429
430 /// verifyRemoved - Verify that the value is removed from all internal data
431 /// structures.
432 void ValueTable::verifyRemoved(const Value *V) const {
433   for (DenseMap<Value*, uint32_t>::const_iterator
434          I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
435     assert(I->first != V && "Inst still occurs in value numbering map!");
436   }
437 }
438
439 //===----------------------------------------------------------------------===//
440 //                                GVN Pass
441 //===----------------------------------------------------------------------===//
442
443 namespace {
444
445   class GVN : public FunctionPass {
446     bool NoLoads;
447     MemoryDependenceAnalysis *MD;
448     DominatorTree *DT;
449     const TargetData *TD;
450     const TargetLibraryInfo *TLI;
451
452     ValueTable VN;
453     
454     /// LeaderTable - A mapping from value numbers to lists of Value*'s that
455     /// have that value number.  Use findLeader to query it.
456     struct LeaderTableEntry {
457       Value *Val;
458       BasicBlock *BB;
459       LeaderTableEntry *Next;
460     };
461     DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
462     BumpPtrAllocator TableAllocator;
463     
464     SmallVector<Instruction*, 8> InstrsToErase;
465   public:
466     static char ID; // Pass identification, replacement for typeid
467     explicit GVN(bool noloads = false)
468         : FunctionPass(ID), NoLoads(noloads), MD(0) {
469       initializeGVNPass(*PassRegistry::getPassRegistry());
470     }
471
472     bool runOnFunction(Function &F);
473     
474     /// markInstructionForDeletion - This removes the specified instruction from
475     /// our various maps and marks it for deletion.
476     void markInstructionForDeletion(Instruction *I) {
477       VN.erase(I);
478       InstrsToErase.push_back(I);
479     }
480     
481     const TargetData *getTargetData() const { return TD; }
482     DominatorTree &getDominatorTree() const { return *DT; }
483     AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
484     MemoryDependenceAnalysis &getMemDep() const { return *MD; }
485   private:
486     /// addToLeaderTable - Push a new Value to the LeaderTable onto the list for
487     /// its value number.
488     void addToLeaderTable(uint32_t N, Value *V, BasicBlock *BB) {
489       LeaderTableEntry &Curr = LeaderTable[N];
490       if (!Curr.Val) {
491         Curr.Val = V;
492         Curr.BB = BB;
493         return;
494       }
495       
496       LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
497       Node->Val = V;
498       Node->BB = BB;
499       Node->Next = Curr.Next;
500       Curr.Next = Node;
501     }
502     
503     /// removeFromLeaderTable - Scan the list of values corresponding to a given
504     /// value number, and remove the given value if encountered.
505     void removeFromLeaderTable(uint32_t N, Value *V, BasicBlock *BB) {
506       LeaderTableEntry* Prev = 0;
507       LeaderTableEntry* Curr = &LeaderTable[N];
508
509       while (Curr->Val != V || Curr->BB != BB) {
510         Prev = Curr;
511         Curr = Curr->Next;
512       }
513       
514       if (Prev) {
515         Prev->Next = Curr->Next;
516       } else {
517         if (!Curr->Next) {
518           Curr->Val = 0;
519           Curr->BB = 0;
520         } else {
521           LeaderTableEntry* Next = Curr->Next;
522           Curr->Val = Next->Val;
523           Curr->BB = Next->BB;
524           Curr->Next = Next->Next;
525         }
526       }
527     }
528
529     // List of critical edges to be split between iterations.
530     SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
531
532     // This transformation requires dominator postdominator info
533     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
534       AU.addRequired<DominatorTree>();
535       AU.addRequired<TargetLibraryInfo>();
536       if (!NoLoads)
537         AU.addRequired<MemoryDependenceAnalysis>();
538       AU.addRequired<AliasAnalysis>();
539
540       AU.addPreserved<DominatorTree>();
541       AU.addPreserved<AliasAnalysis>();
542     }
543     
544
545     // Helper fuctions
546     // FIXME: eliminate or document these better
547     bool processLoad(LoadInst *L);
548     bool processInstruction(Instruction *I);
549     bool processNonLocalLoad(LoadInst *L);
550     bool processBlock(BasicBlock *BB);
551     void dump(DenseMap<uint32_t, Value*> &d);
552     bool iterateOnFunction(Function &F);
553     bool performPRE(Function &F);
554     Value *findLeader(BasicBlock *BB, uint32_t num);
555     void cleanupGlobalSets();
556     void verifyRemoved(const Instruction *I) const;
557     bool splitCriticalEdges();
558     unsigned replaceAllDominatedUsesWith(Value *From, Value *To,
559                                          BasicBlock *Root);
560     bool propagateEquality(Value *LHS, Value *RHS, BasicBlock *Root);
561   };
562
563   char GVN::ID = 0;
564 }
565
566 // createGVNPass - The public interface to this file...
567 FunctionPass *llvm::createGVNPass(bool NoLoads) {
568   return new GVN(NoLoads);
569 }
570
571 INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
572 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
573 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
574 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
575 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
576 INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
577
578 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
579   errs() << "{\n";
580   for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
581        E = d.end(); I != E; ++I) {
582       errs() << I->first << "\n";
583       I->second->dump();
584   }
585   errs() << "}\n";
586 }
587
588 /// IsValueFullyAvailableInBlock - Return true if we can prove that the value
589 /// we're analyzing is fully available in the specified block.  As we go, keep
590 /// track of which blocks we know are fully alive in FullyAvailableBlocks.  This
591 /// map is actually a tri-state map with the following values:
592 ///   0) we know the block *is not* fully available.
593 ///   1) we know the block *is* fully available.
594 ///   2) we do not know whether the block is fully available or not, but we are
595 ///      currently speculating that it will be.
596 ///   3) we are speculating for this block and have used that to speculate for
597 ///      other blocks.
598 static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
599                             DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
600   // Optimistically assume that the block is fully available and check to see
601   // if we already know about this block in one lookup.
602   std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
603     FullyAvailableBlocks.insert(std::make_pair(BB, 2));
604
605   // If the entry already existed for this block, return the precomputed value.
606   if (!IV.second) {
607     // If this is a speculative "available" value, mark it as being used for
608     // speculation of other blocks.
609     if (IV.first->second == 2)
610       IV.first->second = 3;
611     return IV.first->second != 0;
612   }
613
614   // Otherwise, see if it is fully available in all predecessors.
615   pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
616
617   // If this block has no predecessors, it isn't live-in here.
618   if (PI == PE)
619     goto SpeculationFailure;
620
621   for (; PI != PE; ++PI)
622     // If the value isn't fully available in one of our predecessors, then it
623     // isn't fully available in this block either.  Undo our previous
624     // optimistic assumption and bail out.
625     if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
626       goto SpeculationFailure;
627
628   return true;
629
630 // SpeculationFailure - If we get here, we found out that this is not, after
631 // all, a fully-available block.  We have a problem if we speculated on this and
632 // used the speculation to mark other blocks as available.
633 SpeculationFailure:
634   char &BBVal = FullyAvailableBlocks[BB];
635
636   // If we didn't speculate on this, just return with it set to false.
637   if (BBVal == 2) {
638     BBVal = 0;
639     return false;
640   }
641
642   // If we did speculate on this value, we could have blocks set to 1 that are
643   // incorrect.  Walk the (transitive) successors of this block and mark them as
644   // 0 if set to one.
645   SmallVector<BasicBlock*, 32> BBWorklist;
646   BBWorklist.push_back(BB);
647
648   do {
649     BasicBlock *Entry = BBWorklist.pop_back_val();
650     // Note that this sets blocks to 0 (unavailable) if they happen to not
651     // already be in FullyAvailableBlocks.  This is safe.
652     char &EntryVal = FullyAvailableBlocks[Entry];
653     if (EntryVal == 0) continue;  // Already unavailable.
654
655     // Mark as unavailable.
656     EntryVal = 0;
657
658     for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
659       BBWorklist.push_back(*I);
660   } while (!BBWorklist.empty());
661
662   return false;
663 }
664
665
666 /// CanCoerceMustAliasedValueToLoad - Return true if
667 /// CoerceAvailableValueToLoadType will succeed.
668 static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
669                                             Type *LoadTy,
670                                             const TargetData &TD) {
671   // If the loaded or stored value is an first class array or struct, don't try
672   // to transform them.  We need to be able to bitcast to integer.
673   if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
674       StoredVal->getType()->isStructTy() ||
675       StoredVal->getType()->isArrayTy())
676     return false;
677   
678   // The store has to be at least as big as the load.
679   if (TD.getTypeSizeInBits(StoredVal->getType()) <
680         TD.getTypeSizeInBits(LoadTy))
681     return false;
682   
683   return true;
684 }
685   
686
687 /// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
688 /// then a load from a must-aliased pointer of a different type, try to coerce
689 /// the stored value.  LoadedTy is the type of the load we want to replace and
690 /// InsertPt is the place to insert new instructions.
691 ///
692 /// If we can't do it, return null.
693 static Value *CoerceAvailableValueToLoadType(Value *StoredVal, 
694                                              Type *LoadedTy,
695                                              Instruction *InsertPt,
696                                              const TargetData &TD) {
697   if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
698     return 0;
699   
700   // If this is already the right type, just return it.
701   Type *StoredValTy = StoredVal->getType();
702   
703   uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
704   uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
705   
706   // If the store and reload are the same size, we can always reuse it.
707   if (StoreSize == LoadSize) {
708     // Pointer to Pointer -> use bitcast.
709     if (StoredValTy->isPointerTy() && LoadedTy->isPointerTy())
710       return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
711     
712     // Convert source pointers to integers, which can be bitcast.
713     if (StoredValTy->isPointerTy()) {
714       StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
715       StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
716     }
717     
718     Type *TypeToCastTo = LoadedTy;
719     if (TypeToCastTo->isPointerTy())
720       TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
721     
722     if (StoredValTy != TypeToCastTo)
723       StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
724     
725     // Cast to pointer if the load needs a pointer type.
726     if (LoadedTy->isPointerTy())
727       StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
728     
729     return StoredVal;
730   }
731   
732   // If the loaded value is smaller than the available value, then we can
733   // extract out a piece from it.  If the available value is too small, then we
734   // can't do anything.
735   assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
736   
737   // Convert source pointers to integers, which can be manipulated.
738   if (StoredValTy->isPointerTy()) {
739     StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
740     StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
741   }
742   
743   // Convert vectors and fp to integer, which can be manipulated.
744   if (!StoredValTy->isIntegerTy()) {
745     StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
746     StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
747   }
748   
749   // If this is a big-endian system, we need to shift the value down to the low
750   // bits so that a truncate will work.
751   if (TD.isBigEndian()) {
752     Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
753     StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
754   }
755   
756   // Truncate the integer to the right size now.
757   Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
758   StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
759   
760   if (LoadedTy == NewIntTy)
761     return StoredVal;
762   
763   // If the result is a pointer, inttoptr.
764   if (LoadedTy->isPointerTy())
765     return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
766   
767   // Otherwise, bitcast.
768   return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
769 }
770
771 /// AnalyzeLoadFromClobberingWrite - This function is called when we have a
772 /// memdep query of a load that ends up being a clobbering memory write (store,
773 /// memset, memcpy, memmove).  This means that the write *may* provide bits used
774 /// by the load but we can't be sure because the pointers don't mustalias.
775 ///
776 /// Check this case to see if there is anything more we can do before we give
777 /// up.  This returns -1 if we have to give up, or a byte number in the stored
778 /// value of the piece that feeds the load.
779 static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
780                                           Value *WritePtr,
781                                           uint64_t WriteSizeInBits,
782                                           const TargetData &TD) {
783   // If the loaded or stored value is a first class array or struct, don't try
784   // to transform them.  We need to be able to bitcast to integer.
785   if (LoadTy->isStructTy() || LoadTy->isArrayTy())
786     return -1;
787   
788   int64_t StoreOffset = 0, LoadOffset = 0;
789   Value *StoreBase = GetPointerBaseWithConstantOffset(WritePtr, StoreOffset,TD);
790   Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, TD);
791   if (StoreBase != LoadBase)
792     return -1;
793   
794   // If the load and store are to the exact same address, they should have been
795   // a must alias.  AA must have gotten confused.
796   // FIXME: Study to see if/when this happens.  One case is forwarding a memset
797   // to a load from the base of the memset.
798 #if 0
799   if (LoadOffset == StoreOffset) {
800     dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
801     << "Base       = " << *StoreBase << "\n"
802     << "Store Ptr  = " << *WritePtr << "\n"
803     << "Store Offs = " << StoreOffset << "\n"
804     << "Load Ptr   = " << *LoadPtr << "\n";
805     abort();
806   }
807 #endif
808   
809   // If the load and store don't overlap at all, the store doesn't provide
810   // anything to the load.  In this case, they really don't alias at all, AA
811   // must have gotten confused.
812   uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy);
813   
814   if ((WriteSizeInBits & 7) | (LoadSize & 7))
815     return -1;
816   uint64_t StoreSize = WriteSizeInBits >> 3;  // Convert to bytes.
817   LoadSize >>= 3;
818   
819   
820   bool isAAFailure = false;
821   if (StoreOffset < LoadOffset)
822     isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
823   else
824     isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
825
826   if (isAAFailure) {
827 #if 0
828     dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
829     << "Base       = " << *StoreBase << "\n"
830     << "Store Ptr  = " << *WritePtr << "\n"
831     << "Store Offs = " << StoreOffset << "\n"
832     << "Load Ptr   = " << *LoadPtr << "\n";
833     abort();
834 #endif
835     return -1;
836   }
837   
838   // If the Load isn't completely contained within the stored bits, we don't
839   // have all the bits to feed it.  We could do something crazy in the future
840   // (issue a smaller load then merge the bits in) but this seems unlikely to be
841   // valuable.
842   if (StoreOffset > LoadOffset ||
843       StoreOffset+StoreSize < LoadOffset+LoadSize)
844     return -1;
845   
846   // Okay, we can do this transformation.  Return the number of bytes into the
847   // store that the load is.
848   return LoadOffset-StoreOffset;
849 }  
850
851 /// AnalyzeLoadFromClobberingStore - This function is called when we have a
852 /// memdep query of a load that ends up being a clobbering store.
853 static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
854                                           StoreInst *DepSI,
855                                           const TargetData &TD) {
856   // Cannot handle reading from store of first-class aggregate yet.
857   if (DepSI->getValueOperand()->getType()->isStructTy() ||
858       DepSI->getValueOperand()->getType()->isArrayTy())
859     return -1;
860
861   Value *StorePtr = DepSI->getPointerOperand();
862   uint64_t StoreSize =TD.getTypeSizeInBits(DepSI->getValueOperand()->getType());
863   return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
864                                         StorePtr, StoreSize, TD);
865 }
866
867 /// AnalyzeLoadFromClobberingLoad - This function is called when we have a
868 /// memdep query of a load that ends up being clobbered by another load.  See if
869 /// the other load can feed into the second load.
870 static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
871                                          LoadInst *DepLI, const TargetData &TD){
872   // Cannot handle reading from store of first-class aggregate yet.
873   if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
874     return -1;
875   
876   Value *DepPtr = DepLI->getPointerOperand();
877   uint64_t DepSize = TD.getTypeSizeInBits(DepLI->getType());
878   int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, TD);
879   if (R != -1) return R;
880   
881   // If we have a load/load clobber an DepLI can be widened to cover this load,
882   // then we should widen it!
883   int64_t LoadOffs = 0;
884   const Value *LoadBase =
885     GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, TD);
886   unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
887   
888   unsigned Size = MemoryDependenceAnalysis::
889     getLoadLoadClobberFullWidthSize(LoadBase, LoadOffs, LoadSize, DepLI, TD);
890   if (Size == 0) return -1;
891   
892   return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, TD);
893 }
894
895
896
897 static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
898                                             MemIntrinsic *MI,
899                                             const TargetData &TD) {
900   // If the mem operation is a non-constant size, we can't handle it.
901   ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
902   if (SizeCst == 0) return -1;
903   uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
904
905   // If this is memset, we just need to see if the offset is valid in the size
906   // of the memset..
907   if (MI->getIntrinsicID() == Intrinsic::memset)
908     return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
909                                           MemSizeInBits, TD);
910   
911   // If we have a memcpy/memmove, the only case we can handle is if this is a
912   // copy from constant memory.  In that case, we can read directly from the
913   // constant memory.
914   MemTransferInst *MTI = cast<MemTransferInst>(MI);
915   
916   Constant *Src = dyn_cast<Constant>(MTI->getSource());
917   if (Src == 0) return -1;
918   
919   GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, &TD));
920   if (GV == 0 || !GV->isConstant()) return -1;
921   
922   // See if the access is within the bounds of the transfer.
923   int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
924                                               MI->getDest(), MemSizeInBits, TD);
925   if (Offset == -1)
926     return Offset;
927   
928   // Otherwise, see if we can constant fold a load from the constant with the
929   // offset applied as appropriate.
930   Src = ConstantExpr::getBitCast(Src,
931                                  llvm::Type::getInt8PtrTy(Src->getContext()));
932   Constant *OffsetCst = 
933     ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
934   Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
935   Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
936   if (ConstantFoldLoadFromConstPtr(Src, &TD))
937     return Offset;
938   return -1;
939 }
940                                             
941
942 /// GetStoreValueForLoad - This function is called when we have a
943 /// memdep query of a load that ends up being a clobbering store.  This means
944 /// that the store provides bits used by the load but we the pointers don't
945 /// mustalias.  Check this case to see if there is anything more we can do
946 /// before we give up.
947 static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
948                                    Type *LoadTy,
949                                    Instruction *InsertPt, const TargetData &TD){
950   LLVMContext &Ctx = SrcVal->getType()->getContext();
951   
952   uint64_t StoreSize = (TD.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
953   uint64_t LoadSize = (TD.getTypeSizeInBits(LoadTy) + 7) / 8;
954   
955   IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
956   
957   // Compute which bits of the stored value are being used by the load.  Convert
958   // to an integer type to start with.
959   if (SrcVal->getType()->isPointerTy())
960     SrcVal = Builder.CreatePtrToInt(SrcVal, TD.getIntPtrType(Ctx));
961   if (!SrcVal->getType()->isIntegerTy())
962     SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
963   
964   // Shift the bits to the least significant depending on endianness.
965   unsigned ShiftAmt;
966   if (TD.isLittleEndian())
967     ShiftAmt = Offset*8;
968   else
969     ShiftAmt = (StoreSize-LoadSize-Offset)*8;
970   
971   if (ShiftAmt)
972     SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
973   
974   if (LoadSize != StoreSize)
975     SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
976   
977   return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
978 }
979
980 /// GetLoadValueForLoad - This function is called when we have a
981 /// memdep query of a load that ends up being a clobbering load.  This means
982 /// that the load *may* provide bits used by the load but we can't be sure
983 /// because the pointers don't mustalias.  Check this case to see if there is
984 /// anything more we can do before we give up.
985 static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
986                                   Type *LoadTy, Instruction *InsertPt,
987                                   GVN &gvn) {
988   const TargetData &TD = *gvn.getTargetData();
989   // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
990   // widen SrcVal out to a larger load.
991   unsigned SrcValSize = TD.getTypeStoreSize(SrcVal->getType());
992   unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
993   if (Offset+LoadSize > SrcValSize) {
994     assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
995     assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
996     // If we have a load/load clobber an DepLI can be widened to cover this
997     // load, then we should widen it to the next power of 2 size big enough!
998     unsigned NewLoadSize = Offset+LoadSize;
999     if (!isPowerOf2_32(NewLoadSize))
1000       NewLoadSize = NextPowerOf2(NewLoadSize);
1001
1002     Value *PtrVal = SrcVal->getPointerOperand();
1003     
1004     // Insert the new load after the old load.  This ensures that subsequent
1005     // memdep queries will find the new load.  We can't easily remove the old
1006     // load completely because it is already in the value numbering table.
1007     IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
1008     Type *DestPTy = 
1009       IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
1010     DestPTy = PointerType::get(DestPTy, 
1011                        cast<PointerType>(PtrVal->getType())->getAddressSpace());
1012     Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
1013     PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
1014     LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
1015     NewLoad->takeName(SrcVal);
1016     NewLoad->setAlignment(SrcVal->getAlignment());
1017
1018     DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
1019     DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
1020     
1021     // Replace uses of the original load with the wider load.  On a big endian
1022     // system, we need to shift down to get the relevant bits.
1023     Value *RV = NewLoad;
1024     if (TD.isBigEndian())
1025       RV = Builder.CreateLShr(RV,
1026                     NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
1027     RV = Builder.CreateTrunc(RV, SrcVal->getType());
1028     SrcVal->replaceAllUsesWith(RV);
1029     
1030     // We would like to use gvn.markInstructionForDeletion here, but we can't
1031     // because the load is already memoized into the leader map table that GVN
1032     // tracks.  It is potentially possible to remove the load from the table,
1033     // but then there all of the operations based on it would need to be
1034     // rehashed.  Just leave the dead load around.
1035     gvn.getMemDep().removeInstruction(SrcVal);
1036     SrcVal = NewLoad;
1037   }
1038   
1039   return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, TD);
1040 }
1041
1042
1043 /// GetMemInstValueForLoad - This function is called when we have a
1044 /// memdep query of a load that ends up being a clobbering mem intrinsic.
1045 static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
1046                                      Type *LoadTy, Instruction *InsertPt,
1047                                      const TargetData &TD){
1048   LLVMContext &Ctx = LoadTy->getContext();
1049   uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
1050
1051   IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
1052   
1053   // We know that this method is only called when the mem transfer fully
1054   // provides the bits for the load.
1055   if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
1056     // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
1057     // independently of what the offset is.
1058     Value *Val = MSI->getValue();
1059     if (LoadSize != 1)
1060       Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
1061     
1062     Value *OneElt = Val;
1063     
1064     // Splat the value out to the right number of bits.
1065     for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
1066       // If we can double the number of bytes set, do it.
1067       if (NumBytesSet*2 <= LoadSize) {
1068         Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
1069         Val = Builder.CreateOr(Val, ShVal);
1070         NumBytesSet <<= 1;
1071         continue;
1072       }
1073       
1074       // Otherwise insert one byte at a time.
1075       Value *ShVal = Builder.CreateShl(Val, 1*8);
1076       Val = Builder.CreateOr(OneElt, ShVal);
1077       ++NumBytesSet;
1078     }
1079     
1080     return CoerceAvailableValueToLoadType(Val, LoadTy, InsertPt, TD);
1081   }
1082  
1083   // Otherwise, this is a memcpy/memmove from a constant global.
1084   MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
1085   Constant *Src = cast<Constant>(MTI->getSource());
1086
1087   // Otherwise, see if we can constant fold a load from the constant with the
1088   // offset applied as appropriate.
1089   Src = ConstantExpr::getBitCast(Src,
1090                                  llvm::Type::getInt8PtrTy(Src->getContext()));
1091   Constant *OffsetCst = 
1092   ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
1093   Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
1094   Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
1095   return ConstantFoldLoadFromConstPtr(Src, &TD);
1096 }
1097
1098 namespace {
1099
1100 struct AvailableValueInBlock {
1101   /// BB - The basic block in question.
1102   BasicBlock *BB;
1103   enum ValType {
1104     SimpleVal,  // A simple offsetted value that is accessed.
1105     LoadVal,    // A value produced by a load.
1106     MemIntrin   // A memory intrinsic which is loaded from.
1107   };
1108   
1109   /// V - The value that is live out of the block.
1110   PointerIntPair<Value *, 2, ValType> Val;
1111   
1112   /// Offset - The byte offset in Val that is interesting for the load query.
1113   unsigned Offset;
1114   
1115   static AvailableValueInBlock get(BasicBlock *BB, Value *V,
1116                                    unsigned Offset = 0) {
1117     AvailableValueInBlock Res;
1118     Res.BB = BB;
1119     Res.Val.setPointer(V);
1120     Res.Val.setInt(SimpleVal);
1121     Res.Offset = Offset;
1122     return Res;
1123   }
1124
1125   static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
1126                                      unsigned Offset = 0) {
1127     AvailableValueInBlock Res;
1128     Res.BB = BB;
1129     Res.Val.setPointer(MI);
1130     Res.Val.setInt(MemIntrin);
1131     Res.Offset = Offset;
1132     return Res;
1133   }
1134   
1135   static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
1136                                        unsigned Offset = 0) {
1137     AvailableValueInBlock Res;
1138     Res.BB = BB;
1139     Res.Val.setPointer(LI);
1140     Res.Val.setInt(LoadVal);
1141     Res.Offset = Offset;
1142     return Res;
1143   }
1144
1145   bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
1146   bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
1147   bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
1148
1149   Value *getSimpleValue() const {
1150     assert(isSimpleValue() && "Wrong accessor");
1151     return Val.getPointer();
1152   }
1153   
1154   LoadInst *getCoercedLoadValue() const {
1155     assert(isCoercedLoadValue() && "Wrong accessor");
1156     return cast<LoadInst>(Val.getPointer());
1157   }
1158   
1159   MemIntrinsic *getMemIntrinValue() const {
1160     assert(isMemIntrinValue() && "Wrong accessor");
1161     return cast<MemIntrinsic>(Val.getPointer());
1162   }
1163   
1164   /// MaterializeAdjustedValue - Emit code into this block to adjust the value
1165   /// defined here to the specified type.  This handles various coercion cases.
1166   Value *MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const {
1167     Value *Res;
1168     if (isSimpleValue()) {
1169       Res = getSimpleValue();
1170       if (Res->getType() != LoadTy) {
1171         const TargetData *TD = gvn.getTargetData();
1172         assert(TD && "Need target data to handle type mismatch case");
1173         Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(),
1174                                    *TD);
1175         
1176         DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << "  "
1177                      << *getSimpleValue() << '\n'
1178                      << *Res << '\n' << "\n\n\n");
1179       }
1180     } else if (isCoercedLoadValue()) {
1181       LoadInst *Load = getCoercedLoadValue();
1182       if (Load->getType() == LoadTy && Offset == 0) {
1183         Res = Load;
1184       } else {
1185         Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
1186                                   gvn);
1187         
1188         DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << "  "
1189                      << *getCoercedLoadValue() << '\n'
1190                      << *Res << '\n' << "\n\n\n");
1191       }
1192     } else {
1193       const TargetData *TD = gvn.getTargetData();
1194       assert(TD && "Need target data to handle type mismatch case");
1195       Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset,
1196                                    LoadTy, BB->getTerminator(), *TD);
1197       DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
1198                    << "  " << *getMemIntrinValue() << '\n'
1199                    << *Res << '\n' << "\n\n\n");
1200     }
1201     return Res;
1202   }
1203 };
1204
1205 } // end anonymous namespace
1206
1207 /// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1208 /// construct SSA form, allowing us to eliminate LI.  This returns the value
1209 /// that should be used at LI's definition site.
1210 static Value *ConstructSSAForLoadSet(LoadInst *LI, 
1211                          SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
1212                                      GVN &gvn) {
1213   // Check for the fully redundant, dominating load case.  In this case, we can
1214   // just use the dominating value directly.
1215   if (ValuesPerBlock.size() == 1 && 
1216       gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
1217                                                LI->getParent()))
1218     return ValuesPerBlock[0].MaterializeAdjustedValue(LI->getType(), gvn);
1219
1220   // Otherwise, we have to construct SSA form.
1221   SmallVector<PHINode*, 8> NewPHIs;
1222   SSAUpdater SSAUpdate(&NewPHIs);
1223   SSAUpdate.Initialize(LI->getType(), LI->getName());
1224   
1225   Type *LoadTy = LI->getType();
1226   
1227   for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1228     const AvailableValueInBlock &AV = ValuesPerBlock[i];
1229     BasicBlock *BB = AV.BB;
1230     
1231     if (SSAUpdate.HasValueForBlock(BB))
1232       continue;
1233
1234     SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LoadTy, gvn));
1235   }
1236   
1237   // Perform PHI construction.
1238   Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1239   
1240   // If new PHI nodes were created, notify alias analysis.
1241   if (V->getType()->isPointerTy()) {
1242     AliasAnalysis *AA = gvn.getAliasAnalysis();
1243     
1244     for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1245       AA->copyValue(LI, NewPHIs[i]);
1246     
1247     // Now that we've copied information to the new PHIs, scan through
1248     // them again and inform alias analysis that we've added potentially
1249     // escaping uses to any values that are operands to these PHIs.
1250     for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
1251       PHINode *P = NewPHIs[i];
1252       for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii) {
1253         unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
1254         AA->addEscapingUse(P->getOperandUse(jj));
1255       }
1256     }
1257   }
1258
1259   return V;
1260 }
1261
1262 static bool isLifetimeStart(const Instruction *Inst) {
1263   if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
1264     return II->getIntrinsicID() == Intrinsic::lifetime_start;
1265   return false;
1266 }
1267
1268 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1269 /// non-local by performing PHI construction.
1270 bool GVN::processNonLocalLoad(LoadInst *LI) {
1271   // Find the non-local dependencies of the load.
1272   SmallVector<NonLocalDepResult, 64> Deps;
1273   AliasAnalysis::Location Loc = VN.getAliasAnalysis()->getLocation(LI);
1274   MD->getNonLocalPointerDependency(Loc, true, LI->getParent(), Deps);
1275   //DEBUG(dbgs() << "INVESTIGATING NONLOCAL LOAD: "
1276   //             << Deps.size() << *LI << '\n');
1277
1278   // If we had to process more than one hundred blocks to find the
1279   // dependencies, this load isn't worth worrying about.  Optimizing
1280   // it will be too expensive.
1281   unsigned NumDeps = Deps.size();
1282   if (NumDeps > 100)
1283     return false;
1284
1285   // If we had a phi translation failure, we'll have a single entry which is a
1286   // clobber in the current block.  Reject this early.
1287   if (NumDeps == 1 &&
1288       !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
1289     DEBUG(
1290       dbgs() << "GVN: non-local load ";
1291       WriteAsOperand(dbgs(), LI);
1292       dbgs() << " has unknown dependencies\n";
1293     );
1294     return false;
1295   }
1296
1297   // Filter out useless results (non-locals, etc).  Keep track of the blocks
1298   // where we have a value available in repl, also keep track of whether we see
1299   // dependencies that produce an unknown value for the load (such as a call
1300   // that could potentially clobber the load).
1301   SmallVector<AvailableValueInBlock, 64> ValuesPerBlock;
1302   SmallVector<BasicBlock*, 64> UnavailableBlocks;
1303
1304   for (unsigned i = 0, e = NumDeps; i != e; ++i) {
1305     BasicBlock *DepBB = Deps[i].getBB();
1306     MemDepResult DepInfo = Deps[i].getResult();
1307
1308     if (!DepInfo.isDef() && !DepInfo.isClobber()) {
1309       UnavailableBlocks.push_back(DepBB);
1310       continue;
1311     }
1312
1313     if (DepInfo.isClobber()) {
1314       // The address being loaded in this non-local block may not be the same as
1315       // the pointer operand of the load if PHI translation occurs.  Make sure
1316       // to consider the right address.
1317       Value *Address = Deps[i].getAddress();
1318       
1319       // If the dependence is to a store that writes to a superset of the bits
1320       // read by the load, we can extract the bits we need for the load from the
1321       // stored value.
1322       if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1323         if (TD && Address) {
1324           int Offset = AnalyzeLoadFromClobberingStore(LI->getType(), Address,
1325                                                       DepSI, *TD);
1326           if (Offset != -1) {
1327             ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1328                                                        DepSI->getValueOperand(),
1329                                                                 Offset));
1330             continue;
1331           }
1332         }
1333       }
1334       
1335       // Check to see if we have something like this:
1336       //    load i32* P
1337       //    load i8* (P+1)
1338       // if we have this, replace the later with an extraction from the former.
1339       if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
1340         // If this is a clobber and L is the first instruction in its block, then
1341         // we have the first instruction in the entry block.
1342         if (DepLI != LI && Address && TD) {
1343           int Offset = AnalyzeLoadFromClobberingLoad(LI->getType(),
1344                                                      LI->getPointerOperand(),
1345                                                      DepLI, *TD);
1346           
1347           if (Offset != -1) {
1348             ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
1349                                                                     Offset));
1350             continue;
1351           }
1352         }
1353       }
1354
1355       // If the clobbering value is a memset/memcpy/memmove, see if we can
1356       // forward a value on from it.
1357       if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
1358         if (TD && Address) {
1359           int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
1360                                                         DepMI, *TD);
1361           if (Offset != -1) {
1362             ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
1363                                                                   Offset));
1364             continue;
1365           }            
1366         }
1367       }
1368       
1369       UnavailableBlocks.push_back(DepBB);
1370       continue;
1371     }
1372
1373     // DepInfo.isDef() here
1374
1375     Instruction *DepInst = DepInfo.getInst();
1376
1377     // Loading the allocation -> undef.
1378     if (isa<AllocaInst>(DepInst) || isMalloc(DepInst) ||
1379         // Loading immediately after lifetime begin -> undef.
1380         isLifetimeStart(DepInst)) {
1381       ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1382                                              UndefValue::get(LI->getType())));
1383       continue;
1384     }
1385     
1386     if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
1387       // Reject loads and stores that are to the same address but are of
1388       // different types if we have to.
1389       if (S->getValueOperand()->getType() != LI->getType()) {
1390         // If the stored value is larger or equal to the loaded value, we can
1391         // reuse it.
1392         if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
1393                                                         LI->getType(), *TD)) {
1394           UnavailableBlocks.push_back(DepBB);
1395           continue;
1396         }
1397       }
1398
1399       ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1400                                                          S->getValueOperand()));
1401       continue;
1402     }
1403     
1404     if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
1405       // If the types mismatch and we can't handle it, reject reuse of the load.
1406       if (LD->getType() != LI->getType()) {
1407         // If the stored value is larger or equal to the loaded value, we can
1408         // reuse it.
1409         if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
1410           UnavailableBlocks.push_back(DepBB);
1411           continue;
1412         }          
1413       }
1414       ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
1415       continue;
1416     }
1417     
1418     UnavailableBlocks.push_back(DepBB);
1419     continue;
1420   }
1421
1422   // If we have no predecessors that produce a known value for this load, exit
1423   // early.
1424   if (ValuesPerBlock.empty()) return false;
1425
1426   // If all of the instructions we depend on produce a known value for this
1427   // load, then it is fully redundant and we can use PHI insertion to compute
1428   // its value.  Insert PHIs and remove the fully redundant value now.
1429   if (UnavailableBlocks.empty()) {
1430     DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1431     
1432     // Perform PHI construction.
1433     Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1434     LI->replaceAllUsesWith(V);
1435
1436     if (isa<PHINode>(V))
1437       V->takeName(LI);
1438     if (V->getType()->isPointerTy())
1439       MD->invalidateCachedPointerInfo(V);
1440     markInstructionForDeletion(LI);
1441     ++NumGVNLoad;
1442     return true;
1443   }
1444
1445   if (!EnablePRE || !EnableLoadPRE)
1446     return false;
1447
1448   // Okay, we have *some* definitions of the value.  This means that the value
1449   // is available in some of our (transitive) predecessors.  Lets think about
1450   // doing PRE of this load.  This will involve inserting a new load into the
1451   // predecessor when it's not available.  We could do this in general, but
1452   // prefer to not increase code size.  As such, we only do this when we know
1453   // that we only have to insert *one* load (which means we're basically moving
1454   // the load, not inserting a new one).
1455
1456   SmallPtrSet<BasicBlock *, 4> Blockers;
1457   for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1458     Blockers.insert(UnavailableBlocks[i]);
1459
1460   // Let's find the first basic block with more than one predecessor.  Walk
1461   // backwards through predecessors if needed.
1462   BasicBlock *LoadBB = LI->getParent();
1463   BasicBlock *TmpBB = LoadBB;
1464
1465   bool isSinglePred = false;
1466   bool allSingleSucc = true;
1467   while (TmpBB->getSinglePredecessor()) {
1468     isSinglePred = true;
1469     TmpBB = TmpBB->getSinglePredecessor();
1470     if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1471       return false;
1472     if (Blockers.count(TmpBB))
1473       return false;
1474     
1475     // If any of these blocks has more than one successor (i.e. if the edge we
1476     // just traversed was critical), then there are other paths through this 
1477     // block along which the load may not be anticipated.  Hoisting the load 
1478     // above this block would be adding the load to execution paths along
1479     // which it was not previously executed.
1480     if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1481       return false;
1482   }
1483
1484   assert(TmpBB);
1485   LoadBB = TmpBB;
1486
1487   // FIXME: It is extremely unclear what this loop is doing, other than
1488   // artificially restricting loadpre.
1489   if (isSinglePred) {
1490     bool isHot = false;
1491     for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1492       const AvailableValueInBlock &AV = ValuesPerBlock[i];
1493       if (AV.isSimpleValue())
1494         // "Hot" Instruction is in some loop (because it dominates its dep.
1495         // instruction).
1496         if (Instruction *I = dyn_cast<Instruction>(AV.getSimpleValue()))
1497           if (DT->dominates(LI, I)) {
1498             isHot = true;
1499             break;
1500           }
1501     }
1502
1503     // We are interested only in "hot" instructions. We don't want to do any
1504     // mis-optimizations here.
1505     if (!isHot)
1506       return false;
1507   }
1508
1509   // Check to see how many predecessors have the loaded value fully
1510   // available.
1511   DenseMap<BasicBlock*, Value*> PredLoads;
1512   DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1513   for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1514     FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
1515   for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1516     FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1517
1518   SmallVector<std::pair<TerminatorInst*, unsigned>, 4> NeedToSplit;
1519   for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1520        PI != E; ++PI) {
1521     BasicBlock *Pred = *PI;
1522     if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks)) {
1523       continue;
1524     }
1525     PredLoads[Pred] = 0;
1526
1527     if (Pred->getTerminator()->getNumSuccessors() != 1) {
1528       if (isa<IndirectBrInst>(Pred->getTerminator())) {
1529         DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1530               << Pred->getName() << "': " << *LI << '\n');
1531         return false;
1532       }
1533
1534       if (LoadBB->isLandingPad()) {
1535         DEBUG(dbgs()
1536               << "COULD NOT PRE LOAD BECAUSE OF LANDING PAD CRITICAL EDGE '"
1537               << Pred->getName() << "': " << *LI << '\n');
1538         return false;
1539       }
1540
1541       unsigned SuccNum = GetSuccessorNumber(Pred, LoadBB);
1542       NeedToSplit.push_back(std::make_pair(Pred->getTerminator(), SuccNum));
1543     }
1544   }
1545
1546   if (!NeedToSplit.empty()) {
1547     toSplit.append(NeedToSplit.begin(), NeedToSplit.end());
1548     return false;
1549   }
1550
1551   // Decide whether PRE is profitable for this load.
1552   unsigned NumUnavailablePreds = PredLoads.size();
1553   assert(NumUnavailablePreds != 0 &&
1554          "Fully available value should be eliminated above!");
1555   
1556   // If this load is unavailable in multiple predecessors, reject it.
1557   // FIXME: If we could restructure the CFG, we could make a common pred with
1558   // all the preds that don't have an available LI and insert a new load into
1559   // that one block.
1560   if (NumUnavailablePreds != 1)
1561       return false;
1562
1563   // Check if the load can safely be moved to all the unavailable predecessors.
1564   bool CanDoPRE = true;
1565   SmallVector<Instruction*, 8> NewInsts;
1566   for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1567          E = PredLoads.end(); I != E; ++I) {
1568     BasicBlock *UnavailablePred = I->first;
1569
1570     // Do PHI translation to get its value in the predecessor if necessary.  The
1571     // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1572
1573     // If all preds have a single successor, then we know it is safe to insert
1574     // the load on the pred (?!?), so we can insert code to materialize the
1575     // pointer if it is not available.
1576     PHITransAddr Address(LI->getPointerOperand(), TD);
1577     Value *LoadPtr = 0;
1578     if (allSingleSucc) {
1579       LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1580                                                   *DT, NewInsts);
1581     } else {
1582       Address.PHITranslateValue(LoadBB, UnavailablePred, DT);
1583       LoadPtr = Address.getAddr();
1584     }
1585
1586     // If we couldn't find or insert a computation of this phi translated value,
1587     // we fail PRE.
1588     if (LoadPtr == 0) {
1589       DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
1590             << *LI->getPointerOperand() << "\n");
1591       CanDoPRE = false;
1592       break;
1593     }
1594
1595     // Make sure it is valid to move this load here.  We have to watch out for:
1596     //  @1 = getelementptr (i8* p, ...
1597     //  test p and branch if == 0
1598     //  load @1
1599     // It is valid to have the getelementptr before the test, even if p can
1600     // be 0, as getelementptr only does address arithmetic.
1601     // If we are not pushing the value through any multiple-successor blocks
1602     // we do not have this case.  Otherwise, check that the load is safe to
1603     // put anywhere; this can be improved, but should be conservatively safe.
1604     if (!allSingleSucc &&
1605         // FIXME: REEVALUTE THIS.
1606         !isSafeToLoadUnconditionally(LoadPtr,
1607                                      UnavailablePred->getTerminator(),
1608                                      LI->getAlignment(), TD)) {
1609       CanDoPRE = false;
1610       break;
1611     }
1612
1613     I->second = LoadPtr;
1614   }
1615
1616   if (!CanDoPRE) {
1617     while (!NewInsts.empty()) {
1618       Instruction *I = NewInsts.pop_back_val();
1619       if (MD) MD->removeInstruction(I);
1620       I->eraseFromParent();
1621     }
1622     return false;
1623   }
1624
1625   // Okay, we can eliminate this load by inserting a reload in the predecessor
1626   // and using PHI construction to get the value in the other predecessors, do
1627   // it.
1628   DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
1629   DEBUG(if (!NewInsts.empty())
1630           dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
1631                  << *NewInsts.back() << '\n');
1632   
1633   // Assign value numbers to the new instructions.
1634   for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
1635     // FIXME: We really _ought_ to insert these value numbers into their 
1636     // parent's availability map.  However, in doing so, we risk getting into
1637     // ordering issues.  If a block hasn't been processed yet, we would be
1638     // marking a value as AVAIL-IN, which isn't what we intend.
1639     VN.lookup_or_add(NewInsts[i]);
1640   }
1641
1642   for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1643          E = PredLoads.end(); I != E; ++I) {
1644     BasicBlock *UnavailablePred = I->first;
1645     Value *LoadPtr = I->second;
1646
1647     Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1648                                         LI->getAlignment(),
1649                                         UnavailablePred->getTerminator());
1650
1651     // Transfer the old load's TBAA tag to the new load.
1652     if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa))
1653       NewLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1654
1655     // Transfer DebugLoc.
1656     NewLoad->setDebugLoc(LI->getDebugLoc());
1657
1658     // Add the newly created load.
1659     ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
1660                                                         NewLoad));
1661     MD->invalidateCachedPointerInfo(LoadPtr);
1662     DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
1663   }
1664
1665   // Perform PHI construction.
1666   Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1667   LI->replaceAllUsesWith(V);
1668   if (isa<PHINode>(V))
1669     V->takeName(LI);
1670   if (V->getType()->isPointerTy())
1671     MD->invalidateCachedPointerInfo(V);
1672   markInstructionForDeletion(LI);
1673   ++NumPRELoad;
1674   return true;
1675 }
1676
1677 /// processLoad - Attempt to eliminate a load, first by eliminating it
1678 /// locally, and then attempting non-local elimination if that fails.
1679 bool GVN::processLoad(LoadInst *L) {
1680   if (!MD)
1681     return false;
1682
1683   if (!L->isSimple())
1684     return false;
1685
1686   if (L->use_empty()) {
1687     markInstructionForDeletion(L);
1688     return true;
1689   }
1690   
1691   // ... to a pointer that has been loaded from before...
1692   MemDepResult Dep = MD->getDependency(L);
1693
1694   // If we have a clobber and target data is around, see if this is a clobber
1695   // that we can fix up through code synthesis.
1696   if (Dep.isClobber() && TD) {
1697     // Check to see if we have something like this:
1698     //   store i32 123, i32* %P
1699     //   %A = bitcast i32* %P to i8*
1700     //   %B = gep i8* %A, i32 1
1701     //   %C = load i8* %B
1702     //
1703     // We could do that by recognizing if the clobber instructions are obviously
1704     // a common base + constant offset, and if the previous store (or memset)
1705     // completely covers this load.  This sort of thing can happen in bitfield
1706     // access code.
1707     Value *AvailVal = 0;
1708     if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
1709       int Offset = AnalyzeLoadFromClobberingStore(L->getType(),
1710                                                   L->getPointerOperand(),
1711                                                   DepSI, *TD);
1712       if (Offset != -1)
1713         AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
1714                                         L->getType(), L, *TD);
1715     }
1716     
1717     // Check to see if we have something like this:
1718     //    load i32* P
1719     //    load i8* (P+1)
1720     // if we have this, replace the later with an extraction from the former.
1721     if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
1722       // If this is a clobber and L is the first instruction in its block, then
1723       // we have the first instruction in the entry block.
1724       if (DepLI == L)
1725         return false;
1726       
1727       int Offset = AnalyzeLoadFromClobberingLoad(L->getType(),
1728                                                  L->getPointerOperand(),
1729                                                  DepLI, *TD);
1730       if (Offset != -1)
1731         AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
1732     }
1733     
1734     // If the clobbering value is a memset/memcpy/memmove, see if we can forward
1735     // a value on from it.
1736     if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
1737       int Offset = AnalyzeLoadFromClobberingMemInst(L->getType(),
1738                                                     L->getPointerOperand(),
1739                                                     DepMI, *TD);
1740       if (Offset != -1)
1741         AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, *TD);
1742     }
1743         
1744     if (AvailVal) {
1745       DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
1746             << *AvailVal << '\n' << *L << "\n\n\n");
1747       
1748       // Replace the load!
1749       L->replaceAllUsesWith(AvailVal);
1750       if (AvailVal->getType()->isPointerTy())
1751         MD->invalidateCachedPointerInfo(AvailVal);
1752       markInstructionForDeletion(L);
1753       ++NumGVNLoad;
1754       return true;
1755     }
1756   }
1757   
1758   // If the value isn't available, don't do anything!
1759   if (Dep.isClobber()) {
1760     DEBUG(
1761       // fast print dep, using operator<< on instruction is too slow.
1762       dbgs() << "GVN: load ";
1763       WriteAsOperand(dbgs(), L);
1764       Instruction *I = Dep.getInst();
1765       dbgs() << " is clobbered by " << *I << '\n';
1766     );
1767     return false;
1768   }
1769
1770   // If it is defined in another block, try harder.
1771   if (Dep.isNonLocal())
1772     return processNonLocalLoad(L);
1773
1774   if (!Dep.isDef()) {
1775     DEBUG(
1776       // fast print dep, using operator<< on instruction is too slow.
1777       dbgs() << "GVN: load ";
1778       WriteAsOperand(dbgs(), L);
1779       dbgs() << " has unknown dependence\n";
1780     );
1781     return false;
1782   }
1783
1784   Instruction *DepInst = Dep.getInst();
1785   if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1786     Value *StoredVal = DepSI->getValueOperand();
1787     
1788     // The store and load are to a must-aliased pointer, but they may not
1789     // actually have the same type.  See if we know how to reuse the stored
1790     // value (depending on its type).
1791     if (StoredVal->getType() != L->getType()) {
1792       if (TD) {
1793         StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1794                                                    L, *TD);
1795         if (StoredVal == 0)
1796           return false;
1797         
1798         DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1799                      << '\n' << *L << "\n\n\n");
1800       }
1801       else 
1802         return false;
1803     }
1804
1805     // Remove it!
1806     L->replaceAllUsesWith(StoredVal);
1807     if (StoredVal->getType()->isPointerTy())
1808       MD->invalidateCachedPointerInfo(StoredVal);
1809     markInstructionForDeletion(L);
1810     ++NumGVNLoad;
1811     return true;
1812   }
1813
1814   if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1815     Value *AvailableVal = DepLI;
1816     
1817     // The loads are of a must-aliased pointer, but they may not actually have
1818     // the same type.  See if we know how to reuse the previously loaded value
1819     // (depending on its type).
1820     if (DepLI->getType() != L->getType()) {
1821       if (TD) {
1822         AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(),
1823                                                       L, *TD);
1824         if (AvailableVal == 0)
1825           return false;
1826       
1827         DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1828                      << "\n" << *L << "\n\n\n");
1829       }
1830       else 
1831         return false;
1832     }
1833     
1834     // Remove it!
1835     L->replaceAllUsesWith(AvailableVal);
1836     if (DepLI->getType()->isPointerTy())
1837       MD->invalidateCachedPointerInfo(DepLI);
1838     markInstructionForDeletion(L);
1839     ++NumGVNLoad;
1840     return true;
1841   }
1842
1843   // If this load really doesn't depend on anything, then we must be loading an
1844   // undef value.  This can happen when loading for a fresh allocation with no
1845   // intervening stores, for example.
1846   if (isa<AllocaInst>(DepInst) || isMalloc(DepInst)) {
1847     L->replaceAllUsesWith(UndefValue::get(L->getType()));
1848     markInstructionForDeletion(L);
1849     ++NumGVNLoad;
1850     return true;
1851   }
1852   
1853   // If this load occurs either right after a lifetime begin,
1854   // then the loaded value is undefined.
1855   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
1856     if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
1857       L->replaceAllUsesWith(UndefValue::get(L->getType()));
1858       markInstructionForDeletion(L);
1859       ++NumGVNLoad;
1860       return true;
1861     }
1862   }
1863
1864   return false;
1865 }
1866
1867 // findLeader - In order to find a leader for a given value number at a 
1868 // specific basic block, we first obtain the list of all Values for that number,
1869 // and then scan the list to find one whose block dominates the block in 
1870 // question.  This is fast because dominator tree queries consist of only
1871 // a few comparisons of DFS numbers.
1872 Value *GVN::findLeader(BasicBlock *BB, uint32_t num) {
1873   LeaderTableEntry Vals = LeaderTable[num];
1874   if (!Vals.Val) return 0;
1875   
1876   Value *Val = 0;
1877   if (DT->dominates(Vals.BB, BB)) {
1878     Val = Vals.Val;
1879     if (isa<Constant>(Val)) return Val;
1880   }
1881   
1882   LeaderTableEntry* Next = Vals.Next;
1883   while (Next) {
1884     if (DT->dominates(Next->BB, BB)) {
1885       if (isa<Constant>(Next->Val)) return Next->Val;
1886       if (!Val) Val = Next->Val;
1887     }
1888     
1889     Next = Next->Next;
1890   }
1891
1892   return Val;
1893 }
1894
1895 /// replaceAllDominatedUsesWith - Replace all uses of 'From' with 'To' if the
1896 /// use is dominated by the given basic block.  Returns the number of uses that
1897 /// were replaced.
1898 unsigned GVN::replaceAllDominatedUsesWith(Value *From, Value *To,
1899                                           BasicBlock *Root) {
1900   unsigned Count = 0;
1901   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1902        UI != UE; ) {
1903     Use &U = (UI++).getUse();
1904     if (DT->dominates(Root, cast<Instruction>(U.getUser())->getParent())) {
1905       U.set(To);
1906       ++Count;
1907     }
1908   }
1909   return Count;
1910 }
1911
1912 /// propagateEquality - The given values are known to be equal in every block
1913 /// dominated by 'Root'.  Exploit this, for example by replacing 'LHS' with
1914 /// 'RHS' everywhere in the scope.  Returns whether a change was made.
1915 bool GVN::propagateEquality(Value *LHS, Value *RHS, BasicBlock *Root) {
1916   if (LHS == RHS) return false;
1917   assert(LHS->getType() == RHS->getType() && "Equal but types differ!");
1918
1919   // Don't try to propagate equalities between constants.
1920   if (isa<Constant>(LHS) && isa<Constant>(RHS))
1921     return false;
1922
1923   // Make sure that any constants are on the right-hand side.  In general the
1924   // best results are obtained by placing the longest lived value on the RHS.
1925   if (isa<Constant>(LHS))
1926     std::swap(LHS, RHS);
1927
1928   // If neither term is constant then bail out.  This is not for correctness,
1929   // it's just that the non-constant case is much less useful: it occurs just
1930   // as often as the constant case but handling it hardly ever results in an
1931   // improvement.
1932   if (!isa<Constant>(RHS))
1933     return false;
1934
1935   // If value numbering later deduces that an instruction in the scope is equal
1936   // to 'LHS' then ensure it will be turned into 'RHS'.
1937   addToLeaderTable(VN.lookup_or_add(LHS), RHS, Root);
1938
1939   // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope.  As
1940   // LHS always has at least one use that is not dominated by Root, this will
1941   // never do anything if LHS has only one use.
1942   bool Changed = false;
1943   if (!LHS->hasOneUse()) {
1944     unsigned NumReplacements = replaceAllDominatedUsesWith(LHS, RHS, Root);
1945     Changed |= NumReplacements > 0;
1946     NumGVNEqProp += NumReplacements;
1947   }
1948
1949   // Now try to deduce additional equalities from this one.  For example, if the
1950   // known equality was "(A != B)" == "false" then it follows that A and B are
1951   // equal in the scope.  Only boolean equalities with an explicit true or false
1952   // RHS are currently supported.
1953   if (!RHS->getType()->isIntegerTy(1))
1954     // Not a boolean equality - bail out.
1955     return Changed;
1956   ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
1957   if (!CI)
1958     // RHS neither 'true' nor 'false' - bail out.
1959     return Changed;
1960   // Whether RHS equals 'true'.  Otherwise it equals 'false'.
1961   bool isKnownTrue = CI->isAllOnesValue();
1962   bool isKnownFalse = !isKnownTrue;
1963
1964   // If "A && B" is known true then both A and B are known true.  If "A || B"
1965   // is known false then both A and B are known false.
1966   Value *A, *B;
1967   if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
1968       (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
1969     Changed |= propagateEquality(A, RHS, Root);
1970     Changed |= propagateEquality(B, RHS, Root);
1971     return Changed;
1972   }
1973
1974   // If we are propagating an equality like "(A == B)" == "true" then also
1975   // propagate the equality A == B.
1976   if (ICmpInst *Cmp = dyn_cast<ICmpInst>(LHS)) {
1977     // Only equality comparisons are supported.
1978     if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
1979         (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE)) {
1980       Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
1981       Changed |= propagateEquality(Op0, Op1, Root);
1982     }
1983     return Changed;
1984   }
1985
1986   return Changed;
1987 }
1988
1989 /// isOnlyReachableViaThisEdge - There is an edge from 'Src' to 'Dst'.  Return
1990 /// true if every path from the entry block to 'Dst' passes via this edge.  In
1991 /// particular 'Dst' must not be reachable via another edge from 'Src'.
1992 static bool isOnlyReachableViaThisEdge(BasicBlock *Src, BasicBlock *Dst,
1993                                        DominatorTree *DT) {
1994   // While in theory it is interesting to consider the case in which Dst has
1995   // more than one predecessor, because Dst might be part of a loop which is
1996   // only reachable from Src, in practice it is pointless since at the time
1997   // GVN runs all such loops have preheaders, which means that Dst will have
1998   // been changed to have only one predecessor, namely Src.
1999   BasicBlock *Pred = Dst->getSinglePredecessor();
2000   assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
2001   (void)Src;
2002   return Pred != 0;
2003 }
2004
2005 /// processInstruction - When calculating availability, handle an instruction
2006 /// by inserting it into the appropriate sets
2007 bool GVN::processInstruction(Instruction *I) {
2008   // Ignore dbg info intrinsics.
2009   if (isa<DbgInfoIntrinsic>(I))
2010     return false;
2011
2012   // If the instruction can be easily simplified then do so now in preference
2013   // to value numbering it.  Value numbering often exposes redundancies, for
2014   // example if it determines that %y is equal to %x then the instruction
2015   // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
2016   if (Value *V = SimplifyInstruction(I, TD, TLI, DT)) {
2017     I->replaceAllUsesWith(V);
2018     if (MD && V->getType()->isPointerTy())
2019       MD->invalidateCachedPointerInfo(V);
2020     markInstructionForDeletion(I);
2021     ++NumGVNSimpl;
2022     return true;
2023   }
2024
2025   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2026     if (processLoad(LI))
2027       return true;
2028
2029     unsigned Num = VN.lookup_or_add(LI);
2030     addToLeaderTable(Num, LI, LI->getParent());
2031     return false;
2032   }
2033
2034   // For conditional branches, we can perform simple conditional propagation on
2035   // the condition value itself.
2036   if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
2037     if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
2038       return false;
2039
2040     Value *BranchCond = BI->getCondition();
2041
2042     BasicBlock *TrueSucc = BI->getSuccessor(0);
2043     BasicBlock *FalseSucc = BI->getSuccessor(1);
2044     BasicBlock *Parent = BI->getParent();
2045     bool Changed = false;
2046
2047     if (isOnlyReachableViaThisEdge(Parent, TrueSucc, DT))
2048       Changed |= propagateEquality(BranchCond,
2049                                    ConstantInt::getTrue(TrueSucc->getContext()),
2050                                    TrueSucc);
2051
2052     if (isOnlyReachableViaThisEdge(Parent, FalseSucc, DT))
2053       Changed |= propagateEquality(BranchCond,
2054                                    ConstantInt::getFalse(FalseSucc->getContext()),
2055                                    FalseSucc);
2056
2057     return Changed;
2058   }
2059
2060   // For switches, propagate the case values into the case destinations.
2061   if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
2062     Value *SwitchCond = SI->getCondition();
2063     BasicBlock *Parent = SI->getParent();
2064     bool Changed = false;
2065     for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i) {
2066       BasicBlock *Dst = SI->getCaseSuccessor(i);
2067       if (isOnlyReachableViaThisEdge(Parent, Dst, DT))
2068         Changed |= propagateEquality(SwitchCond, SI->getCaseValue(i), Dst);
2069     }
2070     return Changed;
2071   }
2072
2073   // Instructions with void type don't return a value, so there's
2074   // no point in trying to find redudancies in them.
2075   if (I->getType()->isVoidTy()) return false;
2076   
2077   uint32_t NextNum = VN.getNextUnusedValueNumber();
2078   unsigned Num = VN.lookup_or_add(I);
2079
2080   // Allocations are always uniquely numbered, so we can save time and memory
2081   // by fast failing them.
2082   if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
2083     addToLeaderTable(Num, I, I->getParent());
2084     return false;
2085   }
2086
2087   // If the number we were assigned was a brand new VN, then we don't
2088   // need to do a lookup to see if the number already exists
2089   // somewhere in the domtree: it can't!
2090   if (Num == NextNum) {
2091     addToLeaderTable(Num, I, I->getParent());
2092     return false;
2093   }
2094   
2095   // Perform fast-path value-number based elimination of values inherited from
2096   // dominators.
2097   Value *repl = findLeader(I->getParent(), Num);
2098   if (repl == 0) {
2099     // Failure, just remember this instance for future use.
2100     addToLeaderTable(Num, I, I->getParent());
2101     return false;
2102   }
2103   
2104   // Remove it!
2105   I->replaceAllUsesWith(repl);
2106   if (MD && repl->getType()->isPointerTy())
2107     MD->invalidateCachedPointerInfo(repl);
2108   markInstructionForDeletion(I);
2109   return true;
2110 }
2111
2112 /// runOnFunction - This is the main transformation entry point for a function.
2113 bool GVN::runOnFunction(Function& F) {
2114   if (!NoLoads)
2115     MD = &getAnalysis<MemoryDependenceAnalysis>();
2116   DT = &getAnalysis<DominatorTree>();
2117   TD = getAnalysisIfAvailable<TargetData>();
2118   TLI = &getAnalysis<TargetLibraryInfo>();
2119   VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
2120   VN.setMemDep(MD);
2121   VN.setDomTree(DT);
2122
2123   bool Changed = false;
2124   bool ShouldContinue = true;
2125
2126   // Merge unconditional branches, allowing PRE to catch more
2127   // optimization opportunities.
2128   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
2129     BasicBlock *BB = FI++;
2130     
2131     bool removedBlock = MergeBlockIntoPredecessor(BB, this);
2132     if (removedBlock) ++NumGVNBlocks;
2133
2134     Changed |= removedBlock;
2135   }
2136
2137   unsigned Iteration = 0;
2138   while (ShouldContinue) {
2139     DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
2140     ShouldContinue = iterateOnFunction(F);
2141     if (splitCriticalEdges())
2142       ShouldContinue = true;
2143     Changed |= ShouldContinue;
2144     ++Iteration;
2145   }
2146
2147   if (EnablePRE) {
2148     bool PREChanged = true;
2149     while (PREChanged) {
2150       PREChanged = performPRE(F);
2151       Changed |= PREChanged;
2152     }
2153   }
2154   // FIXME: Should perform GVN again after PRE does something.  PRE can move
2155   // computations into blocks where they become fully redundant.  Note that
2156   // we can't do this until PRE's critical edge splitting updates memdep.
2157   // Actually, when this happens, we should just fully integrate PRE into GVN.
2158
2159   cleanupGlobalSets();
2160
2161   return Changed;
2162 }
2163
2164
2165 bool GVN::processBlock(BasicBlock *BB) {
2166   // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
2167   // (and incrementing BI before processing an instruction).
2168   assert(InstrsToErase.empty() &&
2169          "We expect InstrsToErase to be empty across iterations");
2170   bool ChangedFunction = false;
2171
2172   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
2173        BI != BE;) {
2174     ChangedFunction |= processInstruction(BI);
2175     if (InstrsToErase.empty()) {
2176       ++BI;
2177       continue;
2178     }
2179
2180     // If we need some instructions deleted, do it now.
2181     NumGVNInstr += InstrsToErase.size();
2182
2183     // Avoid iterator invalidation.
2184     bool AtStart = BI == BB->begin();
2185     if (!AtStart)
2186       --BI;
2187
2188     for (SmallVector<Instruction*, 4>::iterator I = InstrsToErase.begin(),
2189          E = InstrsToErase.end(); I != E; ++I) {
2190       DEBUG(dbgs() << "GVN removed: " << **I << '\n');
2191       if (MD) MD->removeInstruction(*I);
2192       (*I)->eraseFromParent();
2193       DEBUG(verifyRemoved(*I));
2194     }
2195     InstrsToErase.clear();
2196
2197     if (AtStart)
2198       BI = BB->begin();
2199     else
2200       ++BI;
2201   }
2202
2203   return ChangedFunction;
2204 }
2205
2206 /// performPRE - Perform a purely local form of PRE that looks for diamond
2207 /// control flow patterns and attempts to perform simple PRE at the join point.
2208 bool GVN::performPRE(Function &F) {
2209   bool Changed = false;
2210   DenseMap<BasicBlock*, Value*> predMap;
2211   for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
2212        DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
2213     BasicBlock *CurrentBlock = *DI;
2214
2215     // Nothing to PRE in the entry block.
2216     if (CurrentBlock == &F.getEntryBlock()) continue;
2217
2218     // Don't perform PRE on a landing pad.
2219     if (CurrentBlock->isLandingPad()) continue;
2220
2221     for (BasicBlock::iterator BI = CurrentBlock->begin(),
2222          BE = CurrentBlock->end(); BI != BE; ) {
2223       Instruction *CurInst = BI++;
2224
2225       if (isa<AllocaInst>(CurInst) ||
2226           isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
2227           CurInst->getType()->isVoidTy() ||
2228           CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
2229           isa<DbgInfoIntrinsic>(CurInst))
2230         continue;
2231       
2232       // We don't currently value number ANY inline asm calls.
2233       if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
2234         if (CallI->isInlineAsm())
2235           continue;
2236
2237       uint32_t ValNo = VN.lookup(CurInst);
2238
2239       // Look for the predecessors for PRE opportunities.  We're
2240       // only trying to solve the basic diamond case, where
2241       // a value is computed in the successor and one predecessor,
2242       // but not the other.  We also explicitly disallow cases
2243       // where the successor is its own predecessor, because they're
2244       // more complicated to get right.
2245       unsigned NumWith = 0;
2246       unsigned NumWithout = 0;
2247       BasicBlock *PREPred = 0;
2248       predMap.clear();
2249
2250       for (pred_iterator PI = pred_begin(CurrentBlock),
2251            PE = pred_end(CurrentBlock); PI != PE; ++PI) {
2252         BasicBlock *P = *PI;
2253         // We're not interested in PRE where the block is its
2254         // own predecessor, or in blocks with predecessors
2255         // that are not reachable.
2256         if (P == CurrentBlock) {
2257           NumWithout = 2;
2258           break;
2259         } else if (!DT->dominates(&F.getEntryBlock(), P))  {
2260           NumWithout = 2;
2261           break;
2262         }
2263
2264         Value* predV = findLeader(P, ValNo);
2265         if (predV == 0) {
2266           PREPred = P;
2267           ++NumWithout;
2268         } else if (predV == CurInst) {
2269           NumWithout = 2;
2270         } else {
2271           predMap[P] = predV;
2272           ++NumWith;
2273         }
2274       }
2275
2276       // Don't do PRE when it might increase code size, i.e. when
2277       // we would need to insert instructions in more than one pred.
2278       if (NumWithout != 1 || NumWith == 0)
2279         continue;
2280       
2281       // Don't do PRE across indirect branch.
2282       if (isa<IndirectBrInst>(PREPred->getTerminator()))
2283         continue;
2284
2285       // We can't do PRE safely on a critical edge, so instead we schedule
2286       // the edge to be split and perform the PRE the next time we iterate
2287       // on the function.
2288       unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
2289       if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2290         toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
2291         continue;
2292       }
2293
2294       // Instantiate the expression in the predecessor that lacked it.
2295       // Because we are going top-down through the block, all value numbers
2296       // will be available in the predecessor by the time we need them.  Any
2297       // that weren't originally present will have been instantiated earlier
2298       // in this loop.
2299       Instruction *PREInstr = CurInst->clone();
2300       bool success = true;
2301       for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
2302         Value *Op = PREInstr->getOperand(i);
2303         if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2304           continue;
2305
2306         if (Value *V = findLeader(PREPred, VN.lookup(Op))) {
2307           PREInstr->setOperand(i, V);
2308         } else {
2309           success = false;
2310           break;
2311         }
2312       }
2313
2314       // Fail out if we encounter an operand that is not available in
2315       // the PRE predecessor.  This is typically because of loads which
2316       // are not value numbered precisely.
2317       if (!success) {
2318         delete PREInstr;
2319         DEBUG(verifyRemoved(PREInstr));
2320         continue;
2321       }
2322
2323       PREInstr->insertBefore(PREPred->getTerminator());
2324       PREInstr->setName(CurInst->getName() + ".pre");
2325       PREInstr->setDebugLoc(CurInst->getDebugLoc());
2326       predMap[PREPred] = PREInstr;
2327       VN.add(PREInstr, ValNo);
2328       ++NumGVNPRE;
2329
2330       // Update the availability map to include the new instruction.
2331       addToLeaderTable(ValNo, PREInstr, PREPred);
2332
2333       // Create a PHI to make the value available in this block.
2334       pred_iterator PB = pred_begin(CurrentBlock), PE = pred_end(CurrentBlock);
2335       PHINode* Phi = PHINode::Create(CurInst->getType(), std::distance(PB, PE),
2336                                      CurInst->getName() + ".pre-phi",
2337                                      CurrentBlock->begin());
2338       for (pred_iterator PI = PB; PI != PE; ++PI) {
2339         BasicBlock *P = *PI;
2340         Phi->addIncoming(predMap[P], P);
2341       }
2342
2343       VN.add(Phi, ValNo);
2344       addToLeaderTable(ValNo, Phi, CurrentBlock);
2345       Phi->setDebugLoc(CurInst->getDebugLoc());
2346       CurInst->replaceAllUsesWith(Phi);
2347       if (Phi->getType()->isPointerTy()) {
2348         // Because we have added a PHI-use of the pointer value, it has now
2349         // "escaped" from alias analysis' perspective.  We need to inform
2350         // AA of this.
2351         for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee;
2352              ++ii) {
2353           unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
2354           VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(jj));
2355         }
2356         
2357         if (MD)
2358           MD->invalidateCachedPointerInfo(Phi);
2359       }
2360       VN.erase(CurInst);
2361       removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
2362
2363       DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
2364       if (MD) MD->removeInstruction(CurInst);
2365       CurInst->eraseFromParent();
2366       DEBUG(verifyRemoved(CurInst));
2367       Changed = true;
2368     }
2369   }
2370
2371   if (splitCriticalEdges())
2372     Changed = true;
2373
2374   return Changed;
2375 }
2376
2377 /// splitCriticalEdges - Split critical edges found during the previous
2378 /// iteration that may enable further optimization.
2379 bool GVN::splitCriticalEdges() {
2380   if (toSplit.empty())
2381     return false;
2382   do {
2383     std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
2384     SplitCriticalEdge(Edge.first, Edge.second, this);
2385   } while (!toSplit.empty());
2386   if (MD) MD->invalidateCachedPredecessors();
2387   return true;
2388 }
2389
2390 /// iterateOnFunction - Executes one iteration of GVN
2391 bool GVN::iterateOnFunction(Function &F) {
2392   cleanupGlobalSets();
2393   
2394   // Top-down walk of the dominator tree
2395   bool Changed = false;
2396 #if 0
2397   // Needed for value numbering with phi construction to work.
2398   ReversePostOrderTraversal<Function*> RPOT(&F);
2399   for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2400        RE = RPOT.end(); RI != RE; ++RI)
2401     Changed |= processBlock(*RI);
2402 #else
2403   for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2404        DE = df_end(DT->getRootNode()); DI != DE; ++DI)
2405     Changed |= processBlock(DI->getBlock());
2406 #endif
2407
2408   return Changed;
2409 }
2410
2411 void GVN::cleanupGlobalSets() {
2412   VN.clear();
2413   LeaderTable.clear();
2414   TableAllocator.Reset();
2415 }
2416
2417 /// verifyRemoved - Verify that the specified instruction does not occur in our
2418 /// internal data structures.
2419 void GVN::verifyRemoved(const Instruction *Inst) const {
2420   VN.verifyRemoved(Inst);
2421
2422   // Walk through the value number scope to make sure the instruction isn't
2423   // ferreted away in it.
2424   for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
2425        I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
2426     const LeaderTableEntry *Node = &I->second;
2427     assert(Node->Val != Inst && "Inst still in value numbering scope!");
2428     
2429     while (Node->Next) {
2430       Node = Node->Next;
2431       assert(Node->Val != Inst && "Inst still in value numbering scope!");
2432     }
2433   }
2434 }