Significantly improve handling of vectors that are live across basic blocks,
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeDAG.cpp
index dd8a4f3851e9302f3c69e85ef30b723a87020bf4..93b0d9b1cceae5731a3eb075ee0efd152d6343ff 100644 (file)
@@ -21,7 +21,7 @@
 #include "llvm/CallingConv.h"
 #include "llvm/Constants.h"
 #include <iostream>
-#include <set>
+#include <map>
 using namespace llvm;
 
 //===----------------------------------------------------------------------===//
@@ -74,12 +74,21 @@ class SelectionDAGLegalize {
   /// us to avoid promoting the same thing more than once.
   std::map<SDOperand, SDOperand> PromotedNodes;
 
-  /// ExpandedNodes - For nodes that need to be expanded, and which have more
-  /// than one use, this map indicates which which operands are the expanded
-  /// version of the input.  This allows us to avoid expanding the same node
-  /// more than once.
+  /// ExpandedNodes - For nodes that need to be expanded this map indicates
+  /// which which operands are the expanded version of the input.  This allows
+  /// us to avoid expanding the same node more than once.
   std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
 
+  /// SplitNodes - For vector nodes that need to be split, this map indicates
+  /// which which operands are the split version of the input.  This allows us
+  /// to avoid splitting the same node more than once.
+  std::map<SDOperand, std::pair<SDOperand, SDOperand> > SplitNodes;
+  
+  /// PackedNodes - For nodes that need to be packed from MVT::Vector types to
+  /// concrete packed types, this contains the mapping of ones we have already
+  /// processed to the result.
+  std::map<SDOperand, SDOperand> PackedNodes;
+  
   void AddLegalizedOperand(SDOperand From, SDOperand To) {
     LegalizedNodes.insert(std::make_pair(From, To));
     // If someone requests legalization of the new node, return itself.
@@ -113,21 +122,53 @@ public:
   void LegalizeDAG();
 
 private:
-
+  /// HandleOp - Legalize, Promote, Expand or Pack the specified operand as
+  /// appropriate for its type.
+  void HandleOp(SDOperand Op);
+    
+  /// LegalizeOp - We know that the specified value has a legal type.
+  /// Recursively ensure that the operands have legal types, then return the
+  /// result.
   SDOperand LegalizeOp(SDOperand O);
-  void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
+  
+  /// PromoteOp - Given an operation that produces a value in an invalid type,
+  /// promote it to compute the value into a larger type.  The produced value
+  /// will have the correct bits for the low portion of the register, but no
+  /// guarantee is made about the top bits: it may be zero, sign-extended, or
+  /// garbage.
   SDOperand PromoteOp(SDOperand O);
 
+  /// ExpandOp - Expand the specified SDOperand into its two component pieces
+  /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this,
+  /// the LegalizeNodes map is filled in for any results that are not expanded,
+  /// the ExpandedNodes map is filled in for any results that are expanded, and
+  /// the Lo/Hi values are returned.   This applies to integer types and Vector
+  /// types.
+  void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
+
+  /// SplitVectorOp - Given an operand of MVT::Vector type, break it down into
+  /// two smaller values of MVT::Vector type.
+  void SplitVectorOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
+  
+  /// PackVectorOp - Given an operand of MVT::Vector type, convert it into the
+  /// equivalent operation that returns a packed value (e.g. MVT::V4F32).  When
+  /// this is called, we know that PackedVT is the right type for the result and
+  /// we know that this type is legal for the target.
+  SDOperand PackVectorOp(SDOperand O, MVT::ValueType PackedVT);
+  
   bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest);
 
   void LegalizeSetCCOperands(SDOperand &LHS, SDOperand &RHS, SDOperand &CC);
     
+  SDOperand CreateStackTemporary(MVT::ValueType VT);
+
   SDOperand ExpandLibCall(const char *Name, SDNode *Node,
                           SDOperand &Hi);
   SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
                           SDOperand Source);
 
   SDOperand ExpandBIT_CONVERT(MVT::ValueType DestVT, SDOperand SrcOp);
+  SDOperand ExpandBUILD_VECTOR(SDNode *Node);
   SDOperand ExpandLegalINT_TO_FP(bool isSigned,
                                  SDOperand LegalOp,
                                  MVT::ValueType DestVT);
@@ -149,6 +190,8 @@ private:
 };
 }
 
+/// getScalarizedOpcode - Return the scalar opcode that corresponds to the
+/// specified vector opcode.
 static unsigned getScalarizedOpcode(unsigned VecOp, MVT::ValueType VT) {
   switch (VecOp) {
   default: assert(0 && "Don't know how to scalarize this opcode!");
@@ -220,23 +263,8 @@ void SelectionDAGLegalize::LegalizeDAG() {
          "Error: DAG is cyclic!");
   Visited.clear();
   
-  for (unsigned i = 0, e = Order.size(); i != e; ++i) {
-    SDNode *N = Order[i];
-    switch (getTypeAction(N->getValueType(0))) {
-    default: assert(0 && "Bad type action!");
-    case Legal:
-      LegalizeOp(SDOperand(N, 0));
-      break;
-    case Promote:
-      PromoteOp(SDOperand(N, 0));
-      break;
-    case Expand: {
-      SDOperand X, Y;
-      ExpandOp(SDOperand(N, 0), X, Y);
-      break;
-    }
-    }
-  }
+  for (unsigned i = 0, e = Order.size(); i != e; ++i)
+    HandleOp(SDOperand(Order[i], 0));
 
   // Finally, it's possible the root changed.  Get the new root.
   SDOperand OldRoot = DAG.getRoot();
@@ -246,6 +274,8 @@ void SelectionDAGLegalize::LegalizeDAG() {
   ExpandedNodes.clear();
   LegalizedNodes.clear();
   PromotedNodes.clear();
+  SplitNodes.clear();
+  PackedNodes.clear();
 
   // Remove dead nodes now.
   DAG.RemoveDeadNodes(OldRoot.Val);
@@ -350,8 +380,47 @@ bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N,
   return false;
 }
 
+/// HandleOp - Legalize, Promote, Expand or Pack the specified operand as
+/// appropriate for its type.
+void SelectionDAGLegalize::HandleOp(SDOperand Op) {
+  switch (getTypeAction(Op.getValueType())) {
+  default: assert(0 && "Bad type action!");
+  case Legal:   LegalizeOp(Op); break;
+  case Promote: PromoteOp(Op);  break;
+  case Expand:
+    if (Op.getValueType() != MVT::Vector) {
+      SDOperand X, Y;
+      ExpandOp(Op, X, Y);
+    } else {
+      SDNode *N = Op.Val;
+      unsigned NumOps = N->getNumOperands();
+      unsigned NumElements =
+        cast<ConstantSDNode>(N->getOperand(NumOps-2))->getValue();
+      MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(NumOps-1))->getVT();
+      MVT::ValueType PackedVT = getVectorType(EVT, NumElements);
+      if (PackedVT != MVT::Other && TLI.isTypeLegal(PackedVT)) {
+        // In the common case, this is a legal vector type, convert it to the
+        // packed operation and type now.
+        PackVectorOp(Op, PackedVT);
+      } else if (NumElements == 1) {
+        // Otherwise, if this is a single element vector, convert it to a
+        // scalar operation.
+        PackVectorOp(Op, EVT);
+      } else {
+        // Otherwise, this is a multiple element vector that isn't supported.
+        // Split it in half and legalize both parts.
+        SDOperand X, Y;
+        SplitVectorOp(Op, X, Y);
+      }
+    }
+    break;
+  }
+}
 
 
+/// LegalizeOp - We know that the specified value has a legal type.
+/// Recursively ensure that the operands have legal types, then return the
+/// result.
 SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
   assert(isTypeLegal(Op.getValueType()) &&
          "Caller should expand or promote operands that are not legal!");
@@ -361,19 +430,10 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
   // register on this target, make sure to expand or promote them.
   if (Node->getNumValues() > 1) {
     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
-      switch (getTypeAction(Node->getValueType(i))) {
-      case Legal: break;  // Nothing to do.
-      case Expand: {
-        SDOperand T1, T2;
-        ExpandOp(Op.getValue(i), T1, T2);
-        assert(LegalizedNodes.count(Op) &&
-               "Expansion didn't add legal operands!");
-        return LegalizedNodes[Op];
-      }
-      case Promote:
-        PromoteOp(Op.getValue(i));
+      if (getTypeAction(Node->getValueType(i)) != Legal) {
+        HandleOp(Op.getValue(i));
         assert(LegalizedNodes.count(Op) &&
-               "Promotion didn't add legal operands!");
+               "Handling didn't add legal operands!");
         return LegalizedNodes[Op];
       }
   }
@@ -395,7 +455,6 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
   case ISD::TargetFrameIndex:
   case ISD::TargetConstant:
   case ISD::TargetConstantFP:
-  case ISD::TargetConstantVec:
   case ISD::TargetConstantPool:
   case ISD::TargetGlobalAddress:
   case ISD::TargetExternalSymbol:
@@ -493,6 +552,34 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     }
     break;
   }
