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