Expand small memmovs using inline code. Set the X86 threshold for expanding
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
index 2b119a095aa3717dd6d489f520542b3a0b456865..31cbdb9c787f46b304b02fcb5326ff05a667911f 100644 (file)
@@ -2,36 +2,23 @@
 //
 //                     The LLVM Compiler Infrastructure
 //
-// This file was developed by Nate Begeman and is distributed under the
-// University of Illinois Open Source License. See LICENSE.TXT for details.
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
 //
 //===----------------------------------------------------------------------===//
 //
 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
 // both before and after the DAG is legalized.
-//
-// FIXME: Missing folds
-// sdiv, udiv, srem, urem (X, const) where X is an integer can be expanded into
-//  a sequence of multiplies, shifts, and adds.  This should be controlled by
-//  some kind of hint from the target that int div is expensive.
-// various folds of mulh[s,u] by constants such as -1, powers of 2, etc.
-//
-// FIXME: select C, pow2, pow2 -> something smart
-// FIXME: trunc(select X, Y, Z) -> select X, trunc(Y), trunc(Z)
-// FIXME: Dead stores -> nuke
-// FIXME: shr X, (and Y,31) -> shr X, Y   (TRICKY!)
-// FIXME: mul (x, const) -> shifts + adds
-// FIXME: undef values
-// FIXME: divide by zero is currently left unfolded.  do we want to turn this
-//        into an undef?
-// FIXME: select ne (select cc, 1, 0), 0, true, false -> select cc, true, false
 // 
 //===----------------------------------------------------------------------===//
 
 #define DEBUG_TYPE "dagcombine"
 #include "llvm/CodeGen/SelectionDAG.h"
+#include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/Analysis/AliasAnalysis.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetFrameInfo.h"
 #include "llvm/Target/TargetLowering.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Target/TargetOptions.h"
@@ -42,6 +29,7 @@
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/MathExtras.h"
 #include <algorithm>
+#include <set>
 using namespace llvm;
 
 STATISTIC(NodesCombined   , "Number of dag nodes combined");
@@ -91,16 +79,13 @@ namespace {
     void AddUsersToWorkList(SDNode *N) {
       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
            UI != UE; ++UI)
-        AddToWorkList(*UI);
+        AddToWorkList(UI->getUser());
     }
 
-    /// removeFromWorkList - remove all instances of N from the worklist.
-    ///
-    void removeFromWorkList(SDNode *N) {
-      WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
-                     WorkList.end());
-    }
-    
+    /// visit - call the node-specific routine that knows how to fold each
+    /// particular type of node.
+    SDOperand visit(SDNode *N);
+
   public:
     /// AddToWorkList - Add to the work list making sure it's instance is at the
     /// the back (next to be processed.)
@@ -109,35 +94,16 @@ namespace {
       WorkList.push_back(N);
     }
 
-    SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
-                        bool AddTo = true) {
-      assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
-      ++NodesCombined;
-      DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
-      DOUT << "\nWith: "; DEBUG(To[0].Val->dump(&DAG));
-      DOUT << " and " << NumTo-1 << " other values\n";
-      std::vector<SDNode*> NowDead;
-      DAG.ReplaceAllUsesWith(N, To, &NowDead);
-      
-      if (AddTo) {
-        // Push the new nodes and any users onto the worklist
-        for (unsigned i = 0, e = NumTo; i != e; ++i) {
-          AddToWorkList(To[i].Val);
-          AddUsersToWorkList(To[i].Val);
-        }
-      }
-      
-      // Nodes can be reintroduced into the worklist.  Make sure we do not
-      // process a node that has been replaced.
-      removeFromWorkList(N);
-      for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
-        removeFromWorkList(NowDead[i]);
-      
-      // Finally, since the node is now dead, remove it from the graph.
-      DAG.DeleteNode(N);
-      return SDOperand(N, 0);
+    /// removeFromWorkList - remove all instances of N from the worklist.
+    ///
+    void removeFromWorkList(SDNode *N) {
+      WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
+                     WorkList.end());
     }
     
+    SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
+                        bool AddTo = true);
+    
     SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
       return CombineTo(N, &Res, 1, AddTo);
     }
@@ -147,63 +113,27 @@ namespace {
       SDOperand To[] = { Res0, Res1 };
       return CombineTo(N, To, 2, AddTo);
     }
+    
   private:    
     
     /// SimplifyDemandedBits - Check the specified integer node value to see if
     /// it can be simplified or if things it uses can be simplified by bit
     /// propagation.  If so, return true.
     bool SimplifyDemandedBits(SDOperand Op) {
-      TargetLowering::TargetLoweringOpt TLO(DAG);
-      uint64_t KnownZero, KnownOne;
-      uint64_t Demanded = MVT::getIntVTBitMask(Op.getValueType());
-      if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
-        return false;
-
-      // Revisit the node.
-      AddToWorkList(Op.Val);
-      
-      // Replace the old value with the new one.
-      ++NodesCombined;
-      DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
-      DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
-      DOUT << '\n';
-
-      std::vector<SDNode*> NowDead;
-      DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, NowDead);
-      
-      // Push the new node and any (possibly new) users onto the worklist.
-      AddToWorkList(TLO.New.Val);
-      AddUsersToWorkList(TLO.New.Val);
-      
-      // Nodes can end up on the worklist more than once.  Make sure we do
-      // not process a node that has been replaced.
-      for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
-        removeFromWorkList(NowDead[i]);
-      
-      // Finally, if the node is now dead, remove it from the graph.  The node
-      // may not be dead if the replacement process recursively simplified to
-      // something else needing this node.
-      if (TLO.Old.Val->use_empty()) {
-        removeFromWorkList(TLO.Old.Val);
-        
-        // If the operands of this node are only used by the node, they will now
-        // be dead.  Make sure to visit them first to delete dead nodes early.
-        for (unsigned i = 0, e = TLO.Old.Val->getNumOperands(); i != e; ++i)
-          if (TLO.Old.Val->getOperand(i).Val->hasOneUse())
-            AddToWorkList(TLO.Old.Val->getOperand(i).Val);
-        
-        DAG.DeleteNode(TLO.Old.Val);
-      }
-      return true;
+      APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
+      return SimplifyDemandedBits(Op, Demanded);
     }
 
+    bool SimplifyDemandedBits(SDOperand Op, const APInt &Demanded);
+
     bool CombineToPreIndexedLoadStore(SDNode *N);
     bool CombineToPostIndexedLoadStore(SDNode *N);
     
     
-    /// visit - call the node-specific routine that knows how to fold each
-    /// particular type of node.
-    SDOperand visit(SDNode *N);
+    /// combine - call the node-specific routine that knows how to fold each
+    /// particular type of node. If that doesn't do anything, try the
+    /// target-specific DAG combines.
+    SDOperand combine(SDNode *N);
 
     // Visitation implementation - Implement dag node combining for different
     // node types.  The semantics are as follows:
@@ -213,6 +143,7 @@ namespace {
     //   otherwise            - N should be replaced by the returned Operand.
     //
     SDOperand visitTokenFactor(SDNode *N);
+    SDOperand visitMERGE_VALUES(SDNode *N);
     SDOperand visitADD(SDNode *N);
     SDOperand visitSUB(SDNode *N);
     SDOperand visitADDC(SDNode *N);
@@ -224,6 +155,10 @@ namespace {
     SDOperand visitUREM(SDNode *N);
     SDOperand visitMULHU(SDNode *N);
     SDOperand visitMULHS(SDNode *N);
+    SDOperand visitSMUL_LOHI(SDNode *N);
+    SDOperand visitUMUL_LOHI(SDNode *N);
+    SDOperand visitSDIVREM(SDNode *N);
+    SDOperand visitUDIVREM(SDNode *N);
     SDOperand visitAND(SDNode *N);
     SDOperand visitOR(SDNode *N);
     SDOperand visitXOR(SDNode *N);
@@ -243,6 +178,7 @@ namespace {
     SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
     SDOperand visitTRUNCATE(SDNode *N);
     SDOperand visitBIT_CONVERT(SDNode *N);
+    SDOperand visitBUILD_PAIR(SDNode *N);
     SDOperand visitFADD(SDNode *N);
     SDOperand visitFSUB(SDNode *N);
     SDOperand visitFMUL(SDNode *N);
@@ -263,6 +199,7 @@ namespace {
     SDOperand visitLOAD(SDNode *N);
     SDOperand visitSTORE(SDNode *N);
     SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
+    SDOperand visitEXTRACT_VECTOR_ELT(SDNode *N);
     SDOperand visitBUILD_VECTOR(SDNode *N);
     SDOperand visitCONCAT_VECTORS(SDNode *N);
     SDOperand visitVECTOR_SHUFFLE(SDNode *N);
@@ -270,6 +207,8 @@ namespace {
     SDOperand XformToShuffleWithZero(SDNode *N);
     SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
     
+    SDOperand visitShiftByConstant(SDNode *N, unsigned Amt);
+
     bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
     SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
     SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
@@ -278,12 +217,17 @@ namespace {
                                bool NotExtCompare = false);
     SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
                             ISD::CondCode Cond, bool foldBooleans = true);
+    SDOperand SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 
+                                         unsigned HiOp);
+    SDOperand CombineConsecutiveLoads(SDNode *N, MVT::ValueType VT);
     SDOperand ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT::ValueType);
     SDOperand BuildSDIV(SDNode *N);
     SDOperand BuildUDIV(SDNode *N);
     SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
     SDOperand ReduceLoadWidth(SDNode *N);
     
+    SDOperand GetDemandedBits(SDOperand V, const APInt &Mask);
+    
     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
     /// looking for aliasing nodes and adding them to the Aliases vector.
     void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
@@ -318,6 +262,26 @@ public:
   };
 }
 
+
+namespace {
+/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
+/// nodes from the worklist.
+class VISIBILITY_HIDDEN WorkListRemover : 
+  public SelectionDAG::DAGUpdateListener {
+  DAGCombiner &DC;
+public:
+  explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
+  
+  virtual void NodeDeleted(SDNode *N) {
+    DC.removeFromWorkList(N);
+  }
+  
+  virtual void NodeUpdated(SDNode *N) {
+    // Ignore updates.
+  }
+};
+}
+
 //===----------------------------------------------------------------------===//
 //  TargetLowering::DAGCombinerInfo implementation
 //===----------------------------------------------------------------------===//
@@ -350,7 +314,12 @@ CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
 /// specified expression for the same cost as the expression itself, or 2 if we
 /// can compute the negated form more cheaply than the expression itself.
-static char isNegatibleForFree(SDOperand Op, unsigned Depth = 0) {
+static char isNegatibleForFree(SDOperand Op, bool AfterLegalize,
+                               unsigned Depth = 0) {
+  // No compile time optimizations on this type.
+  if (Op.getValueType() == MVT::ppcf128)
+    return 0;
+
   // fneg is removable even if it has multiple uses.
   if (Op.getOpcode() == ISD::FNEG) return 2;
   
@@ -363,16 +332,18 @@ static char isNegatibleForFree(SDOperand Op, unsigned Depth = 0) {
   switch (Op.getOpcode()) {
   default: return false;
   case ISD::ConstantFP:
-    return 1;
+    // Don't invert constant FP values after legalize.  The negated constant
+    // isn't necessarily legal.
+    return AfterLegalize ? 0 : 1;
   case ISD::FADD:
     // FIXME: determine better conditions for this xform.
     if (!UnsafeFPMath) return 0;
     
     // -(A+B) -> -A - B
-    if (char V = isNegatibleForFree(Op.getOperand(0), Depth+1))
+    if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
       return V;
     // -(A+B) -> -B - A
-    return isNegatibleForFree(Op.getOperand(1), Depth+1);
+    return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
   case ISD::FSUB:
     // We can't turn -(A-B) into B-A when we honor signed zeros. 
     if (!UnsafeFPMath) return 0;
@@ -385,22 +356,22 @@ static char isNegatibleForFree(SDOperand Op, unsigned Depth = 0) {
     if (HonorSignDependentRoundingFPMath()) return 0;
     
     // -(X*Y) -> (-X * Y) or (X*-Y)
-    if (char V = isNegatibleForFree(Op.getOperand(0), Depth+1))
+    if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
       return V;
       
-    return isNegatibleForFree(Op.getOperand(1), Depth+1);
+    return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
     
   case ISD::FP_EXTEND:
   case ISD::FP_ROUND:
   case ISD::FSIN:
-    return isNegatibleForFree(Op.getOperand(0), Depth+1);
+    return isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1);
   }
 }
 
 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
 /// returns the newly negated expression.
 static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
-                                      unsigned Depth = 0) {
+                                      bool AfterLegalize, unsigned Depth = 0) {
   // fneg is removable even if it has multiple uses.
   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
   
@@ -410,21 +381,25 @@ static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
   switch (Op.getOpcode()) {
   default: assert(0 && "Unknown code");
-  case ISD::ConstantFP:
-    return DAG.getConstantFP(-cast<ConstantFPSDNode>(Op)->getValue(),
-                             Op.getValueType());
+  case ISD::ConstantFP: {
+    APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
+    V.changeSign();
+    return DAG.getConstantFP(V, Op.getValueType());
+  }
   case ISD::FADD:
     // FIXME: determine better conditions for this xform.
     assert(UnsafeFPMath);
     
     // -(A+B) -> -A - B
-    if (isNegatibleForFree(Op.getOperand(0), Depth+1))
+    if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
       return DAG.getNode(ISD::FSUB, Op.getValueType(),
-                         GetNegatedExpression(Op.getOperand(0), DAG, Depth+1),
+                         GetNegatedExpression(Op.getOperand(0), DAG, 
+                                              AfterLegalize, Depth+1),
                          Op.getOperand(1));
     // -(A+B) -> -B - A
     return DAG.getNode(ISD::FSUB, Op.getValueType(),
-                       GetNegatedExpression(Op.getOperand(1), DAG, Depth+1),
+                       GetNegatedExpression(Op.getOperand(1), DAG, 
+                                            AfterLegalize, Depth+1),
                        Op.getOperand(0));
   case ISD::FSUB:
     // We can't turn -(A-B) into B-A when we honor signed zeros. 
@@ -432,7 +407,7 @@ static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
 
     // -(0-B) -> B
     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
-      if (N0CFP->getValue() == 0.0)
+      if (N0CFP->getValueAPF().isZero())
         return Op.getOperand(1);
     
     // -(A-B) -> B-A
@@ -444,21 +419,28 @@ static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
     assert(!HonorSignDependentRoundingFPMath());
     
     // -(X*Y) -> -X * Y
-    if (isNegatibleForFree(Op.getOperand(0), Depth+1))
+    if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
       return DAG.getNode(Op.getOpcode(), Op.getValueType(),
-                         GetNegatedExpression(Op.getOperand(0), DAG, Depth+1),
+                         GetNegatedExpression(Op.getOperand(0), DAG, 
+                                              AfterLegalize, Depth+1),
                          Op.getOperand(1));
       
     // -(X*Y) -> X * -Y
     return DAG.getNode(Op.getOpcode(), Op.getValueType(),
                        Op.getOperand(0),
-                       GetNegatedExpression(Op.getOperand(1), DAG, Depth+1));
+                       GetNegatedExpression(Op.getOperand(1), DAG,
+                                            AfterLegalize, Depth+1));
     
   case ISD::FP_EXTEND:
-  case ISD::FP_ROUND:
   case ISD::FSIN:
     return DAG.getNode(Op.getOpcode(), Op.getValueType(),
-                       GetNegatedExpression(Op.getOperand(0), DAG, Depth+1));
+                       GetNegatedExpression(Op.getOperand(0), DAG, 
+                                            AfterLegalize, Depth+1));
+  case ISD::FP_ROUND:
+      return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
+                         GetNegatedExpression(Op.getOperand(0), DAG, 
+                                              AfterLegalize, Depth+1),
+                         Op.getOperand(1));
   }
 }
 
