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