Combine ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD into ISD::LOADX. Add an
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeDAG.cpp
index aeac2622d8a17df80ffa471372e9a12fec52ae6e..07b72a63729385403e25f9a376f76b62e0c2e738 100644 (file)
 #include "llvm/CodeGen/SelectionDAG.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
-#include "llvm/Support/MathExtras.h"
 #include "llvm/Target/TargetLowering.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Target/TargetOptions.h"
 #include "llvm/CallingConv.h"
 #include "llvm/Constants.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/ADT/SmallVector.h"
 #include <iostream>
-#include <set>
+#include <map>
 using namespace llvm;
 
+#ifndef NDEBUG
+static cl::opt<bool>
+ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
+                 cl::desc("Pop up a window to show dags before legalize"));
+#else
+static const bool ViewLegalizeDAGs = 0;
+#endif
+
 //===----------------------------------------------------------------------===//
 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
 /// hacks on it until the target machine can handle it.  This involves
@@ -37,7 +48,7 @@ using namespace llvm;
 /// will attempt merge setcc and brc instructions into brcc's.
 ///
 namespace {
-class SelectionDAGLegalize {
+class VISIBILITY_HIDDEN SelectionDAGLegalize {
   TargetLowering &TLI;
   SelectionDAG &DAG;
 
@@ -56,7 +67,7 @@ class SelectionDAGLegalize {
   enum LegalizeAction {
     Legal,      // The target natively supports this operation.
     Promote,    // This operation should be executed in a larger type.
-    Expand,     // Try to expand this to other ops, otherwise use a libcall.
+    Expand      // Try to expand this to other ops, otherwise use a libcall.
   };
   
   /// ValueTypeActions - This is a bitvector that contains two bits for each
@@ -74,12 +85,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 +133,66 @@ 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);
 
-  bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest);
+  /// 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);
+  
+  /// isShuffleLegal - Return true if a vector shuffle is legal with the
+  /// specified mask and type.  Targets can specify exactly which masks they
+  /// support and the code generator is tasked with not creating illegal masks.
+  ///
+  /// Note that this will also return true for shuffles that are promoted to a
+  /// different type.
+  ///
+  /// If this is a legal shuffle, this method returns the (possibly promoted)
+  /// build_vector Mask.  If it's not a legal shuffle, it returns null.
+  SDNode *isShuffleLegal(MVT::ValueType VT, SDOperand Mask) const;
+  
+  bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
+                                    std::set<SDNode*> &NodesLeadingTo);
 
   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 ExpandSCALAR_TO_VECTOR(SDNode *Node);
   SDOperand ExpandLegalINT_TO_FP(bool isSigned,
                                  SDOperand LegalOp,
                                  MVT::ValueType DestVT);
@@ -143,12 +208,62 @@ private:
   void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
                         SDOperand &Lo, SDOperand &Hi);
 
+  SDOperand LowerVEXTRACT_VECTOR_ELT(SDOperand Op);
+  SDOperand ExpandEXTRACT_VECTOR_ELT(SDOperand Op);
+  
   SDOperand getIntPtrConstant(uint64_t Val) {
     return DAG.getConstant(Val, TLI.getPointerTy());
   }
 };
 }
 
+/// isVectorShuffleLegal - Return true if a vector shuffle is legal with the
+/// specified mask and type.  Targets can specify exactly which masks they
+/// support and the code generator is tasked with not creating illegal masks.
+///
+/// Note that this will also return true for shuffles that are promoted to a
+/// different type.
+SDNode *SelectionDAGLegalize::isShuffleLegal(MVT::ValueType VT, 
+                                             SDOperand Mask) const {
+  switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, VT)) {
+  default: return 0;
+  case TargetLowering::Legal:
+  case TargetLowering::Custom:
+    break;
+  case TargetLowering::Promote: {
+    // If this is promoted to a different type, convert the shuffle mask and
+    // ask if it is legal in the promoted type!
+    MVT::ValueType NVT = TLI.getTypeToPromoteTo(ISD::VECTOR_SHUFFLE, VT);
+
+    // If we changed # elements, change the shuffle mask.
+    unsigned NumEltsGrowth =
+      MVT::getVectorNumElements(NVT) / MVT::getVectorNumElements(VT);
+    assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
+    if (NumEltsGrowth > 1) {
+      // Renumber the elements.
+      SmallVector<SDOperand, 8> Ops;
+      for (unsigned i = 0, e = Mask.getNumOperands(); i != e; ++i) {
+        SDOperand InOp = Mask.getOperand(i);
+        for (unsigned j = 0; j != NumEltsGrowth; ++j) {
+          if (InOp.getOpcode() == ISD::UNDEF)
+            Ops.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
+          else {
+            unsigned InEltNo = cast<ConstantSDNode>(InOp)->getValue();
+            Ops.push_back(DAG.getConstant(InEltNo*NumEltsGrowth+j, MVT::i32));
+          }
+        }
+      }
+      Mask = DAG.getNode(ISD::BUILD_VECTOR, NVT, &Ops[0], Ops.size());
+    }
+    VT = NVT;
+    break;
+  }
+  }
+  return TLI.isShuffleMaskLegal(Mask, VT) ? Mask.Val : 0;
+}
+
+/// 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 +335,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,9 +346,11 @@ void SelectionDAGLegalize::LegalizeDAG() {
   ExpandedNodes.clear();
   LegalizedNodes.clear();
   PromotedNodes.clear();
+  SplitNodes.clear();
+  PackedNodes.clear();
 
   // Remove dead nodes now.
-  DAG.RemoveDeadNodes(OldRoot.Val);
+  DAG.RemoveDeadNodes();
 }
 
 
@@ -306,10 +408,18 @@ static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
 /// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
 /// see if any uses can reach Dest.  If no dest operands can get to dest, 
 /// legalize them, legalize ourself, and return false, otherwise, return true.
-bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, 
-                                                        SDNode *Dest) {
+///
+/// Keep track of the nodes we fine that actually do lead to Dest in
+/// NodesLeadingTo.  This avoids retraversing them exponential number of times.
+///
+bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
+                                            std::set<SDNode*> &NodesLeadingTo) {
   if (N == Dest) return true;  // N certainly leads to Dest :)
   
+  // If we've already processed this node and it does lead to Dest, there is no
+  // need to reprocess it.
+  if (NodesLeadingTo.count(N)) return true;
+  
   // If the first result of this node has been already legalized, then it cannot
   // reach N.
   switch (getTypeAction(N->getValueType(0))) {
@@ -329,29 +439,59 @@ bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N,
   bool OperandsLeadToDest = false;
   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
     OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
-      LegalizeAllNodesNotLeadingTo(N->getOperand(i).Val, Dest);
+      LegalizeAllNodesNotLeadingTo(N->getOperand(i).Val, Dest, NodesLeadingTo);
 
-  if (OperandsLeadToDest) return true;
+  if (OperandsLeadToDest) {
+    NodesLeadingTo.insert(N);
+    return true;
+  }
 
   // Okay, this node looks safe, legalize it and return false.
-  switch (getTypeAction(N->getValueType(0))) {
-  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;
-  }
-  }
+  HandleOp(SDOperand(N, 0));
   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 +501,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];
       }
   }
@@ -393,9 +524,9 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
   case ISD::Register:
   case ISD::BasicBlock:
   case ISD::TargetFrameIndex:
+  case ISD::TargetJumpTable:
   case ISD::TargetConstant:
   case ISD::TargetConstantFP:
-  case ISD::TargetConstantVec:
   case ISD::TargetConstantPool:
   case ISD::TargetGlobalAddress:
   case ISD::TargetExternalSymbol:
@@ -411,32 +542,37 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
       // If this is a target node, legalize it by legalizing the operands then
       // passing it through.
-      std::vector<SDOperand> Ops;
-      bool Changed = false;
-      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
+      SmallVector<SDOperand, 8> Ops;
+      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
         Ops.push_back(LegalizeOp(Node->getOperand(i)));
