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