+    
+  case ISD::INTRINSIC_W_CHAIN:
+  case ISD::INTRINSIC_WO_CHAIN:
+  case ISD::INTRINSIC_VOID: {
+    std::vector<SDOperand> Ops;
+    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
+      Ops.push_back(LegalizeOp(Node->getOperand(i)));
+    Result = DAG.UpdateNodeOperands(Result, Ops);
+    
+    // Allow the target to custom lower its intrinsics if it wants to.
+    if (TLI.getOperationAction(Node->getOpcode(), MVT::Other) == 
+        TargetLowering::Custom) {
+      Tmp3 = TLI.LowerOperation(Result, DAG);
+      if (Tmp3.Val) Result = Tmp3;
+    }
+
+    if (Result.Val->getNumValues() == 1) break;
+
+    // Must have return value and chain result.
+    assert(Result.Val->getNumValues() == 2 &&
+           "Cannot return more than two values!");
+
+    // Since loads produce two values, make sure to remember that we 
+    // legalized both of them.
+    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
+    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
+    return Result.getValue(Op.ResNo);
+  }    
 
   case ISD::LOCATION:
     assert(Node->getNumOperands() == 5 && "Invalid LOCATION node!");
@@ -652,43 +739,6 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     }
     break;
   }
-  case ISD::ConstantVec:
-    switch (TLI.getOperationAction(ISD::ConstantVec, Node->getValueType(0))) {
-    default: assert(0 && "This action is not supported yet!");
-    case TargetLowering::Custom:
-      Tmp3 = TLI.LowerOperation(Result, DAG);
-      if (Tmp3.Val) {
-        Result = Tmp3;
-        break;
-      }
-      // FALLTHROUGH
-    case TargetLowering::Expand:
-      // We assume that vector constants are not legal, and will be immediately
-      // spilled to the constant pool.
-      //
-      // Create a ConstantPacked, and put it in the constant pool.
-      MVT::ValueType VT = Node->getValueType(0);
-      const Type *OpNTy = 
-        MVT::getTypeForValueType(Node->getOperand(0).getValueType());
-      std::vector<Constant*> CV;
-      if (MVT::isFloatingPoint(VT)) {
-        for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
-          double V = cast<ConstantFPSDNode>(Node->getOperand(i))->getValue();
-          CV.push_back(ConstantFP::get(OpNTy, V));
-        }
-      } else {
-        for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
-          uint64_t V = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
-          CV.push_back(ConstantUInt::get(OpNTy, V));
-        }
-      }
-      Constant *CP = ConstantPacked::get(CV);
-      SDOperand CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
-      Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
-                           DAG.getSrcValue(NULL));
-      break;
-    }
-    break;
   case ISD::TokenFactor:
     if (Node->getNumOperands() == 2) {
       Tmp1 = LegalizeOp(Node->getOperand(0));
@@ -708,6 +758,202 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     }
     break;
 