@@ -479,7 +461,7 @@ static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
   if (N.getOpcode() == ISD::SELECT_CC && 
       N.getOperand(2).getOpcode() == ISD::Constant &&
       N.getOperand(3).getOpcode() == ISD::Constant &&
-      cast<ConstantSDNode>(N.getOperand(2))->getValue() == 1 &&
+      cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
     LHS = N.getOperand(0);
     RHS = N.getOperand(1);
@@ -530,6 +512,77 @@ SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
   return SDOperand();
 }
 
+SDOperand DAGCombiner::CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
+                                 bool AddTo) {
+  assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
+  ++NodesCombined;
+  DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
+  DOUT << "\nWith: "; DEBUG(To[0].Val->dump(&DAG));
+  DOUT << " and " << NumTo-1 << " other values\n";
+  WorkListRemover DeadNodes(*this);
+  DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
+  
+  if (AddTo) {
+    // Push the new nodes and any users onto the worklist
+    for (unsigned i = 0, e = NumTo; i != e; ++i) {
+      AddToWorkList(To[i].Val);
+      AddUsersToWorkList(To[i].Val);
+    }
+  }
+  
+  // Nodes can be reintroduced into the worklist.  Make sure we do not
+  // process a node that has been replaced.
+  removeFromWorkList(N);
+  
+  // Finally, since the node is now dead, remove it from the graph.
+  DAG.DeleteNode(N);
+  return SDOperand(N, 0);
+}
+
+/// SimplifyDemandedBits - Check the specified integer node value to see if
+/// it can be simplified or if things it uses can be simplified by bit
+/// propagation.  If so, return true.
+bool DAGCombiner::SimplifyDemandedBits(SDOperand Op, const APInt &Demanded) {
+  TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
+  APInt KnownZero, KnownOne;
+  if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
+    return false;
+  
+  // Revisit the node.
+  AddToWorkList(Op.Val);
+  
+  // Replace the old value with the new one.
+  ++NodesCombined;
+  DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
+  DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
+  DOUT << '\n';
+  
+  // Replace all uses.  If any nodes become isomorphic to other nodes and 
+  // are deleted, make sure to remove them from our worklist.
+  WorkListRemover DeadNodes(*this);
+  DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
+  
+  // Push the new node and any (possibly new) users onto the worklist.
+  AddToWorkList(TLO.New.Val);
+  AddUsersToWorkList(TLO.New.Val);
+  
+  // Finally, if the node is now dead, remove it from the graph.  The node
+  // may not be dead if the replacement process recursively simplified to
+  // something else needing this node.
+  if (TLO.Old.Val->use_empty()) {
+    removeFromWorkList(TLO.Old.Val);
+    
+    // If the operands of this node are only used by the node, they will now
+    // be dead.  Make sure to visit them first to delete dead nodes early.
+    for (unsigned i = 0, e = TLO.Old.Val->getNumOperands(); i != e; ++i)
+      if (TLO.Old.Val->getOperand(i).Val->hasOneUse())
+        AddToWorkList(TLO.Old.Val->getOperand(i).Val);
+    
+    DAG.DeleteNode(TLO.Old.Val);
+  }
+  return true;
+}
+
 //===----------------------------------------------------------------------===//
 //  Main DAG Combiner implementation
 //===----------------------------------------------------------------------===//
@@ -552,10 +605,6 @@ void DAGCombiner::Run(bool RunningAfterLegalize) {
   // done.  Set it to null to avoid confusion.
   DAG.setRoot(SDOperand());
   
-  /// DagCombineInfo - Expose the DAG combiner to the target combiner impls.
-  TargetLowering::DAGCombinerInfo 
-    DagCombineInfo(DAG, !RunningAfterLegalize, false, this);
-
   // while the worklist isn't empty, inspect the node on the end of it and
   // try and combine it.
   while (!WorkList.empty()) {
@@ -573,54 +622,53 @@ void DAGCombiner::Run(bool RunningAfterLegalize) {
       continue;
     }
     
-    SDOperand RV = visit(N);
+    SDOperand RV = combine(N);
     
-    // If nothing happened, try a target-specific DAG combine.
-    if (RV.Val == 0) {
-      assert(N->getOpcode() != ISD::DELETED_NODE &&
-             "Node was deleted but visit returned NULL!");
-      if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
-          TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode()))
-        RV = TLI.PerformDAGCombine(N, DagCombineInfo);
-    }
+    if (RV.Val == 0)
+      continue;
     
-    if (RV.Val) {
-      ++NodesCombined;
-      // If we get back the same node we passed in, rather than a new node or
-      // zero, we know that the node must have defined multiple values and
-      // CombineTo was used.  Since CombineTo takes care of the worklist 
-      // mechanics for us, we have no work to do in this case.
-      if (RV.Val != N) {
-        assert(N->getOpcode() != ISD::DELETED_NODE &&
-               RV.Val->getOpcode() != ISD::DELETED_NODE &&
-               "Node was deleted but visit returned new node!");
-
-        DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
-        DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
-        DOUT << '\n';
-        std::vector<SDNode*> NowDead;
-        if (N->getNumValues() == RV.Val->getNumValues())
-          DAG.ReplaceAllUsesWith(N, RV.Val, &NowDead);
-        else {
-          assert(N->getValueType(0) == RV.getValueType() && "Type mismatch");
-          SDOperand OpV = RV;
-          DAG.ReplaceAllUsesWith(N, &OpV, &NowDead);
-        }
-          
-        // Push the new node and any users onto the worklist
-        AddToWorkList(RV.Val);
-        AddUsersToWorkList(RV.Val);
-          
-        // Nodes can be reintroduced into the worklist.  Make sure we do not
-        // process a node that has been replaced.
-        removeFromWorkList(N);
-        for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
-          removeFromWorkList(NowDead[i]);
-        
-        // Finally, since the node is now dead, remove it from the graph.
-        DAG.DeleteNode(N);
-      }
+    ++NodesCombined;
+    
+    // If we get back the same node we passed in, rather than a new node or
+    // zero, we know that the node must have defined multiple values and
+    // CombineTo was used.  Since CombineTo takes care of the worklist 
+    // mechanics for us, we have no work to do in this case.
+    if (RV.Val == N)
+      continue;
+    
+    assert(N->getOpcode() != ISD::DELETED_NODE &&
+           RV.Val->getOpcode() != ISD::DELETED_NODE &&
+           "Node was deleted but visit returned new node!");
+
+    DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
+    DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
+    DOUT << '\n';
+    WorkListRemover DeadNodes(*this);
+    if (N->getNumValues() == RV.Val->getNumValues())
+      DAG.ReplaceAllUsesWith(N, RV.Val, &DeadNodes);
+    else {
+      assert(N->getValueType(0) == RV.getValueType() &&
+             N->getNumValues() == 1 && "Type mismatch");
+      SDOperand OpV = RV;
+      DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
     }
+      
+    // Push the new node and any users onto the worklist
+    AddToWorkList(RV.Val);
+    AddUsersToWorkList(RV.Val);
+    
+    // Add any uses of the old node to the worklist in case this node is the
+    // last one that uses them.  They may become dead after this node is
+    // deleted.
+    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
+      AddToWorkList(N->getOperand(i).Val);
+      
+    // Nodes can be reintroduced into the worklist.  Make sure we do not
+    // process a node that has been replaced.
+    removeFromWorkList(N);
+    
+    // Finally, since the node is now dead, remove it from the graph.
+    DAG.DeleteNode(N);
   }
   
   // If the root changed (e.g. it was a dead load, update the root).
