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