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