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