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