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