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