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