move some functions, add a comment.
[oota-llvm.git] / lib / Transforms / Scalar / PredicateSimplifier.cpp
index 4ee19f76c98914acb85eac00bdbee1d0c0ba3eff..b8ac1828db8c5ebc2a6bf72387195b50b51eca65 100644 (file)
 #include "llvm/Analysis/Dominators.h"
 #include "llvm/Assembly/Writer.h"
 #include "llvm/Support/CFG.h"
-#include "llvm/Support/Compiler.h"
 #include "llvm/Support/ConstantRange.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/InstVisitor.h"
+#include "llvm/Support/raw_ostream.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Transforms/Utils/Local.h"
 #include <algorithm>
@@ -276,21 +276,21 @@ namespace {
 
 #ifndef NDEBUG
     virtual void dump() const {
-      dump(*cerr.stream());
+      dump(errs());
     }
 
-    void dump(std::ostream &os) const {
+    void dump(raw_ostream &os) const {
       os << "Predicate simplifier DomTreeDFS: \n";
       dump(Entry, 0, os);
       os << "\n\n";
     }
 
-    void dump(Node *N, int depth, std::ostream &os) const {
+    void dump(Node *N, int depth, raw_ostream &os) const {
       ++depth;
       for (int i = 0; i < depth; ++i) { os << " "; }
       os << "[" << depth << "] ";
 
-      os << N->getBlock()->getName() << " (" << N->getDFSNumIn()
+      os << N->getBlock()->getNameStr() << " (" << N->getDFSNumIn()
          << ", " << N->getDFSNumOut() << ")\n";
 
       for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I)
@@ -376,12 +376,12 @@ namespace {
   }
 
   /// ValueNumbering stores the scope-specific value numbers for a given Value.
-  class VISIBILITY_HIDDEN ValueNumbering {
+  class ValueNumbering {
 
     /// VNPair is a tuple of {Value, index number, DomTreeDFS::Node}. It
     /// includes the comparison operators necessary to allow you to store it
     /// in a sorted vector.
-    class VISIBILITY_HIDDEN VNPair {
+    class VNPair {
     public:
       Value *V;
       unsigned index;
@@ -424,10 +424,10 @@ namespace {
 #ifndef NDEBUG
     virtual ~ValueNumbering() {}
     virtual void dump() {
-      dump(*cerr.stream());
+      print(errs());
     }
 
-    void dump(std::ostream &os) {
+    void print(raw_ostream &os) {
       for (unsigned i = 1; i <= Values.size(); ++i) {
         os << i << " = ";
         WriteAsOperand(os, Values[i-1]);
@@ -468,8 +468,8 @@ namespace {
     /// valueNumber - finds the value number for V under the Subtree. If
     /// there is no value number, returns zero.
     unsigned valueNumber(Value *V, DomTreeDFS::Node *Subtree) {
-      if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V))
-          || V->getType() == Type::VoidTy) return 0;
+      if (!(isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) || 
+          V->getType() == Type::getVoidTy(V->getContext())) return 0;
 
       VNMapType::iterator E = VNMap.end();
       VNPair pair(V, 0, Subtree);
@@ -495,7 +495,8 @@ namespace {
     unsigned newVN(Value *V) {
       assert((isa<Constant>(V) || isa<Argument>(V) || isa<Instruction>(V)) &&
              "Bad Value for value numbering.");
-      assert(V->getType() != Type::VoidTy && "Won't value number a void value");
+      assert(V->getType() != Type::getVoidTy(V->getContext()) &&
+             "Won't value number a void value");
 
       Values.push_back(V);
 
@@ -590,7 +591,7 @@ namespace {
   ///
   /// The InequalityGraph class may invalidate Node*s after any mutator call.
   /// @brief The InequalityGraph stores the relationships between values.
-  class VISIBILITY_HIDDEN InequalityGraph {
+  class InequalityGraph {
     ValueNumbering &VN;
     DomTreeDFS::Node *TreeRoot;
 
@@ -606,7 +607,7 @@ namespace {
     /// and contains a pointer to the other end. The edge contains a lattice
     /// value specifying the relationship and an DomTreeDFS::Node specifying
     /// the root in the dominator tree to which this edge applies.
-    class VISIBILITY_HIDDEN Edge {
+    class Edge {
     public:
       Edge(unsigned T, LatticeVal V, DomTreeDFS::Node *ST)
         : To(T), LV(V), Subtree(ST) {}
@@ -637,7 +638,7 @@ namespace {
     /// for the node, as well as the relationships with the neighbours.
     ///
     /// @brief A single node in the InequalityGraph.
-    class VISIBILITY_HIDDEN Node {
+    class Node {
       friend class InequalityGraph;
 
       typedef SmallVector<Edge, 4> RelationsType;
@@ -654,10 +655,10 @@ namespace {
 #ifndef NDEBUG
       virtual ~Node() {}
       virtual void dump() const {
-        dump(*cerr.stream());
+        dump(errs());
       }
     private:
-      void dump(std::ostream &os) const {
+      void dump(raw_ostream &os) const {
         static const std::string names[32] =
           { "000000", "000001", "000002", "000003", "000004", "000005",
             "000006", "000007", "000008", "000009", "     >", "    >=",
@@ -885,10 +886,10 @@ namespace {
 #ifndef NDEBUG
     virtual ~InequalityGraph() {}
     virtual void dump() {
-      dump(*cerr.stream());
+      dump(errs());
     }
 
-    void dump(std::ostream &os) {
+    void dump(raw_ostream &os) {
       for (unsigned i = 1; i <= Nodes.size(); ++i) {
         os << i << " = {";
         node(i)->dump(os);
@@ -902,12 +903,12 @@ namespace {
 
   /// ValueRanges tracks the known integer ranges and anti-ranges of the nodes
   /// in the InequalityGraph.
-  class VISIBILITY_HIDDEN ValueRanges {
+  class ValueRanges {
     ValueNumbering &VN;
     TargetData *TD;
     LLVMContext *Context;
 
-    class VISIBILITY_HIDDEN ScopedRange {
+    class ScopedRange {
       typedef std::vector<std::pair<DomTreeDFS::Node *, ConstantRange> >
               RangeListType;
       RangeListType RangeList;
@@ -921,10 +922,10 @@ namespace {
 #ifndef NDEBUG
       virtual ~ScopedRange() {}
       virtual void dump() const {
-        dump(*cerr.stream());
+        dump(errs());
       }
 
-      void dump(std::ostream &os) const {
+      void dump(raw_ostream &os) const {
         os << "{";
         for (const_iterator I = begin(), E = end(); I != E; ++I) {
           os << &I->second << " (" << I->first->getDFSNumIn() << "), ";
@@ -1033,10 +1034,10 @@ namespace {
     virtual ~ValueRanges() {}
 
     virtual void dump() const {
-      dump(*cerr.stream());
+      dump(errs());
     }
 
-    void dump(std::ostream &os) const {
+    void dump(raw_ostream &os) const {
       for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
         os << (i+1) << " = ";
         Ranges[i].dump(os);
@@ -1169,7 +1170,8 @@ namespace {
         Value *V = VN.value(n); // XXX: redesign worklist.
         const Type *Ty = V->getType();
         if (Ty->isInteger()) {
-          addToWorklist(V, Context->getConstantInt(*I), ICmpInst::ICMP_EQ, VRP);
+          addToWorklist(V, ConstantInt::get(*Context, *I),
+                        ICmpInst::ICMP_EQ, VRP);
           return;
         } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
           assert(*I == 0 && "Pointer is null but not zero?");
@@ -1267,7 +1269,7 @@ namespace {
   /// another discovered to be unreachable. This is used to cull the graph when
   /// analyzing instructions, and to mark blocks with the "unreachable"
   /// terminator instruction after the function has executed.
-  class VISIBILITY_HIDDEN UnreachableBlocks {
+  class UnreachableBlocks {
   private:
     std::vector<BasicBlock *> DeadBlocks;
 
@@ -1297,7 +1299,7 @@ namespace {
            E = DeadBlocks.end(); I != E; ++I) {
         BasicBlock *BB = *I;
 
-        DOUT << "unreachable block: " << BB->getName() << "\n";
+        DEBUG(errs() << "unreachable block: " << BB->getName() << "\n");
 
         for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
              SI != SE; ++SI) {
@@ -1308,7 +1310,7 @@ namespace {
         TerminatorInst *TI = BB->getTerminator();
         TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
         TI->eraseFromParent();
-        new UnreachableInst(BB);
+        new UnreachableInst(BB->getContext(), BB);
         ++NumBlocks;
         modified = true;
       }
@@ -1321,7 +1323,7 @@ namespace {
   /// variables, and forwards changes along to the InequalityGraph. It
   /// also maintains the correct choice for "canonical" in the IG.
   /// @brief VRPSolver calculates inferences from a new relationship.
-  class VISIBILITY_HIDDEN VRPSolver {
+  class VRPSolver {
   private:
     friend class ValueRanges;
 
@@ -1382,11 +1384,13 @@ namespace {
     }
 
     bool makeEqual(Value *V1, Value *V2) {
-      DOUT << "makeEqual(" << *V1 << ", " << *V2 << ")\n";
-      DOUT << "context is ";
-      if (TopInst) DOUT << "I: " << *TopInst << "\n";
-      else DOUT << "BB: " << TopBB->getName()
-                << "(" << Top->getDFSNumIn() << ")\n";
+      DEBUG(errs() << "makeEqual(" << *V1 << ", " << *V2 << ")\n");
+      DEBUG(errs() << "context is ");
+      DEBUG(if (TopInst) 
+              errs() << "I: " << *TopInst << "\n";
+            else 
+              errs() << "BB: " << TopBB->getName()
+                     << "(" << Top->getDFSNumIn() << ")\n");
 
       assert(V1->getType() == V2->getType() &&
              "Can't make two values with different types equal.");
@@ -1486,8 +1490,8 @@ namespace {
             ToNotify.push_back(I);
           }
 
-          DOUT << "Simply removing " << *I2
-               << ", replacing with " << *V1 << "\n";
+          DEBUG(errs() << "Simply removing " << *I2
+                       << ", replacing with " << *V1 << "\n");
           I2->replaceAllUsesWith(V1);
           // leave it dead; it'll get erased later.
           ++NumInstruction;
@@ -1518,8 +1522,8 @@ namespace {
 
         // If that killed the instruction, stop here.
         if (I2 && isInstructionTriviallyDead(I2)) {
-          DOUT << "Killed all uses of " << *I2
-               << ", replacing with " << *V1 << "\n";
+          DEBUG(errs() << "Killed all uses of " << *I2
+                       << ", replacing with " << *V1 << "\n");
           continue;
         }
 
@@ -1690,8 +1694,8 @@ namespace {
     bool isRelatedBy(Value *V1, Value *V2, ICmpInst::Predicate Pred) const {
       if (Constant *C1 = dyn_cast<Constant>(V1))
         if (Constant *C2 = dyn_cast<Constant>(V2))
-          return Context->getConstantExprCompare(Pred, C1, C2) ==
-                 Context->getTrue();
+          return ConstantExpr::getCompare(Pred, C1, C2) ==
+                 ConstantInt::getTrue(*Context);
 
       unsigned n1 = VN.valueNumber(V1, Top);
       unsigned n2 = VN.valueNumber(V2, Top);
@@ -1725,10 +1729,12 @@ namespace {
     /// add - adds a new property to the work queue
     void add(Value *V1, Value *V2, ICmpInst::Predicate Pred,
              Instruction *I = NULL) {
-      DOUT << "adding " << *V1 << " " << Pred << " " << *V2;
-      if (I) DOUT << " context: " << *I;
-      else DOUT << " default context (" << Top->getDFSNumIn() << ")";
-      DOUT << "\n";
+      DEBUG(errs() << "adding " << *V1 << " " << Pred << " " << *V2);
+      if (I)
+        DEBUG(errs() << " context: " << *I);
+      else 
+        DEBUG(errs() << " default context (" << Top->getDFSNumIn() << ")");
+      DEBUG(errs() << "\n");
 
       assert(V1->getType() == V2->getType() &&
              "Can't relate two values with different types.");
@@ -1757,7 +1763,7 @@ namespace {
         switch (BO->getOpcode()) {
           case Instruction::And: {
             // "and i32 %a, %b" EQ -1 then %a EQ -1 and %b EQ -1
-            ConstantInt *CI = cast<ConstantInt>(Context->getAllOnesValue(Ty));
+            ConstantInt *CI = cast<ConstantInt>(Constant::getAllOnesValue(Ty));
             if (Canonical == CI) {
               add(CI, Op0, ICmpInst::ICMP_EQ, NewContext);
               add(CI, Op1, ICmpInst::ICMP_EQ, NewContext);
@@ -1765,7 +1771,7 @@ namespace {
           } break;
           case Instruction::Or: {
             // "or i32 %a, %b" EQ 0 then %a EQ 0 and %b EQ 0
-            Constant *Zero = Context->getNullValue(Ty);
+            Constant *Zero = Constant::getNullValue(Ty);
             if (Canonical == Zero) {
               add(Zero, Op0, ICmpInst::ICMP_EQ, NewContext);
               add(Zero, Op1, ICmpInst::ICMP_EQ, NewContext);
@@ -1783,16 +1789,16 @@ namespace {
             if (ConstantInt *CI = dyn_cast<ConstantInt>(Canonical)) {
               if (ConstantInt *Arg = dyn_cast<ConstantInt>(LHS)) {
                 add(RHS,
-                    Context->getConstantInt(CI->getValue() ^ Arg->getValue()),
+                  ConstantInt::get(*Context, CI->getValue() ^ Arg->getValue()),
                     ICmpInst::ICMP_EQ, NewContext);
               }
             }
             if (Canonical == LHS) {
               if (isa<ConstantInt>(Canonical))
-                add(RHS, Context->getNullValue(Ty), ICmpInst::ICMP_EQ,
+                add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_EQ,
                     NewContext);
             } else if (isRelatedBy(LHS, Canonical, ICmpInst::ICMP_NE)) {
-              add(RHS, Context->getNullValue(Ty), ICmpInst::ICMP_NE,
+              add(RHS, Constant::getNullValue(Ty), ICmpInst::ICMP_NE,
                   NewContext);
             }
           } break;
@@ -1803,10 +1809,10 @@ namespace {
         // "icmp ult i32 %a, %y" EQ true then %a u< y
         // etc.
 
-        if (Canonical == Context->getTrue()) {
+        if (Canonical == ConstantInt::getTrue(*Context)) {
           add(IC->getOperand(0), IC->getOperand(1), IC->getPredicate(),
               NewContext);
-        } else if (Canonical == Context->getFalse()) {
+        } else if (Canonical == ConstantInt::getFalse(*Context)) {
           add(IC->getOperand(0), IC->getOperand(1),
               ICmpInst::getInversePredicate(IC->getPredicate()), NewContext);
         }
@@ -1822,11 +1828,11 @@ namespace {
         if (isRelatedBy(True, False, ICmpInst::ICMP_NE)) {
           if (Canonical == VN.canonicalize(True, Top) ||
               isRelatedBy(Canonical, False, ICmpInst::ICMP_NE))
-            add(SI->getCondition(), Context->getTrue(),
+            add(SI->getCondition(), ConstantInt::getTrue(*Context),
                 ICmpInst::ICMP_EQ, NewContext);
           else if (Canonical == VN.canonicalize(False, Top) ||
                    isRelatedBy(Canonical, True, ICmpInst::ICMP_NE))
-            add(SI->getCondition(), Context->getFalse(),
+            add(SI->getCondition(), ConstantInt::getFalse(*Context),
                 ICmpInst::ICMP_EQ, NewContext);
         }
       } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
@@ -1837,10 +1843,10 @@ namespace {
         }
         // TODO: The GEPI indices are all zero. Copy from definition to operand,
         // jumping the type plane as needed.
-        if (isRelatedBy(GEPI, Context->getNullValue(GEPI->getType()),
+        if (isRelatedBy(GEPI, Constant::getNullValue(GEPI->getType()),
                         ICmpInst::ICMP_NE)) {
           Value *Ptr = GEPI->getPointerOperand();
-          add(Ptr, Context->getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
+          add(Ptr, Constant::getNullValue(Ptr->getType()), ICmpInst::ICMP_NE,
               NewContext);
         }
       } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
@@ -1894,9 +1900,9 @@ namespace {
         const Type *Ty = BO->getType();
         assert(!Ty->isFPOrFPVector() && "Float in work queue!");
 
-        Constant *Zero = Context->getNullValue(Ty);
-        Constant *One = Context->getConstantInt(Ty, 1);
-        ConstantInt *AllOnes = cast<ConstantInt>(Context->getAllOnesValue(Ty));
+        Constant *Zero = Constant::getNullValue(Ty);
+        Constant *One = ConstantInt::get(Ty, 1);
+        ConstantInt *AllOnes = cast<ConstantInt>(Constant::getAllOnesValue(Ty));
 
         switch (Opcode) {
           default: break;
@@ -2050,9 +2056,9 @@ namespace {
 
         ICmpInst::Predicate Pred = IC->getPredicate();
         if (isRelatedBy(Op0, Op1, Pred))
-          add(IC, Context->getTrue(), ICmpInst::ICMP_EQ, NewContext);
+          add(IC, ConstantInt::getTrue(*Context), ICmpInst::ICMP_EQ, NewContext);
         else if (isRelatedBy(Op0, Op1, ICmpInst::getInversePredicate(Pred)))
-          add(IC, Context->getFalse(),
+          add(IC, ConstantInt::getFalse(*Context),
               ICmpInst::ICMP_EQ, NewContext);
 
       } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
@@ -2064,9 +2070,9 @@ namespace {
         // %b EQ %c then %a EQ %b
 
         Value *Canonical = VN.canonicalize(SI->getCondition(), Top);
-        if (Canonical == Context->getTrue()) {
+        if (Canonical == ConstantInt::getTrue(*Context)) {
           add(SI, SI->getTrueValue(), ICmpInst::ICMP_EQ, NewContext);
-        } else if (Canonical == Context->getFalse()) {
+        } else if (Canonical == ConstantInt::getFalse(*Context)) {
           add(SI, SI->getFalseValue(), ICmpInst::ICMP_EQ, NewContext);
         } else if (VN.canonicalize(SI->getTrueValue(), Top) ==
                    VN.canonicalize(SI->getFalseValue(), Top)) {
@@ -2117,9 +2123,9 @@ namespace {
         // TODO: The GEPI indices are all zero. Copy from operand to definition,
         // jumping the type plane as needed.
         Value *Ptr = GEPI->getPointerOperand();
-        if (isRelatedBy(Ptr, Context->getNullValue(Ptr->getType()),
+        if (isRelatedBy(Ptr, Constant::getNullValue(Ptr->getType()),
                         ICmpInst::ICMP_NE)) {
-          add(GEPI, Context->getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
+          add(GEPI, Constant::getNullValue(GEPI->getType()), ICmpInst::ICMP_NE,
               NewContext);
         }
       }
@@ -2127,9 +2133,9 @@ namespace {
 
     /// solve - process the work queue
     void solve() {
-      //DOUT << "WorkList entry, size: " << WorkList.size() << "\n";
+      //DEBUG(errs() << "WorkList entry, size: " << WorkList.size() << "\n");
       while (!WorkList.empty()) {
-        //DOUT << "WorkList size: " << WorkList.size() << "\n";
+        //DEBUG(errs() << "WorkList size: " << WorkList.size() << "\n");
 
         Operation &O = WorkList.front();
         TopInst = O.ContextInst;
@@ -2142,21 +2148,23 @@ namespace {
         assert(O.LHS == VN.canonicalize(O.LHS, Top) && "Canonicalize isn't.");
         assert(O.RHS == VN.canonicalize(O.RHS, Top) && "Canonicalize isn't.");
 
-        DOUT << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
-        if (O.ContextInst) DOUT << " context inst: " << *O.ContextInst;
-        else DOUT << " context block: " << O.ContextBB->getName();
-        DOUT << "\n";
+        DEBUG(errs() << "solving " << *O.LHS << " " << O.Op << " " << *O.RHS;
+              if (O.ContextInst) 
+                errs() << " context inst: " << *O.ContextInst;
+              else
+                errs() << " context block: " << O.ContextBB->getName();
+              errs() << "\n";
 
-        DEBUG(VN.dump());
-        DEBUG(IG.dump());
-        DEBUG(VR.dump());
+              VN.dump();
+              IG.dump();
+              VR.dump(););
 
         // If they're both Constant, skip it. Check for contradiction and mark
         // the BB as unreachable if so.
         if (Constant *CI_L = dyn_cast<Constant>(O.LHS)) {
           if (Constant *CI_R = dyn_cast<Constant>(O.RHS)) {
-            if (Context->getConstantExprCompare(O.Op, CI_L, CI_R) ==
-                Context->getFalse())
+            if (ConstantExpr::getCompare(O.Op, CI_L, CI_R) ==
+                ConstantInt::getFalse(*Context))
               UB.mark(TopBB);
 
             WorkList.pop_front();
@@ -2257,7 +2265,7 @@ namespace {
   /// one equivalent variable with another. It also tracks what
   /// can't be equal and will solve setcc instructions when possible.
   /// @brief Root of the predicate simplifier optimization.
-  class VISIBILITY_HIDDEN PredicateSimplifier : public FunctionPass {
+  class PredicateSimplifier : public FunctionPass {
     DomTreeDFS *DTDFS;
     bool modified;
     ValueNumbering *VN;
@@ -2277,8 +2285,6 @@ namespace {
     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.addRequiredID(BreakCriticalEdgesID);
       AU.addRequired<DominatorTree>();
-      AU.addRequired<TargetData>();
-      AU.addPreserved<TargetData>();
     }
 
   private:
@@ -2288,7 +2294,7 @@ namespace {
     /// PredicateSimplifier::proceedToSuccessor(s) interface to enter the
     /// basic block.
     /// @brief Performs abstract execution of the program.
-    class VISIBILITY_HIDDEN Forwards : public InstVisitor<Forwards> {
+    class Forwards : public InstVisitor<Forwards> {
       friend class InstVisitor<Forwards>;
       PredicateSimplifier *PS;
       DomTreeDFS::Node *DTNode;
@@ -2335,8 +2341,8 @@ namespace {
     // Visits each instruction in the basic block.
     void visitBasicBlock(DomTreeDFS::Node *Node) {
       BasicBlock *BB = Node->getBlock();
-      DOUT << "Entering Basic Block: " << BB->getName()
-           << " (" << Node->getDFSNumIn() << ")\n";
+      DEBUG(errs() << "Entering Basic Block: " << BB->getName()
+            << " (" << Node->getDFSNumIn() << ")\n");
       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
         visitInstruction(I++, Node);
       }
@@ -2344,7 +2350,7 @@ namespace {
 
     // Tries to simplify each Instruction and add new properties.
     void visitInstruction(Instruction *I, DomTreeDFS::Node *DT) {
-      DOUT << "Considering instruction " << *I << "\n";
+      DEBUG(errs() << "Considering instruction " << *I << "\n");
       DEBUG(VN->dump());
       DEBUG(IG->dump());
       DEBUG(VR->dump());
@@ -2367,7 +2373,7 @@ namespace {
       if (V != I) {
         modified = true;
         ++NumInstruction;
-        DOUT << "Removing " << *I << ", replacing with " << *V << "\n";
+        DEBUG(errs() << "Removing " << *I << ", replacing with " << *V << "\n");
         if (unsigned n = VN->valueNumber(I, DTDFS->getRootNode()))
           if (VN->value(n) == I) IG->remove(n);
         VN->remove(I);
@@ -2384,28 +2390,34 @@ namespace {
         if (V != Oper) {
           modified = true;
           ++NumVarsReplaced;
-          DOUT << "Resolving " << *I;
+          DEBUG(errs() << "Resolving " << *I);
           I->setOperand(i, V);
-          DOUT << " into " << *I;
+          DEBUG(errs() << " into " << *I);
         }
       }
 #endif
 
       std::string name = I->getParent()->getName();
-      DOUT << "push (%" << name << ")\n";
+      DEBUG(errs() << "push (%" << name << ")\n");
       Forwards visit(this, DT);
       visit.visit(*I);
-      DOUT << "pop (%" << name << ")\n";
+      DEBUG(errs() << "pop (%" << name << ")\n");
     }
   };
 
   bool PredicateSimplifier::runOnFunction(Function &F) {
     DominatorTree *DT = &getAnalysis<DominatorTree>();
     DTDFS = new DomTreeDFS(DT);
-    TargetData *TD = &getAnalysis<TargetData>();
+    TargetData *TD = getAnalysisIfAvailable<TargetData>();
+
+    // FIXME: PredicateSimplifier should still be able to do basic
+    // optimizations without TargetData. But for now, just exit if
+    // it's not available.
+    if (!TD) return false;
+
     Context = &F.getContext();
 
-    DOUT << "Entering Function: " << F.getName() << "\n";
+    DEBUG(errs() << "Entering Function: " << F.getName() << "\n");
 
     modified = false;
     DomTreeDFS::Node *Root = DTDFS->getRootNode();
@@ -2454,21 +2466,23 @@ namespace {
     for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
          I != E; ++I) {
       BasicBlock *Dest = (*I)->getBlock();
-      DOUT << "Branch thinking about %" << Dest->getName()
-           << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n";
+      DEBUG(errs() << "Branch thinking about %" << Dest->getName()
+            << "(" << PS->DTDFS->getNodeForBlock(Dest)->getDFSNumIn() << ")\n");
 
       if (Dest == TrueDest) {
-        DOUT << "(" << DTNode->getBlock()->getName() << ") true set:\n";
+        DEBUG(errs() << "(" << DTNode->getBlock()->getName() 
+              << ") true set:\n");
         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
-        VRP.add(Context->getTrue(), Condition, ICmpInst::ICMP_EQ);
+        VRP.add(ConstantInt::getTrue(*Context), Condition, ICmpInst::ICMP_EQ);
         VRP.solve();
         DEBUG(VN.dump());
         DEBUG(IG.dump());
         DEBUG(VR.dump());
       } else if (Dest == FalseDest) {
-        DOUT << "(" << DTNode->getBlock()->getName() << ") false set:\n";
+        DEBUG(errs() << "(" << DTNode->getBlock()->getName() 
+              << ") false set:\n");
         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, Dest);
-        VRP.add(Context->getFalse(), Condition, ICmpInst::ICMP_EQ);
+        VRP.add(ConstantInt::getFalse(*Context), Condition, ICmpInst::ICMP_EQ);
         VRP.solve();
         DEBUG(VN.dump());
         DEBUG(IG.dump());
@@ -2488,8 +2502,8 @@ namespace {
     for (DomTreeDFS::Node::iterator I = DTNode->begin(), E = DTNode->end();
          I != E; ++I) {
       BasicBlock *BB = (*I)->getBlock();
-      DOUT << "Switch thinking about BB %" << BB->getName()
-           << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n";
+      DEBUG(errs() << "Switch thinking about BB %" << BB->getName()
+            << "(" << PS->DTDFS->getNodeForBlock(BB)->getDFSNumIn() << ")\n");
 
       VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, BB);
       if (BB == SI.getDefaultDest()) {
@@ -2507,7 +2521,7 @@ namespace {
 
   void PredicateSimplifier::Forwards::visitAllocaInst(AllocaInst &AI) {
     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &AI);
-    VRP.add(AI.getContext().getNullValue(AI.getType()),
+    VRP.add(Constant::getNullValue(AI.getType()),
             &AI, ICmpInst::ICMP_NE);
     VRP.solve();
   }
@@ -2518,7 +2532,7 @@ namespace {
     if (isa<Constant>(Ptr)) return;
 
     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &LI);
-    VRP.add(LI.getContext().getNullValue(Ptr->getType()),
+    VRP.add(Constant::getNullValue(Ptr->getType()),
             Ptr, ICmpInst::ICMP_NE);
     VRP.solve();
   }
@@ -2528,30 +2542,30 @@ namespace {
     if (isa<Constant>(Ptr)) return;
 
     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
-    VRP.add(SI.getContext().getNullValue(Ptr->getType()),
+    VRP.add(Constant::getNullValue(Ptr->getType()),
             Ptr, ICmpInst::ICMP_NE);
     VRP.solve();
   }
 
   void PredicateSimplifier::Forwards::visitSExtInst(SExtInst &SI) {
     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &SI);
-    LLVMContext *Context = &SI.getContext();
+    LLVMContext &Context = SI.getContext();
     uint32_t SrcBitWidth = cast<IntegerType>(SI.getSrcTy())->getBitWidth();
     uint32_t DstBitWidth = cast<IntegerType>(SI.getDestTy())->getBitWidth();
     APInt Min(APInt::getHighBitsSet(DstBitWidth, DstBitWidth-SrcBitWidth+1));
     APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth-1));
-    VRP.add(Context->getConstantInt(Min), &SI, ICmpInst::ICMP_SLE);
-    VRP.add(Context->getConstantInt(Max), &SI, ICmpInst::ICMP_SGE);
+    VRP.add(ConstantInt::get(Context, Min), &SI, ICmpInst::ICMP_SLE);
+    VRP.add(ConstantInt::get(Context, Max), &SI, ICmpInst::ICMP_SGE);
     VRP.solve();
   }
 
   void PredicateSimplifier::Forwards::visitZExtInst(ZExtInst &ZI) {
     VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &ZI);
-    LLVMContext *Context = &ZI.getContext();
+    LLVMContext &Context = ZI.getContext();
     uint32_t SrcBitWidth = cast<IntegerType>(ZI.getSrcTy())->getBitWidth();
     uint32_t DstBitWidth = cast<IntegerType>(ZI.getDestTy())->getBitWidth();
     APInt Max(APInt::getLowBitsSet(DstBitWidth, SrcBitWidth));
-    VRP.add(Context->getConstantInt(Max), &ZI, ICmpInst::ICMP_UGE);
+    VRP.add(ConstantInt::get(Context, Max), &ZI, ICmpInst::ICMP_UGE);
     VRP.solve();
   }
 
@@ -2566,7 +2580,7 @@ namespace {
       case Instruction::SDiv: {
         Value *Divisor = BO.getOperand(1);
         VRPSolver VRP(VN, IG, UB, VR, PS->DTDFS, PS->modified, &BO);
-        VRP.add(BO.getContext().getNullValue(Divisor->getType()), 
+        VRP.add(Constant::getNullValue(Divisor->getType()), 
                 Divisor, ICmpInst::ICMP_NE);
         VRP.solve();
         break;
@@ -2640,7 +2654,7 @@ namespace {
 
     Pred = IC.getPredicate();
 
-    LLVMContext *Context = &IC.getContext();
+    LLVMContext &Context = IC.getContext();
 
     if (ConstantInt *Op1 = dyn_cast<ConstantInt>(IC.getOperand(1))) {
       ConstantInt *NextVal = 0;
@@ -2649,12 +2663,12 @@ namespace {
         case ICmpInst::ICMP_SLT:
         case ICmpInst::ICMP_ULT:
           if (Op1->getValue() != 0)
-            NextVal = Context->getConstantInt(Op1->getValue()-1);
+            NextVal = ConstantInt::get(Context, Op1->getValue()-1);
          break;
         case ICmpInst::ICMP_SGT:
         case ICmpInst::ICMP_UGT:
           if (!Op1->getValue().isAllOnesValue())
-            NextVal = Context->getConstantInt(Op1->getValue()+1);
+            NextVal = ConstantInt::get(Context, Op1->getValue()+1);
          break;
       }