-        Changed = Changed || Node->getOperand(i) != Ops.back();
-      }
-      if (Changed)
-        if (Node->getNumValues() == 1)
-          Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
-        else {
-          std::vector<MVT::ValueType> VTs(Node->value_begin(),
-                                          Node->value_end());
-          Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
-        }
+
+      Result = DAG.UpdateNodeOperands(Result.getValue(0), &Ops[0], Ops.size());
 
       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
         AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
       return Result.getValue(Op.ResNo);
     }
     // Otherwise this is an unhandled builtin node.  splat.
+#ifndef NDEBUG
     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
+#endif
     assert(0 && "Do not know how to legalize this operator!");
     abort();
+  case ISD::JumpTableRelocBase:
+    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
+    case TargetLowering::Custom:
+      Tmp1 = TLI.LowerOperation(Op, DAG);
+      if (Tmp1.Val) Result = Tmp1;
+      break;
+    default:
+      Result = LegalizeOp(Node->getOperand(0));
+      break;
+    }
+    break;
   case ISD::GlobalAddress:
   case ISD::ExternalSymbol:
-  case ISD::ConstantPool:           // Nothing to do.
+  case ISD::ConstantPool:
+  case ISD::JumpTable: // Nothing to do.
     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
     default: assert(0 && "This action is not supported yet!");
     case TargetLowering::Custom:
@@ -493,6 +629,34 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     }
     break;
   }
+    
+  case ISD::INTRINSIC_W_CHAIN:
+  case ISD::INTRINSIC_WO_CHAIN:
+  case ISD::INTRINSIC_VOID: {
+    SmallVector<SDOperand, 8> Ops;
+    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
+      Ops.push_back(LegalizeOp(Node->getOperand(i)));
+    Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
+    
+    // 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!");
@@ -513,7 +677,7 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
           cast<StringSDNode>(Node->getOperand(4))->getValue();
         unsigned SrcFile = DebugInfo->RecordSource(DirName, FName);
 
-        std::vector<SDOperand> Ops;
+        SmallVector<SDOperand, 8> Ops;
         Ops.push_back(Tmp1);  // chain
         SDOperand LineOp = Node->getOperand(1);
         SDOperand ColOp = Node->getOperand(2);
@@ -522,13 +686,13 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
           Ops.push_back(LineOp);  // line #
           Ops.push_back(ColOp);  // col #
           Ops.push_back(DAG.getConstant(SrcFile, MVT::i32));  // source file id
-          Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, Ops);
+          Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, &Ops[0], Ops.size());
         } else {
           unsigned Line = cast<ConstantSDNode>(LineOp)->getValue();
           unsigned Col = cast<ConstantSDNode>(ColOp)->getValue();
           unsigned ID = DebugInfo->RecordLabel(Line, Col, SrcFile);
           Ops.push_back(DAG.getConstant(ID, MVT::i32));
-          Result = DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops);
+          Result = DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,&Ops[0],Ops.size());
         }
       } else {
         Result = Tmp1;  // chain
@@ -538,7 +702,7 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     case TargetLowering::Legal:
       if (Tmp1 != Node->getOperand(0) ||
           getTypeAction(Node->getOperand(1).getValueType()) == Promote) {
-        std::vector<SDOperand> Ops;
+        SmallVector<SDOperand, 8> Ops;
         Ops.push_back(Tmp1);
         if (getTypeAction(Node->getOperand(1).getValueType()) == Legal) {
           Ops.push_back(Node->getOperand(1));  // line # must be legal.
@@ -550,7 +714,7 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
         }
         Ops.push_back(Node->getOperand(3));  // filename must be legal.
         Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
-        Result = DAG.UpdateNodeOperands(Result, Ops);
+        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
       }
       break;
     }
@@ -635,7 +799,7 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
           // Only do this if the target has a native EXTLOAD instruction from
           // f32.
-          TLI.isOperationLegal(ISD::EXTLOAD, MVT::f32)) {
+          TLI.isLoadXLegal(ISD::EXTLOAD, MVT::f32)) {
         LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
         VT = MVT::f32;
         Extend = true;
@@ -652,8 +816,45 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     }
     break;
   }
-  case ISD::ConstantVec:
-    switch (TLI.getOperationAction(ISD::ConstantVec, Node->getValueType(0))) {
+  case ISD::TokenFactor:
+    if (Node->getNumOperands() == 2) {
+      Tmp1 = LegalizeOp(Node->getOperand(0));
+      Tmp2 = LegalizeOp(Node->getOperand(1));
+      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
+    } else if (Node->getNumOperands() == 3) {
+      Tmp1 = LegalizeOp(Node->getOperand(0));
+      Tmp2 = LegalizeOp(Node->getOperand(1));
+      Tmp3 = LegalizeOp(Node->getOperand(2));
+      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
+    } else {
+      SmallVector<SDOperand, 8> Ops;
+      // Legalize the operands.
+      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
+        Ops.push_back(LegalizeOp(Node->getOperand(i)));
+      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
+    }
+    break;
+    
+  case ISD::FORMAL_ARGUMENTS:
+  case ISD::CALL:
+    // The only option for this is to custom lower it.
+    Tmp3 = TLI.LowerOperation(Result.getValue(0), DAG);
+    assert(Tmp3.Val && "Target didn't custom lower this node!");
+    assert(Tmp3.Val->getNumValues() == Result.Val->getNumValues() &&
+           "Lowering call/formal_arguments produced unexpected # results!");
+    
+    // Since CALL/FORMAL_ARGUMENTS nodes produce multiple values, make sure to
+    // remember that we legalized all of them, so it doesn't get relegalized.
+    for (unsigned i = 0, e = Tmp3.Val->getNumValues(); i != e; ++i) {
+      Tmp1 = LegalizeOp(Tmp3.getValue(i));
+      if (Op.ResNo == i)
+        Tmp2 = Tmp1;
+      AddLegalizedOperand(SDOperand(Node, i), Tmp1);
+    }
+    return Tmp2;
+        
+  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);
@@ -663,59 +864,215 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       }
       // 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));
+      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 insert index is a constant, codegen this as a scalar_to_vector,
+      // then a shuffle that inserts it into the right position in the vector.
+      if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Tmp3)) {
+        SDOperand ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, 
+                                      Tmp1.getValueType(), Tmp2);
+        
+        unsigned NumElts = MVT::getVectorNumElements(Tmp1.getValueType());
+        MVT::ValueType ShufMaskVT = MVT::getIntVectorWithNumElements(NumElts);
+        MVT::ValueType ShufMaskEltVT = MVT::getVectorBaseType(ShufMaskVT);
+        
+        // We generate a shuffle of InVec and ScVec, so the shuffle mask should
+        // be 0,1,2,3,4,5... with the appropriate element replaced with elt 0 of
+        // the RHS.
+        SmallVector<SDOperand, 8> ShufOps;
+        for (unsigned i = 0; i != NumElts; ++i) {
+          if (i != InsertPos->getValue())
+            ShufOps.push_back(DAG.getConstant(i, ShufMaskEltVT));
+          else
+            ShufOps.push_back(DAG.getConstant(NumElts, ShufMaskEltVT));
         }
