Fix PR3401: when using large integers, the type
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAG.cpp
index c37fa38a0587adfb5b07fc80e6ee971cd950577a..1b0d61ca0a734984455c2066ba9df54f6a0fa5b9 100644 (file)
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/CodeGen/PseudoSourceValue.h"
-#include "llvm/Support/MathExtras.h"
 #include "llvm/Target/TargetRegisterInfo.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Target/TargetLowering.h"
+#include "llvm/Target/TargetOptions.h"
 #include "llvm/Target/TargetInstrInfo.h"
 #include "llvm/Target/TargetMachine.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/raw_ostream.h"
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallSet.h"
@@ -68,7 +71,7 @@ SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
 /// As such, this method can be used to do an exact bit-for-bit comparison of
 /// two floating point values.
 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
-  return Value.bitwiseIsEqual(V);
+  return getValueAPF().bitwiseIsEqual(V);
 }
 
 bool ConstantFPSDNode::isValueValidForType(MVT VT,
@@ -82,8 +85,10 @@ bool ConstantFPSDNode::isValueValidForType(MVT VT,
   
   // convert modifies in place, so make a copy.
   APFloat Val2 = APFloat(Val);
-  return Val2.convert(*MVTToAPFloatSemantics(VT),
-                      APFloat::rmNearestTiesToEven) == APFloat::opOK;
+  bool losesInfo;
+  (void) Val2.convert(*MVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
+                      &losesInfo);
+  return !losesInfo;
 }
 
 //===----------------------------------------------------------------------===//
@@ -95,7 +100,7 @@ bool ConstantFPSDNode::isValueValidForType(MVT VT,
 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
   // Look through a bit convert.
   if (N->getOpcode() == ISD::BIT_CONVERT)
-    N = N->getOperand(0).Val;
+    N = N->getOperand(0).getNode();
   
   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
   
@@ -110,13 +115,13 @@ bool ISD::isBuildVectorAllOnes(const SDNode *N) {
   
   // Do not accept build_vectors that aren't all constants or which have non-~0
   // elements.
-  SDOperand NotZero = N->getOperand(i);
+  SDValue NotZero = N->getOperand(i);
   if (isa<ConstantSDNode>(NotZero)) {
     if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
       return false;
   } else if (isa<ConstantFPSDNode>(NotZero)) {
     if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
-                convertToAPInt().isAllOnesValue())
+                bitcastToAPInt().isAllOnesValue())
       return false;
   } else
     return false;
@@ -136,7 +141,7 @@ bool ISD::isBuildVectorAllOnes(const SDNode *N) {
 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
   // Look through a bit convert.
   if (N->getOpcode() == ISD::BIT_CONVERT)
-    N = N->getOperand(0).Val;
+    N = N->getOperand(0).getNode();
   
   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
   
@@ -151,7 +156,7 @@ bool ISD::isBuildVectorAllZeros(const SDNode *N) {
   
   // Do not accept build_vectors that aren't all constants or which have non-~0
   // elements.
-  SDOperand Zero = N->getOperand(i);
+  SDValue Zero = N->getOperand(i);
   if (isa<ConstantSDNode>(Zero)) {
     if (!cast<ConstantSDNode>(Zero)->isNullValue())
       return false;
@@ -183,7 +188,7 @@ bool ISD::isScalarToVector(const SDNode *N) {
     return false;
   unsigned NumElems = N->getNumOperands();
   for (unsigned i = 1; i < NumElems; ++i) {
-    SDOperand V = N->getOperand(i);
+    SDValue V = N->getOperand(i);
     if (V.getOpcode() != ISD::UNDEF)
       return false;
   }
@@ -194,7 +199,7 @@ bool ISD::isScalarToVector(const SDNode *N) {
 /// isDebugLabel - Return true if the specified node represents a debug
 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
 bool ISD::isDebugLabel(const SDNode *N) {
-  SDOperand Zero;
+  SDValue Zero;
   if (N->getOpcode() == ISD::DBG_LABEL)
     return true;
   if (N->isMachineOpcode() &&
@@ -212,7 +217,7 @@ ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
   unsigned OldG = (Operation >> 1) & 1;
   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
                        (OldL << 1) |       // New G bit
-                       (OldG << 2));        // New L bit.
+                       (OldG << 2));       // New L bit.
 }
 
 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
@@ -223,8 +228,10 @@ ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
     Operation ^= 7;   // Flip L, G, E bits, but not U.
   else
     Operation ^= 15;  // Flip all of the condition bits.
+
   if (Operation > ISD::SETTRUE2)
-    Operation &= ~8;     // Don't let N and U bits get set.
+    Operation &= ~8;  // Don't let N and U bits get set.
+
   return ISD::CondCode(Operation);
 }
 
@@ -301,7 +308,7 @@ ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
 }
 
 const TargetMachine &SelectionDAG::getTarget() const {
-  return TLI.getTargetMachine();
+  return MF->getTarget();
 }
 
 //===----------------------------------------------------------------------===//
@@ -323,10 +330,10 @@ static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
 ///
 static void AddNodeIDOperands(FoldingSetNodeID &ID,
-                              const SDOperand *Ops, unsigned NumOps) {
+                              const SDValue *Ops, unsigned NumOps) {
   for (; NumOps; --NumOps, ++Ops) {
-    ID.AddPointer(Ops->Val);
-    ID.AddInteger(Ops->ResNo);
+    ID.AddPointer(Ops->getNode());
+    ID.AddInteger(Ops->getResNo());
   }
 }
 
@@ -335,30 +342,22 @@ static void AddNodeIDOperands(FoldingSetNodeID &ID,
 static void AddNodeIDOperands(FoldingSetNodeID &ID,
                               const SDUse *Ops, unsigned NumOps) {
   for (; NumOps; --NumOps, ++Ops) {
-    ID.AddPointer(Ops->getSDOperand().Val);
-    ID.AddInteger(Ops->getSDOperand().ResNo);
+    ID.AddPointer(Ops->getNode());
+    ID.AddInteger(Ops->getResNo());
   }
 }
 
 static void AddNodeIDNode(FoldingSetNodeID &ID,
                           unsigned short OpC, SDVTList VTList, 
-                          const SDOperand *OpList, unsigned N) {
+                          const SDValue *OpList, unsigned N) {
   AddNodeIDOpcode(ID, OpC);
   AddNodeIDValueTypes(ID, VTList);
   AddNodeIDOperands(ID, OpList, N);
 }
 
-
-/// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
-/// data.
-static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
-  AddNodeIDOpcode(ID, N->getOpcode());
-  // Add the return value info.
-  AddNodeIDValueTypes(ID, N->getVTList());
-  // Add the operand info.
-  AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
-
-  // Handle SDNode leafs with special info.
+/// AddNodeIDCustom - If this is an SDNode with special info, add this info to
+/// the NodeID data.
+static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
   switch (N->getOpcode()) {
   default: break;  // Normal nodes don't need extra info.
   case ISD::ARG_FLAGS:
@@ -366,18 +365,18 @@ static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
     break;
   case ISD::TargetConstant:
   case ISD::Constant:
-    ID.Add(cast<ConstantSDNode>(N)->getAPIntValue());
+    ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
     break;
   case ISD::TargetConstantFP:
   case ISD::ConstantFP: {
-    ID.Add(cast<ConstantFPSDNode>(N)->getValueAPF());
+    ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
     break;
   }
   case ISD::TargetGlobalAddress:
   case ISD::GlobalAddress:
   case ISD::TargetGlobalTLSAddress:
   case ISD::GlobalTLSAddress: {
-    GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
+    const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
     ID.AddPointer(GA->getGlobal());
     ID.AddInteger(GA->getOffset());
     break;
@@ -400,11 +399,7 @@ static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
     break;
   case ISD::MEMOPERAND: {
     const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
-    ID.AddPointer(MO.getValue());
-    ID.AddInteger(MO.getFlags());
-    ID.AddInteger(MO.getOffset());
-    ID.AddInteger(MO.getSize());
-    ID.AddInteger(MO.getAlignment());
+    MO.Profile(ID);
     break;
   }
   case ISD::FrameIndex:
@@ -417,7 +412,7 @@ static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
     break;
   case ISD::ConstantPool:
   case ISD::TargetConstantPool: {
-    ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
+    const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
     ID.AddInteger(CP->getAlignment());
     ID.AddInteger(CP->getOffset());
     if (CP->isMachineConstantPoolEntry())
@@ -426,27 +421,31 @@ static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
       ID.AddPointer(CP->getConstVal());
     break;
   }
+  case ISD::CALL: {
+    const CallSDNode *Call = cast<CallSDNode>(N);
+    ID.AddInteger(Call->getCallingConv());
+    ID.AddInteger(Call->isVarArg());
+    break;
+  }
   case ISD::LOAD: {
-    LoadSDNode *LD = cast<LoadSDNode>(N);
+    const LoadSDNode *LD = cast<LoadSDNode>(N);
     ID.AddInteger(LD->getAddressingMode());
     ID.AddInteger(LD->getExtensionType());
     ID.AddInteger(LD->getMemoryVT().getRawBits());
-    ID.AddInteger(LD->getAlignment());
-    ID.AddInteger(LD->isVolatile());
+    ID.AddInteger(LD->getRawFlags());
     break;
   }
   case ISD::STORE: {
-    StoreSDNode *ST = cast<StoreSDNode>(N);
+    const StoreSDNode *ST = cast<StoreSDNode>(N);
     ID.AddInteger(ST->getAddressingMode());
     ID.AddInteger(ST->isTruncatingStore());
     ID.AddInteger(ST->getMemoryVT().getRawBits());
-    ID.AddInteger(ST->getAlignment());
-    ID.AddInteger(ST->isVolatile());
+    ID.AddInteger(ST->getRawFlags());
     break;
   }
   case ISD::ATOMIC_CMP_SWAP:
-  case ISD::ATOMIC_LOAD_ADD:
   case ISD::ATOMIC_SWAP:
+  case ISD::ATOMIC_LOAD_ADD:
   case ISD::ATOMIC_LOAD_SUB:
   case ISD::ATOMIC_LOAD_AND:
   case ISD::ATOMIC_LOAD_OR:
@@ -456,21 +455,59 @@ static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
   case ISD::ATOMIC_LOAD_MAX:
   case ISD::ATOMIC_LOAD_UMIN:
   case ISD::ATOMIC_LOAD_UMAX: {
-    AtomicSDNode *AT = cast<AtomicSDNode>(N);
-    ID.AddInteger(AT->getAlignment());
-    ID.AddInteger(AT->isVolatile());
+    const AtomicSDNode *AT = cast<AtomicSDNode>(N);
+    ID.AddInteger(AT->getRawFlags());
     break;
   }
   } // end switch (N->getOpcode())
 }
 
+/// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
+/// data.
+static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
+  AddNodeIDOpcode(ID, N->getOpcode());
+  // Add the return value info.
+  AddNodeIDValueTypes(ID, N->getVTList());
+  // Add the operand info.
+  AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
+
+  // Handle SDNode leafs with special info.
+  AddNodeIDCustom(ID, N);
+}
+
+/// encodeMemSDNodeFlags - Generic routine for computing a value for use in
+/// the CSE map that carries both alignment and volatility information.
+///
+static inline unsigned
+encodeMemSDNodeFlags(bool isVolatile, unsigned Alignment) {
+  return isVolatile | ((Log2_32(Alignment) + 1) << 1);
+}
+
 //===----------------------------------------------------------------------===//
 //                              SelectionDAG Class
 //===----------------------------------------------------------------------===//
 
-inline alist_traits<SDNode, LargestSDNode>::AllocatorType &
-SelectionDAG::getAllocator() {
-  return AllNodes.getTraits().Allocator;
+/// doNotCSE - Return true if CSE should not be performed for this node.
+static bool doNotCSE(SDNode *N) {
+  if (N->getValueType(0) == MVT::Flag)
+    return true; // Never CSE anything that produces a flag.
+
+  switch (N->getOpcode()) {
+  default: break;
+  case ISD::HANDLENODE:
+  case ISD::DBG_LABEL:
+  case ISD::DBG_STOPPOINT:
+  case ISD::EH_LABEL:
+  case ISD::DECLARE:
+    return true;   // Never CSE these nodes.
+  }
+
+  // Check that remaining values produced are not flags.
+  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
+    if (N->getValueType(i) == MVT::Flag)
+      return true; // Never CSE anything that produces a flag.
+
+  return false;
 }
 
 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
@@ -501,8 +538,7 @@ void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
   // Process the worklist, deleting the nodes and adding their uses to the
   // worklist.
   while (!DeadNodes.empty()) {
-    SDNode *N = DeadNodes.back();
-    DeadNodes.pop_back();
+    SDNode *N = DeadNodes.pop_back_val();
     
     if (UpdateListener)
       UpdateListener->NodeDeleted(N, 0);
@@ -512,22 +548,17 @@ void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
 
     // Next, brutally remove the operand list.  This is safe to do, as there are
     // no cycles in the graph.
-    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
-      SDNode *Operand = I->getVal();
-      Operand->removeUser(std::distance(N->op_begin(), I), N);
-      
+    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
+      SDUse &Use = *I++;
+      SDNode *Operand = Use.getNode();
+      Use.set(SDValue());
+
       // Now that we removed this operand, see if there are no uses of it left.
       if (Operand->use_empty())
         DeadNodes.push_back(Operand);
     }
-    if (N->OperandsNeedDelete) {
-      delete[] N->OperandList;
-    }
-    N->OperandList = 0;
-    N->NumOperands = 0;
-    
-    // Finally, remove N itself.
-    AllNodes.erase(N);
+
+    DeallocateNode(N);
   }
 }
 
@@ -537,8 +568,6 @@ void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
 }
 
 void SelectionDAG::DeleteNode(SDNode *N) {
-  assert(N->use_empty() && "Cannot delete a node that is not dead!");
-
   // First take this out of the appropriate CSE map.
   RemoveNodeFromCSEMaps(N);
 
@@ -548,27 +577,37 @@ void SelectionDAG::DeleteNode(SDNode *N) {
 }
 
 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
+  assert(N != AllNodes.begin() && "Cannot delete the entry node!");
+  assert(N->use_empty() && "Cannot delete a node that is not dead!");
+
+  // Drop all of the operands and decrement used node's use counts.
+  N->DropOperands();
+
+  DeallocateNode(N);
+}
 
-  // Drop all of the operands and decrement used nodes use counts.
-  for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
-    I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
-  if (N->OperandsNeedDelete) {
+void SelectionDAG::DeallocateNode(SDNode *N) {
+  if (N->OperandsNeedDelete)
     delete[] N->OperandList;
-  }
-  N->OperandList = 0;
-  N->NumOperands = 0;
   
-  AllNodes.erase(N);
+  // Set the opcode to DELETED_NODE to help catch bugs when node
+  // memory is reallocated.
+  N->NodeType = ISD::DELETED_NODE;
+
+  NodeAllocator.Deallocate(AllNodes.remove(N));
 }
 
 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
 /// correspond to it.  This is useful when we're about to delete or repurpose
 /// the node.  We don't want future request for structurally identical nodes
 /// to return N anymore.
-void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
+bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
   bool Erased = false;
   switch (N->getOpcode()) {
-  case ISD::HANDLENODE: return;  // noop.
+  case ISD::EntryToken:
+    assert(0 && "EntryToken should not be in CSEMaps!");
+    return false;
+  case ISD::HANDLENODE: return false;  // noop.
   case ISD::CONDCODE:
     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
            "Cond code doesn't exist!");
@@ -602,75 +641,60 @@ void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
   // flag result (which cannot be CSE'd) or is one of the special cases that are
   // not subject to CSE.
   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
-      !N->isTargetOpcode() &&
-      N->getOpcode() != ISD::DBG_LABEL &&
-      N->getOpcode() != ISD::DBG_STOPPOINT &&
-      N->getOpcode() != ISD::EH_LABEL &&
-      N->getOpcode() != ISD::DECLARE) {
+      !N->isMachineOpcode() && !doNotCSE(N)) {
     N->dump(this);
     cerr << "\n";
     assert(0 && "Node is not in map!");
   }
 #endif
+  return Erased;
 }
 
-/// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
-/// has been taken out and modified in some way.  If the specified node already
-/// exists in the CSE maps, do not modify the maps, but return the existing node
-/// instead.  If it doesn't exist, add it and return null.
+/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
+/// maps and modified in place. Add it back to the CSE maps, unless an identical
+/// node already exists, in which case transfer all its users to the existing
+/// node. This transfer can potentially trigger recursive merging.
 ///
-SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
-  assert(N->getNumOperands() && "This is a leaf node!");
-
-  if (N->getValueType(0) == MVT::Flag)
-    return 0;   // Never CSE anything that produces a flag.
-
-  switch (N->getOpcode()) {
-  default: break;
-  case ISD::HANDLENODE:
-  case ISD::DBG_LABEL:
-  case ISD::DBG_STOPPOINT:
-  case ISD::EH_LABEL:
-  case ISD::DECLARE:
-    return 0;    // Never add these nodes.
+void
+SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N,
+                                       DAGUpdateListener *UpdateListener) {
+  // For node types that aren't CSE'd, just act as if no identical node
+  // already exists.
+  if (!doNotCSE(N)) {
+    SDNode *Existing = CSEMap.GetOrInsertNode(N);
+    if (Existing != N) {
+      // If there was already an existing matching node, use ReplaceAllUsesWith
+      // to replace the dead one with the existing one.  This can cause
+      // recursive merging of other unrelated nodes down the line.
+      ReplaceAllUsesWith(N, Existing, UpdateListener);
+
+      // N is now dead.  Inform the listener if it exists and delete it.
+      if (UpdateListener) 
+        UpdateListener->NodeDeleted(N, Existing);
+      DeleteNodeNotInCSEMaps(N);
+      return;
+    }
   }
-  
-  // Check that remaining values produced are not flags.
-  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
-    if (N->getValueType(i) == MVT::Flag)
-      return 0;   // Never CSE anything that produces a flag.
-  
-  SDNode *New = CSEMap.GetOrInsertNode(N);
-  if (New != N) return New;  // Node already existed.
-  return 0;
+
+  // If the node doesn't already exist, we updated it.  Inform a listener if
+  // it exists.
+  if (UpdateListener) 
+    UpdateListener->NodeUpdated(N);
 }
 
 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
 /// were replaced with those specified.  If this node is never memoized, 
 /// return null, otherwise return a pointer to the slot it would take.  If a
 /// node already exists with these operands, the slot will be non-null.
-SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
+SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
                                            void *&InsertPos) {
-  if (N->getValueType(0) == MVT::Flag)
-    return 0;   // Never CSE anything that produces a flag.
+  if (doNotCSE(N))
+    return 0;
 
-  switch (N->getOpcode()) {
-  default: break;
-  case ISD::HANDLENODE:
-  case ISD::DBG_LABEL:
-  case ISD::DBG_STOPPOINT:
-  case ISD::EH_LABEL:
-    return 0;    // Never add these nodes.
-  }
-  
-  // Check that remaining values produced are not flags.
-  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
-    if (N->getValueType(i) == MVT::Flag)
-      return 0;   // Never CSE anything that produces a flag.
-  
-  SDOperand Ops[] = { Op };
+  SDValue Ops[] = { Op };
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
+  AddNodeIDCustom(ID, N);
   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
 }
 
@@ -679,18 +703,15 @@ SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
 /// return null, otherwise return a pointer to the slot it would take.  If a
 /// node already exists with these operands, the slot will be non-null.
 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
-                                           SDOperand Op1, SDOperand Op2,
+                                           SDValue Op1, SDValue Op2,
                                            void *&InsertPos) {
-  if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
-  
-  // Check that remaining values produced are not flags.
-  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
-    if (N->getValueType(i) == MVT::Flag)
-      return 0;   // Never CSE anything that produces a flag.
-                                              
-  SDOperand Ops[] = { Op1, Op2 };
+  if (doNotCSE(N))
+    return 0;
+
+  SDValue Ops[] = { Op1, Op2 };
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
+  AddNodeIDCustom(ID, N);
   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
 }
 
@@ -700,43 +721,14 @@ SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
 /// return null, otherwise return a pointer to the slot it would take.  If a
 /// node already exists with these operands, the slot will be non-null.
 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
-                                           const SDOperand *Ops,unsigned NumOps,
+                                           const SDValue *Ops,unsigned NumOps,
                                            void *&InsertPos) {
-  if (N->getValueType(0) == MVT::Flag)
-    return 0;   // Never CSE anything that produces a flag.
+  if (doNotCSE(N))
+    return 0;
 
-  switch (N->getOpcode()) {
-  default: break;
-  case ISD::HANDLENODE:
-  case ISD::DBG_LABEL:
-  case ISD::DBG_STOPPOINT:
-  case ISD::EH_LABEL:
-  case ISD::DECLARE:
-    return 0;    // Never add these nodes.
-  }
-  
-  // Check that remaining values produced are not flags.
-  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
-    if (N->getValueType(i) == MVT::Flag)
-      return 0;   // Never CSE anything that produces a flag.
-  
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
-  
-  if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
-    ID.AddInteger(LD->getAddressingMode());
-    ID.AddInteger(LD->getExtensionType());
-    ID.AddInteger(LD->getMemoryVT().getRawBits());
-    ID.AddInteger(LD->getAlignment());
-    ID.AddInteger(LD->isVolatile());
-  } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
-    ID.AddInteger(ST->getAddressingMode());
-    ID.AddInteger(ST->isTruncatingStore());
-    ID.AddInteger(ST->getMemoryVT().getRawBits());
-    ID.AddInteger(ST->getAlignment());
-    ID.AddInteger(ST->isVolatile());
-  }
-  
+  AddNodeIDCustom(ID, N);
   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
 }
 
@@ -745,15 +737,33 @@ void SelectionDAG::VerifyNode(SDNode *N) {
   switch (N->getOpcode()) {
   default:
     break;
+  case ISD::BUILD_PAIR: {
+    MVT VT = N->getValueType(0);
+    assert(N->getNumValues() == 1 && "Too many results!");
+    assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
+           "Wrong return type!");
+    assert(N->getNumOperands() == 2 && "Wrong number of operands!");
+    assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
+           "Mismatched operand types!");
+    assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
+           "Wrong operand type!");
+    assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
+           "Wrong return type size");
+    break;
+  }
   case ISD::BUILD_VECTOR: {
-    assert(N->getNumValues() == 1 && "Too many results for BUILD_VECTOR!");
-    assert(N->getValueType(0).isVector() && "Wrong BUILD_VECTOR return type!");
+    assert(N->getNumValues() == 1 && "Too many results!");
+    assert(N->getValueType(0).isVector() && "Wrong return type!");
     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
-           "Wrong number of BUILD_VECTOR operands!");
-    MVT EltVT = N->getValueType(0).getVectorElementType();
-    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
-      assert(I->getSDOperand().getValueType() == EltVT &&
-             "Wrong BUILD_VECTOR operand type!");
+           "Wrong number of operands!");
+    // FIXME: Change vector_shuffle to a variadic node with mask elements being
+    // operands of the node.  Currently the mask is a BUILD_VECTOR passed as an
+    // operand, and it is not always possible to legalize it.  Turning off the
+    // following checks at least makes it possible to legalize most of the time.
+//    MVT EltVT = N->getValueType(0).getVectorElementType();
+//    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
+//      assert(I->getValueType() == EltVT &&
+//             "Wrong operand type!");
     break;
   }
   }