@@ -631,6 +679,7 @@ SDOperand DAGCombiner::visit(SDNode *N) {
   switch(N->getOpcode()) {
   default: break;
   case ISD::TokenFactor:        return visitTokenFactor(N);
+  case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
   case ISD::ADD:                return visitADD(N);
   case ISD::SUB:                return visitSUB(N);
   case ISD::ADDC:               return visitADDC(N);
@@ -642,6 +691,10 @@ SDOperand DAGCombiner::visit(SDNode *N) {
   case ISD::UREM:               return visitUREM(N);
   case ISD::MULHU:              return visitMULHU(N);
   case ISD::MULHS:              return visitMULHS(N);
+  case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
+  case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
+  case ISD::SDIVREM:            return visitSDIVREM(N);
+  case ISD::UDIVREM:            return visitUDIVREM(N);
   case ISD::AND:                return visitAND(N);
   case ISD::OR:                 return visitOR(N);
   case ISD::XOR:                return visitXOR(N);
@@ -660,6 +713,7 @@ SDOperand DAGCombiner::visit(SDNode *N) {
   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
   case ISD::TRUNCATE:           return visitTRUNCATE(N);
   case ISD::BIT_CONVERT:        return visitBIT_CONVERT(N);
+  case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
   case ISD::FADD:               return visitFADD(N);
   case ISD::FSUB:               return visitFSUB(N);
   case ISD::FMUL:               return visitFMUL(N);
@@ -680,6 +734,7 @@ SDOperand DAGCombiner::visit(SDNode *N) {
   case ISD::LOAD:               return visitLOAD(N);
   case ISD::STORE:              return visitSTORE(N);
   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
+  case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
@@ -687,6 +742,46 @@ SDOperand DAGCombiner::visit(SDNode *N) {
   return SDOperand();
 }
 
+SDOperand DAGCombiner::combine(SDNode *N) {
+
+  SDOperand RV = visit(N);
+
+  // If nothing happened, try a target-specific DAG combine.
+  if (RV.Val == 0) {
+    assert(N->getOpcode() != ISD::DELETED_NODE &&
+           "Node was deleted but visit returned NULL!");
+
+    if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
+        TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
+
+      // Expose the DAG combiner to the target combiner impls.
+      TargetLowering::DAGCombinerInfo 
+        DagCombineInfo(DAG, !AfterLegalize, false, this);
+
+      RV = TLI.PerformDAGCombine(N, DagCombineInfo);
+    }
+  }
+
+  // If N is a commutative binary node, try commuting it to enable more 
+  // sdisel CSE.
+  if (RV.Val == 0 && 
+      SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
+      N->getNumValues() == 1) {
+    SDOperand N0 = N->getOperand(0);
+    SDOperand N1 = N->getOperand(1);
+    // Constant operands are canonicalized to RHS.
+    if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
+      SDOperand Ops[] = { N1, N0 };
+      SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
+                                            Ops, 2);
+      if (CSENode)
+        return SDOperand(CSENode, 0);
+    }
+  }
+
+  return RV;
+} 
+
 /// getInputChainForNode - Given a node, return its input chain if it has one,
 /// otherwise return a null sd operand.
 static SDOperand getInputChainForNode(SDNode *N) {
@@ -763,7 +858,7 @@ SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
 
   // If we've change things around then replace token factor.
   if (Changed) {
-    if (Ops.size() == 0) {
+    if (Ops.empty()) {
       // The entry token is the only possible outcome.
       Result = DAG.getEntryNode();
     } else {
@@ -778,6 +873,18 @@ SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
   return Result;
 }
 
+/// MERGE_VALUES can always be eliminated.
+SDOperand DAGCombiner::visitMERGE_VALUES(SDNode *N) {
+  WorkListRemover DeadNodes(*this);
+  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
+    DAG.ReplaceAllUsesOfValueWith(SDOperand(N, i), N->getOperand(i),
+                                  &DeadNodes);
+  removeFromWorkList(N);
+  DAG.DeleteNode(N);
+  return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
+}
+
+
 static
 SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
   MVT::ValueType VT = N0.getValueType();
@@ -822,8 +929,9 @@ SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
            RHS.getOpcode() == ISD::Constant &&
            cast<ConstantSDNode>(RHS)->isNullValue()) {
     std::swap(LHS, RHS);
-    bool isInt = MVT::isInteger(isSlctCC ? Slct.getOperand(0).getValueType()
-                                : Slct.getOperand(0).getOperand(0).getValueType());
+    SDOperand Op0 = Slct.getOperand(0);
+    bool isInt = MVT::isInteger(isSlctCC ? Op0.getValueType()
+                                : Op0.getOperand(0).getValueType());
     CC = ISD::getSetCCInverse(CC, isInt);
     DoXform = true;
     InvCC = true;
@@ -863,7 +971,7 @@ SDOperand DAGCombiner::visitADD(SDNode *N) {
     return N1;
   // fold (add c1, c2) -> c1+c2
   if (N0C && N1C)
-    return DAG.getNode(ISD::ADD, VT, N0, N1);
+    return DAG.getConstant(N0C->getAPIntValue() + N1C->getAPIntValue(), VT);
   // canonicalize constant to RHS
   if (N0C && !N1C)
     return DAG.getNode(ISD::ADD, VT, N1, N0);
@@ -874,7 +982,8 @@ SDOperand DAGCombiner::visitADD(SDNode *N) {
   if (N1C && N0.getOpcode() == ISD::SUB)
     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
       return DAG.getNode(ISD::SUB, VT,
-                         DAG.getConstant(N1C->getValue()+N0C->getValue(), VT),
+                         DAG.getConstant(N1C->getAPIntValue()+
+                                         N0C->getAPIntValue(), VT),
                          N0.getOperand(1));
   // reassociate add
   SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
@@ -897,11 +1006,11 @@ SDOperand DAGCombiner::visitADD(SDNode *N) {
   
   // fold (a+b) -> (a|b) iff a and b share no bits.
   if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
-    uint64_t LHSZero, LHSOne;
-    uint64_t RHSZero, RHSOne;
-    uint64_t Mask = MVT::getIntVTBitMask(VT);
+    APInt LHSZero, LHSOne;
+    APInt RHSZero, RHSOne;
+    APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
     DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
-    if (LHSZero) {
+    if (LHSZero.getBoolValue()) {
       DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
       
       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
@@ -958,11 +1067,11 @@ SDOperand DAGCombiner::visitADDC(SDNode *N) {
     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
   
   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
-  uint64_t LHSZero, LHSOne;
-  uint64_t RHSZero, RHSOne;
-  uint64_t Mask = MVT::getIntVTBitMask(VT);
+  APInt LHSZero, LHSOne;
+  APInt RHSZero, RHSOne;
+  APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
   DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
-  if (LHSZero) {
+  if (LHSZero.getBoolValue()) {
     DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
     
     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
@@ -1022,7 +1131,8 @@ SDOperand DAGCombiner::visitSUB(SDNode *N) {
     return DAG.getNode(ISD::SUB, VT, N0, N1);
   // fold (sub x, c) -> (add x, -c)
   if (N1C)
-    return DAG.getNode(ISD::ADD, VT, N0, DAG.getConstant(-N1C->getValue(), VT));
+    return DAG.getNode(ISD::ADD, VT, N0,
+                       DAG.getConstant(-N1C->getAPIntValue(), VT));
   // fold (A+B)-A -> B
   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
     return N0.getOperand(1);
@@ -1072,9 +1182,9 @@ SDOperand DAGCombiner::visitMUL(SDNode *N) {
   if (N1C && N1C->isAllOnesValue())
     return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
   // fold (mul x, (1 << c)) -> x << c
-  if (N1C && isPowerOf2_64(N1C->getValue()))
+  if (N1C && N1C->getAPIntValue().isPowerOf2())
     return DAG.getNode(ISD::SHL, VT, N0,
-                       DAG.getConstant(Log2_64(N1C->getValue()),
+                       DAG.getConstant(N1C->getAPIntValue().logBase2(),
                                        TLI.getShiftAmountTy()));
   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
   if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
@@ -1151,12 +1261,12 @@ SDOperand DAGCombiner::visitSDIV(SDNode *N) {
     return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
   // If we know the sign bits of both operands are zero, strength reduce to a
   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
-  uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
-  if (DAG.MaskedValueIsZero(N1, SignBit) &&
-      DAG.MaskedValueIsZero(N0, SignBit))
-    return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
+  if (!MVT::isVector(VT)) {
+    if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
+      return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
+  }
   // fold (sdiv X, pow2) -> simple ops after legalize
-  if (N1C && N1C->getValue() && !TLI.isIntDivCheap() &&
+  if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
       (isPowerOf2_64(N1C->getSignExtended()) || 
        isPowerOf2_64(-N1C->getSignExtended()))) {
     // If dividing by powers of two is cheap, then don't perform the following
@@ -1222,17 +1332,18 @@ SDOperand DAGCombiner::visitUDIV(SDNode *N) {
   if (N0C && N1C && !N1C->isNullValue())
     return DAG.getNode(ISD::UDIV, VT, N0, N1);
   // fold (udiv x, (1 << c)) -> x >>u c
-  if (N1C && isPowerOf2_64(N1C->getValue()))
+  if (N1C && N1C->getAPIntValue().isPowerOf2())
     return DAG.getNode(ISD::SRL, VT, N0, 
-                       DAG.getConstant(Log2_64(N1C->getValue()),
+                       DAG.getConstant(N1C->getAPIntValue().logBase2(),
                                        TLI.getShiftAmountTy()));
   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
   if (N1.getOpcode() == ISD::SHL) {
     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
-      if (isPowerOf2_64(SHC->getValue())) {
+      if (SHC->getAPIntValue().isPowerOf2()) {
         MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
         SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
-                                    DAG.getConstant(Log2_64(SHC->getValue()),
+                                    DAG.getConstant(SHC->getAPIntValue()
+                                                                    .logBase2(),
                                                     ADDVT));
         AddToWorkList(Add.Val);
         return DAG.getNode(ISD::SRL, VT, N0, Add);
@@ -1240,7 +1351,7 @@ SDOperand DAGCombiner::visitUDIV(SDNode *N) {
     }
   }
   // fold (udiv x, c) -> alternate
-  if (N1C && N1C->getValue() && !TLI.isIntDivCheap()) {
+  if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
     SDOperand Op = BuildUDIV(N);
     if (Op.Val) return Op;
   }
@@ -1267,20 +1378,23 @@ SDOperand DAGCombiner::visitSREM(SDNode *N) {
     return DAG.getNode(ISD::SREM, VT, N0, N1);
   // If we know the sign bits of both operands are zero, strength reduce to a
   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
-  uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
-  if (DAG.MaskedValueIsZero(N1, SignBit) &&
-      DAG.MaskedValueIsZero(N0, SignBit))
-    return DAG.getNode(ISD::UREM, VT, N0, N1);
+  if (!MVT::isVector(VT)) {
+    if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
+      return DAG.getNode(ISD::UREM, VT, N0, N1);
+  }
   
-  // Unconditionally lower X%C -> X-X/C*C.  This allows the X/C logic to hack on
-  // the remainder operation.
+  // If X/C can be simplified by the division-by-constant logic, lower
+  // X%C to the equivalent of X-X/C*C.
   if (N1C && !N1C->isNullValue()) {
     SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
-    SDOperand Mul = DAG.getNode(ISD::MUL, VT, Div, N1);
-    SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
     AddToWorkList(Div.Val);
-    AddToWorkList(Mul.Val);
-    return Sub;
+    SDOperand OptimizedDiv = combine(Div.Val);
+    if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
+      SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
+      SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
+      AddToWorkList(Mul.Val);
+      return Sub;
+    }
   }
   
   // undef % X -> 0
@@ -1304,28 +1418,34 @@ SDOperand DAGCombiner::visitUREM(SDNode *N) {
   if (N0C && N1C && !N1C->isNullValue())
     return DAG.getNode(ISD::UREM, VT, N0, N1);
   // fold (urem x, pow2) -> (and x, pow2-1)
-  if (N1C && !N1C->isNullValue() && isPowerOf2_64(N1C->getValue()))
-    return DAG.getNode(ISD::AND, VT, N0, DAG.getConstant(N1C->getValue()-1,VT));
+  if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
+    return DAG.getNode(ISD::AND, VT, N0,
+                       DAG.getConstant(N1C->getAPIntValue()-1,VT));
   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
   if (N1.getOpcode() == ISD::SHL) {
     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
-      if (isPowerOf2_64(SHC->getValue())) {
-        SDOperand Add = DAG.getNode(ISD::ADD, VT, N1,DAG.getConstant(~0ULL,VT));
+      if (SHC->getAPIntValue().isPowerOf2()) {
+        SDOperand Add =
+          DAG.getNode(ISD::ADD, VT, N1,
+                 DAG.getConstant(APInt::getAllOnesValue(MVT::getSizeInBits(VT)),
+                                 VT));
         AddToWorkList(Add.Val);
         return DAG.getNode(ISD::AND, VT, N0, Add);
       }
     }
   }
   
-  // Unconditionally lower X%C -> X-X/C*C.  This allows the X/C logic to hack on
-  // the remainder operation.
+  // If X/C can be simplified by the division-by-constant logic, lower
+  // X%C to the equivalent of X-X/C*C.
   if (N1C && !N1C->isNullValue()) {
     SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
-    SDOperand Mul = DAG.getNode(ISD::MUL, VT, Div, N1);
-    SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
-    AddToWorkList(Div.Val);
-    AddToWorkList(Mul.Val);
-    return Sub;
+    SDOperand OptimizedDiv = combine(Div.Val);
+    if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
+      SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
+      SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
+      AddToWorkList(Mul.Val);
+      return Sub;
+    }
   }
   
   // undef % X -> 0
@@ -1348,7 +1468,7 @@ SDOperand DAGCombiner::visitMULHS(SDNode *N) {
   if (N1C && N1C->isNullValue())
     return N1;
   // fold (mulhs x, 1) -> (sra x, size(x)-1)
-  if (N1C && N1C->getValue() == 1)
+  if (N1C && N1C->getAPIntValue() == 1)
     return DAG.getNode(ISD::SRA, N0.getValueType(), N0, 
                        DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
                                        TLI.getShiftAmountTy()));
@@ -1369,7 +1489,7 @@ SDOperand DAGCombiner::visitMULHU(SDNode *N) {
   if (N1C && N1C->isNullValue())
     return N1;
   // fold (mulhu x, 1) -> 0
-  if (N1C && N1C->getValue() == 1)
+  if (N1C && N1C->getAPIntValue() == 1)
     return DAG.getConstant(0, N0.getValueType());
   // fold (mulhu x, undef) -> 0
   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
@@ -1378,6 +1498,87 @@ SDOperand DAGCombiner::visitMULHU(SDNode *N) {
   return SDOperand();
 }
 
+/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
+/// compute two values. LoOp and HiOp give the opcodes for the two computations
+/// that are being performed. Return true if a simplification was made.
+///
+SDOperand DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 
+                                                  unsigned HiOp) {
+  // If the high half is not needed, just compute the low half.
+  bool HiExists = N->hasAnyUseOfValue(1);
+  if (!HiExists &&
+      (!AfterLegalize ||
+       TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
+    SDOperand Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
+                                N->getNumOperands());
+    return CombineTo(N, Res, Res);
+  }
+
+  // If the low half is not needed, just compute the high half.
+  bool LoExists = N->hasAnyUseOfValue(0);
+  if (!LoExists &&
+      (!AfterLegalize ||
+       TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
+    SDOperand Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
+                                N->getNumOperands());
+    return CombineTo(N, Res, Res);
+  }
+
+  // If both halves are used, return as it is.
+  if (LoExists && HiExists)
+    return SDOperand();
+
+  // If the two computed results can be simplified separately, separate them.
+  if (LoExists) {
+    SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
+                               N->op_begin(), N->getNumOperands());
+    AddToWorkList(Lo.Val);
+    SDOperand LoOpt = combine(Lo.Val);
+    if (LoOpt.Val && LoOpt.Val != Lo.Val &&
+        TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))
+      return CombineTo(N, LoOpt, LoOpt);
+  }
+
+  if (HiExists) {
+    SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
+                               N->op_begin(), N->getNumOperands());
+    AddToWorkList(Hi.Val);
+    SDOperand HiOpt = combine(Hi.Val);
+    if (HiOpt.Val && HiOpt != Hi &&
+        TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))
+      return CombineTo(N, HiOpt, HiOpt);
+  }
+  return SDOperand();
+}
+
+SDOperand DAGCombiner::visitSMUL_LOHI(SDNode *N) {
+  SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
+  if (Res.Val) return Res;
+
+  return SDOperand();
+}
+
+SDOperand DAGCombiner::visitUMUL_LOHI(SDNode *N) {
+  SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
+  if (Res.Val) return Res;
+
+  return SDOperand();
+}
+
+SDOperand DAGCombiner::visitSDIVREM(SDNode *N) {
+  SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
+  if (Res.Val) return Res;
+  
+  return SDOperand();
+}
+
+SDOperand DAGCombiner::visitUDIVREM(SDNode *N) {
+  SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
+  if (Res.Val) return Res;
+  
+  return SDOperand();
+}
+
 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
 /// two operands of the same opcode, try to simplify it.
 SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
@@ -1424,6 +1625,7 @@ SDOperand DAGCombiner::visitAND(SDNode *N) {
   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   MVT::ValueType VT = N1.getValueType();
+  unsigned BitWidth = MVT::getSizeInBits(VT);
   
   // fold vector ops
   if (MVT::isVector(VT)) {
@@ -1444,7 +1646,8 @@ SDOperand DAGCombiner::visitAND(SDNode *N) {
   if (N1C && N1C->isAllOnesValue())
     return N0;
   // if (and x, c) is known to be zero, return 0
-  if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
+  if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
+                                   APInt::getAllOnesValue(BitWidth)))
     return DAG.getConstant(0, VT);
   // reassociate and
   SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
@@ -1453,15 +1656,16 @@ SDOperand DAGCombiner::visitAND(SDNode *N) {
   // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
   if (N1C && N0.getOpcode() == ISD::OR)
     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
-      if ((ORI->getValue() & N1C->getValue()) == N1C->getValue())
+      if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
         return N1;
   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
-    unsigned InMask = MVT::getIntVTBitMask(N0.getOperand(0).getValueType());
-    if (DAG.MaskedValueIsZero(N0.getOperand(0),
-                              ~N1C->getValue() & InMask)) {
+    SDOperand N0Op0 = N0.getOperand(0);
+    APInt Mask = ~N1C->getAPIntValue();
+    Mask.trunc(N0Op0.getValueSizeInBits());
+    if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
       SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
-                                   N0.getOperand(0));
+                                   N0Op0);
       
       // Replace uses of the AND with uses of the Zero extend node.
       CombineTo(N, Zext);
@@ -1481,7 +1685,7 @@ SDOperand DAGCombiner::visitAND(SDNode *N) {
     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
         MVT::isInteger(LL.getValueType())) {
       // fold (X == 0) & (Y == 0) -> (X|Y == 0)
-      if (cast<ConstantSDNode>(LR)->getValue() == 0 && Op1 == ISD::SETEQ) {
+      if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
         SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
         AddToWorkList(ORNode.Val);
         return DAG.getSetCC(VT, ORNode, LR, Op1);
@@ -1526,10 +1730,12 @@ SDOperand DAGCombiner::visitAND(SDNode *N) {
   // fold (zext_inreg (extload x)) -> (zextload x)
   if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
-    MVT::ValueType EVT = LN0->getLoadedVT();
+    MVT::ValueType EVT = LN0->getMemoryVT();
     // If we zero all the possible extended bits, then we can turn this into
     // a zextload if we are running before legalize or the operation is legal.
-    if (DAG.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
+    unsigned BitWidth = N1.getValueSizeInBits();
+    if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
+                                     BitWidth - MVT::getSizeInBits(EVT))) &&
         (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
       SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
                                          LN0->getBasePtr(), LN0->getSrcValue(),
@@ -1545,10 +1751,12 @@ SDOperand DAGCombiner::visitAND(SDNode *N) {
   if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
       N0.hasOneUse()) {
     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
-    MVT::ValueType EVT = LN0->getLoadedVT();
+    MVT::ValueType EVT = LN0->getMemoryVT();
     // If we zero all the possible extended bits, then we can turn this into
     // a zextload if we are running before legalize or the operation is legal.
-    if (DAG.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
+    unsigned BitWidth = N1.getValueSizeInBits();
+    if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
+                                     BitWidth - MVT::getSizeInBits(EVT))) &&
         (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
       SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
                                          LN0->getBasePtr(), LN0->getSrcValue(),
@@ -1566,36 +1774,39 @@ SDOperand DAGCombiner::visitAND(SDNode *N) {
   if (N1C && N0.getOpcode() == ISD::LOAD) {
     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
-        LN0->getAddressingMode() == ISD::UNINDEXED &&
-        N0.hasOneUse()) {
+        LN0->isUnindexed() && N0.hasOneUse()) {
       MVT::ValueType EVT, LoadedVT;
-      if (N1C->getValue() == 255)
+      if (N1C->getAPIntValue() == 255)
         EVT = MVT::i8;
-      else if (N1C->getValue() == 65535)
+      else if (N1C->getAPIntValue() == 65535)
         EVT = MVT::i16;
-      else if (N1C->getValue() == ~0U)
+      else if (N1C->getAPIntValue() == ~0U)
         EVT = MVT::i32;
       else
         EVT = MVT::Other;
     
-      LoadedVT = LN0->getLoadedVT();
+      LoadedVT = LN0->getMemoryVT();
       if (EVT != MVT::Other && LoadedVT > EVT &&
           (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
         MVT::ValueType PtrType = N0.getOperand(1).getValueType();
         // For big endian targets, we need to add an offset to the pointer to
         // load the correct bytes.  For little endian systems, we merely need to
         // read fewer bytes from the same pointer.
-        unsigned PtrOff =
-          (MVT::getSizeInBits(LoadedVT) - MVT::getSizeInBits(EVT)) / 8;
+        unsigned LVTStoreBytes = MVT::getStoreSizeInBits(LoadedVT)/8;
+        unsigned EVTStoreBytes = MVT::getStoreSizeInBits(EVT)/8;
+        unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
+        unsigned Alignment = LN0->getAlignment();
         SDOperand NewPtr = LN0->getBasePtr();
-        if (!TLI.isLittleEndian())
+        if (TLI.isBigEndian()) {
           NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
                                DAG.getConstant(PtrOff, PtrType));
+          Alignment = MinAlign(Alignment, PtrOff);
+        }
         AddToWorkList(NewPtr.Val);
         SDOperand Load =
           DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
                          LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
-                         LN0->isVolatile(), LN0->getAlignment());
+                         LN0->isVolatile(), Alignment);
         AddToWorkList(N);
         CombineTo(N0.Val, Load, Load.getValue(1));
         return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
@@ -1613,7 +1824,6 @@ SDOperand DAGCombiner::visitOR(SDNode *N) {
   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   MVT::ValueType VT = N1.getValueType();
-  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
   
   // fold vector ops
   if (MVT::isVector(VT)) {
@@ -1637,8 +1847,7 @@ SDOperand DAGCombiner::visitOR(SDNode *N) {
   if (N1C && N1C->isAllOnesValue())
     return N1;
   // fold (or x, c) -> c iff (x & ~c) == 0
-  if (N1C && 
-      DAG.MaskedValueIsZero(N0,~N1C->getValue() & (~0ULL>>(64-OpSizeInBits))))
+  if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
     return N1;
   // reassociate or
   SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
@@ -1650,7 +1859,8 @@ SDOperand DAGCombiner::visitOR(SDNode *N) {
     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
     return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
                                                  N1),
-                       DAG.getConstant(N1C->getValue() | C1->getValue(), VT));
+                       DAG.getConstant(N1C->getAPIntValue() |
+                                       C1->getAPIntValue(), VT));
   }
   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
@@ -1661,7 +1871,7 @@ SDOperand DAGCombiner::visitOR(SDNode *N) {
         MVT::isInteger(LL.getValueType())) {
       // fold (X != 0) | (Y != 0) -> (X|Y != 0)
       // fold (X <  0) | (Y <  0) -> (X|Y < 0)
-      if (cast<ConstantSDNode>(LR)->getValue() == 0 && 
+      if (cast<ConstantSDNode>(LR)->isNullValue() && 
           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
         SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
         AddToWorkList(ORNode.Val);
@@ -1704,8 +1914,10 @@ SDOperand DAGCombiner::visitOR(SDNode *N) {
       (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
     // We can only do this xform if we know that bits from X that are set in C2
     // but not in C1 are already zero.  Likewise for Y.
-    uint64_t LHSMask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
-    uint64_t RHSMask = cast<ConstantSDNode>(N1.getOperand(1))->getValue();
+    const APInt &LHSMask =
+      cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
+    const APInt &RHSMask =
+      cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
     
     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
@@ -1801,15 +2013,15 @@ SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
     
     // If there is an AND of either shifted operand, apply it to the result.
     if (LHSMask.Val || RHSMask.Val) {
-      uint64_t Mask = MVT::getIntVTBitMask(VT);
+      APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
       
       if (LHSMask.Val) {
-        uint64_t RHSBits = (1ULL << LShVal)-1;
-        Mask &= cast<ConstantSDNode>(LHSMask)->getValue() | RHSBits;
+        APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
+        Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
       }
       if (RHSMask.Val) {
-        uint64_t LHSBits = ~((1ULL << (OpSizeInBits-RShVal))-1);
-        Mask &= cast<ConstantSDNode>(RHSMask)->getValue() | LHSBits;
+        APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
+        Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
       }
         
       Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
@@ -1829,11 +2041,12 @@ SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
       LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
     if (ConstantSDNode *SUBC = 
           dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
-      if (SUBC->getValue() == OpSizeInBits)
+      if (SUBC->getAPIntValue() == OpSizeInBits) {
         if (HasROTL)
           return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
         else
           return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
+      }
     }
   }
   
@@ -1843,11 +2056,12 @@ SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
       RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
     if (ConstantSDNode *SUBC = 
           dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
-      if (SUBC->getValue() == OpSizeInBits)
+      if (SUBC->getAPIntValue() == OpSizeInBits) {
         if (HasROTL)
           return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
         else
           return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
+      }
     }
   }
 
@@ -1867,7 +2081,7 @@ SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
       //   (rotl x, (sub 32, y))
       if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
-        if (SUBC->getValue() == OpSizeInBits) {
+        if (SUBC->getAPIntValue() == OpSizeInBits) {
           if (HasROTL)
             return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
           else
@@ -1881,7 +2095,7 @@ SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
       //   (rotr x, (sub 32, y))
       if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
-        if (SUBC->getValue() == OpSizeInBits) {
+        if (SUBC->getAPIntValue() == OpSizeInBits) {
           if (HasROTL)
             return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
           else
@@ -1909,6 +2123,9 @@ SDOperand DAGCombiner::visitXOR(SDNode *N) {
     if (FoldedVOp.Val) return FoldedVOp;
   }
   
+  // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
+  if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
+    return DAG.getConstant(0, VT);
   // fold (xor x, undef) -> undef
   if (N0.getOpcode() == ISD::UNDEF)
     return N0;
@@ -1928,7 +2145,7 @@ SDOperand DAGCombiner::visitXOR(SDNode *N) {
   if (RXOR.Val != 0)
     return RXOR;
   // fold !(x cc y) -> (x !cc y)
-  if (N1C && N1C->getValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
+  if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
     bool isInt = MVT::isInteger(LHS.getValueType());
     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
                                                isInt);
@@ -1939,8 +2156,18 @@ SDOperand DAGCombiner::visitXOR(SDNode *N) {
     assert(0 && "Unhandled SetCC Equivalent!");
     abort();
   }
+  // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
+  if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
+      N0.Val->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
+    SDOperand V = N0.getOperand(0);
+    V = DAG.getNode(ISD::XOR, V.getValueType(), V, 
+                    DAG.getConstant(1, V.getValueType()));
+    AddToWorkList(V.Val);
+    return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
+  }
+  
   // fold !(x or y) -> (!x and !y) iff x or y are setcc
-  if (N1C && N1C->getValue() == 1 && VT == MVT::i1 &&
+  if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
     SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
@@ -1969,10 +2196,12 @@ SDOperand DAGCombiner::visitXOR(SDNode *N) {
     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
     if (N00C)
       return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
-                         DAG.getConstant(N1C->getValue()^N00C->getValue(), VT));
+                         DAG.getConstant(N1C->getAPIntValue()^
+                                         N00C->getAPIntValue(), VT));
     if (N01C)
       return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
-                         DAG.getConstant(N1C->getValue()^N01C->getValue(), VT));
+                         DAG.getConstant(N1C->getAPIntValue()^
+                                         N01C->getAPIntValue(), VT));
   }
   // fold (xor x, x) -> 0
   if (N0 == N1) {
@@ -2000,6 +2229,77 @@ SDOperand DAGCombiner::visitXOR(SDNode *N) {
   return SDOperand();
 }
 
+/// visitShiftByConstant - Handle transforms common to the three shifts, when
+/// the shift amount is a constant.
+SDOperand DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
+  SDNode *LHS = N->getOperand(0).Val;
+  if (!LHS->hasOneUse()) return SDOperand();
+  
+  // We want to pull some binops through shifts, so that we have (and (shift))
+  // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
+  // thing happens with address calculations, so it's important to canonicalize
+  // it.
+  bool HighBitSet = false;  // Can we transform this if the high bit is set?
+  
+  switch (LHS->getOpcode()) {
+  default: return SDOperand();
+  case ISD::OR:
+  case ISD::XOR:
+    HighBitSet = false; // We can only transform sra if the high bit is clear.
+    break;
+  case ISD::AND:
+    HighBitSet = true;  // We can only transform sra if the high bit is set.
+    break;
+  case ISD::ADD:
+    if (N->getOpcode() != ISD::SHL) 
+      return SDOperand(); // only shl(add) not sr[al](add).
+    HighBitSet = false; // We can only transform sra if the high bit is clear.
+    break;
+  }
+  
+  // We require the RHS of the binop to be a constant as well.
+  ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
+  if (!BinOpCst) return SDOperand();
+  
+  
+  // FIXME: disable this for unless the input to the binop is a shift by a
+  // constant.  If it is not a shift, it pessimizes some common cases like:
+  //
+  //void foo(int *X, int i) { X[i & 1235] = 1; }
+  //int bar(int *X, int i) { return X[i & 255]; }
+  SDNode *BinOpLHSVal = LHS->getOperand(0).Val;
+  if ((BinOpLHSVal->getOpcode() != ISD::SHL && 
+       BinOpLHSVal->getOpcode() != ISD::SRA &&
+       BinOpLHSVal->getOpcode() != ISD::SRL) ||
+      !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
+    return SDOperand();
+  
+  MVT::ValueType VT = N->getValueType(0);
+  
+  // If this is a signed shift right, and the high bit is modified
+  // by the logical operation, do not perform the transformation.
+  // The highBitSet boolean indicates the value of the high bit of
+  // the constant which would cause it to be modified for this
+  // operation.
+  if (N->getOpcode() == ISD::SRA) {
+    bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
+    if (BinOpRHSSignSet != HighBitSet)
+      return SDOperand();
+  }
+  
+  // Fold the constants, shifting the binop RHS by the shift amount.
+  SDOperand NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
+                                 LHS->getOperand(1), N->getOperand(1));
+
+  // Create the new shift.
+  SDOperand NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
+                                   N->getOperand(1));
+
+  // Create the new binop.
+  return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
+}
+
+
 SDOperand DAGCombiner::visitSHL(SDNode *N) {
   SDOperand N0 = N->getOperand(0);
   SDOperand N1 = N->getOperand(1);
@@ -2021,7 +2321,8 @@ SDOperand DAGCombiner::visitSHL(SDNode *N) {
   if (N1C && N1C->isNullValue())
     return N0;
   // if (shl x, c) is known to be zero, return 0
-  if (DAG.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
+  if (DAG.MaskedValueIsZero(SDOperand(N, 0),
+                            APInt::getAllOnesValue(MVT::getSizeInBits(VT))))
     return DAG.getConstant(0, VT);
   if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
     return SDOperand(N, 0);
@@ -2054,7 +2355,8 @@ SDOperand DAGCombiner::visitSHL(SDNode *N) {
   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
     return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
                        DAG.getConstant(~0ULL << N1C->getValue(), VT));
-  return SDOperand();
+  
+  return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
 }
 
 SDOperand DAGCombiner::visitSRA(SDNode *N) {
@@ -2105,6 +2407,39 @@ SDOperand DAGCombiner::visitSRA(SDNode *N) {
                          DAG.getConstant(Sum, N1C->getValueType(0)));
     }
   }
+
+  // fold sra (shl X, m), result_size - n
+  // -> (sign_extend (trunc (shl X, result_size - n - m))) for
+  // result_size - n != m. 
+  // If truncate is free for the target sext(shl) is likely to result in better 
+  // code.
+  if (N0.getOpcode() == ISD::SHL) {
+    // Get the two constanst of the shifts, CN0 = m, CN = n.
+    const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
+    if (N01C && N1C) {
+      // Determine what the truncate's result bitsize and type would be.
+      unsigned VTValSize = MVT::getSizeInBits(VT);
+      MVT::ValueType TruncVT = MVT::getIntegerType(VTValSize - N1C->getValue());
+      // Determine the residual right-shift amount.
+      unsigned ShiftAmt = N1C->getValue() - N01C->getValue();
+      
+      // If the shift is not a no-op (in which case this should be just a sign 
+      // extend already), the truncated to type is legal, sign_extend is legal 
+      // on that type, and the the truncate to that type is both legal and free, 
+      // perform the transform.
+      if (ShiftAmt && 
+          TLI.isTypeLegal(TruncVT) && 
+          TLI.isOperationLegal(ISD::SIGN_EXTEND, TruncVT) &&
+          TLI.isOperationLegal(ISD::TRUNCATE, VT) &&
+          TLI.isTruncateFree(VT, TruncVT)) {
+
+          SDOperand Amt = DAG.getConstant(ShiftAmt, TLI.getShiftAmountTy());
+          SDOperand Shift = DAG.getNode(ISD::SRL, VT, N0.getOperand(0), Amt);
+          SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, TruncVT, Shift);
+          return DAG.getNode(ISD::SIGN_EXTEND, N->getValueType(0), Trunc);
+      }
+    }
+  }
   
   // Simplify, based on bits shifted out of the LHS. 
   if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
@@ -2112,9 +2447,10 @@ SDOperand DAGCombiner::visitSRA(SDNode *N) {
   
   
   // If the sign bit is known to be zero, switch this to a SRL.
-  if (DAG.MaskedValueIsZero(N0, MVT::getIntVTSignBit(VT)))
+  if (DAG.SignBitIsZero(N0))
     return DAG.getNode(ISD::SRL, VT, N0, N1);
-  return SDOperand();
+
+  return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
 }
 
 SDOperand DAGCombiner::visitSRL(SDNode *N) {
@@ -2138,7 +2474,8 @@ SDOperand DAGCombiner::visitSRL(SDNode *N) {
   if (N1C && N1C->isNullValue())
     return N0;
   // if (srl x, c) is known to be zero, return 0
-  if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0), ~0ULL >> (64-OpSizeInBits)))
+  if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
+                                   APInt::getAllOnesValue(OpSizeInBits)))
     return DAG.getConstant(0, VT);
   
   // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
@@ -2173,17 +2510,18 @@ SDOperand DAGCombiner::visitSRL(SDNode *N) {
   
   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
   if (N1C && N0.getOpcode() == ISD::CTLZ && 
-      N1C->getValue() == Log2_32(MVT::getSizeInBits(VT))) {
-    uint64_t KnownZero, KnownOne, Mask = MVT::getIntVTBitMask(VT);
+      N1C->getAPIntValue() == Log2_32(MVT::getSizeInBits(VT))) {
+    APInt KnownZero, KnownOne;
+    APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
     DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
     
     // If any of the input bits are KnownOne, then the input couldn't be all
     // zeros, thus the result of the srl will always be zero.
-    if (KnownOne) return DAG.getConstant(0, VT);
+    if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
     
     // If all of the bits input the to ctlz node are known to be zero, then
     // the result of the ctlz is "32" and the result of the shift is one.
-    uint64_t UnknownBits = ~KnownZero & Mask;
+    APInt UnknownBits = ~KnownZero & Mask;
     if (UnknownBits == 0) return DAG.getConstant(1, VT);
     
     // Otherwise, check to see if there is exactly one bit input to the ctlz.
@@ -2192,7 +2530,7 @@ SDOperand DAGCombiner::visitSRL(SDNode *N) {
       // could be set on input to the CTLZ node.  If this bit is set, the SRL
       // will return 0, if it is clear, it returns 1.  Change the CTLZ/SRL pair
       // to an SRL,XOR pair, which is likely to simplify more.
-      unsigned ShAmt = CountTrailingZeros_64(UnknownBits);
+      unsigned ShAmt = UnknownBits.countTrailingZeros();
       SDOperand Op = N0.getOperand(0);
       if (ShAmt) {
         Op = DAG.getNode(ISD::SRL, VT, Op,
@@ -2208,7 +2546,7 @@ SDOperand DAGCombiner::visitSRL(SDNode *N) {
   if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
     return SDOperand(N, 0);
   
-  return SDOperand();
+  return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
 }
 
 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
@@ -2261,11 +2599,11 @@ SDOperand DAGCombiner::visitSELECT(SDNode *N) {
   if (N0C && N0C->isNullValue())
     return N2;
   // fold select C, 1, X -> C | X
-  if (MVT::i1 == VT && N1C && N1C->getValue() == 1)
+  if (MVT::i1 == VT && N1C && N1C->getAPIntValue() == 1)
     return DAG.getNode(ISD::OR, VT, N0, N2);
   // fold select C, 0, 1 -> ~C
   if (MVT::isInteger(VT) && MVT::isInteger(VT0) &&
-      N1C && N2C && N1C->isNullValue() && N2C->getValue() == 1) {
+      N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
     SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
     if (VT == VT0)
       return XORNode;
@@ -2275,13 +2613,13 @@ SDOperand DAGCombiner::visitSELECT(SDNode *N) {
     return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
   }
   // fold select C, 0, X -> ~C & X
-  if (VT == VT0 && N1C && N1C->isNullValue()) {
+  if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
     SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
     AddToWorkList(XORNode.Val);
     return DAG.getNode(ISD::AND, VT, XORNode, N2);
   }
   // fold select C, X, 1 -> ~C | X
-  if (VT == VT0 && N2C && N2C->getValue() == 1) {
+  if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
     SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
     AddToWorkList(XORNode.Val);
     return DAG.getNode(ISD::OR, VT, XORNode, N1);
@@ -2302,7 +2640,7 @@ SDOperand DAGCombiner::visitSELECT(SDNode *N) {
     return SDOperand(N, 0);  // Don't revisit N.
   
   // fold selects based on a setcc into other things, such as min/max/abs
-  if (N0.getOpcode() == ISD::SETCC)
+  if (N0.getOpcode() == ISD::SETCC) {
     // FIXME:
     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
     // having to say they don't support SELECT_CC on every type the DAG knows
@@ -2312,6 +2650,7 @@ SDOperand DAGCombiner::visitSELECT(SDNode *N) {
                          N1, N2, N0.getOperand(2));
     else
       return SimplifySelect(N0, N1, N2);
+  }
   return SDOperand();
 }
 
@@ -2328,11 +2667,11 @@ SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
     return N2;
   
   // Determine if the condition we're dealing with is constant
-  SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
+  SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
   if (SCC.Val) AddToWorkList(SCC.Val);
 
   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
-    if (SCCC->getValue())
+    if (!SCCC->isNullValue())
       return N2;    // cond always true -> true val
     else
       return N3;    // cond always false -> false val
@@ -2357,6 +2696,74 @@ SDOperand DAGCombiner::visitSETCC(SDNode *N) {
                        cast<CondCodeSDNode>(N->getOperand(2))->get());
 }
 
+// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
+// "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
+// transformation. Returns true if extension are possible and the above
+// mentioned transformation is profitable. 
+static bool ExtendUsesToFormExtLoad(SDNode *N, SDOperand N0,
+                                    unsigned ExtOpc,
+                                    SmallVector<SDNode*, 4> &ExtendNodes,
+                                    TargetLowering &TLI) {
+  bool HasCopyToRegUses = false;
+  bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
+  for (SDNode::use_iterator UI = N0.Val->use_begin(), UE = N0.Val->use_end();
+       UI != UE; ++UI) {
+    SDNode *User = UI->getUser();
+    if (User == N)
+      continue;
+    // FIXME: Only extend SETCC N, N and SETCC N, c for now.
+    if (User->getOpcode() == ISD::SETCC) {
+      ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
+      if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
+        // Sign bits will be lost after a zext.
+        return false;
+      bool Add = false;
+      for (unsigned i = 0; i != 2; ++i) {
+        SDOperand UseOp = User->getOperand(i);
+        if (UseOp == N0)
+          continue;
+        if (!isa<ConstantSDNode>(UseOp))
+          return false;
+        Add = true;
+      }
+      if (Add)
+        ExtendNodes.push_back(User);
+    } else {
+      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
+        SDOperand UseOp = User->getOperand(i);
+        if (UseOp == N0) {
+          // If truncate from extended type to original load type is free
+          // on this target, then it's ok to extend a CopyToReg.
+          if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
+            HasCopyToRegUses = true;
+          else
+            return false;
+        }
+      }
+    }
+  }
+
+  if (HasCopyToRegUses) {
+    bool BothLiveOut = false;
+    for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
+         UI != UE; ++UI) {
+      SDNode *User = UI->getUser();
+      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
+        SDOperand UseOp = User->getOperand(i);
+        if (UseOp.Val == N && UseOp.ResNo == 0) {
+          BothLiveOut = true;
+          break;
+        }
+      }
+    }
+    if (BothLiveOut)
+      // Both unextended and extended values are live out. There had better be
+      // good a reason for the transformation.
+      return ExtendNodes.size();
+  }
+  return true;
+}
+
 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
   SDOperand N0 = N->getOperand(0);
   MVT::ValueType VT = N->getValueType(0);
@@ -2370,20 +2777,18 @@ SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
     return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
   
-  // fold (sext (truncate (load x))) -> (sext (smaller load x))
-  // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
   if (N0.getOpcode() == ISD::TRUNCATE) {
+    // fold (sext (truncate (load x))) -> (sext (smaller load x))
+    // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
     SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
     if (NarrowLoad.Val) {
       if (NarrowLoad.Val != N0.Val)
         CombineTo(N0.Val, NarrowLoad);
       return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
     }
-  }
 
-  // See if the value being truncated is already sign extended.  If so, just
-  // eliminate the trunc/sext pair.
-  if (N0.getOpcode() == ISD::TRUNCATE) {
+    // See if the value being truncated is already sign extended.  If so, just
+    // eliminate the trunc/sext pair.
     SDOperand Op = N0.getOperand(0);
     unsigned OpBits   = MVT::getSizeInBits(Op.getValueType());
     unsigned MidBits  = MVT::getSizeInBits(N0.getValueType());
@@ -2420,19 +2825,40 @@ SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
   }
   
   // fold (sext (load x)) -> (sext (truncate (sextload x)))
-  if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
+  if (ISD::isNON_EXTLoad(N0.Val) &&
       (!AfterLegalize||TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))){
-    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
-    SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
-                                       LN0->getBasePtr(), LN0->getSrcValue(),
-                                       LN0->getSrcValueOffset(),
-                                       N0.getValueType(), 
-                                       LN0->isVolatile(),
-                                       LN0->getAlignment());
-    CombineTo(N, ExtLoad);
-    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
-              ExtLoad.getValue(1));
-    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
+    bool DoXform = true;
+    SmallVector<SDNode*, 4> SetCCs;
+    if (!N0.hasOneUse())
+      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
+    if (DoXform) {
+      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
+      SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
+                                         LN0->getBasePtr(), LN0->getSrcValue(),
+                                         LN0->getSrcValueOffset(),
+                                         N0.getValueType(), 
+                                         LN0->isVolatile(),
+                                         LN0->getAlignment());
+      CombineTo(N, ExtLoad);
+      SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
+      CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
+      // Extend SetCC uses if necessary.
+      for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
+        SDNode *SetCC = SetCCs[i];
+        SmallVector<SDOperand, 4> Ops;
+        for (unsigned j = 0; j != 2; ++j) {
+          SDOperand SOp = SetCC->getOperand(j);
+          if (SOp == Trunc)
+            Ops.push_back(ExtLoad);
+          else
+            Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
+          }
+        Ops.push_back(SetCC->getOperand(2));
+        CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
+                                     &Ops[0], Ops.size()));
+      }
+      return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
+    }
   }
 
   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
@@ -2440,7 +2866,7 @@ SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
   if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
       ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
-    MVT::ValueType EVT = LN0->getLoadedVT();
+    MVT::ValueType EVT = LN0->getMemoryVT();
     if (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
       SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
                                          LN0->getBasePtr(), LN0->getSrcValue(),
@@ -2463,6 +2889,11 @@ SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
     if (SCC.Val) return SCC;
   }
   
+  // fold (sext x) -> (zext x) if the sign bit is known zero.
+  if ((!AfterLegalize || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
+      DAG.SignBitIsZero(N0))
+    return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
+  
   return SDOperand();
 }
 
@@ -2511,24 +2942,46 @@ SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
     } else if (X.getValueType() > VT) {
       X = DAG.getNode(ISD::TRUNCATE, VT, X);
     }
-    uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
+    APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
+    Mask.zext(MVT::getSizeInBits(VT));
     return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
   }
   
   // fold (zext (load x)) -> (zext (truncate (zextload x)))
-  if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
+  if (ISD::isNON_EXTLoad(N0.Val) &&
       (!AfterLegalize||TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
-    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
-    SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
-                                       LN0->getBasePtr(), LN0->getSrcValue(),
-                                       LN0->getSrcValueOffset(),
-                                       N0.getValueType(),
-                                       LN0->isVolatile(), 
-                                       LN0->getAlignment());
-    CombineTo(N, ExtLoad);
-    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
-              ExtLoad.getValue(1));
-    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
+    bool DoXform = true;
+    SmallVector<SDNode*, 4> SetCCs;
+    if (!N0.hasOneUse())
+      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
+    if (DoXform) {
+      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
+      SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
+                                         LN0->getBasePtr(), LN0->getSrcValue(),
+                                         LN0->getSrcValueOffset(),
+                                         N0.getValueType(),
+                                         LN0->isVolatile(), 
+                                         LN0->getAlignment());
+      CombineTo(N, ExtLoad);
+      SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
+      CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
+      // Extend SetCC uses if necessary.
+      for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
+        SDNode *SetCC = SetCCs[i];
+        SmallVector<SDOperand, 4> Ops;
+        for (unsigned j = 0; j != 2; ++j) {
+          SDOperand SOp = SetCC->getOperand(j);
+          if (SOp == Trunc)
+            Ops.push_back(ExtLoad);
+          else
+            Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
+          }
+        Ops.push_back(SetCC->getOperand(2));
+        CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
+                                     &Ops[0], Ops.size()));
+      }
+      return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
+    }
   }
 
   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
@@ -2536,7 +2989,7 @@ SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
   if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
       ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
-    MVT::ValueType EVT = LN0->getLoadedVT();
+    MVT::ValueType EVT = LN0->getMemoryVT();
     SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
                                        LN0->getBasePtr(), LN0->getSrcValue(),
                                        LN0->getSrcValueOffset(), EVT,
@@ -2606,7 +3059,8 @@ SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
     } else if (X.getValueType() > VT) {
       X = DAG.getNode(ISD::TRUNCATE, VT, X);
     }
-    uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
+    APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
+    Mask.zext(MVT::getSizeInBits(VT));
     return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
   }
   
@@ -2633,7 +3087,7 @@ SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
       !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
       N0.hasOneUse()) {
     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
-    MVT::ValueType EVT = LN0->getLoadedVT();
+    MVT::ValueType EVT = LN0->getMemoryVT();
     SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
                                        LN0->getChain(), LN0->getBasePtr(),
                                        LN0->getSrcValue(),
@@ -2659,6 +3113,38 @@ SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
   return SDOperand();
 }
 
+/// GetDemandedBits - See if the specified operand can be simplified with the
+/// knowledge that only the bits specified by Mask are used.  If so, return the
+/// simpler operand, otherwise return a null SDOperand.
+SDOperand DAGCombiner::GetDemandedBits(SDOperand V, const APInt &Mask) {
+  switch (V.getOpcode()) {
+  default: break;
+  case ISD::OR:
+  case ISD::XOR:
+    // If the LHS or RHS don't contribute bits to the or, drop them.
+    if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
+      return V.getOperand(1);
+    if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
+      return V.getOperand(0);
+    break;
+  case ISD::SRL:
+    // Only look at single-use SRLs.
+    if (!V.Val->hasOneUse())
+      break;
+    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
+      // See if we can recursively simplify the LHS.
+      unsigned Amt = RHSC->getValue();
+      APInt NewMask = Mask << Amt;
+      SDOperand SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
+      if (SimplifyLHS.Val) {
+        return DAG.getNode(ISD::SRL, V.getValueType(), 
+                           SimplifyLHS, V.getOperand(1));
+      }
+    }
+  }
+  return SDOperand();
+}
+
 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
 /// bits and then truncated to a narrower type and where N is a multiple
 /// of number of bits of the narrower type, transform it to a narrower load
@@ -2708,23 +3194,28 @@ SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
     MVT::ValueType PtrType = N0.getOperand(1).getValueType();
     // For big endian targets, we need to adjust the offset to the pointer to
     // load the correct bytes.
-    if (!TLI.isLittleEndian())
-      ShAmt = MVT::getSizeInBits(N0.getValueType()) - ShAmt - EVTBits;
+    if (TLI.isBigEndian()) {
+      unsigned LVTStoreBits = MVT::getStoreSizeInBits(N0.getValueType());
+      unsigned EVTStoreBits = MVT::getStoreSizeInBits(EVT);
+      ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
+    }
     uint64_t PtrOff =  ShAmt / 8;
+    unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
     SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
                                    DAG.getConstant(PtrOff, PtrType));
     AddToWorkList(NewPtr.Val);
     SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
       ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
                     LN0->getSrcValue(), LN0->getSrcValueOffset(),
-                    LN0->isVolatile(), LN0->getAlignment())
+                    LN0->isVolatile(), NewAlign)
       : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
                        LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
-                       LN0->isVolatile(), LN0->getAlignment());
+                       LN0->isVolatile(), NewAlign);
     AddToWorkList(N);
     if (CombineSRL) {
-      std::vector<SDNode*> NowDead;
-      DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1), NowDead);
+      WorkListRemover DeadNodes(*this);
+      DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
+                                    &DeadNodes);
       CombineTo(N->getOperand(0).Val, Load);
     } else
       CombineTo(N0.Val, Load, Load.getValue(1));
@@ -2746,6 +3237,7 @@ SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
   SDOperand N1 = N->getOperand(1);
   MVT::ValueType VT = N->getValueType(0);
   MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
+  unsigned VTBits = MVT::getSizeInBits(VT);
   unsigned EVTBits = MVT::getSizeInBits(EVT);
   
   // fold (sext_in_reg c1) -> c1
@@ -2763,7 +3255,7 @@ SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
   }
 
   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
-  if (DAG.MaskedValueIsZero(N0, 1ULL << (EVTBits-1)))
+  if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
     return DAG.getZeroExtendInReg(N0, EVT);
   
   // fold operands of sext_in_reg based on knowledge that the top bits are not
@@ -2794,7 +3286,7 @@ SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
   // fold (sext_inreg (extload x)) -> (sextload x)
   if (ISD::isEXTLoad(N0.Val) && 
       ISD::isUNINDEXEDLoad(N0.Val) &&
-      EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
+      EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
       (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
     SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
@@ -2809,7 +3301,7 @@ SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
   if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
       N0.hasOneUse() &&
-      EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
+      EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
       (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
     SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
@@ -2852,11 +3344,54 @@ SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
       return N0.getOperand(0);
   }
 
+  // See if we can simplify the input to this truncate through knowledge that
+  // only the low bits are being used.  For example "trunc (or (shl x, 8), y)"
+  // -> trunc y
+  SDOperand Shorter =
+    GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
+                                             MVT::getSizeInBits(VT)));
+  if (Shorter.Val)
+    return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
+
   // fold (truncate (load x)) -> (smaller load x)
   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
   return ReduceLoadWidth(N);
 }
 
+static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
+  SDOperand Elt = N->getOperand(i);
+  if (Elt.getOpcode() != ISD::MERGE_VALUES)
+    return Elt.Val;
+  return Elt.getOperand(Elt.ResNo).Val;
+}
+
+/// CombineConsecutiveLoads - build_pair (load, load) -> load
+/// if load locations are consecutive. 
+SDOperand DAGCombiner::CombineConsecutiveLoads(SDNode *N, MVT::ValueType VT) {
+  assert(N->getOpcode() == ISD::BUILD_PAIR);
+
+  SDNode *LD1 = getBuildPairElt(N, 0);
+  if (!ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
+    return SDOperand();
+  MVT::ValueType LD1VT = LD1->getValueType(0);
+  SDNode *LD2 = getBuildPairElt(N, 1);
+  const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
+  if (ISD::isNON_EXTLoad(LD2) &&
+      LD2->hasOneUse() &&
+      TLI.isConsecutiveLoad(LD2, LD1, MVT::getSizeInBits(LD1VT)/8, 1, MFI)) {
+    LoadSDNode *LD = cast<LoadSDNode>(LD1);
+    unsigned Align = LD->getAlignment();
+    unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
+      getABITypeAlignment(MVT::getTypeForValueType(VT));
+    if ((!AfterLegalize || TLI.isTypeLegal(VT)) &&
+        TLI.isOperationLegal(ISD::LOAD, VT) && NewAlign <= Align)
+      return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(),
+                         LD->getSrcValue(), LD->getSrcValueOffset(),
+                         LD->isVolatile(), Align);
+  }
+  return SDOperand();
+}
+
 SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
   SDOperand N0 = N->getOperand(0);
   MVT::ValueType VT = N->getValueType(0);
