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