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