-      } 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));
+        SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMaskVT,
+                                         &ShufOps[0], ShufOps.size());
+        
+        Result = DAG.getNode(ISD::VECTOR_SHUFFLE, Tmp1.getValueType(),
+                             Tmp1, ScVec, ShufMask);
+        Result = LegalizeOp(Result);
+        break;
+      }
+      
+      // 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.
+      MVT::ValueType VT    = Tmp1.getValueType();
+      MVT::ValueType EltVT = Tmp2.getValueType();
+      MVT::ValueType IdxVT = Tmp3.getValueType();
+      MVT::ValueType PtrVT = TLI.getPointerTy();
+      SDOperand StackPtr = CreateStackTemporary(VT);
+      // 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.
+      unsigned CastOpc = (IdxVT > PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
+      Tmp3 = DAG.getNode(CastOpc, PtrVT, Tmp3);
+      // Add the offset to the index.
+      unsigned EltSize = MVT::getSizeInBits(EltVT)/8;
+      Tmp3 = DAG.getNode(ISD::MUL, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
+      SDOperand StackPtr2 = DAG.getNode(ISD::ADD, IdxVT, 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(VT, Ch, StackPtr, DAG.getSrcValue(NULL));
+      break;
+    }
+    }
+    break;
+  case ISD::SCALAR_TO_VECTOR:
+    if (!TLI.isTypeLegal(Node->getOperand(0).getValueType())) {
+      Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
+      break;
+    }
+    
+    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:
+      Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
+      break;
+    }
+    break;
+  case ISD::VECTOR_SHUFFLE:
+    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.
+    switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE,Result.getValueType())) {
+    default: assert(0 && "Unknown operation action!");
+    case TargetLowering::Legal:
+      assert(isShuffleLegal(Result.getValueType(), Node->getOperand(2)) &&
+             "vector shuffle should not be created if not legal!");
+      break;
+    case TargetLowering::Custom:
+      Tmp3 = TLI.LowerOperation(Result, DAG);
+      if (Tmp3.Val) {
+        Result = Tmp3;
+        break;
+      }
+      // FALLTHROUGH
+    case TargetLowering::Expand: {
+      MVT::ValueType VT = Node->getValueType(0);
+      MVT::ValueType EltVT = MVT::getVectorBaseType(VT);
+      MVT::ValueType PtrVT = TLI.getPointerTy();
+      SDOperand Mask = Node->getOperand(2);
+      unsigned NumElems = Mask.getNumOperands();
+      SmallVector<SDOperand,8> Ops;
+      for (unsigned i = 0; i != NumElems; ++i) {
+        SDOperand Arg = Mask.getOperand(i);
+        if (Arg.getOpcode() == ISD::UNDEF) {
+          Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
+        } else {
+          assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
+          unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
+          if (Idx < NumElems)
+            Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1,
+                                      DAG.getConstant(Idx, PtrVT)));
+          else
+            Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2,
+                                      DAG.getConstant(Idx - NumElems, PtrVT)));
         }
       }
-      Constant *CP = ConstantPacked::get(CV);
-      SDOperand CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
-      Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
-                           DAG.getSrcValue(NULL));
+      Result = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
       break;
     }
+    case TargetLowering::Promote: {
+      // Change base type to a different vector type.
+      MVT::ValueType OVT = Node->getValueType(0);
+      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
+
+      // Cast the two input vectors.
+      Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
+      Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
+      
+      // Convert the shuffle mask to the right # elements.
+      Tmp3 = SDOperand(isShuffleLegal(OVT, Node->getOperand(2)), 0);
+      assert(Tmp3.Val && "Shuffle not legal?");
+      Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NVT, Tmp1, Tmp2, Tmp3);
+      Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
+      break;
+    }
+    }
     break;
-  case ISD::TokenFactor:
-    if (Node->getNumOperands() == 2) {
-      Tmp1 = LegalizeOp(Node->getOperand(0));
-      Tmp2 = LegalizeOp(Node->getOperand(1));
-      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
-    } else if (Node->getNumOperands() == 3) {
-      Tmp1 = LegalizeOp(Node->getOperand(0));
-      Tmp2 = LegalizeOp(Node->getOperand(1));
-      Tmp3 = LegalizeOp(Node->getOperand(2));
-      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
-    } else {
-      std::vector<SDOperand> Ops;
-      // Legalize the operands.
-      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
-        Ops.push_back(LegalizeOp(Node->getOperand(i)));
-      Result = DAG.UpdateNodeOperands(Result, Ops);
+  
+  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:
+      Result = ExpandEXTRACT_VECTOR_ELT(Result);
+      break;
     }
     break;
 
+  case ISD::VEXTRACT_VECTOR_ELT: 
+    Result = LegalizeOp(LowerVEXTRACT_VECTOR_ELT(Op));
+    break;
+    
   case ISD::CALLSEQ_START: {
     SDNode *CallEnd = FindCallEndFromCallStart(Node);
     
     // Recursively Legalize all of the inputs of the call end that do not lead
     // to this call start.  This ensures that any libcalls that need be inserted
     // are inserted *before* the CALLSEQ_START.
+    {std::set<SDNode*> NodesLeadingTo;
     for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
-      LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).Val, Node);
+      LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).Val, Node,
+                                   NodesLeadingTo);
+    }
 
     // Now that we legalized all of the inputs (which may have inserted
     // libcalls) create the new CALLSEQ_START node.
@@ -723,14 +1080,16 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
 
     // Merge in the last call, to ensure that this call start after the last
     // call ended.
-    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
-    Tmp1 = LegalizeOp(Tmp1);
+    if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
+      Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
+      Tmp1 = LegalizeOp(Tmp1);
+    }
       
     // Do not try to legalize the target-specific arguments (#1+).
     if (Tmp1 != Node->getOperand(0)) {
-      std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
+      SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
       Ops[0] = Tmp1;
-      Result = DAG.UpdateNodeOperands(Result, Ops);
+      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
     }
     
     // Remember that the CALLSEQ_START is legalized.
@@ -771,18 +1130,18 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     // an optional flag input.
     if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
       if (Tmp1 != Node->getOperand(0)) {
-        std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
+        SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
         Ops[0] = Tmp1;
-        Result = DAG.UpdateNodeOperands(Result, Ops);
+        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
       }
     } else {
       Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
       if (Tmp1 != Node->getOperand(0) ||
           Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
-        std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
+        SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
         Ops[0] = Tmp1;
         Ops.back() = Tmp2;
-        Result = DAG.UpdateNodeOperands(Result, Ops);
+        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
       }
     }
     assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
@@ -834,25 +1193,42 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
     return Op.ResNo ? Tmp2 : Tmp1;
   }