@@ -770,20 +780,50 @@ unsigned SelectionDAG::getMVTAlignment(MVT VT) const {
   return TLI.getTargetData()->getABITypeAlignment(Ty);
 }
 
+SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
+  : TLI(tli), FLI(fli),
+    EntryNode(ISD::EntryToken, getVTList(MVT::Other)),
+    Root(getEntryNode()) {
+  AllNodes.push_back(&EntryNode);
+}
+
+void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi,
+                        DwarfWriter *dw) {
+  MF = &mf;
+  MMI = mmi;
+  DW = dw;
+}
+
 SelectionDAG::~SelectionDAG() {
-  while (!AllNodes.empty()) {
-    SDNode *N = AllNodes.begin();
-    N->SetNextInBucket(0);
-    if (N->OperandsNeedDelete) {
-      delete [] N->OperandList;
-    }
-    N->OperandList = 0;
-    N->NumOperands = 0;
-    AllNodes.pop_front();
-  }
+  allnodes_clear();
+}
+
+void SelectionDAG::allnodes_clear() {
+  assert(&*AllNodes.begin() == &EntryNode);
+  AllNodes.remove(AllNodes.begin());
+  while (!AllNodes.empty())
+    DeallocateNode(AllNodes.begin());
+}
+
+void SelectionDAG::clear() {
+  allnodes_clear();
+  OperandAllocator.Reset();
+  CSEMap.clear();
+
+  ExtendedValueTypeNodes.clear();
+  ExternalSymbols.clear();
+  TargetExternalSymbols.clear();
+  std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
+            static_cast<CondCodeSDNode*>(0));
+  std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
+            static_cast<SDNode*>(0));
+
+  EntryNode.UseList = 0;
+  AllNodes.push_back(&EntryNode);
+  Root = getEntryNode();
 }
 
-SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT VT) {
+SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, MVT VT) {
   if (Op.getValueType() == VT) return Op;
   APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
                                    VT.getSizeInBits());
@@ -791,12 +831,44 @@ SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT VT) {
                  getConstant(Imm, Op.getValueType()));
 }
 
-SDOperand SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
+SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, DebugLoc DL, MVT VT) {
+  if (Op.getValueType() == VT) return Op;
+  APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
+                                   VT.getSizeInBits());
+  return getNode(ISD::AND, DL, Op.getValueType(), Op,
+                 getConstant(Imm, Op.getValueType()));
+}
+
+/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
+///
+SDValue SelectionDAG::getNOT(DebugLoc DL, SDValue Val, MVT VT) {
+  SDValue NegOne;
+  if (VT.isVector()) {
+    MVT EltVT = VT.getVectorElementType();
+    SDValue NegOneElt = getConstant(EltVT.getIntegerVTBitMask(), EltVT);
+    std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOneElt);
+    NegOne = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(), VT,
+                     &NegOnes[0], NegOnes.size());
+  } else {
+    NegOne = getConstant(VT.getIntegerVTBitMask(), VT);
+  }
+
+  return getNode(ISD::XOR, DL, VT, Val, NegOne);
+}
+
+SDValue SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
   MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
+  assert((EltVT.getSizeInBits() >= 64 ||
+         (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
+         "getConstant with a uint64_t value that doesn't fit in the type!");
   return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
 }
 
-SDOperand SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
+SDValue SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
+  return getConstant(*ConstantInt::get(Val), VT, isT);
+}
+
+SDValue SelectionDAG::getConstant(const ConstantInt &Val, MVT VT, bool isT) {
   assert(VT.isInteger() && "Cannot create FP integer constant!");
 
   MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
@@ -806,34 +878,38 @@ SDOperand SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
-  ID.Add(Val);
+  ID.AddPointer(&Val);
   void *IP = 0;
   SDNode *N = NULL;
   if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
     if (!VT.isVector())
-      return SDOperand(N, 0);
+      return SDValue(N, 0);
   if (!N) {
-    N = getAllocator().Allocate<ConstantSDNode>();
-    new (N) ConstantSDNode(isT, Val, EltVT);
+    N = NodeAllocator.Allocate<ConstantSDNode>();
+    new (N) ConstantSDNode(isT, &Val, EltVT);
     CSEMap.InsertNode(N, IP);
     AllNodes.push_back(N);
   }
 
-  SDOperand Result(N, 0);
+  SDValue Result(N, 0);
   if (VT.isVector()) {
-    SmallVector<SDOperand, 8> Ops;
+    SmallVector<SDValue, 8> Ops;
     Ops.assign(VT.getVectorNumElements(), Result);
     Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
   }
   return Result;
 }
 
-SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
+SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
   return getConstant(Val, TLI.getPointerTy(), isTarget);
 }
 
 
-SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
+SDValue SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
+  return getConstantFP(*ConstantFP::get(V), VT, isTarget);
+}
+
+SDValue SelectionDAG::getConstantFP(const ConstantFP& V, MVT VT, bool isTarget){
   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
                                 
   MVT EltVT =
@@ -845,29 +921,29 @@ SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
-  ID.Add(V);
+  ID.AddPointer(&V);
   void *IP = 0;
   SDNode *N = NULL;
   if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
     if (!VT.isVector())
-      return SDOperand(N, 0);
+      return SDValue(N, 0);
   if (!N) {
-    N = getAllocator().Allocate<ConstantFPSDNode>();
-    new (N) ConstantFPSDNode(isTarget, V, EltVT);
+    N = NodeAllocator.Allocate<ConstantFPSDNode>();
+    new (N) ConstantFPSDNode(isTarget, &V, EltVT);
     CSEMap.InsertNode(N, IP);
     AllNodes.push_back(N);
   }
 
-  SDOperand Result(N, 0);
+  SDValue Result(N, 0);
   if (VT.isVector()) {
-    SmallVector<SDOperand, 8> Ops;
+    SmallVector<SDValue, 8> Ops;
     Ops.assign(VT.getVectorNumElements(), Result);
     Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
   }
   return Result;
 }
 
-SDOperand SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
+SDValue SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
   MVT EltVT =
     VT.isVector() ? VT.getVectorElementType() : VT;
   if (EltVT==MVT::f32)
@@ -876,16 +952,21 @@ SDOperand SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
     return getConstantFP(APFloat(Val), VT, isTarget);
 }
 
-SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
-                                         MVT VT, int Offset,
-                                         bool isTargetGA) {
+SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
+                                       MVT VT, int64_t Offset,
+                                       bool isTargetGA) {
   unsigned Opc;
 
+  // Truncate (with sign-extension) the offset value to the pointer size.
+  unsigned BitWidth = TLI.getPointerTy().getSizeInBits();
+  if (BitWidth < 64)
+    Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
+
   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
   if (!GVar) {
     // If GV is an alias then use the aliasee for determining thread-localness.
     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
-      GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
+      GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
   }
 
   if (GVar && GVar->isThreadLocal())
@@ -899,47 +980,50 @@ SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
   ID.AddInteger(Offset);
   void *IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-   return SDOperand(E, 0);
-  SDNode *N = getAllocator().Allocate<GlobalAddressSDNode>();
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
   new (N) GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
+SDValue SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
   ID.AddInteger(FI);
   void *IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
-  SDNode *N = getAllocator().Allocate<FrameIndexSDNode>();
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
   new (N) FrameIndexSDNode(FI, VT, isTarget);
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
+SDValue SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
   ID.AddInteger(JTI);
   void *IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
-  SDNode *N = getAllocator().Allocate<JumpTableSDNode>();
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
   new (N) JumpTableSDNode(JTI, VT, isTarget);
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getConstantPool(Constant *C, MVT VT,
-                                        unsigned Alignment, int Offset,
-                                        bool isTarget) {
+SDValue SelectionDAG::getConstantPool(Constant *C, MVT VT,
+                                      unsigned Alignment, int Offset,
+                                      bool isTarget) {
+  if (Alignment == 0)
+    Alignment =
+      TLI.getTargetData()->getPreferredTypeAlignmentShift(C->getType());
   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
@@ -948,18 +1032,21 @@ SDOperand SelectionDAG::getConstantPool(Constant *C, MVT VT,
   ID.AddPointer(C);
   void *IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
-  SDNode *N = getAllocator().Allocate<ConstantPoolSDNode>();
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
   new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
 }
 
 
-SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
-                                        unsigned Alignment, int Offset,
-                                        bool isTarget) {
+SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
+                                      unsigned Alignment, int Offset,
+                                      bool isTarget) {
+  if (Alignment == 0)
+    Alignment =
+      TLI.getTargetData()->getPreferredTypeAlignmentShift(C->getType());
   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
@@ -968,129 +1055,198 @@ SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
   C->AddSelectionDAGCSEId(ID);
   void *IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
-  SDNode *N = getAllocator().Allocate<ConstantPoolSDNode>();
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
   new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
 }
 
 
-SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
+SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
   ID.AddPointer(MBB);
   void *IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
-  SDNode *N = getAllocator().Allocate<BasicBlockSDNode>();
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
   new (N) BasicBlockSDNode(MBB);
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
+}
+
+SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB, DebugLoc dl) {
+  FoldingSetNodeID ID;
+  AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
+  ID.AddPointer(MBB);
+  void *IP = 0;
+  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
+  new (N) BasicBlockSDNode(MBB, dl);
+  CSEMap.InsertNode(N, IP);
+  AllNodes.push_back(N);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
+SDValue SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
   ID.AddInteger(Flags.getRawBits());
   void *IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
-  SDNode *N = getAllocator().Allocate<ARG_FLAGSSDNode>();
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<ARG_FLAGSSDNode>();
   new (N) ARG_FLAGSSDNode(Flags);
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getValueType(MVT VT) {
+SDValue SelectionDAG::getValueType(MVT VT) {
   if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
     ValueTypeNodes.resize(VT.getSimpleVT()+1);
 
   SDNode *&N = VT.isExtended() ?
     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
 
-  if (N) return SDOperand(N, 0);
-  N = getAllocator().Allocate<VTSDNode>();
+  if (N) return SDValue(N, 0);
+  N = NodeAllocator.Allocate<VTSDNode>();
   new (N) VTSDNode(VT);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
+SDValue SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
   SDNode *&N = ExternalSymbols[Sym];
-  if (N) return SDOperand(N, 0);
-  N = getAllocator().Allocate<ExternalSymbolSDNode>();
+  if (N) return SDValue(N, 0);
+  N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
   new (N) ExternalSymbolSDNode(false, Sym, VT);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
+}
+
+SDValue SelectionDAG::getExternalSymbol(const char *Sym, DebugLoc dl, MVT VT) {
+  SDNode *&N = ExternalSymbols[Sym];
+  if (N) return SDValue(N, 0);
+  N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
+  new (N) ExternalSymbolSDNode(false, dl, Sym, VT);
+  AllNodes.push_back(N);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
+SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
   SDNode *&N = TargetExternalSymbols[Sym];
-  if (N) return SDOperand(N, 0);
-  N = getAllocator().Allocate<ExternalSymbolSDNode>();
+  if (N) return SDValue(N, 0);
+  N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
   new (N) ExternalSymbolSDNode(true, Sym, VT);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
+SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, DebugLoc dl, 
+                                              MVT VT) {
+  SDNode *&N = TargetExternalSymbols[Sym];
+  if (N) return SDValue(N, 0);
+  N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
+  new (N) ExternalSymbolSDNode(true, dl, Sym, VT);
+  AllNodes.push_back(N);
+  return SDValue(N, 0);
+}
+
+SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
   if ((unsigned)Cond >= CondCodeNodes.size())
     CondCodeNodes.resize(Cond+1);
 
   if (CondCodeNodes[Cond] == 0) {
-    CondCodeSDNode *N = getAllocator().Allocate<CondCodeSDNode>();
+    CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
     new (N) CondCodeSDNode(Cond);
     CondCodeNodes[Cond] = N;
     AllNodes.push_back(N);
   }
-  return SDOperand(CondCodeNodes[Cond], 0);
+  return SDValue(CondCodeNodes[Cond], 0);
+}
+
+SDValue SelectionDAG::getConvertRndSat(MVT VT, SDValue Val, SDValue DTy,
+                                       SDValue STy, SDValue Rnd, SDValue Sat,
+                                       ISD::CvtCode Code) {
+  // If the src and dest types are the same, no conversion is necessary.
+  if (DTy == STy)
+    return Val;
+
+  FoldingSetNodeID ID;
+  void* IP = 0;
+  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
+    return SDValue(E, 0);
+  CvtRndSatSDNode *N = NodeAllocator.Allocate<CvtRndSatSDNode>();
+  SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
+  new (N) CvtRndSatSDNode(VT, Ops, 5, Code);
+  CSEMap.InsertNode(N, IP);
+  AllNodes.push_back(N);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
+SDValue SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
   ID.AddInteger(RegNo);
   void *IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
-  SDNode *N = getAllocator().Allocate<RegisterSDNode>();
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
   new (N) RegisterSDNode(RegNo, VT);
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getDbgStopPoint(SDOperand Root,
-                                        unsigned Line, unsigned Col,
-                                        const CompileUnitDesc *CU) {
-  SDNode *N = getAllocator().Allocate<DbgStopPointSDNode>();
+SDValue SelectionDAG::getDbgStopPoint(SDValue Root,
+                                      unsigned Line, unsigned Col,
+                                      Value *CU) {
+  SDNode *N = NodeAllocator.Allocate<DbgStopPointSDNode>();
   new (N) DbgStopPointSDNode(Root, Line, Col, CU);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getLabel(unsigned Opcode,
-                                 SDOperand Root,
-                                 unsigned LabelID) {
+SDValue SelectionDAG::getLabel(unsigned Opcode,
+                               SDValue Root,
+                               unsigned LabelID) {
   FoldingSetNodeID ID;
-  SDOperand Ops[] = { Root };
+  SDValue Ops[] = { Root };
   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
   ID.AddInteger(LabelID);
   void *IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
-  SDNode *N = getAllocator().Allocate<LabelSDNode>();
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
   new (N) LabelSDNode(Opcode, Root, LabelID);
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
+}
+
+SDValue SelectionDAG::getLabel(unsigned Opcode, DebugLoc dl,
+                               SDValue Root,
+                               unsigned LabelID) {
+  FoldingSetNodeID ID;
+  SDValue Ops[] = { Root };
+  AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
+  ID.AddInteger(LabelID);
+  void *IP = 0;
+  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
+  new (N) LabelSDNode(Opcode, dl, Root, LabelID);
+  CSEMap.InsertNode(N, IP);
+  AllNodes.push_back(N);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getSrcValue(const Value *V) {
+SDValue SelectionDAG::getSrcValue(const Value *V) {
   assert((!V || isa<PointerType>(V->getType())) &&
          "SrcValue is not a pointer?");
 
@@ -1100,44 +1256,53 @@ SDOperand SelectionDAG::getSrcValue(const Value *V) {
 
   void *IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
+    return SDValue(E, 0);
 
-  SDNode *N = getAllocator().Allocate<SrcValueSDNode>();
+  SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
   new (N) SrcValueSDNode(V);
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
+SDValue SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
+#ifndef NDEBUG
   const Value *v = MO.getValue();
   assert((!v || isa<PointerType>(v->getType())) &&
          "SrcValue is not a pointer?");
+#endif
 
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
-  ID.AddPointer(v);
-  ID.AddInteger(MO.getFlags());
-  ID.AddInteger(MO.getOffset());
-  ID.AddInteger(MO.getSize());
-  ID.AddInteger(MO.getAlignment());
+  MO.Profile(ID);
 
   void *IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
+    return SDValue(E, 0);
 
-  SDNode *N = getAllocator().Allocate<MemOperandSDNode>();
+  SDNode *N = NodeAllocator.Allocate<MemOperandSDNode>();
   new (N) MemOperandSDNode(MO);
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
+}
+
+/// getShiftAmountOperand - Return the specified value casted to
+/// the target's desired shift amount type.
+SDValue SelectionDAG::getShiftAmountOperand(SDValue Op) {
+  MVT OpTy = Op.getValueType();
+  MVT ShTy = TLI.getShiftAmountTy();
+  if (OpTy == ShTy || OpTy.isVector()) return Op;
+
+  ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ?  ISD::TRUNCATE : ISD::ZERO_EXTEND;
+  return getNode(Opcode, ShTy, Op);
 }
 
 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
 /// specified value type.
-SDOperand SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
+SDValue SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
   MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
-  unsigned ByteSize = VT.getSizeInBits()/8;
+  unsigned ByteSize = VT.getStoreSizeInBits()/8;
   const Type *Ty = VT.getTypeForMVT();
   unsigned StackAlign =
   std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
@@ -1146,8 +1311,24 @@ SDOperand SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
   return getFrameIndex(FrameIdx, TLI.getPointerTy());
 }
 
-SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
-                                  SDOperand N2, ISD::CondCode Cond) {
+/// CreateStackTemporary - Create a stack temporary suitable for holding
+/// either of the specified value types.
+SDValue SelectionDAG::CreateStackTemporary(MVT VT1, MVT VT2) {
+  unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
+                            VT2.getStoreSizeInBits())/8;
+  const Type *Ty1 = VT1.getTypeForMVT();
+  const Type *Ty2 = VT2.getTypeForMVT();
+  const TargetData *TD = TLI.getTargetData();
+  unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
+                            TD->getPrefTypeAlignment(Ty2));
+
+  MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
+  int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align);
+  return getFrameIndex(FrameIdx, TLI.getPointerTy());
+}
+
+SDValue SelectionDAG::FoldSetCC(MVT VT, SDValue N1,
+                                SDValue N2, ISD::CondCode Cond) {
   // These setcc operations always fold.
   switch (Cond) {
   default: break;
@@ -1170,9 +1351,9 @@ SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
     break;
   }
   
-  if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
+  if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
     const APInt &C2 = N2C->getAPIntValue();
-    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
+    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
       const APInt &C1 = N1C->getAPIntValue();
       
       switch (Cond) {
@@ -1190,11 +1371,11 @@ SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
       }
     }
   }
-  if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
-    if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
+  if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
+    if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
       // No compile time operations on this type yet.
       if (N1C->getValueType(0) == MVT::ppcf128)
-        return SDOperand();
+        return SDValue();
 
       APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
       switch (Cond) {
@@ -1245,12 +1426,12 @@ SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
   }
 
   // Could not fold it.
-  return SDOperand();
+  return SDValue();
 }
 
 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
 /// use this predicate to simplify operations downstream.
-bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
+bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
   unsigned BitWidth = Op.getValueSizeInBits();
   return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
 }
@@ -1258,7 +1439,7 @@ bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
 /// this predicate to simplify operations downstream.  Mask is known to be zero
 /// for bits that V cannot have.
-bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask, 
+bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask, 
                                      unsigned Depth) const {
   APInt KnownZero, KnownOne;
   ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
@@ -1270,7 +1451,7 @@ bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask,
 /// known to be either zero or one and return them in the KnownZero/KnownOne
 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
 /// processing.
-void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask, 
+void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask, 
                                      APInt &KnownZero, APInt &KnownOne,
                                      unsigned Depth) const {
   unsigned BitWidth = Mask.getBitWidth();
@@ -1393,16 +1574,25 @@ void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
     KnownOne &= KnownOne2;
     KnownZero &= KnownZero2;
     return;
+  case ISD::SADDO:
+  case ISD::UADDO:
+  case ISD::SSUBO:
+  case ISD::USUBO:
+  case ISD::SMULO:
+  case ISD::UMULO:
+    if (Op.getResNo() != 1)
+      return;
+    // The boolean result conforms to getBooleanContents.  Fall through.
   case ISD::SETCC:
     // If we know the result of a setcc has the top bits zero, use this info.
-    if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
+    if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent &&
         BitWidth > 1)
       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
     return;
   case ISD::SHL:
     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
-      unsigned ShAmt = SA->getValue();
+      unsigned ShAmt = SA->getZExtValue();
 
       // If the shift count is an invalid immediate, don't do anything.
       if (ShAmt >= BitWidth)
@@ -1420,7 +1610,7 @@ void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
   case ISD::SRL:
     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
-      unsigned ShAmt = SA->getValue();
+      unsigned ShAmt = SA->getZExtValue();
 
       // If the shift count is an invalid immediate, don't do anything.
       if (ShAmt >= BitWidth)
@@ -1438,7 +1628,7 @@ void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
     return;
   case ISD::SRA:
     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
-      unsigned ShAmt = SA->getValue();
+      unsigned ShAmt = SA->getZExtValue();
 
       // If the shift count is an invalid immediate, don't do anything.
       if (ShAmt >= BitWidth)
@@ -1512,7 +1702,7 @@ void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
     return;
   }
   case ISD::LOAD: {
-    if (ISD::isZEXTLoad(Op.Val)) {
+    if (ISD::isZEXTLoad(Op.getNode())) {
       LoadSDNode *LD = cast<LoadSDNode>(Op);
       MVT VT = LD->getMemoryVT();
       unsigned MemBits = VT.getSizeInBits();
@@ -1662,15 +1852,13 @@ void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
         ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
 
-        // The sign of a remainder is equal to the sign of the first
-        // operand (zero being positive).
+        // If the sign bit of the first operand is zero, the sign bit of
+        // the result is zero. If the first operand has no one bits below
+        // the second operand's single 1 bit, its sign will be zero.
         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
           KnownZero2 |= ~LowBits;
-        else if (KnownOne2[BitWidth-1])
-          KnownOne2 |= ~LowBits;
 
         KnownZero |= KnownZero2 & Mask;
-        KnownOne |= KnownOne2 & Mask;
 
         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
       }
@@ -1720,7 +1908,7 @@ void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
 /// is always equal to the sign bit (itself), but other cases can give us
 /// information.  For example, immediately after an "SRA X, 2", we know that
 /// the top 3 bits are all equal to each other, so we return 3.
-unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
+unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
   MVT VT = Op.getValueType();
   assert(VT.isInteger() && "Invalid VT!");
   unsigned VTBits = VT.getSizeInBits();
@@ -1765,7 +1953,7 @@ unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
     // SRA X, C   -> adds C sign bits.
     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
-      Tmp += C->getValue();
+      Tmp += C->getZExtValue();
       if (Tmp > VTBits) Tmp = VTBits;
     }
     return Tmp;
@@ -1773,9 +1961,9 @@ unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
       // shl destroys sign bits.
       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
-      if (C->getValue() >= VTBits ||      // Bad shift.
-          C->getValue() >= Tmp) break;    // Shifted all sign bits out.
-      return Tmp - C->getValue();
+      if (C->getZExtValue() >= VTBits ||      // Bad shift.
+          C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
+      return Tmp - C->getZExtValue();
     }
     break;
   case ISD::AND:
@@ -1797,17 +1985,26 @@ unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
     if (Tmp == 1) return 1;  // Early out.
     Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
     return std::min(Tmp, Tmp2);
-    
+
+  case ISD::SADDO:
+  case ISD::UADDO:
+  case ISD::SSUBO:
+  case ISD::USUBO:
+  case ISD::SMULO:
+  case ISD::UMULO:
+    if (Op.getResNo() != 1)
+      break;
+    // The boolean result conforms to getBooleanContents.  Fall through.
   case ISD::SETCC:
     // If setcc returns 0/-1, all bits are sign bits.
-    if (TLI.getSetCCResultContents() ==
-        TargetLowering::ZeroOrNegativeOneSetCCResult)
+    if (TLI.getBooleanContents() ==
+        TargetLowering::ZeroOrNegativeOneBooleanContent)
       return VTBits;
     break;
   case ISD::ROTL:
   case ISD::ROTR:
     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
-      unsigned RotAmt = C->getValue() & (VTBits-1);
+      unsigned RotAmt = C->getZExtValue() & (VTBits-1);
       
       // Handle rotate right by N like a rotate left by 32-N.
       if (Op.getOpcode() == ISD::ROTR)
@@ -1932,33 +2129,35 @@ unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
 }
 
 
-bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
+bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
   GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
   if (!GA) return false;
+  if (GA->getOffset() != 0) return false;
   GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
   if (!GV) return false;
   MachineModuleInfo *MMI = getMachineModuleInfo();
-  return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
+  return MMI && MMI->hasDebugInfo();
 }
 
 
 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
 /// element of the result of the vector shuffle.
-SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
+SDValue SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
   MVT VT = N->getValueType(0);
-  SDOperand PermMask = N->getOperand(2);
-  SDOperand Idx = PermMask.getOperand(i);
+  SDValue PermMask = N->getOperand(2);
+  SDValue Idx = PermMask.getOperand(i);
   if (Idx.getOpcode() == ISD::UNDEF)
     return getNode(ISD::UNDEF, VT.getVectorElementType());
-  unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
+  unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
   unsigned NumElems = PermMask.getNumOperands();
-  SDOperand V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
+  SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
   Index %= NumElems;
 
   if (V.getOpcode() == ISD::BIT_CONVERT) {
     V = V.getOperand(0);
-    if (V.getValueType().getVectorNumElements() != NumElems)
-      return SDOperand();
+    MVT VVT = V.getValueType();
+    if (!VVT.isVector() || VVT.getVectorNumElements() != NumElems)
+      return SDValue();
   }
   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
     return (Index == 0) ? V.getOperand(0)
@@ -1966,33 +2165,42 @@ SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
   if (V.getOpcode() == ISD::BUILD_VECTOR)
     return V.getOperand(Index);
   if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
-    return getShuffleScalarElt(V.Val, Index);
-  return SDOperand();
+    return getShuffleScalarElt(V.getNode(), Index);
+  return SDValue();
 }
 
 
 /// getNode - Gets or creates the specified node.
 ///
-SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT) {
+SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), VT);
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT) {
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
   void *IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
-  SDNode *N = getAllocator().Allocate<SDNode>();
-  new (N) SDNode(Opcode, SDNode::getSDVTList(VT));
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<SDNode>();
+  new (N) SDNode(Opcode, DL, SDNode::getSDVTList(VT));
   CSEMap.InsertNode(N, IP);
   
   AllNodes.push_back(N);
 #ifndef NDEBUG
   VerifyNode(N);
 #endif
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT, SDValue Operand) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, Operand);
 }
 
-SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
+                              MVT VT, SDValue Operand) {
   // Constant fold unary operations with an integer constant operand.
-  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
+  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
     const APInt &Val = C->getAPIntValue();
     unsigned BitWidth = VT.getSizeInBits();
     switch (Opcode) {
@@ -2033,7 +2241,7 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
   }
 
   // Constant fold unary operations with a floating point constant operand.
-  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
+  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
     APFloat V = C->getValueAPF();    // make copy
     if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
       switch (Opcode) {
@@ -2044,38 +2252,43 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
         V.clearSign();
         return getConstantFP(V, VT);
       case ISD::FP_ROUND:
-      case ISD::FP_EXTEND:
+      case ISD::FP_EXTEND: {
+        bool ignored;
         // This can return overflow, underflow, or inexact; we don't care.
         // FIXME need to be more flexible about rounding mode.
         (void)V.convert(*MVTToAPFloatSemantics(VT),
-                        APFloat::rmNearestTiesToEven);
+                        APFloat::rmNearestTiesToEven, &ignored);
         return getConstantFP(V, VT);
+      }
       case ISD::FP_TO_SINT:
       case ISD::FP_TO_UINT: {
         integerPart x;
+        bool ignored;
         assert(integerPartWidth >= 64);
         // FIXME need to be more flexible about rounding mode.
         APFloat::opStatus s = V.convertToInteger(&x, 64U,
                               Opcode==ISD::FP_TO_SINT,
-                              APFloat::rmTowardZero);
+                              APFloat::rmTowardZero, &ignored);
         if (s==APFloat::opInvalidOp)     // inexact is OK, in fact usual
           break;
         return getConstant(x, VT);
       }
       case ISD::BIT_CONVERT:
         if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
-          return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
+          return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
         else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
-          return getConstant(V.convertToAPInt().getZExtValue(), VT);
+          return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
         break;
       }
     }
   }
 
-  unsigned OpOpcode = Operand.Val->getOpcode();
+  unsigned OpOpcode = Operand.getNode()->getOpcode();
   switch (Opcode) {
   case ISD::TokenFactor:
-    return Operand;         // Factor of one node?  No need.
+  case ISD::MERGE_VALUES:
+  case ISD::CONCAT_VECTORS:
+    return Operand;         // Factor, merge or concat of one node?  No need.
   case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
   case ISD::FP_EXTEND:
     assert(VT.isFloatingPoint() &&
@@ -2091,7 +2304,7 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
     assert(Operand.getValueType().bitsLT(VT)
            && "Invalid sext node, dst < src!");
     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
-      return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
+      return getNode(OpOpcode, VT, Operand.getNode()->getOperand(0));
     break;
   case ISD::ZERO_EXTEND:
     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
@@ -2100,7 +2313,7 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
     assert(Operand.getValueType().bitsLT(VT)
            && "Invalid zext node, dst < src!");
     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
-      return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
+      return getNode(ISD::ZERO_EXTEND, VT, Operand.getNode()->getOperand(0));
     break;
   case ISD::ANY_EXTEND:
     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
@@ -2110,7 +2323,7 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
            && "Invalid anyext node, dst < src!");
     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
-      return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
+      return getNode(OpOpcode, VT, Operand.getNode()->getOperand(0));
     break;
   case ISD::TRUNCATE:
     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
@@ -2119,16 +2332,16 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
     assert(Operand.getValueType().bitsGT(VT)
            && "Invalid truncate node, src < dst!");
     if (OpOpcode == ISD::TRUNCATE)
-      return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
+      return getNode(ISD::TRUNCATE, VT, Operand.getNode()->getOperand(0));
     else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
              OpOpcode == ISD::ANY_EXTEND) {
       // If the source is smaller than the dest, we still need an extend.
-      if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
-        return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
-      else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
-        return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
+      if (Operand.getNode()->getOperand(0).getValueType().bitsLT(VT))
+        return getNode(OpOpcode, VT, Operand.getNode()->getOperand(0));
+      else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
+        return getNode(ISD::TRUNCATE, VT, Operand.getNode()->getOperand(0));
       else
-        return Operand.Val->getOperand(0);
+        return Operand.getNode()->getOperand(0);
     }
     break;
   case ISD::BIT_CONVERT:
@@ -2155,15 +2368,16 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
       return Operand.getOperand(0);
     break;
   case ISD::FNEG:
-    if (OpOpcode == ISD::FSUB)   // -(X-Y) -> (Y-X)
-      return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
-                     Operand.Val->getOperand(0));
+    // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
+    if (UnsafeFPMath && OpOpcode == ISD::FSUB)
+      return getNode(ISD::FSUB, VT, Operand.getNode()->getOperand(1),
+                     Operand.getNode()->getOperand(0));
     if (OpOpcode == ISD::FNEG)  // --X -> X
-      return Operand.Val->getOperand(0);
+      return Operand.getNode()->getOperand(0);
     break;
   case ISD::FABS:
     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
-      return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
+      return getNode(ISD::FABS, VT, Operand.getNode()->getOperand(0));
     break;
   }
 
@@ -2171,30 +2385,71 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
   SDVTList VTs = getVTList(VT);
   if (VT != MVT::Flag) { // Don't CSE flag producing nodes
     FoldingSetNodeID ID;
-    SDOperand Ops[1] = { Operand };
+    SDValue Ops[1] = { Operand };
     AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
     void *IP = 0;
     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-      return SDOperand(E, 0);
-    N = getAllocator().Allocate<UnarySDNode>();
-    new (N) UnarySDNode(Opcode, VTs, Operand);
+      return SDValue(E, 0);
+    N = NodeAllocator.Allocate<UnarySDNode>();
+    new (N) UnarySDNode(Opcode, DL, VTs, Operand);
     CSEMap.InsertNode(N, IP);
   } else {
-    N = getAllocator().Allocate<UnarySDNode>();
-    new (N) UnarySDNode(Opcode, VTs, Operand);
+    N = NodeAllocator.Allocate<UnarySDNode>();
+    new (N) UnarySDNode(Opcode, DL, VTs, Operand);
   }
 
   AllNodes.push_back(N);
 #ifndef NDEBUG
   VerifyNode(N);
 #endif
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
+}
+
+SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
+                                             MVT VT,
+                                             ConstantSDNode *Cst1,
+                                             ConstantSDNode *Cst2) {
+  const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
+
+  switch (Opcode) {
+  case ISD::ADD:  return getConstant(C1 + C2, VT);
+  case ISD::SUB:  return getConstant(C1 - C2, VT);
+  case ISD::MUL:  return getConstant(C1 * C2, VT);
+  case ISD::UDIV:
+    if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
+    break;
+  case ISD::UREM:
+    if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
+    break;
+  case ISD::SDIV:
+    if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
+    break;
+  case ISD::SREM:
+    if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
+    break;
+  case ISD::AND:  return getConstant(C1 & C2, VT);
+  case ISD::OR:   return getConstant(C1 | C2, VT);
+  case ISD::XOR:  return getConstant(C1 ^ C2, VT);
+  case ISD::SHL:  return getConstant(C1 << C2, VT);
+  case ISD::SRL:  return getConstant(C1.lshr(C2), VT);
+  case ISD::SRA:  return getConstant(C1.ashr(C2), VT);
+  case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
+  case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
+  default: break;
+  }
+
+  return SDValue();
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
+                              SDValue N1, SDValue N2) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2);
 }
 
-SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
-                                SDOperand N1, SDOperand N2) {
-  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
-  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
+                              SDValue N1, SDValue N2) {
+  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
+  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
   switch (Opcode) {
   default: break;
   case ISD::TokenFactor:
@@ -2203,6 +2458,17 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
     // Fold trivial token factors.
     if (N1.getOpcode() == ISD::EntryToken) return N2;
     if (N2.getOpcode() == ISD::EntryToken) return N1;
+    if (N1 == N2) return N1;
+    break;
+  case ISD::CONCAT_VECTORS:
+    // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
+    // one big BUILD_VECTOR.
+    if (N1.getOpcode() == ISD::BUILD_VECTOR &&
+        N2.getOpcode() == ISD::BUILD_VECTOR) {
+      SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
+      Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
+      return getNode(ISD::BUILD_VECTOR, VT, &Elts[0], Elts.size());
+    }
     break;
   case ISD::AND:
     assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
@@ -2229,16 +2495,33 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
   case ISD::UREM:
   case ISD::MULHU:
   case ISD::MULHS:
-    assert(VT.isInteger() && "This operator does not apply to FP types!");
-    // fall through
   case ISD::MUL:
   case ISD::SDIV:
   case ISD::SREM:
+    assert(VT.isInteger() && "This operator does not apply to FP types!");
+    // fall through
   case ISD::FADD:
   case ISD::FSUB:
   case ISD::FMUL:
   case ISD::FDIV:
   case ISD::FREM:
+    if (UnsafeFPMath) {
+      if (Opcode == ISD::FADD) {
+        // 0+x --> x
+        if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
+          if (CFP->getValueAPF().isZero())
+            return N2;
+        // x+0 --> x
+        if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
+          if (CFP->getValueAPF().isZero())
+            return N1;
+      } else if (Opcode == ISD::FSUB) {
+        // x-0 --> x
+        if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
+          if (CFP->getValueAPF().isZero())
+            return N1;
+      }
+    }
     assert(N1.getValueType() == N2.getValueType() &&
            N1.getValueType() == VT && "Binary operator types must match!");
     break;
@@ -2308,40 +2591,43 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
     break;
   }
   case ISD::EXTRACT_VECTOR_ELT:
-    assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
-
     // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
     if (N1.getOpcode() == ISD::UNDEF)
       return getNode(ISD::UNDEF, VT);
       
     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
     // expanding copies of large vectors from registers.
-    if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
+    if (N2C &&
+        N1.getOpcode() == ISD::CONCAT_VECTORS &&
         N1.getNumOperands() > 0) {
       unsigned Factor =
         N1.getOperand(0).getValueType().getVectorNumElements();
       return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
-                     N1.getOperand(N2C->getValue() / Factor),
-                     getConstant(N2C->getValue() % Factor, N2.getValueType()));
+                     N1.getOperand(N2C->getZExtValue() / Factor),
+                     getConstant(N2C->getZExtValue() % Factor,
+                                 N2.getValueType()));
     }
 
     // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
     // expanding large vector constants.
-    if (N1.getOpcode() == ISD::BUILD_VECTOR)
-      return N1.getOperand(N2C->getValue());
+    if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR)
+      return N1.getOperand(N2C->getZExtValue());
       
     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
     // operations are lowered to scalars.
-    if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
-      if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
-        if (IEC == N2C)
-          return N1.getOperand(1);
-        else
-          return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
-      }
+    if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
+      // If the indices are the same, return the inserted element.
+      if (N1.getOperand(2) == N2)
+        return N1.getOperand(1);
+      // If the indices are known different, extract the element from
+      // the original vector.
+      else if (isa<ConstantSDNode>(N1.getOperand(2)) &&
+               isa<ConstantSDNode>(N2))
+        return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
+    }
     break;
   case ISD::EXTRACT_ELEMENT:
-    assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
+    assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
     assert(!N1.getValueType().isVector() && !VT.isVector() &&
            (N1.getValueType().isInteger() == VT.isInteger()) &&
            "Wrong types for EXTRACT_ELEMENT!");
@@ -2350,12 +2636,12 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
     // 64-bit integers into 32-bit parts.  Instead of building the extract of
     // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 
     if (N1.getOpcode() == ISD::BUILD_PAIR)
-      return N1.getOperand(N2C->getValue());
+      return N1.getOperand(N2C->getZExtValue());
 
     // EXTRACT_ELEMENT of a constant int is also very common.
     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
       unsigned ElementSize = VT.getSizeInBits();
-      unsigned Shift = ElementSize * N2C->getValue();
+      unsigned Shift = ElementSize * N2C->getZExtValue();
       APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
       return getConstant(ShiftedVal.trunc(ElementSize), VT);
     }
@@ -2368,33 +2654,8 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
 
   if (N1C) {
     if (N2C) {
-      const APInt &C1 = N1C->getAPIntValue(), &C2 = N2C->getAPIntValue();
-      switch (Opcode) {
-      case ISD::ADD: return getConstant(C1 + C2, VT);
-      case ISD::SUB: return getConstant(C1 - C2, VT);
-      case ISD::MUL: return getConstant(C1 * C2, VT);
-      case ISD::UDIV:
-        if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
-        break;
-      case ISD::UREM :
-        if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
-        break;
-      case ISD::SDIV :
-        if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
-        break;
-      case ISD::SREM :
-        if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
-        break;
-      case ISD::AND  : return getConstant(C1 & C2, VT);
-      case ISD::OR   : return getConstant(C1 | C2, VT);
-      case ISD::XOR  : return getConstant(C1 ^ C2, VT);
-      case ISD::SHL  : return getConstant(C1 << C2, VT);
-      case ISD::SRL  : return getConstant(C1.lshr(C2), VT);
-      case ISD::SRA  : return getConstant(C1.ashr(C2), VT);
-      case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
-      case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
-      default: break;
-      }
+      SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
+      if (SV.getNode()) return SV;
     } else {      // Cannonicalize constant to RHS if commutative
       if (isCommutativeBinOp(Opcode)) {
         std::swap(N1C, N2C);
@@ -2404,8 +2665,8 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
   }
 
   // Constant fold FP operations.
-  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
-  ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
+  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
+  ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
   if (N1CFP) {
     if (!N2CFP && isCommutativeBinOp(Opcode)) {
       // Cannonicalize constant to RHS if commutative
@@ -2524,42 +2785,59 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
   SDNode *N;
   SDVTList VTs = getVTList(VT);
   if (VT != MVT::Flag) {
-    SDOperand Ops[] = { N1, N2 };
+    SDValue Ops[] = { N1, N2 };
     FoldingSetNodeID ID;
     AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
     void *IP = 0;
     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-      return SDOperand(E, 0);
-    N = getAllocator().Allocate<BinarySDNode>();
-    new (N) BinarySDNode(Opcode, VTs, N1, N2);
+      return SDValue(E, 0);
+    N = NodeAllocator.Allocate<BinarySDNode>();
+    new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
     CSEMap.InsertNode(N, IP);
   } else {
-    N = getAllocator().Allocate<BinarySDNode>();
-    new (N) BinarySDNode(Opcode, VTs, N1, N2);
+    N = NodeAllocator.Allocate<BinarySDNode>();
+    new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
   }
 
   AllNodes.push_back(N);
 #ifndef NDEBUG
   VerifyNode(N);
 #endif
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
-                                SDOperand N1, SDOperand N2, SDOperand N3) {
+SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
+                              SDValue N1, SDValue N2, SDValue N3) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2, N3);
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
+                              SDValue N1, SDValue N2, SDValue N3) {
   // Perform various simplifications.
-  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
-  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
+  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
+  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
   switch (Opcode) {
+  case ISD::CONCAT_VECTORS:
+    // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
+    // one big BUILD_VECTOR.
+    if (N1.getOpcode() == ISD::BUILD_VECTOR &&
+        N2.getOpcode() == ISD::BUILD_VECTOR &&
+        N3.getOpcode() == ISD::BUILD_VECTOR) {
+      SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
+      Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
+      Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
+      return getNode(ISD::BUILD_VECTOR, VT, &Elts[0], Elts.size());
+    }
+    break;
   case ISD::SETCC: {
     // Use FoldSetCC to simplify SETCC's.
-    SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
-    if (Simp.Val) return Simp;
+    SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
+    if (Simp.getNode()) return Simp;
     break;
   }
   case ISD::SELECT:
     if (N1C) {
-     if (N1C->getValue())
+     if (N1C->getZExtValue())
         return N2;             // select true, X, Y -> X
       else
         return N3;             // select false, X, Y -> Y
@@ -2569,14 +2847,15 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
     break;
   case ISD::BRCOND:
     if (N2C) {
-      if (N2C->getValue()) // Unconditional branch
+      if (N2C->getZExtValue()) // Unconditional branch
         return getNode(ISD::BR, MVT::Other, N1, N3);
       else
         return N1;         // Never-taken branch
     }
     break;
   case ISD::VECTOR_SHUFFLE:
-    assert(VT == N1.getValueType() && VT == N2.getValueType() &&
+    assert(N1.getValueType() == N2.getValueType() &&
+           N1.getValueType().isVector() &&
            VT.isVector() && N3.getValueType().isVector() &&
            N3.getOpcode() == ISD::BUILD_VECTOR &&
            VT.getVectorNumElements() == N3.getNumOperands() &&
@@ -2593,47 +2872,59 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
   SDNode *N;
   SDVTList VTs = getVTList(VT);
   if (VT != MVT::Flag) {
-    SDOperand Ops[] = { N1, N2, N3 };
+    SDValue Ops[] = { N1, N2, N3 };
     FoldingSetNodeID ID;
     AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
     void *IP = 0;
     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-      return SDOperand(E, 0);
-    N = getAllocator().Allocate<TernarySDNode>();
-    new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
+      return SDValue(E, 0);
+    N = NodeAllocator.Allocate<TernarySDNode>();
+    new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
     CSEMap.InsertNode(N, IP);
   } else {
-    N = getAllocator().Allocate<TernarySDNode>();
-    new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
+    N = NodeAllocator.Allocate<TernarySDNode>();
+    new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
   }
   AllNodes.push_back(N);
 #ifndef NDEBUG
   VerifyNode(N);
 #endif
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
+                              SDValue N1, SDValue N2, SDValue N3,
+                              SDValue N4) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2, N3, N4);
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
+                              SDValue N1, SDValue N2, SDValue N3,
+                              SDValue N4) {
+  SDValue Ops[] = { N1, N2, N3, N4 };
+  return getNode(Opcode, DL, VT, Ops, 4);
 }
 
-SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
-                                SDOperand N1, SDOperand N2, SDOperand N3,
-                                SDOperand N4) {
-  SDOperand Ops[] = { N1, N2, N3, N4 };
-  return getNode(Opcode, VT, Ops, 4);
+SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
+                              SDValue N1, SDValue N2, SDValue N3,
+                              SDValue N4, SDValue N5) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2, N3, N4, N5);
 }
 
-SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
-                                SDOperand N1, SDOperand N2, SDOperand N3,
-                                SDOperand N4, SDOperand N5) {
-  SDOperand Ops[] = { N1, N2, N3, N4, N5 };
-  return getNode(Opcode, VT, Ops, 5);
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
+                              SDValue N1, SDValue N2, SDValue N3,
+                              SDValue N4, SDValue N5) {
+  SDValue Ops[] = { N1, N2, N3, N4, N5 };
+  return getNode(Opcode, DL, VT, Ops, 5);
 }
 
 /// getMemsetValue - Vectorized representation of the memset value
 /// operand.
