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