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