Allow GVN to eliminate redundant calls to functions without side effects.
[oota-llvm.git] / lib / Transforms / Scalar / GVN.cpp
1 //===- GVN.cpp - Eliminate redundant values and loads ------------===//
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 global value numbering to eliminate fully redundant
11 // instructions.  It also performs simple dead load elimination.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "gvn"
16
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/BasicBlock.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Value.h"
24 #include "llvm/ADT/BitVector.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/DepthFirstIterator.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Analysis/Dominators.h"
31 #include "llvm/Analysis/AliasAnalysis.h"
32 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/Compiler.h"
35 using namespace llvm;
36
37 //===----------------------------------------------------------------------===//
38 //                         ValueTable Class
39 //===----------------------------------------------------------------------===//
40
41 /// This class holds the mapping between values and value numbers.  It is used
42 /// as an efficient mechanism to determine the expression-wise equivalence of
43 /// two values.
44 namespace {
45   struct VISIBILITY_HIDDEN Expression {
46     enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM, 
47                             FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ, 
48                             ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE, 
49                             ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ, 
50                             FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE, 
51                             FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE, 
52                             FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
53                             SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
54                             FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT, 
55                             PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
56                             TOMBSTONE };
57
58     ExpressionOpcode opcode;
59     const Type* type;
60     uint32_t firstVN;
61     uint32_t secondVN;
62     uint32_t thirdVN;
63     SmallVector<uint32_t, 4> varargs;
64     Value* function;
65   
66     Expression() { }
67     Expression(ExpressionOpcode o) : opcode(o) { }
68   
69     bool operator==(const Expression &other) const {
70       if (opcode != other.opcode)
71         return false;
72       else if (opcode == EMPTY || opcode == TOMBSTONE)
73         return true;
74       else if (type != other.type)
75         return false;
76       else if (function != other.function)
77         return false;
78       else if (firstVN != other.firstVN)
79         return false;
80       else if (secondVN != other.secondVN)
81         return false;
82       else if (thirdVN != other.thirdVN)
83         return false;
84       else {
85         if (varargs.size() != other.varargs.size())
86           return false;
87       
88         for (size_t i = 0; i < varargs.size(); ++i)
89           if (varargs[i] != other.varargs[i])
90             return false;
91     
92         return true;
93       }
94     }
95   
96     bool operator!=(const Expression &other) const {
97       if (opcode != other.opcode)
98         return true;
99       else if (opcode == EMPTY || opcode == TOMBSTONE)
100         return false;
101       else if (type != other.type)
102         return true;
103       else if (function != other.function)
104         return true;
105       else if (firstVN != other.firstVN)
106         return true;
107       else if (secondVN != other.secondVN)
108         return true;
109       else if (thirdVN != other.thirdVN)
110         return true;
111       else {
112         if (varargs.size() != other.varargs.size())
113           return true;
114       
115         for (size_t i = 0; i < varargs.size(); ++i)
116           if (varargs[i] != other.varargs[i])
117             return true;
118     
119           return false;
120       }
121     }
122   };
123   
124   class VISIBILITY_HIDDEN ValueTable {
125     private:
126       DenseMap<Value*, uint32_t> valueNumbering;
127       DenseMap<Expression, uint32_t> expressionNumbering;
128       AliasAnalysis* AA;
129   
130       uint32_t nextValueNumber;
131     
132       Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
133       Expression::ExpressionOpcode getOpcode(CmpInst* C);
134       Expression::ExpressionOpcode getOpcode(CastInst* C);
135       Expression create_expression(BinaryOperator* BO);
136       Expression create_expression(CmpInst* C);
137       Expression create_expression(ShuffleVectorInst* V);
138       Expression create_expression(ExtractElementInst* C);
139       Expression create_expression(InsertElementInst* V);
140       Expression create_expression(SelectInst* V);
141       Expression create_expression(CastInst* C);
142       Expression create_expression(GetElementPtrInst* G);
143       Expression create_expression(CallInst* C);
144     public:
145       ValueTable() : nextValueNumber(1) { }
146       uint32_t lookup_or_add(Value* V);
147       uint32_t lookup(Value* V) const;
148       void add(Value* V, uint32_t num);
149       void clear();
150       void erase(Value* v);
151       unsigned size();
152       void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
153   };
154 }
155
156 namespace llvm {
157 template <> struct DenseMapInfo<Expression> {
158   static inline Expression getEmptyKey() {
159     return Expression(Expression::EMPTY);
160   }
161   
162   static inline Expression getTombstoneKey() {
163     return Expression(Expression::TOMBSTONE);
164   }
165   
166   static unsigned getHashValue(const Expression e) {
167     unsigned hash = e.opcode;
168     
169     hash = e.firstVN + hash * 37;
170     hash = e.secondVN + hash * 37;
171     hash = e.thirdVN + hash * 37;
172     
173     hash = (unsigned)((uintptr_t)e.type >> 4) ^
174             (unsigned)((uintptr_t)e.type >> 9) +
175             hash * 37;
176     
177     for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
178          E = e.varargs.end(); I != E; ++I)
179       hash = *I + hash * 37;
180     
181     hash = (unsigned)((uintptr_t)e.function >> 4) ^
182             (unsigned)((uintptr_t)e.function >> 9) +
183             hash * 37;
184     
185     return hash;
186   }
187   static bool isEqual(const Expression &LHS, const Expression &RHS) {
188     return LHS == RHS;
189   }
190   static bool isPod() { return true; }
191 };
192 }
193
194 //===----------------------------------------------------------------------===//
195 //                     ValueTable Internal Functions
196 //===----------------------------------------------------------------------===//
197 Expression::ExpressionOpcode 
198                              ValueTable::getOpcode(BinaryOperator* BO) {
199   switch(BO->getOpcode()) {
200     case Instruction::Add:
201       return Expression::ADD;
202     case Instruction::Sub:
203       return Expression::SUB;
204     case Instruction::Mul:
205       return Expression::MUL;
206     case Instruction::UDiv:
207       return Expression::UDIV;
208     case Instruction::SDiv:
209       return Expression::SDIV;
210     case Instruction::FDiv:
211       return Expression::FDIV;
212     case Instruction::URem:
213       return Expression::UREM;
214     case Instruction::SRem:
215       return Expression::SREM;
216     case Instruction::FRem:
217       return Expression::FREM;
218     case Instruction::Shl:
219       return Expression::SHL;
220     case Instruction::LShr:
221       return Expression::LSHR;
222     case Instruction::AShr:
223       return Expression::ASHR;
224     case Instruction::And:
225       return Expression::AND;
226     case Instruction::Or:
227       return Expression::OR;
228     case Instruction::Xor:
229       return Expression::XOR;
230     
231     // THIS SHOULD NEVER HAPPEN
232     default:
233       assert(0 && "Binary operator with unknown opcode?");
234       return Expression::ADD;
235   }
236 }
237
238 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
239   if (C->getOpcode() == Instruction::ICmp) {
240     switch (C->getPredicate()) {
241       case ICmpInst::ICMP_EQ:
242         return Expression::ICMPEQ;
243       case ICmpInst::ICMP_NE:
244         return Expression::ICMPNE;
245       case ICmpInst::ICMP_UGT:
246         return Expression::ICMPUGT;
247       case ICmpInst::ICMP_UGE:
248         return Expression::ICMPUGE;
249       case ICmpInst::ICMP_ULT:
250         return Expression::ICMPULT;
251       case ICmpInst::ICMP_ULE:
252         return Expression::ICMPULE;
253       case ICmpInst::ICMP_SGT:
254         return Expression::ICMPSGT;
255       case ICmpInst::ICMP_SGE:
256         return Expression::ICMPSGE;
257       case ICmpInst::ICMP_SLT:
258         return Expression::ICMPSLT;
259       case ICmpInst::ICMP_SLE:
260         return Expression::ICMPSLE;
261       
262       // THIS SHOULD NEVER HAPPEN
263       default:
264         assert(0 && "Comparison with unknown predicate?");
265         return Expression::ICMPEQ;
266     }
267   } else {
268     switch (C->getPredicate()) {
269       case FCmpInst::FCMP_OEQ:
270         return Expression::FCMPOEQ;
271       case FCmpInst::FCMP_OGT:
272         return Expression::FCMPOGT;
273       case FCmpInst::FCMP_OGE:
274         return Expression::FCMPOGE;
275       case FCmpInst::FCMP_OLT:
276         return Expression::FCMPOLT;
277       case FCmpInst::FCMP_OLE:
278         return Expression::FCMPOLE;
279       case FCmpInst::FCMP_ONE:
280         return Expression::FCMPONE;
281       case FCmpInst::FCMP_ORD:
282         return Expression::FCMPORD;
283       case FCmpInst::FCMP_UNO:
284         return Expression::FCMPUNO;
285       case FCmpInst::FCMP_UEQ:
286         return Expression::FCMPUEQ;
287       case FCmpInst::FCMP_UGT:
288         return Expression::FCMPUGT;
289       case FCmpInst::FCMP_UGE:
290         return Expression::FCMPUGE;
291       case FCmpInst::FCMP_ULT:
292         return Expression::FCMPULT;
293       case FCmpInst::FCMP_ULE:
294         return Expression::FCMPULE;
295       case FCmpInst::FCMP_UNE:
296         return Expression::FCMPUNE;
297       
298       // THIS SHOULD NEVER HAPPEN
299       default:
300         assert(0 && "Comparison with unknown predicate?");
301         return Expression::FCMPOEQ;
302     }
303   }
304 }
305
306 Expression::ExpressionOpcode 
307                              ValueTable::getOpcode(CastInst* C) {
308   switch(C->getOpcode()) {
309     case Instruction::Trunc:
310       return Expression::TRUNC;
311     case Instruction::ZExt:
312       return Expression::ZEXT;
313     case Instruction::SExt:
314       return Expression::SEXT;
315     case Instruction::FPToUI:
316       return Expression::FPTOUI;
317     case Instruction::FPToSI:
318       return Expression::FPTOSI;
319     case Instruction::UIToFP:
320       return Expression::UITOFP;
321     case Instruction::SIToFP:
322       return Expression::SITOFP;
323     case Instruction::FPTrunc:
324       return Expression::FPTRUNC;
325     case Instruction::FPExt:
326       return Expression::FPEXT;
327     case Instruction::PtrToInt:
328       return Expression::PTRTOINT;
329     case Instruction::IntToPtr:
330       return Expression::INTTOPTR;
331     case Instruction::BitCast:
332       return Expression::BITCAST;
333     
334     // THIS SHOULD NEVER HAPPEN
335     default:
336       assert(0 && "Cast operator with unknown opcode?");
337       return Expression::BITCAST;
338   }
339 }
340
341 Expression ValueTable::create_expression(CallInst* C) {
342   Expression e;
343   
344   e.type = C->getType();
345   e.firstVN = 0;
346   e.secondVN = 0;
347   e.thirdVN = 0;
348   e.function = C->getCalledFunction();
349   e.opcode = Expression::CALL;
350   
351   for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
352        I != E; ++I)
353     e.varargs.push_back(lookup_or_add(*I));
354   
355   return e;
356 }
357
358 Expression ValueTable::create_expression(BinaryOperator* BO) {
359   Expression e;
360     
361   e.firstVN = lookup_or_add(BO->getOperand(0));
362   e.secondVN = lookup_or_add(BO->getOperand(1));
363   e.thirdVN = 0;
364   e.function = 0;
365   e.type = BO->getType();
366   e.opcode = getOpcode(BO);
367   
368   return e;
369 }
370
371 Expression ValueTable::create_expression(CmpInst* C) {
372   Expression e;
373     
374   e.firstVN = lookup_or_add(C->getOperand(0));
375   e.secondVN = lookup_or_add(C->getOperand(1));
376   e.thirdVN = 0;
377   e.function = 0;
378   e.type = C->getType();
379   e.opcode = getOpcode(C);
380   
381   return e;
382 }
383
384 Expression ValueTable::create_expression(CastInst* C) {
385   Expression e;
386     
387   e.firstVN = lookup_or_add(C->getOperand(0));
388   e.secondVN = 0;
389   e.thirdVN = 0;
390   e.function = 0;
391   e.type = C->getType();
392   e.opcode = getOpcode(C);
393   
394   return e;
395 }
396
397 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
398   Expression e;
399     
400   e.firstVN = lookup_or_add(S->getOperand(0));
401   e.secondVN = lookup_or_add(S->getOperand(1));
402   e.thirdVN = lookup_or_add(S->getOperand(2));
403   e.function = 0;
404   e.type = S->getType();
405   e.opcode = Expression::SHUFFLE;
406   
407   return e;
408 }
409
410 Expression ValueTable::create_expression(ExtractElementInst* E) {
411   Expression e;
412     
413   e.firstVN = lookup_or_add(E->getOperand(0));
414   e.secondVN = lookup_or_add(E->getOperand(1));
415   e.thirdVN = 0;
416   e.function = 0;
417   e.type = E->getType();
418   e.opcode = Expression::EXTRACT;
419   
420   return e;
421 }
422
423 Expression ValueTable::create_expression(InsertElementInst* I) {
424   Expression e;
425     
426   e.firstVN = lookup_or_add(I->getOperand(0));
427   e.secondVN = lookup_or_add(I->getOperand(1));
428   e.thirdVN = lookup_or_add(I->getOperand(2));
429   e.function = 0;
430   e.type = I->getType();
431   e.opcode = Expression::INSERT;
432   
433   return e;
434 }
435
436 Expression ValueTable::create_expression(SelectInst* I) {
437   Expression e;
438     
439   e.firstVN = lookup_or_add(I->getCondition());
440   e.secondVN = lookup_or_add(I->getTrueValue());
441   e.thirdVN = lookup_or_add(I->getFalseValue());
442   e.function = 0;
443   e.type = I->getType();
444   e.opcode = Expression::SELECT;
445   
446   return e;
447 }
448
449 Expression ValueTable::create_expression(GetElementPtrInst* G) {
450   Expression e;
451     
452   e.firstVN = lookup_or_add(G->getPointerOperand());
453   e.secondVN = 0;
454   e.thirdVN = 0;
455   e.function = 0;
456   e.type = G->getType();
457   e.opcode = Expression::GEP;
458   
459   for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
460        I != E; ++I)
461     e.varargs.push_back(lookup_or_add(*I));
462   
463   return e;
464 }
465
466 //===----------------------------------------------------------------------===//
467 //                     ValueTable External Functions
468 //===----------------------------------------------------------------------===//
469
470 /// lookup_or_add - Returns the value number for the specified value, assigning
471 /// it a new number if it did not have one before.
472 uint32_t ValueTable::lookup_or_add(Value* V) {
473   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
474   if (VI != valueNumbering.end())
475     return VI->second;
476   
477   if (CallInst* C = dyn_cast<CallInst>(V)) {
478     if (C->getCalledFunction() &&
479         AA->doesNotAccessMemory(C->getCalledFunction())) {
480       Expression e = create_expression(C);
481     
482       DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
483       if (EI != expressionNumbering.end()) {
484         valueNumbering.insert(std::make_pair(V, EI->second));
485         return EI->second;
486       } else {
487         expressionNumbering.insert(std::make_pair(e, nextValueNumber));
488         valueNumbering.insert(std::make_pair(V, nextValueNumber));
489       
490         return nextValueNumber++;
491       }
492     } else {
493       valueNumbering.insert(std::make_pair(V, nextValueNumber));
494       return nextValueNumber++;
495     }
496   } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
497     Expression e = create_expression(BO);
498     
499     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
500     if (EI != expressionNumbering.end()) {
501       valueNumbering.insert(std::make_pair(V, EI->second));
502       return EI->second;
503     } else {
504       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
505       valueNumbering.insert(std::make_pair(V, nextValueNumber));
506       
507       return nextValueNumber++;
508     }
509   } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
510     Expression e = create_expression(C);
511     
512     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
513     if (EI != expressionNumbering.end()) {
514       valueNumbering.insert(std::make_pair(V, EI->second));
515       return EI->second;
516     } else {
517       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
518       valueNumbering.insert(std::make_pair(V, nextValueNumber));
519       
520       return nextValueNumber++;
521     }
522   } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
523     Expression e = create_expression(U);
524     
525     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
526     if (EI != expressionNumbering.end()) {
527       valueNumbering.insert(std::make_pair(V, EI->second));
528       return EI->second;
529     } else {
530       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
531       valueNumbering.insert(std::make_pair(V, nextValueNumber));
532       
533       return nextValueNumber++;
534     }
535   } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
536     Expression e = create_expression(U);
537     
538     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
539     if (EI != expressionNumbering.end()) {
540       valueNumbering.insert(std::make_pair(V, EI->second));
541       return EI->second;
542     } else {
543       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
544       valueNumbering.insert(std::make_pair(V, nextValueNumber));
545       
546       return nextValueNumber++;
547     }
548   } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
549     Expression e = create_expression(U);
550     
551     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
552     if (EI != expressionNumbering.end()) {
553       valueNumbering.insert(std::make_pair(V, EI->second));
554       return EI->second;
555     } else {
556       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
557       valueNumbering.insert(std::make_pair(V, nextValueNumber));
558       
559       return nextValueNumber++;
560     }
561   } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
562     Expression e = create_expression(U);
563     
564     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
565     if (EI != expressionNumbering.end()) {
566       valueNumbering.insert(std::make_pair(V, EI->second));
567       return EI->second;
568     } else {
569       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
570       valueNumbering.insert(std::make_pair(V, nextValueNumber));
571       
572       return nextValueNumber++;
573     }
574   } else if (CastInst* U = dyn_cast<CastInst>(V)) {
575     Expression e = create_expression(U);
576     
577     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
578     if (EI != expressionNumbering.end()) {
579       valueNumbering.insert(std::make_pair(V, EI->second));
580       return EI->second;
581     } else {
582       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
583       valueNumbering.insert(std::make_pair(V, nextValueNumber));
584       
585       return nextValueNumber++;
586     }
587   } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
588     Expression e = create_expression(U);
589     
590     DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
591     if (EI != expressionNumbering.end()) {
592       valueNumbering.insert(std::make_pair(V, EI->second));
593       return EI->second;
594     } else {
595       expressionNumbering.insert(std::make_pair(e, nextValueNumber));
596       valueNumbering.insert(std::make_pair(V, nextValueNumber));
597       
598       return nextValueNumber++;
599     }
600   } else {
601     valueNumbering.insert(std::make_pair(V, nextValueNumber));
602     return nextValueNumber++;
603   }
604 }
605
606 /// lookup - Returns the value number of the specified value. Fails if
607 /// the value has not yet been numbered.
608 uint32_t ValueTable::lookup(Value* V) const {
609   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
610   if (VI != valueNumbering.end())
611     return VI->second;
612   else
613     assert(0 && "Value not numbered?");
614   
615   return 0;
616 }
617
618 /// clear - Remove all entries from the ValueTable
619 void ValueTable::clear() {
620   valueNumbering.clear();
621   expressionNumbering.clear();
622   nextValueNumber = 1;
623 }
624
625 /// erase - Remove a value from the value numbering
626 void ValueTable::erase(Value* V) {
627   valueNumbering.erase(V);
628 }
629
630 //===----------------------------------------------------------------------===//
631 //                       ValueNumberedSet Class
632 //===----------------------------------------------------------------------===//
633 namespace {
634 class ValueNumberedSet {
635   private:
636     SmallPtrSet<Value*, 8> contents;
637     BitVector numbers;
638   public:
639     ValueNumberedSet() { numbers.resize(1); }
640     ValueNumberedSet(const ValueNumberedSet& other) {
641       numbers = other.numbers;
642       contents = other.contents;
643     }
644     
645     typedef SmallPtrSet<Value*, 8>::iterator iterator;
646     
647     iterator begin() { return contents.begin(); }
648     iterator end() { return contents.end(); }
649     
650     bool insert(Value* v) { return contents.insert(v); }
651     void insert(iterator I, iterator E) { contents.insert(I, E); }
652     void erase(Value* v) { contents.erase(v); }
653     unsigned count(Value* v) { return contents.count(v); }
654     size_t size() { return contents.size(); }
655     
656     void set(unsigned i)  {
657       if (i >= numbers.size())
658         numbers.resize(i+1);
659       
660       numbers.set(i);
661     }
662     
663     void operator=(const ValueNumberedSet& other) {
664       contents = other.contents;
665       numbers = other.numbers;
666     }
667     
668     void reset(unsigned i)  {
669       if (i < numbers.size())
670         numbers.reset(i);
671     }
672     
673     bool test(unsigned i)  {
674       if (i >= numbers.size())
675         return false;
676       
677       return numbers.test(i);
678     }
679     
680     void clear() {
681       contents.clear();
682       numbers.clear();
683     }
684 };
685 }
686
687 //===----------------------------------------------------------------------===//
688 //                         GVN Pass
689 //===----------------------------------------------------------------------===//
690
691 namespace {
692
693   class VISIBILITY_HIDDEN GVN : public FunctionPass {
694     bool runOnFunction(Function &F);
695   public:
696     static char ID; // Pass identification, replacement for typeid
697     GVN() : FunctionPass((intptr_t)&ID) { }
698
699   private:
700     ValueTable VN;
701     
702     DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
703     
704     typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
705     PhiMapType phiMap;
706     
707     
708     // This transformation requires dominator postdominator info
709     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
710       AU.setPreservesCFG();
711       AU.addRequired<DominatorTree>();
712       AU.addRequired<MemoryDependenceAnalysis>();
713       AU.addRequired<AliasAnalysis>();
714       AU.addPreserved<AliasAnalysis>();
715       AU.addPreserved<MemoryDependenceAnalysis>();
716     }
717   
718     // Helper fuctions
719     // FIXME: eliminate or document these better
720     Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
721     void val_insert(ValueNumberedSet& s, Value* v);
722     bool processLoad(LoadInst* L,
723                      DenseMap<Value*, LoadInst*>& lastLoad,
724                      SmallVector<Instruction*, 4>& toErase);
725     bool processInstruction(Instruction* I,
726                             ValueNumberedSet& currAvail,
727                             DenseMap<Value*, LoadInst*>& lastSeenLoad,
728                             SmallVector<Instruction*, 4>& toErase);
729     bool processNonLocalLoad(LoadInst* L,
730                              SmallVector<Instruction*, 4>& toErase);
731     Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
732                             DenseMap<BasicBlock*, Value*> &Phis,
733                             bool top_level = false);
734     void dump(DenseMap<BasicBlock*, Value*>& d);
735     bool iterateOnFunction(Function &F);
736     Value* CollapsePhi(PHINode* p);
737     bool isSafeReplacement(PHINode* p, Instruction* inst);
738   };
739   
740   char GVN::ID = 0;
741   
742 }
743
744 // createGVNPass - The public interface to this file...
745 FunctionPass *llvm::createGVNPass() { return new GVN(); }
746
747 static RegisterPass<GVN> X("gvn",
748                            "Global Value Numbering");
749
750 STATISTIC(NumGVNInstr, "Number of instructions deleted");
751 STATISTIC(NumGVNLoad, "Number of loads deleted");
752
753 /// find_leader - Given a set and a value number, return the first
754 /// element of the set with that value number, or 0 if no such element
755 /// is present
756 Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
757   if (!vals.test(v))
758     return 0;
759   
760   for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
761        I != E; ++I)
762     if (v == VN.lookup(*I))
763       return *I;
764   
765   assert(0 && "No leader found, but present bit is set?");
766   return 0;
767 }
768
769 /// val_insert - Insert a value into a set only if there is not a value
770 /// with the same value number already in the set
771 void GVN::val_insert(ValueNumberedSet& s, Value* v) {
772   uint32_t num = VN.lookup(v);
773   if (!s.test(num))
774     s.insert(v);
775 }
776
777 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
778   printf("{\n");
779   for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
780        E = d.end(); I != E; ++I) {
781     if (I->second == MemoryDependenceAnalysis::None)
782       printf("None\n");
783     else
784       I->second->dump();
785   }
786   printf("}\n");
787 }
788
789 Value* GVN::CollapsePhi(PHINode* p) {
790   DominatorTree &DT = getAnalysis<DominatorTree>();
791   Value* constVal = p->hasConstantValue();
792   
793   if (constVal) {
794     if (Instruction* inst = dyn_cast<Instruction>(constVal)) {
795       if (DT.dominates(inst, p))
796         if (isSafeReplacement(p, inst))
797           return inst;
798     } else {
799       return constVal;
800     }
801   }
802   
803   return 0;
804 }
805
806 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
807   if (!isa<PHINode>(inst))
808     return true;
809   
810   for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
811        UI != E; ++UI)
812     if (PHINode* use_phi = dyn_cast<PHINode>(UI))
813       if (use_phi->getParent() == inst->getParent())
814         return false;
815   
816   return true;
817 }
818
819 /// GetValueForBlock - Get the value to use within the specified basic block.
820 /// available values are in Phis.
821 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
822                                DenseMap<BasicBlock*, Value*> &Phis,
823                                bool top_level) { 
824                                  
825   // If we have already computed this value, return the previously computed val.
826   DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
827   if (V != Phis.end() && !top_level) return V->second;
828   
829   BasicBlock* singlePred = BB->getSinglePredecessor();
830   if (singlePred) {
831     Value *ret = GetValueForBlock(singlePred, orig, Phis);
832     Phis[BB] = ret;
833     return ret;
834   }
835   // Otherwise, the idom is the loop, so we need to insert a PHI node.  Do so
836   // now, then get values to fill in the incoming values for the PHI.
837   PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
838                             BB->begin());
839   PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
840   
841   if (Phis.count(BB) == 0)
842     Phis.insert(std::make_pair(BB, PN));
843   
844   // Fill in the incoming values for the block.
845   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
846     Value* val = GetValueForBlock(*PI, orig, Phis);
847     
848     PN->addIncoming(val, *PI);
849   }
850   
851   // Attempt to collapse PHI nodes that are trivially redundant
852   Value* v = CollapsePhi(PN);
853   if (v) {
854     MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
855
856     MD.removeInstruction(PN);
857     PN->replaceAllUsesWith(v);
858
859     for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
860          E = Phis.end(); I != E; ++I)
861       if (I->second == PN)
862         I->second = v;
863
864     PN->eraseFromParent();
865
866     Phis[BB] = v;
867
868     return v;
869   }
870
871   // Cache our phi construction results
872   phiMap[orig->getPointerOperand()].insert(PN);
873   return PN;
874 }
875
876 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
877 /// non-local by performing PHI construction.
878 bool GVN::processNonLocalLoad(LoadInst* L,
879                               SmallVector<Instruction*, 4>& toErase) {
880   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
881   
882   // Find the non-local dependencies of the load
883   DenseMap<BasicBlock*, Value*> deps;
884   MD.getNonLocalDependency(L, deps);
885   
886   DenseMap<BasicBlock*, Value*> repl;
887   
888   // Filter out useless results (non-locals, etc)
889   for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
890        I != E; ++I)
891     if (I->second == MemoryDependenceAnalysis::None) {
892       return false;
893     } else if (I->second == MemoryDependenceAnalysis::NonLocal) {
894       continue;
895     } else if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
896       if (S->getPointerOperand() == L->getPointerOperand())
897         repl[I->first] = S->getOperand(0);
898       else
899         return false;
900     } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
901       if (LD->getPointerOperand() == L->getPointerOperand())
902         repl[I->first] = LD;
903       else
904         return false;
905     } else {
906       return false;
907     }
908   
909   // Use cached PHI construction information from previous runs
910   SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
911   for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
912        I != E; ++I) {
913     if ((*I)->getParent() == L->getParent()) {
914       MD.removeInstruction(L);
915       L->replaceAllUsesWith(*I);
916       toErase.push_back(L);
917       NumGVNLoad++;
918       
919       return true;
920     } else {
921       repl.insert(std::make_pair((*I)->getParent(), *I));
922     }
923   }
924   
925   // Perform PHI construction
926   SmallPtrSet<BasicBlock*, 4> visited;
927   Value* v = GetValueForBlock(L->getParent(), L, repl, true);
928   
929   MD.removeInstruction(L);
930   L->replaceAllUsesWith(v);
931   toErase.push_back(L);
932   NumGVNLoad++;
933
934   return true;
935 }
936
937 /// processLoad - Attempt to eliminate a load, first by eliminating it
938 /// locally, and then attempting non-local elimination if that fails.
939 bool GVN::processLoad(LoadInst* L,
940                          DenseMap<Value*, LoadInst*>& lastLoad,
941                          SmallVector<Instruction*, 4>& toErase) {
942   if (L->isVolatile()) {
943     lastLoad[L->getPointerOperand()] = L;
944     return false;
945   }
946   
947   Value* pointer = L->getPointerOperand();
948   LoadInst*& last = lastLoad[pointer];
949   
950   // ... to a pointer that has been loaded from before...
951   MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
952   bool removedNonLocal = false;
953   Instruction* dep = MD.getDependency(L);
954   if (dep == MemoryDependenceAnalysis::NonLocal &&
955       L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
956     removedNonLocal = processNonLocalLoad(L, toErase);
957     
958     if (!removedNonLocal)
959       last = L;
960     
961     return removedNonLocal;
962   }
963   
964   
965   bool deletedLoad = false;
966   
967   // Walk up the dependency chain until we either find
968   // a dependency we can use, or we can't walk any further
969   while (dep != MemoryDependenceAnalysis::None &&
970          dep != MemoryDependenceAnalysis::NonLocal &&
971          (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
972     // ... that depends on a store ...
973     if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
974       if (S->getPointerOperand() == pointer) {
975         // Remove it!
976         MD.removeInstruction(L);
977         
978         L->replaceAllUsesWith(S->getOperand(0));
979         toErase.push_back(L);
980         deletedLoad = true;
981         NumGVNLoad++;
982       }
983       
984       // Whether we removed it or not, we can't
985       // go any further
986       break;
987     } else if (!last) {
988       // If we don't depend on a store, and we haven't
989       // been loaded before, bail.
990       break;
991     } else if (dep == last) {
992       // Remove it!
993       MD.removeInstruction(L);
994       
995       L->replaceAllUsesWith(last);
996       toErase.push_back(L);
997       deletedLoad = true;
998       NumGVNLoad++;
999         
1000       break;
1001     } else {
1002       dep = MD.getDependency(L, dep);
1003     }
1004   }
1005   
1006   if (!deletedLoad)
1007     last = L;
1008   
1009   return deletedLoad;
1010 }
1011
1012 /// processInstruction - When calculating availability, handle an instruction
1013 /// by inserting it into the appropriate sets
1014 bool GVN::processInstruction(Instruction* I,
1015                                 ValueNumberedSet& currAvail,
1016                                 DenseMap<Value*, LoadInst*>& lastSeenLoad,
1017                                 SmallVector<Instruction*, 4>& toErase) {
1018   if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1019     return processLoad(L, lastSeenLoad, toErase);
1020   }
1021   
1022   unsigned num = VN.lookup_or_add(I);
1023   
1024   // Collapse PHI nodes
1025   if (PHINode* p = dyn_cast<PHINode>(I)) {
1026     Value* constVal = CollapsePhi(p);
1027     
1028     if (constVal) {
1029       for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1030            PI != PE; ++PI)
1031         if (PI->second.count(p))
1032           PI->second.erase(p);
1033         
1034       p->replaceAllUsesWith(constVal);
1035       toErase.push_back(p);
1036     }
1037   // Perform value-number based elimination
1038   } else if (currAvail.test(num)) {
1039     Value* repl = find_leader(currAvail, num);
1040     
1041     VN.erase(I);
1042     I->replaceAllUsesWith(repl);
1043     toErase.push_back(I);
1044     return true;
1045   } else if (!I->isTerminator()) {
1046     currAvail.set(num);
1047     currAvail.insert(I);
1048   }
1049   
1050   return false;
1051 }
1052
1053 // GVN::runOnFunction - This is the main transformation entry point for a
1054 // function.
1055 //
1056 bool GVN::runOnFunction(Function& F) {
1057   VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1058   
1059   bool changed = false;
1060   bool shouldContinue = true;
1061   
1062   while (shouldContinue) {
1063     shouldContinue = iterateOnFunction(F);
1064     changed |= shouldContinue;
1065   }
1066   
1067   return changed;
1068 }
1069
1070
1071 // GVN::iterateOnFunction - Executes one iteration of GVN
1072 bool GVN::iterateOnFunction(Function &F) {
1073   // Clean out global sets from any previous functions
1074   VN.clear();
1075   availableOut.clear();
1076   phiMap.clear();
1077  
1078   bool changed_function = false;
1079   
1080   DominatorTree &DT = getAnalysis<DominatorTree>();   
1081   
1082   SmallVector<Instruction*, 4> toErase;
1083   
1084   // Top-down walk of the dominator tree
1085   for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1086          E = df_end(DT.getRootNode()); DI != E; ++DI) {
1087     
1088     // Get the set to update for this block
1089     ValueNumberedSet& currAvail = availableOut[DI->getBlock()];     
1090     DenseMap<Value*, LoadInst*> lastSeenLoad;
1091     
1092     BasicBlock* BB = DI->getBlock();
1093   
1094     // A block inherits AVAIL_OUT from its dominator
1095     if (DI->getIDom() != 0)
1096       currAvail = availableOut[DI->getIDom()->getBlock()];
1097
1098     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1099          BI != BE; ) {
1100       changed_function |= processInstruction(BI, currAvail,
1101                                              lastSeenLoad, toErase);
1102       
1103       NumGVNInstr += toErase.size();
1104       
1105       // Avoid iterator invalidation
1106       ++BI;
1107       
1108       for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1109            E = toErase.end(); I != E; ++I)
1110         (*I)->eraseFromParent();
1111       
1112       toErase.clear();
1113     }
1114   }
1115   
1116   return changed_function;
1117 }