-static SDOperand getMemsetValue(SDOperand Value, MVT VT, SelectionDAG &DAG) {
+static SDValue getMemsetValue(SDValue Value, MVT VT, SelectionDAG &DAG) {
   unsigned NumBits = VT.isVector() ?
     VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
-    APInt Val = APInt(NumBits, C->getValue() & 255);
+    APInt Val = APInt(NumBits, C->getZExtValue() & 255);
     unsigned Shift = 8;
     for (unsigned i = NumBits; i > 8; i >>= 1) {
       Val = (Val << Shift) | Val;
@@ -2644,12 +2935,15 @@ static SDOperand getMemsetValue(SDOperand Value, MVT VT, SelectionDAG &DAG) {
     return DAG.getConstantFP(APFloat(Val), VT);
   }
 
+  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
   Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
   unsigned Shift = 8;
   for (unsigned i = NumBits; i > 8; i >>= 1) {
     Value = DAG.getNode(ISD::OR, VT,
                         DAG.getNode(ISD::SHL, VT, Value,
-                                    DAG.getConstant(Shift, MVT::i8)), Value);
+                                    DAG.getConstant(Shift,
+                                                    TLI.getShiftAmountTy())),
+                        Value);
     Shift <<= 1;
   }
 
@@ -2659,7 +2953,7 @@ static SDOperand getMemsetValue(SDOperand Value, MVT VT, SelectionDAG &DAG) {
 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
 /// used when a memcpy is turned into a memset when the source is a constant
 /// string ptr.
-static SDOperand getMemsetStringVal(MVT VT, SelectionDAG &DAG,
+static SDValue getMemsetStringVal(MVT VT, SelectionDAG &DAG,
                                     const TargetLowering &TLI,
                                     std::string &Str, unsigned Offset) {
   // Handle vector with all elements zero.
@@ -2687,7 +2981,7 @@ static SDOperand getMemsetStringVal(MVT VT, SelectionDAG &DAG,
 
 /// getMemBasePlusOffset - Returns base and offset node for the 
 ///
-static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
+static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
                                       SelectionDAG &DAG) {
   MVT VT = Base.getValueType();
   return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
@@ -2695,7 +2989,7 @@ static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
 
 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
 ///
-static bool isMemSrcFromString(SDOperand Src, std::string &Str) {
+static bool isMemSrcFromString(SDValue Src, std::string &Str) {
   unsigned SrcDelta = 0;
   GlobalAddressSDNode *G = NULL;
   if (Src.getOpcode() == ISD::GlobalAddress)
@@ -2704,7 +2998,7 @@ static bool isMemSrcFromString(SDOperand Src, std::string &Str) {
            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
            Src.getOperand(1).getOpcode() == ISD::Constant) {
     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
-    SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
+    SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
   }
   if (!G)
     return false;
@@ -2721,7 +3015,7 @@ static bool isMemSrcFromString(SDOperand Src, std::string &Str) {
 /// types of the sequence of memory ops to perform memset / memcpy.
 static
 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
-                              SDOperand Dst, SDOperand Src,
+                              SDValue Dst, SDValue Src,
                               unsigned Limit, uint64_t Size, unsigned &Align,
                               std::string &Str, bool &isSrcStr,
                               SelectionDAG &DAG,
@@ -2729,7 +3023,7 @@ bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
   isSrcStr = isMemSrcFromString(Src, Str);
   bool isSrcConst = isa<ConstantSDNode>(Src);
   bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
-  MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
+  MVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
   if (VT != MVT::iAny) {
     unsigned NewAlign = (unsigned)
       TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
@@ -2802,9 +3096,9 @@ bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
   return true;
 }
 
-static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
-                                         SDOperand Chain, SDOperand Dst,
-                                         SDOperand Src, uint64_t Size,
+static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG,
+                                         SDValue Chain, SDValue Dst,
+                                         SDValue Src, uint64_t Size,
                                          unsigned Align, bool AlwaysInline,
                                          const Value *DstSV, uint64_t DstSVOff,
                                          const Value *SrcSV, uint64_t SrcSVOff){
@@ -2813,7 +3107,7 @@ static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
   // Expand memcpy to a series of load and store ops if the size operand falls
   // below a certain threshold.
   std::vector<MVT> MemOps;
-  uint64_t Limit = -1;
+  uint64_t Limit = -1ULL;
   if (!AlwaysInline)
     Limit = TLI.getMaxStoresPerMemcpy();
   unsigned DstAlign = Align;  // Destination alignment can change.
@@ -2821,17 +3115,17 @@ static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
   bool CopyFromStr;
   if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
                                 Str, CopyFromStr, DAG, TLI))
-    return SDOperand();
+    return SDValue();
 
 
   bool isZeroStr = CopyFromStr && Str.empty();
-  SmallVector<SDOperand, 8> OutChains;
+  SmallVector<SDValue, 8> OutChains;
   unsigned NumMemOps = MemOps.size();
   uint64_t SrcOff = 0, DstOff = 0;
   for (unsigned i = 0; i < NumMemOps; i++) {
     MVT VT = MemOps[i];
     unsigned VTSize = VT.getSizeInBits() / 8;
-    SDOperand Value, Store;
+    SDValue Value, Store;
 
     if (CopyFromStr && (isZeroStr || !VT.isVector())) {
       // It's unlikely a store of a vector immediate can be done in a single
@@ -2860,9 +3154,9 @@ static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
                      &OutChains[0], OutChains.size());
 }
 
-static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
-                                          SDOperand Chain, SDOperand Dst,
-                                          SDOperand Src, uint64_t Size,
+static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG,
+                                          SDValue Chain, SDValue Dst,
+                                          SDValue Src, uint64_t Size,
                                           unsigned Align, bool AlwaysInline,
                                           const Value *DstSV, uint64_t DstSVOff,
                                           const Value *SrcSV, uint64_t SrcSVOff){
@@ -2871,7 +3165,7 @@ static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
   // Expand memmove to a series of load and store ops if the size operand falls
   // below a certain threshold.
   std::vector<MVT> MemOps;
-  uint64_t Limit = -1;
+  uint64_t Limit = -1ULL;
   if (!AlwaysInline)
     Limit = TLI.getMaxStoresPerMemmove();
   unsigned DstAlign = Align;  // Destination alignment can change.
@@ -2879,18 +3173,18 @@ static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
   bool CopyFromStr;
   if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
                                 Str, CopyFromStr, DAG, TLI))
-    return SDOperand();
+    return SDValue();
 
   uint64_t SrcOff = 0, DstOff = 0;
 
-  SmallVector<SDOperand, 8> LoadValues;
-  SmallVector<SDOperand, 8> LoadChains;
-  SmallVector<SDOperand, 8> OutChains;
+  SmallVector<SDValue, 8> LoadValues;
+  SmallVector<SDValue, 8> LoadChains;
+  SmallVector<SDValue, 8> OutChains;
   unsigned NumMemOps = MemOps.size();
   for (unsigned i = 0; i < NumMemOps; i++) {
     MVT VT = MemOps[i];
     unsigned VTSize = VT.getSizeInBits() / 8;
-    SDOperand Value, Store;
+    SDValue Value, Store;
 
     Value = DAG.getLoad(VT, Chain,
                         getMemBasePlusOffset(Src, SrcOff, DAG),
@@ -2905,7 +3199,7 @@ static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
   for (unsigned i = 0; i < NumMemOps; i++) {
     MVT VT = MemOps[i];
     unsigned VTSize = VT.getSizeInBits() / 8;
-    SDOperand Value, Store;
+    SDValue Value, Store;
 
     Store = DAG.getStore(Chain, LoadValues[i],
                          getMemBasePlusOffset(Dst, DstOff, DAG),
@@ -2918,9 +3212,9 @@ static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
                      &OutChains[0], OutChains.size());
 }
 
-static SDOperand getMemsetStores(SelectionDAG &DAG,
-                                 SDOperand Chain, SDOperand Dst,
-                                 SDOperand Src, uint64_t Size,
+static SDValue getMemsetStores(SelectionDAG &DAG,
+                                 SDValue Chain, SDValue Dst,
+                                 SDValue Src, uint64_t Size,
                                  unsigned Align,
                                  const Value *DstSV, uint64_t DstSVOff) {
   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
@@ -2932,19 +3226,19 @@ static SDOperand getMemsetStores(SelectionDAG &DAG,
   bool CopyFromStr;
   if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
                                 Size, Align, Str, CopyFromStr, DAG, TLI))
-    return SDOperand();
+    return SDValue();
 
-  SmallVector<SDOperand, 8> OutChains;
+  SmallVector<SDValue, 8> OutChains;
   uint64_t DstOff = 0;
 
   unsigned NumMemOps = MemOps.size();
   for (unsigned i = 0; i < NumMemOps; i++) {
     MVT VT = MemOps[i];
     unsigned VTSize = VT.getSizeInBits() / 8;
-    SDOperand Value = getMemsetValue(Src, VT, DAG);
-    SDOperand Store = DAG.getStore(Chain, Value,
-                                   getMemBasePlusOffset(Dst, DstOff, DAG),
-                                   DstSV, DstSVOff + DstOff);
+    SDValue Value = getMemsetValue(Src, VT, DAG);
+    SDValue Store = DAG.getStore(Chain, Value,
+                                 getMemBasePlusOffset(Dst, DstOff, DAG),
+                                 DstSV, DstSVOff + DstOff);
     OutChains.push_back(Store);
     DstOff += VTSize;
   }
@@ -2953,11 +3247,11 @@ static SDOperand getMemsetStores(SelectionDAG &DAG,
                      &OutChains[0], OutChains.size());
 }
 
-SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
-                                  SDOperand Src, SDOperand Size,
-                                  unsigned Align, bool AlwaysInline,
-                                  const Value *DstSV, uint64_t DstSVOff,
-                                  const Value *SrcSV, uint64_t SrcSVOff) {
+SDValue SelectionDAG::getMemcpy(SDValue Chain, SDValue Dst,
+                                SDValue Src, SDValue Size,
+                                unsigned Align, bool AlwaysInline,
+                                const Value *DstSV, uint64_t DstSVOff,
+                                const Value *SrcSV, uint64_t SrcSVOff) {
 
   // Check to see if we should lower the memcpy to loads and stores first.
   // For cases within the target-specified limits, this is the best choice.
@@ -2967,20 +3261,21 @@ SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
     if (ConstantSize->isNullValue())
       return Chain;
 
-    SDOperand Result =
-      getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
+    SDValue Result =
+      getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
+                              ConstantSize->getZExtValue(),
                               Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
-    if (Result.Val)
+    if (Result.getNode())
       return Result;
   }
 
   // Then check to see if we should lower the memcpy with target-specific
   // code. If the target chooses to do this, this is the next best.
-  SDOperand Result =
+  SDValue Result =
     TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
                                 AlwaysInline,
                                 DstSV, DstSVOff, SrcSV, SrcSVOff);
-  if (Result.Val)
+  if (Result.getNode())
     return Result;
 
   // If we really need inline code and the target declined to provide it,
@@ -2988,7 +3283,7 @@ SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
   if (AlwaysInline) {
     assert(ConstantSize && "AlwaysInline requires a constant size!");
     return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
-                                   ConstantSize->getValue(), Align, true,
+                                   ConstantSize->getZExtValue(), Align, true,
                                    DstSV, DstSVOff, SrcSV, SrcSVOff);
   }
 
@@ -2999,19 +3294,20 @@ SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
   Entry.Node = Dst; Args.push_back(Entry);
   Entry.Node = Src; Args.push_back(Entry);
   Entry.Node = Size; Args.push_back(Entry);
-  std::pair<SDOperand,SDOperand> CallResult =
+  // FIXME: pass in DebugLoc
+  std::pair<SDValue,SDValue> CallResult =
     TLI.LowerCallTo(Chain, Type::VoidTy,
-                    false, false, false, CallingConv::C, false,
+                    false, false, false, false, CallingConv::C, false,
                     getExternalSymbol("memcpy", TLI.getPointerTy()),
-                    Args, *this);
+                    Args, *this, DebugLoc::getUnknownLoc());
   return CallResult.second;
 }
 
-SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
-                                   SDOperand Src, SDOperand Size,
-                                   unsigned Align,
-                                   const Value *DstSV, uint64_t DstSVOff,
-                                   const Value *SrcSV, uint64_t SrcSVOff) {
+SDValue SelectionDAG::getMemmove(SDValue Chain, SDValue Dst,
+                                 SDValue Src, SDValue Size,
+                                 unsigned Align,
+                                 const Value *DstSV, uint64_t DstSVOff,
+                                 const Value *SrcSV, uint64_t SrcSVOff) {
 
   // Check to see if we should lower the memmove to loads and stores first.
   // For cases within the target-specified limits, this is the best choice.
@@ -3021,19 +3317,20 @@ SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
     if (ConstantSize->isNullValue())
       return Chain;
 
-    SDOperand Result =
-      getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
+    SDValue Result =
+      getMemmoveLoadsAndStores(*this, Chain, Dst, Src,
+                               ConstantSize->getZExtValue(),
                                Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
-    if (Result.Val)
+    if (Result.getNode())
       return Result;
   }
 
   // Then check to see if we should lower the memmove with target-specific
   // code. If the target chooses to do this, this is the next best.
-  SDOperand Result =
+  SDValue Result =
     TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
                                  DstSV, DstSVOff, SrcSV, SrcSVOff);
-  if (Result.Val)
+  if (Result.getNode())
     return Result;
 
   // Emit a library call.
@@ -3043,18 +3340,19 @@ SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
   Entry.Node = Dst; Args.push_back(Entry);
   Entry.Node = Src; Args.push_back(Entry);
   Entry.Node = Size; Args.push_back(Entry);
-  std::pair<SDOperand,SDOperand> CallResult =
+  // FIXME:  pass in DebugLoc
+  std::pair<SDValue,SDValue> CallResult =
     TLI.LowerCallTo(Chain, Type::VoidTy,
-                    false, false, false, CallingConv::C, false,
+                    false, false, false, false, CallingConv::C, false,
                     getExternalSymbol("memmove", TLI.getPointerTy()),
-                    Args, *this);
+                    Args, *this, DebugLoc::getUnknownLoc());
   return CallResult.second;
 }
 
-SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
-                                  SDOperand Src, SDOperand Size,
-                                  unsigned Align,
-                                  const Value *DstSV, uint64_t DstSVOff) {
+SDValue SelectionDAG::getMemset(SDValue Chain, SDValue Dst,
+                                SDValue Src, SDValue Size,
+                                unsigned Align,
+                                const Value *DstSV, uint64_t DstSVOff) {
 
   // Check to see if we should lower the memset to stores first.
   // For cases within the target-specified limits, this is the best choice.
@@ -3064,19 +3362,19 @@ SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
     if (ConstantSize->isNullValue())
       return Chain;
 
-    SDOperand Result =
-      getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
-                      DstSV, DstSVOff);
-    if (Result.Val)
+    SDValue Result =
+      getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getZExtValue(),
+                      Align, DstSV, DstSVOff);
+    if (Result.getNode())
       return Result;
   }
 
   // Then check to see if we should lower the memset with target-specific
   // code. If the target chooses to do this, this is the next best.
-  SDOperand Result =
+  SDValue Result =
     TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
                                 DstSV, DstSVOff);
-  if (Result.Val)
+  if (Result.getNode())
     return Result;
 
   // Emit a library call.
@@ -3094,76 +3392,151 @@ SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
   Args.push_back(Entry);
   Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
   Args.push_back(Entry);
-  std::pair<SDOperand,SDOperand> CallResult =
+  // FIXME: pass in DebugLoc
+  std::pair<SDValue,SDValue> CallResult =
     TLI.LowerCallTo(Chain, Type::VoidTy,
-                    false, false, false, CallingConv::C, false,
+                    false, false, false, false, CallingConv::C, false,
                     getExternalSymbol("memset", TLI.getPointerTy()),
-                    Args, *this);
+                    Args, *this, DebugLoc::getUnknownLoc());
   return CallResult.second;
 }
 
-SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain, 
-                                  SDOperand Ptr, SDOperand Cmp, 
-                                  SDOperand Swp, const Value* PtrVal,
-                                  unsigned Alignment) {
+SDValue SelectionDAG::getAtomic(unsigned Opcode, MVT MemVT,
+                                SDValue Chain,
+                                SDValue Ptr, SDValue Cmp, 
+                                SDValue Swp, const Value* PtrVal,
+                                unsigned Alignment) {
   assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
 
   MVT VT = Cmp.getValueType();
 
   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
-    Alignment = getMVTAlignment(VT);
+    Alignment = getMVTAlignment(MemVT);
 
   SDVTList VTs = getVTList(VT, MVT::Other);
   FoldingSetNodeID ID;
-  SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
+  SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
   AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
   void* IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
-  SDNode* N = getAllocator().Allocate<AtomicSDNode>();
-  new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
+    return SDValue(E, 0);
+  SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
+  new (N) AtomicSDNode(Opcode, VTs, MemVT,
+                       Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain, 
-                                  SDOperand Ptr, SDOperand Val, 
-                                  const Value* PtrVal,
-                                  unsigned Alignment) {
-  assert((   Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB
-          || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
-          || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
-          || Opcode == ISD::ATOMIC_LOAD_NAND 
-          || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
-          || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX) 
-         && "Invalid Atomic Op");
+SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, MVT MemVT,
+                                SDValue Chain,
+                                SDValue Ptr, SDValue Cmp, 
+                                SDValue Swp, const Value* PtrVal,
+                                unsigned Alignment) {
+  assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
+  assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
+
+  MVT VT = Cmp.getValueType();
+
+  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
+    Alignment = getMVTAlignment(MemVT);
+
+  SDVTList VTs = getVTList(VT, MVT::Other);
+  FoldingSetNodeID ID;
+  SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
+  AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
+  void* IP = 0;
+  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
+    return SDValue(E, 0);
+  SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
+  new (N) AtomicSDNode(Opcode, dl, VTs, MemVT,
+                       Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
+  CSEMap.InsertNode(N, IP);
+  AllNodes.push_back(N);
+  return SDValue(N, 0);
+}
+
+SDValue SelectionDAG::getAtomic(unsigned Opcode, MVT MemVT,
+                                SDValue Chain,
+                                SDValue Ptr, SDValue Val, 
+                                const Value* PtrVal,
+                                unsigned Alignment) {
+  assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
+          Opcode == ISD::ATOMIC_LOAD_SUB ||
+          Opcode == ISD::ATOMIC_LOAD_AND ||
+          Opcode == ISD::ATOMIC_LOAD_OR ||
+          Opcode == ISD::ATOMIC_LOAD_XOR ||
+          Opcode == ISD::ATOMIC_LOAD_NAND ||
+          Opcode == ISD::ATOMIC_LOAD_MIN || 
+          Opcode == ISD::ATOMIC_LOAD_MAX ||
+          Opcode == ISD::ATOMIC_LOAD_UMIN || 
+          Opcode == ISD::ATOMIC_LOAD_UMAX ||
+          Opcode == ISD::ATOMIC_SWAP) &&
+         "Invalid Atomic Op");
 
   MVT VT = Val.getValueType();
 
   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
-    Alignment = getMVTAlignment(VT);
+    Alignment = getMVTAlignment(MemVT);
+
+  SDVTList VTs = getVTList(VT, MVT::Other);
+  FoldingSetNodeID ID;
+  SDValue Ops[] = {Chain, Ptr, Val};
+  AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
+  void* IP = 0;
+  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
+    return SDValue(E, 0);
+  SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
+  new (N) AtomicSDNode(Opcode, VTs, MemVT,
+                       Chain, Ptr, Val, PtrVal, Alignment);
+  CSEMap.InsertNode(N, IP);
+  AllNodes.push_back(N);
+  return SDValue(N, 0);
+}
+
+SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, MVT MemVT,
+                                SDValue Chain,
+                                SDValue Ptr, SDValue Val, 
+                                const Value* PtrVal,
+                                unsigned Alignment) {
+  assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
+          Opcode == ISD::ATOMIC_LOAD_SUB ||
+          Opcode == ISD::ATOMIC_LOAD_AND ||
+          Opcode == ISD::ATOMIC_LOAD_OR ||
+          Opcode == ISD::ATOMIC_LOAD_XOR ||
+          Opcode == ISD::ATOMIC_LOAD_NAND ||
+          Opcode == ISD::ATOMIC_LOAD_MIN || 
+          Opcode == ISD::ATOMIC_LOAD_MAX ||
+          Opcode == ISD::ATOMIC_LOAD_UMIN || 
+          Opcode == ISD::ATOMIC_LOAD_UMAX ||
+          Opcode == ISD::ATOMIC_SWAP) &&
+         "Invalid Atomic Op");
+
+  MVT VT = Val.getValueType();
+
+  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
+    Alignment = getMVTAlignment(MemVT);
 
   SDVTList VTs = getVTList(VT, MVT::Other);
   FoldingSetNodeID ID;
-  SDOperand Ops[] = {Chain, Ptr, Val};
+  SDValue Ops[] = {Chain, Ptr, Val};
   AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
   void* IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
-  SDNode* N = getAllocator().Allocate<AtomicSDNode>();
-  new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Val, PtrVal, Alignment);
+    return SDValue(E, 0);
+  SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
+  new (N) AtomicSDNode(Opcode, dl, VTs, MemVT,
+                       Chain, Ptr, Val, PtrVal, Alignment);
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
 }
 
 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
 /// Allowed to return something different (and simpler) if Simplify is true.
-SDOperand SelectionDAG::getMergeValues(const SDOperand *Ops, unsigned NumOps,
-                                       bool Simplify) {
-  if (Simplify && NumOps == 1)
+SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps) {
+  if (NumOps == 1)
     return Ops[0];
 
   SmallVector<MVT, 4> VTs;
@@ -3173,10 +3546,140 @@ SDOperand SelectionDAG::getMergeValues(const SDOperand *Ops, unsigned NumOps,
   return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
 }
 
-SDOperand
+SDValue
+SelectionDAG::getMemIntrinsicNode(unsigned Opcode,
+                                  const MVT *VTs, unsigned NumVTs,
+                                  const SDValue *Ops, unsigned NumOps,
+                                  MVT MemVT, const Value *srcValue, int SVOff,
+                                  unsigned Align, bool Vol,
+                                  bool ReadMem, bool WriteMem) {
+  return getMemIntrinsicNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps,
+                             MemVT, srcValue, SVOff, Align, Vol,
+                             ReadMem, WriteMem);
+}
+
+SDValue
+SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
+                                  const MVT *VTs, unsigned NumVTs,
+                                  const SDValue *Ops, unsigned NumOps,
+                                  MVT MemVT, const Value *srcValue, int SVOff,
+                                  unsigned Align, bool Vol,
+                                  bool ReadMem, bool WriteMem) {
+  return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
+                             MemVT, srcValue, SVOff, Align, Vol,
+                             ReadMem, WriteMem);
+}
+
+SDValue
+SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDVTList VTList,
+                                  const SDValue *Ops, unsigned NumOps,
+                                  MVT MemVT, const Value *srcValue, int SVOff,
+                                  unsigned Align, bool Vol,
+                                  bool ReadMem, bool WriteMem) {
+  // Memoize the node unless it returns a flag.
+  MemIntrinsicSDNode *N;
+  if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
+    FoldingSetNodeID ID;
+    AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
+    void *IP = 0;
+    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
+      return SDValue(E, 0);
+    
+    N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
+    new (N) MemIntrinsicSDNode(Opcode, VTList, Ops, NumOps, MemVT,
+                               srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
+    CSEMap.InsertNode(N, IP);
+  } else {
+    N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
+    new (N) MemIntrinsicSDNode(Opcode, VTList, Ops, NumOps, MemVT,
+                               srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
+  }
+  AllNodes.push_back(N);
+  return SDValue(N, 0);
+}
+
+SDValue
+SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
+                                  const SDValue *Ops, unsigned NumOps,
+                                  MVT MemVT, const Value *srcValue, int SVOff,
+                                  unsigned Align, bool Vol,
+                                  bool ReadMem, bool WriteMem) {
+  // Memoize the node unless it returns a flag.
+  MemIntrinsicSDNode *N;
+  if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
+    FoldingSetNodeID ID;
+    AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
+    void *IP = 0;
+    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
+      return SDValue(E, 0);
+    
+    N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
+    new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT,
+                               srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
+    CSEMap.InsertNode(N, IP);
+  } else {
+    N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
+    new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT,
+                               srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
+  }
+  AllNodes.push_back(N);
+  return SDValue(N, 0);
+}
+
+SDValue
+SelectionDAG::getCall(unsigned CallingConv, bool IsVarArgs, bool IsTailCall,
+                      bool IsInreg, SDVTList VTs,
+                      const SDValue *Operands, unsigned NumOperands) {
+  // Do not include isTailCall in the folding set profile.
+  FoldingSetNodeID ID;
+  AddNodeIDNode(ID, ISD::CALL, VTs, Operands, NumOperands);
+  ID.AddInteger(CallingConv);
+  ID.AddInteger(IsVarArgs);
+  void *IP = 0;
+  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
+    // Instead of including isTailCall in the folding set, we just
+    // set the flag of the existing node.
+    if (!IsTailCall)
+      cast<CallSDNode>(E)->setNotTailCall();
+    return SDValue(E, 0);
+  }
+  SDNode *N = NodeAllocator.Allocate<CallSDNode>();
+  new (N) CallSDNode(CallingConv, IsVarArgs, IsTailCall, IsInreg,
+                     VTs, Operands, NumOperands);
+  CSEMap.InsertNode(N, IP);
+  AllNodes.push_back(N);
+  return SDValue(N, 0);
+}
+
+SDValue
+SelectionDAG::getCall(unsigned CallingConv, DebugLoc dl, bool IsVarArgs,
+                      bool IsTailCall, bool IsInreg, SDVTList VTs,
+                      const SDValue *Operands, unsigned NumOperands) {
+  // Do not include isTailCall in the folding set profile.
+  FoldingSetNodeID ID;
+  AddNodeIDNode(ID, ISD::CALL, VTs, Operands, NumOperands);
+  ID.AddInteger(CallingConv);
+  ID.AddInteger(IsVarArgs);
+  void *IP = 0;
+  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
+    // Instead of including isTailCall in the folding set, we just
+    // set the flag of the existing node.
+    if (!IsTailCall)
+      cast<CallSDNode>(E)->setNotTailCall();
+    return SDValue(E, 0);
+  }
+  SDNode *N = NodeAllocator.Allocate<CallSDNode>();
+  new (N) CallSDNode(CallingConv, dl, IsVarArgs, IsTailCall, IsInreg,
+                     VTs, Operands, NumOperands);
+  CSEMap.InsertNode(N, IP);
+  AllNodes.push_back(N);
+  return SDValue(N, 0);
+}
+
+SDValue
 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
