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