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