GVN.cpp revision 813dbd59127973b1cba17933ca368d3d734121d6
1//===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs global value numbering to eliminate fully redundant
11// instructions.  It also performs simple dead load elimination.
12//
13// Note that this pass does the value numbering itself; it does not use the
14// ValueNumbering analysis passes.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "gvn"
19#include "llvm/Transforms/Scalar.h"
20#include "llvm/BasicBlock.h"
21#include "llvm/Constants.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/Function.h"
24#include "llvm/IntrinsicInst.h"
25#include "llvm/LLVMContext.h"
26#include "llvm/Operator.h"
27#include "llvm/Value.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/DepthFirstIterator.h"
30#include "llvm/ADT/PostOrderIterator.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/Analysis/Dominators.h"
35#include "llvm/Analysis/AliasAnalysis.h"
36#include "llvm/Analysis/MallocHelper.h"
37#include "llvm/Analysis/MemoryDependenceAnalysis.h"
38#include "llvm/Support/CFG.h"
39#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/Debug.h"
41#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/GetElementPtrTypeIterator.h"
43#include "llvm/Support/raw_ostream.h"
44#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
47#include <cstdio>
48using namespace llvm;
49
50STATISTIC(NumGVNInstr,  "Number of instructions deleted");
51STATISTIC(NumGVNLoad,   "Number of loads deleted");
52STATISTIC(NumGVNPRE,    "Number of instructions PRE'd");
53STATISTIC(NumGVNBlocks, "Number of blocks merged");
54STATISTIC(NumPRELoad,   "Number of loads PRE'd");
55
56static cl::opt<bool> EnablePRE("enable-pre",
57                               cl::init(true), cl::Hidden);
58static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
59
60//===----------------------------------------------------------------------===//
61//                         ValueTable Class
62//===----------------------------------------------------------------------===//
63
64/// This class holds the mapping between values and value numbers.  It is used
65/// as an efficient mechanism to determine the expression-wise equivalence of
66/// two values.
67namespace {
68  struct Expression {
69    enum ExpressionOpcode { ADD, FADD, SUB, FSUB, MUL, FMUL,
70                            UDIV, SDIV, FDIV, UREM, SREM,
71                            FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
72                            ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
73                            ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
74                            FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
75                            FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
76                            FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
77                            SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
78                            FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
79                            PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
80                            EMPTY, TOMBSTONE };
81
82    ExpressionOpcode opcode;
83    const Type* type;
84    uint32_t firstVN;
85    uint32_t secondVN;
86    uint32_t thirdVN;
87    SmallVector<uint32_t, 4> varargs;
88    Value *function;
89
90    Expression() { }
91    Expression(ExpressionOpcode o) : opcode(o) { }
92
93    bool operator==(const Expression &other) const {
94      if (opcode != other.opcode)
95        return false;
96      else if (opcode == EMPTY || opcode == TOMBSTONE)
97        return true;
98      else if (type != other.type)
99        return false;
100      else if (function != other.function)
101        return false;
102      else if (firstVN != other.firstVN)
103        return false;
104      else if (secondVN != other.secondVN)
105        return false;
106      else if (thirdVN != other.thirdVN)
107        return false;
108      else {
109        if (varargs.size() != other.varargs.size())
110          return false;
111
112        for (size_t i = 0; i < varargs.size(); ++i)
113          if (varargs[i] != other.varargs[i])
114            return false;
115
116        return true;
117      }
118    }
119
120    bool operator!=(const Expression &other) const {
121      return !(*this == other);
122    }
123  };
124
125  class ValueTable {
126    private:
127      DenseMap<Value*, uint32_t> valueNumbering;
128      DenseMap<Expression, uint32_t> expressionNumbering;
129      AliasAnalysis* AA;
130      MemoryDependenceAnalysis* MD;
131      DominatorTree* DT;
132
133      uint32_t nextValueNumber;
134
135      Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
136      Expression::ExpressionOpcode getOpcode(CmpInst* C);
137      Expression::ExpressionOpcode getOpcode(CastInst* C);
138      Expression create_expression(BinaryOperator* BO);
139      Expression create_expression(CmpInst* C);
140      Expression create_expression(ShuffleVectorInst* V);
141      Expression create_expression(ExtractElementInst* C);
142      Expression create_expression(InsertElementInst* V);
143      Expression create_expression(SelectInst* V);
144      Expression create_expression(CastInst* C);
145      Expression create_expression(GetElementPtrInst* G);
146      Expression create_expression(CallInst* C);
147      Expression create_expression(Constant* C);
148    public:
149      ValueTable() : nextValueNumber(1) { }
150      uint32_t lookup_or_add(Value *V);
151      uint32_t lookup(Value *V) const;
152      void add(Value *V, uint32_t num);
153      void clear();
154      void erase(Value *v);
155      unsigned size();
156      void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
157      AliasAnalysis *getAliasAnalysis() const { return AA; }
158      void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
159      void setDomTree(DominatorTree* D) { DT = D; }
160      uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
161      void verifyRemoved(const Value *) const;
162  };
163}
164
165namespace llvm {
166template <> struct DenseMapInfo<Expression> {
167  static inline Expression getEmptyKey() {
168    return Expression(Expression::EMPTY);
169  }
170
171  static inline Expression getTombstoneKey() {
172    return Expression(Expression::TOMBSTONE);
173  }
174
175  static unsigned getHashValue(const Expression e) {
176    unsigned hash = e.opcode;
177
178    hash = e.firstVN + hash * 37;
179    hash = e.secondVN + hash * 37;
180    hash = e.thirdVN + hash * 37;
181
182    hash = ((unsigned)((uintptr_t)e.type >> 4) ^
183            (unsigned)((uintptr_t)e.type >> 9)) +
184           hash * 37;
185
186    for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
187         E = e.varargs.end(); I != E; ++I)
188      hash = *I + hash * 37;
189
190    hash = ((unsigned)((uintptr_t)e.function >> 4) ^
191            (unsigned)((uintptr_t)e.function >> 9)) +
192           hash * 37;
193
194    return hash;
195  }
196  static bool isEqual(const Expression &LHS, const Expression &RHS) {
197    return LHS == RHS;
198  }
199  static bool isPod() { return true; }
200};
201}
202
203//===----------------------------------------------------------------------===//
204//                     ValueTable Internal Functions
205//===----------------------------------------------------------------------===//
206Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
207  switch(BO->getOpcode()) {
208  default: // THIS SHOULD NEVER HAPPEN
209    llvm_unreachable("Binary operator with unknown opcode?");
210  case Instruction::Add:  return Expression::ADD;
211  case Instruction::FAdd: return Expression::FADD;
212  case Instruction::Sub:  return Expression::SUB;
213  case Instruction::FSub: return Expression::FSUB;
214  case Instruction::Mul:  return Expression::MUL;
215  case Instruction::FMul: return Expression::FMUL;
216  case Instruction::UDiv: return Expression::UDIV;
217  case Instruction::SDiv: return Expression::SDIV;
218  case Instruction::FDiv: return Expression::FDIV;
219  case Instruction::URem: return Expression::UREM;
220  case Instruction::SRem: return Expression::SREM;
221  case Instruction::FRem: return Expression::FREM;
222  case Instruction::Shl:  return Expression::SHL;
223  case Instruction::LShr: return Expression::LSHR;
224  case Instruction::AShr: return Expression::ASHR;
225  case Instruction::And:  return Expression::AND;
226  case Instruction::Or:   return Expression::OR;
227  case Instruction::Xor:  return Expression::XOR;
228  }
229}
230
231Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
232  if (isa<ICmpInst>(C)) {
233    switch (C->getPredicate()) {
234    default:  // THIS SHOULD NEVER HAPPEN
235      llvm_unreachable("Comparison with unknown predicate?");
236    case ICmpInst::ICMP_EQ:  return Expression::ICMPEQ;
237    case ICmpInst::ICMP_NE:  return Expression::ICMPNE;
238    case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
239    case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
240    case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
241    case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
242    case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
243    case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
244    case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
245    case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
246    }
247  } else {
248    switch (C->getPredicate()) {
249    default: // THIS SHOULD NEVER HAPPEN
250      llvm_unreachable("Comparison with unknown predicate?");
251    case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
252    case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
253    case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
254    case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
255    case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
256    case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
257    case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
258    case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
259    case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
260    case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
261    case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
262    case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
263    case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
264    case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
265    }
266  }
267}
268
269Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
270  switch(C->getOpcode()) {
271  default: // THIS SHOULD NEVER HAPPEN
272    llvm_unreachable("Cast operator with unknown opcode?");
273  case Instruction::Trunc:    return Expression::TRUNC;
274  case Instruction::ZExt:     return Expression::ZEXT;
275  case Instruction::SExt:     return Expression::SEXT;
276  case Instruction::FPToUI:   return Expression::FPTOUI;
277  case Instruction::FPToSI:   return Expression::FPTOSI;
278  case Instruction::UIToFP:   return Expression::UITOFP;
279  case Instruction::SIToFP:   return Expression::SITOFP;
280  case Instruction::FPTrunc:  return Expression::FPTRUNC;
281  case Instruction::FPExt:    return Expression::FPEXT;
282  case Instruction::PtrToInt: return Expression::PTRTOINT;
283  case Instruction::IntToPtr: return Expression::INTTOPTR;
284  case Instruction::BitCast:  return Expression::BITCAST;
285  }
286}
287
288Expression ValueTable::create_expression(CallInst* C) {
289  Expression e;
290
291  e.type = C->getType();
292  e.firstVN = 0;
293  e.secondVN = 0;
294  e.thirdVN = 0;
295  e.function = C->getCalledFunction();
296  e.opcode = Expression::CALL;
297
298  for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
299       I != E; ++I)
300    e.varargs.push_back(lookup_or_add(*I));
301
302  return e;
303}
304
305Expression ValueTable::create_expression(BinaryOperator* BO) {
306  Expression e;
307
308  e.firstVN = lookup_or_add(BO->getOperand(0));
309  e.secondVN = lookup_or_add(BO->getOperand(1));
310  e.thirdVN = 0;
311  e.function = 0;
312  e.type = BO->getType();
313  e.opcode = getOpcode(BO);
314
315  return e;
316}
317
318Expression ValueTable::create_expression(CmpInst* C) {
319  Expression e;
320
321  e.firstVN = lookup_or_add(C->getOperand(0));
322  e.secondVN = lookup_or_add(C->getOperand(1));
323  e.thirdVN = 0;
324  e.function = 0;
325  e.type = C->getType();
326  e.opcode = getOpcode(C);
327
328  return e;
329}
330
331Expression ValueTable::create_expression(CastInst* C) {
332  Expression e;
333
334  e.firstVN = lookup_or_add(C->getOperand(0));
335  e.secondVN = 0;
336  e.thirdVN = 0;
337  e.function = 0;
338  e.type = C->getType();
339  e.opcode = getOpcode(C);
340
341  return e;
342}
343
344Expression ValueTable::create_expression(ShuffleVectorInst* S) {
345  Expression e;
346
347  e.firstVN = lookup_or_add(S->getOperand(0));
348  e.secondVN = lookup_or_add(S->getOperand(1));
349  e.thirdVN = lookup_or_add(S->getOperand(2));
350  e.function = 0;
351  e.type = S->getType();
352  e.opcode = Expression::SHUFFLE;
353
354  return e;
355}
356
357Expression ValueTable::create_expression(ExtractElementInst* E) {
358  Expression e;
359
360  e.firstVN = lookup_or_add(E->getOperand(0));
361  e.secondVN = lookup_or_add(E->getOperand(1));
362  e.thirdVN = 0;
363  e.function = 0;
364  e.type = E->getType();
365  e.opcode = Expression::EXTRACT;
366
367  return e;
368}
369
370Expression ValueTable::create_expression(InsertElementInst* I) {
371  Expression e;
372
373  e.firstVN = lookup_or_add(I->getOperand(0));
374  e.secondVN = lookup_or_add(I->getOperand(1));
375  e.thirdVN = lookup_or_add(I->getOperand(2));
376  e.function = 0;
377  e.type = I->getType();
378  e.opcode = Expression::INSERT;
379
380  return e;
381}
382
383Expression ValueTable::create_expression(SelectInst* I) {
384  Expression e;
385
386  e.firstVN = lookup_or_add(I->getCondition());
387  e.secondVN = lookup_or_add(I->getTrueValue());
388  e.thirdVN = lookup_or_add(I->getFalseValue());
389  e.function = 0;
390  e.type = I->getType();
391  e.opcode = Expression::SELECT;
392
393  return e;
394}
395
396Expression ValueTable::create_expression(GetElementPtrInst* G) {
397  Expression e;
398
399  e.firstVN = lookup_or_add(G->getPointerOperand());
400  e.secondVN = 0;
401  e.thirdVN = 0;
402  e.function = 0;
403  e.type = G->getType();
404  e.opcode = Expression::GEP;
405
406  for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
407       I != E; ++I)
408    e.varargs.push_back(lookup_or_add(*I));
409
410  return e;
411}
412
413//===----------------------------------------------------------------------===//
414//                     ValueTable External Functions
415//===----------------------------------------------------------------------===//
416
417/// add - Insert a value into the table with a specified value number.
418void ValueTable::add(Value *V, uint32_t num) {
419  valueNumbering.insert(std::make_pair(V, num));
420}
421
422/// lookup_or_add - Returns the value number for the specified value, assigning
423/// it a new number if it did not have one before.
424uint32_t ValueTable::lookup_or_add(Value *V) {
425  DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
426  if (VI != valueNumbering.end())
427    return VI->second;
428
429  if (CallInst* C = dyn_cast<CallInst>(V)) {
430    if (AA->doesNotAccessMemory(C)) {
431      Expression e = create_expression(C);
432
433      DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
434      if (EI != expressionNumbering.end()) {
435        valueNumbering.insert(std::make_pair(V, EI->second));
436        return EI->second;
437      } else {
438        expressionNumbering.insert(std::make_pair(e, nextValueNumber));
439        valueNumbering.insert(std::make_pair(V, nextValueNumber));
440
441        return nextValueNumber++;
442      }
443    } else if (AA->onlyReadsMemory(C)) {
444      Expression e = create_expression(C);
445
446      if (expressionNumbering.find(e) == expressionNumbering.end()) {
447        expressionNumbering.insert(std::make_pair(e, nextValueNumber));
448        valueNumbering.insert(std::make_pair(V, nextValueNumber));
449        return nextValueNumber++;
450      }
451
452      MemDepResult local_dep = MD->getDependency(C);
453
454      if (!local_dep.isDef() && !local_dep.isNonLocal()) {
455        valueNumbering.insert(std::make_pair(V, nextValueNumber));
456        return nextValueNumber++;
457      }
458
459      if (local_dep.isDef()) {
460        CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
461
462        if (local_cdep->getNumOperands() != C->getNumOperands()) {
463          valueNumbering.insert(std::make_pair(V, nextValueNumber));
464          return nextValueNumber++;
465        }
466
467        for (unsigned i = 1; i < C->getNumOperands(); ++i) {
468          uint32_t c_vn = lookup_or_add(C->getOperand(i));
469          uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
470          if (c_vn != cd_vn) {
471            valueNumbering.insert(std::make_pair(V, nextValueNumber));
472            return nextValueNumber++;
473          }
474        }
475
476        uint32_t v = lookup_or_add(local_cdep);
477        valueNumbering.insert(std::make_pair(V, v));
478        return v;
479      }
480
481      // Non-local case.
482      const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
483        MD->getNonLocalCallDependency(CallSite(C));
484      // FIXME: call/call dependencies for readonly calls should return def, not
485      // clobber!  Move the checking logic to MemDep!
486      CallInst* cdep = 0;
487
488      // Check to see if we have a single dominating call instruction that is
489      // identical to C.
490      for (unsigned i = 0, e = deps.size(); i != e; ++i) {
491        const MemoryDependenceAnalysis::NonLocalDepEntry *I = &deps[i];
492        // Ignore non-local dependencies.
493        if (I->second.isNonLocal())
494          continue;
495
496        // We don't handle non-depedencies.  If we already have a call, reject
497        // instruction dependencies.
498        if (I->second.isClobber() || cdep != 0) {
499          cdep = 0;
500          break;
501        }
502
503        CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->second.getInst());
504        // FIXME: All duplicated with non-local case.
505        if (NonLocalDepCall && DT->properlyDominates(I->first, C->getParent())){
506          cdep = NonLocalDepCall;
507          continue;
508        }
509
510        cdep = 0;
511        break;
512      }
513
514      if (!cdep) {
515        valueNumbering.insert(std::make_pair(V, nextValueNumber));
516        return nextValueNumber++;
517      }
518
519      if (cdep->getNumOperands() != C->getNumOperands()) {
520        valueNumbering.insert(std::make_pair(V, nextValueNumber));
521        return nextValueNumber++;
522      }
523      for (unsigned i = 1; i < C->getNumOperands(); ++i) {
524        uint32_t c_vn = lookup_or_add(C->getOperand(i));
525        uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
526        if (c_vn != cd_vn) {
527          valueNumbering.insert(std::make_pair(V, nextValueNumber));
528          return nextValueNumber++;
529        }
530      }
531
532      uint32_t v = lookup_or_add(cdep);
533      valueNumbering.insert(std::make_pair(V, v));
534      return v;
535
536    } else {
537      valueNumbering.insert(std::make_pair(V, nextValueNumber));
538      return nextValueNumber++;
539    }
540  } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
541    Expression e = create_expression(BO);
542
543    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
544    if (EI != expressionNumbering.end()) {
545      valueNumbering.insert(std::make_pair(V, EI->second));
546      return EI->second;
547    } else {
548      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
549      valueNumbering.insert(std::make_pair(V, nextValueNumber));
550
551      return nextValueNumber++;
552    }
553  } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
554    Expression e = create_expression(C);
555
556    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
557    if (EI != expressionNumbering.end()) {
558      valueNumbering.insert(std::make_pair(V, EI->second));
559      return EI->second;
560    } else {
561      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
562      valueNumbering.insert(std::make_pair(V, nextValueNumber));
563
564      return nextValueNumber++;
565    }
566  } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
567    Expression e = create_expression(U);
568
569    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
570    if (EI != expressionNumbering.end()) {
571      valueNumbering.insert(std::make_pair(V, EI->second));
572      return EI->second;
573    } else {
574      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
575      valueNumbering.insert(std::make_pair(V, nextValueNumber));
576
577      return nextValueNumber++;
578    }
579  } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
580    Expression e = create_expression(U);
581
582    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
583    if (EI != expressionNumbering.end()) {
584      valueNumbering.insert(std::make_pair(V, EI->second));
585      return EI->second;
586    } else {
587      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
588      valueNumbering.insert(std::make_pair(V, nextValueNumber));
589
590      return nextValueNumber++;
591    }
592  } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
593    Expression e = create_expression(U);
594
595    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
596    if (EI != expressionNumbering.end()) {
597      valueNumbering.insert(std::make_pair(V, EI->second));
598      return EI->second;
599    } else {
600      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
601      valueNumbering.insert(std::make_pair(V, nextValueNumber));
602
603      return nextValueNumber++;
604    }
605  } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
606    Expression e = create_expression(U);
607
608    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
609    if (EI != expressionNumbering.end()) {
610      valueNumbering.insert(std::make_pair(V, EI->second));
611      return EI->second;
612    } else {
613      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
614      valueNumbering.insert(std::make_pair(V, nextValueNumber));
615
616      return nextValueNumber++;
617    }
618  } else if (CastInst* U = dyn_cast<CastInst>(V)) {
619    Expression e = create_expression(U);
620
621    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
622    if (EI != expressionNumbering.end()) {
623      valueNumbering.insert(std::make_pair(V, EI->second));
624      return EI->second;
625    } else {
626      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
627      valueNumbering.insert(std::make_pair(V, nextValueNumber));
628
629      return nextValueNumber++;
630    }
631  } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
632    Expression e = create_expression(U);
633
634    DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
635    if (EI != expressionNumbering.end()) {
636      valueNumbering.insert(std::make_pair(V, EI->second));
637      return EI->second;
638    } else {
639      expressionNumbering.insert(std::make_pair(e, nextValueNumber));
640      valueNumbering.insert(std::make_pair(V, nextValueNumber));
641
642      return nextValueNumber++;
643    }
644  } else {
645    valueNumbering.insert(std::make_pair(V, nextValueNumber));
646    return nextValueNumber++;
647  }
648}
649
650/// lookup - Returns the value number of the specified value. Fails if
651/// the value has not yet been numbered.
652uint32_t ValueTable::lookup(Value *V) const {
653  DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
654  assert(VI != valueNumbering.end() && "Value not numbered?");
655  return VI->second;
656}
657
658/// clear - Remove all entries from the ValueTable
659void ValueTable::clear() {
660  valueNumbering.clear();
661  expressionNumbering.clear();
662  nextValueNumber = 1;
663}
664
665/// erase - Remove a value from the value numbering
666void ValueTable::erase(Value *V) {
667  valueNumbering.erase(V);
668}
669
670/// verifyRemoved - Verify that the value is removed from all internal data
671/// structures.
672void ValueTable::verifyRemoved(const Value *V) const {
673  for (DenseMap<Value*, uint32_t>::iterator
674         I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
675    assert(I->first != V && "Inst still occurs in value numbering map!");
676  }
677}
678
679//===----------------------------------------------------------------------===//
680//                                GVN Pass
681//===----------------------------------------------------------------------===//
682
683namespace {
684  struct ValueNumberScope {
685    ValueNumberScope* parent;
686    DenseMap<uint32_t, Value*> table;
687
688    ValueNumberScope(ValueNumberScope* p) : parent(p) { }
689  };
690}
691
692namespace {
693
694  class GVN : public FunctionPass {
695    bool runOnFunction(Function &F);
696  public:
697    static char ID; // Pass identification, replacement for typeid
698    GVN() : FunctionPass(&ID) { }
699
700  private:
701    MemoryDependenceAnalysis *MD;
702    DominatorTree *DT;
703
704    ValueTable VN;
705    DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
706
707    typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
708    PhiMapType phiMap;
709
710
711    // This transformation requires dominator postdominator info
712    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
713      AU.addRequired<DominatorTree>();
714      AU.addRequired<MemoryDependenceAnalysis>();
715      AU.addRequired<AliasAnalysis>();
716
717      AU.addPreserved<DominatorTree>();
718      AU.addPreserved<AliasAnalysis>();
719    }
720
721    // Helper fuctions
722    // FIXME: eliminate or document these better
723    bool processLoad(LoadInst* L,
724                     SmallVectorImpl<Instruction*> &toErase);
725    bool processInstruction(Instruction *I,
726                            SmallVectorImpl<Instruction*> &toErase);
727    bool processNonLocalLoad(LoadInst* L,
728                             SmallVectorImpl<Instruction*> &toErase);
729    bool processBlock(BasicBlock *BB);
730    Value *GetValueForBlock(BasicBlock *BB, Instruction *orig,
731                            DenseMap<BasicBlock*, Value*> &Phis,
732                            bool top_level = false);
733    void dump(DenseMap<uint32_t, Value*>& d);
734    bool iterateOnFunction(Function &F);
735    Value *CollapsePhi(PHINode* p);
736    bool performPRE(Function& F);
737    Value *lookupNumber(BasicBlock *BB, uint32_t num);
738    void cleanupGlobalSets();
739    void verifyRemoved(const Instruction *I) const;
740  };
741
742  char GVN::ID = 0;
743}
744
745// createGVNPass - The public interface to this file...
746FunctionPass *llvm::createGVNPass() { return new GVN(); }
747
748static RegisterPass<GVN> X("gvn",
749                           "Global Value Numbering");
750
751void GVN::dump(DenseMap<uint32_t, Value*>& d) {
752  printf("{\n");
753  for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
754       E = d.end(); I != E; ++I) {
755      printf("%d\n", I->first);
756      I->second->dump();
757  }
758  printf("}\n");
759}
760
761static bool isSafeReplacement(PHINode* p, Instruction *inst) {
762  if (!isa<PHINode>(inst))
763    return true;
764
765  for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
766       UI != E; ++UI)
767    if (PHINode* use_phi = dyn_cast<PHINode>(UI))
768      if (use_phi->getParent() == inst->getParent())
769        return false;
770
771  return true;
772}
773
774Value *GVN::CollapsePhi(PHINode *PN) {
775  Value *ConstVal = PN->hasConstantValue(DT);
776  if (!ConstVal) return 0;
777
778  Instruction *Inst = dyn_cast<Instruction>(ConstVal);
779  if (!Inst)
780    return ConstVal;
781
782  if (DT->dominates(Inst, PN))
783    if (isSafeReplacement(PN, Inst))
784      return Inst;
785  return 0;
786}
787
788/// GetValueForBlock - Get the value to use within the specified basic block.
789/// available values are in Phis.
790Value *GVN::GetValueForBlock(BasicBlock *BB, Instruction *Orig,
791                             DenseMap<BasicBlock*, Value*> &Phis,
792                             bool TopLevel) {
793
794  // If we have already computed this value, return the previously computed val.
795  DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
796  if (V != Phis.end() && !TopLevel) return V->second;
797
798  // If the block is unreachable, just return undef, since this path
799  // can't actually occur at runtime.
800  if (!DT->isReachableFromEntry(BB))
801    return Phis[BB] = UndefValue::get(Orig->getType());
802
803  if (BasicBlock *Pred = BB->getSinglePredecessor()) {
804    Value *ret = GetValueForBlock(Pred, Orig, Phis);
805    Phis[BB] = ret;
806    return ret;
807  }
808
809  // Get the number of predecessors of this block so we can reserve space later.
810  // If there is already a PHI in it, use the #preds from it, otherwise count.
811  // Getting it from the PHI is constant time.
812  unsigned NumPreds;
813  if (PHINode *ExistingPN = dyn_cast<PHINode>(BB->begin()))
814    NumPreds = ExistingPN->getNumIncomingValues();
815  else
816    NumPreds = std::distance(pred_begin(BB), pred_end(BB));
817
818  // Otherwise, we may need to insert a PHI node.  Do so now, then get values to
819  // fill in the incoming values for the PHI.  If the PHI ends up not being
820  // needed, we can always remove it later.
821  PHINode *PN = PHINode::Create(Orig->getType(), Orig->getName()+".rle",
822                                BB->begin());
823  PN->reserveOperandSpace(NumPreds);
824
825  Phis.insert(std::make_pair(BB, PN));
826
827  // Fill in the incoming values for the block.
828  for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
829    Value *val = GetValueForBlock(*PI, Orig, Phis);
830    PN->addIncoming(val, *PI);
831  }
832
833  VN.getAliasAnalysis()->copyValue(Orig, PN);
834
835  // Attempt to collapse PHI nodes that are trivially redundant.  This happens
836  // when we construct a PHI that ends up not being needed.
837  Value *v = CollapsePhi(PN);
838  if (!v) {
839    // Cache our phi construction results
840    if (LoadInst* L = dyn_cast<LoadInst>(Orig))
841      phiMap[L->getPointerOperand()].insert(PN);
842    else
843      phiMap[Orig].insert(PN);
844
845    return PN;
846  }
847
848  PN->replaceAllUsesWith(v);
849  if (isa<PointerType>(v->getType()))
850    MD->invalidateCachedPointerInfo(v);
851
852  for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
853       E = Phis.end(); I != E; ++I)
854    if (I->second == PN)
855      I->second = v;
856
857  DEBUG(errs() << "GVN removed: " << *PN << '\n');
858  MD->removeInstruction(PN);
859  PN->eraseFromParent();
860  DEBUG(verifyRemoved(PN));
861
862  Phis[BB] = v;
863  return v;
864}
865
866/// IsValueFullyAvailableInBlock - Return true if we can prove that the value
867/// we're analyzing is fully available in the specified block.  As we go, keep
868/// track of which blocks we know are fully alive in FullyAvailableBlocks.  This
869/// map is actually a tri-state map with the following values:
870///   0) we know the block *is not* fully available.
871///   1) we know the block *is* fully available.
872///   2) we do not know whether the block is fully available or not, but we are
873///      currently speculating that it will be.
874///   3) we are speculating for this block and have used that to speculate for
875///      other blocks.
876static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
877                            DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
878  // Optimistically assume that the block is fully available and check to see
879  // if we already know about this block in one lookup.
880  std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
881    FullyAvailableBlocks.insert(std::make_pair(BB, 2));
882
883  // If the entry already existed for this block, return the precomputed value.
884  if (!IV.second) {
885    // If this is a speculative "available" value, mark it as being used for
886    // speculation of other blocks.
887    if (IV.first->second == 2)
888      IV.first->second = 3;
889    return IV.first->second != 0;
890  }
891
892  // Otherwise, see if it is fully available in all predecessors.
893  pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
894
895  // If this block has no predecessors, it isn't live-in here.
896  if (PI == PE)
897    goto SpeculationFailure;
898
899  for (; PI != PE; ++PI)
900    // If the value isn't fully available in one of our predecessors, then it
901    // isn't fully available in this block either.  Undo our previous
902    // optimistic assumption and bail out.
903    if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
904      goto SpeculationFailure;
905
906  return true;
907
908// SpeculationFailure - If we get here, we found out that this is not, after
909// all, a fully-available block.  We have a problem if we speculated on this and
910// used the speculation to mark other blocks as available.
911SpeculationFailure:
912  char &BBVal = FullyAvailableBlocks[BB];
913
914  // If we didn't speculate on this, just return with it set to false.
915  if (BBVal == 2) {
916    BBVal = 0;
917    return false;
918  }
919
920  // If we did speculate on this value, we could have blocks set to 1 that are
921  // incorrect.  Walk the (transitive) successors of this block and mark them as
922  // 0 if set to one.
923  SmallVector<BasicBlock*, 32> BBWorklist;
924  BBWorklist.push_back(BB);
925
926  while (!BBWorklist.empty()) {
927    BasicBlock *Entry = BBWorklist.pop_back_val();
928    // Note that this sets blocks to 0 (unavailable) if they happen to not
929    // already be in FullyAvailableBlocks.  This is safe.
930    char &EntryVal = FullyAvailableBlocks[Entry];
931    if (EntryVal == 0) continue;  // Already unavailable.
932
933    // Mark as unavailable.
934    EntryVal = 0;
935
936    for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
937      BBWorklist.push_back(*I);
938  }
939
940  return false;
941}
942
943
944/// CanCoerceMustAliasedValueToLoad - Return true if
945/// CoerceAvailableValueToLoadType will succeed.
946static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
947                                            const Type *LoadTy,
948                                            const TargetData &TD) {
949  // If the loaded or stored value is an first class array or struct, don't try
950  // to transform them.  We need to be able to bitcast to integer.
951  if (isa<StructType>(LoadTy) || isa<ArrayType>(LoadTy) ||
952      isa<StructType>(StoredVal->getType()) ||
953      isa<ArrayType>(StoredVal->getType()))
954    return false;
955
956  // The store has to be at least as big as the load.
957  if (TD.getTypeSizeInBits(StoredVal->getType()) <
958        TD.getTypeSizeInBits(LoadTy))
959    return false;
960
961  return true;
962}
963
964
965/// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
966/// then a load from a must-aliased pointer of a different type, try to coerce
967/// the stored value.  LoadedTy is the type of the load we want to replace and
968/// InsertPt is the place to insert new instructions.
969///
970/// If we can't do it, return null.
971static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
972                                             const Type *LoadedTy,
973                                             Instruction *InsertPt,
974                                             const TargetData &TD) {
975  if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
976    return 0;
977
978  const Type *StoredValTy = StoredVal->getType();
979
980  uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
981  uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
982
983  // If the store and reload are the same size, we can always reuse it.
984  if (StoreSize == LoadSize) {
985    if (isa<PointerType>(StoredValTy) && isa<PointerType>(LoadedTy)) {
986      // Pointer to Pointer -> use bitcast.
987      return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
988    }
989
990    // Convert source pointers to integers, which can be bitcast.
991    if (isa<PointerType>(StoredValTy)) {
992      StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
993      StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
994    }
995
996    const Type *TypeToCastTo = LoadedTy;
997    if (isa<PointerType>(TypeToCastTo))
998      TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
999
1000    if (StoredValTy != TypeToCastTo)
1001      StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
1002
1003    // Cast to pointer if the load needs a pointer type.
1004    if (isa<PointerType>(LoadedTy))
1005      StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
1006
1007    return StoredVal;
1008  }
1009
1010  // If the loaded value is smaller than the available value, then we can
1011  // extract out a piece from it.  If the available value is too small, then we
1012  // can't do anything.
1013  assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
1014
1015  // Convert source pointers to integers, which can be manipulated.
1016  if (isa<PointerType>(StoredValTy)) {
1017    StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
1018    StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
1019  }
1020
1021  // Convert vectors and fp to integer, which can be manipulated.
1022  if (!isa<IntegerType>(StoredValTy)) {
1023    StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
1024    StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
1025  }
1026
1027  // If this is a big-endian system, we need to shift the value down to the low
1028  // bits so that a truncate will work.
1029  if (TD.isBigEndian()) {
1030    Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
1031    StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
1032  }
1033
1034  // Truncate the integer to the right size now.
1035  const Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
1036  StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
1037
1038  if (LoadedTy == NewIntTy)
1039    return StoredVal;
1040
1041  // If the result is a pointer, inttoptr.
1042  if (isa<PointerType>(LoadedTy))
1043    return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
1044
1045  // Otherwise, bitcast.
1046  return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
1047}
1048
1049/// GetBaseWithConstantOffset - Analyze the specified pointer to see if it can
1050/// be expressed as a base pointer plus a constant offset.  Return the base and
1051/// offset to the caller.
1052static Value *GetBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1053                                        const TargetData &TD) {
1054  Operator *PtrOp = dyn_cast<Operator>(Ptr);
1055  if (PtrOp == 0) return Ptr;
1056
1057  // Just look through bitcasts.
1058  if (PtrOp->getOpcode() == Instruction::BitCast)
1059    return GetBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1060
1061  // If this is a GEP with constant indices, we can look through it.
1062  GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1063  if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1064
1065  gep_type_iterator GTI = gep_type_begin(GEP);
1066  for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1067       ++I, ++GTI) {
1068    ConstantInt *OpC = cast<ConstantInt>(*I);
1069    if (OpC->isZero()) continue;
1070
1071    // Handle a struct and array indices which add their offset to the pointer.
1072    if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1073      Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1074    } else {
1075      uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
1076      Offset += OpC->getSExtValue()*Size;
1077    }
1078  }
1079
1080  // Re-sign extend from the pointer size if needed to get overflow edge cases
1081  // right.
1082  unsigned PtrSize = TD.getPointerSizeInBits();
1083  if (PtrSize < 64)
1084    Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1085
1086  return GetBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1087}
1088
1089
1090/// AnalyzeLoadFromClobberingStore - This function is called when we have a
1091/// memdep query of a load that ends up being a clobbering store.  This means
1092/// that the store *may* provide bits used by the load but we can't be sure
1093/// because the pointers don't mustalias.  Check this case to see if there is
1094/// anything more we can do before we give up.  This returns -1 if we have to
1095/// give up, or a byte number in the stored value of the piece that feeds the
1096/// load.
1097static int AnalyzeLoadFromClobberingStore(LoadInst *L, StoreInst *DepSI,
1098                                          const TargetData &TD) {
1099  // If the loaded or stored value is an first class array or struct, don't try
1100  // to transform them.  We need to be able to bitcast to integer.
1101  if (isa<StructType>(L->getType()) || isa<ArrayType>(L->getType()) ||
1102      isa<StructType>(DepSI->getOperand(0)->getType()) ||
1103      isa<ArrayType>(DepSI->getOperand(0)->getType()))
1104    return -1;
1105
1106  int64_t StoreOffset = 0, LoadOffset = 0;
1107  Value *StoreBase =
1108    GetBaseWithConstantOffset(DepSI->getPointerOperand(), StoreOffset, TD);
1109  Value *LoadBase =
1110    GetBaseWithConstantOffset(L->getPointerOperand(), LoadOffset, TD);
1111  if (StoreBase != LoadBase)
1112    return -1;
1113
1114  // If the load and store are to the exact same address, they should have been
1115  // a must alias.  AA must have gotten confused.
1116  // FIXME: Study to see if/when this happens.
1117  if (LoadOffset == StoreOffset) {
1118#if 0
1119    errs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
1120    << "Base       = " << *StoreBase << "\n"
1121    << "Store Ptr  = " << *DepSI->getPointerOperand() << "\n"
1122    << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1123    << "Load Ptr   = " << *L->getPointerOperand() << "\n"
1124    << "Load Offs  = " << LoadOffset << " - " << *L << "\n\n";
1125    errs() << "'" << L->getParent()->getParent()->getName() << "'"
1126    << *L->getParent();
1127#endif
1128    return -1;
1129  }
1130
1131  // If the load and store don't overlap at all, the store doesn't provide
1132  // anything to the load.  In this case, they really don't alias at all, AA
1133  // must have gotten confused.
1134  // FIXME: Investigate cases where this bails out, e.g. rdar://7238614. Then
1135  // remove this check, as it is duplicated with what we have below.
1136  uint64_t StoreSize = TD.getTypeSizeInBits(DepSI->getOperand(0)->getType());
1137  uint64_t LoadSize = TD.getTypeSizeInBits(L->getType());
1138
1139  if ((StoreSize & 7) | (LoadSize & 7))
1140    return -1;
1141  StoreSize >>= 3;  // Convert to bytes.
1142  LoadSize >>= 3;
1143
1144
1145  bool isAAFailure = false;
1146  if (StoreOffset < LoadOffset) {
1147    isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
1148  } else {
1149    isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
1150  }
1151  if (isAAFailure) {
1152#if 0
1153    errs() << "STORE LOAD DEP WITH COMMON BASE:\n"
1154    << "Base       = " << *StoreBase << "\n"
1155    << "Store Ptr  = " << *DepSI->getPointerOperand() << "\n"
1156    << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1157    << "Load Ptr   = " << *L->getPointerOperand() << "\n"
1158    << "Load Offs  = " << LoadOffset << " - " << *L << "\n\n";
1159    errs() << "'" << L->getParent()->getParent()->getName() << "'"
1160    << *L->getParent();
1161#endif
1162    return -1;
1163  }
1164
1165  // If the Load isn't completely contained within the stored bits, we don't
1166  // have all the bits to feed it.  We could do something crazy in the future
1167  // (issue a smaller load then merge the bits in) but this seems unlikely to be
1168  // valuable.
1169  if (StoreOffset > LoadOffset ||
1170      StoreOffset+StoreSize < LoadOffset+LoadSize)
1171    return -1;
1172
1173  // Okay, we can do this transformation.  Return the number of bytes into the
1174  // store that the load is.
1175  return LoadOffset-StoreOffset;
1176}
1177
1178
1179/// GetStoreValueForLoad - This function is called when we have a
1180/// memdep query of a load that ends up being a clobbering store.  This means
1181/// that the store *may* provide bits used by the load but we can't be sure
1182/// because the pointers don't mustalias.  Check this case to see if there is
1183/// anything more we can do before we give up.
1184static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
1185                                   const Type *LoadTy,
1186                                   Instruction *InsertPt, const TargetData &TD){
1187  LLVMContext &Ctx = SrcVal->getType()->getContext();
1188
1189  uint64_t StoreSize = TD.getTypeSizeInBits(SrcVal->getType())/8;
1190  uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
1191
1192
1193  // Compute which bits of the stored value are being used by the load.  Convert
1194  // to an integer type to start with.
1195  if (isa<PointerType>(SrcVal->getType()))
1196    SrcVal = new PtrToIntInst(SrcVal, TD.getIntPtrType(Ctx), "tmp", InsertPt);
1197  if (!isa<IntegerType>(SrcVal->getType()))
1198    SrcVal = new BitCastInst(SrcVal, IntegerType::get(Ctx, StoreSize*8),
1199                             "tmp", InsertPt);
1200
1201  // Shift the bits to the least significant depending on endianness.
1202  unsigned ShiftAmt;
1203  if (TD.isLittleEndian()) {
1204    ShiftAmt = Offset*8;
1205  } else {
1206    ShiftAmt = (StoreSize-LoadSize-Offset)*8;
1207  }
1208
1209  if (ShiftAmt)
1210    SrcVal = BinaryOperator::CreateLShr(SrcVal,
1211                ConstantInt::get(SrcVal->getType(), ShiftAmt), "tmp", InsertPt);
1212
1213  if (LoadSize != StoreSize)
1214    SrcVal = new TruncInst(SrcVal, IntegerType::get(Ctx, LoadSize*8),
1215                           "tmp", InsertPt);
1216
1217  return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
1218}
1219
1220struct AvailableValueInBlock {
1221  /// BB - The basic block in question.
1222  BasicBlock *BB;
1223  /// V - The value that is live out of the block.
1224  Value *V;
1225  /// Offset - The byte offset in V that is interesting for the load query.
1226  unsigned Offset;
1227
1228  static AvailableValueInBlock get(BasicBlock *BB, Value *V,
1229                                   unsigned Offset = 0) {
1230    AvailableValueInBlock Res;
1231    Res.BB = BB;
1232    Res.V = V;
1233    Res.Offset = Offset;
1234    return Res;
1235  }
1236};
1237
1238/// GetAvailableBlockValues - Given the ValuesPerBlock list, convert all of the
1239/// available values to values of the expected LoadTy in their blocks and insert
1240/// the new values into BlockReplValues.
1241static void
1242GetAvailableBlockValues(DenseMap<BasicBlock*, Value*> &BlockReplValues,
1243                  const SmallVector<AvailableValueInBlock, 16> &ValuesPerBlock,
1244                        const Type *LoadTy,
1245                        const TargetData *TD) {
1246
1247  for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1248    BasicBlock *BB = ValuesPerBlock[i].BB;
1249    Value *AvailableVal = ValuesPerBlock[i].V;
1250    unsigned Offset = ValuesPerBlock[i].Offset;
1251
1252    Value *&BlockEntry = BlockReplValues[BB];
1253    if (BlockEntry) continue;
1254
1255    if (AvailableVal->getType() != LoadTy) {
1256      assert(TD && "Need target data to handle type mismatch case");
1257      AvailableVal = GetStoreValueForLoad(AvailableVal, Offset, LoadTy,
1258                                          BB->getTerminator(), *TD);
1259
1260      if (Offset) {
1261        DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
1262            << *ValuesPerBlock[i].V << '\n'
1263            << *AvailableVal << '\n' << "\n\n\n");
1264      }
1265
1266
1267      DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
1268                   << *ValuesPerBlock[i].V << '\n'
1269                   << *AvailableVal << '\n' << "\n\n\n");
1270    }
1271    BlockEntry = AvailableVal;
1272  }
1273}
1274
1275/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1276/// non-local by performing PHI construction.
1277bool GVN::processNonLocalLoad(LoadInst *LI,
1278                              SmallVectorImpl<Instruction*> &toErase) {
1279  // Find the non-local dependencies of the load.
1280  SmallVector<MemoryDependenceAnalysis::NonLocalDepEntry, 64> Deps;
1281  MD->getNonLocalPointerDependency(LI->getOperand(0), true, LI->getParent(),
1282                                   Deps);
1283  //DEBUG(errs() << "INVESTIGATING NONLOCAL LOAD: "
1284  //             << Deps.size() << *LI << '\n');
1285
1286  // If we had to process more than one hundred blocks to find the
1287  // dependencies, this load isn't worth worrying about.  Optimizing
1288  // it will be too expensive.
1289  if (Deps.size() > 100)
1290    return false;
1291
1292  // If we had a phi translation failure, we'll have a single entry which is a
1293  // clobber in the current block.  Reject this early.
1294  if (Deps.size() == 1 && Deps[0].second.isClobber()) {
1295    DEBUG(
1296      errs() << "GVN: non-local load ";
1297      WriteAsOperand(errs(), LI);
1298      errs() << " is clobbered by " << *Deps[0].second.getInst() << '\n';
1299    );
1300    return false;
1301  }
1302
1303  // Filter out useless results (non-locals, etc).  Keep track of the blocks
1304  // where we have a value available in repl, also keep track of whether we see
1305  // dependencies that produce an unknown value for the load (such as a call
1306  // that could potentially clobber the load).
1307  SmallVector<AvailableValueInBlock, 16> ValuesPerBlock;
1308  SmallVector<BasicBlock*, 16> UnavailableBlocks;
1309
1310  const TargetData *TD = 0;
1311
1312  for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
1313    BasicBlock *DepBB = Deps[i].first;
1314    MemDepResult DepInfo = Deps[i].second;
1315
1316    if (DepInfo.isClobber()) {
1317      // If the dependence is to a store that writes to a superset of the bits
1318      // read by the load, we can extract the bits we need for the load from the
1319      // stored value.
1320      if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1321        if (TD == 0)
1322          TD = getAnalysisIfAvailable<TargetData>();
1323        if (TD) {
1324          int Offset = AnalyzeLoadFromClobberingStore(LI, DepSI, *TD);
1325          if (Offset != -1) {
1326            ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1327                                                           DepSI->getOperand(0),
1328                                                                Offset));
1329            continue;
1330          }
1331        }
1332      }
1333
1334      // FIXME: Handle memset/memcpy.
1335      UnavailableBlocks.push_back(DepBB);
1336      continue;
1337    }
1338
1339    Instruction *DepInst = DepInfo.getInst();
1340
1341    // Loading the allocation -> undef.
1342    if (isa<AllocationInst>(DepInst) || isMalloc(DepInst)) {
1343      ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1344                                             UndefValue::get(LI->getType())));
1345      continue;
1346    }
1347
1348    if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
1349      // Reject loads and stores that are to the same address but are of
1350      // different types if we have to.
1351      if (S->getOperand(0)->getType() != LI->getType()) {
1352        if (TD == 0)
1353          TD = getAnalysisIfAvailable<TargetData>();
1354
1355        // If the stored value is larger or equal to the loaded value, we can
1356        // reuse it.
1357        if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getOperand(0),
1358                                                        LI->getType(), *TD)) {
1359          UnavailableBlocks.push_back(DepBB);
1360          continue;
1361        }
1362      }
1363
1364      ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1365                                                          S->getOperand(0)));
1366      continue;
1367    }
1368
1369    if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
1370      // If the types mismatch and we can't handle it, reject reuse of the load.
1371      if (LD->getType() != LI->getType()) {
1372        if (TD == 0)
1373          TD = getAnalysisIfAvailable<TargetData>();
1374
1375        // If the stored value is larger or equal to the loaded value, we can
1376        // reuse it.
1377        if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
1378          UnavailableBlocks.push_back(DepBB);
1379          continue;
1380        }
1381      }
1382      ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB, LD));
1383      continue;
1384    }
1385
1386    UnavailableBlocks.push_back(DepBB);
1387    continue;
1388  }
1389
1390  // If we have no predecessors that produce a known value for this load, exit
1391  // early.
1392  if (ValuesPerBlock.empty()) return false;
1393
1394  // If all of the instructions we depend on produce a known value for this
1395  // load, then it is fully redundant and we can use PHI insertion to compute
1396  // its value.  Insert PHIs and remove the fully redundant value now.
1397  if (UnavailableBlocks.empty()) {
1398    // Use cached PHI construction information from previous runs
1399    SmallPtrSet<Instruction*, 4> &p = phiMap[LI->getPointerOperand()];
1400    // FIXME: What does phiMap do? Are we positive it isn't getting invalidated?
1401    for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
1402         I != E; ++I) {
1403      if ((*I)->getParent() == LI->getParent()) {
1404        DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD #1: " << *LI << '\n');
1405        LI->replaceAllUsesWith(*I);
1406        if (isa<PointerType>((*I)->getType()))
1407          MD->invalidateCachedPointerInfo(*I);
1408        toErase.push_back(LI);
1409        NumGVNLoad++;
1410        return true;
1411      }
1412
1413      ValuesPerBlock.push_back(AvailableValueInBlock::get((*I)->getParent(),
1414                                                          *I));
1415    }
1416
1417    DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1418
1419    // Convert the block information to a map, and insert coersions as needed.
1420    DenseMap<BasicBlock*, Value*> BlockReplValues;
1421    GetAvailableBlockValues(BlockReplValues, ValuesPerBlock, LI->getType(), TD);
1422
1423    // Perform PHI construction.
1424    Value *V = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true);
1425    LI->replaceAllUsesWith(V);
1426
1427    if (isa<PHINode>(V))
1428      V->takeName(LI);
1429    if (isa<PointerType>(V->getType()))
1430      MD->invalidateCachedPointerInfo(V);
1431    toErase.push_back(LI);
1432    NumGVNLoad++;
1433    return true;
1434  }
1435
1436  if (!EnablePRE || !EnableLoadPRE)
1437    return false;
1438
1439  // Okay, we have *some* definitions of the value.  This means that the value
1440  // is available in some of our (transitive) predecessors.  Lets think about
1441  // doing PRE of this load.  This will involve inserting a new load into the
1442  // predecessor when it's not available.  We could do this in general, but
1443  // prefer to not increase code size.  As such, we only do this when we know
1444  // that we only have to insert *one* load (which means we're basically moving
1445  // the load, not inserting a new one).
1446
1447  SmallPtrSet<BasicBlock *, 4> Blockers;
1448  for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1449    Blockers.insert(UnavailableBlocks[i]);
1450
1451  // Lets find first basic block with more than one predecessor.  Walk backwards
1452  // through predecessors if needed.
1453  BasicBlock *LoadBB = LI->getParent();
1454  BasicBlock *TmpBB = LoadBB;
1455
1456  bool isSinglePred = false;
1457  bool allSingleSucc = true;
1458  while (TmpBB->getSinglePredecessor()) {
1459    isSinglePred = true;
1460    TmpBB = TmpBB->getSinglePredecessor();
1461    if (!TmpBB) // If haven't found any, bail now.
1462      return false;
1463    if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1464      return false;
1465    if (Blockers.count(TmpBB))
1466      return false;
1467    if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1468      allSingleSucc = false;
1469  }
1470
1471  assert(TmpBB);
1472  LoadBB = TmpBB;
1473
1474  // If we have a repl set with LI itself in it, this means we have a loop where
1475  // at least one of the values is LI.  Since this means that we won't be able
1476  // to eliminate LI even if we insert uses in the other predecessors, we will
1477  // end up increasing code size.  Reject this by scanning for LI.
1478  for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1479    if (ValuesPerBlock[i].V == LI)
1480      return false;
1481
1482  if (isSinglePred) {
1483    bool isHot = false;
1484    for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1485      if (Instruction *I = dyn_cast<Instruction>(ValuesPerBlock[i].V))
1486        // "Hot" Instruction is in some loop (because it dominates its dep.
1487        // instruction).
1488        if (DT->dominates(LI, I)) {
1489          isHot = true;
1490          break;
1491        }
1492
1493    // We are interested only in "hot" instructions. We don't want to do any
1494    // mis-optimizations here.
1495    if (!isHot)
1496      return false;
1497  }
1498
1499  // Okay, we have some hope :).  Check to see if the loaded value is fully
1500  // available in all but one predecessor.
1501  // FIXME: If we could restructure the CFG, we could make a common pred with
1502  // all the preds that don't have an available LI and insert a new load into
1503  // that one block.
1504  BasicBlock *UnavailablePred = 0;
1505
1506  DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1507  for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1508    FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
1509  for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1510    FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1511
1512  for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1513       PI != E; ++PI) {
1514    if (IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
1515      continue;
1516
1517    // If this load is not available in multiple predecessors, reject it.
1518    if (UnavailablePred && UnavailablePred != *PI)
1519      return false;
1520    UnavailablePred = *PI;
1521  }
1522
1523  assert(UnavailablePred != 0 &&
1524         "Fully available value should be eliminated above!");
1525
1526  // If the loaded pointer is PHI node defined in this block, do PHI translation
1527  // to get its value in the predecessor.
1528  Value *LoadPtr = LI->getOperand(0)->DoPHITranslation(LoadBB, UnavailablePred);
1529
1530  // Make sure the value is live in the predecessor.  If it was defined by a
1531  // non-PHI instruction in this block, we don't know how to recompute it above.
1532  if (Instruction *LPInst = dyn_cast<Instruction>(LoadPtr))
1533    if (!DT->dominates(LPInst->getParent(), UnavailablePred)) {
1534      DEBUG(errs() << "COULDN'T PRE LOAD BECAUSE PTR IS UNAVAILABLE IN PRED: "
1535                   << *LPInst << '\n' << *LI << "\n");
1536      return false;
1537    }
1538
1539  // We don't currently handle critical edges :(
1540  if (UnavailablePred->getTerminator()->getNumSuccessors() != 1) {
1541    DEBUG(errs() << "COULD NOT PRE LOAD BECAUSE OF CRITICAL EDGE '"
1542                 << UnavailablePred->getName() << "': " << *LI << '\n');
1543    return false;
1544  }
1545
1546  // Make sure it is valid to move this load here.  We have to watch out for:
1547  //  @1 = getelementptr (i8* p, ...
1548  //  test p and branch if == 0
1549  //  load @1
1550  // It is valid to have the getelementptr before the test, even if p can be 0,
1551  // as getelementptr only does address arithmetic.
1552  // If we are not pushing the value through any multiple-successor blocks
1553  // we do not have this case.  Otherwise, check that the load is safe to
1554  // put anywhere; this can be improved, but should be conservatively safe.
1555  if (!allSingleSucc &&
1556      !isSafeToLoadUnconditionally(LoadPtr, UnavailablePred->getTerminator()))
1557    return false;
1558
1559  // Okay, we can eliminate this load by inserting a reload in the predecessor
1560  // and using PHI construction to get the value in the other predecessors, do
1561  // it.
1562  DEBUG(errs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
1563
1564  Value *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1565                                LI->getAlignment(),
1566                                UnavailablePred->getTerminator());
1567
1568  SmallPtrSet<Instruction*, 4> &p = phiMap[LI->getPointerOperand()];
1569  for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
1570       I != E; ++I)
1571    ValuesPerBlock.push_back(AvailableValueInBlock::get((*I)->getParent(), *I));
1572
1573  DenseMap<BasicBlock*, Value*> BlockReplValues;
1574  GetAvailableBlockValues(BlockReplValues, ValuesPerBlock, LI->getType(), TD);
1575  BlockReplValues[UnavailablePred] = NewLoad;
1576
1577  // Perform PHI construction.
1578  Value *V = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true);
1579  LI->replaceAllUsesWith(V);
1580  if (isa<PHINode>(V))
1581    V->takeName(LI);
1582  if (isa<PointerType>(V->getType()))
1583    MD->invalidateCachedPointerInfo(V);
1584  toErase.push_back(LI);
1585  NumPRELoad++;
1586  return true;
1587}
1588
1589/// processLoad - Attempt to eliminate a load, first by eliminating it
1590/// locally, and then attempting non-local elimination if that fails.
1591bool GVN::processLoad(LoadInst *L, SmallVectorImpl<Instruction*> &toErase) {
1592  if (L->isVolatile())
1593    return false;
1594
1595  // ... to a pointer that has been loaded from before...
1596  MemDepResult Dep = MD->getDependency(L);
1597
1598  // If the value isn't available, don't do anything!
1599  if (Dep.isClobber()) {
1600    // FIXME: We should handle memset/memcpy/memmove as dependent instructions
1601    // to forward the value if available.
1602    //if (isa<MemIntrinsic>(Dep.getInst()))
1603    //errs() << "LOAD DEPENDS ON MEM: " << *L << "\n" << *Dep.getInst()<<"\n\n";
1604
1605    // Check to see if we have something like this:
1606    //   store i32 123, i32* %P
1607    //   %A = bitcast i32* %P to i8*
1608    //   %B = gep i8* %A, i32 1
1609    //   %C = load i8* %B
1610    //
1611    // We could do that by recognizing if the clobber instructions are obviously
1612    // a common base + constant offset, and if the previous store (or memset)
1613    // completely covers this load.  This sort of thing can happen in bitfield
1614    // access code.
1615    if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst()))
1616      if (const TargetData *TD = getAnalysisIfAvailable<TargetData>()) {
1617        int Offset = AnalyzeLoadFromClobberingStore(L, DepSI, *TD);
1618        if (Offset != -1) {
1619          Value *AvailVal = GetStoreValueForLoad(DepSI->getOperand(0), Offset,
1620                                                 L->getType(), L, *TD);
1621          DEBUG(errs() << "GVN COERCED STORE BITS:\n" << *DepSI << '\n'
1622                       << *AvailVal << '\n' << *L << "\n\n\n");
1623
1624          // Replace the load!
1625          L->replaceAllUsesWith(AvailVal);
1626          if (isa<PointerType>(AvailVal->getType()))
1627            MD->invalidateCachedPointerInfo(AvailVal);
1628          toErase.push_back(L);
1629          NumGVNLoad++;
1630          return true;
1631        }
1632      }
1633
1634    DEBUG(
1635      // fast print dep, using operator<< on instruction would be too slow
1636      errs() << "GVN: load ";
1637      WriteAsOperand(errs(), L);
1638      Instruction *I = Dep.getInst();
1639      errs() << " is clobbered by " << *I << '\n';
1640    );
1641    return false;
1642  }
1643
1644  // If it is defined in another block, try harder.
1645  if (Dep.isNonLocal())
1646    return processNonLocalLoad(L, toErase);
1647
1648  Instruction *DepInst = Dep.getInst();
1649  if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1650    Value *StoredVal = DepSI->getOperand(0);
1651
1652    // The store and load are to a must-aliased pointer, but they may not
1653    // actually have the same type.  See if we know how to reuse the stored
1654    // value (depending on its type).
1655    const TargetData *TD = 0;
1656    if (StoredVal->getType() != L->getType() &&
1657        (TD = getAnalysisIfAvailable<TargetData>())) {
1658      StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1659                                                 L, *TD);
1660      if (StoredVal == 0)
1661        return false;
1662
1663      DEBUG(errs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1664                   << '\n' << *L << "\n\n\n");
1665    }
1666
1667    // Remove it!
1668    L->replaceAllUsesWith(StoredVal);
1669    if (isa<PointerType>(StoredVal->getType()))
1670      MD->invalidateCachedPointerInfo(StoredVal);
1671    toErase.push_back(L);
1672    NumGVNLoad++;
1673    return true;
1674  }
1675
1676  if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1677    Value *AvailableVal = DepLI;
1678
1679    // The loads are of a must-aliased pointer, but they may not actually have
1680    // the same type.  See if we know how to reuse the previously loaded value
1681    // (depending on its type).
1682    const TargetData *TD = 0;
1683    if (DepLI->getType() != L->getType() &&
1684        (TD = getAnalysisIfAvailable<TargetData>())) {
1685      AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(), L,*TD);
1686      if (AvailableVal == 0)
1687        return false;
1688
1689      DEBUG(errs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1690                   << "\n" << *L << "\n\n\n");
1691    }
1692
1693    // Remove it!
1694    L->replaceAllUsesWith(AvailableVal);
1695    if (isa<PointerType>(DepLI->getType()))
1696      MD->invalidateCachedPointerInfo(DepLI);
1697    toErase.push_back(L);
1698    NumGVNLoad++;
1699    return true;
1700  }
1701
1702  // If this load really doesn't depend on anything, then we must be loading an
1703  // undef value.  This can happen when loading for a fresh allocation with no
1704  // intervening stores, for example.
1705  if (isa<AllocationInst>(DepInst) || isMalloc(DepInst)) {
1706    L->replaceAllUsesWith(UndefValue::get(L->getType()));
1707    toErase.push_back(L);
1708    NumGVNLoad++;
1709    return true;
1710  }
1711
1712  return false;
1713}
1714
1715Value *GVN::lookupNumber(BasicBlock *BB, uint32_t num) {
1716  DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1717  if (I == localAvail.end())
1718    return 0;
1719
1720  ValueNumberScope *Locals = I->second;
1721  while (Locals) {
1722    DenseMap<uint32_t, Value*>::iterator I = Locals->table.find(num);
1723    if (I != Locals->table.end())
1724      return I->second;
1725    Locals = Locals->parent;
1726  }
1727
1728  return 0;
1729}
1730
1731
1732/// processInstruction - When calculating availability, handle an instruction
1733/// by inserting it into the appropriate sets
1734bool GVN::processInstruction(Instruction *I,
1735                             SmallVectorImpl<Instruction*> &toErase) {
1736  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1737    bool Changed = processLoad(LI, toErase);
1738
1739    if (!Changed) {
1740      unsigned Num = VN.lookup_or_add(LI);
1741      localAvail[I->getParent()]->table.insert(std::make_pair(Num, LI));
1742    }
1743
1744    return Changed;
1745  }
1746
1747  uint32_t NextNum = VN.getNextUnusedValueNumber();
1748  unsigned Num = VN.lookup_or_add(I);
1749
1750  if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1751    localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
1752
1753    if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
1754      return false;
1755
1756    Value *BranchCond = BI->getCondition();
1757    uint32_t CondVN = VN.lookup_or_add(BranchCond);
1758
1759    BasicBlock *TrueSucc = BI->getSuccessor(0);
1760    BasicBlock *FalseSucc = BI->getSuccessor(1);
1761
1762    if (TrueSucc->getSinglePredecessor())
1763      localAvail[TrueSucc]->table[CondVN] =
1764        ConstantInt::getTrue(TrueSucc->getContext());
1765    if (FalseSucc->getSinglePredecessor())
1766      localAvail[FalseSucc]->table[CondVN] =
1767        ConstantInt::getFalse(TrueSucc->getContext());
1768
1769    return false;
1770
1771  // Allocations are always uniquely numbered, so we can save time and memory
1772  // by fast failing them.
1773  } else if (isa<AllocationInst>(I) || isa<TerminatorInst>(I)) {
1774    localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
1775    return false;
1776  }
1777
1778  // Collapse PHI nodes
1779  if (PHINode* p = dyn_cast<PHINode>(I)) {
1780    Value *constVal = CollapsePhi(p);
1781
1782    if (constVal) {
1783      for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1784           PI != PE; ++PI)
1785        PI->second.erase(p);
1786
1787      p->replaceAllUsesWith(constVal);
1788      if (isa<PointerType>(constVal->getType()))
1789        MD->invalidateCachedPointerInfo(constVal);
1790      VN.erase(p);
1791
1792      toErase.push_back(p);
1793    } else {
1794      localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
1795    }
1796
1797  // If the number we were assigned was a brand new VN, then we don't
1798  // need to do a lookup to see if the number already exists
1799  // somewhere in the domtree: it can't!
1800  } else if (Num == NextNum) {
1801    localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
1802
1803  // Perform fast-path value-number based elimination of values inherited from
1804  // dominators.
1805  } else if (Value *repl = lookupNumber(I->getParent(), Num)) {
1806    // Remove it!
1807    VN.erase(I);
1808    I->replaceAllUsesWith(repl);
1809    if (isa<PointerType>(repl->getType()))
1810      MD->invalidateCachedPointerInfo(repl);
1811    toErase.push_back(I);
1812    return true;
1813
1814  } else {
1815    localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
1816  }
1817
1818  return false;
1819}
1820
1821/// runOnFunction - This is the main transformation entry point for a function.
1822bool GVN::runOnFunction(Function& F) {
1823  MD = &getAnalysis<MemoryDependenceAnalysis>();
1824  DT = &getAnalysis<DominatorTree>();
1825  VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1826  VN.setMemDep(MD);
1827  VN.setDomTree(DT);
1828
1829  bool Changed = false;
1830  bool ShouldContinue = true;
1831
1832  // Merge unconditional branches, allowing PRE to catch more
1833  // optimization opportunities.
1834  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
1835    BasicBlock *BB = FI;
1836    ++FI;
1837    bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1838    if (removedBlock) NumGVNBlocks++;
1839
1840    Changed |= removedBlock;
1841  }
1842
1843  unsigned Iteration = 0;
1844
1845  while (ShouldContinue) {
1846    DEBUG(errs() << "GVN iteration: " << Iteration << "\n");
1847    ShouldContinue = iterateOnFunction(F);
1848    Changed |= ShouldContinue;
1849    ++Iteration;
1850  }
1851
1852  if (EnablePRE) {
1853    bool PREChanged = true;
1854    while (PREChanged) {
1855      PREChanged = performPRE(F);
1856      Changed |= PREChanged;
1857    }
1858  }
1859  // FIXME: Should perform GVN again after PRE does something.  PRE can move
1860  // computations into blocks where they become fully redundant.  Note that
1861  // we can't do this until PRE's critical edge splitting updates memdep.
1862  // Actually, when this happens, we should just fully integrate PRE into GVN.
1863
1864  cleanupGlobalSets();
1865
1866  return Changed;
1867}
1868
1869
1870bool GVN::processBlock(BasicBlock *BB) {
1871  // FIXME: Kill off toErase by doing erasing eagerly in a helper function (and
1872  // incrementing BI before processing an instruction).
1873  SmallVector<Instruction*, 8> toErase;
1874  bool ChangedFunction = false;
1875
1876  for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1877       BI != BE;) {
1878    ChangedFunction |= processInstruction(BI, toErase);
1879    if (toErase.empty()) {
1880      ++BI;
1881      continue;
1882    }
1883
1884    // If we need some instructions deleted, do it now.
1885    NumGVNInstr += toErase.size();
1886
1887    // Avoid iterator invalidation.
1888    bool AtStart = BI == BB->begin();
1889    if (!AtStart)
1890      --BI;
1891
1892    for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1893         E = toErase.end(); I != E; ++I) {
1894      DEBUG(errs() << "GVN removed: " << **I << '\n');
1895      MD->removeInstruction(*I);
1896      (*I)->eraseFromParent();
1897      DEBUG(verifyRemoved(*I));
1898    }
1899    toErase.clear();
1900
1901    if (AtStart)
1902      BI = BB->begin();
1903    else
1904      ++BI;
1905  }
1906
1907  return ChangedFunction;
1908}
1909
1910/// performPRE - Perform a purely local form of PRE that looks for diamond
1911/// control flow patterns and attempts to perform simple PRE at the join point.
1912bool GVN::performPRE(Function& F) {
1913  bool Changed = false;
1914  SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
1915  DenseMap<BasicBlock*, Value*> predMap;
1916  for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1917       DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
1918    BasicBlock *CurrentBlock = *DI;
1919
1920    // Nothing to PRE in the entry block.
1921    if (CurrentBlock == &F.getEntryBlock()) continue;
1922
1923    for (BasicBlock::iterator BI = CurrentBlock->begin(),
1924         BE = CurrentBlock->end(); BI != BE; ) {
1925      Instruction *CurInst = BI++;
1926
1927      if (isa<AllocationInst>(CurInst) ||
1928          isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
1929          (CurInst->getType() == Type::getVoidTy(F.getContext())) ||
1930          CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
1931          isa<DbgInfoIntrinsic>(CurInst))
1932        continue;
1933
1934      uint32_t ValNo = VN.lookup(CurInst);
1935
1936      // Look for the predecessors for PRE opportunities.  We're
1937      // only trying to solve the basic diamond case, where
1938      // a value is computed in the successor and one predecessor,
1939      // but not the other.  We also explicitly disallow cases
1940      // where the successor is its own predecessor, because they're
1941      // more complicated to get right.
1942      unsigned NumWith = 0;
1943      unsigned NumWithout = 0;
1944      BasicBlock *PREPred = 0;
1945      predMap.clear();
1946
1947      for (pred_iterator PI = pred_begin(CurrentBlock),
1948           PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1949        // We're not interested in PRE where the block is its
1950        // own predecessor, on in blocks with predecessors
1951        // that are not reachable.
1952        if (*PI == CurrentBlock) {
1953          NumWithout = 2;
1954          break;
1955        } else if (!localAvail.count(*PI))  {
1956          NumWithout = 2;
1957          break;
1958        }
1959
1960        DenseMap<uint32_t, Value*>::iterator predV =
1961                                            localAvail[*PI]->table.find(ValNo);
1962        if (predV == localAvail[*PI]->table.end()) {
1963          PREPred = *PI;
1964          NumWithout++;
1965        } else if (predV->second == CurInst) {
1966          NumWithout = 2;
1967        } else {
1968          predMap[*PI] = predV->second;
1969          NumWith++;
1970        }
1971      }
1972
1973      // Don't do PRE when it might increase code size, i.e. when
1974      // we would need to insert instructions in more than one pred.
1975      if (NumWithout != 1 || NumWith == 0)
1976        continue;
1977
1978      // We can't do PRE safely on a critical edge, so instead we schedule
1979      // the edge to be split and perform the PRE the next time we iterate
1980      // on the function.
1981      unsigned SuccNum = 0;
1982      for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1983           i != e; ++i)
1984        if (PREPred->getTerminator()->getSuccessor(i) == CurrentBlock) {
1985          SuccNum = i;
1986          break;
1987        }
1988
1989      if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
1990        toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
1991        continue;
1992      }
1993
1994      // Instantiate the expression the in predecessor that lacked it.
1995      // Because we are going top-down through the block, all value numbers
1996      // will be available in the predecessor by the time we need them.  Any
1997      // that weren't original present will have been instantiated earlier
1998      // in this loop.
1999      Instruction *PREInstr = CurInst->clone();
2000      bool success = true;
2001      for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
2002        Value *Op = PREInstr->getOperand(i);
2003        if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2004          continue;
2005
2006        if (Value *V = lookupNumber(PREPred, VN.lookup(Op))) {
2007          PREInstr->setOperand(i, V);
2008        } else {
2009          success = false;
2010          break;
2011        }
2012      }
2013
2014      // Fail out if we encounter an operand that is not available in
2015      // the PRE predecessor.  This is typically because of loads which
2016      // are not value numbered precisely.
2017      if (!success) {
2018        delete PREInstr;
2019        DEBUG(verifyRemoved(PREInstr));
2020        continue;
2021      }
2022
2023      PREInstr->insertBefore(PREPred->getTerminator());
2024      PREInstr->setName(CurInst->getName() + ".pre");
2025      predMap[PREPred] = PREInstr;
2026      VN.add(PREInstr, ValNo);
2027      NumGVNPRE++;
2028
2029      // Update the availability map to include the new instruction.
2030      localAvail[PREPred]->table.insert(std::make_pair(ValNo, PREInstr));
2031
2032      // Create a PHI to make the value available in this block.
2033      PHINode* Phi = PHINode::Create(CurInst->getType(),
2034                                     CurInst->getName() + ".pre-phi",
2035                                     CurrentBlock->begin());
2036      for (pred_iterator PI = pred_begin(CurrentBlock),
2037           PE = pred_end(CurrentBlock); PI != PE; ++PI)
2038        Phi->addIncoming(predMap[*PI], *PI);
2039
2040      VN.add(Phi, ValNo);
2041      localAvail[CurrentBlock]->table[ValNo] = Phi;
2042
2043      CurInst->replaceAllUsesWith(Phi);
2044      if (isa<PointerType>(Phi->getType()))
2045        MD->invalidateCachedPointerInfo(Phi);
2046      VN.erase(CurInst);
2047
2048      DEBUG(errs() << "GVN PRE removed: " << *CurInst << '\n');
2049      MD->removeInstruction(CurInst);
2050      CurInst->eraseFromParent();
2051      DEBUG(verifyRemoved(CurInst));
2052      Changed = true;
2053    }
2054  }
2055
2056  for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
2057       I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
2058    SplitCriticalEdge(I->first, I->second, this);
2059
2060  return Changed || toSplit.size();
2061}
2062
2063/// iterateOnFunction - Executes one iteration of GVN
2064bool GVN::iterateOnFunction(Function &F) {
2065  cleanupGlobalSets();
2066
2067  for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2068       DE = df_end(DT->getRootNode()); DI != DE; ++DI) {
2069    if (DI->getIDom())
2070      localAvail[DI->getBlock()] =
2071                   new ValueNumberScope(localAvail[DI->getIDom()->getBlock()]);
2072    else
2073      localAvail[DI->getBlock()] = new ValueNumberScope(0);
2074  }
2075
2076  // Top-down walk of the dominator tree
2077  bool Changed = false;
2078#if 0
2079  // Needed for value numbering with phi construction to work.
2080  ReversePostOrderTraversal<Function*> RPOT(&F);
2081  for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2082       RE = RPOT.end(); RI != RE; ++RI)
2083    Changed |= processBlock(*RI);
2084#else
2085  for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2086       DE = df_end(DT->getRootNode()); DI != DE; ++DI)
2087    Changed |= processBlock(DI->getBlock());
2088#endif
2089
2090  return Changed;
2091}
2092
2093void GVN::cleanupGlobalSets() {
2094  VN.clear();
2095  phiMap.clear();
2096
2097  for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
2098       I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
2099    delete I->second;
2100  localAvail.clear();
2101}
2102
2103/// verifyRemoved - Verify that the specified instruction does not occur in our
2104/// internal data structures.
2105void GVN::verifyRemoved(const Instruction *Inst) const {
2106  VN.verifyRemoved(Inst);
2107
2108  // Walk through the PHI map to make sure the instruction isn't hiding in there
2109  // somewhere.
2110  for (PhiMapType::iterator
2111         I = phiMap.begin(), E = phiMap.end(); I != E; ++I) {
2112    assert(I->first != Inst && "Inst is still a key in PHI map!");
2113
2114    for (SmallPtrSet<Instruction*, 4>::iterator
2115           II = I->second.begin(), IE = I->second.end(); II != IE; ++II) {
2116      assert(*II != Inst && "Inst is still a value in PHI map!");
2117    }
2118  }
2119
2120  // Walk through the value number scope to make sure the instruction isn't
2121  // ferreted away in it.
2122  for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
2123         I = localAvail.begin(), E = localAvail.end(); I != E; ++I) {
2124    const ValueNumberScope *VNS = I->second;
2125
2126    while (VNS) {
2127      for (DenseMap<uint32_t, Value*>::iterator
2128             II = VNS->table.begin(), IE = VNS->table.end(); II != IE; ++II) {
2129        assert(II->second != Inst && "Inst still in value numbering scope!");
2130      }
2131
2132      VNS = VNS->parent;
2133    }
2134  }
2135}
2136