GVN.cpp revision 88365bb4047a91d42af2aa42839b21e701ea1b03
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                     SmallVector<Instruction*, 4>& toErase);
669    bool processInstruction(Instruction* I,
670                            ValueNumberedSet& currAvail,
671                            DenseMap<Value*, LoadInst*>& lastSeenLoad,
672                            SmallVector<Instruction*, 4>& toErase);
673    bool processNonLocalLoad(LoadInst* L,
674                             SmallVector<Instruction*, 4>& toErase);
675    bool processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
676                       SmallVector<Instruction*, 4>& toErase);
677    bool performCallSlotOptzn(MemCpyInst* cpy, CallInst* C,
678                              SmallVector<Instruction*, 4>& 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                              SmallVector<Instruction*, 4>& 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,
888                         DenseMap<Value*, LoadInst*>& lastLoad,
889                         SmallVector<Instruction*, 4>& toErase) {
890  if (L->isVolatile()) {
891    lastLoad[L->getPointerOperand()] = L;
892    return false;
893  }
894
895  Value* pointer = L->getPointerOperand();
896  LoadInst*& last = lastLoad[pointer];
897
898  // ... to a pointer that has been loaded from before...
899  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
900  bool removedNonLocal = false;
901  Instruction* dep = MD.getDependency(L);
902  if (dep == MemoryDependenceAnalysis::NonLocal &&
903      L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
904    removedNonLocal = processNonLocalLoad(L, toErase);
905
906    if (!removedNonLocal)
907      last = L;
908
909    return removedNonLocal;
910  }
911
912
913  bool deletedLoad = false;
914
915  // Walk up the dependency chain until we either find
916  // a dependency we can use, or we can't walk any further
917  while (dep != MemoryDependenceAnalysis::None &&
918         dep != MemoryDependenceAnalysis::NonLocal &&
919         (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
920    // ... that depends on a store ...
921    if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
922      if (S->getPointerOperand() == pointer) {
923        // Remove it!
924        MD.removeInstruction(L);
925
926        L->replaceAllUsesWith(S->getOperand(0));
927        toErase.push_back(L);
928        deletedLoad = true;
929        NumGVNLoad++;
930      }
931
932      // Whether we removed it or not, we can't
933      // go any further
934      break;
935    } else if (!last) {
936      // If we don't depend on a store, and we haven't
937      // been loaded before, bail.
938      break;
939    } else if (dep == last) {
940      // Remove it!
941      MD.removeInstruction(L);
942
943      L->replaceAllUsesWith(last);
944      toErase.push_back(L);
945      deletedLoad = true;
946      NumGVNLoad++;
947
948      break;
949    } else {
950      dep = MD.getDependency(L, dep);
951    }
952  }
953
954  if (dep != MemoryDependenceAnalysis::None &&
955      dep != MemoryDependenceAnalysis::NonLocal &&
956      isa<AllocationInst>(dep)) {
957    // Check that this load is actually from the
958    // allocation we found
959    Value* v = L->getOperand(0);
960    while (true) {
961      if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
962        v = BC->getOperand(0);
963      else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
964        v = GEP->getOperand(0);
965      else
966        break;
967    }
968    if (v == dep) {
969      // If this load depends directly on an allocation, there isn't
970      // anything stored there; therefore, we can optimize this load
971      // to undef.
972      MD.removeInstruction(L);
973
974      L->replaceAllUsesWith(UndefValue::get(L->getType()));
975      toErase.push_back(L);
976      deletedLoad = true;
977      NumGVNLoad++;
978    }
979  }
980
981  if (!deletedLoad)
982    last = L;
983
984  return deletedLoad;
985}
986
987/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
988/// and checks for the possibility of a call slot optimization by having
989/// the call write its result directly into the destination of the memcpy.
990bool GVN::performCallSlotOptzn(MemCpyInst* cpy, CallInst* C,
991                               SmallVector<Instruction*, 4>& toErase) {
992  // The general transformation to keep in mind is
993  //
994  //   call @func(..., src, ...)
995  //   memcpy(dest, src, ...)
996  //
997  // ->
998  //
999  //   memcpy(dest, src, ...)
1000  //   call @func(..., dest, ...)
1001  //
1002  // Since moving the memcpy is technically awkward, we additionally check that
1003  // src only holds uninitialized values at the moment of the call, meaning that
1004  // the memcpy can be discarded rather than moved.
1005
1006  // Deliberately get the source and destination with bitcasts stripped away,
1007  // because we'll need to do type comparisons based on the underlying type.
1008  Value* cpyDest = cpy->getDest();
1009  Value* cpySrc = cpy->getSource();
1010  CallSite CS = CallSite::get(C);
1011
1012  // We need to be able to reason about the size of the memcpy, so we require
1013  // that it be a constant.
1014  ConstantInt* cpyLength = dyn_cast<ConstantInt>(cpy->getLength());
1015  if (!cpyLength)
1016    return false;
1017
1018  // Require that src be an alloca.  This simplifies the reasoning considerably.
1019  AllocaInst* srcAlloca = dyn_cast<AllocaInst>(cpySrc);
1020  if (!srcAlloca)
1021    return false;
1022
1023  // Check that all of src is copied to dest.
1024  TargetData& TD = getAnalysis<TargetData>();
1025
1026  ConstantInt* srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
1027  if (!srcArraySize)
1028    return false;
1029
1030  uint64_t srcSize = TD.getABITypeSize(srcAlloca->getAllocatedType()) *
1031    srcArraySize->getZExtValue();
1032
1033  if (cpyLength->getZExtValue() < srcSize)
1034    return false;
1035
1036  // Check that accessing the first srcSize bytes of dest will not cause a
1037  // trap.  Otherwise the transform is invalid since it might cause a trap
1038  // to occur earlier than it otherwise would.
1039  if (AllocaInst* A = dyn_cast<AllocaInst>(cpyDest)) {
1040    // The destination is an alloca.  Check it is larger than srcSize.
1041    ConstantInt* destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
1042    if (!destArraySize)
1043      return false;
1044
1045    uint64_t destSize = TD.getABITypeSize(A->getAllocatedType()) *
1046      destArraySize->getZExtValue();
1047
1048    if (destSize < srcSize)
1049      return false;
1050  } else if (Argument* A = dyn_cast<Argument>(cpyDest)) {
1051    // If the destination is an sret parameter then only accesses that are
1052    // outside of the returned struct type can trap.
1053    if (!A->hasStructRetAttr())
1054      return false;
1055
1056    const Type* StructTy = cast<PointerType>(A->getType())->getElementType();
1057    uint64_t destSize = TD.getABITypeSize(StructTy);
1058
1059    if (destSize < srcSize)
1060      return false;
1061  } else {
1062    return false;
1063  }
1064
1065  // Check that src is not accessed except via the call and the memcpy.  This
1066  // guarantees that it holds only undefined values when passed in (so the final
1067  // memcpy can be dropped), that it is not read or written between the call and
1068  // the memcpy, and that writing beyond the end of it is undefined.
1069
1070  SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
1071                                   srcAlloca->use_end());
1072  while (!srcUseList.empty()) {
1073    User* UI = srcUseList.back();
1074    srcUseList.pop_back();
1075
1076    if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
1077      for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
1078           I != E; ++I)
1079        srcUseList.push_back(*I);
1080    } else if (UI != C && UI != cpy) {
1081      return false;
1082    }
1083  }
1084
1085  // Since we're changing the parameter to the callsite, we need to make sure
1086  // that what would be the new parameter dominates the callsite.
1087  DominatorTree& DT = getAnalysis<DominatorTree>();
1088  if (Instruction* cpyDestInst = dyn_cast<Instruction>(cpyDest))
1089    if (!DT.dominates(cpyDestInst, C))
1090      return false;
1091
1092  // In addition to knowing that the call does not access src in some
1093  // unexpected manner, for example via a global, which we deduce from
1094  // the use analysis, we also need to know that it does not sneakily
1095  // access dest.  We rely on AA to figure this out for us.
1096  AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1097  if (AA.getModRefInfo(C, cpy->getRawDest(), srcSize) !=
1098      AliasAnalysis::NoModRef)
1099    return false;
1100
1101  // All the checks have passed, so do the transformation.
1102  for (unsigned i = 0; i < CS.arg_size(); ++i)
1103    if (CS.getArgument(i) == cpySrc) {
1104      if (cpySrc->getType() != cpyDest->getType())
1105        cpyDest = CastInst::createPointerCast(cpyDest, cpySrc->getType(),
1106                                              cpyDest->getName(), C);
1107      CS.setArgument(i, cpyDest);
1108    }
1109
1110  // Drop any cached information about the call, because we may have changed
1111  // its dependence information by changing its parameter.
1112  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1113  MD.dropInstruction(C);
1114
1115  // Remove the memcpy
1116  MD.removeInstruction(cpy);
1117  toErase.push_back(cpy);
1118
1119  return true;
1120}
1121
1122/// processMemCpy - perform simplication of memcpy's.  If we have memcpy A which
1123/// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
1124/// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
1125///  This allows later passes to remove the first memcpy altogether.
1126bool GVN::processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
1127                        SmallVector<Instruction*, 4>& toErase) {
1128  // We can only transforms memcpy's where the dest of one is the source of the
1129  // other
1130  if (M->getSource() != MDep->getDest())
1131    return false;
1132
1133  // Second, the length of the memcpy's must be the same, or the preceeding one
1134  // must be larger than the following one.
1135  ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
1136  ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
1137  if (!C1 || !C2)
1138    return false;
1139
1140  uint64_t DepSize = C1->getValue().getZExtValue();
1141  uint64_t CpySize = C2->getValue().getZExtValue();
1142
1143  if (DepSize < CpySize)
1144    return false;
1145
1146  // Finally, we have to make sure that the dest of the second does not
1147  // alias the source of the first
1148  AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1149  if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
1150      AliasAnalysis::NoAlias)
1151    return false;
1152  else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
1153           AliasAnalysis::NoAlias)
1154    return false;
1155  else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
1156           != AliasAnalysis::NoAlias)
1157    return false;
1158
1159  // If all checks passed, then we can transform these memcpy's
1160  Function* MemCpyFun = Intrinsic::getDeclaration(
1161                                 M->getParent()->getParent()->getParent(),
1162                                 M->getIntrinsicID());
1163
1164  std::vector<Value*> args;
1165  args.push_back(M->getRawDest());
1166  args.push_back(MDep->getRawSource());
1167  args.push_back(M->getLength());
1168  args.push_back(M->getAlignment());
1169
1170  CallInst* C = new CallInst(MemCpyFun, args.begin(), args.end(), "", M);
1171
1172  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1173  if (MD.getDependency(C) == MDep) {
1174    MD.dropInstruction(M);
1175    toErase.push_back(M);
1176    return true;
1177  }
1178
1179  MD.removeInstruction(C);
1180  toErase.push_back(C);
1181  return false;
1182}
1183
1184/// processInstruction - When calculating availability, handle an instruction
1185/// by inserting it into the appropriate sets
1186bool GVN::processInstruction(Instruction* I,
1187                                ValueNumberedSet& currAvail,
1188                                DenseMap<Value*, LoadInst*>& lastSeenLoad,
1189                                SmallVector<Instruction*, 4>& toErase) {
1190  if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1191    return processLoad(L, lastSeenLoad, toErase);
1192  } else if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
1193    MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1194
1195    // The are two possible optimizations we can do for memcpy:
1196    //   a) memcpy-memcpy xform which exposes redundance for DSE
1197    //   b) call-memcpy xform for return slot optimization
1198    Instruction* dep = MD.getDependency(M);
1199    if (dep == MemoryDependenceAnalysis::None ||
1200        dep == MemoryDependenceAnalysis::NonLocal)
1201      return false;
1202    if (MemCpyInst *MemCpy = dyn_cast<MemCpyInst>(dep))
1203      return processMemCpy(M, MemCpy, toErase);
1204    if (CallInst* C = dyn_cast<CallInst>(dep))
1205      return performCallSlotOptzn(M, C, toErase);
1206    return false;
1207  }
1208
1209  unsigned num = VN.lookup_or_add(I);
1210
1211  // Collapse PHI nodes
1212  if (PHINode* p = dyn_cast<PHINode>(I)) {
1213    Value* constVal = CollapsePhi(p);
1214
1215    if (constVal) {
1216      for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1217           PI != PE; ++PI)
1218        if (PI->second.count(p))
1219          PI->second.erase(p);
1220
1221      p->replaceAllUsesWith(constVal);
1222      toErase.push_back(p);
1223    }
1224  // Perform value-number based elimination
1225  } else if (currAvail.test(num)) {
1226    Value* repl = find_leader(currAvail, num);
1227
1228    if (CallInst* CI = dyn_cast<CallInst>(I)) {
1229      AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1230      if (!AA.doesNotAccessMemory(CI)) {
1231        MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1232        if (cast<Instruction>(repl)->getParent() != CI->getParent() ||
1233            MD.getDependency(CI) != MD.getDependency(cast<CallInst>(repl))) {
1234          // There must be an intervening may-alias store, so nothing from
1235          // this point on will be able to be replaced with the preceding call
1236          currAvail.erase(repl);
1237          currAvail.insert(I);
1238
1239          return false;
1240        }
1241      }
1242    }
1243
1244    // Remove it!
1245    MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1246    MD.removeInstruction(I);
1247
1248    VN.erase(I);
1249    I->replaceAllUsesWith(repl);
1250    toErase.push_back(I);
1251    return true;
1252  } else if (!I->isTerminator()) {
1253    currAvail.set(num);
1254    currAvail.insert(I);
1255  }
1256
1257  return false;
1258}
1259
1260// GVN::runOnFunction - This is the main transformation entry point for a
1261// function.
1262//
1263bool GVN::runOnFunction(Function& F) {
1264  VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1265
1266  bool changed = false;
1267  bool shouldContinue = true;
1268
1269  while (shouldContinue) {
1270    shouldContinue = iterateOnFunction(F);
1271    changed |= shouldContinue;
1272  }
1273
1274  return changed;
1275}
1276
1277
1278// GVN::iterateOnFunction - Executes one iteration of GVN
1279bool GVN::iterateOnFunction(Function &F) {
1280  // Clean out global sets from any previous functions
1281  VN.clear();
1282  availableOut.clear();
1283  phiMap.clear();
1284
1285  bool changed_function = false;
1286
1287  DominatorTree &DT = getAnalysis<DominatorTree>();
1288
1289  SmallVector<Instruction*, 4> toErase;
1290
1291  // Top-down walk of the dominator tree
1292  for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1293         E = df_end(DT.getRootNode()); DI != E; ++DI) {
1294
1295    // Get the set to update for this block
1296    ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1297    DenseMap<Value*, LoadInst*> lastSeenLoad;
1298
1299    BasicBlock* BB = DI->getBlock();
1300
1301    // A block inherits AVAIL_OUT from its dominator
1302    if (DI->getIDom() != 0)
1303      currAvail = availableOut[DI->getIDom()->getBlock()];
1304
1305    for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1306         BI != BE; ) {
1307      changed_function |= processInstruction(BI, currAvail,
1308                                             lastSeenLoad, toErase);
1309
1310      NumGVNInstr += toErase.size();
1311
1312      // Avoid iterator invalidation
1313      ++BI;
1314
1315      for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1316           E = toErase.end(); I != E; ++I)
1317        (*I)->eraseFromParent();
1318
1319      toErase.clear();
1320    }
1321  }
1322
1323  return changed_function;
1324}
1325