5fe4f0a3eebecc196079f50a8ad28d489d296d74
[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 //                         GVNPRE Pass
551 //===----------------------------------------------------------------------===//
552
553 namespace {
554
555   class VISIBILITY_HIDDEN GVNPRE : public FunctionPass {
556     bool runOnFunction(Function &F);
557   public:
558     static char ID; // Pass identification, replacement for typeid
559     GVNPRE() : FunctionPass((intptr_t)&ID) { }
560
561   private:
562     ValueTable VN;
563     std::vector<Instruction*> createdExpressions;
564     
565     std::map<BasicBlock*, SmallPtrSet<Value*, 16> > availableOut;
566     std::map<BasicBlock*, SmallPtrSet<Value*, 16> > anticipatedIn;
567     
568     // This transformation requires dominator postdominator info
569     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
570       AU.setPreservesCFG();
571       AU.addRequired<UnifyFunctionExitNodes>();
572       AU.addRequired<DominatorTree>();
573     }
574   
575     // Helper fuctions
576     // FIXME: eliminate or document these better
577     void dump(const SmallPtrSet<Value*, 16>& s) const;
578     void clean(SmallPtrSet<Value*, 16>& set, BitVector& presentInSet);
579     Value* find_leader(SmallPtrSet<Value*, 16>& vals,
580                        uint32_t v);
581     Value* phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ);
582     void phi_translate_set(SmallPtrSet<Value*, 16>& anticIn, BasicBlock* pred,
583                            BasicBlock* succ, SmallPtrSet<Value*, 16>& out);
584     
585     void topo_sort(SmallPtrSet<Value*, 16>& set,
586                    std::vector<Value*>& vec);
587     
588     void cleanup();
589     bool elimination();
590     
591     void val_insert(SmallPtrSet<Value*, 16>& s, Value* v);
592     void val_replace(SmallPtrSet<Value*, 16>& s, Value* v);
593     bool dependsOnInvoke(Value* V);
594     void buildsets_availout(BasicBlock::iterator I,
595                             SmallPtrSet<Value*, 16>& currAvail,
596                             SmallPtrSet<PHINode*, 16>& currPhis,
597                             SmallPtrSet<Value*, 16>& currExps,
598                             SmallPtrSet<Value*, 16>& currTemps,
599                             BitVector& availNumbers,
600                             BitVector& expNumbers);
601     bool buildsets_anticout(BasicBlock* BB,
602                             SmallPtrSet<Value*, 16>& anticOut,
603                             std::set<BasicBlock*>& visited);
604     unsigned buildsets_anticin(BasicBlock* BB,
605                            SmallPtrSet<Value*, 16>& anticOut,
606                            SmallPtrSet<Value*, 16>& currExps,
607                            SmallPtrSet<Value*, 16>& currTemps,
608                            std::set<BasicBlock*>& visited);
609     void buildsets(Function& F);
610     
611     void insertion_pre(Value* e, BasicBlock* BB,
612                        std::map<BasicBlock*, Value*>& avail,
613                       std::map<BasicBlock*, SmallPtrSet<Value*, 16> >& new_set);
614     unsigned insertion_mergepoint(std::vector<Value*>& workList,
615                                   df_iterator<DomTreeNode*>& D,
616                       std::map<BasicBlock*, SmallPtrSet<Value*, 16> >& new_set);
617     bool insertion(Function& F);
618   
619   };
620   
621   char GVNPRE::ID = 0;
622   
623 }
624
625 // createGVNPREPass - The public interface to this file...
626 FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); }
627
628 RegisterPass<GVNPRE> X("gvnpre",
629                        "Global Value Numbering/Partial Redundancy Elimination");
630
631
632 STATISTIC(NumInsertedVals, "Number of values inserted");
633 STATISTIC(NumInsertedPhis, "Number of PHI nodes inserted");
634 STATISTIC(NumEliminated, "Number of redundant instructions eliminated");
635
636 /// find_leader - Given a set and a value number, return the first
637 /// element of the set with that value number, or 0 if no such element
638 /// is present
639 Value* GVNPRE::find_leader(SmallPtrSet<Value*, 16>& vals, uint32_t v) {
640   for (SmallPtrSet<Value*, 16>::iterator I = vals.begin(), E = vals.end();
641        I != E; ++I)
642     if (v == VN.lookup(*I))
643       return *I;
644   
645   return 0;
646 }
647
648 /// val_insert - Insert a value into a set only if there is not a value
649 /// with the same value number already in the set
650 void GVNPRE::val_insert(SmallPtrSet<Value*, 16>& s, Value* v) {
651   uint32_t num = VN.lookup(v);
652   Value* leader = find_leader(s, num);
653   if (leader == 0)
654     s.insert(v);
655 }
656
657 /// val_replace - Insert a value into a set, replacing any values already in
658 /// the set that have the same value number
659 void GVNPRE::val_replace(SmallPtrSet<Value*, 16>& s, Value* v) {
660   uint32_t num = VN.lookup(v);
661   Value* leader = find_leader(s, num);
662   while (leader != 0) {
663     s.erase(leader);
664     leader = find_leader(s, num);
665   }
666   s.insert(v);
667 }
668
669 /// phi_translate - Given a value, its parent block, and a predecessor of its
670 /// parent, translate the value into legal for the predecessor block.  This 
671 /// means translating its operands (and recursively, their operands) through
672 /// any phi nodes in the parent into values available in the predecessor
673 Value* GVNPRE::phi_translate(Value* V, BasicBlock* pred, BasicBlock* succ) {
674   if (V == 0)
675     return 0;
676   
677   // Unary Operations
678   if (CastInst* U = dyn_cast<CastInst>(V)) {
679     Value* newOp1 = 0;
680     if (isa<Instruction>(U->getOperand(0)))
681       newOp1 = phi_translate(U->getOperand(0), pred, succ);
682     else
683       newOp1 = U->getOperand(0);
684     
685     if (newOp1 == 0)
686       return 0;
687     
688     if (newOp1 != U->getOperand(0)) {
689       Instruction* newVal = 0;
690       if (CastInst* C = dyn_cast<CastInst>(U))
691         newVal = CastInst::create(C->getOpcode(),
692                                   newOp1, C->getType(),
693                                   C->getName()+".expr");
694       
695       uint32_t v = VN.lookup_or_add(newVal);
696       
697       Value* leader = find_leader(availableOut[pred], v);
698       if (leader == 0) {
699         createdExpressions.push_back(newVal);
700         return newVal;
701       } else {
702         VN.erase(newVal);
703         delete newVal;
704         return leader;
705       }
706     }
707   
708   // Binary Operations
709   } if (isa<BinaryOperator>(V) || isa<CmpInst>(V) || 
710       isa<ExtractElementInst>(V)) {
711     User* U = cast<User>(V);
712     
713     Value* newOp1 = 0;
714     if (isa<Instruction>(U->getOperand(0)))
715       newOp1 = phi_translate(U->getOperand(0), pred, succ);
716     else
717       newOp1 = U->getOperand(0);
718     
719     if (newOp1 == 0)
720       return 0;
721     
722     Value* newOp2 = 0;
723     if (isa<Instruction>(U->getOperand(1)))
724       newOp2 = phi_translate(U->getOperand(1), pred, succ);
725     else
726       newOp2 = U->getOperand(1);
727     
728     if (newOp2 == 0)
729       return 0;
730     
731     if (newOp1 != U->getOperand(0) || newOp2 != U->getOperand(1)) {
732       Instruction* newVal = 0;
733       if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
734         newVal = BinaryOperator::create(BO->getOpcode(),
735                                         newOp1, newOp2,
736                                         BO->getName()+".expr");
737       else if (CmpInst* C = dyn_cast<CmpInst>(U))
738         newVal = CmpInst::create(C->getOpcode(),
739                                  C->getPredicate(),
740                                  newOp1, newOp2,
741                                  C->getName()+".expr");
742       else if (ExtractElementInst* E = dyn_cast<ExtractElementInst>(U))
743         newVal = new ExtractElementInst(newOp1, newOp2, E->getName()+".expr");
744       
745       uint32_t v = VN.lookup_or_add(newVal);
746       
747       Value* leader = find_leader(availableOut[pred], v);
748       if (leader == 0) {
749         createdExpressions.push_back(newVal);
750         return newVal;
751       } else {
752         VN.erase(newVal);
753         delete newVal;
754         return leader;
755       }
756     }
757   
758   // Ternary Operations
759   } else if (isa<ShuffleVectorInst>(V) || isa<InsertElementInst>(V) ||
760              isa<SelectInst>(V)) {
761     User* U = cast<User>(V);
762     
763     Value* newOp1 = 0;
764     if (isa<Instruction>(U->getOperand(0)))
765       newOp1 = phi_translate(U->getOperand(0), pred, succ);
766     else
767       newOp1 = U->getOperand(0);
768     
769     if (newOp1 == 0)
770       return 0;
771     
772     Value* newOp2 = 0;
773     if (isa<Instruction>(U->getOperand(1)))
774       newOp2 = phi_translate(U->getOperand(1), pred, succ);
775     else
776       newOp2 = U->getOperand(1);
777     
778     if (newOp2 == 0)
779       return 0;
780     
781     Value* newOp3 = 0;
782     if (isa<Instruction>(U->getOperand(2)))
783       newOp3 = phi_translate(U->getOperand(2), pred, succ);
784     else
785       newOp3 = U->getOperand(2);
786     
787     if (newOp3 == 0)
788       return 0;
789     
790     if (newOp1 != U->getOperand(0) ||
791         newOp2 != U->getOperand(1) ||
792         newOp3 != U->getOperand(2)) {
793       Instruction* newVal = 0;
794       if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
795         newVal = new ShuffleVectorInst(newOp1, newOp2, newOp3,
796                                        S->getName()+".expr");
797       else if (InsertElementInst* I = dyn_cast<InsertElementInst>(U))
798         newVal = new InsertElementInst(newOp1, newOp2, newOp3,
799                                        I->getName()+".expr");
800       else if (SelectInst* I = dyn_cast<SelectInst>(U))
801         newVal = new SelectInst(newOp1, newOp2, newOp3, I->getName()+".expr");
802       
803       uint32_t v = VN.lookup_or_add(newVal);
804       
805       Value* leader = find_leader(availableOut[pred], v);
806       if (leader == 0) {
807         createdExpressions.push_back(newVal);
808         return newVal;
809       } else {
810         VN.erase(newVal);
811         delete newVal;
812         return leader;
813       }
814     }
815   
816   // Varargs operators
817   } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
818     Value* newOp1 = 0;
819     if (isa<Instruction>(U->getPointerOperand()))
820       newOp1 = phi_translate(U->getPointerOperand(), pred, succ);
821     else
822       newOp1 = U->getPointerOperand();
823     
824     if (newOp1 == 0)
825       return 0;
826     
827     bool changed_idx = false;
828     std::vector<Value*> newIdx;
829     for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
830          I != E; ++I)
831       if (isa<Instruction>(*I)) {
832         Value* newVal = phi_translate(*I, pred, succ);
833         newIdx.push_back(newVal);
834         if (newVal != *I)
835           changed_idx = true;
836       } else {
837         newIdx.push_back(*I);
838       }
839     
840     if (newOp1 != U->getPointerOperand() || changed_idx) {
841       Instruction* newVal = new GetElementPtrInst(newOp1,
842                                        &newIdx[0], newIdx.size(),
843                                        U->getName()+".expr");
844       
845       uint32_t v = VN.lookup_or_add(newVal);
846       
847       Value* leader = find_leader(availableOut[pred], v);
848       if (leader == 0) {
849         createdExpressions.push_back(newVal);
850         return newVal;
851       } else {
852         VN.erase(newVal);
853         delete newVal;
854         return leader;
855       }
856     }
857   
858   // PHI Nodes
859   } else if (PHINode* P = dyn_cast<PHINode>(V)) {
860     if (P->getParent() == succ)
861       return P->getIncomingValueForBlock(pred);
862   }
863   
864   return V;
865 }
866
867 /// phi_translate_set - Perform phi translation on every element of a set
868 void GVNPRE::phi_translate_set(SmallPtrSet<Value*, 16>& anticIn,
869                               BasicBlock* pred, BasicBlock* succ,
870                               SmallPtrSet<Value*, 16>& out) {
871   for (SmallPtrSet<Value*, 16>::iterator I = anticIn.begin(),
872        E = anticIn.end(); I != E; ++I) {
873     Value* V = phi_translate(*I, pred, succ);
874     if (V != 0)
875       out.insert(V);
876   }
877 }
878
879 /// dependsOnInvoke - Test if a value has an phi node as an operand, any of 
880 /// whose inputs is an invoke instruction.  If this is true, we cannot safely
881 /// PRE the instruction or anything that depends on it.
882 bool GVNPRE::dependsOnInvoke(Value* V) {
883   if (PHINode* p = dyn_cast<PHINode>(V)) {
884     for (PHINode::op_iterator I = p->op_begin(), E = p->op_end(); I != E; ++I)
885       if (isa<InvokeInst>(*I))
886         return true;
887     return false;
888   } else {
889     return false;
890   }
891 }
892
893 /// clean - Remove all non-opaque values from the set whose operands are not
894 /// themselves in the set, as well as all values that depend on invokes (see 
895 /// above)
896 void GVNPRE::clean(SmallPtrSet<Value*, 16>& set, BitVector& presentInSet) {
897   std::vector<Value*> worklist;
898   worklist.reserve(set.size());
899   topo_sort(set, worklist);
900   
901   for (unsigned i = 0; i < worklist.size(); ++i) {
902     Value* v = worklist[i];
903     
904     // Handle unary ops
905     if (CastInst* U = dyn_cast<CastInst>(v)) {
906       bool lhsValid = !isa<Instruction>(U->getOperand(0));
907       lhsValid |= presentInSet.test(VN.lookup(U->getOperand(0)));
908       if (lhsValid)
909         lhsValid = !dependsOnInvoke(U->getOperand(0));
910       
911       if (!lhsValid) {
912         set.erase(U);
913         presentInSet.flip(VN.lookup(U));
914       }
915     
916     // Handle binary ops
917     } else if (isa<BinaryOperator>(v) || isa<CmpInst>(v) ||
918         isa<ExtractElementInst>(v)) {
919       User* U = cast<User>(v);
920       
921       bool lhsValid = !isa<Instruction>(U->getOperand(0));
922       lhsValid |= presentInSet.test(VN.lookup(U->getOperand(0)));
923       if (lhsValid)
924         lhsValid = !dependsOnInvoke(U->getOperand(0));
925     
926       bool rhsValid = !isa<Instruction>(U->getOperand(1));
927       rhsValid |= presentInSet.test(VN.lookup(U->getOperand(1)));
928       if (rhsValid)
929         rhsValid = !dependsOnInvoke(U->getOperand(1));
930       
931       if (!lhsValid || !rhsValid) {
932         set.erase(U);
933         presentInSet.flip(VN.lookup(U));
934       }
935     
936     // Handle ternary ops
937     } else if (isa<ShuffleVectorInst>(v) || isa<InsertElementInst>(v) ||
938                isa<SelectInst>(v)) {
939       User* U = cast<User>(v);
940     
941       bool lhsValid = !isa<Instruction>(U->getOperand(0));
942       lhsValid |= presentInSet.test(VN.lookup(U->getOperand(0)));
943       if (lhsValid)
944         lhsValid = !dependsOnInvoke(U->getOperand(0));
945       
946       bool rhsValid = !isa<Instruction>(U->getOperand(1));
947       rhsValid |= presentInSet.test(VN.lookup(U->getOperand(1)));
948       if (rhsValid)
949         rhsValid = !dependsOnInvoke(U->getOperand(1));
950       
951       bool thirdValid = !isa<Instruction>(U->getOperand(2));
952       thirdValid |= presentInSet.test(VN.lookup(U->getOperand(2)));
953       if (thirdValid)
954         thirdValid = !dependsOnInvoke(U->getOperand(2));
955     
956       if (!lhsValid || !rhsValid || !thirdValid) {
957         set.erase(U);
958         presentInSet.flip(VN.lookup(U));
959       }
960     
961     // Handle varargs ops
962     } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(v)) {
963       bool ptrValid = !isa<Instruction>(U->getPointerOperand());
964       ptrValid |= presentInSet.test(VN.lookup(U->getPointerOperand()));
965       if (ptrValid)
966         ptrValid = !dependsOnInvoke(U->getPointerOperand());
967       
968       bool varValid = true;
969       for (GetElementPtrInst::op_iterator I = U->idx_begin(), E = U->idx_end();
970            I != E; ++I)
971         if (varValid) {
972           varValid &= !isa<Instruction>(*I) || presentInSet.test(VN.lookup(*I));
973           varValid &= !dependsOnInvoke(*I);
974         }
975     
976       if (!ptrValid || !varValid) {
977         set.erase(U);
978         presentInSet.flip(VN.lookup(U));
979       }
980     }
981   }
982 }
983
984 /// topo_sort - Given a set of values, sort them by topological
985 /// order into the provided vector.
986 void GVNPRE::topo_sort(SmallPtrSet<Value*, 16>& set, std::vector<Value*>& vec) {
987   SmallPtrSet<Value*, 16> visited;
988   std::vector<Value*> stack;
989   for (SmallPtrSet<Value*, 16>::iterator I = set.begin(), E = set.end();
990        I != E; ++I) {
991     if (visited.count(*I) == 0)
992       stack.push_back(*I);
993     
994     while (!stack.empty()) {
995       Value* e = stack.back();
996       
997       // Handle unary ops
998       if (CastInst* U = dyn_cast<CastInst>(e)) {
999         Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1000     
1001         if (l != 0 && isa<Instruction>(l) &&
1002             visited.count(l) == 0)
1003           stack.push_back(l);
1004         else {
1005           vec.push_back(e);
1006           visited.insert(e);
1007           stack.pop_back();
1008         }
1009       
1010       // Handle binary ops
1011       } else if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1012           isa<ExtractElementInst>(e)) {
1013         User* U = cast<User>(e);
1014         Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1015         Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
1016     
1017         if (l != 0 && isa<Instruction>(l) &&
1018             visited.count(l) == 0)
1019           stack.push_back(l);
1020         else if (r != 0 && isa<Instruction>(r) &&
1021                  visited.count(r) == 0)
1022           stack.push_back(r);
1023         else {
1024           vec.push_back(e);
1025           visited.insert(e);
1026           stack.pop_back();
1027         }
1028       
1029       // Handle ternary ops
1030       } else if (isa<InsertElementInst>(e) || isa<ShuffleVectorInst>(e) ||
1031                  isa<SelectInst>(e)) {
1032         User* U = cast<User>(e);
1033         Value* l = find_leader(set, VN.lookup(U->getOperand(0)));
1034         Value* r = find_leader(set, VN.lookup(U->getOperand(1)));
1035         Value* m = find_leader(set, VN.lookup(U->getOperand(2)));
1036       
1037         if (l != 0 && isa<Instruction>(l) &&
1038             visited.count(l) == 0)
1039           stack.push_back(l);
1040         else if (r != 0 && isa<Instruction>(r) &&
1041                  visited.count(r) == 0)
1042           stack.push_back(r);
1043         else if (m != 0 && isa<Instruction>(m) &&
1044                  visited.count(m) == 0)
1045           stack.push_back(m);
1046         else {
1047           vec.push_back(e);
1048           visited.insert(e);
1049           stack.pop_back();
1050         }
1051       
1052       // Handle vararg ops
1053       } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(e)) {
1054         Value* p = find_leader(set, VN.lookup(U->getPointerOperand()));
1055         
1056         if (p != 0 && isa<Instruction>(p) &&
1057             visited.count(p) == 0)
1058           stack.push_back(p);
1059         else {
1060           bool push_va = false;
1061           for (GetElementPtrInst::op_iterator I = U->idx_begin(),
1062                E = U->idx_end(); I != E; ++I) {
1063             Value * v = find_leader(set, VN.lookup(*I));
1064             if (v != 0 && isa<Instruction>(v) && visited.count(v) == 0) {
1065               stack.push_back(v);
1066               push_va = true;
1067             }
1068           }
1069           
1070           if (!push_va) {
1071             vec.push_back(e);
1072             visited.insert(e);
1073             stack.pop_back();
1074           }
1075         }
1076       
1077       // Handle opaque ops
1078       } else {
1079         visited.insert(e);
1080         vec.push_back(e);
1081         stack.pop_back();
1082       }
1083     }
1084     
1085     stack.clear();
1086   }
1087 }
1088
1089 /// dump - Dump a set of values to standard error
1090 void GVNPRE::dump(const SmallPtrSet<Value*, 16>& s) const {
1091   DOUT << "{ ";
1092   for (SmallPtrSet<Value*, 16>::iterator I = s.begin(), E = s.end();
1093        I != E; ++I) {
1094     DOUT << "" << VN.lookup(*I) << ": ";
1095     DEBUG((*I)->dump());
1096   }
1097   DOUT << "}\n\n";
1098 }
1099
1100 /// elimination - Phase 3 of the main algorithm.  Perform full redundancy 
1101 /// elimination by walking the dominator tree and removing any instruction that 
1102 /// is dominated by another instruction with the same value number.
1103 bool GVNPRE::elimination() {
1104   DOUT << "\n\nPhase 3: Elimination\n\n";
1105   
1106   bool changed_function = false;
1107   
1108   std::vector<std::pair<Instruction*, Value*> > replace;
1109   std::vector<Instruction*> erase;
1110   
1111   DominatorTree& DT = getAnalysis<DominatorTree>();
1112   
1113   for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1114          E = df_end(DT.getRootNode()); DI != E; ++DI) {
1115     BasicBlock* BB = DI->getBlock();
1116     
1117     //DOUT << "Block: " << BB->getName() << "\n";
1118     //dump(availableOut[BB]);
1119     //DOUT << "\n\n";
1120     
1121     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1122          BI != BE; ++BI) {
1123
1124       if (isa<BinaryOperator>(BI) || isa<CmpInst>(BI) ||
1125           isa<ShuffleVectorInst>(BI) || isa<InsertElementInst>(BI) ||
1126           isa<ExtractElementInst>(BI) || isa<SelectInst>(BI) ||
1127           isa<CastInst>(BI) || isa<GetElementPtrInst>(BI)) {
1128          Value *leader = find_leader(availableOut[BB], VN.lookup(BI));
1129   
1130         if (leader != 0)
1131           if (Instruction* Instr = dyn_cast<Instruction>(leader))
1132             if (Instr->getParent() != 0 && Instr != BI) {
1133               replace.push_back(std::make_pair(BI, leader));
1134               erase.push_back(BI);
1135               ++NumEliminated;
1136             }
1137       }
1138     }
1139   }
1140   
1141   while (!replace.empty()) {
1142     std::pair<Instruction*, Value*> rep = replace.back();
1143     replace.pop_back();
1144     rep.first->replaceAllUsesWith(rep.second);
1145     changed_function = true;
1146   }
1147     
1148   for (std::vector<Instruction*>::iterator I = erase.begin(), E = erase.end();
1149        I != E; ++I)
1150      (*I)->eraseFromParent();
1151   
1152   return changed_function;
1153 }
1154
1155 /// cleanup - Delete any extraneous values that were created to represent
1156 /// expressions without leaders.
1157 void GVNPRE::cleanup() {
1158   while (!createdExpressions.empty()) {
1159     Instruction* I = createdExpressions.back();
1160     createdExpressions.pop_back();
1161     
1162     delete I;
1163   }
1164 }
1165
1166 /// buildsets_availout - When calculating availability, handle an instruction
1167 /// by inserting it into the appropriate sets
1168 void GVNPRE::buildsets_availout(BasicBlock::iterator I,
1169                                 SmallPtrSet<Value*, 16>& currAvail,
1170                                 SmallPtrSet<PHINode*, 16>& currPhis,
1171                                 SmallPtrSet<Value*, 16>& currExps,
1172                                 SmallPtrSet<Value*, 16>& currTemps,
1173                                 BitVector& availNumbers,
1174                                 BitVector& expNumbers) {
1175   // Handle PHI nodes
1176   if (PHINode* p = dyn_cast<PHINode>(I)) {
1177     VN.lookup_or_add(p);
1178     expNumbers.resize(VN.size());
1179     availNumbers.resize(VN.size());
1180     
1181     currPhis.insert(p);
1182   
1183   // Handle unary ops
1184   } else if (CastInst* U = dyn_cast<CastInst>(I)) {
1185     Value* leftValue = U->getOperand(0);
1186     
1187     unsigned num = VN.lookup_or_add(U);
1188     expNumbers.resize(VN.size());
1189     availNumbers.resize(VN.size());
1190       
1191     if (isa<Instruction>(leftValue))
1192       if (!expNumbers.test(VN.lookup(leftValue))) {
1193         currExps.insert(leftValue);
1194         expNumbers.set(VN.lookup(leftValue));
1195       }
1196     
1197     if (!expNumbers.test(VN.lookup(U))) {
1198       currExps.insert(U);
1199       expNumbers.set(num);
1200     }
1201   
1202   // Handle binary ops
1203   } else if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
1204              isa<ExtractElementInst>(I)) {
1205     User* U = cast<User>(I);
1206     Value* leftValue = U->getOperand(0);
1207     Value* rightValue = U->getOperand(1);
1208     
1209     unsigned num = VN.lookup_or_add(U);
1210     expNumbers.resize(VN.size());
1211     availNumbers.resize(VN.size());
1212       
1213     if (isa<Instruction>(leftValue))
1214       if (!expNumbers.test(VN.lookup(leftValue))) {
1215         currExps.insert(leftValue);
1216         expNumbers.set(VN.lookup(leftValue));
1217       }
1218     
1219     if (isa<Instruction>(rightValue))
1220       if (!expNumbers.test(VN.lookup(rightValue))) {
1221         currExps.insert(rightValue);
1222         expNumbers.set(VN.lookup(rightValue));
1223       }
1224     
1225     if (!expNumbers.test(VN.lookup(U))) {
1226       currExps.insert(U);
1227       expNumbers.set(num);
1228     }
1229     
1230   // Handle ternary ops
1231   } else if (isa<InsertElementInst>(I) || isa<ShuffleVectorInst>(I) ||
1232              isa<SelectInst>(I)) {
1233     User* U = cast<User>(I);
1234     Value* leftValue = U->getOperand(0);
1235     Value* rightValue = U->getOperand(1);
1236     Value* thirdValue = U->getOperand(2);
1237       
1238     VN.lookup_or_add(U);
1239     
1240     unsigned num = VN.lookup_or_add(U);
1241     expNumbers.resize(VN.size());
1242     availNumbers.resize(VN.size());
1243     
1244     if (isa<Instruction>(leftValue))
1245       if (!expNumbers.test(VN.lookup(leftValue))) {
1246         currExps.insert(leftValue);
1247         expNumbers.set(VN.lookup(leftValue));
1248       }
1249     if (isa<Instruction>(rightValue))
1250       if (!expNumbers.test(VN.lookup(rightValue))) {
1251         currExps.insert(rightValue);
1252         expNumbers.set(VN.lookup(rightValue));
1253       }
1254     if (isa<Instruction>(thirdValue))
1255       if (!expNumbers.test(VN.lookup(thirdValue))) {
1256         currExps.insert(thirdValue);
1257         expNumbers.set(VN.lookup(thirdValue));
1258       }
1259     
1260     if (!expNumbers.test(VN.lookup(U))) {
1261       currExps.insert(U);
1262       expNumbers.set(num);
1263     }
1264     
1265   // Handle vararg ops
1266   } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(I)) {
1267     Value* ptrValue = U->getPointerOperand();
1268       
1269     VN.lookup_or_add(U);
1270     
1271     unsigned num = VN.lookup_or_add(U);
1272     expNumbers.resize(VN.size());
1273     availNumbers.resize(VN.size());
1274     
1275     if (isa<Instruction>(ptrValue))
1276       if (!expNumbers.test(VN.lookup(ptrValue))) {
1277         currExps.insert(ptrValue);
1278         expNumbers.set(VN.lookup(ptrValue));
1279       }
1280     
1281     for (GetElementPtrInst::op_iterator OI = U->idx_begin(), OE = U->idx_end();
1282          OI != OE; ++OI)
1283       if (isa<Instruction>(*OI) && !expNumbers.test(VN.lookup(*OI))) {
1284         currExps.insert(*OI);
1285         expNumbers.set(VN.lookup(*OI));
1286       }
1287     
1288     if (!expNumbers.test(VN.lookup(U))) {
1289       currExps.insert(U);
1290       expNumbers.set(num);
1291     }
1292     
1293   // Handle opaque ops
1294   } else if (!I->isTerminator()){
1295     VN.lookup_or_add(I);
1296     expNumbers.resize(VN.size());
1297     availNumbers.resize(VN.size());
1298     
1299     currTemps.insert(I);
1300   }
1301     
1302   if (!I->isTerminator())
1303     if (!availNumbers.test(VN.lookup(I))) {
1304       currAvail.insert(I);
1305       availNumbers.set(VN.lookup(I));
1306     }
1307 }
1308
1309 /// buildsets_anticout - When walking the postdom tree, calculate the ANTIC_OUT
1310 /// set as a function of the ANTIC_IN set of the block's predecessors
1311 bool GVNPRE::buildsets_anticout(BasicBlock* BB,
1312                                 SmallPtrSet<Value*, 16>& anticOut,
1313                                 std::set<BasicBlock*>& visited) {
1314   if (BB->getTerminator()->getNumSuccessors() == 1) {
1315     if (BB->getTerminator()->getSuccessor(0) != BB &&
1316         visited.count(BB->getTerminator()->getSuccessor(0)) == 0) {
1317           DOUT << "DEFER: " << BB->getName() << "\n";
1318       return true;
1319     }
1320     else {
1321       phi_translate_set(anticipatedIn[BB->getTerminator()->getSuccessor(0)],
1322                         BB,  BB->getTerminator()->getSuccessor(0), anticOut);
1323     }
1324   } else if (BB->getTerminator()->getNumSuccessors() > 1) {
1325     BasicBlock* first = BB->getTerminator()->getSuccessor(0);
1326     anticOut.insert(anticipatedIn[first].begin(), anticipatedIn[first].end());
1327     
1328     for (unsigned i = 1; i < BB->getTerminator()->getNumSuccessors(); ++i) {
1329       BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i);
1330       SmallPtrSet<Value*, 16>& succAnticIn = anticipatedIn[currSucc];
1331       
1332       std::vector<Value*> temp;
1333       
1334       for (SmallPtrSet<Value*, 16>::iterator I = anticOut.begin(),
1335            E = anticOut.end(); I != E; ++I)
1336         if (find_leader(succAnticIn, VN.lookup(*I)) == 0)
1337           temp.push_back(*I);
1338
1339       for (std::vector<Value*>::iterator I = temp.begin(), E = temp.end();
1340            I != E; ++I)
1341         anticOut.erase(*I);
1342     }
1343   }
1344   
1345   return false;
1346 }
1347
1348 /// buildsets_anticin - Walk the postdom tree, calculating ANTIC_OUT for
1349 /// each block.  ANTIC_IN is then a function of ANTIC_OUT and the GEN
1350 /// sets populated in buildsets_availout
1351 unsigned GVNPRE::buildsets_anticin(BasicBlock* BB,
1352                                SmallPtrSet<Value*, 16>& anticOut,
1353                                SmallPtrSet<Value*, 16>& currExps,
1354                                SmallPtrSet<Value*, 16>& currTemps,
1355                                std::set<BasicBlock*>& visited) {
1356   SmallPtrSet<Value*, 16>& anticIn = anticipatedIn[BB];
1357   unsigned old = anticIn.size();
1358       
1359   bool defer = buildsets_anticout(BB, anticOut, visited);
1360   if (defer)
1361     return 0;
1362   
1363   anticIn.clear();
1364   
1365   BitVector numbers(VN.size());
1366   for (SmallPtrSet<Value*, 16>::iterator I = anticOut.begin(),
1367        E = anticOut.end(); I != E; ++I) {
1368     unsigned num = VN.lookup_or_add(*I);
1369     numbers.resize(VN.size());
1370     
1371     if (isa<Instruction>(*I)) {
1372       anticIn.insert(*I);
1373       numbers.set(num);
1374     }
1375   }
1376   for (SmallPtrSet<Value*, 16>::iterator I = currExps.begin(),
1377        E = currExps.end(); I != E; ++I) {
1378     if (!numbers.test(VN.lookup_or_add(*I))) {
1379       anticIn.insert(*I);
1380       numbers.set(VN.lookup(*I));
1381     }
1382   } 
1383   
1384   for (SmallPtrSet<Value*, 16>::iterator I = currTemps.begin(),
1385        E = currTemps.end(); I != E; ++I) {
1386     anticIn.erase(*I);
1387     numbers.flip(VN.lookup(*I));
1388   }
1389   
1390   clean(anticIn, numbers);
1391   anticOut.clear();
1392   
1393   if (old != anticIn.size())
1394     return 2;
1395   else
1396     return 1;
1397 }
1398
1399 /// buildsets - Phase 1 of the main algorithm.  Construct the AVAIL_OUT
1400 /// and the ANTIC_IN sets.
1401 void GVNPRE::buildsets(Function& F) {
1402   std::map<BasicBlock*, SmallPtrSet<Value*, 16> > generatedExpressions;
1403   std::map<BasicBlock*, SmallPtrSet<PHINode*, 16> > generatedPhis;
1404   std::map<BasicBlock*, SmallPtrSet<Value*, 16> > generatedTemporaries;
1405
1406   DominatorTree &DT = getAnalysis<DominatorTree>();   
1407   
1408   // Phase 1, Part 1: calculate AVAIL_OUT
1409   
1410   // Top-down walk of the dominator tree
1411   for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1412          E = df_end(DT.getRootNode()); DI != E; ++DI) {
1413     
1414     // Get the sets to update for this block
1415     SmallPtrSet<Value*, 16>& currExps = generatedExpressions[DI->getBlock()];
1416     SmallPtrSet<PHINode*, 16>& currPhis = generatedPhis[DI->getBlock()];
1417     SmallPtrSet<Value*, 16>& currTemps = generatedTemporaries[DI->getBlock()];
1418     SmallPtrSet<Value*, 16>& currAvail = availableOut[DI->getBlock()];     
1419     
1420     BasicBlock* BB = DI->getBlock();
1421   
1422     // A block inherits AVAIL_OUT from its dominator
1423     if (DI->getIDom() != 0)
1424     currAvail.insert(availableOut[DI->getIDom()->getBlock()].begin(),
1425                      availableOut[DI->getIDom()->getBlock()].end());
1426     
1427     BitVector availNumbers(VN.size());
1428     for (SmallPtrSet<Value*, 16>::iterator I = currAvail.begin(),
1429         E = currAvail.end(); I != E; ++I)
1430       availNumbers.set(VN.lookup(*I));
1431     
1432     BitVector expNumbers(VN.size());
1433     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1434          BI != BE; ++BI)
1435       buildsets_availout(BI, currAvail, currPhis, currExps,
1436                          currTemps, availNumbers, expNumbers);
1437       
1438   }
1439
1440   // Phase 1, Part 2: calculate ANTIC_IN
1441   
1442   std::set<BasicBlock*> visited;
1443   SmallPtrSet<BasicBlock*, 4> block_changed;
1444   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
1445     block_changed.insert(FI);
1446   
1447   bool changed = true;
1448   unsigned iterations = 0;
1449   
1450   while (changed) {
1451     changed = false;
1452     SmallPtrSet<Value*, 16> anticOut;
1453     
1454     // Postorder walk of the CFG
1455     for (po_iterator<BasicBlock*> BBI = po_begin(&F.getEntryBlock()),
1456          BBE = po_end(&F.getEntryBlock()); BBI != BBE; ++BBI) {
1457       BasicBlock* BB = *BBI;
1458       
1459       if (block_changed.count(BB) != 0) {
1460         unsigned ret = buildsets_anticin(BB, anticOut,generatedExpressions[BB],
1461                                          generatedTemporaries[BB], visited);
1462       
1463         if (ret == 0) {
1464           changed = true;
1465           continue;
1466         } else {
1467           visited.insert(BB);
1468         
1469           if (ret == 2)
1470            for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1471                  PI != PE; ++PI) {
1472               block_changed.insert(*PI);
1473            }
1474           else
1475             block_changed.erase(BB);
1476         
1477           changed |= (ret == 2);
1478         }
1479       }
1480     }
1481     
1482     iterations++;
1483   }
1484   
1485   DOUT << "ITERATIONS: " << iterations << "\n";
1486 }
1487
1488 /// insertion_pre - When a partial redundancy has been identified, eliminate it
1489 /// by inserting appropriate values into the predecessors and a phi node in
1490 /// the main block
1491 void GVNPRE::insertion_pre(Value* e, BasicBlock* BB,
1492                            std::map<BasicBlock*, Value*>& avail,
1493                     std::map<BasicBlock*, SmallPtrSet<Value*, 16> >& new_sets) {
1494   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1495     DOUT << "PRED: " << (*PI)->getName() << "\n";
1496     Value* e2 = avail[*PI];
1497     if (!find_leader(availableOut[*PI], VN.lookup(e2))) {
1498       User* U = cast<User>(e2);
1499       
1500       Value* s1 = 0;
1501       if (isa<BinaryOperator>(U->getOperand(0)) || 
1502           isa<CmpInst>(U->getOperand(0)) ||
1503           isa<ShuffleVectorInst>(U->getOperand(0)) ||
1504           isa<ExtractElementInst>(U->getOperand(0)) ||
1505           isa<InsertElementInst>(U->getOperand(0)) ||
1506           isa<SelectInst>(U->getOperand(0)) ||
1507           isa<CastInst>(U->getOperand(0)) ||
1508           isa<GetElementPtrInst>(U->getOperand(0)))
1509         s1 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(0)));
1510       else
1511         s1 = U->getOperand(0);
1512       
1513       Value* s2 = 0;
1514       
1515       if (isa<BinaryOperator>(U) || 
1516           isa<CmpInst>(U) ||
1517           isa<ShuffleVectorInst>(U) ||
1518           isa<ExtractElementInst>(U) ||
1519           isa<InsertElementInst>(U) ||
1520           isa<SelectInst>(U))
1521         if (isa<BinaryOperator>(U->getOperand(1)) || 
1522             isa<CmpInst>(U->getOperand(1)) ||
1523             isa<ShuffleVectorInst>(U->getOperand(1)) ||
1524             isa<ExtractElementInst>(U->getOperand(1)) ||
1525             isa<InsertElementInst>(U->getOperand(1)) ||
1526             isa<SelectInst>(U->getOperand(1)) ||
1527             isa<CastInst>(U->getOperand(1)) ||
1528             isa<GetElementPtrInst>(U->getOperand(1))) {
1529           s2 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(1)));
1530         } else {
1531           s2 = U->getOperand(1);
1532         }
1533       
1534       // Ternary Operators
1535       Value* s3 = 0;
1536       if (isa<ShuffleVectorInst>(U) ||
1537           isa<InsertElementInst>(U) ||
1538           isa<SelectInst>(U))
1539         if (isa<BinaryOperator>(U->getOperand(2)) || 
1540             isa<CmpInst>(U->getOperand(2)) ||
1541             isa<ShuffleVectorInst>(U->getOperand(2)) ||
1542             isa<ExtractElementInst>(U->getOperand(2)) ||
1543             isa<InsertElementInst>(U->getOperand(2)) ||
1544             isa<SelectInst>(U->getOperand(2)) ||
1545             isa<CastInst>(U->getOperand(2)) ||
1546             isa<GetElementPtrInst>(U->getOperand(2))) {
1547           s3 = find_leader(availableOut[*PI], VN.lookup(U->getOperand(2)));
1548         } else {
1549           s3 = U->getOperand(2);
1550         }
1551       
1552       // Vararg operators
1553       std::vector<Value*> sVarargs;
1554       if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U)) {
1555         for (GetElementPtrInst::op_iterator OI = G->idx_begin(),
1556              OE = G->idx_end(); OI != OE; ++OI) {
1557           if (isa<BinaryOperator>(*OI) || 
1558               isa<CmpInst>(*OI) ||
1559               isa<ShuffleVectorInst>(*OI) ||
1560               isa<ExtractElementInst>(*OI) ||
1561               isa<InsertElementInst>(*OI) ||
1562               isa<SelectInst>(*OI) ||
1563               isa<CastInst>(*OI) ||
1564               isa<GetElementPtrInst>(*OI)) {
1565             sVarargs.push_back(find_leader(availableOut[*PI], 
1566                                VN.lookup(*OI)));
1567           } else {
1568             sVarargs.push_back(*OI);
1569           }
1570         }
1571       }
1572       
1573       Value* newVal = 0;
1574       if (BinaryOperator* BO = dyn_cast<BinaryOperator>(U))
1575         newVal = BinaryOperator::create(BO->getOpcode(), s1, s2,
1576                                         BO->getName()+".gvnpre",
1577                                         (*PI)->getTerminator());
1578       else if (CmpInst* C = dyn_cast<CmpInst>(U))
1579         newVal = CmpInst::create(C->getOpcode(), C->getPredicate(), s1, s2,
1580                                  C->getName()+".gvnpre", 
1581                                  (*PI)->getTerminator());
1582       else if (ShuffleVectorInst* S = dyn_cast<ShuffleVectorInst>(U))
1583         newVal = new ShuffleVectorInst(s1, s2, s3, S->getName()+".gvnpre",
1584                                        (*PI)->getTerminator());
1585       else if (InsertElementInst* S = dyn_cast<InsertElementInst>(U))
1586         newVal = new InsertElementInst(s1, s2, s3, S->getName()+".gvnpre",
1587                                        (*PI)->getTerminator());
1588       else if (ExtractElementInst* S = dyn_cast<ExtractElementInst>(U))
1589         newVal = new ExtractElementInst(s1, s2, S->getName()+".gvnpre",
1590                                         (*PI)->getTerminator());
1591       else if (SelectInst* S = dyn_cast<SelectInst>(U))
1592         newVal = new SelectInst(s1, s2, s3, S->getName()+".gvnpre",
1593                                 (*PI)->getTerminator());
1594       else if (CastInst* C = dyn_cast<CastInst>(U))
1595         newVal = CastInst::create(C->getOpcode(), s1, C->getType(),
1596                                   C->getName()+".gvnpre", 
1597                                   (*PI)->getTerminator());
1598       else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(U))
1599         newVal = new GetElementPtrInst(s1, &sVarargs[0], sVarargs.size(), 
1600                                        G->getName()+".gvnpre", 
1601                                        (*PI)->getTerminator());
1602                                 
1603                   
1604       VN.add(newVal, VN.lookup(U));
1605                   
1606       SmallPtrSet<Value*, 16>& predAvail = availableOut[*PI];
1607       val_replace(predAvail, newVal);
1608       val_replace(new_sets[*PI], newVal);
1609             
1610       std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1611       if (av != avail.end())
1612         avail.erase(av);
1613       avail.insert(std::make_pair(*PI, newVal));
1614                   
1615       ++NumInsertedVals;
1616     }
1617   }
1618               
1619   PHINode* p = 0;
1620               
1621   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
1622     if (p == 0)
1623       p = new PHINode(avail[*PI]->getType(), "gvnpre-join", BB->begin());
1624     
1625     p->addIncoming(avail[*PI], *PI);
1626   }
1627
1628   VN.add(p, VN.lookup(e));
1629   val_replace(availableOut[BB], p);
1630   new_sets[BB].insert(p);
1631               
1632   ++NumInsertedPhis;
1633 }
1634
1635 /// insertion_mergepoint - When walking the dom tree, check at each merge
1636 /// block for the possibility of a partial redundancy.  If present, eliminate it
1637 unsigned GVNPRE::insertion_mergepoint(std::vector<Value*>& workList,
1638                                       df_iterator<DomTreeNode*>& D,
1639                     std::map<BasicBlock*, SmallPtrSet<Value*, 16> >& new_sets) {
1640   bool changed_function = false;
1641   bool new_stuff = false;
1642   
1643   BasicBlock* BB = D->getBlock();
1644   for (unsigned i = 0; i < workList.size(); ++i) {
1645     Value* e = workList[i];
1646           
1647     if (isa<BinaryOperator>(e) || isa<CmpInst>(e) ||
1648         isa<ExtractElementInst>(e) || isa<InsertElementInst>(e) ||
1649         isa<ShuffleVectorInst>(e) || isa<SelectInst>(e) || isa<CastInst>(e) ||
1650         isa<GetElementPtrInst>(e)) {
1651       if (find_leader(availableOut[D->getIDom()->getBlock()],
1652                       VN.lookup(e)) != 0)
1653         continue;
1654             
1655       std::map<BasicBlock*, Value*> avail;
1656       bool by_some = false;
1657       int num_avail = 0;
1658             
1659       for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;
1660            ++PI) {
1661         Value *e2 = phi_translate(e, *PI, BB);
1662         Value *e3 = find_leader(availableOut[*PI], VN.lookup(e2));
1663               
1664         if (e3 == 0) {
1665           std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1666           if (av != avail.end())
1667             avail.erase(av);
1668           avail.insert(std::make_pair(*PI, e2));
1669         } else {
1670           std::map<BasicBlock*, Value*>::iterator av = avail.find(*PI);
1671           if (av != avail.end())
1672             avail.erase(av);
1673           avail.insert(std::make_pair(*PI, e3));
1674                 
1675           by_some = true;
1676           num_avail++;
1677         }
1678       }
1679             
1680       if (by_some && num_avail < std::distance(pred_begin(BB), pred_end(BB))) {
1681         insertion_pre(e, BB, avail, new_sets);
1682               
1683         changed_function = true;
1684         new_stuff = true;
1685       }
1686     }
1687   }
1688   
1689   unsigned retval = 0;
1690   if (changed_function)
1691     retval += 1;
1692   if (new_stuff)
1693     retval += 2;
1694   
1695   return retval;
1696 }
1697
1698 /// insert - Phase 2 of the main algorithm.  Walk the dominator tree looking for
1699 /// merge points.  When one is found, check for a partial redundancy.  If one is
1700 /// present, eliminate it.  Repeat this walk until no changes are made.
1701 bool GVNPRE::insertion(Function& F) {
1702   bool changed_function = false;
1703
1704   DominatorTree &DT = getAnalysis<DominatorTree>();  
1705   
1706   std::map<BasicBlock*, SmallPtrSet<Value*, 16> > new_sets;
1707   bool new_stuff = true;
1708   while (new_stuff) {
1709     new_stuff = false;
1710     for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1711          E = df_end(DT.getRootNode()); DI != E; ++DI) {
1712       BasicBlock* BB = DI->getBlock();
1713       
1714       if (BB == 0)
1715         continue;
1716       
1717       SmallPtrSet<Value*, 16>& availOut = availableOut[BB];
1718       SmallPtrSet<Value*, 16>& anticIn = anticipatedIn[BB];
1719       
1720       // Replace leaders with leaders inherited from dominator
1721       if (DI->getIDom() != 0) {
1722         SmallPtrSet<Value*, 16>& dom_set = new_sets[DI->getIDom()->getBlock()];
1723         for (SmallPtrSet<Value*, 16>::iterator I = dom_set.begin(),
1724              E = dom_set.end(); I != E; ++I) {
1725           val_replace(new_sets[BB], *I);
1726           val_replace(availOut, *I);
1727         }
1728       }
1729       
1730       // If there is more than one predecessor...
1731       if (pred_begin(BB) != pred_end(BB) && ++pred_begin(BB) != pred_end(BB)) {
1732         std::vector<Value*> workList;
1733         workList.reserve(anticIn.size());
1734         topo_sort(anticIn, workList);
1735         
1736         unsigned result = insertion_mergepoint(workList, DI, new_sets);
1737         if (result & 1)
1738           changed_function = true;
1739         if (result & 2)
1740           new_stuff = true;
1741       }
1742     }
1743   }
1744   
1745   return changed_function;
1746 }
1747
1748 // GVNPRE::runOnFunction - This is the main transformation entry point for a
1749 // function.
1750 //
1751 bool GVNPRE::runOnFunction(Function &F) {
1752   // Clean out global sets from any previous functions
1753   VN.clear();
1754   createdExpressions.clear();
1755   availableOut.clear();
1756   anticipatedIn.clear();
1757   
1758   bool changed_function = false;
1759   
1760   // Phase 1: BuildSets
1761   // This phase calculates the AVAIL_OUT and ANTIC_IN sets
1762   buildsets(F);
1763   
1764   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
1765     DOUT << "ANTIC_IN: " << FI->getName() << "\n";
1766     dump(anticipatedIn[FI]);
1767     DOUT << "\n\n";
1768   }
1769   
1770   // Phase 2: Insert
1771   // This phase inserts values to make partially redundant values
1772   // fully redundant
1773   changed_function |= insertion(F);
1774   
1775   // Phase 3: Eliminate
1776   // This phase performs trivial full redundancy elimination
1777   changed_function |= elimination();
1778   
1779   // Phase 4: Cleanup
1780   // This phase cleans up values that were created solely
1781   // as leaders for expressions
1782   cleanup();
1783   
1784   return changed_function;
1785 }