@@ -2895,9 +3430,8 @@ SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
     return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
 
   // fold (conv (load x)) -> (load (conv*)x)
-  // If the resultant load doesn't need a  higher alignment than the original!
-  if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
-      ISD::isUNINDEXEDLoad(N0.Val) &&
+  // If the resultant load doesn't need a higher alignment than the original!
+  if (ISD::isNormalLoad(N0.Val) && N0.hasOneUse() &&
       TLI.isOperationLegal(ISD::LOAD, VT)) {
     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
     unsigned Align = TLI.getTargetMachine().getTargetData()->
@@ -2914,9 +3448,73 @@ SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
     }
   }
   
+  // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
+  // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
+  // This often reduces constant pool loads.
+  if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
+      N0.Val->hasOneUse() && MVT::isInteger(VT) && !MVT::isVector(VT)) {
+    SDOperand NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
+    AddToWorkList(NewConv.Val);
+    
+    APInt SignBit = APInt::getSignBit(MVT::getSizeInBits(VT));
+    if (N0.getOpcode() == ISD::FNEG)
+      return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
+    assert(N0.getOpcode() == ISD::FABS);
+    return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
+  }
+  
+  // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
+  // Note that we don't handle copysign(x,cst) because this can always be folded
+  // to an fneg or fabs.
+  if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse() &&
+      isa<ConstantFPSDNode>(N0.getOperand(0)) &&
+      MVT::isInteger(VT) && !MVT::isVector(VT)) {
+    unsigned OrigXWidth = MVT::getSizeInBits(N0.getOperand(1).getValueType());
+    SDOperand X = DAG.getNode(ISD::BIT_CONVERT, MVT::getIntegerType(OrigXWidth),
+                              N0.getOperand(1));
+    AddToWorkList(X.Val);
+
+    // If X has a different width than the result/lhs, sext it or truncate it.
+    unsigned VTWidth = MVT::getSizeInBits(VT);
+    if (OrigXWidth < VTWidth) {
+      X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
+      AddToWorkList(X.Val);
+    } else if (OrigXWidth > VTWidth) {
+      // To get the sign bit in the right place, we have to shift it right
+      // before truncating.
+      X = DAG.getNode(ISD::SRL, X.getValueType(), X, 
+                      DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
+      AddToWorkList(X.Val);
+      X = DAG.getNode(ISD::TRUNCATE, VT, X);
+      AddToWorkList(X.Val);
+    }
+    
+    APInt SignBit = APInt::getSignBit(MVT::getSizeInBits(VT));
+    X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
+    AddToWorkList(X.Val);
+
+    SDOperand Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
+    Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
+    AddToWorkList(Cst.Val);
+
+    return DAG.getNode(ISD::OR, VT, X, Cst);
+  }
+
+  // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 
+  if (N0.getOpcode() == ISD::BUILD_PAIR) {
+    SDOperand CombineLD = CombineConsecutiveLoads(N0.Val, VT);
+    if (CombineLD.Val)
+      return CombineLD;
+  }
+  
   return SDOperand();
 }
 