+  case ISD::BUILD_VECTOR:
+    switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
+    default: assert(0 && "This action is not supported yet!");
+    case TargetLowering::Custom:
+      Tmp3 = TLI.LowerOperation(Result, DAG);
+      if (Tmp3.Val) {
+        Result = Tmp3;
+        break;
+      }
+      // FALLTHROUGH
+    case TargetLowering::Expand:
+      Result = ExpandBUILD_VECTOR(Result.Val);
+      break;
+    }
+    break;
+  case ISD::INSERT_VECTOR_ELT:
+    Tmp1 = LegalizeOp(Node->getOperand(0));  // InVec
+    Tmp2 = LegalizeOp(Node->getOperand(1));  // InVal
+    Tmp3 = LegalizeOp(Node->getOperand(2));  // InEltNo
+    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
+    
+    switch (TLI.getOperationAction(ISD::INSERT_VECTOR_ELT,
+                                   Node->getValueType(0))) {
+    default: assert(0 && "This action is not supported yet!");
+    case TargetLowering::Legal:
+      break;
+    case TargetLowering::Custom:
+      Tmp3 = TLI.LowerOperation(Result, DAG);
+      if (Tmp3.Val) {
+        Result = Tmp3;
+        break;
+      }
+      // FALLTHROUGH
+    case TargetLowering::Expand: {
+      // If the target doesn't support this, we have to spill the input vector
+      // to a temporary stack slot, update the element, then reload it.  This is
+      // badness.  We could also load the value into a vector register (either
+      // with a "move to register" or "extload into register" instruction, then
+      // permute it into place, if the idx is a constant and if the idx is
+      // supported by the target.
+      SDOperand StackPtr = CreateStackTemporary(Tmp1.getValueType());
+      // Store the vector.
+      SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
+                                 Tmp1, StackPtr, DAG.getSrcValue(NULL));
+
+      // Truncate or zero extend offset to target pointer type.
+      MVT::ValueType IntPtr = TLI.getPointerTy();
+      if (Tmp3.getValueType() > IntPtr)
+        Tmp3 = DAG.getNode(ISD::TRUNCATE, IntPtr, Tmp3);
+      else
+        Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Tmp3);
+
+      // Add the offset to the index.
+      unsigned EltSize = MVT::getSizeInBits(Result.getValueType())/8;
+      Tmp3 = DAG.getNode(ISD::MUL, Tmp3.getValueType(), Tmp3,
+                         DAG.getConstant(EltSize, Tmp3.getValueType()));
+      SDOperand StackPtr2 =
+        DAG.getNode(ISD::ADD, Tmp3.getValueType(), Tmp3, StackPtr);
+      // Store the scalar value.
+      Ch = DAG.getNode(ISD::STORE, MVT::Other, Ch,
+                       Tmp2, StackPtr2, DAG.getSrcValue(NULL));
+      // Load the updated vector.
+      Result = DAG.getLoad(Result.getValueType(), Ch, StackPtr,
+                           DAG.getSrcValue(NULL));
+      break;
+    }
+    }
+    break;
+  case ISD::SCALAR_TO_VECTOR:
+    Tmp1 = LegalizeOp(Node->getOperand(0));  // InVal
+    Result = DAG.UpdateNodeOperands(Result, Tmp1);
+    switch (TLI.getOperationAction(ISD::SCALAR_TO_VECTOR,
+                                   Node->getValueType(0))) {
+    default: assert(0 && "This action is not supported yet!");
+    case TargetLowering::Legal:
+      break;
+    case TargetLowering::Custom:
+      Tmp3 = TLI.LowerOperation(Result, DAG);
+      if (Tmp3.Val) {
+        Result = Tmp3;
+        break;
+      }
+      // FALLTHROUGH
+    case TargetLowering::Expand: {
+      // If the target doesn't support this, store the value to a temporary
+      // stack slot, then EXTLOAD the vector back out.
+      // TODO: If a target doesn't support this, create a stack slot for the
+      // whole vector, then store into it, then load the whole vector.
+      SDOperand StackPtr = 
+        CreateStackTemporary(Node->getOperand(0).getValueType());
+      SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
+                                 Node->getOperand(0), StackPtr,
+                                 DAG.getSrcValue(NULL));
+      Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0), Ch, StackPtr,
+                              DAG.getSrcValue(NULL),
+                              Node->getOperand(0).getValueType());
+      break;
+    }
+    }
+    break;
+  case ISD::VECTOR_SHUFFLE:
+    assert(TLI.isShuffleLegal(Result.getValueType(), Node->getOperand(2)) &&
+           "vector shuffle should not be created if not legal!");
+    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the input vectors,
+    Tmp2 = LegalizeOp(Node->getOperand(1));   // but not the shuffle mask.
+    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
+
+    // Allow targets to custom lower the SHUFFLEs they support.
+    if (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, Result.getValueType())
+        == TargetLowering::Custom) {
+      Tmp1 = TLI.LowerOperation(Result, DAG);
+      if (Tmp1.Val) Result = Tmp1;
+    }
+    break;
+  
+  case ISD::EXTRACT_VECTOR_ELT:
+    Tmp1 = LegalizeOp(Node->getOperand(0));
+    Tmp2 = LegalizeOp(Node->getOperand(1));
+    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
+    
+    switch (TLI.getOperationAction(ISD::EXTRACT_VECTOR_ELT,
+                                   Tmp1.getValueType())) {
+    default: assert(0 && "This action is not supported yet!");
+    case TargetLowering::Legal:
+      break;
+    case TargetLowering::Custom:
+      Tmp3 = TLI.LowerOperation(Result, DAG);
+      if (Tmp3.Val) {
+        Result = Tmp3;
+        break;
+      }
+      // FALLTHROUGH
+    case TargetLowering::Expand: {
+      // If the target doesn't support this, store the value to a temporary
+      // stack slot, then LOAD the scalar element back out.
+      SDOperand StackPtr = CreateStackTemporary(Tmp1.getValueType());
+      SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
+                                 Tmp1, StackPtr, DAG.getSrcValue(NULL));
+      
+      // Add the offset to the index.
+      unsigned EltSize = MVT::getSizeInBits(Result.getValueType())/8;
+      Tmp2 = DAG.getNode(ISD::MUL, Tmp2.getValueType(), Tmp2,
+                         DAG.getConstant(EltSize, Tmp2.getValueType()));
+      StackPtr = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2, StackPtr);
+      
+      Result = DAG.getLoad(Result.getValueType(), Ch, StackPtr,
+                              DAG.getSrcValue(NULL));
+      break;
+    }
+    }
+    break;
+
+  case ISD::VEXTRACT_VECTOR_ELT: {
+    // We know that operand #0 is the Vec vector.  If the index is a constant
+    // or if the invec is a supported hardware type, we can use it.  Otherwise,
+    // lower to a store then an indexed load.
+    Tmp1 = Node->getOperand(0);
+    Tmp2 = LegalizeOp(Node->getOperand(1));
+    
+    SDNode *InVal = Tmp1.Val;
+    unsigned NumElems = cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
+    MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
+    
+    // Figure out if there is a Packed type corresponding to this Vector
+    // type.  If so, convert to the packed type.
+    MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
+    if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
+      // Turn this into a packed extract_vector_elt operation.
+      Tmp1 = PackVectorOp(Tmp1, TVT);
+      Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Node->getValueType(0),
+                           Tmp1, Tmp2);
+      break;
+    } else if (NumElems == 1) {
+      // This must be an access of the only element.
+      Result = PackVectorOp(Tmp1, EVT);
+      break;
+    } else if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Tmp2)) {
+      SDOperand Lo, Hi;
+      SplitVectorOp(Tmp1, Lo, Hi);
+      if (CIdx->getValue() < NumElems/2) {
+        Tmp1 = Lo;
+      } else {
+        Tmp1 = Hi;
+        Tmp2 = DAG.getConstant(CIdx->getValue() - NumElems/2,
+                               Tmp2.getValueType());
+      }
+
+      // It's now an extract from the appropriate high or low part.
+      Result = LegalizeOp(DAG.UpdateNodeOperands(Result, Tmp1, Tmp2));
+    } else {
+      // FIXME: IMPLEMENT STORE/LOAD lowering.  Need alignment of stack slot!!
+      assert(0 && "unimp!");
+    }
+    break;
+  }
+    
   case ISD::CALLSEQ_START: {
     SDNode *CallEnd = FindCallEndFromCallStart(Node);
     
@@ -945,100 +1191,6 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       break;
     }
     break;