-  case ISD::INLINEASM:
-    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize Chain.
-    Tmp2 = Node->getOperand(Node->getNumOperands()-1);
-    if (Tmp2.getValueType() == MVT::Flag)     // Legalize Flag if it exists.
-      Tmp2 = Tmp3 = SDOperand(0, 0);
-    else
-      Tmp3 = LegalizeOp(Tmp2);
-    
-    if (Tmp1 != Node->getOperand(0) || Tmp2 != Tmp3) {
-      std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
-      Ops[0] = Tmp1;
-      if (Tmp3.Val) Ops.back() = Tmp3;
-      Result = DAG.UpdateNodeOperands(Result, Ops);
+  case ISD::INLINEASM: {
+    SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
+    bool Changed = false;
+    // Legalize all of the operands of the inline asm, in case they are nodes
+    // that need to be expanded or something.  Note we skip the asm string and
+    // all of the TargetConstant flags.
+    SDOperand Op = LegalizeOp(Ops[0]);
+    Changed = Op != Ops[0];
+    Ops[0] = Op;
+
+    bool HasInFlag = Ops.back().getValueType() == MVT::Flag;
+    for (unsigned i = 2, e = Ops.size()-HasInFlag; i < e; ) {
+      unsigned NumVals = cast<ConstantSDNode>(Ops[i])->getValue() >> 3;
+      for (++i; NumVals; ++i, --NumVals) {
+        SDOperand Op = LegalizeOp(Ops[i]);
+        if (Op != Ops[i]) {
+          Changed = true;
+          Ops[i] = Op;
+        }
+      }
     }
+
+    if (HasInFlag) {
+      Op = LegalizeOp(Ops.back());
+      Changed |= Op != Ops.back();
+      Ops.back() = Op;
+    }
+    
+    if (Changed)
+      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
       
     // INLINE asm returns a chain and flag, make sure to add both to the map.
     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
     return Result.getValue(Op.ResNo);
+  }
   case ISD::BR:
     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
     // Ensure that libcalls are emitted before a branch.
@@ -862,7 +1238,21 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     
     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
     break;
-
+  case ISD::BRIND:
+    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();
+    
+    switch (getTypeAction(Node->getOperand(1).getValueType())) {
+    default: assert(0 && "Indirect target must be legal type (pointer)!");
+    case Legal:
+      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
+      break;
+    }
+    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
+    break;
   case ISD::BRCOND:
     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
     // Ensure that libcalls are emitted before a return.
@@ -945,139 +1335,56 @@ 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.
 
     MVT::ValueType VT = Node->getValueType(0);
     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
-    Tmp2 = Result.getValue(0);
-    Tmp3 = Result.getValue(1);
+    Tmp3 = Result.getValue(0);
+    Tmp4 = Result.getValue(1);
     
     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
     default: assert(0 && "This action is not supported yet!");
     case TargetLowering::Legal: break;
     case TargetLowering::Custom:
-      Tmp1 = TLI.LowerOperation(Tmp2, DAG);
+      Tmp1 = TLI.LowerOperation(Tmp3, DAG);
       if (Tmp1.Val) {
-        Tmp2 = LegalizeOp(Tmp1);
-        Tmp3 = LegalizeOp(Tmp1.getValue(1));
+        Tmp3 = LegalizeOp(Tmp1);
+        Tmp4 = LegalizeOp(Tmp1.getValue(1));
       }
       break;
+    case TargetLowering::Promote: {
+      // Only promote a load of vector type to another.
+      assert(MVT::isVector(VT) && "Cannot promote this load!");
+      // Change base type to a different vector type.
+      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
+
+      Tmp1 = DAG.getLoad(NVT, Tmp1, Tmp2, Node->getOperand(2));
+      Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp1));
+      Tmp4 = LegalizeOp(Tmp1.getValue(1));
+      break;
+    }
     }
     // Since loads produce two values, make sure to remember that we 
     // legalized both of them.
-    AddLegalizedOperand(SDOperand(Node, 0), Tmp2);
-    AddLegalizedOperand(SDOperand(Node, 1), Tmp3);
-    return Op.ResNo ? Tmp3 : Tmp2;
+    AddLegalizedOperand(SDOperand(Node, 0), Tmp3);
+    AddLegalizedOperand(SDOperand(Node, 1), Tmp4);
+    return Op.ResNo ? Tmp4 : Tmp3;
   }
-  case ISD::EXTLOAD:
-  case ISD::SEXTLOAD:
-  case ISD::ZEXTLOAD: {
+  case ISD::LOADX: {
     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
 
     MVT::ValueType SrcVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
-    switch (TLI.getOperationAction(Node->getOpcode(), SrcVT)) {
+    unsigned LType = cast<ConstantSDNode>(Node->getOperand(4))->getValue();
+    switch (TLI.getLoadXAction(LType, SrcVT)) {
     default: assert(0 && "This action is not supported yet!");
     case TargetLowering::Promote:
-      assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
+      assert(SrcVT == MVT::i1 && "Can only promote LOADX from i1 -> i8!");
       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
-                                      DAG.getValueType(MVT::i8));
+                                      DAG.getValueType(MVT::i8),
+                                      Node->getOperand(4));
       Tmp1 = Result.getValue(0);
       Tmp2 = Result.getValue(1);
       break;
@@ -1086,12 +1393,12 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       // FALLTHROUGH
     case TargetLowering::Legal:
       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
-                                      Node->getOperand(3));
+                                      Node->getOperand(3), Node->getOperand(4));
       Tmp1 = Result.getValue(0);
       Tmp2 = Result.getValue(1);
       
       if (isCustom) {
-        Tmp3 = TLI.LowerOperation(Tmp3, DAG);
+        Tmp3 = TLI.LowerOperation(Result, DAG);
         if (Tmp3.Val) {
           Tmp1 = LegalizeOp(Tmp3);
           Tmp2 = LegalizeOp(Tmp3.getValue(1));
@@ -1107,14 +1414,13 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
         Tmp2 = LegalizeOp(Load.getValue(1));
         break;
       }
-      assert(Node->getOpcode() != ISD::EXTLOAD &&
-             "EXTLOAD should always be supported!");
+      assert(LType != ISD::EXTLOAD && "EXTLOAD should always be supported!");
       // Turn the unsupported load into an EXTLOAD followed by an explicit
       // zero/sign extend inreg.
       Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
                               Tmp1, Tmp2, Node->getOperand(2), SrcVT);
       SDOperand ValRes;
-      if (Node->getOpcode() == ISD::SEXTLOAD)
+      if (LType == ISD::SEXTLOAD)
         ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
                              Result, DAG.getValueType(SrcVT));
       else
@@ -1192,23 +1498,58 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
     Tmp1 = LegalizeOp(Tmp1);
     LastCALLSEQ_END = DAG.getEntryNode();
-    
+      
     switch (Node->getNumOperands()) {
-    case 2:  // ret val
-      switch (getTypeAction(Node->getOperand(1).getValueType())) {
+    case 3:  // ret val
+      Tmp2 = Node->getOperand(1);
+      Tmp3 = Node->getOperand(2);  // Signness
+      switch (getTypeAction(Tmp2.getValueType())) {
       case Legal:
-        Tmp2 = LegalizeOp(Node->getOperand(1));
-        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
+        Result = DAG.UpdateNodeOperands(Result, Tmp1, LegalizeOp(Tmp2), Tmp3);
         break;
-      case Expand: {
-        SDOperand Lo, Hi;
-        ExpandOp(Node->getOperand(1), Lo, Hi);
-        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
+      case Expand:
+        if (Tmp2.getValueType() != MVT::Vector) {
+          SDOperand Lo, Hi;
+          ExpandOp(Tmp2, Lo, Hi);
+          Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3, Hi, Tmp3);
+          Result = LegalizeOp(Result);
+        } else {
+          SDNode *InVal = Tmp2.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 return of the packed type.
+            Tmp2 = PackVectorOp(Tmp2, TVT);
+            Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
+          } else if (NumElems == 1) {
+            // Turn this into a return of the scalar type.
+            Tmp2 = PackVectorOp(Tmp2, EVT);
+            Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
+            
+            // FIXME: Returns of gcc generic vectors smaller than a legal type
+            // should be returned in integer registers!
+            
+            // The scalarized value type may not be legal, e.g. it might require
+            // promotion or expansion.  Relegalize the return.
+            Result = LegalizeOp(Result);
+          } else {
+            // FIXME: Returns of gcc generic vectors larger than a legal vector
+            // type should be returned by reference!
+            SDOperand Lo, Hi;
+            SplitVectorOp(Tmp2, Lo, Hi);
+            Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3, Hi, Tmp3);
+            Result = LegalizeOp(Result);
+          }
+        }
         break;
-      }
       case Promote:
         Tmp2 = PromoteOp(Node->getOperand(1));
-        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
+        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
         Result = LegalizeOp(Result);
         break;
       }
@@ -1217,18 +1558,23 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       Result = DAG.UpdateNodeOperands(Result, Tmp1);
       break;
     default: { // ret <values>
-      std::vector<SDOperand> NewValues;
+      SmallVector<SDOperand, 8> NewValues;
       NewValues.push_back(Tmp1);
-      for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
+      for (unsigned i = 1, e = Node->getNumOperands(); i < e; i += 2)
         switch (getTypeAction(Node->getOperand(i).getValueType())) {
         case Legal:
           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
+          NewValues.push_back(Node->getOperand(i+1));
           break;
         case Expand: {
           SDOperand Lo, Hi;
+          assert(Node->getOperand(i).getValueType() != MVT::Vector &&
+                 "FIXME: TODO: implement returning non-legal vector types!");
           ExpandOp(Node->getOperand(i), Lo, Hi);
           NewValues.push_back(Lo);
+          NewValues.push_back(Node->getOperand(i+1));
           NewValues.push_back(Hi);
+          NewValues.push_back(Node->getOperand(i+1));
           break;
         }
         case Promote:
@@ -1236,9 +1582,10 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
         }
           
       if (NewValues.size() == Node->getNumOperands())
-        Result = DAG.UpdateNodeOperands(Result, NewValues);
+        Result = DAG.UpdateNodeOperands(Result, &NewValues[0],NewValues.size());
       else
-        Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
+        Result = DAG.getNode(ISD::RET, MVT::Other,
+                             &NewValues[0], NewValues.size());
       break;
     }
     }
