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