-  case ISD::BRCONDTWOWAY:
-    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
-    switch (getTypeAction(Node->getOperand(1).getValueType())) {
-    case Expand: assert(0 && "It's impossible to expand bools");
-    case Legal:
-      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
-      break;
-    case Promote:
-      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
-      break;
-    }
-      
-    // If this target does not support BRCONDTWOWAY, lower it to a BRCOND/BR
-    // pair.
-    switch (TLI.getOperationAction(ISD::BRCONDTWOWAY, MVT::Other)) {
-    case TargetLowering::Promote:
-    default: assert(0 && "This action is not supported yet!");
-    case TargetLowering::Legal:
-      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
-                                      Node->getOperand(3));
-      break;
-    case TargetLowering::Expand:
-      // If BRTWOWAY_CC is legal for this target, then simply expand this node
-      // to that.  Otherwise, skip BRTWOWAY_CC and expand directly to a
-      // BRCOND/BR pair.
-      if (TLI.isOperationLegal(ISD::BRTWOWAY_CC, MVT::Other)) {
-        if (Tmp2.getOpcode() == ISD::SETCC) {
-          Tmp3 = Tmp2.getOperand(0);
-          Tmp4 = Tmp2.getOperand(1);
-          Tmp2 = Tmp2.getOperand(2);
-        } else {
-          Tmp3 = Tmp2;
-          Tmp4 = DAG.getConstant(0, Tmp2.getValueType());
-          Tmp2 = DAG.getCondCode(ISD::SETNE);
-        }
-        std::vector<SDOperand> Ops;
-        Ops.push_back(Tmp1);
-        Ops.push_back(Tmp2);
-        Ops.push_back(Tmp3);
-        Ops.push_back(Tmp4);
-        Ops.push_back(Node->getOperand(2));
-        Ops.push_back(Node->getOperand(3));
-        Result = DAG.getNode(ISD::BRTWOWAY_CC, MVT::Other, Ops);
-      } else {
-        Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
-                             Node->getOperand(2));
-        Result = DAG.getNode(ISD::BR, MVT::Other, Result, Node->getOperand(3));
-      }
-      break;
-    }
-    break;
-  case ISD::BRTWOWAY_CC: {
-    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
-    // Ensure that libcalls are emitted before a branch.
-    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
-    Tmp1 = LegalizeOp(Tmp1);
-    LastCALLSEQ_END = DAG.getEntryNode();
-    
-    Tmp2 = Node->getOperand(2);              // LHS 
-    Tmp3 = Node->getOperand(3);              // RHS
-    Tmp4 = Node->getOperand(1);              // CC
-    
-    LegalizeSetCCOperands(Tmp2, Tmp3, Tmp4);
-    
-    // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
-    // the LHS is a legal SETCC itself.  In this case, we need to compare
-    // the result against zero to select between true and false values.
-    if (Tmp3.Val == 0) {
-      Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
-      Tmp4 = DAG.getCondCode(ISD::SETNE);
-    }
-    std::vector<SDOperand> Ops;
-    Ops.push_back(Tmp1);
-    Ops.push_back(Tmp4);
-    Ops.push_back(Tmp2);
-    Ops.push_back(Tmp3);
-    Ops.push_back(Node->getOperand(4));
-    Ops.push_back(Node->getOperand(5));
-    Result = DAG.UpdateNodeOperands(Result, Ops);
-
-    // Everything is legal, see if we should expand this op or something.
-    switch (TLI.getOperationAction(ISD::BRTWOWAY_CC, MVT::Other)) {
-    default: assert(0 && "This action is not supported yet!");
-    case TargetLowering::Legal: break;
-    case TargetLowering::Expand: 
-      Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1,
-                           DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), Tmp2,
-                                       Tmp3, Tmp4), 
-                           Result.getOperand(4));
-      Result = DAG.getNode(ISD::BR, MVT::Other, Result, Result.getOperand(5));
-      break;
-    }
-    break;
-  }
   case ISD::LOAD: {
     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
@@ -1260,6 +1412,7 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
 
     // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
     // FIXME: We shouldn't do this for TargetConstantFP's.
+    // FIXME: move this to the DAG Combiner!
     if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
       if (CFP->getValueType(0) == MVT::f32) {
         Tmp3 = DAG.getConstant(FloatToBits(CFP->getValue()), MVT::i32);
@@ -1298,25 +1451,47 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       break;
 
     case Expand:
+      unsigned IncrementSize = 0;
       SDOperand Lo, Hi;
-      ExpandOp(Node->getOperand(1), Lo, Hi);
-
-      if (!TLI.isLittleEndian())
-        std::swap(Lo, Hi);
-
-      Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2,
-                       Node->getOperand(3));
+      
       // If this is a vector type, then we have to calculate the increment as
       // the product of the element size in bytes, and the number of elements
       // in the high half of the vector.
-      unsigned IncrementSize;
-      if (MVT::Vector == Hi.getValueType()) {
-        unsigned NumElems = cast<ConstantSDNode>(Hi.getOperand(0))->getValue();
-        MVT::ValueType EVT = cast<VTSDNode>(Hi.getOperand(1))->getVT();
-        IncrementSize = NumElems * MVT::getSizeInBits(EVT)/8;
+      if (Node->getOperand(1).getValueType() == MVT::Vector) {
+        SDNode *InVal = Node->getOperand(1).Val;
+        unsigned NumElems =
+          cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
+        MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
+
+        // Figure out if there is a Packed type corresponding to this Vector
+        // type.  If so, convert to the packed type.
+        MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
+        if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
+          // Turn this into a normal store of the packed type.
+          Tmp3 = PackVectorOp(Node->getOperand(1), TVT);
+          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
+                                          Node->getOperand(3));
+          break;
+        } else if (NumElems == 1) {
+          // Turn this into a normal store of the scalar type.
+          Tmp3 = PackVectorOp(Node->getOperand(1), EVT);
+          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
+                                          Node->getOperand(3));
+          break;
+        } else {
+          SplitVectorOp(Node->getOperand(1), Lo, Hi);
+          IncrementSize = NumElems/2 * MVT::getSizeInBits(EVT)/8;
+        }
       } else {
+        ExpandOp(Node->getOperand(1), Lo, Hi);
         IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
       }
+
+      if (!TLI.isLittleEndian())
+        std::swap(Lo, Hi);
+
+      Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2,
+                       Node->getOperand(3));
       Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
                          getIntPtrConstant(IncrementSize));
       assert(isTypeLegal(Tmp2.getValueType()) &&
@@ -1775,7 +1950,71 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       break;
     }
     break;
