GVN.cpp revision 83d63919bd990ce00f62e18114504b9e4a5cb35e
19fc12334a7d14347cd6951d0653264b2597bd3a0Sam Judd//===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
20ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd//
30ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd//                     The LLVM Compiler Infrastructure
40ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd//
5bcf4a0dae04a4ad14287eeb34069a97c96fe9bb1Sam Judd// This file is distributed under the University of Illinois Open Source
60ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd// License. See LICENSE.TXT for details.
70ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd//
80ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd//===----------------------------------------------------------------------===//
90ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd//
10fcd787c911d5fbca2a34ff0963d4665543a03275Sam Judd// This pass performs global value numbering to eliminate fully redundant
110ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd// instructions.  It also performs simple dead load elimination.
12fcd787c911d5fbca2a34ff0963d4665543a03275Sam Judd//
130ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd// Note that this pass does the value numbering itself; it does not use the
140ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd// ValueNumbering analysis passes.
15fcd787c911d5fbca2a34ff0963d4665543a03275Sam Judd//
160ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd//===----------------------------------------------------------------------===//
170ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd
180ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd#define DEBUG_TYPE "gvn"
190ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd#include "llvm/Transforms/Scalar.h"
200ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd#include "llvm/BasicBlock.h"
21bcf4a0dae04a4ad14287eeb34069a97c96fe9bb1Sam Judd#include "llvm/Constants.h"
220ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd#include "llvm/DerivedTypes.h"
230ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd#include "llvm/Function.h"
240ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd#include "llvm/IntrinsicInst.h"
250ae32dc10d668a04f9f0484d587aefe5a7210e1cSam Judd#include "llvm/LLVMContext.h"
26#include "llvm/Value.h"
27#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/DepthFirstIterator.h"
29#include "llvm/ADT/PostOrderIterator.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/Statistic.h"
33#include "llvm/Analysis/Dominators.h"
34#include "llvm/Analysis/AliasAnalysis.h"
35#include "llvm/Analysis/MallocHelper.h"
36#include "llvm/Analysis/MemoryDependenceAnalysis.h"
37#include "llvm/Support/CFG.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/raw_ostream.h"
42#include "llvm/Transforms/Utils/BasicBlockUtils.h"
43#include "llvm/Transforms/Utils/Local.h"
44#include <cstdio>
45using namespace llvm;
46
47STATISTIC(NumGVNInstr,  "Number of instructions deleted");
48STATISTIC(NumGVNLoad,   "Number of loads deleted");
49STATISTIC(NumGVNPRE,    "Number of instructions PRE'd");
50STATISTIC(NumGVNBlocks, "Number of blocks merged");
51STATISTIC(NumPRELoad,   "Number of loads PRE'd");
52
53static cl::opt<bool> EnablePRE("enable-pre",
54                               cl::init(true), cl::Hidden);
55static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
56
57//===----------------------------------------------------------------------===//
58//                         ValueTable Class
59//===----------------------------------------------------------------------===//
60
61/// This class holds the mapping between values and value numbers.  It is used
62/// as an efficient mechanism to determine the expression-wise equivalence of
63/// two values.
64namespace {
65  struct Expression {
66    enum ExpressionOpcode { ADD, FADD, SUB, FSUB, MUL, FMUL,
67                            UDIV, SDIV, FDIV, UREM, SREM,
68                            FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
69                            ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
70                            ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
71                            FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
72                            FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
73                            FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
74                            SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
75                            FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
76                            PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
77                            EMPTY, TOMBSTONE };
78
79    ExpressionOpcode opcode;
80    const Type* type;
81    uint32_t firstVN;
82    uint32_t secondVN;
83    uint32_t thirdVN;
84    SmallVector<uint32_t, 4> varargs;
85    Value* function;
86
87    Expression() { }
88    Expression(ExpressionOpcode o) : opcode(o) { }
89
90    bool operator==(const Expression &other) const {
91      if (opcode != other.opcode)
92        return false;
93      else if (opcode == EMPTY || opcode == TOMBSTONE)
94        return true;
95      else if (type != other.type)
96        return false;
97      else if (function != other.function)
98        return false;
99      else if (firstVN != other.firstVN)
100        return false;
101      else if (secondVN != other.secondVN)
102        return false;
103      else if (thirdVN != other.thirdVN)
104        return false;
105      else {
106        if (varargs.size() != other.varargs.size())
107          return false;
108
109        for (size_t i = 0; i < varargs.size(); ++i)
110          if (varargs[i] != other.varargs[i])
111            return false;
112
113        return true;
114      }
115    }
116
117    bool operator!=(const Expression &other) const {
118      return !(*this == other);
119    }
120  };
121
122  class ValueTable {
123    private:
124      DenseMap<Value*, uint32_t> valueNumbering;
125      DenseMap<Expression, uint32_t> expressionNumbering;
126      AliasAnalysis* AA;
127      MemoryDependenceAnalysis* MD;
128      DominatorTree* DT;
129
130      uint32_t nextValueNumber;
131
132      Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
133      Expression::ExpressionOpcode getOpcode(CmpInst* C);
134      Expression::ExpressionOpcode getOpcode(CastInst* C);
135      Expression create_expression(BinaryOperator* BO);
136      Expression create_expression(CmpInst* C);
137      Expression create_expression(ShuffleVectorInst* V);
138      Expression create_expression(ExtractElementInst* C);
139      Expression create_expression(InsertElementInst* V);
140      Expression create_expression(SelectInst* V);
141      Expression create_expression(CastInst* C);
142      Expression create_expression(GetElementPtrInst* G);
143      Expression create_expression(CallInst* C);
144      Expression create_expression(Constant* C);
145    public:
146      ValueTable() : nextValueNumber(1) { }
147      uint32_t lookup_or_add(Value* V);
148      uint32_t lookup(Value* V) const;
149      void add(Value* V, uint32_t num);
150      void clear();
151      void erase(Value* v);
152      unsigned size();
153      void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
154      AliasAnalysis *getAliasAnalysis() const { return AA; }
155      void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
156      void setDomTree(DominatorTree* D) { DT = D; }
157      uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
158      void verifyRemoved(const Value *) const;
159  };
160}
161
162namespace llvm {
163template <> struct DenseMapInfo<Expression> {
164  static inline Expression getEmptyKey() {
165    return Expression(Expression::EMPTY);
166  }
167
168  static inline Expression getTombstoneKey() {
169    return Expression(Expression::TOMBSTONE);
170  }
171
172  static unsigned getHashValue(const Expression e) {
173    unsigned hash = e.opcode;
174
175    hash = e.firstVN + hash * 37;
176    hash = e.secondVN + hash * 37;
177    hash = e.thirdVN + hash * 37;
178
179    hash = ((unsigned)((uintptr_t)e.type >> 4) ^
180            (unsigned)((uintptr_t)e.type >> 9)) +
181           hash * 37;
182
183    for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
184         E = e.varargs.end(); I != E; ++I)
185      hash = *I + hash * 37;
186
187    hash = ((unsigned)((uintptr_t)e.function >> 4) ^
188            (unsigned)((uintptr_t)e.function >> 9)) +
189           hash * 37;
190
191    return hash;
192  }
193  static bool isEqual(const Expression &LHS, const Expression &RHS) {
194    return LHS == RHS;
195  }
196  static bool isPod() { return true; }
197};
198}
199
200//===----------------------------------------------------------------------===//
201//                     ValueTable Internal Functions
202//===----------------------------------------------------------------------===//
203Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
204  switch(BO->getOpcode()) {
205  default: // THIS SHOULD NEVER HAPPEN
206    llvm_unreachable("Binary operator with unknown opcode?");
207  case Instruction::Add:  return Expression::ADD;
208  case Instruction::FAdd: return Expression::FADD;
209  case Instruction::Sub:  return Expression::SUB;
210  case Instruction::FSub: return Expression::FSUB;
211  case Instruction::Mul:  return Expression::MUL;
212  case Instruction::FMul: return Expression::FMUL;
213  case Instruction::UDiv: return Expression::UDIV;
214  case Instruction::SDiv: return Expression::SDIV;
215  case Instruction::FDiv: return Expression::FDIV;
216  case Instruction::URem: return Expression::UREM;
217  case Instruction::SRem: return Expression::SREM;
218  case Instruction::FRem: return Expression::FREM;
219  case Instruction::Shl:  return Expression::SHL;
220  case Instruction::LShr: return Expression::LSHR;
221  case Instruction::AShr: return Expression::ASHR;
222  case Instruction::And:  return Expression::AND;
223  case Instruction::Or:   return Expression::OR;
224  case Instruction::Xor:  return Expression::XOR;
225  }
226}
227
228Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
229  if (isa<ICmpInst>(C)) {
230    switch (C->getPredicate()) {
231    default:  // THIS SHOULD NEVER HAPPEN
232      llvm_unreachable("Comparison with unknown predicate?");
233    case ICmpInst::ICMP_EQ:  return Expression::ICMPEQ;
234    case ICmpInst::ICMP_NE:  return Expression::ICMPNE;
235    case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
236    case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
237    case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
238    case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
239    case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
240    case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
241    case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
242    case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
243    }
244  } else {
245    switch (C->getPredicate()) {
246    default: // THIS SHOULD NEVER HAPPEN
247      llvm_unreachable("Comparison with unknown predicate?");
248    case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
249    case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
250    case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
251    case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
252    case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
253    case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
254    case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
255    case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
256    case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
257    case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
258    case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
259    case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
260    case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
261    case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
262    }
263  }
264}
265
266Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
267  switch(C->getOpcode()) {
268  default: // THIS SHOULD NEVER HAPPEN
269    llvm_unreachable("Cast operator with unknown opcode?");
270  case Instruction::Trunc:    return Expression::TRUNC;
271  case Instruction::ZExt:     return Expression::ZEXT;
272  case Instruction::SExt:     return Expression::SEXT;
273  case Instruction::FPToUI:   return Expression::FPTOUI;
274  case Instruction::FPToSI:   return Expression::FPTOSI;
275  case Instruction::UIToFP:   return Expression::UITOFP;
276  case Instruction::SIToFP:   return Expression::SITOFP;
277  case Instruction::FPTrunc:  return Expression::FPTRUNC;
278  case Instruction::FPExt:    return Expression::FPEXT;
279  case Instruction::PtrToInt: return Expression::PTRTOINT;
280  case Instruction::IntToPtr: return Expression::INTTOPTR;
281  case Instruction::BitCast:  return Expression::BITCAST;
282  }
283}
284
285Expression ValueTable::create_expression(CallInst* C) {
286  Expression e;
287
288  e.type = C->getType();
289  e.firstVN = 0;
290  e.secondVN = 0;
291  e.thirdVN = 0;
292  e.function = C->getCalledFunction();
293  e.opcode = Expression::CALL;
294
295  for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
296       I != E; ++I)
297    e.varargs.push_back(lookup_or_add(*I));
298
299  return e;
300}
301
302Expression ValueTable::create_expression(BinaryOperator* BO) {
303  Expression e;
304
305  e.firstVN = lookup_or_add(BO->getOperand(0));
306  e.secondVN = lookup_or_add(BO->getOperand(1));
307  e.thirdVN = 0;
308  e.function = 0;
309  e.type = BO->getType();
310  e.opcode = getOpcode(BO);
311
312  return e;
313}
314
315Expression ValueTable::create_expression(CmpInst* C) {
316  Expression e;
317
318  e.firstVN = lookup_or_add(C->getOperand(0));
319  e.secondVN = lookup_or_add(C->getOperand(1));
320  e.thirdVN = 0;
321  e.function = 0;
322  e.type = C->getType();
323  e.opcode = getOpcode(C);
324
325  return e;
326}
327
328Expression ValueTable::create_expression(CastInst* C) {
329  Expression e;
330
331  e.firstVN = lookup_or_add(C->getOperand(0));
332  e.secondVN = 0;
333  e.thirdVN = 0;
334  e.function = 0;
335  e.type = C->getType();
336  e.opcode = getOpcode(C);
337
338  return e;
339}
340
341Expression ValueTable::create_expression(ShuffleVectorInst* S) {
342  Expression e;
343
344  e.firstVN = lookup_or_add(S->getOperand(0));
345  e.secondVN = lookup_or_add(S->getOperand(1));
346  e.thirdVN = lookup_or_add(S->getOperand(2));
347  e.function = 0;
348  e.type = S->getType();
349  e.opcode = Expression::SHUFFLE;
350
351  return e;
352}
353
354Expression ValueTable::create_expression(ExtractElementInst* E) {
355  Expression e;
356
357  e.firstVN = lookup_or_add(E->getOperand(0));
358  e.secondVN = lookup_or_add(E->getOperand(1));
359  e.thirdVN = 0;
360  e.function = 0;
361  e.type = E->getType();
362  e.opcode = Expression::EXTRACT;
363
364  return e;
365}
366
367Expression ValueTable::create_expression(InsertElementInst* I) {
368  Expression e;
369
370  e.firstVN = lookup_or_add(I->getOperand(0));
371  e.secondVN = lookup_or_add(I->getOperand(1));
372  e.thirdVN = lookup_or_add(I->getOperand(2));
373  e.function = 0;
374  e.type = I->getType();
375  e.opcode = Expression::INSERT;
376
377  return e;
378}
379
380Expression ValueTable::create_expression(SelectInst* I) {
381  Expression e;
382
383  e.firstVN = lookup_or_add(I->getCondition());
384  e.secondVN = lookup_or_add(I->getTrueValue());
385  e.thirdVN = lookup_or_add(I->getFalseValue());
386  e.function = 0;
387  e.type = I->getType();
388  e.opcode = Expression::SELECT;
389
390  return e;
391}
392
393Expression ValueTable::create_expression(GetElementPtrInst* G) {
394  Expression e;
395
396  e.firstVN = lookup_or_add(G->getPointerOperand());
397  e.secondVN = 0;
398  e.thirdVN = 0;
399  e.function = 0;
400  e.type = G->getType();
401  e.opcode = Expression::GEP;
402
403  for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
404       I != E; ++I)
405    e.varargs.push_back(lookup_or_add(*I));
406
407  return e;
408}
409
410//===----------------------------------------------------------------------===//
411//                     ValueTable External Functions
412//===----------------------------------------------------------------------===//
413
414/// add - Insert a value into the table with a specified value number.
415void ValueTable::add(Value* V, uint32_t num) {
416  valueNumbering.insert(std::make_pair(V, num));
417}
418
419/// lookup_or_add - Returns the value number for the specified value, assigning
420/// it a new number if it did not have one before.
421uint32_t ValueTable::lookup_or_add(Value* V) {
422  DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
423  if (VI != valueNumbering.end())
424    return VI->second;
425
426  if (CallInst* C = dyn_cast<CallInst>(V)) {
427    if (AA->doesNotAccessMemory(C)) {
428      Expression e = create_expression(C);
429
430      DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
431      if (EI != expressionNumbering.end()) {
432        valueNumbering.insert(std::make_pair(V, EI->second));
433        return EI->second;
434      } else {
435        expressionNumbering.insert(std::make_pair(e, nextValueNumber));
436        valueNumbering.insert(std::make_pair(V, nextValueNumber));
437
438        return nextValueNumber++;
439      }
440    } else if (AA->onlyReadsMemory(C)) {
441      Expression e = create_expression(C);
442
443      if (expressionNumbering.find(e) == expressionNumbering.end()) {
444        expressionNumbering.insert(std::make_pair(e, nextValueNumber));
445        valueNumbering.insert(std::make_pair(V, nextValueNumber));
446        return nextValueNumber++;
447      }
448
449      MemDepResult local_dep = MD->getDependency(C);
450
451      if (!local_dep.isDef() && !local_dep.isNonLocal()) {
452        valueNumbering.insert(std::make_pair(V, nextValueNumber));
453        return nextValueNumber++;
454      }
455
456      if (local_dep.isDef()) {
457        CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
458
459        if (local_cdep->getNumOperands() != C->getNumOperands()) {
460          valueNumbering.insert(std::make_pair(V, nextValueNumber));
461          return nextValueNumber++;
462        }
463
464        for (unsigned i = 1; i < C->getNumOperands(); ++i) {
465          uint32_t c_vn = lookup_or_add(C->getOperand(i));
466          uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
467          if (c_vn != cd_vn) {
468            valueNumbering.insert(std::make_pair(V, nextValueNumber));
469            return nextValueNumber++;
470          }
471        }
472
473        uint32_t v = lookup_or_add(local_cdep);
474        valueNumbering.insert(std::make_pair(V, v));
475        return v;
476      }
477
478      // Non-local case.
479      const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
480        MD->getNonLocalCallDependency(CallSite(C));
481      // FIXME: call/call dependencies for readonly calls should return def, not
482      // clobber!  Move the checking logic to MemDep!
483      CallInst* cdep = 0;
484
485      // Check to see if we have a single dominating call instruction that is
486      // identical to C.
487      for (unsigned i = 0, e = deps.size(); i != e; ++i) {
488        const MemoryDependenceAnalysis::NonLocalDepEntry *I = &deps[i];
489        // Ignore non-local dependencies.
490        if (I->second.isNonLocal())
491          continue;
492
493        // We don't handle non-depedencies.  If we already have a call, reject
494        // instruction dependencies.
495        if (I->second.isClobber() || cdep != 0) {
496          cdep = 0;
497          break;
498        }
499
500        CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->second.getInst());
501        // FIXME: All duplicated with non-local case.
502        if (NonLocalDepCall && DT->properlyDominates(I->first, C->getParent())){
503          cdep = NonLocalDepCall;
504          continue;
505        }
506
507        cdep = 0;
508        break;
509      }
510
511      if (!cdep) {
512        valueNumbering.insert(std::make_pair(V, nextValueNumber));
513        return nextValueNumber++;
514      }
515
516      if (cdep->getNumOperands() != C->getNumOperands()) {
517        valueNumbering.insert(std::make_pair(V, nextValueNumber));
518        return nextValueNumber++;
519      }
520      for (unsigned i = 1; i < C->getNumOperands(); ++i) {
521        uint32_t c_vn = lookup_or_add(C->getOperand(i));
522        uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
523        if (c_vn != cd_vn) {
524          valueNumbering.insert(std::make_pair(V, nextValueNumber));
525          return nextValueNumber++;
526        }
527      }
528
529      uint32_t v = lookup_or_add(cdep);
530      valueNumbering.insert(std::make_pair(V, v));
531      return v;
532
533    } else {
534      valueNumbering.insert(std::make_pair(V, nextValueNumber));
535      return nextValueNumber++;
536    }
537  } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
538    Expression e = create_expression(BO);
539
540    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
541    if (EI != expressionNumbering.end()) {
542      valueNumbering.insert(std::make_pair(V, EI->second));
543      return EI->second;
544    } else {
545      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
546      valueNumbering.insert(std::make_pair(V, nextValueNumber));
547
548      return nextValueNumber++;
549    }
550  } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
551    Expression e = create_expression(C);
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 (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
564    Expression e = create_expression(U);
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 (ExtractElementInst* U = dyn_cast<ExtractElementInst>(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 (InsertElementInst* U = dyn_cast<InsertElementInst>(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 (SelectInst* U = dyn_cast<SelectInst>(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 (CastInst* U = dyn_cast<CastInst>(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 (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(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 {
642    valueNumbering.insert(std::make_pair(V, nextValueNumber));
643    return nextValueNumber++;
644  }
645}
646
647/// lookup - Returns the value number of the specified value. Fails if
648/// the value has not yet been numbered.
649uint32_t ValueTable::lookup(Value* V) const {
650  DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
651  assert(VI != valueNumbering.end() && "Value not numbered?");
652  return VI->second;
653}
654
655/// clear - Remove all entries from the ValueTable
656void ValueTable::clear() {
657  valueNumbering.clear();
658  expressionNumbering.clear();
659  nextValueNumber = 1;
660}
661
662/// erase - Remove a value from the value numbering
663void ValueTable::erase(Value* V) {
664  valueNumbering.erase(V);
665}
666
667/// verifyRemoved - Verify that the value is removed from all internal data
668/// structures.
669void ValueTable::verifyRemoved(const Value *V) const {
670  for (DenseMap<Value*, uint32_t>::iterator
671         I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
672    assert(I->first != V && "Inst still occurs in value numbering map!");
673  }
674}
675
676//===----------------------------------------------------------------------===//
677//                                GVN Pass
678//===----------------------------------------------------------------------===//
679
680namespace {
681  struct ValueNumberScope {
682    ValueNumberScope* parent;
683    DenseMap<uint32_t, Value*> table;
684
685    ValueNumberScope(ValueNumberScope* p) : parent(p) { }
686  };
687}
688
689namespace {
690
691  class GVN : public FunctionPass {
692    bool runOnFunction(Function &F);
693  public:
694    static char ID; // Pass identification, replacement for typeid
695    GVN() : FunctionPass(&ID) { }
696
697  private:
698    MemoryDependenceAnalysis *MD;
699    DominatorTree *DT;
700
701    ValueTable VN;
702    DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
703
704    typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
705    PhiMapType phiMap;
706
707
708    // This transformation requires dominator postdominator info
709    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
710      AU.addRequired<DominatorTree>();
711      AU.addRequired<MemoryDependenceAnalysis>();
712      AU.addRequired<AliasAnalysis>();
713
714      AU.addPreserved<DominatorTree>();
715      AU.addPreserved<AliasAnalysis>();
716    }
717
718    // Helper fuctions
719    // FIXME: eliminate or document these better
720    bool processLoad(LoadInst* L,
721                     SmallVectorImpl<Instruction*> &toErase);
722    bool processInstruction(Instruction* I,
723                            SmallVectorImpl<Instruction*> &toErase);
724    bool processNonLocalLoad(LoadInst* L,
725                             SmallVectorImpl<Instruction*> &toErase);
726    bool processBlock(BasicBlock* BB);
727    Value *GetValueForBlock(BasicBlock *BB, Instruction* orig,
728                            DenseMap<BasicBlock*, Value*> &Phis,
729                            bool top_level = false);
730    void dump(DenseMap<uint32_t, Value*>& d);
731    bool iterateOnFunction(Function &F);
732    Value* CollapsePhi(PHINode* p);
733    bool performPRE(Function& F);
734    Value* lookupNumber(BasicBlock* BB, uint32_t num);
735    Value* AttemptRedundancyElimination(Instruction* orig, unsigned valno);
736    void cleanupGlobalSets();
737    void verifyRemoved(const Instruction *I) const;
738  };
739
740  char GVN::ID = 0;
741}
742
743// createGVNPass - The public interface to this file...
744FunctionPass *llvm::createGVNPass() { return new GVN(); }
745
746static RegisterPass<GVN> X("gvn",
747                           "Global Value Numbering");
748
749void GVN::dump(DenseMap<uint32_t, Value*>& d) {
750  printf("{\n");
751  for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
752       E = d.end(); I != E; ++I) {
753      printf("%d\n", I->first);
754      I->second->dump();
755  }
756  printf("}\n");
757}
758
759static bool isSafeReplacement(PHINode* p, Instruction* inst) {
760  if (!isa<PHINode>(inst))
761    return true;
762
763  for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
764       UI != E; ++UI)
765    if (PHINode* use_phi = dyn_cast<PHINode>(UI))
766      if (use_phi->getParent() == inst->getParent())
767        return false;
768
769  return true;
770}
771
772Value* GVN::CollapsePhi(PHINode* p) {
773  Value* constVal = p->hasConstantValue(DT);
774  if (!constVal) return 0;
775
776  Instruction* inst = dyn_cast<Instruction>(constVal);
777  if (!inst)
778    return constVal;
779
780  if (DT->dominates(inst, p))
781    if (isSafeReplacement(p, inst))
782      return inst;
783  return 0;
784}
785
786/// GetValueForBlock - Get the value to use within the specified basic block.
787/// available values are in Phis.
788Value *GVN::GetValueForBlock(BasicBlock *BB, Instruction* orig,
789                             DenseMap<BasicBlock*, Value*> &Phis,
790                             bool top_level) {
791
792  // If we have already computed this value, return the previously computed val.
793  DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
794  if (V != Phis.end() && !top_level) return V->second;
795
796  // If the block is unreachable, just return undef, since this path
797  // can't actually occur at runtime.
798  if (!DT->isReachableFromEntry(BB))
799    return Phis[BB] = UndefValue::get(orig->getType());
800
801  if (BasicBlock *Pred = BB->getSinglePredecessor()) {
802    Value *ret = GetValueForBlock(Pred, orig, Phis);
803    Phis[BB] = ret;
804    return ret;
805  }
806
807  // Get the number of predecessors of this block so we can reserve space later.
808  // If there is already a PHI in it, use the #preds from it, otherwise count.
809  // Getting it from the PHI is constant time.
810  unsigned NumPreds;
811  if (PHINode *ExistingPN = dyn_cast<PHINode>(BB->begin()))
812    NumPreds = ExistingPN->getNumIncomingValues();
813  else
814    NumPreds = std::distance(pred_begin(BB), pred_end(BB));
815
816  // Otherwise, the idom is the loop, so we need to insert a PHI node.  Do so
817  // now, then get values to fill in the incoming values for the PHI.
818  PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
819                                BB->begin());
820  PN->reserveOperandSpace(NumPreds);
821
822  Phis.insert(std::make_pair(BB, PN));
823
824  // Fill in the incoming values for the block.
825  for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
826    Value* val = GetValueForBlock(*PI, orig, Phis);
827    PN->addIncoming(val, *PI);
828  }
829
830  VN.getAliasAnalysis()->copyValue(orig, PN);
831
832  // Attempt to collapse PHI nodes that are trivially redundant
833  Value* v = CollapsePhi(PN);
834  if (!v) {
835    // Cache our phi construction results
836    if (LoadInst* L = dyn_cast<LoadInst>(orig))
837      phiMap[L->getPointerOperand()].insert(PN);
838    else
839      phiMap[orig].insert(PN);
840
841    return PN;
842  }
843
844  PN->replaceAllUsesWith(v);
845  if (isa<PointerType>(v->getType()))
846    MD->invalidateCachedPointerInfo(v);
847
848  for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
849       E = Phis.end(); I != E; ++I)
850    if (I->second == PN)
851      I->second = v;
852
853  DEBUG(errs() << "GVN removed: " << *PN << '\n');
854  MD->removeInstruction(PN);
855  PN->eraseFromParent();
856  DEBUG(verifyRemoved(PN));
857
858  Phis[BB] = v;
859  return v;
860}
861
862/// IsValueFullyAvailableInBlock - Return true if we can prove that the value
863/// we're analyzing is fully available in the specified block.  As we go, keep
864/// track of which blocks we know are fully alive in FullyAvailableBlocks.  This
865/// map is actually a tri-state map with the following values:
866///   0) we know the block *is not* fully available.
867///   1) we know the block *is* fully available.
868///   2) we do not know whether the block is fully available or not, but we are
869///      currently speculating that it will be.
870///   3) we are speculating for this block and have used that to speculate for
871///      other blocks.
872static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
873                            DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
874  // Optimistically assume that the block is fully available and check to see
875  // if we already know about this block in one lookup.
876  std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
877    FullyAvailableBlocks.insert(std::make_pair(BB, 2));
878
879  // If the entry already existed for this block, return the precomputed value.
880  if (!IV.second) {
881    // If this is a speculative "available" value, mark it as being used for
882    // speculation of other blocks.
883    if (IV.first->second == 2)
884      IV.first->second = 3;
885    return IV.first->second != 0;
886  }
887
888  // Otherwise, see if it is fully available in all predecessors.
889  pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
890
891  // If this block has no predecessors, it isn't live-in here.
892  if (PI == PE)
893    goto SpeculationFailure;
894
895  for (; PI != PE; ++PI)
896    // If the value isn't fully available in one of our predecessors, then it
897    // isn't fully available in this block either.  Undo our previous
898    // optimistic assumption and bail out.
899    if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
900      goto SpeculationFailure;
901
902  return true;
903
904// SpeculationFailure - If we get here, we found out that this is not, after
905// all, a fully-available block.  We have a problem if we speculated on this and
906// used the speculation to mark other blocks as available.
907SpeculationFailure:
908  char &BBVal = FullyAvailableBlocks[BB];
909
910  // If we didn't speculate on this, just return with it set to false.
911  if (BBVal == 2) {
912    BBVal = 0;
913    return false;
914  }
915
916  // If we did speculate on this value, we could have blocks set to 1 that are
917  // incorrect.  Walk the (transitive) successors of this block and mark them as
918  // 0 if set to one.
919  SmallVector<BasicBlock*, 32> BBWorklist;
920  BBWorklist.push_back(BB);
921
922  while (!BBWorklist.empty()) {
923    BasicBlock *Entry = BBWorklist.pop_back_val();
924    // Note that this sets blocks to 0 (unavailable) if they happen to not
925    // already be in FullyAvailableBlocks.  This is safe.
926    char &EntryVal = FullyAvailableBlocks[Entry];
927    if (EntryVal == 0) continue;  // Already unavailable.
928
929    // Mark as unavailable.
930    EntryVal = 0;
931
932    for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
933      BBWorklist.push_back(*I);
934  }
935
936  return false;
937}
938
939/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
940/// non-local by performing PHI construction.
941bool GVN::processNonLocalLoad(LoadInst *LI,
942                              SmallVectorImpl<Instruction*> &toErase) {
943  // Find the non-local dependencies of the load.
944  SmallVector<MemoryDependenceAnalysis::NonLocalDepEntry, 64> Deps;
945  MD->getNonLocalPointerDependency(LI->getOperand(0), true, LI->getParent(),
946                                   Deps);
947  //DEBUG(errs() << "INVESTIGATING NONLOCAL LOAD: "
948  //             << Deps.size() << *LI << '\n');
949
950  // If we had to process more than one hundred blocks to find the
951  // dependencies, this load isn't worth worrying about.  Optimizing
952  // it will be too expensive.
953  if (Deps.size() > 100)
954    return false;
955
956  // If we had a phi translation failure, we'll have a single entry which is a
957  // clobber in the current block.  Reject this early.
958  if (Deps.size() == 1 && Deps[0].second.isClobber()) {
959    DEBUG(
960      errs() << "GVN: non-local load ";
961      WriteAsOperand(errs(), LI);
962      errs() << " is clobbered by " << *Deps[0].second.getInst() << '\n';
963    );
964    return false;
965  }
966
967  // Filter out useless results (non-locals, etc).  Keep track of the blocks
968  // where we have a value available in repl, also keep track of whether we see
969  // dependencies that produce an unknown value for the load (such as a call
970  // that could potentially clobber the load).
971  SmallVector<std::pair<BasicBlock*, Value*>, 16> ValuesPerBlock;
972  SmallVector<BasicBlock*, 16> UnavailableBlocks;
973
974  for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
975    BasicBlock *DepBB = Deps[i].first;
976    MemDepResult DepInfo = Deps[i].second;
977
978    if (DepInfo.isClobber()) {
979      UnavailableBlocks.push_back(DepBB);
980      continue;
981    }
982
983    Instruction *DepInst = DepInfo.getInst();
984
985    // Loading the allocation -> undef.
986    if (isa<AllocationInst>(DepInst) || isMalloc(DepInst)) {
987      ValuesPerBlock.push_back(std::make_pair(DepBB,
988                               UndefValue::get(LI->getType())));
989      continue;
990    }
991
992    if (StoreInst* S = dyn_cast<StoreInst>(DepInst)) {
993      // Reject loads and stores that are to the same address but are of
994      // different types.
995      // NOTE: 403.gcc does have this case (e.g. in readonly_fields_p) because
996      // of bitfield access, it would be interesting to optimize for it at some
997      // point.
998      if (S->getOperand(0)->getType() != LI->getType()) {
999        UnavailableBlocks.push_back(DepBB);
1000        continue;
1001      }
1002
1003      ValuesPerBlock.push_back(std::make_pair(DepBB, S->getOperand(0)));
1004
1005    } else if (LoadInst* LD = dyn_cast<LoadInst>(DepInst)) {
1006      if (LD->getType() != LI->getType()) {
1007        UnavailableBlocks.push_back(DepBB);
1008        continue;
1009      }
1010      ValuesPerBlock.push_back(std::make_pair(DepBB, LD));
1011    } else {
1012      UnavailableBlocks.push_back(DepBB);
1013      continue;
1014    }
1015  }
1016
1017  // If we have no predecessors that produce a known value for this load, exit
1018  // early.
1019  if (ValuesPerBlock.empty()) return false;
1020
1021  // If all of the instructions we depend on produce a known value for this
1022  // load, then it is fully redundant and we can use PHI insertion to compute
1023  // its value.  Insert PHIs and remove the fully redundant value now.
1024  if (UnavailableBlocks.empty()) {
1025    // Use cached PHI construction information from previous runs
1026    SmallPtrSet<Instruction*, 4> &p = phiMap[LI->getPointerOperand()];
1027    // FIXME: What does phiMap do? Are we positive it isn't getting invalidated?
1028    for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
1029         I != E; ++I) {
1030      if ((*I)->getParent() == LI->getParent()) {
1031        DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD #1: " << *LI << '\n');
1032        LI->replaceAllUsesWith(*I);
1033        if (isa<PointerType>((*I)->getType()))
1034          MD->invalidateCachedPointerInfo(*I);
1035        toErase.push_back(LI);
1036        NumGVNLoad++;
1037        return true;
1038      }
1039
1040      ValuesPerBlock.push_back(std::make_pair((*I)->getParent(), *I));
1041    }
1042
1043    DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1044
1045    DenseMap<BasicBlock*, Value*> BlockReplValues;
1046    BlockReplValues.insert(ValuesPerBlock.begin(), ValuesPerBlock.end());
1047    // Perform PHI construction.
1048    Value* v = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true);
1049    LI->replaceAllUsesWith(v);
1050
1051    if (isa<PHINode>(v))
1052      v->takeName(LI);
1053    if (isa<PointerType>(v->getType()))
1054      MD->invalidateCachedPointerInfo(v);
1055    toErase.push_back(LI);
1056    NumGVNLoad++;
1057    return true;
1058  }
1059
1060  if (!EnablePRE || !EnableLoadPRE)
1061    return false;
1062
1063  // Okay, we have *some* definitions of the value.  This means that the value
1064  // is available in some of our (transitive) predecessors.  Lets think about
1065  // doing PRE of this load.  This will involve inserting a new load into the
1066  // predecessor when it's not available.  We could do this in general, but
1067  // prefer to not increase code size.  As such, we only do this when we know
1068  // that we only have to insert *one* load (which means we're basically moving
1069  // the load, not inserting a new one).
1070
1071  SmallPtrSet<BasicBlock *, 4> Blockers;
1072  for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1073    Blockers.insert(UnavailableBlocks[i]);
1074
1075  // Lets find first basic block with more than one predecessor.  Walk backwards
1076  // through predecessors if needed.
1077  BasicBlock *LoadBB = LI->getParent();
1078  BasicBlock *TmpBB = LoadBB;
1079
1080  bool isSinglePred = false;
1081  bool allSingleSucc = true;
1082  while (TmpBB->getSinglePredecessor()) {
1083    isSinglePred = true;
1084    TmpBB = TmpBB->getSinglePredecessor();
1085    if (!TmpBB) // If haven't found any, bail now.
1086      return false;
1087    if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1088      return false;
1089    if (Blockers.count(TmpBB))
1090      return false;
1091    if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1092      allSingleSucc = false;
1093  }
1094
1095  assert(TmpBB);
1096  LoadBB = TmpBB;
1097
1098  // If we have a repl set with LI itself in it, this means we have a loop where
1099  // at least one of the values is LI.  Since this means that we won't be able
1100  // to eliminate LI even if we insert uses in the other predecessors, we will
1101  // end up increasing code size.  Reject this by scanning for LI.
1102  for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1103    if (ValuesPerBlock[i].second == LI)
1104      return false;
1105
1106  if (isSinglePred) {
1107    bool isHot = false;
1108    for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1109      if (Instruction *I = dyn_cast<Instruction>(ValuesPerBlock[i].second))
1110	// "Hot" Instruction is in some loop (because it dominates its dep.
1111	// instruction).
1112	if (DT->dominates(LI, I)) {
1113	  isHot = true;
1114	  break;
1115	}
1116
1117    // We are interested only in "hot" instructions. We don't want to do any
1118    // mis-optimizations here.
1119    if (!isHot)
1120      return false;
1121  }
1122
1123  // Okay, we have some hope :).  Check to see if the loaded value is fully
1124  // available in all but one predecessor.
1125  // FIXME: If we could restructure the CFG, we could make a common pred with
1126  // all the preds that don't have an available LI and insert a new load into
1127  // that one block.
1128  BasicBlock *UnavailablePred = 0;
1129
1130  DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1131  for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1132    FullyAvailableBlocks[ValuesPerBlock[i].first] = true;
1133  for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1134    FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1135
1136  for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1137       PI != E; ++PI) {
1138    if (IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
1139      continue;
1140
1141    // If this load is not available in multiple predecessors, reject it.
1142    if (UnavailablePred && UnavailablePred != *PI)
1143      return false;
1144    UnavailablePred = *PI;
1145  }
1146
1147  assert(UnavailablePred != 0 &&
1148         "Fully available value should be eliminated above!");
1149
1150  // If the loaded pointer is PHI node defined in this block, do PHI translation
1151  // to get its value in the predecessor.
1152  Value *LoadPtr = LI->getOperand(0)->DoPHITranslation(LoadBB, UnavailablePred);
1153
1154  // Make sure the value is live in the predecessor.  If it was defined by a
1155  // non-PHI instruction in this block, we don't know how to recompute it above.
1156  if (Instruction *LPInst = dyn_cast<Instruction>(LoadPtr))
1157    if (!DT->dominates(LPInst->getParent(), UnavailablePred)) {
1158      DEBUG(errs() << "COULDN'T PRE LOAD BECAUSE PTR IS UNAVAILABLE IN PRED: "
1159                   << *LPInst << '\n' << *LI << "\n");
1160      return false;
1161    }
1162
1163  // We don't currently handle critical edges :(
1164  if (UnavailablePred->getTerminator()->getNumSuccessors() != 1) {
1165    DEBUG(errs() << "COULD NOT PRE LOAD BECAUSE OF CRITICAL EDGE '"
1166                 << UnavailablePred->getName() << "': " << *LI << '\n');
1167    return false;
1168  }
1169
1170  // Make sure it is valid to move this load here.  We have to watch out for:
1171  //  @1 = getelementptr (i8* p, ...
1172  //  test p and branch if == 0
1173  //  load @1
1174  // It is valid to have the getelementptr before the test, even if p can be 0,
1175  // as getelementptr only does address arithmetic.
1176  // If we are not pushing the value through any multiple-successor blocks
1177  // we do not have this case.  Otherwise, check that the load is safe to
1178  // put anywhere; this can be improved, but should be conservatively safe.
1179  if (!allSingleSucc &&
1180      !isSafeToLoadUnconditionally(LoadPtr, UnavailablePred->getTerminator()))
1181    return false;
1182
1183  // Okay, we can eliminate this load by inserting a reload in the predecessor
1184  // and using PHI construction to get the value in the other predecessors, do
1185  // it.
1186  DEBUG(errs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
1187
1188  Value *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1189                                LI->getAlignment(),
1190                                UnavailablePred->getTerminator());
1191
1192  SmallPtrSet<Instruction*, 4> &p = phiMap[LI->getPointerOperand()];
1193  for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
1194       I != E; ++I)
1195    ValuesPerBlock.push_back(std::make_pair((*I)->getParent(), *I));
1196
1197  DenseMap<BasicBlock*, Value*> BlockReplValues;
1198  BlockReplValues.insert(ValuesPerBlock.begin(), ValuesPerBlock.end());
1199  BlockReplValues[UnavailablePred] = NewLoad;
1200
1201  // Perform PHI construction.
1202  Value* v = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true);
1203  LI->replaceAllUsesWith(v);
1204  if (isa<PHINode>(v))
1205    v->takeName(LI);
1206  if (isa<PointerType>(v->getType()))
1207    MD->invalidateCachedPointerInfo(v);
1208  toErase.push_back(LI);
1209  NumPRELoad++;
1210  return true;
1211}
1212
1213/// processLoad - Attempt to eliminate a load, first by eliminating it
1214/// locally, and then attempting non-local elimination if that fails.
1215bool GVN::processLoad(LoadInst *L, SmallVectorImpl<Instruction*> &toErase) {
1216  if (L->isVolatile())
1217    return false;
1218
1219  Value* pointer = L->getPointerOperand();
1220
1221  // ... to a pointer that has been loaded from before...
1222  MemDepResult dep = MD->getDependency(L);
1223
1224  // If the value isn't available, don't do anything!
1225  if (dep.isClobber()) {
1226    DEBUG(
1227      // fast print dep, using operator<< on instruction would be too slow
1228      errs() << "GVN: load ";
1229      WriteAsOperand(errs(), L);
1230      Instruction *I = dep.getInst();
1231      errs() << " is clobbered by " << *I << '\n';
1232    );
1233    return false;
1234  }
1235
1236  // If it is defined in another block, try harder.
1237  if (dep.isNonLocal())
1238    return processNonLocalLoad(L, toErase);
1239
1240  Instruction *DepInst = dep.getInst();
1241  if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1242    // Only forward substitute stores to loads of the same type.
1243    // FIXME: Could do better!
1244    if (DepSI->getPointerOperand()->getType() != pointer->getType())
1245      return false;
1246
1247    // Remove it!
1248    L->replaceAllUsesWith(DepSI->getOperand(0));
1249    if (isa<PointerType>(DepSI->getOperand(0)->getType()))
1250      MD->invalidateCachedPointerInfo(DepSI->getOperand(0));
1251    toErase.push_back(L);
1252    NumGVNLoad++;
1253    return true;
1254  }
1255
1256  if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1257    // Only forward substitute stores to loads of the same type.
1258    // FIXME: Could do better! load i32 -> load i8 -> truncate on little endian.
1259    if (DepLI->getType() != L->getType())
1260      return false;
1261
1262    // Remove it!
1263    L->replaceAllUsesWith(DepLI);
1264    if (isa<PointerType>(DepLI->getType()))
1265      MD->invalidateCachedPointerInfo(DepLI);
1266    toErase.push_back(L);
1267    NumGVNLoad++;
1268    return true;
1269  }
1270
1271  // If this load really doesn't depend on anything, then we must be loading an
1272  // undef value.  This can happen when loading for a fresh allocation with no
1273  // intervening stores, for example.
1274  if (isa<AllocationInst>(DepInst) || isMalloc(DepInst)) {
1275    L->replaceAllUsesWith(UndefValue::get(L->getType()));
1276    toErase.push_back(L);
1277    NumGVNLoad++;
1278    return true;
1279  }
1280
1281  return false;
1282}
1283
1284Value* GVN::lookupNumber(BasicBlock* BB, uint32_t num) {
1285  DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1286  if (I == localAvail.end())
1287    return 0;
1288
1289  ValueNumberScope* locals = I->second;
1290
1291  while (locals) {
1292    DenseMap<uint32_t, Value*>::iterator I = locals->table.find(num);
1293    if (I != locals->table.end())
1294      return I->second;
1295    else
1296      locals = locals->parent;
1297  }
1298
1299  return 0;
1300}
1301
1302/// AttemptRedundancyElimination - If the "fast path" of redundancy elimination
1303/// by inheritance from the dominator fails, see if we can perform phi
1304/// construction to eliminate the redundancy.
1305Value* GVN::AttemptRedundancyElimination(Instruction* orig, unsigned valno) {
1306  BasicBlock* BaseBlock = orig->getParent();
1307
1308  SmallPtrSet<BasicBlock*, 4> Visited;
1309  SmallVector<BasicBlock*, 8> Stack;
1310  Stack.push_back(BaseBlock);
1311
1312  DenseMap<BasicBlock*, Value*> Results;
1313
1314  // Walk backwards through our predecessors, looking for instances of the
1315  // value number we're looking for.  Instances are recorded in the Results
1316  // map, which is then used to perform phi construction.
1317  while (!Stack.empty()) {
1318    BasicBlock* Current = Stack.back();
1319    Stack.pop_back();
1320
1321    // If we've walked all the way to a proper dominator, then give up. Cases
1322    // where the instance is in the dominator will have been caught by the fast
1323    // path, and any cases that require phi construction further than this are
1324    // probably not worth it anyways.  Note that this is a SIGNIFICANT compile
1325    // time improvement.
1326    if (DT->properlyDominates(Current, orig->getParent())) return 0;
1327
1328    DenseMap<BasicBlock*, ValueNumberScope*>::iterator LA =
1329                                                       localAvail.find(Current);
1330    if (LA == localAvail.end()) return 0;
1331    DenseMap<uint32_t, Value*>::iterator V = LA->second->table.find(valno);
1332
1333    if (V != LA->second->table.end()) {
1334      // Found an instance, record it.
1335      Results.insert(std::make_pair(Current, V->second));
1336      continue;
1337    }
1338
1339    // If we reach the beginning of the function, then give up.
1340    if (pred_begin(Current) == pred_end(Current))
1341      return 0;
1342
1343    for (pred_iterator PI = pred_begin(Current), PE = pred_end(Current);
1344         PI != PE; ++PI)
1345      if (Visited.insert(*PI))
1346        Stack.push_back(*PI);
1347  }
1348
1349  // If we didn't find instances, give up.  Otherwise, perform phi construction.
1350  if (Results.size() == 0)
1351    return 0;
1352  else
1353    return GetValueForBlock(BaseBlock, orig, Results, true);
1354}
1355
1356/// processInstruction - When calculating availability, handle an instruction
1357/// by inserting it into the appropriate sets
1358bool GVN::processInstruction(Instruction *I,
1359                             SmallVectorImpl<Instruction*> &toErase) {
1360  if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1361    bool changed = processLoad(L, toErase);
1362
1363    if (!changed) {
1364      unsigned num = VN.lookup_or_add(L);
1365      localAvail[I->getParent()]->table.insert(std::make_pair(num, L));
1366    }
1367
1368    return changed;
1369  }
1370
1371  uint32_t nextNum = VN.getNextUnusedValueNumber();
1372  unsigned num = VN.lookup_or_add(I);
1373
1374  if (BranchInst* BI = dyn_cast<BranchInst>(I)) {
1375    localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1376
1377    if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
1378      return false;
1379
1380    Value* branchCond = BI->getCondition();
1381    uint32_t condVN = VN.lookup_or_add(branchCond);
1382
1383    BasicBlock* trueSucc = BI->getSuccessor(0);
1384    BasicBlock* falseSucc = BI->getSuccessor(1);
1385
1386    if (trueSucc->getSinglePredecessor())
1387      localAvail[trueSucc]->table[condVN] =
1388        ConstantInt::getTrue(trueSucc->getContext());
1389    if (falseSucc->getSinglePredecessor())
1390      localAvail[falseSucc]->table[condVN] =
1391        ConstantInt::getFalse(trueSucc->getContext());
1392
1393    return false;
1394
1395  // Allocations are always uniquely numbered, so we can save time and memory
1396  // by fast failing them.
1397  } else if (isa<AllocationInst>(I) || isMalloc(I) || isa<TerminatorInst>(I)) {
1398    localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1399    return false;
1400  }
1401
1402  // Collapse PHI nodes
1403  if (PHINode* p = dyn_cast<PHINode>(I)) {
1404    Value* constVal = CollapsePhi(p);
1405
1406    if (constVal) {
1407      for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1408           PI != PE; ++PI)
1409        PI->second.erase(p);
1410
1411      p->replaceAllUsesWith(constVal);
1412      if (isa<PointerType>(constVal->getType()))
1413        MD->invalidateCachedPointerInfo(constVal);
1414      VN.erase(p);
1415
1416      toErase.push_back(p);
1417    } else {
1418      localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1419    }
1420
1421  // If the number we were assigned was a brand new VN, then we don't
1422  // need to do a lookup to see if the number already exists
1423  // somewhere in the domtree: it can't!
1424  } else if (num == nextNum) {
1425    localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1426
1427  // Perform fast-path value-number based elimination of values inherited from
1428  // dominators.
1429  } else if (Value* repl = lookupNumber(I->getParent(), num)) {
1430    // Remove it!
1431    VN.erase(I);
1432    I->replaceAllUsesWith(repl);
1433    if (isa<PointerType>(repl->getType()))
1434      MD->invalidateCachedPointerInfo(repl);
1435    toErase.push_back(I);
1436    return true;
1437
1438#if 0
1439  // Perform slow-pathvalue-number based elimination with phi construction.
1440  } else if (Value* repl = AttemptRedundancyElimination(I, num)) {
1441    // Remove it!
1442    VN.erase(I);
1443    I->replaceAllUsesWith(repl);
1444    if (isa<PointerType>(repl->getType()))
1445      MD->invalidateCachedPointerInfo(repl);
1446    toErase.push_back(I);
1447    return true;
1448#endif
1449  } else {
1450    localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1451  }
1452
1453  return false;
1454}
1455
1456/// runOnFunction - This is the main transformation entry point for a function.
1457bool GVN::runOnFunction(Function& F) {
1458  MD = &getAnalysis<MemoryDependenceAnalysis>();
1459  DT = &getAnalysis<DominatorTree>();
1460  VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1461  VN.setMemDep(MD);
1462  VN.setDomTree(DT);
1463
1464  bool changed = false;
1465  bool shouldContinue = true;
1466
1467  // Merge unconditional branches, allowing PRE to catch more
1468  // optimization opportunities.
1469  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
1470    BasicBlock* BB = FI;
1471    ++FI;
1472    bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1473    if (removedBlock) NumGVNBlocks++;
1474
1475    changed |= removedBlock;
1476  }
1477
1478  unsigned Iteration = 0;
1479
1480  while (shouldContinue) {
1481    DEBUG(errs() << "GVN iteration: " << Iteration << "\n");
1482    shouldContinue = iterateOnFunction(F);
1483    changed |= shouldContinue;
1484    ++Iteration;
1485  }
1486
1487  if (EnablePRE) {
1488    bool PREChanged = true;
1489    while (PREChanged) {
1490      PREChanged = performPRE(F);
1491      changed |= PREChanged;
1492    }
1493  }
1494  // FIXME: Should perform GVN again after PRE does something.  PRE can move
1495  // computations into blocks where they become fully redundant.  Note that
1496  // we can't do this until PRE's critical edge splitting updates memdep.
1497  // Actually, when this happens, we should just fully integrate PRE into GVN.
1498
1499  cleanupGlobalSets();
1500
1501  return changed;
1502}
1503
1504
1505bool GVN::processBlock(BasicBlock* BB) {
1506  // FIXME: Kill off toErase by doing erasing eagerly in a helper function (and
1507  // incrementing BI before processing an instruction).
1508  SmallVector<Instruction*, 8> toErase;
1509  bool changed_function = false;
1510
1511  for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1512       BI != BE;) {
1513    changed_function |= processInstruction(BI, toErase);
1514    if (toErase.empty()) {
1515      ++BI;
1516      continue;
1517    }
1518
1519    // If we need some instructions deleted, do it now.
1520    NumGVNInstr += toErase.size();
1521
1522    // Avoid iterator invalidation.
1523    bool AtStart = BI == BB->begin();
1524    if (!AtStart)
1525      --BI;
1526
1527    for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1528         E = toErase.end(); I != E; ++I) {
1529      DEBUG(errs() << "GVN removed: " << **I << '\n');
1530      MD->removeInstruction(*I);
1531      (*I)->eraseFromParent();
1532      DEBUG(verifyRemoved(*I));
1533    }
1534    toErase.clear();
1535
1536    if (AtStart)
1537      BI = BB->begin();
1538    else
1539      ++BI;
1540  }
1541
1542  return changed_function;
1543}
1544
1545/// performPRE - Perform a purely local form of PRE that looks for diamond
1546/// control flow patterns and attempts to perform simple PRE at the join point.
1547bool GVN::performPRE(Function& F) {
1548  bool Changed = false;
1549  SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
1550  DenseMap<BasicBlock*, Value*> predMap;
1551  for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1552       DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
1553    BasicBlock* CurrentBlock = *DI;
1554
1555    // Nothing to PRE in the entry block.
1556    if (CurrentBlock == &F.getEntryBlock()) continue;
1557
1558    for (BasicBlock::iterator BI = CurrentBlock->begin(),
1559         BE = CurrentBlock->end(); BI != BE; ) {
1560      Instruction *CurInst = BI++;
1561
1562      if (isa<AllocationInst>(CurInst) || isMalloc(CurInst) ||
1563          isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
1564          (CurInst->getType() == Type::getVoidTy(F.getContext())) ||
1565          CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
1566          isa<DbgInfoIntrinsic>(CurInst))
1567        continue;
1568
1569      uint32_t valno = VN.lookup(CurInst);
1570
1571      // Look for the predecessors for PRE opportunities.  We're
1572      // only trying to solve the basic diamond case, where
1573      // a value is computed in the successor and one predecessor,
1574      // but not the other.  We also explicitly disallow cases
1575      // where the successor is its own predecessor, because they're
1576      // more complicated to get right.
1577      unsigned numWith = 0;
1578      unsigned numWithout = 0;
1579      BasicBlock* PREPred = 0;
1580      predMap.clear();
1581
1582      for (pred_iterator PI = pred_begin(CurrentBlock),
1583           PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1584        // We're not interested in PRE where the block is its
1585        // own predecessor, on in blocks with predecessors
1586        // that are not reachable.
1587        if (*PI == CurrentBlock) {
1588          numWithout = 2;
1589          break;
1590        } else if (!localAvail.count(*PI))  {
1591          numWithout = 2;
1592          break;
1593        }
1594
1595        DenseMap<uint32_t, Value*>::iterator predV =
1596                                            localAvail[*PI]->table.find(valno);
1597        if (predV == localAvail[*PI]->table.end()) {
1598          PREPred = *PI;
1599          numWithout++;
1600        } else if (predV->second == CurInst) {
1601          numWithout = 2;
1602        } else {
1603          predMap[*PI] = predV->second;
1604          numWith++;
1605        }
1606      }
1607
1608      // Don't do PRE when it might increase code size, i.e. when
1609      // we would need to insert instructions in more than one pred.
1610      if (numWithout != 1 || numWith == 0)
1611        continue;
1612
1613      // We can't do PRE safely on a critical edge, so instead we schedule
1614      // the edge to be split and perform the PRE the next time we iterate
1615      // on the function.
1616      unsigned succNum = 0;
1617      for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1618           i != e; ++i)
1619        if (PREPred->getTerminator()->getSuccessor(i) == CurrentBlock) {
1620          succNum = i;
1621          break;
1622        }
1623
1624      if (isCriticalEdge(PREPred->getTerminator(), succNum)) {
1625        toSplit.push_back(std::make_pair(PREPred->getTerminator(), succNum));
1626        continue;
1627      }
1628
1629      // Instantiate the expression the in predecessor that lacked it.
1630      // Because we are going top-down through the block, all value numbers
1631      // will be available in the predecessor by the time we need them.  Any
1632      // that weren't original present will have been instantiated earlier
1633      // in this loop.
1634      Instruction* PREInstr = CurInst->clone(CurInst->getContext());
1635      bool success = true;
1636      for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
1637        Value *Op = PREInstr->getOperand(i);
1638        if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
1639          continue;
1640
1641        if (Value *V = lookupNumber(PREPred, VN.lookup(Op))) {
1642          PREInstr->setOperand(i, V);
1643        } else {
1644          success = false;
1645          break;
1646        }
1647      }
1648
1649      // Fail out if we encounter an operand that is not available in
1650      // the PRE predecessor.  This is typically because of loads which
1651      // are not value numbered precisely.
1652      if (!success) {
1653        delete PREInstr;
1654        DEBUG(verifyRemoved(PREInstr));
1655        continue;
1656      }
1657
1658      PREInstr->insertBefore(PREPred->getTerminator());
1659      PREInstr->setName(CurInst->getName() + ".pre");
1660      predMap[PREPred] = PREInstr;
1661      VN.add(PREInstr, valno);
1662      NumGVNPRE++;
1663
1664      // Update the availability map to include the new instruction.
1665      localAvail[PREPred]->table.insert(std::make_pair(valno, PREInstr));
1666
1667      // Create a PHI to make the value available in this block.
1668      PHINode* Phi = PHINode::Create(CurInst->getType(),
1669                                     CurInst->getName() + ".pre-phi",
1670                                     CurrentBlock->begin());
1671      for (pred_iterator PI = pred_begin(CurrentBlock),
1672           PE = pred_end(CurrentBlock); PI != PE; ++PI)
1673        Phi->addIncoming(predMap[*PI], *PI);
1674
1675      VN.add(Phi, valno);
1676      localAvail[CurrentBlock]->table[valno] = Phi;
1677
1678      CurInst->replaceAllUsesWith(Phi);
1679      if (isa<PointerType>(Phi->getType()))
1680        MD->invalidateCachedPointerInfo(Phi);
1681      VN.erase(CurInst);
1682
1683      DEBUG(errs() << "GVN PRE removed: " << *CurInst << '\n');
1684      MD->removeInstruction(CurInst);
1685      CurInst->eraseFromParent();
1686      DEBUG(verifyRemoved(CurInst));
1687      Changed = true;
1688    }
1689  }
1690
1691  for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
1692       I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
1693    SplitCriticalEdge(I->first, I->second, this);
1694
1695  return Changed || toSplit.size();
1696}
1697
1698/// iterateOnFunction - Executes one iteration of GVN
1699bool GVN::iterateOnFunction(Function &F) {
1700  cleanupGlobalSets();
1701
1702  for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1703       DE = df_end(DT->getRootNode()); DI != DE; ++DI) {
1704    if (DI->getIDom())
1705      localAvail[DI->getBlock()] =
1706                   new ValueNumberScope(localAvail[DI->getIDom()->getBlock()]);
1707    else
1708      localAvail[DI->getBlock()] = new ValueNumberScope(0);
1709  }
1710
1711  // Top-down walk of the dominator tree
1712  bool changed = false;
1713#if 0
1714  // Needed for value numbering with phi construction to work.
1715  ReversePostOrderTraversal<Function*> RPOT(&F);
1716  for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
1717       RE = RPOT.end(); RI != RE; ++RI)
1718    changed |= processBlock(*RI);
1719#else
1720  for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1721       DE = df_end(DT->getRootNode()); DI != DE; ++DI)
1722    changed |= processBlock(DI->getBlock());
1723#endif
1724
1725  return changed;
1726}
1727
1728void GVN::cleanupGlobalSets() {
1729  VN.clear();
1730  phiMap.clear();
1731
1732  for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1733       I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
1734    delete I->second;
1735  localAvail.clear();
1736}
1737
1738/// verifyRemoved - Verify that the specified instruction does not occur in our
1739/// internal data structures.
1740void GVN::verifyRemoved(const Instruction *Inst) const {
1741  VN.verifyRemoved(Inst);
1742
1743  // Walk through the PHI map to make sure the instruction isn't hiding in there
1744  // somewhere.
1745  for (PhiMapType::iterator
1746         I = phiMap.begin(), E = phiMap.end(); I != E; ++I) {
1747    assert(I->first != Inst && "Inst is still a key in PHI map!");
1748
1749    for (SmallPtrSet<Instruction*, 4>::iterator
1750           II = I->second.begin(), IE = I->second.end(); II != IE; ++II) {
1751      assert(*II != Inst && "Inst is still a value in PHI map!");
1752    }
1753  }
1754
1755  // Walk through the value number scope to make sure the instruction isn't
1756  // ferreted away in it.
1757  for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1758         I = localAvail.begin(), E = localAvail.end(); I != E; ++I) {
1759    const ValueNumberScope *VNS = I->second;
1760
1761    while (VNS) {
1762      for (DenseMap<uint32_t, Value*>::iterator
1763             II = VNS->table.begin(), IE = VNS->table.end(); II != IE; ++II) {
1764        assert(II->second != Inst && "Inst still in value numbering scope!");
1765      }
1766
1767      VNS = VNS->parent;
1768    }
1769  }
1770}
1771