@@ -1287,6 +1634,13 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
         Tmp1 = TLI.LowerOperation(Result, DAG);
         if (Tmp1.Val) Result = Tmp1;
         break;
+      case TargetLowering::Promote:
+        assert(MVT::isVector(VT) && "Unknown legal promote case!");
+        Tmp3 = DAG.getNode(ISD::BIT_CONVERT, 
+                           TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
+        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
+                                        Node->getOperand(3));
+        break;
       }
       break;
     }
@@ -1299,25 +1653,51 @@ 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));
+          Result = LegalizeOp(Result);
+          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));
+          // The scalarized value type may not be legal, e.g. it might require
+          // promotion or expansion.  Relegalize the scalar store.
+          Result = LegalizeOp(Result);
+          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()) &&
@@ -1484,7 +1864,10 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       MVT::ValueType NVT =
         TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
       unsigned ExtOp, TruncOp;
-      if (MVT::isInteger(Tmp2.getValueType())) {
+      if (MVT::isVector(Tmp2.getValueType())) {
+        ExtOp   = ISD::BIT_CONVERT;
+        TruncOp = ISD::BIT_CONVERT;
+      } else if (MVT::isInteger(Tmp2.getValueType())) {
         ExtOp   = ISD::ANY_EXTEND;
         TruncOp = ISD::TRUNCATE;
       } else {
@@ -1661,7 +2044,7 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       // Otherwise, the target does not support this operation.  Lower the
       // operation to an explicit libcall as appropriate.
       MVT::ValueType IntPtr = TLI.getPointerTy();
-      const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
+      const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
       std::vector<std::pair<SDOperand, const Type*> > Args;
 
       const char *FnName = 0;
@@ -1700,14 +2083,14 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
   case ISD::SHL_PARTS:
   case ISD::SRA_PARTS:
   case ISD::SRL_PARTS: {
-    std::vector<SDOperand> Ops;
+    SmallVector<SDOperand, 8> Ops;
     bool Changed = false;
     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
       Ops.push_back(LegalizeOp(Node->getOperand(i)));
       Changed |= Ops.back() != Node->getOperand(i);
     }
     if (Changed)
-      Result = DAG.UpdateNodeOperands(Result, Ops);
+      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
 
     switch (TLI.getOperationAction(Node->getOpcode(),
                                    Node->getValueType(0))) {
@@ -1768,12 +2151,62 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
       
     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
-    default: assert(0 && "Operation not supported");
+    default: assert(0 && "BinOp legalize operation not supported");
     case TargetLowering::Legal: break;
     case TargetLowering::Custom:
       Tmp1 = TLI.LowerOperation(Result, DAG);
       if (Tmp1.Val) Result = Tmp1;
       break;
+    case TargetLowering::Expand: {
+      if (Node->getValueType(0) == MVT::i32) {
+        switch (Node->getOpcode()) {
+        default:  assert(0 && "Do not know how to expand this integer BinOp!");
+        case ISD::UDIV:
+        case ISD::SDIV:
+          const char *FnName = Node->getOpcode() == ISD::UDIV
+            ? "__udivsi3" : "__divsi3";
+          SDOperand Dummy;
+          Result = ExpandLibCall(FnName, Node, Dummy);
+        };
+        break;
+      }
+
+      assert(MVT::isVector(Node->getValueType(0)) &&
+             "Cannot expand this binary operator!");
+      // Expand the operation into a bunch of nasty scalar code.
+      SmallVector<SDOperand, 8> Ops;
+      MVT::ValueType EltVT = MVT::getVectorBaseType(Node->getValueType(0));
+      MVT::ValueType PtrVT = TLI.getPointerTy();
+      for (unsigned i = 0, e = MVT::getVectorNumElements(Node->getValueType(0));
+           i != e; ++i) {
+        SDOperand Idx = DAG.getConstant(i, PtrVT);
+        SDOperand LHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1, Idx);
+        SDOperand RHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2, Idx);
+        Ops.push_back(DAG.getNode(Node->getOpcode(), EltVT, LHS, RHS));
+      }
+      Result = DAG.getNode(ISD::BUILD_VECTOR, Node->getValueType(0), 
+                           &Ops[0], Ops.size());
+      break;
+    }
+    case TargetLowering::Promote: {
+      switch (Node->getOpcode()) {
+      default:  assert(0 && "Do not know how to promote this BinOp!");
+      case ISD::AND:
+      case ISD::OR:
+      case ISD::XOR: {
+        MVT::ValueType OVT = Node->getValueType(0);
+        MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
+        assert(MVT::isVector(OVT) && "Cannot promote this BinOp!");
+        // Bit convert each of the values to the new type.
+        Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
+        Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
+        Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
+        // Bit convert the result back the original type.
+        Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
+        break;
+      }
+      }
+    }
     }
     break;
     
@@ -1851,7 +2284,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:
@@ -1864,7 +2296,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);
@@ -1910,13 +2341,23 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       }
       break;
     case TargetLowering::Expand:
+      unsigned DivOpc= (Node->getOpcode() == ISD::UREM) ? ISD::UDIV : ISD::SDIV;
       if (MVT::isInteger(Node->getValueType(0))) {
-        // X % Y -> X-X/Y*Y
-        MVT::ValueType VT = Node->getValueType(0);
-        unsigned Opc = Node->getOpcode() == ISD::UREM ? ISD::UDIV : ISD::SDIV;
-        Result = DAG.getNode(Opc, VT, Tmp1, Tmp2);
-        Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
-        Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
+        if (TLI.getOperationAction(DivOpc, Node->getValueType(0)) ==
+            TargetLowering::Legal) {
+          // X % Y -> X-X/Y*Y
+          MVT::ValueType VT = Node->getValueType(0);
+          Result = DAG.getNode(DivOpc, VT, Tmp1, Tmp2);
+          Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
+          Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
+        } else {
+          assert(Node->getValueType(0) == MVT::i32 &&
+                 "Cannot expand this binary operator!");
+          const char *FnName = Node->getOpcode() == ISD::UREM
+            ? "__umodsi3" : "__modsi3";
+          SDOperand Dummy;
+          Result = ExpandLibCall(FnName, Node, Dummy);
+        }
       } else {
         // Floating point mod -> fmod libcall.
         const char *FnName = Node->getValueType(0) == MVT::f32 ? "fmodf":"fmod";
@@ -2173,7 +2614,14 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
       break;
     }
     break;
-    
+  case ISD::FPOWI: {
+    // We always lower FPOWI into a libcall.  No target support it yet.
+    const char *FnName = Node->getValueType(0) == MVT::f32
+                            ? "__powisf2" : "__powidf2";
+    SDOperand Dummy;
+    Result = ExpandLibCall(FnName, Node, Dummy);
+    break;
+  }
   case ISD::BIT_CONVERT:
     if (!isTypeLegal(Node->getOperand(0).getValueType())) {
       Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
@@ -2191,6 +2639,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: {
@@ -2392,8 +2870,8 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
         // slots and always reusing the same one.  We currently always create
         // new ones, as reuse may inhibit scheduling.
         const Type *Ty = MVT::getTypeForValueType(ExtraVT);
-        unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
-        unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
+        unsigned TySize = (unsigned)TLI.getTargetData()->getTypeSize(Ty);
+        unsigned Align  = TLI.getTargetData()->getTypeAlignment(Ty);
         MachineFunction &MF = DAG.getMachineFunction();
         int SSFI =
           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
@@ -2413,6 +2891,9 @@ SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
   }
   }
   
