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