+SDOperand DAGCombiner::visitBUILD_PAIR(SDNode *N) {
+  MVT::ValueType VT = N->getValueType(0);
+  return CombineConsecutiveLoads(N, VT);
+}
+
 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the 
 /// destination element value type.
@@ -2977,7 +3575,7 @@ ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
          i += NumInputsPerOutput) {
       bool isLE = TLI.isLittleEndian();
-      uint64_t NewBits = 0;
+      APInt NewBits = APInt(DstBitSize, 0);
       bool EltIsUndef = true;
       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
         // Shift the previously computed bits over.
@@ -2986,7 +3584,8 @@ ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
         if (Op.getOpcode() == ISD::UNDEF) continue;
         EltIsUndef = false;
         
-        NewBits |= cast<ConstantSDNode>(Op)->getValue();
+        NewBits |=
+          APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize);
       }
       
       if (EltIsUndef)
@@ -2995,14 +3594,16 @@ ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
     }
 
-    MVT::ValueType VT = MVT::getVectorType(DstEltVT,
-                                           Ops.size());
+    MVT::ValueType VT = MVT::getVectorType(DstEltVT, Ops.size()); 
     return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
   }
   
   // Finally, this must be the case where we are shrinking elements: each input
   // turns into multiple outputs.
+  bool isS2V = ISD::isScalarToVector(BV);
   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
