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