Teach Legalize how to pack VVECTOR_SHUFFLE nodes into VECTOR_SHUFFLE nodes.
[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/Support/MathExtras.h"
18 #include "llvm/Target/TargetLowering.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Target/TargetOptions.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include <iostream>
24 #include <map>
25 using namespace llvm;
26
27 //===----------------------------------------------------------------------===//
28 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
29 /// hacks on it until the target machine can handle it.  This involves
30 /// eliminating value sizes the machine cannot handle (promoting small sizes to
31 /// large sizes or splitting up large values into small values) as well as
32 /// eliminating operations the machine cannot handle.
33 ///
34 /// This code also does a small amount of optimization and recognition of idioms
35 /// as part of its processing.  For example, if a target does not support a
36 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
37 /// will attempt merge setcc and brc instructions into brcc's.
38 ///
39 namespace {
40 class SelectionDAGLegalize {
41   TargetLowering &TLI;
42   SelectionDAG &DAG;
43
44   // Libcall insertion helpers.
45   
46   /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
47   /// legalized.  We use this to ensure that calls are properly serialized
48   /// against each other, including inserted libcalls.
49   SDOperand LastCALLSEQ_END;
50   
51   /// IsLegalizingCall - This member is used *only* for purposes of providing
52   /// helpful assertions that a libcall isn't created while another call is 
53   /// being legalized (which could lead to non-serialized call sequences).
54   bool IsLegalizingCall;
55   
56   enum LegalizeAction {
57     Legal,      // The target natively supports this operation.
58     Promote,    // This operation should be executed in a larger type.
59     Expand,     // Try to expand this to other ops, otherwise use a libcall.
60   };
61   
62   /// ValueTypeActions - This is a bitvector that contains two bits for each
63   /// value type, where the two bits correspond to the LegalizeAction enum.
64   /// This can be queried with "getTypeAction(VT)".
65   TargetLowering::ValueTypeActionImpl ValueTypeActions;
66
67   /// LegalizedNodes - For nodes that are of legal width, and that have more
68   /// than one use, this map indicates what regularized operand to use.  This
69   /// allows us to avoid legalizing the same thing more than once.
70   std::map<SDOperand, SDOperand> LegalizedNodes;
71
72   /// PromotedNodes - For nodes that are below legal width, and that have more
73   /// than one use, this map indicates what promoted value to use.  This allows
74   /// us to avoid promoting the same thing more than once.
75   std::map<SDOperand, SDOperand> PromotedNodes;
76
77   /// ExpandedNodes - For nodes that need to be expanded this map indicates
78   /// which which operands are the expanded version of the input.  This allows
79   /// us to avoid expanding the same node more than once.
80   std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
81
82   /// SplitNodes - For vector nodes that need to be split, this map indicates
83   /// which which operands are the split version of the input.  This allows us
84   /// to avoid splitting the same node more than once.
85   std::map<SDOperand, std::pair<SDOperand, SDOperand> > SplitNodes;
86   
87   /// PackedNodes - For nodes that need to be packed from MVT::Vector types to
88   /// concrete packed types, this contains the mapping of ones we have already
89   /// processed to the result.
90   std::map<SDOperand, SDOperand> PackedNodes;
91   
92   void AddLegalizedOperand(SDOperand From, SDOperand To) {
93     LegalizedNodes.insert(std::make_pair(From, To));
94     // If someone requests legalization of the new node, return itself.
95     if (From != To)
96       LegalizedNodes.insert(std::make_pair(To, To));
97   }
98   void AddPromotedOperand(SDOperand From, SDOperand To) {
99     bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
100     assert(isNew && "Got into the map somehow?");
101     // If someone requests legalization of the new node, return itself.
102     LegalizedNodes.insert(std::make_pair(To, To));
103   }
104
105 public:
106
107   SelectionDAGLegalize(SelectionDAG &DAG);
108
109   /// getTypeAction - Return how we should legalize values of this type, either
110   /// it is already legal or we need to expand it into multiple registers of
111   /// smaller integer type, or we need to promote it to a larger type.
112   LegalizeAction getTypeAction(MVT::ValueType VT) const {
113     return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
114   }
115
116   /// isTypeLegal - Return true if this type is legal on this target.
117   ///
118   bool isTypeLegal(MVT::ValueType VT) const {
119     return getTypeAction(VT) == Legal;
120   }
121
122   void LegalizeDAG();
123
124 private:
125   /// HandleOp - Legalize, Promote, Expand or Pack the specified operand as
126   /// appropriate for its type.
127   void HandleOp(SDOperand Op);
128     
129   /// LegalizeOp - We know that the specified value has a legal type.
130   /// Recursively ensure that the operands have legal types, then return the
131   /// result.
132   SDOperand LegalizeOp(SDOperand O);
133   
134   /// PromoteOp - Given an operation that produces a value in an invalid type,
135   /// promote it to compute the value into a larger type.  The produced value
136   /// will have the correct bits for the low portion of the register, but no
137   /// guarantee is made about the top bits: it may be zero, sign-extended, or
138   /// garbage.
139   SDOperand PromoteOp(SDOperand O);
140
141   /// ExpandOp - Expand the specified SDOperand into its two component pieces
142   /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this,
143   /// the LegalizeNodes map is filled in for any results that are not expanded,
144   /// the ExpandedNodes map is filled in for any results that are expanded, and
145   /// the Lo/Hi values are returned.   This applies to integer types and Vector
146   /// types.
147   void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
148
149   /// SplitVectorOp - Given an operand of MVT::Vector type, break it down into
150   /// two smaller values of MVT::Vector type.
151   void SplitVectorOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
152   
153   /// PackVectorOp - Given an operand of MVT::Vector type, convert it into the
154   /// equivalent operation that returns a packed value (e.g. MVT::V4F32).  When
155   /// this is called, we know that PackedVT is the right type for the result and
156   /// we know that this type is legal for the target.
157   SDOperand PackVectorOp(SDOperand O, MVT::ValueType PackedVT);
158   
159   bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest);
160
161   void LegalizeSetCCOperands(SDOperand &LHS, SDOperand &RHS, SDOperand &CC);
162     
163   SDOperand CreateStackTemporary(MVT::ValueType VT);
164
165   SDOperand ExpandLibCall(const char *Name, SDNode *Node,
166                           SDOperand &Hi);
167   SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
168                           SDOperand Source);
169
170   SDOperand ExpandBIT_CONVERT(MVT::ValueType DestVT, SDOperand SrcOp);
171   SDOperand ExpandBUILD_VECTOR(SDNode *Node);
172   SDOperand ExpandLegalINT_TO_FP(bool isSigned,
173                                  SDOperand LegalOp,
174                                  MVT::ValueType DestVT);
175   SDOperand PromoteLegalINT_TO_FP(SDOperand LegalOp, MVT::ValueType DestVT,
176                                   bool isSigned);
177   SDOperand PromoteLegalFP_TO_INT(SDOperand LegalOp, MVT::ValueType DestVT,
178                                   bool isSigned);
179
180   SDOperand ExpandBSWAP(SDOperand Op);
181   SDOperand ExpandBitCount(unsigned Opc, SDOperand Op);
182   bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
183                    SDOperand &Lo, SDOperand &Hi);
184   void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
185                         SDOperand &Lo, SDOperand &Hi);
186
187   SDOperand getIntPtrConstant(uint64_t Val) {
188     return DAG.getConstant(Val, TLI.getPointerTy());
189   }
190 };
191 }
192
193 /// getScalarizedOpcode - Return the scalar opcode that corresponds to the
194 /// specified vector opcode.
195 static unsigned getScalarizedOpcode(unsigned VecOp, MVT::ValueType VT) {
196   switch (VecOp) {
197   default: assert(0 && "Don't know how to scalarize this opcode!");
198   case ISD::VADD:  return MVT::isInteger(VT) ? ISD::ADD : ISD::FADD;
199   case ISD::VSUB:  return MVT::isInteger(VT) ? ISD::SUB : ISD::FSUB;
200   case ISD::VMUL:  return MVT::isInteger(VT) ? ISD::MUL : ISD::FMUL;
201   case ISD::VSDIV: return MVT::isInteger(VT) ? ISD::SDIV: ISD::FDIV;
202   case ISD::VUDIV: return MVT::isInteger(VT) ? ISD::UDIV: ISD::FDIV;
203   case ISD::VAND:  return MVT::isInteger(VT) ? ISD::AND : 0;
204   case ISD::VOR:   return MVT::isInteger(VT) ? ISD::OR  : 0;
205   case ISD::VXOR:  return MVT::isInteger(VT) ? ISD::XOR : 0;
206   }
207 }
208
209 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
210   : TLI(dag.getTargetLoweringInfo()), DAG(dag),
211     ValueTypeActions(TLI.getValueTypeActions()) {
212   assert(MVT::LAST_VALUETYPE <= 32 &&
213          "Too many value types for ValueTypeActions to hold!");
214 }
215
216 /// ComputeTopDownOrdering - Add the specified node to the Order list if it has
217 /// not been visited yet and if all of its operands have already been visited.
218 static void ComputeTopDownOrdering(SDNode *N, std::vector<SDNode*> &Order,
219                                    std::map<SDNode*, unsigned> &Visited) {
220   if (++Visited[N] != N->getNumOperands())
221     return;  // Haven't visited all operands yet
222   
223   Order.push_back(N);
224   
225   if (N->hasOneUse()) { // Tail recurse in common case.
226     ComputeTopDownOrdering(*N->use_begin(), Order, Visited);
227     return;
228   }
229   
230   // Now that we have N in, add anything that uses it if all of their operands
231   // are now done.
232   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); UI != E;++UI)
233     ComputeTopDownOrdering(*UI, Order, Visited);
234 }
235
236
237 void SelectionDAGLegalize::LegalizeDAG() {
238   LastCALLSEQ_END = DAG.getEntryNode();
239   IsLegalizingCall = false;
240   
241   // The legalize process is inherently a bottom-up recursive process (users
242   // legalize their uses before themselves).  Given infinite stack space, we
243   // could just start legalizing on the root and traverse the whole graph.  In
244   // practice however, this causes us to run out of stack space on large basic
245   // blocks.  To avoid this problem, compute an ordering of the nodes where each
246   // node is only legalized after all of its operands are legalized.
247   std::map<SDNode*, unsigned> Visited;
248   std::vector<SDNode*> Order;
249   
250   // Compute ordering from all of the leaves in the graphs, those (like the
251   // entry node) that have no operands.
252   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
253        E = DAG.allnodes_end(); I != E; ++I) {
254     if (I->getNumOperands() == 0) {
255       Visited[I] = 0 - 1U;
256       ComputeTopDownOrdering(I, Order, Visited);
257     }
258   }
259   
260   assert(Order.size() == Visited.size() &&
261          Order.size() == 
262             (unsigned)std::distance(DAG.allnodes_begin(), DAG.allnodes_end()) &&
263          "Error: DAG is cyclic!");
264   Visited.clear();
265   
266   for (unsigned i = 0, e = Order.size(); i != e; ++i)
267     HandleOp(SDOperand(Order[i], 0));
268
269   // Finally, it's possible the root changed.  Get the new root.
270   SDOperand OldRoot = DAG.getRoot();
271   assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
272   DAG.setRoot(LegalizedNodes[OldRoot]);
273
274   ExpandedNodes.clear();
275   LegalizedNodes.clear();
276   PromotedNodes.clear();
277   SplitNodes.clear();
278   PackedNodes.clear();
279
280   // Remove dead nodes now.
281   DAG.RemoveDeadNodes(OldRoot.Val);
282 }
283
284
285 /// FindCallEndFromCallStart - Given a chained node that is part of a call
286 /// sequence, find the CALLSEQ_END node that terminates the call sequence.
287 static SDNode *FindCallEndFromCallStart(SDNode *Node) {
288   if (Node->getOpcode() == ISD::CALLSEQ_END)
289     return Node;
290   if (Node->use_empty())
291     return 0;   // No CallSeqEnd
292   
293   // The chain is usually at the end.
294   SDOperand TheChain(Node, Node->getNumValues()-1);
295   if (TheChain.getValueType() != MVT::Other) {
296     // Sometimes it's at the beginning.
297     TheChain = SDOperand(Node, 0);
298     if (TheChain.getValueType() != MVT::Other) {
299       // Otherwise, hunt for it.
300       for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
301         if (Node->getValueType(i) == MVT::Other) {
302           TheChain = SDOperand(Node, i);
303           break;
304         }
305           
306       // Otherwise, we walked into a node without a chain.  
307       if (TheChain.getValueType() != MVT::Other)
308         return 0;
309     }
310   }
311   
312   for (SDNode::use_iterator UI = Node->use_begin(),
313        E = Node->use_end(); UI != E; ++UI) {
314     
315     // Make sure to only follow users of our token chain.
316     SDNode *User = *UI;
317     for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
318       if (User->getOperand(i) == TheChain)
319         if (SDNode *Result = FindCallEndFromCallStart(User))
320           return Result;
321   }
322   return 0;
323 }
324
325 /// FindCallStartFromCallEnd - Given a chained node that is part of a call 
326 /// sequence, find the CALLSEQ_START node that initiates the call sequence.
327 static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
328   assert(Node && "Didn't find callseq_start for a call??");
329   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
330   
331   assert(Node->getOperand(0).getValueType() == MVT::Other &&
332          "Node doesn't have a token chain argument!");
333   return FindCallStartFromCallEnd(Node->getOperand(0).Val);
334 }
335
336 /// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
337 /// see if any uses can reach Dest.  If no dest operands can get to dest, 
338 /// legalize them, legalize ourself, and return false, otherwise, return true.
339 bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, 
340                                                         SDNode *Dest) {
341   if (N == Dest) return true;  // N certainly leads to Dest :)
342   
343   // If the first result of this node has been already legalized, then it cannot
344   // reach N.
345   switch (getTypeAction(N->getValueType(0))) {
346   case Legal: 
347     if (LegalizedNodes.count(SDOperand(N, 0))) return false;
348     break;
349   case Promote:
350     if (PromotedNodes.count(SDOperand(N, 0))) return false;
351     break;
352   case Expand:
353     if (ExpandedNodes.count(SDOperand(N, 0))) return false;
354     break;
355   }
356   
357   // Okay, this node has not already been legalized.  Check and legalize all
358   // operands.  If none lead to Dest, then we can legalize this node.
359   bool OperandsLeadToDest = false;
360   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
361     OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
362       LegalizeAllNodesNotLeadingTo(N->getOperand(i).Val, Dest);
363
364   if (OperandsLeadToDest) return true;
365
366   // Okay, this node looks safe, legalize it and return false.
367   switch (getTypeAction(N->getValueType(0))) {
368   case Legal:
369     LegalizeOp(SDOperand(N, 0));
370     break;
371   case Promote:
372     PromoteOp(SDOperand(N, 0));
373     break;
374   case Expand: {
375     SDOperand X, Y;
376     ExpandOp(SDOperand(N, 0), X, Y);
377     break;
378   }
379   }
380   return false;
381 }
382
383 /// HandleOp - Legalize, Promote, Expand or Pack the specified operand as
384 /// appropriate for its type.
385 void SelectionDAGLegalize::HandleOp(SDOperand Op) {
386   switch (getTypeAction(Op.getValueType())) {
387   default: assert(0 && "Bad type action!");
388   case Legal:   LegalizeOp(Op); break;
389   case Promote: PromoteOp(Op);  break;
390   case Expand:
391     if (Op.getValueType() != MVT::Vector) {
392       SDOperand X, Y;
393       ExpandOp(Op, X, Y);
394     } else {
395       SDNode *N = Op.Val;
396       unsigned NumOps = N->getNumOperands();
397       unsigned NumElements =
398         cast<ConstantSDNode>(N->getOperand(NumOps-2))->getValue();
399       MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(NumOps-1))->getVT();
400       MVT::ValueType PackedVT = getVectorType(EVT, NumElements);
401       if (PackedVT != MVT::Other && TLI.isTypeLegal(PackedVT)) {
402         // In the common case, this is a legal vector type, convert it to the
403         // packed operation and type now.
404         PackVectorOp(Op, PackedVT);
405       } else if (NumElements == 1) {
406         // Otherwise, if this is a single element vector, convert it to a
407         // scalar operation.
408         PackVectorOp(Op, EVT);
409       } else {
410         // Otherwise, this is a multiple element vector that isn't supported.
411         // Split it in half and legalize both parts.
412         SDOperand X, Y;
413         SplitVectorOp(Op, X, Y);
414       }
415     }
416     break;
417   }
418 }
419
420
421 /// LegalizeOp - We know that the specified value has a legal type.
422 /// Recursively ensure that the operands have legal types, then return the
423 /// result.
424 SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
425   assert(isTypeLegal(Op.getValueType()) &&
426          "Caller should expand or promote operands that are not legal!");
427   SDNode *Node = Op.Val;
428
429   // If this operation defines any values that cannot be represented in a
430   // register on this target, make sure to expand or promote them.
431   if (Node->getNumValues() > 1) {
432     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
433       if (getTypeAction(Node->getValueType(i)) != Legal) {
434         HandleOp(Op.getValue(i));
435         assert(LegalizedNodes.count(Op) &&
436                "Handling didn't add legal operands!");
437         return LegalizedNodes[Op];
438       }
439   }
440
441   // Note that LegalizeOp may be reentered even from single-use nodes, which
442   // means that we always must cache transformed nodes.
443   std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
444   if (I != LegalizedNodes.end()) return I->second;
445
446   SDOperand Tmp1, Tmp2, Tmp3, Tmp4;
447   SDOperand Result = Op;
448   bool isCustom = false;
449   
450   switch (Node->getOpcode()) {
451   case ISD::FrameIndex:
452   case ISD::EntryToken:
453   case ISD::Register:
454   case ISD::BasicBlock:
455   case ISD::TargetFrameIndex:
456   case ISD::TargetConstant:
457   case ISD::TargetConstantFP:
458   case ISD::TargetConstantPool:
459   case ISD::TargetGlobalAddress:
460   case ISD::TargetExternalSymbol:
461   case ISD::VALUETYPE:
462   case ISD::SRCVALUE:
463   case ISD::STRING:
464   case ISD::CONDCODE:
465     // Primitives must all be legal.
466     assert(TLI.isOperationLegal(Node->getValueType(0), Node->getValueType(0)) &&
467            "This must be legal!");
468     break;
469   default:
470     if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
471       // If this is a target node, legalize it by legalizing the operands then
472       // passing it through.
473       std::vector<SDOperand> Ops;
474       bool Changed = false;
475       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
476         Ops.push_back(LegalizeOp(Node->getOperand(i)));
477         Changed = Changed || Node->getOperand(i) != Ops.back();
478       }
479       if (Changed)
480         if (Node->getNumValues() == 1)
481           Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
482         else {
483           std::vector<MVT::ValueType> VTs(Node->value_begin(),
484                                           Node->value_end());
485           Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
486         }
487
488       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
489         AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
490       return Result.getValue(Op.ResNo);
491     }
492     // Otherwise this is an unhandled builtin node.  splat.
493     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
494     assert(0 && "Do not know how to legalize this operator!");
495     abort();
496   case ISD::GlobalAddress:
497   case ISD::ExternalSymbol:
498   case ISD::ConstantPool:           // Nothing to do.
499     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
500     default: assert(0 && "This action is not supported yet!");
501     case TargetLowering::Custom:
502       Tmp1 = TLI.LowerOperation(Op, DAG);
503       if (Tmp1.Val) Result = Tmp1;
504       // FALLTHROUGH if the target doesn't want to lower this op after all.
505     case TargetLowering::Legal:
506       break;
507     }
508     break;
509   case ISD::AssertSext:
510   case ISD::AssertZext:
511     Tmp1 = LegalizeOp(Node->getOperand(0));
512     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
513     break;
514   case ISD::MERGE_VALUES:
515     // Legalize eliminates MERGE_VALUES nodes.
516     Result = Node->getOperand(Op.ResNo);
517     break;
518   case ISD::CopyFromReg:
519     Tmp1 = LegalizeOp(Node->getOperand(0));
520     Result = Op.getValue(0);
521     if (Node->getNumValues() == 2) {
522       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
523     } else {
524       assert(Node->getNumValues() == 3 && "Invalid copyfromreg!");
525       if (Node->getNumOperands() == 3) {
526         Tmp2 = LegalizeOp(Node->getOperand(2));
527         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
528       } else {
529         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
530       }
531       AddLegalizedOperand(Op.getValue(2), Result.getValue(2));
532     }
533     // Since CopyFromReg produces two values, make sure to remember that we
534     // legalized both of them.
535     AddLegalizedOperand(Op.getValue(0), Result);
536     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
537     return Result.getValue(Op.ResNo);
538   case ISD::UNDEF: {
539     MVT::ValueType VT = Op.getValueType();
540     switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
541     default: assert(0 && "This action is not supported yet!");
542     case TargetLowering::Expand:
543       if (MVT::isInteger(VT))
544         Result = DAG.getConstant(0, VT);
545       else if (MVT::isFloatingPoint(VT))
546         Result = DAG.getConstantFP(0, VT);
547       else
548         assert(0 && "Unknown value type!");
549       break;
550     case TargetLowering::Legal:
551       break;
552     }
553     break;
554   }
555     
556   case ISD::INTRINSIC_W_CHAIN:
557   case ISD::INTRINSIC_WO_CHAIN:
558   case ISD::INTRINSIC_VOID: {
559     std::vector<SDOperand> Ops;
560     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
561       Ops.push_back(LegalizeOp(Node->getOperand(i)));
562     Result = DAG.UpdateNodeOperands(Result, Ops);
563     
564     // Allow the target to custom lower its intrinsics if it wants to.
565     if (TLI.getOperationAction(Node->getOpcode(), MVT::Other) == 
566         TargetLowering::Custom) {
567       Tmp3 = TLI.LowerOperation(Result, DAG);
568       if (Tmp3.Val) Result = Tmp3;
569     }
570
571     if (Result.Val->getNumValues() == 1) break;
572
573     // Must have return value and chain result.
574     assert(Result.Val->getNumValues() == 2 &&
575            "Cannot return more than two values!");
576
577     // Since loads produce two values, make sure to remember that we 
578     // legalized both of them.
579     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
580     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
581     return Result.getValue(Op.ResNo);
582   }    
583
584   case ISD::LOCATION:
585     assert(Node->getNumOperands() == 5 && "Invalid LOCATION node!");
586     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
587     
588     switch (TLI.getOperationAction(ISD::LOCATION, MVT::Other)) {
589     case TargetLowering::Promote:
590     default: assert(0 && "This action is not supported yet!");
591     case TargetLowering::Expand: {
592       MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
593       bool useDEBUG_LOC = TLI.isOperationLegal(ISD::DEBUG_LOC, MVT::Other);
594       bool useDEBUG_LABEL = TLI.isOperationLegal(ISD::DEBUG_LABEL, MVT::Other);
595       
596       if (DebugInfo && (useDEBUG_LOC || useDEBUG_LABEL)) {
597         const std::string &FName =
598           cast<StringSDNode>(Node->getOperand(3))->getValue();
599         const std::string &DirName = 
600           cast<StringSDNode>(Node->getOperand(4))->getValue();
601         unsigned SrcFile = DebugInfo->RecordSource(DirName, FName);
602
603         std::vector<SDOperand> Ops;
604         Ops.push_back(Tmp1);  // chain
605         SDOperand LineOp = Node->getOperand(1);
606         SDOperand ColOp = Node->getOperand(2);
607         
608         if (useDEBUG_LOC) {
609           Ops.push_back(LineOp);  // line #
610           Ops.push_back(ColOp);  // col #
611           Ops.push_back(DAG.getConstant(SrcFile, MVT::i32));  // source file id
612           Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, Ops);
613         } else {
614           unsigned Line = cast<ConstantSDNode>(LineOp)->getValue();
615           unsigned Col = cast<ConstantSDNode>(ColOp)->getValue();
616           unsigned ID = DebugInfo->RecordLabel(Line, Col, SrcFile);
617           Ops.push_back(DAG.getConstant(ID, MVT::i32));
618           Result = DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops);
619         }
620       } else {
621         Result = Tmp1;  // chain
622       }
623       break;
624     }
625     case TargetLowering::Legal:
626       if (Tmp1 != Node->getOperand(0) ||
627           getTypeAction(Node->getOperand(1).getValueType()) == Promote) {
628         std::vector<SDOperand> Ops;
629         Ops.push_back(Tmp1);
630         if (getTypeAction(Node->getOperand(1).getValueType()) == Legal) {
631           Ops.push_back(Node->getOperand(1));  // line # must be legal.
632           Ops.push_back(Node->getOperand(2));  // col # must be legal.
633         } else {
634           // Otherwise promote them.
635           Ops.push_back(PromoteOp(Node->getOperand(1)));
636           Ops.push_back(PromoteOp(Node->getOperand(2)));
637         }
638         Ops.push_back(Node->getOperand(3));  // filename must be legal.
639         Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
640         Result = DAG.UpdateNodeOperands(Result, Ops);
641       }
642       break;
643     }
644     break;
645     
646   case ISD::DEBUG_LOC:
647     assert(Node->getNumOperands() == 4 && "Invalid DEBUG_LOC node!");
648     switch (TLI.getOperationAction(ISD::DEBUG_LOC, MVT::Other)) {
649     default: assert(0 && "This action is not supported yet!");
650     case TargetLowering::Legal:
651       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
652       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the line #.
653       Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the col #.
654       Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize the source file id.
655       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
656       break;
657     }
658     break;    
659
660   case ISD::DEBUG_LABEL:
661     assert(Node->getNumOperands() == 2 && "Invalid DEBUG_LABEL node!");
662     switch (TLI.getOperationAction(ISD::DEBUG_LABEL, MVT::Other)) {
663     default: assert(0 && "This action is not supported yet!");
664     case TargetLowering::Legal:
665       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
666       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the label id.
667       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
668       break;
669     }
670     break;
671
672   case ISD::Constant:
673     // We know we don't need to expand constants here, constants only have one
674     // value and we check that it is fine above.
675
676     // FIXME: Maybe we should handle things like targets that don't support full
677     // 32-bit immediates?
678     break;
679   case ISD::ConstantFP: {
680     // Spill FP immediates to the constant pool if the target cannot directly
681     // codegen them.  Targets often have some immediate values that can be
682     // efficiently generated into an FP register without a load.  We explicitly
683     // leave these constants as ConstantFP nodes for the target to deal with.
684     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
685
686     // Check to see if this FP immediate is already legal.
687     bool isLegal = false;
688     for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
689            E = TLI.legal_fpimm_end(); I != E; ++I)
690       if (CFP->isExactlyValue(*I)) {
691         isLegal = true;
692         break;
693       }
694
695     // If this is a legal constant, turn it into a TargetConstantFP node.
696     if (isLegal) {
697       Result = DAG.getTargetConstantFP(CFP->getValue(), CFP->getValueType(0));
698       break;
699     }
700
701     switch (TLI.getOperationAction(ISD::ConstantFP, CFP->getValueType(0))) {
702     default: assert(0 && "This action is not supported yet!");
703     case TargetLowering::Custom:
704       Tmp3 = TLI.LowerOperation(Result, DAG);
705       if (Tmp3.Val) {
706         Result = Tmp3;
707         break;
708       }
709       // FALLTHROUGH
710     case TargetLowering::Expand:
711       // Otherwise we need to spill the constant to memory.
712       bool Extend = false;
713
714       // If a FP immediate is precise when represented as a float and if the
715       // target can do an extending load from float to double, we put it into
716       // the constant pool as a float, even if it's is statically typed as a
717       // double.
718       MVT::ValueType VT = CFP->getValueType(0);
719       bool isDouble = VT == MVT::f64;
720       ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
721                                              Type::FloatTy, CFP->getValue());
722       if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
723           // Only do this if the target has a native EXTLOAD instruction from
724           // f32.
725           TLI.isOperationLegal(ISD::EXTLOAD, MVT::f32)) {
726         LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
727         VT = MVT::f32;
728         Extend = true;
729       }
730
731       SDOperand CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
732       if (Extend) {
733         Result = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
734                                 CPIdx, DAG.getSrcValue(NULL), MVT::f32);
735       } else {
736         Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
737                              DAG.getSrcValue(NULL));
738       }
739     }
740     break;
741   }
742   case ISD::TokenFactor:
743     if (Node->getNumOperands() == 2) {
744       Tmp1 = LegalizeOp(Node->getOperand(0));
745       Tmp2 = LegalizeOp(Node->getOperand(1));
746       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
747     } else if (Node->getNumOperands() == 3) {
748       Tmp1 = LegalizeOp(Node->getOperand(0));
749       Tmp2 = LegalizeOp(Node->getOperand(1));
750       Tmp3 = LegalizeOp(Node->getOperand(2));
751       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
752     } else {
753       std::vector<SDOperand> Ops;
754       // Legalize the operands.
755       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
756         Ops.push_back(LegalizeOp(Node->getOperand(i)));
757       Result = DAG.UpdateNodeOperands(Result, Ops);
758     }
759     break;
760
761   case ISD::BUILD_VECTOR:
762     switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
763     default: assert(0 && "This action is not supported yet!");
764     case TargetLowering::Custom:
765       Tmp3 = TLI.LowerOperation(Result, DAG);
766       if (Tmp3.Val) {
767         Result = Tmp3;
768         break;
769       }
770       // FALLTHROUGH
771     case TargetLowering::Expand:
772       Result = ExpandBUILD_VECTOR(Result.Val);
773       break;
774     }
775     break;
776   case ISD::INSERT_VECTOR_ELT:
777     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVec
778     Tmp2 = LegalizeOp(Node->getOperand(1));  // InVal
779     Tmp3 = LegalizeOp(Node->getOperand(2));  // InEltNo
780     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
781     
782     switch (TLI.getOperationAction(ISD::INSERT_VECTOR_ELT,
783                                    Node->getValueType(0))) {
784     default: assert(0 && "This action is not supported yet!");
785     case TargetLowering::Legal:
786       break;
787     case TargetLowering::Custom:
788       Tmp3 = TLI.LowerOperation(Result, DAG);
789       if (Tmp3.Val) {
790         Result = Tmp3;
791         break;
792       }
793       // FALLTHROUGH
794     case TargetLowering::Expand: {
795       // If the target doesn't support this, we have to spill the input vector
796       // to a temporary stack slot, update the element, then reload it.  This is
797       // badness.  We could also load the value into a vector register (either
798       // with a "move to register" or "extload into register" instruction, then
799       // permute it into place, if the idx is a constant and if the idx is
800       // supported by the target.
801       assert(0 && "INSERT_VECTOR_ELT expand not supported yet!");
802       break;
803     }
804     }
805     break;
806   case ISD::SCALAR_TO_VECTOR:
807     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVal
808     Result = DAG.UpdateNodeOperands(Result, Tmp1);
809     switch (TLI.getOperationAction(ISD::SCALAR_TO_VECTOR,
810                                    Node->getValueType(0))) {
811     default: assert(0 && "This action is not supported yet!");
812     case TargetLowering::Legal:
813       break;
814     case TargetLowering::Custom:
815       Tmp3 = TLI.LowerOperation(Result, DAG);
816       if (Tmp3.Val) {
817         Result = Tmp3;
818         break;
819       }
820       // FALLTHROUGH
821     case TargetLowering::Expand: {
822       // If the target doesn't support this, store the value to a temporary
823       // stack slot, then EXTLOAD the vector back out.
824       // TODO: If a target doesn't support this, create a stack slot for the
825       // whole vector, then store into it, then load the whole vector.
826       SDOperand StackPtr = 
827         CreateStackTemporary(Node->getOperand(0).getValueType());
828       SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
829                                  Node->getOperand(0), StackPtr,
830                                  DAG.getSrcValue(NULL));
831       Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0), Ch, StackPtr,
832                               DAG.getSrcValue(NULL),
833                               Node->getOperand(0).getValueType());
834       break;
835     }
836     }
837     break;
838   case ISD::VECTOR_SHUFFLE:
839     assert(TLI.isShuffleLegal(Result.getValueType(), Node->getOperand(2)) &&
840            "vector shuffle should not be created if not legal!");
841     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the input vectors,
842     Tmp2 = LegalizeOp(Node->getOperand(1));   // but not the shuffle mask.
843     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
844
845     // Allow targets to custom lower the SHUFFLEs they support.
846     if (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, Result.getValueType())
847         == TargetLowering::Custom) {
848       Tmp1 = TLI.LowerOperation(Result, DAG);
849       if (Tmp1.Val) Result = Tmp1;
850     }
851     break;
852   
853   case ISD::EXTRACT_VECTOR_ELT:
854     Tmp1 = LegalizeOp(Node->getOperand(0));
855     Tmp2 = LegalizeOp(Node->getOperand(1));
856     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
857     
858     switch (TLI.getOperationAction(ISD::EXTRACT_VECTOR_ELT,
859                                    Tmp1.getValueType())) {
860     default: assert(0 && "This action is not supported yet!");
861     case TargetLowering::Legal:
862       break;
863     case TargetLowering::Custom:
864       Tmp3 = TLI.LowerOperation(Result, DAG);
865       if (Tmp3.Val) {
866         Result = Tmp3;
867         break;
868       }
869       // FALLTHROUGH
870     case TargetLowering::Expand: {
871       // If the target doesn't support this, store the value to a temporary
872       // stack slot, then LOAD the scalar element back out.
873       SDOperand StackPtr = CreateStackTemporary(Tmp1.getValueType());
874       SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
875                                  Tmp1, StackPtr, DAG.getSrcValue(NULL));
876       
877       // Add the offset to the index.
878       unsigned EltSize = MVT::getSizeInBits(Result.getValueType())/8;
879       Tmp2 = DAG.getNode(ISD::MUL, Tmp2.getValueType(), Tmp2,
880                          DAG.getConstant(EltSize, Tmp2.getValueType()));
881       StackPtr = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2, StackPtr);
882       
883       Result = DAG.getLoad(Result.getValueType(), Ch, StackPtr,
884                               DAG.getSrcValue(NULL));
885       break;
886     }
887     }
888     break;
889
890   case ISD::VEXTRACT_VECTOR_ELT: {
891     // We know that operand #0 is the Vec vector.  If the index is a constant
892     // or if the invec is a supported hardware type, we can use it.  Otherwise,
893     // lower to a store then an indexed load.
894     Tmp1 = Node->getOperand(0);
895     Tmp2 = LegalizeOp(Node->getOperand(1));
896     
897     SDNode *InVal = Tmp1.Val;
898     unsigned NumElems = cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
899     MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
900     
901     // Figure out if there is a Packed type corresponding to this Vector
902     // type.  If so, convert to the packed type.
903     MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
904     if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
905       // Turn this into a packed extract_vector_elt operation.
906       Tmp1 = PackVectorOp(Tmp1, TVT);
907       Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Node->getValueType(0),
908                            Tmp1, Tmp2);
909       break;
910     } else if (NumElems == 1) {
911       // This must be an access of the only element.
912       Result = PackVectorOp(Tmp1, EVT);
913       break;
914     } else if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Tmp2)) {
915       SDOperand Lo, Hi;
916       SplitVectorOp(Tmp1, Lo, Hi);
917       if (CIdx->getValue() < NumElems/2) {
918         Tmp1 = Lo;
919       } else {
920         Tmp1 = Hi;
921         Tmp2 = DAG.getConstant(CIdx->getValue() - NumElems/2,
922                                Tmp2.getValueType());
923       }
924
925       // It's now an extract from the appropriate high or low part.
926       Result = LegalizeOp(DAG.UpdateNodeOperands(Result, Tmp1, Tmp2));
927     } else {
928       // FIXME: IMPLEMENT STORE/LOAD lowering.  Need alignment of stack slot!!
929       assert(0 && "unimp!");
930     }
931     break;
932   }
933     
934   case ISD::CALLSEQ_START: {
935     SDNode *CallEnd = FindCallEndFromCallStart(Node);
936     
937     // Recursively Legalize all of the inputs of the call end that do not lead
938     // to this call start.  This ensures that any libcalls that need be inserted
939     // are inserted *before* the CALLSEQ_START.
940     for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
941       LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).Val, Node);
942
943     // Now that we legalized all of the inputs (which may have inserted
944     // libcalls) create the new CALLSEQ_START node.
945     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
946
947     // Merge in the last call, to ensure that this call start after the last
948     // call ended.
949     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
950     Tmp1 = LegalizeOp(Tmp1);
951       
952     // Do not try to legalize the target-specific arguments (#1+).
953     if (Tmp1 != Node->getOperand(0)) {
954       std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
955       Ops[0] = Tmp1;
956       Result = DAG.UpdateNodeOperands(Result, Ops);
957     }
958     
959     // Remember that the CALLSEQ_START is legalized.
960     AddLegalizedOperand(Op.getValue(0), Result);
961     if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
962       AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
963     
964     // Now that the callseq_start and all of the non-call nodes above this call
965     // sequence have been legalized, legalize the call itself.  During this 
966     // process, no libcalls can/will be inserted, guaranteeing that no calls
967     // can overlap.
968     assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
969     SDOperand InCallSEQ = LastCALLSEQ_END;
970     // Note that we are selecting this call!
971     LastCALLSEQ_END = SDOperand(CallEnd, 0);
972     IsLegalizingCall = true;
973     
974     // Legalize the call, starting from the CALLSEQ_END.
975     LegalizeOp(LastCALLSEQ_END);
976     assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
977     return Result;
978   }
979   case ISD::CALLSEQ_END:
980     // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
981     // will cause this node to be legalized as well as handling libcalls right.
982     if (LastCALLSEQ_END.Val != Node) {
983       LegalizeOp(SDOperand(FindCallStartFromCallEnd(Node), 0));
984       std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
985       assert(I != LegalizedNodes.end() &&
986              "Legalizing the call start should have legalized this node!");
987       return I->second;
988     }
989     
990     // Otherwise, the call start has been legalized and everything is going 
991     // according to plan.  Just legalize ourselves normally here.
992     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
993     // Do not try to legalize the target-specific arguments (#1+), except for
994     // an optional flag input.
995     if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
996       if (Tmp1 != Node->getOperand(0)) {
997         std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
998         Ops[0] = Tmp1;
999         Result = DAG.UpdateNodeOperands(Result, Ops);
1000       }
1001     } else {
1002       Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1003       if (Tmp1 != Node->getOperand(0) ||
1004           Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1005         std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1006         Ops[0] = Tmp1;
1007         Ops.back() = Tmp2;
1008         Result = DAG.UpdateNodeOperands(Result, Ops);
1009       }
1010     }
1011     assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1012     // This finishes up call legalization.
1013     IsLegalizingCall = false;
1014     
1015     // If the CALLSEQ_END node has a flag, remember that we legalized it.
1016     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1017     if (Node->getNumValues() == 2)
1018       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1019     return Result.getValue(Op.ResNo);
1020   case ISD::DYNAMIC_STACKALLOC: {
1021     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1022     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
1023     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
1024     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1025
1026     Tmp1 = Result.getValue(0);
1027     Tmp2 = Result.getValue(1);
1028     switch (TLI.getOperationAction(Node->getOpcode(),
1029                                    Node->getValueType(0))) {
1030     default: assert(0 && "This action is not supported yet!");
1031     case TargetLowering::Expand: {
1032       unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1033       assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1034              " not tell us which reg is the stack pointer!");
1035       SDOperand Chain = Tmp1.getOperand(0);
1036       SDOperand Size  = Tmp2.getOperand(1);
1037       SDOperand SP = DAG.getCopyFromReg(Chain, SPReg, Node->getValueType(0));
1038       Tmp1 = DAG.getNode(ISD::SUB, Node->getValueType(0), SP, Size);    // Value
1039       Tmp2 = DAG.getCopyToReg(SP.getValue(1), SPReg, Tmp1);      // Output chain
1040       Tmp1 = LegalizeOp(Tmp1);
1041       Tmp2 = LegalizeOp(Tmp2);
1042       break;
1043     }
1044     case TargetLowering::Custom:
1045       Tmp3 = TLI.LowerOperation(Tmp1, DAG);
1046       if (Tmp3.Val) {
1047         Tmp1 = LegalizeOp(Tmp3);
1048         Tmp2 = LegalizeOp(Tmp3.getValue(1));
1049       }
1050       break;
1051     case TargetLowering::Legal:
1052       break;
1053     }
1054     // Since this op produce two values, make sure to remember that we
1055     // legalized both of them.
1056     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1057     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1058     return Op.ResNo ? Tmp2 : Tmp1;
1059   }
1060   case ISD::INLINEASM:
1061     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize Chain.
1062     Tmp2 = Node->getOperand(Node->getNumOperands()-1);
1063     if (Tmp2.getValueType() == MVT::Flag)     // Legalize Flag if it exists.
1064       Tmp2 = Tmp3 = SDOperand(0, 0);
1065     else
1066       Tmp3 = LegalizeOp(Tmp2);
1067     
1068     if (Tmp1 != Node->getOperand(0) || Tmp2 != Tmp3) {
1069       std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1070       Ops[0] = Tmp1;
1071       if (Tmp3.Val) Ops.back() = Tmp3;
1072       Result = DAG.UpdateNodeOperands(Result, Ops);
1073     }
1074       
1075     // INLINE asm returns a chain and flag, make sure to add both to the map.
1076     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1077     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1078     return Result.getValue(Op.ResNo);
1079   case ISD::BR:
1080     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1081     // Ensure that libcalls are emitted before a branch.
1082     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1083     Tmp1 = LegalizeOp(Tmp1);
1084     LastCALLSEQ_END = DAG.getEntryNode();
1085     
1086     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1087     break;
1088
1089   case ISD::BRCOND:
1090     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1091     // Ensure that libcalls are emitted before a return.
1092     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1093     Tmp1 = LegalizeOp(Tmp1);
1094     LastCALLSEQ_END = DAG.getEntryNode();
1095
1096     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1097     case Expand: assert(0 && "It's impossible to expand bools");
1098     case Legal:
1099       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
1100       break;
1101     case Promote:
1102       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
1103       break;
1104     }
1105
1106     // Basic block destination (Op#2) is always legal.
1107     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1108       
1109     switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {  
1110     default: assert(0 && "This action is not supported yet!");
1111     case TargetLowering::Legal: break;
1112     case TargetLowering::Custom:
1113       Tmp1 = TLI.LowerOperation(Result, DAG);
1114       if (Tmp1.Val) Result = Tmp1;
1115       break;
1116     case TargetLowering::Expand:
1117       // Expand brcond's setcc into its constituent parts and create a BR_CC
1118       // Node.
1119       if (Tmp2.getOpcode() == ISD::SETCC) {
1120         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
1121                              Tmp2.getOperand(0), Tmp2.getOperand(1),
1122                              Node->getOperand(2));
1123       } else {
1124         // Make sure the condition is either zero or one.  It may have been
1125         // promoted from something else.
1126         unsigned NumBits = MVT::getSizeInBits(Tmp2.getValueType());
1127         if (!TLI.MaskedValueIsZero(Tmp2, (~0ULL >> (64-NumBits))^1))
1128           Tmp2 = DAG.getZeroExtendInReg(Tmp2, MVT::i1);
1129         
1130         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, 
1131                              DAG.getCondCode(ISD::SETNE), Tmp2,
1132                              DAG.getConstant(0, Tmp2.getValueType()),
1133                              Node->getOperand(2));
1134       }
1135       break;
1136     }
1137     break;
1138   case ISD::BR_CC:
1139     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1140     // Ensure that libcalls are emitted before a branch.
1141     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1142     Tmp1 = LegalizeOp(Tmp1);
1143     LastCALLSEQ_END = DAG.getEntryNode();
1144     
1145     Tmp2 = Node->getOperand(2);              // LHS 
1146     Tmp3 = Node->getOperand(3);              // RHS
1147     Tmp4 = Node->getOperand(1);              // CC
1148
1149     LegalizeSetCCOperands(Tmp2, Tmp3, Tmp4);
1150     
1151     // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
1152     // the LHS is a legal SETCC itself.  In this case, we need to compare
1153     // the result against zero to select between true and false values.
1154     if (Tmp3.Val == 0) {
1155       Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
1156       Tmp4 = DAG.getCondCode(ISD::SETNE);
1157     }
1158     
1159     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp4, Tmp2, Tmp3, 
1160                                     Node->getOperand(4));
1161       
1162     switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
1163     default: assert(0 && "Unexpected action for BR_CC!");
1164     case TargetLowering::Legal: break;
1165     case TargetLowering::Custom:
1166       Tmp4 = TLI.LowerOperation(Result, DAG);
1167       if (Tmp4.Val) Result = Tmp4;
1168       break;
1169     }
1170     break;
1171   case ISD::LOAD: {
1172     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1173     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1174
1175     MVT::ValueType VT = Node->getValueType(0);
1176     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1177     Tmp2 = Result.getValue(0);
1178     Tmp3 = Result.getValue(1);
1179     
1180     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1181     default: assert(0 && "This action is not supported yet!");
1182     case TargetLowering::Legal: break;
1183     case TargetLowering::Custom:
1184       Tmp1 = TLI.LowerOperation(Tmp2, DAG);
1185       if (Tmp1.Val) {
1186         Tmp2 = LegalizeOp(Tmp1);
1187         Tmp3 = LegalizeOp(Tmp1.getValue(1));
1188       }
1189       break;
1190     }
1191     // Since loads produce two values, make sure to remember that we 
1192     // legalized both of them.
1193     AddLegalizedOperand(SDOperand(Node, 0), Tmp2);
1194     AddLegalizedOperand(SDOperand(Node, 1), Tmp3);
1195     return Op.ResNo ? Tmp3 : Tmp2;
1196   }
1197   case ISD::EXTLOAD:
1198   case ISD::SEXTLOAD:
1199   case ISD::ZEXTLOAD: {
1200     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1201     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1202
1203     MVT::ValueType SrcVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
1204     switch (TLI.getOperationAction(Node->getOpcode(), SrcVT)) {
1205     default: assert(0 && "This action is not supported yet!");
1206     case TargetLowering::Promote:
1207       assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
1208       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
1209                                       DAG.getValueType(MVT::i8));
1210       Tmp1 = Result.getValue(0);
1211       Tmp2 = Result.getValue(1);
1212       break;
1213     case TargetLowering::Custom:
1214       isCustom = true;
1215       // FALLTHROUGH
1216     case TargetLowering::Legal:
1217       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
1218                                       Node->getOperand(3));
1219       Tmp1 = Result.getValue(0);
1220       Tmp2 = Result.getValue(1);
1221       
1222       if (isCustom) {
1223         Tmp3 = TLI.LowerOperation(Tmp3, DAG);
1224         if (Tmp3.Val) {
1225           Tmp1 = LegalizeOp(Tmp3);
1226           Tmp2 = LegalizeOp(Tmp3.getValue(1));
1227         }
1228       }
1229       break;
1230     case TargetLowering::Expand:
1231       // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
1232       if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
1233         SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, Node->getOperand(2));
1234         Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
1235         Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
1236         Tmp2 = LegalizeOp(Load.getValue(1));
1237         break;
1238       }
1239       assert(Node->getOpcode() != ISD::EXTLOAD &&
1240              "EXTLOAD should always be supported!");
1241       // Turn the unsupported load into an EXTLOAD followed by an explicit
1242       // zero/sign extend inreg.
1243       Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
1244                               Tmp1, Tmp2, Node->getOperand(2), SrcVT);
1245       SDOperand ValRes;
1246       if (Node->getOpcode() == ISD::SEXTLOAD)
1247         ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1248                              Result, DAG.getValueType(SrcVT));
1249       else
1250         ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
1251       Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
1252       Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
1253       break;
1254     }
1255     // Since loads produce two values, make sure to remember that we legalized
1256     // both of them.
1257     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1258     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1259     return Op.ResNo ? Tmp2 : Tmp1;
1260   }
1261   case ISD::EXTRACT_ELEMENT: {
1262     MVT::ValueType OpTy = Node->getOperand(0).getValueType();
1263     switch (getTypeAction(OpTy)) {
1264     default: assert(0 && "EXTRACT_ELEMENT action for type unimplemented!");
1265     case Legal:
1266       if (cast<ConstantSDNode>(Node->getOperand(1))->getValue()) {
1267         // 1 -> Hi
1268         Result = DAG.getNode(ISD::SRL, OpTy, Node->getOperand(0),
1269                              DAG.getConstant(MVT::getSizeInBits(OpTy)/2, 
1270                                              TLI.getShiftAmountTy()));
1271         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Result);
1272       } else {
1273         // 0 -> Lo
1274         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), 
1275                              Node->getOperand(0));
1276       }
1277       break;
1278     case Expand:
1279       // Get both the low and high parts.
1280       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1281       if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
1282         Result = Tmp2;  // 1 -> Hi
1283       else
1284         Result = Tmp1;  // 0 -> Lo
1285       break;
1286     }
1287     break;
1288   }
1289
1290   case ISD::CopyToReg:
1291     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1292
1293     assert(isTypeLegal(Node->getOperand(2).getValueType()) &&
1294            "Register type must be legal!");
1295     // Legalize the incoming value (must be a legal type).
1296     Tmp2 = LegalizeOp(Node->getOperand(2));
1297     if (Node->getNumValues() == 1) {
1298       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2);
1299     } else {
1300       assert(Node->getNumValues() == 2 && "Unknown CopyToReg");
1301       if (Node->getNumOperands() == 4) {
1302         Tmp3 = LegalizeOp(Node->getOperand(3));
1303         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2,
1304                                         Tmp3);
1305       } else {
1306         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
1307       }
1308       
1309       // Since this produces two values, make sure to remember that we legalized
1310       // both of them.
1311       AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1312       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1313       return Result;
1314     }
1315     break;
1316
1317   case ISD::RET:
1318     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1319
1320     // Ensure that libcalls are emitted before a return.
1321     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1322     Tmp1 = LegalizeOp(Tmp1);
1323     LastCALLSEQ_END = DAG.getEntryNode();
1324     
1325     switch (Node->getNumOperands()) {
1326     case 2:  // ret val
1327       switch (getTypeAction(Node->getOperand(1).getValueType())) {
1328       case Legal:
1329         Tmp2 = LegalizeOp(Node->getOperand(1));
1330         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1331         break;
1332       case Expand: {
1333         SDOperand Lo, Hi;
1334         ExpandOp(Node->getOperand(1), Lo, Hi);
1335         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
1336         break;
1337       }
1338       case Promote:
1339         Tmp2 = PromoteOp(Node->getOperand(1));
1340         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1341         Result = LegalizeOp(Result);
1342         break;
1343       }
1344       break;
1345     case 1:  // ret void
1346       Result = DAG.UpdateNodeOperands(Result, Tmp1);
1347       break;
1348     default: { // ret <values>
1349       std::vector<SDOperand> NewValues;
1350       NewValues.push_back(Tmp1);
1351       for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1352         switch (getTypeAction(Node->getOperand(i).getValueType())) {
1353         case Legal:
1354           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
1355           break;
1356         case Expand: {
1357           SDOperand Lo, Hi;
1358           ExpandOp(Node->getOperand(i), Lo, Hi);
1359           NewValues.push_back(Lo);
1360           NewValues.push_back(Hi);
1361           break;
1362         }
1363         case Promote:
1364           assert(0 && "Can't promote multiple return value yet!");
1365         }
1366           
1367       if (NewValues.size() == Node->getNumOperands())
1368         Result = DAG.UpdateNodeOperands(Result, NewValues);
1369       else
1370         Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
1371       break;
1372     }
1373     }
1374
1375     if (Result.getOpcode() == ISD::RET) {
1376       switch (TLI.getOperationAction(Result.getOpcode(), MVT::Other)) {
1377       default: assert(0 && "This action is not supported yet!");
1378       case TargetLowering::Legal: break;
1379       case TargetLowering::Custom:
1380         Tmp1 = TLI.LowerOperation(Result, DAG);
1381         if (Tmp1.Val) Result = Tmp1;
1382         break;
1383       }
1384     }
1385     break;
1386   case ISD::STORE: {
1387     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1388     Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1389
1390     // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
1391     // FIXME: We shouldn't do this for TargetConstantFP's.
1392     // FIXME: move this to the DAG Combiner!
1393     if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
1394       if (CFP->getValueType(0) == MVT::f32) {
1395         Tmp3 = DAG.getConstant(FloatToBits(CFP->getValue()), MVT::i32);
1396       } else {
1397         assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
1398         Tmp3 = DAG.getConstant(DoubleToBits(CFP->getValue()), MVT::i64);
1399       }
1400       Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Tmp3, Tmp2, 
1401                            Node->getOperand(3));
1402       break;
1403     }
1404
1405     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1406     case Legal: {
1407       Tmp3 = LegalizeOp(Node->getOperand(1));
1408       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
1409                                       Node->getOperand(3));
1410
1411       MVT::ValueType VT = Tmp3.getValueType();
1412       switch (TLI.getOperationAction(ISD::STORE, VT)) {
1413       default: assert(0 && "This action is not supported yet!");
1414       case TargetLowering::Legal:  break;
1415       case TargetLowering::Custom:
1416         Tmp1 = TLI.LowerOperation(Result, DAG);
1417         if (Tmp1.Val) Result = Tmp1;
1418         break;
1419       }
1420       break;
1421     }
1422     case Promote:
1423       // Truncate the value and store the result.
1424       Tmp3 = PromoteOp(Node->getOperand(1));
1425       Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
1426                            Node->getOperand(3),
1427                           DAG.getValueType(Node->getOperand(1).getValueType()));
1428       break;
1429
1430     case Expand:
1431       unsigned IncrementSize = 0;
1432       SDOperand Lo, Hi;
1433       
1434       // If this is a vector type, then we have to calculate the increment as
1435       // the product of the element size in bytes, and the number of elements
1436       // in the high half of the vector.
1437       if (Node->getOperand(1).getValueType() == MVT::Vector) {
1438         SDNode *InVal = Node->getOperand(1).Val;
1439         unsigned NumElems =
1440           cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
1441         MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
1442
1443         // Figure out if there is a Packed type corresponding to this Vector
1444         // type.  If so, convert to the packed type.
1445         MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
1446         if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
1447           // Turn this into a normal store of the packed type.
1448           Tmp3 = PackVectorOp(Node->getOperand(1), TVT);
1449           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
1450                                           Node->getOperand(3));
1451           break;
1452         } else if (NumElems == 1) {
1453           // Turn this into a normal store of the scalar type.
1454           Tmp3 = PackVectorOp(Node->getOperand(1), EVT);
1455           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
1456                                           Node->getOperand(3));
1457           break;
1458         } else {
1459           SplitVectorOp(Node->getOperand(1), Lo, Hi);
1460           IncrementSize = NumElems/2 * MVT::getSizeInBits(EVT)/8;
1461         }
1462       } else {
1463         ExpandOp(Node->getOperand(1), Lo, Hi);
1464         IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
1465       }
1466
1467       if (!TLI.isLittleEndian())
1468         std::swap(Lo, Hi);
1469
1470       Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2,
1471                        Node->getOperand(3));
1472       Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
1473                          getIntPtrConstant(IncrementSize));
1474       assert(isTypeLegal(Tmp2.getValueType()) &&
1475              "Pointers must be legal!");
1476       // FIXME: This sets the srcvalue of both halves to be the same, which is
1477       // wrong.
1478       Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2,
1479                        Node->getOperand(3));
1480       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
1481       break;
1482     }
1483     break;
1484   }
1485   case ISD::PCMARKER:
1486     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1487     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1488     break;
1489   case ISD::STACKSAVE:
1490     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1491     Result = DAG.UpdateNodeOperands(Result, Tmp1);
1492     Tmp1 = Result.getValue(0);
1493     Tmp2 = Result.getValue(1);
1494     
1495     switch (TLI.getOperationAction(ISD::STACKSAVE, MVT::Other)) {
1496     default: assert(0 && "This action is not supported yet!");
1497     case TargetLowering::Legal: break;
1498     case TargetLowering::Custom:
1499       Tmp3 = TLI.LowerOperation(Result, DAG);
1500       if (Tmp3.Val) {
1501         Tmp1 = LegalizeOp(Tmp3);
1502         Tmp2 = LegalizeOp(Tmp3.getValue(1));
1503       }
1504       break;
1505     case TargetLowering::Expand:
1506       // Expand to CopyFromReg if the target set 
1507       // StackPointerRegisterToSaveRestore.
1508       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
1509         Tmp1 = DAG.getCopyFromReg(Result.getOperand(0), SP,
1510                                   Node->getValueType(0));
1511         Tmp2 = Tmp1.getValue(1);
1512       } else {
1513         Tmp1 = DAG.getNode(ISD::UNDEF, Node->getValueType(0));
1514         Tmp2 = Node->getOperand(0);
1515       }
1516       break;
1517     }
1518
1519     // Since stacksave produce two values, make sure to remember that we
1520     // legalized both of them.
1521     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1522     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1523     return Op.ResNo ? Tmp2 : Tmp1;
1524
1525   case ISD::STACKRESTORE:
1526     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1527     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1528     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1529       
1530     switch (TLI.getOperationAction(ISD::STACKRESTORE, MVT::Other)) {
1531     default: assert(0 && "This action is not supported yet!");
1532     case TargetLowering::Legal: break;
1533     case TargetLowering::Custom:
1534       Tmp1 = TLI.LowerOperation(Result, DAG);
1535       if (Tmp1.Val) Result = Tmp1;
1536       break;
1537     case TargetLowering::Expand:
1538       // Expand to CopyToReg if the target set 
1539       // StackPointerRegisterToSaveRestore.
1540       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
1541         Result = DAG.getCopyToReg(Tmp1, SP, Tmp2);
1542       } else {
1543         Result = Tmp1;
1544       }
1545       break;
1546     }
1547     break;
1548
1549   case ISD::READCYCLECOUNTER:
1550     Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
1551     Result = DAG.UpdateNodeOperands(Result, Tmp1);
1552
1553     // Since rdcc produce two values, make sure to remember that we legalized
1554     // both of them.
1555     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1556     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1557     return Result;
1558
1559   case ISD::TRUNCSTORE: {
1560     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1561     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1562
1563     assert(isTypeLegal(Node->getOperand(1).getValueType()) &&
1564            "Cannot handle illegal TRUNCSTORE yet!");
1565     Tmp2 = LegalizeOp(Node->getOperand(1));
1566     
1567     // The only promote case we handle is TRUNCSTORE:i1 X into
1568     //   -> TRUNCSTORE:i8 (and X, 1)
1569     if (cast<VTSDNode>(Node->getOperand(4))->getVT() == MVT::i1 &&
1570         TLI.getOperationAction(ISD::TRUNCSTORE, MVT::i1) == 
1571               TargetLowering::Promote) {
1572       // Promote the bool to a mask then store.
1573       Tmp2 = DAG.getNode(ISD::AND, Tmp2.getValueType(), Tmp2,
1574                          DAG.getConstant(1, Tmp2.getValueType()));
1575       Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
1576                            Node->getOperand(3), DAG.getValueType(MVT::i8));
1577
1578     } else if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1579                Tmp3 != Node->getOperand(2)) {
1580       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
1581                                       Node->getOperand(3), Node->getOperand(4));
1582     }
1583
1584     MVT::ValueType StVT = cast<VTSDNode>(Result.Val->getOperand(4))->getVT();
1585     switch (TLI.getOperationAction(Result.Val->getOpcode(), StVT)) {
1586     default: assert(0 && "This action is not supported yet!");
1587     case TargetLowering::Legal: break;
1588     case TargetLowering::Custom:
1589       Tmp1 = TLI.LowerOperation(Result, DAG);
1590       if (Tmp1.Val) Result = Tmp1;
1591       break;
1592     }
1593     break;
1594   }
1595   case ISD::SELECT:
1596     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1597     case Expand: assert(0 && "It's impossible to expand bools");
1598     case Legal:
1599       Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1600       break;
1601     case Promote:
1602       Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
1603       break;
1604     }
1605     Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
1606     Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
1607
1608     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1609       
1610     switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
1611     default: assert(0 && "This action is not supported yet!");
1612     case TargetLowering::Legal: break;
1613     case TargetLowering::Custom: {
1614       Tmp1 = TLI.LowerOperation(Result, DAG);
1615       if (Tmp1.Val) Result = Tmp1;
1616       break;
1617     }
1618     case TargetLowering::Expand:
1619       if (Tmp1.getOpcode() == ISD::SETCC) {
1620         Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1), 
1621                               Tmp2, Tmp3,
1622                               cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
1623       } else {
1624         // Make sure the condition is either zero or one.  It may have been
1625         // promoted from something else.
1626         unsigned NumBits = MVT::getSizeInBits(Tmp1.getValueType());
1627         if (!TLI.MaskedValueIsZero(Tmp1, (~0ULL >> (64-NumBits))^1))
1628           Tmp1 = DAG.getZeroExtendInReg(Tmp1, MVT::i1);
1629         Result = DAG.getSelectCC(Tmp1, 
1630                                  DAG.getConstant(0, Tmp1.getValueType()),
1631                                  Tmp2, Tmp3, ISD::SETNE);
1632       }
1633       break;
1634     case TargetLowering::Promote: {
1635       MVT::ValueType NVT =
1636         TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
1637       unsigned ExtOp, TruncOp;
1638       if (MVT::isInteger(Tmp2.getValueType())) {
1639         ExtOp   = ISD::ANY_EXTEND;
1640         TruncOp = ISD::TRUNCATE;
1641       } else {
1642         ExtOp   = ISD::FP_EXTEND;
1643         TruncOp = ISD::FP_ROUND;
1644       }
1645       // Promote each of the values to the new type.
1646       Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
1647       Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
1648       // Perform the larger operation, then round down.
1649       Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
1650       Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
1651       break;
1652     }
1653     }
1654     break;
1655   case ISD::SELECT_CC: {
1656     Tmp1 = Node->getOperand(0);               // LHS
1657     Tmp2 = Node->getOperand(1);               // RHS
1658     Tmp3 = LegalizeOp(Node->getOperand(2));   // True
1659     Tmp4 = LegalizeOp(Node->getOperand(3));   // False
1660     SDOperand CC = Node->getOperand(4);
1661     
1662     LegalizeSetCCOperands(Tmp1, Tmp2, CC);
1663     
1664     // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
1665     // the LHS is a legal SETCC itself.  In this case, we need to compare
1666     // the result against zero to select between true and false values.
1667     if (Tmp2.Val == 0) {
1668       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
1669       CC = DAG.getCondCode(ISD::SETNE);
1670     }
1671     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, CC);
1672
1673     // Everything is legal, see if we should expand this op or something.
1674     switch (TLI.getOperationAction(ISD::SELECT_CC, Tmp3.getValueType())) {
1675     default: assert(0 && "This action is not supported yet!");
1676     case TargetLowering::Legal: break;
1677     case TargetLowering::Custom:
1678       Tmp1 = TLI.LowerOperation(Result, DAG);
1679       if (Tmp1.Val) Result = Tmp1;
1680       break;
1681     }
1682     break;
1683   }
1684   case ISD::SETCC:
1685     Tmp1 = Node->getOperand(0);
1686     Tmp2 = Node->getOperand(1);
1687     Tmp3 = Node->getOperand(2);
1688     LegalizeSetCCOperands(Tmp1, Tmp2, Tmp3);
1689     
1690     // If we had to Expand the SetCC operands into a SELECT node, then it may 
1691     // not always be possible to return a true LHS & RHS.  In this case, just 
1692     // return the value we legalized, returned in the LHS
1693     if (Tmp2.Val == 0) {
1694       Result = Tmp1;
1695       break;
1696     }
1697
1698     switch (TLI.getOperationAction(ISD::SETCC, Tmp1.getValueType())) {
1699     default: assert(0 && "Cannot handle this action for SETCC yet!");
1700     case TargetLowering::Custom:
1701       isCustom = true;
1702       // FALLTHROUGH.
1703     case TargetLowering::Legal:
1704       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1705       if (isCustom) {
1706         Tmp3 = TLI.LowerOperation(Result, DAG);
1707         if (Tmp3.Val) Result = Tmp3;
1708       }
1709       break;
1710     case TargetLowering::Promote: {
1711       // First step, figure out the appropriate operation to use.
1712       // Allow SETCC to not be supported for all legal data types
1713       // Mostly this targets FP
1714       MVT::ValueType NewInTy = Node->getOperand(0).getValueType();
1715       MVT::ValueType OldVT = NewInTy;
1716
1717       // Scan for the appropriate larger type to use.
1718       while (1) {
1719         NewInTy = (MVT::ValueType)(NewInTy+1);
1720
1721         assert(MVT::isInteger(NewInTy) == MVT::isInteger(OldVT) &&
1722                "Fell off of the edge of the integer world");
1723         assert(MVT::isFloatingPoint(NewInTy) == MVT::isFloatingPoint(OldVT) &&
1724                "Fell off of the edge of the floating point world");
1725           
1726         // If the target supports SETCC of this type, use it.
1727         if (TLI.isOperationLegal(ISD::SETCC, NewInTy))
1728           break;
1729       }
1730       if (MVT::isInteger(NewInTy))
1731         assert(0 && "Cannot promote Legal Integer SETCC yet");
1732       else {
1733         Tmp1 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp1);
1734         Tmp2 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp2);
1735       }
1736       Tmp1 = LegalizeOp(Tmp1);
1737       Tmp2 = LegalizeOp(Tmp2);
1738       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1739       Result = LegalizeOp(Result);
1740       break;
1741     }
1742     case TargetLowering::Expand:
1743       // Expand a setcc node into a select_cc of the same condition, lhs, and
1744       // rhs that selects between const 1 (true) and const 0 (false).
1745       MVT::ValueType VT = Node->getValueType(0);
1746       Result = DAG.getNode(ISD::SELECT_CC, VT, Tmp1, Tmp2, 
1747                            DAG.getConstant(1, VT), DAG.getConstant(0, VT),
1748                            Node->getOperand(2));
1749       break;
1750     }
1751     break;
1752   case ISD::MEMSET:
1753   case ISD::MEMCPY:
1754   case ISD::MEMMOVE: {
1755     Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
1756     Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
1757
1758     if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
1759       switch (getTypeAction(Node->getOperand(2).getValueType())) {
1760       case Expand: assert(0 && "Cannot expand a byte!");
1761       case Legal:
1762         Tmp3 = LegalizeOp(Node->getOperand(2));
1763         break;
1764       case Promote:
1765         Tmp3 = PromoteOp(Node->getOperand(2));
1766         break;
1767       }
1768     } else {
1769       Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
1770     }
1771
1772     SDOperand Tmp4;
1773     switch (getTypeAction(Node->getOperand(3).getValueType())) {
1774     case Expand: {
1775       // Length is too big, just take the lo-part of the length.
1776       SDOperand HiPart;
1777       ExpandOp(Node->getOperand(3), HiPart, Tmp4);
1778       break;
1779     }
1780     case Legal:
1781       Tmp4 = LegalizeOp(Node->getOperand(3));
1782       break;
1783     case Promote:
1784       Tmp4 = PromoteOp(Node->getOperand(3));
1785       break;
1786     }
1787
1788     SDOperand Tmp5;
1789     switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
1790     case Expand: assert(0 && "Cannot expand this yet!");
1791     case Legal:
1792       Tmp5 = LegalizeOp(Node->getOperand(4));
1793       break;
1794     case Promote:
1795       Tmp5 = PromoteOp(Node->getOperand(4));
1796       break;
1797     }
1798
1799     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1800     default: assert(0 && "This action not implemented for this operation!");
1801     case TargetLowering::Custom:
1802       isCustom = true;
1803       // FALLTHROUGH
1804     case TargetLowering::Legal:
1805       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, Tmp5);
1806       if (isCustom) {
1807         Tmp1 = TLI.LowerOperation(Result, DAG);
1808         if (Tmp1.Val) Result = Tmp1;
1809       }
1810       break;
1811     case TargetLowering::Expand: {
1812       // Otherwise, the target does not support this operation.  Lower the
1813       // operation to an explicit libcall as appropriate.
1814       MVT::ValueType IntPtr = TLI.getPointerTy();
1815       const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
1816       std::vector<std::pair<SDOperand, const Type*> > Args;
1817
1818       const char *FnName = 0;
1819       if (Node->getOpcode() == ISD::MEMSET) {
1820         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1821         // Extend the (previously legalized) ubyte argument to be an int value
1822         // for the call.
1823         if (Tmp3.getValueType() > MVT::i32)
1824           Tmp3 = DAG.getNode(ISD::TRUNCATE, MVT::i32, Tmp3);
1825         else
1826           Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
1827         Args.push_back(std::make_pair(Tmp3, Type::IntTy));
1828         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1829
1830         FnName = "memset";
1831       } else if (Node->getOpcode() == ISD::MEMCPY ||
1832                  Node->getOpcode() == ISD::MEMMOVE) {
1833         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1834         Args.push_back(std::make_pair(Tmp3, IntPtrTy));
1835         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1836         FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
1837       } else {
1838         assert(0 && "Unknown op!");
1839       }
1840
1841       std::pair<SDOperand,SDOperand> CallResult =
1842         TLI.LowerCallTo(Tmp1, Type::VoidTy, false, CallingConv::C, false,
1843                         DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
1844       Result = CallResult.second;
1845       break;
1846     }
1847     }
1848     break;
1849   }
1850
1851   case ISD::SHL_PARTS:
1852   case ISD::SRA_PARTS:
1853   case ISD::SRL_PARTS: {
1854     std::vector<SDOperand> Ops;
1855     bool Changed = false;
1856     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1857       Ops.push_back(LegalizeOp(Node->getOperand(i)));
1858       Changed |= Ops.back() != Node->getOperand(i);
1859     }
1860     if (Changed)
1861       Result = DAG.UpdateNodeOperands(Result, Ops);
1862
1863     switch (TLI.getOperationAction(Node->getOpcode(),
1864                                    Node->getValueType(0))) {
1865     default: assert(0 && "This action is not supported yet!");
1866     case TargetLowering::Legal: break;
1867     case TargetLowering::Custom:
1868       Tmp1 = TLI.LowerOperation(Result, DAG);
1869       if (Tmp1.Val) {
1870         SDOperand Tmp2, RetVal(0, 0);
1871         for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
1872           Tmp2 = LegalizeOp(Tmp1.getValue(i));
1873           AddLegalizedOperand(SDOperand(Node, i), Tmp2);
1874           if (i == Op.ResNo)
1875             RetVal = Tmp2;
1876         }
1877         assert(RetVal.Val && "Illegal result number");
1878         return RetVal;
1879       }
1880       break;
1881     }
1882
1883     // Since these produce multiple values, make sure to remember that we
1884     // legalized all of them.
1885     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1886       AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
1887     return Result.getValue(Op.ResNo);
1888   }
1889
1890     // Binary operators
1891   case ISD::ADD:
1892   case ISD::SUB:
1893   case ISD::MUL:
1894   case ISD::MULHS:
1895   case ISD::MULHU:
1896   case ISD::UDIV:
1897   case ISD::SDIV:
1898   case ISD::AND:
1899   case ISD::OR:
1900   case ISD::XOR:
1901   case ISD::SHL:
1902   case ISD::SRL:
1903   case ISD::SRA:
1904   case ISD::FADD:
1905   case ISD::FSUB:
1906   case ISD::FMUL:
1907   case ISD::FDIV:
1908     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1909     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1910     case Expand: assert(0 && "Not possible");
1911     case Legal:
1912       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
1913       break;
1914     case Promote:
1915       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
1916       break;
1917     }
1918     
1919     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1920       
1921     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1922     default: assert(0 && "Operation not supported");
1923     case TargetLowering::Legal: break;
1924     case TargetLowering::Custom:
1925       Tmp1 = TLI.LowerOperation(Result, DAG);
1926       if (Tmp1.Val) Result = Tmp1;
1927       break;
1928     }
1929     break;
1930     
1931   case ISD::FCOPYSIGN:  // FCOPYSIGN does not require LHS/RHS to match type!
1932     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1933     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1934       case Expand: assert(0 && "Not possible");
1935       case Legal:
1936         Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
1937         break;
1938       case Promote:
1939         Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
1940         break;
1941     }
1942       
1943     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1944     
1945     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1946     default: assert(0 && "Operation not supported");
1947     case TargetLowering::Custom:
1948       Tmp1 = TLI.LowerOperation(Result, DAG);
1949       if (Tmp1.Val) Result = Tmp1;
1950       break;
1951     case TargetLowering::Legal: break;
1952     case TargetLowering::Expand:
1953       // If this target supports fabs/fneg natively, do this efficiently.
1954       if (TLI.isOperationLegal(ISD::FABS, Tmp1.getValueType()) &&
1955           TLI.isOperationLegal(ISD::FNEG, Tmp1.getValueType())) {
1956         // Get the sign bit of the RHS.
1957         MVT::ValueType IVT = 
1958           Tmp2.getValueType() == MVT::f32 ? MVT::i32 : MVT::i64;
1959         SDOperand SignBit = DAG.getNode(ISD::BIT_CONVERT, IVT, Tmp2);
1960         SignBit = DAG.getSetCC(TLI.getSetCCResultTy(),
1961                                SignBit, DAG.getConstant(0, IVT), ISD::SETLT);
1962         // Get the absolute value of the result.
1963         SDOperand AbsVal = DAG.getNode(ISD::FABS, Tmp1.getValueType(), Tmp1);
1964         // Select between the nabs and abs value based on the sign bit of
1965         // the input.
1966         Result = DAG.getNode(ISD::SELECT, AbsVal.getValueType(), SignBit,
1967                              DAG.getNode(ISD::FNEG, AbsVal.getValueType(), 
1968                                          AbsVal),
1969                              AbsVal);
1970         Result = LegalizeOp(Result);
1971         break;
1972       }
1973       
1974       // Otherwise, do bitwise ops!
1975       
1976       // copysign -> copysignf/copysign libcall.
1977       const char *FnName;
1978       if (Node->getValueType(0) == MVT::f32) {
1979         FnName = "copysignf";
1980         if (Tmp2.getValueType() != MVT::f32)  // Force operands to match type.
1981           Result = DAG.UpdateNodeOperands(Result, Tmp1, 
1982                                     DAG.getNode(ISD::FP_ROUND, MVT::f32, Tmp2));
1983       } else {
1984         FnName = "copysign";
1985         if (Tmp2.getValueType() != MVT::f64)  // Force operands to match type.
1986           Result = DAG.UpdateNodeOperands(Result, Tmp1, 
1987                                    DAG.getNode(ISD::FP_EXTEND, MVT::f64, Tmp2));
1988       }
1989       SDOperand Dummy;
1990       Result = ExpandLibCall(FnName, Node, Dummy);
1991       break;
1992     }
1993     break;
1994     
1995   case ISD::ADDC:
1996   case ISD::SUBC:
1997     Tmp1 = LegalizeOp(Node->getOperand(0));
1998     Tmp2 = LegalizeOp(Node->getOperand(1));
1999     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2000     // Since this produces two values, make sure to remember that we legalized
2001     // both of them.
2002     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2003     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2004     return Result;
2005
2006   case ISD::ADDE:
2007   case ISD::SUBE:
2008     Tmp1 = LegalizeOp(Node->getOperand(0));
2009     Tmp2 = LegalizeOp(Node->getOperand(1));
2010     Tmp3 = LegalizeOp(Node->getOperand(2));
2011     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2012     // Since this produces two values, make sure to remember that we legalized
2013     // both of them.
2014     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2015     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2016     return Result;
2017     
2018   case ISD::BUILD_PAIR: {
2019     MVT::ValueType PairTy = Node->getValueType(0);
2020     // TODO: handle the case where the Lo and Hi operands are not of legal type
2021     Tmp1 = LegalizeOp(Node->getOperand(0));   // Lo
2022     Tmp2 = LegalizeOp(Node->getOperand(1));   // Hi
2023     switch (TLI.getOperationAction(ISD::BUILD_PAIR, PairTy)) {
2024     case TargetLowering::Promote:
2025     case TargetLowering::Custom:
2026       assert(0 && "Cannot promote/custom this yet!");
2027     case TargetLowering::Legal:
2028       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
2029         Result = DAG.getNode(ISD::BUILD_PAIR, PairTy, Tmp1, Tmp2);
2030       break;
2031     case TargetLowering::Expand:
2032       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, PairTy, Tmp1);
2033       Tmp2 = DAG.getNode(ISD::ANY_EXTEND, PairTy, Tmp2);
2034       Tmp2 = DAG.getNode(ISD::SHL, PairTy, Tmp2,
2035                          DAG.getConstant(MVT::getSizeInBits(PairTy)/2, 
2036                                          TLI.getShiftAmountTy()));
2037       Result = DAG.getNode(ISD::OR, PairTy, Tmp1, Tmp2);
2038       break;
2039     }
2040     break;
2041   }
2042
2043   case ISD::UREM:
2044   case ISD::SREM:
2045   case ISD::FREM:
2046     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2047     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2048
2049     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2050     case TargetLowering::Promote: assert(0 && "Cannot promote this yet!");
2051     case TargetLowering::Custom:
2052       isCustom = true;
2053       // FALLTHROUGH
2054     case TargetLowering::Legal:
2055       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2056       if (isCustom) {
2057         Tmp1 = TLI.LowerOperation(Result, DAG);
2058         if (Tmp1.Val) Result = Tmp1;
2059       }
2060       break;
2061     case TargetLowering::Expand:
2062       if (MVT::isInteger(Node->getValueType(0))) {
2063         // X % Y -> X-X/Y*Y
2064         MVT::ValueType VT = Node->getValueType(0);
2065         unsigned Opc = Node->getOpcode() == ISD::UREM ? ISD::UDIV : ISD::SDIV;
2066         Result = DAG.getNode(Opc, VT, Tmp1, Tmp2);
2067         Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
2068         Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
2069       } else {
2070         // Floating point mod -> fmod libcall.
2071         const char *FnName = Node->getValueType(0) == MVT::f32 ? "fmodf":"fmod";
2072         SDOperand Dummy;
2073         Result = ExpandLibCall(FnName, Node, Dummy);
2074       }
2075       break;
2076     }
2077     break;
2078   case ISD::VAARG: {
2079     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2080     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2081
2082     MVT::ValueType VT = Node->getValueType(0);
2083     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
2084     default: assert(0 && "This action is not supported yet!");
2085     case TargetLowering::Custom:
2086       isCustom = true;
2087       // FALLTHROUGH
2088     case TargetLowering::Legal:
2089       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2090       Result = Result.getValue(0);
2091       Tmp1 = Result.getValue(1);
2092
2093       if (isCustom) {
2094         Tmp2 = TLI.LowerOperation(Result, DAG);
2095         if (Tmp2.Val) {
2096           Result = LegalizeOp(Tmp2);
2097           Tmp1 = LegalizeOp(Tmp2.getValue(1));
2098         }
2099       }
2100       break;
2101     case TargetLowering::Expand: {
2102       SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
2103                                      Node->getOperand(2));
2104       // Increment the pointer, VAList, to the next vaarg
2105       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList, 
2106                          DAG.getConstant(MVT::getSizeInBits(VT)/8, 
2107                                          TLI.getPointerTy()));
2108       // Store the incremented VAList to the legalized pointer
2109       Tmp3 = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), Tmp3, Tmp2, 
2110                          Node->getOperand(2));
2111       // Load the actual argument out of the pointer VAList
2112       Result = DAG.getLoad(VT, Tmp3, VAList, DAG.getSrcValue(0));
2113       Tmp1 = LegalizeOp(Result.getValue(1));
2114       Result = LegalizeOp(Result);
2115       break;
2116     }
2117     }
2118     // Since VAARG produces two values, make sure to remember that we 
2119     // legalized both of them.
2120     AddLegalizedOperand(SDOperand(Node, 0), Result);
2121     AddLegalizedOperand(SDOperand(Node, 1), Tmp1);
2122     return Op.ResNo ? Tmp1 : Result;
2123   }
2124     
2125   case ISD::VACOPY: 
2126     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2127     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the dest pointer.
2128     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the source pointer.
2129
2130     switch (TLI.getOperationAction(ISD::VACOPY, MVT::Other)) {
2131     default: assert(0 && "This action is not supported yet!");
2132     case TargetLowering::Custom:
2133       isCustom = true;
2134       // FALLTHROUGH
2135     case TargetLowering::Legal:
2136       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
2137                                       Node->getOperand(3), Node->getOperand(4));
2138       if (isCustom) {
2139         Tmp1 = TLI.LowerOperation(Result, DAG);
2140         if (Tmp1.Val) Result = Tmp1;
2141       }
2142       break;
2143     case TargetLowering::Expand:
2144       // This defaults to loading a pointer from the input and storing it to the
2145       // output, returning the chain.
2146       Tmp4 = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp3, Node->getOperand(3));
2147       Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp4.getValue(1), Tmp4, Tmp2,
2148                            Node->getOperand(4));
2149       break;
2150     }
2151     break;
2152
2153   case ISD::VAEND: 
2154     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2155     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2156
2157     switch (TLI.getOperationAction(ISD::VAEND, MVT::Other)) {
2158     default: assert(0 && "This action is not supported yet!");
2159     case TargetLowering::Custom:
2160       isCustom = true;
2161       // FALLTHROUGH
2162     case TargetLowering::Legal:
2163       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2164       if (isCustom) {
2165         Tmp1 = TLI.LowerOperation(Tmp1, DAG);
2166         if (Tmp1.Val) Result = Tmp1;
2167       }
2168       break;
2169     case TargetLowering::Expand:
2170       Result = Tmp1; // Default to a no-op, return the chain
2171       break;
2172     }
2173     break;
2174     
2175   case ISD::VASTART: 
2176     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2177     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2178
2179     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2180     
2181     switch (TLI.getOperationAction(ISD::VASTART, MVT::Other)) {
2182     default: assert(0 && "This action is not supported yet!");
2183     case TargetLowering::Legal: break;
2184     case TargetLowering::Custom:
2185       Tmp1 = TLI.LowerOperation(Result, DAG);
2186       if (Tmp1.Val) Result = Tmp1;
2187       break;
2188     }
2189     break;
2190     
2191   case ISD::ROTL:
2192   case ISD::ROTR:
2193     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2194     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2195     
2196     assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
2197            "Cannot handle this yet!");
2198     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2199     break;
2200     
2201   case ISD::BSWAP:
2202     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2203     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2204     case TargetLowering::Custom:
2205       assert(0 && "Cannot custom legalize this yet!");
2206     case TargetLowering::Legal:
2207       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2208       break;
2209     case TargetLowering::Promote: {
2210       MVT::ValueType OVT = Tmp1.getValueType();
2211       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2212       unsigned DiffBits = getSizeInBits(NVT) - getSizeInBits(OVT);
2213
2214       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2215       Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
2216       Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
2217                            DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
2218       break;
2219     }
2220     case TargetLowering::Expand:
2221       Result = ExpandBSWAP(Tmp1);
2222       break;
2223     }
2224     break;
2225     
2226   case ISD::CTPOP:
2227   case ISD::CTTZ:
2228   case ISD::CTLZ:
2229     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2230     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2231     case TargetLowering::Custom: assert(0 && "Cannot custom handle this yet!");
2232     case TargetLowering::Legal:
2233       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2234       break;
2235     case TargetLowering::Promote: {
2236       MVT::ValueType OVT = Tmp1.getValueType();
2237       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2238
2239       // Zero extend the argument.
2240       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2241       // Perform the larger operation, then subtract if needed.
2242       Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2243       switch (Node->getOpcode()) {
2244       case ISD::CTPOP:
2245         Result = Tmp1;
2246         break;
2247       case ISD::CTTZ:
2248         //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2249         Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
2250                             DAG.getConstant(getSizeInBits(NVT), NVT),
2251                             ISD::SETEQ);
2252         Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
2253                            DAG.getConstant(getSizeInBits(OVT),NVT), Tmp1);
2254         break;
2255       case ISD::CTLZ:
2256         // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2257         Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
2258                              DAG.getConstant(getSizeInBits(NVT) -
2259                                              getSizeInBits(OVT), NVT));
2260         break;
2261       }
2262       break;
2263     }
2264     case TargetLowering::Expand:
2265       Result = ExpandBitCount(Node->getOpcode(), Tmp1);
2266       break;
2267     }
2268     break;
2269
2270     // Unary operators
2271   case ISD::FABS:
2272   case ISD::FNEG:
2273   case ISD::FSQRT:
2274   case ISD::FSIN:
2275   case ISD::FCOS:
2276     Tmp1 = LegalizeOp(Node->getOperand(0));
2277     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2278     case TargetLowering::Promote:
2279     case TargetLowering::Custom:
2280      isCustom = true;
2281      // FALLTHROUGH
2282     case TargetLowering::Legal:
2283       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2284       if (isCustom) {
2285         Tmp1 = TLI.LowerOperation(Result, DAG);
2286         if (Tmp1.Val) Result = Tmp1;
2287       }
2288       break;
2289     case TargetLowering::Expand:
2290       switch (Node->getOpcode()) {
2291       default: assert(0 && "Unreachable!");
2292       case ISD::FNEG:
2293         // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
2294         Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2295         Result = DAG.getNode(ISD::FSUB, Node->getValueType(0), Tmp2, Tmp1);
2296         break;
2297       case ISD::FABS: {
2298         // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2299         MVT::ValueType VT = Node->getValueType(0);
2300         Tmp2 = DAG.getConstantFP(0.0, VT);
2301         Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1, Tmp2, ISD::SETUGT);
2302         Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
2303         Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
2304         break;
2305       }
2306       case ISD::FSQRT:
2307       case ISD::FSIN:
2308       case ISD::FCOS: {
2309         MVT::ValueType VT = Node->getValueType(0);
2310         const char *FnName = 0;
2311         switch(Node->getOpcode()) {
2312         case ISD::FSQRT: FnName = VT == MVT::f32 ? "sqrtf" : "sqrt"; break;
2313         case ISD::FSIN:  FnName = VT == MVT::f32 ? "sinf"  : "sin"; break;
2314         case ISD::FCOS:  FnName = VT == MVT::f32 ? "cosf"  : "cos"; break;
2315         default: assert(0 && "Unreachable!");
2316         }
2317         SDOperand Dummy;
2318         Result = ExpandLibCall(FnName, Node, Dummy);
2319         break;
2320       }
2321       }
2322       break;
2323     }
2324     break;
2325     
2326   case ISD::BIT_CONVERT:
2327     if (!isTypeLegal(Node->getOperand(0).getValueType())) {
2328       Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2329     } else {
2330       switch (TLI.getOperationAction(ISD::BIT_CONVERT,
2331                                      Node->getOperand(0).getValueType())) {
2332       default: assert(0 && "Unknown operation action!");
2333       case TargetLowering::Expand:
2334         Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2335         break;
2336       case TargetLowering::Legal:
2337         Tmp1 = LegalizeOp(Node->getOperand(0));
2338         Result = DAG.UpdateNodeOperands(Result, Tmp1);
2339         break;
2340       }
2341     }
2342     break;
2343   case ISD::VBIT_CONVERT: {
2344     assert(Op.getOperand(0).getValueType() == MVT::Vector &&
2345            "Can only have VBIT_CONVERT where input or output is MVT::Vector!");
2346     
2347     // The input has to be a vector type, we have to either scalarize it, pack
2348     // it, or convert it based on whether the input vector type is legal.
2349     SDNode *InVal = Node->getOperand(0).Val;
2350     unsigned NumElems =
2351       cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
2352     MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
2353     
2354     // Figure out if there is a Packed type corresponding to this Vector
2355     // type.  If so, convert to the packed type.
2356     MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
2357     if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
2358       // Turn this into a bit convert of the packed input.
2359       Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), 
2360                            PackVectorOp(Node->getOperand(0), TVT));
2361       break;
2362     } else if (NumElems == 1) {
2363       // Turn this into a bit convert of the scalar input.
2364       Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), 
2365                            PackVectorOp(Node->getOperand(0), EVT));
2366       break;
2367     } else {
2368       // FIXME: UNIMP!  Store then reload
2369       assert(0 && "Cast from unsupported vector type not implemented yet!");
2370     }
2371   }
2372       
2373     // Conversion operators.  The source and destination have different types.
2374   case ISD::SINT_TO_FP:
2375   case ISD::UINT_TO_FP: {
2376     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
2377     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2378     case Legal:
2379       switch (TLI.getOperationAction(Node->getOpcode(),
2380                                      Node->getOperand(0).getValueType())) {
2381       default: assert(0 && "Unknown operation action!");
2382       case TargetLowering::Custom:
2383         isCustom = true;
2384         // FALLTHROUGH
2385       case TargetLowering::Legal:
2386         Tmp1 = LegalizeOp(Node->getOperand(0));
2387         Result = DAG.UpdateNodeOperands(Result, Tmp1);
2388         if (isCustom) {
2389           Tmp1 = TLI.LowerOperation(Result, DAG);
2390           if (Tmp1.Val) Result = Tmp1;
2391         }
2392         break;
2393       case TargetLowering::Expand:
2394         Result = ExpandLegalINT_TO_FP(isSigned,
2395                                       LegalizeOp(Node->getOperand(0)),
2396                                       Node->getValueType(0));
2397         break;
2398       case TargetLowering::Promote:
2399         Result = PromoteLegalINT_TO_FP(LegalizeOp(Node->getOperand(0)),
2400                                        Node->getValueType(0),
2401                                        isSigned);
2402         break;
2403       }
2404       break;
2405     case Expand:
2406       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
2407                              Node->getValueType(0), Node->getOperand(0));
2408       break;
2409     case Promote:
2410       Tmp1 = PromoteOp(Node->getOperand(0));
2411       if (isSigned) {
2412         Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp1.getValueType(),
2413                  Tmp1, DAG.getValueType(Node->getOperand(0).getValueType()));
2414       } else {
2415         Tmp1 = DAG.getZeroExtendInReg(Tmp1,
2416                                       Node->getOperand(0).getValueType());
2417       }
2418       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2419       Result = LegalizeOp(Result);  // The 'op' is not necessarily legal!
2420       break;
2421     }
2422     break;
2423   }
2424   case ISD::TRUNCATE:
2425     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2426     case Legal:
2427       Tmp1 = LegalizeOp(Node->getOperand(0));
2428       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2429       break;
2430     case Expand:
2431       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2432
2433       // Since the result is legal, we should just be able to truncate the low
2434       // part of the source.
2435       Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
2436       break;
2437     case Promote:
2438       Result = PromoteOp(Node->getOperand(0));
2439       Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
2440       break;
2441     }
2442     break;
2443
2444   case ISD::FP_TO_SINT:
2445   case ISD::FP_TO_UINT:
2446     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2447     case Legal:
2448       Tmp1 = LegalizeOp(Node->getOperand(0));
2449
2450       switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
2451       default: assert(0 && "Unknown operation action!");
2452       case TargetLowering::Custom:
2453         isCustom = true;
2454         // FALLTHROUGH
2455       case TargetLowering::Legal:
2456         Result = DAG.UpdateNodeOperands(Result, Tmp1);
2457         if (isCustom) {
2458           Tmp1 = TLI.LowerOperation(Result, DAG);
2459           if (Tmp1.Val) Result = Tmp1;
2460         }
2461         break;
2462       case TargetLowering::Promote:
2463         Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
2464                                        Node->getOpcode() == ISD::FP_TO_SINT);
2465         break;
2466       case TargetLowering::Expand:
2467         if (Node->getOpcode() == ISD::FP_TO_UINT) {
2468           SDOperand True, False;
2469           MVT::ValueType VT =  Node->getOperand(0).getValueType();
2470           MVT::ValueType NVT = Node->getValueType(0);
2471           unsigned ShiftAmt = MVT::getSizeInBits(Node->getValueType(0))-1;
2472           Tmp2 = DAG.getConstantFP((double)(1ULL << ShiftAmt), VT);
2473           Tmp3 = DAG.getSetCC(TLI.getSetCCResultTy(),
2474                             Node->getOperand(0), Tmp2, ISD::SETLT);
2475           True = DAG.getNode(ISD::FP_TO_SINT, NVT, Node->getOperand(0));
2476           False = DAG.getNode(ISD::FP_TO_SINT, NVT,
2477                               DAG.getNode(ISD::FSUB, VT, Node->getOperand(0),
2478                                           Tmp2));
2479           False = DAG.getNode(ISD::XOR, NVT, False, 
2480                               DAG.getConstant(1ULL << ShiftAmt, NVT));
2481           Result = DAG.getNode(ISD::SELECT, NVT, Tmp3, True, False);
2482           break;
2483         } else {
2484           assert(0 && "Do not know how to expand FP_TO_SINT yet!");
2485         }
2486         break;
2487       }
2488       break;
2489     case Expand:
2490       assert(0 && "Shouldn't need to expand other operators here!");
2491     case Promote:
2492       Tmp1 = PromoteOp(Node->getOperand(0));
2493       Result = DAG.UpdateNodeOperands(Result, LegalizeOp(Tmp1));
2494       Result = LegalizeOp(Result);
2495       break;
2496     }
2497     break;
2498
2499   case ISD::ANY_EXTEND:
2500   case ISD::ZERO_EXTEND:
2501   case ISD::SIGN_EXTEND:
2502   case ISD::FP_EXTEND:
2503   case ISD::FP_ROUND:
2504     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2505     case Expand: assert(0 && "Shouldn't need to expand other operators here!");
2506     case Legal:
2507       Tmp1 = LegalizeOp(Node->getOperand(0));
2508       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2509       break;
2510     case Promote:
2511       switch (Node->getOpcode()) {
2512       case ISD::ANY_EXTEND:
2513         Tmp1 = PromoteOp(Node->getOperand(0));
2514         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Tmp1);
2515         break;
2516       case ISD::ZERO_EXTEND:
2517         Result = PromoteOp(Node->getOperand(0));
2518         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2519         Result = DAG.getZeroExtendInReg(Result,
2520                                         Node->getOperand(0).getValueType());
2521         break;
2522       case ISD::SIGN_EXTEND:
2523         Result = PromoteOp(Node->getOperand(0));
2524         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2525         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2526                              Result,
2527                           DAG.getValueType(Node->getOperand(0).getValueType()));
2528         break;
2529       case ISD::FP_EXTEND:
2530         Result = PromoteOp(Node->getOperand(0));
2531         if (Result.getValueType() != Op.getValueType())
2532           // Dynamically dead while we have only 2 FP types.
2533           Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
2534         break;
2535       case ISD::FP_ROUND:
2536         Result = PromoteOp(Node->getOperand(0));
2537         Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
2538         break;
2539       }
2540     }
2541     break;
2542   case ISD::FP_ROUND_INREG:
2543   case ISD::SIGN_EXTEND_INREG: {
2544     Tmp1 = LegalizeOp(Node->getOperand(0));
2545     MVT::ValueType ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2546
2547     // If this operation is not supported, convert it to a shl/shr or load/store
2548     // pair.
2549     switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
2550     default: assert(0 && "This action not supported for this op yet!");
2551     case TargetLowering::Legal:
2552       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
2553       break;
2554     case TargetLowering::Expand:
2555       // If this is an integer extend and shifts are supported, do that.
2556       if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
2557         // NOTE: we could fall back on load/store here too for targets without
2558         // SAR.  However, it is doubtful that any exist.
2559         unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
2560                             MVT::getSizeInBits(ExtraVT);
2561         SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
2562         Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
2563                              Node->getOperand(0), ShiftCst);
2564         Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
2565                              Result, ShiftCst);
2566       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
2567         // The only way we can lower this is to turn it into a STORETRUNC,
2568         // EXTLOAD pair, targetting a temporary location (a stack slot).
2569
2570         // NOTE: there is a choice here between constantly creating new stack
2571         // slots and always reusing the same one.  We currently always create
2572         // new ones, as reuse may inhibit scheduling.
2573         const Type *Ty = MVT::getTypeForValueType(ExtraVT);
2574         unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
2575         unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
2576         MachineFunction &MF = DAG.getMachineFunction();
2577         int SSFI =
2578           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
2579         SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
2580         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
2581                              Node->getOperand(0), StackSlot,
2582                              DAG.getSrcValue(NULL), DAG.getValueType(ExtraVT));
2583         Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
2584                                 Result, StackSlot, DAG.getSrcValue(NULL),
2585                                 ExtraVT);
2586       } else {
2587         assert(0 && "Unknown op");
2588       }
2589       break;
2590     }
2591     break;
2592   }
2593   }
2594   
2595   // Make sure that the generated code is itself legal.
2596   if (Result != Op)
2597     Result = LegalizeOp(Result);
2598
2599   // Note that LegalizeOp may be reentered even from single-use nodes, which
2600   // means that we always must cache transformed nodes.
2601   AddLegalizedOperand(Op, Result);
2602   return Result;
2603 }
2604
2605 /// PromoteOp - Given an operation that produces a value in an invalid type,
2606 /// promote it to compute the value into a larger type.  The produced value will
2607 /// have the correct bits for the low portion of the register, but no guarantee
2608 /// is made about the top bits: it may be zero, sign-extended, or garbage.
2609 SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
2610   MVT::ValueType VT = Op.getValueType();
2611   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
2612   assert(getTypeAction(VT) == Promote &&
2613          "Caller should expand or legalize operands that are not promotable!");
2614   assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
2615          "Cannot promote to smaller type!");
2616
2617   SDOperand Tmp1, Tmp2, Tmp3;
2618   SDOperand Result;
2619   SDNode *Node = Op.Val;
2620
2621   std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
2622   if (I != PromotedNodes.end()) return I->second;
2623
2624   switch (Node->getOpcode()) {
2625   case ISD::CopyFromReg:
2626     assert(0 && "CopyFromReg must be legal!");
2627   default:
2628     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
2629     assert(0 && "Do not know how to promote this operator!");
2630     abort();
2631   case ISD::UNDEF:
2632     Result = DAG.getNode(ISD::UNDEF, NVT);
2633     break;
2634   case ISD::Constant:
2635     if (VT != MVT::i1)
2636       Result = DAG.getNode(ISD::SIGN_EXTEND, NVT, Op);
2637     else
2638       Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
2639     assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
2640     break;
2641   case ISD::ConstantFP:
2642     Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
2643     assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
2644     break;
2645
2646   case ISD::SETCC:
2647     assert(isTypeLegal(TLI.getSetCCResultTy()) && "SetCC type is not legal??");
2648     Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),Node->getOperand(0),
2649                          Node->getOperand(1), Node->getOperand(2));
2650     break;
2651
2652   case ISD::TRUNCATE:
2653     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2654     case Legal:
2655       Result = LegalizeOp(Node->getOperand(0));
2656       assert(Result.getValueType() >= NVT &&
2657              "This truncation doesn't make sense!");
2658       if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
2659         Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
2660       break;
2661     case Promote:
2662       // The truncation is not required, because we don't guarantee anything
2663       // about high bits anyway.
2664       Result = PromoteOp(Node->getOperand(0));
2665       break;
2666     case Expand:
2667       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2668       // Truncate the low part of the expanded value to the result type
2669       Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
2670     }
2671     break;
2672   case ISD::SIGN_EXTEND:
2673   case ISD::ZERO_EXTEND:
2674   case ISD::ANY_EXTEND:
2675     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2676     case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
2677     case Legal:
2678       // Input is legal?  Just do extend all the way to the larger type.
2679       Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
2680       break;
2681     case Promote:
2682       // Promote the reg if it's smaller.
2683       Result = PromoteOp(Node->getOperand(0));
2684       // The high bits are not guaranteed to be anything.  Insert an extend.
2685       if (Node->getOpcode() == ISD::SIGN_EXTEND)
2686         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
2687                          DAG.getValueType(Node->getOperand(0).getValueType()));
2688       else if (Node->getOpcode() == ISD::ZERO_EXTEND)
2689         Result = DAG.getZeroExtendInReg(Result,
2690                                         Node->getOperand(0).getValueType());
2691       break;
2692     }
2693     break;
2694   case ISD::BIT_CONVERT:
2695     Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2696     Result = PromoteOp(Result);
2697     break;
2698     
2699   case ISD::FP_EXTEND:
2700     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
2701   case ISD::FP_ROUND:
2702     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2703     case Expand: assert(0 && "BUG: Cannot expand FP regs!");
2704     case Promote:  assert(0 && "Unreachable with 2 FP types!");
2705     case Legal:
2706       // Input is legal?  Do an FP_ROUND_INREG.
2707       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Node->getOperand(0),
2708                            DAG.getValueType(VT));
2709       break;
2710     }
2711     break;
2712
2713   case ISD::SINT_TO_FP:
2714   case ISD::UINT_TO_FP:
2715     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2716     case Legal:
2717       // No extra round required here.
2718       Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
2719       break;
2720
2721     case Promote:
2722       Result = PromoteOp(Node->getOperand(0));
2723       if (Node->getOpcode() == ISD::SINT_TO_FP)
2724         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2725                              Result,
2726                          DAG.getValueType(Node->getOperand(0).getValueType()));
2727       else
2728         Result = DAG.getZeroExtendInReg(Result,
2729                                         Node->getOperand(0).getValueType());
2730       // No extra round required here.
2731       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2732       break;
2733     case Expand:
2734       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
2735                              Node->getOperand(0));
2736       // Round if we cannot tolerate excess precision.
2737       if (NoExcessFPPrecision)
2738         Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2739                              DAG.getValueType(VT));
2740       break;
2741     }
2742     break;
2743
2744   case ISD::SIGN_EXTEND_INREG:
2745     Result = PromoteOp(Node->getOperand(0));
2746     Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result, 
2747                          Node->getOperand(1));
2748     break;
2749   case ISD::FP_TO_SINT:
2750   case ISD::FP_TO_UINT:
2751     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2752     case Legal:
2753       Tmp1 = Node->getOperand(0);
2754       break;
2755     case Promote:
2756       // The input result is prerounded, so we don't have to do anything
2757       // special.
2758       Tmp1 = PromoteOp(Node->getOperand(0));
2759       break;
2760     case Expand:
2761       assert(0 && "not implemented");
2762     }
2763     // If we're promoting a UINT to a larger size, check to see if the new node
2764     // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
2765     // we can use that instead.  This allows us to generate better code for
2766     // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
2767     // legal, such as PowerPC.
2768     if (Node->getOpcode() == ISD::FP_TO_UINT && 
2769         !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
2770         (TLI.isOperationLegal(ISD::FP_TO_SINT, NVT) ||
2771          TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
2772       Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
2773     } else {
2774       Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2775     }
2776     break;
2777
2778   case ISD::FABS:
2779   case ISD::FNEG:
2780     Tmp1 = PromoteOp(Node->getOperand(0));
2781     assert(Tmp1.getValueType() == NVT);
2782     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2783     // NOTE: we do not have to do any extra rounding here for
2784     // NoExcessFPPrecision, because we know the input will have the appropriate
2785     // precision, and these operations don't modify precision at all.
2786     break;
2787
2788   case ISD::FSQRT:
2789   case ISD::FSIN:
2790   case ISD::FCOS:
2791     Tmp1 = PromoteOp(Node->getOperand(0));
2792     assert(Tmp1.getValueType() == NVT);
2793     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2794     if (NoExcessFPPrecision)
2795       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2796                            DAG.getValueType(VT));
2797     break;
2798
2799   case ISD::AND:
2800   case ISD::OR:
2801   case ISD::XOR:
2802   case ISD::ADD:
2803   case ISD::SUB:
2804   case ISD::MUL:
2805     // The input may have strange things in the top bits of the registers, but
2806     // these operations don't care.  They may have weird bits going out, but
2807     // that too is okay if they are integer operations.
2808     Tmp1 = PromoteOp(Node->getOperand(0));
2809     Tmp2 = PromoteOp(Node->getOperand(1));
2810     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2811     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2812     break;
2813   case ISD::FADD:
2814   case ISD::FSUB:
2815   case ISD::FMUL:
2816     Tmp1 = PromoteOp(Node->getOperand(0));
2817     Tmp2 = PromoteOp(Node->getOperand(1));
2818     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2819     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2820     
2821     // Floating point operations will give excess precision that we may not be
2822     // able to tolerate.  If we DO allow excess precision, just leave it,
2823     // otherwise excise it.
2824     // FIXME: Why would we need to round FP ops more than integer ones?
2825     //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
2826     if (NoExcessFPPrecision)
2827       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2828                            DAG.getValueType(VT));
2829     break;
2830
2831   case ISD::SDIV:
2832   case ISD::SREM:
2833     // These operators require that their input be sign extended.
2834     Tmp1 = PromoteOp(Node->getOperand(0));
2835     Tmp2 = PromoteOp(Node->getOperand(1));
2836     if (MVT::isInteger(NVT)) {
2837       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
2838                          DAG.getValueType(VT));
2839       Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
2840                          DAG.getValueType(VT));
2841     }
2842     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2843
2844     // Perform FP_ROUND: this is probably overly pessimistic.
2845     if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
2846       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2847                            DAG.getValueType(VT));
2848     break;
2849   case ISD::FDIV:
2850   case ISD::FREM:
2851   case ISD::FCOPYSIGN:
2852     // These operators require that their input be fp extended.
2853     Tmp1 = PromoteOp(Node->getOperand(0));
2854     Tmp2 = PromoteOp(Node->getOperand(1));
2855     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2856     
2857     // Perform FP_ROUND: this is probably overly pessimistic.
2858     if (NoExcessFPPrecision && Node->getOpcode() != ISD::FCOPYSIGN)
2859       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2860                            DAG.getValueType(VT));
2861     break;
2862
2863   case ISD::UDIV:
2864   case ISD::UREM:
2865     // These operators require that their input be zero extended.
2866     Tmp1 = PromoteOp(Node->getOperand(0));
2867     Tmp2 = PromoteOp(Node->getOperand(1));
2868     assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
2869     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
2870     Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
2871     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2872     break;
2873
2874   case ISD::SHL:
2875     Tmp1 = PromoteOp(Node->getOperand(0));
2876     Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Node->getOperand(1));
2877     break;
2878   case ISD::SRA:
2879     // The input value must be properly sign extended.
2880     Tmp1 = PromoteOp(Node->getOperand(0));
2881     Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
2882                        DAG.getValueType(VT));
2883     Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Node->getOperand(1));
2884     break;
2885   case ISD::SRL:
2886     // The input value must be properly zero extended.
2887     Tmp1 = PromoteOp(Node->getOperand(0));
2888     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
2889     Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Node->getOperand(1));
2890     break;
2891
2892   case ISD::VAARG:
2893     Tmp1 = Node->getOperand(0);   // Get the chain.
2894     Tmp2 = Node->getOperand(1);   // Get the pointer.
2895     if (TLI.getOperationAction(ISD::VAARG, VT) == TargetLowering::Custom) {
2896       Tmp3 = DAG.getVAArg(VT, Tmp1, Tmp2, Node->getOperand(2));
2897       Result = TLI.CustomPromoteOperation(Tmp3, DAG);
2898     } else {
2899       SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
2900                                      Node->getOperand(2));
2901       // Increment the pointer, VAList, to the next vaarg
2902       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList, 
2903                          DAG.getConstant(MVT::getSizeInBits(VT)/8, 
2904                                          TLI.getPointerTy()));
2905       // Store the incremented VAList to the legalized pointer
2906       Tmp3 = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), Tmp3, Tmp2, 
2907                          Node->getOperand(2));
2908       // Load the actual argument out of the pointer VAList
2909       Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp3, VAList,
2910                               DAG.getSrcValue(0), VT);
2911     }
2912     // Remember that we legalized the chain.
2913     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
2914     break;
2915
2916   case ISD::LOAD:
2917     Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Node->getOperand(0),
2918                             Node->getOperand(1), Node->getOperand(2), VT);
2919     // Remember that we legalized the chain.
2920     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
2921     break;
2922   case ISD::SEXTLOAD:
2923   case ISD::ZEXTLOAD:
2924   case ISD::EXTLOAD:
2925     Result = DAG.getExtLoad(Node->getOpcode(), NVT, Node->getOperand(0),
2926                             Node->getOperand(1), Node->getOperand(2),
2927                             cast<VTSDNode>(Node->getOperand(3))->getVT());
2928     // Remember that we legalized the chain.
2929     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
2930     break;
2931   case ISD::SELECT:
2932     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
2933     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
2934     Result = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), Tmp2, Tmp3);
2935     break;
2936   case ISD::SELECT_CC:
2937     Tmp2 = PromoteOp(Node->getOperand(2));   // True
2938     Tmp3 = PromoteOp(Node->getOperand(3));   // False
2939     Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
2940                          Node->getOperand(1), Tmp2, Tmp3, Node->getOperand(4));
2941     break;
2942   case ISD::BSWAP:
2943     Tmp1 = Node->getOperand(0);
2944     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2945     Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
2946     Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
2947                          DAG.getConstant(getSizeInBits(NVT) - getSizeInBits(VT),
2948                                          TLI.getShiftAmountTy()));
2949     break;
2950   case ISD::CTPOP:
2951   case ISD::CTTZ:
2952   case ISD::CTLZ:
2953     // Zero extend the argument
2954     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
2955     // Perform the larger operation, then subtract if needed.
2956     Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2957     switch(Node->getOpcode()) {
2958     case ISD::CTPOP:
2959       Result = Tmp1;
2960       break;
2961     case ISD::CTTZ:
2962       // if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2963       Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
2964                           DAG.getConstant(getSizeInBits(NVT), NVT), ISD::SETEQ);
2965       Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
2966                            DAG.getConstant(getSizeInBits(VT), NVT), Tmp1);
2967       break;
2968     case ISD::CTLZ:
2969       //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2970       Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
2971                            DAG.getConstant(getSizeInBits(NVT) -
2972                                            getSizeInBits(VT), NVT));
2973       break;
2974     }
2975     break;
2976   }
2977
2978   assert(Result.Val && "Didn't set a result!");
2979
2980   // Make sure the result is itself legal.
2981   Result = LegalizeOp(Result);
2982   
2983   // Remember that we promoted this!
2984   AddPromotedOperand(Op, Result);
2985   return Result;
2986 }
2987
2988 /// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
2989 /// with condition CC on the current target.  This usually involves legalizing
2990 /// or promoting the arguments.  In the case where LHS and RHS must be expanded,
2991 /// there may be no choice but to create a new SetCC node to represent the
2992 /// legalized value of setcc lhs, rhs.  In this case, the value is returned in
2993 /// LHS, and the SDOperand returned in RHS has a nil SDNode value.
2994 void SelectionDAGLegalize::LegalizeSetCCOperands(SDOperand &LHS,
2995                                                  SDOperand &RHS,
2996                                                  SDOperand &CC) {
2997   SDOperand Tmp1, Tmp2, Result;    
2998   
2999   switch (getTypeAction(LHS.getValueType())) {
3000   case Legal:
3001     Tmp1 = LegalizeOp(LHS);   // LHS
3002     Tmp2 = LegalizeOp(RHS);   // RHS
3003     break;
3004   case Promote:
3005     Tmp1 = PromoteOp(LHS);   // LHS
3006     Tmp2 = PromoteOp(RHS);   // RHS
3007
3008     // If this is an FP compare, the operands have already been extended.
3009     if (MVT::isInteger(LHS.getValueType())) {
3010       MVT::ValueType VT = LHS.getValueType();
3011       MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
3012
3013       // Otherwise, we have to insert explicit sign or zero extends.  Note
3014       // that we could insert sign extends for ALL conditions, but zero extend
3015       // is cheaper on many machines (an AND instead of two shifts), so prefer
3016       // it.
3017       switch (cast<CondCodeSDNode>(CC)->get()) {
3018       default: assert(0 && "Unknown integer comparison!");
3019       case ISD::SETEQ:
3020       case ISD::SETNE:
3021       case ISD::SETUGE:
3022       case ISD::SETUGT:
3023       case ISD::SETULE:
3024       case ISD::SETULT:
3025         // ALL of these operations will work if we either sign or zero extend
3026         // the operands (including the unsigned comparisons!).  Zero extend is
3027         // usually a simpler/cheaper operation, so prefer it.
3028         Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3029         Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
3030         break;
3031       case ISD::SETGE:
3032       case ISD::SETGT:
3033       case ISD::SETLT:
3034       case ISD::SETLE:
3035         Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
3036                            DAG.getValueType(VT));
3037         Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
3038                            DAG.getValueType(VT));
3039         break;
3040       }
3041     }
3042     break;
3043   case Expand:
3044     SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
3045     ExpandOp(LHS, LHSLo, LHSHi);
3046     ExpandOp(RHS, RHSLo, RHSHi);
3047     switch (cast<CondCodeSDNode>(CC)->get()) {
3048     case ISD::SETEQ:
3049     case ISD::SETNE:
3050       if (RHSLo == RHSHi)
3051         if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
3052           if (RHSCST->isAllOnesValue()) {
3053             // Comparison to -1.
3054             Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
3055             Tmp2 = RHSLo;
3056             break;
3057           }
3058
3059       Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
3060       Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
3061       Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
3062       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3063       break;
3064     default:
3065       // If this is a comparison of the sign bit, just look at the top part.
3066       // X > -1,  x < 0
3067       if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(RHS))
3068         if ((cast<CondCodeSDNode>(CC)->get() == ISD::SETLT && 
3069              CST->getValue() == 0) ||             // X < 0
3070             (cast<CondCodeSDNode>(CC)->get() == ISD::SETGT &&
3071              CST->isAllOnesValue())) {            // X > -1
3072           Tmp1 = LHSHi;
3073           Tmp2 = RHSHi;
3074           break;
3075         }
3076
3077       // FIXME: This generated code sucks.
3078       ISD::CondCode LowCC;
3079       switch (cast<CondCodeSDNode>(CC)->get()) {
3080       default: assert(0 && "Unknown integer setcc!");
3081       case ISD::SETLT:
3082       case ISD::SETULT: LowCC = ISD::SETULT; break;
3083       case ISD::SETGT:
3084       case ISD::SETUGT: LowCC = ISD::SETUGT; break;
3085       case ISD::SETLE:
3086       case ISD::SETULE: LowCC = ISD::SETULE; break;
3087       case ISD::SETGE:
3088       case ISD::SETUGE: LowCC = ISD::SETUGE; break;
3089       }
3090
3091       // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
3092       // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
3093       // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
3094
3095       // NOTE: on targets without efficient SELECT of bools, we can always use
3096       // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
3097       Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC);
3098       Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), LHSHi, RHSHi, CC);
3099       Result = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
3100       Result = LegalizeOp(DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
3101                                       Result, Tmp1, Tmp2));
3102       Tmp1 = Result;
3103       Tmp2 = SDOperand();
3104     }
3105   }
3106   LHS = Tmp1;
3107   RHS = Tmp2;
3108 }
3109
3110 /// ExpandBIT_CONVERT - Expand a BIT_CONVERT node into a store/load combination.
3111 /// The resultant code need not be legal.  Note that SrcOp is the input operand
3112 /// to the BIT_CONVERT, not the BIT_CONVERT node itself.
3113 SDOperand SelectionDAGLegalize::ExpandBIT_CONVERT(MVT::ValueType DestVT, 
3114                                                   SDOperand SrcOp) {
3115   // Create the stack frame object.
3116   SDOperand FIPtr = CreateStackTemporary(DestVT);
3117   
3118   // Emit a store to the stack slot.
3119   SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3120                                 SrcOp, FIPtr, DAG.getSrcValue(NULL));
3121   // Result is a load from the stack slot.
3122   return DAG.getLoad(DestVT, Store, FIPtr, DAG.getSrcValue(0));
3123 }
3124
3125 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
3126 /// support the operation, but do support the resultant packed vector type.
3127 SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
3128   
3129   // If the only non-undef value is the low element, turn this into a 
3130   // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
3131   unsigned NumElems = Node->getNumOperands();
3132   bool isOnlyLowElement = true;
3133   SDOperand SplatValue = Node->getOperand(0);
3134   std::map<SDOperand, std::vector<unsigned> > Values;
3135   Values[SplatValue].push_back(0);
3136   bool isConstant = true;
3137   if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
3138       SplatValue.getOpcode() != ISD::UNDEF)
3139     isConstant = false;
3140   
3141   for (unsigned i = 1; i < NumElems; ++i) {
3142     SDOperand V = Node->getOperand(i);
3143     std::map<SDOperand, std::vector<unsigned> >::iterator I = Values.find(V);
3144     if (I != Values.end())
3145       I->second.push_back(i);
3146     else
3147       Values[V].push_back(i);
3148     if (V.getOpcode() != ISD::UNDEF)
3149       isOnlyLowElement = false;
3150     if (SplatValue != V)
3151       SplatValue = SDOperand(0,0);
3152
3153     // If this isn't a constant element or an undef, we can't use a constant
3154     // pool load.
3155     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
3156         V.getOpcode() != ISD::UNDEF)
3157       isConstant = false;
3158   }
3159   
3160   if (isOnlyLowElement) {
3161     // If the low element is an undef too, then this whole things is an undef.
3162     if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
3163       return DAG.getNode(ISD::UNDEF, Node->getValueType(0));
3164     // Otherwise, turn this into a scalar_to_vector node.
3165     return DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
3166                        Node->getOperand(0));
3167   }
3168   
3169   // If all elements are constants, create a load from the constant pool.
3170   if (isConstant) {
3171     MVT::ValueType VT = Node->getValueType(0);
3172     const Type *OpNTy = 
3173       MVT::getTypeForValueType(Node->getOperand(0).getValueType());
3174     std::vector<Constant*> CV;
3175     for (unsigned i = 0, e = NumElems; i != e; ++i) {
3176       if (ConstantFPSDNode *V = 
3177           dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
3178         CV.push_back(ConstantFP::get(OpNTy, V->getValue()));
3179       } else if (ConstantSDNode *V = 
3180                  dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
3181         CV.push_back(ConstantUInt::get(OpNTy, V->getValue()));
3182       } else {
3183         assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
3184         CV.push_back(UndefValue::get(OpNTy));
3185       }
3186     }
3187     Constant *CP = ConstantPacked::get(CV);
3188     SDOperand CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
3189     return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
3190                        DAG.getSrcValue(NULL));
3191   }
3192   
3193   if (SplatValue.Val) {   // Splat of one value?
3194     // Build the shuffle constant vector: <0, 0, 0, 0>
3195     MVT::ValueType MaskVT = 
3196       MVT::getIntVectorWithNumElements(NumElems);
3197     SDOperand Zero = DAG.getConstant(0, MVT::getVectorBaseType(MaskVT));
3198     std::vector<SDOperand> ZeroVec(NumElems, Zero);
3199     SDOperand SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, ZeroVec);
3200
3201     // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
3202     if (TLI.isShuffleLegal(Node->getValueType(0), SplatMask)) {
3203       // Get the splatted value into the low element of a vector register.
3204       SDOperand LowValVec = 
3205         DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), SplatValue);
3206     
3207       // Return shuffle(LowValVec, undef, <0,0,0,0>)
3208       return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), LowValVec,
3209                          DAG.getNode(ISD::UNDEF, Node->getValueType(0)),
3210                          SplatMask);
3211     }
3212   }
3213   
3214   // If there are only two unique elements, we may be able to turn this into a
3215   // vector shuffle.
3216   if (Values.size() == 2) {
3217     // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
3218     MVT::ValueType MaskVT = 
3219       MVT::getIntVectorWithNumElements(NumElems);
3220     std::vector<SDOperand> MaskVec(NumElems);
3221     unsigned i = 0;
3222     for (std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
3223            E = Values.end(); I != E; ++I) {
3224       for (std::vector<unsigned>::iterator II = I->second.begin(),
3225              EE = I->second.end(); II != EE; ++II)
3226         MaskVec[*II] = DAG.getConstant(i, MVT::getVectorBaseType(MaskVT));
3227       i += NumElems;
3228     }
3229     SDOperand ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
3230
3231     // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
3232     if (TLI.isShuffleLegal(Node->getValueType(0), ShuffleMask) &&
3233         TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0))) {
3234       std::vector<SDOperand> Ops;
3235       for(std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
3236             E = Values.end(); I != E; ++I) {
3237         SDOperand Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
3238                                    I->first);
3239         Ops.push_back(Op);
3240       }
3241       Ops.push_back(ShuffleMask);
3242
3243       // Return shuffle(LoValVec, HiValVec, <0,1,0,1>)
3244       return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), Ops);
3245     }
3246   }
3247   
3248   // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
3249   // aligned object on the stack, store each element into it, then load
3250   // the result as a vector.
3251   MVT::ValueType VT = Node->getValueType(0);
3252   // Create the stack frame object.
3253   SDOperand FIPtr = CreateStackTemporary(VT);
3254   
3255   // Emit a store of each element to the stack slot.
3256   std::vector<SDOperand> Stores;
3257   unsigned TypeByteSize = 
3258     MVT::getSizeInBits(Node->getOperand(0).getValueType())/8;
3259   unsigned VectorSize = MVT::getSizeInBits(VT)/8;
3260   // Store (in the right endianness) the elements to memory.
3261   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3262     // Ignore undef elements.
3263     if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
3264     
3265     unsigned Offset = TypeByteSize*i;
3266     
3267     SDOperand Idx = DAG.getConstant(Offset, FIPtr.getValueType());
3268     Idx = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr, Idx);
3269     
3270     Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3271                                  Node->getOperand(i), Idx, 
3272                                  DAG.getSrcValue(NULL)));
3273   }
3274   
3275   SDOperand StoreChain;
3276   if (!Stores.empty())    // Not all undef elements?
3277     StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
3278   else
3279     StoreChain = DAG.getEntryNode();
3280   
3281   // Result is a load from the stack slot.
3282   return DAG.getLoad(VT, StoreChain, FIPtr, DAG.getSrcValue(0));
3283 }
3284
3285 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
3286 /// specified value type.
3287 SDOperand SelectionDAGLegalize::CreateStackTemporary(MVT::ValueType VT) {
3288   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
3289   unsigned ByteSize = MVT::getSizeInBits(VT)/8;
3290   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
3291   return DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
3292 }
3293
3294 void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
3295                                             SDOperand Op, SDOperand Amt,
3296                                             SDOperand &Lo, SDOperand &Hi) {
3297   // Expand the subcomponents.
3298   SDOperand LHSL, LHSH;
3299   ExpandOp(Op, LHSL, LHSH);
3300
3301   std::vector<SDOperand> Ops;
3302   Ops.push_back(LHSL);
3303   Ops.push_back(LHSH);
3304   Ops.push_back(Amt);
3305   std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
3306   Lo = DAG.getNode(NodeOp, VTs, Ops);
3307   Hi = Lo.getValue(1);
3308 }
3309
3310
3311 /// ExpandShift - Try to find a clever way to expand this shift operation out to
3312 /// smaller elements.  If we can't find a way that is more efficient than a
3313 /// libcall on this target, return false.  Otherwise, return true with the
3314 /// low-parts expanded into Lo and Hi.
3315 bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
3316                                        SDOperand &Lo, SDOperand &Hi) {
3317   assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
3318          "This is not a shift!");
3319
3320   MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
3321   SDOperand ShAmt = LegalizeOp(Amt);
3322   MVT::ValueType ShTy = ShAmt.getValueType();
3323   unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
3324   unsigned NVTBits = MVT::getSizeInBits(NVT);
3325
3326   // Handle the case when Amt is an immediate.  Other cases are currently broken
3327   // and are disabled.
3328   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
3329     unsigned Cst = CN->getValue();
3330     // Expand the incoming operand to be shifted, so that we have its parts
3331     SDOperand InL, InH;
3332     ExpandOp(Op, InL, InH);
3333     switch(Opc) {
3334     case ISD::SHL:
3335       if (Cst > VTBits) {
3336         Lo = DAG.getConstant(0, NVT);
3337         Hi = DAG.getConstant(0, NVT);
3338       } else if (Cst > NVTBits) {
3339         Lo = DAG.getConstant(0, NVT);
3340         Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
3341       } else if (Cst == NVTBits) {
3342         Lo = DAG.getConstant(0, NVT);
3343         Hi = InL;
3344       } else {
3345         Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
3346         Hi = DAG.getNode(ISD::OR, NVT,
3347            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
3348            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
3349       }
3350       return true;
3351     case ISD::SRL:
3352       if (Cst > VTBits) {
3353         Lo = DAG.getConstant(0, NVT);
3354         Hi = DAG.getConstant(0, NVT);
3355       } else if (Cst > NVTBits) {
3356         Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
3357         Hi = DAG.getConstant(0, NVT);
3358       } else if (Cst == NVTBits) {
3359         Lo = InH;
3360         Hi = DAG.getConstant(0, NVT);
3361       } else {
3362         Lo = DAG.getNode(ISD::OR, NVT,
3363            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
3364            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
3365         Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
3366       }
3367       return true;
3368     case ISD::SRA:
3369       if (Cst > VTBits) {
3370         Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
3371                               DAG.getConstant(NVTBits-1, ShTy));
3372       } else if (Cst > NVTBits) {
3373         Lo = DAG.getNode(ISD::SRA, NVT, InH,
3374                            DAG.getConstant(Cst-NVTBits, ShTy));
3375         Hi = DAG.getNode(ISD::SRA, NVT, InH,
3376                               DAG.getConstant(NVTBits-1, ShTy));
3377       } else if (Cst == NVTBits) {
3378         Lo = InH;
3379         Hi = DAG.getNode(ISD::SRA, NVT, InH,
3380                               DAG.getConstant(NVTBits-1, ShTy));
3381       } else {
3382         Lo = DAG.getNode(ISD::OR, NVT,
3383            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
3384            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
3385         Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
3386       }
3387       return true;
3388     }
3389   }
3390   return false;
3391 }
3392
3393
3394 // ExpandLibCall - Expand a node into a call to a libcall.  If the result value
3395 // does not fit into a register, return the lo part and set the hi part to the
3396 // by-reg argument.  If it does fit into a single register, return the result
3397 // and leave the Hi part unset.
3398 SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
3399                                               SDOperand &Hi) {
3400   assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
3401   // The input chain to this libcall is the entry node of the function. 
3402   // Legalizing the call will automatically add the previous call to the
3403   // dependence.
3404   SDOperand InChain = DAG.getEntryNode();
3405   
3406   TargetLowering::ArgListTy Args;
3407   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3408     MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
3409     const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
3410     Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
3411   }
3412   SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
3413
3414   // Splice the libcall in wherever FindInputOutputChains tells us to.
3415   const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
3416   std::pair<SDOperand,SDOperand> CallInfo =
3417     TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, false,
3418                     Callee, Args, DAG);
3419
3420   // Legalize the call sequence, starting with the chain.  This will advance
3421   // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
3422   // was added by LowerCallTo (guaranteeing proper serialization of calls).
3423   LegalizeOp(CallInfo.second);
3424   SDOperand Result;
3425   switch (getTypeAction(CallInfo.first.getValueType())) {
3426   default: assert(0 && "Unknown thing");
3427   case Legal:
3428     Result = CallInfo.first;
3429     break;
3430   case Expand:
3431     ExpandOp(CallInfo.first, Result, Hi);
3432     break;
3433   }
3434   return Result;
3435 }
3436
3437
3438 /// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
3439 /// destination type is legal.
3440 SDOperand SelectionDAGLegalize::
3441 ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
3442   assert(isTypeLegal(DestTy) && "Destination type is not legal!");
3443   assert(getTypeAction(Source.getValueType()) == Expand &&
3444          "This is not an expansion!");
3445   assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
3446
3447   if (!isSigned) {
3448     assert(Source.getValueType() == MVT::i64 &&
3449            "This only works for 64-bit -> FP");
3450     // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
3451     // incoming integer is set.  To handle this, we dynamically test to see if
3452     // it is set, and, if so, add a fudge factor.
3453     SDOperand Lo, Hi;
3454     ExpandOp(Source, Lo, Hi);
3455
3456     // If this is unsigned, and not supported, first perform the conversion to
3457     // signed, then adjust the result if the sign bit is set.
3458     SDOperand SignedConv = ExpandIntToFP(true, DestTy,
3459                    DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), Lo, Hi));
3460
3461     SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
3462                                      DAG.getConstant(0, Hi.getValueType()),
3463                                      ISD::SETLT);
3464     SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
3465     SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
3466                                       SignSet, Four, Zero);
3467     uint64_t FF = 0x5f800000ULL;
3468     if (TLI.isLittleEndian()) FF <<= 32;
3469     static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
3470
3471     SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
3472     CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
3473     SDOperand FudgeInReg;
3474     if (DestTy == MVT::f32)
3475       FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
3476                                DAG.getSrcValue(NULL));
3477     else {
3478       assert(DestTy == MVT::f64 && "Unexpected conversion");
3479       FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
3480                                   CPIdx, DAG.getSrcValue(NULL), MVT::f32);
3481     }
3482     return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
3483   }
3484
3485   // Check to see if the target has a custom way to lower this.  If so, use it.
3486   switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
3487   default: assert(0 && "This action not implemented for this operation!");
3488   case TargetLowering::Legal:
3489   case TargetLowering::Expand:
3490     break;   // This case is handled below.
3491   case TargetLowering::Custom: {
3492     SDOperand NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
3493                                                   Source), DAG);
3494     if (NV.Val)
3495       return LegalizeOp(NV);
3496     break;   // The target decided this was legal after all
3497   }
3498   }
3499
3500   // Expand the source, then glue it back together for the call.  We must expand
3501   // the source in case it is shared (this pass of legalize must traverse it).
3502   SDOperand SrcLo, SrcHi;
3503   ExpandOp(Source, SrcLo, SrcHi);
3504   Source = DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), SrcLo, SrcHi);
3505
3506   const char *FnName = 0;
3507   if (DestTy == MVT::f32)
3508     FnName = "__floatdisf";
3509   else {
3510     assert(DestTy == MVT::f64 && "Unknown fp value type!");
3511     FnName = "__floatdidf";
3512   }
3513   
3514   Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
3515   SDOperand UnusedHiPart;
3516   return ExpandLibCall(FnName, Source.Val, UnusedHiPart);
3517 }
3518
3519 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
3520 /// INT_TO_FP operation of the specified operand when the target requests that
3521 /// we expand it.  At this point, we know that the result and operand types are
3522 /// legal for the target.
3523 SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
3524                                                      SDOperand Op0,
3525                                                      MVT::ValueType DestVT) {
3526   if (Op0.getValueType() == MVT::i32) {
3527     // simple 32-bit [signed|unsigned] integer to float/double expansion
3528     
3529     // get the stack frame index of a 8 byte buffer
3530     MachineFunction &MF = DAG.getMachineFunction();
3531     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3532     // get address of 8 byte buffer
3533     SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3534     // word offset constant for Hi/Lo address computation
3535     SDOperand WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
3536     // set up Hi and Lo (into buffer) address based on endian
3537     SDOperand Hi = StackSlot;
3538     SDOperand Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot,WordOff);
3539     if (TLI.isLittleEndian())
3540       std::swap(Hi, Lo);
3541     
3542     // if signed map to unsigned space
3543     SDOperand Op0Mapped;
3544     if (isSigned) {
3545       // constant used to invert sign bit (signed to unsigned mapping)
3546       SDOperand SignBit = DAG.getConstant(0x80000000u, MVT::i32);
3547       Op0Mapped = DAG.getNode(ISD::XOR, MVT::i32, Op0, SignBit);
3548     } else {
3549       Op0Mapped = Op0;
3550     }
3551     // store the lo of the constructed double - based on integer input
3552     SDOperand Store1 = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3553                                    Op0Mapped, Lo, DAG.getSrcValue(NULL));
3554     // initial hi portion of constructed double
3555     SDOperand InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
3556     // store the hi of the constructed double - biased exponent
3557     SDOperand Store2 = DAG.getNode(ISD::STORE, MVT::Other, Store1,
3558                                    InitialHi, Hi, DAG.getSrcValue(NULL));
3559     // load the constructed double
3560     SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot,
3561                                DAG.getSrcValue(NULL));
3562     // FP constant to bias correct the final result
3563     SDOperand Bias = DAG.getConstantFP(isSigned ?
3564                                             BitsToDouble(0x4330000080000000ULL)
3565                                           : BitsToDouble(0x4330000000000000ULL),
3566                                      MVT::f64);
3567     // subtract the bias
3568     SDOperand Sub = DAG.getNode(ISD::FSUB, MVT::f64, Load, Bias);
3569     // final result
3570     SDOperand Result;
3571     // handle final rounding
3572     if (DestVT == MVT::f64) {
3573       // do nothing
3574       Result = Sub;
3575     } else {
3576      // if f32 then cast to f32
3577       Result = DAG.getNode(ISD::FP_ROUND, MVT::f32, Sub);
3578     }
3579     return Result;
3580   }
3581   assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
3582   SDOperand Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
3583
3584   SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Op0,
3585                                    DAG.getConstant(0, Op0.getValueType()),
3586                                    ISD::SETLT);
3587   SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
3588   SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
3589                                     SignSet, Four, Zero);
3590
3591   // If the sign bit of the integer is set, the large number will be treated
3592   // as a negative number.  To counteract this, the dynamic code adds an
3593   // offset depending on the data type.
3594   uint64_t FF;
3595   switch (Op0.getValueType()) {
3596   default: assert(0 && "Unsupported integer type!");
3597   case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
3598   case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
3599   case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
3600   case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
3601   }
3602   if (TLI.isLittleEndian()) FF <<= 32;
3603   static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
3604
3605   SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
3606   CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
3607   SDOperand FudgeInReg;
3608   if (DestVT == MVT::f32)
3609     FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
3610                              DAG.getSrcValue(NULL));
3611   else {
3612     assert(DestVT == MVT::f64 && "Unexpected conversion");
3613     FudgeInReg = LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, MVT::f64,
3614                                            DAG.getEntryNode(), CPIdx,
3615                                            DAG.getSrcValue(NULL), MVT::f32));
3616   }
3617
3618   return DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg);
3619 }
3620
3621 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
3622 /// *INT_TO_FP operation of the specified operand when the target requests that
3623 /// we promote it.  At this point, we know that the result and operand types are
3624 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
3625 /// operation that takes a larger input.
3626 SDOperand SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDOperand LegalOp,
3627                                                       MVT::ValueType DestVT,
3628                                                       bool isSigned) {
3629   // First step, figure out the appropriate *INT_TO_FP operation to use.
3630   MVT::ValueType NewInTy = LegalOp.getValueType();
3631
3632   unsigned OpToUse = 0;
3633
3634   // Scan for the appropriate larger type to use.
3635   while (1) {
3636     NewInTy = (MVT::ValueType)(NewInTy+1);
3637     assert(MVT::isInteger(NewInTy) && "Ran out of possibilities!");
3638
3639     // If the target supports SINT_TO_FP of this type, use it.
3640     switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
3641       default: break;
3642       case TargetLowering::Legal:
3643         if (!TLI.isTypeLegal(NewInTy))
3644           break;  // Can't use this datatype.
3645         // FALL THROUGH.
3646       case TargetLowering::Custom:
3647         OpToUse = ISD::SINT_TO_FP;
3648         break;
3649     }
3650     if (OpToUse) break;
3651     if (isSigned) continue;
3652
3653     // If the target supports UINT_TO_FP of this type, use it.
3654     switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
3655       default: break;
3656       case TargetLowering::Legal:
3657         if (!TLI.isTypeLegal(NewInTy))
3658           break;  // Can't use this datatype.
3659         // FALL THROUGH.
3660       case TargetLowering::Custom:
3661         OpToUse = ISD::UINT_TO_FP;
3662         break;
3663     }
3664     if (OpToUse) break;
3665
3666     // Otherwise, try a larger type.
3667   }
3668
3669   // Okay, we found the operation and type to use.  Zero extend our input to the
3670   // desired type then run the operation on it.
3671   return DAG.getNode(OpToUse, DestVT,
3672                      DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
3673                                  NewInTy, LegalOp));
3674 }
3675
3676 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
3677 /// FP_TO_*INT operation of the specified operand when the target requests that
3678 /// we promote it.  At this point, we know that the result and operand types are
3679 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
3680 /// operation that returns a larger result.
3681 SDOperand SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDOperand LegalOp,
3682                                                       MVT::ValueType DestVT,
3683                                                       bool isSigned) {
3684   // First step, figure out the appropriate FP_TO*INT operation to use.
3685   MVT::ValueType NewOutTy = DestVT;
3686
3687   unsigned OpToUse = 0;
3688
3689   // Scan for the appropriate larger type to use.
3690   while (1) {
3691     NewOutTy = (MVT::ValueType)(NewOutTy+1);
3692     assert(MVT::isInteger(NewOutTy) && "Ran out of possibilities!");
3693
3694     // If the target supports FP_TO_SINT returning this type, use it.
3695     switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
3696     default: break;
3697     case TargetLowering::Legal:
3698       if (!TLI.isTypeLegal(NewOutTy))
3699         break;  // Can't use this datatype.
3700       // FALL THROUGH.
3701     case TargetLowering::Custom:
3702       OpToUse = ISD::FP_TO_SINT;
3703       break;
3704     }
3705     if (OpToUse) break;
3706
3707     // If the target supports FP_TO_UINT of this type, use it.
3708     switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
3709     default: break;
3710     case TargetLowering::Legal:
3711       if (!TLI.isTypeLegal(NewOutTy))
3712         break;  // Can't use this datatype.
3713       // FALL THROUGH.
3714     case TargetLowering::Custom:
3715       OpToUse = ISD::FP_TO_UINT;
3716       break;
3717     }
3718     if (OpToUse) break;
3719
3720     // Otherwise, try a larger type.
3721   }
3722
3723   // Okay, we found the operation and type to use.  Truncate the result of the
3724   // extended FP_TO_*INT operation to the desired size.
3725   return DAG.getNode(ISD::TRUNCATE, DestVT,
3726                      DAG.getNode(OpToUse, NewOutTy, LegalOp));
3727 }
3728
3729 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
3730 ///
3731 SDOperand SelectionDAGLegalize::ExpandBSWAP(SDOperand Op) {
3732   MVT::ValueType VT = Op.getValueType();
3733   MVT::ValueType SHVT = TLI.getShiftAmountTy();
3734   SDOperand Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
3735   switch (VT) {
3736   default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
3737   case MVT::i16:
3738     Tmp2 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
3739     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
3740     return DAG.getNode(ISD::OR, VT, Tmp1, Tmp2);
3741   case MVT::i32:
3742     Tmp4 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
3743     Tmp3 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
3744     Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
3745     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
3746     Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
3747     Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(0xFF00, VT));
3748     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
3749     Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
3750     return DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
3751   case MVT::i64:
3752     Tmp8 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(56, SHVT));
3753     Tmp7 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(40, SHVT));
3754     Tmp6 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
3755     Tmp5 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
3756     Tmp4 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
3757     Tmp3 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
3758     Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(40, SHVT));
3759     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(56, SHVT));
3760     Tmp7 = DAG.getNode(ISD::AND, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
3761     Tmp6 = DAG.getNode(ISD::AND, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
3762     Tmp5 = DAG.getNode(ISD::AND, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
3763     Tmp4 = DAG.getNode(ISD::AND, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
3764     Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
3765     Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
3766     Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp7);
3767     Tmp6 = DAG.getNode(ISD::OR, VT, Tmp6, Tmp5);
3768     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
3769     Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
3770     Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp6);
3771     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
3772     return DAG.getNode(ISD::OR, VT, Tmp8, Tmp4);
3773   }
3774 }
3775
3776 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
3777 ///
3778 SDOperand SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDOperand Op) {
3779   switch (Opc) {
3780   default: assert(0 && "Cannot expand this yet!");
3781   case ISD::CTPOP: {
3782     static const uint64_t mask[6] = {
3783       0x5555555555555555ULL, 0x3333333333333333ULL,
3784       0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
3785       0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
3786     };
3787     MVT::ValueType VT = Op.getValueType();
3788     MVT::ValueType ShVT = TLI.getShiftAmountTy();
3789     unsigned len = getSizeInBits(VT);
3790     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
3791       //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
3792       SDOperand Tmp2 = DAG.getConstant(mask[i], VT);
3793       SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
3794       Op = DAG.getNode(ISD::ADD, VT, DAG.getNode(ISD::AND, VT, Op, Tmp2),
3795                        DAG.getNode(ISD::AND, VT,
3796                                    DAG.getNode(ISD::SRL, VT, Op, Tmp3),Tmp2));
3797     }
3798     return Op;
3799   }
3800   case ISD::CTLZ: {
3801     // for now, we do this:
3802     // x = x | (x >> 1);
3803     // x = x | (x >> 2);
3804     // ...
3805     // x = x | (x >>16);
3806     // x = x | (x >>32); // for 64-bit input
3807     // return popcount(~x);
3808     //
3809     // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
3810     MVT::ValueType VT = Op.getValueType();
3811     MVT::ValueType ShVT = TLI.getShiftAmountTy();
3812     unsigned len = getSizeInBits(VT);
3813     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
3814       SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
3815       Op = DAG.getNode(ISD::OR, VT, Op, DAG.getNode(ISD::SRL, VT, Op, Tmp3));
3816     }
3817     Op = DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(~0ULL, VT));
3818     return DAG.getNode(ISD::CTPOP, VT, Op);
3819   }
3820   case ISD::CTTZ: {
3821     // for now, we use: { return popcount(~x & (x - 1)); }
3822     // unless the target has ctlz but not ctpop, in which case we use:
3823     // { return 32 - nlz(~x & (x-1)); }
3824     // see also http://www.hackersdelight.org/HDcode/ntz.cc
3825     MVT::ValueType VT = Op.getValueType();
3826     SDOperand Tmp2 = DAG.getConstant(~0ULL, VT);
3827     SDOperand Tmp3 = DAG.getNode(ISD::AND, VT,
3828                        DAG.getNode(ISD::XOR, VT, Op, Tmp2),
3829                        DAG.getNode(ISD::SUB, VT, Op, DAG.getConstant(1, VT)));
3830     // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
3831     if (!TLI.isOperationLegal(ISD::CTPOP, VT) &&
3832         TLI.isOperationLegal(ISD::CTLZ, VT))
3833       return DAG.getNode(ISD::SUB, VT,
3834                          DAG.getConstant(getSizeInBits(VT), VT),
3835                          DAG.getNode(ISD::CTLZ, VT, Tmp3));
3836     return DAG.getNode(ISD::CTPOP, VT, Tmp3);
3837   }
3838   }
3839 }
3840
3841
3842 /// ExpandOp - Expand the specified SDOperand into its two component pieces
3843 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
3844 /// LegalizeNodes map is filled in for any results that are not expanded, the
3845 /// ExpandedNodes map is filled in for any results that are expanded, and the
3846 /// Lo/Hi values are returned.
3847 void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
3848   MVT::ValueType VT = Op.getValueType();
3849   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
3850   SDNode *Node = Op.Val;
3851   assert(getTypeAction(VT) == Expand && "Not an expanded type!");
3852   assert((MVT::isInteger(VT) || VT == MVT::Vector) && 
3853          "Cannot expand FP values!");
3854   assert(((MVT::isInteger(NVT) && NVT < VT) || VT == MVT::Vector) &&
3855          "Cannot expand to FP value or to larger int value!");
3856
3857   // See if we already expanded it.
3858   std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
3859     = ExpandedNodes.find(Op);
3860   if (I != ExpandedNodes.end()) {
3861     Lo = I->second.first;
3862     Hi = I->second.second;
3863     return;
3864   }
3865
3866   switch (Node->getOpcode()) {
3867   case ISD::CopyFromReg:
3868     assert(0 && "CopyFromReg must be legal!");
3869   default:
3870     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
3871     assert(0 && "Do not know how to expand this operator!");
3872     abort();
3873   case ISD::UNDEF:
3874     Lo = DAG.getNode(ISD::UNDEF, NVT);
3875     Hi = DAG.getNode(ISD::UNDEF, NVT);
3876     break;
3877   case ISD::Constant: {
3878     uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
3879     Lo = DAG.getConstant(Cst, NVT);
3880     Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
3881     break;
3882   }
3883   case ISD::BUILD_PAIR:
3884     // Return the operands.
3885     Lo = Node->getOperand(0);
3886     Hi = Node->getOperand(1);
3887     break;
3888     
3889   case ISD::SIGN_EXTEND_INREG:
3890     ExpandOp(Node->getOperand(0), Lo, Hi);
3891     // Sign extend the lo-part.
3892     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
3893                      DAG.getConstant(MVT::getSizeInBits(NVT)-1,
3894                                      TLI.getShiftAmountTy()));
3895     // sext_inreg the low part if needed.
3896     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
3897     break;
3898
3899   case ISD::BSWAP: {
3900     ExpandOp(Node->getOperand(0), Lo, Hi);
3901     SDOperand TempLo = DAG.getNode(ISD::BSWAP, NVT, Hi);
3902     Hi = DAG.getNode(ISD::BSWAP, NVT, Lo);
3903     Lo = TempLo;
3904     break;
3905   }
3906     
3907   case ISD::CTPOP:
3908     ExpandOp(Node->getOperand(0), Lo, Hi);
3909     Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
3910                      DAG.getNode(ISD::CTPOP, NVT, Lo),
3911                      DAG.getNode(ISD::CTPOP, NVT, Hi));
3912     Hi = DAG.getConstant(0, NVT);
3913     break;
3914
3915   case ISD::CTLZ: {
3916     // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
3917     ExpandOp(Node->getOperand(0), Lo, Hi);
3918     SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
3919     SDOperand HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
3920     SDOperand TopNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), HLZ, BitsC,
3921                                         ISD::SETNE);
3922     SDOperand LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
3923     LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
3924
3925     Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
3926     Hi = DAG.getConstant(0, NVT);
3927     break;
3928   }
3929
3930   case ISD::CTTZ: {
3931     // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
3932     ExpandOp(Node->getOperand(0), Lo, Hi);
3933     SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
3934     SDOperand LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
3935     SDOperand BotNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), LTZ, BitsC,
3936                                         ISD::SETNE);
3937     SDOperand HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
3938     HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
3939
3940     Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
3941     Hi = DAG.getConstant(0, NVT);
3942     break;
3943   }
3944
3945   case ISD::VAARG: {
3946     SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
3947     SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
3948     Lo = DAG.getVAArg(NVT, Ch, Ptr, Node->getOperand(2));
3949     Hi = DAG.getVAArg(NVT, Lo.getValue(1), Ptr, Node->getOperand(2));
3950
3951     // Remember that we legalized the chain.
3952     Hi = LegalizeOp(Hi);
3953     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
3954     if (!TLI.isLittleEndian())
3955       std::swap(Lo, Hi);
3956     break;
3957   }
3958     
3959   case ISD::LOAD: {
3960     SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
3961     SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
3962     Lo = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
3963
3964     // Increment the pointer to the other half.
3965     unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
3966     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
3967                       getIntPtrConstant(IncrementSize));
3968     // FIXME: This creates a bogus srcvalue!
3969     Hi = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
3970
3971     // Build a factor node to remember that this load is independent of the
3972     // other one.
3973     SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
3974                                Hi.getValue(1));
3975
3976     // Remember that we legalized the chain.
3977     AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
3978     if (!TLI.isLittleEndian())
3979       std::swap(Lo, Hi);
3980     break;
3981   }
3982   case ISD::AND:
3983   case ISD::OR:
3984   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
3985     SDOperand LL, LH, RL, RH;
3986     ExpandOp(Node->getOperand(0), LL, LH);
3987     ExpandOp(Node->getOperand(1), RL, RH);
3988     Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
3989     Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
3990     break;
3991   }
3992   case ISD::SELECT: {
3993     SDOperand LL, LH, RL, RH;
3994     ExpandOp(Node->getOperand(1), LL, LH);
3995     ExpandOp(Node->getOperand(2), RL, RH);
3996     Lo = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LL, RL);
3997     Hi = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LH, RH);
3998     break;
3999   }
4000   case ISD::SELECT_CC: {
4001     SDOperand TL, TH, FL, FH;
4002     ExpandOp(Node->getOperand(2), TL, TH);
4003     ExpandOp(Node->getOperand(3), FL, FH);
4004     Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4005                      Node->getOperand(1), TL, FL, Node->getOperand(4));
4006     Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4007                      Node->getOperand(1), TH, FH, Node->getOperand(4));
4008     break;
4009   }
4010   case ISD::SEXTLOAD: {
4011     SDOperand Chain = Node->getOperand(0);
4012     SDOperand Ptr   = Node->getOperand(1);
4013     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4014     
4015     if (EVT == NVT)
4016       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4017     else
4018       Lo = DAG.getExtLoad(ISD::SEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4019                           EVT);
4020     
4021     // Remember that we legalized the chain.
4022     AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4023     
4024     // The high part is obtained by SRA'ing all but one of the bits of the lo
4025     // part.
4026     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
4027     Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
4028                                                        TLI.getShiftAmountTy()));
4029     break;
4030   }
4031   case ISD::ZEXTLOAD: {
4032     SDOperand Chain = Node->getOperand(0);
4033     SDOperand Ptr   = Node->getOperand(1);
4034     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4035     
4036     if (EVT == NVT)
4037       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4038     else
4039       Lo = DAG.getExtLoad(ISD::ZEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4040                           EVT);
4041     
4042     // Remember that we legalized the chain.
4043     AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4044
4045     // The high part is just a zero.
4046     Hi = DAG.getConstant(0, NVT);
4047     break;
4048   }
4049   case ISD::EXTLOAD: {
4050     SDOperand Chain = Node->getOperand(0);
4051     SDOperand Ptr   = Node->getOperand(1);
4052     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4053     
4054     if (EVT == NVT)
4055       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4056     else
4057       Lo = DAG.getExtLoad(ISD::EXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4058                           EVT);
4059     
4060     // Remember that we legalized the chain.
4061     AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4062     
4063     // The high part is undefined.
4064     Hi = DAG.getNode(ISD::UNDEF, NVT);
4065     break;
4066   }
4067   case ISD::ANY_EXTEND:
4068     // The low part is any extension of the input (which degenerates to a copy).
4069     Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, Node->getOperand(0));
4070     // The high part is undefined.
4071     Hi = DAG.getNode(ISD::UNDEF, NVT);
4072     break;
4073   case ISD::SIGN_EXTEND: {
4074     // The low part is just a sign extension of the input (which degenerates to
4075     // a copy).
4076     Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, Node->getOperand(0));
4077
4078     // The high part is obtained by SRA'ing all but one of the bits of the lo
4079     // part.
4080     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
4081     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
4082                      DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
4083     break;
4084   }
4085   case ISD::ZERO_EXTEND:
4086     // The low part is just a zero extension of the input (which degenerates to
4087     // a copy).
4088     Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
4089
4090     // The high part is just a zero.
4091     Hi = DAG.getConstant(0, NVT);
4092     break;
4093     
4094   case ISD::BIT_CONVERT: {
4095     SDOperand Tmp = ExpandBIT_CONVERT(Node->getValueType(0), 
4096                                       Node->getOperand(0));
4097     ExpandOp(Tmp, Lo, Hi);
4098     break;
4099   }
4100
4101   case ISD::READCYCLECOUNTER:
4102     assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) == 
4103                  TargetLowering::Custom &&
4104            "Must custom expand ReadCycleCounter");
4105     Lo = TLI.LowerOperation(Op, DAG);
4106     assert(Lo.Val && "Node must be custom expanded!");
4107     Hi = Lo.getValue(1);
4108     AddLegalizedOperand(SDOperand(Node, 1), // Remember we legalized the chain.
4109                         LegalizeOp(Lo.getValue(2)));
4110     break;
4111
4112     // These operators cannot be expanded directly, emit them as calls to
4113     // library functions.
4114   case ISD::FP_TO_SINT:
4115     if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
4116       SDOperand Op;
4117       switch (getTypeAction(Node->getOperand(0).getValueType())) {
4118       case Expand: assert(0 && "cannot expand FP!");
4119       case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
4120       case Promote: Op = PromoteOp (Node->getOperand(0)); break;
4121       }
4122
4123       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
4124
4125       // Now that the custom expander is done, expand the result, which is still
4126       // VT.
4127       if (Op.Val) {
4128         ExpandOp(Op, Lo, Hi);
4129         break;
4130       }
4131     }
4132
4133     if (Node->getOperand(0).getValueType() == MVT::f32)
4134       Lo = ExpandLibCall("__fixsfdi", Node, Hi);
4135     else
4136       Lo = ExpandLibCall("__fixdfdi", Node, Hi);
4137     break;
4138
4139   case ISD::FP_TO_UINT:
4140     if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
4141       SDOperand Op;
4142       switch (getTypeAction(Node->getOperand(0).getValueType())) {
4143         case Expand: assert(0 && "cannot expand FP!");
4144         case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
4145         case Promote: Op = PromoteOp (Node->getOperand(0)); break;
4146       }
4147         
4148       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_UINT, VT, Op), DAG);
4149
4150       // Now that the custom expander is done, expand the result.
4151       if (Op.Val) {
4152         ExpandOp(Op, Lo, Hi);
4153         break;
4154       }
4155     }
4156
4157     if (Node->getOperand(0).getValueType() == MVT::f32)
4158       Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
4159     else
4160       Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
4161     break;
4162
4163   case ISD::SHL: {
4164     // If the target wants custom lowering, do so.
4165     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4166     if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
4167       SDOperand Op = DAG.getNode(ISD::SHL, VT, Node->getOperand(0), ShiftAmt);
4168       Op = TLI.LowerOperation(Op, DAG);
4169       if (Op.Val) {
4170         // Now that the custom expander is done, expand the result, which is
4171         // still VT.
4172         ExpandOp(Op, Lo, Hi);
4173         break;
4174       }
4175     }
4176     
4177     // If we can emit an efficient shift operation, do so now.
4178     if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi))
4179       break;
4180
4181     // If this target supports SHL_PARTS, use it.
4182     TargetLowering::LegalizeAction Action =
4183       TLI.getOperationAction(ISD::SHL_PARTS, NVT);
4184     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4185         Action == TargetLowering::Custom) {
4186       ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4187       break;
4188     }
4189
4190     // Otherwise, emit a libcall.
4191     Lo = ExpandLibCall("__ashldi3", Node, Hi);
4192     break;
4193   }
4194
4195   case ISD::SRA: {
4196     // If the target wants custom lowering, do so.
4197     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4198     if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
4199       SDOperand Op = DAG.getNode(ISD::SRA, VT, Node->getOperand(0), ShiftAmt);
4200       Op = TLI.LowerOperation(Op, DAG);
4201       if (Op.Val) {
4202         // Now that the custom expander is done, expand the result, which is
4203         // still VT.
4204         ExpandOp(Op, Lo, Hi);
4205         break;
4206       }
4207     }
4208     
4209     // If we can emit an efficient shift operation, do so now.
4210     if (ExpandShift(ISD::SRA, Node->getOperand(0), ShiftAmt, Lo, Hi))
4211       break;
4212
4213     // If this target supports SRA_PARTS, use it.
4214     TargetLowering::LegalizeAction Action =
4215       TLI.getOperationAction(ISD::SRA_PARTS, NVT);
4216     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4217         Action == TargetLowering::Custom) {
4218       ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4219       break;
4220     }
4221
4222     // Otherwise, emit a libcall.
4223     Lo = ExpandLibCall("__ashrdi3", Node, Hi);
4224     break;
4225   }
4226
4227   case ISD::SRL: {
4228     // If the target wants custom lowering, do so.
4229     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4230     if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
4231       SDOperand Op = DAG.getNode(ISD::SRL, VT, Node->getOperand(0), ShiftAmt);
4232       Op = TLI.LowerOperation(Op, DAG);
4233       if (Op.Val) {
4234         // Now that the custom expander is done, expand the result, which is
4235         // still VT.
4236         ExpandOp(Op, Lo, Hi);
4237         break;
4238       }
4239     }
4240
4241     // If we can emit an efficient shift operation, do so now.
4242     if (ExpandShift(ISD::SRL, Node->getOperand(0), ShiftAmt, Lo, Hi))
4243       break;
4244
4245     // If this target supports SRL_PARTS, use it.
4246     TargetLowering::LegalizeAction Action =
4247       TLI.getOperationAction(ISD::SRL_PARTS, NVT);
4248     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4249         Action == TargetLowering::Custom) {
4250       ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4251       break;
4252     }
4253
4254     // Otherwise, emit a libcall.
4255     Lo = ExpandLibCall("__lshrdi3", Node, Hi);
4256     break;
4257   }
4258
4259   case ISD::ADD:
4260   case ISD::SUB: {
4261     // If the target wants to custom expand this, let them.
4262     if (TLI.getOperationAction(Node->getOpcode(), VT) ==
4263             TargetLowering::Custom) {
4264       Op = TLI.LowerOperation(Op, DAG);
4265       if (Op.Val) {
4266         ExpandOp(Op, Lo, Hi);
4267         break;
4268       }
4269     }
4270     
4271     // Expand the subcomponents.
4272     SDOperand LHSL, LHSH, RHSL, RHSH;
4273     ExpandOp(Node->getOperand(0), LHSL, LHSH);
4274     ExpandOp(Node->getOperand(1), RHSL, RHSH);
4275     std::vector<MVT::ValueType> VTs;
4276     std::vector<SDOperand> LoOps, HiOps;
4277     VTs.push_back(LHSL.getValueType());
4278     VTs.push_back(MVT::Flag);
4279     LoOps.push_back(LHSL);
4280     LoOps.push_back(RHSL);
4281     HiOps.push_back(LHSH);
4282     HiOps.push_back(RHSH);
4283     if (Node->getOpcode() == ISD::ADD) {
4284       Lo = DAG.getNode(ISD::ADDC, VTs, LoOps);
4285       HiOps.push_back(Lo.getValue(1));
4286       Hi = DAG.getNode(ISD::ADDE, VTs, HiOps);
4287     } else {
4288       Lo = DAG.getNode(ISD::SUBC, VTs, LoOps);
4289       HiOps.push_back(Lo.getValue(1));
4290       Hi = DAG.getNode(ISD::SUBE, VTs, HiOps);
4291     }
4292     break;
4293   }
4294   case ISD::MUL: {
4295     if (TLI.isOperationLegal(ISD::MULHU, NVT)) {
4296       SDOperand LL, LH, RL, RH;
4297       ExpandOp(Node->getOperand(0), LL, LH);
4298       ExpandOp(Node->getOperand(1), RL, RH);
4299       unsigned SH = MVT::getSizeInBits(RH.getValueType())-1;
4300       // MULHS implicitly sign extends its inputs.  Check to see if ExpandOp
4301       // extended the sign bit of the low half through the upper half, and if so
4302       // emit a MULHS instead of the alternate sequence that is valid for any
4303       // i64 x i64 multiply.
4304       if (TLI.isOperationLegal(ISD::MULHS, NVT) &&
4305           // is RH an extension of the sign bit of RL?
4306           RH.getOpcode() == ISD::SRA && RH.getOperand(0) == RL &&
4307           RH.getOperand(1).getOpcode() == ISD::Constant &&
4308           cast<ConstantSDNode>(RH.getOperand(1))->getValue() == SH &&
4309           // is LH an extension of the sign bit of LL?
4310           LH.getOpcode() == ISD::SRA && LH.getOperand(0) == LL &&
4311           LH.getOperand(1).getOpcode() == ISD::Constant &&
4312           cast<ConstantSDNode>(LH.getOperand(1))->getValue() == SH) {
4313         Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
4314       } else {
4315         Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
4316         RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
4317         LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
4318         Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
4319         Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
4320       }
4321       Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
4322     } else {
4323       Lo = ExpandLibCall("__muldi3" , Node, Hi);
4324     }
4325     break;
4326   }
4327   case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
4328   case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
4329   case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
4330   case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
4331   }
4332
4333   // Make sure the resultant values have been legalized themselves, unless this
4334   // is a type that requires multi-step expansion.
4335   if (getTypeAction(NVT) != Expand && NVT != MVT::isVoid) {
4336     Lo = LegalizeOp(Lo);
4337     Hi = LegalizeOp(Hi);
4338   }
4339
4340   // Remember in a map if the values will be reused later.
4341   bool isNew =
4342     ExpandedNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
4343   assert(isNew && "Value already expanded?!?");
4344 }
4345
4346 /// SplitVectorOp - Given an operand of MVT::Vector type, break it down into
4347 /// two smaller values of MVT::Vector type.
4348 void SelectionDAGLegalize::SplitVectorOp(SDOperand Op, SDOperand &Lo,
4349                                          SDOperand &Hi) {
4350   assert(Op.getValueType() == MVT::Vector && "Cannot split non-vector type!");
4351   SDNode *Node = Op.Val;
4352   unsigned NumElements = cast<ConstantSDNode>(*(Node->op_end()-2))->getValue();
4353   assert(NumElements > 1 && "Cannot split a single element vector!");
4354   unsigned NewNumElts = NumElements/2;
4355   SDOperand NewNumEltsNode = DAG.getConstant(NewNumElts, MVT::i32);
4356   SDOperand TypeNode = *(Node->op_end()-1);
4357   
4358   // See if we already split it.
4359   std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
4360     = SplitNodes.find(Op);
4361   if (I != SplitNodes.end()) {
4362     Lo = I->second.first;
4363     Hi = I->second.second;
4364     return;
4365   }
4366   
4367   switch (Node->getOpcode()) {
4368   default: Node->dump(); assert(0 && "Unknown vector operation!");
4369   case ISD::VBUILD_VECTOR: {
4370     std::vector<SDOperand> LoOps(Node->op_begin(), Node->op_begin()+NewNumElts);
4371     LoOps.push_back(NewNumEltsNode);
4372     LoOps.push_back(TypeNode);
4373     Lo = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, LoOps);
4374
4375     std::vector<SDOperand> HiOps(Node->op_begin()+NewNumElts, Node->op_end()-2);
4376     HiOps.push_back(NewNumEltsNode);
4377     HiOps.push_back(TypeNode);
4378     Hi = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, HiOps);
4379     break;
4380   }
4381   case ISD::VADD:
4382   case ISD::VSUB:
4383   case ISD::VMUL:
4384   case ISD::VSDIV:
4385   case ISD::VUDIV:
4386   case ISD::VAND:
4387   case ISD::VOR:
4388   case ISD::VXOR: {
4389     SDOperand LL, LH, RL, RH;
4390     SplitVectorOp(Node->getOperand(0), LL, LH);
4391     SplitVectorOp(Node->getOperand(1), RL, RH);
4392     
4393     Lo = DAG.getNode(Node->getOpcode(), MVT::Vector, LL, RL,
4394                      NewNumEltsNode, TypeNode);
4395     Hi = DAG.getNode(Node->getOpcode(), MVT::Vector, LH, RH,
4396                      NewNumEltsNode, TypeNode);
4397     break;
4398   }
4399   case ISD::VLOAD: {
4400     SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
4401     SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
4402     MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
4403     
4404     Lo = DAG.getVecLoad(NewNumElts, EVT, Ch, Ptr, Node->getOperand(2));
4405     unsigned IncrementSize = NewNumElts * MVT::getSizeInBits(EVT)/8;
4406     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4407                       getIntPtrConstant(IncrementSize));
4408     // FIXME: This creates a bogus srcvalue!
4409     Hi = DAG.getVecLoad(NewNumElts, EVT, Ch, Ptr, Node->getOperand(2));
4410     
4411     // Build a factor node to remember that this load is independent of the
4412     // other one.
4413     SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
4414                                Hi.getValue(1));
4415     
4416     // Remember that we legalized the chain.
4417     AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
4418     if (!TLI.isLittleEndian())
4419       std::swap(Lo, Hi);
4420     break;
4421   }
4422   case ISD::VBIT_CONVERT: {
4423     // We know the result is a vector.  The input may be either a vector or a
4424     // scalar value.
4425     if (Op.getOperand(0).getValueType() != MVT::Vector) {
4426       // Lower to a store/load.  FIXME: this could be improved probably.
4427       SDOperand Ptr = CreateStackTemporary(Op.getOperand(0).getValueType());
4428
4429       SDOperand St = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
4430                                  Op.getOperand(0), Ptr, DAG.getSrcValue(0));
4431       MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
4432       St = DAG.getVecLoad(NumElements, EVT, St, Ptr, DAG.getSrcValue(0));
4433       SplitVectorOp(St, Lo, Hi);
4434     } else {
4435       // If the input is a vector type, we have to either scalarize it, pack it
4436       // or convert it based on whether the input vector type is legal.
4437       SDNode *InVal = Node->getOperand(0).Val;
4438       unsigned NumElems =
4439         cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
4440       MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
4441
4442       // If the input is from a single element vector, scalarize the vector,
4443       // then treat like a scalar.
4444       if (NumElems == 1) {
4445         SDOperand Scalar = PackVectorOp(Op.getOperand(0), EVT);
4446         Scalar = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Scalar,
4447                              Op.getOperand(1), Op.getOperand(2));
4448         SplitVectorOp(Scalar, Lo, Hi);
4449       } else {
4450         // Split the input vector.
4451         SplitVectorOp(Op.getOperand(0), Lo, Hi);
4452
4453         // Convert each of the pieces now.
4454         Lo = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Lo,
4455                          NewNumEltsNode, TypeNode);
4456         Hi = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Hi,
4457                          NewNumEltsNode, TypeNode);
4458       }
4459       break;
4460     }
4461   }
4462   }
4463       
4464   // Remember in a map if the values will be reused later.
4465   bool isNew =
4466     SplitNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
4467   assert(isNew && "Value already expanded?!?");
4468 }
4469
4470
4471 /// PackVectorOp - Given an operand of MVT::Vector type, convert it into the
4472 /// equivalent operation that returns a scalar (e.g. F32) or packed value
4473 /// (e.g. MVT::V4F32).  When this is called, we know that PackedVT is the right
4474 /// type for the result.
4475 SDOperand SelectionDAGLegalize::PackVectorOp(SDOperand Op, 
4476                                              MVT::ValueType NewVT) {
4477   // FIXME: THIS IS A TEMPORARY HACK
4478   if (Op.getValueType() == NewVT) return Op;
4479     
4480   assert(Op.getValueType() == MVT::Vector && "Bad PackVectorOp invocation!");
4481   SDNode *Node = Op.Val;
4482   
4483   // See if we already packed it.
4484   std::map<SDOperand, SDOperand>::iterator I = PackedNodes.find(Op);
4485   if (I != PackedNodes.end()) return I->second;
4486   
4487   SDOperand Result;
4488   switch (Node->getOpcode()) {
4489   default: 
4490     Node->dump(); std::cerr << "\n";
4491     assert(0 && "Unknown vector operation in PackVectorOp!");
4492   case ISD::VADD:
4493   case ISD::VSUB:
4494   case ISD::VMUL:
4495   case ISD::VSDIV:
4496   case ISD::VUDIV:
4497   case ISD::VAND:
4498   case ISD::VOR:
4499   case ISD::VXOR:
4500     Result = DAG.getNode(getScalarizedOpcode(Node->getOpcode(), NewVT),
4501                          NewVT, 
4502                          PackVectorOp(Node->getOperand(0), NewVT),
4503                          PackVectorOp(Node->getOperand(1), NewVT));
4504     break;
4505   case ISD::VLOAD: {
4506     SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
4507     SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
4508     
4509     Result = DAG.getLoad(NewVT, Ch, Ptr, Node->getOperand(2));
4510     
4511     // Remember that we legalized the chain.
4512     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4513     break;
4514   }
4515   case ISD::VBUILD_VECTOR:
4516     if (!MVT::isVector(NewVT)) {
4517       // Returning a scalar?
4518       Result = Node->getOperand(0);
4519     } else {
4520       // Returning a BUILD_VECTOR?
4521       std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end()-2);
4522       Result = DAG.getNode(ISD::BUILD_VECTOR, NewVT, Ops);
4523     }
4524     break;
4525   case ISD::VINSERT_VECTOR_ELT:
4526     if (!MVT::isVector(NewVT)) {
4527       // Returning a scalar?  Must be the inserted element.
4528       Result = Node->getOperand(1);
4529     } else {
4530       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT,
4531                            PackVectorOp(Node->getOperand(0), NewVT),
4532                            Node->getOperand(1), Node->getOperand(2));
4533     }
4534     break;
4535   case ISD::VVECTOR_SHUFFLE:
4536     if (!MVT::isVector(NewVT)) {
4537       // Returning a scalar?  Figure out if it is the LHS or RHS and return it.
4538       SDOperand EltNum = Node->getOperand(2).getOperand(0);
4539       if (cast<ConstantSDNode>(EltNum)->getValue())
4540         Result = PackVectorOp(Node->getOperand(1), NewVT);
4541       else
4542         Result = PackVectorOp(Node->getOperand(0), NewVT);
4543     } else {
4544       // Otherwise, return a VECTOR_SHUFFLE node.  First convert the index
4545       // vector from a VBUILD_VECTOR to a BUILD_VECTOR.
4546       std::vector<SDOperand> BuildVecIdx(Node->getOperand(2).Val->op_begin(),
4547                                          Node->getOperand(2).Val->op_end()-2);
4548       MVT::ValueType BVT = MVT::getIntVectorWithNumElements(BuildVecIdx.size());
4549       SDOperand BV = DAG.getNode(ISD::BUILD_VECTOR, BVT, BuildVecIdx);
4550       
4551       Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT,
4552                            PackVectorOp(Node->getOperand(0), NewVT),
4553                            PackVectorOp(Node->getOperand(1), NewVT), BV);
4554     }
4555     break;
4556   case ISD::VBIT_CONVERT:
4557     if (Op.getOperand(0).getValueType() != MVT::Vector)
4558       Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, Op.getOperand(0));
4559     else {
4560       // If the input is a vector type, we have to either scalarize it, pack it
4561       // or convert it based on whether the input vector type is legal.
4562       SDNode *InVal = Node->getOperand(0).Val;
4563       unsigned NumElems =
4564         cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
4565       MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
4566         
4567       // Figure out if there is a Packed type corresponding to this Vector
4568       // type.  If so, convert to the packed type.
4569       MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
4570       if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
4571         // Turn this into a bit convert of the packed input.
4572         Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, 
4573                              PackVectorOp(Node->getOperand(0), TVT));
4574         break;
4575       } else if (NumElems == 1) {
4576         // Turn this into a bit convert of the scalar input.
4577         Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, 
4578                              PackVectorOp(Node->getOperand(0), EVT));
4579         break;
4580       } else {
4581         // FIXME: UNIMP!
4582         assert(0 && "Cast from unsupported vector type not implemented yet!");
4583       }
4584     }
4585   }
4586
4587   if (TLI.isTypeLegal(NewVT))
4588     Result = LegalizeOp(Result);
4589   bool isNew = PackedNodes.insert(std::make_pair(Op, Result)).second;
4590   assert(isNew && "Value already packed?");
4591   return Result;
4592 }
4593
4594
4595 // SelectionDAG::Legalize - This is the entry point for the file.
4596 //
4597 void SelectionDAG::Legalize() {
4598   /// run - This is the main entry point to this class.
4599   ///
4600   SelectionDAGLegalize(*this).LegalizeDAG();
4601 }
4602