+  MVT::ValueType VT = MVT::getVectorType(DstEltVT,
+                                     NumOutputsPerInput * BV->getNumOperands());
   SmallVector<SDOperand, 8> Ops;
   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
@@ -3010,19 +3611,20 @@ ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
         Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
       continue;
     }
-    uint64_t OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getValue();
-
+    APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue();
     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
-      unsigned ThisVal = OpVal & ((1ULL << DstBitSize)-1);
-      OpVal >>= DstBitSize;
+      APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
+      if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
+        // Simply turn this into a SCALAR_TO_VECTOR of the new type.
+        return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]);
+      OpVal = OpVal.lshr(DstBitSize);
     }
 
     // For big endian targets, swap the order of the pieces of each element.
-    if (!TLI.isLittleEndian())
+    if (TLI.isBigEndian())
       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
   }
-  MVT::ValueType VT = MVT::getVectorType(DstEltVT, Ops.size());
   return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
 }
 
@@ -3042,17 +3644,19 @@ SDOperand DAGCombiner::visitFADD(SDNode *N) {
   }
   
   // fold (fadd c1, c2) -> c1+c2
-  if (N0CFP && N1CFP)
+  if (N0CFP && N1CFP && VT != MVT::ppcf128)
     return DAG.getNode(ISD::FADD, VT, N0, N1);
   // canonicalize constant to RHS
   if (N0CFP && !N1CFP)
     return DAG.getNode(ISD::FADD, VT, N1, N0);
   // fold (A + (-B)) -> A-B
-  if (isNegatibleForFree(N1) == 2)
-    return DAG.getNode(ISD::FSUB, VT, N0, GetNegatedExpression(N1, DAG));
+  if (isNegatibleForFree(N1, AfterLegalize) == 2)
+    return DAG.getNode(ISD::FSUB, VT, N0, 
+                       GetNegatedExpression(N1, DAG, AfterLegalize));
   // fold ((-A) + B) -> B-A
-  if (isNegatibleForFree(N0) == 2)
-    return DAG.getNode(ISD::FSUB, VT, N1, GetNegatedExpression(N0, DAG));
+  if (isNegatibleForFree(N0, AfterLegalize) == 2)
+    return DAG.getNode(ISD::FSUB, VT, N1, 
+                       GetNegatedExpression(N0, DAG, AfterLegalize));
   
   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
   if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
@@ -3077,17 +3681,18 @@ SDOperand DAGCombiner::visitFSUB(SDNode *N) {
   }
   
   // fold (fsub c1, c2) -> c1-c2
-  if (N0CFP && N1CFP)
+  if (N0CFP && N1CFP && VT != MVT::ppcf128)
     return DAG.getNode(ISD::FSUB, VT, N0, N1);
   // fold (0-B) -> -B
-  if (UnsafeFPMath && N0CFP && N0CFP->getValue() == 0.0) {
-    if (isNegatibleForFree(N1))
-      return GetNegatedExpression(N1, DAG);
+  if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
+    if (isNegatibleForFree(N1, AfterLegalize))
+      return GetNegatedExpression(N1, DAG, AfterLegalize);
     return DAG.getNode(ISD::FNEG, VT, N1);
   }
   // fold (A-(-B)) -> A+B
-  if (isNegatibleForFree(N1))
-    return DAG.getNode(ISD::FADD, VT, N0, GetNegatedExpression(N1, DAG));
+  if (isNegatibleForFree(N1, AfterLegalize))
+    return DAG.getNode(ISD::FADD, VT, N0,
+                       GetNegatedExpression(N1, DAG, AfterLegalize));
   
   return SDOperand();
 }
@@ -3106,7 +3711,7 @@ SDOperand DAGCombiner::visitFMUL(SDNode *N) {
   }
   
   // fold (fmul c1, c2) -> c1*c2
-  if (N0CFP && N1CFP)
+  if (N0CFP && N1CFP && VT != MVT::ppcf128)
     return DAG.getNode(ISD::FMUL, VT, N0, N1);
   // canonicalize constant to RHS
   if (N0CFP && !N1CFP)
@@ -3119,13 +3724,14 @@ SDOperand DAGCombiner::visitFMUL(SDNode *N) {
     return DAG.getNode(ISD::FNEG, VT, N0);
   
   // -X * -Y -> X*Y
-  if (char LHSNeg = isNegatibleForFree(N0)) {
-    if (char RHSNeg = isNegatibleForFree(N1)) {
+  if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
+    if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
       // Both can be negated for free, check to see if at least one is cheaper
       // negated.
       if (LHSNeg == 2 || RHSNeg == 2)
-        return DAG.getNode(ISD::FMUL, VT, GetNegatedExpression(N0, DAG),
-                           GetNegatedExpression(N1, DAG));
+        return DAG.getNode(ISD::FMUL, VT, 
+                           GetNegatedExpression(N0, DAG, AfterLegalize),
+                           GetNegatedExpression(N1, DAG, AfterLegalize));
     }
   }
   
@@ -3152,18 +3758,19 @@ SDOperand DAGCombiner::visitFDIV(SDNode *N) {
   }
   
   // fold (fdiv c1, c2) -> c1/c2
-  if (N0CFP && N1CFP)
+  if (N0CFP && N1CFP && VT != MVT::ppcf128)
     return DAG.getNode(ISD::FDIV, VT, N0, N1);
   
   
   // -X / -Y -> X*Y
-  if (char LHSNeg = isNegatibleForFree(N0)) {
-    if (char RHSNeg = isNegatibleForFree(N1)) {
+  if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
+    if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
       // Both can be negated for free, check to see if at least one is cheaper
       // negated.
       if (LHSNeg == 2 || RHSNeg == 2)
-        return DAG.getNode(ISD::FDIV, VT, GetNegatedExpression(N0, DAG),
-                           GetNegatedExpression(N1, DAG));
+        return DAG.getNode(ISD::FDIV, VT, 
+                           GetNegatedExpression(N0, DAG, AfterLegalize),
+                           GetNegatedExpression(N1, DAG, AfterLegalize));
     }
   }
   
@@ -3178,7 +3785,7 @@ SDOperand DAGCombiner::visitFREM(SDNode *N) {
   MVT::ValueType VT = N->getValueType(0);
 
   // fold (frem c1, c2) -> fmod(c1,c2)
-  if (N0CFP && N1CFP)
+  if (N0CFP && N1CFP && VT != MVT::ppcf128)
     return DAG.getNode(ISD::FREM, VT, N0, N1);
 
   return SDOperand();
@@ -3191,11 +3798,11 @@ SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
   MVT::ValueType VT = N->getValueType(0);
 
-  if (N0CFP && N1CFP)  // Constant fold
+  if (N0CFP && N1CFP && VT != MVT::ppcf128)  // Constant fold
     return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
   
   if (N1CFP) {
-    APFloat V = N1CFP->getValueAPF();
+    const APFloat& V = N1CFP->getValueAPF();
     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
     if (!V.isNegative())
@@ -3235,7 +3842,7 @@ SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
   MVT::ValueType VT = N->getValueType(0);
   
   // fold (sint_to_fp c1) -> c1fp
-  if (N0C)
+  if (N0C && N0.getValueType() != MVT::ppcf128)
     return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
   return SDOperand();
 }
@@ -3246,7 +3853,7 @@ SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
   MVT::ValueType VT = N->getValueType(0);
 
   // fold (uint_to_fp c1) -> c1fp
-  if (N0C)
+  if (N0C && N0.getValueType() != MVT::ppcf128)
     return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
   return SDOperand();
 }
@@ -3268,27 +3875,37 @@ SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
   MVT::ValueType VT = N->getValueType(0);
   
   // fold (fp_to_uint c1fp) -> c1
-  if (N0CFP)
+  if (N0CFP && VT != MVT::ppcf128)
     return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
   return SDOperand();
 }
 
 SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
   SDOperand N0 = N->getOperand(0);
+  SDOperand N1 = N->getOperand(1);
   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   MVT::ValueType VT = N->getValueType(0);
   
   // fold (fp_round c1fp) -> c1fp
-  if (N0CFP)
-    return DAG.getNode(ISD::FP_ROUND, VT, N0);
+  if (N0CFP && N0.getValueType() != MVT::ppcf128)
+    return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
   
   // fold (fp_round (fp_extend x)) -> x
   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
     return N0.getOperand(0);
   
+  // fold (fp_round (fp_round x)) -> (fp_round x)
+  if (N0.getOpcode() == ISD::FP_ROUND) {
+    // This is a value preserving truncation if both round's are.
+    bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
+                   N0.Val->getConstantOperandVal(1) == 1;
+    return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
+                       DAG.getIntPtrConstant(IsTrunc));
+  }
+  
   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
-    SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0));
+    SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
     AddToWorkList(Tmp.Val);
     return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
   }
@@ -3304,7 +3921,7 @@ SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
   
   // fold (fp_round_inreg c1fp) -> c1fp
   if (N0CFP) {
-    SDOperand Round = DAG.getConstantFP(N0CFP->getValue(), EVT);
+    SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
     return DAG.getNode(ISD::FP_EXTEND, VT, Round);
   }
   return SDOperand();
@@ -3315,11 +3932,26 @@ SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   MVT::ValueType VT = N->getValueType(0);
   
+  // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
+  if (N->hasOneUse() && 
+      N->use_begin()->getSDOperand().getOpcode() == ISD::FP_ROUND)
+    return SDOperand();
+
   // fold (fp_extend c1fp) -> c1fp
-  if (N0CFP)
+  if (N0CFP && VT != MVT::ppcf128)
     return DAG.getNode(ISD::FP_EXTEND, VT, N0);
-  
-  // fold (fpext (load x)) -> (fpext (fpround (extload x)))
+
+  // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
+  // value of X.
+  if (N0.getOpcode() == ISD::FP_ROUND && N0.Val->getConstantOperandVal(1) == 1){
+    SDOperand In = N0.getOperand(0);
+    if (In.getValueType() == VT) return In;
+    if (VT < In.getValueType())
+      return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
+    return DAG.getNode(ISD::FP_EXTEND, VT, In);
+  }
+      
+  // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
   if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
       (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
@@ -3330,7 +3962,8 @@ SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
                                        LN0->isVolatile(), 
                                        LN0->getAlignment());
     CombineTo(N, ExtLoad);
-    CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad),
+    CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad,
+                                  DAG.getIntPtrConstant(1)),
               ExtLoad.getValue(1));
     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
   }
@@ -3342,9 +3975,24 @@ SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
 SDOperand DAGCombiner::visitFNEG(SDNode *N) {
   SDOperand N0 = N->getOperand(0);
 
-  if (isNegatibleForFree(N0))
-    return GetNegatedExpression(N0, DAG);
-
+  if (isNegatibleForFree(N0, AfterLegalize))
+    return GetNegatedExpression(N0, DAG, AfterLegalize);
+
+  // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
+  // constant pool values.
+  if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
+      MVT::isInteger(N0.getOperand(0).getValueType()) &&
+      !MVT::isVector(N0.getOperand(0).getValueType())) {
+    SDOperand Int = N0.getOperand(0);
+    MVT::ValueType IntVT = Int.getValueType();
+    if (MVT::isInteger(IntVT) && !MVT::isVector(IntVT)) {
+      Int = DAG.getNode(ISD::XOR, IntVT, Int, 
+                        DAG.getConstant(MVT::getIntVTSignBit(IntVT), IntVT));
+      AddToWorkList(Int.Val);
+      return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
+    }
+  }
+  
   return SDOperand();
 }
 
@@ -3354,7 +4002,7 @@ SDOperand DAGCombiner::visitFABS(SDNode *N) {
   MVT::ValueType VT = N->getValueType(0);
   
   // fold (fabs c1) -> fabs(c1)
-  if (N0CFP)
+  if (N0CFP && VT != MVT::ppcf128)
     return DAG.getNode(ISD::FABS, VT, N0);
   // fold (fabs (fabs x)) -> (fabs x)
   if (N0.getOpcode() == ISD::FABS)
@@ -3364,6 +4012,21 @@ SDOperand DAGCombiner::visitFABS(SDNode *N) {
   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
     return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
   
+  // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
+  // constant pool values.
+  if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
+      MVT::isInteger(N0.getOperand(0).getValueType()) &&
+      !MVT::isVector(N0.getOperand(0).getValueType())) {
+    SDOperand Int = N0.getOperand(0);
+    MVT::ValueType IntVT = Int.getValueType();
+    if (MVT::isInteger(IntVT) && !MVT::isVector(IntVT)) {
+      Int = DAG.getNode(ISD::AND, IntVT, Int, 
+                        DAG.getConstant(~MVT::getIntVTSignBit(IntVT), IntVT));
+      AddToWorkList(Int.Val);
+      return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
+    }
+  }
+  
   return SDOperand();
 }
 
