GVN.cpp revision 88ffdddcc42d80972644643da1096793dabae802
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/BitVector.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/CommandLine.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Support/GetElementPtrTypeIterator.h"
38#include "llvm/Target/TargetData.h"
39using namespace llvm;
40
41STATISTIC(NumGVNInstr, "Number of instructions deleted");
42STATISTIC(NumGVNLoad, "Number of loads deleted");
43STATISTIC(NumMemSetInfer, "Number of memsets inferred");
44
45namespace {
46  cl::opt<bool>
47  FormMemSet("form-memset-from-stores",
48             cl::desc("Transform straight-line stores to memsets"),
49             cl::init(false), cl::Hidden);
50}
51
52//===----------------------------------------------------------------------===//
53//                         ValueTable Class
54//===----------------------------------------------------------------------===//
55
56/// This class holds the mapping between values and value numbers.  It is used
57/// as an efficient mechanism to determine the expression-wise equivalence of
58/// two values.
59namespace {
60  struct VISIBILITY_HIDDEN Expression {
61    enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
62                            FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
63                            ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
64                            ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
65                            FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
66                            FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
67                            FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
68                            SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
69                            FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
70                            PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
71                            TOMBSTONE };
72
73    ExpressionOpcode opcode;
74    const Type* type;
75    uint32_t firstVN;
76    uint32_t secondVN;
77    uint32_t thirdVN;
78    SmallVector<uint32_t, 4> varargs;
79    Value* function;
80
81    Expression() { }
82    Expression(ExpressionOpcode o) : opcode(o) { }
83
84    bool operator==(const Expression &other) const {
85      if (opcode != other.opcode)
86        return false;
87      else if (opcode == EMPTY || opcode == TOMBSTONE)
88        return true;
89      else if (type != other.type)
90        return false;
91      else if (function != other.function)
92        return false;
93      else if (firstVN != other.firstVN)
94        return false;
95      else if (secondVN != other.secondVN)
96        return false;
97      else if (thirdVN != other.thirdVN)
98        return false;
99      else {
100        if (varargs.size() != other.varargs.size())
101          return false;
102
103        for (size_t i = 0; i < varargs.size(); ++i)
104          if (varargs[i] != other.varargs[i])
105            return false;
106
107        return true;
108      }
109    }
110
111    bool operator!=(const Expression &other) const {
112      if (opcode != other.opcode)
113        return true;
114      else if (opcode == EMPTY || opcode == TOMBSTONE)
115        return false;
116      else if (type != other.type)
117        return true;
118      else if (function != other.function)
119        return true;
120      else if (firstVN != other.firstVN)
121        return true;
122      else if (secondVN != other.secondVN)
123        return true;
124      else if (thirdVN != other.thirdVN)
125        return true;
126      else {
127        if (varargs.size() != other.varargs.size())
128          return true;
129
130        for (size_t i = 0; i < varargs.size(); ++i)
131          if (varargs[i] != other.varargs[i])
132            return true;
133
134          return false;
135      }
136    }
137  };
138
139  class VISIBILITY_HIDDEN ValueTable {
140    private:
141      DenseMap<Value*, uint32_t> valueNumbering;
142      DenseMap<Expression, uint32_t> expressionNumbering;
143      AliasAnalysis* AA;
144
145      uint32_t nextValueNumber;
146
147      Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
148      Expression::ExpressionOpcode getOpcode(CmpInst* C);
149      Expression::ExpressionOpcode getOpcode(CastInst* C);
150      Expression create_expression(BinaryOperator* BO);
151      Expression create_expression(CmpInst* C);
152      Expression create_expression(ShuffleVectorInst* V);
153      Expression create_expression(ExtractElementInst* C);
154      Expression create_expression(InsertElementInst* V);
155      Expression create_expression(SelectInst* V);
156      Expression create_expression(CastInst* C);
157      Expression create_expression(GetElementPtrInst* G);
158      Expression create_expression(CallInst* C);
159    public:
160      ValueTable() : nextValueNumber(1) { }
161      uint32_t lookup_or_add(Value* V);
162      uint32_t lookup(Value* V) const;
163      void add(Value* V, uint32_t num);
164      void clear();
165      void erase(Value* v);
166      unsigned size();
167      void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
168      uint32_t hash_operand(Value* v);
169  };
170}
171
172namespace llvm {
173template <> struct DenseMapInfo<Expression> {
174  static inline Expression getEmptyKey() {
175    return Expression(Expression::EMPTY);
176  }
177
178  static inline Expression getTombstoneKey() {
179    return Expression(Expression::TOMBSTONE);
180  }
181
182  static unsigned getHashValue(const Expression e) {
183    unsigned hash = e.opcode;
184
185    hash = e.firstVN + hash * 37;
186    hash = e.secondVN + hash * 37;
187    hash = e.thirdVN + hash * 37;
188
189    hash = ((unsigned)((uintptr_t)e.type >> 4) ^
190            (unsigned)((uintptr_t)e.type >> 9)) +
191           hash * 37;
192
193    for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
194         E = e.varargs.end(); I != E; ++I)
195      hash = *I + hash * 37;
196
197    hash = ((unsigned)((uintptr_t)e.function >> 4) ^
198            (unsigned)((uintptr_t)e.function >> 9)) +
199           hash * 37;
200
201    return hash;
202  }
203  static bool isEqual(const Expression &LHS, const Expression &RHS) {
204    return LHS == RHS;
205  }
206  static bool isPod() { return true; }
207};
208}
209
210//===----------------------------------------------------------------------===//
211//                     ValueTable Internal Functions
212//===----------------------------------------------------------------------===//
213Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
214  switch(BO->getOpcode()) {
215  default: // THIS SHOULD NEVER HAPPEN
216    assert(0 && "Binary operator with unknown opcode?");
217  case Instruction::Add:  return Expression::ADD;
218  case Instruction::Sub:  return Expression::SUB;
219  case Instruction::Mul:  return Expression::MUL;
220  case Instruction::UDiv: return Expression::UDIV;
221  case Instruction::SDiv: return Expression::SDIV;
222  case Instruction::FDiv: return Expression::FDIV;
223  case Instruction::URem: return Expression::UREM;
224  case Instruction::SRem: return Expression::SREM;
225  case Instruction::FRem: return Expression::FREM;
226  case Instruction::Shl:  return Expression::SHL;
227  case Instruction::LShr: return Expression::LSHR;
228  case Instruction::AShr: return Expression::ASHR;
229  case Instruction::And:  return Expression::AND;
230  case Instruction::Or:   return Expression::OR;
231  case Instruction::Xor:  return Expression::XOR;
232  }
233}
234
235Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
236  if (isa<ICmpInst>(C)) {
237    switch (C->getPredicate()) {
238    default:  // THIS SHOULD NEVER HAPPEN
239      assert(0 && "Comparison with unknown predicate?");
240    case ICmpInst::ICMP_EQ:  return Expression::ICMPEQ;
241    case ICmpInst::ICMP_NE:  return Expression::ICMPNE;
242    case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
243    case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
244    case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
245    case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
246    case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
247    case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
248    case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
249    case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
250    }
251  }
252  assert(isa<FCmpInst>(C) && "Unknown compare");
253  switch (C->getPredicate()) {
254  default: // THIS SHOULD NEVER HAPPEN
255    assert(0 && "Comparison with unknown predicate?");
256  case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
257  case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
258  case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
259  case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
260  case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
261  case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
262  case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
263  case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
264  case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
265  case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
266  case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
267  case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
268  case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
269  case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
270  }
271}
272
273Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
274  switch(C->getOpcode()) {
275  default: // THIS SHOULD NEVER HAPPEN
276    assert(0 && "Cast operator with unknown opcode?");
277  case Instruction::Trunc:    return Expression::TRUNC;
278  case Instruction::ZExt:     return Expression::ZEXT;
279  case Instruction::SExt:     return Expression::SEXT;
280  case Instruction::FPToUI:   return Expression::FPTOUI;
281  case Instruction::FPToSI:   return Expression::FPTOSI;
282  case Instruction::UIToFP:   return Expression::UITOFP;
283  case Instruction::SIToFP:   return Expression::SITOFP;
284  case Instruction::FPTrunc:  return Expression::FPTRUNC;
285  case Instruction::FPExt:    return Expression::FPEXT;
286  case Instruction::PtrToInt: return Expression::PTRTOINT;
287  case Instruction::IntToPtr: return Expression::INTTOPTR;
288  case Instruction::BitCast:  return Expression::BITCAST;
289  }
290}
291
292uint32_t ValueTable::hash_operand(Value* v) {
293  if (CallInst* CI = dyn_cast<CallInst>(v))
294    if (!AA->doesNotAccessMemory(CI))
295      return nextValueNumber++;
296
297  return lookup_or_add(v);
298}
299
300Expression ValueTable::create_expression(CallInst* C) {
301  Expression e;
302
303  e.type = C->getType();
304  e.firstVN = 0;
305  e.secondVN = 0;
306  e.thirdVN = 0;
307  e.function = C->getCalledFunction();
308  e.opcode = Expression::CALL;
309
310  for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
311       I != E; ++I)
312    e.varargs.push_back(hash_operand(*I));
313
314  return e;
315}
316
317Expression ValueTable::create_expression(BinaryOperator* BO) {
318  Expression e;
319
320  e.firstVN = hash_operand(BO->getOperand(0));
321  e.secondVN = hash_operand(BO->getOperand(1));
322  e.thirdVN = 0;
323  e.function = 0;
324  e.type = BO->getType();
325  e.opcode = getOpcode(BO);
326
327  return e;
328}
329
330Expression ValueTable::create_expression(CmpInst* C) {
331  Expression e;
332
333  e.firstVN = hash_operand(C->getOperand(0));
334  e.secondVN = hash_operand(C->getOperand(1));
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(CastInst* C) {
344  Expression e;
345
346  e.firstVN = hash_operand(C->getOperand(0));
347  e.secondVN = 0;
348  e.thirdVN = 0;
349  e.function = 0;
350  e.type = C->getType();
351  e.opcode = getOpcode(C);
352
353  return e;
354}
355
356Expression ValueTable::create_expression(ShuffleVectorInst* S) {
357  Expression e;
358
359  e.firstVN = hash_operand(S->getOperand(0));
360  e.secondVN = hash_operand(S->getOperand(1));
361  e.thirdVN = hash_operand(S->getOperand(2));
362  e.function = 0;
363  e.type = S->getType();
364  e.opcode = Expression::SHUFFLE;
365
366  return e;
367}
368
369Expression ValueTable::create_expression(ExtractElementInst* E) {
370  Expression e;
371
372  e.firstVN = hash_operand(E->getOperand(0));
373  e.secondVN = hash_operand(E->getOperand(1));
374  e.thirdVN = 0;
375  e.function = 0;
376  e.type = E->getType();
377  e.opcode = Expression::EXTRACT;
378
379  return e;
380}
381
382Expression ValueTable::create_expression(InsertElementInst* I) {
383  Expression e;
384
385  e.firstVN = hash_operand(I->getOperand(0));
386  e.secondVN = hash_operand(I->getOperand(1));
387  e.thirdVN = hash_operand(I->getOperand(2));
388  e.function = 0;
389  e.type = I->getType();
390  e.opcode = Expression::INSERT;
391
392  return e;
393}
394
395Expression ValueTable::create_expression(SelectInst* I) {
396  Expression e;
397
398  e.firstVN = hash_operand(I->getCondition());
399  e.secondVN = hash_operand(I->getTrueValue());
400  e.thirdVN = hash_operand(I->getFalseValue());
401  e.function = 0;
402  e.type = I->getType();
403  e.opcode = Expression::SELECT;
404
405  return e;
406}
407
408Expression ValueTable::create_expression(GetElementPtrInst* G) {
409  Expression e;
410
411  e.firstVN = hash_operand(G->getPointerOperand());
412  e.secondVN = 0;
413  e.thirdVN = 0;
414  e.function = 0;
415  e.type = G->getType();
416  e.opcode = Expression::GEP;
417
418  for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
419       I != E; ++I)
420    e.varargs.push_back(hash_operand(*I));
421
422  return e;
423}
424
425//===----------------------------------------------------------------------===//
426//                     ValueTable External Functions
427//===----------------------------------------------------------------------===//
428
429/// lookup_or_add - Returns the value number for the specified value, assigning
430/// it a new number if it did not have one before.
431uint32_t ValueTable::lookup_or_add(Value* V) {
432  DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
433  if (VI != valueNumbering.end())
434    return VI->second;
435
436  if (CallInst* C = dyn_cast<CallInst>(V)) {
437    if (AA->onlyReadsMemory(C)) { // includes doesNotAccessMemory
438      Expression e = create_expression(C);
439
440      DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
441      if (EI != expressionNumbering.end()) {
442        valueNumbering.insert(std::make_pair(V, EI->second));
443        return EI->second;
444      } else {
445        expressionNumbering.insert(std::make_pair(e, nextValueNumber));
446        valueNumbering.insert(std::make_pair(V, nextValueNumber));
447
448        return nextValueNumber++;
449      }
450    } else {
451      valueNumbering.insert(std::make_pair(V, nextValueNumber));
452      return nextValueNumber++;
453    }
454  } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
455    Expression e = create_expression(BO);
456
457    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
458    if (EI != expressionNumbering.end()) {
459      valueNumbering.insert(std::make_pair(V, EI->second));
460      return EI->second;
461    } else {
462      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
463      valueNumbering.insert(std::make_pair(V, nextValueNumber));
464
465      return nextValueNumber++;
466    }
467  } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
468    Expression e = create_expression(C);
469
470    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
471    if (EI != expressionNumbering.end()) {
472      valueNumbering.insert(std::make_pair(V, EI->second));
473      return EI->second;
474    } else {
475      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
476      valueNumbering.insert(std::make_pair(V, nextValueNumber));
477
478      return nextValueNumber++;
479    }
480  } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
481    Expression e = create_expression(U);
482
483    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
484    if (EI != expressionNumbering.end()) {
485      valueNumbering.insert(std::make_pair(V, EI->second));
486      return EI->second;
487    } else {
488      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
489      valueNumbering.insert(std::make_pair(V, nextValueNumber));
490
491      return nextValueNumber++;
492    }
493  } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
494    Expression e = create_expression(U);
495
496    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
497    if (EI != expressionNumbering.end()) {
498      valueNumbering.insert(std::make_pair(V, EI->second));
499      return EI->second;
500    } else {
501      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
502      valueNumbering.insert(std::make_pair(V, nextValueNumber));
503
504      return nextValueNumber++;
505    }
506  } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
507    Expression e = create_expression(U);
508
509    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
510    if (EI != expressionNumbering.end()) {
511      valueNumbering.insert(std::make_pair(V, EI->second));
512      return EI->second;
513    } else {
514      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
515      valueNumbering.insert(std::make_pair(V, nextValueNumber));
516
517      return nextValueNumber++;
518    }
519  } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
520    Expression e = create_expression(U);
521
522    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
523    if (EI != expressionNumbering.end()) {
524      valueNumbering.insert(std::make_pair(V, EI->second));
525      return EI->second;
526    } else {
527      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
528      valueNumbering.insert(std::make_pair(V, nextValueNumber));
529
530      return nextValueNumber++;
531    }
532  } else if (CastInst* U = dyn_cast<CastInst>(V)) {
533    Expression e = create_expression(U);
534
535    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
536    if (EI != expressionNumbering.end()) {
537      valueNumbering.insert(std::make_pair(V, EI->second));
538      return EI->second;
539    } else {
540      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
541      valueNumbering.insert(std::make_pair(V, nextValueNumber));
542
543      return nextValueNumber++;
544    }
545  } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
546    Expression e = create_expression(U);
547
548    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
549    if (EI != expressionNumbering.end()) {
550      valueNumbering.insert(std::make_pair(V, EI->second));
551      return EI->second;
552    } else {
553      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
554      valueNumbering.insert(std::make_pair(V, nextValueNumber));
555
556      return nextValueNumber++;
557    }
558  } else {
559    valueNumbering.insert(std::make_pair(V, nextValueNumber));
560    return nextValueNumber++;
561  }
562}
563
564/// lookup - Returns the value number of the specified value. Fails if
565/// the value has not yet been numbered.
566uint32_t ValueTable::lookup(Value* V) const {
567  DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
568  assert(VI != valueNumbering.end() && "Value not numbered?");
569  return VI->second;
570}
571
572/// clear - Remove all entries from the ValueTable
573void ValueTable::clear() {
574  valueNumbering.clear();
575  expressionNumbering.clear();
576  nextValueNumber = 1;
577}
578
579/// erase - Remove a value from the value numbering
580void ValueTable::erase(Value* V) {
581  valueNumbering.erase(V);
582}
583
584//===----------------------------------------------------------------------===//
585//                       ValueNumberedSet Class
586//===----------------------------------------------------------------------===//
587namespace {
588class VISIBILITY_HIDDEN ValueNumberedSet {
589  private:
590    SmallPtrSet<Value*, 8> contents;
591    BitVector numbers;
592  public:
593    ValueNumberedSet() { numbers.resize(1); }
594    ValueNumberedSet(const ValueNumberedSet& other) {
595      numbers = other.numbers;
596      contents = other.contents;
597    }
598
599    typedef SmallPtrSet<Value*, 8>::iterator iterator;
600
601    iterator begin() { return contents.begin(); }
602    iterator end() { return contents.end(); }
603
604    bool insert(Value* v) { return contents.insert(v); }
605    void insert(iterator I, iterator E) { contents.insert(I, E); }
606    void erase(Value* v) { contents.erase(v); }
607    unsigned count(Value* v) { return contents.count(v); }
608    size_t size() { return contents.size(); }
609
610    void set(unsigned i)  {
611      if (i >= numbers.size())
612        numbers.resize(i+1);
613
614      numbers.set(i);
615    }
616
617    void operator=(const ValueNumberedSet& other) {
618      contents = other.contents;
619      numbers = other.numbers;
620    }
621
622    void reset(unsigned i)  {
623      if (i < numbers.size())
624        numbers.reset(i);
625    }
626
627    bool test(unsigned i)  {
628      if (i >= numbers.size())
629        return false;
630
631      return numbers.test(i);
632    }
633
634    void clear() {
635      contents.clear();
636      numbers.clear();
637    }
638};
639}
640
641//===----------------------------------------------------------------------===//
642//                         GVN Pass
643//===----------------------------------------------------------------------===//
644
645namespace {
646
647  class VISIBILITY_HIDDEN GVN : public FunctionPass {
648    bool runOnFunction(Function &F);
649  public:
650    static char ID; // Pass identification, replacement for typeid
651    GVN() : FunctionPass((intptr_t)&ID) { }
652
653  private:
654    ValueTable VN;
655
656    DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
657
658    typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
659    PhiMapType phiMap;
660
661
662    // This transformation requires dominator postdominator info
663    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
664      AU.setPreservesCFG();
665      AU.addRequired<DominatorTree>();
666      AU.addRequired<MemoryDependenceAnalysis>();
667      AU.addRequired<AliasAnalysis>();
668      AU.addRequired<TargetData>();
669      AU.addPreserved<AliasAnalysis>();
670      AU.addPreserved<MemoryDependenceAnalysis>();
671      AU.addPreserved<TargetData>();
672    }
673
674    // Helper fuctions
675    // FIXME: eliminate or document these better
676    Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
677    void val_insert(ValueNumberedSet& s, Value* v);
678    bool processLoad(LoadInst* L,
679                     DenseMap<Value*, LoadInst*> &lastLoad,
680                     SmallVectorImpl<Instruction*> &toErase);
681    bool processStore(StoreInst *SI, SmallVectorImpl<Instruction*> &toErase);
682    bool processInstruction(Instruction* I,
683                            ValueNumberedSet& currAvail,
684                            DenseMap<Value*, LoadInst*>& lastSeenLoad,
685                            SmallVectorImpl<Instruction*> &toErase);
686    bool processNonLocalLoad(LoadInst* L,
687                             SmallVectorImpl<Instruction*> &toErase);
688    bool processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
689                       SmallVectorImpl<Instruction*> &toErase);
690    bool performCallSlotOptzn(MemCpyInst* cpy, CallInst* C,
691                              SmallVectorImpl<Instruction*> &toErase);
692    Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
693                            DenseMap<BasicBlock*, Value*> &Phis,
694                            bool top_level = false);
695    void dump(DenseMap<BasicBlock*, Value*>& d);
696    bool iterateOnFunction(Function &F);
697    Value* CollapsePhi(PHINode* p);
698    bool isSafeReplacement(PHINode* p, Instruction* inst);
699  };
700
701  char GVN::ID = 0;
702}
703
704// createGVNPass - The public interface to this file...
705FunctionPass *llvm::createGVNPass() { return new GVN(); }
706
707static RegisterPass<GVN> X("gvn",
708                           "Global Value Numbering");
709
710/// find_leader - Given a set and a value number, return the first
711/// element of the set with that value number, or 0 if no such element
712/// is present
713Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
714  if (!vals.test(v))
715    return 0;
716
717  for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
718       I != E; ++I)
719    if (v == VN.lookup(*I))
720      return *I;
721
722  assert(0 && "No leader found, but present bit is set?");
723  return 0;
724}
725
726/// val_insert - Insert a value into a set only if there is not a value
727/// with the same value number already in the set
728void GVN::val_insert(ValueNumberedSet& s, Value* v) {
729  uint32_t num = VN.lookup(v);
730  if (!s.test(num))
731    s.insert(v);
732}
733
734void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
735  printf("{\n");
736  for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
737       E = d.end(); I != E; ++I) {
738    if (I->second == MemoryDependenceAnalysis::None)
739      printf("None\n");
740    else
741      I->second->dump();
742  }
743  printf("}\n");
744}
745
746Value* GVN::CollapsePhi(PHINode* p) {
747  DominatorTree &DT = getAnalysis<DominatorTree>();
748  Value* constVal = p->hasConstantValue();
749
750  if (!constVal) return 0;
751
752  Instruction* inst = dyn_cast<Instruction>(constVal);
753  if (!inst)
754    return constVal;
755
756  if (DT.dominates(inst, p))
757    if (isSafeReplacement(p, inst))
758      return inst;
759  return 0;
760}
761
762bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
763  if (!isa<PHINode>(inst))
764    return true;
765
766  for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
767       UI != E; ++UI)
768    if (PHINode* use_phi = dyn_cast<PHINode>(UI))
769      if (use_phi->getParent() == inst->getParent())
770        return false;
771
772  return true;
773}
774
775/// GetValueForBlock - Get the value to use within the specified basic block.
776/// available values are in Phis.
777Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
778                             DenseMap<BasicBlock*, Value*> &Phis,
779                             bool top_level) {
780
781  // If we have already computed this value, return the previously computed val.
782  DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
783  if (V != Phis.end() && !top_level) return V->second;
784
785  BasicBlock* singlePred = BB->getSinglePredecessor();
786  if (singlePred) {
787    Value *ret = GetValueForBlock(singlePred, orig, Phis);
788    Phis[BB] = ret;
789    return ret;
790  }
791
792  // Otherwise, the idom is the loop, so we need to insert a PHI node.  Do so
793  // now, then get values to fill in the incoming values for the PHI.
794  PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
795                            BB->begin());
796  PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
797
798  if (Phis.count(BB) == 0)
799    Phis.insert(std::make_pair(BB, PN));
800
801  // Fill in the incoming values for the block.
802  for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
803    Value* val = GetValueForBlock(*PI, orig, Phis);
804    PN->addIncoming(val, *PI);
805  }
806
807  AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
808  AA.copyValue(orig, PN);
809
810  // Attempt to collapse PHI nodes that are trivially redundant
811  Value* v = CollapsePhi(PN);
812  if (!v) {
813    // Cache our phi construction results
814    phiMap[orig->getPointerOperand()].insert(PN);
815    return PN;
816  }
817
818  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
819
820  MD.removeInstruction(PN);
821  PN->replaceAllUsesWith(v);
822
823  for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
824       E = Phis.end(); I != E; ++I)
825    if (I->second == PN)
826      I->second = v;
827
828  PN->eraseFromParent();
829
830  Phis[BB] = v;
831  return v;
832}
833
834/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
835/// non-local by performing PHI construction.
836bool GVN::processNonLocalLoad(LoadInst* L,
837                              SmallVectorImpl<Instruction*> &toErase) {
838  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
839
840  // Find the non-local dependencies of the load
841  DenseMap<BasicBlock*, Value*> deps;
842  MD.getNonLocalDependency(L, deps);
843
844  DenseMap<BasicBlock*, Value*> repl;
845
846  // Filter out useless results (non-locals, etc)
847  for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
848       I != E; ++I) {
849    if (I->second == MemoryDependenceAnalysis::None)
850      return false;
851
852    if (I->second == MemoryDependenceAnalysis::NonLocal)
853      continue;
854
855    if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
856      if (S->getPointerOperand() != L->getPointerOperand())
857        return false;
858      repl[I->first] = S->getOperand(0);
859    } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
860      if (LD->getPointerOperand() != L->getPointerOperand())
861        return false;
862      repl[I->first] = LD;
863    } else {
864      return false;
865    }
866  }
867
868  // Use cached PHI construction information from previous runs
869  SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
870  for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
871       I != E; ++I) {
872    if ((*I)->getParent() == L->getParent()) {
873      MD.removeInstruction(L);
874      L->replaceAllUsesWith(*I);
875      toErase.push_back(L);
876      NumGVNLoad++;
877      return true;
878    }
879
880    repl.insert(std::make_pair((*I)->getParent(), *I));
881  }
882
883  // Perform PHI construction
884  SmallPtrSet<BasicBlock*, 4> visited;
885  Value* v = GetValueForBlock(L->getParent(), L, repl, true);
886
887  MD.removeInstruction(L);
888  L->replaceAllUsesWith(v);
889  toErase.push_back(L);
890  NumGVNLoad++;
891
892  return true;
893}
894
895/// processLoad - Attempt to eliminate a load, first by eliminating it
896/// locally, and then attempting non-local elimination if that fails.
897bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
898                      SmallVectorImpl<Instruction*> &toErase) {
899  if (L->isVolatile()) {
900    lastLoad[L->getPointerOperand()] = L;
901    return false;
902  }
903
904  Value* pointer = L->getPointerOperand();
905  LoadInst*& last = lastLoad[pointer];
906
907  // ... to a pointer that has been loaded from before...
908  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
909  bool removedNonLocal = false;
910  Instruction* dep = MD.getDependency(L);
911  if (dep == MemoryDependenceAnalysis::NonLocal &&
912      L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
913    removedNonLocal = processNonLocalLoad(L, toErase);
914
915    if (!removedNonLocal)
916      last = L;
917
918    return removedNonLocal;
919  }
920
921
922  bool deletedLoad = false;
923
924  // Walk up the dependency chain until we either find
925  // a dependency we can use, or we can't walk any further
926  while (dep != MemoryDependenceAnalysis::None &&
927         dep != MemoryDependenceAnalysis::NonLocal &&
928         (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
929    // ... that depends on a store ...
930    if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
931      if (S->getPointerOperand() == pointer) {
932        // Remove it!
933        MD.removeInstruction(L);
934
935        L->replaceAllUsesWith(S->getOperand(0));
936        toErase.push_back(L);
937        deletedLoad = true;
938        NumGVNLoad++;
939      }
940
941      // Whether we removed it or not, we can't
942      // go any further
943      break;
944    } else if (!last) {
945      // If we don't depend on a store, and we haven't
946      // been loaded before, bail.
947      break;
948    } else if (dep == last) {
949      // Remove it!
950      MD.removeInstruction(L);
951
952      L->replaceAllUsesWith(last);
953      toErase.push_back(L);
954      deletedLoad = true;
955      NumGVNLoad++;
956
957      break;
958    } else {
959      dep = MD.getDependency(L, dep);
960    }
961  }
962
963  if (dep != MemoryDependenceAnalysis::None &&
964      dep != MemoryDependenceAnalysis::NonLocal &&
965      isa<AllocationInst>(dep)) {
966    // Check that this load is actually from the
967    // allocation we found
968    Value* v = L->getOperand(0);
969    while (true) {
970      if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
971        v = BC->getOperand(0);
972      else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
973        v = GEP->getOperand(0);
974      else
975        break;
976    }
977    if (v == dep) {
978      // If this load depends directly on an allocation, there isn't
979      // anything stored there; therefore, we can optimize this load
980      // to undef.
981      MD.removeInstruction(L);
982
983      L->replaceAllUsesWith(UndefValue::get(L->getType()));
984      toErase.push_back(L);
985      deletedLoad = true;
986      NumGVNLoad++;
987    }
988  }
989
990  if (!deletedLoad)
991    last = L;
992
993  return deletedLoad;
994}
995
996/// isBytewiseValue - If the specified value can be set by repeating the same
997/// byte in memory, return the i8 value that it is represented with.  This is
998/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
999/// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
1000/// byte store (e.g. i16 0x1234), return null.
1001static Value *isBytewiseValue(Value *V) {
1002  // All byte-wide stores are splatable, even of arbitrary variables.
1003  if (V->getType() == Type::Int8Ty) return V;
1004
1005  // Constant float and double values can be handled as integer values if the
1006  // corresponding integer value is "byteable".  An important case is 0.0.
1007  if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1008    if (CFP->getType() == Type::FloatTy)
1009      V = ConstantExpr::getBitCast(CFP, Type::Int32Ty);
1010    if (CFP->getType() == Type::DoubleTy)
1011      V = ConstantExpr::getBitCast(CFP, Type::Int64Ty);
1012    // Don't handle long double formats, which have strange constraints.
1013  }
1014
1015  // We can handle constant integers that are power of two in size and a
1016  // multiple of 8 bits.
1017  if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1018    unsigned Width = CI->getBitWidth();
1019    if (isPowerOf2_32(Width) && Width > 8) {
1020      // We can handle this value if the recursive binary decomposition is the
1021      // same at all levels.
1022      APInt Val = CI->getValue();
1023      APInt Val2;
1024      while (Val.getBitWidth() != 8) {
1025        unsigned NextWidth = Val.getBitWidth()/2;
1026        Val2  = Val.lshr(NextWidth);
1027        Val2.trunc(Val.getBitWidth()/2);
1028        Val.trunc(Val.getBitWidth()/2);
1029
1030        // If the top/bottom halves aren't the same, reject it.
1031        if (Val != Val2)
1032          return 0;
1033      }
1034      return ConstantInt::get(Val);
1035    }
1036  }
1037
1038  // Conceptually, we could handle things like:
1039  //   %a = zext i8 %X to i16
1040  //   %b = shl i16 %a, 8
1041  //   %c = or i16 %a, %b
1042  // but until there is an example that actually needs this, it doesn't seem
1043  // worth worrying about.
1044  return 0;
1045}
1046
1047static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
1048                                  bool &VariableIdxFound, TargetData &TD) {
1049  // Skip over the first indices.
1050  gep_type_iterator GTI = gep_type_begin(GEP);
1051  for (unsigned i = 1; i != Idx; ++i, ++GTI)
1052    /*skip along*/;
1053
1054  // Compute the offset implied by the rest of the indices.
1055  int64_t Offset = 0;
1056  for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
1057    ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
1058    if (OpC == 0)
1059      return VariableIdxFound = true;
1060    if (OpC->isZero()) continue;  // No offset.
1061
1062    // Handle struct indices, which add their field offset to the pointer.
1063    if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1064      Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1065      continue;
1066    }
1067
1068    // Otherwise, we have a sequential type like an array or vector.  Multiply
1069    // the index by the ElementSize.
1070    uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
1071    Offset += Size*OpC->getSExtValue();
1072  }
1073
1074  return Offset;
1075}
1076
1077/// IsPointerAtOffset - Return true if Ptr1 is exactly provably equal to Ptr2
1078/// plus the specified constant offset.  For example, Ptr1 might be &A[42], and
1079/// Ptr2 might be &A[40] and Offset might be 8.
1080static bool IsPointerAtOffset(Value *Ptr1, Value *Ptr2, uint64_t Offset,
1081                              TargetData &TD) {
1082  // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
1083  // base.  After that base, they may have some number of common (and
1084  // potentially variable) indices.  After that they handle some constant
1085  // offset, which determines their offset from each other.  At this point, we
1086  // handle no other case.
1087  GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
1088  GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
1089  if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
1090    return false;
1091
1092  // Skip any common indices and track the GEP types.
1093  unsigned Idx = 1;
1094  for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
1095    if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
1096      break;
1097
1098  bool VariableIdxFound = false;
1099  int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
1100  int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
1101  if (VariableIdxFound) return false;
1102
1103  return Offset1 == Offset2+(int64_t)Offset;
1104}
1105
1106
1107/// processStore - When GVN is scanning forward over instructions, we look for
1108/// some other patterns to fold away.  In particular, this looks for stores to
1109/// neighboring locations of memory.  If it sees enough consequtive ones
1110/// (currently 4) it attempts to merge them together into a memcpy/memset.
1111bool GVN::processStore(StoreInst *SI, SmallVectorImpl<Instruction*> &toErase) {
1112  if (!FormMemSet) return false;
1113  if (SI->isVolatile()) return false;
1114
1115  // There are two cases that are interesting for this code to handle: memcpy
1116  // and memset.  Right now we only handle memset.
1117
1118  // Ensure that the value being stored is something that can be memset'able a
1119  // byte at a time like "0" or "-1" or any width, as well as things like
1120  // 0xA0A0A0A0 and 0.0.
1121  Value *ByteVal = isBytewiseValue(SI->getOperand(0));
1122  if (!ByteVal)
1123    return false;
1124
1125  TargetData &TD = getAnalysis<TargetData>();
1126  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
1127
1128  // Okay, so we now have a single store that can be splatable.  Try to 'grow'
1129  // this store by looking for neighboring stores to the immediate left or right
1130  // of the store we have so far.  While we could in theory handle stores in
1131  // this order:  A[0], A[2], A[1]
1132  // in practice, right now we only worry about cases where stores are
1133  // consequtive in increasing or decreasing address order.
1134  uint64_t BytesSoFar = TD.getTypeStoreSize(SI->getOperand(0)->getType());
1135  uint64_t BytesFromSI = 0;
1136  unsigned StartAlign = SI->getAlignment();
1137  Value *StartPtr = SI->getPointerOperand();
1138  SmallVector<StoreInst*, 16> Stores;
1139  Stores.push_back(SI);
1140
1141  BasicBlock::iterator BI = SI;
1142  for (++BI; !isa<TerminatorInst>(BI); ++BI) {
1143    if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) {
1144      // If the call is readnone, ignore it, otherwise bail out.  We don't even
1145      // allow readonly here because we don't want something like:
1146      // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
1147      if (AA.getModRefBehavior(CallSite::get(BI)) ==
1148            AliasAnalysis::DoesNotAccessMemory)
1149        continue;
1150
1151      // TODO: If this is a memset, try to join it in.
1152
1153      break;
1154    } else if (isa<VAArgInst>(BI) || isa<LoadInst>(BI))
1155      break;
1156
1157    // If this is a non-store instruction it is fine, ignore it.
1158    StoreInst *NextStore = dyn_cast<StoreInst>(BI);
1159    if (NextStore == 0) continue;
1160
1161    // If this is a store, see if we can merge it in.
1162    if (NextStore->isVolatile()) break;
1163
1164    // Check to see if this stored value is of the same byte-splattable value.
1165    if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
1166      break;
1167
1168    Value *ThisPointer = NextStore->getPointerOperand();
1169    unsigned AccessSize = TD.getTypeStoreSize(SI->getOperand(0)->getType());
1170
1171    // If so, check to see if the store is before the current range or after it
1172    // in either case, extend the range, otherwise reject it.
1173    if (IsPointerAtOffset(ThisPointer, StartPtr, BytesSoFar, TD)) {
1174      // Okay, this extends the stored area on the end, just add to the bytes
1175      // so far and remember this store.
1176      BytesSoFar += AccessSize;
1177      Stores.push_back(NextStore);
1178      continue;
1179    }
1180
1181    if (IsPointerAtOffset(StartPtr, ThisPointer, AccessSize, TD)) {
1182      // Okay, the store is before the current range.  Reset our start pointer
1183      // and get new alignment info etc.
1184      BytesSoFar  += AccessSize;
1185      BytesFromSI += AccessSize;
1186      Stores.push_back(NextStore);
1187      StartPtr = ThisPointer;
1188      StartAlign = NextStore->getAlignment();
1189      continue;
1190    }
1191
1192    // Otherwise, this store wasn't contiguous with our current range, bail out.
1193    break;
1194  }
1195
1196  // If we found less than 4 stores to merge, bail out, it isn't worth losing
1197  // type information in llvm IR to do the transformation.
1198  if (Stores.size() < 4)
1199    return false;
1200
1201  // Otherwise, we do want to transform this!  Create a new memset.  We put the
1202  // memset right after the first store that we found in this block.  This
1203  // ensures that the caller will increment the iterator to  the memset before
1204  // it deletes all the stores.
1205  BasicBlock::iterator InsertPt = SI; ++InsertPt;
1206
1207  Function *F = Intrinsic::getDeclaration(SI->getParent()->getParent()
1208                                          ->getParent(), Intrinsic::memset_i64);
1209
1210  // StartPtr may not dominate the starting point.  Instead of using it, base
1211  // the destination pointer off the input to the first store in the block.
1212  StartPtr = SI->getPointerOperand();
1213
1214  // Cast the start ptr to be i8* as memset requires.
1215  const Type *i8Ptr = PointerType::getUnqual(Type::Int8Ty);
1216  if (StartPtr->getType() != i8Ptr)
1217    StartPtr = new BitCastInst(StartPtr, i8Ptr, StartPtr->getNameStart(),
1218                               InsertPt);
1219
1220  // Offset the pointer if needed.
1221  if (BytesFromSI)
1222    StartPtr = new GetElementPtrInst(StartPtr, ConstantInt::get(Type::Int64Ty,
1223                                                                -BytesFromSI),
1224                                     "ptroffset", InsertPt);
1225
1226  Value *Ops[] = {
1227    StartPtr, ByteVal,   // Start, value
1228    ConstantInt::get(Type::Int64Ty, BytesSoFar),  // size
1229    ConstantInt::get(Type::Int32Ty, StartAlign)   // align
1230  };
1231  new CallInst(F, Ops, Ops+4, "", InsertPt);
1232
1233  // Zap all the stores.
1234  toErase.append(Stores.begin(), Stores.end());
1235
1236  ++NumMemSetInfer;
1237  return true;
1238}
1239
1240
1241/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
1242/// and checks for the possibility of a call slot optimization by having
1243/// the call write its result directly into the destination of the memcpy.
1244bool GVN::performCallSlotOptzn(MemCpyInst *cpy, CallInst *C,
1245                               SmallVectorImpl<Instruction*> &toErase) {
1246  // The general transformation to keep in mind is
1247  //
1248  //   call @func(..., src, ...)
1249  //   memcpy(dest, src, ...)
1250  //
1251  // ->
1252  //
1253  //   memcpy(dest, src, ...)
1254  //   call @func(..., dest, ...)
1255  //
1256  // Since moving the memcpy is technically awkward, we additionally check that
1257  // src only holds uninitialized values at the moment of the call, meaning that
1258  // the memcpy can be discarded rather than moved.
1259
1260  // Deliberately get the source and destination with bitcasts stripped away,
1261  // because we'll need to do type comparisons based on the underlying type.
1262  Value* cpyDest = cpy->getDest();
1263  Value* cpySrc = cpy->getSource();
1264  CallSite CS = CallSite::get(C);
1265
1266  // We need to be able to reason about the size of the memcpy, so we require
1267  // that it be a constant.
1268  ConstantInt* cpyLength = dyn_cast<ConstantInt>(cpy->getLength());
1269  if (!cpyLength)
1270    return false;
1271
1272  // Require that src be an alloca.  This simplifies the reasoning considerably.
1273  AllocaInst* srcAlloca = dyn_cast<AllocaInst>(cpySrc);
1274  if (!srcAlloca)
1275    return false;
1276
1277  // Check that all of src is copied to dest.
1278  TargetData& TD = getAnalysis<TargetData>();
1279
1280  ConstantInt* srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
1281  if (!srcArraySize)
1282    return false;
1283
1284  uint64_t srcSize = TD.getABITypeSize(srcAlloca->getAllocatedType()) *
1285    srcArraySize->getZExtValue();
1286
1287  if (cpyLength->getZExtValue() < srcSize)
1288    return false;
1289
1290  // Check that accessing the first srcSize bytes of dest will not cause a
1291  // trap.  Otherwise the transform is invalid since it might cause a trap
1292  // to occur earlier than it otherwise would.
1293  if (AllocaInst* A = dyn_cast<AllocaInst>(cpyDest)) {
1294    // The destination is an alloca.  Check it is larger than srcSize.
1295    ConstantInt* destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
1296    if (!destArraySize)
1297      return false;
1298
1299    uint64_t destSize = TD.getABITypeSize(A->getAllocatedType()) *
1300      destArraySize->getZExtValue();
1301
1302    if (destSize < srcSize)
1303      return false;
1304  } else if (Argument* A = dyn_cast<Argument>(cpyDest)) {
1305    // If the destination is an sret parameter then only accesses that are
1306    // outside of the returned struct type can trap.
1307    if (!A->hasStructRetAttr())
1308      return false;
1309
1310    const Type* StructTy = cast<PointerType>(A->getType())->getElementType();
1311    uint64_t destSize = TD.getABITypeSize(StructTy);
1312
1313    if (destSize < srcSize)
1314      return false;
1315  } else {
1316    return false;
1317  }
1318
1319  // Check that src is not accessed except via the call and the memcpy.  This
1320  // guarantees that it holds only undefined values when passed in (so the final
1321  // memcpy can be dropped), that it is not read or written between the call and
1322  // the memcpy, and that writing beyond the end of it is undefined.
1323  SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
1324                                   srcAlloca->use_end());
1325  while (!srcUseList.empty()) {
1326    User* UI = srcUseList.back();
1327    srcUseList.pop_back();
1328
1329    if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
1330      for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
1331           I != E; ++I)
1332        srcUseList.push_back(*I);
1333    } else if (UI != C && UI != cpy) {
1334      return false;
1335    }
1336  }
1337
1338  // Since we're changing the parameter to the callsite, we need to make sure
1339  // that what would be the new parameter dominates the callsite.
1340  DominatorTree& DT = getAnalysis<DominatorTree>();
1341  if (Instruction* cpyDestInst = dyn_cast<Instruction>(cpyDest))
1342    if (!DT.dominates(cpyDestInst, C))
1343      return false;
1344
1345  // In addition to knowing that the call does not access src in some
1346  // unexpected manner, for example via a global, which we deduce from
1347  // the use analysis, we also need to know that it does not sneakily
1348  // access dest.  We rely on AA to figure this out for us.
1349  AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1350  if (AA.getModRefInfo(C, cpy->getRawDest(), srcSize) !=
1351      AliasAnalysis::NoModRef)
1352    return false;
1353
1354  // All the checks have passed, so do the transformation.
1355  for (unsigned i = 0; i < CS.arg_size(); ++i)
1356    if (CS.getArgument(i) == cpySrc) {
1357      if (cpySrc->getType() != cpyDest->getType())
1358        cpyDest = CastInst::createPointerCast(cpyDest, cpySrc->getType(),
1359                                              cpyDest->getName(), C);
1360      CS.setArgument(i, cpyDest);
1361    }
1362
1363  // Drop any cached information about the call, because we may have changed
1364  // its dependence information by changing its parameter.
1365  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1366  MD.dropInstruction(C);
1367
1368  // Remove the memcpy
1369  MD.removeInstruction(cpy);
1370  toErase.push_back(cpy);
1371
1372  return true;
1373}
1374
1375/// processMemCpy - perform simplication of memcpy's.  If we have memcpy A which
1376/// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
1377/// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
1378///  This allows later passes to remove the first memcpy altogether.
1379bool GVN::processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
1380                        SmallVectorImpl<Instruction*> &toErase) {
1381  // We can only transforms memcpy's where the dest of one is the source of the
1382  // other
1383  if (M->getSource() != MDep->getDest())
1384    return false;
1385
1386  // Second, the length of the memcpy's must be the same, or the preceeding one
1387  // must be larger than the following one.
1388  ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
1389  ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
1390  if (!C1 || !C2)
1391    return false;
1392
1393  uint64_t DepSize = C1->getValue().getZExtValue();
1394  uint64_t CpySize = C2->getValue().getZExtValue();
1395
1396  if (DepSize < CpySize)
1397    return false;
1398
1399  // Finally, we have to make sure that the dest of the second does not
1400  // alias the source of the first
1401  AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1402  if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
1403      AliasAnalysis::NoAlias)
1404    return false;
1405  else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
1406           AliasAnalysis::NoAlias)
1407    return false;
1408  else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
1409           != AliasAnalysis::NoAlias)
1410    return false;
1411
1412  // If all checks passed, then we can transform these memcpy's
1413  Function* MemCpyFun = Intrinsic::getDeclaration(
1414                                 M->getParent()->getParent()->getParent(),
1415                                 M->getIntrinsicID());
1416
1417  std::vector<Value*> args;
1418  args.push_back(M->getRawDest());
1419  args.push_back(MDep->getRawSource());
1420  args.push_back(M->getLength());
1421  args.push_back(M->getAlignment());
1422
1423  CallInst* C = new CallInst(MemCpyFun, args.begin(), args.end(), "", M);
1424
1425  MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1426  if (MD.getDependency(C) == MDep) {
1427    MD.dropInstruction(M);
1428    toErase.push_back(M);
1429    return true;
1430  }
1431
1432  MD.removeInstruction(C);
1433  toErase.push_back(C);
1434  return false;
1435}
1436
1437/// processInstruction - When calculating availability, handle an instruction
1438/// by inserting it into the appropriate sets
1439bool GVN::processInstruction(Instruction *I, ValueNumberedSet &currAvail,
1440                             DenseMap<Value*, LoadInst*> &lastSeenLoad,
1441                             SmallVectorImpl<Instruction*> &toErase) {
1442  if (LoadInst* L = dyn_cast<LoadInst>(I))
1443    return processLoad(L, lastSeenLoad, toErase);
1444
1445  if (StoreInst *SI = dyn_cast<StoreInst>(I))
1446    return processStore(SI, toErase);
1447
1448  if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
1449    MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1450
1451    // The are two possible optimizations we can do for memcpy:
1452    //   a) memcpy-memcpy xform which exposes redundance for DSE
1453    //   b) call-memcpy xform for return slot optimization
1454    Instruction* dep = MD.getDependency(M);
1455    if (dep == MemoryDependenceAnalysis::None ||
1456        dep == MemoryDependenceAnalysis::NonLocal)
1457      return false;
1458    if (MemCpyInst *MemCpy = dyn_cast<MemCpyInst>(dep))
1459      return processMemCpy(M, MemCpy, toErase);
1460    if (CallInst* C = dyn_cast<CallInst>(dep))
1461      return performCallSlotOptzn(M, C, toErase);
1462    return false;
1463  }
1464
1465  unsigned num = VN.lookup_or_add(I);
1466
1467  // Collapse PHI nodes
1468  if (PHINode* p = dyn_cast<PHINode>(I)) {
1469    Value* constVal = CollapsePhi(p);
1470
1471    if (constVal) {
1472      for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1473           PI != PE; ++PI)
1474        if (PI->second.count(p))
1475          PI->second.erase(p);
1476
1477      p->replaceAllUsesWith(constVal);
1478      toErase.push_back(p);
1479    }
1480  // Perform value-number based elimination
1481  } else if (currAvail.test(num)) {
1482    Value* repl = find_leader(currAvail, num);
1483
1484    if (CallInst* CI = dyn_cast<CallInst>(I)) {
1485      AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1486      if (!AA.doesNotAccessMemory(CI)) {
1487        MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1488        if (cast<Instruction>(repl)->getParent() != CI->getParent() ||
1489            MD.getDependency(CI) != MD.getDependency(cast<CallInst>(repl))) {
1490          // There must be an intervening may-alias store, so nothing from
1491          // this point on will be able to be replaced with the preceding call
1492          currAvail.erase(repl);
1493          currAvail.insert(I);
1494
1495          return false;
1496        }
1497      }
1498    }
1499
1500    // Remove it!
1501    MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1502    MD.removeInstruction(I);
1503
1504    VN.erase(I);
1505    I->replaceAllUsesWith(repl);
1506    toErase.push_back(I);
1507    return true;
1508  } else if (!I->isTerminator()) {
1509    currAvail.set(num);
1510    currAvail.insert(I);
1511  }
1512
1513  return false;
1514}
1515
1516// GVN::runOnFunction - This is the main transformation entry point for a
1517// function.
1518//
1519bool GVN::runOnFunction(Function& F) {
1520  VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1521
1522  bool changed = false;
1523  bool shouldContinue = true;
1524
1525  while (shouldContinue) {
1526    shouldContinue = iterateOnFunction(F);
1527    changed |= shouldContinue;
1528  }
1529
1530  return changed;
1531}
1532
1533
1534// GVN::iterateOnFunction - Executes one iteration of GVN
1535bool GVN::iterateOnFunction(Function &F) {
1536  // Clean out global sets from any previous functions
1537  VN.clear();
1538  availableOut.clear();
1539  phiMap.clear();
1540
1541  bool changed_function = false;
1542
1543  DominatorTree &DT = getAnalysis<DominatorTree>();
1544
1545  SmallVector<Instruction*, 4> toErase;
1546  DenseMap<Value*, LoadInst*> lastSeenLoad;
1547
1548  // Top-down walk of the dominator tree
1549  for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1550         E = df_end(DT.getRootNode()); DI != E; ++DI) {
1551
1552    // Get the set to update for this block
1553    ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1554    lastSeenLoad.clear();
1555
1556    BasicBlock* BB = DI->getBlock();
1557
1558    // A block inherits AVAIL_OUT from its dominator
1559    if (DI->getIDom() != 0)
1560      currAvail = availableOut[DI->getIDom()->getBlock()];
1561
1562    for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1563         BI != BE; ) {
1564      changed_function |= processInstruction(BI, currAvail,
1565                                             lastSeenLoad, toErase);
1566
1567      NumGVNInstr += toErase.size();
1568
1569      // Avoid iterator invalidation
1570      ++BI;
1571
1572      for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1573           E = toErase.end(); I != E; ++I)
1574        (*I)->eraseFromParent();
1575
1576      toErase.clear();
1577    }
1578  }
1579
1580  return changed_function;
1581}
1582