+  assert(Result.getValueType() == Op.getValueType() &&
+         "Bad legalization!");
+  
   // Make sure that the generated code is itself legal.
   if (Result != Op)
     Result = LegalizeOp(Result);
@@ -2446,7 +2927,9 @@ SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
   case ISD::CopyFromReg:
     assert(0 && "CopyFromReg must be legal!");
   default:
+#ifndef NDEBUG
     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
+#endif
     assert(0 && "Do not know how to promote this operator!");
     abort();
   case ISD::UNDEF:
@@ -2469,7 +2952,7 @@ SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
     Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),Node->getOperand(0),
                          Node->getOperand(1), Node->getOperand(2));
     break;
-
+    
   case ISD::TRUNCATE:
     switch (getTypeAction(Node->getOperand(0).getValueType())) {
     case Legal:
@@ -2671,8 +3154,26 @@ SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
   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));
+    switch (getTypeAction(Node->getOperand(0).getValueType())) {
+      case Legal:
+        Tmp1 = LegalizeOp(Node->getOperand(0));
+        break;
+      case Promote:
+        Tmp1 = PromoteOp(Node->getOperand(0));
+        break;
+      case Expand:
+        assert(0 && "not implemented");
+    }
+    switch (getTypeAction(Node->getOperand(1).getValueType())) {
+      case Legal:
+        Tmp2 = LegalizeOp(Node->getOperand(1));
+        break;
+      case Promote:
+        Tmp2 = PromoteOp(Node->getOperand(1));
+        break;
+      case Expand:
+        assert(0 && "not implemented");
+    }
     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
     
     // Perform FP_ROUND: this is probably overly pessimistic.
@@ -2740,12 +3241,12 @@ SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
     // Remember that we legalized the chain.
     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
     break;
-  case ISD::SEXTLOAD:
-  case ISD::ZEXTLOAD:
-  case ISD::EXTLOAD:
-    Result = DAG.getExtLoad(Node->getOpcode(), NVT, Node->getOperand(0),
-                            Node->getOperand(1), Node->getOperand(2),
-                            cast<VTSDNode>(Node->getOperand(3))->getVT());
+  case ISD::LOADX:
+    Result =
+      DAG.getExtLoad((ISD::LoadExtType)Node->getConstantOperandVal(4),
+                     NVT, Node->getOperand(0), Node->getOperand(1),
+                     Node->getOperand(2),
+                     cast<VTSDNode>(Node->getOperand(3))->getVT());
     // Remember that we legalized the chain.
     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
     break;
@@ -2794,6 +3295,12 @@ SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
       break;
     }
     break;
+  case ISD::VEXTRACT_VECTOR_ELT:
+    Result = PromoteOp(LowerVEXTRACT_VECTOR_ELT(Op));
+    break;
+  case ISD::EXTRACT_VECTOR_ELT:
+    Result = PromoteOp(ExpandEXTRACT_VECTOR_ELT(Op));
+    break;
   }
 
   assert(Result.Val && "Didn't set a result!");
@@ -2806,6 +3313,74 @@ SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
   return Result;
 }
 
+/// LowerVEXTRACT_VECTOR_ELT - Lower a VEXTRACT_VECTOR_ELT operation into a
+/// EXTRACT_VECTOR_ELT operation, to memory operations, or to scalar code based
+/// on the vector type.  The return type of this matches the element type of the
+/// vector, which may not be legal for the target.
+SDOperand SelectionDAGLegalize::LowerVEXTRACT_VECTOR_ELT(SDOperand Op) {
+  // 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.
+  SDOperand Vec = Op.getOperand(0);
+  SDOperand Idx = LegalizeOp(Op.getOperand(1));
+  
+  SDNode *InVal = Vec.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.
+    Vec = PackVectorOp(Vec, TVT);
+    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Op.getValueType(), Vec, Idx);
+  } else if (NumElems == 1) {
+    // This must be an access of the only element.  Return it.
+    return PackVectorOp(Vec, EVT);
+  } else if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
+    SDOperand Lo, Hi;
+    SplitVectorOp(Vec, Lo, Hi);
+    if (CIdx->getValue() < NumElems/2) {
+      Vec = Lo;
+    } else {
+      Vec = Hi;
+      Idx = DAG.getConstant(CIdx->getValue() - NumElems/2, Idx.getValueType());
+    }
+    
+    // It's now an extract from the appropriate high or low part.  Recurse.
+    Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
+    return LowerVEXTRACT_VECTOR_ELT(Op);
+  } else {
+    // Variable index case for extract element.
+    // FIXME: IMPLEMENT STORE/LOAD lowering.  Need alignment of stack slot!!
+    assert(0 && "unimp!");
+    return SDOperand();
+  }
+}
+
+/// ExpandEXTRACT_VECTOR_ELT - Expand an EXTRACT_VECTOR_ELT operation into
+/// memory traffic.
+SDOperand SelectionDAGLegalize::ExpandEXTRACT_VECTOR_ELT(SDOperand Op) {
+  SDOperand Vector = Op.getOperand(0);
+  SDOperand Idx    = Op.getOperand(1);
+  
+  // 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(Vector.getValueType());
+  SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
+                             Vector, StackPtr, DAG.getSrcValue(NULL));
+  
+  // Add the offset to the index.
+  unsigned EltSize = MVT::getSizeInBits(Op.getValueType())/8;
+  Idx = DAG.getNode(ISD::MUL, Idx.getValueType(), Idx,
+                    DAG.getConstant(EltSize, Idx.getValueType()));
+  StackPtr = DAG.getNode(ISD::ADD, Idx.getValueType(), Idx, StackPtr);
+  
+  return DAG.getLoad(Op.getValueType(), Ch, StackPtr, DAG.getSrcValue(NULL));
+}
+
+
 /// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
 /// with condition CC on the current target.  This usually involves legalizing
 /// or promoting the arguments.  In the case where LHS and RHS must be expanded,
@@ -2924,26 +3499,203 @@ void SelectionDAGLegalize::LegalizeSetCCOperands(SDOperand &LHS,
       Tmp2 = SDOperand();
     }
   }
-  LHS = Tmp1;
-  RHS = Tmp2;
+  LHS = Tmp1;
+  RHS = Tmp2;
+}
+
+/// ExpandBIT_CONVERT - Expand a BIT_CONVERT node into a store/load combination.
+/// The resultant code need not be legal.  Note that SrcOp is the input operand
+/// to the BIT_CONVERT, not the BIT_CONVERT node itself.
+SDOperand SelectionDAGLegalize::ExpandBIT_CONVERT(MVT::ValueType DestVT, 
+                                                  SDOperand SrcOp) {
+  // Create the stack frame object.
+  SDOperand FIPtr = CreateStackTemporary(DestVT);
+  
+  // Emit a store to the stack slot.
+  SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
+                                SrcOp, FIPtr, DAG.getSrcValue(NULL));
+  // Result is a load from the stack slot.
+  return DAG.getLoad(DestVT, Store, FIPtr, DAG.getSrcValue(0));
+}
+
+SDOperand SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
+  // Create a vector sized/aligned stack slot, store the value to element #0,
+  // then load the whole vector back out.
+  SDOperand StackPtr = CreateStackTemporary(Node->getValueType(0));
+  SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
+                             Node->getOperand(0), StackPtr,
+                             DAG.getSrcValue(NULL));
+  return DAG.getLoad(Node->getValueType(0), Ch, StackPtr,DAG.getSrcValue(NULL));
+}
+
+
+/// 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);
+    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[0], ZeroVec.size());
+
+    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
+    if (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[0], MaskVec.size());
+
+    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
+    if (TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0)) &&
+        isShuffleLegal(Node->getValueType(0), ShuffleMask)) {
+      SmallVector<SDOperand, 8> 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[0], Ops.size());
+    }
+  }
+  
+  // 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.
+  SmallVector<SDOperand, 8> 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[0], Stores.size());
+  else
+    StoreChain = DAG.getEntryNode();
+  
+  // Result is a load from the stack slot.
+  return DAG.getLoad(VT, StoreChain, FIPtr, DAG.getSrcValue(0));
 }
 