-                      MVT VT, SDOperand Chain,
-                      SDOperand Ptr, SDOperand Offset,
+                      MVT VT, SDValue Chain,
+                      SDValue Ptr, SDValue Offset,
                       const Value *SV, int SVOffset, MVT EVT,
                       bool isVolatile, unsigned Alignment) {
   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
@@ -3189,7 +3692,8 @@ SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
   } else {
     // Extending load.
     if (VT.isVector())
-      assert(EVT == VT.getVectorElementType() && "Invalid vector extload!");
+      assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
+             "Invalid vector extload!");
     else
       assert(EVT.bitsLT(VT) &&
              "Should only be an extending load, not truncating!");
@@ -3205,47 +3709,116 @@ SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
 
   SDVTList VTs = Indexed ?
     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
-  SDOperand Ops[] = { Chain, Ptr, Offset };
+  SDValue Ops[] = { Chain, Ptr, Offset };
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
   ID.AddInteger(AM);
   ID.AddInteger(ExtType);
   ID.AddInteger(EVT.getRawBits());
-  ID.AddInteger(Alignment);
-  ID.AddInteger(isVolatile);
+  ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
   void *IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
-  SDNode *N = getAllocator().Allocate<LoadSDNode>();
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
   new (N) LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
                      Alignment, isVolatile);
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
+}
+
+SDValue
+SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl, 
+                      ISD::LoadExtType ExtType, MVT VT, SDValue Chain,
+                      SDValue Ptr, SDValue Offset,
+                      const Value *SV, int SVOffset, MVT EVT,
+                      bool isVolatile, unsigned Alignment) {
+  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
+    Alignment = getMVTAlignment(VT);
+
+  if (VT == EVT) {
+    ExtType = ISD::NON_EXTLOAD;
+  } else if (ExtType == ISD::NON_EXTLOAD) {
+    assert(VT == EVT && "Non-extending load from different memory type!");
+  } else {
+    // Extending load.
+    if (VT.isVector())
+      assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
+             "Invalid vector extload!");
+    else
+      assert(EVT.bitsLT(VT) &&
+             "Should only be an extending load, not truncating!");
+    assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
+           "Cannot sign/zero extend a FP/Vector load!");
+    assert(VT.isInteger() == EVT.isInteger() &&
+           "Cannot convert from FP to Int or Int -> FP!");
+  }
+
+  bool Indexed = AM != ISD::UNINDEXED;
+  assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
+         "Unindexed load with an offset!");
+
+  SDVTList VTs = Indexed ?
+    getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
+  SDValue Ops[] = { Chain, Ptr, Offset };
+  FoldingSetNodeID ID;
+  AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
+  ID.AddInteger(AM);
+  ID.AddInteger(ExtType);
+  ID.AddInteger(EVT.getRawBits());
+  ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
+  void *IP = 0;
+  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
+  new (N) LoadSDNode(Ops, dl, VTs, AM, ExtType, EVT, SV, SVOffset,
+                     Alignment, isVolatile);
+  CSEMap.InsertNode(N, IP);
+  AllNodes.push_back(N);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getLoad(MVT VT,
-                                SDOperand Chain, SDOperand Ptr,
-                                const Value *SV, int SVOffset,
-                                bool isVolatile, unsigned Alignment) {
-  SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
+SDValue SelectionDAG::getLoad(MVT VT,
+                              SDValue Chain, SDValue Ptr,
+                              const Value *SV, int SVOffset,
+                              bool isVolatile, unsigned Alignment) {
+  SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
                  SV, SVOffset, VT, isVolatile, Alignment);
 }
 
-SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
-                                   SDOperand Chain, SDOperand Ptr,
-                                   const Value *SV,
-                                   int SVOffset, MVT EVT,
-                                   bool isVolatile, unsigned Alignment) {
-  SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
+SDValue SelectionDAG::getLoad(MVT VT, DebugLoc dl,
+                              SDValue Chain, SDValue Ptr,
+                              const Value *SV, int SVOffset,
+                              bool isVolatile, unsigned Alignment) {
+  SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
+  return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
+                 SV, SVOffset, VT, isVolatile, Alignment);
+}
+
+SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
+                                 SDValue Chain, SDValue Ptr,
+                                 const Value *SV,
+                                 int SVOffset, MVT EVT,
+                                 bool isVolatile, unsigned Alignment) {
+  SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
   return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
                  SV, SVOffset, EVT, isVolatile, Alignment);
 }
 
-SDOperand
-SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
-                             SDOperand Offset, ISD::MemIndexedMode AM) {
+SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, MVT VT,
+                                 SDValue Chain, SDValue Ptr,
+                                 const Value *SV,
+                                 int SVOffset, MVT EVT,
+                                 bool isVolatile, unsigned Alignment) {
+  SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
+  return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef,
+                 SV, SVOffset, EVT, isVolatile, Alignment);
+}
+
+SDValue
+SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDValue Base,
+                             SDValue Offset, ISD::MemIndexedMode AM) {
   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
   assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
          "Load is already a indexed load!");
@@ -3255,39 +3828,78 @@ SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
                  LD->isVolatile(), LD->getAlignment());
 }
 
-SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
-                                 SDOperand Ptr, const Value *SV, int SVOffset,
-                                 bool isVolatile, unsigned Alignment) {
+SDValue
+SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
+                             SDValue Offset, ISD::MemIndexedMode AM) {
+  LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
+  assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
+         "Load is already a indexed load!");
+  return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(),
+                 LD->getChain(), Base, Offset, LD->getSrcValue(),
+                 LD->getSrcValueOffset(), LD->getMemoryVT(),
+                 LD->isVolatile(), LD->getAlignment());
+}
+
+SDValue SelectionDAG::getStore(SDValue Chain, SDValue Val,
+                               SDValue Ptr, const Value *SV, int SVOffset,
+                               bool isVolatile, unsigned Alignment) {
   MVT VT = Val.getValueType();
 
   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
     Alignment = getMVTAlignment(VT);
 
   SDVTList VTs = getVTList(MVT::Other);
-  SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
-  SDOperand Ops[] = { Chain, Val, Ptr, Undef };
+  SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
+  SDValue Ops[] = { Chain, Val, Ptr, Undef };
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
   ID.AddInteger(ISD::UNINDEXED);
   ID.AddInteger(false);
   ID.AddInteger(VT.getRawBits());
-  ID.AddInteger(Alignment);
-  ID.AddInteger(isVolatile);
+  ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
   void *IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
-  SDNode *N = getAllocator().Allocate<StoreSDNode>();
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
   new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
                       VT, SV, SVOffset, Alignment, isVolatile);
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
+}
+
+SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
+                               SDValue Ptr, const Value *SV, int SVOffset,
+                               bool isVolatile, unsigned Alignment) {
+  MVT VT = Val.getValueType();
+
+  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
+    Alignment = getMVTAlignment(VT);
+
+  SDVTList VTs = getVTList(MVT::Other);
+  SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
+  SDValue Ops[] = { Chain, Val, Ptr, Undef };
+  FoldingSetNodeID ID;
+  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
+  ID.AddInteger(ISD::UNINDEXED);
+  ID.AddInteger(false);
+  ID.AddInteger(VT.getRawBits());
+  ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
+  void *IP = 0;
+  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
+  new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, false,
+                      VT, SV, SVOffset, Alignment, isVolatile);
+  CSEMap.InsertNode(N, IP);
+  AllNodes.push_back(N);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
-                                      SDOperand Ptr, const Value *SV,
-                                      int SVOffset, MVT SVT,
-                                      bool isVolatile, unsigned Alignment) {
+SDValue SelectionDAG::getTruncStore(SDValue Chain, SDValue Val,
+                                    SDValue Ptr, const Value *SV,
+                                    int SVOffset, MVT SVT,
+                                    bool isVolatile, unsigned Alignment) {
   MVT VT = Val.getValueType();
 
   if (VT == SVT)
@@ -3301,89 +3913,155 @@ SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
     Alignment = getMVTAlignment(VT);
 
   SDVTList VTs = getVTList(MVT::Other);
-  SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
-  SDOperand Ops[] = { Chain, Val, Ptr, Undef };
+  SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
+  SDValue Ops[] = { Chain, Val, Ptr, Undef };
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
   ID.AddInteger(ISD::UNINDEXED);
   ID.AddInteger(1);
   ID.AddInteger(SVT.getRawBits());
-  ID.AddInteger(Alignment);
-  ID.AddInteger(isVolatile);
+  ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
   void *IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
-  SDNode *N = getAllocator().Allocate<StoreSDNode>();
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
   new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
                       SVT, SV, SVOffset, Alignment, isVolatile);
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
+}
+
+SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
+                                    SDValue Ptr, const Value *SV,
+                                    int SVOffset, MVT SVT,
+                                    bool isVolatile, unsigned Alignment) {
+  MVT VT = Val.getValueType();
+
+  if (VT == SVT)
+    return getStore(Chain, dl, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
+
+  assert(VT.bitsGT(SVT) && "Not a truncation?");
+  assert(VT.isInteger() == SVT.isInteger() &&
+         "Can't do FP-INT conversion!");
+
+  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
+    Alignment = getMVTAlignment(VT);
+
+  SDVTList VTs = getVTList(MVT::Other);
+  SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
+  SDValue Ops[] = { Chain, Val, Ptr, Undef };
+  FoldingSetNodeID ID;
+  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
+  ID.AddInteger(ISD::UNINDEXED);
+  ID.AddInteger(1);
+  ID.AddInteger(SVT.getRawBits());
+  ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
+  void *IP = 0;
+  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
+  new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, true,
+                      SVT, SV, SVOffset, Alignment, isVolatile);
+  CSEMap.InsertNode(N, IP);
+  AllNodes.push_back(N);
+  return SDValue(N, 0);
 }
 
-SDOperand
-SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
-                              SDOperand Offset, ISD::MemIndexedMode AM) {
+SDValue
+SelectionDAG::getIndexedStore(SDValue OrigStore, SDValue Base,
+                              SDValue Offset, ISD::MemIndexedMode AM) {
   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
   assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
          "Store is already a indexed store!");
   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
-  SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
+  SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
   FoldingSetNodeID ID;
   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
   ID.AddInteger(AM);
   ID.AddInteger(ST->isTruncatingStore());
   ID.AddInteger(ST->getMemoryVT().getRawBits());
-  ID.AddInteger(ST->getAlignment());
-  ID.AddInteger(ST->isVolatile());
+  ID.AddInteger(ST->getRawFlags());
   void *IP = 0;
   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-    return SDOperand(E, 0);
-  SDNode *N = getAllocator().Allocate<StoreSDNode>();
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
   new (N) StoreSDNode(Ops, VTs, AM,
                       ST->isTruncatingStore(), ST->getMemoryVT(),
                       ST->getSrcValue(), ST->getSrcValueOffset(),
                       ST->getAlignment(), ST->isVolatile());
   CSEMap.InsertNode(N, IP);
   AllNodes.push_back(N);
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
+}
+
+SDValue
+SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
+                              SDValue Offset, ISD::MemIndexedMode AM) {
+  StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
+  assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
+         "Store is already a indexed store!");
+  SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
+  SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
+  FoldingSetNodeID ID;
+  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
+  ID.AddInteger(AM);
+  ID.AddInteger(ST->isTruncatingStore());
+  ID.AddInteger(ST->getMemoryVT().getRawBits());
+  ID.AddInteger(ST->getRawFlags());
+  void *IP = 0;
+  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
+    return SDValue(E, 0);
+  SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
+  new (N) StoreSDNode(Ops, dl, VTs, AM,
+                      ST->isTruncatingStore(), ST->getMemoryVT(),
+                      ST->getSrcValue(), ST->getSrcValueOffset(),
+                      ST->getAlignment(), ST->isVolatile());
+  CSEMap.InsertNode(N, IP);
+  AllNodes.push_back(N);
+  return SDValue(N, 0);
 }
 
-SDOperand SelectionDAG::getVAArg(MVT VT,
-                                 SDOperand Chain, SDOperand Ptr,
-                                 SDOperand SV) {
-  SDOperand Ops[] = { Chain, Ptr, SV };
+SDValue SelectionDAG::getVAArg(MVT VT,
+                               SDValue Chain, SDValue Ptr,
+                               SDValue SV) {
+  SDValue Ops[] = { Chain, Ptr, SV };
   return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
 }
 
-SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
-                                const SDUse *Ops, unsigned NumOps) {
+SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
+                              const SDUse *Ops, unsigned NumOps) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, Ops, NumOps);
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
+                              const SDUse *Ops, unsigned NumOps) {
   switch (NumOps) {
-  case 0: return getNode(Opcode, VT);
-  case 1: return getNode(Opcode, VT, Ops[0].getSDOperand());
-  case 2: return getNode(Opcode, VT, Ops[0].getSDOperand(),
-                         Ops[1].getSDOperand());
-  case 3: return getNode(Opcode, VT, Ops[0].getSDOperand(),
-                         Ops[1].getSDOperand(), Ops[2].getSDOperand());
+  case 0: return getNode(Opcode, DL, VT);
+  case 1: return getNode(Opcode, DL, VT, Ops[0]);
+  case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
+  case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
   default: break;
   }
 
-  // Copy from an SDUse array into an SDOperand array for use with
+  // Copy from an SDUse array into an SDValue array for use with
   // the regular getNode logic.
-  SmallVector<SDOperand, 8> NewOps;
-  NewOps.reserve(NumOps);
-  for (unsigned i = 0; i != NumOps; ++i)
-    NewOps.push_back(Ops[i].getSDOperand());
-  return getNode(Opcode, VT, Ops, NumOps);
+  SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
+  return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
+                              const SDValue *Ops, unsigned NumOps) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, Ops, NumOps);
 }
 
-SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
-                                const SDOperand *Ops, unsigned NumOps) {
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
+                              const SDValue *Ops, unsigned NumOps) {
   switch (NumOps) {
-  case 0: return getNode(Opcode, VT);
-  case 1: return getNode(Opcode, VT, Ops[0]);
-  case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
-  case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
+  case 0: return getNode(Opcode, DL, VT);
+  case 1: return getNode(Opcode, DL, VT, Ops[0]);
+  case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
+  case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
   default: break;
   }
   
@@ -3410,45 +4088,66 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
   // Memoize nodes.
   SDNode *N;
   SDVTList VTs = getVTList(VT);
+
   if (VT != MVT::Flag) {
     FoldingSetNodeID ID;
     AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
     void *IP = 0;
+
     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-      return SDOperand(E, 0);
-    N = getAllocator().Allocate<SDNode>();
-    new (N) SDNode(Opcode, VTs, Ops, NumOps);
+      return SDValue(E, 0);
+
+    N = NodeAllocator.Allocate<SDNode>();
+    new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
     CSEMap.InsertNode(N, IP);
   } else {
-    N = getAllocator().Allocate<SDNode>();
-    new (N) SDNode(Opcode, VTs, Ops, NumOps);
+    N = NodeAllocator.Allocate<SDNode>();
+    new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
   }
+
   AllNodes.push_back(N);
 #ifndef NDEBUG
   VerifyNode(N);
 #endif
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode,
+                              const std::vector<MVT> &ResultTys,
+                              const SDValue *Ops, unsigned NumOps) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), ResultTys, Ops, NumOps);
 }
 
-SDOperand SelectionDAG::getNode(unsigned Opcode,
-                                const std::vector<MVT> &ResultTys,
-                                const SDOperand *Ops, unsigned NumOps) {
-  return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
+                              const std::vector<MVT> &ResultTys,
+                              const SDValue *Ops, unsigned NumOps) {
+  return getNode(Opcode, DL, getNodeValueTypes(ResultTys), ResultTys.size(),
                  Ops, NumOps);
 }
 
-SDOperand SelectionDAG::getNode(unsigned Opcode,
-                                const MVT *VTs, unsigned NumVTs,
-                                const SDOperand *Ops, unsigned NumOps) {
+SDValue SelectionDAG::getNode(unsigned Opcode,
+                              const MVT *VTs, unsigned NumVTs,
+                              const SDValue *Ops, unsigned NumOps) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), VTs, NumVTs, Ops, NumOps);
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
+                              const MVT *VTs, unsigned NumVTs,
+                              const SDValue *Ops, unsigned NumOps) {
   if (NumVTs == 1)
-    return getNode(Opcode, VTs[0], Ops, NumOps);
-  return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
+    return getNode(Opcode, DL, VTs[0], Ops, NumOps);
+  return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
 }  
   
-SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
-                                const SDOperand *Ops, unsigned NumOps) {
+SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
+                              const SDValue *Ops, unsigned NumOps) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, Ops, NumOps);
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
+                              const SDValue *Ops, unsigned NumOps) {
   if (VTList.NumVTs == 1)
-    return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
+    return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
 
   switch (Opcode) {
   // FIXME: figure out how to safely handle things like
@@ -3460,14 +4159,14 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
   case ISD::SHL_PARTS:
     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
-      return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
+      return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
     else if (N3.getOpcode() == ISD::AND)
       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
         // If the and is only masking out bits that cannot effect the shift,
         // eliminate the and.
         unsigned NumBits = VT.getSizeInBits()*2;
         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
-          return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
+          return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
       }
     break;
 #endif
@@ -3480,77 +4179,108 @@ SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
     void *IP = 0;
     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
-      return SDOperand(E, 0);
+      return SDValue(E, 0);
     if (NumOps == 1) {
-      N = getAllocator().Allocate<UnarySDNode>();
-      new (N) UnarySDNode(Opcode, VTList, Ops[0]);
+      N = NodeAllocator.Allocate<UnarySDNode>();
+      new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
     } else if (NumOps == 2) {
-      N = getAllocator().Allocate<BinarySDNode>();
-      new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
+      N = NodeAllocator.Allocate<BinarySDNode>();
+      new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
     } else if (NumOps == 3) {
-      N = getAllocator().Allocate<TernarySDNode>();
-      new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
+      N = NodeAllocator.Allocate<TernarySDNode>();
+      new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
     } else {
-      N = getAllocator().Allocate<SDNode>();
-      new (N) SDNode(Opcode, VTList, Ops, NumOps);
+      N = NodeAllocator.Allocate<SDNode>();
+      new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
     }
     CSEMap.InsertNode(N, IP);
   } else {
     if (NumOps == 1) {
-      N = getAllocator().Allocate<UnarySDNode>();
-      new (N) UnarySDNode(Opcode, VTList, Ops[0]);
+      N = NodeAllocator.Allocate<UnarySDNode>();
+      new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
     } else if (NumOps == 2) {
-      N = getAllocator().Allocate<BinarySDNode>();
-      new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
+      N = NodeAllocator.Allocate<BinarySDNode>();
+      new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
     } else if (NumOps == 3) {
-      N = getAllocator().Allocate<TernarySDNode>();
-      new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
+      N = NodeAllocator.Allocate<TernarySDNode>();
+      new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
     } else {
-      N = getAllocator().Allocate<SDNode>();
-      new (N) SDNode(Opcode, VTList, Ops, NumOps);
+      N = NodeAllocator.Allocate<SDNode>();
+      new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
     }
   }
   AllNodes.push_back(N);
 #ifndef NDEBUG
   VerifyNode(N);
 #endif
-  return SDOperand(N, 0);
+  return SDValue(N, 0);
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList); 
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
+  return getNode(Opcode, DL, VTList, 0, 0);
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
+                              SDValue N1) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1);
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
+                              SDValue N1) {
+  SDValue Ops[] = { N1 };
+  return getNode(Opcode, DL, VTList, Ops, 1);
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
+                              SDValue N1, SDValue N2) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2);
+}
+
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
+                              SDValue N1, SDValue N2) {
+  SDValue Ops[] = { N1, N2 };
+  return getNode(Opcode, DL, VTList, Ops, 2);
 }
 
-SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
-  return getNode(Opcode, VTList, 0, 0);
+SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
+                              SDValue N1, SDValue N2, SDValue N3) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2, N3);
 }
 
-SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
-                                SDOperand N1) {
-  SDOperand Ops[] = { N1 };
-  return getNode(Opcode, VTList, Ops, 1);
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
+                              SDValue N1, SDValue N2, SDValue N3) {
+  SDValue Ops[] = { N1, N2, N3 };
+  return getNode(Opcode, DL, VTList, Ops, 3);
 }
 
-SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
-                                SDOperand N1, SDOperand N2) {
-  SDOperand Ops[] = { N1, N2 };
-  return getNode(Opcode, VTList, Ops, 2);
+SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
+                              SDValue N1, SDValue N2, SDValue N3,
+                              SDValue N4) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2, N3, N4);
 }
 
-SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
-                                SDOperand N1, SDOperand N2, SDOperand N3) {
-  SDOperand Ops[] = { N1, N2, N3 };
-  return getNode(Opcode, VTList, Ops, 3);
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
+                              SDValue N1, SDValue N2, SDValue N3,
+                              SDValue N4) {
+  SDValue Ops[] = { N1, N2, N3, N4 };
+  return getNode(Opcode, DL, VTList, Ops, 4);
 }
 
-SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
-                                SDOperand N1, SDOperand N2, SDOperand N3,
-                                SDOperand N4) {
-  SDOperand Ops[] = { N1, N2, N3, N4 };
-  return getNode(Opcode, VTList, Ops, 4);
+SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
+                              SDValue N1, SDValue N2, SDValue N3,
+                              SDValue N4, SDValue N5) {
+  return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2, N3, N4, N5);
 }
 
-SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
-                                SDOperand N1, SDOperand N2, SDOperand N3,
-                                SDOperand N4, SDOperand N5) {
-  SDOperand Ops[] = { N1, N2, N3, N4, N5 };
-  return getNode(Opcode, VTList, Ops, 5);
+SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
+                              SDValue N1, SDValue N2, SDValue N3,
+                              SDValue N4, SDValue N5) {
+  SDValue Ops[] = { N1, N2, N3, N4, N5 };
+  return getNode(Opcode, DL, VTList, Ops, 5);
 }
 
 SDVTList SelectionDAG::getVTList(MVT VT) {
@@ -3587,6 +4317,23 @@ SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3) {
   return Result;
 }
 
+SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3, MVT VT4) {
+  for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
+       E = VTList.rend(); I != E; ++I)
+    if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
+                          I->VTs[2] == VT3 && I->VTs[3] == VT4)
+      return *I;
+
+  MVT *Array = Allocator.Allocate<MVT>(3);
+  Array[0] = VT1;
+  Array[1] = VT2;
+  Array[2] = VT3;
+  Array[3] = VT4;
+  SDVTList Result = makeVTList(Array, 4);
+  VTList.push_back(Result);
+  return Result;
+}
+
 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
   switch (NumVTs) {
     case 0: assert(0 && "Cannot have nodes without results!");
@@ -3625,9 +4372,8 @@ SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
 /// already exists.  If the resultant node does not exist in the DAG, the
 /// input node is returned.  As a degenerate case, if you specify the same
 /// input operands as the node already has, the input node is returned.
-SDOperand SelectionDAG::
-UpdateNodeOperands(SDOperand InN, SDOperand Op) {
-  SDNode *N = InN.Val;
+SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
+  SDNode *N = InN.getNode();
   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
   
   // Check to see if there is no change.
@@ -3636,26 +4382,24 @@ UpdateNodeOperands(SDOperand InN, SDOperand Op) {
   // See if the modified node already exists.
   void *InsertPos = 0;
   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
-    return SDOperand(Existing, InN.ResNo);
+    return SDValue(Existing, InN.getResNo());
   
   // Nope it doesn't.  Remove the node from its current place in the maps.
   if (InsertPos)
-    RemoveNodeFromCSEMaps(N);
+    if (!RemoveNodeFromCSEMaps(N))
+      InsertPos = 0;
   
   // Now we update the operands.
-  N->OperandList[0].getVal()->removeUser(0, N);
-  N->OperandList[0] = Op;
-  N->OperandList[0].setUser(N);
-  Op.Val->addUser(0, N);
+  N->OperandList[0].set(Op);
   
   // If this gets put into a CSE map, add it.
   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
   return InN;
 }
 
-SDOperand SelectionDAG::
-UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
-  SDNode *N = InN.Val;
+SDValue SelectionDAG::
+UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
+  SDNode *N = InN.getNode();
   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
   
   // Check to see if there is no change.
@@ -3665,54 +4409,47 @@ UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
   // See if the modified node already exists.
   void *InsertPos = 0;
   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
-    return SDOperand(Existing, InN.ResNo);
+    return SDValue(Existing, InN.getResNo());
   
   // Nope it doesn't.  Remove the node from its current place in the maps.
   if (InsertPos)
-    RemoveNodeFromCSEMaps(N);
+    if (!RemoveNodeFromCSEMaps(N))
+      InsertPos = 0;
   
   // Now we update the operands.
-  if (N->OperandList[0] != Op1) {
-    N->OperandList[0].getVal()->removeUser(0, N);
-    N->OperandList[0] = Op1;
-    N->OperandList[0].setUser(N);
-    Op1.Val->addUser(0, N);
-  }
-  if (N->OperandList[1] != Op2) {
-    N->OperandList[1].getVal()->removeUser(1, N);
-    N->OperandList[1] = Op2;
-    N->OperandList[1].setUser(N);
-    Op2.Val->addUser(1, N);
-  }
+  if (N->OperandList[0] != Op1)
+    N->OperandList[0].set(Op1);
+  if (N->OperandList[1] != Op2)
+    N->OperandList[1].set(Op2);
   
   // If this gets put into a CSE map, add it.
   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
   return InN;
 }
 
-SDOperand SelectionDAG::
-UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
-  SDOperand Ops[] = { Op1, Op2, Op3 };
+SDValue SelectionDAG::
+UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
+  SDValue Ops[] = { Op1, Op2, Op3 };
   return UpdateNodeOperands(N, Ops, 3);
 }
 
-SDOperand SelectionDAG::
-UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, 
-                   SDOperand Op3, SDOperand Op4) {
-  SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
+SDValue SelectionDAG::
+UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, 
+                   SDValue Op3, SDValue Op4) {
+  SDValue Ops[] = { Op1, Op2, Op3, Op4 };
   return UpdateNodeOperands(N, Ops, 4);
 }
 
-SDOperand SelectionDAG::
-UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
-                   SDOperand Op3, SDOperand Op4, SDOperand Op5) {
-  SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
+SDValue SelectionDAG::
+UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
+                   SDValue Op3, SDValue Op4, SDValue Op5) {
+  SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
   return UpdateNodeOperands(N, Ops, 5);
 }
 
-SDOperand SelectionDAG::
-UpdateNodeOperands(SDOperand InN, const SDOperand *Ops, unsigned NumOps) {
-  SDNode *N = InN.Val;
+SDValue SelectionDAG::
+UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
+  SDNode *N = InN.getNode();
   assert(N->getNumOperands() == NumOps &&
          "Update with wrong number of operands");
   
@@ -3731,21 +4468,17 @@ UpdateNodeOperands(SDOperand InN, const SDOperand *Ops, unsigned NumOps) {
   // See if the modified node already exists.
   void *InsertPos = 0;
   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
-    return SDOperand(Existing, InN.ResNo);
+    return SDValue(Existing, InN.getResNo());
   
   // Nope it doesn't.  Remove the node from its current place in the maps.
   if (InsertPos)
-    RemoveNodeFromCSEMaps(N);
+    if (!RemoveNodeFromCSEMaps(N))
+      InsertPos = 0;
   
   // Now we update the operands.
-  for (unsigned i = 0; i != NumOps; ++i) {
-    if (N->OperandList[i] != Ops[i]) {
-      N->OperandList[i].getVal()->removeUser(i, N);
-      N->OperandList[i] = Ops[i];
-      N->OperandList[i].setUser(N);
-      Ops[i].Val->addUser(i, N);
-    }
-  }
+  for (unsigned i = 0; i != NumOps; ++i)
+    if (N->OperandList[i] != Ops[i])
+      N->OperandList[i].set(Ops[i]);
 
   // If this gets put into a CSE map, add it.
   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
@@ -3757,10 +4490,10 @@ UpdateNodeOperands(SDOperand InN, const SDOperand *Ops, unsigned NumOps) {
 void SDNode::DropOperands() {
   // Unlike the code in MorphNodeTo that does this, we don't need to
   // watch for dead nodes here.
-  for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
-    I->getVal()->removeUser(std::distance(op_begin(), I), this);
-
-  NumOperands = 0;
+  for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
+    SDUse &Use = *I++;
+    Use.set(SDValue());
+  }
 }
 
 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
@@ -3773,37 +4506,37 @@ SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
 }
 
 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
-                                   MVT VT, SDOperand Op1) {
+                                   MVT VT, SDValue Op1) {
   SDVTList VTs = getVTList(VT);
-  SDOperand Ops[] = { Op1 };
+  SDValue Ops[] = { Op1 };
   return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
 }
 
 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
-                                   MVT VT, SDOperand Op1,
-                                   SDOperand Op2) {
+                                   MVT VT, SDValue Op1,
+                                   SDValue Op2) {
   SDVTList VTs = getVTList(VT);
-  SDOperand Ops[] = { Op1, Op2 };
+  SDValue Ops[] = { Op1, Op2 };
   return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
 }
 
 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
-                                   MVT VT, SDOperand Op1,
-                                   SDOperand Op2, SDOperand Op3) {
+                                   MVT VT, SDValue Op1,
+                                   SDValue Op2, SDValue Op3) {
   SDVTList VTs = getVTList(VT);
-  SDOperand Ops[] = { Op1, Op2, Op3 };
+  SDValue Ops[] = { Op1, Op2, Op3 };
   return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
 }
 
 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
-                                   MVT VT, const SDOperand *Ops,
+                                   MVT VT, const SDValue *Ops,
                                    unsigned NumOps) {
   SDVTList VTs = getVTList(VT);
   return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
 }
 
 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
-                                   MVT VT1, MVT VT2, const SDOperand *Ops,
+                                   MVT VT1, MVT VT2, const SDValue *Ops,
                                    unsigned NumOps) {
   SDVTList VTs = getVTList(VT1, VT2);
   return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
@@ -3812,43 +4545,59 @@ SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
                                    MVT VT1, MVT VT2) {
   SDVTList VTs = getVTList(VT1, VT2);
-  return SelectNodeTo(N, MachineOpc, VTs, (SDOperand *)0, 0);
+  return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
 }
 
 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
                                    MVT VT1, MVT VT2, MVT VT3,
-                                   const SDOperand *Ops, unsigned NumOps) {
+                                   const SDValue *Ops, unsigned NumOps) {
   SDVTList VTs = getVTList(VT1, VT2, VT3);
   return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
 }
 
+SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
+                                   MVT VT1, MVT VT2, MVT VT3, MVT VT4,
+                                   const SDValue *Ops, unsigned NumOps) {
+  SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
+  return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
+}
+
 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 
                                    MVT VT1, MVT VT2,
-                                   SDOperand Op1) {
+                                   SDValue Op1) {
   SDVTList VTs = getVTList(VT1, VT2);
-  SDOperand Ops[] = { Op1 };
+  SDValue Ops[] = { Op1 };
   return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
 }
 
 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 
                                    MVT VT1, MVT VT2,
-                                   SDOperand Op1, SDOperand Op2) {
+                                   SDValue Op1, SDValue Op2) {
   SDVTList VTs = getVTList(VT1, VT2);
-  SDOperand Ops[] = { Op1, Op2 };
+  SDValue Ops[] = { Op1, Op2 };
   return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
 }
 
 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
                                    MVT VT1, MVT VT2,
-                                   SDOperand Op1, SDOperand Op2, 
-                                   SDOperand Op3) {
+                                   SDValue Op1, SDValue Op2, 
+                                   SDValue Op3) {
   SDVTList VTs = getVTList(VT1, VT2);
-  SDOperand Ops[] = { Op1, Op2, Op3 };
+  SDValue Ops[] = { Op1, Op2, Op3 };
+  return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
+}
+
+SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
+                                   MVT VT1, MVT VT2, MVT VT3,
+                                   SDValue Op1, SDValue Op2, 
+                                   SDValue Op3) {
+  SDVTList VTs = getVTList(VT1, VT2, VT3);
+  SDValue Ops[] = { Op1, Op2, Op3 };
   return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
 }
 
 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
-                                   SDVTList VTs, const SDOperand *Ops,
+                                   SDVTList VTs, const SDValue *Ops,
                                    unsigned NumOps) {
   return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
 }
@@ -3860,37 +4609,37 @@ SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
 }
 
 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
-                                  MVT VT, SDOperand Op1) {
+                                  MVT VT, SDValue Op1) {
   SDVTList VTs = getVTList(VT);
-  SDOperand Ops[] = { Op1 };
+  SDValue Ops[] = { Op1 };
   return MorphNodeTo(N, Opc, VTs, Ops, 1);
 }
 
 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
-                                  MVT VT, SDOperand Op1,
-                                  SDOperand Op2) {
+                                  MVT VT, SDValue Op1,
+                                  SDValue Op2) {
   SDVTList VTs = getVTList(VT);
-  SDOperand Ops[] = { Op1, Op2 };
+  SDValue Ops[] = { Op1, Op2 };
   return MorphNodeTo(N, Opc, VTs, Ops, 2);
 }
 
 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
-                                  MVT VT, SDOperand Op1,
-                                  SDOperand Op2, SDOperand Op3) {
+                                  MVT VT, SDValue Op1,
+                                  SDValue Op2, SDValue Op3) {
   SDVTList VTs = getVTList(VT);
-  SDOperand Ops[] = { Op1, Op2, Op3 };
+  SDValue Ops[] = { Op1, Op2, Op3 };
   return MorphNodeTo(N, Opc, VTs, Ops, 3);
 }
 
 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
-                                  MVT VT, const SDOperand *Ops,
+                                  MVT VT, const SDValue *Ops,
                                   unsigned NumOps) {
   SDVTList VTs = getVTList(VT);
   return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
 }
 
 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
-                                  MVT VT1, MVT VT2, const SDOperand *Ops,
+                                  MVT VT1, MVT VT2, const SDValue *Ops,
                                   unsigned NumOps) {
   SDVTList VTs = getVTList(VT1, VT2);
   return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
@@ -3899,38 +4648,38 @@ SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
                                   MVT VT1, MVT VT2) {
   SDVTList VTs = getVTList(VT1, VT2);
-  return MorphNodeTo(N, Opc, VTs, (SDOperand *)0, 0);
+  return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
 }
 
 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
                                   MVT VT1, MVT VT2, MVT VT3,
-                                  const SDOperand *Ops, unsigned NumOps) {
+                                  const SDValue *Ops, unsigned NumOps) {
   SDVTList VTs = getVTList(VT1, VT2, VT3);
   return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
 }
 
 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 
                                   MVT VT1, MVT VT2,
-                                  SDOperand Op1) {
+                                  SDValue Op1) {
   SDVTList VTs = getVTList(VT1, VT2);
-  SDOperand Ops[] = { Op1 };
+  SDValue Ops[] = { Op1 };
   return MorphNodeTo(N, Opc, VTs, Ops, 1);
 }
 
 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 
                                   MVT VT1, MVT VT2,
-                                  SDOperand Op1, SDOperand Op2) {
+                                  SDValue Op1, SDValue Op2) {
   SDVTList VTs = getVTList(VT1, VT2);
-  SDOperand Ops[] = { Op1, Op2 };
+  SDValue Ops[] = { Op1, Op2 };
   return MorphNodeTo(N, Opc, VTs, Ops, 2);
 }
 
 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
                                   MVT VT1, MVT VT2,
-                                  SDOperand Op1, SDOperand Op2, 
-                                  SDOperand Op3) {
+                                  SDValue Op1, SDValue Op2, 
+                                  SDValue Op3) {
   SDVTList VTs = getVTList(VT1, VT2);
-  SDOperand Ops[] = { Op1, Op2, Op3 };
+  SDValue Ops[] = { Op1, Op2, Op3 };
   return MorphNodeTo(N, Opc, VTs, Ops, 3);
 }
 
@@ -3943,11 +4692,11 @@ SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
 ///
 /// Using MorphNodeTo is faster than creating a new node and swapping it in
 /// with ReplaceAllUsesWith both because it often avoids allocating a new
-/// node, and because it doesn't require CSE recalulation for any of
+/// node, and because it doesn't require CSE recalculation for any of
 /// the node's users.
 ///
 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
-                                  SDVTList VTs, const SDOperand *Ops,
+                                  SDVTList VTs, const SDValue *Ops,
                                   unsigned NumOps) {
   // If an identical node already exists, use it.
   void *IP = 0;
@@ -3958,7 +4707,8 @@ SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
       return ON;
   }
 
-  RemoveNodeFromCSEMaps(N);
+  if (!RemoveNodeFromCSEMaps(N))
+    IP = 0;
 
   // Start the morphing.
   N->NodeType = Opc;
@@ -3968,10 +4718,10 @@ SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
   // Clear the operands list, updating used nodes to remove this from their
   // use list.  Keep track of any operands that become dead as a result.
   SmallPtrSet<SDNode*, 16> DeadNodeSet;
-  for (SDNode::op_iterator B = N->op_begin(), I = B, E = N->op_end();
-       I != E; ++I) {
-    SDNode *Used = I->getVal();
-    Used->removeUser(std::distance(B, I), N);
+  for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
+    SDUse &Use = *I++;
+    SDNode *Used = Use.getNode();
+    Use.set(SDValue());
     if (Used->use_empty())
       DeadNodeSet.insert(Used);
   }
@@ -3981,11 +4731,12 @@ SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
   if (NumOps > N->NumOperands) {
     if (N->OperandsNeedDelete)
       delete[] N->OperandList;
+
     if (N->isMachineOpcode()) {
       // We're creating a final node that will live unmorphed for the
-      // remainder of this SelectionDAG's duration, so we can allocate the
-      // operands directly out of the pool with no recycling metadata.
-      N->OperandList = Allocator.Allocate<SDUse>(NumOps);
+      // remainder of the current SelectionDAG iteration, so we can allocate
+      // the operands directly out of a pool with no recycling metadata.
+      N->OperandList = OperandAllocator.Allocate<SDUse>(NumOps);
       N->OperandsNeedDelete = false;
     } else {
       N->OperandList = new SDUse[NumOps];
@@ -3996,11 +4747,8 @@ SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
   // Assign the new operands.
   N->NumOperands = NumOps;
   for (unsigned i = 0, e = NumOps; i != e; ++i) {
-    N->OperandList[i] = Ops[i];
     N->OperandList[i].setUser(N);
-    SDNode *ToUse = N->OperandList[i].getVal();
-    ToUse->addUser(i, N);
-    DeadNodeSet.erase(ToUse);
+    N->OperandList[i].setInitial(Ops[i]);
   }
 
   // Delete any nodes that are still dead after adding the uses for the
@@ -4025,94 +4773,198 @@ SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
 /// node of the specified opcode and operands, it returns that node instead of
 /// the current one.
 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
-  return getNode(~Opcode, VT).Val;
+  return getNode(~Opcode, VT).getNode();
+}
+SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT) {
+  return getNode(~Opcode, dl, VT).getNode();
+}
+
+SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDValue Op1) {
+  return getNode(~Opcode, VT, Op1).getNode();
 }
-SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDOperand Op1) {
-  return getNode(~Opcode, VT, Op1).Val;
+SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
+                                    SDValue Op1) {
+  return getNode(~Opcode, dl, VT, Op1).getNode();
 }
+
 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
-                                    SDOperand Op1, SDOperand Op2) {
-  return getNode(~Opcode, VT, Op1, Op2).Val;
+                                    SDValue Op1, SDValue Op2) {
+  return getNode(~Opcode, VT, Op1, Op2).getNode();
 }
+SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
+                                    SDValue Op1, SDValue Op2) {
+  return getNode(~Opcode, dl, VT, Op1, Op2).getNode();
+}
+
 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
-                                    SDOperand Op1, SDOperand Op2,
-                                    SDOperand Op3) {
-  return getNode(~Opcode, VT, Op1, Op2, Op3).Val;
+                                    SDValue Op1, SDValue Op2,
+                                    SDValue Op3) {
+  return getNode(~Opcode, VT, Op1, Op2, Op3).getNode();
 }
+SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
+                                    SDValue Op1, SDValue Op2,
+                                    SDValue Op3) {
+  return getNode(~Opcode, dl, VT, Op1, Op2, Op3).getNode();
+}
+
 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
-                                    const SDOperand *Ops, unsigned NumOps) {
-  return getNode(~Opcode, VT, Ops, NumOps).Val;
+                                    const SDValue *Ops, unsigned NumOps) {
+  return getNode(~Opcode, VT, Ops, NumOps).getNode();
+}
+SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
+                                    const SDValue *Ops, unsigned NumOps) {
+  return getNode(~Opcode, dl, VT, Ops, NumOps).getNode();
 }
+
 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
   const MVT *VTs = getNodeValueTypes(VT1, VT2);
-  SDOperand Op;
-  return getNode(~Opcode, VTs, 2, &Op, 0).Val;
+  SDValue Op;
+  return getNode(~Opcode, VTs, 2, &Op, 0).getNode();
+}
+SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, 
+                                    MVT VT1, MVT VT2) {
+  const MVT *VTs = getNodeValueTypes(VT1, VT2);
+  SDValue Op;
+  return getNode(~Opcode, dl, VTs, 2, &Op, 0).getNode();
 }
+
 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
-                                    MVT VT2, SDOperand Op1) {
+                                    MVT VT2, SDValue Op1) {
+  const MVT *VTs = getNodeValueTypes(VT1, VT2);
+  return getNode(~Opcode, VTs, 2, &Op1, 1).getNode();
+}
+SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
+                                    MVT VT2, SDValue Op1) {
   const MVT *VTs = getNodeValueTypes(VT1, VT2);
-  return getNode(~Opcode, VTs, 2, &Op1, 1).Val;
+  return getNode(~Opcode, dl, VTs, 2, &Op1, 1).getNode();
 }
+
 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
-                                    MVT VT2, SDOperand Op1,
-                                    SDOperand Op2) {
+                                    MVT VT2, SDValue Op1,
+                                    SDValue Op2) {
+  const MVT *VTs = getNodeValueTypes(VT1, VT2);
+  SDValue Ops[] = { Op1, Op2 };
+  return getNode(~Opcode, VTs, 2, Ops, 2).getNode();
+}
+SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
+                                    MVT VT2, SDValue Op1,
+                                    SDValue Op2) {
   const MVT *VTs = getNodeValueTypes(VT1, VT2);
-  SDOperand Ops[] = { Op1, Op2 };
-  return getNode(~Opcode, VTs, 2, Ops, 2).Val;
+  SDValue Ops[] = { Op1, Op2 };
+  return getNode(~Opcode, dl, VTs, 2, Ops, 2).getNode();
 }
+
 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
-                                    MVT VT2, SDOperand Op1,
-                                    SDOperand Op2, SDOperand Op3) {
+                                    MVT VT2, SDValue Op1,
+                                    SDValue Op2, SDValue Op3) {
+  const MVT *VTs = getNodeValueTypes(VT1, VT2);
+  SDValue Ops[] = { Op1, Op2, Op3 };
+  return getNode(~Opcode, VTs, 2, Ops, 3).getNode();
+}
+SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
+                                    MVT VT2, SDValue Op1,
+                                    SDValue Op2, SDValue Op3) {
   const MVT *VTs = getNodeValueTypes(VT1, VT2);
-  SDOperand Ops[] = { Op1, Op2, Op3 };
-  return getNode(~Opcode, VTs, 2, Ops, 3).Val;
+  SDValue Ops[] = { Op1, Op2, Op3 };
+  return getNode(~Opcode, dl, VTs, 2, Ops, 3).getNode();
 }
+
 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