-  
+    
+  case ISD::FCOPYSIGN:  // FCOPYSIGN does not require LHS/RHS to match type!
+    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
+    switch (getTypeAction(Node->getOperand(1).getValueType())) {
+      case Expand: assert(0 && "Not possible");
+      case Legal:
+        Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
+        break;
+      case Promote:
+        Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
+        break;
+    }
+      
+    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
+    
+    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
+    default: assert(0 && "Operation not supported");
+    case TargetLowering::Custom:
+      Tmp1 = TLI.LowerOperation(Result, DAG);
+      if (Tmp1.Val) Result = Tmp1;
+      break;
+    case TargetLowering::Legal: break;
+    case TargetLowering::Expand:
+      // If this target supports fabs/fneg natively, do this efficiently.
+      if (TLI.isOperationLegal(ISD::FABS, Tmp1.getValueType()) &&
+          TLI.isOperationLegal(ISD::FNEG, Tmp1.getValueType())) {
+        // Get the sign bit of the RHS.
+        MVT::ValueType IVT = 
+          Tmp2.getValueType() == MVT::f32 ? MVT::i32 : MVT::i64;
+        SDOperand SignBit = DAG.getNode(ISD::BIT_CONVERT, IVT, Tmp2);
+        SignBit = DAG.getSetCC(TLI.getSetCCResultTy(),
+                               SignBit, DAG.getConstant(0, IVT), ISD::SETLT);
+        // Get the absolute value of the result.
+        SDOperand AbsVal = DAG.getNode(ISD::FABS, Tmp1.getValueType(), Tmp1);
+        // Select between the nabs and abs value based on the sign bit of
+        // the input.
+        Result = DAG.getNode(ISD::SELECT, AbsVal.getValueType(), SignBit,
+                             DAG.getNode(ISD::FNEG, AbsVal.getValueType(), 
+                                         AbsVal),
+                             AbsVal);
+        Result = LegalizeOp(Result);
+        break;
+      }
+      
+      // Otherwise, do bitwise ops!
+      
+      // copysign -> copysignf/copysign libcall.
+      const char *FnName;
+      if (Node->getValueType(0) == MVT::f32) {
+        FnName = "copysignf";
+        if (Tmp2.getValueType() != MVT::f32)  // Force operands to match type.
+          Result = DAG.UpdateNodeOperands(Result, Tmp1, 
+                                    DAG.getNode(ISD::FP_ROUND, MVT::f32, Tmp2));
+      } else {
+        FnName = "copysign";
+        if (Tmp2.getValueType() != MVT::f64)  // Force operands to match type.
+          Result = DAG.UpdateNodeOperands(Result, Tmp1, 
+                                   DAG.getNode(ISD::FP_EXTEND, MVT::f64, Tmp2));
+      }
+      SDOperand Dummy;
+      Result = ExpandLibCall(FnName, Node, Dummy);
+      break;
+    }
+    break;
+    
   case ISD::ADDC:
   case ISD::SUBC:
     Tmp1 = LegalizeOp(Node->getOperand(0));
@@ -1786,7 +2025,6 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
     return Result;
-    break;
 
   case ISD::ADDE:
   case ISD::SUBE:
@@ -1799,7 +2037,6 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
     return Result;
-    break;
     
   case ISD::BUILD_PAIR: {
     MVT::ValueType PairTy = Node->getValueType(0);
@@ -2126,6 +2363,36 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       }
     }
     break;
+  case ISD::VBIT_CONVERT: {
+    assert(Op.getOperand(0).getValueType() == MVT::Vector &&
+           "Can only have VBIT_CONVERT where input or output is MVT::Vector!");
+    
+    // The input has to be a vector type, we have to either scalarize it, pack
+    // it, or convert it based on whether the input vector type is legal.
+    SDNode *InVal = Node->getOperand(0).Val;
+    unsigned NumElems =
+      cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
+    MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
+    
+    // Figure out if there is a Packed type corresponding to this Vector
+    // type.  If so, convert to the packed type.
+    MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
+    if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
+      // Turn this into a bit convert of the packed input.
+      Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), 
+                           PackVectorOp(Node->getOperand(0), TVT));
+      break;
+    } else if (NumElems == 1) {
+      // Turn this into a bit convert of the scalar input.
+      Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), 
+                           PackVectorOp(Node->getOperand(0), EVT));
+      break;
+    } else {
+      // FIXME: UNIMP!  Store then reload
+      assert(0 && "Cast from unsupported vector type not implemented yet!");
+    }
+  }
+      
     // Conversion operators.  The source and destination have different types.
   case ISD::SINT_TO_FP:
   case ISD::UINT_TO_FP: {
@@ -2604,13 +2871,14 @@ SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
     break;
   case ISD::FDIV:
   case ISD::FREM:
+  case ISD::FCOPYSIGN:
     // These operators require that their input be fp extended.
     Tmp1 = PromoteOp(Node->getOperand(0));
     Tmp2 = PromoteOp(Node->getOperand(1));
     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
     
     // Perform FP_ROUND: this is probably overly pessimistic.
-    if (NoExcessFPPrecision)
+    if (NoExcessFPPrecision && Node->getOpcode() != ISD::FCOPYSIGN)
       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
                            DAG.getValueType(VT));
     break;
