Add support for promoting stores from one legal type to another, allowing us
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeDAG.cpp
1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SelectionDAG::Legalize method.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/Target/TargetLowering.h"
18 #include "llvm/Target/TargetData.h"
19 #include "llvm/Target/TargetOptions.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/CommandLine.h"
24 #include <iostream>
25 #include <map>
26 using namespace llvm;
27
28 #ifndef NDEBUG
29 static cl::opt<bool>
30 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
31                  cl::desc("Pop up a window to show dags before legalize"));
32 #else
33 static const bool ViewLegalizeDAGs = 0;
34 #endif
35
36 //===----------------------------------------------------------------------===//
37 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
38 /// hacks on it until the target machine can handle it.  This involves
39 /// eliminating value sizes the machine cannot handle (promoting small sizes to
40 /// large sizes or splitting up large values into small values) as well as
41 /// eliminating operations the machine cannot handle.
42 ///
43 /// This code also does a small amount of optimization and recognition of idioms
44 /// as part of its processing.  For example, if a target does not support a
45 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
46 /// will attempt merge setcc and brc instructions into brcc's.
47 ///
48 namespace {
49 class SelectionDAGLegalize {
50   TargetLowering &TLI;
51   SelectionDAG &DAG;
52
53   // Libcall insertion helpers.
54   
55   /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
56   /// legalized.  We use this to ensure that calls are properly serialized
57   /// against each other, including inserted libcalls.
58   SDOperand LastCALLSEQ_END;
59   
60   /// IsLegalizingCall - This member is used *only* for purposes of providing
61   /// helpful assertions that a libcall isn't created while another call is 
62   /// being legalized (which could lead to non-serialized call sequences).
63   bool IsLegalizingCall;
64   
65   enum LegalizeAction {
66     Legal,      // The target natively supports this operation.
67     Promote,    // This operation should be executed in a larger type.
68     Expand,     // Try to expand this to other ops, otherwise use a libcall.
69   };
70   
71   /// ValueTypeActions - This is a bitvector that contains two bits for each
72   /// value type, where the two bits correspond to the LegalizeAction enum.
73   /// This can be queried with "getTypeAction(VT)".
74   TargetLowering::ValueTypeActionImpl ValueTypeActions;
75
76   /// LegalizedNodes - For nodes that are of legal width, and that have more
77   /// than one use, this map indicates what regularized operand to use.  This
78   /// allows us to avoid legalizing the same thing more than once.
79   std::map<SDOperand, SDOperand> LegalizedNodes;
80
81   /// PromotedNodes - For nodes that are below legal width, and that have more
82   /// than one use, this map indicates what promoted value to use.  This allows
83   /// us to avoid promoting the same thing more than once.
84   std::map<SDOperand, SDOperand> PromotedNodes;
85
86   /// ExpandedNodes - For nodes that need to be expanded this map indicates
87   /// which which operands are the expanded version of the input.  This allows
88   /// us to avoid expanding the same node more than once.
89   std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
90
91   /// SplitNodes - For vector nodes that need to be split, this map indicates
92   /// which which operands are the split version of the input.  This allows us
93   /// to avoid splitting the same node more than once.
94   std::map<SDOperand, std::pair<SDOperand, SDOperand> > SplitNodes;
95   
96   /// PackedNodes - For nodes that need to be packed from MVT::Vector types to
97   /// concrete packed types, this contains the mapping of ones we have already
98   /// processed to the result.
99   std::map<SDOperand, SDOperand> PackedNodes;
100   
101   void AddLegalizedOperand(SDOperand From, SDOperand To) {
102     LegalizedNodes.insert(std::make_pair(From, To));
103     // If someone requests legalization of the new node, return itself.
104     if (From != To)
105       LegalizedNodes.insert(std::make_pair(To, To));
106   }
107   void AddPromotedOperand(SDOperand From, SDOperand To) {
108     bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
109     assert(isNew && "Got into the map somehow?");
110     // If someone requests legalization of the new node, return itself.
111     LegalizedNodes.insert(std::make_pair(To, To));
112   }
113
114 public:
115
116   SelectionDAGLegalize(SelectionDAG &DAG);
117
118   /// getTypeAction - Return how we should legalize values of this type, either
119   /// it is already legal or we need to expand it into multiple registers of
120   /// smaller integer type, or we need to promote it to a larger type.
121   LegalizeAction getTypeAction(MVT::ValueType VT) const {
122     return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
123   }
124
125   /// isTypeLegal - Return true if this type is legal on this target.
126   ///
127   bool isTypeLegal(MVT::ValueType VT) const {
128     return getTypeAction(VT) == Legal;
129   }
130
131   void LegalizeDAG();
132
133 private:
134   /// HandleOp - Legalize, Promote, Expand or Pack the specified operand as
135   /// appropriate for its type.
136   void HandleOp(SDOperand Op);
137     
138   /// LegalizeOp - We know that the specified value has a legal type.
139   /// Recursively ensure that the operands have legal types, then return the
140   /// result.
141   SDOperand LegalizeOp(SDOperand O);
142   
143   /// PromoteOp - Given an operation that produces a value in an invalid type,
144   /// promote it to compute the value into a larger type.  The produced value
145   /// will have the correct bits for the low portion of the register, but no
146   /// guarantee is made about the top bits: it may be zero, sign-extended, or
147   /// garbage.
148   SDOperand PromoteOp(SDOperand O);
149
150   /// ExpandOp - Expand the specified SDOperand into its two component pieces
151   /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this,
152   /// the LegalizeNodes map is filled in for any results that are not expanded,
153   /// the ExpandedNodes map is filled in for any results that are expanded, and
154   /// the Lo/Hi values are returned.   This applies to integer types and Vector
155   /// types.
156   void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
157
158   /// SplitVectorOp - Given an operand of MVT::Vector type, break it down into
159   /// two smaller values of MVT::Vector type.
160   void SplitVectorOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
161   
162   /// PackVectorOp - Given an operand of MVT::Vector type, convert it into the
163   /// equivalent operation that returns a packed value (e.g. MVT::V4F32).  When
164   /// this is called, we know that PackedVT is the right type for the result and
165   /// we know that this type is legal for the target.
166   SDOperand PackVectorOp(SDOperand O, MVT::ValueType PackedVT);
167   
168   /// isShuffleLegal - Return true if a vector shuffle is legal with the
169   /// specified mask and type.  Targets can specify exactly which masks they
170   /// support and the code generator is tasked with not creating illegal masks.
171   ///
172   /// Note that this will also return true for shuffles that are promoted to a
173   /// different type.
174   ///
175   /// If this is a legal shuffle, this method returns the (possibly promoted)
176   /// build_vector Mask.  If it's not a legal shuffle, it returns null.
177   SDNode *isShuffleLegal(MVT::ValueType VT, SDOperand Mask) const;
178   
179   bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest);
180
181   void LegalizeSetCCOperands(SDOperand &LHS, SDOperand &RHS, SDOperand &CC);
182     
183   SDOperand CreateStackTemporary(MVT::ValueType VT);
184
185   SDOperand ExpandLibCall(const char *Name, SDNode *Node,
186                           SDOperand &Hi);
187   SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
188                           SDOperand Source);
189
190   SDOperand ExpandBIT_CONVERT(MVT::ValueType DestVT, SDOperand SrcOp);
191   SDOperand ExpandBUILD_VECTOR(SDNode *Node);
192   SDOperand ExpandSCALAR_TO_VECTOR(SDNode *Node);
193   SDOperand ExpandLegalINT_TO_FP(bool isSigned,
194                                  SDOperand LegalOp,
195                                  MVT::ValueType DestVT);
196   SDOperand PromoteLegalINT_TO_FP(SDOperand LegalOp, MVT::ValueType DestVT,
197                                   bool isSigned);
198   SDOperand PromoteLegalFP_TO_INT(SDOperand LegalOp, MVT::ValueType DestVT,
199                                   bool isSigned);
200
201   SDOperand ExpandBSWAP(SDOperand Op);
202   SDOperand ExpandBitCount(unsigned Opc, SDOperand Op);
203   bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
204                    SDOperand &Lo, SDOperand &Hi);
205   void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
206                         SDOperand &Lo, SDOperand &Hi);
207
208   SDOperand LowerVEXTRACT_VECTOR_ELT(SDOperand Op);
209   SDOperand ExpandEXTRACT_VECTOR_ELT(SDOperand Op);
210   
211   SDOperand getIntPtrConstant(uint64_t Val) {
212     return DAG.getConstant(Val, TLI.getPointerTy());
213   }
214 };
215 }
216
217 /// isVectorShuffleLegal - Return true if a vector shuffle is legal with the
218 /// specified mask and type.  Targets can specify exactly which masks they
219 /// support and the code generator is tasked with not creating illegal masks.
220 ///
221 /// Note that this will also return true for shuffles that are promoted to a
222 /// different type.
223 SDNode *SelectionDAGLegalize::isShuffleLegal(MVT::ValueType VT, 
224                                              SDOperand Mask) const {
225   switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, VT)) {
226   default: return 0;
227   case TargetLowering::Legal:
228   case TargetLowering::Custom:
229     break;
230   case TargetLowering::Promote: {
231     // If this is promoted to a different type, convert the shuffle mask and
232     // ask if it is legal in the promoted type!
233     MVT::ValueType NVT = TLI.getTypeToPromoteTo(ISD::VECTOR_SHUFFLE, VT);
234
235     // If we changed # elements, change the shuffle mask.
236     unsigned NumEltsGrowth =
237       MVT::getVectorNumElements(NVT) / MVT::getVectorNumElements(VT);
238     assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
239     if (NumEltsGrowth > 1) {
240       // Renumber the elements.
241       std::vector<SDOperand> Ops;
242       for (unsigned i = 0, e = Mask.getNumOperands(); i != e; ++i) {
243         SDOperand InOp = Mask.getOperand(i);
244         for (unsigned j = 0; j != NumEltsGrowth; ++j) {
245           if (InOp.getOpcode() == ISD::UNDEF)
246             Ops.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
247           else {
248             unsigned InEltNo = cast<ConstantSDNode>(InOp)->getValue();
249             Ops.push_back(DAG.getConstant(InEltNo*NumEltsGrowth+j, MVT::i32));
250           }
251         }
252       }
253       Mask = DAG.getNode(ISD::BUILD_VECTOR, NVT, Ops);
254     }
255     VT = NVT;
256     break;
257   }
258   }
259   return TLI.isShuffleMaskLegal(Mask, VT) ? Mask.Val : 0;
260 }
261
262 /// getScalarizedOpcode - Return the scalar opcode that corresponds to the
263 /// specified vector opcode.
264 static unsigned getScalarizedOpcode(unsigned VecOp, MVT::ValueType VT) {
265   switch (VecOp) {
266   default: assert(0 && "Don't know how to scalarize this opcode!");
267   case ISD::VADD:  return MVT::isInteger(VT) ? ISD::ADD : ISD::FADD;
268   case ISD::VSUB:  return MVT::isInteger(VT) ? ISD::SUB : ISD::FSUB;
269   case ISD::VMUL:  return MVT::isInteger(VT) ? ISD::MUL : ISD::FMUL;
270   case ISD::VSDIV: return MVT::isInteger(VT) ? ISD::SDIV: ISD::FDIV;
271   case ISD::VUDIV: return MVT::isInteger(VT) ? ISD::UDIV: ISD::FDIV;
272   case ISD::VAND:  return MVT::isInteger(VT) ? ISD::AND : 0;
273   case ISD::VOR:   return MVT::isInteger(VT) ? ISD::OR  : 0;
274   case ISD::VXOR:  return MVT::isInteger(VT) ? ISD::XOR : 0;
275   }
276 }
277
278 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
279   : TLI(dag.getTargetLoweringInfo()), DAG(dag),
280     ValueTypeActions(TLI.getValueTypeActions()) {
281   assert(MVT::LAST_VALUETYPE <= 32 &&
282          "Too many value types for ValueTypeActions to hold!");
283 }
284
285 /// ComputeTopDownOrdering - Add the specified node to the Order list if it has
286 /// not been visited yet and if all of its operands have already been visited.
287 static void ComputeTopDownOrdering(SDNode *N, std::vector<SDNode*> &Order,
288                                    std::map<SDNode*, unsigned> &Visited) {
289   if (++Visited[N] != N->getNumOperands())
290     return;  // Haven't visited all operands yet
291   
292   Order.push_back(N);
293   
294   if (N->hasOneUse()) { // Tail recurse in common case.
295     ComputeTopDownOrdering(*N->use_begin(), Order, Visited);
296     return;
297   }
298   
299   // Now that we have N in, add anything that uses it if all of their operands
300   // are now done.
301   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); UI != E;++UI)
302     ComputeTopDownOrdering(*UI, Order, Visited);
303 }
304
305
306 void SelectionDAGLegalize::LegalizeDAG() {
307   LastCALLSEQ_END = DAG.getEntryNode();
308   IsLegalizingCall = false;
309   
310   // The legalize process is inherently a bottom-up recursive process (users
311   // legalize their uses before themselves).  Given infinite stack space, we
312   // could just start legalizing on the root and traverse the whole graph.  In
313   // practice however, this causes us to run out of stack space on large basic
314   // blocks.  To avoid this problem, compute an ordering of the nodes where each
315   // node is only legalized after all of its operands are legalized.
316   std::map<SDNode*, unsigned> Visited;
317   std::vector<SDNode*> Order;
318   
319   // Compute ordering from all of the leaves in the graphs, those (like the
320   // entry node) that have no operands.
321   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
322        E = DAG.allnodes_end(); I != E; ++I) {
323     if (I->getNumOperands() == 0) {
324       Visited[I] = 0 - 1U;
325       ComputeTopDownOrdering(I, Order, Visited);
326     }
327   }
328   
329   assert(Order.size() == Visited.size() &&
330          Order.size() == 
331             (unsigned)std::distance(DAG.allnodes_begin(), DAG.allnodes_end()) &&
332          "Error: DAG is cyclic!");
333   Visited.clear();
334   
335   for (unsigned i = 0, e = Order.size(); i != e; ++i)
336     HandleOp(SDOperand(Order[i], 0));
337
338   // Finally, it's possible the root changed.  Get the new root.
339   SDOperand OldRoot = DAG.getRoot();
340   assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
341   DAG.setRoot(LegalizedNodes[OldRoot]);
342
343   ExpandedNodes.clear();
344   LegalizedNodes.clear();
345   PromotedNodes.clear();
346   SplitNodes.clear();
347   PackedNodes.clear();
348
349   // Remove dead nodes now.
350   DAG.RemoveDeadNodes(OldRoot.Val);
351 }
352
353
354 /// FindCallEndFromCallStart - Given a chained node that is part of a call
355 /// sequence, find the CALLSEQ_END node that terminates the call sequence.
356 static SDNode *FindCallEndFromCallStart(SDNode *Node) {
357   if (Node->getOpcode() == ISD::CALLSEQ_END)
358     return Node;
359   if (Node->use_empty())
360     return 0;   // No CallSeqEnd
361   
362   // The chain is usually at the end.
363   SDOperand TheChain(Node, Node->getNumValues()-1);
364   if (TheChain.getValueType() != MVT::Other) {
365     // Sometimes it's at the beginning.
366     TheChain = SDOperand(Node, 0);
367     if (TheChain.getValueType() != MVT::Other) {
368       // Otherwise, hunt for it.
369       for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
370         if (Node->getValueType(i) == MVT::Other) {
371           TheChain = SDOperand(Node, i);
372           break;
373         }
374           
375       // Otherwise, we walked into a node without a chain.  
376       if (TheChain.getValueType() != MVT::Other)
377         return 0;
378     }
379   }
380   
381   for (SDNode::use_iterator UI = Node->use_begin(),
382        E = Node->use_end(); UI != E; ++UI) {
383     
384     // Make sure to only follow users of our token chain.
385     SDNode *User = *UI;
386     for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
387       if (User->getOperand(i) == TheChain)
388         if (SDNode *Result = FindCallEndFromCallStart(User))
389           return Result;
390   }
391   return 0;
392 }
393
394 /// FindCallStartFromCallEnd - Given a chained node that is part of a call 
395 /// sequence, find the CALLSEQ_START node that initiates the call sequence.
396 static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
397   assert(Node && "Didn't find callseq_start for a call??");
398   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
399   
400   assert(Node->getOperand(0).getValueType() == MVT::Other &&
401          "Node doesn't have a token chain argument!");
402   return FindCallStartFromCallEnd(Node->getOperand(0).Val);
403 }
404
405 /// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
406 /// see if any uses can reach Dest.  If no dest operands can get to dest, 
407 /// legalize them, legalize ourself, and return false, otherwise, return true.
408 bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, 
409                                                         SDNode *Dest) {
410   if (N == Dest) return true;  // N certainly leads to Dest :)
411   
412   // If the first result of this node has been already legalized, then it cannot
413   // reach N.
414   switch (getTypeAction(N->getValueType(0))) {
415   case Legal: 
416     if (LegalizedNodes.count(SDOperand(N, 0))) return false;
417     break;
418   case Promote:
419     if (PromotedNodes.count(SDOperand(N, 0))) return false;
420     break;
421   case Expand:
422     if (ExpandedNodes.count(SDOperand(N, 0))) return false;
423     break;
424   }
425   
426   // Okay, this node has not already been legalized.  Check and legalize all
427   // operands.  If none lead to Dest, then we can legalize this node.
428   bool OperandsLeadToDest = false;
429   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
430     OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
431       LegalizeAllNodesNotLeadingTo(N->getOperand(i).Val, Dest);
432
433   if (OperandsLeadToDest) return true;
434
435   // Okay, this node looks safe, legalize it and return false.
436   switch (getTypeAction(N->getValueType(0))) {
437   case Legal:
438     LegalizeOp(SDOperand(N, 0));
439     break;
440   case Promote:
441     PromoteOp(SDOperand(N, 0));
442     break;
443   case Expand: {
444     SDOperand X, Y;
445     ExpandOp(SDOperand(N, 0), X, Y);
446     break;
447   }
448   }
449   return false;
450 }
451
452 /// HandleOp - Legalize, Promote, Expand or Pack the specified operand as
453 /// appropriate for its type.
454 void SelectionDAGLegalize::HandleOp(SDOperand Op) {
455   switch (getTypeAction(Op.getValueType())) {
456   default: assert(0 && "Bad type action!");
457   case Legal:   LegalizeOp(Op); break;
458   case Promote: PromoteOp(Op);  break;
459   case Expand:
460     if (Op.getValueType() != MVT::Vector) {
461       SDOperand X, Y;
462       ExpandOp(Op, X, Y);
463     } else {
464       SDNode *N = Op.Val;
465       unsigned NumOps = N->getNumOperands();
466       unsigned NumElements =
467         cast<ConstantSDNode>(N->getOperand(NumOps-2))->getValue();
468       MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(NumOps-1))->getVT();
469       MVT::ValueType PackedVT = getVectorType(EVT, NumElements);
470       if (PackedVT != MVT::Other && TLI.isTypeLegal(PackedVT)) {
471         // In the common case, this is a legal vector type, convert it to the
472         // packed operation and type now.
473         PackVectorOp(Op, PackedVT);
474       } else if (NumElements == 1) {
475         // Otherwise, if this is a single element vector, convert it to a
476         // scalar operation.
477         PackVectorOp(Op, EVT);
478       } else {
479         // Otherwise, this is a multiple element vector that isn't supported.
480         // Split it in half and legalize both parts.
481         SDOperand X, Y;
482         SplitVectorOp(Op, X, Y);
483       }
484     }
485     break;
486   }
487 }
488
489
490 /// LegalizeOp - We know that the specified value has a legal type.
491 /// Recursively ensure that the operands have legal types, then return the
492 /// result.
493 SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
494   assert(isTypeLegal(Op.getValueType()) &&
495          "Caller should expand or promote operands that are not legal!");
496   SDNode *Node = Op.Val;
497
498   // If this operation defines any values that cannot be represented in a
499   // register on this target, make sure to expand or promote them.
500   if (Node->getNumValues() > 1) {
501     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
502       if (getTypeAction(Node->getValueType(i)) != Legal) {
503         HandleOp(Op.getValue(i));
504         assert(LegalizedNodes.count(Op) &&
505                "Handling didn't add legal operands!");
506         return LegalizedNodes[Op];
507       }
508   }
509
510   // Note that LegalizeOp may be reentered even from single-use nodes, which
511   // means that we always must cache transformed nodes.
512   std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
513   if (I != LegalizedNodes.end()) return I->second;
514
515   SDOperand Tmp1, Tmp2, Tmp3, Tmp4;
516   SDOperand Result = Op;
517   bool isCustom = false;
518   
519   switch (Node->getOpcode()) {
520   case ISD::FrameIndex:
521   case ISD::EntryToken:
522   case ISD::Register:
523   case ISD::BasicBlock:
524   case ISD::TargetFrameIndex:
525   case ISD::TargetConstant:
526   case ISD::TargetConstantFP:
527   case ISD::TargetConstantPool:
528   case ISD::TargetGlobalAddress:
529   case ISD::TargetExternalSymbol:
530   case ISD::VALUETYPE:
531   case ISD::SRCVALUE:
532   case ISD::STRING:
533   case ISD::CONDCODE:
534     // Primitives must all be legal.
535     assert(TLI.isOperationLegal(Node->getValueType(0), Node->getValueType(0)) &&
536            "This must be legal!");
537     break;
538   default:
539     if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
540       // If this is a target node, legalize it by legalizing the operands then
541       // passing it through.
542       std::vector<SDOperand> Ops;
543       bool Changed = false;
544       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
545         Ops.push_back(LegalizeOp(Node->getOperand(i)));
546         Changed = Changed || Node->getOperand(i) != Ops.back();
547       }
548       if (Changed)
549         if (Node->getNumValues() == 1)
550           Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
551         else {
552           std::vector<MVT::ValueType> VTs(Node->value_begin(),
553                                           Node->value_end());
554           Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
555         }
556
557       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
558         AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
559       return Result.getValue(Op.ResNo);
560     }
561     // Otherwise this is an unhandled builtin node.  splat.
562     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
563     assert(0 && "Do not know how to legalize this operator!");
564     abort();
565   case ISD::GlobalAddress:
566   case ISD::ExternalSymbol:
567   case ISD::ConstantPool:           // Nothing to do.
568     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
569     default: assert(0 && "This action is not supported yet!");
570     case TargetLowering::Custom:
571       Tmp1 = TLI.LowerOperation(Op, DAG);
572       if (Tmp1.Val) Result = Tmp1;
573       // FALLTHROUGH if the target doesn't want to lower this op after all.
574     case TargetLowering::Legal:
575       break;
576     }
577     break;
578   case ISD::AssertSext:
579   case ISD::AssertZext:
580     Tmp1 = LegalizeOp(Node->getOperand(0));
581     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
582     break;
583   case ISD::MERGE_VALUES:
584     // Legalize eliminates MERGE_VALUES nodes.
585     Result = Node->getOperand(Op.ResNo);
586     break;
587   case ISD::CopyFromReg:
588     Tmp1 = LegalizeOp(Node->getOperand(0));
589     Result = Op.getValue(0);
590     if (Node->getNumValues() == 2) {
591       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
592     } else {
593       assert(Node->getNumValues() == 3 && "Invalid copyfromreg!");
594       if (Node->getNumOperands() == 3) {
595         Tmp2 = LegalizeOp(Node->getOperand(2));
596         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
597       } else {
598         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
599       }
600       AddLegalizedOperand(Op.getValue(2), Result.getValue(2));
601     }
602     // Since CopyFromReg produces two values, make sure to remember that we
603     // legalized both of them.
604     AddLegalizedOperand(Op.getValue(0), Result);
605     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
606     return Result.getValue(Op.ResNo);
607   case ISD::UNDEF: {
608     MVT::ValueType VT = Op.getValueType();
609     switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
610     default: assert(0 && "This action is not supported yet!");
611     case TargetLowering::Expand:
612       if (MVT::isInteger(VT))
613         Result = DAG.getConstant(0, VT);
614       else if (MVT::isFloatingPoint(VT))
615         Result = DAG.getConstantFP(0, VT);
616       else
617         assert(0 && "Unknown value type!");
618       break;
619     case TargetLowering::Legal:
620       break;
621     }
622     break;
623   }
624     
625   case ISD::INTRINSIC_W_CHAIN:
626   case ISD::INTRINSIC_WO_CHAIN:
627   case ISD::INTRINSIC_VOID: {
628     std::vector<SDOperand> Ops;
629     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
630       Ops.push_back(LegalizeOp(Node->getOperand(i)));
631     Result = DAG.UpdateNodeOperands(Result, Ops);
632     
633     // Allow the target to custom lower its intrinsics if it wants to.
634     if (TLI.getOperationAction(Node->getOpcode(), MVT::Other) == 
635         TargetLowering::Custom) {
636       Tmp3 = TLI.LowerOperation(Result, DAG);
637       if (Tmp3.Val) Result = Tmp3;
638     }
639
640     if (Result.Val->getNumValues() == 1) break;
641
642     // Must have return value and chain result.
643     assert(Result.Val->getNumValues() == 2 &&
644            "Cannot return more than two values!");
645
646     // Since loads produce two values, make sure to remember that we 
647     // legalized both of them.
648     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
649     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
650     return Result.getValue(Op.ResNo);
651   }    
652
653   case ISD::LOCATION:
654     assert(Node->getNumOperands() == 5 && "Invalid LOCATION node!");
655     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
656     
657     switch (TLI.getOperationAction(ISD::LOCATION, MVT::Other)) {
658     case TargetLowering::Promote:
659     default: assert(0 && "This action is not supported yet!");
660     case TargetLowering::Expand: {
661       MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
662       bool useDEBUG_LOC = TLI.isOperationLegal(ISD::DEBUG_LOC, MVT::Other);
663       bool useDEBUG_LABEL = TLI.isOperationLegal(ISD::DEBUG_LABEL, MVT::Other);
664       
665       if (DebugInfo && (useDEBUG_LOC || useDEBUG_LABEL)) {
666         const std::string &FName =
667           cast<StringSDNode>(Node->getOperand(3))->getValue();
668         const std::string &DirName = 
669           cast<StringSDNode>(Node->getOperand(4))->getValue();
670         unsigned SrcFile = DebugInfo->RecordSource(DirName, FName);
671
672         std::vector<SDOperand> Ops;
673         Ops.push_back(Tmp1);  // chain
674         SDOperand LineOp = Node->getOperand(1);
675         SDOperand ColOp = Node->getOperand(2);
676         
677         if (useDEBUG_LOC) {
678           Ops.push_back(LineOp);  // line #
679           Ops.push_back(ColOp);  // col #
680           Ops.push_back(DAG.getConstant(SrcFile, MVT::i32));  // source file id
681           Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, Ops);
682         } else {
683           unsigned Line = cast<ConstantSDNode>(LineOp)->getValue();
684           unsigned Col = cast<ConstantSDNode>(ColOp)->getValue();
685           unsigned ID = DebugInfo->RecordLabel(Line, Col, SrcFile);
686           Ops.push_back(DAG.getConstant(ID, MVT::i32));
687           Result = DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops);
688         }
689       } else {
690         Result = Tmp1;  // chain
691       }
692       break;
693     }
694     case TargetLowering::Legal:
695       if (Tmp1 != Node->getOperand(0) ||
696           getTypeAction(Node->getOperand(1).getValueType()) == Promote) {
697         std::vector<SDOperand> Ops;
698         Ops.push_back(Tmp1);
699         if (getTypeAction(Node->getOperand(1).getValueType()) == Legal) {
700           Ops.push_back(Node->getOperand(1));  // line # must be legal.
701           Ops.push_back(Node->getOperand(2));  // col # must be legal.
702         } else {
703           // Otherwise promote them.
704           Ops.push_back(PromoteOp(Node->getOperand(1)));
705           Ops.push_back(PromoteOp(Node->getOperand(2)));
706         }
707         Ops.push_back(Node->getOperand(3));  // filename must be legal.
708         Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
709         Result = DAG.UpdateNodeOperands(Result, Ops);
710       }
711       break;
712     }
713     break;
714     
715   case ISD::DEBUG_LOC:
716     assert(Node->getNumOperands() == 4 && "Invalid DEBUG_LOC node!");
717     switch (TLI.getOperationAction(ISD::DEBUG_LOC, MVT::Other)) {
718     default: assert(0 && "This action is not supported yet!");
719     case TargetLowering::Legal:
720       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
721       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the line #.
722       Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the col #.
723       Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize the source file id.
724       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
725       break;
726     }
727     break;    
728
729   case ISD::DEBUG_LABEL:
730     assert(Node->getNumOperands() == 2 && "Invalid DEBUG_LABEL node!");
731     switch (TLI.getOperationAction(ISD::DEBUG_LABEL, MVT::Other)) {
732     default: assert(0 && "This action is not supported yet!");
733     case TargetLowering::Legal:
734       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
735       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the label id.
736       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
737       break;
738     }
739     break;
740
741   case ISD::Constant:
742     // We know we don't need to expand constants here, constants only have one
743     // value and we check that it is fine above.
744
745     // FIXME: Maybe we should handle things like targets that don't support full
746     // 32-bit immediates?
747     break;
748   case ISD::ConstantFP: {
749     // Spill FP immediates to the constant pool if the target cannot directly
750     // codegen them.  Targets often have some immediate values that can be
751     // efficiently generated into an FP register without a load.  We explicitly
752     // leave these constants as ConstantFP nodes for the target to deal with.
753     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
754
755     // Check to see if this FP immediate is already legal.
756     bool isLegal = false;
757     for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
758            E = TLI.legal_fpimm_end(); I != E; ++I)
759       if (CFP->isExactlyValue(*I)) {
760         isLegal = true;
761         break;
762       }
763
764     // If this is a legal constant, turn it into a TargetConstantFP node.
765     if (isLegal) {
766       Result = DAG.getTargetConstantFP(CFP->getValue(), CFP->getValueType(0));
767       break;
768     }
769
770     switch (TLI.getOperationAction(ISD::ConstantFP, CFP->getValueType(0))) {
771     default: assert(0 && "This action is not supported yet!");
772     case TargetLowering::Custom:
773       Tmp3 = TLI.LowerOperation(Result, DAG);
774       if (Tmp3.Val) {
775         Result = Tmp3;
776         break;
777       }
778       // FALLTHROUGH
779     case TargetLowering::Expand:
780       // Otherwise we need to spill the constant to memory.
781       bool Extend = false;
782
783       // If a FP immediate is precise when represented as a float and if the
784       // target can do an extending load from float to double, we put it into
785       // the constant pool as a float, even if it's is statically typed as a
786       // double.
787       MVT::ValueType VT = CFP->getValueType(0);
788       bool isDouble = VT == MVT::f64;
789       ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
790                                              Type::FloatTy, CFP->getValue());
791       if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
792           // Only do this if the target has a native EXTLOAD instruction from
793           // f32.
794           TLI.isOperationLegal(ISD::EXTLOAD, MVT::f32)) {
795         LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
796         VT = MVT::f32;
797         Extend = true;
798       }
799
800       SDOperand CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
801       if (Extend) {
802         Result = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
803                                 CPIdx, DAG.getSrcValue(NULL), MVT::f32);
804       } else {
805         Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
806                              DAG.getSrcValue(NULL));
807       }
808     }
809     break;
810   }
811   case ISD::TokenFactor:
812     if (Node->getNumOperands() == 2) {
813       Tmp1 = LegalizeOp(Node->getOperand(0));
814       Tmp2 = LegalizeOp(Node->getOperand(1));
815       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
816     } else if (Node->getNumOperands() == 3) {
817       Tmp1 = LegalizeOp(Node->getOperand(0));
818       Tmp2 = LegalizeOp(Node->getOperand(1));
819       Tmp3 = LegalizeOp(Node->getOperand(2));
820       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
821     } else {
822       std::vector<SDOperand> Ops;
823       // Legalize the operands.
824       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
825         Ops.push_back(LegalizeOp(Node->getOperand(i)));
826       Result = DAG.UpdateNodeOperands(Result, Ops);
827     }
828     break;
829     
830   case ISD::FORMAL_ARGUMENTS:
831     // The only option for this is to custom lower it.
832     Result = TLI.LowerOperation(Result, DAG);
833     assert(Result.Val && "Target didn't custom lower ISD::FORMAL_ARGUMENTS!");
834     break;
835         
836   case ISD::BUILD_VECTOR:
837     switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
838     default: assert(0 && "This action is not supported yet!");
839     case TargetLowering::Custom:
840       Tmp3 = TLI.LowerOperation(Result, DAG);
841       if (Tmp3.Val) {
842         Result = Tmp3;
843         break;
844       }
845       // FALLTHROUGH
846     case TargetLowering::Expand:
847       Result = ExpandBUILD_VECTOR(Result.Val);
848       break;
849     }
850     break;
851   case ISD::INSERT_VECTOR_ELT:
852     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVec
853     Tmp2 = LegalizeOp(Node->getOperand(1));  // InVal
854     Tmp3 = LegalizeOp(Node->getOperand(2));  // InEltNo
855     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
856     
857     switch (TLI.getOperationAction(ISD::INSERT_VECTOR_ELT,
858                                    Node->getValueType(0))) {
859     default: assert(0 && "This action is not supported yet!");
860     case TargetLowering::Legal:
861       break;
862     case TargetLowering::Custom:
863       Tmp3 = TLI.LowerOperation(Result, DAG);
864       if (Tmp3.Val) {
865         Result = Tmp3;
866         break;
867       }
868       // FALLTHROUGH
869     case TargetLowering::Expand: {
870       // If the target doesn't support this, we have to spill the input vector
871       // to a temporary stack slot, update the element, then reload it.  This is
872       // badness.  We could also load the value into a vector register (either
873       // with a "move to register" or "extload into register" instruction, then
874       // permute it into place, if the idx is a constant and if the idx is
875       // supported by the target.
876       MVT::ValueType VT    = Tmp1.getValueType();
877       MVT::ValueType EltVT = Tmp2.getValueType();
878       MVT::ValueType IdxVT = Tmp3.getValueType();
879       MVT::ValueType PtrVT = TLI.getPointerTy();
880       SDOperand StackPtr = CreateStackTemporary(VT);
881       // Store the vector.
882       SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
883                                  Tmp1, StackPtr, DAG.getSrcValue(NULL));
884
885       // Truncate or zero extend offset to target pointer type.
886       unsigned CastOpc = (IdxVT > PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
887       Tmp3 = DAG.getNode(CastOpc, PtrVT, Tmp3);
888       // Add the offset to the index.
889       unsigned EltSize = MVT::getSizeInBits(EltVT)/8;
890       Tmp3 = DAG.getNode(ISD::MUL, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
891       SDOperand StackPtr2 = DAG.getNode(ISD::ADD, IdxVT, Tmp3, StackPtr);
892       // Store the scalar value.
893       Ch = DAG.getNode(ISD::STORE, MVT::Other, Ch,
894                        Tmp2, StackPtr2, DAG.getSrcValue(NULL));
895       // Load the updated vector.
896       Result = DAG.getLoad(VT, Ch, StackPtr, DAG.getSrcValue(NULL));
897       break;
898     }
899     }
900     break;
901   case ISD::SCALAR_TO_VECTOR:
902     if (!TLI.isTypeLegal(Node->getOperand(0).getValueType())) {
903       Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
904       break;
905     }
906     
907     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVal
908     Result = DAG.UpdateNodeOperands(Result, Tmp1);
909     switch (TLI.getOperationAction(ISD::SCALAR_TO_VECTOR,
910                                    Node->getValueType(0))) {
911     default: assert(0 && "This action is not supported yet!");
912     case TargetLowering::Legal:
913       break;
914     case TargetLowering::Custom:
915       Tmp3 = TLI.LowerOperation(Result, DAG);
916       if (Tmp3.Val) {
917         Result = Tmp3;
918         break;
919       }
920       // FALLTHROUGH
921     case TargetLowering::Expand:
922       Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
923       break;
924     }
925     break;
926   case ISD::VECTOR_SHUFFLE:
927     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the input vectors,
928     Tmp2 = LegalizeOp(Node->getOperand(1));   // but not the shuffle mask.
929     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
930
931     // Allow targets to custom lower the SHUFFLEs they support.
932     switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE,Result.getValueType())) {
933     default: assert(0 && "Unknown operation action!");
934     case TargetLowering::Legal:
935       assert(isShuffleLegal(Result.getValueType(), Node->getOperand(2)) &&
936              "vector shuffle should not be created if not legal!");
937       break;
938     case TargetLowering::Custom:
939       Tmp3 = TLI.LowerOperation(Result, DAG);
940       if (Tmp3.Val) {
941         Result = Tmp3;
942         break;
943       }
944       // FALLTHROUGH
945     case TargetLowering::Expand: {
946       MVT::ValueType VT = Node->getValueType(0);
947       MVT::ValueType EltVT = MVT::getVectorBaseType(VT);
948       MVT::ValueType PtrVT = TLI.getPointerTy();
949       SDOperand Mask = Node->getOperand(2);
950       unsigned NumElems = Mask.getNumOperands();
951       std::vector<SDOperand> Ops;
952       for (unsigned i = 0; i != NumElems; ++i) {
953         SDOperand Arg = Mask.getOperand(i);
954         if (Arg.getOpcode() == ISD::UNDEF) {
955           Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
956         } else {
957           assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
958           unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
959           if (Idx < NumElems)
960             Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1,
961                                       DAG.getConstant(Idx, PtrVT)));
962           else
963             Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2,
964                                       DAG.getConstant(Idx - NumElems, PtrVT)));
965         }
966       }
967       Result = DAG.getNode(ISD::BUILD_VECTOR, VT, Ops);
968       break;
969     }
970     case TargetLowering::Promote: {
971       // Change base type to a different vector type.
972       MVT::ValueType OVT = Node->getValueType(0);
973       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
974
975       // Cast the two input vectors.
976       Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
977       Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
978       
979       // Convert the shuffle mask to the right # elements.
980       Tmp3 = SDOperand(isShuffleLegal(OVT, Node->getOperand(2)), 0);
981       assert(Tmp3.Val && "Shuffle not legal?");
982       Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NVT, Tmp1, Tmp2, Tmp3);
983       Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
984       break;
985     }
986     }
987     break;
988   
989   case ISD::EXTRACT_VECTOR_ELT:
990     Tmp1 = LegalizeOp(Node->getOperand(0));
991     Tmp2 = LegalizeOp(Node->getOperand(1));
992     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
993     
994     switch (TLI.getOperationAction(ISD::EXTRACT_VECTOR_ELT,
995                                    Tmp1.getValueType())) {
996     default: assert(0 && "This action is not supported yet!");
997     case TargetLowering::Legal:
998       break;
999     case TargetLowering::Custom:
1000       Tmp3 = TLI.LowerOperation(Result, DAG);
1001       if (Tmp3.Val) {
1002         Result = Tmp3;
1003         break;
1004       }
1005       // FALLTHROUGH
1006     case TargetLowering::Expand:
1007       Result = ExpandEXTRACT_VECTOR_ELT(Result);
1008       break;
1009     }
1010     break;
1011
1012   case ISD::VEXTRACT_VECTOR_ELT: 
1013     Result = LegalizeOp(LowerVEXTRACT_VECTOR_ELT(Op));
1014     break;
1015     
1016   case ISD::CALLSEQ_START: {
1017     SDNode *CallEnd = FindCallEndFromCallStart(Node);
1018     
1019     // Recursively Legalize all of the inputs of the call end that do not lead
1020     // to this call start.  This ensures that any libcalls that need be inserted
1021     // are inserted *before* the CALLSEQ_START.
1022     for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1023       LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).Val, Node);
1024
1025     // Now that we legalized all of the inputs (which may have inserted
1026     // libcalls) create the new CALLSEQ_START node.
1027     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1028
1029     // Merge in the last call, to ensure that this call start after the last
1030     // call ended.
1031     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1032     Tmp1 = LegalizeOp(Tmp1);
1033       
1034     // Do not try to legalize the target-specific arguments (#1+).
1035     if (Tmp1 != Node->getOperand(0)) {
1036       std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1037       Ops[0] = Tmp1;
1038       Result = DAG.UpdateNodeOperands(Result, Ops);
1039     }
1040     
1041     // Remember that the CALLSEQ_START is legalized.
1042     AddLegalizedOperand(Op.getValue(0), Result);
1043     if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
1044       AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1045     
1046     // Now that the callseq_start and all of the non-call nodes above this call
1047     // sequence have been legalized, legalize the call itself.  During this 
1048     // process, no libcalls can/will be inserted, guaranteeing that no calls
1049     // can overlap.
1050     assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1051     SDOperand InCallSEQ = LastCALLSEQ_END;
1052     // Note that we are selecting this call!
1053     LastCALLSEQ_END = SDOperand(CallEnd, 0);
1054     IsLegalizingCall = true;
1055     
1056     // Legalize the call, starting from the CALLSEQ_END.
1057     LegalizeOp(LastCALLSEQ_END);
1058     assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1059     return Result;
1060   }
1061   case ISD::CALLSEQ_END:
1062     // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1063     // will cause this node to be legalized as well as handling libcalls right.
1064     if (LastCALLSEQ_END.Val != Node) {
1065       LegalizeOp(SDOperand(FindCallStartFromCallEnd(Node), 0));
1066       std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
1067       assert(I != LegalizedNodes.end() &&
1068              "Legalizing the call start should have legalized this node!");
1069       return I->second;
1070     }
1071     
1072     // Otherwise, the call start has been legalized and everything is going 
1073     // according to plan.  Just legalize ourselves normally here.
1074     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1075     // Do not try to legalize the target-specific arguments (#1+), except for
1076     // an optional flag input.
1077     if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1078       if (Tmp1 != Node->getOperand(0)) {
1079         std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1080         Ops[0] = Tmp1;
1081         Result = DAG.UpdateNodeOperands(Result, Ops);
1082       }
1083     } else {
1084       Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1085       if (Tmp1 != Node->getOperand(0) ||
1086           Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1087         std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1088         Ops[0] = Tmp1;
1089         Ops.back() = Tmp2;
1090         Result = DAG.UpdateNodeOperands(Result, Ops);
1091       }
1092     }
1093     assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1094     // This finishes up call legalization.
1095     IsLegalizingCall = false;
1096     
1097     // If the CALLSEQ_END node has a flag, remember that we legalized it.
1098     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1099     if (Node->getNumValues() == 2)
1100       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1101     return Result.getValue(Op.ResNo);
1102   case ISD::DYNAMIC_STACKALLOC: {
1103     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1104     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
1105     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
1106     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1107
1108     Tmp1 = Result.getValue(0);
1109     Tmp2 = Result.getValue(1);
1110     switch (TLI.getOperationAction(Node->getOpcode(),
1111                                    Node->getValueType(0))) {
1112     default: assert(0 && "This action is not supported yet!");
1113     case TargetLowering::Expand: {
1114       unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1115       assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1116              " not tell us which reg is the stack pointer!");
1117       SDOperand Chain = Tmp1.getOperand(0);
1118       SDOperand Size  = Tmp2.getOperand(1);
1119       SDOperand SP = DAG.getCopyFromReg(Chain, SPReg, Node->getValueType(0));
1120       Tmp1 = DAG.getNode(ISD::SUB, Node->getValueType(0), SP, Size);    // Value
1121       Tmp2 = DAG.getCopyToReg(SP.getValue(1), SPReg, Tmp1);      // Output chain
1122       Tmp1 = LegalizeOp(Tmp1);
1123       Tmp2 = LegalizeOp(Tmp2);
1124       break;
1125     }
1126     case TargetLowering::Custom:
1127       Tmp3 = TLI.LowerOperation(Tmp1, DAG);
1128       if (Tmp3.Val) {
1129         Tmp1 = LegalizeOp(Tmp3);
1130         Tmp2 = LegalizeOp(Tmp3.getValue(1));
1131       }
1132       break;
1133     case TargetLowering::Legal:
1134       break;
1135     }
1136     // Since this op produce two values, make sure to remember that we
1137     // legalized both of them.
1138     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1139     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1140     return Op.ResNo ? Tmp2 : Tmp1;
1141   }
1142   case ISD::INLINEASM:
1143     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize Chain.
1144     Tmp2 = Node->getOperand(Node->getNumOperands()-1);
1145     if (Tmp2.getValueType() == MVT::Flag)     // Legalize Flag if it exists.
1146       Tmp2 = Tmp3 = SDOperand(0, 0);
1147     else
1148       Tmp3 = LegalizeOp(Tmp2);
1149     
1150     if (Tmp1 != Node->getOperand(0) || Tmp2 != Tmp3) {
1151       std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1152       Ops[0] = Tmp1;
1153       if (Tmp3.Val) Ops.back() = Tmp3;
1154       Result = DAG.UpdateNodeOperands(Result, Ops);
1155     }
1156       
1157     // INLINE asm returns a chain and flag, make sure to add both to the map.
1158     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1159     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1160     return Result.getValue(Op.ResNo);
1161   case ISD::BR:
1162     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1163     // Ensure that libcalls are emitted before a branch.
1164     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1165     Tmp1 = LegalizeOp(Tmp1);
1166     LastCALLSEQ_END = DAG.getEntryNode();
1167     
1168     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1169     break;
1170
1171   case ISD::BRCOND:
1172     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1173     // Ensure that libcalls are emitted before a return.
1174     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1175     Tmp1 = LegalizeOp(Tmp1);
1176     LastCALLSEQ_END = DAG.getEntryNode();
1177
1178     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1179     case Expand: assert(0 && "It's impossible to expand bools");
1180     case Legal:
1181       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
1182       break;
1183     case Promote:
1184       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
1185       break;
1186     }
1187
1188     // Basic block destination (Op#2) is always legal.
1189     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1190       
1191     switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {  
1192     default: assert(0 && "This action is not supported yet!");
1193     case TargetLowering::Legal: break;
1194     case TargetLowering::Custom:
1195       Tmp1 = TLI.LowerOperation(Result, DAG);
1196       if (Tmp1.Val) Result = Tmp1;
1197       break;
1198     case TargetLowering::Expand:
1199       // Expand brcond's setcc into its constituent parts and create a BR_CC
1200       // Node.
1201       if (Tmp2.getOpcode() == ISD::SETCC) {
1202         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
1203                              Tmp2.getOperand(0), Tmp2.getOperand(1),
1204                              Node->getOperand(2));
1205       } else {
1206         // Make sure the condition is either zero or one.  It may have been
1207         // promoted from something else.
1208         unsigned NumBits = MVT::getSizeInBits(Tmp2.getValueType());
1209         if (!TLI.MaskedValueIsZero(Tmp2, (~0ULL >> (64-NumBits))^1))
1210           Tmp2 = DAG.getZeroExtendInReg(Tmp2, MVT::i1);
1211         
1212         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, 
1213                              DAG.getCondCode(ISD::SETNE), Tmp2,
1214                              DAG.getConstant(0, Tmp2.getValueType()),
1215                              Node->getOperand(2));
1216       }
1217       break;
1218     }
1219     break;
1220   case ISD::BR_CC:
1221     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1222     // Ensure that libcalls are emitted before a branch.
1223     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1224     Tmp1 = LegalizeOp(Tmp1);
1225     LastCALLSEQ_END = DAG.getEntryNode();
1226     
1227     Tmp2 = Node->getOperand(2);              // LHS 
1228     Tmp3 = Node->getOperand(3);              // RHS
1229     Tmp4 = Node->getOperand(1);              // CC
1230
1231     LegalizeSetCCOperands(Tmp2, Tmp3, Tmp4);
1232     
1233     // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
1234     // the LHS is a legal SETCC itself.  In this case, we need to compare
1235     // the result against zero to select between true and false values.
1236     if (Tmp3.Val == 0) {
1237       Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
1238       Tmp4 = DAG.getCondCode(ISD::SETNE);
1239     }
1240     
1241     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp4, Tmp2, Tmp3, 
1242                                     Node->getOperand(4));
1243       
1244     switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
1245     default: assert(0 && "Unexpected action for BR_CC!");
1246     case TargetLowering::Legal: break;
1247     case TargetLowering::Custom:
1248       Tmp4 = TLI.LowerOperation(Result, DAG);
1249       if (Tmp4.Val) Result = Tmp4;
1250       break;
1251     }
1252     break;
1253   case ISD::LOAD: {
1254     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1255     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1256
1257     MVT::ValueType VT = Node->getValueType(0);
1258     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1259     Tmp3 = Result.getValue(0);
1260     Tmp4 = Result.getValue(1);
1261     
1262     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1263     default: assert(0 && "This action is not supported yet!");
1264     case TargetLowering::Legal: break;
1265     case TargetLowering::Custom:
1266       Tmp1 = TLI.LowerOperation(Tmp3, DAG);
1267       if (Tmp1.Val) {
1268         Tmp3 = LegalizeOp(Tmp1);
1269         Tmp4 = LegalizeOp(Tmp1.getValue(1));
1270       }
1271       break;
1272     case TargetLowering::Promote: {
1273       // Only promote a load of vector type to another.
1274       assert(MVT::isVector(VT) && "Cannot promote this load!");
1275       // Change base type to a different vector type.
1276       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
1277
1278       Tmp1 = DAG.getLoad(NVT, Tmp1, Tmp2, Node->getOperand(2));
1279       Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp1));
1280       Tmp4 = LegalizeOp(Tmp1.getValue(1));
1281       break;
1282     }
1283     }
1284     // Since loads produce two values, make sure to remember that we 
1285     // legalized both of them.
1286     AddLegalizedOperand(SDOperand(Node, 0), Tmp3);
1287     AddLegalizedOperand(SDOperand(Node, 1), Tmp4);
1288     return Op.ResNo ? Tmp4 : Tmp3;
1289   }
1290   case ISD::EXTLOAD:
1291   case ISD::SEXTLOAD:
1292   case ISD::ZEXTLOAD: {
1293     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1294     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1295
1296     MVT::ValueType SrcVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
1297     switch (TLI.getOperationAction(Node->getOpcode(), SrcVT)) {
1298     default: assert(0 && "This action is not supported yet!");
1299     case TargetLowering::Promote:
1300       assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
1301       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
1302                                       DAG.getValueType(MVT::i8));
1303       Tmp1 = Result.getValue(0);
1304       Tmp2 = Result.getValue(1);
1305       break;
1306     case TargetLowering::Custom:
1307       isCustom = true;
1308       // FALLTHROUGH
1309     case TargetLowering::Legal:
1310       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
1311                                       Node->getOperand(3));
1312       Tmp1 = Result.getValue(0);
1313       Tmp2 = Result.getValue(1);
1314       
1315       if (isCustom) {
1316         Tmp3 = TLI.LowerOperation(Tmp3, DAG);
1317         if (Tmp3.Val) {
1318           Tmp1 = LegalizeOp(Tmp3);
1319           Tmp2 = LegalizeOp(Tmp3.getValue(1));
1320         }
1321       }
1322       break;
1323     case TargetLowering::Expand:
1324       // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
1325       if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
1326         SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, Node->getOperand(2));
1327         Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
1328         Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
1329         Tmp2 = LegalizeOp(Load.getValue(1));
1330         break;
1331       }
1332       assert(Node->getOpcode() != ISD::EXTLOAD &&
1333              "EXTLOAD should always be supported!");
1334       // Turn the unsupported load into an EXTLOAD followed by an explicit
1335       // zero/sign extend inreg.
1336       Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
1337                               Tmp1, Tmp2, Node->getOperand(2), SrcVT);
1338       SDOperand ValRes;
1339       if (Node->getOpcode() == ISD::SEXTLOAD)
1340         ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1341                              Result, DAG.getValueType(SrcVT));
1342       else
1343         ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
1344       Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
1345       Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
1346       break;
1347     }
1348     // Since loads produce two values, make sure to remember that we legalized
1349     // both of them.
1350     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1351     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1352     return Op.ResNo ? Tmp2 : Tmp1;
1353   }
1354   case ISD::EXTRACT_ELEMENT: {
1355     MVT::ValueType OpTy = Node->getOperand(0).getValueType();
1356     switch (getTypeAction(OpTy)) {
1357     default: assert(0 && "EXTRACT_ELEMENT action for type unimplemented!");
1358     case Legal:
1359       if (cast<ConstantSDNode>(Node->getOperand(1))->getValue()) {
1360         // 1 -> Hi
1361         Result = DAG.getNode(ISD::SRL, OpTy, Node->getOperand(0),
1362                              DAG.getConstant(MVT::getSizeInBits(OpTy)/2, 
1363                                              TLI.getShiftAmountTy()));
1364         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Result);
1365       } else {
1366         // 0 -> Lo
1367         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), 
1368                              Node->getOperand(0));
1369       }
1370       break;
1371     case Expand:
1372       // Get both the low and high parts.
1373       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1374       if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
1375         Result = Tmp2;  // 1 -> Hi
1376       else
1377         Result = Tmp1;  // 0 -> Lo
1378       break;
1379     }
1380     break;
1381   }
1382
1383   case ISD::CopyToReg:
1384     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1385
1386     assert(isTypeLegal(Node->getOperand(2).getValueType()) &&
1387            "Register type must be legal!");
1388     // Legalize the incoming value (must be a legal type).
1389     Tmp2 = LegalizeOp(Node->getOperand(2));
1390     if (Node->getNumValues() == 1) {
1391       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2);
1392     } else {
1393       assert(Node->getNumValues() == 2 && "Unknown CopyToReg");
1394       if (Node->getNumOperands() == 4) {
1395         Tmp3 = LegalizeOp(Node->getOperand(3));
1396         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2,
1397                                         Tmp3);
1398       } else {
1399         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
1400       }
1401       
1402       // Since this produces two values, make sure to remember that we legalized
1403       // both of them.
1404       AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1405       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1406       return Result;
1407     }
1408     break;
1409
1410   case ISD::RET:
1411     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1412
1413     // Ensure that libcalls are emitted before a return.
1414     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1415     Tmp1 = LegalizeOp(Tmp1);
1416     LastCALLSEQ_END = DAG.getEntryNode();
1417       
1418     switch (Node->getNumOperands()) {
1419     case 2:  // ret val
1420       Tmp2 = Node->getOperand(1);
1421       switch (getTypeAction(Tmp2.getValueType())) {
1422       case Legal:
1423         Result = DAG.UpdateNodeOperands(Result, Tmp1, LegalizeOp(Tmp2));
1424         break;
1425       case Expand:
1426         if (Tmp2.getValueType() != MVT::Vector) {
1427           SDOperand Lo, Hi;
1428           ExpandOp(Tmp2, Lo, Hi);
1429           Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
1430         } else {
1431           SDNode *InVal = Tmp2.Val;
1432           unsigned NumElems =
1433             cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
1434           MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
1435           
1436           // Figure out if there is a Packed type corresponding to this Vector
1437           // type.  If so, convert to the packed type.
1438           MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
1439           if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
1440             // Turn this into a return of the packed type.
1441             Tmp2 = PackVectorOp(Tmp2, TVT);
1442             Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1443           } else if (NumElems == 1) {
1444             // Turn this into a return of the scalar type.
1445             Tmp2 = PackVectorOp(Tmp2, EVT);
1446             Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1447             
1448             // FIXME: Returns of gcc generic vectors smaller than a legal type
1449             // should be returned in integer registers!
1450             
1451             // The scalarized value type may not be legal, e.g. it might require
1452             // promotion or expansion.  Relegalize the return.
1453             Result = LegalizeOp(Result);
1454           } else {
1455             // FIXME: Returns of gcc generic vectors larger than a legal vector
1456             // type should be returned by reference!
1457             SDOperand Lo, Hi;
1458             SplitVectorOp(Tmp2, Lo, Hi);
1459             Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
1460             Result = LegalizeOp(Result);
1461           }
1462         }
1463         break;
1464       case Promote:
1465         Tmp2 = PromoteOp(Node->getOperand(1));
1466         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1467         Result = LegalizeOp(Result);
1468         break;
1469       }
1470       break;
1471     case 1:  // ret void
1472       Result = DAG.UpdateNodeOperands(Result, Tmp1);
1473       break;
1474     default: { // ret <values>
1475       std::vector<SDOperand> NewValues;
1476       NewValues.push_back(Tmp1);
1477       for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1478         switch (getTypeAction(Node->getOperand(i).getValueType())) {
1479         case Legal:
1480           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
1481           break;
1482         case Expand: {
1483           SDOperand Lo, Hi;
1484           assert(Node->getOperand(i).getValueType() != MVT::Vector &&
1485                  "FIXME: TODO: implement returning non-legal vector types!");
1486           ExpandOp(Node->getOperand(i), Lo, Hi);
1487           NewValues.push_back(Lo);
1488           NewValues.push_back(Hi);
1489           break;
1490         }
1491         case Promote:
1492           assert(0 && "Can't promote multiple return value yet!");
1493         }
1494           
1495       if (NewValues.size() == Node->getNumOperands())
1496         Result = DAG.UpdateNodeOperands(Result, NewValues);
1497       else
1498         Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
1499       break;
1500     }
1501     }
1502
1503     if (Result.getOpcode() == ISD::RET) {
1504       switch (TLI.getOperationAction(Result.getOpcode(), MVT::Other)) {
1505       default: assert(0 && "This action is not supported yet!");
1506       case TargetLowering::Legal: break;
1507       case TargetLowering::Custom:
1508         Tmp1 = TLI.LowerOperation(Result, DAG);
1509         if (Tmp1.Val) Result = Tmp1;
1510         break;
1511       }
1512     }
1513     break;
1514   case ISD::STORE: {
1515     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1516     Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1517
1518     // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
1519     // FIXME: We shouldn't do this for TargetConstantFP's.
1520     // FIXME: move this to the DAG Combiner!
1521     if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
1522       if (CFP->getValueType(0) == MVT::f32) {
1523         Tmp3 = DAG.getConstant(FloatToBits(CFP->getValue()), MVT::i32);
1524       } else {
1525         assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
1526         Tmp3 = DAG.getConstant(DoubleToBits(CFP->getValue()), MVT::i64);
1527       }
1528       Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Tmp3, Tmp2, 
1529                            Node->getOperand(3));
1530       break;
1531     }
1532
1533     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1534     case Legal: {
1535       Tmp3 = LegalizeOp(Node->getOperand(1));
1536       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
1537                                       Node->getOperand(3));
1538
1539       MVT::ValueType VT = Tmp3.getValueType();
1540       switch (TLI.getOperationAction(ISD::STORE, VT)) {
1541       default: assert(0 && "This action is not supported yet!");
1542       case TargetLowering::Legal:  break;
1543       case TargetLowering::Custom:
1544         Tmp1 = TLI.LowerOperation(Result, DAG);
1545         if (Tmp1.Val) Result = Tmp1;
1546         break;
1547       case TargetLowering::Promote:
1548         assert(MVT::isVector(VT) && "Unknown legal promote case!");
1549         Tmp3 = DAG.getNode(ISD::BIT_CONVERT, 
1550                            TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
1551         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
1552                                         Node->getOperand(3));
1553         break;
1554       }
1555       break;
1556     }
1557     case Promote:
1558       // Truncate the value and store the result.
1559       Tmp3 = PromoteOp(Node->getOperand(1));
1560       Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
1561                            Node->getOperand(3),
1562                           DAG.getValueType(Node->getOperand(1).getValueType()));
1563       break;
1564
1565     case Expand:
1566       unsigned IncrementSize = 0;
1567       SDOperand Lo, Hi;
1568       
1569       // If this is a vector type, then we have to calculate the increment as
1570       // the product of the element size in bytes, and the number of elements
1571       // in the high half of the vector.
1572       if (Node->getOperand(1).getValueType() == MVT::Vector) {
1573         SDNode *InVal = Node->getOperand(1).Val;
1574         unsigned NumElems =
1575           cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
1576         MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
1577
1578         // Figure out if there is a Packed type corresponding to this Vector
1579         // type.  If so, convert to the packed type.
1580         MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
1581         if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
1582           // Turn this into a normal store of the packed type.
1583           Tmp3 = PackVectorOp(Node->getOperand(1), TVT);
1584           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
1585                                           Node->getOperand(3));
1586           Result = LegalizeOp(Result);
1587           break;
1588         } else if (NumElems == 1) {
1589           // Turn this into a normal store of the scalar type.
1590           Tmp3 = PackVectorOp(Node->getOperand(1), EVT);
1591           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
1592                                           Node->getOperand(3));
1593           // The scalarized value type may not be legal, e.g. it might require
1594           // promotion or expansion.  Relegalize the scalar store.
1595           Result = LegalizeOp(Result);
1596           break;
1597         } else {
1598           SplitVectorOp(Node->getOperand(1), Lo, Hi);
1599           IncrementSize = NumElems/2 * MVT::getSizeInBits(EVT)/8;
1600         }
1601       } else {
1602         ExpandOp(Node->getOperand(1), Lo, Hi);
1603         IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
1604
1605         if (!TLI.isLittleEndian())
1606           std::swap(Lo, Hi);
1607       }
1608
1609       Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2,
1610                        Node->getOperand(3));
1611       Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
1612                          getIntPtrConstant(IncrementSize));
1613       assert(isTypeLegal(Tmp2.getValueType()) &&
1614              "Pointers must be legal!");
1615       // FIXME: This sets the srcvalue of both halves to be the same, which is
1616       // wrong.
1617       Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2,
1618                        Node->getOperand(3));
1619       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
1620       break;
1621     }
1622     break;
1623   }
1624   case ISD::PCMARKER:
1625     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1626     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1627     break;
1628   case ISD::STACKSAVE:
1629     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1630     Result = DAG.UpdateNodeOperands(Result, Tmp1);
1631     Tmp1 = Result.getValue(0);
1632     Tmp2 = Result.getValue(1);
1633     
1634     switch (TLI.getOperationAction(ISD::STACKSAVE, MVT::Other)) {
1635     default: assert(0 && "This action is not supported yet!");
1636     case TargetLowering::Legal: break;
1637     case TargetLowering::Custom:
1638       Tmp3 = TLI.LowerOperation(Result, DAG);
1639       if (Tmp3.Val) {
1640         Tmp1 = LegalizeOp(Tmp3);
1641         Tmp2 = LegalizeOp(Tmp3.getValue(1));
1642       }
1643       break;
1644     case TargetLowering::Expand:
1645       // Expand to CopyFromReg if the target set 
1646       // StackPointerRegisterToSaveRestore.
1647       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
1648         Tmp1 = DAG.getCopyFromReg(Result.getOperand(0), SP,
1649                                   Node->getValueType(0));
1650         Tmp2 = Tmp1.getValue(1);
1651       } else {
1652         Tmp1 = DAG.getNode(ISD::UNDEF, Node->getValueType(0));
1653         Tmp2 = Node->getOperand(0);
1654       }
1655       break;
1656     }
1657
1658     // Since stacksave produce two values, make sure to remember that we
1659     // legalized both of them.
1660     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1661     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1662     return Op.ResNo ? Tmp2 : Tmp1;
1663
1664   case ISD::STACKRESTORE:
1665     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1666     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1667     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1668       
1669     switch (TLI.getOperationAction(ISD::STACKRESTORE, MVT::Other)) {
1670     default: assert(0 && "This action is not supported yet!");
1671     case TargetLowering::Legal: break;
1672     case TargetLowering::Custom:
1673       Tmp1 = TLI.LowerOperation(Result, DAG);
1674       if (Tmp1.Val) Result = Tmp1;
1675       break;
1676     case TargetLowering::Expand:
1677       // Expand to CopyToReg if the target set 
1678       // StackPointerRegisterToSaveRestore.
1679       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
1680         Result = DAG.getCopyToReg(Tmp1, SP, Tmp2);
1681       } else {
1682         Result = Tmp1;
1683       }
1684       break;
1685     }
1686     break;
1687
1688   case ISD::READCYCLECOUNTER:
1689     Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
1690     Result = DAG.UpdateNodeOperands(Result, Tmp1);
1691
1692     // Since rdcc produce two values, make sure to remember that we legalized
1693     // both of them.
1694     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1695     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1696     return Result;
1697
1698   case ISD::TRUNCSTORE: {
1699     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1700     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1701
1702     assert(isTypeLegal(Node->getOperand(1).getValueType()) &&
1703            "Cannot handle illegal TRUNCSTORE yet!");
1704     Tmp2 = LegalizeOp(Node->getOperand(1));
1705     
1706     // The only promote case we handle is TRUNCSTORE:i1 X into
1707     //   -> TRUNCSTORE:i8 (and X, 1)
1708     if (cast<VTSDNode>(Node->getOperand(4))->getVT() == MVT::i1 &&
1709         TLI.getOperationAction(ISD::TRUNCSTORE, MVT::i1) == 
1710               TargetLowering::Promote) {
1711       // Promote the bool to a mask then store.
1712       Tmp2 = DAG.getNode(ISD::AND, Tmp2.getValueType(), Tmp2,
1713                          DAG.getConstant(1, Tmp2.getValueType()));
1714       Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
1715                            Node->getOperand(3), DAG.getValueType(MVT::i8));
1716
1717     } else if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1718                Tmp3 != Node->getOperand(2)) {
1719       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
1720                                       Node->getOperand(3), Node->getOperand(4));
1721     }
1722
1723     MVT::ValueType StVT = cast<VTSDNode>(Result.Val->getOperand(4))->getVT();
1724     switch (TLI.getOperationAction(Result.Val->getOpcode(), StVT)) {
1725     default: assert(0 && "This action is not supported yet!");
1726     case TargetLowering::Legal: break;
1727     case TargetLowering::Custom:
1728       Tmp1 = TLI.LowerOperation(Result, DAG);
1729       if (Tmp1.Val) Result = Tmp1;
1730       break;
1731     }
1732     break;
1733   }
1734   case ISD::SELECT:
1735     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1736     case Expand: assert(0 && "It's impossible to expand bools");
1737     case Legal:
1738       Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1739       break;
1740     case Promote:
1741       Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
1742       break;
1743     }
1744     Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
1745     Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
1746
1747     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1748       
1749     switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
1750     default: assert(0 && "This action is not supported yet!");
1751     case TargetLowering::Legal: break;
1752     case TargetLowering::Custom: {
1753       Tmp1 = TLI.LowerOperation(Result, DAG);
1754       if (Tmp1.Val) Result = Tmp1;
1755       break;
1756     }
1757     case TargetLowering::Expand:
1758       if (Tmp1.getOpcode() == ISD::SETCC) {
1759         Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1), 
1760                               Tmp2, Tmp3,
1761                               cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
1762       } else {
1763         // Make sure the condition is either zero or one.  It may have been
1764         // promoted from something else.
1765         unsigned NumBits = MVT::getSizeInBits(Tmp1.getValueType());
1766         if (!TLI.MaskedValueIsZero(Tmp1, (~0ULL >> (64-NumBits))^1))
1767           Tmp1 = DAG.getZeroExtendInReg(Tmp1, MVT::i1);
1768         Result = DAG.getSelectCC(Tmp1, 
1769                                  DAG.getConstant(0, Tmp1.getValueType()),
1770                                  Tmp2, Tmp3, ISD::SETNE);
1771       }
1772       break;
1773     case TargetLowering::Promote: {
1774       MVT::ValueType NVT =
1775         TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
1776       unsigned ExtOp, TruncOp;
1777       if (MVT::isVector(Tmp2.getValueType())) {
1778         ExtOp   = ISD::BIT_CONVERT;
1779         TruncOp = ISD::BIT_CONVERT;
1780       } else if (MVT::isInteger(Tmp2.getValueType())) {
1781         ExtOp   = ISD::ANY_EXTEND;
1782         TruncOp = ISD::TRUNCATE;
1783       } else {
1784         ExtOp   = ISD::FP_EXTEND;
1785         TruncOp = ISD::FP_ROUND;
1786       }
1787       // Promote each of the values to the new type.
1788       Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
1789       Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
1790       // Perform the larger operation, then round down.
1791       Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
1792       Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
1793       break;
1794     }
1795     }
1796     break;
1797   case ISD::SELECT_CC: {
1798     Tmp1 = Node->getOperand(0);               // LHS
1799     Tmp2 = Node->getOperand(1);               // RHS
1800     Tmp3 = LegalizeOp(Node->getOperand(2));   // True
1801     Tmp4 = LegalizeOp(Node->getOperand(3));   // False
1802     SDOperand CC = Node->getOperand(4);
1803     
1804     LegalizeSetCCOperands(Tmp1, Tmp2, CC);
1805     
1806     // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
1807     // the LHS is a legal SETCC itself.  In this case, we need to compare
1808     // the result against zero to select between true and false values.
1809     if (Tmp2.Val == 0) {
1810       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
1811       CC = DAG.getCondCode(ISD::SETNE);
1812     }
1813     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, CC);
1814
1815     // Everything is legal, see if we should expand this op or something.
1816     switch (TLI.getOperationAction(ISD::SELECT_CC, Tmp3.getValueType())) {
1817     default: assert(0 && "This action is not supported yet!");
1818     case TargetLowering::Legal: break;
1819     case TargetLowering::Custom:
1820       Tmp1 = TLI.LowerOperation(Result, DAG);
1821       if (Tmp1.Val) Result = Tmp1;
1822       break;
1823     }
1824     break;
1825   }
1826   case ISD::SETCC:
1827     Tmp1 = Node->getOperand(0);
1828     Tmp2 = Node->getOperand(1);
1829     Tmp3 = Node->getOperand(2);
1830     LegalizeSetCCOperands(Tmp1, Tmp2, Tmp3);
1831     
1832     // If we had to Expand the SetCC operands into a SELECT node, then it may 
1833     // not always be possible to return a true LHS & RHS.  In this case, just 
1834     // return the value we legalized, returned in the LHS
1835     if (Tmp2.Val == 0) {
1836       Result = Tmp1;
1837       break;
1838     }
1839
1840     switch (TLI.getOperationAction(ISD::SETCC, Tmp1.getValueType())) {
1841     default: assert(0 && "Cannot handle this action for SETCC yet!");
1842     case TargetLowering::Custom:
1843       isCustom = true;
1844       // FALLTHROUGH.
1845     case TargetLowering::Legal:
1846       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1847       if (isCustom) {
1848         Tmp3 = TLI.LowerOperation(Result, DAG);
1849         if (Tmp3.Val) Result = Tmp3;
1850       }
1851       break;
1852     case TargetLowering::Promote: {
1853       // First step, figure out the appropriate operation to use.
1854       // Allow SETCC to not be supported for all legal data types
1855       // Mostly this targets FP
1856       MVT::ValueType NewInTy = Node->getOperand(0).getValueType();
1857       MVT::ValueType OldVT = NewInTy;
1858
1859       // Scan for the appropriate larger type to use.
1860       while (1) {
1861         NewInTy = (MVT::ValueType)(NewInTy+1);
1862
1863         assert(MVT::isInteger(NewInTy) == MVT::isInteger(OldVT) &&
1864                "Fell off of the edge of the integer world");
1865         assert(MVT::isFloatingPoint(NewInTy) == MVT::isFloatingPoint(OldVT) &&
1866                "Fell off of the edge of the floating point world");
1867           
1868         // If the target supports SETCC of this type, use it.
1869         if (TLI.isOperationLegal(ISD::SETCC, NewInTy))
1870           break;
1871       }
1872       if (MVT::isInteger(NewInTy))
1873         assert(0 && "Cannot promote Legal Integer SETCC yet");
1874       else {
1875         Tmp1 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp1);
1876         Tmp2 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp2);
1877       }
1878       Tmp1 = LegalizeOp(Tmp1);
1879       Tmp2 = LegalizeOp(Tmp2);
1880       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1881       Result = LegalizeOp(Result);
1882       break;
1883     }
1884     case TargetLowering::Expand:
1885       // Expand a setcc node into a select_cc of the same condition, lhs, and
1886       // rhs that selects between const 1 (true) and const 0 (false).
1887       MVT::ValueType VT = Node->getValueType(0);
1888       Result = DAG.getNode(ISD::SELECT_CC, VT, Tmp1, Tmp2, 
1889                            DAG.getConstant(1, VT), DAG.getConstant(0, VT),
1890                            Node->getOperand(2));
1891       break;
1892     }
1893     break;
1894   case ISD::MEMSET:
1895   case ISD::MEMCPY:
1896   case ISD::MEMMOVE: {
1897     Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
1898     Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
1899
1900     if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
1901       switch (getTypeAction(Node->getOperand(2).getValueType())) {
1902       case Expand: assert(0 && "Cannot expand a byte!");
1903       case Legal:
1904         Tmp3 = LegalizeOp(Node->getOperand(2));
1905         break;
1906       case Promote:
1907         Tmp3 = PromoteOp(Node->getOperand(2));
1908         break;
1909       }
1910     } else {
1911       Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
1912     }
1913
1914     SDOperand Tmp4;
1915     switch (getTypeAction(Node->getOperand(3).getValueType())) {
1916     case Expand: {
1917       // Length is too big, just take the lo-part of the length.
1918       SDOperand HiPart;
1919       ExpandOp(Node->getOperand(3), HiPart, Tmp4);
1920       break;
1921     }
1922     case Legal:
1923       Tmp4 = LegalizeOp(Node->getOperand(3));
1924       break;
1925     case Promote:
1926       Tmp4 = PromoteOp(Node->getOperand(3));
1927       break;
1928     }
1929
1930     SDOperand Tmp5;
1931     switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
1932     case Expand: assert(0 && "Cannot expand this yet!");
1933     case Legal:
1934       Tmp5 = LegalizeOp(Node->getOperand(4));
1935       break;
1936     case Promote:
1937       Tmp5 = PromoteOp(Node->getOperand(4));
1938       break;
1939     }
1940
1941     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1942     default: assert(0 && "This action not implemented for this operation!");
1943     case TargetLowering::Custom:
1944       isCustom = true;
1945       // FALLTHROUGH
1946     case TargetLowering::Legal:
1947       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, Tmp5);
1948       if (isCustom) {
1949         Tmp1 = TLI.LowerOperation(Result, DAG);
1950         if (Tmp1.Val) Result = Tmp1;
1951       }
1952       break;
1953     case TargetLowering::Expand: {
1954       // Otherwise, the target does not support this operation.  Lower the
1955       // operation to an explicit libcall as appropriate.
1956       MVT::ValueType IntPtr = TLI.getPointerTy();
1957       const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
1958       std::vector<std::pair<SDOperand, const Type*> > Args;
1959
1960       const char *FnName = 0;
1961       if (Node->getOpcode() == ISD::MEMSET) {
1962         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1963         // Extend the (previously legalized) ubyte argument to be an int value
1964         // for the call.
1965         if (Tmp3.getValueType() > MVT::i32)
1966           Tmp3 = DAG.getNode(ISD::TRUNCATE, MVT::i32, Tmp3);
1967         else
1968           Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
1969         Args.push_back(std::make_pair(Tmp3, Type::IntTy));
1970         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1971
1972         FnName = "memset";
1973       } else if (Node->getOpcode() == ISD::MEMCPY ||
1974                  Node->getOpcode() == ISD::MEMMOVE) {
1975         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1976         Args.push_back(std::make_pair(Tmp3, IntPtrTy));
1977         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1978         FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
1979       } else {
1980         assert(0 && "Unknown op!");
1981       }
1982
1983       std::pair<SDOperand,SDOperand> CallResult =
1984         TLI.LowerCallTo(Tmp1, Type::VoidTy, false, CallingConv::C, false,
1985                         DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
1986       Result = CallResult.second;
1987       break;
1988     }
1989     }
1990     break;
1991   }
1992
1993   case ISD::SHL_PARTS:
1994   case ISD::SRA_PARTS:
1995   case ISD::SRL_PARTS: {
1996     std::vector<SDOperand> Ops;
1997     bool Changed = false;
1998     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1999       Ops.push_back(LegalizeOp(Node->getOperand(i)));
2000       Changed |= Ops.back() != Node->getOperand(i);
2001     }
2002     if (Changed)
2003       Result = DAG.UpdateNodeOperands(Result, Ops);
2004
2005     switch (TLI.getOperationAction(Node->getOpcode(),
2006                                    Node->getValueType(0))) {
2007     default: assert(0 && "This action is not supported yet!");
2008     case TargetLowering::Legal: break;
2009     case TargetLowering::Custom:
2010       Tmp1 = TLI.LowerOperation(Result, DAG);
2011       if (Tmp1.Val) {
2012         SDOperand Tmp2, RetVal(0, 0);
2013         for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
2014           Tmp2 = LegalizeOp(Tmp1.getValue(i));
2015           AddLegalizedOperand(SDOperand(Node, i), Tmp2);
2016           if (i == Op.ResNo)
2017             RetVal = Tmp2;
2018         }
2019         assert(RetVal.Val && "Illegal result number");
2020         return RetVal;
2021       }
2022       break;
2023     }
2024
2025     // Since these produce multiple values, make sure to remember that we
2026     // legalized all of them.
2027     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
2028       AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
2029     return Result.getValue(Op.ResNo);
2030   }
2031
2032     // Binary operators
2033   case ISD::ADD:
2034   case ISD::SUB:
2035   case ISD::MUL:
2036   case ISD::MULHS:
2037   case ISD::MULHU:
2038   case ISD::UDIV:
2039   case ISD::SDIV:
2040   case ISD::AND:
2041   case ISD::OR:
2042   case ISD::XOR:
2043   case ISD::SHL:
2044   case ISD::SRL:
2045   case ISD::SRA:
2046   case ISD::FADD:
2047   case ISD::FSUB:
2048   case ISD::FMUL:
2049   case ISD::FDIV:
2050     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2051     switch (getTypeAction(Node->getOperand(1).getValueType())) {
2052     case Expand: assert(0 && "Not possible");
2053     case Legal:
2054       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
2055       break;
2056     case Promote:
2057       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
2058       break;
2059     }
2060     
2061     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2062       
2063     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2064     default: assert(0 && "BinOp legalize operation not supported");
2065     case TargetLowering::Legal: break;
2066     case TargetLowering::Custom:
2067       Tmp1 = TLI.LowerOperation(Result, DAG);
2068       if (Tmp1.Val) Result = Tmp1;
2069       break;
2070     case TargetLowering::Expand: {
2071       assert(MVT::isVector(Node->getValueType(0)) &&
2072              "Cannot expand this binary operator!");
2073       // Expand the operation into a bunch of nasty scalar code.
2074       std::vector<SDOperand> Ops;
2075       MVT::ValueType EltVT = MVT::getVectorBaseType(Node->getValueType(0));
2076       MVT::ValueType PtrVT = TLI.getPointerTy();
2077       for (unsigned i = 0, e = MVT::getVectorNumElements(Node->getValueType(0));
2078            i != e; ++i) {
2079         SDOperand Idx = DAG.getConstant(i, PtrVT);
2080         SDOperand LHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1, Idx);
2081         SDOperand RHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2, Idx);
2082         Ops.push_back(DAG.getNode(Node->getOpcode(), EltVT, LHS, RHS));
2083       }
2084       Result = DAG.getNode(ISD::BUILD_VECTOR, Node->getValueType(0), Ops);
2085       break;
2086     }
2087     case TargetLowering::Promote: {
2088       switch (Node->getOpcode()) {
2089       default:  assert(0 && "Do not know how to promote this BinOp!");
2090       case ISD::AND:
2091       case ISD::OR:
2092       case ISD::XOR: {
2093         MVT::ValueType OVT = Node->getValueType(0);
2094         MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2095         assert(MVT::isVector(OVT) && "Cannot promote this BinOp!");
2096         // Bit convert each of the values to the new type.
2097         Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
2098         Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
2099         Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2100         // Bit convert the result back the original type.
2101         Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
2102         break;
2103       }
2104       }
2105     }
2106     }
2107     break;
2108     
2109   case ISD::FCOPYSIGN:  // FCOPYSIGN does not require LHS/RHS to match type!
2110     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2111     switch (getTypeAction(Node->getOperand(1).getValueType())) {
2112       case Expand: assert(0 && "Not possible");
2113       case Legal:
2114         Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
2115         break;
2116       case Promote:
2117         Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
2118         break;
2119     }
2120       
2121     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2122     
2123     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2124     default: assert(0 && "Operation not supported");
2125     case TargetLowering::Custom:
2126       Tmp1 = TLI.LowerOperation(Result, DAG);
2127       if (Tmp1.Val) Result = Tmp1;
2128       break;
2129     case TargetLowering::Legal: break;
2130     case TargetLowering::Expand:
2131       // If this target supports fabs/fneg natively, do this efficiently.
2132       if (TLI.isOperationLegal(ISD::FABS, Tmp1.getValueType()) &&
2133           TLI.isOperationLegal(ISD::FNEG, Tmp1.getValueType())) {
2134         // Get the sign bit of the RHS.
2135         MVT::ValueType IVT = 
2136           Tmp2.getValueType() == MVT::f32 ? MVT::i32 : MVT::i64;
2137         SDOperand SignBit = DAG.getNode(ISD::BIT_CONVERT, IVT, Tmp2);
2138         SignBit = DAG.getSetCC(TLI.getSetCCResultTy(),
2139                                SignBit, DAG.getConstant(0, IVT), ISD::SETLT);
2140         // Get the absolute value of the result.
2141         SDOperand AbsVal = DAG.getNode(ISD::FABS, Tmp1.getValueType(), Tmp1);
2142         // Select between the nabs and abs value based on the sign bit of
2143         // the input.
2144         Result = DAG.getNode(ISD::SELECT, AbsVal.getValueType(), SignBit,
2145                              DAG.getNode(ISD::FNEG, AbsVal.getValueType(), 
2146                                          AbsVal),
2147                              AbsVal);
2148         Result = LegalizeOp(Result);
2149         break;
2150       }
2151       
2152       // Otherwise, do bitwise ops!
2153       
2154       // copysign -> copysignf/copysign libcall.
2155       const char *FnName;
2156       if (Node->getValueType(0) == MVT::f32) {
2157         FnName = "copysignf";
2158         if (Tmp2.getValueType() != MVT::f32)  // Force operands to match type.
2159           Result = DAG.UpdateNodeOperands(Result, Tmp1, 
2160                                     DAG.getNode(ISD::FP_ROUND, MVT::f32, Tmp2));
2161       } else {
2162         FnName = "copysign";
2163         if (Tmp2.getValueType() != MVT::f64)  // Force operands to match type.
2164           Result = DAG.UpdateNodeOperands(Result, Tmp1, 
2165                                    DAG.getNode(ISD::FP_EXTEND, MVT::f64, Tmp2));
2166       }
2167       SDOperand Dummy;
2168       Result = ExpandLibCall(FnName, Node, Dummy);
2169       break;
2170     }
2171     break;
2172     
2173   case ISD::ADDC:
2174   case ISD::SUBC:
2175     Tmp1 = LegalizeOp(Node->getOperand(0));
2176     Tmp2 = LegalizeOp(Node->getOperand(1));
2177     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2178     // Since this produces two values, make sure to remember that we legalized
2179     // both of them.
2180     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2181     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2182     return Result;
2183
2184   case ISD::ADDE:
2185   case ISD::SUBE:
2186     Tmp1 = LegalizeOp(Node->getOperand(0));
2187     Tmp2 = LegalizeOp(Node->getOperand(1));
2188     Tmp3 = LegalizeOp(Node->getOperand(2));
2189     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2190     // Since this produces two values, make sure to remember that we legalized
2191     // both of them.
2192     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2193     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2194     return Result;
2195     
2196   case ISD::BUILD_PAIR: {
2197     MVT::ValueType PairTy = Node->getValueType(0);
2198     // TODO: handle the case where the Lo and Hi operands are not of legal type
2199     Tmp1 = LegalizeOp(Node->getOperand(0));   // Lo
2200     Tmp2 = LegalizeOp(Node->getOperand(1));   // Hi
2201     switch (TLI.getOperationAction(ISD::BUILD_PAIR, PairTy)) {
2202     case TargetLowering::Promote:
2203     case TargetLowering::Custom:
2204       assert(0 && "Cannot promote/custom this yet!");
2205     case TargetLowering::Legal:
2206       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
2207         Result = DAG.getNode(ISD::BUILD_PAIR, PairTy, Tmp1, Tmp2);
2208       break;
2209     case TargetLowering::Expand:
2210       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, PairTy, Tmp1);
2211       Tmp2 = DAG.getNode(ISD::ANY_EXTEND, PairTy, Tmp2);
2212       Tmp2 = DAG.getNode(ISD::SHL, PairTy, Tmp2,
2213                          DAG.getConstant(MVT::getSizeInBits(PairTy)/2, 
2214                                          TLI.getShiftAmountTy()));
2215       Result = DAG.getNode(ISD::OR, PairTy, Tmp1, Tmp2);
2216       break;
2217     }
2218     break;
2219   }
2220
2221   case ISD::UREM:
2222   case ISD::SREM:
2223   case ISD::FREM:
2224     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2225     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2226
2227     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2228     case TargetLowering::Promote: assert(0 && "Cannot promote this yet!");
2229     case TargetLowering::Custom:
2230       isCustom = true;
2231       // FALLTHROUGH
2232     case TargetLowering::Legal:
2233       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2234       if (isCustom) {
2235         Tmp1 = TLI.LowerOperation(Result, DAG);
2236         if (Tmp1.Val) Result = Tmp1;
2237       }
2238       break;
2239     case TargetLowering::Expand:
2240       if (MVT::isInteger(Node->getValueType(0))) {
2241         // X % Y -> X-X/Y*Y
2242         MVT::ValueType VT = Node->getValueType(0);
2243         unsigned Opc = Node->getOpcode() == ISD::UREM ? ISD::UDIV : ISD::SDIV;
2244         Result = DAG.getNode(Opc, VT, Tmp1, Tmp2);
2245         Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
2246         Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
2247       } else {
2248         // Floating point mod -> fmod libcall.
2249         const char *FnName = Node->getValueType(0) == MVT::f32 ? "fmodf":"fmod";
2250         SDOperand Dummy;
2251         Result = ExpandLibCall(FnName, Node, Dummy);
2252       }
2253       break;
2254     }
2255     break;
2256   case ISD::VAARG: {
2257     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2258     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2259
2260     MVT::ValueType VT = Node->getValueType(0);
2261     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
2262     default: assert(0 && "This action is not supported yet!");
2263     case TargetLowering::Custom:
2264       isCustom = true;
2265       // FALLTHROUGH
2266     case TargetLowering::Legal:
2267       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2268       Result = Result.getValue(0);
2269       Tmp1 = Result.getValue(1);
2270
2271       if (isCustom) {
2272         Tmp2 = TLI.LowerOperation(Result, DAG);
2273         if (Tmp2.Val) {
2274           Result = LegalizeOp(Tmp2);
2275           Tmp1 = LegalizeOp(Tmp2.getValue(1));
2276         }
2277       }
2278       break;
2279     case TargetLowering::Expand: {
2280       SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
2281                                      Node->getOperand(2));
2282       // Increment the pointer, VAList, to the next vaarg
2283       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList, 
2284                          DAG.getConstant(MVT::getSizeInBits(VT)/8, 
2285                                          TLI.getPointerTy()));
2286       // Store the incremented VAList to the legalized pointer
2287       Tmp3 = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), Tmp3, Tmp2, 
2288                          Node->getOperand(2));
2289       // Load the actual argument out of the pointer VAList
2290       Result = DAG.getLoad(VT, Tmp3, VAList, DAG.getSrcValue(0));
2291       Tmp1 = LegalizeOp(Result.getValue(1));
2292       Result = LegalizeOp(Result);
2293       break;
2294     }
2295     }
2296     // Since VAARG produces two values, make sure to remember that we 
2297     // legalized both of them.
2298     AddLegalizedOperand(SDOperand(Node, 0), Result);
2299     AddLegalizedOperand(SDOperand(Node, 1), Tmp1);
2300     return Op.ResNo ? Tmp1 : Result;
2301   }
2302     
2303   case ISD::VACOPY: 
2304     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2305     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the dest pointer.
2306     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the source pointer.
2307
2308     switch (TLI.getOperationAction(ISD::VACOPY, MVT::Other)) {
2309     default: assert(0 && "This action is not supported yet!");
2310     case TargetLowering::Custom:
2311       isCustom = true;
2312       // FALLTHROUGH
2313     case TargetLowering::Legal:
2314       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
2315                                       Node->getOperand(3), Node->getOperand(4));
2316       if (isCustom) {
2317         Tmp1 = TLI.LowerOperation(Result, DAG);
2318         if (Tmp1.Val) Result = Tmp1;
2319       }
2320       break;
2321     case TargetLowering::Expand:
2322       // This defaults to loading a pointer from the input and storing it to the
2323       // output, returning the chain.
2324       Tmp4 = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp3, Node->getOperand(3));
2325       Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp4.getValue(1), Tmp4, Tmp2,
2326                            Node->getOperand(4));
2327       break;
2328     }
2329     break;
2330
2331   case ISD::VAEND: 
2332     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2333     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2334
2335     switch (TLI.getOperationAction(ISD::VAEND, MVT::Other)) {
2336     default: assert(0 && "This action is not supported yet!");
2337     case TargetLowering::Custom:
2338       isCustom = true;
2339       // FALLTHROUGH
2340     case TargetLowering::Legal:
2341       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2342       if (isCustom) {
2343         Tmp1 = TLI.LowerOperation(Tmp1, DAG);
2344         if (Tmp1.Val) Result = Tmp1;
2345       }
2346       break;
2347     case TargetLowering::Expand:
2348       Result = Tmp1; // Default to a no-op, return the chain
2349       break;
2350     }
2351     break;
2352     
2353   case ISD::VASTART: 
2354     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2355     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2356
2357     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2358     
2359     switch (TLI.getOperationAction(ISD::VASTART, MVT::Other)) {
2360     default: assert(0 && "This action is not supported yet!");
2361     case TargetLowering::Legal: break;
2362     case TargetLowering::Custom:
2363       Tmp1 = TLI.LowerOperation(Result, DAG);
2364       if (Tmp1.Val) Result = Tmp1;
2365       break;
2366     }
2367     break;
2368     
2369   case ISD::ROTL:
2370   case ISD::ROTR:
2371     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2372     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2373     
2374     assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
2375            "Cannot handle this yet!");
2376     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2377     break;
2378     
2379   case ISD::BSWAP:
2380     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2381     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2382     case TargetLowering::Custom:
2383       assert(0 && "Cannot custom legalize this yet!");
2384     case TargetLowering::Legal:
2385       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2386       break;
2387     case TargetLowering::Promote: {
2388       MVT::ValueType OVT = Tmp1.getValueType();
2389       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2390       unsigned DiffBits = getSizeInBits(NVT) - getSizeInBits(OVT);
2391
2392       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2393       Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
2394       Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
2395                            DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
2396       break;
2397     }
2398     case TargetLowering::Expand:
2399       Result = ExpandBSWAP(Tmp1);
2400       break;
2401     }
2402     break;
2403     
2404   case ISD::CTPOP:
2405   case ISD::CTTZ:
2406   case ISD::CTLZ:
2407     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2408     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2409     case TargetLowering::Custom: assert(0 && "Cannot custom handle this yet!");
2410     case TargetLowering::Legal:
2411       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2412       break;
2413     case TargetLowering::Promote: {
2414       MVT::ValueType OVT = Tmp1.getValueType();
2415       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2416
2417       // Zero extend the argument.
2418       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2419       // Perform the larger operation, then subtract if needed.
2420       Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2421       switch (Node->getOpcode()) {
2422       case ISD::CTPOP:
2423         Result = Tmp1;
2424         break;
2425       case ISD::CTTZ:
2426         //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2427         Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
2428                             DAG.getConstant(getSizeInBits(NVT), NVT),
2429                             ISD::SETEQ);
2430         Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
2431                            DAG.getConstant(getSizeInBits(OVT),NVT), Tmp1);
2432         break;
2433       case ISD::CTLZ:
2434         // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2435         Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
2436                              DAG.getConstant(getSizeInBits(NVT) -
2437                                              getSizeInBits(OVT), NVT));
2438         break;
2439       }
2440       break;
2441     }
2442     case TargetLowering::Expand:
2443       Result = ExpandBitCount(Node->getOpcode(), Tmp1);
2444       break;
2445     }
2446     break;
2447
2448     // Unary operators
2449   case ISD::FABS:
2450   case ISD::FNEG:
2451   case ISD::FSQRT:
2452   case ISD::FSIN:
2453   case ISD::FCOS:
2454     Tmp1 = LegalizeOp(Node->getOperand(0));
2455     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2456     case TargetLowering::Promote:
2457     case TargetLowering::Custom:
2458      isCustom = true;
2459      // FALLTHROUGH
2460     case TargetLowering::Legal:
2461       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2462       if (isCustom) {
2463         Tmp1 = TLI.LowerOperation(Result, DAG);
2464         if (Tmp1.Val) Result = Tmp1;
2465       }
2466       break;
2467     case TargetLowering::Expand:
2468       switch (Node->getOpcode()) {
2469       default: assert(0 && "Unreachable!");
2470       case ISD::FNEG:
2471         // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
2472         Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2473         Result = DAG.getNode(ISD::FSUB, Node->getValueType(0), Tmp2, Tmp1);
2474         break;
2475       case ISD::FABS: {
2476         // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2477         MVT::ValueType VT = Node->getValueType(0);
2478         Tmp2 = DAG.getConstantFP(0.0, VT);
2479         Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1, Tmp2, ISD::SETUGT);
2480         Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
2481         Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
2482         break;
2483       }
2484       case ISD::FSQRT:
2485       case ISD::FSIN:
2486       case ISD::FCOS: {
2487         MVT::ValueType VT = Node->getValueType(0);
2488         const char *FnName = 0;
2489         switch(Node->getOpcode()) {
2490         case ISD::FSQRT: FnName = VT == MVT::f32 ? "sqrtf" : "sqrt"; break;
2491         case ISD::FSIN:  FnName = VT == MVT::f32 ? "sinf"  : "sin"; break;
2492         case ISD::FCOS:  FnName = VT == MVT::f32 ? "cosf"  : "cos"; break;
2493         default: assert(0 && "Unreachable!");
2494         }
2495         SDOperand Dummy;
2496         Result = ExpandLibCall(FnName, Node, Dummy);
2497         break;
2498       }
2499       }
2500       break;
2501     }
2502     break;
2503     
2504   case ISD::BIT_CONVERT:
2505     if (!isTypeLegal(Node->getOperand(0).getValueType())) {
2506       Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2507     } else {
2508       switch (TLI.getOperationAction(ISD::BIT_CONVERT,
2509                                      Node->getOperand(0).getValueType())) {
2510       default: assert(0 && "Unknown operation action!");
2511       case TargetLowering::Expand:
2512         Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2513         break;
2514       case TargetLowering::Legal:
2515         Tmp1 = LegalizeOp(Node->getOperand(0));
2516         Result = DAG.UpdateNodeOperands(Result, Tmp1);
2517         break;
2518       }
2519     }
2520     break;
2521   case ISD::VBIT_CONVERT: {
2522     assert(Op.getOperand(0).getValueType() == MVT::Vector &&
2523            "Can only have VBIT_CONVERT where input or output is MVT::Vector!");
2524     
2525     // The input has to be a vector type, we have to either scalarize it, pack
2526     // it, or convert it based on whether the input vector type is legal.
2527     SDNode *InVal = Node->getOperand(0).Val;
2528     unsigned NumElems =
2529       cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
2530     MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
2531     
2532     // Figure out if there is a Packed type corresponding to this Vector
2533     // type.  If so, convert to the packed type.
2534     MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
2535     if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
2536       // Turn this into a bit convert of the packed input.
2537       Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), 
2538                            PackVectorOp(Node->getOperand(0), TVT));
2539       break;
2540     } else if (NumElems == 1) {
2541       // Turn this into a bit convert of the scalar input.
2542       Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), 
2543                            PackVectorOp(Node->getOperand(0), EVT));
2544       break;
2545     } else {
2546       // FIXME: UNIMP!  Store then reload
2547       assert(0 && "Cast from unsupported vector type not implemented yet!");
2548     }
2549   }
2550       
2551     // Conversion operators.  The source and destination have different types.
2552   case ISD::SINT_TO_FP:
2553   case ISD::UINT_TO_FP: {
2554     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
2555     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2556     case Legal:
2557       switch (TLI.getOperationAction(Node->getOpcode(),
2558                                      Node->getOperand(0).getValueType())) {
2559       default: assert(0 && "Unknown operation action!");
2560       case TargetLowering::Custom:
2561         isCustom = true;
2562         // FALLTHROUGH
2563       case TargetLowering::Legal:
2564         Tmp1 = LegalizeOp(Node->getOperand(0));
2565         Result = DAG.UpdateNodeOperands(Result, Tmp1);
2566         if (isCustom) {
2567           Tmp1 = TLI.LowerOperation(Result, DAG);
2568           if (Tmp1.Val) Result = Tmp1;
2569         }
2570         break;
2571       case TargetLowering::Expand:
2572         Result = ExpandLegalINT_TO_FP(isSigned,
2573                                       LegalizeOp(Node->getOperand(0)),
2574                                       Node->getValueType(0));
2575         break;
2576       case TargetLowering::Promote:
2577         Result = PromoteLegalINT_TO_FP(LegalizeOp(Node->getOperand(0)),
2578                                        Node->getValueType(0),
2579                                        isSigned);
2580         break;
2581       }
2582       break;
2583     case Expand:
2584       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
2585                              Node->getValueType(0), Node->getOperand(0));
2586       break;
2587     case Promote:
2588       Tmp1 = PromoteOp(Node->getOperand(0));
2589       if (isSigned) {
2590         Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp1.getValueType(),
2591                  Tmp1, DAG.getValueType(Node->getOperand(0).getValueType()));
2592       } else {
2593         Tmp1 = DAG.getZeroExtendInReg(Tmp1,
2594                                       Node->getOperand(0).getValueType());
2595       }
2596       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2597       Result = LegalizeOp(Result);  // The 'op' is not necessarily legal!
2598       break;
2599     }
2600     break;
2601   }
2602   case ISD::TRUNCATE:
2603     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2604     case Legal:
2605       Tmp1 = LegalizeOp(Node->getOperand(0));
2606       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2607       break;
2608     case Expand:
2609       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2610
2611       // Since the result is legal, we should just be able to truncate the low
2612       // part of the source.
2613       Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
2614       break;
2615     case Promote:
2616       Result = PromoteOp(Node->getOperand(0));
2617       Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
2618       break;
2619     }
2620     break;
2621
2622   case ISD::FP_TO_SINT:
2623   case ISD::FP_TO_UINT:
2624     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2625     case Legal:
2626       Tmp1 = LegalizeOp(Node->getOperand(0));
2627
2628       switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
2629       default: assert(0 && "Unknown operation action!");
2630       case TargetLowering::Custom:
2631         isCustom = true;
2632         // FALLTHROUGH
2633       case TargetLowering::Legal:
2634         Result = DAG.UpdateNodeOperands(Result, Tmp1);
2635         if (isCustom) {
2636           Tmp1 = TLI.LowerOperation(Result, DAG);
2637           if (Tmp1.Val) Result = Tmp1;
2638         }
2639         break;
2640       case TargetLowering::Promote:
2641         Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
2642                                        Node->getOpcode() == ISD::FP_TO_SINT);
2643         break;
2644       case TargetLowering::Expand:
2645         if (Node->getOpcode() == ISD::FP_TO_UINT) {
2646           SDOperand True, False;
2647           MVT::ValueType VT =  Node->getOperand(0).getValueType();
2648           MVT::ValueType NVT = Node->getValueType(0);
2649           unsigned ShiftAmt = MVT::getSizeInBits(Node->getValueType(0))-1;
2650           Tmp2 = DAG.getConstantFP((double)(1ULL << ShiftAmt), VT);
2651           Tmp3 = DAG.getSetCC(TLI.getSetCCResultTy(),
2652                             Node->getOperand(0), Tmp2, ISD::SETLT);
2653           True = DAG.getNode(ISD::FP_TO_SINT, NVT, Node->getOperand(0));
2654           False = DAG.getNode(ISD::FP_TO_SINT, NVT,
2655                               DAG.getNode(ISD::FSUB, VT, Node->getOperand(0),
2656                                           Tmp2));
2657           False = DAG.getNode(ISD::XOR, NVT, False, 
2658                               DAG.getConstant(1ULL << ShiftAmt, NVT));
2659           Result = DAG.getNode(ISD::SELECT, NVT, Tmp3, True, False);
2660           break;
2661         } else {
2662           assert(0 && "Do not know how to expand FP_TO_SINT yet!");
2663         }
2664         break;
2665       }
2666       break;
2667     case Expand:
2668       assert(0 && "Shouldn't need to expand other operators here!");
2669     case Promote:
2670       Tmp1 = PromoteOp(Node->getOperand(0));
2671       Result = DAG.UpdateNodeOperands(Result, LegalizeOp(Tmp1));
2672       Result = LegalizeOp(Result);
2673       break;
2674     }
2675     break;
2676
2677   case ISD::ANY_EXTEND:
2678   case ISD::ZERO_EXTEND:
2679   case ISD::SIGN_EXTEND:
2680   case ISD::FP_EXTEND:
2681   case ISD::FP_ROUND:
2682     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2683     case Expand: assert(0 && "Shouldn't need to expand other operators here!");
2684     case Legal:
2685       Tmp1 = LegalizeOp(Node->getOperand(0));
2686       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2687       break;
2688     case Promote:
2689       switch (Node->getOpcode()) {
2690       case ISD::ANY_EXTEND:
2691         Tmp1 = PromoteOp(Node->getOperand(0));
2692         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Tmp1);
2693         break;
2694       case ISD::ZERO_EXTEND:
2695         Result = PromoteOp(Node->getOperand(0));
2696         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2697         Result = DAG.getZeroExtendInReg(Result,
2698                                         Node->getOperand(0).getValueType());
2699         break;
2700       case ISD::SIGN_EXTEND:
2701         Result = PromoteOp(Node->getOperand(0));
2702         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2703         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2704                              Result,
2705                           DAG.getValueType(Node->getOperand(0).getValueType()));
2706         break;
2707       case ISD::FP_EXTEND:
2708         Result = PromoteOp(Node->getOperand(0));
2709         if (Result.getValueType() != Op.getValueType())
2710           // Dynamically dead while we have only 2 FP types.
2711           Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
2712         break;
2713       case ISD::FP_ROUND:
2714         Result = PromoteOp(Node->getOperand(0));
2715         Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
2716         break;
2717       }
2718     }
2719     break;
2720   case ISD::FP_ROUND_INREG:
2721   case ISD::SIGN_EXTEND_INREG: {
2722     Tmp1 = LegalizeOp(Node->getOperand(0));
2723     MVT::ValueType ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2724
2725     // If this operation is not supported, convert it to a shl/shr or load/store
2726     // pair.
2727     switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
2728     default: assert(0 && "This action not supported for this op yet!");
2729     case TargetLowering::Legal:
2730       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
2731       break;
2732     case TargetLowering::Expand:
2733       // If this is an integer extend and shifts are supported, do that.
2734       if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
2735         // NOTE: we could fall back on load/store here too for targets without
2736         // SAR.  However, it is doubtful that any exist.
2737         unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
2738                             MVT::getSizeInBits(ExtraVT);
2739         SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
2740         Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
2741                              Node->getOperand(0), ShiftCst);
2742         Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
2743                              Result, ShiftCst);
2744       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
2745         // The only way we can lower this is to turn it into a STORETRUNC,
2746         // EXTLOAD pair, targetting a temporary location (a stack slot).
2747
2748         // NOTE: there is a choice here between constantly creating new stack
2749         // slots and always reusing the same one.  We currently always create
2750         // new ones, as reuse may inhibit scheduling.
2751         const Type *Ty = MVT::getTypeForValueType(ExtraVT);
2752         unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
2753         unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
2754         MachineFunction &MF = DAG.getMachineFunction();
2755         int SSFI =
2756           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
2757         SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
2758         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
2759                              Node->getOperand(0), StackSlot,
2760                              DAG.getSrcValue(NULL), DAG.getValueType(ExtraVT));
2761         Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
2762                                 Result, StackSlot, DAG.getSrcValue(NULL),
2763                                 ExtraVT);
2764       } else {
2765         assert(0 && "Unknown op");
2766       }
2767       break;
2768     }
2769     break;
2770   }
2771   }
2772   
2773   assert(Result.getValueType() == Op.getValueType() &&
2774          "Bad legalization!");
2775   
2776   // Make sure that the generated code is itself legal.
2777   if (Result != Op)
2778     Result = LegalizeOp(Result);
2779
2780   // Note that LegalizeOp may be reentered even from single-use nodes, which
2781   // means that we always must cache transformed nodes.
2782   AddLegalizedOperand(Op, Result);
2783   return Result;
2784 }
2785
2786 /// PromoteOp - Given an operation that produces a value in an invalid type,
2787 /// promote it to compute the value into a larger type.  The produced value will
2788 /// have the correct bits for the low portion of the register, but no guarantee
2789 /// is made about the top bits: it may be zero, sign-extended, or garbage.
2790 SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
2791   MVT::ValueType VT = Op.getValueType();
2792   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
2793   assert(getTypeAction(VT) == Promote &&
2794          "Caller should expand or legalize operands that are not promotable!");
2795   assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
2796          "Cannot promote to smaller type!");
2797
2798   SDOperand Tmp1, Tmp2, Tmp3;
2799   SDOperand Result;
2800   SDNode *Node = Op.Val;
2801
2802   std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
2803   if (I != PromotedNodes.end()) return I->second;
2804
2805   switch (Node->getOpcode()) {
2806   case ISD::CopyFromReg:
2807     assert(0 && "CopyFromReg must be legal!");
2808   default:
2809     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
2810     assert(0 && "Do not know how to promote this operator!");
2811     abort();
2812   case ISD::UNDEF:
2813     Result = DAG.getNode(ISD::UNDEF, NVT);
2814     break;
2815   case ISD::Constant:
2816     if (VT != MVT::i1)
2817       Result = DAG.getNode(ISD::SIGN_EXTEND, NVT, Op);
2818     else
2819       Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
2820     assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
2821     break;
2822   case ISD::ConstantFP:
2823     Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
2824     assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
2825     break;
2826
2827   case ISD::SETCC:
2828     assert(isTypeLegal(TLI.getSetCCResultTy()) && "SetCC type is not legal??");
2829     Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),Node->getOperand(0),
2830                          Node->getOperand(1), Node->getOperand(2));
2831     break;
2832     
2833   case ISD::TRUNCATE:
2834     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2835     case Legal:
2836       Result = LegalizeOp(Node->getOperand(0));
2837       assert(Result.getValueType() >= NVT &&
2838              "This truncation doesn't make sense!");
2839       if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
2840         Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
2841       break;
2842     case Promote:
2843       // The truncation is not required, because we don't guarantee anything
2844       // about high bits anyway.
2845       Result = PromoteOp(Node->getOperand(0));
2846       break;
2847     case Expand:
2848       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2849       // Truncate the low part of the expanded value to the result type
2850       Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
2851     }
2852     break;
2853   case ISD::SIGN_EXTEND:
2854   case ISD::ZERO_EXTEND:
2855   case ISD::ANY_EXTEND:
2856     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2857     case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
2858     case Legal:
2859       // Input is legal?  Just do extend all the way to the larger type.
2860       Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
2861       break;
2862     case Promote:
2863       // Promote the reg if it's smaller.
2864       Result = PromoteOp(Node->getOperand(0));
2865       // The high bits are not guaranteed to be anything.  Insert an extend.
2866       if (Node->getOpcode() == ISD::SIGN_EXTEND)
2867         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
2868                          DAG.getValueType(Node->getOperand(0).getValueType()));
2869       else if (Node->getOpcode() == ISD::ZERO_EXTEND)
2870         Result = DAG.getZeroExtendInReg(Result,
2871                                         Node->getOperand(0).getValueType());
2872       break;
2873     }
2874     break;
2875   case ISD::BIT_CONVERT:
2876     Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2877     Result = PromoteOp(Result);
2878     break;
2879     
2880   case ISD::FP_EXTEND:
2881     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
2882   case ISD::FP_ROUND:
2883     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2884     case Expand: assert(0 && "BUG: Cannot expand FP regs!");
2885     case Promote:  assert(0 && "Unreachable with 2 FP types!");
2886     case Legal:
2887       // Input is legal?  Do an FP_ROUND_INREG.
2888       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Node->getOperand(0),
2889                            DAG.getValueType(VT));
2890       break;
2891     }
2892     break;
2893
2894   case ISD::SINT_TO_FP:
2895   case ISD::UINT_TO_FP:
2896     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2897     case Legal:
2898       // No extra round required here.
2899       Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
2900       break;
2901
2902     case Promote:
2903       Result = PromoteOp(Node->getOperand(0));
2904       if (Node->getOpcode() == ISD::SINT_TO_FP)
2905         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2906                              Result,
2907                          DAG.getValueType(Node->getOperand(0).getValueType()));
2908       else
2909         Result = DAG.getZeroExtendInReg(Result,
2910                                         Node->getOperand(0).getValueType());
2911       // No extra round required here.
2912       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2913       break;
2914     case Expand:
2915       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
2916                              Node->getOperand(0));
2917       // Round if we cannot tolerate excess precision.
2918       if (NoExcessFPPrecision)
2919         Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2920                              DAG.getValueType(VT));
2921       break;
2922     }
2923     break;
2924
2925   case ISD::SIGN_EXTEND_INREG:
2926     Result = PromoteOp(Node->getOperand(0));
2927     Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result, 
2928                          Node->getOperand(1));
2929     break;
2930   case ISD::FP_TO_SINT:
2931   case ISD::FP_TO_UINT:
2932     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2933     case Legal:
2934       Tmp1 = Node->getOperand(0);
2935       break;
2936     case Promote:
2937       // The input result is prerounded, so we don't have to do anything
2938       // special.
2939       Tmp1 = PromoteOp(Node->getOperand(0));
2940       break;
2941     case Expand:
2942       assert(0 && "not implemented");
2943     }
2944     // If we're promoting a UINT to a larger size, check to see if the new node
2945     // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
2946     // we can use that instead.  This allows us to generate better code for
2947     // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
2948     // legal, such as PowerPC.
2949     if (Node->getOpcode() == ISD::FP_TO_UINT && 
2950         !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
2951         (TLI.isOperationLegal(ISD::FP_TO_SINT, NVT) ||
2952          TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
2953       Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
2954     } else {
2955       Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2956     }
2957     break;
2958
2959   case ISD::FABS:
2960   case ISD::FNEG:
2961     Tmp1 = PromoteOp(Node->getOperand(0));
2962     assert(Tmp1.getValueType() == NVT);
2963     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2964     // NOTE: we do not have to do any extra rounding here for
2965     // NoExcessFPPrecision, because we know the input will have the appropriate
2966     // precision, and these operations don't modify precision at all.
2967     break;
2968
2969   case ISD::FSQRT:
2970   case ISD::FSIN:
2971   case ISD::FCOS:
2972     Tmp1 = PromoteOp(Node->getOperand(0));
2973     assert(Tmp1.getValueType() == NVT);
2974     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2975     if (NoExcessFPPrecision)
2976       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2977                            DAG.getValueType(VT));
2978     break;
2979
2980   case ISD::AND:
2981   case ISD::OR:
2982   case ISD::XOR:
2983     // The input may have strange things in the top bits of the registers, but
2984     // these operations don't care.  They may have weird bits going out, but
2985     // that too is okay if they are integer operations.
2986     Tmp1 = PromoteOp(Node->getOperand(0));
2987     Tmp2 = PromoteOp(Node->getOperand(1));
2988     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2989     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2990     break;
2991   case ISD::ADD:
2992   case ISD::SUB:
2993   case ISD::MUL:
2994     // The input may have strange things in the top bits of the registers, but
2995     // these operations don't care.  They may have weird bits going out, but
2996     // that too is okay if they are integer operations.
2997     Tmp1 = PromoteOp(Node->getOperand(0));
2998     Tmp2 = PromoteOp(Node->getOperand(1));
2999     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
3000     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3001     break;
3002   case ISD::FADD:
3003   case ISD::FSUB:
3004   case ISD::FMUL:
3005     Tmp1 = PromoteOp(Node->getOperand(0));
3006     Tmp2 = PromoteOp(Node->getOperand(1));
3007     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
3008     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3009     
3010     // Floating point operations will give excess precision that we may not be
3011     // able to tolerate.  If we DO allow excess precision, just leave it,
3012     // otherwise excise it.
3013     // FIXME: Why would we need to round FP ops more than integer ones?
3014     //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
3015     if (NoExcessFPPrecision)
3016       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3017                            DAG.getValueType(VT));
3018     break;
3019
3020   case ISD::SDIV:
3021   case ISD::SREM:
3022     // These operators require that their input be sign extended.
3023     Tmp1 = PromoteOp(Node->getOperand(0));
3024     Tmp2 = PromoteOp(Node->getOperand(1));
3025     if (MVT::isInteger(NVT)) {
3026       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
3027                          DAG.getValueType(VT));
3028       Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
3029                          DAG.getValueType(VT));
3030     }
3031     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3032
3033     // Perform FP_ROUND: this is probably overly pessimistic.
3034     if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
3035       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3036                            DAG.getValueType(VT));
3037     break;
3038   case ISD::FDIV:
3039   case ISD::FREM:
3040   case ISD::FCOPYSIGN:
3041     // These operators require that their input be fp extended.
3042     Tmp1 = PromoteOp(Node->getOperand(0));
3043     Tmp2 = PromoteOp(Node->getOperand(1));
3044     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3045     
3046     // Perform FP_ROUND: this is probably overly pessimistic.
3047     if (NoExcessFPPrecision && Node->getOpcode() != ISD::FCOPYSIGN)
3048       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3049                            DAG.getValueType(VT));
3050     break;
3051
3052   case ISD::UDIV:
3053   case ISD::UREM:
3054     // These operators require that their input be zero extended.
3055     Tmp1 = PromoteOp(Node->getOperand(0));
3056     Tmp2 = PromoteOp(Node->getOperand(1));
3057     assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
3058     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3059     Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
3060     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3061     break;
3062
3063   case ISD::SHL:
3064     Tmp1 = PromoteOp(Node->getOperand(0));
3065     Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Node->getOperand(1));
3066     break;
3067   case ISD::SRA:
3068     // The input value must be properly sign extended.
3069     Tmp1 = PromoteOp(Node->getOperand(0));
3070     Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
3071                        DAG.getValueType(VT));
3072     Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Node->getOperand(1));
3073     break;
3074   case ISD::SRL:
3075     // The input value must be properly zero extended.
3076     Tmp1 = PromoteOp(Node->getOperand(0));
3077     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3078     Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Node->getOperand(1));
3079     break;
3080
3081   case ISD::VAARG:
3082     Tmp1 = Node->getOperand(0);   // Get the chain.
3083     Tmp2 = Node->getOperand(1);   // Get the pointer.
3084     if (TLI.getOperationAction(ISD::VAARG, VT) == TargetLowering::Custom) {
3085       Tmp3 = DAG.getVAArg(VT, Tmp1, Tmp2, Node->getOperand(2));
3086       Result = TLI.CustomPromoteOperation(Tmp3, DAG);
3087     } else {
3088       SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
3089                                      Node->getOperand(2));
3090       // Increment the pointer, VAList, to the next vaarg
3091       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList, 
3092                          DAG.getConstant(MVT::getSizeInBits(VT)/8, 
3093                                          TLI.getPointerTy()));
3094       // Store the incremented VAList to the legalized pointer
3095       Tmp3 = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), Tmp3, Tmp2, 
3096                          Node->getOperand(2));
3097       // Load the actual argument out of the pointer VAList
3098       Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp3, VAList,
3099                               DAG.getSrcValue(0), VT);
3100     }
3101     // Remember that we legalized the chain.
3102     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
3103     break;
3104
3105   case ISD::LOAD:
3106     Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Node->getOperand(0),
3107                             Node->getOperand(1), Node->getOperand(2), VT);
3108     // Remember that we legalized the chain.
3109     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
3110     break;
3111   case ISD::SEXTLOAD:
3112   case ISD::ZEXTLOAD:
3113   case ISD::EXTLOAD:
3114     Result = DAG.getExtLoad(Node->getOpcode(), NVT, Node->getOperand(0),
3115                             Node->getOperand(1), Node->getOperand(2),
3116                             cast<VTSDNode>(Node->getOperand(3))->getVT());
3117     // Remember that we legalized the chain.
3118     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
3119     break;
3120   case ISD::SELECT:
3121     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
3122     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
3123     Result = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), Tmp2, Tmp3);
3124     break;
3125   case ISD::SELECT_CC:
3126     Tmp2 = PromoteOp(Node->getOperand(2));   // True
3127     Tmp3 = PromoteOp(Node->getOperand(3));   // False
3128     Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
3129                          Node->getOperand(1), Tmp2, Tmp3, Node->getOperand(4));
3130     break;
3131   case ISD::BSWAP:
3132     Tmp1 = Node->getOperand(0);
3133     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
3134     Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
3135     Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
3136                          DAG.getConstant(getSizeInBits(NVT) - getSizeInBits(VT),
3137                                          TLI.getShiftAmountTy()));
3138     break;
3139   case ISD::CTPOP:
3140   case ISD::CTTZ:
3141   case ISD::CTLZ:
3142     // Zero extend the argument
3143     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
3144     // Perform the larger operation, then subtract if needed.
3145     Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
3146     switch(Node->getOpcode()) {
3147     case ISD::CTPOP:
3148       Result = Tmp1;
3149       break;
3150     case ISD::CTTZ:
3151       // if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3152       Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
3153                           DAG.getConstant(getSizeInBits(NVT), NVT), ISD::SETEQ);
3154       Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
3155                            DAG.getConstant(getSizeInBits(VT), NVT), Tmp1);
3156       break;
3157     case ISD::CTLZ:
3158       //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3159       Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
3160                            DAG.getConstant(getSizeInBits(NVT) -
3161                                            getSizeInBits(VT), NVT));
3162       break;
3163     }
3164     break;
3165   case ISD::VEXTRACT_VECTOR_ELT:
3166     Result = PromoteOp(LowerVEXTRACT_VECTOR_ELT(Op));
3167     break;
3168   case ISD::EXTRACT_VECTOR_ELT:
3169     Result = PromoteOp(ExpandEXTRACT_VECTOR_ELT(Op));
3170     break;
3171   }
3172
3173   assert(Result.Val && "Didn't set a result!");
3174
3175   // Make sure the result is itself legal.
3176   Result = LegalizeOp(Result);
3177   
3178   // Remember that we promoted this!
3179   AddPromotedOperand(Op, Result);
3180   return Result;
3181 }
3182
3183 /// LowerVEXTRACT_VECTOR_ELT - Lower a VEXTRACT_VECTOR_ELT operation into a
3184 /// EXTRACT_VECTOR_ELT operation, to memory operations, or to scalar code based
3185 /// on the vector type.  The return type of this matches the element type of the
3186 /// vector, which may not be legal for the target.
3187 SDOperand SelectionDAGLegalize::LowerVEXTRACT_VECTOR_ELT(SDOperand Op) {
3188   // We know that operand #0 is the Vec vector.  If the index is a constant
3189   // or if the invec is a supported hardware type, we can use it.  Otherwise,
3190   // lower to a store then an indexed load.
3191   SDOperand Vec = Op.getOperand(0);
3192   SDOperand Idx = LegalizeOp(Op.getOperand(1));
3193   
3194   SDNode *InVal = Vec.Val;
3195   unsigned NumElems = cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
3196   MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
3197   
3198   // Figure out if there is a Packed type corresponding to this Vector
3199   // type.  If so, convert to the packed type.
3200   MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
3201   if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
3202     // Turn this into a packed extract_vector_elt operation.
3203     Vec = PackVectorOp(Vec, TVT);
3204     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Op.getValueType(), Vec, Idx);
3205   } else if (NumElems == 1) {
3206     // This must be an access of the only element.  Return it.
3207     return PackVectorOp(Vec, EVT);
3208   } else if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
3209     SDOperand Lo, Hi;
3210     SplitVectorOp(Vec, Lo, Hi);
3211     if (CIdx->getValue() < NumElems/2) {
3212       Vec = Lo;
3213     } else {
3214       Vec = Hi;
3215       Idx = DAG.getConstant(CIdx->getValue() - NumElems/2, Idx.getValueType());
3216     }
3217     
3218     // It's now an extract from the appropriate high or low part.  Recurse.
3219     Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
3220     return LowerVEXTRACT_VECTOR_ELT(Op);
3221   } else {
3222     // Variable index case for extract element.
3223     // FIXME: IMPLEMENT STORE/LOAD lowering.  Need alignment of stack slot!!
3224     assert(0 && "unimp!");
3225     return SDOperand();
3226   }
3227 }
3228
3229 /// ExpandEXTRACT_VECTOR_ELT - Expand an EXTRACT_VECTOR_ELT operation into
3230 /// memory traffic.
3231 SDOperand SelectionDAGLegalize::ExpandEXTRACT_VECTOR_ELT(SDOperand Op) {
3232   SDOperand Vector = Op.getOperand(0);
3233   SDOperand Idx    = Op.getOperand(1);
3234   
3235   // If the target doesn't support this, store the value to a temporary
3236   // stack slot, then LOAD the scalar element back out.
3237   SDOperand StackPtr = CreateStackTemporary(Vector.getValueType());
3238   SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3239                              Vector, StackPtr, DAG.getSrcValue(NULL));
3240   
3241   // Add the offset to the index.
3242   unsigned EltSize = MVT::getSizeInBits(Op.getValueType())/8;
3243   Idx = DAG.getNode(ISD::MUL, Idx.getValueType(), Idx,
3244                     DAG.getConstant(EltSize, Idx.getValueType()));
3245   StackPtr = DAG.getNode(ISD::ADD, Idx.getValueType(), Idx, StackPtr);
3246   
3247   return DAG.getLoad(Op.getValueType(), Ch, StackPtr, DAG.getSrcValue(NULL));
3248 }
3249
3250
3251 /// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
3252 /// with condition CC on the current target.  This usually involves legalizing
3253 /// or promoting the arguments.  In the case where LHS and RHS must be expanded,
3254 /// there may be no choice but to create a new SetCC node to represent the
3255 /// legalized value of setcc lhs, rhs.  In this case, the value is returned in
3256 /// LHS, and the SDOperand returned in RHS has a nil SDNode value.
3257 void SelectionDAGLegalize::LegalizeSetCCOperands(SDOperand &LHS,
3258                                                  SDOperand &RHS,
3259                                                  SDOperand &CC) {
3260   SDOperand Tmp1, Tmp2, Result;    
3261   
3262   switch (getTypeAction(LHS.getValueType())) {
3263   case Legal:
3264     Tmp1 = LegalizeOp(LHS);   // LHS
3265     Tmp2 = LegalizeOp(RHS);   // RHS
3266     break;
3267   case Promote:
3268     Tmp1 = PromoteOp(LHS);   // LHS
3269     Tmp2 = PromoteOp(RHS);   // RHS
3270
3271     // If this is an FP compare, the operands have already been extended.
3272     if (MVT::isInteger(LHS.getValueType())) {
3273       MVT::ValueType VT = LHS.getValueType();
3274       MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
3275
3276       // Otherwise, we have to insert explicit sign or zero extends.  Note
3277       // that we could insert sign extends for ALL conditions, but zero extend
3278       // is cheaper on many machines (an AND instead of two shifts), so prefer
3279       // it.
3280       switch (cast<CondCodeSDNode>(CC)->get()) {
3281       default: assert(0 && "Unknown integer comparison!");
3282       case ISD::SETEQ:
3283       case ISD::SETNE:
3284       case ISD::SETUGE:
3285       case ISD::SETUGT:
3286       case ISD::SETULE:
3287       case ISD::SETULT:
3288         // ALL of these operations will work if we either sign or zero extend
3289         // the operands (including the unsigned comparisons!).  Zero extend is
3290         // usually a simpler/cheaper operation, so prefer it.
3291         Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3292         Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
3293         break;
3294       case ISD::SETGE:
3295       case ISD::SETGT:
3296       case ISD::SETLT:
3297       case ISD::SETLE:
3298         Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
3299                            DAG.getValueType(VT));
3300         Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
3301                            DAG.getValueType(VT));
3302         break;
3303       }
3304     }
3305     break;
3306   case Expand:
3307     SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
3308     ExpandOp(LHS, LHSLo, LHSHi);
3309     ExpandOp(RHS, RHSLo, RHSHi);
3310     switch (cast<CondCodeSDNode>(CC)->get()) {
3311     case ISD::SETEQ:
3312     case ISD::SETNE:
3313       if (RHSLo == RHSHi)
3314         if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
3315           if (RHSCST->isAllOnesValue()) {
3316             // Comparison to -1.
3317             Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
3318             Tmp2 = RHSLo;
3319             break;
3320           }
3321
3322       Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
3323       Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
3324       Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
3325       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3326       break;
3327     default:
3328       // If this is a comparison of the sign bit, just look at the top part.
3329       // X > -1,  x < 0
3330       if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(RHS))
3331         if ((cast<CondCodeSDNode>(CC)->get() == ISD::SETLT && 
3332              CST->getValue() == 0) ||             // X < 0
3333             (cast<CondCodeSDNode>(CC)->get() == ISD::SETGT &&
3334              CST->isAllOnesValue())) {            // X > -1
3335           Tmp1 = LHSHi;
3336           Tmp2 = RHSHi;
3337           break;
3338         }
3339
3340       // FIXME: This generated code sucks.
3341       ISD::CondCode LowCC;
3342       switch (cast<CondCodeSDNode>(CC)->get()) {
3343       default: assert(0 && "Unknown integer setcc!");
3344       case ISD::SETLT:
3345       case ISD::SETULT: LowCC = ISD::SETULT; break;
3346       case ISD::SETGT:
3347       case ISD::SETUGT: LowCC = ISD::SETUGT; break;
3348       case ISD::SETLE:
3349       case ISD::SETULE: LowCC = ISD::SETULE; break;
3350       case ISD::SETGE:
3351       case ISD::SETUGE: LowCC = ISD::SETUGE; break;
3352       }
3353
3354       // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
3355       // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
3356       // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
3357
3358       // NOTE: on targets without efficient SELECT of bools, we can always use
3359       // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
3360       Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC);
3361       Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), LHSHi, RHSHi, CC);
3362       Result = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
3363       Result = LegalizeOp(DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
3364                                       Result, Tmp1, Tmp2));
3365       Tmp1 = Result;
3366       Tmp2 = SDOperand();
3367     }
3368   }
3369   LHS = Tmp1;
3370   RHS = Tmp2;
3371 }
3372
3373 /// ExpandBIT_CONVERT - Expand a BIT_CONVERT node into a store/load combination.
3374 /// The resultant code need not be legal.  Note that SrcOp is the input operand
3375 /// to the BIT_CONVERT, not the BIT_CONVERT node itself.
3376 SDOperand SelectionDAGLegalize::ExpandBIT_CONVERT(MVT::ValueType DestVT, 
3377                                                   SDOperand SrcOp) {
3378   // Create the stack frame object.
3379   SDOperand FIPtr = CreateStackTemporary(DestVT);
3380   
3381   // Emit a store to the stack slot.
3382   SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3383                                 SrcOp, FIPtr, DAG.getSrcValue(NULL));
3384   // Result is a load from the stack slot.
3385   return DAG.getLoad(DestVT, Store, FIPtr, DAG.getSrcValue(0));
3386 }
3387
3388 SDOperand SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
3389   // Create a vector sized/aligned stack slot, store the value to element #0,
3390   // then load the whole vector back out.
3391   SDOperand StackPtr = CreateStackTemporary(Node->getValueType(0));
3392   SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3393                              Node->getOperand(0), StackPtr,
3394                              DAG.getSrcValue(NULL));
3395   return DAG.getLoad(Node->getValueType(0), Ch, StackPtr,DAG.getSrcValue(NULL));
3396 }
3397
3398
3399 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
3400 /// support the operation, but do support the resultant packed vector type.
3401 SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
3402   
3403   // If the only non-undef value is the low element, turn this into a 
3404   // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
3405   unsigned NumElems = Node->getNumOperands();
3406   bool isOnlyLowElement = true;
3407   SDOperand SplatValue = Node->getOperand(0);
3408   std::map<SDOperand, std::vector<unsigned> > Values;
3409   Values[SplatValue].push_back(0);
3410   bool isConstant = true;
3411   if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
3412       SplatValue.getOpcode() != ISD::UNDEF)
3413     isConstant = false;
3414   
3415   for (unsigned i = 1; i < NumElems; ++i) {
3416     SDOperand V = Node->getOperand(i);
3417     std::map<SDOperand, std::vector<unsigned> >::iterator I = Values.find(V);
3418     if (I != Values.end())
3419       I->second.push_back(i);
3420     else
3421       Values[V].push_back(i);
3422     if (V.getOpcode() != ISD::UNDEF)
3423       isOnlyLowElement = false;
3424     if (SplatValue != V)
3425       SplatValue = SDOperand(0,0);
3426
3427     // If this isn't a constant element or an undef, we can't use a constant
3428     // pool load.
3429     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
3430         V.getOpcode() != ISD::UNDEF)
3431       isConstant = false;
3432   }
3433   
3434   if (isOnlyLowElement) {
3435     // If the low element is an undef too, then this whole things is an undef.
3436     if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
3437       return DAG.getNode(ISD::UNDEF, Node->getValueType(0));
3438     // Otherwise, turn this into a scalar_to_vector node.
3439     return DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
3440                        Node->getOperand(0));
3441   }
3442   
3443   // If all elements are constants, create a load from the constant pool.
3444   if (isConstant) {
3445     MVT::ValueType VT = Node->getValueType(0);
3446     const Type *OpNTy = 
3447       MVT::getTypeForValueType(Node->getOperand(0).getValueType());
3448     std::vector<Constant*> CV;
3449     for (unsigned i = 0, e = NumElems; i != e; ++i) {
3450       if (ConstantFPSDNode *V = 
3451           dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
3452         CV.push_back(ConstantFP::get(OpNTy, V->getValue()));
3453       } else if (ConstantSDNode *V = 
3454                  dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
3455         CV.push_back(ConstantUInt::get(OpNTy, V->getValue()));
3456       } else {
3457         assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
3458         CV.push_back(UndefValue::get(OpNTy));
3459       }
3460     }
3461     Constant *CP = ConstantPacked::get(CV);
3462     SDOperand CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
3463     return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
3464                        DAG.getSrcValue(NULL));
3465   }
3466   
3467   if (SplatValue.Val) {   // Splat of one value?
3468     // Build the shuffle constant vector: <0, 0, 0, 0>
3469     MVT::ValueType MaskVT = 
3470       MVT::getIntVectorWithNumElements(NumElems);
3471     SDOperand Zero = DAG.getConstant(0, MVT::getVectorBaseType(MaskVT));
3472     std::vector<SDOperand> ZeroVec(NumElems, Zero);
3473     SDOperand SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, ZeroVec);
3474
3475     // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
3476     if (isShuffleLegal(Node->getValueType(0), SplatMask)) {
3477       // Get the splatted value into the low element of a vector register.
3478       SDOperand LowValVec = 
3479         DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), SplatValue);
3480     
3481       // Return shuffle(LowValVec, undef, <0,0,0,0>)
3482       return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), LowValVec,
3483                          DAG.getNode(ISD::UNDEF, Node->getValueType(0)),
3484                          SplatMask);
3485     }
3486   }
3487   
3488   // If there are only two unique elements, we may be able to turn this into a
3489   // vector shuffle.
3490   if (Values.size() == 2) {
3491     // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
3492     MVT::ValueType MaskVT = 
3493       MVT::getIntVectorWithNumElements(NumElems);
3494     std::vector<SDOperand> MaskVec(NumElems);
3495     unsigned i = 0;
3496     for (std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
3497            E = Values.end(); I != E; ++I) {
3498       for (std::vector<unsigned>::iterator II = I->second.begin(),
3499              EE = I->second.end(); II != EE; ++II)
3500         MaskVec[*II] = DAG.getConstant(i, MVT::getVectorBaseType(MaskVT));
3501       i += NumElems;
3502     }
3503     SDOperand ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
3504
3505     // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
3506     if (TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0)) &&
3507         isShuffleLegal(Node->getValueType(0), ShuffleMask)) {
3508       std::vector<SDOperand> Ops;
3509       for(std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
3510             E = Values.end(); I != E; ++I) {
3511         SDOperand Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
3512                                    I->first);
3513         Ops.push_back(Op);
3514       }
3515       Ops.push_back(ShuffleMask);
3516
3517       // Return shuffle(LoValVec, HiValVec, <0,1,0,1>)
3518       return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), Ops);
3519     }
3520   }
3521   
3522   // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
3523   // aligned object on the stack, store each element into it, then load
3524   // the result as a vector.
3525   MVT::ValueType VT = Node->getValueType(0);
3526   // Create the stack frame object.
3527   SDOperand FIPtr = CreateStackTemporary(VT);
3528   
3529   // Emit a store of each element to the stack slot.
3530   std::vector<SDOperand> Stores;
3531   unsigned TypeByteSize = 
3532     MVT::getSizeInBits(Node->getOperand(0).getValueType())/8;
3533   unsigned VectorSize = MVT::getSizeInBits(VT)/8;
3534   // Store (in the right endianness) the elements to memory.
3535   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3536     // Ignore undef elements.
3537     if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
3538     
3539     unsigned Offset = TypeByteSize*i;
3540     
3541     SDOperand Idx = DAG.getConstant(Offset, FIPtr.getValueType());
3542     Idx = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr, Idx);
3543     
3544     Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3545                                  Node->getOperand(i), Idx, 
3546                                  DAG.getSrcValue(NULL)));
3547   }
3548   
3549   SDOperand StoreChain;
3550   if (!Stores.empty())    // Not all undef elements?
3551     StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
3552   else
3553     StoreChain = DAG.getEntryNode();
3554   
3555   // Result is a load from the stack slot.
3556   return DAG.getLoad(VT, StoreChain, FIPtr, DAG.getSrcValue(0));
3557 }
3558
3559 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
3560 /// specified value type.
3561 SDOperand SelectionDAGLegalize::CreateStackTemporary(MVT::ValueType VT) {
3562   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
3563   unsigned ByteSize = MVT::getSizeInBits(VT)/8;
3564   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
3565   return DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
3566 }
3567
3568 void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
3569                                             SDOperand Op, SDOperand Amt,
3570                                             SDOperand &Lo, SDOperand &Hi) {
3571   // Expand the subcomponents.
3572   SDOperand LHSL, LHSH;
3573   ExpandOp(Op, LHSL, LHSH);
3574
3575   std::vector<SDOperand> Ops;
3576   Ops.push_back(LHSL);
3577   Ops.push_back(LHSH);
3578   Ops.push_back(Amt);
3579   std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
3580   Lo = DAG.getNode(NodeOp, VTs, Ops);
3581   Hi = Lo.getValue(1);
3582 }
3583
3584
3585 /// ExpandShift - Try to find a clever way to expand this shift operation out to
3586 /// smaller elements.  If we can't find a way that is more efficient than a
3587 /// libcall on this target, return false.  Otherwise, return true with the
3588 /// low-parts expanded into Lo and Hi.
3589 bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
3590                                        SDOperand &Lo, SDOperand &Hi) {
3591   assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
3592          "This is not a shift!");
3593
3594   MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
3595   SDOperand ShAmt = LegalizeOp(Amt);
3596   MVT::ValueType ShTy = ShAmt.getValueType();
3597   unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
3598   unsigned NVTBits = MVT::getSizeInBits(NVT);
3599
3600   // Handle the case when Amt is an immediate.  Other cases are currently broken
3601   // and are disabled.
3602   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
3603     unsigned Cst = CN->getValue();
3604     // Expand the incoming operand to be shifted, so that we have its parts
3605     SDOperand InL, InH;
3606     ExpandOp(Op, InL, InH);
3607     switch(Opc) {
3608     case ISD::SHL:
3609       if (Cst > VTBits) {
3610         Lo = DAG.getConstant(0, NVT);
3611         Hi = DAG.getConstant(0, NVT);
3612       } else if (Cst > NVTBits) {
3613         Lo = DAG.getConstant(0, NVT);
3614         Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
3615       } else if (Cst == NVTBits) {
3616         Lo = DAG.getConstant(0, NVT);
3617         Hi = InL;
3618       } else {
3619         Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
3620         Hi = DAG.getNode(ISD::OR, NVT,
3621            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
3622            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
3623       }
3624       return true;
3625     case ISD::SRL:
3626       if (Cst > VTBits) {
3627         Lo = DAG.getConstant(0, NVT);
3628         Hi = DAG.getConstant(0, NVT);
3629       } else if (Cst > NVTBits) {
3630         Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
3631         Hi = DAG.getConstant(0, NVT);
3632       } else if (Cst == NVTBits) {
3633         Lo = InH;
3634         Hi = DAG.getConstant(0, NVT);
3635       } else {
3636         Lo = DAG.getNode(ISD::OR, NVT,
3637            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
3638            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
3639         Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
3640       }
3641       return true;
3642     case ISD::SRA:
3643       if (Cst > VTBits) {
3644         Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
3645                               DAG.getConstant(NVTBits-1, ShTy));
3646       } else if (Cst > NVTBits) {
3647         Lo = DAG.getNode(ISD::SRA, NVT, InH,
3648                            DAG.getConstant(Cst-NVTBits, ShTy));
3649         Hi = DAG.getNode(ISD::SRA, NVT, InH,
3650                               DAG.getConstant(NVTBits-1, ShTy));
3651       } else if (Cst == NVTBits) {
3652         Lo = InH;
3653         Hi = DAG.getNode(ISD::SRA, NVT, InH,
3654                               DAG.getConstant(NVTBits-1, ShTy));
3655       } else {
3656         Lo = DAG.getNode(ISD::OR, NVT,
3657            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
3658            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
3659         Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
3660       }
3661       return true;
3662     }
3663   }
3664   return false;
3665 }
3666
3667
3668 // ExpandLibCall - Expand a node into a call to a libcall.  If the result value
3669 // does not fit into a register, return the lo part and set the hi part to the
3670 // by-reg argument.  If it does fit into a single register, return the result
3671 // and leave the Hi part unset.
3672 SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
3673                                               SDOperand &Hi) {
3674   assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
3675   // The input chain to this libcall is the entry node of the function. 
3676   // Legalizing the call will automatically add the previous call to the
3677   // dependence.
3678   SDOperand InChain = DAG.getEntryNode();
3679   
3680   TargetLowering::ArgListTy Args;
3681   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3682     MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
3683     const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
3684     Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
3685   }
3686   SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
3687
3688   // Splice the libcall in wherever FindInputOutputChains tells us to.
3689   const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
3690   std::pair<SDOperand,SDOperand> CallInfo =
3691     TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, false,
3692                     Callee, Args, DAG);
3693
3694   // Legalize the call sequence, starting with the chain.  This will advance
3695   // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
3696   // was added by LowerCallTo (guaranteeing proper serialization of calls).
3697   LegalizeOp(CallInfo.second);
3698   SDOperand Result;
3699   switch (getTypeAction(CallInfo.first.getValueType())) {
3700   default: assert(0 && "Unknown thing");
3701   case Legal:
3702     Result = CallInfo.first;
3703     break;
3704   case Expand:
3705     ExpandOp(CallInfo.first, Result, Hi);
3706     break;
3707   }
3708   return Result;
3709 }
3710
3711
3712 /// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
3713 /// destination type is legal.
3714 SDOperand SelectionDAGLegalize::
3715 ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
3716   assert(isTypeLegal(DestTy) && "Destination type is not legal!");
3717   assert(getTypeAction(Source.getValueType()) == Expand &&
3718          "This is not an expansion!");
3719   assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
3720
3721   if (!isSigned) {
3722     assert(Source.getValueType() == MVT::i64 &&
3723            "This only works for 64-bit -> FP");
3724     // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
3725     // incoming integer is set.  To handle this, we dynamically test to see if
3726     // it is set, and, if so, add a fudge factor.
3727     SDOperand Lo, Hi;
3728     ExpandOp(Source, Lo, Hi);
3729
3730     // If this is unsigned, and not supported, first perform the conversion to
3731     // signed, then adjust the result if the sign bit is set.
3732     SDOperand SignedConv = ExpandIntToFP(true, DestTy,
3733                    DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), Lo, Hi));
3734
3735     SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
3736                                      DAG.getConstant(0, Hi.getValueType()),
3737                                      ISD::SETLT);
3738     SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
3739     SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
3740                                       SignSet, Four, Zero);
3741     uint64_t FF = 0x5f800000ULL;
3742     if (TLI.isLittleEndian()) FF <<= 32;
3743     static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
3744
3745     SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
3746     CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
3747     SDOperand FudgeInReg;
3748     if (DestTy == MVT::f32)
3749       FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
3750                                DAG.getSrcValue(NULL));
3751     else {
3752       assert(DestTy == MVT::f64 && "Unexpected conversion");
3753       FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
3754                                   CPIdx, DAG.getSrcValue(NULL), MVT::f32);
3755     }
3756     return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
3757   }
3758
3759   // Check to see if the target has a custom way to lower this.  If so, use it.
3760   switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
3761   default: assert(0 && "This action not implemented for this operation!");
3762   case TargetLowering::Legal:
3763   case TargetLowering::Expand:
3764     break;   // This case is handled below.
3765   case TargetLowering::Custom: {
3766     SDOperand NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
3767                                                   Source), DAG);
3768     if (NV.Val)
3769       return LegalizeOp(NV);
3770     break;   // The target decided this was legal after all
3771   }
3772   }
3773
3774   // Expand the source, then glue it back together for the call.  We must expand
3775   // the source in case it is shared (this pass of legalize must traverse it).
3776   SDOperand SrcLo, SrcHi;
3777   ExpandOp(Source, SrcLo, SrcHi);
3778   Source = DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), SrcLo, SrcHi);
3779
3780   const char *FnName = 0;
3781   if (DestTy == MVT::f32)
3782     FnName = "__floatdisf";
3783   else {
3784     assert(DestTy == MVT::f64 && "Unknown fp value type!");
3785     FnName = "__floatdidf";
3786   }
3787   
3788   Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
3789   SDOperand UnusedHiPart;
3790   return ExpandLibCall(FnName, Source.Val, UnusedHiPart);
3791 }
3792
3793 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
3794 /// INT_TO_FP operation of the specified operand when the target requests that
3795 /// we expand it.  At this point, we know that the result and operand types are
3796 /// legal for the target.
3797 SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
3798                                                      SDOperand Op0,
3799                                                      MVT::ValueType DestVT) {
3800   if (Op0.getValueType() == MVT::i32) {
3801     // simple 32-bit [signed|unsigned] integer to float/double expansion
3802     
3803     // get the stack frame index of a 8 byte buffer
3804     MachineFunction &MF = DAG.getMachineFunction();
3805     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3806     // get address of 8 byte buffer
3807     SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3808     // word offset constant for Hi/Lo address computation
3809     SDOperand WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
3810     // set up Hi and Lo (into buffer) address based on endian
3811     SDOperand Hi = StackSlot;
3812     SDOperand Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot,WordOff);
3813     if (TLI.isLittleEndian())
3814       std::swap(Hi, Lo);
3815     
3816     // if signed map to unsigned space
3817     SDOperand Op0Mapped;
3818     if (isSigned) {
3819       // constant used to invert sign bit (signed to unsigned mapping)
3820       SDOperand SignBit = DAG.getConstant(0x80000000u, MVT::i32);
3821       Op0Mapped = DAG.getNode(ISD::XOR, MVT::i32, Op0, SignBit);
3822     } else {
3823       Op0Mapped = Op0;
3824     }
3825     // store the lo of the constructed double - based on integer input
3826     SDOperand Store1 = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3827                                    Op0Mapped, Lo, DAG.getSrcValue(NULL));
3828     // initial hi portion of constructed double
3829     SDOperand InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
3830     // store the hi of the constructed double - biased exponent
3831     SDOperand Store2 = DAG.getNode(ISD::STORE, MVT::Other, Store1,
3832                                    InitialHi, Hi, DAG.getSrcValue(NULL));
3833     // load the constructed double
3834     SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot,
3835                                DAG.getSrcValue(NULL));
3836     // FP constant to bias correct the final result
3837     SDOperand Bias = DAG.getConstantFP(isSigned ?
3838                                             BitsToDouble(0x4330000080000000ULL)
3839                                           : BitsToDouble(0x4330000000000000ULL),
3840                                      MVT::f64);
3841     // subtract the bias
3842     SDOperand Sub = DAG.getNode(ISD::FSUB, MVT::f64, Load, Bias);
3843     // final result
3844     SDOperand Result;
3845     // handle final rounding
3846     if (DestVT == MVT::f64) {
3847       // do nothing
3848       Result = Sub;
3849     } else {
3850      // if f32 then cast to f32
3851       Result = DAG.getNode(ISD::FP_ROUND, MVT::f32, Sub);
3852     }
3853     return Result;
3854   }
3855   assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
3856   SDOperand Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
3857
3858   SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Op0,
3859                                    DAG.getConstant(0, Op0.getValueType()),
3860                                    ISD::SETLT);
3861   SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
3862   SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
3863                                     SignSet, Four, Zero);
3864
3865   // If the sign bit of the integer is set, the large number will be treated
3866   // as a negative number.  To counteract this, the dynamic code adds an
3867   // offset depending on the data type.
3868   uint64_t FF;
3869   switch (Op0.getValueType()) {
3870   default: assert(0 && "Unsupported integer type!");
3871   case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
3872   case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
3873   case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
3874   case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
3875   }
3876   if (TLI.isLittleEndian()) FF <<= 32;
3877   static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
3878
3879   SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
3880   CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
3881   SDOperand FudgeInReg;
3882   if (DestVT == MVT::f32)
3883     FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
3884                              DAG.getSrcValue(NULL));
3885   else {
3886     assert(DestVT == MVT::f64 && "Unexpected conversion");
3887     FudgeInReg = LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, MVT::f64,
3888                                            DAG.getEntryNode(), CPIdx,
3889                                            DAG.getSrcValue(NULL), MVT::f32));
3890   }
3891
3892   return DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg);
3893 }
3894
3895 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
3896 /// *INT_TO_FP operation of the specified operand when the target requests that
3897 /// we promote it.  At this point, we know that the result and operand types are
3898 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
3899 /// operation that takes a larger input.
3900 SDOperand SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDOperand LegalOp,
3901                                                       MVT::ValueType DestVT,
3902                                                       bool isSigned) {
3903   // First step, figure out the appropriate *INT_TO_FP operation to use.
3904   MVT::ValueType NewInTy = LegalOp.getValueType();
3905
3906   unsigned OpToUse = 0;
3907
3908   // Scan for the appropriate larger type to use.
3909   while (1) {
3910     NewInTy = (MVT::ValueType)(NewInTy+1);
3911     assert(MVT::isInteger(NewInTy) && "Ran out of possibilities!");
3912
3913     // If the target supports SINT_TO_FP of this type, use it.
3914     switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
3915       default: break;
3916       case TargetLowering::Legal:
3917         if (!TLI.isTypeLegal(NewInTy))
3918           break;  // Can't use this datatype.
3919         // FALL THROUGH.
3920       case TargetLowering::Custom:
3921         OpToUse = ISD::SINT_TO_FP;
3922         break;
3923     }
3924     if (OpToUse) break;
3925     if (isSigned) continue;
3926
3927     // If the target supports UINT_TO_FP of this type, use it.
3928     switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
3929       default: break;
3930       case TargetLowering::Legal:
3931         if (!TLI.isTypeLegal(NewInTy))
3932           break;  // Can't use this datatype.
3933         // FALL THROUGH.
3934       case TargetLowering::Custom:
3935         OpToUse = ISD::UINT_TO_FP;
3936         break;
3937     }
3938     if (OpToUse) break;
3939
3940     // Otherwise, try a larger type.
3941   }
3942
3943   // Okay, we found the operation and type to use.  Zero extend our input to the
3944   // desired type then run the operation on it.
3945   return DAG.getNode(OpToUse, DestVT,
3946                      DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
3947                                  NewInTy, LegalOp));
3948 }
3949
3950 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
3951 /// FP_TO_*INT operation of the specified operand when the target requests that
3952 /// we promote it.  At this point, we know that the result and operand types are
3953 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
3954 /// operation that returns a larger result.
3955 SDOperand SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDOperand LegalOp,
3956                                                       MVT::ValueType DestVT,
3957                                                       bool isSigned) {
3958   // First step, figure out the appropriate FP_TO*INT operation to use.
3959   MVT::ValueType NewOutTy = DestVT;
3960
3961   unsigned OpToUse = 0;
3962
3963   // Scan for the appropriate larger type to use.
3964   while (1) {
3965     NewOutTy = (MVT::ValueType)(NewOutTy+1);
3966     assert(MVT::isInteger(NewOutTy) && "Ran out of possibilities!");
3967
3968     // If the target supports FP_TO_SINT returning this type, use it.
3969     switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
3970     default: break;
3971     case TargetLowering::Legal:
3972       if (!TLI.isTypeLegal(NewOutTy))
3973         break;  // Can't use this datatype.
3974       // FALL THROUGH.
3975     case TargetLowering::Custom:
3976       OpToUse = ISD::FP_TO_SINT;
3977       break;
3978     }
3979     if (OpToUse) break;
3980
3981     // If the target supports FP_TO_UINT of this type, use it.
3982     switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
3983     default: break;
3984     case TargetLowering::Legal:
3985       if (!TLI.isTypeLegal(NewOutTy))
3986         break;  // Can't use this datatype.
3987       // FALL THROUGH.
3988     case TargetLowering::Custom:
3989       OpToUse = ISD::FP_TO_UINT;
3990       break;
3991     }
3992     if (OpToUse) break;
3993
3994     // Otherwise, try a larger type.
3995   }
3996
3997   // Okay, we found the operation and type to use.  Truncate the result of the
3998   // extended FP_TO_*INT operation to the desired size.
3999   return DAG.getNode(ISD::TRUNCATE, DestVT,
4000                      DAG.getNode(OpToUse, NewOutTy, LegalOp));
4001 }
4002
4003 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
4004 ///
4005 SDOperand SelectionDAGLegalize::ExpandBSWAP(SDOperand Op) {
4006   MVT::ValueType VT = Op.getValueType();
4007   MVT::ValueType SHVT = TLI.getShiftAmountTy();
4008   SDOperand Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
4009   switch (VT) {
4010   default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
4011   case MVT::i16:
4012     Tmp2 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
4013     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
4014     return DAG.getNode(ISD::OR, VT, Tmp1, Tmp2);
4015   case MVT::i32:
4016     Tmp4 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
4017     Tmp3 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
4018     Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
4019     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
4020     Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
4021     Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(0xFF00, VT));
4022     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
4023     Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
4024     return DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
4025   case MVT::i64:
4026     Tmp8 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(56, SHVT));
4027     Tmp7 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(40, SHVT));
4028     Tmp6 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
4029     Tmp5 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
4030     Tmp4 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
4031     Tmp3 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
4032     Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(40, SHVT));
4033     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(56, SHVT));
4034     Tmp7 = DAG.getNode(ISD::AND, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
4035     Tmp6 = DAG.getNode(ISD::AND, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
4036     Tmp5 = DAG.getNode(ISD::AND, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
4037     Tmp4 = DAG.getNode(ISD::AND, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
4038     Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
4039     Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
4040     Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp7);
4041     Tmp6 = DAG.getNode(ISD::OR, VT, Tmp6, Tmp5);
4042     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
4043     Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
4044     Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp6);
4045     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
4046     return DAG.getNode(ISD::OR, VT, Tmp8, Tmp4);
4047   }
4048 }
4049
4050 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
4051 ///
4052 SDOperand SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDOperand Op) {
4053   switch (Opc) {
4054   default: assert(0 && "Cannot expand this yet!");
4055   case ISD::CTPOP: {
4056     static const uint64_t mask[6] = {
4057       0x5555555555555555ULL, 0x3333333333333333ULL,
4058       0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
4059       0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
4060     };
4061     MVT::ValueType VT = Op.getValueType();
4062     MVT::ValueType ShVT = TLI.getShiftAmountTy();
4063     unsigned len = getSizeInBits(VT);
4064     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
4065       //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
4066       SDOperand Tmp2 = DAG.getConstant(mask[i], VT);
4067       SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
4068       Op = DAG.getNode(ISD::ADD, VT, DAG.getNode(ISD::AND, VT, Op, Tmp2),
4069                        DAG.getNode(ISD::AND, VT,
4070                                    DAG.getNode(ISD::SRL, VT, Op, Tmp3),Tmp2));
4071     }
4072     return Op;
4073   }
4074   case ISD::CTLZ: {
4075     // for now, we do this:
4076     // x = x | (x >> 1);
4077     // x = x | (x >> 2);
4078     // ...
4079     // x = x | (x >>16);
4080     // x = x | (x >>32); // for 64-bit input
4081     // return popcount(~x);
4082     //
4083     // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
4084     MVT::ValueType VT = Op.getValueType();
4085     MVT::ValueType ShVT = TLI.getShiftAmountTy();
4086     unsigned len = getSizeInBits(VT);
4087     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
4088       SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
4089       Op = DAG.getNode(ISD::OR, VT, Op, DAG.getNode(ISD::SRL, VT, Op, Tmp3));
4090     }
4091     Op = DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(~0ULL, VT));
4092     return DAG.getNode(ISD::CTPOP, VT, Op);
4093   }
4094   case ISD::CTTZ: {
4095     // for now, we use: { return popcount(~x & (x - 1)); }
4096     // unless the target has ctlz but not ctpop, in which case we use:
4097     // { return 32 - nlz(~x & (x-1)); }
4098     // see also http://www.hackersdelight.org/HDcode/ntz.cc
4099     MVT::ValueType VT = Op.getValueType();
4100     SDOperand Tmp2 = DAG.getConstant(~0ULL, VT);
4101     SDOperand Tmp3 = DAG.getNode(ISD::AND, VT,
4102                        DAG.getNode(ISD::XOR, VT, Op, Tmp2),
4103                        DAG.getNode(ISD::SUB, VT, Op, DAG.getConstant(1, VT)));
4104     // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
4105     if (!TLI.isOperationLegal(ISD::CTPOP, VT) &&
4106         TLI.isOperationLegal(ISD::CTLZ, VT))
4107       return DAG.getNode(ISD::SUB, VT,
4108                          DAG.getConstant(getSizeInBits(VT), VT),
4109                          DAG.getNode(ISD::CTLZ, VT, Tmp3));
4110     return DAG.getNode(ISD::CTPOP, VT, Tmp3);
4111   }
4112   }
4113 }
4114
4115 /// ExpandOp - Expand the specified SDOperand into its two component pieces
4116 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
4117 /// LegalizeNodes map is filled in for any results that are not expanded, the
4118 /// ExpandedNodes map is filled in for any results that are expanded, and the
4119 /// Lo/Hi values are returned.
4120 void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
4121   MVT::ValueType VT = Op.getValueType();
4122   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
4123   SDNode *Node = Op.Val;
4124   assert(getTypeAction(VT) == Expand && "Not an expanded type!");
4125   assert((MVT::isInteger(VT) || VT == MVT::Vector) && 
4126          "Cannot expand FP values!");
4127   assert(((MVT::isInteger(NVT) && NVT < VT) || VT == MVT::Vector) &&
4128          "Cannot expand to FP value or to larger int value!");
4129
4130   // See if we already expanded it.
4131   std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
4132     = ExpandedNodes.find(Op);
4133   if (I != ExpandedNodes.end()) {
4134     Lo = I->second.first;
4135     Hi = I->second.second;
4136     return;
4137   }
4138
4139   switch (Node->getOpcode()) {
4140   case ISD::CopyFromReg:
4141     assert(0 && "CopyFromReg must be legal!");
4142   default:
4143     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
4144     assert(0 && "Do not know how to expand this operator!");
4145     abort();
4146   case ISD::UNDEF:
4147     Lo = DAG.getNode(ISD::UNDEF, NVT);
4148     Hi = DAG.getNode(ISD::UNDEF, NVT);
4149     break;
4150   case ISD::Constant: {
4151     uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
4152     Lo = DAG.getConstant(Cst, NVT);
4153     Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
4154     break;
4155   }
4156   case ISD::BUILD_PAIR:
4157     // Return the operands.
4158     Lo = Node->getOperand(0);
4159     Hi = Node->getOperand(1);
4160     break;
4161     
4162   case ISD::SIGN_EXTEND_INREG:
4163     ExpandOp(Node->getOperand(0), Lo, Hi);
4164     // Sign extend the lo-part.
4165     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
4166                      DAG.getConstant(MVT::getSizeInBits(NVT)-1,
4167                                      TLI.getShiftAmountTy()));
4168     // sext_inreg the low part if needed.
4169     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
4170     break;
4171
4172   case ISD::BSWAP: {
4173     ExpandOp(Node->getOperand(0), Lo, Hi);
4174     SDOperand TempLo = DAG.getNode(ISD::BSWAP, NVT, Hi);
4175     Hi = DAG.getNode(ISD::BSWAP, NVT, Lo);
4176     Lo = TempLo;
4177     break;
4178   }
4179     
4180   case ISD::CTPOP:
4181     ExpandOp(Node->getOperand(0), Lo, Hi);
4182     Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
4183                      DAG.getNode(ISD::CTPOP, NVT, Lo),
4184                      DAG.getNode(ISD::CTPOP, NVT, Hi));
4185     Hi = DAG.getConstant(0, NVT);
4186     break;
4187
4188   case ISD::CTLZ: {
4189     // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
4190     ExpandOp(Node->getOperand(0), Lo, Hi);
4191     SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
4192     SDOperand HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
4193     SDOperand TopNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), HLZ, BitsC,
4194                                         ISD::SETNE);
4195     SDOperand LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
4196     LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
4197
4198     Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
4199     Hi = DAG.getConstant(0, NVT);
4200     break;
4201   }
4202
4203   case ISD::CTTZ: {
4204     // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
4205     ExpandOp(Node->getOperand(0), Lo, Hi);
4206     SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
4207     SDOperand LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
4208     SDOperand BotNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), LTZ, BitsC,
4209                                         ISD::SETNE);
4210     SDOperand HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
4211     HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
4212
4213     Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
4214     Hi = DAG.getConstant(0, NVT);
4215     break;
4216   }
4217
4218   case ISD::VAARG: {
4219     SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
4220     SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
4221     Lo = DAG.getVAArg(NVT, Ch, Ptr, Node->getOperand(2));
4222     Hi = DAG.getVAArg(NVT, Lo.getValue(1), Ptr, Node->getOperand(2));
4223
4224     // Remember that we legalized the chain.
4225     Hi = LegalizeOp(Hi);
4226     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
4227     if (!TLI.isLittleEndian())
4228       std::swap(Lo, Hi);
4229     break;
4230   }
4231     
4232   case ISD::LOAD: {
4233     SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
4234     SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
4235     Lo = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
4236
4237     // Increment the pointer to the other half.
4238     unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
4239     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4240                       getIntPtrConstant(IncrementSize));
4241     // FIXME: This creates a bogus srcvalue!
4242     Hi = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
4243
4244     // Build a factor node to remember that this load is independent of the
4245     // other one.
4246     SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
4247                                Hi.getValue(1));
4248
4249     // Remember that we legalized the chain.
4250     AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
4251     if (!TLI.isLittleEndian())
4252       std::swap(Lo, Hi);
4253     break;
4254   }
4255   case ISD::AND:
4256   case ISD::OR:
4257   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
4258     SDOperand LL, LH, RL, RH;
4259     ExpandOp(Node->getOperand(0), LL, LH);
4260     ExpandOp(Node->getOperand(1), RL, RH);
4261     Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
4262     Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
4263     break;
4264   }
4265   case ISD::SELECT: {
4266     SDOperand LL, LH, RL, RH;
4267     ExpandOp(Node->getOperand(1), LL, LH);
4268     ExpandOp(Node->getOperand(2), RL, RH);
4269     Lo = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LL, RL);
4270     Hi = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LH, RH);
4271     break;
4272   }
4273   case ISD::SELECT_CC: {
4274     SDOperand TL, TH, FL, FH;
4275     ExpandOp(Node->getOperand(2), TL, TH);
4276     ExpandOp(Node->getOperand(3), FL, FH);
4277     Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4278                      Node->getOperand(1), TL, FL, Node->getOperand(4));
4279     Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4280                      Node->getOperand(1), TH, FH, Node->getOperand(4));
4281     break;
4282   }
4283   case ISD::SEXTLOAD: {
4284     SDOperand Chain = Node->getOperand(0);
4285     SDOperand Ptr   = Node->getOperand(1);
4286     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4287     
4288     if (EVT == NVT)
4289       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4290     else
4291       Lo = DAG.getExtLoad(ISD::SEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4292                           EVT);
4293     
4294     // Remember that we legalized the chain.
4295     AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4296     
4297     // The high part is obtained by SRA'ing all but one of the bits of the lo
4298     // part.
4299     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
4300     Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
4301                                                        TLI.getShiftAmountTy()));
4302     break;
4303   }
4304   case ISD::ZEXTLOAD: {
4305     SDOperand Chain = Node->getOperand(0);
4306     SDOperand Ptr   = Node->getOperand(1);
4307     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4308     
4309     if (EVT == NVT)
4310       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4311     else
4312       Lo = DAG.getExtLoad(ISD::ZEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4313                           EVT);
4314     
4315     // Remember that we legalized the chain.
4316     AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4317
4318     // The high part is just a zero.
4319     Hi = DAG.getConstant(0, NVT);
4320     break;
4321   }
4322   case ISD::EXTLOAD: {
4323     SDOperand Chain = Node->getOperand(0);
4324     SDOperand Ptr   = Node->getOperand(1);
4325     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4326     
4327     if (EVT == NVT)
4328       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4329     else
4330       Lo = DAG.getExtLoad(ISD::EXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4331                           EVT);
4332     
4333     // Remember that we legalized the chain.
4334     AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4335     
4336     // The high part is undefined.
4337     Hi = DAG.getNode(ISD::UNDEF, NVT);
4338     break;
4339   }
4340   case ISD::ANY_EXTEND:
4341     // The low part is any extension of the input (which degenerates to a copy).
4342     Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, Node->getOperand(0));
4343     // The high part is undefined.
4344     Hi = DAG.getNode(ISD::UNDEF, NVT);
4345     break;
4346   case ISD::SIGN_EXTEND: {
4347     // The low part is just a sign extension of the input (which degenerates to
4348     // a copy).
4349     Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, Node->getOperand(0));
4350
4351     // The high part is obtained by SRA'ing all but one of the bits of the lo
4352     // part.
4353     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
4354     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
4355                      DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
4356     break;
4357   }
4358   case ISD::ZERO_EXTEND:
4359     // The low part is just a zero extension of the input (which degenerates to
4360     // a copy).
4361     Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
4362
4363     // The high part is just a zero.
4364     Hi = DAG.getConstant(0, NVT);
4365     break;
4366     
4367   case ISD::BIT_CONVERT: {
4368     SDOperand Tmp = ExpandBIT_CONVERT(Node->getValueType(0), 
4369                                       Node->getOperand(0));
4370     ExpandOp(Tmp, Lo, Hi);
4371     break;
4372   }
4373
4374   case ISD::READCYCLECOUNTER:
4375     assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) == 
4376                  TargetLowering::Custom &&
4377            "Must custom expand ReadCycleCounter");
4378     Lo = TLI.LowerOperation(Op, DAG);
4379     assert(Lo.Val && "Node must be custom expanded!");
4380     Hi = Lo.getValue(1);
4381     AddLegalizedOperand(SDOperand(Node, 1), // Remember we legalized the chain.
4382                         LegalizeOp(Lo.getValue(2)));
4383     break;
4384
4385     // These operators cannot be expanded directly, emit them as calls to
4386     // library functions.
4387   case ISD::FP_TO_SINT:
4388     if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
4389       SDOperand Op;
4390       switch (getTypeAction(Node->getOperand(0).getValueType())) {
4391       case Expand: assert(0 && "cannot expand FP!");
4392       case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
4393       case Promote: Op = PromoteOp (Node->getOperand(0)); break;
4394       }
4395
4396       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
4397
4398       // Now that the custom expander is done, expand the result, which is still
4399       // VT.
4400       if (Op.Val) {
4401         ExpandOp(Op, Lo, Hi);
4402         break;
4403       }
4404     }
4405
4406     if (Node->getOperand(0).getValueType() == MVT::f32)
4407       Lo = ExpandLibCall("__fixsfdi", Node, Hi);
4408     else
4409       Lo = ExpandLibCall("__fixdfdi", Node, Hi);
4410     break;
4411
4412   case ISD::FP_TO_UINT:
4413     if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
4414       SDOperand Op;
4415       switch (getTypeAction(Node->getOperand(0).getValueType())) {
4416         case Expand: assert(0 && "cannot expand FP!");
4417         case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
4418         case Promote: Op = PromoteOp (Node->getOperand(0)); break;
4419       }
4420         
4421       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_UINT, VT, Op), DAG);
4422
4423       // Now that the custom expander is done, expand the result.
4424       if (Op.Val) {
4425         ExpandOp(Op, Lo, Hi);
4426         break;
4427       }
4428     }
4429
4430     if (Node->getOperand(0).getValueType() == MVT::f32)
4431       Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
4432     else
4433       Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
4434     break;
4435
4436   case ISD::SHL: {
4437     // If the target wants custom lowering, do so.
4438     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4439     if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
4440       SDOperand Op = DAG.getNode(ISD::SHL, VT, Node->getOperand(0), ShiftAmt);
4441       Op = TLI.LowerOperation(Op, DAG);
4442       if (Op.Val) {
4443         // Now that the custom expander is done, expand the result, which is
4444         // still VT.
4445         ExpandOp(Op, Lo, Hi);
4446         break;
4447       }
4448     }
4449     
4450     // If we can emit an efficient shift operation, do so now.
4451     if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi))
4452       break;
4453
4454     // If this target supports SHL_PARTS, use it.
4455     TargetLowering::LegalizeAction Action =
4456       TLI.getOperationAction(ISD::SHL_PARTS, NVT);
4457     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4458         Action == TargetLowering::Custom) {
4459       ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4460       break;
4461     }
4462
4463     // Otherwise, emit a libcall.
4464     Lo = ExpandLibCall("__ashldi3", Node, Hi);
4465     break;
4466   }
4467
4468   case ISD::SRA: {
4469     // If the target wants custom lowering, do so.
4470     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4471     if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
4472       SDOperand Op = DAG.getNode(ISD::SRA, VT, Node->getOperand(0), ShiftAmt);
4473       Op = TLI.LowerOperation(Op, DAG);
4474       if (Op.Val) {
4475         // Now that the custom expander is done, expand the result, which is
4476         // still VT.
4477         ExpandOp(Op, Lo, Hi);
4478         break;
4479       }
4480     }
4481     
4482     // If we can emit an efficient shift operation, do so now.
4483     if (ExpandShift(ISD::SRA, Node->getOperand(0), ShiftAmt, Lo, Hi))
4484       break;
4485
4486     // If this target supports SRA_PARTS, use it.
4487     TargetLowering::LegalizeAction Action =
4488       TLI.getOperationAction(ISD::SRA_PARTS, NVT);
4489     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4490         Action == TargetLowering::Custom) {
4491       ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4492       break;
4493     }
4494
4495     // Otherwise, emit a libcall.
4496     Lo = ExpandLibCall("__ashrdi3", Node, Hi);
4497     break;
4498   }
4499
4500   case ISD::SRL: {
4501     // If the target wants custom lowering, do so.
4502     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4503     if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
4504       SDOperand Op = DAG.getNode(ISD::SRL, VT, Node->getOperand(0), ShiftAmt);
4505       Op = TLI.LowerOperation(Op, DAG);
4506       if (Op.Val) {
4507         // Now that the custom expander is done, expand the result, which is
4508         // still VT.
4509         ExpandOp(Op, Lo, Hi);
4510         break;
4511       }
4512     }
4513
4514     // If we can emit an efficient shift operation, do so now.
4515     if (ExpandShift(ISD::SRL, Node->getOperand(0), ShiftAmt, Lo, Hi))
4516       break;
4517
4518     // If this target supports SRL_PARTS, use it.
4519     TargetLowering::LegalizeAction Action =
4520       TLI.getOperationAction(ISD::SRL_PARTS, NVT);
4521     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4522         Action == TargetLowering::Custom) {
4523       ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4524       break;
4525     }
4526
4527     // Otherwise, emit a libcall.
4528     Lo = ExpandLibCall("__lshrdi3", Node, Hi);
4529     break;
4530   }
4531
4532   case ISD::ADD:
4533   case ISD::SUB: {
4534     // If the target wants to custom expand this, let them.
4535     if (TLI.getOperationAction(Node->getOpcode(), VT) ==
4536             TargetLowering::Custom) {
4537       Op = TLI.LowerOperation(Op, DAG);
4538       if (Op.Val) {
4539         ExpandOp(Op, Lo, Hi);
4540         break;
4541       }
4542     }
4543     
4544     // Expand the subcomponents.
4545     SDOperand LHSL, LHSH, RHSL, RHSH;
4546     ExpandOp(Node->getOperand(0), LHSL, LHSH);
4547     ExpandOp(Node->getOperand(1), RHSL, RHSH);
4548     std::vector<MVT::ValueType> VTs;
4549     std::vector<SDOperand> LoOps, HiOps;
4550     VTs.push_back(LHSL.getValueType());
4551     VTs.push_back(MVT::Flag);
4552     LoOps.push_back(LHSL);
4553     LoOps.push_back(RHSL);
4554     HiOps.push_back(LHSH);
4555     HiOps.push_back(RHSH);
4556     if (Node->getOpcode() == ISD::ADD) {
4557       Lo = DAG.getNode(ISD::ADDC, VTs, LoOps);
4558       HiOps.push_back(Lo.getValue(1));
4559       Hi = DAG.getNode(ISD::ADDE, VTs, HiOps);
4560     } else {
4561       Lo = DAG.getNode(ISD::SUBC, VTs, LoOps);
4562       HiOps.push_back(Lo.getValue(1));
4563       Hi = DAG.getNode(ISD::SUBE, VTs, HiOps);
4564     }
4565     break;
4566   }
4567   case ISD::MUL: {
4568     if (TLI.isOperationLegal(ISD::MULHU, NVT)) {
4569       SDOperand LL, LH, RL, RH;
4570       ExpandOp(Node->getOperand(0), LL, LH);
4571       ExpandOp(Node->getOperand(1), RL, RH);
4572       unsigned SH = MVT::getSizeInBits(RH.getValueType())-1;
4573       // MULHS implicitly sign extends its inputs.  Check to see if ExpandOp
4574       // extended the sign bit of the low half through the upper half, and if so
4575       // emit a MULHS instead of the alternate sequence that is valid for any
4576       // i64 x i64 multiply.
4577       if (TLI.isOperationLegal(ISD::MULHS, NVT) &&
4578           // is RH an extension of the sign bit of RL?
4579           RH.getOpcode() == ISD::SRA && RH.getOperand(0) == RL &&
4580           RH.getOperand(1).getOpcode() == ISD::Constant &&
4581           cast<ConstantSDNode>(RH.getOperand(1))->getValue() == SH &&
4582           // is LH an extension of the sign bit of LL?
4583           LH.getOpcode() == ISD::SRA && LH.getOperand(0) == LL &&
4584           LH.getOperand(1).getOpcode() == ISD::Constant &&
4585           cast<ConstantSDNode>(LH.getOperand(1))->getValue() == SH) {
4586         Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
4587       } else {
4588         Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
4589         RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
4590         LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
4591         Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
4592         Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
4593       }
4594       Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
4595     } else {
4596       Lo = ExpandLibCall("__muldi3" , Node, Hi);
4597     }
4598     break;
4599   }
4600   case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
4601   case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
4602   case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
4603   case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
4604   }
4605
4606   // Make sure the resultant values have been legalized themselves, unless this
4607   // is a type that requires multi-step expansion.
4608   if (getTypeAction(NVT) != Expand && NVT != MVT::isVoid) {
4609     Lo = LegalizeOp(Lo);
4610     Hi = LegalizeOp(Hi);
4611   }
4612
4613   // Remember in a map if the values will be reused later.
4614   bool isNew =
4615     ExpandedNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
4616   assert(isNew && "Value already expanded?!?");
4617 }
4618
4619 /// SplitVectorOp - Given an operand of MVT::Vector type, break it down into
4620 /// two smaller values of MVT::Vector type.
4621 void SelectionDAGLegalize::SplitVectorOp(SDOperand Op, SDOperand &Lo,
4622                                          SDOperand &Hi) {
4623   assert(Op.getValueType() == MVT::Vector && "Cannot split non-vector type!");
4624   SDNode *Node = Op.Val;
4625   unsigned NumElements = cast<ConstantSDNode>(*(Node->op_end()-2))->getValue();
4626   assert(NumElements > 1 && "Cannot split a single element vector!");
4627   unsigned NewNumElts = NumElements/2;
4628   SDOperand NewNumEltsNode = DAG.getConstant(NewNumElts, MVT::i32);
4629   SDOperand TypeNode = *(Node->op_end()-1);
4630   
4631   // See if we already split it.
4632   std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
4633     = SplitNodes.find(Op);
4634   if (I != SplitNodes.end()) {
4635     Lo = I->second.first;
4636     Hi = I->second.second;
4637     return;
4638   }
4639   
4640   switch (Node->getOpcode()) {
4641   default: Node->dump(); assert(0 && "Unhandled operation in SplitVectorOp!");
4642   case ISD::VBUILD_VECTOR: {
4643     std::vector<SDOperand> LoOps(Node->op_begin(), Node->op_begin()+NewNumElts);
4644     LoOps.push_back(NewNumEltsNode);
4645     LoOps.push_back(TypeNode);
4646     Lo = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, LoOps);
4647
4648     std::vector<SDOperand> HiOps(Node->op_begin()+NewNumElts, Node->op_end()-2);
4649     HiOps.push_back(NewNumEltsNode);
4650     HiOps.push_back(TypeNode);
4651     Hi = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, HiOps);
4652     break;
4653   }
4654   case ISD::VADD:
4655   case ISD::VSUB:
4656   case ISD::VMUL:
4657   case ISD::VSDIV:
4658   case ISD::VUDIV:
4659   case ISD::VAND:
4660   case ISD::VOR:
4661   case ISD::VXOR: {
4662     SDOperand LL, LH, RL, RH;
4663     SplitVectorOp(Node->getOperand(0), LL, LH);
4664     SplitVectorOp(Node->getOperand(1), RL, RH);
4665     
4666     Lo = DAG.getNode(Node->getOpcode(), MVT::Vector, LL, RL,
4667                      NewNumEltsNode, TypeNode);
4668     Hi = DAG.getNode(Node->getOpcode(), MVT::Vector, LH, RH,
4669                      NewNumEltsNode, TypeNode);
4670     break;
4671   }
4672   case ISD::VLOAD: {
4673     SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
4674     SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
4675     MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
4676     
4677     Lo = DAG.getVecLoad(NewNumElts, EVT, Ch, Ptr, Node->getOperand(2));
4678     unsigned IncrementSize = NewNumElts * MVT::getSizeInBits(EVT)/8;
4679     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4680                       getIntPtrConstant(IncrementSize));
4681     // FIXME: This creates a bogus srcvalue!
4682     Hi = DAG.getVecLoad(NewNumElts, EVT, Ch, Ptr, Node->getOperand(2));
4683     
4684     // Build a factor node to remember that this load is independent of the
4685     // other one.
4686     SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
4687                                Hi.getValue(1));
4688     
4689     // Remember that we legalized the chain.
4690     AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
4691     break;
4692   }
4693   case ISD::VBIT_CONVERT: {
4694     // We know the result is a vector.  The input may be either a vector or a
4695     // scalar value.
4696     if (Op.getOperand(0).getValueType() != MVT::Vector) {
4697       // Lower to a store/load.  FIXME: this could be improved probably.
4698       SDOperand Ptr = CreateStackTemporary(Op.getOperand(0).getValueType());
4699
4700       SDOperand St = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
4701                                  Op.getOperand(0), Ptr, DAG.getSrcValue(0));
4702       MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
4703       St = DAG.getVecLoad(NumElements, EVT, St, Ptr, DAG.getSrcValue(0));
4704       SplitVectorOp(St, Lo, Hi);
4705     } else {
4706       // If the input is a vector type, we have to either scalarize it, pack it
4707       // or convert it based on whether the input vector type is legal.
4708       SDNode *InVal = Node->getOperand(0).Val;
4709       unsigned NumElems =
4710         cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
4711       MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
4712
4713       // If the input is from a single element vector, scalarize the vector,
4714       // then treat like a scalar.
4715       if (NumElems == 1) {
4716         SDOperand Scalar = PackVectorOp(Op.getOperand(0), EVT);
4717         Scalar = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Scalar,
4718                              Op.getOperand(1), Op.getOperand(2));
4719         SplitVectorOp(Scalar, Lo, Hi);
4720       } else {
4721         // Split the input vector.
4722         SplitVectorOp(Op.getOperand(0), Lo, Hi);
4723
4724         // Convert each of the pieces now.
4725         Lo = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Lo,
4726                          NewNumEltsNode, TypeNode);
4727         Hi = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Hi,
4728                          NewNumEltsNode, TypeNode);
4729       }
4730       break;
4731     }
4732   }
4733   }
4734       
4735   // Remember in a map if the values will be reused later.
4736   bool isNew =
4737     SplitNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
4738   assert(isNew && "Value already expanded?!?");
4739 }
4740
4741
4742 /// PackVectorOp - Given an operand of MVT::Vector type, convert it into the
4743 /// equivalent operation that returns a scalar (e.g. F32) or packed value
4744 /// (e.g. MVT::V4F32).  When this is called, we know that PackedVT is the right
4745 /// type for the result.
4746 SDOperand SelectionDAGLegalize::PackVectorOp(SDOperand Op, 
4747                                              MVT::ValueType NewVT) {
4748   assert(Op.getValueType() == MVT::Vector && "Bad PackVectorOp invocation!");
4749   SDNode *Node = Op.Val;
4750   
4751   // See if we already packed it.
4752   std::map<SDOperand, SDOperand>::iterator I = PackedNodes.find(Op);
4753   if (I != PackedNodes.end()) return I->second;
4754   
4755   SDOperand Result;
4756   switch (Node->getOpcode()) {
4757   default: 
4758     Node->dump(); std::cerr << "\n";
4759     assert(0 && "Unknown vector operation in PackVectorOp!");
4760   case ISD::VADD:
4761   case ISD::VSUB:
4762   case ISD::VMUL:
4763   case ISD::VSDIV:
4764   case ISD::VUDIV:
4765   case ISD::VAND:
4766   case ISD::VOR:
4767   case ISD::VXOR:
4768     Result = DAG.getNode(getScalarizedOpcode(Node->getOpcode(), NewVT),
4769                          NewVT, 
4770                          PackVectorOp(Node->getOperand(0), NewVT),
4771                          PackVectorOp(Node->getOperand(1), NewVT));
4772     break;
4773   case ISD::VLOAD: {
4774     SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
4775     SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
4776     
4777     Result = DAG.getLoad(NewVT, Ch, Ptr, Node->getOperand(2));
4778     
4779     // Remember that we legalized the chain.
4780     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4781     break;
4782   }
4783   case ISD::VBUILD_VECTOR:
4784     if (Node->getOperand(0).getValueType() == NewVT) {
4785       // Returning a scalar?
4786       Result = Node->getOperand(0);
4787     } else {
4788       // Returning a BUILD_VECTOR?
4789       
4790       // If all elements of the build_vector are undefs, return an undef.
4791       bool AllUndef = true;
4792       for (unsigned i = 0, e = Node->getNumOperands()-2; i != e; ++i)
4793         if (Node->getOperand(i).getOpcode() != ISD::UNDEF) {
4794           AllUndef = false;
4795           break;
4796         }
4797       if (AllUndef) {
4798         Result = DAG.getNode(ISD::UNDEF, NewVT);
4799       } else {
4800         std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end()-2);
4801         Result = DAG.getNode(ISD::BUILD_VECTOR, NewVT, Ops);
4802       }
4803     }
4804     break;
4805   case ISD::VINSERT_VECTOR_ELT:
4806     if (!MVT::isVector(NewVT)) {
4807       // Returning a scalar?  Must be the inserted element.
4808       Result = Node->getOperand(1);
4809     } else {
4810       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT,
4811                            PackVectorOp(Node->getOperand(0), NewVT),
4812                            Node->getOperand(1), Node->getOperand(2));
4813     }
4814     break;
4815   case ISD::VVECTOR_SHUFFLE:
4816     if (!MVT::isVector(NewVT)) {
4817       // Returning a scalar?  Figure out if it is the LHS or RHS and return it.
4818       SDOperand EltNum = Node->getOperand(2).getOperand(0);
4819       if (cast<ConstantSDNode>(EltNum)->getValue())
4820         Result = PackVectorOp(Node->getOperand(1), NewVT);
4821       else
4822         Result = PackVectorOp(Node->getOperand(0), NewVT);
4823     } else {
4824       // Otherwise, return a VECTOR_SHUFFLE node.  First convert the index
4825       // vector from a VBUILD_VECTOR to a BUILD_VECTOR.
4826       std::vector<SDOperand> BuildVecIdx(Node->getOperand(2).Val->op_begin(),
4827                                          Node->getOperand(2).Val->op_end()-2);
4828       MVT::ValueType BVT = MVT::getIntVectorWithNumElements(BuildVecIdx.size());
4829       SDOperand BV = DAG.getNode(ISD::BUILD_VECTOR, BVT, BuildVecIdx);
4830       
4831       Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT,
4832                            PackVectorOp(Node->getOperand(0), NewVT),
4833                            PackVectorOp(Node->getOperand(1), NewVT), BV);
4834     }
4835     break;
4836   case ISD::VBIT_CONVERT:
4837     if (Op.getOperand(0).getValueType() != MVT::Vector)
4838       Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, Op.getOperand(0));
4839     else {
4840       // If the input is a vector type, we have to either scalarize it, pack it
4841       // or convert it based on whether the input vector type is legal.
4842       SDNode *InVal = Node->getOperand(0).Val;
4843       unsigned NumElems =
4844         cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
4845       MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
4846         
4847       // Figure out if there is a Packed type corresponding to this Vector
4848       // type.  If so, convert to the packed type.
4849       MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
4850       if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
4851         // Turn this into a bit convert of the packed input.
4852         Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, 
4853                              PackVectorOp(Node->getOperand(0), TVT));
4854         break;
4855       } else if (NumElems == 1) {
4856         // Turn this into a bit convert of the scalar input.
4857         Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, 
4858                              PackVectorOp(Node->getOperand(0), EVT));
4859         break;
4860       } else {
4861         // FIXME: UNIMP!
4862         assert(0 && "Cast from unsupported vector type not implemented yet!");
4863       }
4864     }
4865     break;
4866   case ISD::VSELECT:
4867     Result = DAG.getNode(ISD::SELECT, NewVT, Op.getOperand(0),
4868                          PackVectorOp(Op.getOperand(1), NewVT),
4869                          PackVectorOp(Op.getOperand(2), NewVT));
4870     break;
4871   }
4872
4873   if (TLI.isTypeLegal(NewVT))
4874     Result = LegalizeOp(Result);
4875   bool isNew = PackedNodes.insert(std::make_pair(Op, Result)).second;
4876   assert(isNew && "Value already packed?");
4877   return Result;
4878 }
4879
4880
4881 // SelectionDAG::Legalize - This is the entry point for the file.
4882 //
4883 void SelectionDAG::Legalize() {
4884   if (ViewLegalizeDAGs) viewGraph();
4885
4886   /// run - This is the main entry point to this class.
4887   ///
4888   SelectionDAGLegalize(*this).LegalizeDAG();
4889 }
4890