-                                    const SDOperand *Ops, unsigned NumOps) {
+                                    const SDValue *Ops, unsigned NumOps) {
+  const MVT *VTs = getNodeValueTypes(VT1, VT2);
+  return getNode(~Opcode, VTs, 2, Ops, NumOps).getNode();
+}
+SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, 
+                                    MVT VT1, MVT VT2,
+                                    const SDValue *Ops, unsigned NumOps) {
   const MVT *VTs = getNodeValueTypes(VT1, VT2);
-  return getNode(~Opcode, VTs, 2, Ops, NumOps).Val;
+  return getNode(~Opcode, dl, VTs, 2, Ops, NumOps).getNode();
 }
+
 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
-                                    SDOperand Op1, SDOperand Op2) {
+                                    SDValue Op1, SDValue Op2) {
+  const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
+  SDValue Ops[] = { Op1, Op2 };
+  return getNode(~Opcode, VTs, 3, Ops, 2).getNode();
+}
+SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
+                                    MVT VT1, MVT VT2, MVT VT3,
+                                    SDValue Op1, SDValue Op2) {
   const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
-  SDOperand Ops[] = { Op1, Op2 };
-  return getNode(~Opcode, VTs, 3, Ops, 2).Val;
+  SDValue Ops[] = { Op1, Op2 };
+  return getNode(~Opcode, dl, VTs, 3, Ops, 2).getNode();
 }
+
 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
-                                    SDOperand Op1, SDOperand Op2,
-                                    SDOperand Op3) {
+                                    SDValue Op1, SDValue Op2,
+                                    SDValue Op3) {
+  const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
+  SDValue Ops[] = { Op1, Op2, Op3 };
+  return getNode(~Opcode, VTs, 3, Ops, 3).getNode();
+}
+SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
+                                    MVT VT1, MVT VT2, MVT VT3,
+                                    SDValue Op1, SDValue Op2,
+                                    SDValue Op3) {
   const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
-  SDOperand Ops[] = { Op1, Op2, Op3 };
-  return getNode(~Opcode, VTs, 3, Ops, 3).Val;
+  SDValue Ops[] = { Op1, Op2, Op3 };
+  return getNode(~Opcode, dl, VTs, 3, Ops, 3).getNode();
 }
+
 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
-                                    const SDOperand *Ops, unsigned NumOps) {
+                                    const SDValue *Ops, unsigned NumOps) {
   const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
-  return getNode(~Opcode, VTs, 3, Ops, NumOps).Val;
+  return getNode(~Opcode, VTs, 3, Ops, NumOps).getNode();
 }
+SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
+                                    MVT VT1, MVT VT2, MVT VT3,
+                                    const SDValue *Ops, unsigned NumOps) {
+  const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
+  return getNode(~Opcode, VTs, 3, Ops, NumOps).getNode();
+}
+
 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
                                     MVT VT2, MVT VT3, MVT VT4,
-                                    const SDOperand *Ops, unsigned NumOps) {
+                                    const SDValue *Ops, unsigned NumOps) {
   std::vector<MVT> VTList;
   VTList.push_back(VT1);
   VTList.push_back(VT2);
   VTList.push_back(VT3);
   VTList.push_back(VT4);
   const MVT *VTs = getNodeValueTypes(VTList);
-  return getNode(~Opcode, VTs, 4, Ops, NumOps).Val;
+  return getNode(~Opcode, VTs, 4, Ops, NumOps).getNode();
 }
+SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
+                                    MVT VT2, MVT VT3, MVT VT4,
+                                    const SDValue *Ops, unsigned NumOps) {
+  std::vector<MVT> VTList;
+  VTList.push_back(VT1);
+  VTList.push_back(VT2);
+  VTList.push_back(VT3);
+  VTList.push_back(VT4);
+  const MVT *VTs = getNodeValueTypes(VTList);
+  return getNode(~Opcode, dl, VTs, 4, Ops, NumOps).getNode();
+}
+
 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
                                     const std::vector<MVT> &ResultTys,
-                                    const SDOperand *Ops, unsigned NumOps) {
+                                    const SDValue *Ops, unsigned NumOps) {
   const MVT *VTs = getNodeValueTypes(ResultTys);
   return getNode(~Opcode, VTs, ResultTys.size(),
-                 Ops, NumOps).Val;
+                 Ops, NumOps).getNode();
+}
+SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
+                                    const std::vector<MVT> &ResultTys,
+                                    const SDValue *Ops, unsigned NumOps) {
+  const MVT *VTs = getNodeValueTypes(ResultTys);
+  return getNode(~Opcode, dl, VTs, ResultTys.size(),
+                 Ops, NumOps).getNode();
 }
 
 /// getNodeIfExists - Get the specified node if it's already available, or
 /// else return NULL.
 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
-                                      const SDOperand *Ops, unsigned NumOps) {
+                                      const SDValue *Ops, unsigned NumOps) {
   if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
     FoldingSetNodeID ID;
     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
@@ -4123,49 +4975,45 @@ SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
   return NULL;
 }
 
-
 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
 /// This can cause recursive merging of nodes in the DAG.
 ///
 /// This version assumes From has a single result value.
 ///
-void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
+void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
                                       DAGUpdateListener *UpdateListener) {
-  SDNode *From = FromN.Val;
-  assert(From->getNumValues() == 1 && FromN.ResNo == 0 && 
+  SDNode *From = FromN.getNode();
+  assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 
          "Cannot replace with this method!");
-  assert(From != To.Val && "Cannot replace uses of with self");
-
-  while (!From->use_empty()) {
-    SDNode::use_iterator UI = From->use_begin();
-    SDNode *U = *UI;
+  assert(From != To.getNode() && "Cannot replace uses of with self");
+
+  // Iterate over all the existing uses of From. New uses will be added
+  // to the beginning of the use list, which we avoid visiting.
+  // This specifically avoids visiting uses of From that arise while the
+  // replacement is happening, because any such uses would be the result
+  // of CSE: If an existing node looks like From after one of its operands
+  // is replaced by To, we don't want to replace of all its users with To
+  // too. See PR3018 for more info.
+  SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
+  while (UI != UE) {
+    SDNode *User = *UI;
 
     // This node is about to morph, remove its old self from the CSE maps.
-    RemoveNodeFromCSEMaps(U);
-    int operandNum = 0;
-    for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
-         I != E; ++I, ++operandNum)
-      if (I->getVal() == From) {
-        From->removeUser(operandNum, U);
-        *I = To;
-        I->setUser(U);
-        To.Val->addUser(operandNum, U);
-      }    
-
-    // Now that we have modified U, add it back to the CSE maps.  If it already
-    // exists there, recursively merge the results together.
-    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
-      ReplaceAllUsesWith(U, Existing, UpdateListener);
-      // U is now dead.  Inform the listener if it exists and delete it.
-      if (UpdateListener) 
-        UpdateListener->NodeDeleted(U, Existing);
-      DeleteNodeNotInCSEMaps(U);
-    } else {
-      // If the node doesn't already exist, we updated it.  Inform a listener if
-      // it exists.
-      if (UpdateListener) 
-        UpdateListener->NodeUpdated(U);
-    }
+    RemoveNodeFromCSEMaps(User);
+
+    // A user can appear in a use list multiple times, and when this
+    // happens the uses are usually next to each other in the list.
+    // To help reduce the number of CSE recomputations, process all
+    // the uses of this user that we can find this way.
+    do {
+      SDUse &Use = UI.getUse();
+      ++UI;
+      Use.set(To);
+    } while (UI != UE && *UI == User);
+
+    // Now that we have modified User, add it back to the CSE maps.  If it
+    // already exists there, recursively merge the results together.
+    AddModifiedNodeToCSEMaps(User, UpdateListener);
   }
 }
 
@@ -4185,35 +5033,28 @@ void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
   if (From == To)
     return;
 
-  while (!From->use_empty()) {
-    SDNode::use_iterator UI = From->use_begin();
-    SDNode *U = *UI;
+  // Iterate over just the existing users of From. See the comments in
+  // the ReplaceAllUsesWith above.
+  SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
+  while (UI != UE) {
+    SDNode *User = *UI;
 
     // This node is about to morph, remove its old self from the CSE maps.
-    RemoveNodeFromCSEMaps(U);
-    int operandNum = 0;
-    for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
-         I != E; ++I, ++operandNum)
-      if (I->getVal() == From) {
-        From->removeUser(operandNum, U);
-        I->getVal() = To;
-        To->addUser(operandNum, U);
-      }
+    RemoveNodeFromCSEMaps(User);
 
-    // Now that we have modified U, add it back to the CSE maps.  If it already
-    // exists there, recursively merge the results together.
-    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
-      ReplaceAllUsesWith(U, Existing, UpdateListener);
-      // U is now dead.  Inform the listener if it exists and delete it.
-      if (UpdateListener) 
-        UpdateListener->NodeDeleted(U, Existing);
-      DeleteNodeNotInCSEMaps(U);
-    } else {
-      // If the node doesn't already exist, we updated it.  Inform a listener if
-      // it exists.
-      if (UpdateListener) 
-        UpdateListener->NodeUpdated(U);
-    }
+    // A user can appear in a use list multiple times, and when this
+    // happens the uses are usually next to each other in the list.
+    // To help reduce the number of CSE recomputations, process all
+    // the uses of this user that we can find this way.
+    do {
+      SDUse &Use = UI.getUse();
+      ++UI;
+      Use.setNode(To);
+    } while (UI != UE && *UI == User);
+
+    // Now that we have modified User, add it back to the CSE maps.  If it
+    // already exists there, recursively merge the results together.
+    AddModifiedNodeToCSEMaps(User, UpdateListener);
   }
 }
 
@@ -4223,216 +5064,239 @@ void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
 /// This version can replace From with any result values.  To must match the
 /// number and types of values returned by From.
 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
-                                      const SDOperand *To,
+                                      const SDValue *To,
                                       DAGUpdateListener *UpdateListener) {
   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
-    return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
+    return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
 
-  while (!From->use_empty()) {
-    SDNode::use_iterator UI = From->use_begin();
-    SDNode *U = *UI;
+  // Iterate over just the existing users of From. See the comments in
+  // the ReplaceAllUsesWith above.
+  SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
+  while (UI != UE) {
+    SDNode *User = *UI;
 
     // This node is about to morph, remove its old self from the CSE maps.
-    RemoveNodeFromCSEMaps(U);
-    int operandNum = 0;
-    for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
-         I != E; ++I, ++operandNum)
-      if (I->getVal() == From) {
-        const SDOperand &ToOp = To[I->getSDOperand().ResNo];
-        From->removeUser(operandNum, U);
-        *I = ToOp;
-        I->setUser(U);
-        ToOp.Val->addUser(operandNum, U);
-      }
+    RemoveNodeFromCSEMaps(User);
 
-    // Now that we have modified U, add it back to the CSE maps.  If it already
-    // exists there, recursively merge the results together.
-    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
-      ReplaceAllUsesWith(U, Existing, UpdateListener);
-      // U is now dead.  Inform the listener if it exists and delete it.
-      if (UpdateListener) 
-        UpdateListener->NodeDeleted(U, Existing);
-      DeleteNodeNotInCSEMaps(U);
-    } else {
-      // If the node doesn't already exist, we updated it.  Inform a listener if
-      // it exists.
-      if (UpdateListener) 
-        UpdateListener->NodeUpdated(U);
-    }
+    // A user can appear in a use list multiple times, and when this
+    // happens the uses are usually next to each other in the list.
+    // To help reduce the number of CSE recomputations, process all
+    // the uses of this user that we can find this way.
+    do {
+      SDUse &Use = UI.getUse();
+      const SDValue &ToOp = To[Use.getResNo()];
+      ++UI;
+      Use.set(ToOp);
+    } while (UI != UE && *UI == User);
+
+    // Now that we have modified User, add it back to the CSE maps.  If it
+    // already exists there, recursively merge the results together.
+    AddModifiedNodeToCSEMaps(User, UpdateListener);
   }
 }
 
 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
-/// uses of other values produced by From.Val alone.  The Deleted vector is
-/// handled the same way as for ReplaceAllUsesWith.
-void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
+/// uses of other values produced by From.getNode() alone.  The Deleted
+/// vector is handled the same way as for ReplaceAllUsesWith.
+void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
                                              DAGUpdateListener *UpdateListener){
   // Handle the really simple, really trivial case efficiently.
   if (From == To) return;
 
   // Handle the simple, trivial, case efficiently.
-  if (From.Val->getNumValues() == 1) {
+  if (From.getNode()->getNumValues() == 1) {
     ReplaceAllUsesWith(From, To, UpdateListener);
     return;
   }
 
-  // Get all of the users of From.Val.  We want these in a nice,
-  // deterministically ordered and uniqued set, so we use a SmallSetVector.
-  SmallSetVector<SDNode*, 16> Users(From.Val->use_begin(), From.Val->use_end());
+  // Iterate over just the existing users of From. See the comments in
+  // the ReplaceAllUsesWith above.
+  SDNode::use_iterator UI = From.getNode()->use_begin(),
+                       UE = From.getNode()->use_end();
+  while (UI != UE) {
+    SDNode *User = *UI;
+    bool UserRemovedFromCSEMaps = false;
+
+    // A user can appear in a use list multiple times, and when this
+    // happens the uses are usually next to each other in the list.
+    // To help reduce the number of CSE recomputations, process all
+    // the uses of this user that we can find this way.
+    do {
+      SDUse &Use = UI.getUse();
+
+      // Skip uses of different values from the same node.
+      if (Use.getResNo() != From.getResNo()) {
+        ++UI;
+        continue;
+      }
 
-  while (!Users.empty()) {
-    // We know that this user uses some value of From.  If it is the right
-    // value, update it.
-    SDNode *User = Users.back();
-    Users.pop_back();
-    
-    // Scan for an operand that matches From.
-    SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
-    for (; Op != E; ++Op)
-      if (*Op == From) break;
-    
-    // If there are no matches, the user must use some other result of From.
-    if (Op == E) continue;
-      
-    // Okay, we know this user needs to be updated.  Remove its old self
-    // from the CSE maps.
-    RemoveNodeFromCSEMaps(User);
-    
-    // Update all operands that match "From" in case there are multiple uses.
-    for (; Op != E; ++Op) {
-      if (*Op == From) {
-        From.Val->removeUser(Op-User->op_begin(), User);
-        *Op = To;
-        Op->setUser(User);
-        To.Val->addUser(Op-User->op_begin(), User);
+      // If this node hasn't been modified yet, it's still in the CSE maps,
+      // so remove its old self from the CSE maps.
+      if (!UserRemovedFromCSEMaps) {
+        RemoveNodeFromCSEMaps(User);
+        UserRemovedFromCSEMaps = true;
       }
-    }
-               
+
+      ++UI;
+      Use.set(To);
+    } while (UI != UE && *UI == User);
+
+    // We are iterating over all uses of the From node, so if a use
+    // doesn't use the specific value, no changes are made.
+    if (!UserRemovedFromCSEMaps)
+      continue;
+
     // Now that we have modified User, add it back to the CSE maps.  If it
     // already exists there, recursively merge the results together.
-    SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
-    if (!Existing) {
-      if (UpdateListener) UpdateListener->NodeUpdated(User);
-      continue;  // Continue on to next user.
-    }
-    
-    // If there was already an existing matching node, use ReplaceAllUsesWith
-    // to replace the dead one with the existing one.  This can cause
-    // recursive merging of other unrelated nodes down the line.
-    ReplaceAllUsesWith(User, Existing, UpdateListener);
-    
-    // User is now dead.  Notify a listener if present.
-    if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
-    DeleteNodeNotInCSEMaps(User);
+    AddModifiedNodeToCSEMaps(User, UpdateListener);
+  }
+}
+
+namespace {
+  /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
+  /// to record information about a use.
+  struct UseMemo {
+    SDNode *User;
+    unsigned Index;
+    SDUse *Use;
+  };
+
+  /// operator< - Sort Memos by User.
+  bool operator<(const UseMemo &L, const UseMemo &R) {
+    return (intptr_t)L.User < (intptr_t)R.User;
   }
 }
 
 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
-/// uses of other values produced by From.Val alone.  The same value may
-/// appear in both the From and To list.  The Deleted vector is
+/// uses of other values produced by From.getNode() alone.  The same value
+/// may appear in both the From and To list.  The Deleted vector is
 /// handled the same way as for ReplaceAllUsesWith.
-void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDOperand *From,
-                                              const SDOperand *To,
+void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
+                                              const SDValue *To,
                                               unsigned Num,
                                               DAGUpdateListener *UpdateListener){
   // Handle the simple, trivial case efficiently.
   if (Num == 1)
     return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
 
-  SmallVector<std::pair<SDNode *, unsigned>, 16> Users;
-  for (unsigned i = 0; i != Num; ++i)
-    for (SDNode::use_iterator UI = From[i].Val->use_begin(), 
-         E = From[i].Val->use_end(); UI != E; ++UI)
-      Users.push_back(std::make_pair(*UI, i));
+  // Read up all the uses and make records of them. This helps
+  // processing new uses that are introduced during the
+  // replacement process.
+  SmallVector<UseMemo, 4> Uses;
+  for (unsigned i = 0; i != Num; ++i) {
+    unsigned FromResNo = From[i].getResNo();
+    SDNode *FromNode = From[i].getNode();
+    for (SDNode::use_iterator UI = FromNode->use_begin(), 
+         E = FromNode->use_end(); UI != E; ++UI) {
+      SDUse &Use = UI.getUse();
+      if (Use.getResNo() == FromResNo) {
+        UseMemo Memo = { *UI, i, &Use };
+        Uses.push_back(Memo);
+      }
+    }
+  }
 
-  while (!Users.empty()) {
+  // Sort the uses, so that all the uses from a given User are together.
+  std::sort(Uses.begin(), Uses.end());
+
+  for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
+       UseIndex != UseIndexEnd; ) {
     // We know that this user uses some value of From.  If it is the right
     // value, update it.
-    SDNode *User = Users.back().first;
-    unsigned i = Users.back().second;
-    Users.pop_back();
-    
-    // Scan for an operand that matches From.
-    SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
-    for (; Op != E; ++Op)
-      if (*Op == From[i]) break;
-    
-    // If there are no matches, the user must use some other result of From.
-    if (Op == E) continue;
-      
-    // Okay, we know this user needs to be updated.  Remove its old self
-    // from the CSE maps.
+    SDNode *User = Uses[UseIndex].User;
+
+    // This node is about to morph, remove its old self from the CSE maps.
     RemoveNodeFromCSEMaps(User);
-    
-    // Update all operands that match "From" in case there are multiple uses.
-    for (; Op != E; ++Op) {
-      if (*Op == From[i]) {
-        From[i].Val->removeUser(Op-User->op_begin(), User);
-        *Op = To[i];
-        Op->setUser(User);
-        To[i].Val->addUser(Op-User->op_begin(), User);
-      }
-    }
-               
+
+    // The Uses array is sorted, so all the uses for a given User
+    // are next to each other in the list.
+    // To help reduce the number of CSE recomputations, process all
+    // the uses of this user that we can find this way.
+    do {
+      unsigned i = Uses[UseIndex].Index;
+      SDUse &Use = *Uses[UseIndex].Use;
+      ++UseIndex;
+
+      Use.set(To[i]);
+    } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
+
     // Now that we have modified User, add it back to the CSE maps.  If it
     // already exists there, recursively merge the results together.
-    SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
-    if (!Existing) {
-      if (UpdateListener) UpdateListener->NodeUpdated(User);
-      continue;  // Continue on to next user.
-    }
-    
-    // If there was already an existing matching node, use ReplaceAllUsesWith
-    // to replace the dead one with the existing one.  This can cause
-    // recursive merging of other unrelated nodes down the line.
-    ReplaceAllUsesWith(User, Existing, UpdateListener);
-    
-    // User is now dead.  Notify a listener if present.
-    if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
-    DeleteNodeNotInCSEMaps(User);
+    AddModifiedNodeToCSEMaps(User, UpdateListener);
   }
 }
 
 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
 /// based on their topological order. It returns the maximum id and a vector
 /// of the SDNodes* in assigned order by reference.
-unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
-  unsigned DAGSize = AllNodes.size();
-  std::vector<unsigned> InDegree(DAGSize);
-  std::vector<SDNode*> Sources;
-
-  // Use a two pass approach to avoid using a std::map which is slow.
-  unsigned Id = 0;
-  for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
-    SDNode *N = I;
-    N->setNodeId(Id++);
-    unsigned Degree = N->use_size();
-    InDegree[N->getNodeId()] = Degree;
-    if (Degree == 0)
-      Sources.push_back(N);
-  }
-
-  TopOrder.clear();
-  TopOrder.reserve(DAGSize);
-  while (!Sources.empty()) {
-    SDNode *N = Sources.back();
-    Sources.pop_back();
-    TopOrder.push_back(N);
-    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
-      SDNode *P = I->getVal();
-      unsigned Degree = --InDegree[P->getNodeId()];
-      if (Degree == 0)
-        Sources.push_back(P);
+unsigned SelectionDAG::AssignTopologicalOrder() {
+
+  unsigned DAGSize = 0;
+
+  // SortedPos tracks the progress of the algorithm. Nodes before it are
+  // sorted, nodes after it are unsorted. When the algorithm completes
+  // it is at the end of the list.
+  allnodes_iterator SortedPos = allnodes_begin();
+
+  // Visit all the nodes. Move nodes with no operands to the front of
+  // the list immediately. Annotate nodes that do have operands with their
+  // operand count. Before we do this, the Node Id fields of the nodes
+  // may contain arbitrary values. After, the Node Id fields for nodes
+  // before SortedPos will contain the topological sort index, and the
+  // Node Id fields for nodes At SortedPos and after will contain the
+  // count of outstanding operands.
+  for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
+    SDNode *N = I++;
+    unsigned Degree = N->getNumOperands();
+    if (Degree == 0) {
+      // A node with no uses, add it to the result array immediately.
+      N->setNodeId(DAGSize++);
+      allnodes_iterator Q = N;
+      if (Q != SortedPos)
+        SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
+      ++SortedPos;
+    } else {
+      // Temporarily use the Node Id as scratch space for the degree count.
+      N->setNodeId(Degree);
     }
   }
 
-  // Second pass, assign the actual topological order as node ids.
-  Id = 0;
-  for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
-       TI != TE; ++TI)
-    (*TI)->setNodeId(Id++);
+  // Visit all the nodes. As we iterate, moves nodes into sorted order,
+  // such that by the time the end is reached all nodes will be sorted.
+  for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
+    SDNode *N = I;
+    for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
+         UI != UE; ++UI) {
+      SDNode *P = *UI;
+      unsigned Degree = P->getNodeId();
+      --Degree;
+      if (Degree == 0) {
+        // All of P's operands are sorted, so P may sorted now.
+        P->setNodeId(DAGSize++);
+        if (P != SortedPos)
+          SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
+        ++SortedPos;
+      } else {
+        // Update P's outstanding operand count.
+        P->setNodeId(Degree);
+      }
+    }
+  }
 
-  return Id;
+  assert(SortedPos == AllNodes.end() &&
+         "Topological sort incomplete!");
+  assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
+         "First node in topological sort is not the entry token!");
+  assert(AllNodes.front().getNodeId() == 0 &&
+         "First node in topological sort has non-zero id!");
+  assert(AllNodes.front().getNumOperands() == 0 &&
+         "First node in topological sort has operands!");
+  assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
+         "Last node in topologic sort has unexpected id!");
+  assert(AllNodes.back().use_empty() &&
+         "Last node in topologic sort has users!");
+  assert(DAGSize == allnodes_size() && "Node count mismatch!");
+  return DAGSize;
 }
 
 