@@ -2868,10 +3136,7 @@ void SelectionDAGLegalize::LegalizeSetCCOperands(SDOperand &LHS,
 SDOperand SelectionDAGLegalize::ExpandBIT_CONVERT(MVT::ValueType DestVT, 
                                                   SDOperand SrcOp) {
   // Create the stack frame object.
-  MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
-  unsigned ByteSize = MVT::getSizeInBits(DestVT)/8;
-  int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
-  SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
+  SDOperand FIPtr = CreateStackTemporary(DestVT);
   
   // Emit a store to the stack slot.
   SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
@@ -2880,6 +3145,175 @@ SDOperand SelectionDAGLegalize::ExpandBIT_CONVERT(MVT::ValueType DestVT,
   return DAG.getLoad(DestVT, Store, FIPtr, DAG.getSrcValue(0));
 }
 
+/// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
+/// support the operation, but do support the resultant packed vector type.
+SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
+  
+  // If the only non-undef value is the low element, turn this into a 
+  // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
+  unsigned NumElems = Node->getNumOperands();
+  bool isOnlyLowElement = true;
+  SDOperand SplatValue = Node->getOperand(0);
+  std::map<SDOperand, std::vector<unsigned> > Values;
+  Values[SplatValue].push_back(0);
+  bool isConstant = true;
+  if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
+      SplatValue.getOpcode() != ISD::UNDEF)
+    isConstant = false;
+  
+  for (unsigned i = 1; i < NumElems; ++i) {
+    SDOperand V = Node->getOperand(i);
+    std::map<SDOperand, std::vector<unsigned> >::iterator I = Values.find(V);
+    if (I != Values.end())
+      I->second.push_back(i);
+    else
+      Values[V].push_back(i);
+    if (V.getOpcode() != ISD::UNDEF)
+      isOnlyLowElement = false;
+    if (SplatValue != V)
+      SplatValue = SDOperand(0,0);
+
+    // If this isn't a constant element or an undef, we can't use a constant
+    // pool load.
+    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
+        V.getOpcode() != ISD::UNDEF)
+      isConstant = false;
+  }
+  
+  if (isOnlyLowElement) {
+    // If the low element is an undef too, then this whole things is an undef.
+    if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
+      return DAG.getNode(ISD::UNDEF, Node->getValueType(0));
+    // Otherwise, turn this into a scalar_to_vector node.
+    return DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
+                       Node->getOperand(0));
+  }
+  
+  // If all elements are constants, create a load from the constant pool.
+  if (isConstant) {
+    MVT::ValueType VT = Node->getValueType(0);
+    const Type *OpNTy = 
+      MVT::getTypeForValueType(Node->getOperand(0).getValueType());
+    std::vector<Constant*> CV;
+    for (unsigned i = 0, e = NumElems; i != e; ++i) {
+      if (ConstantFPSDNode *V = 
+          dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
+        CV.push_back(ConstantFP::get(OpNTy, V->getValue()));
+      } else if (ConstantSDNode *V = 
+                 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
+        CV.push_back(ConstantUInt::get(OpNTy, V->getValue()));
+      } else {
+        assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
+        CV.push_back(UndefValue::get(OpNTy));
+      }
+    }
+    Constant *CP = ConstantPacked::get(CV);
+    SDOperand CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
+    return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
+                       DAG.getSrcValue(NULL));
+  }
+  
+  if (SplatValue.Val) {   // Splat of one value?
+    // Build the shuffle constant vector: <0, 0, 0, 0>
+    MVT::ValueType MaskVT = 
+      MVT::getIntVectorWithNumElements(NumElems);
+    SDOperand Zero = DAG.getConstant(0, MVT::getVectorBaseType(MaskVT));
+    std::vector<SDOperand> ZeroVec(NumElems, Zero);
+    SDOperand SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, ZeroVec);
+
+    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
+    if (TLI.isShuffleLegal(Node->getValueType(0), SplatMask)) {
+      // Get the splatted value into the low element of a vector register.
+      SDOperand LowValVec = 
+        DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), SplatValue);
+    
+      // Return shuffle(LowValVec, undef, <0,0,0,0>)
+      return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), LowValVec,
+                         DAG.getNode(ISD::UNDEF, Node->getValueType(0)),
+                         SplatMask);
+    }
+  }
+  
+  // If there are only two unique elements, we may be able to turn this into a
+  // vector shuffle.
+  if (Values.size() == 2) {
+    // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
+    MVT::ValueType MaskVT = 
+      MVT::getIntVectorWithNumElements(NumElems);
+    std::vector<SDOperand> MaskVec(NumElems);
+    unsigned i = 0;
+    for (std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
+           E = Values.end(); I != E; ++I) {
+      for (std::vector<unsigned>::iterator II = I->second.begin(),
+             EE = I->second.end(); II != EE; ++II)
+        MaskVec[*II] = DAG.getConstant(i, MVT::getVectorBaseType(MaskVT));
+      i += NumElems;
+    }
+    SDOperand ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
+
+    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
+    if (TLI.isShuffleLegal(Node->getValueType(0), ShuffleMask) &&
+        TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0))) {
+      std::vector<SDOperand> Ops;
+      for(std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
+            E = Values.end(); I != E; ++I) {
+        SDOperand Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
+                                   I->first);
+        Ops.push_back(Op);
+      }
+      Ops.push_back(ShuffleMask);
+
+      // Return shuffle(LoValVec, HiValVec, <0,1,0,1>)
+      return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), Ops);
+    }
+  }
+  
+  // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
+  // aligned object on the stack, store each element into it, then load
+  // the result as a vector.
+  MVT::ValueType VT = Node->getValueType(0);
+  // Create the stack frame object.
+  SDOperand FIPtr = CreateStackTemporary(VT);
+  
+  // Emit a store of each element to the stack slot.
+  std::vector<SDOperand> Stores;
+  unsigned TypeByteSize = 
+    MVT::getSizeInBits(Node->getOperand(0).getValueType())/8;
+  unsigned VectorSize = MVT::getSizeInBits(VT)/8;
+  // Store (in the right endianness) the elements to memory.
+  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
+    // Ignore undef elements.
+    if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
+    
+    unsigned Offset = TypeByteSize*i;
+    
+    SDOperand Idx = DAG.getConstant(Offset, FIPtr.getValueType());
+    Idx = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr, Idx);
+    
+    Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
+                                 Node->getOperand(i), Idx, 
+                                 DAG.getSrcValue(NULL)));
+  }
+  
+  SDOperand StoreChain;
+  if (!Stores.empty())    // Not all undef elements?
+    StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
+  else
+    StoreChain = DAG.getEntryNode();
+  
+  // Result is a load from the stack slot.
+  return DAG.getLoad(VT, StoreChain, FIPtr, DAG.getSrcValue(0));
+}
+
+/// CreateStackTemporary - Create a stack temporary, suitable for holding the
+/// specified value type.
+SDOperand SelectionDAGLegalize::CreateStackTemporary(MVT::ValueType VT) {
+  MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
+  unsigned ByteSize = MVT::getSizeInBits(VT)/8;
+  int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
+  return DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
+}
+
 void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
                                             SDOperand Op, SDOperand Amt,
                                             SDOperand &Lo, SDOperand &Hi) {
@@ -3123,14 +3557,11 @@ SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
     // word offset constant for Hi/Lo address computation
     SDOperand WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
     // set up Hi and Lo (into buffer) address based on endian
-    SDOperand Hi, Lo;
-    if (TLI.isLittleEndian()) {
-      Hi = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot, WordOff);
-      Lo = StackSlot;
-    } else {
-      Hi = StackSlot;
-      Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot, WordOff);
-    }
+    SDOperand Hi = StackSlot;
+    SDOperand Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot,WordOff);
+    if (TLI.isLittleEndian())
+      std::swap(Hi, Lo);
+    
     // if signed map to unsigned space
     SDOperand Op0Mapped;
     if (isSigned) {
@@ -3472,43 +3903,6 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
     Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
     break;
   }
-  case ISD::VConstant: {
-    unsigned NumElements =
-      cast<ConstantSDNode>(Node->getOperand(0))->getValue() / 2;
-    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
-    MVT::ValueType TVT = (NumElements > 1)
-                         ? getVectorType(EVT, NumElements) : EVT;
-    // If type of bisected vector is legal, turn it into a ConstantVec (which
-    // will be lowered to a ConstantPool or something else). Otherwise, bisect
-    // the VConstant, and return each half as a new VConstant.
-    unsigned Opc = ISD::ConstantVec;
-    std::vector<SDOperand> LoOps, HiOps;
-    if (!(TVT != MVT::Other &&
-          (!MVT::isVector(TVT) || TLI.isTypeLegal(TVT)))) {
-      Opc = ISD::VConstant;
-      TVT = MVT::Vector;
-      SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
-      SDOperand Typ = DAG.getValueType(EVT);
-      HiOps.push_back(Num);
-      HiOps.push_back(Typ);
-      LoOps.push_back(Num);
-      LoOps.push_back(Typ);
-    }
-
-    if (NumElements == 1) {
-      Hi = Node->getOperand(2);
-      Lo = Node->getOperand(3);
-    } else {
-      for (unsigned I = 0, E = NumElements; I < E; ++I) {
-        HiOps.push_back(Node->getOperand(I+2));
-        LoOps.push_back(Node->getOperand(I+2+NumElements));
-      }
-      Hi = DAG.getNode(Opc, TVT, HiOps);
-      Lo = DAG.getNode(Opc, TVT, LoOps);
-    }
-    break;
-  }
-
   case ISD::BUILD_PAIR:
     // Return the operands.
     Lo = Node->getOperand(0);
@@ -3608,80 +4002,6 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
       std::swap(Lo, Hi);
     break;
   }