@@ -3377,7 +4040,7 @@ SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
   if (N1C && N1C->isNullValue())
     return Chain;
   // unconditional branch
-  if (N1C && N1C->getValue() == 1)
+  if (N1C && N1C->getAPIntValue() == 1)
     return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
   // on the target.
@@ -3402,7 +4065,7 @@ SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
 
   // fold br_cc true, dest -> br dest (unconditional branch)
-  if (SCCC && SCCC->getValue())
+  if (SCCC && !SCCC->isNullValue())
     return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
                        N->getOperand(4));
   // fold br_cc false, dest -> unconditional fall through
@@ -3432,17 +4095,17 @@ bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
   SDOperand Ptr;
   MVT::ValueType VT;
   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
-    if (LD->getAddressingMode() != ISD::UNINDEXED)
+    if (LD->isIndexed())
       return false;
-    VT = LD->getLoadedVT();
+    VT = LD->getMemoryVT();
     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
       return false;
     Ptr = LD->getBasePtr();
   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
-    if (ST->getAddressingMode() != ISD::UNINDEXED)
+    if (ST->isIndexed())
       return false;
-    VT = ST->getStoredVT();
+    VT = ST->getMemoryVT();
     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
       return false;
@@ -3465,7 +4128,7 @@ bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
     return false;
   // Don't create a indexed load / store with zero offset.
   if (isa<ConstantSDNode>(Offset) &&
-      cast<ConstantSDNode>(Offset)->getValue() == 0)
+      cast<ConstantSDNode>(Offset)->isNullValue())
     return false;
   
   // Try turning it into a pre-indexed load / store except when:
@@ -3484,7 +4147,7 @@ bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
   // Check #2.
   if (!isLoad) {
     SDOperand Val = cast<StoreSDNode>(N)->getValue();
-    if (Val == BasePtr || BasePtr.Val->isPredecessor(Val.Val))
+    if (Val == BasePtr || BasePtr.Val->isPredecessorOf(Val.Val))
       return false;
   }
 
@@ -3492,16 +4155,16 @@ bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
   bool RealUse = false;
   for (SDNode::use_iterator I = Ptr.Val->use_begin(),
          E = Ptr.Val->use_end(); I != E; ++I) {
-    SDNode *Use = *I;
+    SDNode *Use = I->getUser();
     if (Use == N)
       continue;
-    if (Use->isPredecessor(N))
+    if (Use->isPredecessorOf(N))
       return false;
 
     if (!((Use->getOpcode() == ISD::LOAD &&
            cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
-          (Use->getOpcode() == ISD::STORE) &&
-          cast<StoreSDNode>(Use)->getBasePtr() == Ptr))
+          (Use->getOpcode() == ISD::STORE &&
+           cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
       RealUse = true;
   }
   if (!RealUse)
@@ -3517,30 +4180,24 @@ bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
   DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
   DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
   DOUT << '\n';
-  std::vector<SDNode*> NowDead;
+  WorkListRemover DeadNodes(*this);
   if (isLoad) {
     DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
-                                  NowDead);
+                                  &DeadNodes);
     DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
-                                  NowDead);
+                                  &DeadNodes);
   } else {
     DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
-                                  NowDead);
+                                  &DeadNodes);
   }
 
-  // Nodes can end up on the worklist more than once.  Make sure we do
-  // not process a node that has been replaced.
-  for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
-    removeFromWorkList(NowDead[i]);
   // Finally, since the node is now dead, remove it from the graph.
   DAG.DeleteNode(N);
 
   // Replace the uses of Ptr with uses of the updated base value.
   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
-                                NowDead);
+                                &DeadNodes);
   removeFromWorkList(Ptr.Val);
-  for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
-    removeFromWorkList(NowDead[i]);
   DAG.DeleteNode(Ptr.Val);
 
   return true;
@@ -3559,17 +4216,17 @@ bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
   SDOperand Ptr;
   MVT::ValueType VT;
   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
-    if (LD->getAddressingMode() != ISD::UNINDEXED)
+    if (LD->isIndexed())
       return false;
-    VT = LD->getLoadedVT();
+    VT = LD->getMemoryVT();
     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
       return false;
     Ptr = LD->getBasePtr();
   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
-    if (ST->getAddressingMode() != ISD::UNINDEXED)
+    if (ST->isIndexed())
       return false;
-    VT = ST->getStoredVT();
+    VT = ST->getMemoryVT();
     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
       return false;
@@ -3583,7 +4240,7 @@ bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
   
   for (SDNode::use_iterator I = Ptr.Val->use_begin(),
          E = Ptr.Val->use_end(); I != E; ++I) {
-    SDNode *Op = *I;
+    SDNode *Op = I->getUser();
     if (Op == N ||
         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
       continue;
@@ -3598,7 +4255,7 @@ bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
         continue;
       // Don't create a indexed load / store with zero offset.
       if (isa<ConstantSDNode>(Offset) &&
-          cast<ConstantSDNode>(Offset)->getValue() == 0)
+          cast<ConstantSDNode>(Offset)->isNullValue())
         continue;
 
       // Try turning it into a post-indexed load / store except when
@@ -3611,7 +4268,7 @@ bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
       bool TryNext = false;
       for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
              EE = BasePtr.Val->use_end(); II != EE; ++II) {
-        SDNode *Use = *II;
+        SDNode *Use = II->getUser();
         if (Use == Ptr.Val)
           continue;
 
@@ -3621,11 +4278,11 @@ bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
           bool RealUse = false;
           for (SDNode::use_iterator III = Use->use_begin(),
                  EEE = Use->use_end(); III != EEE; ++III) {
-            SDNode *UseUse = *III;
+            SDNode *UseUse = III->getUser();
             if (!((UseUse->getOpcode() == ISD::LOAD &&
                    cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
-                  (UseUse->getOpcode() == ISD::STORE) &&
-                  cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use))
+                  (UseUse->getOpcode() == ISD::STORE &&
+                   cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use)))
               RealUse = true;
           }
 
@@ -3639,7 +4296,7 @@ bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
         continue;
 
       // Check for #2
-      if (!Op->isPredecessor(N) && !N->isPredecessor(Op)) {
+      if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
         SDOperand Result = isLoad
           ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
           : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
@@ -3648,33 +4305,26 @@ bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
         DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
         DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
         DOUT << '\n';
-        std::vector<SDNode*> NowDead;
+        WorkListRemover DeadNodes(*this);
         if (isLoad) {
           DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
-                                        NowDead);
+                                        &DeadNodes);
           DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
-                                        NowDead);
+                                        &DeadNodes);
         } else {
           DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
-                                        NowDead);
+                                        &DeadNodes);
         }
 
-        // Nodes can end up on the worklist more than once.  Make sure we do
-        // not process a node that has been replaced.
-        for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
-          removeFromWorkList(NowDead[i]);
         // Finally, since the node is now dead, remove it from the graph.
         DAG.DeleteNode(N);
 
         // Replace the uses of Use with uses of the updated base value.
         DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
                                       Result.getValue(isLoad ? 1 : 0),
-                                      NowDead);
+                                      &DeadNodes);
         removeFromWorkList(Op);
-        for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
-          removeFromWorkList(NowDead[i]);
         DAG.DeleteNode(Op);
-
         return true;
       }
     }
@@ -3682,11 +4332,65 @@ bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
   return false;
 }
 
+/// InferAlignment - If we can infer some alignment information from this
+/// pointer, return it.
+static unsigned InferAlignment(SDOperand Ptr, SelectionDAG &DAG) {
+  // If this is a direct reference to a stack slot, use information about the
+  // stack slot's alignment.
+  int FrameIdx = 1 << 31;
+  int64_t FrameOffset = 0;
+  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
+    FrameIdx = FI->getIndex();
+  } else if (Ptr.getOpcode() == ISD::ADD && 
+             isa<ConstantSDNode>(Ptr.getOperand(1)) &&
+             isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
+    FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
+    FrameOffset = Ptr.getConstantOperandVal(1);
+  }
+             
+  if (FrameIdx != (1 << 31)) {
+    // FIXME: Handle FI+CST.
+    const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
+    if (MFI.isFixedObjectIndex(FrameIdx)) {
+      int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx);
+
+      // The alignment of the frame index can be determined from its offset from
+      // the incoming frame position.  If the frame object is at offset 32 and
+      // the stack is guaranteed to be 16-byte aligned, then we know that the
+      // object is 16-byte aligned.
+      unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
+      unsigned Align = MinAlign(ObjectOffset, StackAlign);
+      
+      // Finally, the frame object itself may have a known alignment.  Factor
+      // the alignment + offset into a new alignment.  For example, if we know
+      // the  FI is 8 byte aligned, but the pointer is 4 off, we really have a
+      // 4-byte alignment of the resultant pointer.  Likewise align 4 + 4-byte
+      // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
+      unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx), 
+                                      FrameOffset);
+      return std::max(Align, FIInfoAlign);
+    }
+  }
+  
+  return 0;
+}
 
 SDOperand DAGCombiner::visitLOAD(SDNode *N) {
   LoadSDNode *LD  = cast<LoadSDNode>(N);
   SDOperand Chain = LD->getChain();
   SDOperand Ptr   = LD->getBasePtr();
+  
+  // Try to infer better alignment information than the load already has.
+  if (LD->isUnindexed()) {
+    if (unsigned Align = InferAlignment(Ptr, DAG)) {
+      if (Align > LD->getAlignment())
+        return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
+                              Chain, Ptr, LD->getSrcValue(),
+                              LD->getSrcValueOffset(), LD->getMemoryVT(),
+                              LD->isVolatile(), Align);
+    }
+  }
+  
 
   // If load is not volatile and there are no uses of the loaded value (and
   // the updated indexed value in case of indexed loads), change uses of the
@@ -3694,16 +4398,41 @@ SDOperand DAGCombiner::visitLOAD(SDNode *N) {
   if (!LD->isVolatile()) {
     if (N->getValueType(1) == MVT::Other) {
       // Unindexed loads.
-      if (N->hasNUsesOfValue(0, 0))
-        return CombineTo(N, DAG.getNode(ISD::UNDEF, N->getValueType(0)), Chain);
+      if (N->hasNUsesOfValue(0, 0)) {
+        // It's not safe to use the two value CombineTo variant here. e.g.
+        // v1, chain2 = load chain1, loc
+        // v2, chain3 = load chain2, loc
+        // v3         = add v2, c
+        // Now we replace use of chain2 with chain1.  This makes the second load
+        // isomorphic to the one we are deleting, and thus makes this load live.
+        DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
+        DOUT << "\nWith chain: "; DEBUG(Chain.Val->dump(&DAG));
+        DOUT << "\n";
+        WorkListRemover DeadNodes(*this);
+        DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Chain, &DeadNodes);
+        if (N->use_empty()) {
+          removeFromWorkList(N);
+          DAG.DeleteNode(N);
+        }
+        return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
+      }
     } else {
       // Indexed loads.
       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
       if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
-        SDOperand Undef0 = DAG.getNode(ISD::UNDEF, N->getValueType(0));
-        SDOperand Undef1 = DAG.getNode(ISD::UNDEF, N->getValueType(1));
-        SDOperand To[] = { Undef0, Undef1, Chain };
-        return CombineTo(N, To, 3);
+        SDOperand Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
+        DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
+        DOUT << "\nWith: "; DEBUG(Undef.Val->dump(&DAG));
+        DOUT << " and 2 other values\n";
+        WorkListRemover DeadNodes(*this);
+        DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Undef, &DeadNodes);
+        DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
+                                    DAG.getNode(ISD::UNDEF, N->getValueType(1)),
+                                      &DeadNodes);
+        DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 2), Chain, &DeadNodes);
+        removeFromWorkList(N);
+        DAG.DeleteNode(N);
+        return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
       }
     }
   }
@@ -3712,7 +4441,8 @@ SDOperand DAGCombiner::visitLOAD(SDNode *N) {
   // value.
   // TODO: Handle store large -> read small portion.
   // TODO: Handle TRUNCSTORE/LOADEXT
-  if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
+  if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
+      !LD->isVolatile()) {
     if (ISD::isNON_TRUNCStore(Chain.Val)) {
       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
       if (PrevST->getBasePtr() == Ptr &&
@@ -3732,14 +4462,14 @@ SDOperand DAGCombiner::visitLOAD(SDNode *N) {
       // Replace the chain to void dependency.
       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
         ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
-                              LD->getSrcValue(), LD->getSrcValueOffset(),
-                              LD->isVolatile(), LD->getAlignment());
+                               LD->getSrcValue(), LD->getSrcValueOffset(),
+                               LD->isVolatile(), LD->getAlignment());
       } else {
         ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
                                   LD->getValueType(0),
                                   BetterChain, Ptr, LD->getSrcValue(),
                                   LD->getSrcValueOffset(),
-                                  LD->getLoadedVT(),
+                                  LD->getMemoryVT(),
                                   LD->isVolatile(), 
                                   LD->getAlignment());
       }
@@ -3761,16 +4491,27 @@ SDOperand DAGCombiner::visitLOAD(SDNode *N) {
   return SDOperand();
 }
 
+
 SDOperand DAGCombiner::visitSTORE(SDNode *N) {
   StoreSDNode *ST  = cast<StoreSDNode>(N);
   SDOperand Chain = ST->getChain();
   SDOperand Value = ST->getValue();
   SDOperand Ptr   = ST->getBasePtr();
   
+  // Try to infer better alignment information than the store already has.
+  if (ST->isUnindexed()) {
+    if (unsigned Align = InferAlignment(Ptr, DAG)) {
+      if (Align > ST->getAlignment())
+        return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
+                                 ST->getSrcValueOffset(), ST->getMemoryVT(),
+                                 ST->isVolatile(), Align);
+    }
+  }
+  
   // If this is a store of a bit convert, store the input value if the
   // resultant store does not need a higher alignment than the original.
   if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
