GVN.cpp revision 241f65321efc6ad84ed875cd9494df8ca1cff309
1//===- GVN.cpp - Eliminate redundant values and loads ------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs global value numbering to eliminate fully redundant
11// instructions.  It also performs simple dead load elimination.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "gvn"
16#include "llvm/Transforms/Scalar.h"
17#include "llvm/BasicBlock.h"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
21#include "llvm/IntrinsicInst.h"
22#include "llvm/Instructions.h"
23#include "llvm/ParameterAttributes.h"
24#include "llvm/Value.h"
25#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/DepthFirstIterator.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/ADT/SparseBitVector.h"
30#include "llvm/ADT/Statistic.h"
31#include "llvm/Analysis/Dominators.h"
32#include "llvm/Analysis/AliasAnalysis.h"
33#include "llvm/Analysis/MemoryDependenceAnalysis.h"
34#include "llvm/Support/CFG.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/GetElementPtrTypeIterator.h"
39#include "llvm/Target/TargetData.h"
40#include <list>
41using namespace llvm;
42
43STATISTIC(NumGVNInstr, "Number of instructions deleted");
44STATISTIC(NumGVNLoad, "Number of loads deleted");
45
46//===----------------------------------------------------------------------===//
47//                         ValueTable Class
48//===----------------------------------------------------------------------===//
49
50/// This class holds the mapping between values and value numbers.  It is used
51/// as an efficient mechanism to determine the expression-wise equivalence of
52/// two values.
53namespace {
54  struct VISIBILITY_HIDDEN Expression {
55    enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
56                            FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
57                            ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
58                            ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
59                            FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
60                            FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
61                            FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
62                            SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
63                            FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
64                            PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
65                            TOMBSTONE };
66
67    ExpressionOpcode opcode;
68    const Type* type;
69    uint32_t firstVN;
70    uint32_t secondVN;
71    uint32_t thirdVN;
72    SmallVector<uint32_t, 4> varargs;
73    Value* function;
74
75    Expression() { }
76    Expression(ExpressionOpcode o) : opcode(o) { }
77
78    bool operator==(const Expression &other) const {
79      if (opcode != other.opcode)
80        return false;
81      else if (opcode == EMPTY || opcode == TOMBSTONE)
82        return true;
83      else if (type != other.type)
84        return false;
85      else if (function != other.function)
86        return false;
87      else if (firstVN != other.firstVN)
88        return false;
89      else if (secondVN != other.secondVN)
90        return false;
91      else if (thirdVN != other.thirdVN)
92        return false;
93      else {
94        if (varargs.size() != other.varargs.size())
95          return false;
96
97        for (size_t i = 0; i < varargs.size(); ++i)
98          if (varargs[i] != other.varargs[i])
99            return false;
100
101        return true;
102      }
103    }
104
105    bool operator!=(const Expression &other) const {
106      if (opcode != other.opcode)
107        return true;
108      else if (opcode == EMPTY || opcode == TOMBSTONE)
109        return false;
110      else if (type != other.type)
111        return true;
112      else if (function != other.function)
113        return true;
114      else if (firstVN != other.firstVN)
115        return true;
116      else if (secondVN != other.secondVN)
117        return true;
118      else if (thirdVN != other.thirdVN)
119        return true;
120      else {
121        if (varargs.size() != other.varargs.size())
122          return true;
123
124        for (size_t i = 0; i < varargs.size(); ++i)
125          if (varargs[i] != other.varargs[i])
126            return true;
127
128          return false;
129      }
130    }
131  };
132
133  class VISIBILITY_HIDDEN ValueTable {
134    private:
135      DenseMap<Value*, uint32_t> valueNumbering;
136      DenseMap<Expression, uint32_t> expressionNumbering;
137      AliasAnalysis* AA;
138      MemoryDependenceAnalysis* MD;
139
140      uint32_t nextValueNumber;
141
142      Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
143      Expression::ExpressionOpcode getOpcode(CmpInst* C);
144      Expression::ExpressionOpcode getOpcode(CastInst* C);
145      Expression create_expression(BinaryOperator* BO);
146      Expression create_expression(CmpInst* C);
147      Expression create_expression(ShuffleVectorInst* V);
148      Expression create_expression(ExtractElementInst* C);
149      Expression create_expression(InsertElementInst* V);
150      Expression create_expression(SelectInst* V);
151      Expression create_expression(CastInst* C);
152      Expression create_expression(GetElementPtrInst* G);
153      Expression create_expression(CallInst* 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  };
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)) {
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) && "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/// lookup_or_add - Returns the value number for the specified value, assigning
417/// it a new number if it did not have one before.
418uint32_t ValueTable::lookup_or_add(Value* V) {
419  DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
420  if (VI != valueNumbering.end())
421    return VI->second;
422
423  if (CallInst* C = dyn_cast<CallInst>(V)) {
424    if (AA->doesNotAccessMemory(C)) {
425      Expression e = create_expression(C);
426
427      DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
428      if (EI != expressionNumbering.end()) {
429        valueNumbering.insert(std::make_pair(V, EI->second));
430        return EI->second;
431      } else {
432        expressionNumbering.insert(std::make_pair(e, nextValueNumber));
433        valueNumbering.insert(std::make_pair(V, nextValueNumber));
434
435        return nextValueNumber++;
436      }
437    } else if (AA->onlyReadsMemory(C)) {
438      Expression e = create_expression(C);
439
440      Instruction* dep = MD->getDependency(C);
441
442      if (dep == MemoryDependenceAnalysis::NonLocal ||
443          !isa<CallInst>(dep)) {
444        expressionNumbering.insert(std::make_pair(e, nextValueNumber));
445        valueNumbering.insert(std::make_pair(V, nextValueNumber));
446
447        return nextValueNumber++;
448      }
449
450      CallInst* cdep = cast<CallInst>(dep);
451      Expression d_exp = create_expression(cdep);
452
453      if (e != d_exp) {
454        expressionNumbering.insert(std::make_pair(e, nextValueNumber));
455        valueNumbering.insert(std::make_pair(V, nextValueNumber));
456
457        return nextValueNumber++;
458      } else {
459        uint32_t v = expressionNumbering[d_exp];
460        valueNumbering.insert(std::make_pair(V, v));
461        return v;
462      }
463
464    } else {
465      valueNumbering.insert(std::make_pair(V, nextValueNumber));
466      return nextValueNumber++;
467    }
468  } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
469    Expression e = create_expression(BO);
470
471    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
472    if (EI != expressionNumbering.end()) {
473      valueNumbering.insert(std::make_pair(V, EI->second));
474      return EI->second;
475    } else {
476      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
477      valueNumbering.insert(std::make_pair(V, nextValueNumber));
478
479      return nextValueNumber++;
480    }
481  } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
482    Expression e = create_expression(C);
483
484    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
485    if (EI != expressionNumbering.end()) {
486      valueNumbering.insert(std::make_pair(V, EI->second));
487      return EI->second;
488    } else {
489      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
490      valueNumbering.insert(std::make_pair(V, nextValueNumber));
491
492      return nextValueNumber++;
493    }
494  } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
495    Expression e = create_expression(U);
496
497    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
498    if (EI != expressionNumbering.end()) {
499      valueNumbering.insert(std::make_pair(V, EI->second));
500      return EI->second;
501    } else {
502      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
503      valueNumbering.insert(std::make_pair(V, nextValueNumber));
504
505      return nextValueNumber++;
506    }
507  } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
508    Expression e = create_expression(U);
509
510    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
511    if (EI != expressionNumbering.end()) {
512      valueNumbering.insert(std::make_pair(V, EI->second));
513      return EI->second;
514    } else {
515      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
516      valueNumbering.insert(std::make_pair(V, nextValueNumber));
517
518      return nextValueNumber++;
519    }
520  } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
521    Expression e = create_expression(U);
522
523    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
524    if (EI != expressionNumbering.end()) {
525      valueNumbering.insert(std::make_pair(V, EI->second));
526      return EI->second;
527    } else {
528      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
529      valueNumbering.insert(std::make_pair(V, nextValueNumber));
530
531      return nextValueNumber++;
532    }
533  } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
534    Expression e = create_expression(U);
535
536    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
537    if (EI != expressionNumbering.end()) {
538      valueNumbering.insert(std::make_pair(V, EI->second));
539      return EI->second;
540    } else {
541      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
542      valueNumbering.insert(std::make_pair(V, nextValueNumber));
543
544      return nextValueNumber++;
545    }
546  } else if (CastInst* U = dyn_cast<CastInst>(V)) {
547    Expression e = create_expression(U);
548
549    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
550    if (EI != expressionNumbering.end()) {
551      valueNumbering.insert(std::make_pair(V, EI->second));
552      return EI->second;
553    } else {
554      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
555      valueNumbering.insert(std::make_pair(V, nextValueNumber));
556
557      return nextValueNumber++;
558    }
559  } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
560    Expression e = create_expression(U);
561
562    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
563    if (EI != expressionNumbering.end()) {
564      valueNumbering.insert(std::make_pair(V, EI->second));
565      return EI->second;
566    } else {
567      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
568      valueNumbering.insert(std::make_pair(V, nextValueNumber));
569
570      return nextValueNumber++;
571    }
572  } else {
573    valueNumbering.insert(std::make_pair(V, nextValueNumber));
574    return nextValueNumber++;
575  }
576}
577
578/// lookup - Returns the value number of the specified value. Fails if
579/// the value has not yet been numbered.
580uint32_t ValueTable::lookup(Value* V) const {
581  DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
582  assert(VI != valueNumbering.end() && "Value not numbered?");
583  return VI->second;
584}
585
586/// clear - Remove all entries from the ValueTable
587void ValueTable::clear() {
588  valueNumbering.clear();
589  expressionNumbering.clear();
590  nextValueNumber = 1;
591}
592
593/// erase - Remove a value from the value numbering
594void ValueTable::erase(Value* V) {
595  valueNumbering.erase(V);
596}
597
598//===----------------------------------------------------------------------===//
599//                       ValueNumberedSet Class
600//===----------------------------------------------------------------------===//
601namespace {
602class VISIBILITY_HIDDEN ValueNumberedSet {
603  private:
604    SmallPtrSet<Value*, 8> contents;
605    SparseBitVector<64> numbers;
606  public:
607    ValueNumberedSet() { }
608    ValueNumberedSet(const ValueNumberedSet& other) {
609      numbers = other.numbers;
610      contents = other.contents;
611    }
612
613    typedef SmallPtrSet<Value*, 8>::iterator iterator;
614
615    iterator begin() { return contents.begin(); }
616    iterator end() { return contents.end(); }
617
618    bool insert(Value* v) { return contents.insert(v); }
619    void insert(iterator I, iterator E) { contents.insert(I, E); }
620    void erase(Value* v) { contents.erase(v); }
621    unsigned count(Value* v) { return contents.count(v); }
622    size_t size() { return contents.size(); }
623
624    void set(unsigned i)  {
625      numbers.set(i);
626    }
627
628    void operator=(const ValueNumberedSet& other) {
629      contents = other.contents;
630      numbers = other.numbers;
631    }
632
633    void reset(unsigned i)  {
634      numbers.reset(i);
635    }
636
637    bool test(unsigned i)  {
638      return numbers.test(i);
639    }
640};
641}
642
643//===----------------------------------------------------------------------===//
644//                         GVN Pass
645//===----------------------------------------------------------------------===//
646
647namespace {
648
649  class VISIBILITY_HIDDEN GVN : public FunctionPass {
650    bool runOnFunction(Function &F);
651  public:
652    static char ID; // Pass identification, replacement for typeid
653    GVN() : FunctionPass((intptr_t)&ID) { }
654
655  private:
656    ValueTable VN;
657
658    DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
659
660    typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
661    PhiMapType phiMap;
662
663
664    // This transformation requires dominator postdominator info
665    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
666      AU.setPreservesCFG();
667      AU.addRequired<DominatorTree>();
668      AU.addRequired<MemoryDependenceAnalysis>();
669      AU.addRequired<AliasAnalysis>();
670      AU.addRequired<TargetData>();
671      AU.addPreserved<AliasAnalysis>();
672      AU.addPreserved<MemoryDependenceAnalysis>();
673      AU.addPreserved<TargetData>();
674    }
675
676    // Helper fuctions
677    // FIXME: eliminate or document these better
678    Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
679    void val_insert(ValueNumberedSet& s, Value* v);
680    bool processLoad(LoadInst* L,
681                     DenseMap<Value*, LoadInst*> &lastLoad,
682                     SmallVectorImpl<Instruction*> &toErase);
683    bool processInstruction(Instruction* I,
684                            ValueNumberedSet& currAvail,
685                            DenseMap<Value*, LoadInst*>& lastSeenLoad,
686                            SmallVectorImpl<Instruction*> &toErase);
687    bool processNonLocalLoad(LoadInst* L,
688                             SmallVectorImpl<Instruction*> &toErase);
689    Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
690                            DenseMap<BasicBlock*, Value*> &Phis,
691                            bool top_level = false);
692    void dump(DenseMap<BasicBlock*, Value*>& d);
693    bool iterateOnFunction(Function &F);
694    Value* CollapsePhi(PHINode* p);
695    bool isSafeReplacement(PHINode* p, Instruction* inst);
696  };
697
698  char GVN::ID = 0;
699}
700
701// createGVNPass - The public interface to this file...
702FunctionPass *llvm::createGVNPass() { return new GVN(); }
703
704static RegisterPass<GVN> X("gvn",
705                           "Global Value Numbering");
706
707/// find_leader - Given a set and a value number, return the first
708/// element of the set with that value number, or 0 if no such element
709/// is present
710Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
711  if (!vals.test(v))
712    return 0;
713
714  for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
715       I != E; ++I)
716    if (v == VN.lookup(*I))
717      return *I;
718
719  assert(0 && "No leader found, but present bit is set?");
720  return 0;
721}
722
723/// val_insert - Insert a value into a set only if there is not a value
724/// with the same value number already in the set
725void GVN::val_insert(ValueNumberedSet& s, Value* v) {
726  uint32_t num = VN.lookup(v);
727  if (!s.test(num))
728    s.insert(v);
729}
730
731void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
732  printf("{\n");
733  for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
734       E = d.end(); I != E; ++I) {
735    if (I->second == MemoryDependenceAnalysis::None)
736      printf("None\n");
737    else
738      I->second->dump();
739  }
740  printf("}\n");
741}
742
743Value* GVN::CollapsePhi(PHINode* p) {
744  DominatorTree &DT = getAnalysis<DominatorTree>();
745  Value* constVal = p->hasConstantValue();
746
747  if (!constVal) return 0;
748
749  Instruction* inst = dyn_cast<Instruction>(constVal);
750  if (!inst)
751    return constVal;
752
753  if (DT.dominates(inst, p))
754    if (isSafeReplacement(p, inst))
755      return inst;
756  return 0;
757}
758
759bool GVN::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
772/// GetValueForBlock - Get the value to use within the specified basic block.
773/// available values are in Phis.
774Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
775                             DenseMap<BasicBlock*, Value*> &Phis,
776                             bool top_level) {
777
778  // If we have already computed this value, return the previously computed val.
779  DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
780  if (V != Phis.end() && !top_level) return V->second;
781
782  BasicBlock* singlePred = BB->getSinglePredecessor();
783  if (singlePred) {
784    Value *ret = GetValueForBlock(singlePred, orig, Phis);
785    Phis[BB] = ret;
786    return ret;
787  }
788
789  // Otherwise, the idom is the loop, so we need to insert a PHI node.  Do so
790  // now, then get values to fill in the incoming values for the PHI.
791  PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
792                                BB->begin());
793  PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
794
795  if (Phis.count(BB) == 0)
796    Phis.insert(std::make_pair(BB, PN));
797
798  // Fill in the incoming values for the block.
799  for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
800    Value* val = GetValueForBlock(*PI, orig, Phis);
801    PN->addIncoming(val, *PI);
802  }
803
804  AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
805  AA.copyValue(orig, PN);
806
807  // Attempt to collapse PHI nodes that are trivially redundant
808  Value* v = CollapsePhi(PN);
809  if (!v) {
810    // Cache our phi construction results
811    phiMap[orig->getPointerOperand()].insert(PN);
812    return PN;
813  }
814
815  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
816
817  MD.removeInstruction(PN);
818  PN->replaceAllUsesWith(v);
819
820  for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
821       E = Phis.end(); I != E; ++I)
822    if (I->second == PN)
823      I->second = v;
824
825  PN->eraseFromParent();
826
827  Phis[BB] = v;
828  return v;
829}
830
831/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
832/// non-local by performing PHI construction.
833bool GVN::processNonLocalLoad(LoadInst* L,
834                              SmallVectorImpl<Instruction*> &toErase) {
835  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
836
837  // Find the non-local dependencies of the load
838  DenseMap<BasicBlock*, Value*> deps;
839  MD.getNonLocalDependency(L, deps);
840
841  DenseMap<BasicBlock*, Value*> repl;
842
843  // Filter out useless results (non-locals, etc)
844  for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
845       I != E; ++I) {
846    if (I->second == MemoryDependenceAnalysis::None)
847      return false;
848
849    if (I->second == MemoryDependenceAnalysis::NonLocal)
850      continue;
851
852    if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
853      if (S->getPointerOperand() != L->getPointerOperand())
854        return false;
855      repl[I->first] = S->getOperand(0);
856    } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
857      if (LD->getPointerOperand() != L->getPointerOperand())
858        return false;
859      repl[I->first] = LD;
860    } else {
861      return false;
862    }
863  }
864
865  // Use cached PHI construction information from previous runs
866  SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
867  for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
868       I != E; ++I) {
869    if ((*I)->getParent() == L->getParent()) {
870      MD.removeInstruction(L);
871      L->replaceAllUsesWith(*I);
872      toErase.push_back(L);
873      NumGVNLoad++;
874      return true;
875    }
876
877    repl.insert(std::make_pair((*I)->getParent(), *I));
878  }
879
880  // Perform PHI construction
881  SmallPtrSet<BasicBlock*, 4> visited;
882  Value* v = GetValueForBlock(L->getParent(), L, repl, true);
883
884  MD.removeInstruction(L);
885  L->replaceAllUsesWith(v);
886  toErase.push_back(L);
887  NumGVNLoad++;
888
889  return true;
890}
891
892/// processLoad - Attempt to eliminate a load, first by eliminating it
893/// locally, and then attempting non-local elimination if that fails.
894bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
895                      SmallVectorImpl<Instruction*> &toErase) {
896  if (L->isVolatile()) {
897    lastLoad[L->getPointerOperand()] = L;
898    return false;
899  }
900
901  Value* pointer = L->getPointerOperand();
902  LoadInst*& last = lastLoad[pointer];
903
904  // ... to a pointer that has been loaded from before...
905  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
906  bool removedNonLocal = false;
907  Instruction* dep = MD.getDependency(L);
908  if (dep == MemoryDependenceAnalysis::NonLocal &&
909      L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
910    removedNonLocal = processNonLocalLoad(L, toErase);
911
912    if (!removedNonLocal)
913      last = L;
914
915    return removedNonLocal;
916  }
917
918
919  bool deletedLoad = false;
920
921  // Walk up the dependency chain until we either find
922  // a dependency we can use, or we can't walk any further
923  while (dep != MemoryDependenceAnalysis::None &&
924         dep != MemoryDependenceAnalysis::NonLocal &&
925         (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
926    // ... that depends on a store ...
927    if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
928      if (S->getPointerOperand() == pointer) {
929        // Remove it!
930        MD.removeInstruction(L);
931
932        L->replaceAllUsesWith(S->getOperand(0));
933        toErase.push_back(L);
934        deletedLoad = true;
935        NumGVNLoad++;
936      }
937
938      // Whether we removed it or not, we can't
939      // go any further
940      break;
941    } else if (!last) {
942      // If we don't depend on a store, and we haven't
943      // been loaded before, bail.
944      break;
945    } else if (dep == last) {
946      // Remove it!
947      MD.removeInstruction(L);
948
949      L->replaceAllUsesWith(last);
950      toErase.push_back(L);
951      deletedLoad = true;
952      NumGVNLoad++;
953
954      break;
955    } else {
956      dep = MD.getDependency(L, dep);
957    }
958  }
959
960  if (dep != MemoryDependenceAnalysis::None &&
961      dep != MemoryDependenceAnalysis::NonLocal &&
962      isa<AllocationInst>(dep)) {
963    // Check that this load is actually from the
964    // allocation we found
965    Value* v = L->getOperand(0);
966    while (true) {
967      if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
968        v = BC->getOperand(0);
969      else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
970        v = GEP->getOperand(0);
971      else
972        break;
973    }
974    if (v == dep) {
975      // If this load depends directly on an allocation, there isn't
976      // anything stored there; therefore, we can optimize this load
977      // to undef.
978      MD.removeInstruction(L);
979
980      L->replaceAllUsesWith(UndefValue::get(L->getType()));
981      toErase.push_back(L);
982      deletedLoad = true;
983      NumGVNLoad++;
984    }
985  }
986
987  if (!deletedLoad)
988    last = L;
989
990  return deletedLoad;
991}
992
993/// processInstruction - When calculating availability, handle an instruction
994/// by inserting it into the appropriate sets
995bool GVN::processInstruction(Instruction *I, ValueNumberedSet &currAvail,
996                             DenseMap<Value*, LoadInst*> &lastSeenLoad,
997                             SmallVectorImpl<Instruction*> &toErase) {
998  if (LoadInst* L = dyn_cast<LoadInst>(I))
999    return processLoad(L, lastSeenLoad, toErase);
1000
1001  // Allocations are always uniquely numbered, so we can save time and memory
1002  // by fast failing them.
1003  if (isa<AllocationInst>(I))
1004    return false;
1005
1006  unsigned num = VN.lookup_or_add(I);
1007
1008  // Collapse PHI nodes
1009  if (PHINode* p = dyn_cast<PHINode>(I)) {
1010    Value* constVal = CollapsePhi(p);
1011
1012    if (constVal) {
1013      for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1014           PI != PE; ++PI)
1015        if (PI->second.count(p))
1016          PI->second.erase(p);
1017
1018      p->replaceAllUsesWith(constVal);
1019      toErase.push_back(p);
1020    }
1021  // Perform value-number based elimination
1022  } else if (currAvail.test(num)) {
1023    Value* repl = find_leader(currAvail, num);
1024
1025    // Remove it!
1026    MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1027    MD.removeInstruction(I);
1028
1029    VN.erase(I);
1030    I->replaceAllUsesWith(repl);
1031    toErase.push_back(I);
1032    return true;
1033  } else if (!I->isTerminator()) {
1034    currAvail.set(num);
1035    currAvail.insert(I);
1036  }
1037
1038  return false;
1039}
1040
1041// GVN::runOnFunction - This is the main transformation entry point for a
1042// function.
1043//
1044bool GVN::runOnFunction(Function& F) {
1045  VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1046  VN.setMemDep(&getAnalysis<MemoryDependenceAnalysis>());
1047
1048  bool changed = false;
1049  bool shouldContinue = true;
1050
1051  while (shouldContinue) {
1052    shouldContinue = iterateOnFunction(F);
1053    changed |= shouldContinue;
1054  }
1055
1056  return changed;
1057}
1058
1059
1060// GVN::iterateOnFunction - Executes one iteration of GVN
1061bool GVN::iterateOnFunction(Function &F) {
1062  // Clean out global sets from any previous functions
1063  VN.clear();
1064  availableOut.clear();
1065  phiMap.clear();
1066
1067  bool changed_function = false;
1068
1069  DominatorTree &DT = getAnalysis<DominatorTree>();
1070
1071  SmallVector<Instruction*, 8> toErase;
1072  DenseMap<Value*, LoadInst*> lastSeenLoad;
1073  DenseMap<DomTreeNode*, size_t> numChildrenVisited;
1074
1075  // Top-down walk of the dominator tree
1076  for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1077         E = df_end(DT.getRootNode()); DI != E; ++DI) {
1078
1079    // Get the set to update for this block
1080    ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1081    lastSeenLoad.clear();
1082
1083    BasicBlock* BB = DI->getBlock();
1084
1085    // A block inherits AVAIL_OUT from its dominator
1086    if (DI->getIDom() != 0) {
1087      currAvail = availableOut[DI->getIDom()->getBlock()];
1088
1089      numChildrenVisited[DI->getIDom()]++;
1090
1091      if (numChildrenVisited[DI->getIDom()] == DI->getIDom()->getNumChildren()) {
1092        availableOut.erase(DI->getIDom()->getBlock());
1093        numChildrenVisited.erase(DI->getIDom());
1094      }
1095    }
1096
1097    for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1098         BI != BE;) {
1099      changed_function |= processInstruction(BI, currAvail,
1100                                             lastSeenLoad, toErase);
1101      if (toErase.empty()) {
1102        ++BI;
1103        continue;
1104      }
1105
1106      // If we need some instructions deleted, do it now.
1107      NumGVNInstr += toErase.size();
1108
1109      // Avoid iterator invalidation.
1110      bool AtStart = BI == BB->begin();
1111      if (!AtStart)
1112        --BI;
1113
1114      for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1115           E = toErase.end(); I != E; ++I)
1116        (*I)->eraseFromParent();
1117
1118      if (AtStart)
1119        BI = BB->begin();
1120      else
1121        ++BI;
1122
1123      toErase.clear();
1124    }
1125  }
1126
1127  return changed_function;
1128}
1129