-  case ISD::VLOAD: {
-    SDOperand Ch = Node->getOperand(2);   // Legalize the chain.
-    SDOperand Ptr = Node->getOperand(3);  // Legalize the pointer.
-    unsigned NumElements =cast<ConstantSDNode>(Node->getOperand(0))->getValue();
-    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
-    MVT::ValueType TVT = (NumElements/2 > 1)
-      ? getVectorType(EVT, NumElements/2) : EVT;
-    
-    // If type of split vector is legal, turn into a pair of scalar or
-    // packed loads.
-    if (TVT != MVT::Other &&
-        (!MVT::isVector(TVT) ||
-         (TLI.isTypeLegal(TVT) && TLI.isOperationLegal(ISD::LOAD, TVT)))) {
-      Lo = DAG.getLoad(TVT, Ch, Ptr, Node->getOperand(4));
-      // Increment the pointer to the other half.
-      unsigned IncrementSize = MVT::getSizeInBits(TVT)/8;
-      Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
-                        getIntPtrConstant(IncrementSize));
-      // FIXME: This creates a bogus srcvalue!
-      Hi = DAG.getLoad(TVT, Ch, Ptr, Node->getOperand(4));
-    } else {
-      NumElements /= 2; // Split the vector in half
-      Lo = DAG.getVecLoad(NumElements, EVT, Ch, Ptr, Node->getOperand(4));
-      unsigned IncrementSize = NumElements * MVT::getSizeInBits(EVT)/8;
-      Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
-                        getIntPtrConstant(IncrementSize));
-      // FIXME: This creates a bogus srcvalue!
-      Hi = DAG.getVecLoad(NumElements, EVT, Ch, Ptr, Node->getOperand(4));
-    }
-    
-    // Build a factor node to remember that this load is independent of the
-    // other one.
-    SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
-                               Hi.getValue(1));
-    
-    // Remember that we legalized the chain.
-    AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
-    if (!TLI.isLittleEndian())
-      std::swap(Lo, Hi);
-    break;
-  }
-  case ISD::VADD:
-  case ISD::VSUB:
-  case ISD::VMUL:
-  case ISD::VSDIV:
-  case ISD::VUDIV:
-  case ISD::VAND:
-  case ISD::VOR:
-  case ISD::VXOR: {
-    unsigned NumElements =cast<ConstantSDNode>(Node->getOperand(0))->getValue();
-    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
-    MVT::ValueType TVT = (NumElements/2 > 1)
-                         ? getVectorType(EVT, NumElements/2) : EVT;
-    SDOperand LL, LH, RL, RH;
-    
-    ExpandOp(Node->getOperand(2), LL, LH);
-    ExpandOp(Node->getOperand(3), RL, RH);
-
-    // If type of split vector is legal, turn into a pair of scalar / packed
-    // ADD, SUB, or MUL.
-    unsigned Opc = getScalarizedOpcode(Node->getOpcode(), EVT);
-    if (TVT != MVT::Other &&
-        (!MVT::isVector(TVT) ||
-         (TLI.isTypeLegal(TVT) && TLI.isOperationLegal(Opc, TVT)))) {
-      Lo = DAG.getNode(Opc, TVT, LL, RL);
-      Hi = DAG.getNode(Opc, TVT, LH, RH);
-    } else {
-      SDOperand Num = DAG.getConstant(NumElements/2, MVT::i32);
-      SDOperand Typ = DAG.getValueType(EVT);
-      Lo = DAG.getNode(Node->getOpcode(), MVT::Vector, Num, Typ, LL, RL);
-      Hi = DAG.getNode(Node->getOpcode(), MVT::Vector, Num, Typ, LH, RH);
-    }
-    break;
-  }
   case ISD::AND:
   case ISD::OR:
   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
@@ -4046,6 +4366,251 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
   assert(isNew && "Value already expanded?!?");
 }
 