-      ST->getAddressingMode() == ISD::UNINDEXED) {
+      ST->isUnindexed()) {
     unsigned Align = ST->getAlignment();
     MVT::ValueType SVT = Value.getOperand(0).getValueType();
     unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
@@ -3786,9 +4527,14 @@ SDOperand DAGCombiner::visitSTORE(SDNode *N) {
       SDOperand Tmp;
       switch (CFP->getValueType(0)) {
       default: assert(0 && "Unknown FP type");
+      case MVT::f80:    // We don't do this for these yet.
+      case MVT::f128:
+      case MVT::ppcf128:
+        break;
       case MVT::f32:
         if (!AfterLegalize || TLI.isTypeLegal(MVT::i32)) {
-          Tmp = DAG.getConstant(FloatToBits(CFP->getValueAPF().convertToFloat()), MVT::i32);
+          Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
+                              convertToAPInt().getZExtValue(), MVT::i32);
           return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
                               ST->getSrcValueOffset(), ST->isVolatile(),
                               ST->getAlignment());
@@ -3796,18 +4542,19 @@ SDOperand DAGCombiner::visitSTORE(SDNode *N) {
         break;
       case MVT::f64:
         if (!AfterLegalize || TLI.isTypeLegal(MVT::i64)) {
-          Tmp = DAG.getConstant(DoubleToBits(CFP->getValueAPF().convertToDouble()), MVT::i64);
+          Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
+                                  getZExtValue(), MVT::i64);
           return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
                               ST->getSrcValueOffset(), ST->isVolatile(),
                               ST->getAlignment());
         } else if (TLI.isTypeLegal(MVT::i32)) {
-          // Many FP stores are not make apparent until after legalize, e.g. for
+          // Many FP stores are not made apparent until after legalize, e.g. for
           // argument passing.  Since this is so common, custom legalize the
           // 64-bit integer store into two 32-bit stores.
-          uint64_t Val = DoubleToBits(CFP->getValueAPF().convertToDouble());
+          uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
           SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
           SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
-          if (!TLI.isLittleEndian()) std::swap(Lo, Hi);
+          if (TLI.isBigEndian()) std::swap(Lo, Hi);
 
           int SVOffset = ST->getSrcValueOffset();
           unsigned Alignment = ST->getAlignment();
@@ -3819,8 +4566,7 @@ SDOperand DAGCombiner::visitSTORE(SDNode *N) {
           Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
                             DAG.getConstant(4, Ptr.getValueType()));
           SVOffset += 4;
-          if (Alignment > 4)
-            Alignment = 4;
+          Alignment = MinAlign(Alignment, 4U);
           SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
                                        SVOffset, isVolatile, Alignment);
           return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
@@ -3840,12 +4586,13 @@ SDOperand DAGCombiner::visitSTORE(SDNode *N) {
       SDOperand ReplStore;
       if (ST->isTruncatingStore()) {
         ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
-          ST->getSrcValue(), ST->getSrcValueOffset(), ST->getStoredVT(),
-          ST->isVolatile(), ST->getAlignment());
+                                      ST->getSrcValue(),ST->getSrcValueOffset(),
+                                      ST->getMemoryVT(),
+                                      ST->isVolatile(), ST->getAlignment());
       } else {
         ReplStore = DAG.getStore(BetterChain, Value, Ptr,
-          ST->getSrcValue(), ST->getSrcValueOffset(),
-          ST->isVolatile(), ST->getAlignment());
+                                 ST->getSrcValue(), ST->getSrcValueOffset(),
+                                 ST->isVolatile(), ST->getAlignment());
       }
       
       // Create token to keep both nodes around.
@@ -3861,6 +4608,56 @@ SDOperand DAGCombiner::visitSTORE(SDNode *N) {
   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
     return SDOperand(N, 0);
 
+  // FIXME: is there such a thing as a truncating indexed store?
+  if (ST->isTruncatingStore() && ST->isUnindexed() &&
+      MVT::isInteger(Value.getValueType())) {
+    // See if we can simplify the input to this truncstore with knowledge that
+    // only the low bits are being used.  For example:
+    // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
+    SDOperand Shorter = 
+      GetDemandedBits(Value,
+                 APInt::getLowBitsSet(Value.getValueSizeInBits(),
+                                      MVT::getSizeInBits(ST->getMemoryVT())));
+    AddToWorkList(Value.Val);
+    if (Shorter.Val)
+      return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
+                               ST->getSrcValueOffset(), ST->getMemoryVT(),
+                               ST->isVolatile(), ST->getAlignment());
+    
+    // Otherwise, see if we can simplify the operation with
+    // SimplifyDemandedBits, which only works if the value has a single use.
+    if (SimplifyDemandedBits(Value,
+                             APInt::getLowBitsSet(
+                               Value.getValueSizeInBits(),
+                               MVT::getSizeInBits(ST->getMemoryVT()))))
+      return SDOperand(N, 0);
+  }
+  
+  // If this is a load followed by a store to the same location, then the store
+  // is dead/noop.
+  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
+    if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
+        ST->isUnindexed() && !ST->isVolatile() &&
+        // There can't be any side effects between the load and store, such as
+        // a call or store.
+        Chain.reachesChainWithoutSideEffects(SDOperand(Ld, 1))) {
+      // The store is dead, remove it.
+      return Chain;
+    }
+  }
+  
+  // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
+  // truncating store.  We can do this even if this is already a truncstore.
+  if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
+      && TLI.isTypeLegal(Value.getOperand(0).getValueType()) &&
+      Value.Val->hasOneUse() && ST->isUnindexed() &&
+      TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
+                            ST->getMemoryVT())) {
+    return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
+                             ST->getSrcValueOffset(), ST->getMemoryVT(),
+                             ST->isVolatile(), ST->getAlignment());
+  }
+  
   return SDOperand();
 }
 
@@ -3883,6 +4680,88 @@ SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
   return SDOperand();
 }
 
+SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
+  // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
+  // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
+  // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
+
+  // Perform only after legalization to ensure build_vector / vector_shuffle
+  // optimizations have already been done.
+  if (!AfterLegalize) return SDOperand();
+
+  SDOperand InVec = N->getOperand(0);
+  SDOperand EltNo = N->getOperand(1);
+
+  if (isa<ConstantSDNode>(EltNo)) {
+    unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
+    bool NewLoad = false;
+    MVT::ValueType VT = InVec.getValueType();
+    MVT::ValueType EVT = MVT::getVectorElementType(VT);
+    MVT::ValueType LVT = EVT;
+    if (InVec.getOpcode() == ISD::BIT_CONVERT) {
+      MVT::ValueType BCVT = InVec.getOperand(0).getValueType();
+      if (!MVT::isVector(BCVT)
+          || (MVT::getSizeInBits(EVT) >
+              MVT::getSizeInBits(MVT::getVectorElementType(BCVT))))
+        return SDOperand();
+      InVec = InVec.getOperand(0);
+      EVT = MVT::getVectorElementType(BCVT);
+      NewLoad = true;
+    }
+
+    LoadSDNode *LN0 = NULL;
+    if (ISD::isNormalLoad(InVec.Val))
+      LN0 = cast<LoadSDNode>(InVec);
+    else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
+             InVec.getOperand(0).getValueType() == EVT &&
+             ISD::isNormalLoad(InVec.getOperand(0).Val)) {
+      LN0 = cast<LoadSDNode>(InVec.getOperand(0));
+    } else if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
+      // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
+      // =>
+      // (load $addr+1*size)
+      unsigned Idx = cast<ConstantSDNode>(InVec.getOperand(2).
+                                          getOperand(Elt))->getValue();
+      unsigned NumElems = InVec.getOperand(2).getNumOperands();
+      InVec = (Idx < NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
+      if (InVec.getOpcode() == ISD::BIT_CONVERT)
+        InVec = InVec.getOperand(0);
+      if (ISD::isNormalLoad(InVec.Val)) {
+        LN0 = cast<LoadSDNode>(InVec);
+        Elt = (Idx < NumElems) ? Idx : Idx - NumElems;
+      }
+    }
+    if (!LN0 || !LN0->hasOneUse())
+      return SDOperand();
+
+    unsigned Align = LN0->getAlignment();
+    if (NewLoad) {
+      // Check the resultant load doesn't need a higher alignment than the
+      // original load.
+      unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
+        getABITypeAlignment(MVT::getTypeForValueType(LVT));
+      if (!TLI.isOperationLegal(ISD::LOAD, LVT) || NewAlign > Align)
+        return SDOperand();
+      Align = NewAlign;
+    }
+
+    SDOperand NewPtr = LN0->getBasePtr();
+    if (Elt) {
+      unsigned PtrOff = MVT::getSizeInBits(LVT) * Elt / 8;
+      MVT::ValueType PtrType = NewPtr.getValueType();
+      if (TLI.isBigEndian())
+        PtrOff = MVT::getSizeInBits(VT) / 8 - PtrOff;
+      NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
+                           DAG.getConstant(PtrOff, PtrType));
+    }
+    return DAG.getLoad(LVT, LN0->getChain(), NewPtr,
+                       LN0->getSrcValue(), LN0->getSrcValueOffset(),
+                       LN0->isVolatile(), Align);
+  }
+  return SDOperand();
+}
+  
+
 SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
   unsigned NumInScalars = N->getNumOperands();
   MVT::ValueType VT = N->getValueType(0);
@@ -3947,13 +4826,11 @@ SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
 
       // Otherwise, use InIdx + VecSize
       unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
-      BuildVecIndices.push_back(DAG.getConstant(Idx+NumInScalars,
-                                                TLI.getPointerTy()));
+      BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
     }
     
     // Add count and size info.
-    MVT::ValueType BuildVecVT =
-      MVT::getVectorType(TLI.getPointerTy(), NumElts);
+    MVT::ValueType BuildVecVT = MVT::getVectorType(TLI.getPointerTy(), NumElts);
     
     // Return the new VECTOR_SHUFFLE node.
     SDOperand Ops[5];
@@ -4075,8 +4952,7 @@ SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
         if (!Base.Val)
           return N0;
         for (unsigned i = 0; i != NumElems; ++i) {
-          if (V->getOperand(i).getOpcode() != ISD::UNDEF &&
-              V->getOperand(i) != Base) {
+          if (V->getOperand(i) != Base) {
             AllSame = false;
             break;
           }
@@ -4207,7 +5083,7 @@ SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
         if ((RHSOp.getOpcode() == ISD::Constant &&
              cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
             (RHSOp.getOpcode() == ISD::ConstantFP &&
-             !cast<ConstantFPSDNode>(RHSOp.Val)->getValue()))
+             cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
           break;
       }
       Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
@@ -4275,7 +5151,7 @@ bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
       LoadSDNode *RLD = cast<LoadSDNode>(RHS);
 
       // If this is an EXTLOAD, the VT's must match.
-      if (LLD->getLoadedVT() == RLD->getLoadedVT()) {
+      if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
         // FIXME: this conflates two src values, discarding one.  This is not
         // the right thing to do, but nothing uses srcvalues now.  When they do,
         // turn SrcValue into a list of locations.
@@ -4283,8 +5159,8 @@ bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
         if (TheSelect->getOpcode() == ISD::SELECT) {
           // Check that the condition doesn't reach either load.  If so, folding
           // this will induce a cycle into the DAG.
-          if (!LLD->isPredecessor(TheSelect->getOperand(0).Val) &&
-              !RLD->isPredecessor(TheSelect->getOperand(0).Val)) {
+          if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
+              !RLD->isPredecessorOf(TheSelect->getOperand(0).Val)) {
             Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
                                TheSelect->getOperand(0), LLD->getBasePtr(),
                                RLD->getBasePtr());
@@ -4292,10 +5168,10 @@ bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
         } else {
           // Check that the condition doesn't reach either load.  If so, folding
           // this will induce a cycle into the DAG.
-          if (!LLD->isPredecessor(TheSelect->getOperand(0).Val) &&
-              !RLD->isPredecessor(TheSelect->getOperand(0).Val) &&
-              !LLD->isPredecessor(TheSelect->getOperand(1).Val) &&
-              !RLD->isPredecessor(TheSelect->getOperand(1).Val)) {
+          if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
+              !RLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
+              !LLD->isPredecessorOf(TheSelect->getOperand(1).Val) &&
+              !RLD->isPredecessorOf(TheSelect->getOperand(1).Val)) {
             Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
                              TheSelect->getOperand(0),
                              TheSelect->getOperand(1), 
@@ -4317,7 +5193,7 @@ bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
                                   TheSelect->getValueType(0),
                                   LLD->getChain(), Addr, LLD->getSrcValue(),
                                   LLD->getSrcValueOffset(),
-                                  LLD->getLoadedVT(),
+                                  LLD->getMemoryVT(),
                                   LLD->isVolatile(), 
                                   LLD->getAlignment());
           }
@@ -4347,15 +5223,15 @@ SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
 
   // Determine if the condition we're dealing with is constant
-  SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
+  SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
   if (SCC.Val) AddToWorkList(SCC.Val);
   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
 
   // fold select_cc true, x, y -> x
-  if (SCCC && SCCC->getValue())
+  if (SCCC && !SCCC->isNullValue())
     return N2;
   // fold select_cc false, x, y -> y
-  if (SCCC && SCCC->getValue() == 0)
+  if (SCCC && SCCC->isNullValue())
     return N3;
   
   // Check to see if we can simplify the select into an fabs node
@@ -4381,15 +5257,15 @@ SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
       MVT::isInteger(N0.getValueType()) && 
       MVT::isInteger(N2.getValueType()) && 
-      (N1C->isNullValue() ||                    // (a < 0) ? b : 0
-       (N1C->getValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
+      (N1C->isNullValue() ||                         // (a < 0) ? b : 0
+       (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
     MVT::ValueType XType = N0.getValueType();
     MVT::ValueType AType = N2.getValueType();
     if (XType >= AType) {
       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
       // single-bit constant.
-      if (N2C && ((N2C->getValue() & (N2C->getValue()-1)) == 0)) {
-        unsigned ShCtV = Log2_64(N2C->getValue());
+      if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
+        unsigned ShCtV = N2C->getAPIntValue().logBase2();
         ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
         SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
         SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
@@ -4413,12 +5289,12 @@ SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
   }
   
   // fold select C, 16, 0 -> shl C, 4
-  if (N2C && N3C && N3C->isNullValue() && isPowerOf2_64(N2C->getValue()) &&
+  if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
       TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
     
     // If the caller doesn't want us to simplify this into a zext of a compare,
     // don't do it.
-    if (NotExtCompare && N2C->getValue() == 1)
+    if (NotExtCompare && N2C->getAPIntValue() == 1)
       return SDOperand();
     
     // Get a SetCC of the condition
@@ -4427,7 +5303,7 @@ SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
     SDOperand Temp, SCC;
     // cast from setcc result type to select result type
     if (AfterLegalize) {
-      SCC  = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
+      SCC  = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
       if (N2.getValueType() < SCC.getValueType())
         Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
       else
@@ -4439,21 +5315,21 @@ SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
     AddToWorkList(SCC.Val);
     AddToWorkList(Temp.Val);
     
-    if (N2C->getValue() == 1)
+    if (N2C->getAPIntValue() == 1)
       return Temp;
     // shl setcc result by log2 n2c
     return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
-                       DAG.getConstant(Log2_64(N2C->getValue()),
+                       DAG.getConstant(N2C->getAPIntValue().logBase2(),
                                        TLI.getShiftAmountTy()));
   }
     
   // Check to see if this is the equivalent of setcc
   // FIXME: Turn all of these into setcc if setcc if setcc is legal
   // otherwise, go ahead with the folds.
-  if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getValue() == 1ULL)) {
+  if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
     MVT::ValueType XType = N0.getValueType();
-    if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultTy())) {
-      SDOperand Res = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
+    if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(N0))) {
+      SDOperand Res = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
       if (Res.getValueType() != VT)
         Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
       return Res;
@@ -4606,8 +5482,9 @@ bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
 
   if (CombinerGlobalAA) {
     // Use alias analysis information.
-    int Overlap1 = Size1 + SrcValueOffset1;
-    int Overlap2 = Size2 + SrcValueOffset2;
+    int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
+    int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
+    int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
     AliasAnalysis::AliasResult AAResult = 
                              AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
     if (AAResult == AliasAnalysis::NoAlias)
@@ -4625,13 +5502,13 @@ bool DAGCombiner::FindAliasInfo(SDNode *N,
                         const Value *&SrcValue, int &SrcValueOffset) {
   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
     Ptr = LD->getBasePtr();
-    Size = MVT::getSizeInBits(LD->getLoadedVT()) >> 3;
+    Size = MVT::getSizeInBits(LD->getMemoryVT()) >> 3;
     SrcValue = LD->getSrcValue();
     SrcValueOffset = LD->getSrcValueOffset();
     return true;
   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
     Ptr = ST->getBasePtr();
-    Size = MVT::getSizeInBits(ST->getStoredVT()) >> 3;
+    Size = MVT::getSizeInBits(ST->getMemoryVT()) >> 3;
     SrcValue = ST->getSrcValue();
     SrcValueOffset = ST->getSrcValueOffset();
   } else {