GVN.cpp revision 4b7b3a7c19db3d0da12a44a0849730296c26fbf9
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/ADT/DenseMap.h"
21#include "llvm/ADT/DepthFirstIterator.h"
22#include "llvm/ADT/Hashing.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/Analysis/AliasAnalysis.h"
26#include "llvm/Analysis/ConstantFolding.h"
27#include "llvm/Analysis/Dominators.h"
28#include "llvm/Analysis/InstructionSimplify.h"
29#include "llvm/Analysis/Loads.h"
30#include "llvm/Analysis/MemoryBuiltins.h"
31#include "llvm/Analysis/MemoryDependenceAnalysis.h"
32#include "llvm/Analysis/PHITransAddr.h"
33#include "llvm/Analysis/ValueTracking.h"
34#include "llvm/Assembly/Writer.h"
35#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/GlobalVariable.h"
37#include "llvm/IR/IRBuilder.h"
38#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/LLVMContext.h"
40#include "llvm/IR/Metadata.h"
41#include "llvm/Support/Allocator.h"
42#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/Debug.h"
44#include "llvm/Support/PatternMatch.h"
45#include "llvm/Target/TargetLibraryInfo.h"
46#include "llvm/Transforms/Utils/BasicBlockUtils.h"
47#include "llvm/Transforms/Utils/SSAUpdater.h"
48#include <vector>
49using namespace llvm;
50using namespace PatternMatch;
51
52STATISTIC(NumGVNInstr,  "Number of instructions deleted");
53STATISTIC(NumGVNLoad,   "Number of loads deleted");
54STATISTIC(NumGVNPRE,    "Number of instructions PRE'd");
55STATISTIC(NumGVNBlocks, "Number of blocks merged");
56STATISTIC(NumGVNSimpl,  "Number of instructions simplified");
57STATISTIC(NumGVNEqProp, "Number of equalities propagated");
58STATISTIC(NumPRELoad,   "Number of loads PRE'd");
59
60static cl::opt<bool> EnablePRE("enable-pre",
61                               cl::init(true), cl::Hidden);
62static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
63
64// Maximum allowed recursion depth.
65static cl::opt<uint32_t>
66MaxRecurseDepth("max-recurse-depth", cl::Hidden, cl::init(1000), cl::ZeroOrMore,
67                cl::desc("Max recurse depth (default = 1000)"));
68
69//===----------------------------------------------------------------------===//
70//                         ValueTable Class
71//===----------------------------------------------------------------------===//
72
73/// This class holds the mapping between values and value numbers.  It is used
74/// as an efficient mechanism to determine the expression-wise equivalence of
75/// two values.
76namespace {
77  struct Expression {
78    uint32_t opcode;
79    Type *type;
80    SmallVector<uint32_t, 4> varargs;
81
82    Expression(uint32_t o = ~2U) : opcode(o) { }
83
84    bool operator==(const Expression &other) const {
85      if (opcode != other.opcode)
86        return false;
87      if (opcode == ~0U || opcode == ~1U)
88        return true;
89      if (type != other.type)
90        return false;
91      if (varargs != other.varargs)
92        return false;
93      return true;
94    }
95
96    friend hash_code hash_value(const Expression &Value) {
97      return hash_combine(Value.opcode, Value.type,
98                          hash_combine_range(Value.varargs.begin(),
99                                             Value.varargs.end()));
100    }
101  };
102
103  class ValueTable {
104    DenseMap<Value*, uint32_t> valueNumbering;
105    DenseMap<Expression, uint32_t> expressionNumbering;
106    AliasAnalysis *AA;
107    MemoryDependenceAnalysis *MD;
108    DominatorTree *DT;
109
110    uint32_t nextValueNumber;
111
112    Expression create_expression(Instruction* I);
113    Expression create_cmp_expression(unsigned Opcode,
114                                     CmpInst::Predicate Predicate,
115                                     Value *LHS, Value *RHS);
116    Expression create_extractvalue_expression(ExtractValueInst* EI);
117    uint32_t lookup_or_add_call(CallInst* C);
118  public:
119    ValueTable() : nextValueNumber(1) { }
120    uint32_t lookup_or_add(Value *V);
121    uint32_t lookup(Value *V) const;
122    uint32_t lookup_or_add_cmp(unsigned Opcode, CmpInst::Predicate Pred,
123                               Value *LHS, Value *RHS);
124    void add(Value *V, uint32_t num);
125    void clear();
126    void erase(Value *v);
127    void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
128    AliasAnalysis *getAliasAnalysis() const { return AA; }
129    void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
130    void setDomTree(DominatorTree* D) { DT = D; }
131    uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
132    void verifyRemoved(const Value *) const;
133  };
134}
135
136namespace llvm {
137template <> struct DenseMapInfo<Expression> {
138  static inline Expression getEmptyKey() {
139    return ~0U;
140  }
141
142  static inline Expression getTombstoneKey() {
143    return ~1U;
144  }
145
146  static unsigned getHashValue(const Expression e) {
147    using llvm::hash_value;
148    return static_cast<unsigned>(hash_value(e));
149  }
150  static bool isEqual(const Expression &LHS, const Expression &RHS) {
151    return LHS == RHS;
152  }
153};
154
155}
156
157//===----------------------------------------------------------------------===//
158//                     ValueTable Internal Functions
159//===----------------------------------------------------------------------===//
160
161Expression ValueTable::create_expression(Instruction *I) {
162  Expression e;
163  e.type = I->getType();
164  e.opcode = I->getOpcode();
165  for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
166       OI != OE; ++OI)
167    e.varargs.push_back(lookup_or_add(*OI));
168  if (I->isCommutative()) {
169    // Ensure that commutative instructions that only differ by a permutation
170    // of their operands get the same value number by sorting the operand value
171    // numbers.  Since all commutative instructions have two operands it is more
172    // efficient to sort by hand rather than using, say, std::sort.
173    assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
174    if (e.varargs[0] > e.varargs[1])
175      std::swap(e.varargs[0], e.varargs[1]);
176  }
177
178  if (CmpInst *C = dyn_cast<CmpInst>(I)) {
179    // Sort the operand value numbers so x<y and y>x get the same value number.
180    CmpInst::Predicate Predicate = C->getPredicate();
181    if (e.varargs[0] > e.varargs[1]) {
182      std::swap(e.varargs[0], e.varargs[1]);
183      Predicate = CmpInst::getSwappedPredicate(Predicate);
184    }
185    e.opcode = (C->getOpcode() << 8) | Predicate;
186  } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
187    for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
188         II != IE; ++II)
189      e.varargs.push_back(*II);
190  }
191
192  return e;
193}
194
195Expression ValueTable::create_cmp_expression(unsigned Opcode,
196                                             CmpInst::Predicate Predicate,
197                                             Value *LHS, Value *RHS) {
198  assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
199         "Not a comparison!");
200  Expression e;
201  e.type = CmpInst::makeCmpResultType(LHS->getType());
202  e.varargs.push_back(lookup_or_add(LHS));
203  e.varargs.push_back(lookup_or_add(RHS));
204
205  // Sort the operand value numbers so x<y and y>x get the same value number.
206  if (e.varargs[0] > e.varargs[1]) {
207    std::swap(e.varargs[0], e.varargs[1]);
208    Predicate = CmpInst::getSwappedPredicate(Predicate);
209  }
210  e.opcode = (Opcode << 8) | Predicate;
211  return e;
212}
213
214Expression ValueTable::create_extractvalue_expression(ExtractValueInst *EI) {
215  assert(EI != 0 && "Not an ExtractValueInst?");
216  Expression e;
217  e.type = EI->getType();
218  e.opcode = 0;
219
220  IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
221  if (I != 0 && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
222    // EI might be an extract from one of our recognised intrinsics. If it
223    // is we'll synthesize a semantically equivalent expression instead on
224    // an extract value expression.
225    switch (I->getIntrinsicID()) {
226      case Intrinsic::sadd_with_overflow:
227      case Intrinsic::uadd_with_overflow:
228        e.opcode = Instruction::Add;
229        break;
230      case Intrinsic::ssub_with_overflow:
231      case Intrinsic::usub_with_overflow:
232        e.opcode = Instruction::Sub;
233        break;
234      case Intrinsic::smul_with_overflow:
235      case Intrinsic::umul_with_overflow:
236        e.opcode = Instruction::Mul;
237        break;
238      default:
239        break;
240    }
241
242    if (e.opcode != 0) {
243      // Intrinsic recognized. Grab its args to finish building the expression.
244      assert(I->getNumArgOperands() == 2 &&
245             "Expect two args for recognised intrinsics.");
246      e.varargs.push_back(lookup_or_add(I->getArgOperand(0)));
247      e.varargs.push_back(lookup_or_add(I->getArgOperand(1)));
248      return e;
249    }
250  }
251
252  // Not a recognised intrinsic. Fall back to producing an extract value
253  // expression.
254  e.opcode = EI->getOpcode();
255  for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
256       OI != OE; ++OI)
257    e.varargs.push_back(lookup_or_add(*OI));
258
259  for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
260         II != IE; ++II)
261    e.varargs.push_back(*II);
262
263  return e;
264}
265
266//===----------------------------------------------------------------------===//
267//                     ValueTable External Functions
268//===----------------------------------------------------------------------===//
269
270/// add - Insert a value into the table with a specified value number.
271void ValueTable::add(Value *V, uint32_t num) {
272  valueNumbering.insert(std::make_pair(V, num));
273}
274
275uint32_t ValueTable::lookup_or_add_call(CallInst *C) {
276  if (AA->doesNotAccessMemory(C)) {
277    Expression exp = create_expression(C);
278    uint32_t &e = expressionNumbering[exp];
279    if (!e) e = nextValueNumber++;
280    valueNumbering[C] = e;
281    return e;
282  } else if (AA->onlyReadsMemory(C)) {
283    Expression exp = create_expression(C);
284    uint32_t &e = expressionNumbering[exp];
285    if (!e) {
286      e = nextValueNumber++;
287      valueNumbering[C] = e;
288      return e;
289    }
290    if (!MD) {
291      e = nextValueNumber++;
292      valueNumbering[C] = e;
293      return e;
294    }
295
296    MemDepResult local_dep = MD->getDependency(C);
297
298    if (!local_dep.isDef() && !local_dep.isNonLocal()) {
299      valueNumbering[C] =  nextValueNumber;
300      return nextValueNumber++;
301    }
302
303    if (local_dep.isDef()) {
304      CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
305
306      if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
307        valueNumbering[C] = nextValueNumber;
308        return nextValueNumber++;
309      }
310
311      for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
312        uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
313        uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
314        if (c_vn != cd_vn) {
315          valueNumbering[C] = nextValueNumber;
316          return nextValueNumber++;
317        }
318      }
319
320      uint32_t v = lookup_or_add(local_cdep);
321      valueNumbering[C] = v;
322      return v;
323    }
324
325    // Non-local case.
326    const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
327      MD->getNonLocalCallDependency(CallSite(C));
328    // FIXME: Move the checking logic to MemDep!
329    CallInst* cdep = 0;
330
331    // Check to see if we have a single dominating call instruction that is
332    // identical to C.
333    for (unsigned i = 0, e = deps.size(); i != e; ++i) {
334      const NonLocalDepEntry *I = &deps[i];
335      if (I->getResult().isNonLocal())
336        continue;
337
338      // We don't handle non-definitions.  If we already have a call, reject
339      // instruction dependencies.
340      if (!I->getResult().isDef() || cdep != 0) {
341        cdep = 0;
342        break;
343      }
344
345      CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
346      // FIXME: All duplicated with non-local case.
347      if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
348        cdep = NonLocalDepCall;
349        continue;
350      }
351
352      cdep = 0;
353      break;
354    }
355
356    if (!cdep) {
357      valueNumbering[C] = nextValueNumber;
358      return nextValueNumber++;
359    }
360
361    if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
362      valueNumbering[C] = nextValueNumber;
363      return nextValueNumber++;
364    }
365    for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
366      uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
367      uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
368      if (c_vn != cd_vn) {
369        valueNumbering[C] = nextValueNumber;
370        return nextValueNumber++;
371      }
372    }
373
374    uint32_t v = lookup_or_add(cdep);
375    valueNumbering[C] = v;
376    return v;
377
378  } else {
379    valueNumbering[C] = nextValueNumber;
380    return nextValueNumber++;
381  }
382}
383
384/// lookup_or_add - Returns the value number for the specified value, assigning
385/// it a new number if it did not have one before.
386uint32_t ValueTable::lookup_or_add(Value *V) {
387  DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
388  if (VI != valueNumbering.end())
389    return VI->second;
390
391  if (!isa<Instruction>(V)) {
392    valueNumbering[V] = nextValueNumber;
393    return nextValueNumber++;
394  }
395
396  Instruction* I = cast<Instruction>(V);
397  Expression exp;
398  switch (I->getOpcode()) {
399    case Instruction::Call:
400      return lookup_or_add_call(cast<CallInst>(I));
401    case Instruction::Add:
402    case Instruction::FAdd:
403    case Instruction::Sub:
404    case Instruction::FSub:
405    case Instruction::Mul:
406    case Instruction::FMul:
407    case Instruction::UDiv:
408    case Instruction::SDiv:
409    case Instruction::FDiv:
410    case Instruction::URem:
411    case Instruction::SRem:
412    case Instruction::FRem:
413    case Instruction::Shl:
414    case Instruction::LShr:
415    case Instruction::AShr:
416    case Instruction::And:
417    case Instruction::Or:
418    case Instruction::Xor:
419    case Instruction::ICmp:
420    case Instruction::FCmp:
421    case Instruction::Trunc:
422    case Instruction::ZExt:
423    case Instruction::SExt:
424    case Instruction::FPToUI:
425    case Instruction::FPToSI:
426    case Instruction::UIToFP:
427    case Instruction::SIToFP:
428    case Instruction::FPTrunc:
429    case Instruction::FPExt:
430    case Instruction::PtrToInt:
431    case Instruction::IntToPtr:
432    case Instruction::BitCast:
433    case Instruction::Select:
434    case Instruction::ExtractElement:
435    case Instruction::InsertElement:
436    case Instruction::ShuffleVector:
437    case Instruction::InsertValue:
438    case Instruction::GetElementPtr:
439      exp = create_expression(I);
440      break;
441    case Instruction::ExtractValue:
442      exp = create_extractvalue_expression(cast<ExtractValueInst>(I));
443      break;
444    default:
445      valueNumbering[V] = nextValueNumber;
446      return nextValueNumber++;
447  }
448
449  uint32_t& e = expressionNumbering[exp];
450  if (!e) e = nextValueNumber++;
451  valueNumbering[V] = e;
452  return e;
453}
454
455/// lookup - Returns the value number of the specified value. Fails if
456/// the value has not yet been numbered.
457uint32_t ValueTable::lookup(Value *V) const {
458  DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
459  assert(VI != valueNumbering.end() && "Value not numbered?");
460  return VI->second;
461}
462
463/// lookup_or_add_cmp - Returns the value number of the given comparison,
464/// assigning it a new number if it did not have one before.  Useful when
465/// we deduced the result of a comparison, but don't immediately have an
466/// instruction realizing that comparison to hand.
467uint32_t ValueTable::lookup_or_add_cmp(unsigned Opcode,
468                                       CmpInst::Predicate Predicate,
469                                       Value *LHS, Value *RHS) {
470  Expression exp = create_cmp_expression(Opcode, Predicate, LHS, RHS);
471  uint32_t& e = expressionNumbering[exp];
472  if (!e) e = nextValueNumber++;
473  return e;
474}
475
476/// clear - Remove all entries from the ValueTable.
477void ValueTable::clear() {
478  valueNumbering.clear();
479  expressionNumbering.clear();
480  nextValueNumber = 1;
481}
482
483/// erase - Remove a value from the value numbering.
484void ValueTable::erase(Value *V) {
485  valueNumbering.erase(V);
486}
487
488/// verifyRemoved - Verify that the value is removed from all internal data
489/// structures.
490void ValueTable::verifyRemoved(const Value *V) const {
491  for (DenseMap<Value*, uint32_t>::const_iterator
492         I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
493    assert(I->first != V && "Inst still occurs in value numbering map!");
494  }
495}
496
497//===----------------------------------------------------------------------===//
498//                                GVN Pass
499//===----------------------------------------------------------------------===//
500
501namespace {
502  class GVN;
503  struct AvailableValueInBlock {
504    /// BB - The basic block in question.
505    BasicBlock *BB;
506    enum ValType {
507      SimpleVal,  // A simple offsetted value that is accessed.
508      LoadVal,    // A value produced by a load.
509      MemIntrin   // A memory intrinsic which is loaded from.
510    };
511
512    /// V - The value that is live out of the block.
513    PointerIntPair<Value *, 2, ValType> Val;
514
515    /// Offset - The byte offset in Val that is interesting for the load query.
516    unsigned Offset;
517
518    static AvailableValueInBlock get(BasicBlock *BB, Value *V,
519                                     unsigned Offset = 0) {
520      AvailableValueInBlock Res;
521      Res.BB = BB;
522      Res.Val.setPointer(V);
523      Res.Val.setInt(SimpleVal);
524      Res.Offset = Offset;
525      return Res;
526    }
527
528    static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
529                                       unsigned Offset = 0) {
530      AvailableValueInBlock Res;
531      Res.BB = BB;
532      Res.Val.setPointer(MI);
533      Res.Val.setInt(MemIntrin);
534      Res.Offset = Offset;
535      return Res;
536    }
537
538    static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
539                                         unsigned Offset = 0) {
540      AvailableValueInBlock Res;
541      Res.BB = BB;
542      Res.Val.setPointer(LI);
543      Res.Val.setInt(LoadVal);
544      Res.Offset = Offset;
545      return Res;
546    }
547
548    bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
549    bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
550    bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
551
552    Value *getSimpleValue() const {
553      assert(isSimpleValue() && "Wrong accessor");
554      return Val.getPointer();
555    }
556
557    LoadInst *getCoercedLoadValue() const {
558      assert(isCoercedLoadValue() && "Wrong accessor");
559      return cast<LoadInst>(Val.getPointer());
560    }
561
562    MemIntrinsic *getMemIntrinValue() const {
563      assert(isMemIntrinValue() && "Wrong accessor");
564      return cast<MemIntrinsic>(Val.getPointer());
565    }
566
567    /// MaterializeAdjustedValue - Emit code into this block to adjust the value
568    /// defined here to the specified type.  This handles various coercion cases.
569    Value *MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const;
570  };
571
572  class GVN : public FunctionPass {
573    bool NoLoads;
574    MemoryDependenceAnalysis *MD;
575    DominatorTree *DT;
576    const DataLayout *TD;
577    const TargetLibraryInfo *TLI;
578
579    ValueTable VN;
580
581    /// LeaderTable - A mapping from value numbers to lists of Value*'s that
582    /// have that value number.  Use findLeader to query it.
583    struct LeaderTableEntry {
584      Value *Val;
585      const BasicBlock *BB;
586      LeaderTableEntry *Next;
587    };
588    DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
589    BumpPtrAllocator TableAllocator;
590
591    SmallVector<Instruction*, 8> InstrsToErase;
592
593    typedef SmallVector<NonLocalDepResult, 64> LoadDepVect;
594    typedef SmallVector<AvailableValueInBlock, 64> AvailValInBlkVect;
595    typedef SmallVector<BasicBlock*, 64> UnavailBlkVect;
596
597  public:
598    static char ID; // Pass identification, replacement for typeid
599    explicit GVN(bool noloads = false)
600        : FunctionPass(ID), NoLoads(noloads), MD(0) {
601      initializeGVNPass(*PassRegistry::getPassRegistry());
602    }
603
604    bool runOnFunction(Function &F);
605
606    /// markInstructionForDeletion - This removes the specified instruction from
607    /// our various maps and marks it for deletion.
608    void markInstructionForDeletion(Instruction *I) {
609      VN.erase(I);
610      InstrsToErase.push_back(I);
611    }
612
613    const DataLayout *getDataLayout() const { return TD; }
614    DominatorTree &getDominatorTree() const { return *DT; }
615    AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
616    MemoryDependenceAnalysis &getMemDep() const { return *MD; }
617  private:
618    /// addToLeaderTable - Push a new Value to the LeaderTable onto the list for
619    /// its value number.
620    void addToLeaderTable(uint32_t N, Value *V, const BasicBlock *BB) {
621      LeaderTableEntry &Curr = LeaderTable[N];
622      if (!Curr.Val) {
623        Curr.Val = V;
624        Curr.BB = BB;
625        return;
626      }
627
628      LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
629      Node->Val = V;
630      Node->BB = BB;
631      Node->Next = Curr.Next;
632      Curr.Next = Node;
633    }
634
635    /// removeFromLeaderTable - Scan the list of values corresponding to a given
636    /// value number, and remove the given instruction if encountered.
637    void removeFromLeaderTable(uint32_t N, Instruction *I, BasicBlock *BB) {
638      LeaderTableEntry* Prev = 0;
639      LeaderTableEntry* Curr = &LeaderTable[N];
640
641      while (Curr->Val != I || Curr->BB != BB) {
642        Prev = Curr;
643        Curr = Curr->Next;
644      }
645
646      if (Prev) {
647        Prev->Next = Curr->Next;
648      } else {
649        if (!Curr->Next) {
650          Curr->Val = 0;
651          Curr->BB = 0;
652        } else {
653          LeaderTableEntry* Next = Curr->Next;
654          Curr->Val = Next->Val;
655          Curr->BB = Next->BB;
656          Curr->Next = Next->Next;
657        }
658      }
659    }
660
661    // List of critical edges to be split between iterations.
662    SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
663
664    // This transformation requires dominator postdominator info
665    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
666      AU.addRequired<DominatorTree>();
667      AU.addRequired<TargetLibraryInfo>();
668      if (!NoLoads)
669        AU.addRequired<MemoryDependenceAnalysis>();
670      AU.addRequired<AliasAnalysis>();
671
672      AU.addPreserved<DominatorTree>();
673      AU.addPreserved<AliasAnalysis>();
674    }
675
676
677    // Helper fuctions of redundant load elimination
678    bool processLoad(LoadInst *L);
679    bool processNonLocalLoad(LoadInst *L);
680    void AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
681                                 AvailValInBlkVect &ValuesPerBlock,
682                                 UnavailBlkVect &UnavailableBlocks);
683    bool PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
684                        UnavailBlkVect &UnavailableBlocks);
685
686    // Other helper routines
687    bool processInstruction(Instruction *I);
688    bool processBlock(BasicBlock *BB);
689    void dump(DenseMap<uint32_t, Value*> &d);
690    bool iterateOnFunction(Function &F);
691    bool performPRE(Function &F);
692    Value *findLeader(const BasicBlock *BB, uint32_t num);
693    void cleanupGlobalSets();
694    void verifyRemoved(const Instruction *I) const;
695    bool splitCriticalEdges();
696    BasicBlock *splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ);
697    unsigned replaceAllDominatedUsesWith(Value *From, Value *To,
698                                         const BasicBlockEdge &Root);
699    bool propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root);
700  };
701
702  char GVN::ID = 0;
703}
704
705// createGVNPass - The public interface to this file...
706FunctionPass *llvm::createGVNPass(bool NoLoads) {
707  return new GVN(NoLoads);
708}
709
710INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
711INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
712INITIALIZE_PASS_DEPENDENCY(DominatorTree)
713INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
714INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
715INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
716
717#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
718void GVN::dump(DenseMap<uint32_t, Value*>& d) {
719  errs() << "{\n";
720  for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
721       E = d.end(); I != E; ++I) {
722      errs() << I->first << "\n";
723      I->second->dump();
724  }
725  errs() << "}\n";
726}
727#endif
728
729/// IsValueFullyAvailableInBlock - Return true if we can prove that the value
730/// we're analyzing is fully available in the specified block.  As we go, keep
731/// track of which blocks we know are fully alive in FullyAvailableBlocks.  This
732/// map is actually a tri-state map with the following values:
733///   0) we know the block *is not* fully available.
734///   1) we know the block *is* fully available.
735///   2) we do not know whether the block is fully available or not, but we are
736///      currently speculating that it will be.
737///   3) we are speculating for this block and have used that to speculate for
738///      other blocks.
739static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
740                            DenseMap<BasicBlock*, char> &FullyAvailableBlocks,
741                            uint32_t RecurseDepth) {
742  if (RecurseDepth > MaxRecurseDepth)
743    return false;
744
745  // Optimistically assume that the block is fully available and check to see
746  // if we already know about this block in one lookup.
747  std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
748    FullyAvailableBlocks.insert(std::make_pair(BB, 2));
749
750  // If the entry already existed for this block, return the precomputed value.
751  if (!IV.second) {
752    // If this is a speculative "available" value, mark it as being used for
753    // speculation of other blocks.
754    if (IV.first->second == 2)
755      IV.first->second = 3;
756    return IV.first->second != 0;
757  }
758
759  // Otherwise, see if it is fully available in all predecessors.
760  pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
761
762  // If this block has no predecessors, it isn't live-in here.
763  if (PI == PE)
764    goto SpeculationFailure;
765
766  for (; PI != PE; ++PI)
767    // If the value isn't fully available in one of our predecessors, then it
768    // isn't fully available in this block either.  Undo our previous
769    // optimistic assumption and bail out.
770    if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks,RecurseDepth+1))
771      goto SpeculationFailure;
772
773  return true;
774
775// SpeculationFailure - If we get here, we found out that this is not, after
776// all, a fully-available block.  We have a problem if we speculated on this and
777// used the speculation to mark other blocks as available.
778SpeculationFailure:
779  char &BBVal = FullyAvailableBlocks[BB];
780
781  // If we didn't speculate on this, just return with it set to false.
782  if (BBVal == 2) {
783    BBVal = 0;
784    return false;
785  }
786
787  // If we did speculate on this value, we could have blocks set to 1 that are
788  // incorrect.  Walk the (transitive) successors of this block and mark them as
789  // 0 if set to one.
790  SmallVector<BasicBlock*, 32> BBWorklist;
791  BBWorklist.push_back(BB);
792
793  do {
794    BasicBlock *Entry = BBWorklist.pop_back_val();
795    // Note that this sets blocks to 0 (unavailable) if they happen to not
796    // already be in FullyAvailableBlocks.  This is safe.
797    char &EntryVal = FullyAvailableBlocks[Entry];
798    if (EntryVal == 0) continue;  // Already unavailable.
799
800    // Mark as unavailable.
801    EntryVal = 0;
802
803    for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
804      BBWorklist.push_back(*I);
805  } while (!BBWorklist.empty());
806
807  return false;
808}
809
810
811/// CanCoerceMustAliasedValueToLoad - Return true if
812/// CoerceAvailableValueToLoadType will succeed.
813static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
814                                            Type *LoadTy,
815                                            const DataLayout &TD) {
816  // If the loaded or stored value is an first class array or struct, don't try
817  // to transform them.  We need to be able to bitcast to integer.
818  if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
819      StoredVal->getType()->isStructTy() ||
820      StoredVal->getType()->isArrayTy())
821    return false;
822
823  // The store has to be at least as big as the load.
824  if (TD.getTypeSizeInBits(StoredVal->getType()) <
825        TD.getTypeSizeInBits(LoadTy))
826    return false;
827
828  return true;
829}
830
831/// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
832/// then a load from a must-aliased pointer of a different type, try to coerce
833/// the stored value.  LoadedTy is the type of the load we want to replace and
834/// InsertPt is the place to insert new instructions.
835///
836/// If we can't do it, return null.
837static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
838                                             Type *LoadedTy,
839                                             Instruction *InsertPt,
840                                             const DataLayout &TD) {
841  if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
842    return 0;
843
844  // If this is already the right type, just return it.
845  Type *StoredValTy = StoredVal->getType();
846
847  uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
848  uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
849
850  // If the store and reload are the same size, we can always reuse it.
851  if (StoreSize == LoadSize) {
852    // Pointer to Pointer -> use bitcast.
853    if (StoredValTy->getScalarType()->isPointerTy() &&
854        LoadedTy->getScalarType()->isPointerTy())
855      return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
856
857    // Convert source pointers to integers, which can be bitcast.
858    if (StoredValTy->getScalarType()->isPointerTy()) {
859      StoredValTy = TD.getIntPtrType(StoredValTy);
860      StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
861    }
862
863    Type *TypeToCastTo = LoadedTy;
864    if (TypeToCastTo->getScalarType()->isPointerTy())
865      TypeToCastTo = TD.getIntPtrType(TypeToCastTo);
866
867    if (StoredValTy != TypeToCastTo)
868      StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
869
870    // Cast to pointer if the load needs a pointer type.
871    if (LoadedTy->getScalarType()->isPointerTy())
872      StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
873
874    return StoredVal;
875  }
876
877  // If the loaded value is smaller than the available value, then we can
878  // extract out a piece from it.  If the available value is too small, then we
879  // can't do anything.
880  assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
881
882  // Convert source pointers to integers, which can be manipulated.
883  if (StoredValTy->getScalarType()->isPointerTy()) {
884    StoredValTy = TD.getIntPtrType(StoredValTy);
885    StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
886  }
887
888  // Convert vectors and fp to integer, which can be manipulated.
889  if (!StoredValTy->isIntegerTy()) {
890    StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
891    StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
892  }
893
894  // If this is a big-endian system, we need to shift the value down to the low
895  // bits so that a truncate will work.
896  if (TD.isBigEndian()) {
897    Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
898    StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
899  }
900
901  // Truncate the integer to the right size now.
902  Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
903  StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
904
905  if (LoadedTy == NewIntTy)
906    return StoredVal;
907
908  // If the result is a pointer, inttoptr.
909  if (LoadedTy->getScalarType()->isPointerTy())
910    return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
911
912  // Otherwise, bitcast.
913  return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
914}
915
916/// AnalyzeLoadFromClobberingWrite - This function is called when we have a
917/// memdep query of a load that ends up being a clobbering memory write (store,
918/// memset, memcpy, memmove).  This means that the write *may* provide bits used
919/// by the load but we can't be sure because the pointers don't mustalias.
920///
921/// Check this case to see if there is anything more we can do before we give
922/// up.  This returns -1 if we have to give up, or a byte number in the stored
923/// value of the piece that feeds the load.
924static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
925                                          Value *WritePtr,
926                                          uint64_t WriteSizeInBits,
927                                          const DataLayout &TD) {
928  // If the loaded or stored value is a first class array or struct, don't try
929  // to transform them.  We need to be able to bitcast to integer.
930  if (LoadTy->isStructTy() || LoadTy->isArrayTy())
931    return -1;
932
933  int64_t StoreOffset = 0, LoadOffset = 0;
934  Value *StoreBase = GetPointerBaseWithConstantOffset(WritePtr,StoreOffset,&TD);
935  Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, &TD);
936  if (StoreBase != LoadBase)
937    return -1;
938
939  // If the load and store are to the exact same address, they should have been
940  // a must alias.  AA must have gotten confused.
941  // FIXME: Study to see if/when this happens.  One case is forwarding a memset
942  // to a load from the base of the memset.
943#if 0
944  if (LoadOffset == StoreOffset) {
945    dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
946    << "Base       = " << *StoreBase << "\n"
947    << "Store Ptr  = " << *WritePtr << "\n"
948    << "Store Offs = " << StoreOffset << "\n"
949    << "Load Ptr   = " << *LoadPtr << "\n";
950    abort();
951  }
952#endif
953
954  // If the load and store don't overlap at all, the store doesn't provide
955  // anything to the load.  In this case, they really don't alias at all, AA
956  // must have gotten confused.
957  uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy);
958
959  if ((WriteSizeInBits & 7) | (LoadSize & 7))
960    return -1;
961  uint64_t StoreSize = WriteSizeInBits >> 3;  // Convert to bytes.
962  LoadSize >>= 3;
963
964
965  bool isAAFailure = false;
966  if (StoreOffset < LoadOffset)
967    isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
968  else
969    isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
970
971  if (isAAFailure) {
972#if 0
973    dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
974    << "Base       = " << *StoreBase << "\n"
975    << "Store Ptr  = " << *WritePtr << "\n"
976    << "Store Offs = " << StoreOffset << "\n"
977    << "Load Ptr   = " << *LoadPtr << "\n";
978    abort();
979#endif
980    return -1;
981  }
982
983  // If the Load isn't completely contained within the stored bits, we don't
984  // have all the bits to feed it.  We could do something crazy in the future
985  // (issue a smaller load then merge the bits in) but this seems unlikely to be
986  // valuable.
987  if (StoreOffset > LoadOffset ||
988      StoreOffset+StoreSize < LoadOffset+LoadSize)
989    return -1;
990
991  // Okay, we can do this transformation.  Return the number of bytes into the
992  // store that the load is.
993  return LoadOffset-StoreOffset;
994}
995
996/// AnalyzeLoadFromClobberingStore - This function is called when we have a
997/// memdep query of a load that ends up being a clobbering store.
998static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
999                                          StoreInst *DepSI,
1000                                          const DataLayout &TD) {
1001  // Cannot handle reading from store of first-class aggregate yet.
1002  if (DepSI->getValueOperand()->getType()->isStructTy() ||
1003      DepSI->getValueOperand()->getType()->isArrayTy())
1004    return -1;
1005
1006  Value *StorePtr = DepSI->getPointerOperand();
1007  uint64_t StoreSize =TD.getTypeSizeInBits(DepSI->getValueOperand()->getType());
1008  return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
1009                                        StorePtr, StoreSize, TD);
1010}
1011
1012/// AnalyzeLoadFromClobberingLoad - This function is called when we have a
1013/// memdep query of a load that ends up being clobbered by another load.  See if
1014/// the other load can feed into the second load.
1015static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
1016                                         LoadInst *DepLI, const DataLayout &TD){
1017  // Cannot handle reading from store of first-class aggregate yet.
1018  if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
1019    return -1;
1020
1021  Value *DepPtr = DepLI->getPointerOperand();
1022  uint64_t DepSize = TD.getTypeSizeInBits(DepLI->getType());
1023  int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, TD);
1024  if (R != -1) return R;
1025
1026  // If we have a load/load clobber an DepLI can be widened to cover this load,
1027  // then we should widen it!
1028  int64_t LoadOffs = 0;
1029  const Value *LoadBase =
1030    GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, &TD);
1031  unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
1032
1033  unsigned Size = MemoryDependenceAnalysis::
1034    getLoadLoadClobberFullWidthSize(LoadBase, LoadOffs, LoadSize, DepLI, TD);
1035  if (Size == 0) return -1;
1036
1037  return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, TD);
1038}
1039
1040
1041
1042static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
1043                                            MemIntrinsic *MI,
1044                                            const DataLayout &TD) {
1045  // If the mem operation is a non-constant size, we can't handle it.
1046  ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
1047  if (SizeCst == 0) return -1;
1048  uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
1049
1050  // If this is memset, we just need to see if the offset is valid in the size
1051  // of the memset..
1052  if (MI->getIntrinsicID() == Intrinsic::memset)
1053    return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
1054                                          MemSizeInBits, TD);
1055
1056  // If we have a memcpy/memmove, the only case we can handle is if this is a
1057  // copy from constant memory.  In that case, we can read directly from the
1058  // constant memory.
1059  MemTransferInst *MTI = cast<MemTransferInst>(MI);
1060
1061  Constant *Src = dyn_cast<Constant>(MTI->getSource());
1062  if (Src == 0) return -1;
1063
1064  GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, &TD));
1065  if (GV == 0 || !GV->isConstant()) return -1;
1066
1067  // See if the access is within the bounds of the transfer.
1068  int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
1069                                              MI->getDest(), MemSizeInBits, TD);
1070  if (Offset == -1)
1071    return Offset;
1072
1073  // Otherwise, see if we can constant fold a load from the constant with the
1074  // offset applied as appropriate.
1075  Src = ConstantExpr::getBitCast(Src,
1076                                 llvm::Type::getInt8PtrTy(Src->getContext()));
1077  Constant *OffsetCst =
1078    ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
1079  Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
1080  Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
1081  if (ConstantFoldLoadFromConstPtr(Src, &TD))
1082    return Offset;
1083  return -1;
1084}
1085
1086
1087/// GetStoreValueForLoad - This function is called when we have a
1088/// memdep query of a load that ends up being a clobbering store.  This means
1089/// that the store provides bits used by the load but we the pointers don't
1090/// mustalias.  Check this case to see if there is anything more we can do
1091/// before we give up.
1092static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
1093                                   Type *LoadTy,
1094                                   Instruction *InsertPt, const DataLayout &TD){
1095  LLVMContext &Ctx = SrcVal->getType()->getContext();
1096
1097  uint64_t StoreSize = (TD.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
1098  uint64_t LoadSize = (TD.getTypeSizeInBits(LoadTy) + 7) / 8;
1099
1100  IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
1101
1102  // Compute which bits of the stored value are being used by the load.  Convert
1103  // to an integer type to start with.
1104  if (SrcVal->getType()->getScalarType()->isPointerTy())
1105    SrcVal = Builder.CreatePtrToInt(SrcVal,
1106        TD.getIntPtrType(SrcVal->getType()));
1107  if (!SrcVal->getType()->isIntegerTy())
1108    SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
1109
1110  // Shift the bits to the least significant depending on endianness.
1111  unsigned ShiftAmt;
1112  if (TD.isLittleEndian())
1113    ShiftAmt = Offset*8;
1114  else
1115    ShiftAmt = (StoreSize-LoadSize-Offset)*8;
1116
1117  if (ShiftAmt)
1118    SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
1119
1120  if (LoadSize != StoreSize)
1121    SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
1122
1123  return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
1124}
1125
1126/// GetLoadValueForLoad - This function is called when we have a
1127/// memdep query of a load that ends up being a clobbering load.  This means
1128/// that the load *may* provide bits used by the load but we can't be sure
1129/// because the pointers don't mustalias.  Check this case to see if there is
1130/// anything more we can do before we give up.
1131static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
1132                                  Type *LoadTy, Instruction *InsertPt,
1133                                  GVN &gvn) {
1134  const DataLayout &TD = *gvn.getDataLayout();
1135  // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
1136  // widen SrcVal out to a larger load.
1137  unsigned SrcValSize = TD.getTypeStoreSize(SrcVal->getType());
1138  unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
1139  if (Offset+LoadSize > SrcValSize) {
1140    assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
1141    assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
1142    // If we have a load/load clobber an DepLI can be widened to cover this
1143    // load, then we should widen it to the next power of 2 size big enough!
1144    unsigned NewLoadSize = Offset+LoadSize;
1145    if (!isPowerOf2_32(NewLoadSize))
1146      NewLoadSize = NextPowerOf2(NewLoadSize);
1147
1148    Value *PtrVal = SrcVal->getPointerOperand();
1149
1150    // Insert the new load after the old load.  This ensures that subsequent
1151    // memdep queries will find the new load.  We can't easily remove the old
1152    // load completely because it is already in the value numbering table.
1153    IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
1154    Type *DestPTy =
1155      IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
1156    DestPTy = PointerType::get(DestPTy,
1157                       cast<PointerType>(PtrVal->getType())->getAddressSpace());
1158    Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
1159    PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
1160    LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
1161    NewLoad->takeName(SrcVal);
1162    NewLoad->setAlignment(SrcVal->getAlignment());
1163
1164    DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
1165    DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
1166
1167    // Replace uses of the original load with the wider load.  On a big endian
1168    // system, we need to shift down to get the relevant bits.
1169    Value *RV = NewLoad;
1170    if (TD.isBigEndian())
1171      RV = Builder.CreateLShr(RV,
1172                    NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
1173    RV = Builder.CreateTrunc(RV, SrcVal->getType());
1174    SrcVal->replaceAllUsesWith(RV);
1175
1176    // We would like to use gvn.markInstructionForDeletion here, but we can't
1177    // because the load is already memoized into the leader map table that GVN
1178    // tracks.  It is potentially possible to remove the load from the table,
1179    // but then there all of the operations based on it would need to be
1180    // rehashed.  Just leave the dead load around.
1181    gvn.getMemDep().removeInstruction(SrcVal);
1182    SrcVal = NewLoad;
1183  }
1184
1185  return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, TD);
1186}
1187
1188
1189/// GetMemInstValueForLoad - This function is called when we have a
1190/// memdep query of a load that ends up being a clobbering mem intrinsic.
1191static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
1192                                     Type *LoadTy, Instruction *InsertPt,
1193                                     const DataLayout &TD){
1194  LLVMContext &Ctx = LoadTy->getContext();
1195  uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
1196
1197  IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
1198
1199  // We know that this method is only called when the mem transfer fully
1200  // provides the bits for the load.
1201  if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
1202    // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
1203    // independently of what the offset is.
1204    Value *Val = MSI->getValue();
1205    if (LoadSize != 1)
1206      Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
1207
1208    Value *OneElt = Val;
1209
1210    // Splat the value out to the right number of bits.
1211    for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
1212      // If we can double the number of bytes set, do it.
1213      if (NumBytesSet*2 <= LoadSize) {
1214        Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
1215        Val = Builder.CreateOr(Val, ShVal);
1216        NumBytesSet <<= 1;
1217        continue;
1218      }
1219
1220      // Otherwise insert one byte at a time.
1221      Value *ShVal = Builder.CreateShl(Val, 1*8);
1222      Val = Builder.CreateOr(OneElt, ShVal);
1223      ++NumBytesSet;
1224    }
1225
1226    return CoerceAvailableValueToLoadType(Val, LoadTy, InsertPt, TD);
1227  }
1228
1229  // Otherwise, this is a memcpy/memmove from a constant global.
1230  MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
1231  Constant *Src = cast<Constant>(MTI->getSource());
1232
1233  // Otherwise, see if we can constant fold a load from the constant with the
1234  // offset applied as appropriate.
1235  Src = ConstantExpr::getBitCast(Src,
1236                                 llvm::Type::getInt8PtrTy(Src->getContext()));
1237  Constant *OffsetCst =
1238  ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
1239  Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
1240  Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
1241  return ConstantFoldLoadFromConstPtr(Src, &TD);
1242}
1243
1244
1245/// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1246/// construct SSA form, allowing us to eliminate LI.  This returns the value
1247/// that should be used at LI's definition site.
1248static Value *ConstructSSAForLoadSet(LoadInst *LI,
1249                         SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
1250                                     GVN &gvn) {
1251  // Check for the fully redundant, dominating load case.  In this case, we can
1252  // just use the dominating value directly.
1253  if (ValuesPerBlock.size() == 1 &&
1254      gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
1255                                               LI->getParent()))
1256    return ValuesPerBlock[0].MaterializeAdjustedValue(LI->getType(), gvn);
1257
1258  // Otherwise, we have to construct SSA form.
1259  SmallVector<PHINode*, 8> NewPHIs;
1260  SSAUpdater SSAUpdate(&NewPHIs);
1261  SSAUpdate.Initialize(LI->getType(), LI->getName());
1262
1263  Type *LoadTy = LI->getType();
1264
1265  for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1266    const AvailableValueInBlock &AV = ValuesPerBlock[i];
1267    BasicBlock *BB = AV.BB;
1268
1269    if (SSAUpdate.HasValueForBlock(BB))
1270      continue;
1271
1272    SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LoadTy, gvn));
1273  }
1274
1275  // Perform PHI construction.
1276  Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1277
1278  // If new PHI nodes were created, notify alias analysis.
1279  if (V->getType()->getScalarType()->isPointerTy()) {
1280    AliasAnalysis *AA = gvn.getAliasAnalysis();
1281
1282    for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1283      AA->copyValue(LI, NewPHIs[i]);
1284
1285    // Now that we've copied information to the new PHIs, scan through
1286    // them again and inform alias analysis that we've added potentially
1287    // escaping uses to any values that are operands to these PHIs.
1288    for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
1289      PHINode *P = NewPHIs[i];
1290      for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii) {
1291        unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
1292        AA->addEscapingUse(P->getOperandUse(jj));
1293      }
1294    }
1295  }
1296
1297  return V;
1298}
1299
1300Value *AvailableValueInBlock::MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const {
1301  Value *Res;
1302  if (isSimpleValue()) {
1303    Res = getSimpleValue();
1304    if (Res->getType() != LoadTy) {
1305      const DataLayout *TD = gvn.getDataLayout();
1306      assert(TD && "Need target data to handle type mismatch case");
1307      Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(),
1308                                 *TD);
1309
1310      DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << "  "
1311                   << *getSimpleValue() << '\n'
1312                   << *Res << '\n' << "\n\n\n");
1313    }
1314  } else if (isCoercedLoadValue()) {
1315    LoadInst *Load = getCoercedLoadValue();
1316    if (Load->getType() == LoadTy && Offset == 0) {
1317      Res = Load;
1318    } else {
1319      Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
1320                                gvn);
1321
1322      DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << "  "
1323                   << *getCoercedLoadValue() << '\n'
1324                   << *Res << '\n' << "\n\n\n");
1325    }
1326  } else {
1327    const DataLayout *TD = gvn.getDataLayout();
1328    assert(TD && "Need target data to handle type mismatch case");
1329    Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset,
1330                                 LoadTy, BB->getTerminator(), *TD);
1331    DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
1332                 << "  " << *getMemIntrinValue() << '\n'
1333                 << *Res << '\n' << "\n\n\n");
1334  }
1335  return Res;
1336}
1337
1338static bool isLifetimeStart(const Instruction *Inst) {
1339  if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
1340    return II->getIntrinsicID() == Intrinsic::lifetime_start;
1341  return false;
1342}
1343
1344void GVN::AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
1345                                  AvailValInBlkVect &ValuesPerBlock,
1346                                  UnavailBlkVect &UnavailableBlocks) {
1347
1348  // Filter out useless results (non-locals, etc).  Keep track of the blocks
1349  // where we have a value available in repl, also keep track of whether we see
1350  // dependencies that produce an unknown value for the load (such as a call
1351  // that could potentially clobber the load).
1352  unsigned NumDeps = Deps.size();
1353  for (unsigned i = 0, e = NumDeps; i != e; ++i) {
1354    BasicBlock *DepBB = Deps[i].getBB();
1355    MemDepResult DepInfo = Deps[i].getResult();
1356
1357    if (!DepInfo.isDef() && !DepInfo.isClobber()) {
1358      UnavailableBlocks.push_back(DepBB);
1359      continue;
1360    }
1361
1362    if (DepInfo.isClobber()) {
1363      // The address being loaded in this non-local block may not be the same as
1364      // the pointer operand of the load if PHI translation occurs.  Make sure
1365      // to consider the right address.
1366      Value *Address = Deps[i].getAddress();
1367
1368      // If the dependence is to a store that writes to a superset of the bits
1369      // read by the load, we can extract the bits we need for the load from the
1370      // stored value.
1371      if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1372        if (TD && Address) {
1373          int Offset = AnalyzeLoadFromClobberingStore(LI->getType(), Address,
1374                                                      DepSI, *TD);
1375          if (Offset != -1) {
1376            ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1377                                                       DepSI->getValueOperand(),
1378                                                                Offset));
1379            continue;
1380          }
1381        }
1382      }
1383
1384      // Check to see if we have something like this:
1385      //    load i32* P
1386      //    load i8* (P+1)
1387      // if we have this, replace the later with an extraction from the former.
1388      if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
1389        // If this is a clobber and L is the first instruction in its block, then
1390        // we have the first instruction in the entry block.
1391        if (DepLI != LI && Address && TD) {
1392          int Offset = AnalyzeLoadFromClobberingLoad(LI->getType(),
1393                                                     LI->getPointerOperand(),
1394                                                     DepLI, *TD);
1395
1396          if (Offset != -1) {
1397            ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
1398                                                                    Offset));
1399            continue;
1400          }
1401        }
1402      }
1403
1404      // If the clobbering value is a memset/memcpy/memmove, see if we can
1405      // forward a value on from it.
1406      if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
1407        if (TD && Address) {
1408          int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
1409                                                        DepMI, *TD);
1410          if (Offset != -1) {
1411            ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
1412                                                                  Offset));
1413            continue;
1414          }
1415        }
1416      }
1417
1418      UnavailableBlocks.push_back(DepBB);
1419      continue;
1420    }
1421
1422    // DepInfo.isDef() here
1423
1424    Instruction *DepInst = DepInfo.getInst();
1425
1426    // Loading the allocation -> undef.
1427    if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI) ||
1428        // Loading immediately after lifetime begin -> undef.
1429        isLifetimeStart(DepInst)) {
1430      ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1431                                             UndefValue::get(LI->getType())));
1432      continue;
1433    }
1434
1435    if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
1436      // Reject loads and stores that are to the same address but are of
1437      // different types if we have to.
1438      if (S->getValueOperand()->getType() != LI->getType()) {
1439        // If the stored value is larger or equal to the loaded value, we can
1440        // reuse it.
1441        if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
1442                                                        LI->getType(), *TD)) {
1443          UnavailableBlocks.push_back(DepBB);
1444          continue;
1445        }
1446      }
1447
1448      ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1449                                                         S->getValueOperand()));
1450      continue;
1451    }
1452
1453    if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
1454      // If the types mismatch and we can't handle it, reject reuse of the load.
1455      if (LD->getType() != LI->getType()) {
1456        // If the stored value is larger or equal to the loaded value, we can
1457        // reuse it.
1458        if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
1459          UnavailableBlocks.push_back(DepBB);
1460          continue;
1461        }
1462      }
1463      ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
1464      continue;
1465    }
1466
1467    UnavailableBlocks.push_back(DepBB);
1468  }
1469}
1470
1471bool GVN::PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
1472                         UnavailBlkVect &UnavailableBlocks) {
1473  // Okay, we have *some* definitions of the value.  This means that the value
1474  // is available in some of our (transitive) predecessors.  Lets think about
1475  // doing PRE of this load.  This will involve inserting a new load into the
1476  // predecessor when it's not available.  We could do this in general, but
1477  // prefer to not increase code size.  As such, we only do this when we know
1478  // that we only have to insert *one* load (which means we're basically moving
1479  // the load, not inserting a new one).
1480
1481  SmallPtrSet<BasicBlock *, 4> Blockers;
1482  for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1483    Blockers.insert(UnavailableBlocks[i]);
1484
1485  // Let's find the first basic block with more than one predecessor.  Walk
1486  // backwards through predecessors if needed.
1487  BasicBlock *LoadBB = LI->getParent();
1488  BasicBlock *TmpBB = LoadBB;
1489
1490  while (TmpBB->getSinglePredecessor()) {
1491    TmpBB = TmpBB->getSinglePredecessor();
1492    if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1493      return false;
1494    if (Blockers.count(TmpBB))
1495      return false;
1496
1497    // If any of these blocks has more than one successor (i.e. if the edge we
1498    // just traversed was critical), then there are other paths through this
1499    // block along which the load may not be anticipated.  Hoisting the load
1500    // above this block would be adding the load to execution paths along
1501    // which it was not previously executed.
1502    if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1503      return false;
1504  }
1505
1506  assert(TmpBB);
1507  LoadBB = TmpBB;
1508
1509  // Check to see how many predecessors have the loaded value fully
1510  // available.
1511  DenseMap<BasicBlock*, Value*> PredLoads;
1512  DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1513  for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1514    FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
1515  for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1516    FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1517
1518  SmallVector<BasicBlock *, 4> CriticalEdgePred;
1519  for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1520       PI != E; ++PI) {
1521    BasicBlock *Pred = *PI;
1522    if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks, 0)) {
1523      continue;
1524    }
1525    PredLoads[Pred] = 0;
1526
1527    if (Pred->getTerminator()->getNumSuccessors() != 1) {
1528      if (isa<IndirectBrInst>(Pred->getTerminator())) {
1529        DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1530              << Pred->getName() << "': " << *LI << '\n');
1531        return false;
1532      }
1533
1534      if (LoadBB->isLandingPad()) {
1535        DEBUG(dbgs()
1536              << "COULD NOT PRE LOAD BECAUSE OF LANDING PAD CRITICAL EDGE '"
1537              << Pred->getName() << "': " << *LI << '\n');
1538        return false;
1539      }
1540
1541      CriticalEdgePred.push_back(Pred);
1542    }
1543  }
1544
1545  // Decide whether PRE is profitable for this load.
1546  unsigned NumUnavailablePreds = PredLoads.size();
1547  assert(NumUnavailablePreds != 0 &&
1548         "Fully available value should already be eliminated!");
1549
1550  // If this load is unavailable in multiple predecessors, reject it.
1551  // FIXME: If we could restructure the CFG, we could make a common pred with
1552  // all the preds that don't have an available LI and insert a new load into
1553  // that one block.
1554  if (NumUnavailablePreds != 1)
1555      return false;
1556
1557  // Split critical edges, and update the unavailable predecessors accordingly.
1558  for (SmallVector<BasicBlock *, 4>::iterator I = CriticalEdgePred.begin(),
1559         E = CriticalEdgePred.end(); I != E; I++) {
1560    BasicBlock *OrigPred = *I;
1561    BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
1562    PredLoads.erase(OrigPred);
1563    PredLoads[NewPred] = 0;
1564    DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
1565                 << LoadBB->getName() << '\n');
1566  }
1567
1568  // Check if the load can safely be moved to all the unavailable predecessors.
1569  bool CanDoPRE = true;
1570  SmallVector<Instruction*, 8> NewInsts;
1571  for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1572         E = PredLoads.end(); I != E; ++I) {
1573    BasicBlock *UnavailablePred = I->first;
1574
1575    // Do PHI translation to get its value in the predecessor if necessary.  The
1576    // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1577
1578    // If all preds have a single successor, then we know it is safe to insert
1579    // the load on the pred (?!?), so we can insert code to materialize the
1580    // pointer if it is not available.
1581    PHITransAddr Address(LI->getPointerOperand(), TD);
1582    Value *LoadPtr = 0;
1583    LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1584                                                *DT, NewInsts);
1585
1586    // If we couldn't find or insert a computation of this phi translated value,
1587    // we fail PRE.
1588    if (LoadPtr == 0) {
1589      DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
1590            << *LI->getPointerOperand() << "\n");
1591      CanDoPRE = false;
1592      break;
1593    }
1594
1595    I->second = LoadPtr;
1596  }
1597
1598  if (!CanDoPRE) {
1599    while (!NewInsts.empty()) {
1600      Instruction *I = NewInsts.pop_back_val();
1601      if (MD) MD->removeInstruction(I);
1602      I->eraseFromParent();
1603    }
1604    // HINT:Don't revert the edge-splitting as following transformation may
1605    // also need to split these critial edges.
1606    return !CriticalEdgePred.empty();
1607  }
1608
1609  // Okay, we can eliminate this load by inserting a reload in the predecessor
1610  // and using PHI construction to get the value in the other predecessors, do
1611  // it.
1612  DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
1613  DEBUG(if (!NewInsts.empty())
1614          dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
1615                 << *NewInsts.back() << '\n');
1616
1617  // Assign value numbers to the new instructions.
1618  for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
1619    // FIXME: We really _ought_ to insert these value numbers into their
1620    // parent's availability map.  However, in doing so, we risk getting into
1621    // ordering issues.  If a block hasn't been processed yet, we would be
1622    // marking a value as AVAIL-IN, which isn't what we intend.
1623    VN.lookup_or_add(NewInsts[i]);
1624  }
1625
1626  for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1627         E = PredLoads.end(); I != E; ++I) {
1628    BasicBlock *UnavailablePred = I->first;
1629    Value *LoadPtr = I->second;
1630
1631    Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1632                                        LI->getAlignment(),
1633                                        UnavailablePred->getTerminator());
1634
1635    // Transfer the old load's TBAA tag to the new load.
1636    if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa))
1637      NewLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1638
1639    // Transfer DebugLoc.
1640    NewLoad->setDebugLoc(LI->getDebugLoc());
1641
1642    // Add the newly created load.
1643    ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
1644                                                        NewLoad));
1645    MD->invalidateCachedPointerInfo(LoadPtr);
1646    DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
1647  }
1648
1649  // Perform PHI construction.
1650  Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1651  LI->replaceAllUsesWith(V);
1652  if (isa<PHINode>(V))
1653    V->takeName(LI);
1654  if (V->getType()->getScalarType()->isPointerTy())
1655    MD->invalidateCachedPointerInfo(V);
1656  markInstructionForDeletion(LI);
1657  ++NumPRELoad;
1658  return true;
1659}
1660
1661/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1662/// non-local by performing PHI construction.
1663bool GVN::processNonLocalLoad(LoadInst *LI) {
1664  // Step 1: Find the non-local dependencies of the load.
1665  LoadDepVect Deps;
1666  AliasAnalysis::Location Loc = VN.getAliasAnalysis()->getLocation(LI);
1667  MD->getNonLocalPointerDependency(Loc, true, LI->getParent(), Deps);
1668
1669  // If we had to process more than one hundred blocks to find the
1670  // dependencies, this load isn't worth worrying about.  Optimizing
1671  // it will be too expensive.
1672  unsigned NumDeps = Deps.size();
1673  if (NumDeps > 100)
1674    return false;
1675
1676  // If we had a phi translation failure, we'll have a single entry which is a
1677  // clobber in the current block.  Reject this early.
1678  if (NumDeps == 1 &&
1679      !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
1680    DEBUG(
1681      dbgs() << "GVN: non-local load ";
1682      WriteAsOperand(dbgs(), LI);
1683      dbgs() << " has unknown dependencies\n";
1684    );
1685    return false;
1686  }
1687
1688  // Step 2: Analyze the availability of the load
1689  AvailValInBlkVect ValuesPerBlock;
1690  UnavailBlkVect UnavailableBlocks;
1691  AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks);
1692
1693  // If we have no predecessors that produce a known value for this load, exit
1694  // early.
1695  if (ValuesPerBlock.empty())
1696    return false;
1697
1698  // Step 3: Eliminate fully redundancy.
1699  //
1700  // If all of the instructions we depend on produce a known value for this
1701  // load, then it is fully redundant and we can use PHI insertion to compute
1702  // its value.  Insert PHIs and remove the fully redundant value now.
1703  if (UnavailableBlocks.empty()) {
1704    DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1705
1706    // Perform PHI construction.
1707    Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1708    LI->replaceAllUsesWith(V);
1709
1710    if (isa<PHINode>(V))
1711      V->takeName(LI);
1712    if (V->getType()->getScalarType()->isPointerTy())
1713      MD->invalidateCachedPointerInfo(V);
1714    markInstructionForDeletion(LI);
1715    ++NumGVNLoad;
1716    return true;
1717  }
1718
1719  // Step 4: Eliminate partial redundancy.
1720  if (!EnablePRE || !EnableLoadPRE)
1721    return false;
1722
1723  return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks);
1724}
1725
1726
1727static void patchReplacementInstruction(Instruction *I, Value *Repl) {
1728  // Patch the replacement so that it is not more restrictive than the value
1729  // being replaced.
1730  BinaryOperator *Op = dyn_cast<BinaryOperator>(I);
1731  BinaryOperator *ReplOp = dyn_cast<BinaryOperator>(Repl);
1732  if (Op && ReplOp && isa<OverflowingBinaryOperator>(Op) &&
1733      isa<OverflowingBinaryOperator>(ReplOp)) {
1734    if (ReplOp->hasNoSignedWrap() && !Op->hasNoSignedWrap())
1735      ReplOp->setHasNoSignedWrap(false);
1736    if (ReplOp->hasNoUnsignedWrap() && !Op->hasNoUnsignedWrap())
1737      ReplOp->setHasNoUnsignedWrap(false);
1738  }
1739  if (Instruction *ReplInst = dyn_cast<Instruction>(Repl)) {
1740    SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
1741    ReplInst->getAllMetadataOtherThanDebugLoc(Metadata);
1742    for (int i = 0, n = Metadata.size(); i < n; ++i) {
1743      unsigned Kind = Metadata[i].first;
1744      MDNode *IMD = I->getMetadata(Kind);
1745      MDNode *ReplMD = Metadata[i].second;
1746      switch(Kind) {
1747      default:
1748        ReplInst->setMetadata(Kind, NULL); // Remove unknown metadata
1749        break;
1750      case LLVMContext::MD_dbg:
1751        llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
1752      case LLVMContext::MD_tbaa:
1753        ReplInst->setMetadata(Kind, MDNode::getMostGenericTBAA(IMD, ReplMD));
1754        break;
1755      case LLVMContext::MD_range:
1756        ReplInst->setMetadata(Kind, MDNode::getMostGenericRange(IMD, ReplMD));
1757        break;
1758      case LLVMContext::MD_prof:
1759        llvm_unreachable("MD_prof in a non terminator instruction");
1760        break;
1761      case LLVMContext::MD_fpmath:
1762        ReplInst->setMetadata(Kind, MDNode::getMostGenericFPMath(IMD, ReplMD));
1763        break;
1764      }
1765    }
1766  }
1767}
1768
1769static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1770  patchReplacementInstruction(I, Repl);
1771  I->replaceAllUsesWith(Repl);
1772}
1773
1774/// processLoad - Attempt to eliminate a load, first by eliminating it
1775/// locally, and then attempting non-local elimination if that fails.
1776bool GVN::processLoad(LoadInst *L) {
1777  if (!MD)
1778    return false;
1779
1780  if (!L->isSimple())
1781    return false;
1782
1783  if (L->use_empty()) {
1784    markInstructionForDeletion(L);
1785    return true;
1786  }
1787
1788  // ... to a pointer that has been loaded from before...
1789  MemDepResult Dep = MD->getDependency(L);
1790
1791  // If we have a clobber and target data is around, see if this is a clobber
1792  // that we can fix up through code synthesis.
1793  if (Dep.isClobber() && TD) {
1794    // Check to see if we have something like this:
1795    //   store i32 123, i32* %P
1796    //   %A = bitcast i32* %P to i8*
1797    //   %B = gep i8* %A, i32 1
1798    //   %C = load i8* %B
1799    //
1800    // We could do that by recognizing if the clobber instructions are obviously
1801    // a common base + constant offset, and if the previous store (or memset)
1802    // completely covers this load.  This sort of thing can happen in bitfield
1803    // access code.
1804    Value *AvailVal = 0;
1805    if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
1806      int Offset = AnalyzeLoadFromClobberingStore(L->getType(),
1807                                                  L->getPointerOperand(),
1808                                                  DepSI, *TD);
1809      if (Offset != -1)
1810        AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
1811                                        L->getType(), L, *TD);
1812    }
1813
1814    // Check to see if we have something like this:
1815    //    load i32* P
1816    //    load i8* (P+1)
1817    // if we have this, replace the later with an extraction from the former.
1818    if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
1819      // If this is a clobber and L is the first instruction in its block, then
1820      // we have the first instruction in the entry block.
1821      if (DepLI == L)
1822        return false;
1823
1824      int Offset = AnalyzeLoadFromClobberingLoad(L->getType(),
1825                                                 L->getPointerOperand(),
1826                                                 DepLI, *TD);
1827      if (Offset != -1)
1828        AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
1829    }
1830
1831    // If the clobbering value is a memset/memcpy/memmove, see if we can forward
1832    // a value on from it.
1833    if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
1834      int Offset = AnalyzeLoadFromClobberingMemInst(L->getType(),
1835                                                    L->getPointerOperand(),
1836                                                    DepMI, *TD);
1837      if (Offset != -1)
1838        AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, *TD);
1839    }
1840
1841    if (AvailVal) {
1842      DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
1843            << *AvailVal << '\n' << *L << "\n\n\n");
1844
1845      // Replace the load!
1846      L->replaceAllUsesWith(AvailVal);
1847      if (AvailVal->getType()->getScalarType()->isPointerTy())
1848        MD->invalidateCachedPointerInfo(AvailVal);
1849      markInstructionForDeletion(L);
1850      ++NumGVNLoad;
1851      return true;
1852    }
1853  }
1854
1855  // If the value isn't available, don't do anything!
1856  if (Dep.isClobber()) {
1857    DEBUG(
1858      // fast print dep, using operator<< on instruction is too slow.
1859      dbgs() << "GVN: load ";
1860      WriteAsOperand(dbgs(), L);
1861      Instruction *I = Dep.getInst();
1862      dbgs() << " is clobbered by " << *I << '\n';
1863    );
1864    return false;
1865  }
1866
1867  // If it is defined in another block, try harder.
1868  if (Dep.isNonLocal())
1869    return processNonLocalLoad(L);
1870
1871  if (!Dep.isDef()) {
1872    DEBUG(
1873      // fast print dep, using operator<< on instruction is too slow.
1874      dbgs() << "GVN: load ";
1875      WriteAsOperand(dbgs(), L);
1876      dbgs() << " has unknown dependence\n";
1877    );
1878    return false;
1879  }
1880
1881  Instruction *DepInst = Dep.getInst();
1882  if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1883    Value *StoredVal = DepSI->getValueOperand();
1884
1885    // The store and load are to a must-aliased pointer, but they may not
1886    // actually have the same type.  See if we know how to reuse the stored
1887    // value (depending on its type).
1888    if (StoredVal->getType() != L->getType()) {
1889      if (TD) {
1890        StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1891                                                   L, *TD);
1892        if (StoredVal == 0)
1893          return false;
1894
1895        DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1896                     << '\n' << *L << "\n\n\n");
1897      }
1898      else
1899        return false;
1900    }
1901
1902    // Remove it!
1903    L->replaceAllUsesWith(StoredVal);
1904    if (StoredVal->getType()->getScalarType()->isPointerTy())
1905      MD->invalidateCachedPointerInfo(StoredVal);
1906    markInstructionForDeletion(L);
1907    ++NumGVNLoad;
1908    return true;
1909  }
1910
1911  if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1912    Value *AvailableVal = DepLI;
1913
1914    // The loads are of a must-aliased pointer, but they may not actually have
1915    // the same type.  See if we know how to reuse the previously loaded value
1916    // (depending on its type).
1917    if (DepLI->getType() != L->getType()) {
1918      if (TD) {
1919        AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(),
1920                                                      L, *TD);
1921        if (AvailableVal == 0)
1922          return false;
1923
1924        DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1925                     << "\n" << *L << "\n\n\n");
1926      }
1927      else
1928        return false;
1929    }
1930
1931    // Remove it!
1932    patchAndReplaceAllUsesWith(L, AvailableVal);
1933    if (DepLI->getType()->getScalarType()->isPointerTy())
1934      MD->invalidateCachedPointerInfo(DepLI);
1935    markInstructionForDeletion(L);
1936    ++NumGVNLoad;
1937    return true;
1938  }
1939
1940  // If this load really doesn't depend on anything, then we must be loading an
1941  // undef value.  This can happen when loading for a fresh allocation with no
1942  // intervening stores, for example.
1943  if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1944    L->replaceAllUsesWith(UndefValue::get(L->getType()));
1945    markInstructionForDeletion(L);
1946    ++NumGVNLoad;
1947    return true;
1948  }
1949
1950  // If this load occurs either right after a lifetime begin,
1951  // then the loaded value is undefined.
1952  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
1953    if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
1954      L->replaceAllUsesWith(UndefValue::get(L->getType()));
1955      markInstructionForDeletion(L);
1956      ++NumGVNLoad;
1957      return true;
1958    }
1959  }
1960
1961  return false;
1962}
1963
1964// findLeader - In order to find a leader for a given value number at a
1965// specific basic block, we first obtain the list of all Values for that number,
1966// and then scan the list to find one whose block dominates the block in
1967// question.  This is fast because dominator tree queries consist of only
1968// a few comparisons of DFS numbers.
1969Value *GVN::findLeader(const BasicBlock *BB, uint32_t num) {
1970  LeaderTableEntry Vals = LeaderTable[num];
1971  if (!Vals.Val) return 0;
1972
1973  Value *Val = 0;
1974  if (DT->dominates(Vals.BB, BB)) {
1975    Val = Vals.Val;
1976    if (isa<Constant>(Val)) return Val;
1977  }
1978
1979  LeaderTableEntry* Next = Vals.Next;
1980  while (Next) {
1981    if (DT->dominates(Next->BB, BB)) {
1982      if (isa<Constant>(Next->Val)) return Next->Val;
1983      if (!Val) Val = Next->Val;
1984    }
1985
1986    Next = Next->Next;
1987  }
1988
1989  return Val;
1990}
1991
1992/// replaceAllDominatedUsesWith - Replace all uses of 'From' with 'To' if the
1993/// use is dominated by the given basic block.  Returns the number of uses that
1994/// were replaced.
1995unsigned GVN::replaceAllDominatedUsesWith(Value *From, Value *To,
1996                                          const BasicBlockEdge &Root) {
1997  unsigned Count = 0;
1998  for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1999       UI != UE; ) {
2000    Use &U = (UI++).getUse();
2001
2002    if (DT->dominates(Root, U)) {
2003      U.set(To);
2004      ++Count;
2005    }
2006  }
2007  return Count;
2008}
2009
2010/// isOnlyReachableViaThisEdge - There is an edge from 'Src' to 'Dst'.  Return
2011/// true if every path from the entry block to 'Dst' passes via this edge.  In
2012/// particular 'Dst' must not be reachable via another edge from 'Src'.
2013static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E,
2014                                       DominatorTree *DT) {
2015  // While in theory it is interesting to consider the case in which Dst has
2016  // more than one predecessor, because Dst might be part of a loop which is
2017  // only reachable from Src, in practice it is pointless since at the time
2018  // GVN runs all such loops have preheaders, which means that Dst will have
2019  // been changed to have only one predecessor, namely Src.
2020  const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
2021  const BasicBlock *Src = E.getStart();
2022  assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
2023  (void)Src;
2024  return Pred != 0;
2025}
2026
2027/// propagateEquality - The given values are known to be equal in every block
2028/// dominated by 'Root'.  Exploit this, for example by replacing 'LHS' with
2029/// 'RHS' everywhere in the scope.  Returns whether a change was made.
2030bool GVN::propagateEquality(Value *LHS, Value *RHS,
2031                            const BasicBlockEdge &Root) {
2032  SmallVector<std::pair<Value*, Value*>, 4> Worklist;
2033  Worklist.push_back(std::make_pair(LHS, RHS));
2034  bool Changed = false;
2035  // For speed, compute a conservative fast approximation to
2036  // DT->dominates(Root, Root.getEnd());
2037  bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT);
2038
2039  while (!Worklist.empty()) {
2040    std::pair<Value*, Value*> Item = Worklist.pop_back_val();
2041    LHS = Item.first; RHS = Item.second;
2042
2043    if (LHS == RHS) continue;
2044    assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
2045
2046    // Don't try to propagate equalities between constants.
2047    if (isa<Constant>(LHS) && isa<Constant>(RHS)) continue;
2048
2049    // Prefer a constant on the right-hand side, or an Argument if no constants.
2050    if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
2051      std::swap(LHS, RHS);
2052    assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
2053
2054    // If there is no obvious reason to prefer the left-hand side over the right-
2055    // hand side, ensure the longest lived term is on the right-hand side, so the
2056    // shortest lived term will be replaced by the longest lived.  This tends to
2057    // expose more simplifications.
2058    uint32_t LVN = VN.lookup_or_add(LHS);
2059    if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
2060        (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
2061      // Move the 'oldest' value to the right-hand side, using the value number as
2062      // a proxy for age.
2063      uint32_t RVN = VN.lookup_or_add(RHS);
2064      if (LVN < RVN) {
2065        std::swap(LHS, RHS);
2066        LVN = RVN;
2067      }
2068    }
2069
2070    // If value numbering later sees that an instruction in the scope is equal
2071    // to 'LHS' then ensure it will be turned into 'RHS'.  In order to preserve
2072    // the invariant that instructions only occur in the leader table for their
2073    // own value number (this is used by removeFromLeaderTable), do not do this
2074    // if RHS is an instruction (if an instruction in the scope is morphed into
2075    // LHS then it will be turned into RHS by the next GVN iteration anyway, so
2076    // using the leader table is about compiling faster, not optimizing better).
2077    // The leader table only tracks basic blocks, not edges. Only add to if we
2078    // have the simple case where the edge dominates the end.
2079    if (RootDominatesEnd && !isa<Instruction>(RHS))
2080      addToLeaderTable(LVN, RHS, Root.getEnd());
2081
2082    // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope.  As
2083    // LHS always has at least one use that is not dominated by Root, this will
2084    // never do anything if LHS has only one use.
2085    if (!LHS->hasOneUse()) {
2086      unsigned NumReplacements = replaceAllDominatedUsesWith(LHS, RHS, Root);
2087      Changed |= NumReplacements > 0;
2088      NumGVNEqProp += NumReplacements;
2089    }
2090
2091    // Now try to deduce additional equalities from this one.  For example, if the
2092    // known equality was "(A != B)" == "false" then it follows that A and B are
2093    // equal in the scope.  Only boolean equalities with an explicit true or false
2094    // RHS are currently supported.
2095    if (!RHS->getType()->isIntegerTy(1))
2096      // Not a boolean equality - bail out.
2097      continue;
2098    ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
2099    if (!CI)
2100      // RHS neither 'true' nor 'false' - bail out.
2101      continue;
2102    // Whether RHS equals 'true'.  Otherwise it equals 'false'.
2103    bool isKnownTrue = CI->isAllOnesValue();
2104    bool isKnownFalse = !isKnownTrue;
2105
2106    // If "A && B" is known true then both A and B are known true.  If "A || B"
2107    // is known false then both A and B are known false.
2108    Value *A, *B;
2109    if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
2110        (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
2111      Worklist.push_back(std::make_pair(A, RHS));
2112      Worklist.push_back(std::make_pair(B, RHS));
2113      continue;
2114    }
2115
2116    // If we are propagating an equality like "(A == B)" == "true" then also
2117    // propagate the equality A == B.  When propagating a comparison such as
2118    // "(A >= B)" == "true", replace all instances of "A < B" with "false".
2119    if (ICmpInst *Cmp = dyn_cast<ICmpInst>(LHS)) {
2120      Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
2121
2122      // If "A == B" is known true, or "A != B" is known false, then replace
2123      // A with B everywhere in the scope.
2124      if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
2125          (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE))
2126        Worklist.push_back(std::make_pair(Op0, Op1));
2127
2128      // If "A >= B" is known true, replace "A < B" with false everywhere.
2129      CmpInst::Predicate NotPred = Cmp->getInversePredicate();
2130      Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
2131      // Since we don't have the instruction "A < B" immediately to hand, work out
2132      // the value number that it would have and use that to find an appropriate
2133      // instruction (if any).
2134      uint32_t NextNum = VN.getNextUnusedValueNumber();
2135      uint32_t Num = VN.lookup_or_add_cmp(Cmp->getOpcode(), NotPred, Op0, Op1);
2136      // If the number we were assigned was brand new then there is no point in
2137      // looking for an instruction realizing it: there cannot be one!
2138      if (Num < NextNum) {
2139        Value *NotCmp = findLeader(Root.getEnd(), Num);
2140        if (NotCmp && isa<Instruction>(NotCmp)) {
2141          unsigned NumReplacements =
2142            replaceAllDominatedUsesWith(NotCmp, NotVal, Root);
2143          Changed |= NumReplacements > 0;
2144          NumGVNEqProp += NumReplacements;
2145        }
2146      }
2147      // Ensure that any instruction in scope that gets the "A < B" value number
2148      // is replaced with false.
2149      // The leader table only tracks basic blocks, not edges. Only add to if we
2150      // have the simple case where the edge dominates the end.
2151      if (RootDominatesEnd)
2152        addToLeaderTable(Num, NotVal, Root.getEnd());
2153
2154      continue;
2155    }
2156  }
2157
2158  return Changed;
2159}
2160
2161/// processInstruction - When calculating availability, handle an instruction
2162/// by inserting it into the appropriate sets
2163bool GVN::processInstruction(Instruction *I) {
2164  // Ignore dbg info intrinsics.
2165  if (isa<DbgInfoIntrinsic>(I))
2166    return false;
2167
2168  // If the instruction can be easily simplified then do so now in preference
2169  // to value numbering it.  Value numbering often exposes redundancies, for
2170  // example if it determines that %y is equal to %x then the instruction
2171  // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
2172  if (Value *V = SimplifyInstruction(I, TD, TLI, DT)) {
2173    I->replaceAllUsesWith(V);
2174    if (MD && V->getType()->getScalarType()->isPointerTy())
2175      MD->invalidateCachedPointerInfo(V);
2176    markInstructionForDeletion(I);
2177    ++NumGVNSimpl;
2178    return true;
2179  }
2180
2181  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2182    if (processLoad(LI))
2183      return true;
2184
2185    unsigned Num = VN.lookup_or_add(LI);
2186    addToLeaderTable(Num, LI, LI->getParent());
2187    return false;
2188  }
2189
2190  // For conditional branches, we can perform simple conditional propagation on
2191  // the condition value itself.
2192  if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
2193    if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
2194      return false;
2195
2196    Value *BranchCond = BI->getCondition();
2197
2198    BasicBlock *TrueSucc = BI->getSuccessor(0);
2199    BasicBlock *FalseSucc = BI->getSuccessor(1);
2200    // Avoid multiple edges early.
2201    if (TrueSucc == FalseSucc)
2202      return false;
2203
2204    BasicBlock *Parent = BI->getParent();
2205    bool Changed = false;
2206
2207    Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext());
2208    BasicBlockEdge TrueE(Parent, TrueSucc);
2209    Changed |= propagateEquality(BranchCond, TrueVal, TrueE);
2210
2211    Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext());
2212    BasicBlockEdge FalseE(Parent, FalseSucc);
2213    Changed |= propagateEquality(BranchCond, FalseVal, FalseE);
2214
2215    return Changed;
2216  }
2217
2218  // For switches, propagate the case values into the case destinations.
2219  if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
2220    Value *SwitchCond = SI->getCondition();
2221    BasicBlock *Parent = SI->getParent();
2222    bool Changed = false;
2223
2224    // Remember how many outgoing edges there are to every successor.
2225    SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2226    for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i)
2227      ++SwitchEdges[SI->getSuccessor(i)];
2228
2229    for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2230         i != e; ++i) {
2231      BasicBlock *Dst = i.getCaseSuccessor();
2232      // If there is only a single edge, propagate the case value into it.
2233      if (SwitchEdges.lookup(Dst) == 1) {
2234        BasicBlockEdge E(Parent, Dst);
2235        Changed |= propagateEquality(SwitchCond, i.getCaseValue(), E);
2236      }
2237    }
2238    return Changed;
2239  }
2240
2241  // Instructions with void type don't return a value, so there's
2242  // no point in trying to find redundancies in them.
2243  if (I->getType()->isVoidTy()) return false;
2244
2245  uint32_t NextNum = VN.getNextUnusedValueNumber();
2246  unsigned Num = VN.lookup_or_add(I);
2247
2248  // Allocations are always uniquely numbered, so we can save time and memory
2249  // by fast failing them.
2250  if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
2251    addToLeaderTable(Num, I, I->getParent());
2252    return false;
2253  }
2254
2255  // If the number we were assigned was a brand new VN, then we don't
2256  // need to do a lookup to see if the number already exists
2257  // somewhere in the domtree: it can't!
2258  if (Num >= NextNum) {
2259    addToLeaderTable(Num, I, I->getParent());
2260    return false;
2261  }
2262
2263  // Perform fast-path value-number based elimination of values inherited from
2264  // dominators.
2265  Value *repl = findLeader(I->getParent(), Num);
2266  if (repl == 0) {
2267    // Failure, just remember this instance for future use.
2268    addToLeaderTable(Num, I, I->getParent());
2269    return false;
2270  }
2271
2272  // Remove it!
2273  patchAndReplaceAllUsesWith(I, repl);
2274  if (MD && repl->getType()->getScalarType()->isPointerTy())
2275    MD->invalidateCachedPointerInfo(repl);
2276  markInstructionForDeletion(I);
2277  return true;
2278}
2279
2280/// runOnFunction - This is the main transformation entry point for a function.
2281bool GVN::runOnFunction(Function& F) {
2282  if (!NoLoads)
2283    MD = &getAnalysis<MemoryDependenceAnalysis>();
2284  DT = &getAnalysis<DominatorTree>();
2285  TD = getAnalysisIfAvailable<DataLayout>();
2286  TLI = &getAnalysis<TargetLibraryInfo>();
2287  VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
2288  VN.setMemDep(MD);
2289  VN.setDomTree(DT);
2290
2291  bool Changed = false;
2292  bool ShouldContinue = true;
2293
2294  // Merge unconditional branches, allowing PRE to catch more
2295  // optimization opportunities.
2296  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
2297    BasicBlock *BB = FI++;
2298
2299    bool removedBlock = MergeBlockIntoPredecessor(BB, this);
2300    if (removedBlock) ++NumGVNBlocks;
2301
2302    Changed |= removedBlock;
2303  }
2304
2305  unsigned Iteration = 0;
2306  while (ShouldContinue) {
2307    DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
2308    ShouldContinue = iterateOnFunction(F);
2309    Changed |= ShouldContinue;
2310    ++Iteration;
2311  }
2312
2313  if (EnablePRE) {
2314    bool PREChanged = true;
2315    while (PREChanged) {
2316      PREChanged = performPRE(F);
2317      Changed |= PREChanged;
2318    }
2319  }
2320
2321  // FIXME: Should perform GVN again after PRE does something.  PRE can move
2322  // computations into blocks where they become fully redundant.  Note that
2323  // we can't do this until PRE's critical edge splitting updates memdep.
2324  // Actually, when this happens, we should just fully integrate PRE into GVN.
2325
2326  cleanupGlobalSets();
2327
2328  return Changed;
2329}
2330
2331
2332bool GVN::processBlock(BasicBlock *BB) {
2333  // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
2334  // (and incrementing BI before processing an instruction).
2335  assert(InstrsToErase.empty() &&
2336         "We expect InstrsToErase to be empty across iterations");
2337  bool ChangedFunction = false;
2338
2339  for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
2340       BI != BE;) {
2341    ChangedFunction |= processInstruction(BI);
2342    if (InstrsToErase.empty()) {
2343      ++BI;
2344      continue;
2345    }
2346
2347    // If we need some instructions deleted, do it now.
2348    NumGVNInstr += InstrsToErase.size();
2349
2350    // Avoid iterator invalidation.
2351    bool AtStart = BI == BB->begin();
2352    if (!AtStart)
2353      --BI;
2354
2355    for (SmallVector<Instruction*, 4>::iterator I = InstrsToErase.begin(),
2356         E = InstrsToErase.end(); I != E; ++I) {
2357      DEBUG(dbgs() << "GVN removed: " << **I << '\n');
2358      if (MD) MD->removeInstruction(*I);
2359      DEBUG(verifyRemoved(*I));
2360      (*I)->eraseFromParent();
2361    }
2362    InstrsToErase.clear();
2363
2364    if (AtStart)
2365      BI = BB->begin();
2366    else
2367      ++BI;
2368  }
2369
2370  return ChangedFunction;
2371}
2372
2373/// performPRE - Perform a purely local form of PRE that looks for diamond
2374/// control flow patterns and attempts to perform simple PRE at the join point.
2375bool GVN::performPRE(Function &F) {
2376  bool Changed = false;
2377  SmallVector<std::pair<Value*, BasicBlock*>, 8> predMap;
2378  for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
2379       DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
2380    BasicBlock *CurrentBlock = *DI;
2381
2382    // Nothing to PRE in the entry block.
2383    if (CurrentBlock == &F.getEntryBlock()) continue;
2384
2385    // Don't perform PRE on a landing pad.
2386    if (CurrentBlock->isLandingPad()) continue;
2387
2388    for (BasicBlock::iterator BI = CurrentBlock->begin(),
2389         BE = CurrentBlock->end(); BI != BE; ) {
2390      Instruction *CurInst = BI++;
2391
2392      if (isa<AllocaInst>(CurInst) ||
2393          isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
2394          CurInst->getType()->isVoidTy() ||
2395          CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
2396          isa<DbgInfoIntrinsic>(CurInst))
2397        continue;
2398
2399      // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
2400      // sinking the compare again, and it would force the code generator to
2401      // move the i1 from processor flags or predicate registers into a general
2402      // purpose register.
2403      if (isa<CmpInst>(CurInst))
2404        continue;
2405
2406      // We don't currently value number ANY inline asm calls.
2407      if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
2408        if (CallI->isInlineAsm())
2409          continue;
2410
2411      uint32_t ValNo = VN.lookup(CurInst);
2412
2413      // Look for the predecessors for PRE opportunities.  We're
2414      // only trying to solve the basic diamond case, where
2415      // a value is computed in the successor and one predecessor,
2416      // but not the other.  We also explicitly disallow cases
2417      // where the successor is its own predecessor, because they're
2418      // more complicated to get right.
2419      unsigned NumWith = 0;
2420      unsigned NumWithout = 0;
2421      BasicBlock *PREPred = 0;
2422      predMap.clear();
2423
2424      for (pred_iterator PI = pred_begin(CurrentBlock),
2425           PE = pred_end(CurrentBlock); PI != PE; ++PI) {
2426        BasicBlock *P = *PI;
2427        // We're not interested in PRE where the block is its
2428        // own predecessor, or in blocks with predecessors
2429        // that are not reachable.
2430        if (P == CurrentBlock) {
2431          NumWithout = 2;
2432          break;
2433        } else if (!DT->isReachableFromEntry(P))  {
2434          NumWithout = 2;
2435          break;
2436        }
2437
2438        Value* predV = findLeader(P, ValNo);
2439        if (predV == 0) {
2440          predMap.push_back(std::make_pair(static_cast<Value *>(0), P));
2441          PREPred = P;
2442          ++NumWithout;
2443        } else if (predV == CurInst) {
2444          /* CurInst dominates this predecessor. */
2445          NumWithout = 2;
2446          break;
2447        } else {
2448          predMap.push_back(std::make_pair(predV, P));
2449          ++NumWith;
2450        }
2451      }
2452
2453      // Don't do PRE when it might increase code size, i.e. when
2454      // we would need to insert instructions in more than one pred.
2455      if (NumWithout != 1 || NumWith == 0)
2456        continue;
2457
2458      // Don't do PRE across indirect branch.
2459      if (isa<IndirectBrInst>(PREPred->getTerminator()))
2460        continue;
2461
2462      // We can't do PRE safely on a critical edge, so instead we schedule
2463      // the edge to be split and perform the PRE the next time we iterate
2464      // on the function.
2465      unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
2466      if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2467        toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
2468        continue;
2469      }
2470
2471      // Instantiate the expression in the predecessor that lacked it.
2472      // Because we are going top-down through the block, all value numbers
2473      // will be available in the predecessor by the time we need them.  Any
2474      // that weren't originally present will have been instantiated earlier
2475      // in this loop.
2476      Instruction *PREInstr = CurInst->clone();
2477      bool success = true;
2478      for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
2479        Value *Op = PREInstr->getOperand(i);
2480        if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2481          continue;
2482
2483        if (Value *V = findLeader(PREPred, VN.lookup(Op))) {
2484          PREInstr->setOperand(i, V);
2485        } else {
2486          success = false;
2487          break;
2488        }
2489      }
2490
2491      // Fail out if we encounter an operand that is not available in
2492      // the PRE predecessor.  This is typically because of loads which
2493      // are not value numbered precisely.
2494      if (!success) {
2495        DEBUG(verifyRemoved(PREInstr));
2496        delete PREInstr;
2497        continue;
2498      }
2499
2500      PREInstr->insertBefore(PREPred->getTerminator());
2501      PREInstr->setName(CurInst->getName() + ".pre");
2502      PREInstr->setDebugLoc(CurInst->getDebugLoc());
2503      VN.add(PREInstr, ValNo);
2504      ++NumGVNPRE;
2505
2506      // Update the availability map to include the new instruction.
2507      addToLeaderTable(ValNo, PREInstr, PREPred);
2508
2509      // Create a PHI to make the value available in this block.
2510      PHINode* Phi = PHINode::Create(CurInst->getType(), predMap.size(),
2511                                     CurInst->getName() + ".pre-phi",
2512                                     CurrentBlock->begin());
2513      for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
2514        if (Value *V = predMap[i].first)
2515          Phi->addIncoming(V, predMap[i].second);
2516        else
2517          Phi->addIncoming(PREInstr, PREPred);
2518      }
2519
2520      VN.add(Phi, ValNo);
2521      addToLeaderTable(ValNo, Phi, CurrentBlock);
2522      Phi->setDebugLoc(CurInst->getDebugLoc());
2523      CurInst->replaceAllUsesWith(Phi);
2524      if (Phi->getType()->getScalarType()->isPointerTy()) {
2525        // Because we have added a PHI-use of the pointer value, it has now
2526        // "escaped" from alias analysis' perspective.  We need to inform
2527        // AA of this.
2528        for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee;
2529             ++ii) {
2530          unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
2531          VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(jj));
2532        }
2533
2534        if (MD)
2535          MD->invalidateCachedPointerInfo(Phi);
2536      }
2537      VN.erase(CurInst);
2538      removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
2539
2540      DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
2541      if (MD) MD->removeInstruction(CurInst);
2542      DEBUG(verifyRemoved(CurInst));
2543      CurInst->eraseFromParent();
2544      Changed = true;
2545    }
2546  }
2547
2548  if (splitCriticalEdges())
2549    Changed = true;
2550
2551  return Changed;
2552}
2553
2554/// Split the critical edge connecting the given two blocks, and return
2555/// the block inserted to the critical edge.
2556BasicBlock *GVN::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
2557  BasicBlock *BB = SplitCriticalEdge(Pred, Succ, this);
2558  if (MD)
2559    MD->invalidateCachedPredecessors();
2560  return BB;
2561}
2562
2563/// splitCriticalEdges - Split critical edges found during the previous
2564/// iteration that may enable further optimization.
2565bool GVN::splitCriticalEdges() {
2566  if (toSplit.empty())
2567    return false;
2568  do {
2569    std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
2570    SplitCriticalEdge(Edge.first, Edge.second, this);
2571  } while (!toSplit.empty());
2572  if (MD) MD->invalidateCachedPredecessors();
2573  return true;
2574}
2575
2576/// iterateOnFunction - Executes one iteration of GVN
2577bool GVN::iterateOnFunction(Function &F) {
2578  cleanupGlobalSets();
2579
2580  // Top-down walk of the dominator tree
2581  bool Changed = false;
2582#if 0
2583  // Needed for value numbering with phi construction to work.
2584  ReversePostOrderTraversal<Function*> RPOT(&F);
2585  for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2586       RE = RPOT.end(); RI != RE; ++RI)
2587    Changed |= processBlock(*RI);
2588#else
2589  // Save the blocks this function have before transformation begins. GVN may
2590  // split critical edge, and hence may invalidate the RPO/DT iterator.
2591  //
2592  std::vector<BasicBlock *> BBVect;
2593  BBVect.reserve(256);
2594  for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2595       DE = df_end(DT->getRootNode()); DI != DE; ++DI)
2596    BBVect.push_back(DI->getBlock());
2597
2598  for (std::vector<BasicBlock *>::iterator I = BBVect.begin(), E = BBVect.end();
2599       I != E; I++)
2600    Changed |= processBlock(*I);
2601#endif
2602
2603  return Changed;
2604}
2605
2606void GVN::cleanupGlobalSets() {
2607  VN.clear();
2608  LeaderTable.clear();
2609  TableAllocator.Reset();
2610}
2611
2612/// verifyRemoved - Verify that the specified instruction does not occur in our
2613/// internal data structures.
2614void GVN::verifyRemoved(const Instruction *Inst) const {
2615  VN.verifyRemoved(Inst);
2616
2617  // Walk through the value number scope to make sure the instruction isn't
2618  // ferreted away in it.
2619  for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
2620       I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
2621    const LeaderTableEntry *Node = &I->second;
2622    assert(Node->Val != Inst && "Inst still in value numbering scope!");
2623
2624    while (Node->Next) {
2625      Node = Node->Next;
2626      assert(Node->Val != Inst && "Inst still in value numbering scope!");
2627    }
2628  }
2629}
2630