+/// SplitVectorOp - Given an operand of MVT::Vector type, break it down into
+/// two smaller values of MVT::Vector type.
+void SelectionDAGLegalize::SplitVectorOp(SDOperand Op, SDOperand &Lo,
+                                         SDOperand &Hi) {
+  assert(Op.getValueType() == MVT::Vector && "Cannot split non-vector type!");
+  SDNode *Node = Op.Val;
+  unsigned NumElements = cast<ConstantSDNode>(*(Node->op_end()-2))->getValue();
+  assert(NumElements > 1 && "Cannot split a single element vector!");
+  unsigned NewNumElts = NumElements/2;
+  SDOperand NewNumEltsNode = DAG.getConstant(NewNumElts, MVT::i32);
+  SDOperand TypeNode = *(Node->op_end()-1);
+  
+  // See if we already split it.
+  std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
+    = SplitNodes.find(Op);
+  if (I != SplitNodes.end()) {
+    Lo = I->second.first;
+    Hi = I->second.second;
+    return;
+  }
+  
+  switch (Node->getOpcode()) {
+  default: Node->dump(); assert(0 && "Unknown vector operation!");
+  case ISD::VBUILD_VECTOR: {
+    std::vector<SDOperand> LoOps(Node->op_begin(), Node->op_begin()+NewNumElts);
+    LoOps.push_back(NewNumEltsNode);
+    LoOps.push_back(TypeNode);
+    Lo = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, LoOps);
+
+    std::vector<SDOperand> HiOps(Node->op_begin()+NewNumElts, Node->op_end()-2);
+    HiOps.push_back(NewNumEltsNode);
+    HiOps.push_back(TypeNode);
+    Hi = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, HiOps);
+    break;
+  }
+  case ISD::VADD:
+  case ISD::VSUB:
+  case ISD::VMUL:
+  case ISD::VSDIV:
+  case ISD::VUDIV:
+  case ISD::VAND:
+  case ISD::VOR:
+  case ISD::VXOR: {
+    SDOperand LL, LH, RL, RH;
+    SplitVectorOp(Node->getOperand(0), LL, LH);
+    SplitVectorOp(Node->getOperand(1), RL, RH);
+    
+    Lo = DAG.getNode(Node->getOpcode(), MVT::Vector, LL, RL,
+                     NewNumEltsNode, TypeNode);
+    Hi = DAG.getNode(Node->getOpcode(), MVT::Vector, LH, RH,
+                     NewNumEltsNode, TypeNode);
+    break;
+  }
+  case ISD::VLOAD: {
+    SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
+    SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
+    MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
+    
+    Lo = DAG.getVecLoad(NewNumElts, EVT, Ch, Ptr, Node->getOperand(2));
+    unsigned IncrementSize = NewNumElts * MVT::getSizeInBits(EVT)/8;
+    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
+                      getIntPtrConstant(IncrementSize));
+    // FIXME: This creates a bogus srcvalue!
+    Hi = DAG.getVecLoad(NewNumElts, EVT, Ch, Ptr, Node->getOperand(2));
+    
+    // Build a factor node to remember that this load is independent of the
+    // other one.
+    SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
+                               Hi.getValue(1));
+    
+    // Remember that we legalized the chain.
+    AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
+    if (!TLI.isLittleEndian())
+      std::swap(Lo, Hi);
+    break;
+  }
+  case ISD::VBIT_CONVERT: {
+    // We know the result is a vector.  The input may be either a vector or a
+    // scalar value.
+    if (Op.getOperand(0).getValueType() != MVT::Vector) {
+      // Lower to a store/load.  FIXME: this could be improved probably.
+      SDOperand Ptr = CreateStackTemporary(Op.getOperand(0).getValueType());
+
+      SDOperand St = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
+                                 Op.getOperand(0), Ptr, DAG.getSrcValue(0));
+      MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
+      St = DAG.getVecLoad(NumElements, EVT, St, Ptr, DAG.getSrcValue(0));
+      SplitVectorOp(St, Lo, Hi);
+    } else {
+      // If the input is a vector type, we have to either scalarize it, pack it
+      // or convert it based on whether the input vector type is legal.
+      SDNode *InVal = Node->getOperand(0).Val;
+      unsigned NumElems =
+        cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
+      MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
+
+      // If the input is from a single element vector, scalarize the vector,
+      // then treat like a scalar.
+      if (NumElems == 1) {
+        SDOperand Scalar = PackVectorOp(Op.getOperand(0), EVT);
+        Scalar = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Scalar,
+                             Op.getOperand(1), Op.getOperand(2));
+        SplitVectorOp(Scalar, Lo, Hi);
+      } else {
+        // Split the input vector.
+        SplitVectorOp(Op.getOperand(0), Lo, Hi);
+
+        // Convert each of the pieces now.
+        Lo = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Lo,
+                         NewNumEltsNode, TypeNode);
+        Hi = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Hi,
+                         NewNumEltsNode, TypeNode);
+      }
+      break;
+    }
+  }
+  }
+      
+  // Remember in a map if the values will be reused later.
+  bool isNew =
+    SplitNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
+  assert(isNew && "Value already expanded?!?");
+}
+
+
+/// PackVectorOp - Given an operand of MVT::Vector type, convert it into the
+/// equivalent operation that returns a scalar (e.g. F32) or packed value
+/// (e.g. MVT::V4F32).  When this is called, we know that PackedVT is the right
+/// type for the result.
+SDOperand SelectionDAGLegalize::PackVectorOp(SDOperand Op, 
+                                             MVT::ValueType NewVT) {
+  assert(Op.getValueType() == MVT::Vector && "Bad PackVectorOp invocation!");
+  SDNode *Node = Op.Val;
+  
+  // See if we already packed it.
+  std::map<SDOperand, SDOperand>::iterator I = PackedNodes.find(Op);
+  if (I != PackedNodes.end()) return I->second;
+  
+  SDOperand Result;
+  switch (Node->getOpcode()) {
+  default: 
+    Node->dump(); std::cerr << "\n";
+    assert(0 && "Unknown vector operation in PackVectorOp!");
+  case ISD::VADD:
+  case ISD::VSUB:
+  case ISD::VMUL:
+  case ISD::VSDIV:
+  case ISD::VUDIV:
+  case ISD::VAND:
+  case ISD::VOR:
+  case ISD::VXOR:
+    Result = DAG.getNode(getScalarizedOpcode(Node->getOpcode(), NewVT),
+                         NewVT, 
+                         PackVectorOp(Node->getOperand(0), NewVT),
+                         PackVectorOp(Node->getOperand(1), NewVT));
+    break;
+  case ISD::VLOAD: {
+    SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
+    SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
+    
+    Result = DAG.getLoad(NewVT, Ch, Ptr, Node->getOperand(2));
+    
+    // Remember that we legalized the chain.
+    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
+    break;
+  }
+  case ISD::VBUILD_VECTOR:
+    if (Node->getOperand(0).getValueType() == NewVT) {
+      // Returning a scalar?
+      Result = Node->getOperand(0);
+    } else {
+      // Returning a BUILD_VECTOR?
+      std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end()-2);
+      Result = DAG.getNode(ISD::BUILD_VECTOR, NewVT, Ops);
+    }
+    break;
+  case ISD::VINSERT_VECTOR_ELT:
+    if (!MVT::isVector(NewVT)) {
+      // Returning a scalar?  Must be the inserted element.
+      Result = Node->getOperand(1);
+    } else {
+      Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT,
+                           PackVectorOp(Node->getOperand(0), NewVT),
+                           Node->getOperand(1), Node->getOperand(2));
+    }
+    break;
+  case ISD::VVECTOR_SHUFFLE:
+    if (!MVT::isVector(NewVT)) {
+      // Returning a scalar?  Figure out if it is the LHS or RHS and return it.
+      SDOperand EltNum = Node->getOperand(2).getOperand(0);
+      if (cast<ConstantSDNode>(EltNum)->getValue())
+        Result = PackVectorOp(Node->getOperand(1), NewVT);
+      else
+        Result = PackVectorOp(Node->getOperand(0), NewVT);
+    } else {
+      // Otherwise, return a VECTOR_SHUFFLE node.  First convert the index
+      // vector from a VBUILD_VECTOR to a BUILD_VECTOR.
+      std::vector<SDOperand> BuildVecIdx(Node->getOperand(2).Val->op_begin(),
+                                         Node->getOperand(2).Val->op_end()-2);
+      MVT::ValueType BVT = MVT::getIntVectorWithNumElements(BuildVecIdx.size());
+      SDOperand BV = DAG.getNode(ISD::BUILD_VECTOR, BVT, BuildVecIdx);
+      
+      Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT,
+                           PackVectorOp(Node->getOperand(0), NewVT),
+                           PackVectorOp(Node->getOperand(1), NewVT), BV);
+    }
+    break;
+  case ISD::VBIT_CONVERT:
+    if (Op.getOperand(0).getValueType() != MVT::Vector)
+      Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, Op.getOperand(0));
+    else {
+      // If the input is a vector type, we have to either scalarize it, pack it
+      // or convert it based on whether the input vector type is legal.
+      SDNode *InVal = Node->getOperand(0).Val;
+      unsigned NumElems =
+        cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
+      MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
+        
+      // Figure out if there is a Packed type corresponding to this Vector
+      // type.  If so, convert to the packed type.
+      MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
+      if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
+        // Turn this into a bit convert of the packed input.
+        Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, 
+                             PackVectorOp(Node->getOperand(0), TVT));
+        break;
+      } else if (NumElems == 1) {
+        // Turn this into a bit convert of the scalar input.
+        Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, 
+                             PackVectorOp(Node->getOperand(0), EVT));
+        break;
+      } else {
+        // FIXME: UNIMP!
+        assert(0 && "Cast from unsupported vector type not implemented yet!");
+      }
+    }
+  }
+
+  if (TLI.isTypeLegal(NewVT))
+    Result = LegalizeOp(Result);
+  bool isNew = PackedNodes.insert(std::make_pair(Op, Result)).second;
+  assert(isNew && "Value already packed?");
+  return Result;
+}
+
 
 // SelectionDAG::Legalize - This is the entry point for the file.
 //