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