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