Clean up the use of static and anonymous namespaces. This turned up
[oota-llvm.git] / lib / Transforms / Scalar / GVNPRE.cpp
1 //===- GVNPRE.cpp - Eliminate redundant values and expressions ------------===//
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 a hybrid of global value numbering and partial redundancy
11 // elimination, known as GVN-PRE.  It performs partial redundancy elimination on
12 // values, rather than lexical expressions, allowing a more comprehensive view 
13 // the optimization.  It replaces redundant values with uses of earlier 
14 // occurences of the same value.  While this is beneficial in that it eliminates
15 // unneeded computation, it also increases register pressure by creating large
16 // live ranges, and should be used with caution on platforms that are very 
17 // sensitive to register pressure.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #define DEBUG_TYPE "gvnpre"
22 #include "llvm/Value.h"
23 #include "llvm/Transforms/Scalar.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Function.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/Analysis/Dominators.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/DepthFirstIterator.h"
31 #include "llvm/ADT/PostOrderIterator.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
36 #include "llvm/Support/CFG.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/Debug.h"
39 #include <algorithm>
40 #include <deque>
41 #include <map>
42 using namespace llvm;
43
44 //===----------------------------------------------------------------------===//
45 //                         ValueTable Class
46 //===----------------------------------------------------------------------===//
47
48 namespace {
49
50 /// This class holds the mapping between values and value numbers.  It is used
51 /// as an efficient mechanism to determine the expression-wise equivalence of
52 /// two values.
53
54 struct Expression {
55   enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM, 
56                           FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ, 
57                           ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE, 
58                           ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ, 
59                           FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE, 
60                           FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE, 
61                           FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
62                           SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
63                           FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT, 
64                           PTRTOINT, INTTOPTR, BITCAST, GEP, EMPTY,
65                           TOMBSTONE };
66
67   ExpressionOpcode opcode;
68   const Type* type;
69   uint32_t firstVN;
70   uint32_t secondVN;
71   uint32_t thirdVN;
72   SmallVector<uint32_t, 4> varargs;
73   
74   Expression() { }
75   explicit Expression(ExpressionOpcode o) : opcode(o) { }
76   
77   bool operator==(const Expression &other) const {
78     if (opcode != other.opcode)
79       return false;
80     else if (opcode == EMPTY || opcode == TOMBSTONE)
81       return true;
82     else if (type != other.type)
83       return false;
84     else if (firstVN != other.firstVN)
85       return false;
86     else if (secondVN != other.secondVN)
87       return false;
88     else if (thirdVN != other.thirdVN)
89       return false;
90     else {
91       if (varargs.size() != other.varargs.size())
92         return false;
93       
94       for (size_t i = 0; i < varargs.size(); ++i)
95         if (varargs[i] != other.varargs[i])
96           return false;
97     
98       return true;
99     }
100   }
101   
102   bool operator!=(const Expression &other) const {
103     if (opcode != other.opcode)
104       return true;
105     else if (opcode == EMPTY || opcode == TOMBSTONE)
106       return false;
107     else if (type != other.type)
108       return true;
109     else if (firstVN != other.firstVN)
110       return true;
111     else if (secondVN != other.secondVN)
112       return true;
113     else if (thirdVN != other.thirdVN)
114       return true;
115     else {
116       if (varargs.size() != other.varargs.size())
117         return true;
118       
119       for (size_t i = 0; i < varargs.size(); ++i)
120         if (varargs[i] != other.varargs[i])
121           return true;
122     
123       return false;
124     }
125   }
126 };
127
128 }
129
130 namespace {
131   class VISIBILITY_HIDDEN ValueTable {
132     private:
133       DenseMap<Value*, uint32_t> valueNumbering;
134       DenseMap<Expression, uint32_t> expressionNumbering;
135   
136       uint32_t nextValueNumber;
137     
138       Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
139       Expression::ExpressionOpcode getOpcode(CmpInst* C);
140       Expression::ExpressionOpcode getOpcode(CastInst* C);
141       Expression create_expression(BinaryOperator* BO);
142       Expression create_expression(CmpInst* C);
143       Expression create_expression(ShuffleVectorInst* V);
144       Expression create_expression(ExtractElementInst* C);
145       Expression create_expression(InsertElementInst* V);
146       Expression create_expression(SelectInst* V);
147       Expression create_expression(CastInst* C);
148       Expression create_expression(GetElementPtrInst* G);
149     public:
150       ValueTable() { nextValueNumber = 1; }
151       uint32_t lookup_or_add(Value* V);
152       uint32_t lookup(Value* V) const;
153       void add(Value* V, uint32_t num);
154       void clear();
155       void erase(Value* v);
156       unsigned size();
157   };
158 }
159
160 namespace llvm {
161 template <> struct DenseMapInfo<Expression> {
162   static inline Expression getEmptyKey() {
163     return Expression(Expression::EMPTY);
164   }
165   
166   static inline Expression getTombstoneKey() {
167     return Expression(Expression::TOMBSTONE);
168   }
169   
170   static unsigned getHashValue(const Expression e) {
171     unsigned hash = e.opcode;
172     
173     hash = e.firstVN + hash * 37;
174     hash = e.secondVN + hash * 37;
175     hash = e.thirdVN + hash * 37;
176     
177     hash = ((unsigned)((uintptr_t)e.type >> 4) ^
178             (unsigned)((uintptr_t)e.type >> 9)) +
179            hash * 37;
180     
181     for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
182          E = e.varargs.end(); I != E; ++I)
183       hash = *I + hash * 37;
184     
185     return hash;
186   }
187   static bool isEqual(const Expression &LHS, const Expression &RHS) {
188     return LHS == RHS;
189   }
190   static bool isPod() { return true; }
191 };
192 }
193
194 //===----------------------------------------------------------------------===//
195 //                     ValueTable Internal Functions
196 //===----------------------------------------------------------------------===//
197 Expression::ExpressionOpcode 
198                              ValueTable::getOpcode(BinaryOperator* BO) {
199   switch(BO->getOpcode()) {
200     case Instruction::Add:
201       return Expression::ADD;
202     case Instruction::Sub:
203       return Expression::SUB;
204     case Instruction::Mul:
205       return Expression::MUL;
206     case Instruction::UDiv:
207       return Expression::UDIV;
208     case Instruction::SDiv:
209       return Expression::SDIV;
210     case Instruction::FDiv:
211       return Expression::FDIV;
212     case Instruction::URem:
213       return Expression::UREM;
214     case Instruction::SRem:
215       return Expression::SREM;
216     case Instruction::FRem:
217       return Expression::FREM;
218     case Instruction::Shl:
219       return Expression::SHL;
220     case Instruction::LShr:
221       return Expression::LSHR;
222     case Instruction::AShr:
223       return Expression::ASHR;
224     case Instruction::And:
225       return Expression::AND;
226     case Instruction::Or:
227       return Expression::OR;
228     case Instruction::Xor:
229       return Expression::XOR;
230     
231     // THIS SHOULD NEVER HAPPEN
232     default:
233       assert(0 && "Binary operator with unknown opcode?");
234       return Expression::ADD;
235   }
236 }
237
238 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
239   if (C->getOpcode() == Instruction::ICmp) {
240     switch (C->getPredicate()) {
241       case ICmpInst::ICMP_EQ:
242         return Expression::ICMPEQ;
243       case ICmpInst::ICMP_NE:
244         return Expression::ICMPNE;
245       case ICmpInst::ICMP_UGT:
246         return Expression::ICMPUGT;
247       case ICmpInst::ICMP_UGE:
248         return Expression::ICMPUGE;
249       case ICmpInst::ICMP_ULT:
250         return Expression::ICMPULT;
251       case ICmpInst::ICMP_ULE:
252         return Expression::ICMPULE;
253       case ICmpInst::ICMP_SGT:
254         return Expression::ICMPSGT;
255       case ICmpInst::ICMP_SGE:
256         return Expression::ICMPSGE;
257       case ICmpInst::ICMP_SLT:
258         return Expression::ICMPSLT;
259       case ICmpInst::ICMP_SLE:
260         return Expression::ICMPSLE;
261       
262       // THIS SHOULD NEVER HAPPEN
263       default:
264         assert(0 && "Comparison with unknown predicate?");
265         return Expression::ICMPEQ;
266     }
267   } else {
268     switch (C->getPredicate()) {
269       case FCmpInst::FCMP_OEQ:
270         return Expression::FCMPOEQ;
271       case FCmpInst::FCMP_OGT:
272         return Expression::FCMPOGT;
273       case FCmpInst::FCMP_OGE:
274         return Expression::FCMPOGE;
275       case FCmpInst::FCMP_OLT:
276         return Expression::FCMPOLT;
277       case FCmpInst::FCMP_OLE:
278         return Expression::FCMPOLE;
279       case FCmpInst::FCMP_ONE:
280         return Expression::FCMPONE;
281       case FCmpInst::FCMP_ORD:
282         return Expression::FCMPORD;
283       case FCmpInst::FCMP_UNO:
284         return Expression::FCMPUNO;
285       case FCmpInst::FCMP_UEQ:
286         return Expression::FCMPUEQ;
287       case FCmpInst::FCMP_UGT:
288         return Expression::FCMPUGT;
289       case FCmpInst::FCMP_UGE:
290         return Expression::FCMPUGE;
291       case FCmpInst::FCMP_ULT:
292         return Expression::FCMPULT;
293       case FCmpInst::FCMP_ULE:
294         return Expression::FCMPULE;
295       case FCmpInst::FCMP_UNE:
296         return Expression::FCMPUNE;
297       
298       // THIS SHOULD NEVER HAPPEN
299       default:
300         assert(0 && "Comparison with unknown predicate?");
301         return Expression::FCMPOEQ;
302     }
303   }
304 }
305
306 Expression::ExpressionOpcode 
307                              ValueTable::getOpcode(CastInst* C) {
308   switch(C->getOpcode()) {
309     case Instruction::Trunc:
310       return Expression::TRUNC;
311     case Instruction::ZExt:
312       return Expression::ZEXT;
313     case Instruction::SExt:
314       return Expression::SEXT;
315     case Instruction::FPToUI:
316       return Expression::FPTOUI;
317     case Instruction::FPToSI:
318       return Expression::FPTOSI;
319     case Instruction::UIToFP:
320       return Expression::UITOFP;
321     case Instruction::SIToFP:
322       return Expression::SITOFP;
323     case Instruction::FPTrunc:
324       return Expression::FPTRUNC;
325     case Instruction::FPExt:
326       return Expression::FPEXT;
327     case Instruction::PtrToInt:
328       return Expression::PTRTOINT;
329     case Instruction::IntToPtr:
330       return Expression::INTTOPTR;
331     case Instruction::BitCast:
332       return Expression::BITCAST;
333     
334     // THIS SHOULD NEVER HAPPEN
335     default:
336       assert(0 && "Cast operator with unknown opcode?");
337       return Expression::BITCAST;
338   }
339 }
340
341 Expression ValueTable::create_expression(BinaryOperator* BO) {
342   Expression e;
343     
344   e.firstVN = lookup_or_add(BO->getOperand(0));
345   e.secondVN = lookup_or_add(BO->getOperand(1));
346   e.thirdVN = 0;
347   e.type = BO->getType();
348   e.opcode = getOpcode(BO);
349   
350   return e;
351 }
352
353 Expression ValueTable::create_expression(CmpInst* C) {
354   Expression e;
355     
356   e.firstVN = lookup_or_add(C->getOperand(0));
357   e.secondVN = lookup_or_add(C->getOperand(1));
358   e.thirdVN = 0;
359   e.type = C->getType();
360   e.opcode = getOpcode(C);
361   
362   return e;
363 }
364
365 Expression ValueTable::create_expression(CastInst* C) {
366   Expression e;
367     
368   e.firstVN = lookup_or_add(C->getOperand(0));
369   e.secondVN = 0;
370   e.thirdVN = 0;
371   e.type = C->getType();
372   e.opcode = getOpcode(C);
373   
374   return e;
375 }
376
377 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
378   Expression e;
379     
380   e.firstVN = lookup_or_add(S->getOperand(0));
381   e.secondVN = lookup_or_add(S->getOperand(1));
382   e.thirdVN = lookup_or_add(S->getOperand(2));
383   e.type = S->getType();
384   e.opcode = Expression::SHUFFLE;
385   
386   return e;
387 }
388
389 Expression ValueTable::create_expression(ExtractElementInst* E) {
390   Expression e;
391     
392   e.firstVN = lookup_or_add(E->getOperand(0));
393   e.secondVN = lookup_or_add(E->getOperand(1));
394   e.thirdVN = 0;
395   e.type = E->getType();
396   e.opcode = Expression::EXTRACT;
397   
398   return e;
399 }
400
401 Expression ValueTable::create_expression(InsertElementInst* I) {
402   Expression e;
403     
404   e.firstVN = lookup_or_add(I->getOperand(0));
405   e.secondVN = lookup_or_add(I->getOperand(1));
406   e.thirdVN = lookup_or_add(I->getOperand(2));
407   e.type = I->getType();
408   e.opcode = Expression::INSERT;
409   
410   return e;
411 }
412
413 Expression ValueTable::create_expression(SelectInst* I) {
414   Expression e;
415     
416   e.firstVN = lookup_or_add(I->getCondition());
417   e.secondVN = lookup_or_add(I->getTrueValue());
418   e.thirdVN = lookup_or_add(I->getFalseValue());
419   e.type = I->getType();
420   e.opcode = Expression::SELECT;
421   
422   return e;
423 }
424
425 Expression ValueTable::create_expression(GetElementPtrInst* G) {
426   Expression e;
427     
428   e.firstVN = lookup_or_add(G->getPointerOperand());
429   e.secondVN = 0;
430   e.thirdVN = 0;
431   e.type = G->getType();
432   e.opcode = Expression::GEP;
433   
434   for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
435        I != E; ++I)
436     e.varargs.push_back(lookup_or_add(*I));
437   
438   return e;
439 }
440
441 //===----------------------------------------------------------------------===//
442 //                     ValueTable External Functions
443 //===----------------------------------------------------------------------===//
444
445 /// lookup_or_add - Returns the value number for the specified value, assigning
446 /// it a new number if it did not have one before.
447 uint32_t ValueTable::lookup_or_add(Value* V) {
448   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
449   if (VI != valueNumbering.end())
450     return VI->second;
451   
452   
453   if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
454     Expression e = create_expression(BO);
455     
456     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
457     if (EI != expressionNumbering.end()) {
458       valueNumbering.insert(std::make_pair(V, EI->second));
459       return EI->second;
460     } else {
461       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
462       valueNumbering.insert(std::make_pair(V, nextValueNumber));
463       
464       return nextValueNumber++;
465     }
466   } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
467     Expression e = create_expression(C);
468     
469     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
470     if (EI != expressionNumbering.end()) {
471       valueNumbering.insert(std::make_pair(V, EI->second));
472       return EI->second;
473     } else {
474       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
475       valueNumbering.insert(std::make_pair(V, nextValueNumber));
476       
477       return nextValueNumber++;
478     }
479   } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
480     Expression e = create_expression(U);
481     
482     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
483     if (EI != expressionNumbering.end()) {
484       valueNumbering.insert(std::make_pair(V, EI->second));
485       return EI->second;
486     } else {
487       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
488       valueNumbering.insert(std::make_pair(V, nextValueNumber));
489       
490       return nextValueNumber++;
491     }
492   } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
493     Expression e = create_expression(U);
494     
495     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
496     if (EI != expressionNumbering.end()) {
497       valueNumbering.insert(std::make_pair(V, EI->second));
498       return EI->second;
499     } else {
500       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
501       valueNumbering.insert(std::make_pair(V, nextValueNumber));
502       
503       return nextValueNumber++;
504     }
505   } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
506     Expression e = create_expression(U);
507     
508     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
509     if (EI != expressionNumbering.end()) {
510       valueNumbering.insert(std::make_pair(V, EI->second));
511       return EI->second;
512     } else {
513       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
514       valueNumbering.insert(std::make_pair(V, nextValueNumber));
515       
516       return nextValueNumber++;
517     }
518   } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
519     Expression e = create_expression(U);
520     
521     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
522     if (EI != expressionNumbering.end()) {
523       valueNumbering.insert(std::make_pair(V, EI->second));
524       return EI->second;
525     } else {
526       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
527       valueNumbering.insert(std::make_pair(V, nextValueNumber));
528       
529       return nextValueNumber++;
530     }
531   } else if (CastInst* U = dyn_cast<CastInst>(V)) {
532     Expression e = create_expression(U);
533     
534     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
535     if (EI != expressionNumbering.end()) {
536       valueNumbering.insert(std::make_pair(V, EI->second));
537       return EI->second;
538     } else {
539       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
540       valueNumbering.insert(std::make_pair(V, nextValueNumber));
541       
542       return nextValueNumber++;
543     }
544   } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
545     Expression e = create_expression(U);
546     
547     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
548     if (EI != expressionNumbering.end()) {
549       valueNumbering.insert(std::make_pair(V, EI->second));
550       return EI->second;
551     } else {
552       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
553       valueNumbering.insert(std::make_pair(V, nextValueNumber));
554       
555       return nextValueNumber++;
556     }
557   } else {
558     valueNumbering.insert(std::make_pair(V, nextValueNumber));
559     return nextValueNumber++;
560   }
561 }
562
563 /// lookup - Returns the value number of the specified value. Fails if
564 /// the value has not yet been numbered.
565 uint32_t ValueTable::lookup(Value* V) const {
566   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
567   if (VI != valueNumbering.end())
568     return VI->second;
569   else
570     assert(0 && "Value not numbered?");
571   
572   return 0;
573 }
574
575 /// add - Add the specified value with the given value number, removing
576 /// its old number, if any
577 void ValueTable::add(Value* V, uint32_t num) {
578   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
579   if (VI != valueNumbering.end())
580     valueNumbering.erase(VI);
581   valueNumbering.insert(std::make_pair(V, num));
582 }
583
584 /// clear - Remove all entries from the ValueTable
585 void ValueTable::clear() {
586   valueNumbering.clear();
587   expressionNumbering.clear();
588   nextValueNumber = 1;
589 }
590
591 /// erase - Remove a value from the value numbering
592 void ValueTable::erase(Value* V) {
593   valueNumbering.erase(V);
594 }
595
596 /// size - Return the number of assigned value numbers
597 unsigned ValueTable::size() {
598   // NOTE: zero is never assigned
599   return nextValueNumber;
600 }
601
602 namespace {
603
604 //===----------------------------------------------------------------------===//
605 //                       ValueNumberedSet Class
606 //===----------------------------------------------------------------------===//
607
608 class ValueNumberedSet {
609   private:
610     SmallPtrSet<Value*, 8> contents;
611     BitVector numbers;
612   public:
613     ValueNumberedSet() { numbers.resize(1); }
614     ValueNumberedSet(const ValueNumberedSet& other) {
615       numbers = other.numbers;
616       contents = other.contents;
617     }
618     
619     typedef SmallPtrSet<Value*, 8>::iterator iterator;
620     
621     iterator begin() { return contents.begin(); }
622     iterator end() { return contents.end(); }
623     
624     bool insert(Value* v) { return contents.insert(v); }
625     void insert(iterator I, iterator E) { contents.insert(I, E); }
626     void erase(Value* v) { contents.erase(v); }
627     unsigned count(Value* v) { return contents.count(v); }
628     size_t size() { return contents.size(); }
629     
630     void set(unsigned i)  {
631       if (i >= numbers.size())
632         numbers.resize(i+1);
633       
634       numbers.set(i);
635     }
636     
637     void operator=(const ValueNumberedSet& other) {
638       contents = other.contents;
639       numbers = other.numbers;
640     }
641     
642     void reset(unsigned i)  {
643       if (i < numbers.size())
644         numbers.reset(i);
645     }
646     
647     bool test(unsigned i)  {
648       if (i >= numbers.size())
649         return false;
650       
651       return numbers.test(i);
652     }
653     
654     void clear() {
655       contents.clear();
656       numbers.clear();
657     }
658 };
659
660 }
661
662 //===----------------------------------------------------------------------===//
663 //                         GVNPRE Pass
664 //===----------------------------------------------------------------------===//
665
666 namespace {
667
668   class VISIBILITY_HIDDEN GVNPRE : public FunctionPass {
669     bool runOnFunction(Function &F);
670   public:
671     static char ID; // Pass identification, replacement for typeid
672     GVNPRE() : FunctionPass((intptr_t)&ID) { }
673
674   private:
675     ValueTable VN;
676     SmallVector<Instruction*, 8> createdExpressions;
677     
678     DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
679     DenseMap<BasicBlock*, ValueNumberedSet> anticipatedIn;
680     DenseMap<BasicBlock*, ValueNumberedSet> generatedPhis;
681     
682     // This transformation requires dominator postdominator info
683     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
684       AU.setPreservesCFG();
685       AU.addRequiredID(BreakCriticalEdgesID);
686       AU.addRequired<UnifyFunctionExitNodes>();
687       AU.addRequired<DominatorTree>();
688     }
689   
690     // Helper fuctions
691     // FIXME: eliminate or document these better
692     void dump(ValueNumberedSet& s) const ;
693     void clean(ValueNumberedSet& set) ;
694     Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
695     Value* phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) ;
696     void phi_translate_set(ValueNumberedSet& anticIn, BasicBlock* pred,
697                            BasicBlock* succ, ValueNumberedSet& out) ;
698     
699     void topo_sort(ValueNumberedSet& set,
700                    SmallVector<Value*, 8>& vec) ;
701     
702     void cleanup() ;
703     bool elimination() ;
704     
705     void val_insert(ValueNumberedSet& s, Value* v) ;
706     void val_replace(ValueNumberedSet& s, Value* v) ;
707     bool dependsOnInvoke(Value* V) ;
708     void buildsets_availout(BasicBlock::iterator I,
709                             ValueNumberedSet& currAvail,
710                             ValueNumberedSet& currPhis,
711                             ValueNumberedSet& currExps,
712                             SmallPtrSet<Value*, 16>& currTemps);
713     bool buildsets_anticout(BasicBlock* BB,
714                             ValueNumberedSet& anticOut,
715                             SmallPtrSet<BasicBlock*, 8>& visited);
716     unsigned buildsets_anticin(BasicBlock* BB,
717                            ValueNumberedSet& anticOut,
718                            ValueNumberedSet& currExps,
719                            SmallPtrSet<Value*, 16>& currTemps,
720                            SmallPtrSet<BasicBlock*, 8>& visited);
721     void buildsets(Function& F) ;
722     
723     void insertion_pre(Value* e, BasicBlock* BB,
724                        DenseMap<BasicBlock*, Value*>& avail,
725                        std::map<BasicBlock*,ValueNumberedSet>& new_set);
726     unsigned insertion_mergepoint(SmallVector<Value*, 8>& workList,
727                                   df_iterator<DomTreeNode*>& D,
728                       std::map<BasicBlock*, ValueNumberedSet>& new_set);
729     bool insertion(Function& F) ;
730   
731   };
732   
733   char GVNPRE::ID = 0;
734   
735 }
736
737 // createGVNPREPass - The public interface to this file...
738 FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
739
740 static RegisterPass<GVNPRE> X("gvnpre",
741                       "Global Value Numbering/Partial Redundancy Elimination");
742
743
744 STATISTIC(NumInsertedVals, "Number of values inserted");
745 STATISTIC(NumInsertedPhis, "Number of PHI nodes inserted");
746 STATISTIC(NumEliminated, "Number of redundant instructions eliminated");
747
748 /// find_leader - Given a set and a value number, return the first
749 /// element of the set with that value number, or 0 if no such element
750 /// is present
751 Value* GVNPRE::find_leader(ValueNumberedSet& vals, uint32_t v) {
752   if (!vals.test(v))
753     return 0;
754   
755   for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
756        I != E; ++I)
757     if (v == VN.lookup(*I))
758       return *I;
759   
760   assert(0 && "No leader found, but present bit is set?");
761   return 0;
762 }
763
764 /// val_insert - Insert a value into a set only if there is not a value
765 /// with the same value number already in the set
766 void GVNPRE::val_insert(ValueNumberedSet& s, Value* v) {
767   uint32_t num = VN.lookup(v);
768   if (!s.test(num))
769     s.insert(v);
770 }
771
772 /// val_replace - Insert a value into a set, replacing any values already in
773 /// the set that have the same value number
774 void GVNPRE::val_replace(ValueNumberedSet& s, Value* v) {
775   if (s.count(v)) return;
776   
777   uint32_t num = VN.lookup(v);
778   Value* leader = find_leader(s, num);
779   if (leader != 0)
780     s.erase(leader);
781   s.insert(v);
782   s.set(num);
783 }
784
785 /// phi_translate - Given a value, its parent block, and a predecessor of its
786 /// parent, translate the value into legal for the predecessor block.  This 
787 /// means translating its operands (and recursively, their operands) through
788 /// any phi nodes in the parent into values available in the predecessor
789 Value* GVNPRE::phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) {
790   if (V == 0)
791     return 0;
792   
793   // Unary Operations
794   if (CastInst* U = dyn_cast<CastInst>(V)) {
795     Value* newOp1 = 0;
796     if (isa<Instruction>(U->getOperand(0)))
797       newOp1 = phi_translate(U->getOperand(0), pred, succ);
798     else
799       newOp1 = U->getOperand(0);
800     
801     if (newOp1 == 0)
802       return 0;
803     
804     if (newOp1 != U->getOperand(0)) {
805       Instruction* newVal = 0;
806       if (CastInst* C = dyn_cast<CastInst>(U))
807         newVal = CastInst::create(C->getOpcode(),
808                                   newOp1, C->getType(),
809                                   C->getName()+".expr");
810       
811       uint32_t v = VN.lookup_or_add(newVal);
812       
813       Value* leader = find_leader(availableOut[pred], v);
814       if (leader == 0) {
815         createdExpressions.push_back(newVal);
816         return newVal;
817       } else {
818         VN.erase(newVal);
819         delete newVal;
820         return leader;
821       }
822     }
823   
824   // Binary Operations
825   } if (isa<BinaryOperator>(V) || isa<CmpInst>(V) || 
826       isa<ExtractElementInst>(V)) {
827     User* U = cast<User>(V);
828     
829     Value* newOp1 = 0;
830     if (isa<Instruction>(U->getOperand(0)))
831       newOp1 = phi_translate(U->getOperand(0), pred, succ);
832     else
833       newOp1 = U->getOperand(0);
834     
835     if (newOp1 == 0)
836       return 0;
837     
838     Value* newOp2 = 0;
839     if (isa<Instruction>(U->getOperand(1)))
840       newOp2 = phi_translate(U->getOperand(1), pred, succ);
841     else
842       newOp2 = U->getOperand(1);
843     
844     if (newOp2 == 0)
845       return 0;
846     
847     if (newOp1 != U->getOperand(0) || newOp2 != U->getOperand(1)) {
848       Instruction* newVal = 0;
849       if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
850         newVal = BinaryOperator::create(BO->getOpcode(),
851                                         newOp1, newOp2,
852                                         BO->getName()+".expr");
853       else if (CmpInst* C = dyn_cast<CmpInst>(U))
854         newVal = CmpInst::create(C->getOpcode(),
855                                  C->getPredicate(),
856                                  newOp1, newOp2,
857                                  C->getName()+".expr");
858       else if (ExtractElementInst* E = dyn_cast<ExtractElementInst>(U))
859         newVal = new ExtractElementInst(newOp1, newOp2, E->getName()+".expr");
860       
861       uint32_t v = VN.lookup_or_add(newVal);
862       
863       Value* leader = find_leader(availableOut[pred], v);
864       if (leader == 0) {
865         createdExpressions.push_back(newVal);
866         return newVal;
867       } else {
868         VN.erase(newVal);
869         delete newVal;
870         return leader;
871       }
872     }
873   
874   // Ternary Operations
875   } else if (isa<ShuffleVectorInst>(V) || isa<InsertElementInst>(V) ||
876              isa<SelectInst>(V)) {
877     User* U = cast<User>(V);
878     
879     Value* newOp1 = 0;
880     if (isa<Instruction>(U->getOperand(0)))
881       newOp1 = phi_translate(U->getOperand(0), pred, succ);
882     else
883       newOp1 = U->getOperand(0);
884     
885     if (newOp1 == 0)
886       return 0;
887     
888     Value* newOp2 = 0;
889     if (isa<Instruction>(U->getOperand(1)))
890       newOp2 = phi_translate(U->getOperand(1), pred, succ);
891     else
892       newOp2 = U->getOperand(1);
893     
894     if (newOp2 == 0)
895       return 0;
896     
897     Value* newOp3 = 0;
898     if (isa<Instruction>(U->getOperand(2)))
899       newOp3 = phi_translate(U->getOperand(2), pred, succ);
900     else
901       newOp3 = U->getOperand(2);
902     
903     if (newOp3 == 0)
904       return 0;
905     
906     if (newOp1 != U->getOperand(0) ||
907         newOp2 != U->getOperand(1) ||
908         newOp3 != U->getOperand(2)) {
909       Instruction* newVal = 0;
910       if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
911         newVal = new ShuffleVectorInst(newOp1, newOp2, newOp3,
912                                        S->getName()+".expr");
913       else if (InsertElementInst* I = dyn_cast<InsertElementInst>(U))
914         newVal = InsertElementInst::Create(newOp1, newOp2, newOp3,
915                                            I->getName()+".expr");
916       else if (SelectInst* I = dyn_cast<SelectInst>(U))
917         newVal = SelectInst::Create(newOp1, newOp2, newOp3, I->getName()+".expr");
918       
919       uint32_t v = VN.lookup_or_add(newVal);
920       
921       Value* leader = find_leader(availableOut[pred], v);
922       if (leader == 0) {
923         createdExpressions.push_back(newVal);
924         return newVal;
925       } else {
926         VN.erase(newVal);
927         delete newVal;
928         return leader;
929       }
930     }
931   
932   // Varargs operators
933   } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
934     Value* newOp1 = 0;
935     if (isa<Instruction>(U->getPointerOperand()))
936       newOp1 = phi_translate(U->getPointerOperand(), pred, succ);
937     else
938       newOp1 = U->getPointerOperand();
939     
940     if (newOp1 == 0)
941       return 0;
942     
943     bool changed_idx = false;
944     SmallVector<Value*, 4> newIdx;
945     for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
946          I != E; ++I)
947       if (isa<Instruction>(*I)) {
948         Value* newVal = phi_translate(*I, pred, succ);
949         newIdx.push_back(newVal);
950         if (newVal != *I)
951           changed_idx = true;
952       } else {
953         newIdx.push_back(*I);
954       }
955     
956     if (newOp1 != U->getPointerOperand() || changed_idx) {
957       Instruction* newVal =
958           GetElementPtrInst::Create(newOp1,
959                                     newIdx.begin(), newIdx.end(),
960                                     U->getName()+".expr");
961       
962       uint32_t v = VN.lookup_or_add(newVal);
963       
964       Value* leader = find_leader(availableOut[pred], v);
965       if (leader == 0) {
966         createdExpressions.push_back(newVal);
967         return newVal;
968       } else {
969         VN.erase(newVal);
970         delete newVal;
971         return leader;
972       }
973     }
974   
975   // PHI Nodes
976   } else if (PHINode* P = dyn_cast<PHINode>(V)) {
977     if (P->getParent() == succ)
978       return P->getIncomingValueForBlock(pred);
979   }
980   
981   return V;
982 }
983
984 /// phi_translate_set - Perform phi translation on every element of a set
985 void GVNPRE::phi_translate_set(ValueNumberedSet& anticIn,
986                               BasicBlock* pred, BasicBlock* succ,
987                               ValueNumberedSet& out) {
988   for (ValueNumberedSet::iterator I = anticIn.begin(),
989        E = anticIn.end(); I != E; ++I) {
990     Value* V = phi_translate(*I, pred, succ);
991     if (V != 0 && !out.test(VN.lookup_or_add(V))) {
992       out.insert(V);
993       out.set(VN.lookup(V));
994     }
995   }
996 }
997
998 /// dependsOnInvoke - Test if a value has an phi node as an operand, any of 
999 /// whose inputs is an invoke instruction.  If this is true, we cannot safely
1000 /// PRE the instruction or anything that depends on it.
1001 bool GVNPRE::dependsOnInvoke(Value* V) {
1002   if (PHINode* p = dyn_cast<PHINode>(V)) {
1003     for (PHINode::op_iterator I = p->op_begin(), E = p->op_end(); I != E; ++I)
1004       if (isa<InvokeInst>(*I))
1005         return true;
1006     return false;
1007   } else {
1008     return false;
1009   }
1010 }
1011
1012 /// clean - Remove all non-opaque values from the set whose operands are not
1013 /// themselves in the set, as well as all values that depend on invokes (see 
1014 /// above)
1015 void GVNPRE::clean(ValueNumberedSet& set) {
1016   SmallVector<Value*, 8> worklist;
1017   worklist.reserve(set.size());
1018   topo_sort(set, worklist);
1019   
1020   for (unsigned i = 0; i < worklist.size(); ++i) {
1021     Value* v = worklist[i];
1022     
1023     // Handle unary ops
1024     if (CastInst* U = dyn_cast<CastInst>(v)) {
1025       bool lhsValid = !isa<Instruction>(U->getOperand(0));
1026       lhsValid |= set.test(VN.lookup(U->getOperand(0)));
1027       if (lhsValid)
1028         lhsValid = !dependsOnInvoke(U->getOperand(0));
1029       
1030       if (!lhsValid) {
1031         set.erase(U);
1032         set.reset(VN.lookup(U));
1033       }
1034     
1035     // Handle binary ops
1036     } else if (isa<BinaryOperator>(v) || isa<CmpInst>(v) ||
1037         isa<ExtractElementInst>(v)) {
1038       User* U = cast<User>(v);
1039       
1040       bool lhsValid = !isa<Instruction>(U->getOperand(0));
1041       lhsValid |= set.test(VN.lookup(U->getOperand(0)));
1042       if (lhsValid)
1043         lhsValid = !dependsOnInvoke(U->getOperand(0));
1044     
1045       bool rhsValid = !isa<Instruction>(U->getOperand(1));
1046       rhsValid |= set.test(VN.lookup(U->getOperand(1)));
1047       if (rhsValid)
1048         rhsValid = !dependsOnInvoke(U->getOperand(1));
1049       
1050       if (!lhsValid || !rhsValid) {
1051         set.erase(U);
1052         set.reset(VN.lookup(U));
1053       }
1054     
1055     // Handle ternary ops
1056     } else if (isa<ShuffleVectorInst>(v) || isa<InsertElementInst>(v) ||
1057                isa<SelectInst>(v)) {
1058       User* U = cast<User>(v);
1059     
1060       bool lhsValid = !isa<Instruction>(U->getOperand(0));
1061       lhsValid |= set.test(VN.lookup(U->getOperand(0)));
1062       if (lhsValid)
1063         lhsValid = !dependsOnInvoke(U->getOperand(0));
1064       
1065       bool rhsValid = !isa<Instruction>(U->getOperand(1));
1066       rhsValid |= set.test(VN.lookup(U->getOperand(1)));
1067       if (rhsValid)
1068         rhsValid = !dependsOnInvoke(U->getOperand(1));
1069       
1070       bool thirdValid = !isa<Instruction>(U->getOperand(2));
1071       thirdValid |= set.test(VN.lookup(U->getOperand(2)));
1072       if (thirdValid)
1073         thirdValid = !dependsOnInvoke(U->getOperand(2));
1074     
1075       if (!lhsValid || !rhsValid || !thirdValid) {
1076         set.erase(U);
1077         set.reset(VN.lookup(U));
1078       }
1079     
1080     // Handle varargs ops
1081     } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(v)) {
1082       bool ptrValid = !isa<Instruction>(U->getPointerOperand());
1083       ptrValid |= set.test(VN.lookup(U->getPointerOperand()));
1084       if (ptrValid)
1085         ptrValid = !dependsOnInvoke(U->getPointerOperand());
1086       
1087       bool varValid = true;
1088       for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
1089            I != E; ++I)
1090         if (varValid) {
1091           varValid &= !isa<Instruction>(*I) || set.test(VN.lookup(*I));
1092           varValid &= !dependsOnInvoke(*I);
1093         }
1094     
1095       if (!ptrValid || !varValid) {
1096         set.erase(U);
1097         set.reset(VN.lookup(U));
1098       }
1099     }
1100   }
1101 }
1102
1103 /// topo_sort - Given a set of values, sort them by topological
1104 /// order into the provided vector.
1105 void GVNPRE::topo_sort(ValueNumberedSet& set, SmallVector<Value*, 8>& vec) {
1106   SmallPtrSet<Value*, 16> visited;
1107   SmallVector<Value*, 8> stack;
1108   for (ValueNumberedSet::iterator I = set.begin(), E = set.end();
1109        I != E; ++I) {
1110     if (visited.count(*I) == 0)
1111       stack.push_back(*I);
1112     
1113     while (!stack.empty()) {
1114       Value* e = stack.back();
1115       
1116       // Handle unary ops
1117       if (CastInst* U = dyn_cast<CastInst>(e)) {
1118         Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1119     
1120         if (l != 0 && isa<Instruction>(l) &&
1121             visited.count(l) == 0)
1122           stack.push_back(l);
1123         else {
1124           vec.push_back(e);
1125           visited.insert(e);
1126           stack.pop_back();
1127         }
1128       
1129       // Handle binary ops
1130       } else if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1131           isa<ExtractElementInst>(e)) {
1132         User* U = cast<User>(e);
1133         Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1134         Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
1135     
1136         if (l != 0 && isa<Instruction>(l) &&
1137             visited.count(l) == 0)
1138           stack.push_back(l);
1139         else if (r != 0 && isa<Instruction>(r) &&
1140                  visited.count(r) == 0)
1141           stack.push_back(r);
1142         else {
1143           vec.push_back(e);
1144           visited.insert(e);
1145           stack.pop_back();
1146         }
1147       
1148       // Handle ternary ops
1149       } else if (isa<InsertElementInst>(e) || isa<ShuffleVectorInst>(e) ||
1150                  isa<SelectInst>(e)) {
1151         User* U = cast<User>(e);
1152         Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1153         Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
1154         Value* m = find_leader(set, VN.lookup(U->getOperand(2)));
1155       
1156         if (l != 0 && isa<Instruction>(l) &&
1157             visited.count(l) == 0)
1158           stack.push_back(l);
1159         else if (r != 0 && isa<Instruction>(r) &&
1160                  visited.count(r) == 0)
1161           stack.push_back(r);
1162         else if (m != 0 && isa<Instruction>(m) &&
1163                  visited.count(m) == 0)
1164           stack.push_back(m);
1165         else {
1166           vec.push_back(e);
1167           visited.insert(e);
1168           stack.pop_back();
1169         }
1170       
1171       // Handle vararg ops
1172       } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(e)) {
1173         Value* p = find_leader(set, VN.lookup(U->getPointerOperand()));
1174         
1175         if (p != 0 && isa<Instruction>(p) &&
1176             visited.count(p) == 0)
1177           stack.push_back(p);
1178         else {
1179           bool push_va = false;
1180           for (GetElementPtrInst::op_iterator I = U->idx_begin(),
1181                E = U->idx_end(); I != E; ++I) {
1182             Value * v = find_leader(set, VN.lookup(*I));
1183             if (v != 0 && isa<Instruction>(v) && visited.count(v) == 0) {
1184               stack.push_back(v);
1185               push_va = true;
1186             }
1187           }
1188           
1189           if (!push_va) {
1190             vec.push_back(e);
1191             visited.insert(e);
1192             stack.pop_back();
1193           }
1194         }
1195       
1196       // Handle opaque ops
1197       } else {
1198         visited.insert(e);
1199         vec.push_back(e);
1200         stack.pop_back();
1201       }
1202     }
1203     
1204     stack.clear();
1205   }
1206 }
1207
1208 /// dump - Dump a set of values to standard error
1209 void GVNPRE::dump(ValueNumberedSet& s) const {
1210   DOUT << "{ ";
1211   for (ValueNumberedSet::iterator I = s.begin(), E = s.end();
1212        I != E; ++I) {
1213     DOUT << "" << VN.lookup(*I) << ": ";
1214     DEBUG((*I)->dump());
1215   }
1216   DOUT << "}\n\n";
1217 }
1218
1219 /// elimination - Phase 3 of the main algorithm.  Perform full redundancy 
1220 /// elimination by walking the dominator tree and removing any instruction that 
1221 /// is dominated by another instruction with the same value number.
1222 bool GVNPRE::elimination() {
1223   bool changed_function = false;
1224   
1225   SmallVector<std::pair<Instruction*, Value*>, 8> replace;
1226   SmallVector<Instruction*, 8> erase;
1227   
1228   DominatorTree& DT = getAnalysis<DominatorTree>();
1229   
1230   for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1231          E = df_end(DT.getRootNode()); DI != E; ++DI) {
1232     BasicBlock* BB = DI->getBlock();
1233     
1234     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1235          BI != BE; ++BI) {
1236
1237       if (isa<BinaryOperator>(BI) || isa<CmpInst>(BI) ||
1238           isa<ShuffleVectorInst>(BI) || isa<InsertElementInst>(BI) ||
1239           isa<ExtractElementInst>(BI) || isa<SelectInst>(BI) ||
1240           isa<CastInst>(BI) || isa<GetElementPtrInst>(BI)) {
1241         
1242         if (availableOut[BB].test(VN.lookup(BI)) &&
1243             !availableOut[BB].count(BI)) {
1244           Value *leader = find_leader(availableOut[BB], VN.lookup(BI));
1245           if (Instruction* Instr = dyn_cast<Instruction>(leader))
1246             if (Instr->getParent() != 0 && Instr != BI) {
1247               replace.push_back(std::make_pair(BI, leader));
1248               erase.push_back(BI);
1249               ++NumEliminated;
1250             }
1251         }
1252       }
1253     }
1254   }
1255   
1256   while (!replace.empty()) {
1257     std::pair<Instruction*, Value*> rep = replace.back();
1258     replace.pop_back();
1259     rep.first->replaceAllUsesWith(rep.second);
1260     changed_function = true;
1261   }
1262     
1263   for (SmallVector<Instruction*, 8>::iterator I = erase.begin(),
1264        E = erase.end(); I != E; ++I)
1265      (*I)->eraseFromParent();
1266   
1267   return changed_function;
1268 }
1269
1270 /// cleanup - Delete any extraneous values that were created to represent
1271 /// expressions without leaders.
1272 void GVNPRE::cleanup() {
1273   while (!createdExpressions.empty()) {
1274     Instruction* I = createdExpressions.back();
1275     createdExpressions.pop_back();
1276     
1277     delete I;
1278   }
1279 }
1280
1281 /// buildsets_availout - When calculating availability, handle an instruction
1282 /// by inserting it into the appropriate sets
1283 void GVNPRE::buildsets_availout(BasicBlock::iterator I,
1284                                 ValueNumberedSet& currAvail,
1285                                 ValueNumberedSet& currPhis,
1286                                 ValueNumberedSet& currExps,
1287                                 SmallPtrSet<Value*, 16>& currTemps) {
1288   // Handle PHI nodes
1289   if (PHINode* p = dyn_cast<PHINode>(I)) {
1290     unsigned num = VN.lookup_or_add(p);
1291     
1292     currPhis.insert(p);
1293     currPhis.set(num);
1294   
1295   // Handle unary ops
1296   } else if (CastInst* U = dyn_cast<CastInst>(I)) {
1297     Value* leftValue = U->getOperand(0);
1298     
1299     unsigned num = VN.lookup_or_add(U);
1300       
1301     if (isa<Instruction>(leftValue))
1302       if (!currExps.test(VN.lookup(leftValue))) {
1303         currExps.insert(leftValue);
1304         currExps.set(VN.lookup(leftValue));
1305       }
1306     
1307     if (!currExps.test(num)) {
1308       currExps.insert(U);
1309       currExps.set(num);
1310     }
1311   
1312   // Handle binary ops
1313   } else if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
1314              isa<ExtractElementInst>(I)) {
1315     User* U = cast<User>(I);
1316     Value* leftValue = U->getOperand(0);
1317     Value* rightValue = U->getOperand(1);
1318     
1319     unsigned num = VN.lookup_or_add(U);
1320       
1321     if (isa<Instruction>(leftValue))
1322       if (!currExps.test(VN.lookup(leftValue))) {
1323         currExps.insert(leftValue);
1324         currExps.set(VN.lookup(leftValue));
1325       }
1326     
1327     if (isa<Instruction>(rightValue))
1328       if (!currExps.test(VN.lookup(rightValue))) {
1329         currExps.insert(rightValue);
1330         currExps.set(VN.lookup(rightValue));
1331       }
1332     
1333     if (!currExps.test(num)) {
1334       currExps.insert(U);
1335       currExps.set(num);
1336     }
1337     
1338   // Handle ternary ops
1339   } else if (isa<InsertElementInst>(I) || isa<ShuffleVectorInst>(I) ||
1340              isa<SelectInst>(I)) {
1341     User* U = cast<User>(I);
1342     Value* leftValue = U->getOperand(0);
1343     Value* rightValue = U->getOperand(1);
1344     Value* thirdValue = U->getOperand(2);
1345       
1346     VN.lookup_or_add(U);
1347     
1348     unsigned num = VN.lookup_or_add(U);
1349     
1350     if (isa<Instruction>(leftValue))
1351       if (!currExps.test(VN.lookup(leftValue))) {
1352         currExps.insert(leftValue);
1353         currExps.set(VN.lookup(leftValue));
1354       }
1355     if (isa<Instruction>(rightValue))
1356       if (!currExps.test(VN.lookup(rightValue))) {
1357         currExps.insert(rightValue);
1358         currExps.set(VN.lookup(rightValue));
1359       }
1360     if (isa<Instruction>(thirdValue))
1361       if (!currExps.test(VN.lookup(thirdValue))) {
1362         currExps.insert(thirdValue);
1363         currExps.set(VN.lookup(thirdValue));
1364       }
1365     
1366     if (!currExps.test(num)) {
1367       currExps.insert(U);
1368       currExps.set(num);
1369     }
1370     
1371   // Handle vararg ops
1372   } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(I)) {
1373     Value* ptrValue = U->getPointerOperand();
1374       
1375     VN.lookup_or_add(U);
1376     
1377     unsigned num = VN.lookup_or_add(U);
1378     
1379     if (isa<Instruction>(ptrValue))
1380       if (!currExps.test(VN.lookup(ptrValue))) {
1381         currExps.insert(ptrValue);
1382         currExps.set(VN.lookup(ptrValue));
1383       }
1384     
1385     for (GetElementPtrInst::op_iterator OI = U->idx_begin(), OE = U->idx_end();
1386          OI != OE; ++OI)
1387       if (isa<Instruction>(*OI) && !currExps.test(VN.lookup(*OI))) {
1388         currExps.insert(*OI);
1389         currExps.set(VN.lookup(*OI));
1390       }
1391     
1392     if (!currExps.test(VN.lookup(U))) {
1393       currExps.insert(U);
1394       currExps.set(num);
1395     }
1396     
1397   // Handle opaque ops
1398   } else if (!I->isTerminator()){
1399     VN.lookup_or_add(I);
1400     
1401     currTemps.insert(I);
1402   }
1403     
1404   if (!I->isTerminator())
1405     if (!currAvail.test(VN.lookup(I))) {
1406       currAvail.insert(I);
1407       currAvail.set(VN.lookup(I));
1408     }
1409 }
1410
1411 /// buildsets_anticout - When walking the postdom tree, calculate the ANTIC_OUT
1412 /// set as a function of the ANTIC_IN set of the block's predecessors
1413 bool GVNPRE::buildsets_anticout(BasicBlock* BB,
1414                                 ValueNumberedSet& anticOut,
1415                                 SmallPtrSet<BasicBlock*, 8>& visited) {
1416   if (BB->getTerminator()->getNumSuccessors() == 1) {
1417     if (BB->getTerminator()->getSuccessor(0) != BB &&
1418         visited.count(BB->getTerminator()->getSuccessor(0)) == 0) {
1419       return true;
1420     }
1421     else {
1422       phi_translate_set(anticipatedIn[BB->getTerminator()->getSuccessor(0)],
1423                         BB,  BB->getTerminator()->getSuccessor(0), anticOut);
1424     }
1425   } else if (BB->getTerminator()->getNumSuccessors() > 1) {
1426     BasicBlock* first = BB->getTerminator()->getSuccessor(0);
1427     for (ValueNumberedSet::iterator I = anticipatedIn[first].begin(),
1428          E = anticipatedIn[first].end(); I != E; ++I) {
1429       anticOut.insert(*I);
1430       anticOut.set(VN.lookup(*I));
1431     }
1432     
1433     for (unsigned i = 1; i < BB->getTerminator()->getNumSuccessors(); ++i) {
1434       BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
1435       ValueNumberedSet& succAnticIn = anticipatedIn[currSucc];
1436       
1437       SmallVector<Value*, 16> temp;
1438       
1439       for (ValueNumberedSet::iterator I = anticOut.begin(),
1440            E = anticOut.end(); I != E; ++I)
1441         if (!succAnticIn.test(VN.lookup(*I)))
1442           temp.push_back(*I);
1443
1444       for (SmallVector<Value*, 16>::iterator I = temp.begin(), E = temp.end();
1445            I != E; ++I) {
1446         anticOut.erase(*I);
1447         anticOut.reset(VN.lookup(*I));
1448       }
1449     }
1450   }
1451   
1452   return false;
1453 }
1454
1455 /// buildsets_anticin - Walk the postdom tree, calculating ANTIC_OUT for
1456 /// each block.  ANTIC_IN is then a function of ANTIC_OUT and the GEN
1457 /// sets populated in buildsets_availout
1458 unsigned GVNPRE::buildsets_anticin(BasicBlock* BB,
1459                                ValueNumberedSet& anticOut,
1460                                ValueNumberedSet& currExps,
1461                                SmallPtrSet<Value*, 16>& currTemps,
1462                                SmallPtrSet<BasicBlock*, 8>& visited) {
1463   ValueNumberedSet& anticIn = anticipatedIn[BB];
1464   unsigned old = anticIn.size();
1465       
1466   bool defer = buildsets_anticout(BB, anticOut, visited);
1467   if (defer)
1468     return 0;
1469   
1470   anticIn.clear();
1471   
1472   for (ValueNumberedSet::iterator I = anticOut.begin(),
1473        E = anticOut.end(); I != E; ++I) {
1474     anticIn.insert(*I);
1475     anticIn.set(VN.lookup(*I));
1476   }
1477   for (ValueNumberedSet::iterator I = currExps.begin(),
1478        E = currExps.end(); I != E; ++I) {
1479     if (!anticIn.test(VN.lookup(*I))) {
1480       anticIn.insert(*I);
1481       anticIn.set(VN.lookup(*I));
1482     }
1483   } 
1484   
1485   for (SmallPtrSet<Value*, 16>::iterator I = currTemps.begin(),
1486        E = currTemps.end(); I != E; ++I) {
1487     anticIn.erase(*I);
1488     anticIn.reset(VN.lookup(*I));
1489   }
1490   
1491   clean(anticIn);
1492   anticOut.clear();
1493   
1494   if (old != anticIn.size())
1495     return 2;
1496   else
1497     return 1;
1498 }
1499
1500 /// buildsets - Phase 1 of the main algorithm.  Construct the AVAIL_OUT
1501 /// and the ANTIC_IN sets.
1502 void GVNPRE::buildsets(Function& F) {
1503   DenseMap<BasicBlock*, ValueNumberedSet> generatedExpressions;
1504   DenseMap<BasicBlock*, SmallPtrSet<Value*, 16> > generatedTemporaries;
1505
1506   DominatorTree &DT = getAnalysis<DominatorTree>();   
1507   
1508   // Phase 1, Part 1: calculate AVAIL_OUT
1509   
1510   // Top-down walk of the dominator tree
1511   for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1512          E = df_end(DT.getRootNode()); DI != E; ++DI) {
1513     
1514     // Get the sets to update for this block
1515     ValueNumberedSet& currExps = generatedExpressions[DI->getBlock()];
1516     ValueNumberedSet& currPhis = generatedPhis[DI->getBlock()];
1517     SmallPtrSet<Value*, 16>& currTemps = generatedTemporaries[DI->getBlock()];
1518     ValueNumberedSet& currAvail = availableOut[DI->getBlock()];     
1519     
1520     BasicBlock* BB = DI->getBlock();
1521   
1522     // A block inherits AVAIL_OUT from its dominator
1523     if (DI->getIDom() != 0)
1524       currAvail = availableOut[DI->getIDom()->getBlock()];
1525
1526     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1527          BI != BE; ++BI)
1528       buildsets_availout(BI, currAvail, currPhis, currExps,
1529                          currTemps);
1530       
1531   }
1532
1533   // Phase 1, Part 2: calculate ANTIC_IN
1534   
1535   SmallPtrSet<BasicBlock*, 8> visited;
1536   SmallPtrSet<BasicBlock*, 4> block_changed;
1537   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
1538     block_changed.insert(FI);
1539   
1540   bool changed = true;
1541   unsigned iterations = 0;
1542   
1543   while (changed) {
1544     changed = false;
1545     ValueNumberedSet anticOut;
1546     
1547     // Postorder walk of the CFG
1548     for (po_iterator<BasicBlock*> BBI = po_begin(&F.getEntryBlock()),
1549          BBE = po_end(&F.getEntryBlock()); BBI != BBE; ++BBI) {
1550       BasicBlock* BB = *BBI;
1551       
1552       if (block_changed.count(BB) != 0) {
1553         unsigned ret = buildsets_anticin(BB, anticOut,generatedExpressions[BB],
1554                                          generatedTemporaries[BB], visited);
1555       
1556         if (ret == 0) {
1557           changed = true;
1558           continue;
1559         } else {
1560           visited.insert(BB);
1561         
1562           if (ret == 2)
1563            for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1564                  PI != PE; ++PI) {
1565               block_changed.insert(*PI);
1566            }
1567           else
1568             block_changed.erase(BB);
1569         
1570           changed |= (ret == 2);
1571         }
1572       }
1573     }
1574     
1575     iterations++;
1576   }
1577 }
1578
1579 /// insertion_pre - When a partial redundancy has been identified, eliminate it
1580 /// by inserting appropriate values into the predecessors and a phi node in
1581 /// the main block
1582 void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
1583                            DenseMap<BasicBlock*, Value*>& avail,
1584                     std::map<BasicBlock*, ValueNumberedSet>& new_sets) {
1585   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1586     Value* e2 = avail[*PI];
1587     if (!availableOut[*PI].test(VN.lookup(e2))) {
1588       User* U = cast<User>(e2);
1589       
1590       Value* s1 = 0;
1591       if (isa<BinaryOperator>(U->getOperand(0)) || 
1592           isa<CmpInst>(U->getOperand(0)) ||
1593           isa<ShuffleVectorInst>(U->getOperand(0)) ||
1594           isa<ExtractElementInst>(U->getOperand(0)) ||
1595           isa<InsertElementInst>(U->getOperand(0)) ||
1596           isa<SelectInst>(U->getOperand(0)) ||
1597           isa<CastInst>(U->getOperand(0)) ||
1598           isa<GetElementPtrInst>(U->getOperand(0)))
1599         s1 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(0)));
1600       else
1601         s1 = U->getOperand(0);
1602       
1603       Value* s2 = 0;
1604       
1605       if (isa<BinaryOperator>(U) || 
1606           isa<CmpInst>(U) ||
1607           isa<ShuffleVectorInst>(U) ||
1608           isa<ExtractElementInst>(U) ||
1609           isa<InsertElementInst>(U) ||
1610           isa<SelectInst>(U)) {
1611         if (isa<BinaryOperator>(U->getOperand(1)) || 
1612             isa<CmpInst>(U->getOperand(1)) ||
1613             isa<ShuffleVectorInst>(U->getOperand(1)) ||
1614             isa<ExtractElementInst>(U->getOperand(1)) ||
1615             isa<InsertElementInst>(U->getOperand(1)) ||
1616             isa<SelectInst>(U->getOperand(1)) ||
1617             isa<CastInst>(U->getOperand(1)) ||
1618             isa<GetElementPtrInst>(U->getOperand(1))) {
1619           s2 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(1)));
1620         } else {
1621           s2 = U->getOperand(1);
1622         }
1623       }
1624       
1625       // Ternary Operators
1626       Value* s3 = 0;
1627       if (isa<ShuffleVectorInst>(U) ||
1628           isa<InsertElementInst>(U) ||
1629           isa<SelectInst>(U)) {
1630         if (isa<BinaryOperator>(U->getOperand(2)) || 
1631             isa<CmpInst>(U->getOperand(2)) ||
1632             isa<ShuffleVectorInst>(U->getOperand(2)) ||
1633             isa<ExtractElementInst>(U->getOperand(2)) ||
1634             isa<InsertElementInst>(U->getOperand(2)) ||
1635             isa<SelectInst>(U->getOperand(2)) ||
1636             isa<CastInst>(U->getOperand(2)) ||
1637             isa<GetElementPtrInst>(U->getOperand(2))) {
1638           s3 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(2)));
1639         } else {
1640           s3 = U->getOperand(2);
1641         }
1642       }
1643       
1644       // Vararg operators
1645       SmallVector<Value*, 4> sVarargs;
1646       if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U)) {
1647         for (GetElementPtrInst::op_iterator OI = G->idx_begin(),
1648              OE = G->idx_end(); OI != OE; ++OI) {
1649           if (isa<BinaryOperator>(*OI) || 
1650               isa<CmpInst>(*OI) ||
1651               isa<ShuffleVectorInst>(*OI) ||
1652               isa<ExtractElementInst>(*OI) ||
1653               isa<InsertElementInst>(*OI) ||
1654               isa<SelectInst>(*OI) ||
1655               isa<CastInst>(*OI) ||
1656               isa<GetElementPtrInst>(*OI)) {
1657             sVarargs.push_back(find_leader(availableOut[*PI], 
1658                                VN.lookup(*OI)));
1659           } else {
1660             sVarargs.push_back(*OI);
1661           }
1662         }
1663       }
1664       
1665       Value* newVal = 0;
1666       if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
1667         newVal = BinaryOperator::create(BO->getOpcode(), s1, s2,
1668                                         BO->getName()+".gvnpre",
1669                                         (*PI)->getTerminator());
1670       else if (CmpInst* C = dyn_cast<CmpInst>(U))
1671         newVal = CmpInst::create(C->getOpcode(), C->getPredicate(), s1, s2,
1672                                  C->getName()+".gvnpre", 
1673                                  (*PI)->getTerminator());
1674       else if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
1675         newVal = new ShuffleVectorInst(s1, s2, s3, S->getName()+".gvnpre",
1676                                        (*PI)->getTerminator());
1677       else if (InsertElementInst* S = dyn_cast<InsertElementInst>(U))
1678         newVal = InsertElementInst::Create(s1, s2, s3, S->getName()+".gvnpre",
1679                                            (*PI)->getTerminator());
1680       else if (ExtractElementInst* S = dyn_cast<ExtractElementInst>(U))
1681         newVal = new ExtractElementInst(s1, s2, S->getName()+".gvnpre",
1682                                         (*PI)->getTerminator());
1683       else if (SelectInst* S = dyn_cast<SelectInst>(U))
1684         newVal = SelectInst::Create(s1, s2, s3, S->getName()+".gvnpre",
1685                                     (*PI)->getTerminator());
1686       else if (CastInst* C = dyn_cast<CastInst>(U))
1687         newVal = CastInst::create(C->getOpcode(), s1, C->getType(),
1688                                   C->getName()+".gvnpre", 
1689                                   (*PI)->getTerminator());
1690       else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U))
1691         newVal = GetElementPtrInst::Create(s1, sVarargs.begin(), sVarargs.end(),
1692                                            G->getName()+".gvnpre", 
1693                                            (*PI)->getTerminator());
1694
1695       VN.add(newVal, VN.lookup(U));
1696                   
1697       ValueNumberedSet& predAvail = availableOut[*PI];
1698       val_replace(predAvail, newVal);
1699       val_replace(new_sets[*PI], newVal);
1700       predAvail.set(VN.lookup(newVal));
1701             
1702       DenseMap<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1703       if (av != avail.end())
1704         avail.erase(av);
1705       avail.insert(std::make_pair(*PI, newVal));
1706                   
1707       ++NumInsertedVals;
1708     }
1709   }
1710               
1711   PHINode* p = 0;
1712               
1713   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1714     if (p == 0)
1715       p = PHINode::Create(avail[*PI]->getType(), "gvnpre-join", BB->begin());
1716     
1717     p->addIncoming(avail[*PI], *PI);
1718   }
1719
1720   VN.add(p, VN.lookup(e));
1721   val_replace(availableOut[BB], p);
1722   availableOut[BB].set(VN.lookup(e));
1723   generatedPhis[BB].insert(p);
1724   generatedPhis[BB].set(VN.lookup(e));
1725   new_sets[BB].insert(p);
1726   new_sets[BB].set(VN.lookup(e));
1727               
1728   ++NumInsertedPhis;
1729 }
1730
1731 /// insertion_mergepoint - When walking the dom tree, check at each merge
1732 /// block for the possibility of a partial redundancy.  If present, eliminate it
1733 unsigned GVNPRE::insertion_mergepoint(SmallVector<Value*, 8>& workList,
1734                                       df_iterator<DomTreeNode*>& D,
1735                     std::map<BasicBlock*, ValueNumberedSet >& new_sets) {
1736   bool changed_function = false;
1737   bool new_stuff = false;
1738   
1739   BasicBlock* BB = D->getBlock();
1740   for (unsigned i = 0; i < workList.size(); ++i) {
1741     Value* e = workList[i];
1742           
1743     if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1744         isa<ExtractElementInst>(e) || isa<InsertElementInst>(e) ||
1745         isa<ShuffleVectorInst>(e) || isa<SelectInst>(e) || isa<CastInst>(e) ||
1746         isa<GetElementPtrInst>(e)) {
1747       if (availableOut[D->getIDom()->getBlock()].test(VN.lookup(e)))
1748         continue;
1749             
1750       DenseMap<BasicBlock*, Value*> avail;
1751       bool by_some = false;
1752       bool all_same = true;
1753       Value * first_s = 0;
1754             
1755       for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;
1756            ++PI) {
1757         Value *e2 = phi_translate(e, *PI, BB);
1758         Value *e3 = find_leader(availableOut[*PI], VN.lookup(e2));
1759               
1760         if (e3 == 0) {
1761           DenseMap<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1762           if (av != avail.end())
1763             avail.erase(av);
1764           avail.insert(std::make_pair(*PI, e2));
1765           all_same = false;
1766         } else {
1767           DenseMap<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1768           if (av != avail.end())
1769             avail.erase(av);
1770           avail.insert(std::make_pair(*PI, e3));
1771                 
1772           by_some = true;
1773           if (first_s == 0)
1774             first_s = e3;
1775           else if (first_s != e3)
1776             all_same = false;
1777         }
1778       }
1779             
1780       if (by_some && !all_same &&
1781           !generatedPhis[BB].test(VN.lookup(e))) {
1782         insertion_pre(e, BB, avail, new_sets);
1783               
1784         changed_function = true;
1785         new_stuff = true;
1786       }
1787     }
1788   }
1789   
1790   unsigned retval = 0;
1791   if (changed_function)
1792     retval += 1;
1793   if (new_stuff)
1794     retval += 2;
1795   
1796   return retval;
1797 }
1798
1799 /// insert - Phase 2 of the main algorithm.  Walk the dominator tree looking for
1800 /// merge points.  When one is found, check for a partial redundancy.  If one is
1801 /// present, eliminate it.  Repeat this walk until no changes are made.
1802 bool GVNPRE::insertion(Function& F) {
1803   bool changed_function = false;
1804
1805   DominatorTree &DT = getAnalysis<DominatorTree>();  
1806   
1807   std::map<BasicBlock*, ValueNumberedSet> new_sets;
1808   bool new_stuff = true;
1809   while (new_stuff) {
1810     new_stuff = false;
1811     for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1812          E = df_end(DT.getRootNode()); DI != E; ++DI) {
1813       BasicBlock* BB = DI->getBlock();
1814       
1815       if (BB == 0)
1816         continue;
1817       
1818       ValueNumberedSet& availOut = availableOut[BB];
1819       ValueNumberedSet& anticIn = anticipatedIn[BB];
1820       
1821       // Replace leaders with leaders inherited from dominator
1822       if (DI->getIDom() != 0) {
1823         ValueNumberedSet& dom_set = new_sets[DI->getIDom()->getBlock()];
1824         for (ValueNumberedSet::iterator I = dom_set.begin(),
1825              E = dom_set.end(); I != E; ++I) {
1826           val_replace(new_sets[BB], *I);
1827           val_replace(availOut, *I);
1828         }
1829       }
1830       
1831       // If there is more than one predecessor...
1832       if (pred_begin(BB) != pred_end(BB) && ++pred_begin(BB) != pred_end(BB)) {
1833         SmallVector<Value*, 8> workList;
1834         workList.reserve(anticIn.size());
1835         topo_sort(anticIn, workList);
1836         
1837         unsigned result = insertion_mergepoint(workList, DI, new_sets);
1838         if (result & 1)
1839           changed_function = true;
1840         if (result & 2)
1841           new_stuff = true;
1842       }
1843     }
1844   }
1845   
1846   return changed_function;
1847 }
1848
1849 // GVNPRE::runOnFunction - This is the main transformation entry point for a
1850 // function.
1851 //
1852 bool GVNPRE::runOnFunction(Function &F) {
1853   // Clean out global sets from any previous functions
1854   VN.clear();
1855   createdExpressions.clear();
1856   availableOut.clear();
1857   anticipatedIn.clear();
1858   generatedPhis.clear();
1859  
1860   bool changed_function = false;
1861   
1862   // Phase 1: BuildSets
1863   // This phase calculates the AVAIL_OUT and ANTIC_IN sets
1864   buildsets(F);
1865   
1866   // Phase 2: Insert
1867   // This phase inserts values to make partially redundant values
1868   // fully redundant
1869   changed_function |= insertion(F);
1870   
1871   // Phase 3: Eliminate
1872   // This phase performs trivial full redundancy elimination
1873   changed_function |= elimination();
1874   
1875   // Phase 4: Cleanup
1876   // This phase cleans up values that were created solely
1877   // as leaders for expressions
1878   cleanup();
1879   
1880   return changed_function;
1881 }