GVN.cpp revision 8e1e95cb043c9eb7766d283587cd0a830b1f3209
1//===- GVN.cpp - Eliminate redundant values and loads ------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs 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/IntrinsicInst.h"
23#include "llvm/Instructions.h"
24#include "llvm/ParameterAttributes.h"
25#include "llvm/Value.h"
26#include "llvm/ADT/BitVector.h"
27#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/DepthFirstIterator.h"
29#include "llvm/ADT/SmallPtrSet.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/Analysis/Dominators.h"
33#include "llvm/Analysis/AliasAnalysis.h"
34#include "llvm/Analysis/MemoryDependenceAnalysis.h"
35#include "llvm/Support/CFG.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Target/TargetData.h"
38using namespace llvm;
39
40//===----------------------------------------------------------------------===//
41//                         ValueTable Class
42//===----------------------------------------------------------------------===//
43
44/// This class holds the mapping between values and value numbers.  It is used
45/// as an efficient mechanism to determine the expression-wise equivalence of
46/// two values.
47namespace {
48  struct VISIBILITY_HIDDEN Expression {
49    enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
50                            FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
51                            ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
52                            ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
53                            FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
54                            FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
55                            FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
56                            SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
57                            FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
58                            PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
59                            TOMBSTONE };
60
61    ExpressionOpcode opcode;
62    const Type* type;
63    uint32_t firstVN;
64    uint32_t secondVN;
65    uint32_t thirdVN;
66    SmallVector<uint32_t, 4> varargs;
67    Value* function;
68
69    Expression() { }
70    Expression(ExpressionOpcode o) : opcode(o) { }
71
72    bool operator==(const Expression &other) const {
73      if (opcode != other.opcode)
74        return false;
75      else if (opcode == EMPTY || opcode == TOMBSTONE)
76        return true;
77      else if (type != other.type)
78        return false;
79      else if (function != other.function)
80        return false;
81      else if (firstVN != other.firstVN)
82        return false;
83      else if (secondVN != other.secondVN)
84        return false;
85      else if (thirdVN != other.thirdVN)
86        return false;
87      else {
88        if (varargs.size() != other.varargs.size())
89          return false;
90
91        for (size_t i = 0; i < varargs.size(); ++i)
92          if (varargs[i] != other.varargs[i])
93            return false;
94
95        return true;
96      }
97    }
98
99    bool operator!=(const Expression &other) const {
100      if (opcode != other.opcode)
101        return true;
102      else if (opcode == EMPTY || opcode == TOMBSTONE)
103        return false;
104      else if (type != other.type)
105        return true;
106      else if (function != other.function)
107        return true;
108      else if (firstVN != other.firstVN)
109        return true;
110      else if (secondVN != other.secondVN)
111        return true;
112      else if (thirdVN != other.thirdVN)
113        return true;
114      else {
115        if (varargs.size() != other.varargs.size())
116          return true;
117
118        for (size_t i = 0; i < varargs.size(); ++i)
119          if (varargs[i] != other.varargs[i])
120            return true;
121
122          return false;
123      }
124    }
125  };
126
127  class VISIBILITY_HIDDEN ValueTable {
128    private:
129      DenseMap<Value*, uint32_t> valueNumbering;
130      DenseMap<Expression, uint32_t> expressionNumbering;
131      AliasAnalysis* AA;
132
133      uint32_t nextValueNumber;
134
135      Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
136      Expression::ExpressionOpcode getOpcode(CmpInst* C);
137      Expression::ExpressionOpcode getOpcode(CastInst* C);
138      Expression create_expression(BinaryOperator* BO);
139      Expression create_expression(CmpInst* C);
140      Expression create_expression(ShuffleVectorInst* V);
141      Expression create_expression(ExtractElementInst* C);
142      Expression create_expression(InsertElementInst* V);
143      Expression create_expression(SelectInst* V);
144      Expression create_expression(CastInst* C);
145      Expression create_expression(GetElementPtrInst* G);
146      Expression create_expression(CallInst* C);
147    public:
148      ValueTable() : nextValueNumber(1) { }
149      uint32_t lookup_or_add(Value* V);
150      uint32_t lookup(Value* V) const;
151      void add(Value* V, uint32_t num);
152      void clear();
153      void erase(Value* v);
154      unsigned size();
155      void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
156      uint32_t hash_operand(Value* v);
157  };
158}
159
160namespace llvm {
161template <> struct DenseMapInfo<Expression> {
162  static inline Expression getEmptyKey() {
163    return Expression(Expression::EMPTY);
164  }
165
166  static inline Expression getTombstoneKey() {
167    return Expression(Expression::TOMBSTONE);
168  }
169
170  static unsigned getHashValue(const Expression e) {
171    unsigned hash = e.opcode;
172
173    hash = e.firstVN + hash * 37;
174    hash = e.secondVN + hash * 37;
175    hash = e.thirdVN + hash * 37;
176
177    hash = ((unsigned)((uintptr_t)e.type >> 4) ^
178            (unsigned)((uintptr_t)e.type >> 9)) +
179           hash * 37;
180
181    for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
182         E = e.varargs.end(); I != E; ++I)
183      hash = *I + hash * 37;
184
185    hash = ((unsigned)((uintptr_t)e.function >> 4) ^
186            (unsigned)((uintptr_t)e.function >> 9)) +
187           hash * 37;
188
189    return hash;
190  }
191  static bool isEqual(const Expression &LHS, const Expression &RHS) {
192    return LHS == RHS;
193  }
194  static bool isPod() { return true; }
195};
196}
197
198//===----------------------------------------------------------------------===//
199//                     ValueTable Internal Functions
200//===----------------------------------------------------------------------===//
201Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
202  switch(BO->getOpcode()) {
203  default: // THIS SHOULD NEVER HAPPEN
204    assert(0 && "Binary operator with unknown opcode?");
205  case Instruction::Add:  return Expression::ADD;
206  case Instruction::Sub:  return Expression::SUB;
207  case Instruction::Mul:  return Expression::MUL;
208  case Instruction::UDiv: return Expression::UDIV;
209  case Instruction::SDiv: return Expression::SDIV;
210  case Instruction::FDiv: return Expression::FDIV;
211  case Instruction::URem: return Expression::UREM;
212  case Instruction::SRem: return Expression::SREM;
213  case Instruction::FRem: return Expression::FREM;
214  case Instruction::Shl:  return Expression::SHL;
215  case Instruction::LShr: return Expression::LSHR;
216  case Instruction::AShr: return Expression::ASHR;
217  case Instruction::And:  return Expression::AND;
218  case Instruction::Or:   return Expression::OR;
219  case Instruction::Xor:  return Expression::XOR;
220  }
221}
222
223Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
224  if (isa<ICmpInst>(C)) {
225    switch (C->getPredicate()) {
226    default:  // THIS SHOULD NEVER HAPPEN
227      assert(0 && "Comparison with unknown predicate?");
228    case ICmpInst::ICMP_EQ:  return Expression::ICMPEQ;
229    case ICmpInst::ICMP_NE:  return Expression::ICMPNE;
230    case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
231    case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
232    case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
233    case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
234    case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
235    case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
236    case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
237    case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
238    }
239  }
240  assert(isa<FCmpInst>(C) && "Unknown compare");
241  switch (C->getPredicate()) {
242  default: // THIS SHOULD NEVER HAPPEN
243    assert(0 && "Comparison with unknown predicate?");
244  case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
245  case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
246  case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
247  case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
248  case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
249  case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
250  case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
251  case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
252  case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
253  case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
254  case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
255  case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
256  case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
257  case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
258  }
259}
260
261Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
262  switch(C->getOpcode()) {
263  default: // THIS SHOULD NEVER HAPPEN
264    assert(0 && "Cast operator with unknown opcode?");
265  case Instruction::Trunc:    return Expression::TRUNC;
266  case Instruction::ZExt:     return Expression::ZEXT;
267  case Instruction::SExt:     return Expression::SEXT;
268  case Instruction::FPToUI:   return Expression::FPTOUI;
269  case Instruction::FPToSI:   return Expression::FPTOSI;
270  case Instruction::UIToFP:   return Expression::UITOFP;
271  case Instruction::SIToFP:   return Expression::SITOFP;
272  case Instruction::FPTrunc:  return Expression::FPTRUNC;
273  case Instruction::FPExt:    return Expression::FPEXT;
274  case Instruction::PtrToInt: return Expression::PTRTOINT;
275  case Instruction::IntToPtr: return Expression::INTTOPTR;
276  case Instruction::BitCast:  return Expression::BITCAST;
277  }
278}
279
280uint32_t ValueTable::hash_operand(Value* v) {
281  if (CallInst* CI = dyn_cast<CallInst>(v))
282    if (!AA->doesNotAccessMemory(CI))
283      return nextValueNumber++;
284
285  return lookup_or_add(v);
286}
287
288Expression ValueTable::create_expression(CallInst* C) {
289  Expression e;
290
291  e.type = C->getType();
292  e.firstVN = 0;
293  e.secondVN = 0;
294  e.thirdVN = 0;
295  e.function = C->getCalledFunction();
296  e.opcode = Expression::CALL;
297
298  for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
299       I != E; ++I)
300    e.varargs.push_back(hash_operand(*I));
301
302  return e;
303}
304
305Expression ValueTable::create_expression(BinaryOperator* BO) {
306  Expression e;
307
308  e.firstVN = hash_operand(BO->getOperand(0));
309  e.secondVN = hash_operand(BO->getOperand(1));
310  e.thirdVN = 0;
311  e.function = 0;
312  e.type = BO->getType();
313  e.opcode = getOpcode(BO);
314
315  return e;
316}
317
318Expression ValueTable::create_expression(CmpInst* C) {
319  Expression e;
320
321  e.firstVN = hash_operand(C->getOperand(0));
322  e.secondVN = hash_operand(C->getOperand(1));
323  e.thirdVN = 0;
324  e.function = 0;
325  e.type = C->getType();
326  e.opcode = getOpcode(C);
327
328  return e;
329}
330
331Expression ValueTable::create_expression(CastInst* C) {
332  Expression e;
333
334  e.firstVN = hash_operand(C->getOperand(0));
335  e.secondVN = 0;
336  e.thirdVN = 0;
337  e.function = 0;
338  e.type = C->getType();
339  e.opcode = getOpcode(C);
340
341  return e;
342}
343
344Expression ValueTable::create_expression(ShuffleVectorInst* S) {
345  Expression e;
346
347  e.firstVN = hash_operand(S->getOperand(0));
348  e.secondVN = hash_operand(S->getOperand(1));
349  e.thirdVN = hash_operand(S->getOperand(2));
350  e.function = 0;
351  e.type = S->getType();
352  e.opcode = Expression::SHUFFLE;
353
354  return e;
355}
356
357Expression ValueTable::create_expression(ExtractElementInst* E) {
358  Expression e;
359
360  e.firstVN = hash_operand(E->getOperand(0));
361  e.secondVN = hash_operand(E->getOperand(1));
362  e.thirdVN = 0;
363  e.function = 0;
364  e.type = E->getType();
365  e.opcode = Expression::EXTRACT;
366
367  return e;
368}
369
370Expression ValueTable::create_expression(InsertElementInst* I) {
371  Expression e;
372
373  e.firstVN = hash_operand(I->getOperand(0));
374  e.secondVN = hash_operand(I->getOperand(1));
375  e.thirdVN = hash_operand(I->getOperand(2));
376  e.function = 0;
377  e.type = I->getType();
378  e.opcode = Expression::INSERT;
379
380  return e;
381}
382
383Expression ValueTable::create_expression(SelectInst* I) {
384  Expression e;
385
386  e.firstVN = hash_operand(I->getCondition());
387  e.secondVN = hash_operand(I->getTrueValue());
388  e.thirdVN = hash_operand(I->getFalseValue());
389  e.function = 0;
390  e.type = I->getType();
391  e.opcode = Expression::SELECT;
392
393  return e;
394}
395
396Expression ValueTable::create_expression(GetElementPtrInst* G) {
397  Expression e;
398
399  e.firstVN = hash_operand(G->getPointerOperand());
400  e.secondVN = 0;
401  e.thirdVN = 0;
402  e.function = 0;
403  e.type = G->getType();
404  e.opcode = Expression::GEP;
405
406  for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
407       I != E; ++I)
408    e.varargs.push_back(hash_operand(*I));
409
410  return e;
411}
412
413//===----------------------------------------------------------------------===//
414//                     ValueTable External Functions
415//===----------------------------------------------------------------------===//
416
417/// lookup_or_add - Returns the value number for the specified value, assigning
418/// it a new number if it did not have one before.
419uint32_t ValueTable::lookup_or_add(Value* V) {
420  DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
421  if (VI != valueNumbering.end())
422    return VI->second;
423
424  if (CallInst* C = dyn_cast<CallInst>(V)) {
425    if (AA->onlyReadsMemory(C)) { // includes doesNotAccessMemory
426      Expression e = create_expression(C);
427
428      DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
429      if (EI != expressionNumbering.end()) {
430        valueNumbering.insert(std::make_pair(V, EI->second));
431        return EI->second;
432      } else {
433        expressionNumbering.insert(std::make_pair(e, nextValueNumber));
434        valueNumbering.insert(std::make_pair(V, nextValueNumber));
435
436        return nextValueNumber++;
437      }
438    } else {
439      valueNumbering.insert(std::make_pair(V, nextValueNumber));
440      return nextValueNumber++;
441    }
442  } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
443    Expression e = create_expression(BO);
444
445    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
446    if (EI != expressionNumbering.end()) {
447      valueNumbering.insert(std::make_pair(V, EI->second));
448      return EI->second;
449    } else {
450      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
451      valueNumbering.insert(std::make_pair(V, nextValueNumber));
452
453      return nextValueNumber++;
454    }
455  } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
456    Expression e = create_expression(C);
457
458    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
459    if (EI != expressionNumbering.end()) {
460      valueNumbering.insert(std::make_pair(V, EI->second));
461      return EI->second;
462    } else {
463      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
464      valueNumbering.insert(std::make_pair(V, nextValueNumber));
465
466      return nextValueNumber++;
467    }
468  } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
469    Expression e = create_expression(U);
470
471    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
472    if (EI != expressionNumbering.end()) {
473      valueNumbering.insert(std::make_pair(V, EI->second));
474      return EI->second;
475    } else {
476      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
477      valueNumbering.insert(std::make_pair(V, nextValueNumber));
478
479      return nextValueNumber++;
480    }
481  } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
482    Expression e = create_expression(U);
483
484    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
485    if (EI != expressionNumbering.end()) {
486      valueNumbering.insert(std::make_pair(V, EI->second));
487      return EI->second;
488    } else {
489      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
490      valueNumbering.insert(std::make_pair(V, nextValueNumber));
491
492      return nextValueNumber++;
493    }
494  } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
495    Expression e = create_expression(U);
496
497    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
498    if (EI != expressionNumbering.end()) {
499      valueNumbering.insert(std::make_pair(V, EI->second));
500      return EI->second;
501    } else {
502      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
503      valueNumbering.insert(std::make_pair(V, nextValueNumber));
504
505      return nextValueNumber++;
506    }
507  } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
508    Expression e = create_expression(U);
509
510    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
511    if (EI != expressionNumbering.end()) {
512      valueNumbering.insert(std::make_pair(V, EI->second));
513      return EI->second;
514    } else {
515      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
516      valueNumbering.insert(std::make_pair(V, nextValueNumber));
517
518      return nextValueNumber++;
519    }
520  } else if (CastInst* U = dyn_cast<CastInst>(V)) {
521    Expression e = create_expression(U);
522
523    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
524    if (EI != expressionNumbering.end()) {
525      valueNumbering.insert(std::make_pair(V, EI->second));
526      return EI->second;
527    } else {
528      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
529      valueNumbering.insert(std::make_pair(V, nextValueNumber));
530
531      return nextValueNumber++;
532    }
533  } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
534    Expression e = create_expression(U);
535
536    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
537    if (EI != expressionNumbering.end()) {
538      valueNumbering.insert(std::make_pair(V, EI->second));
539      return EI->second;
540    } else {
541      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
542      valueNumbering.insert(std::make_pair(V, nextValueNumber));
543
544      return nextValueNumber++;
545    }
546  } else {
547    valueNumbering.insert(std::make_pair(V, nextValueNumber));
548    return nextValueNumber++;
549  }
550}
551
552/// lookup - Returns the value number of the specified value. Fails if
553/// the value has not yet been numbered.
554uint32_t ValueTable::lookup(Value* V) const {
555  DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
556  assert(VI != valueNumbering.end() && "Value not numbered?");
557  return VI->second;
558}
559
560/// clear - Remove all entries from the ValueTable
561void ValueTable::clear() {
562  valueNumbering.clear();
563  expressionNumbering.clear();
564  nextValueNumber = 1;
565}
566
567/// erase - Remove a value from the value numbering
568void ValueTable::erase(Value* V) {
569  valueNumbering.erase(V);
570}
571
572//===----------------------------------------------------------------------===//
573//                       ValueNumberedSet Class
574//===----------------------------------------------------------------------===//
575namespace {
576class VISIBILITY_HIDDEN ValueNumberedSet {
577  private:
578    SmallPtrSet<Value*, 8> contents;
579    BitVector numbers;
580  public:
581    ValueNumberedSet() { numbers.resize(1); }
582    ValueNumberedSet(const ValueNumberedSet& other) {
583      numbers = other.numbers;
584      contents = other.contents;
585    }
586
587    typedef SmallPtrSet<Value*, 8>::iterator iterator;
588
589    iterator begin() { return contents.begin(); }
590    iterator end() { return contents.end(); }
591
592    bool insert(Value* v) { return contents.insert(v); }
593    void insert(iterator I, iterator E) { contents.insert(I, E); }
594    void erase(Value* v) { contents.erase(v); }
595    unsigned count(Value* v) { return contents.count(v); }
596    size_t size() { return contents.size(); }
597
598    void set(unsigned i)  {
599      if (i >= numbers.size())
600        numbers.resize(i+1);
601
602      numbers.set(i);
603    }
604
605    void operator=(const ValueNumberedSet& other) {
606      contents = other.contents;
607      numbers = other.numbers;
608    }
609
610    void reset(unsigned i)  {
611      if (i < numbers.size())
612        numbers.reset(i);
613    }
614
615    bool test(unsigned i)  {
616      if (i >= numbers.size())
617        return false;
618
619      return numbers.test(i);
620    }
621
622    void clear() {
623      contents.clear();
624      numbers.clear();
625    }
626};
627}
628
629//===----------------------------------------------------------------------===//
630//                         GVN Pass
631//===----------------------------------------------------------------------===//
632
633namespace {
634
635  class VISIBILITY_HIDDEN GVN : public FunctionPass {
636    bool runOnFunction(Function &F);
637  public:
638    static char ID; // Pass identification, replacement for typeid
639    GVN() : FunctionPass((intptr_t)&ID) { }
640
641  private:
642    ValueTable VN;
643
644    DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
645
646    typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
647    PhiMapType phiMap;
648
649
650    // This transformation requires dominator postdominator info
651    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
652      AU.setPreservesCFG();
653      AU.addRequired<DominatorTree>();
654      AU.addRequired<MemoryDependenceAnalysis>();
655      AU.addRequired<AliasAnalysis>();
656      AU.addRequired<TargetData>();
657      AU.addPreserved<AliasAnalysis>();
658      AU.addPreserved<MemoryDependenceAnalysis>();
659      AU.addPreserved<TargetData>();
660    }
661
662    // Helper fuctions
663    // FIXME: eliminate or document these better
664    Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
665    void val_insert(ValueNumberedSet& s, Value* v);
666    bool processLoad(LoadInst* L,
667                     DenseMap<Value*, LoadInst*> &lastLoad,
668                     SmallVectorImpl<Instruction*> &toErase);
669    bool processInstruction(Instruction* I,
670                            ValueNumberedSet& currAvail,
671                            DenseMap<Value*, LoadInst*>& lastSeenLoad,
672                            SmallVectorImpl<Instruction*> &toErase);
673    bool processNonLocalLoad(LoadInst* L,
674                             SmallVectorImpl<Instruction*> &toErase);
675    bool processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
676                       SmallVectorImpl<Instruction*> &toErase);
677    bool performCallSlotOptzn(MemCpyInst* cpy, CallInst* C,
678                              SmallVectorImpl<Instruction*> &toErase);
679    Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
680                            DenseMap<BasicBlock*, Value*> &Phis,
681                            bool top_level = false);
682    void dump(DenseMap<BasicBlock*, Value*>& d);
683    bool iterateOnFunction(Function &F);
684    Value* CollapsePhi(PHINode* p);
685    bool isSafeReplacement(PHINode* p, Instruction* inst);
686  };
687
688  char GVN::ID = 0;
689}
690
691// createGVNPass - The public interface to this file...
692FunctionPass *llvm::createGVNPass() { return new GVN(); }
693
694static RegisterPass<GVN> X("gvn",
695                           "Global Value Numbering");
696
697STATISTIC(NumGVNInstr, "Number of instructions deleted");
698STATISTIC(NumGVNLoad, "Number of loads deleted");
699
700/// find_leader - Given a set and a value number, return the first
701/// element of the set with that value number, or 0 if no such element
702/// is present
703Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
704  if (!vals.test(v))
705    return 0;
706
707  for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
708       I != E; ++I)
709    if (v == VN.lookup(*I))
710      return *I;
711
712  assert(0 && "No leader found, but present bit is set?");
713  return 0;
714}
715
716/// val_insert - Insert a value into a set only if there is not a value
717/// with the same value number already in the set
718void GVN::val_insert(ValueNumberedSet& s, Value* v) {
719  uint32_t num = VN.lookup(v);
720  if (!s.test(num))
721    s.insert(v);
722}
723
724void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
725  printf("{\n");
726  for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
727       E = d.end(); I != E; ++I) {
728    if (I->second == MemoryDependenceAnalysis::None)
729      printf("None\n");
730    else
731      I->second->dump();
732  }
733  printf("}\n");
734}
735
736Value* GVN::CollapsePhi(PHINode* p) {
737  DominatorTree &DT = getAnalysis<DominatorTree>();
738  Value* constVal = p->hasConstantValue();
739
740  if (!constVal) return 0;
741
742  Instruction* inst = dyn_cast<Instruction>(constVal);
743  if (!inst)
744    return constVal;
745
746  if (DT.dominates(inst, p))
747    if (isSafeReplacement(p, inst))
748      return inst;
749  return 0;
750}
751
752bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
753  if (!isa<PHINode>(inst))
754    return true;
755
756  for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
757       UI != E; ++UI)
758    if (PHINode* use_phi = dyn_cast<PHINode>(UI))
759      if (use_phi->getParent() == inst->getParent())
760        return false;
761
762  return true;
763}
764
765/// GetValueForBlock - Get the value to use within the specified basic block.
766/// available values are in Phis.
767Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
768                             DenseMap<BasicBlock*, Value*> &Phis,
769                             bool top_level) {
770
771  // If we have already computed this value, return the previously computed val.
772  DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
773  if (V != Phis.end() && !top_level) return V->second;
774
775  BasicBlock* singlePred = BB->getSinglePredecessor();
776  if (singlePred) {
777    Value *ret = GetValueForBlock(singlePred, orig, Phis);
778    Phis[BB] = ret;
779    return ret;
780  }
781
782  // Otherwise, the idom is the loop, so we need to insert a PHI node.  Do so
783  // now, then get values to fill in the incoming values for the PHI.
784  PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
785                            BB->begin());
786  PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
787
788  if (Phis.count(BB) == 0)
789    Phis.insert(std::make_pair(BB, PN));
790
791  // Fill in the incoming values for the block.
792  for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
793    Value* val = GetValueForBlock(*PI, orig, Phis);
794    PN->addIncoming(val, *PI);
795  }
796
797  AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
798  AA.copyValue(orig, PN);
799
800  // Attempt to collapse PHI nodes that are trivially redundant
801  Value* v = CollapsePhi(PN);
802  if (!v) {
803    // Cache our phi construction results
804    phiMap[orig->getPointerOperand()].insert(PN);
805    return PN;
806  }
807
808  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
809
810  MD.removeInstruction(PN);
811  PN->replaceAllUsesWith(v);
812
813  for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
814       E = Phis.end(); I != E; ++I)
815    if (I->second == PN)
816      I->second = v;
817
818  PN->eraseFromParent();
819
820  Phis[BB] = v;
821  return v;
822}
823
824/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
825/// non-local by performing PHI construction.
826bool GVN::processNonLocalLoad(LoadInst* L,
827                              SmallVectorImpl<Instruction*> &toErase) {
828  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
829
830  // Find the non-local dependencies of the load
831  DenseMap<BasicBlock*, Value*> deps;
832  MD.getNonLocalDependency(L, deps);
833
834  DenseMap<BasicBlock*, Value*> repl;
835
836  // Filter out useless results (non-locals, etc)
837  for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
838       I != E; ++I) {
839    if (I->second == MemoryDependenceAnalysis::None)
840      return false;
841
842    if (I->second == MemoryDependenceAnalysis::NonLocal)
843      continue;
844
845    if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
846      if (S->getPointerOperand() != L->getPointerOperand())
847        return false;
848      repl[I->first] = S->getOperand(0);
849    } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
850      if (LD->getPointerOperand() != L->getPointerOperand())
851        return false;
852      repl[I->first] = LD;
853    } else {
854      return false;
855    }
856  }
857
858  // Use cached PHI construction information from previous runs
859  SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
860  for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
861       I != E; ++I) {
862    if ((*I)->getParent() == L->getParent()) {
863      MD.removeInstruction(L);
864      L->replaceAllUsesWith(*I);
865      toErase.push_back(L);
866      NumGVNLoad++;
867      return true;
868    }
869
870    repl.insert(std::make_pair((*I)->getParent(), *I));
871  }
872
873  // Perform PHI construction
874  SmallPtrSet<BasicBlock*, 4> visited;
875  Value* v = GetValueForBlock(L->getParent(), L, repl, true);
876
877  MD.removeInstruction(L);
878  L->replaceAllUsesWith(v);
879  toErase.push_back(L);
880  NumGVNLoad++;
881
882  return true;
883}
884
885/// processLoad - Attempt to eliminate a load, first by eliminating it
886/// locally, and then attempting non-local elimination if that fails.
887bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
888                      SmallVectorImpl<Instruction*> &toErase) {
889  if (L->isVolatile()) {
890    lastLoad[L->getPointerOperand()] = L;
891    return false;
892  }
893
894  Value* pointer = L->getPointerOperand();
895  LoadInst*& last = lastLoad[pointer];
896
897  // ... to a pointer that has been loaded from before...
898  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
899  bool removedNonLocal = false;
900  Instruction* dep = MD.getDependency(L);
901  if (dep == MemoryDependenceAnalysis::NonLocal &&
902      L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
903    removedNonLocal = processNonLocalLoad(L, toErase);
904
905    if (!removedNonLocal)
906      last = L;
907
908    return removedNonLocal;
909  }
910
911
912  bool deletedLoad = false;
913
914  // Walk up the dependency chain until we either find
915  // a dependency we can use, or we can't walk any further
916  while (dep != MemoryDependenceAnalysis::None &&
917         dep != MemoryDependenceAnalysis::NonLocal &&
918         (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
919    // ... that depends on a store ...
920    if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
921      if (S->getPointerOperand() == pointer) {
922        // Remove it!
923        MD.removeInstruction(L);
924
925        L->replaceAllUsesWith(S->getOperand(0));
926        toErase.push_back(L);
927        deletedLoad = true;
928        NumGVNLoad++;
929      }
930
931      // Whether we removed it or not, we can't
932      // go any further
933      break;
934    } else if (!last) {
935      // If we don't depend on a store, and we haven't
936      // been loaded before, bail.
937      break;
938    } else if (dep == last) {
939      // Remove it!
940      MD.removeInstruction(L);
941
942      L->replaceAllUsesWith(last);
943      toErase.push_back(L);
944      deletedLoad = true;
945      NumGVNLoad++;
946
947      break;
948    } else {
949      dep = MD.getDependency(L, dep);
950    }
951  }
952
953  if (dep != MemoryDependenceAnalysis::None &&
954      dep != MemoryDependenceAnalysis::NonLocal &&
955      isa<AllocationInst>(dep)) {
956    // Check that this load is actually from the
957    // allocation we found
958    Value* v = L->getOperand(0);
959    while (true) {
960      if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
961        v = BC->getOperand(0);
962      else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
963        v = GEP->getOperand(0);
964      else
965        break;
966    }
967    if (v == dep) {
968      // If this load depends directly on an allocation, there isn't
969      // anything stored there; therefore, we can optimize this load
970      // to undef.
971      MD.removeInstruction(L);
972
973      L->replaceAllUsesWith(UndefValue::get(L->getType()));
974      toErase.push_back(L);
975      deletedLoad = true;
976      NumGVNLoad++;
977    }
978  }
979
980  if (!deletedLoad)
981    last = L;
982
983  return deletedLoad;
984}
985
986/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
987/// and checks for the possibility of a call slot optimization by having
988/// the call write its result directly into the destination of the memcpy.
989bool GVN::performCallSlotOptzn(MemCpyInst *cpy, CallInst *C,
990                               SmallVectorImpl<Instruction*> &toErase) {
991  // The general transformation to keep in mind is
992  //
993  //   call @func(..., src, ...)
994  //   memcpy(dest, src, ...)
995  //
996  // ->
997  //
998  //   memcpy(dest, src, ...)
999  //   call @func(..., dest, ...)
1000  //
1001  // Since moving the memcpy is technically awkward, we additionally check that
1002  // src only holds uninitialized values at the moment of the call, meaning that
1003  // the memcpy can be discarded rather than moved.
1004
1005  // Deliberately get the source and destination with bitcasts stripped away,
1006  // because we'll need to do type comparisons based on the underlying type.
1007  Value* cpyDest = cpy->getDest();
1008  Value* cpySrc = cpy->getSource();
1009  CallSite CS = CallSite::get(C);
1010
1011  // We need to be able to reason about the size of the memcpy, so we require
1012  // that it be a constant.
1013  ConstantInt* cpyLength = dyn_cast<ConstantInt>(cpy->getLength());
1014  if (!cpyLength)
1015    return false;
1016
1017  // Require that src be an alloca.  This simplifies the reasoning considerably.
1018  AllocaInst* srcAlloca = dyn_cast<AllocaInst>(cpySrc);
1019  if (!srcAlloca)
1020    return false;
1021
1022  // Check that all of src is copied to dest.
1023  TargetData& TD = getAnalysis<TargetData>();
1024
1025  ConstantInt* srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
1026  if (!srcArraySize)
1027    return false;
1028
1029  uint64_t srcSize = TD.getABITypeSize(srcAlloca->getAllocatedType()) *
1030    srcArraySize->getZExtValue();
1031
1032  if (cpyLength->getZExtValue() < srcSize)
1033    return false;
1034
1035  // Check that accessing the first srcSize bytes of dest will not cause a
1036  // trap.  Otherwise the transform is invalid since it might cause a trap
1037  // to occur earlier than it otherwise would.
1038  if (AllocaInst* A = dyn_cast<AllocaInst>(cpyDest)) {
1039    // The destination is an alloca.  Check it is larger than srcSize.
1040    ConstantInt* destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
1041    if (!destArraySize)
1042      return false;
1043
1044    uint64_t destSize = TD.getABITypeSize(A->getAllocatedType()) *
1045      destArraySize->getZExtValue();
1046
1047    if (destSize < srcSize)
1048      return false;
1049  } else if (Argument* A = dyn_cast<Argument>(cpyDest)) {
1050    // If the destination is an sret parameter then only accesses that are
1051    // outside of the returned struct type can trap.
1052    if (!A->hasStructRetAttr())
1053      return false;
1054
1055    const Type* StructTy = cast<PointerType>(A->getType())->getElementType();
1056    uint64_t destSize = TD.getABITypeSize(StructTy);
1057
1058    if (destSize < srcSize)
1059      return false;
1060  } else {
1061    return false;
1062  }
1063
1064  // Check that src is not accessed except via the call and the memcpy.  This
1065  // guarantees that it holds only undefined values when passed in (so the final
1066  // memcpy can be dropped), that it is not read or written between the call and
1067  // the memcpy, and that writing beyond the end of it is undefined.
1068  SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
1069                                   srcAlloca->use_end());
1070  while (!srcUseList.empty()) {
1071    User* UI = srcUseList.back();
1072    srcUseList.pop_back();
1073
1074    if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
1075      for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
1076           I != E; ++I)
1077        srcUseList.push_back(*I);
1078    } else if (UI != C && UI != cpy) {
1079      return false;
1080    }
1081  }
1082
1083  // Since we're changing the parameter to the callsite, we need to make sure
1084  // that what would be the new parameter dominates the callsite.
1085  DominatorTree& DT = getAnalysis<DominatorTree>();
1086  if (Instruction* cpyDestInst = dyn_cast<Instruction>(cpyDest))
1087    if (!DT.dominates(cpyDestInst, C))
1088      return false;
1089
1090  // In addition to knowing that the call does not access src in some
1091  // unexpected manner, for example via a global, which we deduce from
1092  // the use analysis, we also need to know that it does not sneakily
1093  // access dest.  We rely on AA to figure this out for us.
1094  AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1095  if (AA.getModRefInfo(C, cpy->getRawDest(), srcSize) !=
1096      AliasAnalysis::NoModRef)
1097    return false;
1098
1099  // All the checks have passed, so do the transformation.
1100  for (unsigned i = 0; i < CS.arg_size(); ++i)
1101    if (CS.getArgument(i) == cpySrc) {
1102      if (cpySrc->getType() != cpyDest->getType())
1103        cpyDest = CastInst::createPointerCast(cpyDest, cpySrc->getType(),
1104                                              cpyDest->getName(), C);
1105      CS.setArgument(i, cpyDest);
1106    }
1107
1108  // Drop any cached information about the call, because we may have changed
1109  // its dependence information by changing its parameter.
1110  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1111  MD.dropInstruction(C);
1112
1113  // Remove the memcpy
1114  MD.removeInstruction(cpy);
1115  toErase.push_back(cpy);
1116
1117  return true;
1118}
1119
1120/// processMemCpy - perform simplication of memcpy's.  If we have memcpy A which
1121/// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
1122/// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
1123///  This allows later passes to remove the first memcpy altogether.
1124bool GVN::processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
1125                        SmallVectorImpl<Instruction*> &toErase) {
1126  // We can only transforms memcpy's where the dest of one is the source of the
1127  // other
1128  if (M->getSource() != MDep->getDest())
1129    return false;
1130
1131  // Second, the length of the memcpy's must be the same, or the preceeding one
1132  // must be larger than the following one.
1133  ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
1134  ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
1135  if (!C1 || !C2)
1136    return false;
1137
1138  uint64_t DepSize = C1->getValue().getZExtValue();
1139  uint64_t CpySize = C2->getValue().getZExtValue();
1140
1141  if (DepSize < CpySize)
1142    return false;
1143
1144  // Finally, we have to make sure that the dest of the second does not
1145  // alias the source of the first
1146  AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1147  if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
1148      AliasAnalysis::NoAlias)
1149    return false;
1150  else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
1151           AliasAnalysis::NoAlias)
1152    return false;
1153  else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
1154           != AliasAnalysis::NoAlias)
1155    return false;
1156
1157  // If all checks passed, then we can transform these memcpy's
1158  Function* MemCpyFun = Intrinsic::getDeclaration(
1159                                 M->getParent()->getParent()->getParent(),
1160                                 M->getIntrinsicID());
1161
1162  std::vector<Value*> args;
1163  args.push_back(M->getRawDest());
1164  args.push_back(MDep->getRawSource());
1165  args.push_back(M->getLength());
1166  args.push_back(M->getAlignment());
1167
1168  CallInst* C = new CallInst(MemCpyFun, args.begin(), args.end(), "", M);
1169
1170  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1171  if (MD.getDependency(C) == MDep) {
1172    MD.dropInstruction(M);
1173    toErase.push_back(M);
1174    return true;
1175  }
1176
1177  MD.removeInstruction(C);
1178  toErase.push_back(C);
1179  return false;
1180}
1181
1182/// processInstruction - When calculating availability, handle an instruction
1183/// by inserting it into the appropriate sets
1184bool GVN::processInstruction(Instruction *I, ValueNumberedSet &currAvail,
1185                             DenseMap<Value*, LoadInst*> &lastSeenLoad,
1186                             SmallVectorImpl<Instruction*> &toErase) {
1187  if (LoadInst* L = dyn_cast<LoadInst>(I))
1188    return processLoad(L, lastSeenLoad, toErase);
1189
1190  if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
1191    MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1192
1193    // The are two possible optimizations we can do for memcpy:
1194    //   a) memcpy-memcpy xform which exposes redundance for DSE
1195    //   b) call-memcpy xform for return slot optimization
1196    Instruction* dep = MD.getDependency(M);
1197    if (dep == MemoryDependenceAnalysis::None ||
1198        dep == MemoryDependenceAnalysis::NonLocal)
1199      return false;
1200    if (MemCpyInst *MemCpy = dyn_cast<MemCpyInst>(dep))
1201      return processMemCpy(M, MemCpy, toErase);
1202    if (CallInst* C = dyn_cast<CallInst>(dep))
1203      return performCallSlotOptzn(M, C, toErase);
1204    return false;
1205  }
1206
1207  unsigned num = VN.lookup_or_add(I);
1208
1209  // Collapse PHI nodes
1210  if (PHINode* p = dyn_cast<PHINode>(I)) {
1211    Value* constVal = CollapsePhi(p);
1212
1213    if (constVal) {
1214      for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1215           PI != PE; ++PI)
1216        if (PI->second.count(p))
1217          PI->second.erase(p);
1218
1219      p->replaceAllUsesWith(constVal);
1220      toErase.push_back(p);
1221    }
1222  // Perform value-number based elimination
1223  } else if (currAvail.test(num)) {
1224    Value* repl = find_leader(currAvail, num);
1225
1226    if (CallInst* CI = dyn_cast<CallInst>(I)) {
1227      AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1228      if (!AA.doesNotAccessMemory(CI)) {
1229        MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1230        if (cast<Instruction>(repl)->getParent() != CI->getParent() ||
1231            MD.getDependency(CI) != MD.getDependency(cast<CallInst>(repl))) {
1232          // There must be an intervening may-alias store, so nothing from
1233          // this point on will be able to be replaced with the preceding call
1234          currAvail.erase(repl);
1235          currAvail.insert(I);
1236
1237          return false;
1238        }
1239      }
1240    }
1241
1242    // Remove it!
1243    MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1244    MD.removeInstruction(I);
1245
1246    VN.erase(I);
1247    I->replaceAllUsesWith(repl);
1248    toErase.push_back(I);
1249    return true;
1250  } else if (!I->isTerminator()) {
1251    currAvail.set(num);
1252    currAvail.insert(I);
1253  }
1254
1255  return false;
1256}
1257
1258// GVN::runOnFunction - This is the main transformation entry point for a
1259// function.
1260//
1261bool GVN::runOnFunction(Function& F) {
1262  VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1263
1264  bool changed = false;
1265  bool shouldContinue = true;
1266
1267  while (shouldContinue) {
1268    shouldContinue = iterateOnFunction(F);
1269    changed |= shouldContinue;
1270  }
1271
1272  return changed;
1273}
1274
1275
1276// GVN::iterateOnFunction - Executes one iteration of GVN
1277bool GVN::iterateOnFunction(Function &F) {
1278  // Clean out global sets from any previous functions
1279  VN.clear();
1280  availableOut.clear();
1281  phiMap.clear();
1282
1283  bool changed_function = false;
1284
1285  DominatorTree &DT = getAnalysis<DominatorTree>();
1286
1287  SmallVector<Instruction*, 4> toErase;
1288  DenseMap<Value*, LoadInst*> lastSeenLoad;
1289
1290  // Top-down walk of the dominator tree
1291  for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1292         E = df_end(DT.getRootNode()); DI != E; ++DI) {
1293
1294    // Get the set to update for this block
1295    ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1296    lastSeenLoad.clear();
1297
1298    BasicBlock* BB = DI->getBlock();
1299
1300    // A block inherits AVAIL_OUT from its dominator
1301    if (DI->getIDom() != 0)
1302      currAvail = availableOut[DI->getIDom()->getBlock()];
1303
1304    for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1305         BI != BE; ) {
1306      changed_function |= processInstruction(BI, currAvail,
1307                                             lastSeenLoad, toErase);
1308
1309      NumGVNInstr += toErase.size();
1310
1311      // Avoid iterator invalidation
1312      ++BI;
1313
1314      for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1315           E = toErase.end(); I != E; ++I)
1316        (*I)->eraseFromParent();
1317
1318      toErase.clear();
1319    }
1320  }
1321
1322  return changed_function;
1323}
1324