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