@@ -4441,39 +5305,12 @@ unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
 //                              SDNode Class
 //===----------------------------------------------------------------------===//
 
-// Out-of-line virtual method to give class a home.
-void SDNode::ANCHOR() {}
-void UnarySDNode::ANCHOR() {}
-void BinarySDNode::ANCHOR() {}
-void TernarySDNode::ANCHOR() {}
-void HandleSDNode::ANCHOR() {}
-void ConstantSDNode::ANCHOR() {}
-void ConstantFPSDNode::ANCHOR() {}
-void GlobalAddressSDNode::ANCHOR() {}
-void FrameIndexSDNode::ANCHOR() {}
-void JumpTableSDNode::ANCHOR() {}
-void ConstantPoolSDNode::ANCHOR() {}
-void BasicBlockSDNode::ANCHOR() {}
-void SrcValueSDNode::ANCHOR() {}
-void MemOperandSDNode::ANCHOR() {}
-void RegisterSDNode::ANCHOR() {}
-void DbgStopPointSDNode::ANCHOR() {}
-void LabelSDNode::ANCHOR() {}
-void ExternalSymbolSDNode::ANCHOR() {}
-void CondCodeSDNode::ANCHOR() {}
-void ARG_FLAGSSDNode::ANCHOR() {}
-void VTSDNode::ANCHOR() {}
-void MemSDNode::ANCHOR() {}
-void LoadSDNode::ANCHOR() {}
-void StoreSDNode::ANCHOR() {}
-void AtomicSDNode::ANCHOR() {}
-
 HandleSDNode::~HandleSDNode() {
   DropOperands();
 }
 
 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
-                                         MVT VT, int o)
+                                         MVT VT, int64_t o)
   : SDNode(isa<GlobalVariable>(GA) &&
            cast<GlobalVariable>(GA)->isThreadLocal() ?
            // Thread Local
@@ -4488,8 +5325,42 @@ MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, MVT memvt,
                      const Value *srcValue, int SVO,
                      unsigned alignment, bool vol)
  : SDNode(Opc, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
-   Flags(vol | ((Log2_32(alignment) + 1) << 1)) {
+   Flags(encodeMemSDNodeFlags(vol, alignment)) {
+
+  assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
+  assert(getAlignment() == alignment && "Alignment representation error!");
+  assert(isVolatile() == vol && "Volatile representation error!");
+}
 
+MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, const SDValue *Ops,
+                     unsigned NumOps, MVT memvt, const Value *srcValue,
+                     int SVO, unsigned alignment, bool vol)
+   : SDNode(Opc, VTs, Ops, NumOps),
+     MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
+     Flags(vol | ((Log2_32(alignment) + 1) << 1)) {
+  assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
+  assert(getAlignment() == alignment && "Alignment representation error!");
+  assert(isVolatile() == vol && "Volatile representation error!");
+}
+
+MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, MVT memvt,
+                     const Value *srcValue, int SVO,
+                     unsigned alignment, bool vol)
+ : SDNode(Opc, dl, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
+   Flags(encodeMemSDNodeFlags(vol, alignment)) {
+
+  assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
+  assert(getAlignment() == alignment && "Alignment representation error!");
+  assert(isVolatile() == vol && "Volatile representation error!");
+}
+
+MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, 
+                     const SDValue *Ops,
+                     unsigned NumOps, MVT memvt, const Value *srcValue,
+                     int SVO, unsigned alignment, bool vol)
+   : SDNode(Opc, dl, VTs, Ops, NumOps),
+     MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
+     Flags(vol | ((Log2_32(alignment) + 1) << 1)) {
   assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
   assert(getAlignment() == alignment && "Alignment representation error!");
   assert(isVolatile() == vol && "Volatile representation error!");
@@ -4498,22 +5369,27 @@ MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, MVT memvt,
 /// getMemOperand - Return a MachineMemOperand object describing the memory
 /// reference performed by this memory reference.
 MachineMemOperand MemSDNode::getMemOperand() const {
-  int Flags;
+  int Flags = 0;
   if (isa<LoadSDNode>(this))
     Flags = MachineMemOperand::MOLoad;
   else if (isa<StoreSDNode>(this))
     Flags = MachineMemOperand::MOStore;
-  else {
-    assert(isa<AtomicSDNode>(this) && "Unknown MemSDNode opcode!");
+  else if (isa<AtomicSDNode>(this)) {
     Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
   }
+  else {
+    const MemIntrinsicSDNode* MemIntrinNode = dyn_cast<MemIntrinsicSDNode>(this);
+    assert(MemIntrinNode && "Unknown MemSDNode opcode!");
+    if (MemIntrinNode->readMem()) Flags |= MachineMemOperand::MOLoad;
+    if (MemIntrinNode->writeMem()) Flags |= MachineMemOperand::MOStore;
+  }
 
   int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
   if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
   
   // Check if the memory reference references a frame index
   const FrameIndexSDNode *FI = 
-  dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
+  dyn_cast<const FrameIndexSDNode>(getBasePtr().getNode());
   if (!getSrcValue() && FI)
     return MachineMemOperand(PseudoSourceValue::getFixedStack(FI->getIndex()),
                              Flags, 0, Size, getAlignment());
@@ -4524,7 +5400,7 @@ MachineMemOperand MemSDNode::getMemOperand() const {
 
 /// Profile - Gather unique data for the node.
 ///
-void SDNode::Profile(FoldingSetNodeID &ID) {
+void SDNode::Profile(FoldingSetNodeID &ID) const {
   AddNodeIDNode(ID, this);
 }
 
@@ -4549,7 +5425,7 @@ bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
 
   // TODO: Only iterate over uses of a given value of the node
   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
-    if (UI.getUse().getSDOperand().ResNo == Value) {
+    if (UI.getUse().getResNo() == Value) {
       if (NUses == 0)
         return false;
       --NUses;
@@ -4567,7 +5443,7 @@ bool SDNode::hasAnyUseOfValue(unsigned Value) const {
   assert(Value < getNumValues() && "Bad value!");
 
   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
-    if (UI.getUse().getSDOperand().ResNo == Value)
+    if (UI.getUse().getResNo() == Value)
       return true;
 
   return false;
@@ -4591,7 +5467,7 @@ bool SDNode::isOnlyUserOf(SDNode *N) const {
 
 /// isOperand - Return true if this node is an operand of N.
 ///
-bool SDOperand::isOperandOf(SDNode *N) const {
+bool SDValue::isOperandOf(SDNode *N) const {
   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
     if (*this == N->getOperand(i))
       return true;
@@ -4600,7 +5476,7 @@ bool SDOperand::isOperandOf(SDNode *N) const {
 
 bool SDNode::isOperandOf(SDNode *N) const {
   for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
-    if (this == N->OperandList[i].getVal())
+    if (this == N->OperandList[i].getNode())
       return true;
   return false;
 }
@@ -4610,7 +5486,7 @@ bool SDNode::isOperandOf(SDNode *N) const {
 /// side-effecting instructions.  In practice, this looks through token
 /// factors and non-volatile loads.  In order to remain efficient, this only
 /// looks a couple of nodes in, it does not do an exhaustive search.
-bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest, 
+bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 
                                                unsigned Depth) const {
   if (*this == Dest) return true;
   
@@ -4642,7 +5518,7 @@ static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
     return;
 
   for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
-    SDNode *Op = N->getOperand(i).Val;
+    SDNode *Op = N->getOperand(i).getNode();
     if (Op == P) {
       found = true;
       return;
@@ -4664,7 +5540,7 @@ bool SDNode::isPredecessorOf(SDNode *N) const {
 
 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
   assert(Num < NumOperands && "Invalid child # of SDNode!");
-  return cast<ConstantSDNode>(OperandList[Num])->getValue();
+  return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
 }
 
 std::string SDNode::getOperationName(const SelectionDAG *G) const {
@@ -4680,7 +5556,7 @@ std::string SDNode::getOperationName(const SelectionDAG *G) const {
       return "<<Unknown Machine Node>>";
     }
     if (G) {
-      TargetLowering &TLI = G->getTargetLoweringInfo();
+      const TargetLowering &TLI = G->getTargetLoweringInfo();
       const char *Name = TLI.getTargetNodeName(getOpcode());
       if (Name) return Name;
       return "<<Unknown Target Node>>";
@@ -4693,18 +5569,18 @@ std::string SDNode::getOperationName(const SelectionDAG *G) const {
 #endif
   case ISD::PREFETCH:      return "Prefetch";
   case ISD::MEMBARRIER:    return "MemBarrier";
-  case ISD::ATOMIC_CMP_SWAP:  return "AtomicCmpSwap";
-  case ISD::ATOMIC_LOAD_ADD:  return "AtomicLoadAdd";
-  case ISD::ATOMIC_LOAD_SUB:  return "AtomicLoadSub";
-  case ISD::ATOMIC_LOAD_AND:  return "AtomicLoadAnd";
-  case ISD::ATOMIC_LOAD_OR:   return "AtomicLoadOr";
-  case ISD::ATOMIC_LOAD_XOR:  return "AtomicLoadXor";
-  case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
-  case ISD::ATOMIC_LOAD_MIN:  return "AtomicLoadMin";
-  case ISD::ATOMIC_LOAD_MAX:  return "AtomicLoadMax";
-  case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
-  case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
-  case ISD::ATOMIC_SWAP:   return "AtomicSWAP";
+  case ISD::ATOMIC_CMP_SWAP:    return "AtomicCmpSwap";
+  case ISD::ATOMIC_SWAP:        return "AtomicSwap";
+  case ISD::ATOMIC_LOAD_ADD:    return "AtomicLoadAdd";
+  case ISD::ATOMIC_LOAD_SUB:    return "AtomicLoadSub";
+  case ISD::ATOMIC_LOAD_AND:    return "AtomicLoadAnd";
+  case ISD::ATOMIC_LOAD_OR:     return "AtomicLoadOr";
+  case ISD::ATOMIC_LOAD_XOR:    return "AtomicLoadXor";
+  case ISD::ATOMIC_LOAD_NAND:   return "AtomicLoadNand";
+  case ISD::ATOMIC_LOAD_MIN:    return "AtomicLoadMin";
+  case ISD::ATOMIC_LOAD_MAX:    return "AtomicLoadMax";
+  case ISD::ATOMIC_LOAD_UMIN:   return "AtomicLoadUMin";
+  case ISD::ATOMIC_LOAD_UMAX:   return "AtomicLoadUMax";
   case ISD::PCMARKER:      return "PCMarker";
   case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
   case ISD::SRCVALUE:      return "SrcValue";
@@ -4735,12 +5611,12 @@ std::string SDNode::getOperationName(const SelectionDAG *G) const {
   case ISD::ConstantPool:  return "ConstantPool";
   case ISD::ExternalSymbol: return "ExternalSymbol";
   case ISD::INTRINSIC_WO_CHAIN: {
-    unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
+    unsigned IID = cast<ConstantSDNode>(getOperand(0))->getZExtValue();
     return Intrinsic::getName((Intrinsic::ID)IID);
   }
   case ISD::INTRINSIC_VOID:
   case ISD::INTRINSIC_W_CHAIN: {
-    unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
+    unsigned IID = cast<ConstantSDNode>(getOperand(1))->getZExtValue();
     return Intrinsic::getName((Intrinsic::ID)IID);
   }
 
@@ -4774,6 +5650,11 @@ std::string SDNode::getOperationName(const SelectionDAG *G) const {
   case ISD::FCOS:   return "fcos";
   case ISD::FPOWI:  return "fpowi";
   case ISD::FPOW:   return "fpow";
+  case ISD::FTRUNC: return "ftrunc";
+  case ISD::FFLOOR: return "ffloor";
+  case ISD::FCEIL:  return "fceil";
+  case ISD::FRINT:  return "frint";
+  case ISD::FNEARBYINT: return "fnearbyint";
 
   // Binary operators
   case ISD::ADD:    return "add";
@@ -4788,7 +5669,7 @@ std::string SDNode::getOperationName(const SelectionDAG *G) const {
   case ISD::SMUL_LOHI:  return "smul_lohi";
   case ISD::UMUL_LOHI:  return "umul_lohi";
   case ISD::SDIVREM:    return "sdivrem";
-  case ISD::UDIVREM:    return "divrem";
+  case ISD::UDIVREM:    return "udivrem";
   case ISD::AND:    return "and";
   case ISD::OR:     return "or";
   case ISD::XOR:    return "xor";
@@ -4818,6 +5699,12 @@ std::string SDNode::getOperationName(const SelectionDAG *G) const {
   case ISD::CARRY_FALSE:         return "carry_false";
   case ISD::ADDC:        return "addc";
   case ISD::ADDE:        return "adde";
+  case ISD::SADDO:       return "saddo";
+  case ISD::UADDO:       return "uaddo";
+  case ISD::SSUBO:       return "ssubo";
+  case ISD::USUBO:       return "usubo";
+  case ISD::SMULO:       return "smulo";
+  case ISD::UMULO:       return "umulo";
   case ISD::SUBC:        return "subc";
   case ISD::SUBE:        return "sube";
   case ISD::SHL_PARTS:   return "shl_parts";
@@ -4843,6 +5730,21 @@ std::string SDNode::getOperationName(const SelectionDAG *G) const {
   case ISD::FP_TO_SINT:  return "fp_to_sint";
   case ISD::FP_TO_UINT:  return "fp_to_uint";
   case ISD::BIT_CONVERT: return "bit_convert";
+  
+  case ISD::CONVERT_RNDSAT: {
+    switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
+    default: assert(0 && "Unknown cvt code!");
+    case ISD::CVT_FF:  return "cvt_ff";
+    case ISD::CVT_FS:  return "cvt_fs";
+    case ISD::CVT_FU:  return "cvt_fu";
+    case ISD::CVT_SF:  return "cvt_sf";
+    case ISD::CVT_UF:  return "cvt_uf";
+    case ISD::CVT_SS:  return "cvt_ss";
+    case ISD::CVT_SU:  return "cvt_su";
+    case ISD::CVT_US:  return "cvt_us";
+    case ISD::CVT_UU:  return "cvt_uu";
+    }
+  }
 
     // Control flow instructions
   case ISD::BR:      return "br";
@@ -4951,178 +5853,177 @@ std::string ISD::ArgFlagsTy::getArgFlagsString() {
 
 void SDNode::dump() const { dump(0); }
 void SDNode::dump(const SelectionDAG *G) const {
-  cerr << (void*)this << ": ";
+  print(errs(), G);
+  errs().flush();
+}
+
+void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
+  OS << (void*)this << ": ";
 
   for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
-    if (i) cerr << ",";
+    if (i) OS << ",";
     if (getValueType(i) == MVT::Other)
-      cerr << "ch";
+      OS << "ch";
     else
-      cerr << getValueType(i).getMVTString();
+      OS << getValueType(i).getMVTString();
   }
-  cerr << " = " << getOperationName(G);
+  OS << " = " << getOperationName(G);
 
-  cerr << " ";
+  OS << " ";
   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
-    if (i) cerr << ", ";
-    cerr << (void*)getOperand(i).Val;
-    if (unsigned RN = getOperand(i).ResNo)
-      cerr << ":" << RN;
+    if (i) OS << ", ";
+    OS << (void*)getOperand(i).getNode();
+    if (unsigned RN = getOperand(i).getResNo())
+      OS << ":" << RN;
   }
 
   if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
-    SDNode *Mask = getOperand(2).Val;
-    cerr << "<";
+    SDNode *Mask = getOperand(2).getNode();
+    OS << "<";
     for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
-      if (i) cerr << ",";
+      if (i) OS << ",";
       if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
-        cerr << "u";
+        OS << "u";
       else
-        cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
+        OS << cast<ConstantSDNode>(Mask->getOperand(i))->getZExtValue();
     }
-    cerr << ">";
+    OS << ">";
   }
 
   if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
-    cerr << "<" << CSDN->getAPIntValue().toStringUnsigned() << ">";
+    OS << '<' << CSDN->getAPIntValue() << '>';
   } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
     if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
-      cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
+      OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
     else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
-      cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
+      OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
     else {
-      cerr << "<APFloat(";
-      CSDN->getValueAPF().convertToAPInt().dump();
-      cerr << ")>";
+      OS << "<APFloat(";
+      CSDN->getValueAPF().bitcastToAPInt().dump();
+      OS << ")>";
     }
   } else if (const GlobalAddressSDNode *GADN =
              dyn_cast<GlobalAddressSDNode>(this)) {
-    int offset = GADN->getOffset();
-    cerr << "<";
-    WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
+    int64_t offset = GADN->getOffset();
+    OS << '<';
+    WriteAsOperand(OS, GADN->getGlobal());
+    OS << '>';
     if (offset > 0)
-      cerr << " + " << offset;
+      OS << " + " << offset;
     else
-      cerr << " " << offset;
+      OS << " " << offset;
   } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
-    cerr << "<" << FIDN->getIndex() << ">";
+    OS << "<" << FIDN->getIndex() << ">";
   } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
-    cerr << "<" << JTDN->getIndex() << ">";
+    OS << "<" << JTDN->getIndex() << ">";
   } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
     int offset = CP->getOffset();
     if (CP->isMachineConstantPoolEntry())
-      cerr << "<" << *CP->getMachineCPVal() << ">";
+      OS << "<" << *CP->getMachineCPVal() << ">";
     else
-      cerr << "<" << *CP->getConstVal() << ">";
+      OS << "<" << *CP->getConstVal() << ">";
     if (offset > 0)
-      cerr << " + " << offset;
+      OS << " + " << offset;
     else
-      cerr << " " << offset;
+      OS << " " << offset;
   } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
-    cerr << "<";
+    OS << "<";
     const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
     if (LBB)
-      cerr << LBB->getName() << " ";
-    cerr << (const void*)BBDN->getBasicBlock() << ">";
+      OS << LBB->getName() << " ";
+    OS << (const void*)BBDN->getBasicBlock() << ">";
   } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
     if (G && R->getReg() &&
         TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
-      cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
+      OS << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
     } else {
-      cerr << " #" << R->getReg();
+      OS << " #" << R->getReg();
     }
   } else if (const ExternalSymbolSDNode *ES =
              dyn_cast<ExternalSymbolSDNode>(this)) {
-    cerr << "'" << ES->getSymbol() << "'";
+    OS << "'" << ES->getSymbol() << "'";
   } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
     if (M->getValue())
-      cerr << "<" << M->getValue() << ">";
+      OS << "<" << M->getValue() << ">";
     else
-      cerr << "<null>";
+      OS << "<null>";
   } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
     if (M->MO.getValue())
-      cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
+      OS << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
     else
-      cerr << "<null:" << M->MO.getOffset() << ">";
+      OS << "<null:" << M->MO.getOffset() << ">";
   } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
-    cerr << N->getArgFlags().getArgFlagsString();
+    OS << N->getArgFlags().getArgFlagsString();
   } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
-    cerr << ":" << N->getVT().getMVTString();
+    OS << ":" << N->getVT().getMVTString();
   }
   else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
     const Value *SrcValue = LD->getSrcValue();
     int SrcOffset = LD->getSrcValueOffset();
-    cerr << " <";
+    OS << " <";
     if (SrcValue)
-      cerr << SrcValue;
+      OS << SrcValue;
     else
-      cerr << "null";
-    cerr << ":" << SrcOffset << ">";
+      OS << "null";
+    OS << ":" << SrcOffset << ">";
 
     bool doExt = true;
     switch (LD->getExtensionType()) {
     default: doExt = false; break;
-    case ISD::EXTLOAD:
-      cerr << " <anyext ";
-      break;
-    case ISD::SEXTLOAD:
-      cerr << " <sext ";
-      break;
-    case ISD::ZEXTLOAD:
-      cerr << " <zext ";
-      break;
+    case ISD::EXTLOAD: OS << " <anyext "; break;
+    case ISD::SEXTLOAD: OS << " <sext "; break;
+    case ISD::ZEXTLOAD: OS << " <zext "; break;
     }
     if (doExt)
-      cerr << LD->getMemoryVT().getMVTString() << ">";
+      OS << LD->getMemoryVT().getMVTString() << ">";
 
     const char *AM = getIndexedModeName(LD->getAddressingMode());
     if (*AM)
-      cerr << " " << AM;
+      OS << " " << AM;
     if (LD->isVolatile())
-      cerr << " <volatile>";
-    cerr << " alignment=" << LD->getAlignment();
+      OS << " <volatile>";
+    OS << " alignment=" << LD->getAlignment();
   } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
     const Value *SrcValue = ST->getSrcValue();
     int SrcOffset = ST->getSrcValueOffset();
-    cerr << " <";
+    OS << " <";
     if (SrcValue)
-      cerr << SrcValue;
+      OS << SrcValue;
     else
-      cerr << "null";
-    cerr << ":" << SrcOffset << ">";
+      OS << "null";
+    OS << ":" << SrcOffset << ">";
 
     if (ST->isTruncatingStore())
-      cerr << " <trunc "
-           << ST->getMemoryVT().getMVTString() << ">";
+      OS << " <trunc " << ST->getMemoryVT().getMVTString() << ">";
 
     const char *AM = getIndexedModeName(ST->getAddressingMode());
     if (*AM)
-      cerr << " " << AM;
+      OS << " " << AM;
     if (ST->isVolatile())
-      cerr << " <volatile>";
-    cerr << " alignment=" << ST->getAlignment();
+      OS << " <volatile>";
+    OS << " alignment=" << ST->getAlignment();
   } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
     const Value *SrcValue = AT->getSrcValue();
     int SrcOffset = AT->getSrcValueOffset();
-    cerr << " <";
+    OS << " <";
     if (SrcValue)
-      cerr << SrcValue;
+      OS << SrcValue;
     else
-      cerr << "null";
-    cerr << ":" << SrcOffset << ">";
+      OS << "null";
+    OS << ":" << SrcOffset << ">";
     if (AT->isVolatile())
-      cerr << " <volatile>";
-    cerr << " alignment=" << AT->getAlignment();
+      OS << " <volatile>";
+    OS << " alignment=" << AT->getAlignment();
   }
 }
 
 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
-    if (N->getOperand(i).Val->hasOneUse())
-      DumpNodes(N->getOperand(i).Val, indent+2, G);
+    if (N->getOperand(i).getNode()->hasOneUse())
+      DumpNodes(N->getOperand(i).getNode(), indent+2, G);
     else
       cerr << "\n" << std::string(indent+2, ' ')
-           << (void*)N->getOperand(i).Val << ": <multiple use>";
+           << (void*)N->getOperand(i).getNode() << ": <multiple use>";
 
 
   cerr << "\n" << std::string(indent, ' ');
@@ -5135,11 +6036,11 @@ void SelectionDAG::dump() const {
   for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
        I != E; ++I) {
     const SDNode *N = I;
-    if (!N->hasOneUse() && N != getRoot().Val)
+    if (!N->hasOneUse() && N != getRoot().getNode())
       DumpNodes(N, 2, this);
   }
 
-  if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
+  if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
 
   cerr << "\n\n";
 }