-/// ExpandBIT_CONVERT - Expand a BIT_CONVERT node into a store/load combination.
-/// The resultant code need not be legal.  Note that SrcOp is the input operand
-/// to the BIT_CONVERT, not the BIT_CONVERT node itself.
-SDOperand SelectionDAGLegalize::ExpandBIT_CONVERT(MVT::ValueType DestVT, 
-                                                  SDOperand SrcOp) {
-  // Create the stack frame object.
+/// 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(DestVT)/8;
+  unsigned ByteSize = MVT::getSizeInBits(VT)/8;
   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
-  SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
-  
-  // Emit a store to the stack slot.
-  SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
-                                SrcOp, FIPtr, DAG.getSrcValue(NULL));
-  // Result is a load from the stack slot.
-  return DAG.getLoad(DestVT, Store, FIPtr, DAG.getSrcValue(0));
+  return DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
 }
 
 void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
@@ -2953,12 +3705,9 @@ void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
   SDOperand LHSL, LHSH;
   ExpandOp(Op, LHSL, LHSH);
 
-  std::vector<SDOperand> Ops;
-  Ops.push_back(LHSL);
-  Ops.push_back(LHSH);
-  Ops.push_back(Amt);
-  std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
-  Lo = DAG.getNode(NodeOp, VTs, Ops);
+  SDOperand Ops[] = { LHSL, LHSH, Amt };
+  MVT::ValueType VT = LHSL.getValueType();
+  Lo = DAG.getNode(NodeOp, DAG.getNodeValueTypes(VT, VT), 2, Ops, 3);
   Hi = Lo.getValue(1);
 }
 
@@ -3042,6 +3791,72 @@ bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
       return true;
     }
   }
+  
+  // Okay, the shift amount isn't constant.  However, if we can tell that it is
+  // >= 32 or < 32, we can still simplify it, without knowing the actual value.
+  uint64_t Mask = NVTBits, KnownZero, KnownOne;
+  TLI.ComputeMaskedBits(Amt, Mask, KnownZero, KnownOne);
+  
+  // If we know that the high bit of the shift amount is one, then we can do
+  // this as a couple of simple shifts.
+  if (KnownOne & Mask) {
+    // Mask out the high bit, which we know is set.
+    Amt = DAG.getNode(ISD::AND, Amt.getValueType(), Amt,
+                      DAG.getConstant(NVTBits-1, Amt.getValueType()));
+    
+    // Expand the incoming operand to be shifted, so that we have its parts
+    SDOperand InL, InH;
+    ExpandOp(Op, InL, InH);
+    switch(Opc) {
+    case ISD::SHL:
+      Lo = DAG.getConstant(0, NVT);              // Low part is zero.
+      Hi = DAG.getNode(ISD::SHL, NVT, InL, Amt); // High part from Lo part.
+      return true;
+    case ISD::SRL:
+      Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
+      Lo = DAG.getNode(ISD::SRL, NVT, InH, Amt); // Lo part from Hi part.
+      return true;
+    case ISD::SRA:
+      Hi = DAG.getNode(ISD::SRA, NVT, InH,       // Sign extend high part.
+                       DAG.getConstant(NVTBits-1, Amt.getValueType()));
+      Lo = DAG.getNode(ISD::SRA, NVT, InH, Amt); // Lo part from Hi part.
+      return true;
+    }
+  }
+  
+  // If we know that the high bit of the shift amount is zero, then we can do
+  // this as a couple of simple shifts.
+  if (KnownZero & Mask) {
+    // Compute 32-amt.
+    SDOperand Amt2 = DAG.getNode(ISD::SUB, Amt.getValueType(),
+                                 DAG.getConstant(NVTBits, Amt.getValueType()),
+                                 Amt);
+    
+    // Expand the incoming operand to be shifted, so that we have its parts
+    SDOperand InL, InH;
+    ExpandOp(Op, InL, InH);
+    switch(Opc) {
+    case ISD::SHL:
+      Lo = DAG.getNode(ISD::SHL, NVT, InL, Amt);
+      Hi = DAG.getNode(ISD::OR, NVT,
+                       DAG.getNode(ISD::SHL, NVT, InH, Amt),
+                       DAG.getNode(ISD::SRL, NVT, InL, Amt2));
+      return true;
+    case ISD::SRL:
+      Hi = DAG.getNode(ISD::SRL, NVT, InH, Amt);
+      Lo = DAG.getNode(ISD::OR, NVT,
+                       DAG.getNode(ISD::SRL, NVT, InL, Amt),
+                       DAG.getNode(ISD::SHL, NVT, InH, Amt2));
+      return true;
+    case ISD::SRA:
+      Hi = DAG.getNode(ISD::SRA, NVT, InH, Amt);
+      Lo = DAG.getNode(ISD::OR, NVT,
+                       DAG.getNode(ISD::SRL, NVT, InL, Amt),
+                       DAG.getNode(ISD::SHL, NVT, InH, Amt2));
+      return true;
+    }
+  }
+  
   return false;
 }
 
@@ -3189,14 +4004,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) {
@@ -3496,7 +4308,6 @@ SDOperand SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDOperand Op) {
   }
 }
 
-
 /// 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
@@ -3525,7 +4336,9 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
   case ISD::CopyFromReg:
     assert(0 && "CopyFromReg must be legal!");
   default:
+#ifndef NDEBUG
     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
+#endif
     assert(0 && "Do not know how to expand this operator!");
     abort();
   case ISD::UNDEF:
@@ -3538,43 +4351,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);
@@ -3674,80 +4450,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.
@@ -3776,10 +4478,11 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
                      Node->getOperand(1), TH, FH, Node->getOperand(4));
     break;
   }
-  case ISD::SEXTLOAD: {
+  case ISD::LOADX: {
     SDOperand Chain = Node->getOperand(0);
     SDOperand Ptr   = Node->getOperand(1);
     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
+    unsigned LType = Node->getConstantOperandVal(4);
     
     if (EVT == NVT)
       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
@@ -3789,48 +4492,20 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
     
     // Remember that we legalized the chain.
     AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
-    
-    // The high part is obtained by SRA'ing all but one of the bits of the lo
-    // part.
-    unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
-    Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
-                                                       TLI.getShiftAmountTy()));
-    break;
-  }
-  case ISD::ZEXTLOAD: {
-    SDOperand Chain = Node->getOperand(0);
-    SDOperand Ptr   = Node->getOperand(1);
-    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
-    
-    if (EVT == NVT)
-      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
-    else
-      Lo = DAG.getExtLoad(ISD::ZEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
-                          EVT);
-    
-    // Remember that we legalized the chain.
-    AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
 
-    // The high part is just a zero.
-    Hi = DAG.getConstant(0, NVT);
-    break;
-  }
-  case ISD::EXTLOAD: {
-    SDOperand Chain = Node->getOperand(0);
-    SDOperand Ptr   = Node->getOperand(1);
-    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
-    
-    if (EVT == NVT)
-      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
-    else
-      Lo = DAG.getExtLoad(ISD::EXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
-                          EVT);
-    
-    // Remember that we legalized the chain.
-    AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
-    
-    // The high part is undefined.
-    Hi = DAG.getNode(ISD::UNDEF, NVT);
+    if (LType == ISD::SEXTLOAD) {
+      // The high part is obtained by SRA'ing all but one of the bits of the lo
+      // part.
+      unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
+      Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
+                                                          TLI.getShiftAmountTy()));
+    } else if (LType == ISD::ZEXTLOAD) {
+      // The high part is just a zero.
+      Hi = DAG.getConstant(0, NVT);
+    } else /* if (LType == ISD::EXTLOAD) */ {
+      // The high part is undefined.
+      Hi = DAG.getNode(ISD::UNDEF, NVT);
+    }
     break;
   }
   case ISD::ANY_EXTEND:
@@ -3861,8 +4536,21 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
     break;
     
   case ISD::BIT_CONVERT: {
-    SDOperand Tmp = ExpandBIT_CONVERT(Node->getValueType(0), 
-                                      Node->getOperand(0));
+    SDOperand Tmp;
+    if (TLI.getOperationAction(ISD::BIT_CONVERT, VT) == TargetLowering::Custom){
+      // If the target wants to, allow it to lower this itself.
+      switch (getTypeAction(Node->getOperand(0).getValueType())) {
+      case Expand: assert(0 && "cannot expand FP!");
+      case Legal:   Tmp = LegalizeOp(Node->getOperand(0)); break;
+      case Promote: Tmp = PromoteOp (Node->getOperand(0)); break;
+      }
+      Tmp = TLI.LowerOperation(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp), DAG);
+    }
+
+    // Turn this into a load/store pair by default.
+    if (Tmp.Val == 0)
+      Tmp = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
+    
     ExpandOp(Tmp, Lo, Hi);
     break;
   }
@@ -3943,6 +4631,24 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
       }
     }
     
+    // If ADDC/ADDE are supported and if the shift amount is a constant 1, emit 
+    // this X << 1 as X+X.
+    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(ShiftAmt)) {
+      if (ShAmt->getValue() == 1 && TLI.isOperationLegal(ISD::ADDC, NVT) && 
+          TLI.isOperationLegal(ISD::ADDE, NVT)) {
+        SDOperand LoOps[2], HiOps[3];
+        ExpandOp(Node->getOperand(0), LoOps[0], HiOps[0]);
+        SDVTList VTList = DAG.getVTList(LoOps[0].getValueType(), MVT::Flag);
+        LoOps[1] = LoOps[0];
+        Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
+
+        HiOps[1] = HiOps[0];
+        HiOps[2] = Lo.getValue(1);
+        Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
+        break;
+      }
+    }
+    
     // If we can emit an efficient shift operation, do so now.
     if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi))
       break;
@@ -4041,27 +4747,37 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
     SDOperand LHSL, LHSH, RHSL, RHSH;
     ExpandOp(Node->getOperand(0), LHSL, LHSH);
     ExpandOp(Node->getOperand(1), RHSL, RHSH);
-    std::vector<MVT::ValueType> VTs;
-    std::vector<SDOperand> LoOps, HiOps;
-    VTs.push_back(LHSL.getValueType());
-    VTs.push_back(MVT::Flag);
-    LoOps.push_back(LHSL);
-    LoOps.push_back(RHSL);
-    HiOps.push_back(LHSH);
-    HiOps.push_back(RHSH);
+    SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
+    SDOperand LoOps[2], HiOps[3];
+    LoOps[0] = LHSL;
+    LoOps[1] = RHSL;
+    HiOps[0] = LHSH;
+    HiOps[1] = RHSH;
     if (Node->getOpcode() == ISD::ADD) {
-      Lo = DAG.getNode(ISD::ADDC, VTs, LoOps);
-      HiOps.push_back(Lo.getValue(1));
-      Hi = DAG.getNode(ISD::ADDE, VTs, HiOps);
+      Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
+      HiOps[2] = Lo.getValue(1);
+      Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
     } else {
-      Lo = DAG.getNode(ISD::SUBC, VTs, LoOps);
-      HiOps.push_back(Lo.getValue(1));
-      Hi = DAG.getNode(ISD::SUBE, VTs, HiOps);
+      Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
+      HiOps[2] = Lo.getValue(1);
+      Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
     }
     break;
   }
   case ISD::MUL: {
-    if (TLI.isOperationLegal(ISD::MULHU, NVT)) {
+    // If the target wants to custom expand this, let them.
+    if (TLI.getOperationAction(ISD::MUL, VT) == TargetLowering::Custom) {
+      SDOperand New = TLI.LowerOperation(Op, DAG);
+      if (New.Val) {
+        ExpandOp(New, Lo, Hi);
+        break;
+      }
+    }
+    
+    bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, NVT);
+    bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, NVT);
+    bool UseLibCall = true;
+    if (HasMULHS || HasMULHU) {
       SDOperand LL, LH, RL, RH;
       ExpandOp(Node->getOperand(0), LL, LH);
       ExpandOp(Node->getOperand(1), RL, RH);
@@ -4070,7 +4786,7 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
       // extended the sign bit of the low half through the upper half, and if so
       // emit a MULHS instead of the alternate sequence that is valid for any
       // i64 x i64 multiply.
-      if (TLI.isOperationLegal(ISD::MULHS, NVT) &&
+      if (HasMULHS &&
           // is RH an extension of the sign bit of RL?
           RH.getOpcode() == ISD::SRA && RH.getOperand(0) == RL &&
           RH.getOperand(1).getOpcode() == ISD::Constant &&
@@ -4079,18 +4795,28 @@ void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
           LH.getOpcode() == ISD::SRA && LH.getOperand(0) == LL &&
           LH.getOperand(1).getOpcode() == ISD::Constant &&
           cast<ConstantSDNode>(LH.getOperand(1))->getValue() == SH) {
+        // FIXME: Move this to the dag combiner.
+        
+        // Low part:
+        Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
+        // High part:
         Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
-      } else {
+        break;
+      } else if (HasMULHU) {
+        // Low part:
+        Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
+        
+        // High part:
         Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
         RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
         LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
         Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
         Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
+        break;
       }
-      Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
-    } else {
-      Lo = ExpandLibCall("__muldi3" , Node, Hi);
     }
+
+    Lo = ExpandLibCall("__muldi3" , Node, Hi);
     break;
   }
   case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
@@ -4112,10 +4838,283 @@ 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: 
+#ifndef NDEBUG
+    Node->dump();
+#endif
+    assert(0 && "Unhandled operation in SplitVectorOp!");
+  case ISD::VBUILD_VECTOR: {
+    SmallVector<SDOperand, 8> 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[0], LoOps.size());
+
+    SmallVector<SDOperand, 8> 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[0], HiOps.size());
+    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));
+    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: 
+#ifndef NDEBUG
+    Node->dump(); std::cerr << "\n";
+#endif
+    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?
+      
+      // If all elements of the build_vector are undefs, return an undef.
+      bool AllUndef = true;
+      for (unsigned i = 0, e = Node->getNumOperands()-2; i != e; ++i)
+        if (Node->getOperand(i).getOpcode() != ISD::UNDEF) {
+          AllUndef = false;
+          break;
+        }
+      if (AllUndef) {
+        Result = DAG.getNode(ISD::UNDEF, NewVT);
+      } else {
+        Result = DAG.getNode(ISD::BUILD_VECTOR, NewVT, Node->op_begin(),
+                             Node->getNumOperands()-2);
+      }
+    }
+    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,
+                                 Node->getOperand(2).Val->op_begin(),
+                                 Node->getOperand(2).Val->getNumOperands()-2);
+      
+      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!");
+      }
+    }
+    break;
+  case ISD::VSELECT:
+    Result = DAG.getNode(ISD::SELECT, NewVT, Op.getOperand(0),
+                         PackVectorOp(Op.getOperand(1), NewVT),
+                         PackVectorOp(Op.getOperand(2), NewVT));
+    break;
+  }
+
+  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.
 //
 void SelectionDAG::Legalize() {
+  if (ViewLegalizeDAGs) viewGraph();
+
   /// run - This is the main entry point to this class.
   ///
   SelectionDAGLegalize(*this).LegalizeDAG();