PRE requires that critical edges be split.
[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/BasicBlock.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Value.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DepthFirstIterator.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/Dominators.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 using namespace llvm;
39
40 STATISTIC(NumGVNInstr, "Number of instructions deleted");
41 STATISTIC(NumGVNLoad, "Number of loads deleted");
42 STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
43
44 //===----------------------------------------------------------------------===//
45 //                         ValueTable Class
46 //===----------------------------------------------------------------------===//
47
48 /// This class holds the mapping between values and value numbers.  It is used
49 /// as an efficient mechanism to determine the expression-wise equivalence of
50 /// two values.
51 namespace {
52   struct VISIBILITY_HIDDEN Expression {
53     enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM, 
54                             FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ, 
55                             ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE, 
56                             ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ, 
57                             FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE, 
58                             FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE, 
59                             FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
60                             SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
61                             FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT, 
62                             PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
63                             EMPTY, TOMBSTONE };
64
65     ExpressionOpcode opcode;
66     const Type* type;
67     uint32_t firstVN;
68     uint32_t secondVN;
69     uint32_t thirdVN;
70     SmallVector<uint32_t, 4> varargs;
71     Value* function;
72   
73     Expression() { }
74     Expression(ExpressionOpcode o) : opcode(o) { }
75   
76     bool operator==(const Expression &other) const {
77       if (opcode != other.opcode)
78         return false;
79       else if (opcode == EMPTY || opcode == TOMBSTONE)
80         return true;
81       else if (type != other.type)
82         return false;
83       else if (function != other.function)
84         return false;
85       else if (firstVN != other.firstVN)
86         return false;
87       else if (secondVN != other.secondVN)
88         return false;
89       else if (thirdVN != other.thirdVN)
90         return false;
91       else {
92         if (varargs.size() != other.varargs.size())
93           return false;
94       
95         for (size_t i = 0; i < varargs.size(); ++i)
96           if (varargs[i] != other.varargs[i])
97             return false;
98     
99         return true;
100       }
101     }
102   
103     bool operator!=(const Expression &other) const {
104       if (opcode != other.opcode)
105         return true;
106       else if (opcode == EMPTY || opcode == TOMBSTONE)
107         return false;
108       else if (type != other.type)
109         return true;
110       else if (function != other.function)
111         return true;
112       else if (firstVN != other.firstVN)
113         return true;
114       else if (secondVN != other.secondVN)
115         return true;
116       else if (thirdVN != other.thirdVN)
117         return true;
118       else {
119         if (varargs.size() != other.varargs.size())
120           return true;
121       
122         for (size_t i = 0; i < varargs.size(); ++i)
123           if (varargs[i] != other.varargs[i])
124             return true;
125     
126           return false;
127       }
128     }
129   };
130   
131   class VISIBILITY_HIDDEN ValueTable {
132     private:
133       DenseMap<Value*, uint32_t> valueNumbering;
134       DenseMap<Expression, uint32_t> expressionNumbering;
135       AliasAnalysis* AA;
136       MemoryDependenceAnalysis* MD;
137       DominatorTree* DT;
138   
139       uint32_t nextValueNumber;
140     
141       Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
142       Expression::ExpressionOpcode getOpcode(CmpInst* C);
143       Expression::ExpressionOpcode getOpcode(CastInst* C);
144       Expression create_expression(BinaryOperator* BO);
145       Expression create_expression(CmpInst* C);
146       Expression create_expression(ShuffleVectorInst* V);
147       Expression create_expression(ExtractElementInst* C);
148       Expression create_expression(InsertElementInst* V);
149       Expression create_expression(SelectInst* V);
150       Expression create_expression(CastInst* C);
151       Expression create_expression(GetElementPtrInst* G);
152       Expression create_expression(CallInst* C);
153       Expression create_expression(Constant* C);
154     public:
155       ValueTable() : nextValueNumber(1) { }
156       uint32_t lookup_or_add(Value* V);
157       uint32_t lookup(Value* V) const;
158       void add(Value* V, uint32_t num);
159       void clear();
160       void erase(Value* v);
161       unsigned size();
162       void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
163       void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
164       void setDomTree(DominatorTree* D) { DT = D; }
165   };
166 }
167
168 namespace llvm {
169 template <> struct DenseMapInfo<Expression> {
170   static inline Expression getEmptyKey() {
171     return Expression(Expression::EMPTY);
172   }
173   
174   static inline Expression getTombstoneKey() {
175     return Expression(Expression::TOMBSTONE);
176   }
177   
178   static unsigned getHashValue(const Expression e) {
179     unsigned hash = e.opcode;
180     
181     hash = e.firstVN + hash * 37;
182     hash = e.secondVN + hash * 37;
183     hash = e.thirdVN + hash * 37;
184     
185     hash = ((unsigned)((uintptr_t)e.type >> 4) ^
186             (unsigned)((uintptr_t)e.type >> 9)) +
187            hash * 37;
188     
189     for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
190          E = e.varargs.end(); I != E; ++I)
191       hash = *I + hash * 37;
192     
193     hash = ((unsigned)((uintptr_t)e.function >> 4) ^
194             (unsigned)((uintptr_t)e.function >> 9)) +
195            hash * 37;
196     
197     return hash;
198   }
199   static bool isEqual(const Expression &LHS, const Expression &RHS) {
200     return LHS == RHS;
201   }
202   static bool isPod() { return true; }
203 };
204 }
205
206 //===----------------------------------------------------------------------===//
207 //                     ValueTable Internal Functions
208 //===----------------------------------------------------------------------===//
209 Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
210   switch(BO->getOpcode()) {
211   default: // THIS SHOULD NEVER HAPPEN
212     assert(0 && "Binary operator with unknown opcode?");
213   case Instruction::Add:  return Expression::ADD;
214   case Instruction::Sub:  return Expression::SUB;
215   case Instruction::Mul:  return Expression::MUL;
216   case Instruction::UDiv: return Expression::UDIV;
217   case Instruction::SDiv: return Expression::SDIV;
218   case Instruction::FDiv: return Expression::FDIV;
219   case Instruction::URem: return Expression::UREM;
220   case Instruction::SRem: return Expression::SREM;
221   case Instruction::FRem: return Expression::FREM;
222   case Instruction::Shl:  return Expression::SHL;
223   case Instruction::LShr: return Expression::LSHR;
224   case Instruction::AShr: return Expression::ASHR;
225   case Instruction::And:  return Expression::AND;
226   case Instruction::Or:   return Expression::OR;
227   case Instruction::Xor:  return Expression::XOR;
228   }
229 }
230
231 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
232   if (isa<ICmpInst>(C) || isa<VICmpInst>(C)) {
233     switch (C->getPredicate()) {
234     default:  // THIS SHOULD NEVER HAPPEN
235       assert(0 && "Comparison with unknown predicate?");
236     case ICmpInst::ICMP_EQ:  return Expression::ICMPEQ;
237     case ICmpInst::ICMP_NE:  return Expression::ICMPNE;
238     case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
239     case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
240     case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
241     case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
242     case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
243     case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
244     case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
245     case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
246     }
247   }
248   assert((isa<FCmpInst>(C) || isa<VFCmpInst>(C)) && "Unknown compare");
249   switch (C->getPredicate()) {
250   default: // THIS SHOULD NEVER HAPPEN
251     assert(0 && "Comparison with unknown predicate?");
252   case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
253   case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
254   case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
255   case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
256   case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
257   case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
258   case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
259   case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
260   case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
261   case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
262   case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
263   case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
264   case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
265   case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
266   }
267 }
268
269 Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
270   switch(C->getOpcode()) {
271   default: // THIS SHOULD NEVER HAPPEN
272     assert(0 && "Cast operator with unknown opcode?");
273   case Instruction::Trunc:    return Expression::TRUNC;
274   case Instruction::ZExt:     return Expression::ZEXT;
275   case Instruction::SExt:     return Expression::SEXT;
276   case Instruction::FPToUI:   return Expression::FPTOUI;
277   case Instruction::FPToSI:   return Expression::FPTOSI;
278   case Instruction::UIToFP:   return Expression::UITOFP;
279   case Instruction::SIToFP:   return Expression::SITOFP;
280   case Instruction::FPTrunc:  return Expression::FPTRUNC;
281   case Instruction::FPExt:    return Expression::FPEXT;
282   case Instruction::PtrToInt: return Expression::PTRTOINT;
283   case Instruction::IntToPtr: return Expression::INTTOPTR;
284   case Instruction::BitCast:  return Expression::BITCAST;
285   }
286 }
287
288 Expression ValueTable::create_expression(CallInst* C) {
289   Expression e;
290   
291   e.type = C->getType();
292   e.firstVN = 0;
293   e.secondVN = 0;
294   e.thirdVN = 0;
295   e.function = C->getCalledFunction();
296   e.opcode = Expression::CALL;
297   
298   for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
299        I != E; ++I)
300     e.varargs.push_back(lookup_or_add(*I));
301   
302   return e;
303 }
304
305 Expression ValueTable::create_expression(BinaryOperator* BO) {
306   Expression e;
307     
308   e.firstVN = lookup_or_add(BO->getOperand(0));
309   e.secondVN = lookup_or_add(BO->getOperand(1));
310   e.thirdVN = 0;
311   e.function = 0;
312   e.type = BO->getType();
313   e.opcode = getOpcode(BO);
314   
315   return e;
316 }
317
318 Expression ValueTable::create_expression(CmpInst* C) {
319   Expression e;
320     
321   e.firstVN = lookup_or_add(C->getOperand(0));
322   e.secondVN = lookup_or_add(C->getOperand(1));
323   e.thirdVN = 0;
324   e.function = 0;
325   e.type = C->getType();
326   e.opcode = getOpcode(C);
327   
328   return e;
329 }
330
331 Expression ValueTable::create_expression(CastInst* C) {
332   Expression e;
333     
334   e.firstVN = lookup_or_add(C->getOperand(0));
335   e.secondVN = 0;
336   e.thirdVN = 0;
337   e.function = 0;
338   e.type = C->getType();
339   e.opcode = getOpcode(C);
340   
341   return e;
342 }
343
344 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
345   Expression e;
346     
347   e.firstVN = lookup_or_add(S->getOperand(0));
348   e.secondVN = lookup_or_add(S->getOperand(1));
349   e.thirdVN = lookup_or_add(S->getOperand(2));
350   e.function = 0;
351   e.type = S->getType();
352   e.opcode = Expression::SHUFFLE;
353   
354   return e;
355 }
356
357 Expression ValueTable::create_expression(ExtractElementInst* E) {
358   Expression e;
359     
360   e.firstVN = lookup_or_add(E->getOperand(0));
361   e.secondVN = lookup_or_add(E->getOperand(1));
362   e.thirdVN = 0;
363   e.function = 0;
364   e.type = E->getType();
365   e.opcode = Expression::EXTRACT;
366   
367   return e;
368 }
369
370 Expression ValueTable::create_expression(InsertElementInst* I) {
371   Expression e;
372     
373   e.firstVN = lookup_or_add(I->getOperand(0));
374   e.secondVN = lookup_or_add(I->getOperand(1));
375   e.thirdVN = lookup_or_add(I->getOperand(2));
376   e.function = 0;
377   e.type = I->getType();
378   e.opcode = Expression::INSERT;
379   
380   return e;
381 }
382
383 Expression ValueTable::create_expression(SelectInst* I) {
384   Expression e;
385     
386   e.firstVN = lookup_or_add(I->getCondition());
387   e.secondVN = lookup_or_add(I->getTrueValue());
388   e.thirdVN = lookup_or_add(I->getFalseValue());
389   e.function = 0;
390   e.type = I->getType();
391   e.opcode = Expression::SELECT;
392   
393   return e;
394 }
395
396 Expression ValueTable::create_expression(GetElementPtrInst* G) {
397   Expression e;
398   
399   e.firstVN = lookup_or_add(G->getPointerOperand());
400   e.secondVN = 0;
401   e.thirdVN = 0;
402   e.function = 0;
403   e.type = G->getType();
404   e.opcode = Expression::GEP;
405   
406   for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
407        I != E; ++I)
408     e.varargs.push_back(lookup_or_add(*I));
409   
410   return e;
411 }
412
413 //===----------------------------------------------------------------------===//
414 //                     ValueTable External Functions
415 //===----------------------------------------------------------------------===//
416
417 /// add - Insert a value into the table with a specified value number.
418 void ValueTable::add(Value* V, uint32_t num) {
419   valueNumbering.insert(std::make_pair(V, num));
420 }
421
422 /// lookup_or_add - Returns the value number for the specified value, assigning
423 /// it a new number if it did not have one before.
424 uint32_t ValueTable::lookup_or_add(Value* V) {
425   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
426   if (VI != valueNumbering.end())
427     return VI->second;
428   
429   if (CallInst* C = dyn_cast<CallInst>(V)) {
430     if (AA->doesNotAccessMemory(C)) {
431       Expression e = create_expression(C);
432     
433       DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
434       if (EI != expressionNumbering.end()) {
435         valueNumbering.insert(std::make_pair(V, EI->second));
436         return EI->second;
437       } else {
438         expressionNumbering.insert(std::make_pair(e, nextValueNumber));
439         valueNumbering.insert(std::make_pair(V, nextValueNumber));
440       
441         return nextValueNumber++;
442       }
443     } else if (AA->onlyReadsMemory(C)) {
444       Expression e = create_expression(C);
445       
446       if (expressionNumbering.find(e) == expressionNumbering.end()) {
447         expressionNumbering.insert(std::make_pair(e, nextValueNumber));
448         valueNumbering.insert(std::make_pair(V, nextValueNumber));
449         return nextValueNumber++;
450       }
451       
452       Instruction* local_dep = MD->getDependency(C);
453       
454       if (local_dep == MemoryDependenceAnalysis::None) {
455         valueNumbering.insert(std::make_pair(V, nextValueNumber));
456         return nextValueNumber++;
457       } else if (local_dep != MemoryDependenceAnalysis::NonLocal) {
458         if (!isa<CallInst>(local_dep)) {
459           valueNumbering.insert(std::make_pair(V, nextValueNumber));
460           return nextValueNumber++;
461         }
462         
463         CallInst* local_cdep = cast<CallInst>(local_dep);
464         
465         if (local_cdep->getCalledFunction() != C->getCalledFunction() ||
466             local_cdep->getNumOperands() != C->getNumOperands()) {
467           valueNumbering.insert(std::make_pair(V, nextValueNumber));
468           return nextValueNumber++;
469         } else if (!C->getCalledFunction()) { 
470           valueNumbering.insert(std::make_pair(V, nextValueNumber));
471           return nextValueNumber++;
472         } else {
473           for (unsigned i = 1; i < C->getNumOperands(); ++i) {
474             uint32_t c_vn = lookup_or_add(C->getOperand(i));
475             uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
476             if (c_vn != cd_vn) {
477               valueNumbering.insert(std::make_pair(V, nextValueNumber));
478               return nextValueNumber++;
479             }
480           }
481         
482           uint32_t v = lookup_or_add(local_cdep);
483           valueNumbering.insert(std::make_pair(V, v));
484           return v;
485         }
486       }
487       
488       
489       DenseMap<BasicBlock*, Value*> deps;
490       MD->getNonLocalDependency(C, deps);
491       CallInst* cdep = 0;
492       
493       for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(),
494            E = deps.end(); I != E; ++I) {
495         if (I->second == MemoryDependenceAnalysis::None) {
496           valueNumbering.insert(std::make_pair(V, nextValueNumber));
497
498           return nextValueNumber++;
499         } else if (I->second != MemoryDependenceAnalysis::NonLocal) {
500           if (DT->properlyDominates(I->first, C->getParent())) {
501             if (CallInst* CD = dyn_cast<CallInst>(I->second))
502               cdep = CD;
503             else {
504               valueNumbering.insert(std::make_pair(V, nextValueNumber));
505               return nextValueNumber++;
506             }
507           } else {
508             valueNumbering.insert(std::make_pair(V, nextValueNumber));
509             return nextValueNumber++;
510           }
511         }
512       }
513       
514       if (!cdep) {
515         valueNumbering.insert(std::make_pair(V, nextValueNumber));
516         return nextValueNumber++;
517       }
518       
519       if (cdep->getCalledFunction() != C->getCalledFunction() ||
520           cdep->getNumOperands() != C->getNumOperands()) {
521         valueNumbering.insert(std::make_pair(V, nextValueNumber));
522         return nextValueNumber++;
523       } else if (!C->getCalledFunction()) { 
524         valueNumbering.insert(std::make_pair(V, nextValueNumber));
525         return nextValueNumber++;
526       } else {
527         for (unsigned i = 1; i < C->getNumOperands(); ++i) {
528           uint32_t c_vn = lookup_or_add(C->getOperand(i));
529           uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
530           if (c_vn != cd_vn) {
531             valueNumbering.insert(std::make_pair(V, nextValueNumber));
532             return nextValueNumber++;
533           }
534         }
535         
536         uint32_t v = lookup_or_add(cdep);
537         valueNumbering.insert(std::make_pair(V, v));
538         return v;
539       }
540       
541     } else {
542       valueNumbering.insert(std::make_pair(V, nextValueNumber));
543       return nextValueNumber++;
544     }
545   } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
546     Expression e = create_expression(BO);
547     
548     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
549     if (EI != expressionNumbering.end()) {
550       valueNumbering.insert(std::make_pair(V, EI->second));
551       return EI->second;
552     } else {
553       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
554       valueNumbering.insert(std::make_pair(V, nextValueNumber));
555       
556       return nextValueNumber++;
557     }
558   } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
559     Expression e = create_expression(C);
560     
561     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
562     if (EI != expressionNumbering.end()) {
563       valueNumbering.insert(std::make_pair(V, EI->second));
564       return EI->second;
565     } else {
566       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
567       valueNumbering.insert(std::make_pair(V, nextValueNumber));
568       
569       return nextValueNumber++;
570     }
571   } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
572     Expression e = create_expression(U);
573     
574     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
575     if (EI != expressionNumbering.end()) {
576       valueNumbering.insert(std::make_pair(V, EI->second));
577       return EI->second;
578     } else {
579       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
580       valueNumbering.insert(std::make_pair(V, nextValueNumber));
581       
582       return nextValueNumber++;
583     }
584   } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
585     Expression e = create_expression(U);
586     
587     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
588     if (EI != expressionNumbering.end()) {
589       valueNumbering.insert(std::make_pair(V, EI->second));
590       return EI->second;
591     } else {
592       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
593       valueNumbering.insert(std::make_pair(V, nextValueNumber));
594       
595       return nextValueNumber++;
596     }
597   } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
598     Expression e = create_expression(U);
599     
600     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
601     if (EI != expressionNumbering.end()) {
602       valueNumbering.insert(std::make_pair(V, EI->second));
603       return EI->second;
604     } else {
605       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
606       valueNumbering.insert(std::make_pair(V, nextValueNumber));
607       
608       return nextValueNumber++;
609     }
610   } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
611     Expression e = create_expression(U);
612     
613     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
614     if (EI != expressionNumbering.end()) {
615       valueNumbering.insert(std::make_pair(V, EI->second));
616       return EI->second;
617     } else {
618       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
619       valueNumbering.insert(std::make_pair(V, nextValueNumber));
620       
621       return nextValueNumber++;
622     }
623   } else if (CastInst* U = dyn_cast<CastInst>(V)) {
624     Expression e = create_expression(U);
625     
626     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
627     if (EI != expressionNumbering.end()) {
628       valueNumbering.insert(std::make_pair(V, EI->second));
629       return EI->second;
630     } else {
631       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
632       valueNumbering.insert(std::make_pair(V, nextValueNumber));
633       
634       return nextValueNumber++;
635     }
636   } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
637     Expression e = create_expression(U);
638     
639     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
640     if (EI != expressionNumbering.end()) {
641       valueNumbering.insert(std::make_pair(V, EI->second));
642       return EI->second;
643     } else {
644       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
645       valueNumbering.insert(std::make_pair(V, nextValueNumber));
646       
647       return nextValueNumber++;
648     }
649   } else {
650     valueNumbering.insert(std::make_pair(V, nextValueNumber));
651     return nextValueNumber++;
652   }
653 }
654
655 /// lookup - Returns the value number of the specified value. Fails if
656 /// the value has not yet been numbered.
657 uint32_t ValueTable::lookup(Value* V) const {
658   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
659   assert(VI != valueNumbering.end() && "Value not numbered?");
660   return VI->second;
661 }
662
663 /// clear - Remove all entries from the ValueTable
664 void ValueTable::clear() {
665   valueNumbering.clear();
666   expressionNumbering.clear();
667   nextValueNumber = 1;
668 }
669
670 /// erase - Remove a value from the value numbering
671 void ValueTable::erase(Value* V) {
672   valueNumbering.erase(V);
673 }
674
675 //===----------------------------------------------------------------------===//
676 //                         GVN Pass
677 //===----------------------------------------------------------------------===//
678
679 namespace llvm {
680   template<> struct DenseMapInfo<uint32_t> {
681     static inline uint32_t getEmptyKey() { return ~0; }
682     static inline uint32_t getTombstoneKey() { return ~0 - 1; }
683     static unsigned getHashValue(const uint32_t& Val) { return Val * 37; }
684     static bool isPod() { return true; }
685     static bool isEqual(const uint32_t& LHS, const uint32_t& RHS) {
686       return LHS == RHS;
687     }
688   };
689 }
690
691 namespace {
692
693   class VISIBILITY_HIDDEN GVN : public FunctionPass {
694     bool runOnFunction(Function &F);
695   public:
696     static char ID; // Pass identification, replacement for typeid
697     GVN() : FunctionPass((intptr_t)&ID) { }
698
699   private:
700     ValueTable VN;
701     DenseMap<BasicBlock*, DenseMap<uint32_t, Value*> > localAvail;
702     
703     typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
704     PhiMapType phiMap;
705     
706     
707     // This transformation requires dominator postdominator info
708     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
709       AU.setPreservesCFG();
710       AU.addRequired<DominatorTree>();
711       AU.addRequired<MemoryDependenceAnalysis>();
712       AU.addRequired<AliasAnalysis>();
713       AU.addPreserved<AliasAnalysis>();
714       AU.addPreserved<MemoryDependenceAnalysis>();
715     }
716   
717     // Helper fuctions
718     // FIXME: eliminate or document these better
719     bool processLoad(LoadInst* L,
720                      DenseMap<Value*, LoadInst*> &lastLoad,
721                      SmallVectorImpl<Instruction*> &toErase);
722     bool processInstruction(Instruction* I,
723                             DenseMap<Value*, LoadInst*>& lastSeenLoad,
724                             SmallVectorImpl<Instruction*> &toErase);
725     bool processNonLocalLoad(LoadInst* L,
726                              SmallVectorImpl<Instruction*> &toErase);
727     bool processBlock(DomTreeNode* DTN);
728     Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
729                             DenseMap<BasicBlock*, Value*> &Phis,
730                             bool top_level = false);
731     void dump(DenseMap<uint32_t, Value*>& d);
732     bool iterateOnFunction(Function &F);
733     Value* CollapsePhi(PHINode* p);
734     bool isSafeReplacement(PHINode* p, Instruction* inst);
735     bool performPRE(Function& F);
736   };
737   
738   char GVN::ID = 0;
739 }
740
741 // createGVNPass - The public interface to this file...
742 FunctionPass *llvm::createGVNPass() { return new GVN(); }
743
744 static RegisterPass<GVN> X("gvn",
745                            "Global Value Numbering");
746
747 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
748   printf("{\n");
749   for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
750        E = d.end(); I != E; ++I) {
751       printf("%d\n", I->first);
752       I->second->dump();
753   }
754   printf("}\n");
755 }
756
757 Value* GVN::CollapsePhi(PHINode* p) {
758   DominatorTree &DT = getAnalysis<DominatorTree>();
759   Value* constVal = p->hasConstantValue();
760   
761   if (!constVal) return 0;
762   
763   Instruction* inst = dyn_cast<Instruction>(constVal);
764   if (!inst)
765     return constVal;
766     
767   if (DT.dominates(inst, p))
768     if (isSafeReplacement(p, inst))
769       return inst;
770   return 0;
771 }
772
773 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
774   if (!isa<PHINode>(inst))
775     return true;
776   
777   for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
778        UI != E; ++UI)
779     if (PHINode* use_phi = dyn_cast<PHINode>(UI))
780       if (use_phi->getParent() == inst->getParent())
781         return false;
782   
783   return true;
784 }
785
786 /// GetValueForBlock - Get the value to use within the specified basic block.
787 /// available values are in Phis.
788 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
789                              DenseMap<BasicBlock*, Value*> &Phis,
790                              bool top_level) { 
791                                  
792   // If we have already computed this value, return the previously computed val.
793   DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
794   if (V != Phis.end() && !top_level) return V->second;
795   
796   BasicBlock* singlePred = BB->getSinglePredecessor();
797   if (singlePred) {
798     Value *ret = GetValueForBlock(singlePred, orig, Phis);
799     Phis[BB] = ret;
800     return ret;
801   }
802   
803   // Otherwise, the idom is the loop, so we need to insert a PHI node.  Do so
804   // now, then get values to fill in the incoming values for the PHI.
805   PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
806                                 BB->begin());
807   PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
808   
809   if (Phis.count(BB) == 0)
810     Phis.insert(std::make_pair(BB, PN));
811   
812   // Fill in the incoming values for the block.
813   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
814     Value* val = GetValueForBlock(*PI, orig, Phis);
815     PN->addIncoming(val, *PI);
816   }
817   
818   AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
819   AA.copyValue(orig, PN);
820   
821   // Attempt to collapse PHI nodes that are trivially redundant
822   Value* v = CollapsePhi(PN);
823   if (!v) {
824     // Cache our phi construction results
825     phiMap[orig->getPointerOperand()].insert(PN);
826     return PN;
827   }
828     
829   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
830
831   MD.removeInstruction(PN);
832   PN->replaceAllUsesWith(v);
833
834   for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
835        E = Phis.end(); I != E; ++I)
836     if (I->second == PN)
837       I->second = v;
838
839   PN->eraseFromParent();
840
841   Phis[BB] = v;
842   return v;
843 }
844
845 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
846 /// non-local by performing PHI construction.
847 bool GVN::processNonLocalLoad(LoadInst* L,
848                               SmallVectorImpl<Instruction*> &toErase) {
849   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
850   
851   // Find the non-local dependencies of the load
852   DenseMap<BasicBlock*, Value*> deps;
853   MD.getNonLocalDependency(L, deps);
854   
855   DenseMap<BasicBlock*, Value*> repl;
856   
857   // Filter out useless results (non-locals, etc)
858   for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
859        I != E; ++I) {
860     if (I->second == MemoryDependenceAnalysis::None)
861       return false;
862   
863     if (I->second == MemoryDependenceAnalysis::NonLocal)
864       continue;
865   
866     if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
867       if (S->getPointerOperand() != L->getPointerOperand())
868         return false;
869       repl[I->first] = S->getOperand(0);
870     } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
871       if (LD->getPointerOperand() != L->getPointerOperand())
872         return false;
873       repl[I->first] = LD;
874     } else {
875       return false;
876     }
877   }
878   
879   // Use cached PHI construction information from previous runs
880   SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
881   for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
882        I != E; ++I) {
883     if ((*I)->getParent() == L->getParent()) {
884       MD.removeInstruction(L);
885       L->replaceAllUsesWith(*I);
886       toErase.push_back(L);
887       NumGVNLoad++;
888       return true;
889     }
890     
891     repl.insert(std::make_pair((*I)->getParent(), *I));
892   }
893   
894   // Perform PHI construction
895   SmallPtrSet<BasicBlock*, 4> visited;
896   Value* v = GetValueForBlock(L->getParent(), L, repl, true);
897   
898   MD.removeInstruction(L);
899   L->replaceAllUsesWith(v);
900   toErase.push_back(L);
901   NumGVNLoad++;
902
903   return true;
904 }
905
906 /// processLoad - Attempt to eliminate a load, first by eliminating it
907 /// locally, and then attempting non-local elimination if that fails.
908 bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
909                       SmallVectorImpl<Instruction*> &toErase) {
910   if (L->isVolatile()) {
911     lastLoad[L->getPointerOperand()] = L;
912     return false;
913   }
914   
915   Value* pointer = L->getPointerOperand();
916   LoadInst*& last = lastLoad[pointer];
917   
918   // ... to a pointer that has been loaded from before...
919   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
920   bool removedNonLocal = false;
921   Instruction* dep = MD.getDependency(L);
922   if (dep == MemoryDependenceAnalysis::NonLocal &&
923       L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
924     removedNonLocal = processNonLocalLoad(L, toErase);
925     
926     if (!removedNonLocal)
927       last = L;
928     
929     return removedNonLocal;
930   }
931   
932   
933   bool deletedLoad = false;
934   
935   // Walk up the dependency chain until we either find
936   // a dependency we can use, or we can't walk any further
937   while (dep != MemoryDependenceAnalysis::None &&
938          dep != MemoryDependenceAnalysis::NonLocal &&
939          (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
940     // ... that depends on a store ...
941     if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
942       if (S->getPointerOperand() == pointer) {
943         // Remove it!
944         MD.removeInstruction(L);
945         
946         L->replaceAllUsesWith(S->getOperand(0));
947         toErase.push_back(L);
948         deletedLoad = true;
949         NumGVNLoad++;
950       }
951       
952       // Whether we removed it or not, we can't
953       // go any further
954       break;
955     } else if (!last) {
956       // If we don't depend on a store, and we haven't
957       // been loaded before, bail.
958       break;
959     } else if (dep == last) {
960       // Remove it!
961       MD.removeInstruction(L);
962       
963       L->replaceAllUsesWith(last);
964       toErase.push_back(L);
965       deletedLoad = true;
966       NumGVNLoad++;
967         
968       break;
969     } else {
970       dep = MD.getDependency(L, dep);
971     }
972   }
973
974   if (dep != MemoryDependenceAnalysis::None &&
975       dep != MemoryDependenceAnalysis::NonLocal &&
976       isa<AllocationInst>(dep)) {
977     // Check that this load is actually from the
978     // allocation we found
979     Value* v = L->getOperand(0);
980     while (true) {
981       if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
982         v = BC->getOperand(0);
983       else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
984         v = GEP->getOperand(0);
985       else
986         break;
987     }
988     if (v == dep) {
989       // If this load depends directly on an allocation, there isn't
990       // anything stored there; therefore, we can optimize this load
991       // to undef.
992       MD.removeInstruction(L);
993
994       L->replaceAllUsesWith(UndefValue::get(L->getType()));
995       toErase.push_back(L);
996       deletedLoad = true;
997       NumGVNLoad++;
998     }
999   }
1000
1001   if (!deletedLoad)
1002     last = L;
1003   
1004   return deletedLoad;
1005 }
1006
1007 /// processInstruction - When calculating availability, handle an instruction
1008 /// by inserting it into the appropriate sets
1009 bool GVN::processInstruction(Instruction *I,
1010                              DenseMap<Value*, LoadInst*> &lastSeenLoad,
1011                              SmallVectorImpl<Instruction*> &toErase) {
1012   if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1013     bool changed = processLoad(L, lastSeenLoad, toErase);
1014     
1015     if (!changed) {
1016       unsigned num = VN.lookup_or_add(L);
1017       localAvail[I->getParent()].insert(std::make_pair(num, L));
1018     }
1019     
1020     return changed;
1021   }
1022   
1023   unsigned num = VN.lookup_or_add(I);
1024   
1025   // Allocations are always uniquely numbered, so we can save time and memory
1026   // by fast failing them.
1027   if (isa<AllocationInst>(I)) {
1028     localAvail[I->getParent()].insert(std::make_pair(num, I));
1029     return false;
1030   }
1031   
1032   // Collapse PHI nodes
1033   if (PHINode* p = dyn_cast<PHINode>(I)) {
1034     Value* constVal = CollapsePhi(p);
1035     
1036     if (constVal) {
1037       for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1038            PI != PE; ++PI)
1039         if (PI->second.count(p))
1040           PI->second.erase(p);
1041         
1042       p->replaceAllUsesWith(constVal);
1043       toErase.push_back(p);
1044     } else {
1045       localAvail[I->getParent()].insert(std::make_pair(num, I));
1046     }
1047   // Perform value-number based elimination
1048   } else if (localAvail[I->getParent()].count(num)) {
1049     Value* repl = localAvail[I->getParent()][num];
1050     
1051     // Remove it!
1052     MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1053     MD.removeInstruction(I);
1054     
1055     VN.erase(I);
1056     I->replaceAllUsesWith(repl);
1057     toErase.push_back(I);
1058     return true;
1059   } else if (!I->isTerminator()) {
1060     localAvail[I->getParent()].insert(std::make_pair(num, I));
1061   }
1062   
1063   return false;
1064 }
1065
1066 // GVN::runOnFunction - This is the main transformation entry point for a
1067 // function.
1068 //
1069 bool GVN::runOnFunction(Function& F) {
1070   VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1071   VN.setMemDep(&getAnalysis<MemoryDependenceAnalysis>());
1072   VN.setDomTree(&getAnalysis<DominatorTree>());
1073   
1074   bool changed = false;
1075   bool shouldContinue = true;
1076   
1077   while (shouldContinue) {
1078     shouldContinue = iterateOnFunction(F);
1079     changed |= shouldContinue;
1080   }
1081   
1082   return changed;
1083 }
1084
1085
1086 bool GVN::processBlock(DomTreeNode* DTN) {
1087   BasicBlock* BB = DTN->getBlock();
1088
1089   SmallVector<Instruction*, 8> toErase;
1090   DenseMap<Value*, LoadInst*> lastSeenLoad;
1091   bool changed_function = false;
1092   
1093   if (DTN->getIDom())
1094     localAvail.insert(std::make_pair(BB,
1095                       localAvail[DTN->getIDom()->getBlock()]));
1096   
1097   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1098        BI != BE;) {
1099     changed_function |= processInstruction(BI, lastSeenLoad, toErase);
1100     if (toErase.empty()) {
1101       ++BI;
1102       continue;
1103     }
1104     
1105     // If we need some instructions deleted, do it now.
1106     NumGVNInstr += toErase.size();
1107     
1108     // Avoid iterator invalidation.
1109     bool AtStart = BI == BB->begin();
1110     if (!AtStart)
1111       --BI;
1112
1113     for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1114          E = toErase.end(); I != E; ++I)
1115       (*I)->eraseFromParent();
1116
1117     if (AtStart)
1118       BI = BB->begin();
1119     else
1120       ++BI;
1121     
1122     toErase.clear();
1123   }
1124   
1125   return changed_function;
1126 }
1127
1128 /// performPRE - Perform a purely local form of PRE that looks for diamond
1129 /// control flow patterns and attempts to perform simple PRE at the join point.
1130 bool GVN::performPRE(Function& F) {
1131   bool changed = false;
1132   SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
1133   for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1134        DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
1135     BasicBlock* CurrentBlock = *DI;
1136     
1137     // Nothing to PRE in the entry block.
1138     if (CurrentBlock == &F.getEntryBlock()) continue;
1139     
1140     for (BasicBlock::iterator BI = CurrentBlock->begin(),
1141          BE = CurrentBlock->end(); BI != BE; ) {
1142       if (isa<AllocaInst>(BI) || isa<TerminatorInst>(BI) ||
1143           isa<LoadInst>(BI) || isa<StoreInst>(BI) ||
1144           isa<CallInst>(BI) || isa<PHINode>(BI)) {
1145         BI++;
1146         continue;
1147       }
1148       
1149       uint32_t valno = VN.lookup(BI);
1150       
1151       // Look for the predecessors for PRE opportunities.  We're
1152       // only trying to solve the basic diamond case, where
1153       // a value is computed in the successor and one predecessor,
1154       // but not the other.  We also explicitly disallow cases
1155       // where the successor is its own predecessor, because they're
1156       // more complicated to get right.
1157       unsigned numWith = 0;
1158       unsigned numWithout = 0;
1159       BasicBlock* PREPred = 0;
1160       for (pred_iterator PI = pred_begin(CurrentBlock),
1161            PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1162         // We're not interested in PRE where the block is its
1163         // own predecessor.
1164         if (*PI == CurrentBlock)
1165           numWithout = 2;
1166           
1167         if (!localAvail[*PI].count(valno)) {
1168           PREPred = *PI;
1169           numWithout++;
1170         } else if (localAvail[*PI][valno] == BI) {
1171           numWithout = 2;
1172         } else {
1173           numWith++;
1174         }
1175       }
1176       
1177       // Don't do PRE when it might increase code size, i.e. when
1178       // we would need to insert instructions in more than one pred.
1179       if (numWithout != 1 || numWith == 0) {
1180         BI++;
1181         continue;
1182       }
1183       
1184       // We can't do PRE safely on a critical edge, so instead we schedule
1185       // the edge to be split and perform the PRE the next time we iterate
1186       // on the function.
1187       unsigned succNum = 0;
1188       for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1189            i != e; ++i)
1190         if (PREPred->getTerminator()->getSuccessor(i) == PREPred) {
1191           succNum = i;
1192           break;
1193         }
1194         
1195       if (isCriticalEdge(PREPred->getTerminator(), succNum)) {
1196         toSplit.push_back(std::make_pair(PREPred->getTerminator(), succNum));
1197         changed = true;
1198         BI++;
1199         continue;
1200       }
1201       
1202       // Instantiate the expression the in predecessor that lacked it.
1203       // Because we are going top-down through the block, all value numbers
1204       // will be available in the predecessor by the time we need them.  Any
1205       // that weren't original present will have been instantiated earlier
1206       // in this loop.
1207       Instruction* PREInstr = BI->clone();
1208       bool success = true;
1209       for (unsigned i = 0; i < BI->getNumOperands(); ++i) {
1210         Value* op = BI->getOperand(i);
1211         if (isa<Argument>(op) || isa<Constant>(op) || isa<GlobalValue>(op))
1212           PREInstr->setOperand(i, op);
1213         else if (!localAvail[PREPred].count(VN.lookup(op))) {
1214           success = false;
1215           break;
1216         } else
1217           PREInstr->setOperand(i, localAvail[PREPred][VN.lookup(op)]);
1218       }
1219       
1220       // Fail out if we encounter an operand that is not available in
1221       // the PRE predecessor.  This is typically because of loads which 
1222       // are not value numbered precisely.
1223       if (!success) {
1224         delete PREInstr;
1225         BI++;
1226         continue;
1227       }
1228       
1229       PREInstr->insertBefore(PREPred->getTerminator());
1230       PREInstr->setName(BI->getName() + ".pre");
1231       VN.add(PREInstr, valno);
1232       NumGVNPRE++;
1233       
1234       // Update the availability map to include the new instruction.
1235       localAvail[PREPred].insert(std::make_pair(valno, PREInstr));
1236       
1237       // Create a PHI to make the value available in this block.
1238       PHINode* Phi = PHINode::Create(BI->getType(),
1239                                      BI->getName() + ".pre-phi",
1240                                      CurrentBlock->begin());
1241       for (pred_iterator PI = pred_begin(CurrentBlock),
1242            PE = pred_end(CurrentBlock); PI != PE; ++PI)
1243         Phi->addIncoming(localAvail[*PI][valno], *PI);
1244       
1245       VN.add(Phi, valno);
1246       
1247       // The newly created PHI completely replaces the old instruction,
1248       // so we need to update the maps to reflect this.
1249       for (DenseMap<BasicBlock*, DenseMap<uint32_t, Value*> >::iterator
1250            UI = localAvail.begin(), UE = localAvail.end(); UI != UE; ++UI)
1251         for (DenseMap<uint32_t, Value*>::iterator UUI = UI->second.begin(),
1252              UUE = UI->second.end(); UUI != UUE; ++UUI)
1253             if (UUI->second == BI)
1254               UUI->second = Phi;
1255       
1256       BI->replaceAllUsesWith(Phi);
1257       VN.erase(BI);
1258       
1259       Instruction* erase = BI;
1260       BI++;
1261       erase->eraseFromParent();
1262       
1263       changed = true;
1264     }
1265   }
1266   
1267   for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
1268        I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
1269     SplitCriticalEdge(I->first, I->second, this);
1270   
1271   return changed;
1272 }
1273
1274 // GVN::iterateOnFunction - Executes one iteration of GVN
1275 bool GVN::iterateOnFunction(Function &F) {
1276   // Clean out global sets from any previous functions
1277   VN.clear();
1278   localAvail.clear();
1279   phiMap.clear();
1280   
1281   DominatorTree &DT = getAnalysis<DominatorTree>();   
1282
1283   // Top-down walk of the dominator tree
1284   bool changed = false;
1285   for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1286        DE = df_end(DT.getRootNode()); DI != DE; ++DI)
1287     changed |= processBlock(*DI);
1288     
1289   changed |= performPRE(F);
1290   return changed;
1291 }