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