Reapply r60997, this time without forgetting that
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeDAG.cpp
1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/CodeGen/MachineModuleInfo.h"
19 #include "llvm/CodeGen/PseudoSourceValue.h"
20 #include "llvm/Target/TargetFrameInfo.h"
21 #include "llvm/Target/TargetLowering.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/Target/TargetSubtarget.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/Constants.h"
28 #include "llvm/DerivedTypes.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include <map>
36 using namespace llvm;
37
38 //===----------------------------------------------------------------------===//
39 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
40 /// hacks on it until the target machine can handle it.  This involves
41 /// eliminating value sizes the machine cannot handle (promoting small sizes to
42 /// large sizes or splitting up large values into small values) as well as
43 /// eliminating operations the machine cannot handle.
44 ///
45 /// This code also does a small amount of optimization and recognition of idioms
46 /// as part of its processing.  For example, if a target does not support a
47 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
48 /// will attempt merge setcc and brc instructions into brcc's.
49 ///
50 namespace {
51 class VISIBILITY_HIDDEN SelectionDAGLegalize {
52   TargetLowering &TLI;
53   SelectionDAG &DAG;
54   bool TypesNeedLegalizing;
55
56   // Libcall insertion helpers.
57   
58   /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
59   /// legalized.  We use this to ensure that calls are properly serialized
60   /// against each other, including inserted libcalls.
61   SDValue LastCALLSEQ_END;
62   
63   /// IsLegalizingCall - This member is used *only* for purposes of providing
64   /// helpful assertions that a libcall isn't created while another call is 
65   /// being legalized (which could lead to non-serialized call sequences).
66   bool IsLegalizingCall;
67   
68   enum LegalizeAction {
69     Legal,      // The target natively supports this operation.
70     Promote,    // This operation should be executed in a larger type.
71     Expand      // Try to expand this to other ops, otherwise use a libcall.
72   };
73   
74   /// ValueTypeActions - This is a bitvector that contains two bits for each
75   /// value type, where the two bits correspond to the LegalizeAction enum.
76   /// This can be queried with "getTypeAction(VT)".
77   TargetLowering::ValueTypeActionImpl ValueTypeActions;
78
79   /// LegalizedNodes - For nodes that are of legal width, and that have more
80   /// than one use, this map indicates what regularized operand to use.  This
81   /// allows us to avoid legalizing the same thing more than once.
82   DenseMap<SDValue, SDValue> LegalizedNodes;
83
84   /// PromotedNodes - For nodes that are below legal width, and that have more
85   /// than one use, this map indicates what promoted value to use.  This allows
86   /// us to avoid promoting the same thing more than once.
87   DenseMap<SDValue, SDValue> PromotedNodes;
88
89   /// ExpandedNodes - For nodes that need to be expanded this map indicates
90   /// which operands are the expanded version of the input.  This allows
91   /// us to avoid expanding the same node more than once.
92   DenseMap<SDValue, std::pair<SDValue, SDValue> > ExpandedNodes;
93
94   /// SplitNodes - For vector nodes that need to be split, this map indicates
95   /// which operands are the split version of the input.  This allows us
96   /// to avoid splitting the same node more than once.
97   std::map<SDValue, std::pair<SDValue, SDValue> > SplitNodes;
98   
99   /// ScalarizedNodes - For nodes that need to be converted from vector types to
100   /// scalar types, this contains the mapping of ones we have already
101   /// processed to the result.
102   std::map<SDValue, SDValue> ScalarizedNodes;
103   
104   /// WidenNodes - For nodes that need to be widened from one vector type to
105   /// another, this contains the mapping of those that we have already widen.
106   /// This allows us to avoid widening more than once.
107   std::map<SDValue, SDValue> WidenNodes;
108
109   void AddLegalizedOperand(SDValue From, SDValue To) {
110     LegalizedNodes.insert(std::make_pair(From, To));
111     // If someone requests legalization of the new node, return itself.
112     if (From != To)
113       LegalizedNodes.insert(std::make_pair(To, To));
114   }
115   void AddPromotedOperand(SDValue From, SDValue To) {
116     bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
117     assert(isNew && "Got into the map somehow?");
118     isNew = isNew;
119     // If someone requests legalization of the new node, return itself.
120     LegalizedNodes.insert(std::make_pair(To, To));
121   }
122   void AddWidenedOperand(SDValue From, SDValue To) {
123     bool isNew = WidenNodes.insert(std::make_pair(From, To)).second;
124     assert(isNew && "Got into the map somehow?");
125     isNew = isNew;
126     // If someone requests legalization of the new node, return itself.
127     LegalizedNodes.insert(std::make_pair(To, To));
128   }
129
130 public:
131   explicit SelectionDAGLegalize(SelectionDAG &DAG, bool TypesNeedLegalizing);
132
133   /// getTypeAction - Return how we should legalize values of this type, either
134   /// it is already legal or we need to expand it into multiple registers of
135   /// smaller integer type, or we need to promote it to a larger type.
136   LegalizeAction getTypeAction(MVT VT) const {
137     return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
138   }
139
140   /// isTypeLegal - Return true if this type is legal on this target.
141   ///
142   bool isTypeLegal(MVT VT) const {
143     return getTypeAction(VT) == Legal;
144   }
145
146   void LegalizeDAG();
147
148 private:
149   /// HandleOp - Legalize, Promote, or Expand the specified operand as
150   /// appropriate for its type.
151   void HandleOp(SDValue Op);
152     
153   /// LegalizeOp - We know that the specified value has a legal type.
154   /// Recursively ensure that the operands have legal types, then return the
155   /// result.
156   SDValue LegalizeOp(SDValue O);
157   
158   /// UnrollVectorOp - We know that the given vector has a legal type, however
159   /// the operation it performs is not legal and is an operation that we have
160   /// no way of lowering.  "Unroll" the vector, splitting out the scalars and
161   /// operating on each element individually.
162   SDValue UnrollVectorOp(SDValue O);
163   
164   /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
165   /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
166   /// is necessary to spill the vector being inserted into to memory, perform
167   /// the insert there, and then read the result back.
168   SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
169                                            SDValue Idx);
170
171   /// PromoteOp - Given an operation that produces a value in an invalid type,
172   /// promote it to compute the value into a larger type.  The produced value
173   /// will have the correct bits for the low portion of the register, but no
174   /// guarantee is made about the top bits: it may be zero, sign-extended, or
175   /// garbage.
176   SDValue PromoteOp(SDValue O);
177
178   /// ExpandOp - Expand the specified SDValue into its two component pieces
179   /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this,
180   /// the LegalizedNodes map is filled in for any results that are not expanded,
181   /// the ExpandedNodes map is filled in for any results that are expanded, and
182   /// the Lo/Hi values are returned.   This applies to integer types and Vector
183   /// types.
184   void ExpandOp(SDValue O, SDValue &Lo, SDValue &Hi);
185
186   /// WidenVectorOp - Widen a vector operation to a wider type given by WidenVT 
187   /// (e.g., v3i32 to v4i32).  The produced value will have the correct value
188   /// for the existing elements but no guarantee is made about the new elements
189   /// at the end of the vector: it may be zero, ones, or garbage. This is useful
190   /// when we have an instruction operating on an illegal vector type and we
191   /// want to widen it to do the computation on a legal wider vector type.
192   SDValue WidenVectorOp(SDValue Op, MVT WidenVT);
193
194   /// SplitVectorOp - Given an operand of vector type, break it down into
195   /// two smaller values.
196   void SplitVectorOp(SDValue O, SDValue &Lo, SDValue &Hi);
197   
198   /// ScalarizeVectorOp - Given an operand of single-element vector type
199   /// (e.g. v1f32), convert it into the equivalent operation that returns a
200   /// scalar (e.g. f32) value.
201   SDValue ScalarizeVectorOp(SDValue O);
202   
203   /// Useful 16 element vector type that is used to pass operands for widening.
204   typedef SmallVector<SDValue, 16> SDValueVector;  
205   
206   /// LoadWidenVectorOp - Load a vector for a wider type. Returns true if
207   /// the LdChain contains a single load and false if it contains a token
208   /// factor for multiple loads. It takes
209   ///   Result:  location to return the result
210   ///   LdChain: location to return the load chain
211   ///   Op:      load operation to widen
212   ///   NVT:     widen vector result type we want for the load
213   bool LoadWidenVectorOp(SDValue& Result, SDValue& LdChain, 
214                          SDValue Op, MVT NVT);
215                         
216   /// Helper genWidenVectorLoads - Helper function to generate a set of
217   /// loads to load a vector with a resulting wider type. It takes
218   ///   LdChain: list of chains for the load we have generated
219   ///   Chain:   incoming chain for the ld vector
220   ///   BasePtr: base pointer to load from
221   ///   SV:      memory disambiguation source value
222   ///   SVOffset:  memory disambiugation offset
223   ///   Alignment: alignment of the memory
224   ///   isVolatile: volatile load
225   ///   LdWidth:    width of memory that we want to load 
226   ///   ResType:    the wider result result type for the resulting loaded vector
227   SDValue genWidenVectorLoads(SDValueVector& LdChain, SDValue Chain,
228                                 SDValue BasePtr, const Value *SV,
229                                 int SVOffset, unsigned Alignment,
230                                 bool isVolatile, unsigned LdWidth,
231                                 MVT ResType);
232   
233   /// StoreWidenVectorOp - Stores a widen vector into non widen memory
234   /// location. It takes
235   ///     ST:      store node that we want to replace
236   ///     Chain:   incoming store chain
237   ///     BasePtr: base address of where we want to store into
238   SDValue StoreWidenVectorOp(StoreSDNode *ST, SDValue Chain, 
239                                SDValue BasePtr);
240   
241   /// Helper genWidenVectorStores - Helper function to generate a set of
242   /// stores to store a widen vector into non widen memory
243   // It takes
244   //   StChain: list of chains for the stores we have generated
245   //   Chain:   incoming chain for the ld vector
246   //   BasePtr: base pointer to load from
247   //   SV:      memory disambiguation source value
248   //   SVOffset:   memory disambiugation offset
249   //   Alignment:  alignment of the memory
250   //   isVolatile: volatile lod
251   //   ValOp:   value to store  
252   //   StWidth: width of memory that we want to store 
253   void genWidenVectorStores(SDValueVector& StChain, SDValue Chain,
254                             SDValue BasePtr, const Value *SV,
255                             int SVOffset, unsigned Alignment,
256                             bool isVolatile, SDValue ValOp,
257                             unsigned StWidth);
258  
259   /// isShuffleLegal - Return non-null if a vector shuffle is legal with the
260   /// specified mask and type.  Targets can specify exactly which masks they
261   /// support and the code generator is tasked with not creating illegal masks.
262   ///
263   /// Note that this will also return true for shuffles that are promoted to a
264   /// different type.
265   ///
266   /// If this is a legal shuffle, this method returns the (possibly promoted)
267   /// build_vector Mask.  If it's not a legal shuffle, it returns null.
268   SDNode *isShuffleLegal(MVT VT, SDValue Mask) const;
269   
270   bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
271                                     SmallPtrSet<SDNode*, 32> &NodesLeadingTo);
272
273   void LegalizeSetCCOperands(SDValue &LHS, SDValue &RHS, SDValue &CC);
274   void LegalizeSetCCCondCode(MVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC);
275   void LegalizeSetCC(MVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC) {
276     LegalizeSetCCOperands(LHS, RHS, CC);
277     LegalizeSetCCCondCode(VT, LHS, RHS, CC);
278   }
279     
280   SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned,
281                           SDValue &Hi);
282   SDValue ExpandIntToFP(bool isSigned, MVT DestTy, SDValue Source);
283
284   SDValue EmitStackConvert(SDValue SrcOp, MVT SlotVT, MVT DestVT);
285   SDValue ExpandBUILD_VECTOR(SDNode *Node);
286   SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
287   SDValue LegalizeINT_TO_FP(SDValue Result, bool isSigned, MVT DestTy, SDValue Op);
288   SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, MVT DestVT);
289   SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, MVT DestVT, bool isSigned);
290   SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, MVT DestVT, bool isSigned);
291
292   SDValue ExpandBSWAP(SDValue Op);
293   SDValue ExpandBitCount(unsigned Opc, SDValue Op);
294   bool ExpandShift(unsigned Opc, SDValue Op, SDValue Amt,
295                    SDValue &Lo, SDValue &Hi);
296   void ExpandShiftParts(unsigned NodeOp, SDValue Op, SDValue Amt,
297                         SDValue &Lo, SDValue &Hi);
298
299   SDValue ExpandEXTRACT_SUBVECTOR(SDValue Op);
300   SDValue ExpandEXTRACT_VECTOR_ELT(SDValue Op);
301
302   // Returns the legalized (truncated or extended) shift amount.
303   SDValue LegalizeShiftAmount(SDValue ShiftAmt);
304 };
305 }
306
307 /// isVectorShuffleLegal - Return true if a vector shuffle is legal with the
308 /// specified mask and type.  Targets can specify exactly which masks they
309 /// support and the code generator is tasked with not creating illegal masks.
310 ///
311 /// Note that this will also return true for shuffles that are promoted to a
312 /// different type.
313 SDNode *SelectionDAGLegalize::isShuffleLegal(MVT VT, SDValue Mask) const {
314   switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, VT)) {
315   default: return 0;
316   case TargetLowering::Legal:
317   case TargetLowering::Custom:
318     break;
319   case TargetLowering::Promote: {
320     // If this is promoted to a different type, convert the shuffle mask and
321     // ask if it is legal in the promoted type!
322     MVT NVT = TLI.getTypeToPromoteTo(ISD::VECTOR_SHUFFLE, VT);
323     MVT EltVT = NVT.getVectorElementType();
324
325     // If we changed # elements, change the shuffle mask.
326     unsigned NumEltsGrowth =
327       NVT.getVectorNumElements() / VT.getVectorNumElements();
328     assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
329     if (NumEltsGrowth > 1) {
330       // Renumber the elements.
331       SmallVector<SDValue, 8> Ops;
332       for (unsigned i = 0, e = Mask.getNumOperands(); i != e; ++i) {
333         SDValue InOp = Mask.getOperand(i);
334         for (unsigned j = 0; j != NumEltsGrowth; ++j) {
335           if (InOp.getOpcode() == ISD::UNDEF)
336             Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
337           else {
338             unsigned InEltNo = cast<ConstantSDNode>(InOp)->getZExtValue();
339             Ops.push_back(DAG.getConstant(InEltNo*NumEltsGrowth+j, EltVT));
340           }
341         }
342       }
343       Mask = DAG.getNode(ISD::BUILD_VECTOR, NVT, &Ops[0], Ops.size());
344     }
345     VT = NVT;
346     break;
347   }
348   }
349   return TLI.isShuffleMaskLegal(Mask, VT) ? Mask.getNode() : 0;
350 }
351
352 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag, bool types)
353   : TLI(dag.getTargetLoweringInfo()), DAG(dag), TypesNeedLegalizing(types),
354     ValueTypeActions(TLI.getValueTypeActions()) {
355   assert(MVT::LAST_VALUETYPE <= 32 &&
356          "Too many value types for ValueTypeActions to hold!");
357 }
358
359 void SelectionDAGLegalize::LegalizeDAG() {
360   LastCALLSEQ_END = DAG.getEntryNode();
361   IsLegalizingCall = false;
362   
363   // The legalize process is inherently a bottom-up recursive process (users
364   // legalize their uses before themselves).  Given infinite stack space, we
365   // could just start legalizing on the root and traverse the whole graph.  In
366   // practice however, this causes us to run out of stack space on large basic
367   // blocks.  To avoid this problem, compute an ordering of the nodes where each
368   // node is only legalized after all of its operands are legalized.
369   DAG.AssignTopologicalOrder();
370   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
371        E = prior(DAG.allnodes_end()); I != next(E); ++I)
372     HandleOp(SDValue(I, 0));
373
374   // Finally, it's possible the root changed.  Get the new root.
375   SDValue OldRoot = DAG.getRoot();
376   assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
377   DAG.setRoot(LegalizedNodes[OldRoot]);
378
379   ExpandedNodes.clear();
380   LegalizedNodes.clear();
381   PromotedNodes.clear();
382   SplitNodes.clear();
383   ScalarizedNodes.clear();
384   WidenNodes.clear();
385
386   // Remove dead nodes now.
387   DAG.RemoveDeadNodes();
388 }
389
390
391 /// FindCallEndFromCallStart - Given a chained node that is part of a call
392 /// sequence, find the CALLSEQ_END node that terminates the call sequence.
393 static SDNode *FindCallEndFromCallStart(SDNode *Node) {
394   if (Node->getOpcode() == ISD::CALLSEQ_END)
395     return Node;
396   if (Node->use_empty())
397     return 0;   // No CallSeqEnd
398   
399   // The chain is usually at the end.
400   SDValue TheChain(Node, Node->getNumValues()-1);
401   if (TheChain.getValueType() != MVT::Other) {
402     // Sometimes it's at the beginning.
403     TheChain = SDValue(Node, 0);
404     if (TheChain.getValueType() != MVT::Other) {
405       // Otherwise, hunt for it.
406       for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
407         if (Node->getValueType(i) == MVT::Other) {
408           TheChain = SDValue(Node, i);
409           break;
410         }
411           
412       // Otherwise, we walked into a node without a chain.  
413       if (TheChain.getValueType() != MVT::Other)
414         return 0;
415     }
416   }
417   
418   for (SDNode::use_iterator UI = Node->use_begin(),
419        E = Node->use_end(); UI != E; ++UI) {
420     
421     // Make sure to only follow users of our token chain.
422     SDNode *User = *UI;
423     for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
424       if (User->getOperand(i) == TheChain)
425         if (SDNode *Result = FindCallEndFromCallStart(User))
426           return Result;
427   }
428   return 0;
429 }
430
431 /// FindCallStartFromCallEnd - Given a chained node that is part of a call 
432 /// sequence, find the CALLSEQ_START node that initiates the call sequence.
433 static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
434   assert(Node && "Didn't find callseq_start for a call??");
435   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
436   
437   assert(Node->getOperand(0).getValueType() == MVT::Other &&
438          "Node doesn't have a token chain argument!");
439   return FindCallStartFromCallEnd(Node->getOperand(0).getNode());
440 }
441
442 /// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
443 /// see if any uses can reach Dest.  If no dest operands can get to dest, 
444 /// legalize them, legalize ourself, and return false, otherwise, return true.
445 ///
446 /// Keep track of the nodes we fine that actually do lead to Dest in
447 /// NodesLeadingTo.  This avoids retraversing them exponential number of times.
448 ///
449 bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
450                                      SmallPtrSet<SDNode*, 32> &NodesLeadingTo) {
451   if (N == Dest) return true;  // N certainly leads to Dest :)
452   
453   // If we've already processed this node and it does lead to Dest, there is no
454   // need to reprocess it.
455   if (NodesLeadingTo.count(N)) return true;
456   
457   // If the first result of this node has been already legalized, then it cannot
458   // reach N.
459   switch (getTypeAction(N->getValueType(0))) {
460   case Legal: 
461     if (LegalizedNodes.count(SDValue(N, 0))) return false;
462     break;
463   case Promote:
464     if (PromotedNodes.count(SDValue(N, 0))) return false;
465     break;
466   case Expand:
467     if (ExpandedNodes.count(SDValue(N, 0))) return false;
468     break;
469   }
470   
471   // Okay, this node has not already been legalized.  Check and legalize all
472   // operands.  If none lead to Dest, then we can legalize this node.
473   bool OperandsLeadToDest = false;
474   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
475     OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
476       LegalizeAllNodesNotLeadingTo(N->getOperand(i).getNode(), Dest, NodesLeadingTo);
477
478   if (OperandsLeadToDest) {
479     NodesLeadingTo.insert(N);
480     return true;
481   }
482
483   // Okay, this node looks safe, legalize it and return false.
484   HandleOp(SDValue(N, 0));
485   return false;
486 }
487
488 /// HandleOp - Legalize, Promote, Widen, or Expand the specified operand as
489 /// appropriate for its type.
490 void SelectionDAGLegalize::HandleOp(SDValue Op) {
491   MVT VT = Op.getValueType();
492   // If the type legalizer was run then we should never see any illegal result
493   // types here except for target constants (the type legalizer does not touch
494   // those).
495   assert((TypesNeedLegalizing || getTypeAction(VT) == Legal ||
496           Op.getOpcode() == ISD::TargetConstant) &&
497          "Illegal type introduced after type legalization?");
498   switch (getTypeAction(VT)) {
499   default: assert(0 && "Bad type action!");
500   case Legal:   (void)LegalizeOp(Op); break;
501   case Promote:
502     if (!VT.isVector()) {
503       (void)PromoteOp(Op);
504       break;
505     }
506     else  {
507       // See if we can widen otherwise use Expand to either scalarize or split
508       MVT WidenVT = TLI.getWidenVectorType(VT);
509       if (WidenVT != MVT::Other) {
510         (void) WidenVectorOp(Op, WidenVT);
511         break;
512       }
513       // else fall thru to expand since we can't widen the vector
514     }
515   case Expand:
516     if (!VT.isVector()) {
517       // If this is an illegal scalar, expand it into its two component
518       // pieces.
519       SDValue X, Y;
520       if (Op.getOpcode() == ISD::TargetConstant)
521         break;  // Allow illegal target nodes.
522       ExpandOp(Op, X, Y);
523     } else if (VT.getVectorNumElements() == 1) {
524       // If this is an illegal single element vector, convert it to a
525       // scalar operation.
526       (void)ScalarizeVectorOp(Op);
527     } else {
528       // This is an illegal multiple element vector.
529       // Split it in half and legalize both parts.
530       SDValue X, Y;
531       SplitVectorOp(Op, X, Y);
532     }
533     break;
534   }
535 }
536
537 /// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
538 /// a load from the constant pool.
539 static SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
540                                   SelectionDAG &DAG, TargetLowering &TLI) {
541   bool Extend = false;
542
543   // If a FP immediate is precise when represented as a float and if the
544   // target can do an extending load from float to double, we put it into
545   // the constant pool as a float, even if it's is statically typed as a
546   // double.  This shrinks FP constants and canonicalizes them for targets where
547   // an FP extending load is the same cost as a normal load (such as on the x87
548   // fp stack or PPC FP unit).
549   MVT VT = CFP->getValueType(0);
550   ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
551   if (!UseCP) {
552     if (VT!=MVT::f64 && VT!=MVT::f32)
553       assert(0 && "Invalid type expansion");
554     return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
555                            (VT == MVT::f64) ? MVT::i64 : MVT::i32);
556   }
557
558   MVT OrigVT = VT;
559   MVT SVT = VT;
560   while (SVT != MVT::f32) {
561     SVT = (MVT::SimpleValueType)(SVT.getSimpleVT() - 1);
562     if (CFP->isValueValidForType(SVT, CFP->getValueAPF()) &&
563         // Only do this if the target has a native EXTLOAD instruction from
564         // smaller type.
565         TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
566         TLI.ShouldShrinkFPConstant(OrigVT)) {
567       const Type *SType = SVT.getTypeForMVT();
568       LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
569       VT = SVT;
570       Extend = true;
571     }
572   }
573
574   SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
575   unsigned Alignment = 1 << cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
576   if (Extend)
577     return DAG.getExtLoad(ISD::EXTLOAD, OrigVT, DAG.getEntryNode(),
578                           CPIdx, PseudoSourceValue::getConstantPool(),
579                           0, VT, false, Alignment);
580   return DAG.getLoad(OrigVT, DAG.getEntryNode(), CPIdx,
581                      PseudoSourceValue::getConstantPool(), 0, false, Alignment);
582 }
583
584
585 /// ExpandFCOPYSIGNToBitwiseOps - Expands fcopysign to a series of bitwise
586 /// operations.
587 static
588 SDValue ExpandFCOPYSIGNToBitwiseOps(SDNode *Node, MVT NVT,
589                                     SelectionDAG &DAG, TargetLowering &TLI) {
590   MVT VT = Node->getValueType(0);
591   MVT SrcVT = Node->getOperand(1).getValueType();
592   assert((SrcVT == MVT::f32 || SrcVT == MVT::f64) &&
593          "fcopysign expansion only supported for f32 and f64");
594   MVT SrcNVT = (SrcVT == MVT::f64) ? MVT::i64 : MVT::i32;
595
596   // First get the sign bit of second operand.
597   SDValue Mask1 = (SrcVT == MVT::f64)
598     ? DAG.getConstantFP(BitsToDouble(1ULL << 63), SrcVT)
599     : DAG.getConstantFP(BitsToFloat(1U << 31), SrcVT);
600   Mask1 = DAG.getNode(ISD::BIT_CONVERT, SrcNVT, Mask1);
601   SDValue SignBit= DAG.getNode(ISD::BIT_CONVERT, SrcNVT, Node->getOperand(1));
602   SignBit = DAG.getNode(ISD::AND, SrcNVT, SignBit, Mask1);
603   // Shift right or sign-extend it if the two operands have different types.
604   int SizeDiff = SrcNVT.getSizeInBits() - NVT.getSizeInBits();
605   if (SizeDiff > 0) {
606     SignBit = DAG.getNode(ISD::SRL, SrcNVT, SignBit,
607                           DAG.getConstant(SizeDiff, TLI.getShiftAmountTy()));
608     SignBit = DAG.getNode(ISD::TRUNCATE, NVT, SignBit);
609   } else if (SizeDiff < 0) {
610     SignBit = DAG.getNode(ISD::ZERO_EXTEND, NVT, SignBit);
611     SignBit = DAG.getNode(ISD::SHL, NVT, SignBit,
612                           DAG.getConstant(-SizeDiff, TLI.getShiftAmountTy()));
613   }
614
615   // Clear the sign bit of first operand.
616   SDValue Mask2 = (VT == MVT::f64)
617     ? DAG.getConstantFP(BitsToDouble(~(1ULL << 63)), VT)
618     : DAG.getConstantFP(BitsToFloat(~(1U << 31)), VT);
619   Mask2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask2);
620   SDValue Result = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
621   Result = DAG.getNode(ISD::AND, NVT, Result, Mask2);
622
623   // Or the value with the sign bit.
624   Result = DAG.getNode(ISD::OR, NVT, Result, SignBit);
625   return Result;
626 }
627
628 /// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
629 static
630 SDValue ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
631                              TargetLowering &TLI) {
632   SDValue Chain = ST->getChain();
633   SDValue Ptr = ST->getBasePtr();
634   SDValue Val = ST->getValue();
635   MVT VT = Val.getValueType();
636   int Alignment = ST->getAlignment();
637   int SVOffset = ST->getSrcValueOffset();
638   if (ST->getMemoryVT().isFloatingPoint() ||
639       ST->getMemoryVT().isVector()) {
640     MVT intVT = MVT::getIntegerVT(VT.getSizeInBits());
641     if (TLI.isTypeLegal(intVT)) {
642       // Expand to a bitconvert of the value to the integer type of the
643       // same size, then a (misaligned) int store.
644       // FIXME: Does not handle truncating floating point stores!
645       SDValue Result = DAG.getNode(ISD::BIT_CONVERT, intVT, Val);
646       return DAG.getStore(Chain, Result, Ptr, ST->getSrcValue(),
647                           SVOffset, ST->isVolatile(), Alignment);
648     } else {
649       // Do a (aligned) store to a stack slot, then copy from the stack slot
650       // to the final destination using (unaligned) integer loads and stores.
651       MVT StoredVT = ST->getMemoryVT();
652       MVT RegVT =
653         TLI.getRegisterType(MVT::getIntegerVT(StoredVT.getSizeInBits()));
654       unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
655       unsigned RegBytes = RegVT.getSizeInBits() / 8;
656       unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
657
658       // Make sure the stack slot is also aligned for the register type.
659       SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
660
661       // Perform the original store, only redirected to the stack slot.
662       SDValue Store = DAG.getTruncStore(Chain, Val, StackPtr, NULL, 0,StoredVT);
663       SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
664       SmallVector<SDValue, 8> Stores;
665       unsigned Offset = 0;
666
667       // Do all but one copies using the full register width.
668       for (unsigned i = 1; i < NumRegs; i++) {
669         // Load one integer register's worth from the stack slot.
670         SDValue Load = DAG.getLoad(RegVT, Store, StackPtr, NULL, 0);
671         // Store it to the final location.  Remember the store.
672         Stores.push_back(DAG.getStore(Load.getValue(1), Load, Ptr,
673                                       ST->getSrcValue(), SVOffset + Offset,
674                                       ST->isVolatile(),
675                                       MinAlign(ST->getAlignment(), Offset)));
676         // Increment the pointers.
677         Offset += RegBytes;
678         StackPtr = DAG.getNode(ISD::ADD, StackPtr.getValueType(), StackPtr,
679                                Increment);
680         Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr, Increment);
681       }
682
683       // The last store may be partial.  Do a truncating store.  On big-endian
684       // machines this requires an extending load from the stack slot to ensure
685       // that the bits are in the right place.
686       MVT MemVT = MVT::getIntegerVT(8 * (StoredBytes - Offset));
687
688       // Load from the stack slot.
689       SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, RegVT, Store, StackPtr,
690                                     NULL, 0, MemVT);
691
692       Stores.push_back(DAG.getTruncStore(Load.getValue(1), Load, Ptr,
693                                          ST->getSrcValue(), SVOffset + Offset,
694                                          MemVT, ST->isVolatile(),
695                                          MinAlign(ST->getAlignment(), Offset)));
696       // The order of the stores doesn't matter - say it with a TokenFactor.
697       return DAG.getNode(ISD::TokenFactor, MVT::Other, &Stores[0],
698                          Stores.size());
699     }
700   }
701   assert(ST->getMemoryVT().isInteger() &&
702          !ST->getMemoryVT().isVector() &&
703          "Unaligned store of unknown type.");
704   // Get the half-size VT
705   MVT NewStoredVT =
706     (MVT::SimpleValueType)(ST->getMemoryVT().getSimpleVT() - 1);
707   int NumBits = NewStoredVT.getSizeInBits();
708   int IncrementSize = NumBits / 8;
709
710   // Divide the stored value in two parts.
711   SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
712   SDValue Lo = Val;
713   SDValue Hi = DAG.getNode(ISD::SRL, VT, Val, ShiftAmount);
714
715   // Store the two parts
716   SDValue Store1, Store2;
717   Store1 = DAG.getTruncStore(Chain, TLI.isLittleEndian()?Lo:Hi, Ptr,
718                              ST->getSrcValue(), SVOffset, NewStoredVT,
719                              ST->isVolatile(), Alignment);
720   Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
721                     DAG.getConstant(IncrementSize, TLI.getPointerTy()));
722   Alignment = MinAlign(Alignment, IncrementSize);
723   Store2 = DAG.getTruncStore(Chain, TLI.isLittleEndian()?Hi:Lo, Ptr,
724                              ST->getSrcValue(), SVOffset + IncrementSize,
725                              NewStoredVT, ST->isVolatile(), Alignment);
726
727   return DAG.getNode(ISD::TokenFactor, MVT::Other, Store1, Store2);
728 }
729
730 /// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
731 static
732 SDValue ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
733                             TargetLowering &TLI) {
734   int SVOffset = LD->getSrcValueOffset();
735   SDValue Chain = LD->getChain();
736   SDValue Ptr = LD->getBasePtr();
737   MVT VT = LD->getValueType(0);
738   MVT LoadedVT = LD->getMemoryVT();
739   if (VT.isFloatingPoint() || VT.isVector()) {
740     MVT intVT = MVT::getIntegerVT(LoadedVT.getSizeInBits());
741     if (TLI.isTypeLegal(intVT)) {
742       // Expand to a (misaligned) integer load of the same size,
743       // then bitconvert to floating point or vector.
744       SDValue newLoad = DAG.getLoad(intVT, Chain, Ptr, LD->getSrcValue(),
745                                     SVOffset, LD->isVolatile(),
746                                     LD->getAlignment());
747       SDValue Result = DAG.getNode(ISD::BIT_CONVERT, LoadedVT, newLoad);
748       if (VT.isFloatingPoint() && LoadedVT != VT)
749         Result = DAG.getNode(ISD::FP_EXTEND, VT, Result);
750
751       SDValue Ops[] = { Result, Chain };
752       return DAG.getMergeValues(Ops, 2);
753     } else {
754       // Copy the value to a (aligned) stack slot using (unaligned) integer
755       // loads and stores, then do a (aligned) load from the stack slot.
756       MVT RegVT = TLI.getRegisterType(intVT);
757       unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
758       unsigned RegBytes = RegVT.getSizeInBits() / 8;
759       unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
760
761       // Make sure the stack slot is also aligned for the register type.
762       SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
763
764       SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
765       SmallVector<SDValue, 8> Stores;
766       SDValue StackPtr = StackBase;
767       unsigned Offset = 0;
768
769       // Do all but one copies using the full register width.
770       for (unsigned i = 1; i < NumRegs; i++) {
771         // Load one integer register's worth from the original location.
772         SDValue Load = DAG.getLoad(RegVT, Chain, Ptr, LD->getSrcValue(),
773                                    SVOffset + Offset, LD->isVolatile(),
774                                    MinAlign(LD->getAlignment(), Offset));
775         // Follow the load with a store to the stack slot.  Remember the store.
776         Stores.push_back(DAG.getStore(Load.getValue(1), Load, StackPtr,
777                                       NULL, 0));
778         // Increment the pointers.
779         Offset += RegBytes;
780         Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr, Increment);
781         StackPtr = DAG.getNode(ISD::ADD, StackPtr.getValueType(), StackPtr,
782                                Increment);
783       }
784
785       // The last copy may be partial.  Do an extending load.
786       MVT MemVT = MVT::getIntegerVT(8 * (LoadedBytes - Offset));
787       SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, RegVT, Chain, Ptr,
788                                     LD->getSrcValue(), SVOffset + Offset,
789                                     MemVT, LD->isVolatile(),
790                                     MinAlign(LD->getAlignment(), Offset));
791       // Follow the load with a store to the stack slot.  Remember the store.
792       // On big-endian machines this requires a truncating store to ensure
793       // that the bits end up in the right place.
794       Stores.push_back(DAG.getTruncStore(Load.getValue(1), Load, StackPtr,
795                                          NULL, 0, MemVT));
796
797       // The order of the stores doesn't matter - say it with a TokenFactor.
798       SDValue TF = DAG.getNode(ISD::TokenFactor, MVT::Other, &Stores[0],
799                                Stores.size());
800
801       // Finally, perform the original load only redirected to the stack slot.
802       Load = DAG.getExtLoad(LD->getExtensionType(), VT, TF, StackBase,
803                             NULL, 0, LoadedVT);
804
805       // Callers expect a MERGE_VALUES node.
806       SDValue Ops[] = { Load, TF };
807       return DAG.getMergeValues(Ops, 2);
808     }
809   }
810   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
811          "Unaligned load of unsupported type.");
812
813   // Compute the new VT that is half the size of the old one.  This is an
814   // integer MVT.
815   unsigned NumBits = LoadedVT.getSizeInBits();
816   MVT NewLoadedVT;
817   NewLoadedVT = MVT::getIntegerVT(NumBits/2);
818   NumBits >>= 1;
819   
820   unsigned Alignment = LD->getAlignment();
821   unsigned IncrementSize = NumBits / 8;
822   ISD::LoadExtType HiExtType = LD->getExtensionType();
823
824   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
825   if (HiExtType == ISD::NON_EXTLOAD)
826     HiExtType = ISD::ZEXTLOAD;
827
828   // Load the value in two parts
829   SDValue Lo, Hi;
830   if (TLI.isLittleEndian()) {
831     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, VT, Chain, Ptr, LD->getSrcValue(),
832                         SVOffset, NewLoadedVT, LD->isVolatile(), Alignment);
833     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
834                       DAG.getConstant(IncrementSize, TLI.getPointerTy()));
835     Hi = DAG.getExtLoad(HiExtType, VT, Chain, Ptr, LD->getSrcValue(),
836                         SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
837                         MinAlign(Alignment, IncrementSize));
838   } else {
839     Hi = DAG.getExtLoad(HiExtType, VT, Chain, Ptr, LD->getSrcValue(), SVOffset,
840                         NewLoadedVT,LD->isVolatile(), Alignment);
841     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
842                       DAG.getConstant(IncrementSize, TLI.getPointerTy()));
843     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, VT, Chain, Ptr, LD->getSrcValue(),
844                         SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
845                         MinAlign(Alignment, IncrementSize));
846   }
847
848   // aggregate the two parts
849   SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
850   SDValue Result = DAG.getNode(ISD::SHL, VT, Hi, ShiftAmount);
851   Result = DAG.getNode(ISD::OR, VT, Result, Lo);
852
853   SDValue TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
854                              Hi.getValue(1));
855
856   SDValue Ops[] = { Result, TF };
857   return DAG.getMergeValues(Ops, 2);
858 }
859
860 /// UnrollVectorOp - We know that the given vector has a legal type, however
861 /// the operation it performs is not legal and is an operation that we have
862 /// no way of lowering.  "Unroll" the vector, splitting out the scalars and
863 /// operating on each element individually.
864 SDValue SelectionDAGLegalize::UnrollVectorOp(SDValue Op) {
865   MVT VT = Op.getValueType();
866   assert(isTypeLegal(VT) &&
867          "Caller should expand or promote operands that are not legal!");
868   assert(Op.getNode()->getNumValues() == 1 &&
869          "Can't unroll a vector with multiple results!");
870   unsigned NE = VT.getVectorNumElements();
871   MVT EltVT = VT.getVectorElementType();
872
873   SmallVector<SDValue, 8> Scalars;
874   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
875   for (unsigned i = 0; i != NE; ++i) {
876     for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
877       SDValue Operand = Op.getOperand(j);
878       MVT OperandVT = Operand.getValueType();
879       if (OperandVT.isVector()) {
880         // A vector operand; extract a single element.
881         MVT OperandEltVT = OperandVT.getVectorElementType();
882         Operands[j] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
883                                   OperandEltVT,
884                                   Operand,
885                                   DAG.getConstant(i, MVT::i32));
886       } else {
887         // A scalar operand; just use it as is.
888         Operands[j] = Operand;
889       }
890     }
891
892     switch (Op.getOpcode()) {
893     default:
894       Scalars.push_back(DAG.getNode(Op.getOpcode(), EltVT,
895                                     &Operands[0], Operands.size()));
896       break;
897     case ISD::SHL:
898     case ISD::SRA:
899     case ISD::SRL:
900       Scalars.push_back(DAG.getNode(Op.getOpcode(), EltVT, Operands[0],
901                                     LegalizeShiftAmount(Operands[1])));
902       break;
903     }
904   }
905
906   return DAG.getNode(ISD::BUILD_VECTOR, VT, &Scalars[0], Scalars.size());
907 }
908
909 /// GetFPLibCall - Return the right libcall for the given floating point type.
910 static RTLIB::Libcall GetFPLibCall(MVT VT,
911                                    RTLIB::Libcall Call_F32,
912                                    RTLIB::Libcall Call_F64,
913                                    RTLIB::Libcall Call_F80,
914                                    RTLIB::Libcall Call_PPCF128) {
915   return
916     VT == MVT::f32 ? Call_F32 :
917     VT == MVT::f64 ? Call_F64 :
918     VT == MVT::f80 ? Call_F80 :
919     VT == MVT::ppcf128 ? Call_PPCF128 :
920     RTLIB::UNKNOWN_LIBCALL;
921 }
922
923 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
924 /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
925 /// is necessary to spill the vector being inserted into to memory, perform
926 /// the insert there, and then read the result back.
927 SDValue SelectionDAGLegalize::
928 PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx) {
929   SDValue Tmp1 = Vec;
930   SDValue Tmp2 = Val;
931   SDValue Tmp3 = Idx;
932   
933   // If the target doesn't support this, we have to spill the input vector
934   // to a temporary stack slot, update the element, then reload it.  This is
935   // badness.  We could also load the value into a vector register (either
936   // with a "move to register" or "extload into register" instruction, then
937   // permute it into place, if the idx is a constant and if the idx is
938   // supported by the target.
939   MVT VT    = Tmp1.getValueType();
940   MVT EltVT = VT.getVectorElementType();
941   MVT IdxVT = Tmp3.getValueType();
942   MVT PtrVT = TLI.getPointerTy();
943   SDValue StackPtr = DAG.CreateStackTemporary(VT);
944
945   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
946
947   // Store the vector.
948   SDValue Ch = DAG.getStore(DAG.getEntryNode(), Tmp1, StackPtr,
949                             PseudoSourceValue::getFixedStack(SPFI), 0);
950
951   // Truncate or zero extend offset to target pointer type.
952   unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
953   Tmp3 = DAG.getNode(CastOpc, PtrVT, Tmp3);
954   // Add the offset to the index.
955   unsigned EltSize = EltVT.getSizeInBits()/8;
956   Tmp3 = DAG.getNode(ISD::MUL, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
957   SDValue StackPtr2 = DAG.getNode(ISD::ADD, IdxVT, Tmp3, StackPtr);
958   // Store the scalar value.
959   Ch = DAG.getTruncStore(Ch, Tmp2, StackPtr2,
960                          PseudoSourceValue::getFixedStack(SPFI), 0, EltVT);
961   // Load the updated vector.
962   return DAG.getLoad(VT, Ch, StackPtr,
963                      PseudoSourceValue::getFixedStack(SPFI), 0);
964 }
965
966 SDValue SelectionDAGLegalize::LegalizeShiftAmount(SDValue ShiftAmt) {
967   if (TLI.getShiftAmountTy().bitsLT(ShiftAmt.getValueType()))
968     return DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), ShiftAmt);
969
970   if (TLI.getShiftAmountTy().bitsGT(ShiftAmt.getValueType()))
971     return DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), ShiftAmt);
972
973   return ShiftAmt;
974 }
975
976
977 /// LegalizeOp - We know that the specified value has a legal type, and
978 /// that its operands are legal.  Now ensure that the operation itself
979 /// is legal, recursively ensuring that the operands' operations remain
980 /// legal.
981 SDValue SelectionDAGLegalize::LegalizeOp(SDValue Op) {
982   if (Op.getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
983     return Op;
984   
985   assert(isTypeLegal(Op.getValueType()) &&
986          "Caller should expand or promote operands that are not legal!");
987   SDNode *Node = Op.getNode();
988
989   // If this operation defines any values that cannot be represented in a
990   // register on this target, make sure to expand or promote them.
991   if (Node->getNumValues() > 1) {
992     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
993       if (getTypeAction(Node->getValueType(i)) != Legal) {
994         HandleOp(Op.getValue(i));
995         assert(LegalizedNodes.count(Op) &&
996                "Handling didn't add legal operands!");
997         return LegalizedNodes[Op];
998       }
999   }
1000
1001   // Note that LegalizeOp may be reentered even from single-use nodes, which
1002   // means that we always must cache transformed nodes.
1003   DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1004   if (I != LegalizedNodes.end()) return I->second;
1005
1006   SDValue Tmp1, Tmp2, Tmp3, Tmp4;
1007   SDValue Result = Op;
1008   bool isCustom = false;
1009   
1010   switch (Node->getOpcode()) {
1011   case ISD::FrameIndex:
1012   case ISD::EntryToken:
1013   case ISD::Register:
1014   case ISD::BasicBlock:
1015   case ISD::TargetFrameIndex:
1016   case ISD::TargetJumpTable:
1017   case ISD::TargetConstant:
1018   case ISD::TargetConstantFP:
1019   case ISD::TargetConstantPool:
1020   case ISD::TargetGlobalAddress:
1021   case ISD::TargetGlobalTLSAddress:
1022   case ISD::TargetExternalSymbol:
1023   case ISD::VALUETYPE:
1024   case ISD::SRCVALUE:
1025   case ISD::MEMOPERAND:
1026   case ISD::CONDCODE:
1027   case ISD::ARG_FLAGS:
1028     // Primitives must all be legal.
1029     assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
1030            "This must be legal!");
1031     break;
1032   default:
1033     if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
1034       // If this is a target node, legalize it by legalizing the operands then
1035       // passing it through.
1036       SmallVector<SDValue, 8> Ops;
1037       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1038         Ops.push_back(LegalizeOp(Node->getOperand(i)));
1039
1040       Result = DAG.UpdateNodeOperands(Result.getValue(0), &Ops[0], Ops.size());
1041
1042       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1043         AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
1044       return Result.getValue(Op.getResNo());
1045     }
1046     // Otherwise this is an unhandled builtin node.  splat.
1047 #ifndef NDEBUG
1048     cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
1049 #endif
1050     assert(0 && "Do not know how to legalize this operator!");
1051     abort();
1052   case ISD::GLOBAL_OFFSET_TABLE:
1053   case ISD::GlobalAddress:
1054   case ISD::GlobalTLSAddress:
1055   case ISD::ExternalSymbol:
1056   case ISD::ConstantPool:
1057   case ISD::JumpTable: // Nothing to do.
1058     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1059     default: assert(0 && "This action is not supported yet!");
1060     case TargetLowering::Custom:
1061       Tmp1 = TLI.LowerOperation(Op, DAG);
1062       if (Tmp1.getNode()) Result = Tmp1;
1063       // FALLTHROUGH if the target doesn't want to lower this op after all.
1064     case TargetLowering::Legal:
1065       break;
1066     }
1067     break;
1068   case ISD::FRAMEADDR:
1069   case ISD::RETURNADDR:
1070     // The only option for these nodes is to custom lower them.  If the target
1071     // does not custom lower them, then return zero.
1072     Tmp1 = TLI.LowerOperation(Op, DAG);
1073     if (Tmp1.getNode()) 
1074       Result = Tmp1;
1075     else
1076       Result = DAG.getConstant(0, TLI.getPointerTy());
1077     break;
1078   case ISD::FRAME_TO_ARGS_OFFSET: {
1079     MVT VT = Node->getValueType(0);
1080     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1081     default: assert(0 && "This action is not supported yet!");
1082     case TargetLowering::Custom:
1083       Result = TLI.LowerOperation(Op, DAG);
1084       if (Result.getNode()) break;
1085       // Fall Thru
1086     case TargetLowering::Legal:
1087       Result = DAG.getConstant(0, VT);
1088       break;
1089     }
1090     }
1091     break;
1092   case ISD::EXCEPTIONADDR: {
1093     Tmp1 = LegalizeOp(Node->getOperand(0));
1094     MVT VT = Node->getValueType(0);
1095     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1096     default: assert(0 && "This action is not supported yet!");
1097     case TargetLowering::Expand: {
1098         unsigned Reg = TLI.getExceptionAddressRegister();
1099         Result = DAG.getCopyFromReg(Tmp1, Reg, VT);
1100       }
1101       break;
1102     case TargetLowering::Custom:
1103       Result = TLI.LowerOperation(Op, DAG);
1104       if (Result.getNode()) break;
1105       // Fall Thru
1106     case TargetLowering::Legal: {
1107       SDValue Ops[] = { DAG.getConstant(0, VT), Tmp1 };
1108       Result = DAG.getMergeValues(Ops, 2);
1109       break;
1110     }
1111     }
1112     }
1113     if (Result.getNode()->getNumValues() == 1) break;
1114
1115     assert(Result.getNode()->getNumValues() == 2 &&
1116            "Cannot return more than two values!");
1117
1118     // Since we produced two values, make sure to remember that we
1119     // legalized both of them.
1120     Tmp1 = LegalizeOp(Result);
1121     Tmp2 = LegalizeOp(Result.getValue(1));
1122     AddLegalizedOperand(Op.getValue(0), Tmp1);
1123     AddLegalizedOperand(Op.getValue(1), Tmp2);
1124     return Op.getResNo() ? Tmp2 : Tmp1;
1125   case ISD::EHSELECTION: {
1126     Tmp1 = LegalizeOp(Node->getOperand(0));
1127     Tmp2 = LegalizeOp(Node->getOperand(1));
1128     MVT VT = Node->getValueType(0);
1129     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1130     default: assert(0 && "This action is not supported yet!");
1131     case TargetLowering::Expand: {
1132         unsigned Reg = TLI.getExceptionSelectorRegister();
1133         Result = DAG.getCopyFromReg(Tmp2, Reg, VT);
1134       }
1135       break;
1136     case TargetLowering::Custom:
1137       Result = TLI.LowerOperation(Op, DAG);
1138       if (Result.getNode()) break;
1139       // Fall Thru
1140     case TargetLowering::Legal: {
1141       SDValue Ops[] = { DAG.getConstant(0, VT), Tmp2 };
1142       Result = DAG.getMergeValues(Ops, 2);
1143       break;
1144     }
1145     }
1146     }
1147     if (Result.getNode()->getNumValues() == 1) break;
1148
1149     assert(Result.getNode()->getNumValues() == 2 &&
1150            "Cannot return more than two values!");
1151
1152     // Since we produced two values, make sure to remember that we
1153     // legalized both of them.
1154     Tmp1 = LegalizeOp(Result);
1155     Tmp2 = LegalizeOp(Result.getValue(1));
1156     AddLegalizedOperand(Op.getValue(0), Tmp1);
1157     AddLegalizedOperand(Op.getValue(1), Tmp2);
1158     return Op.getResNo() ? Tmp2 : Tmp1;
1159   case ISD::EH_RETURN: {
1160     MVT VT = Node->getValueType(0);
1161     // The only "good" option for this node is to custom lower it.
1162     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1163     default: assert(0 && "This action is not supported at all!");
1164     case TargetLowering::Custom:
1165       Result = TLI.LowerOperation(Op, DAG);
1166       if (Result.getNode()) break;
1167       // Fall Thru
1168     case TargetLowering::Legal:
1169       // Target does not know, how to lower this, lower to noop
1170       Result = LegalizeOp(Node->getOperand(0));
1171       break;
1172     }
1173     }
1174     break;
1175   case ISD::AssertSext:
1176   case ISD::AssertZext:
1177     Tmp1 = LegalizeOp(Node->getOperand(0));
1178     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1179     break;
1180   case ISD::MERGE_VALUES:
1181     // Legalize eliminates MERGE_VALUES nodes.
1182     Result = Node->getOperand(Op.getResNo());
1183     break;
1184   case ISD::CopyFromReg:
1185     Tmp1 = LegalizeOp(Node->getOperand(0));
1186     Result = Op.getValue(0);
1187     if (Node->getNumValues() == 2) {
1188       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1189     } else {
1190       assert(Node->getNumValues() == 3 && "Invalid copyfromreg!");
1191       if (Node->getNumOperands() == 3) {
1192         Tmp2 = LegalizeOp(Node->getOperand(2));
1193         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
1194       } else {
1195         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1196       }
1197       AddLegalizedOperand(Op.getValue(2), Result.getValue(2));
1198     }
1199     // Since CopyFromReg produces two values, make sure to remember that we
1200     // legalized both of them.
1201     AddLegalizedOperand(Op.getValue(0), Result);
1202     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1203     return Result.getValue(Op.getResNo());
1204   case ISD::UNDEF: {
1205     MVT VT = Op.getValueType();
1206     switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
1207     default: assert(0 && "This action is not supported yet!");
1208     case TargetLowering::Expand:
1209       if (VT.isInteger())
1210         Result = DAG.getConstant(0, VT);
1211       else if (VT.isFloatingPoint())
1212         Result = DAG.getConstantFP(APFloat(APInt(VT.getSizeInBits(), 0)),
1213                                    VT);
1214       else
1215         assert(0 && "Unknown value type!");
1216       break;
1217     case TargetLowering::Legal:
1218       break;
1219     }
1220     break;
1221   }
1222     
1223   case ISD::INTRINSIC_W_CHAIN:
1224   case ISD::INTRINSIC_WO_CHAIN:
1225   case ISD::INTRINSIC_VOID: {
1226     SmallVector<SDValue, 8> Ops;
1227     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1228       Ops.push_back(LegalizeOp(Node->getOperand(i)));
1229     Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1230     
1231     // Allow the target to custom lower its intrinsics if it wants to.
1232     if (TLI.getOperationAction(Node->getOpcode(), MVT::Other) == 
1233         TargetLowering::Custom) {
1234       Tmp3 = TLI.LowerOperation(Result, DAG);
1235       if (Tmp3.getNode()) Result = Tmp3;
1236     }
1237
1238     if (Result.getNode()->getNumValues() == 1) break;
1239
1240     // Must have return value and chain result.
1241     assert(Result.getNode()->getNumValues() == 2 &&
1242            "Cannot return more than two values!");
1243
1244     // Since loads produce two values, make sure to remember that we 
1245     // legalized both of them.
1246     AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1247     AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1248     return Result.getValue(Op.getResNo());
1249   }    
1250
1251   case ISD::DBG_STOPPOINT:
1252     assert(Node->getNumOperands() == 1 && "Invalid DBG_STOPPOINT node!");
1253     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
1254     
1255     switch (TLI.getOperationAction(ISD::DBG_STOPPOINT, MVT::Other)) {
1256     case TargetLowering::Promote:
1257     default: assert(0 && "This action is not supported yet!");
1258     case TargetLowering::Expand: {
1259       MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1260       bool useDEBUG_LOC = TLI.isOperationLegal(ISD::DEBUG_LOC, MVT::Other);
1261       bool useLABEL = TLI.isOperationLegal(ISD::DBG_LABEL, MVT::Other);
1262       
1263       const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(Node);
1264       if (MMI && (useDEBUG_LOC || useLABEL)) {
1265         const CompileUnitDesc *CompileUnit = DSP->getCompileUnit();
1266         unsigned SrcFile = MMI->RecordSource(CompileUnit);
1267
1268         unsigned Line = DSP->getLine();
1269         unsigned Col = DSP->getColumn();
1270         
1271         if (useDEBUG_LOC) {
1272           SDValue Ops[] = { Tmp1, DAG.getConstant(Line, MVT::i32),
1273                               DAG.getConstant(Col, MVT::i32),
1274                               DAG.getConstant(SrcFile, MVT::i32) };
1275           Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, Ops, 4);
1276         } else {
1277           unsigned ID = MMI->RecordSourceLine(Line, Col, SrcFile);
1278           Result = DAG.getLabel(ISD::DBG_LABEL, Tmp1, ID);
1279         }
1280       } else {
1281         Result = Tmp1;  // chain
1282       }
1283       break;
1284     }
1285     case TargetLowering::Legal: {
1286       LegalizeAction Action = getTypeAction(Node->getOperand(1).getValueType());
1287       if (Action == Legal && Tmp1 == Node->getOperand(0))
1288         break;
1289
1290       SmallVector<SDValue, 8> Ops;
1291       Ops.push_back(Tmp1);
1292       if (Action == Legal) {
1293         Ops.push_back(Node->getOperand(1));  // line # must be legal.
1294         Ops.push_back(Node->getOperand(2));  // col # must be legal.
1295       } else {
1296         // Otherwise promote them.
1297         Ops.push_back(PromoteOp(Node->getOperand(1)));
1298         Ops.push_back(PromoteOp(Node->getOperand(2)));
1299       }
1300       Ops.push_back(Node->getOperand(3));  // filename must be legal.
1301       Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
1302       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1303       break;
1304     }
1305     }
1306     break;
1307
1308   case ISD::DECLARE:
1309     assert(Node->getNumOperands() == 3 && "Invalid DECLARE node!");
1310     switch (TLI.getOperationAction(ISD::DECLARE, MVT::Other)) {
1311     default: assert(0 && "This action is not supported yet!");
1312     case TargetLowering::Legal:
1313       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1314       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the address.
1315       Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the variable.
1316       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1317       break;
1318     case TargetLowering::Expand:
1319       Result = LegalizeOp(Node->getOperand(0));
1320       break;
1321     }
1322     break;    
1323     
1324   case ISD::DEBUG_LOC:
1325     assert(Node->getNumOperands() == 4 && "Invalid DEBUG_LOC node!");
1326     switch (TLI.getOperationAction(ISD::DEBUG_LOC, MVT::Other)) {
1327     default: assert(0 && "This action is not supported yet!");
1328     case TargetLowering::Legal: {
1329       LegalizeAction Action = getTypeAction(Node->getOperand(1).getValueType());
1330       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1331       if (Action == Legal && Tmp1 == Node->getOperand(0))
1332         break;
1333       if (Action == Legal) {
1334         Tmp2 = Node->getOperand(1);
1335         Tmp3 = Node->getOperand(2);
1336         Tmp4 = Node->getOperand(3);
1337       } else {
1338         Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the line #.
1339         Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the col #.
1340         Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize the source file id.
1341       }
1342       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
1343       break;
1344     }
1345     }
1346     break;    
1347
1348   case ISD::DBG_LABEL:
1349   case ISD::EH_LABEL:
1350     assert(Node->getNumOperands() == 1 && "Invalid LABEL node!");
1351     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1352     default: assert(0 && "This action is not supported yet!");
1353     case TargetLowering::Legal:
1354       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1355       Result = DAG.UpdateNodeOperands(Result, Tmp1);
1356       break;
1357     case TargetLowering::Expand:
1358       Result = LegalizeOp(Node->getOperand(0));
1359       break;
1360     }
1361     break;
1362
1363   case ISD::PREFETCH:
1364     assert(Node->getNumOperands() == 4 && "Invalid Prefetch node!");
1365     switch (TLI.getOperationAction(ISD::PREFETCH, MVT::Other)) {
1366     default: assert(0 && "This action is not supported yet!");
1367     case TargetLowering::Legal:
1368       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1369       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the address.
1370       Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the rw specifier.
1371       Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize locality specifier.
1372       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
1373       break;
1374     case TargetLowering::Expand:
1375       // It's a noop.
1376       Result = LegalizeOp(Node->getOperand(0));
1377       break;
1378     }
1379     break;
1380
1381   case ISD::MEMBARRIER: {
1382     assert(Node->getNumOperands() == 6 && "Invalid MemBarrier node!");
1383     switch (TLI.getOperationAction(ISD::MEMBARRIER, MVT::Other)) {
1384     default: assert(0 && "This action is not supported yet!");
1385     case TargetLowering::Legal: {
1386       SDValue Ops[6];
1387       Ops[0] = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1388       for (int x = 1; x < 6; ++x) {
1389         Ops[x] = Node->getOperand(x);
1390         if (!isTypeLegal(Ops[x].getValueType()))
1391           Ops[x] = PromoteOp(Ops[x]);
1392       }
1393       Result = DAG.UpdateNodeOperands(Result, &Ops[0], 6);
1394       break;
1395     }
1396     case TargetLowering::Expand:
1397       //There is no libgcc call for this op
1398       Result = Node->getOperand(0);  // Noop
1399     break;
1400     }
1401     break;
1402   }
1403
1404   case ISD::ATOMIC_CMP_SWAP_8:
1405   case ISD::ATOMIC_CMP_SWAP_16:
1406   case ISD::ATOMIC_CMP_SWAP_32:
1407   case ISD::ATOMIC_CMP_SWAP_64: {
1408     unsigned int num_operands = 4;
1409     assert(Node->getNumOperands() == num_operands && "Invalid Atomic node!");
1410     SDValue Ops[4];
1411     for (unsigned int x = 0; x < num_operands; ++x)
1412       Ops[x] = LegalizeOp(Node->getOperand(x));
1413     Result = DAG.UpdateNodeOperands(Result, &Ops[0], num_operands);
1414     
1415     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1416       default: assert(0 && "This action is not supported yet!");
1417       case TargetLowering::Custom:
1418         Result = TLI.LowerOperation(Result, DAG);
1419         break;
1420       case TargetLowering::Legal:
1421         break;
1422     }
1423     AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1424     AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1425     return Result.getValue(Op.getResNo());
1426   }
1427   case ISD::ATOMIC_LOAD_ADD_8:
1428   case ISD::ATOMIC_LOAD_SUB_8:
1429   case ISD::ATOMIC_LOAD_AND_8:
1430   case ISD::ATOMIC_LOAD_OR_8:
1431   case ISD::ATOMIC_LOAD_XOR_8:
1432   case ISD::ATOMIC_LOAD_NAND_8:
1433   case ISD::ATOMIC_LOAD_MIN_8:
1434   case ISD::ATOMIC_LOAD_MAX_8:
1435   case ISD::ATOMIC_LOAD_UMIN_8:
1436   case ISD::ATOMIC_LOAD_UMAX_8:
1437   case ISD::ATOMIC_SWAP_8: 
1438   case ISD::ATOMIC_LOAD_ADD_16:
1439   case ISD::ATOMIC_LOAD_SUB_16:
1440   case ISD::ATOMIC_LOAD_AND_16:
1441   case ISD::ATOMIC_LOAD_OR_16:
1442   case ISD::ATOMIC_LOAD_XOR_16:
1443   case ISD::ATOMIC_LOAD_NAND_16:
1444   case ISD::ATOMIC_LOAD_MIN_16:
1445   case ISD::ATOMIC_LOAD_MAX_16:
1446   case ISD::ATOMIC_LOAD_UMIN_16:
1447   case ISD::ATOMIC_LOAD_UMAX_16:
1448   case ISD::ATOMIC_SWAP_16:
1449   case ISD::ATOMIC_LOAD_ADD_32:
1450   case ISD::ATOMIC_LOAD_SUB_32:
1451   case ISD::ATOMIC_LOAD_AND_32:
1452   case ISD::ATOMIC_LOAD_OR_32:
1453   case ISD::ATOMIC_LOAD_XOR_32:
1454   case ISD::ATOMIC_LOAD_NAND_32:
1455   case ISD::ATOMIC_LOAD_MIN_32:
1456   case ISD::ATOMIC_LOAD_MAX_32:
1457   case ISD::ATOMIC_LOAD_UMIN_32:
1458   case ISD::ATOMIC_LOAD_UMAX_32:
1459   case ISD::ATOMIC_SWAP_32:
1460   case ISD::ATOMIC_LOAD_ADD_64:
1461   case ISD::ATOMIC_LOAD_SUB_64:
1462   case ISD::ATOMIC_LOAD_AND_64:
1463   case ISD::ATOMIC_LOAD_OR_64:
1464   case ISD::ATOMIC_LOAD_XOR_64:
1465   case ISD::ATOMIC_LOAD_NAND_64:
1466   case ISD::ATOMIC_LOAD_MIN_64:
1467   case ISD::ATOMIC_LOAD_MAX_64:
1468   case ISD::ATOMIC_LOAD_UMIN_64:
1469   case ISD::ATOMIC_LOAD_UMAX_64:
1470   case ISD::ATOMIC_SWAP_64: {
1471     unsigned int num_operands = 3;
1472     assert(Node->getNumOperands() == num_operands && "Invalid Atomic node!");
1473     SDValue Ops[3];
1474     for (unsigned int x = 0; x < num_operands; ++x)
1475       Ops[x] = LegalizeOp(Node->getOperand(x));
1476     Result = DAG.UpdateNodeOperands(Result, &Ops[0], num_operands);
1477
1478     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1479     default: assert(0 && "This action is not supported yet!");
1480     case TargetLowering::Custom:
1481       Result = TLI.LowerOperation(Result, DAG);
1482       break;
1483     case TargetLowering::Legal:
1484       break;
1485     }
1486     AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1487     AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1488     return Result.getValue(Op.getResNo());
1489   }
1490   case ISD::Constant: {
1491     ConstantSDNode *CN = cast<ConstantSDNode>(Node);
1492     unsigned opAction =
1493       TLI.getOperationAction(ISD::Constant, CN->getValueType(0));
1494
1495     // We know we don't need to expand constants here, constants only have one
1496     // value and we check that it is fine above.
1497
1498     if (opAction == TargetLowering::Custom) {
1499       Tmp1 = TLI.LowerOperation(Result, DAG);
1500       if (Tmp1.getNode())
1501         Result = Tmp1;
1502     }
1503     break;
1504   }
1505   case ISD::ConstantFP: {
1506     // Spill FP immediates to the constant pool if the target cannot directly
1507     // codegen them.  Targets often have some immediate values that can be
1508     // efficiently generated into an FP register without a load.  We explicitly
1509     // leave these constants as ConstantFP nodes for the target to deal with.
1510     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
1511
1512     switch (TLI.getOperationAction(ISD::ConstantFP, CFP->getValueType(0))) {
1513     default: assert(0 && "This action is not supported yet!");
1514     case TargetLowering::Legal:
1515       break;
1516     case TargetLowering::Custom:
1517       Tmp3 = TLI.LowerOperation(Result, DAG);
1518       if (Tmp3.getNode()) {
1519         Result = Tmp3;
1520         break;
1521       }
1522       // FALLTHROUGH
1523     case TargetLowering::Expand: {
1524       // Check to see if this FP immediate is already legal.
1525       bool isLegal = false;
1526       for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
1527              E = TLI.legal_fpimm_end(); I != E; ++I) {
1528         if (CFP->isExactlyValue(*I)) {
1529           isLegal = true;
1530           break;
1531         }
1532       }
1533       // If this is a legal constant, turn it into a TargetConstantFP node.
1534       if (isLegal)
1535         break;
1536       Result = ExpandConstantFP(CFP, true, DAG, TLI);
1537     }
1538     }
1539     break;
1540   }
1541   case ISD::TokenFactor:
1542     if (Node->getNumOperands() == 2) {
1543       Tmp1 = LegalizeOp(Node->getOperand(0));
1544       Tmp2 = LegalizeOp(Node->getOperand(1));
1545       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1546     } else if (Node->getNumOperands() == 3) {
1547       Tmp1 = LegalizeOp(Node->getOperand(0));
1548       Tmp2 = LegalizeOp(Node->getOperand(1));
1549       Tmp3 = LegalizeOp(Node->getOperand(2));
1550       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1551     } else {
1552       SmallVector<SDValue, 8> Ops;
1553       // Legalize the operands.
1554       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1555         Ops.push_back(LegalizeOp(Node->getOperand(i)));
1556       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1557     }
1558     break;
1559     
1560   case ISD::FORMAL_ARGUMENTS:
1561   case ISD::CALL:
1562     // The only option for this is to custom lower it.
1563     Tmp3 = TLI.LowerOperation(Result.getValue(0), DAG);
1564     assert(Tmp3.getNode() && "Target didn't custom lower this node!");
1565     // A call within a calling sequence must be legalized to something
1566     // other than the normal CALLSEQ_END.  Violating this gets Legalize
1567     // into an infinite loop.
1568     assert ((!IsLegalizingCall ||
1569              Node->getOpcode() != ISD::CALL ||
1570              Tmp3.getNode()->getOpcode() != ISD::CALLSEQ_END) &&
1571             "Nested CALLSEQ_START..CALLSEQ_END not supported.");
1572
1573     // The number of incoming and outgoing values should match; unless the final
1574     // outgoing value is a flag.
1575     assert((Tmp3.getNode()->getNumValues() == Result.getNode()->getNumValues() ||
1576             (Tmp3.getNode()->getNumValues() == Result.getNode()->getNumValues() + 1 &&
1577              Tmp3.getNode()->getValueType(Tmp3.getNode()->getNumValues() - 1) ==
1578                MVT::Flag)) &&
1579            "Lowering call/formal_arguments produced unexpected # results!");
1580     
1581     // Since CALL/FORMAL_ARGUMENTS nodes produce multiple values, make sure to
1582     // remember that we legalized all of them, so it doesn't get relegalized.
1583     for (unsigned i = 0, e = Tmp3.getNode()->getNumValues(); i != e; ++i) {
1584       if (Tmp3.getNode()->getValueType(i) == MVT::Flag)
1585         continue;
1586       Tmp1 = LegalizeOp(Tmp3.getValue(i));
1587       if (Op.getResNo() == i)
1588         Tmp2 = Tmp1;
1589       AddLegalizedOperand(SDValue(Node, i), Tmp1);
1590     }
1591     return Tmp2;
1592    case ISD::EXTRACT_SUBREG: {
1593       Tmp1 = LegalizeOp(Node->getOperand(0));
1594       ConstantSDNode *idx = dyn_cast<ConstantSDNode>(Node->getOperand(1));
1595       assert(idx && "Operand must be a constant");
1596       Tmp2 = DAG.getTargetConstant(idx->getAPIntValue(), idx->getValueType(0));
1597       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1598     }
1599     break;
1600   case ISD::INSERT_SUBREG: {
1601       Tmp1 = LegalizeOp(Node->getOperand(0));
1602       Tmp2 = LegalizeOp(Node->getOperand(1));      
1603       ConstantSDNode *idx = dyn_cast<ConstantSDNode>(Node->getOperand(2));
1604       assert(idx && "Operand must be a constant");
1605       Tmp3 = DAG.getTargetConstant(idx->getAPIntValue(), idx->getValueType(0));
1606       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1607     }
1608     break;      
1609   case ISD::BUILD_VECTOR:
1610     switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
1611     default: assert(0 && "This action is not supported yet!");
1612     case TargetLowering::Custom:
1613       Tmp3 = TLI.LowerOperation(Result, DAG);
1614       if (Tmp3.getNode()) {
1615         Result = Tmp3;
1616         break;
1617       }
1618       // FALLTHROUGH
1619     case TargetLowering::Expand:
1620       Result = ExpandBUILD_VECTOR(Result.getNode());
1621       break;
1622     }
1623     break;
1624   case ISD::INSERT_VECTOR_ELT:
1625     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVec
1626     Tmp3 = LegalizeOp(Node->getOperand(2));  // InEltNo
1627
1628     // The type of the value to insert may not be legal, even though the vector
1629     // type is legal.  Legalize/Promote accordingly.  We do not handle Expand
1630     // here.
1631     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1632     default: assert(0 && "Cannot expand insert element operand");
1633     case Legal:   Tmp2 = LegalizeOp(Node->getOperand(1)); break;
1634     case Promote: Tmp2 = PromoteOp(Node->getOperand(1));  break;
1635     case Expand:
1636       // FIXME: An alternative would be to check to see if the target is not
1637       // going to custom lower this operation, we could bitcast to half elt 
1638       // width and perform two inserts at that width, if that is legal.
1639       Tmp2 = Node->getOperand(1);
1640       break;
1641     }
1642     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1643     
1644     switch (TLI.getOperationAction(ISD::INSERT_VECTOR_ELT,
1645                                    Node->getValueType(0))) {
1646     default: assert(0 && "This action is not supported yet!");
1647     case TargetLowering::Legal:
1648       break;
1649     case TargetLowering::Custom:
1650       Tmp4 = TLI.LowerOperation(Result, DAG);
1651       if (Tmp4.getNode()) {
1652         Result = Tmp4;
1653         break;
1654       }
1655       // FALLTHROUGH
1656     case TargetLowering::Promote:
1657       // Fall thru for vector case
1658     case TargetLowering::Expand: {
1659       // If the insert index is a constant, codegen this as a scalar_to_vector,
1660       // then a shuffle that inserts it into the right position in the vector.
1661       if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Tmp3)) {
1662         // SCALAR_TO_VECTOR requires that the type of the value being inserted
1663         // match the element type of the vector being created.
1664         if (Tmp2.getValueType() == 
1665             Op.getValueType().getVectorElementType()) {
1666           SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, 
1667                                         Tmp1.getValueType(), Tmp2);
1668           
1669           unsigned NumElts = Tmp1.getValueType().getVectorNumElements();
1670           MVT ShufMaskVT =
1671             MVT::getIntVectorWithNumElements(NumElts);
1672           MVT ShufMaskEltVT = ShufMaskVT.getVectorElementType();
1673           
1674           // We generate a shuffle of InVec and ScVec, so the shuffle mask
1675           // should be 0,1,2,3,4,5... with the appropriate element replaced with
1676           // elt 0 of the RHS.
1677           SmallVector<SDValue, 8> ShufOps;
1678           for (unsigned i = 0; i != NumElts; ++i) {
1679             if (i != InsertPos->getZExtValue())
1680               ShufOps.push_back(DAG.getConstant(i, ShufMaskEltVT));
1681             else
1682               ShufOps.push_back(DAG.getConstant(NumElts, ShufMaskEltVT));
1683           }
1684           SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMaskVT,
1685                                            &ShufOps[0], ShufOps.size());
1686           
1687           Result = DAG.getNode(ISD::VECTOR_SHUFFLE, Tmp1.getValueType(),
1688                                Tmp1, ScVec, ShufMask);
1689           Result = LegalizeOp(Result);
1690           break;
1691         }
1692       }
1693       Result = PerformInsertVectorEltInMemory(Tmp1, Tmp2, Tmp3);
1694       break;
1695     }
1696     }
1697     break;
1698   case ISD::SCALAR_TO_VECTOR:
1699     if (!TLI.isTypeLegal(Node->getOperand(0).getValueType())) {
1700       Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
1701       break;
1702     }
1703     
1704     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVal
1705     Result = DAG.UpdateNodeOperands(Result, Tmp1);
1706     switch (TLI.getOperationAction(ISD::SCALAR_TO_VECTOR,
1707                                    Node->getValueType(0))) {
1708     default: assert(0 && "This action is not supported yet!");
1709     case TargetLowering::Legal:
1710       break;
1711     case TargetLowering::Custom:
1712       Tmp3 = TLI.LowerOperation(Result, DAG);
1713       if (Tmp3.getNode()) {
1714         Result = Tmp3;
1715         break;
1716       }
1717       // FALLTHROUGH
1718     case TargetLowering::Expand:
1719       Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
1720       break;
1721     }
1722     break;
1723   case ISD::VECTOR_SHUFFLE:
1724     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the input vectors,
1725     Tmp2 = LegalizeOp(Node->getOperand(1));   // but not the shuffle mask.
1726     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1727
1728     // Allow targets to custom lower the SHUFFLEs they support.
1729     switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE,Result.getValueType())) {
1730     default: assert(0 && "Unknown operation action!");
1731     case TargetLowering::Legal:
1732       assert(isShuffleLegal(Result.getValueType(), Node->getOperand(2)) &&
1733              "vector shuffle should not be created if not legal!");
1734       break;
1735     case TargetLowering::Custom:
1736       Tmp3 = TLI.LowerOperation(Result, DAG);
1737       if (Tmp3.getNode()) {
1738         Result = Tmp3;
1739         break;
1740       }
1741       // FALLTHROUGH
1742     case TargetLowering::Expand: {
1743       MVT VT = Node->getValueType(0);
1744       MVT EltVT = VT.getVectorElementType();
1745       MVT PtrVT = TLI.getPointerTy();
1746       SDValue Mask = Node->getOperand(2);
1747       unsigned NumElems = Mask.getNumOperands();
1748       SmallVector<SDValue,8> Ops;
1749       for (unsigned i = 0; i != NumElems; ++i) {
1750         SDValue Arg = Mask.getOperand(i);
1751         if (Arg.getOpcode() == ISD::UNDEF) {
1752           Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
1753         } else {
1754           assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1755           unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
1756           if (Idx < NumElems)
1757             Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1,
1758                                       DAG.getConstant(Idx, PtrVT)));
1759           else
1760             Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2,
1761                                       DAG.getConstant(Idx - NumElems, PtrVT)));
1762         }
1763       }
1764       Result = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1765       break;
1766     }
1767     case TargetLowering::Promote: {
1768       // Change base type to a different vector type.
1769       MVT OVT = Node->getValueType(0);
1770       MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
1771
1772       // Cast the two input vectors.
1773       Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
1774       Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
1775       
1776       // Convert the shuffle mask to the right # elements.
1777       Tmp3 = SDValue(isShuffleLegal(OVT, Node->getOperand(2)), 0);
1778       assert(Tmp3.getNode() && "Shuffle not legal?");
1779       Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NVT, Tmp1, Tmp2, Tmp3);
1780       Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
1781       break;
1782     }
1783     }
1784     break;
1785   
1786   case ISD::EXTRACT_VECTOR_ELT:
1787     Tmp1 = Node->getOperand(0);
1788     Tmp2 = LegalizeOp(Node->getOperand(1));
1789     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1790     Result = ExpandEXTRACT_VECTOR_ELT(Result);
1791     break;
1792
1793   case ISD::EXTRACT_SUBVECTOR: 
1794     Tmp1 = Node->getOperand(0);
1795     Tmp2 = LegalizeOp(Node->getOperand(1));
1796     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1797     Result = ExpandEXTRACT_SUBVECTOR(Result);
1798     break;
1799     
1800   case ISD::CONCAT_VECTORS: {
1801     // Use extract/insert/build vector for now. We might try to be
1802     // more clever later.
1803     MVT PtrVT = TLI.getPointerTy();
1804     SmallVector<SDValue, 8> Ops;
1805     unsigned NumOperands = Node->getNumOperands();
1806     for (unsigned i=0; i < NumOperands; ++i) {
1807       SDValue SubOp = Node->getOperand(i);
1808       MVT VVT = SubOp.getNode()->getValueType(0);
1809       MVT EltVT = VVT.getVectorElementType();
1810       unsigned NumSubElem = VVT.getVectorNumElements();
1811       for (unsigned j=0; j < NumSubElem; ++j) {
1812         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, SubOp,
1813                                   DAG.getConstant(j, PtrVT)));
1814       }
1815     }
1816     return LegalizeOp(DAG.getNode(ISD::BUILD_VECTOR, Node->getValueType(0),
1817                       &Ops[0], Ops.size()));
1818   }
1819
1820   case ISD::CALLSEQ_START: {
1821     SDNode *CallEnd = FindCallEndFromCallStart(Node);
1822     
1823     // Recursively Legalize all of the inputs of the call end that do not lead
1824     // to this call start.  This ensures that any libcalls that need be inserted
1825     // are inserted *before* the CALLSEQ_START.
1826     {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
1827     for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1828       LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).getNode(), Node,
1829                                    NodesLeadingTo);
1830     }
1831
1832     // Now that we legalized all of the inputs (which may have inserted
1833     // libcalls) create the new CALLSEQ_START node.
1834     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1835
1836     // Merge in the last call, to ensure that this call start after the last
1837     // call ended.
1838     if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
1839       Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1840       Tmp1 = LegalizeOp(Tmp1);
1841     }
1842       
1843     // Do not try to legalize the target-specific arguments (#1+).
1844     if (Tmp1 != Node->getOperand(0)) {
1845       SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1846       Ops[0] = Tmp1;
1847       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1848     }
1849     
1850     // Remember that the CALLSEQ_START is legalized.
1851     AddLegalizedOperand(Op.getValue(0), Result);
1852     if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
1853       AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1854     
1855     // Now that the callseq_start and all of the non-call nodes above this call
1856     // sequence have been legalized, legalize the call itself.  During this 
1857     // process, no libcalls can/will be inserted, guaranteeing that no calls
1858     // can overlap.
1859     assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1860     // Note that we are selecting this call!
1861     LastCALLSEQ_END = SDValue(CallEnd, 0);
1862     IsLegalizingCall = true;
1863     
1864     // Legalize the call, starting from the CALLSEQ_END.
1865     LegalizeOp(LastCALLSEQ_END);
1866     assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1867     return Result;
1868   }
1869   case ISD::CALLSEQ_END:
1870     // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1871     // will cause this node to be legalized as well as handling libcalls right.
1872     if (LastCALLSEQ_END.getNode() != Node) {
1873       LegalizeOp(SDValue(FindCallStartFromCallEnd(Node), 0));
1874       DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1875       assert(I != LegalizedNodes.end() &&
1876              "Legalizing the call start should have legalized this node!");
1877       return I->second;
1878     }
1879     
1880     // Otherwise, the call start has been legalized and everything is going 
1881     // according to plan.  Just legalize ourselves normally here.
1882     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1883     // Do not try to legalize the target-specific arguments (#1+), except for
1884     // an optional flag input.
1885     if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1886       if (Tmp1 != Node->getOperand(0)) {
1887         SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1888         Ops[0] = Tmp1;
1889         Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1890       }
1891     } else {
1892       Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1893       if (Tmp1 != Node->getOperand(0) ||
1894           Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1895         SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1896         Ops[0] = Tmp1;
1897         Ops.back() = Tmp2;
1898         Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1899       }
1900     }
1901     assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1902     // This finishes up call legalization.
1903     IsLegalizingCall = false;
1904     
1905     // If the CALLSEQ_END node has a flag, remember that we legalized it.
1906     AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1907     if (Node->getNumValues() == 2)
1908       AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1909     return Result.getValue(Op.getResNo());
1910   case ISD::DYNAMIC_STACKALLOC: {
1911     MVT VT = Node->getValueType(0);
1912     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1913     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
1914     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
1915     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1916
1917     Tmp1 = Result.getValue(0);
1918     Tmp2 = Result.getValue(1);
1919     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1920     default: assert(0 && "This action is not supported yet!");
1921     case TargetLowering::Expand: {
1922       unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1923       assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1924              " not tell us which reg is the stack pointer!");
1925       SDValue Chain = Tmp1.getOperand(0);
1926
1927       // Chain the dynamic stack allocation so that it doesn't modify the stack
1928       // pointer when other instructions are using the stack.
1929       Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1930
1931       SDValue Size  = Tmp2.getOperand(1);
1932       SDValue SP = DAG.getCopyFromReg(Chain, SPReg, VT);
1933       Chain = SP.getValue(1);
1934       unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1935       unsigned StackAlign =
1936         TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1937       if (Align > StackAlign)
1938         SP = DAG.getNode(ISD::AND, VT, SP,
1939                          DAG.getConstant(-(uint64_t)Align, VT));
1940       Tmp1 = DAG.getNode(ISD::SUB, VT, SP, Size);       // Value
1941       Chain = DAG.getCopyToReg(Chain, SPReg, Tmp1);     // Output chain
1942
1943       Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
1944                                 DAG.getIntPtrConstant(0, true), SDValue());
1945
1946       Tmp1 = LegalizeOp(Tmp1);
1947       Tmp2 = LegalizeOp(Tmp2);
1948       break;
1949     }
1950     case TargetLowering::Custom:
1951       Tmp3 = TLI.LowerOperation(Tmp1, DAG);
1952       if (Tmp3.getNode()) {
1953         Tmp1 = LegalizeOp(Tmp3);
1954         Tmp2 = LegalizeOp(Tmp3.getValue(1));
1955       }
1956       break;
1957     case TargetLowering::Legal:
1958       break;
1959     }
1960     // Since this op produce two values, make sure to remember that we
1961     // legalized both of them.
1962     AddLegalizedOperand(SDValue(Node, 0), Tmp1);
1963     AddLegalizedOperand(SDValue(Node, 1), Tmp2);
1964     return Op.getResNo() ? Tmp2 : Tmp1;
1965   }
1966   case ISD::INLINEASM: {
1967     SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1968     bool Changed = false;
1969     // Legalize all of the operands of the inline asm, in case they are nodes
1970     // that need to be expanded or something.  Note we skip the asm string and
1971     // all of the TargetConstant flags.
1972     SDValue Op = LegalizeOp(Ops[0]);
1973     Changed = Op != Ops[0];
1974     Ops[0] = Op;
1975
1976     bool HasInFlag = Ops.back().getValueType() == MVT::Flag;
1977     for (unsigned i = 2, e = Ops.size()-HasInFlag; i < e; ) {
1978       unsigned NumVals = cast<ConstantSDNode>(Ops[i])->getZExtValue() >> 3;
1979       for (++i; NumVals; ++i, --NumVals) {
1980         SDValue Op = LegalizeOp(Ops[i]);
1981         if (Op != Ops[i]) {
1982           Changed = true;
1983           Ops[i] = Op;
1984         }
1985       }
1986     }
1987
1988     if (HasInFlag) {
1989       Op = LegalizeOp(Ops.back());
1990       Changed |= Op != Ops.back();
1991       Ops.back() = Op;
1992     }
1993     
1994     if (Changed)
1995       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1996       
1997     // INLINE asm returns a chain and flag, make sure to add both to the map.
1998     AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1999     AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
2000     return Result.getValue(Op.getResNo());
2001   }
2002   case ISD::BR:
2003     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2004     // Ensure that libcalls are emitted before a branch.
2005     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
2006     Tmp1 = LegalizeOp(Tmp1);
2007     LastCALLSEQ_END = DAG.getEntryNode();
2008     
2009     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
2010     break;
2011   case ISD::BRIND:
2012     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2013     // Ensure that libcalls are emitted before a branch.
2014     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
2015     Tmp1 = LegalizeOp(Tmp1);
2016     LastCALLSEQ_END = DAG.getEntryNode();
2017     
2018     switch (getTypeAction(Node->getOperand(1).getValueType())) {
2019     default: assert(0 && "Indirect target must be legal type (pointer)!");
2020     case Legal:
2021       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
2022       break;
2023     }
2024     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2025     break;
2026   case ISD::BR_JT:
2027     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2028     // Ensure that libcalls are emitted before a branch.
2029     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
2030     Tmp1 = LegalizeOp(Tmp1);
2031     LastCALLSEQ_END = DAG.getEntryNode();
2032
2033     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the jumptable node.
2034     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2035
2036     switch (TLI.getOperationAction(ISD::BR_JT, MVT::Other)) {  
2037     default: assert(0 && "This action is not supported yet!");
2038     case TargetLowering::Legal: break;
2039     case TargetLowering::Custom:
2040       Tmp1 = TLI.LowerOperation(Result, DAG);
2041       if (Tmp1.getNode()) Result = Tmp1;
2042       break;
2043     case TargetLowering::Expand: {
2044       SDValue Chain = Result.getOperand(0);
2045       SDValue Table = Result.getOperand(1);
2046       SDValue Index = Result.getOperand(2);
2047
2048       MVT PTy = TLI.getPointerTy();
2049       MachineFunction &MF = DAG.getMachineFunction();
2050       unsigned EntrySize = MF.getJumpTableInfo()->getEntrySize();
2051       Index= DAG.getNode(ISD::MUL, PTy, Index, DAG.getConstant(EntrySize, PTy));
2052       SDValue Addr = DAG.getNode(ISD::ADD, PTy, Index, Table);
2053
2054       MVT MemVT = MVT::getIntegerVT(EntrySize * 8);
2055       SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, PTy, Chain, Addr,
2056                                   PseudoSourceValue::getJumpTable(), 0, MemVT);
2057       Addr = LD;
2058       if (TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2059         // For PIC, the sequence is:
2060         // BRIND(load(Jumptable + index) + RelocBase)
2061         // RelocBase can be JumpTable, GOT or some sort of global base.
2062         Addr = DAG.getNode(ISD::ADD, PTy, Addr,
2063                            TLI.getPICJumpTableRelocBase(Table, DAG));
2064       }
2065       Result = DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), Addr);
2066     }
2067     }
2068     break;
2069   case ISD::BRCOND:
2070     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2071     // Ensure that libcalls are emitted before a return.
2072     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
2073     Tmp1 = LegalizeOp(Tmp1);
2074     LastCALLSEQ_END = DAG.getEntryNode();
2075
2076     switch (getTypeAction(Node->getOperand(1).getValueType())) {
2077     case Expand: assert(0 && "It's impossible to expand bools");
2078     case Legal:
2079       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
2080       break;
2081     case Promote: {
2082       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
2083       
2084       // The top bits of the promoted condition are not necessarily zero, ensure
2085       // that the value is properly zero extended.
2086       unsigned BitWidth = Tmp2.getValueSizeInBits();
2087       if (!DAG.MaskedValueIsZero(Tmp2, 
2088                                  APInt::getHighBitsSet(BitWidth, BitWidth-1)))
2089         Tmp2 = DAG.getZeroExtendInReg(Tmp2, MVT::i1);
2090       break;
2091     }
2092     }
2093
2094     // Basic block destination (Op#2) is always legal.
2095     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2096       
2097     switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {  
2098     default: assert(0 && "This action is not supported yet!");
2099     case TargetLowering::Legal: break;
2100     case TargetLowering::Custom:
2101       Tmp1 = TLI.LowerOperation(Result, DAG);
2102       if (Tmp1.getNode()) Result = Tmp1;
2103       break;
2104     case TargetLowering::Expand:
2105       // Expand brcond's setcc into its constituent parts and create a BR_CC
2106       // Node.
2107       if (Tmp2.getOpcode() == ISD::SETCC) {
2108         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
2109                              Tmp2.getOperand(0), Tmp2.getOperand(1),
2110                              Node->getOperand(2));
2111       } else {
2112         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, 
2113                              DAG.getCondCode(ISD::SETNE), Tmp2,
2114                              DAG.getConstant(0, Tmp2.getValueType()),
2115                              Node->getOperand(2));
2116       }
2117       break;
2118     }
2119     break;
2120   case ISD::BR_CC:
2121     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2122     // Ensure that libcalls are emitted before a branch.
2123     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
2124     Tmp1 = LegalizeOp(Tmp1);
2125     Tmp2 = Node->getOperand(2);              // LHS 
2126     Tmp3 = Node->getOperand(3);              // RHS
2127     Tmp4 = Node->getOperand(1);              // CC
2128
2129     LegalizeSetCC(TLI.getSetCCResultType(Tmp2), Tmp2, Tmp3, Tmp4);
2130     LastCALLSEQ_END = DAG.getEntryNode();
2131
2132     // If we didn't get both a LHS and RHS back from LegalizeSetCC,
2133     // the LHS is a legal SETCC itself.  In this case, we need to compare
2134     // the result against zero to select between true and false values.
2135     if (Tmp3.getNode() == 0) {
2136       Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
2137       Tmp4 = DAG.getCondCode(ISD::SETNE);
2138     }
2139     
2140     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp4, Tmp2, Tmp3, 
2141                                     Node->getOperand(4));
2142       
2143     switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
2144     default: assert(0 && "Unexpected action for BR_CC!");
2145     case TargetLowering::Legal: break;
2146     case TargetLowering::Custom:
2147       Tmp4 = TLI.LowerOperation(Result, DAG);
2148       if (Tmp4.getNode()) Result = Tmp4;
2149       break;
2150     }
2151     break;
2152   case ISD::LOAD: {
2153     LoadSDNode *LD = cast<LoadSDNode>(Node);
2154     Tmp1 = LegalizeOp(LD->getChain());   // Legalize the chain.
2155     Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
2156
2157     ISD::LoadExtType ExtType = LD->getExtensionType();
2158     if (ExtType == ISD::NON_EXTLOAD) {
2159       MVT VT = Node->getValueType(0);
2160       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
2161       Tmp3 = Result.getValue(0);
2162       Tmp4 = Result.getValue(1);
2163     
2164       switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
2165       default: assert(0 && "This action is not supported yet!");
2166       case TargetLowering::Legal:
2167         // If this is an unaligned load and the target doesn't support it,
2168         // expand it.
2169         if (!TLI.allowsUnalignedMemoryAccesses()) {
2170           unsigned ABIAlignment = TLI.getTargetData()->
2171             getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
2172           if (LD->getAlignment() < ABIAlignment){
2173             Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()), DAG,
2174                                          TLI);
2175             Tmp3 = Result.getOperand(0);
2176             Tmp4 = Result.getOperand(1);
2177             Tmp3 = LegalizeOp(Tmp3);
2178             Tmp4 = LegalizeOp(Tmp4);
2179           }
2180         }
2181         break;
2182       case TargetLowering::Custom:
2183         Tmp1 = TLI.LowerOperation(Tmp3, DAG);
2184         if (Tmp1.getNode()) {
2185           Tmp3 = LegalizeOp(Tmp1);
2186           Tmp4 = LegalizeOp(Tmp1.getValue(1));
2187         }
2188         break;
2189       case TargetLowering::Promote: {
2190         // Only promote a load of vector type to another.
2191         assert(VT.isVector() && "Cannot promote this load!");
2192         // Change base type to a different vector type.
2193         MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
2194
2195         Tmp1 = DAG.getLoad(NVT, Tmp1, Tmp2, LD->getSrcValue(),
2196                            LD->getSrcValueOffset(),
2197                            LD->isVolatile(), LD->getAlignment());
2198         Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp1));
2199         Tmp4 = LegalizeOp(Tmp1.getValue(1));
2200         break;
2201       }
2202       }
2203       // Since loads produce two values, make sure to remember that we 
2204       // legalized both of them.
2205       AddLegalizedOperand(SDValue(Node, 0), Tmp3);
2206       AddLegalizedOperand(SDValue(Node, 1), Tmp4);
2207       return Op.getResNo() ? Tmp4 : Tmp3;
2208     } else {
2209       MVT SrcVT = LD->getMemoryVT();
2210       unsigned SrcWidth = SrcVT.getSizeInBits();
2211       int SVOffset = LD->getSrcValueOffset();
2212       unsigned Alignment = LD->getAlignment();
2213       bool isVolatile = LD->isVolatile();
2214
2215       if (SrcWidth != SrcVT.getStoreSizeInBits() &&
2216           // Some targets pretend to have an i1 loading operation, and actually
2217           // load an i8.  This trick is correct for ZEXTLOAD because the top 7
2218           // bits are guaranteed to be zero; it helps the optimizers understand
2219           // that these bits are zero.  It is also useful for EXTLOAD, since it
2220           // tells the optimizers that those bits are undefined.  It would be
2221           // nice to have an effective generic way of getting these benefits...
2222           // Until such a way is found, don't insist on promoting i1 here.
2223           (SrcVT != MVT::i1 ||
2224            TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
2225         // Promote to a byte-sized load if not loading an integral number of
2226         // bytes.  For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
2227         unsigned NewWidth = SrcVT.getStoreSizeInBits();
2228         MVT NVT = MVT::getIntegerVT(NewWidth);
2229         SDValue Ch;
2230
2231         // The extra bits are guaranteed to be zero, since we stored them that
2232         // way.  A zext load from NVT thus automatically gives zext from SrcVT.
2233
2234         ISD::LoadExtType NewExtType =
2235           ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
2236
2237         Result = DAG.getExtLoad(NewExtType, Node->getValueType(0),
2238                                 Tmp1, Tmp2, LD->getSrcValue(), SVOffset,
2239                                 NVT, isVolatile, Alignment);
2240
2241         Ch = Result.getValue(1); // The chain.
2242
2243         if (ExtType == ISD::SEXTLOAD)
2244           // Having the top bits zero doesn't help when sign extending.
2245           Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2246                                Result, DAG.getValueType(SrcVT));
2247         else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
2248           // All the top bits are guaranteed to be zero - inform the optimizers.
2249           Result = DAG.getNode(ISD::AssertZext, Result.getValueType(), Result,
2250                                DAG.getValueType(SrcVT));
2251
2252         Tmp1 = LegalizeOp(Result);
2253         Tmp2 = LegalizeOp(Ch);
2254       } else if (SrcWidth & (SrcWidth - 1)) {
2255         // If not loading a power-of-2 number of bits, expand as two loads.
2256         assert(SrcVT.isExtended() && !SrcVT.isVector() &&
2257                "Unsupported extload!");
2258         unsigned RoundWidth = 1 << Log2_32(SrcWidth);
2259         assert(RoundWidth < SrcWidth);
2260         unsigned ExtraWidth = SrcWidth - RoundWidth;
2261         assert(ExtraWidth < RoundWidth);
2262         assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
2263                "Load size not an integral number of bytes!");
2264         MVT RoundVT = MVT::getIntegerVT(RoundWidth);
2265         MVT ExtraVT = MVT::getIntegerVT(ExtraWidth);
2266         SDValue Lo, Hi, Ch;
2267         unsigned IncrementSize;
2268
2269         if (TLI.isLittleEndian()) {
2270           // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
2271           // Load the bottom RoundWidth bits.
2272           Lo = DAG.getExtLoad(ISD::ZEXTLOAD, Node->getValueType(0), Tmp1, Tmp2,
2273                               LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
2274                               Alignment);
2275
2276           // Load the remaining ExtraWidth bits.
2277           IncrementSize = RoundWidth / 8;
2278           Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2279                              DAG.getIntPtrConstant(IncrementSize));
2280           Hi = DAG.getExtLoad(ExtType, Node->getValueType(0), Tmp1, Tmp2,
2281                               LD->getSrcValue(), SVOffset + IncrementSize,
2282                               ExtraVT, isVolatile,
2283                               MinAlign(Alignment, IncrementSize));
2284
2285           // Build a factor node to remember that this load is independent of the
2286           // other one.
2287           Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
2288                            Hi.getValue(1));
2289
2290           // Move the top bits to the right place.
2291           Hi = DAG.getNode(ISD::SHL, Hi.getValueType(), Hi,
2292                            DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
2293
2294           // Join the hi and lo parts.
2295           Result = DAG.getNode(ISD::OR, Node->getValueType(0), Lo, Hi);
2296         } else {
2297           // Big endian - avoid unaligned loads.
2298           // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
2299           // Load the top RoundWidth bits.
2300           Hi = DAG.getExtLoad(ExtType, Node->getValueType(0), Tmp1, Tmp2,
2301                               LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
2302                               Alignment);
2303
2304           // Load the remaining ExtraWidth bits.
2305           IncrementSize = RoundWidth / 8;
2306           Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2307                              DAG.getIntPtrConstant(IncrementSize));
2308           Lo = DAG.getExtLoad(ISD::ZEXTLOAD, Node->getValueType(0), Tmp1, Tmp2,
2309                               LD->getSrcValue(), SVOffset + IncrementSize,
2310                               ExtraVT, isVolatile,
2311                               MinAlign(Alignment, IncrementSize));
2312
2313           // Build a factor node to remember that this load is independent of the
2314           // other one.
2315           Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
2316                            Hi.getValue(1));
2317
2318           // Move the top bits to the right place.
2319           Hi = DAG.getNode(ISD::SHL, Hi.getValueType(), Hi,
2320                            DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
2321
2322           // Join the hi and lo parts.
2323           Result = DAG.getNode(ISD::OR, Node->getValueType(0), Lo, Hi);
2324         }
2325
2326         Tmp1 = LegalizeOp(Result);
2327         Tmp2 = LegalizeOp(Ch);
2328       } else {
2329         switch (TLI.getLoadExtAction(ExtType, SrcVT)) {
2330         default: assert(0 && "This action is not supported yet!");
2331         case TargetLowering::Custom:
2332           isCustom = true;
2333           // FALLTHROUGH
2334         case TargetLowering::Legal:
2335           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
2336           Tmp1 = Result.getValue(0);
2337           Tmp2 = Result.getValue(1);
2338
2339           if (isCustom) {
2340             Tmp3 = TLI.LowerOperation(Result, DAG);
2341             if (Tmp3.getNode()) {
2342               Tmp1 = LegalizeOp(Tmp3);
2343               Tmp2 = LegalizeOp(Tmp3.getValue(1));
2344             }
2345           } else {
2346             // If this is an unaligned load and the target doesn't support it,
2347             // expand it.
2348             if (!TLI.allowsUnalignedMemoryAccesses()) {
2349               unsigned ABIAlignment = TLI.getTargetData()->
2350                 getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
2351               if (LD->getAlignment() < ABIAlignment){
2352                 Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()), DAG,
2353                                              TLI);
2354                 Tmp1 = Result.getOperand(0);
2355                 Tmp2 = Result.getOperand(1);
2356                 Tmp1 = LegalizeOp(Tmp1);
2357                 Tmp2 = LegalizeOp(Tmp2);
2358               }
2359             }
2360           }
2361           break;
2362         case TargetLowering::Expand:
2363           // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
2364           if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
2365             SDValue Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, LD->getSrcValue(),
2366                                          LD->getSrcValueOffset(),
2367                                          LD->isVolatile(), LD->getAlignment());
2368             Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
2369             Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
2370             Tmp2 = LegalizeOp(Load.getValue(1));
2371             break;
2372           }
2373           assert(ExtType != ISD::EXTLOAD &&"EXTLOAD should always be supported!");
2374           // Turn the unsupported load into an EXTLOAD followed by an explicit
2375           // zero/sign extend inreg.
2376           Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
2377                                   Tmp1, Tmp2, LD->getSrcValue(),
2378                                   LD->getSrcValueOffset(), SrcVT,
2379                                   LD->isVolatile(), LD->getAlignment());
2380           SDValue ValRes;
2381           if (ExtType == ISD::SEXTLOAD)
2382             ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2383                                  Result, DAG.getValueType(SrcVT));
2384           else
2385             ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
2386           Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
2387           Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
2388           break;
2389         }
2390       }
2391
2392       // Since loads produce two values, make sure to remember that we legalized
2393       // both of them.
2394       AddLegalizedOperand(SDValue(Node, 0), Tmp1);
2395       AddLegalizedOperand(SDValue(Node, 1), Tmp2);
2396       return Op.getResNo() ? Tmp2 : Tmp1;
2397     }
2398   }
2399   case ISD::EXTRACT_ELEMENT: {
2400     MVT OpTy = Node->getOperand(0).getValueType();
2401     switch (getTypeAction(OpTy)) {
2402     default: assert(0 && "EXTRACT_ELEMENT action for type unimplemented!");
2403     case Legal:
2404       if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
2405         // 1 -> Hi
2406         Result = DAG.getNode(ISD::SRL, OpTy, Node->getOperand(0),
2407                              DAG.getConstant(OpTy.getSizeInBits()/2,
2408                                              TLI.getShiftAmountTy()));
2409         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Result);
2410       } else {
2411         // 0 -> Lo
2412         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), 
2413                              Node->getOperand(0));
2414       }
2415       break;
2416     case Expand:
2417       // Get both the low and high parts.
2418       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2419       if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue())
2420         Result = Tmp2;  // 1 -> Hi
2421       else
2422         Result = Tmp1;  // 0 -> Lo
2423       break;
2424     }
2425     break;
2426   }
2427
2428   case ISD::CopyToReg:
2429     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2430
2431     assert(isTypeLegal(Node->getOperand(2).getValueType()) &&
2432            "Register type must be legal!");
2433     // Legalize the incoming value (must be a legal type).
2434     Tmp2 = LegalizeOp(Node->getOperand(2));
2435     if (Node->getNumValues() == 1) {
2436       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2);
2437     } else {
2438       assert(Node->getNumValues() == 2 && "Unknown CopyToReg");
2439       if (Node->getNumOperands() == 4) {
2440         Tmp3 = LegalizeOp(Node->getOperand(3));
2441         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2,
2442                                         Tmp3);
2443       } else {
2444         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
2445       }
2446       
2447       // Since this produces two values, make sure to remember that we legalized
2448       // both of them.
2449       AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
2450       AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
2451       return Result;
2452     }
2453     break;
2454
2455   case ISD::RET:
2456     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2457
2458     // Ensure that libcalls are emitted before a return.
2459     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
2460     Tmp1 = LegalizeOp(Tmp1);
2461     LastCALLSEQ_END = DAG.getEntryNode();
2462       
2463     switch (Node->getNumOperands()) {
2464     case 3:  // ret val
2465       Tmp2 = Node->getOperand(1);
2466       Tmp3 = Node->getOperand(2);  // Signness
2467       switch (getTypeAction(Tmp2.getValueType())) {
2468       case Legal:
2469         Result = DAG.UpdateNodeOperands(Result, Tmp1, LegalizeOp(Tmp2), Tmp3);
2470         break;
2471       case Expand:
2472         if (!Tmp2.getValueType().isVector()) {
2473           SDValue Lo, Hi;
2474           ExpandOp(Tmp2, Lo, Hi);
2475
2476           // Big endian systems want the hi reg first.
2477           if (TLI.isBigEndian())
2478             std::swap(Lo, Hi);
2479           
2480           if (Hi.getNode())
2481             Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3, Hi,Tmp3);
2482           else
2483             Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3);
2484           Result = LegalizeOp(Result);
2485         } else {
2486           SDNode *InVal = Tmp2.getNode();
2487           int InIx = Tmp2.getResNo();
2488           unsigned NumElems = InVal->getValueType(InIx).getVectorNumElements();
2489           MVT EVT = InVal->getValueType(InIx).getVectorElementType();
2490           
2491           // Figure out if there is a simple type corresponding to this Vector
2492           // type.  If so, convert to the vector type.
2493           MVT TVT = MVT::getVectorVT(EVT, NumElems);
2494           if (TLI.isTypeLegal(TVT)) {
2495             // Turn this into a return of the vector type.
2496             Tmp2 = LegalizeOp(Tmp2);
2497             Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2498           } else if (NumElems == 1) {
2499             // Turn this into a return of the scalar type.
2500             Tmp2 = ScalarizeVectorOp(Tmp2);
2501             Tmp2 = LegalizeOp(Tmp2);
2502             Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2503             
2504             // FIXME: Returns of gcc generic vectors smaller than a legal type
2505             // should be returned in integer registers!
2506             
2507             // The scalarized value type may not be legal, e.g. it might require
2508             // promotion or expansion.  Relegalize the return.
2509             Result = LegalizeOp(Result);
2510           } else {
2511             // FIXME: Returns of gcc generic vectors larger than a legal vector
2512             // type should be returned by reference!
2513             SDValue Lo, Hi;
2514             SplitVectorOp(Tmp2, Lo, Hi);
2515             Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3, Hi,Tmp3);
2516             Result = LegalizeOp(Result);
2517           }
2518         }
2519         break;
2520       case Promote:
2521         Tmp2 = PromoteOp(Node->getOperand(1));
2522         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2523         Result = LegalizeOp(Result);
2524         break;
2525       }
2526       break;
2527     case 1:  // ret void
2528       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2529       break;
2530     default: { // ret <values>
2531       SmallVector<SDValue, 8> NewValues;
2532       NewValues.push_back(Tmp1);
2533       for (unsigned i = 1, e = Node->getNumOperands(); i < e; i += 2)
2534         switch (getTypeAction(Node->getOperand(i).getValueType())) {
2535         case Legal:
2536           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
2537           NewValues.push_back(Node->getOperand(i+1));
2538           break;
2539         case Expand: {
2540           SDValue Lo, Hi;
2541           assert(!Node->getOperand(i).getValueType().isExtended() &&
2542                  "FIXME: TODO: implement returning non-legal vector types!");
2543           ExpandOp(Node->getOperand(i), Lo, Hi);
2544           NewValues.push_back(Lo);
2545           NewValues.push_back(Node->getOperand(i+1));
2546           if (Hi.getNode()) {
2547             NewValues.push_back(Hi);
2548             NewValues.push_back(Node->getOperand(i+1));
2549           }
2550           break;
2551         }
2552         case Promote:
2553           assert(0 && "Can't promote multiple return value yet!");
2554         }
2555           
2556       if (NewValues.size() == Node->getNumOperands())
2557         Result = DAG.UpdateNodeOperands(Result, &NewValues[0],NewValues.size());
2558       else
2559         Result = DAG.getNode(ISD::RET, MVT::Other,
2560                              &NewValues[0], NewValues.size());
2561       break;
2562     }
2563     }
2564
2565     if (Result.getOpcode() == ISD::RET) {
2566       switch (TLI.getOperationAction(Result.getOpcode(), MVT::Other)) {
2567       default: assert(0 && "This action is not supported yet!");
2568       case TargetLowering::Legal: break;
2569       case TargetLowering::Custom:
2570         Tmp1 = TLI.LowerOperation(Result, DAG);
2571         if (Tmp1.getNode()) Result = Tmp1;
2572         break;
2573       }
2574     }
2575     break;
2576   case ISD::STORE: {
2577     StoreSDNode *ST = cast<StoreSDNode>(Node);
2578     Tmp1 = LegalizeOp(ST->getChain());    // Legalize the chain.
2579     Tmp2 = LegalizeOp(ST->getBasePtr());  // Legalize the pointer.
2580     int SVOffset = ST->getSrcValueOffset();
2581     unsigned Alignment = ST->getAlignment();
2582     bool isVolatile = ST->isVolatile();
2583
2584     if (!ST->isTruncatingStore()) {
2585       // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
2586       // FIXME: We shouldn't do this for TargetConstantFP's.
2587       // FIXME: move this to the DAG Combiner!  Note that we can't regress due
2588       // to phase ordering between legalized code and the dag combiner.  This
2589       // probably means that we need to integrate dag combiner and legalizer
2590       // together.
2591       // We generally can't do this one for long doubles.
2592       if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
2593         if (CFP->getValueType(0) == MVT::f32 && 
2594             getTypeAction(MVT::i32) == Legal) {
2595           Tmp3 = DAG.getConstant(CFP->getValueAPF().
2596                                           bitcastToAPInt().zextOrTrunc(32),
2597                                   MVT::i32);
2598           Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2599                                 SVOffset, isVolatile, Alignment);
2600           break;
2601         } else if (CFP->getValueType(0) == MVT::f64) {
2602           // If this target supports 64-bit registers, do a single 64-bit store.
2603           if (getTypeAction(MVT::i64) == Legal) {
2604             Tmp3 = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
2605                                      zextOrTrunc(64), MVT::i64);
2606             Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2607                                   SVOffset, isVolatile, Alignment);
2608             break;
2609           } else if (getTypeAction(MVT::i32) == Legal && !ST->isVolatile()) {
2610             // Otherwise, if the target supports 32-bit registers, use 2 32-bit
2611             // stores.  If the target supports neither 32- nor 64-bits, this
2612             // xform is certainly not worth it.
2613             const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
2614             SDValue Lo = DAG.getConstant(APInt(IntVal).trunc(32), MVT::i32);
2615             SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
2616             if (TLI.isBigEndian()) std::swap(Lo, Hi);
2617
2618             Lo = DAG.getStore(Tmp1, Lo, Tmp2, ST->getSrcValue(),
2619                               SVOffset, isVolatile, Alignment);
2620             Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2621                                DAG.getIntPtrConstant(4));
2622             Hi = DAG.getStore(Tmp1, Hi, Tmp2, ST->getSrcValue(), SVOffset+4,
2623                               isVolatile, MinAlign(Alignment, 4U));
2624
2625             Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2626             break;
2627           }
2628         }
2629       }
2630       
2631       switch (getTypeAction(ST->getMemoryVT())) {
2632       case Legal: {
2633         Tmp3 = LegalizeOp(ST->getValue());
2634         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
2635                                         ST->getOffset());
2636
2637         MVT VT = Tmp3.getValueType();
2638         switch (TLI.getOperationAction(ISD::STORE, VT)) {
2639         default: assert(0 && "This action is not supported yet!");
2640         case TargetLowering::Legal:
2641           // If this is an unaligned store and the target doesn't support it,
2642           // expand it.
2643           if (!TLI.allowsUnalignedMemoryAccesses()) {
2644             unsigned ABIAlignment = TLI.getTargetData()->
2645               getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
2646             if (ST->getAlignment() < ABIAlignment)
2647               Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()), DAG,
2648                                             TLI);
2649           }
2650           break;
2651         case TargetLowering::Custom:
2652           Tmp1 = TLI.LowerOperation(Result, DAG);
2653           if (Tmp1.getNode()) Result = Tmp1;
2654           break;
2655         case TargetLowering::Promote:
2656           assert(VT.isVector() && "Unknown legal promote case!");
2657           Tmp3 = DAG.getNode(ISD::BIT_CONVERT, 
2658                              TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
2659           Result = DAG.getStore(Tmp1, Tmp3, Tmp2,
2660                                 ST->getSrcValue(), SVOffset, isVolatile,
2661                                 Alignment);
2662           break;
2663         }
2664         break;
2665       }
2666       case Promote:
2667         if (!ST->getMemoryVT().isVector()) {
2668           // Truncate the value and store the result.
2669           Tmp3 = PromoteOp(ST->getValue());
2670           Result = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2671                                      SVOffset, ST->getMemoryVT(),
2672                                      isVolatile, Alignment);
2673           break;
2674         }
2675         // Fall thru to expand for vector
2676       case Expand: {
2677         unsigned IncrementSize = 0;
2678         SDValue Lo, Hi;
2679       
2680         // If this is a vector type, then we have to calculate the increment as
2681         // the product of the element size in bytes, and the number of elements
2682         // in the high half of the vector.
2683         if (ST->getValue().getValueType().isVector()) {
2684           SDNode *InVal = ST->getValue().getNode();
2685           int InIx = ST->getValue().getResNo();
2686           MVT InVT = InVal->getValueType(InIx);
2687           unsigned NumElems = InVT.getVectorNumElements();
2688           MVT EVT = InVT.getVectorElementType();
2689
2690           // Figure out if there is a simple type corresponding to this Vector
2691           // type.  If so, convert to the vector type.
2692           MVT TVT = MVT::getVectorVT(EVT, NumElems);
2693           if (TLI.isTypeLegal(TVT)) {
2694             // Turn this into a normal store of the vector type.
2695             Tmp3 = LegalizeOp(ST->getValue());
2696             Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2697                                   SVOffset, isVolatile, Alignment);
2698             Result = LegalizeOp(Result);
2699             break;
2700           } else if (NumElems == 1) {
2701             // Turn this into a normal store of the scalar type.
2702             Tmp3 = ScalarizeVectorOp(ST->getValue());
2703             Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2704                                   SVOffset, isVolatile, Alignment);
2705             // The scalarized value type may not be legal, e.g. it might require
2706             // promotion or expansion.  Relegalize the scalar store.
2707             Result = LegalizeOp(Result);
2708             break;
2709           } else {
2710             // Check if we have widen this node with another value
2711             std::map<SDValue, SDValue>::iterator I =
2712               WidenNodes.find(ST->getValue());
2713             if (I != WidenNodes.end()) {
2714               Result = StoreWidenVectorOp(ST, Tmp1, Tmp2);
2715               break;
2716             }
2717             else {
2718               SplitVectorOp(ST->getValue(), Lo, Hi);
2719               IncrementSize = Lo.getNode()->getValueType(0).getVectorNumElements() *
2720                               EVT.getSizeInBits()/8;
2721             }
2722           }
2723         } else {
2724           ExpandOp(ST->getValue(), Lo, Hi);
2725           IncrementSize = Hi.getNode() ? Hi.getValueType().getSizeInBits()/8 : 0;
2726
2727           if (Hi.getNode() && TLI.isBigEndian())
2728             std::swap(Lo, Hi);
2729         }
2730
2731         Lo = DAG.getStore(Tmp1, Lo, Tmp2, ST->getSrcValue(),
2732                           SVOffset, isVolatile, Alignment);
2733
2734         if (Hi.getNode() == NULL) {
2735           // Must be int <-> float one-to-one expansion.
2736           Result = Lo;
2737           break;
2738         }
2739
2740         Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2741                            DAG.getIntPtrConstant(IncrementSize));
2742         assert(isTypeLegal(Tmp2.getValueType()) &&
2743                "Pointers must be legal!");
2744         SVOffset += IncrementSize;
2745         Alignment = MinAlign(Alignment, IncrementSize);
2746         Hi = DAG.getStore(Tmp1, Hi, Tmp2, ST->getSrcValue(),
2747                           SVOffset, isVolatile, Alignment);
2748         Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2749         break;
2750       }  // case Expand
2751       }
2752     } else {
2753       switch (getTypeAction(ST->getValue().getValueType())) {
2754       case Legal:
2755         Tmp3 = LegalizeOp(ST->getValue());
2756         break;
2757       case Promote:
2758         if (!ST->getValue().getValueType().isVector()) {
2759           // We can promote the value, the truncstore will still take care of it.
2760           Tmp3 = PromoteOp(ST->getValue());
2761           break;
2762         }
2763         // Vector case falls through to expand
2764       case Expand:
2765         // Just store the low part.  This may become a non-trunc store, so make
2766         // sure to use getTruncStore, not UpdateNodeOperands below.
2767         ExpandOp(ST->getValue(), Tmp3, Tmp4);
2768         return DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2769                                  SVOffset, MVT::i8, isVolatile, Alignment);
2770       }
2771
2772       MVT StVT = ST->getMemoryVT();
2773       unsigned StWidth = StVT.getSizeInBits();
2774
2775       if (StWidth != StVT.getStoreSizeInBits()) {
2776         // Promote to a byte-sized store with upper bits zero if not
2777         // storing an integral number of bytes.  For example, promote
2778         // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
2779         MVT NVT = MVT::getIntegerVT(StVT.getStoreSizeInBits());
2780         Tmp3 = DAG.getZeroExtendInReg(Tmp3, StVT);
2781         Result = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2782                                    SVOffset, NVT, isVolatile, Alignment);
2783       } else if (StWidth & (StWidth - 1)) {
2784         // If not storing a power-of-2 number of bits, expand as two stores.
2785         assert(StVT.isExtended() && !StVT.isVector() &&
2786                "Unsupported truncstore!");
2787         unsigned RoundWidth = 1 << Log2_32(StWidth);
2788         assert(RoundWidth < StWidth);
2789         unsigned ExtraWidth = StWidth - RoundWidth;
2790         assert(ExtraWidth < RoundWidth);
2791         assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
2792                "Store size not an integral number of bytes!");
2793         MVT RoundVT = MVT::getIntegerVT(RoundWidth);
2794         MVT ExtraVT = MVT::getIntegerVT(ExtraWidth);
2795         SDValue Lo, Hi;
2796         unsigned IncrementSize;
2797
2798         if (TLI.isLittleEndian()) {
2799           // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
2800           // Store the bottom RoundWidth bits.
2801           Lo = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2802                                  SVOffset, RoundVT,
2803                                  isVolatile, Alignment);
2804
2805           // Store the remaining ExtraWidth bits.
2806           IncrementSize = RoundWidth / 8;
2807           Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2808                              DAG.getIntPtrConstant(IncrementSize));
2809           Hi = DAG.getNode(ISD::SRL, Tmp3.getValueType(), Tmp3,
2810                            DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
2811           Hi = DAG.getTruncStore(Tmp1, Hi, Tmp2, ST->getSrcValue(),
2812                                  SVOffset + IncrementSize, ExtraVT, isVolatile,
2813                                  MinAlign(Alignment, IncrementSize));
2814         } else {
2815           // Big endian - avoid unaligned stores.
2816           // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
2817           // Store the top RoundWidth bits.
2818           Hi = DAG.getNode(ISD::SRL, Tmp3.getValueType(), Tmp3,
2819                            DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
2820           Hi = DAG.getTruncStore(Tmp1, Hi, Tmp2, ST->getSrcValue(), SVOffset,
2821                                  RoundVT, isVolatile, Alignment);
2822
2823           // Store the remaining ExtraWidth bits.
2824           IncrementSize = RoundWidth / 8;
2825           Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2826                              DAG.getIntPtrConstant(IncrementSize));
2827           Lo = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2828                                  SVOffset + IncrementSize, ExtraVT, isVolatile,
2829                                  MinAlign(Alignment, IncrementSize));
2830         }
2831
2832         // The order of the stores doesn't matter.
2833         Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2834       } else {
2835         if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
2836             Tmp2 != ST->getBasePtr())
2837           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
2838                                           ST->getOffset());
2839
2840         switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
2841         default: assert(0 && "This action is not supported yet!");
2842         case TargetLowering::Legal:
2843           // If this is an unaligned store and the target doesn't support it,
2844           // expand it.
2845           if (!TLI.allowsUnalignedMemoryAccesses()) {
2846             unsigned ABIAlignment = TLI.getTargetData()->
2847               getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
2848             if (ST->getAlignment() < ABIAlignment)
2849               Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()), DAG,
2850                                             TLI);
2851           }
2852           break;
2853         case TargetLowering::Custom:
2854           Result = TLI.LowerOperation(Result, DAG);
2855           break;
2856         case Expand:
2857           // TRUNCSTORE:i16 i32 -> STORE i16
2858           assert(isTypeLegal(StVT) && "Do not know how to expand this store!");
2859           Tmp3 = DAG.getNode(ISD::TRUNCATE, StVT, Tmp3);
2860           Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(), SVOffset,
2861                                 isVolatile, Alignment);
2862           break;
2863         }
2864       }
2865     }
2866     break;
2867   }
2868   case ISD::PCMARKER:
2869     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2870     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
2871     break;
2872   case ISD::STACKSAVE:
2873     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2874     Result = DAG.UpdateNodeOperands(Result, Tmp1);
2875     Tmp1 = Result.getValue(0);
2876     Tmp2 = Result.getValue(1);
2877     
2878     switch (TLI.getOperationAction(ISD::STACKSAVE, MVT::Other)) {
2879     default: assert(0 && "This action is not supported yet!");
2880     case TargetLowering::Legal: break;
2881     case TargetLowering::Custom:
2882       Tmp3 = TLI.LowerOperation(Result, DAG);
2883       if (Tmp3.getNode()) {
2884         Tmp1 = LegalizeOp(Tmp3);
2885         Tmp2 = LegalizeOp(Tmp3.getValue(1));
2886       }
2887       break;
2888     case TargetLowering::Expand:
2889       // Expand to CopyFromReg if the target set 
2890       // StackPointerRegisterToSaveRestore.
2891       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2892         Tmp1 = DAG.getCopyFromReg(Result.getOperand(0), SP,
2893                                   Node->getValueType(0));
2894         Tmp2 = Tmp1.getValue(1);
2895       } else {
2896         Tmp1 = DAG.getNode(ISD::UNDEF, Node->getValueType(0));
2897         Tmp2 = Node->getOperand(0);
2898       }
2899       break;
2900     }
2901
2902     // Since stacksave produce two values, make sure to remember that we
2903     // legalized both of them.
2904     AddLegalizedOperand(SDValue(Node, 0), Tmp1);
2905     AddLegalizedOperand(SDValue(Node, 1), Tmp2);
2906     return Op.getResNo() ? Tmp2 : Tmp1;
2907
2908   case ISD::STACKRESTORE:
2909     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2910     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2911     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2912       
2913     switch (TLI.getOperationAction(ISD::STACKRESTORE, MVT::Other)) {
2914     default: assert(0 && "This action is not supported yet!");
2915     case TargetLowering::Legal: break;
2916     case TargetLowering::Custom:
2917       Tmp1 = TLI.LowerOperation(Result, DAG);
2918       if (Tmp1.getNode()) Result = Tmp1;
2919       break;
2920     case TargetLowering::Expand:
2921       // Expand to CopyToReg if the target set 
2922       // StackPointerRegisterToSaveRestore.
2923       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2924         Result = DAG.getCopyToReg(Tmp1, SP, Tmp2);
2925       } else {
2926         Result = Tmp1;
2927       }
2928       break;
2929     }
2930     break;
2931
2932   case ISD::READCYCLECOUNTER:
2933     Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
2934     Result = DAG.UpdateNodeOperands(Result, Tmp1);
2935     switch (TLI.getOperationAction(ISD::READCYCLECOUNTER,
2936                                    Node->getValueType(0))) {
2937     default: assert(0 && "This action is not supported yet!");
2938     case TargetLowering::Legal:
2939       Tmp1 = Result.getValue(0);
2940       Tmp2 = Result.getValue(1);
2941       break;
2942     case TargetLowering::Custom:
2943       Result = TLI.LowerOperation(Result, DAG);
2944       Tmp1 = LegalizeOp(Result.getValue(0));
2945       Tmp2 = LegalizeOp(Result.getValue(1));
2946       break;
2947     }
2948
2949     // Since rdcc produce two values, make sure to remember that we legalized
2950     // both of them.
2951     AddLegalizedOperand(SDValue(Node, 0), Tmp1);
2952     AddLegalizedOperand(SDValue(Node, 1), Tmp2);
2953     return Result;
2954
2955   case ISD::SELECT:
2956     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2957     case Expand: assert(0 && "It's impossible to expand bools");
2958     case Legal:
2959       Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
2960       break;
2961     case Promote: {
2962       assert(!Node->getOperand(0).getValueType().isVector() && "not possible");
2963       Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
2964       // Make sure the condition is either zero or one.
2965       unsigned BitWidth = Tmp1.getValueSizeInBits();
2966       if (!DAG.MaskedValueIsZero(Tmp1,
2967                                  APInt::getHighBitsSet(BitWidth, BitWidth-1)))
2968         Tmp1 = DAG.getZeroExtendInReg(Tmp1, MVT::i1);
2969       break;
2970     }
2971     }
2972     Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
2973     Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
2974
2975     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2976       
2977     switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
2978     default: assert(0 && "This action is not supported yet!");
2979     case TargetLowering::Legal: break;
2980     case TargetLowering::Custom: {
2981       Tmp1 = TLI.LowerOperation(Result, DAG);
2982       if (Tmp1.getNode()) Result = Tmp1;
2983       break;
2984     }
2985     case TargetLowering::Expand:
2986       if (Tmp1.getOpcode() == ISD::SETCC) {
2987         Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1), 
2988                               Tmp2, Tmp3,
2989                               cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
2990       } else {
2991         Result = DAG.getSelectCC(Tmp1, 
2992                                  DAG.getConstant(0, Tmp1.getValueType()),
2993                                  Tmp2, Tmp3, ISD::SETNE);
2994       }
2995       break;
2996     case TargetLowering::Promote: {
2997       MVT NVT =
2998         TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
2999       unsigned ExtOp, TruncOp;
3000       if (Tmp2.getValueType().isVector()) {
3001         ExtOp   = ISD::BIT_CONVERT;
3002         TruncOp = ISD::BIT_CONVERT;
3003       } else if (Tmp2.getValueType().isInteger()) {
3004         ExtOp   = ISD::ANY_EXTEND;
3005         TruncOp = ISD::TRUNCATE;
3006       } else {
3007         ExtOp   = ISD::FP_EXTEND;
3008         TruncOp = ISD::FP_ROUND;
3009       }
3010       // Promote each of the values to the new type.
3011       Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
3012       Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
3013       // Perform the larger operation, then round down.
3014       Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
3015       if (TruncOp != ISD::FP_ROUND)
3016         Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
3017       else
3018         Result = DAG.getNode(TruncOp, Node->getValueType(0), Result,
3019                              DAG.getIntPtrConstant(0));
3020       break;
3021     }
3022     }
3023     break;
3024   case ISD::SELECT_CC: {
3025     Tmp1 = Node->getOperand(0);               // LHS
3026     Tmp2 = Node->getOperand(1);               // RHS
3027     Tmp3 = LegalizeOp(Node->getOperand(2));   // True
3028     Tmp4 = LegalizeOp(Node->getOperand(3));   // False
3029     SDValue CC = Node->getOperand(4);
3030     
3031     LegalizeSetCC(TLI.getSetCCResultType(Tmp1), Tmp1, Tmp2, CC);
3032     
3033     // If we didn't get both a LHS and RHS back from LegalizeSetCC,
3034     // the LHS is a legal SETCC itself.  In this case, we need to compare
3035     // the result against zero to select between true and false values.
3036     if (Tmp2.getNode() == 0) {
3037       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3038       CC = DAG.getCondCode(ISD::SETNE);
3039     }
3040     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, CC);
3041
3042     // Everything is legal, see if we should expand this op or something.
3043     switch (TLI.getOperationAction(ISD::SELECT_CC, Tmp3.getValueType())) {
3044     default: assert(0 && "This action is not supported yet!");
3045     case TargetLowering::Legal: break;
3046     case TargetLowering::Custom:
3047       Tmp1 = TLI.LowerOperation(Result, DAG);
3048       if (Tmp1.getNode()) Result = Tmp1;
3049       break;
3050     }
3051     break;
3052   }
3053   case ISD::SETCC:
3054     Tmp1 = Node->getOperand(0);
3055     Tmp2 = Node->getOperand(1);
3056     Tmp3 = Node->getOperand(2);
3057     LegalizeSetCC(Node->getValueType(0), Tmp1, Tmp2, Tmp3);
3058     
3059     // If we had to Expand the SetCC operands into a SELECT node, then it may 
3060     // not always be possible to return a true LHS & RHS.  In this case, just 
3061     // return the value we legalized, returned in the LHS
3062     if (Tmp2.getNode() == 0) {
3063       Result = Tmp1;
3064       break;
3065     }
3066
3067     switch (TLI.getOperationAction(ISD::SETCC, Tmp1.getValueType())) {
3068     default: assert(0 && "Cannot handle this action for SETCC yet!");
3069     case TargetLowering::Custom:
3070       isCustom = true;
3071       // FALLTHROUGH.
3072     case TargetLowering::Legal:
3073       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
3074       if (isCustom) {
3075         Tmp4 = TLI.LowerOperation(Result, DAG);
3076         if (Tmp4.getNode()) Result = Tmp4;
3077       }
3078       break;
3079     case TargetLowering::Promote: {
3080       // First step, figure out the appropriate operation to use.
3081       // Allow SETCC to not be supported for all legal data types
3082       // Mostly this targets FP
3083       MVT NewInTy = Node->getOperand(0).getValueType();
3084       MVT OldVT = NewInTy; OldVT = OldVT;
3085
3086       // Scan for the appropriate larger type to use.
3087       while (1) {
3088         NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT()+1);
3089
3090         assert(NewInTy.isInteger() == OldVT.isInteger() &&
3091                "Fell off of the edge of the integer world");
3092         assert(NewInTy.isFloatingPoint() == OldVT.isFloatingPoint() &&
3093                "Fell off of the edge of the floating point world");
3094           
3095         // If the target supports SETCC of this type, use it.
3096         if (TLI.isOperationLegal(ISD::SETCC, NewInTy))
3097           break;
3098       }
3099       if (NewInTy.isInteger())
3100         assert(0 && "Cannot promote Legal Integer SETCC yet");
3101       else {
3102         Tmp1 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp1);
3103         Tmp2 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp2);
3104       }
3105       Tmp1 = LegalizeOp(Tmp1);
3106       Tmp2 = LegalizeOp(Tmp2);
3107       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
3108       Result = LegalizeOp(Result);
3109       break;
3110     }
3111     case TargetLowering::Expand:
3112       // Expand a setcc node into a select_cc of the same condition, lhs, and
3113       // rhs that selects between const 1 (true) and const 0 (false).
3114       MVT VT = Node->getValueType(0);
3115       Result = DAG.getNode(ISD::SELECT_CC, VT, Tmp1, Tmp2, 
3116                            DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3117                            Tmp3);
3118       break;
3119     }
3120     break;
3121   case ISD::VSETCC: {
3122     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3123     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3124     SDValue CC = Node->getOperand(2);
3125     
3126     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, CC);
3127
3128     // Everything is legal, see if we should expand this op or something.
3129     switch (TLI.getOperationAction(ISD::VSETCC, Tmp1.getValueType())) {
3130     default: assert(0 && "This action is not supported yet!");
3131     case TargetLowering::Legal: break;
3132     case TargetLowering::Custom:
3133       Tmp1 = TLI.LowerOperation(Result, DAG);
3134       if (Tmp1.getNode()) Result = Tmp1;
3135       break;
3136     case TargetLowering::Expand: {
3137       // Unroll into a nasty set of scalar code for now.
3138       MVT VT = Node->getValueType(0);
3139       unsigned NumElems = VT.getVectorNumElements();
3140       MVT EltVT = VT.getVectorElementType();
3141       MVT TmpEltVT = Tmp1.getValueType().getVectorElementType();
3142       SmallVector<SDValue, 8> Ops(NumElems);
3143       for (unsigned i = 0; i < NumElems; ++i) {
3144         SDValue In1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, TmpEltVT,
3145                                   Tmp1, DAG.getIntPtrConstant(i));
3146         Ops[i] = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(In1), In1,
3147                               DAG.getNode(ISD::EXTRACT_VECTOR_ELT, TmpEltVT,
3148                                           Tmp2, DAG.getIntPtrConstant(i)),
3149                               CC);
3150         Ops[i] = DAG.getNode(ISD::SIGN_EXTEND, EltVT, Ops[i]);
3151       }
3152       Result = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], NumElems);
3153       break;
3154     }
3155     }
3156     break;
3157   }
3158
3159   case ISD::SHL_PARTS:
3160   case ISD::SRA_PARTS:
3161   case ISD::SRL_PARTS: {
3162     SmallVector<SDValue, 8> Ops;
3163     bool Changed = false;
3164     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3165       Ops.push_back(LegalizeOp(Node->getOperand(i)));
3166       Changed |= Ops.back() != Node->getOperand(i);
3167     }
3168     if (Changed)
3169       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
3170
3171     switch (TLI.getOperationAction(Node->getOpcode(),
3172                                    Node->getValueType(0))) {
3173     default: assert(0 && "This action is not supported yet!");
3174     case TargetLowering::Legal: break;
3175     case TargetLowering::Custom:
3176       Tmp1 = TLI.LowerOperation(Result, DAG);
3177       if (Tmp1.getNode()) {
3178         SDValue Tmp2, RetVal(0, 0);
3179         for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
3180           Tmp2 = LegalizeOp(Tmp1.getValue(i));
3181           AddLegalizedOperand(SDValue(Node, i), Tmp2);
3182           if (i == Op.getResNo())
3183             RetVal = Tmp2;
3184         }
3185         assert(RetVal.getNode() && "Illegal result number");
3186         return RetVal;
3187       }
3188       break;
3189     }
3190
3191     // Since these produce multiple values, make sure to remember that we
3192     // legalized all of them.
3193     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
3194       AddLegalizedOperand(SDValue(Node, i), Result.getValue(i));
3195     return Result.getValue(Op.getResNo());
3196   }
3197
3198     // Binary operators
3199   case ISD::ADD:
3200   case ISD::SUB:
3201   case ISD::MUL:
3202   case ISD::MULHS:
3203   case ISD::MULHU:
3204   case ISD::UDIV:
3205   case ISD::SDIV:
3206   case ISD::AND:
3207   case ISD::OR:
3208   case ISD::XOR:
3209   case ISD::SHL:
3210   case ISD::SRL:
3211   case ISD::SRA:
3212   case ISD::FADD:
3213   case ISD::FSUB:
3214   case ISD::FMUL:
3215   case ISD::FDIV:
3216   case ISD::FPOW:
3217     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3218     switch (getTypeAction(Node->getOperand(1).getValueType())) {
3219     case Expand: assert(0 && "Not possible");
3220     case Legal:
3221       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
3222       break;
3223     case Promote:
3224       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
3225       break;
3226     }
3227
3228     if ((Node->getOpcode() == ISD::SHL ||
3229          Node->getOpcode() == ISD::SRL ||
3230          Node->getOpcode() == ISD::SRA) &&
3231         !Node->getValueType(0).isVector()) {
3232       Tmp2 = LegalizeShiftAmount(Tmp2);
3233     }
3234
3235     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3236
3237     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3238     default: assert(0 && "BinOp legalize operation not supported");
3239     case TargetLowering::Legal: break;
3240     case TargetLowering::Custom:
3241       Tmp1 = TLI.LowerOperation(Result, DAG);
3242       if (Tmp1.getNode()) {
3243         Result = Tmp1;
3244         break;
3245       }
3246       // Fall through if the custom lower can't deal with the operation
3247     case TargetLowering::Expand: {
3248       MVT VT = Op.getValueType();
3249       
3250       // See if multiply or divide can be lowered using two-result operations.
3251       SDVTList VTs = DAG.getVTList(VT, VT);
3252       if (Node->getOpcode() == ISD::MUL) {
3253         // We just need the low half of the multiply; try both the signed
3254         // and unsigned forms. If the target supports both SMUL_LOHI and
3255         // UMUL_LOHI, form a preference by checking which forms of plain
3256         // MULH it supports.
3257         bool HasSMUL_LOHI = TLI.isOperationLegal(ISD::SMUL_LOHI, VT);
3258         bool HasUMUL_LOHI = TLI.isOperationLegal(ISD::UMUL_LOHI, VT);
3259         bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, VT);
3260         bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, VT);
3261         unsigned OpToUse = 0;
3262         if (HasSMUL_LOHI && !HasMULHS) {
3263           OpToUse = ISD::SMUL_LOHI;
3264         } else if (HasUMUL_LOHI && !HasMULHU) {
3265           OpToUse = ISD::UMUL_LOHI;
3266         } else if (HasSMUL_LOHI) {
3267           OpToUse = ISD::SMUL_LOHI;
3268         } else if (HasUMUL_LOHI) {
3269           OpToUse = ISD::UMUL_LOHI;
3270         }
3271         if (OpToUse) {
3272           Result = SDValue(DAG.getNode(OpToUse, VTs, Tmp1, Tmp2).getNode(), 0);
3273           break;
3274         }
3275       }
3276       if (Node->getOpcode() == ISD::MULHS &&
3277           TLI.isOperationLegal(ISD::SMUL_LOHI, VT)) {
3278         Result = SDValue(DAG.getNode(ISD::SMUL_LOHI, VTs, Tmp1, Tmp2).getNode(),
3279                          1);
3280         break;
3281       }
3282       if (Node->getOpcode() == ISD::MULHU && 
3283           TLI.isOperationLegal(ISD::UMUL_LOHI, VT)) {
3284         Result = SDValue(DAG.getNode(ISD::UMUL_LOHI, VTs, Tmp1, Tmp2).getNode(),
3285                          1);
3286         break;
3287       }
3288       if (Node->getOpcode() == ISD::SDIV &&
3289           TLI.isOperationLegal(ISD::SDIVREM, VT)) {
3290         Result = SDValue(DAG.getNode(ISD::SDIVREM, VTs, Tmp1, Tmp2).getNode(),
3291                          0);
3292         break;
3293       }
3294       if (Node->getOpcode() == ISD::UDIV &&
3295           TLI.isOperationLegal(ISD::UDIVREM, VT)) {
3296         Result = SDValue(DAG.getNode(ISD::UDIVREM, VTs, Tmp1, Tmp2).getNode(),
3297                          0);
3298         break;
3299       }
3300       
3301       // Check to see if we have a libcall for this operator.
3302       RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3303       bool isSigned = false;
3304       switch (Node->getOpcode()) {
3305       case ISD::UDIV:
3306       case ISD::SDIV:
3307         if (VT == MVT::i32) {
3308           LC = Node->getOpcode() == ISD::UDIV
3309                ? RTLIB::UDIV_I32 : RTLIB::SDIV_I32;
3310           isSigned = Node->getOpcode() == ISD::SDIV;
3311         }
3312         break;
3313       case ISD::MUL:
3314         if (VT == MVT::i32)
3315           LC = RTLIB::MUL_I32;
3316         break;
3317       case ISD::FPOW:
3318         LC = GetFPLibCall(VT, RTLIB::POW_F32, RTLIB::POW_F64, RTLIB::POW_F80,
3319                           RTLIB::POW_PPCF128);
3320         break;
3321       default: break;
3322       }
3323       if (LC != RTLIB::UNKNOWN_LIBCALL) {
3324         SDValue Dummy;
3325         Result = ExpandLibCall(LC, Node, isSigned, Dummy);
3326         break;
3327       }
3328       
3329       assert(Node->getValueType(0).isVector() &&
3330              "Cannot expand this binary operator!");
3331       // Expand the operation into a bunch of nasty scalar code.
3332       Result = LegalizeOp(UnrollVectorOp(Op));
3333       break;
3334     }
3335     case TargetLowering::Promote: {
3336       switch (Node->getOpcode()) {
3337       default:  assert(0 && "Do not know how to promote this BinOp!");
3338       case ISD::AND:
3339       case ISD::OR:
3340       case ISD::XOR: {
3341         MVT OVT = Node->getValueType(0);
3342         MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3343         assert(OVT.isVector() && "Cannot promote this BinOp!");
3344         // Bit convert each of the values to the new type.
3345         Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
3346         Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
3347         Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3348         // Bit convert the result back the original type.
3349         Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
3350         break;
3351       }
3352       }
3353     }
3354     }
3355     break;
3356     
3357   case ISD::SMUL_LOHI:
3358   case ISD::UMUL_LOHI:
3359   case ISD::SDIVREM:
3360   case ISD::UDIVREM:
3361     // These nodes will only be produced by target-specific lowering, so
3362     // they shouldn't be here if they aren't legal.
3363     assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
3364            "This must be legal!");
3365
3366     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3367     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3368     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3369     break;
3370
3371   case ISD::FCOPYSIGN:  // FCOPYSIGN does not require LHS/RHS to match type!
3372     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3373     switch (getTypeAction(Node->getOperand(1).getValueType())) {
3374       case Expand: assert(0 && "Not possible");
3375       case Legal:
3376         Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
3377         break;
3378       case Promote:
3379         Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
3380         break;
3381     }
3382       
3383     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3384     
3385     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3386     default: assert(0 && "Operation not supported");
3387     case TargetLowering::Custom:
3388       Tmp1 = TLI.LowerOperation(Result, DAG);
3389       if (Tmp1.getNode()) Result = Tmp1;
3390       break;
3391     case TargetLowering::Legal: break;
3392     case TargetLowering::Expand: {
3393       // If this target supports fabs/fneg natively and select is cheap,
3394       // do this efficiently.
3395       if (!TLI.isSelectExpensive() &&
3396           TLI.getOperationAction(ISD::FABS, Tmp1.getValueType()) ==
3397           TargetLowering::Legal &&
3398           TLI.getOperationAction(ISD::FNEG, Tmp1.getValueType()) ==
3399           TargetLowering::Legal) {
3400         // Get the sign bit of the RHS.
3401         MVT IVT =
3402           Tmp2.getValueType() == MVT::f32 ? MVT::i32 : MVT::i64;
3403         SDValue SignBit = DAG.getNode(ISD::BIT_CONVERT, IVT, Tmp2);
3404         SignBit = DAG.getSetCC(TLI.getSetCCResultType(SignBit),
3405                                SignBit, DAG.getConstant(0, IVT), ISD::SETLT);
3406         // Get the absolute value of the result.
3407         SDValue AbsVal = DAG.getNode(ISD::FABS, Tmp1.getValueType(), Tmp1);
3408         // Select between the nabs and abs value based on the sign bit of
3409         // the input.
3410         Result = DAG.getNode(ISD::SELECT, AbsVal.getValueType(), SignBit,
3411                              DAG.getNode(ISD::FNEG, AbsVal.getValueType(), 
3412                                          AbsVal),
3413                              AbsVal);
3414         Result = LegalizeOp(Result);
3415         break;
3416       }
3417       
3418       // Otherwise, do bitwise ops!
3419       MVT NVT =
3420         Node->getValueType(0) == MVT::f32 ? MVT::i32 : MVT::i64;
3421       Result = ExpandFCOPYSIGNToBitwiseOps(Node, NVT, DAG, TLI);
3422       Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), Result);
3423       Result = LegalizeOp(Result);
3424       break;
3425     }
3426     }
3427     break;
3428     
3429   case ISD::ADDC:
3430   case ISD::SUBC:
3431     Tmp1 = LegalizeOp(Node->getOperand(0));
3432     Tmp2 = LegalizeOp(Node->getOperand(1));
3433     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3434     Tmp3 = Result.getValue(0);
3435     Tmp4 = Result.getValue(1);
3436
3437     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3438     default: assert(0 && "This action is not supported yet!");
3439     case TargetLowering::Legal:
3440       break;
3441     case TargetLowering::Custom:
3442       Tmp1 = TLI.LowerOperation(Tmp3, DAG);
3443       if (Tmp1.getNode() != NULL) {
3444         Tmp3 = LegalizeOp(Tmp1);
3445         Tmp4 = LegalizeOp(Tmp1.getValue(1));
3446       }
3447       break;
3448     }
3449     // Since this produces two values, make sure to remember that we legalized
3450     // both of them.
3451     AddLegalizedOperand(SDValue(Node, 0), Tmp3);
3452     AddLegalizedOperand(SDValue(Node, 1), Tmp4);
3453     return Op.getResNo() ? Tmp4 : Tmp3;
3454
3455   case ISD::ADDE:
3456   case ISD::SUBE:
3457     Tmp1 = LegalizeOp(Node->getOperand(0));
3458     Tmp2 = LegalizeOp(Node->getOperand(1));
3459     Tmp3 = LegalizeOp(Node->getOperand(2));
3460     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
3461     Tmp3 = Result.getValue(0);
3462     Tmp4 = Result.getValue(1);
3463
3464     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3465     default: assert(0 && "This action is not supported yet!");
3466     case TargetLowering::Legal:
3467       break;
3468     case TargetLowering::Custom:
3469       Tmp1 = TLI.LowerOperation(Tmp3, DAG);
3470       if (Tmp1.getNode() != NULL) {
3471         Tmp3 = LegalizeOp(Tmp1);
3472         Tmp4 = LegalizeOp(Tmp1.getValue(1));
3473       }
3474       break;
3475     }
3476     // Since this produces two values, make sure to remember that we legalized
3477     // both of them.
3478     AddLegalizedOperand(SDValue(Node, 0), Tmp3);
3479     AddLegalizedOperand(SDValue(Node, 1), Tmp4);
3480     return Op.getResNo() ? Tmp4 : Tmp3;
3481     
3482   case ISD::BUILD_PAIR: {
3483     MVT PairTy = Node->getValueType(0);
3484     // TODO: handle the case where the Lo and Hi operands are not of legal type
3485     Tmp1 = LegalizeOp(Node->getOperand(0));   // Lo
3486     Tmp2 = LegalizeOp(Node->getOperand(1));   // Hi
3487     switch (TLI.getOperationAction(ISD::BUILD_PAIR, PairTy)) {
3488     case TargetLowering::Promote:
3489     case TargetLowering::Custom:
3490       assert(0 && "Cannot promote/custom this yet!");
3491     case TargetLowering::Legal:
3492       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
3493         Result = DAG.getNode(ISD::BUILD_PAIR, PairTy, Tmp1, Tmp2);
3494       break;
3495     case TargetLowering::Expand:
3496       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, PairTy, Tmp1);
3497       Tmp2 = DAG.getNode(ISD::ANY_EXTEND, PairTy, Tmp2);
3498       Tmp2 = DAG.getNode(ISD::SHL, PairTy, Tmp2,
3499                          DAG.getConstant(PairTy.getSizeInBits()/2,
3500                                          TLI.getShiftAmountTy()));
3501       Result = DAG.getNode(ISD::OR, PairTy, Tmp1, Tmp2);
3502       break;
3503     }
3504     break;
3505   }
3506
3507   case ISD::UREM:
3508   case ISD::SREM:
3509   case ISD::FREM:
3510     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3511     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3512
3513     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3514     case TargetLowering::Promote: assert(0 && "Cannot promote this yet!");
3515     case TargetLowering::Custom:
3516       isCustom = true;
3517       // FALLTHROUGH
3518     case TargetLowering::Legal:
3519       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3520       if (isCustom) {
3521         Tmp1 = TLI.LowerOperation(Result, DAG);
3522         if (Tmp1.getNode()) Result = Tmp1;
3523       }
3524       break;
3525     case TargetLowering::Expand: {
3526       unsigned DivOpc= (Node->getOpcode() == ISD::UREM) ? ISD::UDIV : ISD::SDIV;
3527       bool isSigned = DivOpc == ISD::SDIV;
3528       MVT VT = Node->getValueType(0);
3529  
3530       // See if remainder can be lowered using two-result operations.
3531       SDVTList VTs = DAG.getVTList(VT, VT);
3532       if (Node->getOpcode() == ISD::SREM &&
3533           TLI.isOperationLegal(ISD::SDIVREM, VT)) {
3534         Result = SDValue(DAG.getNode(ISD::SDIVREM, VTs, Tmp1, Tmp2).getNode(), 1);
3535         break;
3536       }
3537       if (Node->getOpcode() == ISD::UREM &&
3538           TLI.isOperationLegal(ISD::UDIVREM, VT)) {
3539         Result = SDValue(DAG.getNode(ISD::UDIVREM, VTs, Tmp1, Tmp2).getNode(), 1);
3540         break;
3541       }
3542
3543       if (VT.isInteger()) {
3544         if (TLI.getOperationAction(DivOpc, VT) ==
3545             TargetLowering::Legal) {
3546           // X % Y -> X-X/Y*Y
3547           Result = DAG.getNode(DivOpc, VT, Tmp1, Tmp2);
3548           Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
3549           Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
3550         } else if (VT.isVector()) {
3551           Result = LegalizeOp(UnrollVectorOp(Op));
3552         } else {
3553           assert(VT == MVT::i32 &&
3554                  "Cannot expand this binary operator!");
3555           RTLIB::Libcall LC = Node->getOpcode() == ISD::UREM
3556             ? RTLIB::UREM_I32 : RTLIB::SREM_I32;
3557           SDValue Dummy;
3558           Result = ExpandLibCall(LC, Node, isSigned, Dummy);
3559         }
3560       } else {
3561         assert(VT.isFloatingPoint() &&
3562                "remainder op must have integer or floating-point type");
3563         if (VT.isVector()) {
3564           Result = LegalizeOp(UnrollVectorOp(Op));
3565         } else {
3566           // Floating point mod -> fmod libcall.
3567           RTLIB::Libcall LC = GetFPLibCall(VT, RTLIB::REM_F32, RTLIB::REM_F64,
3568                                            RTLIB::REM_F80, RTLIB::REM_PPCF128);
3569           SDValue Dummy;
3570           Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
3571         }
3572       }
3573       break;
3574     }
3575     }
3576     break;
3577   case ISD::VAARG: {
3578     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3579     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3580
3581     MVT VT = Node->getValueType(0);
3582     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
3583     default: assert(0 && "This action is not supported yet!");
3584     case TargetLowering::Custom:
3585       isCustom = true;
3586       // FALLTHROUGH
3587     case TargetLowering::Legal:
3588       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3589       Result = Result.getValue(0);
3590       Tmp1 = Result.getValue(1);
3591
3592       if (isCustom) {
3593         Tmp2 = TLI.LowerOperation(Result, DAG);
3594         if (Tmp2.getNode()) {
3595           Result = LegalizeOp(Tmp2);
3596           Tmp1 = LegalizeOp(Tmp2.getValue(1));
3597         }
3598       }
3599       break;
3600     case TargetLowering::Expand: {
3601       const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3602       SDValue VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2, V, 0);
3603       // Increment the pointer, VAList, to the next vaarg
3604       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList,
3605         DAG.getConstant(TLI.getTargetData()->getABITypeSize(VT.getTypeForMVT()),
3606                         TLI.getPointerTy()));
3607       // Store the incremented VAList to the legalized pointer
3608       Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Tmp2, V, 0);
3609       // Load the actual argument out of the pointer VAList
3610       Result = DAG.getLoad(VT, Tmp3, VAList, NULL, 0);
3611       Tmp1 = LegalizeOp(Result.getValue(1));
3612       Result = LegalizeOp(Result);
3613       break;
3614     }
3615     }
3616     // Since VAARG produces two values, make sure to remember that we 
3617     // legalized both of them.
3618     AddLegalizedOperand(SDValue(Node, 0), Result);
3619     AddLegalizedOperand(SDValue(Node, 1), Tmp1);
3620     return Op.getResNo() ? Tmp1 : Result;
3621   }
3622     
3623   case ISD::VACOPY: 
3624     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3625     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the dest pointer.
3626     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the source pointer.
3627
3628     switch (TLI.getOperationAction(ISD::VACOPY, MVT::Other)) {
3629     default: assert(0 && "This action is not supported yet!");
3630     case TargetLowering::Custom:
3631       isCustom = true;
3632       // FALLTHROUGH
3633     case TargetLowering::Legal:
3634       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
3635                                       Node->getOperand(3), Node->getOperand(4));
3636       if (isCustom) {
3637         Tmp1 = TLI.LowerOperation(Result, DAG);
3638         if (Tmp1.getNode()) Result = Tmp1;
3639       }
3640       break;
3641     case TargetLowering::Expand:
3642       // This defaults to loading a pointer from the input and storing it to the
3643       // output, returning the chain.
3644       const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
3645       const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
3646       Tmp4 = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp3, VS, 0);
3647       Result = DAG.getStore(Tmp4.getValue(1), Tmp4, Tmp2, VD, 0);
3648       break;
3649     }
3650     break;
3651
3652   case ISD::VAEND: 
3653     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3654     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3655
3656     switch (TLI.getOperationAction(ISD::VAEND, MVT::Other)) {
3657     default: assert(0 && "This action is not supported yet!");
3658     case TargetLowering::Custom:
3659       isCustom = true;
3660       // FALLTHROUGH
3661     case TargetLowering::Legal:
3662       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3663       if (isCustom) {
3664         Tmp1 = TLI.LowerOperation(Tmp1, DAG);
3665         if (Tmp1.getNode()) Result = Tmp1;
3666       }
3667       break;
3668     case TargetLowering::Expand:
3669       Result = Tmp1; // Default to a no-op, return the chain
3670       break;
3671     }
3672     break;
3673     
3674   case ISD::VASTART: 
3675     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3676     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3677
3678     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3679     
3680     switch (TLI.getOperationAction(ISD::VASTART, MVT::Other)) {
3681     default: assert(0 && "This action is not supported yet!");
3682     case TargetLowering::Legal: break;
3683     case TargetLowering::Custom:
3684       Tmp1 = TLI.LowerOperation(Result, DAG);
3685       if (Tmp1.getNode()) Result = Tmp1;
3686       break;
3687     }
3688     break;
3689     
3690   case ISD::ROTL:
3691   case ISD::ROTR:
3692     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3693     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3694     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3695     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3696     default:
3697       assert(0 && "ROTL/ROTR legalize operation not supported");
3698       break;
3699     case TargetLowering::Legal:
3700       break;
3701     case TargetLowering::Custom:
3702       Tmp1 = TLI.LowerOperation(Result, DAG);
3703       if (Tmp1.getNode()) Result = Tmp1;
3704       break;
3705     case TargetLowering::Promote:
3706       assert(0 && "Do not know how to promote ROTL/ROTR");
3707       break;
3708     case TargetLowering::Expand:
3709       assert(0 && "Do not know how to expand ROTL/ROTR");
3710       break;
3711     }
3712     break;
3713     
3714   case ISD::BSWAP:
3715     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
3716     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3717     case TargetLowering::Custom:
3718       assert(0 && "Cannot custom legalize this yet!");
3719     case TargetLowering::Legal:
3720       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3721       break;
3722     case TargetLowering::Promote: {
3723       MVT OVT = Tmp1.getValueType();
3724       MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3725       unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
3726
3727       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
3728       Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
3729       Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
3730                            DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
3731       break;
3732     }
3733     case TargetLowering::Expand:
3734       Result = ExpandBSWAP(Tmp1);
3735       break;
3736     }
3737     break;
3738     
3739   case ISD::CTPOP:
3740   case ISD::CTTZ:
3741   case ISD::CTLZ:
3742     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
3743     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3744     case TargetLowering::Custom:
3745     case TargetLowering::Legal:
3746       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3747       if (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)) ==
3748           TargetLowering::Custom) {
3749         Tmp1 = TLI.LowerOperation(Result, DAG);
3750         if (Tmp1.getNode()) {
3751           Result = Tmp1;
3752         }
3753       }
3754       break;
3755     case TargetLowering::Promote: {
3756       MVT OVT = Tmp1.getValueType();
3757       MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3758
3759       // Zero extend the argument.
3760       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
3761       // Perform the larger operation, then subtract if needed.
3762       Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
3763       switch (Node->getOpcode()) {
3764       case ISD::CTPOP:
3765         Result = Tmp1;
3766         break;
3767       case ISD::CTTZ:
3768         //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3769         Tmp2 = DAG.getSetCC(TLI.getSetCCResultType(Tmp1), Tmp1,
3770                             DAG.getConstant(NVT.getSizeInBits(), NVT),
3771                             ISD::SETEQ);
3772         Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
3773                              DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
3774         break;
3775       case ISD::CTLZ:
3776         // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3777         Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
3778                              DAG.getConstant(NVT.getSizeInBits() -
3779                                              OVT.getSizeInBits(), NVT));
3780         break;
3781       }
3782       break;
3783     }
3784     case TargetLowering::Expand:
3785       Result = ExpandBitCount(Node->getOpcode(), Tmp1);
3786       break;
3787     }
3788     break;
3789
3790     // Unary operators
3791   case ISD::FABS:
3792   case ISD::FNEG:
3793   case ISD::FSQRT:
3794   case ISD::FSIN:
3795   case ISD::FCOS:
3796   case ISD::FLOG:
3797   case ISD::FLOG2:
3798   case ISD::FLOG10:
3799   case ISD::FEXP:
3800   case ISD::FEXP2:
3801   case ISD::FTRUNC:
3802   case ISD::FFLOOR:
3803   case ISD::FCEIL:
3804   case ISD::FRINT:
3805   case ISD::FNEARBYINT:
3806     Tmp1 = LegalizeOp(Node->getOperand(0));
3807     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3808     case TargetLowering::Promote:
3809     case TargetLowering::Custom:
3810      isCustom = true;
3811      // FALLTHROUGH
3812     case TargetLowering::Legal:
3813       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3814       if (isCustom) {
3815         Tmp1 = TLI.LowerOperation(Result, DAG);
3816         if (Tmp1.getNode()) Result = Tmp1;
3817       }
3818       break;
3819     case TargetLowering::Expand:
3820       switch (Node->getOpcode()) {
3821       default: assert(0 && "Unreachable!");
3822       case ISD::FNEG:
3823         // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
3824         Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
3825         Result = DAG.getNode(ISD::FSUB, Node->getValueType(0), Tmp2, Tmp1);
3826         break;
3827       case ISD::FABS: {
3828         // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
3829         MVT VT = Node->getValueType(0);
3830         Tmp2 = DAG.getConstantFP(0.0, VT);
3831         Tmp2 = DAG.getSetCC(TLI.getSetCCResultType(Tmp1), Tmp1, Tmp2,
3832                             ISD::SETUGT);
3833         Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
3834         Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
3835         break;
3836       }
3837       case ISD::FSQRT:
3838       case ISD::FSIN:
3839       case ISD::FCOS: 
3840       case ISD::FLOG:
3841       case ISD::FLOG2:
3842       case ISD::FLOG10:
3843       case ISD::FEXP:
3844       case ISD::FEXP2:
3845       case ISD::FTRUNC:
3846       case ISD::FFLOOR:
3847       case ISD::FCEIL:
3848       case ISD::FRINT:
3849       case ISD::FNEARBYINT: {
3850         MVT VT = Node->getValueType(0);
3851
3852         // Expand unsupported unary vector operators by unrolling them.
3853         if (VT.isVector()) {
3854           Result = LegalizeOp(UnrollVectorOp(Op));
3855           break;
3856         }
3857
3858         RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3859         switch(Node->getOpcode()) {
3860         case ISD::FSQRT:
3861           LC = GetFPLibCall(VT, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
3862                             RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128);
3863           break;
3864         case ISD::FSIN:
3865           LC = GetFPLibCall(VT, RTLIB::SIN_F32, RTLIB::SIN_F64,
3866                             RTLIB::SIN_F80, RTLIB::SIN_PPCF128);
3867           break;
3868         case ISD::FCOS:
3869           LC = GetFPLibCall(VT, RTLIB::COS_F32, RTLIB::COS_F64,
3870                             RTLIB::COS_F80, RTLIB::COS_PPCF128);
3871           break;
3872         case ISD::FLOG:
3873           LC = GetFPLibCall(VT, RTLIB::LOG_F32, RTLIB::LOG_F64,
3874                             RTLIB::LOG_F80, RTLIB::LOG_PPCF128);
3875           break;
3876         case ISD::FLOG2:
3877           LC = GetFPLibCall(VT, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
3878                             RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128);
3879           break;
3880         case ISD::FLOG10:
3881           LC = GetFPLibCall(VT, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
3882                             RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128);
3883           break;
3884         case ISD::FEXP:
3885           LC = GetFPLibCall(VT, RTLIB::EXP_F32, RTLIB::EXP_F64,
3886                             RTLIB::EXP_F80, RTLIB::EXP_PPCF128);
3887           break;
3888         case ISD::FEXP2:
3889           LC = GetFPLibCall(VT, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
3890                             RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128);
3891           break;
3892         case ISD::FTRUNC:
3893           LC = GetFPLibCall(VT, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
3894                             RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128);
3895           break;
3896         case ISD::FFLOOR:
3897           LC = GetFPLibCall(VT, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
3898                             RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128);
3899           break;
3900         case ISD::FCEIL:
3901           LC = GetFPLibCall(VT, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
3902                             RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128);
3903           break;
3904         case ISD::FRINT:
3905           LC = GetFPLibCall(VT, RTLIB::RINT_F32, RTLIB::RINT_F64,
3906                             RTLIB::RINT_F80, RTLIB::RINT_PPCF128);
3907           break;
3908         case ISD::FNEARBYINT:
3909           LC = GetFPLibCall(VT, RTLIB::NEARBYINT_F32, RTLIB::NEARBYINT_F64,
3910                             RTLIB::NEARBYINT_F80, RTLIB::NEARBYINT_PPCF128);
3911           break;
3912       break;
3913         default: assert(0 && "Unreachable!");
3914         }
3915         SDValue Dummy;
3916         Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
3917         break;
3918       }
3919       }
3920       break;
3921     }
3922     break;
3923   case ISD::FPOWI: {
3924     MVT VT = Node->getValueType(0);
3925
3926     // Expand unsupported unary vector operators by unrolling them.
3927     if (VT.isVector()) {
3928       Result = LegalizeOp(UnrollVectorOp(Op));
3929       break;
3930     }
3931
3932     // We always lower FPOWI into a libcall.  No target support for it yet.
3933     RTLIB::Libcall LC = GetFPLibCall(VT, RTLIB::POWI_F32, RTLIB::POWI_F64,
3934                                      RTLIB::POWI_F80, RTLIB::POWI_PPCF128);
3935     SDValue Dummy;
3936     Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
3937     break;
3938   }
3939   case ISD::BIT_CONVERT:
3940     if (!isTypeLegal(Node->getOperand(0).getValueType())) {
3941       Result = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
3942                                 Node->getValueType(0));
3943     } else if (Op.getOperand(0).getValueType().isVector()) {
3944       // The input has to be a vector type, we have to either scalarize it, pack
3945       // it, or convert it based on whether the input vector type is legal.
3946       SDNode *InVal = Node->getOperand(0).getNode();
3947       int InIx = Node->getOperand(0).getResNo();
3948       unsigned NumElems = InVal->getValueType(InIx).getVectorNumElements();
3949       MVT EVT = InVal->getValueType(InIx).getVectorElementType();
3950     
3951       // Figure out if there is a simple type corresponding to this Vector
3952       // type.  If so, convert to the vector type.
3953       MVT TVT = MVT::getVectorVT(EVT, NumElems);
3954       if (TLI.isTypeLegal(TVT)) {
3955         // Turn this into a bit convert of the vector input.
3956         Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), 
3957                              LegalizeOp(Node->getOperand(0)));
3958         break;
3959       } else if (NumElems == 1) {
3960         // Turn this into a bit convert of the scalar input.
3961         Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), 
3962                              ScalarizeVectorOp(Node->getOperand(0)));
3963         break;
3964       } else {
3965         // FIXME: UNIMP!  Store then reload
3966         assert(0 && "Cast from unsupported vector type not implemented yet!");
3967       }
3968     } else {
3969       switch (TLI.getOperationAction(ISD::BIT_CONVERT,
3970                                      Node->getOperand(0).getValueType())) {
3971       default: assert(0 && "Unknown operation action!");
3972       case TargetLowering::Expand:
3973         Result = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
3974                                   Node->getValueType(0));
3975         break;
3976       case TargetLowering::Legal:
3977         Tmp1 = LegalizeOp(Node->getOperand(0));
3978         Result = DAG.UpdateNodeOperands(Result, Tmp1);
3979         break;
3980       }
3981     }
3982     break;
3983   case ISD::CONVERT_RNDSAT: {
3984     ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(Node)->getCvtCode();
3985     switch (CvtCode) {
3986     default: assert(0 && "Unknown cvt code!");
3987     case ISD::CVT_SF:
3988     case ISD::CVT_UF:
3989     case ISD::CVT_FF:
3990       break;
3991     case ISD::CVT_FS:
3992     case ISD::CVT_FU:
3993     case ISD::CVT_SS:
3994     case ISD::CVT_SU:
3995     case ISD::CVT_US:
3996     case ISD::CVT_UU: {
3997       SDValue DTyOp = Node->getOperand(1);
3998       SDValue STyOp = Node->getOperand(2);
3999       SDValue RndOp = Node->getOperand(3);
4000       SDValue SatOp = Node->getOperand(4);
4001       switch (getTypeAction(Node->getOperand(0).getValueType())) {
4002       case Expand: assert(0 && "Shouldn't need to expand other operators here!");
4003       case Legal:
4004         Tmp1 = LegalizeOp(Node->getOperand(0));
4005         Result = DAG.UpdateNodeOperands(Result, Tmp1, DTyOp, STyOp,
4006                                         RndOp, SatOp);
4007         if (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)) ==
4008             TargetLowering::Custom) {
4009           Tmp1 = TLI.LowerOperation(Result, DAG);
4010           if (Tmp1.getNode()) Result = Tmp1;
4011         }
4012         break;
4013       case Promote:
4014         Result = PromoteOp(Node->getOperand(0));
4015         // For FP, make Op1 a i32
4016         
4017         Result = DAG.getConvertRndSat(Op.getValueType(), Result,
4018                                       DTyOp, STyOp, RndOp, SatOp, CvtCode);
4019         break;
4020       }
4021       break;
4022     }
4023     } // end switch CvtCode
4024     break;
4025   }
4026     // Conversion operators.  The source and destination have different types.
4027   case ISD::SINT_TO_FP:
4028   case ISD::UINT_TO_FP: {
4029     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
4030     Result = LegalizeINT_TO_FP(Result, isSigned,
4031                                Node->getValueType(0), Node->getOperand(0));
4032     break;
4033   }
4034   case ISD::TRUNCATE:
4035     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4036     case Legal:
4037       Tmp1 = LegalizeOp(Node->getOperand(0));
4038       switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
4039       default: assert(0 && "Unknown TRUNCATE legalization operation action!");
4040       case TargetLowering::Custom:
4041         isCustom = true;
4042         // FALLTHROUGH
4043       case TargetLowering::Legal:
4044         Result = DAG.UpdateNodeOperands(Result, Tmp1);
4045         if (isCustom) {
4046           Tmp1 = TLI.LowerOperation(Result, DAG);
4047           if (Tmp1.getNode()) Result = Tmp1;
4048         }
4049         break;
4050       case TargetLowering::Expand:
4051         assert(Result.getValueType().isVector() && "must be vector type");
4052         // Unroll the truncate.  We should do better.
4053         Result = LegalizeOp(UnrollVectorOp(Result));
4054       }
4055       break;
4056     case Expand:
4057       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
4058
4059       // Since the result is legal, we should just be able to truncate the low
4060       // part of the source.
4061       Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
4062       break;
4063     case Promote:
4064       Result = PromoteOp(Node->getOperand(0));
4065       Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
4066       break;
4067     }
4068     break;
4069
4070   case ISD::FP_TO_SINT:
4071   case ISD::FP_TO_UINT:
4072     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4073     case Legal:
4074       Tmp1 = LegalizeOp(Node->getOperand(0));
4075
4076       switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
4077       default: assert(0 && "Unknown operation action!");
4078       case TargetLowering::Custom:
4079         isCustom = true;
4080         // FALLTHROUGH
4081       case TargetLowering::Legal:
4082         Result = DAG.UpdateNodeOperands(Result, Tmp1);
4083         if (isCustom) {
4084           Tmp1 = TLI.LowerOperation(Result, DAG);
4085           if (Tmp1.getNode()) Result = Tmp1;
4086         }
4087         break;
4088       case TargetLowering::Promote:
4089         Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
4090                                        Node->getOpcode() == ISD::FP_TO_SINT);
4091         break;
4092       case TargetLowering::Expand:
4093         if (Node->getOpcode() == ISD::FP_TO_UINT) {
4094           SDValue True, False;
4095           MVT VT =  Node->getOperand(0).getValueType();
4096           MVT NVT = Node->getValueType(0);
4097           const uint64_t zero[] = {0, 0};
4098           APFloat apf = APFloat(APInt(VT.getSizeInBits(), 2, zero));
4099           APInt x = APInt::getSignBit(NVT.getSizeInBits());
4100           (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
4101           Tmp2 = DAG.getConstantFP(apf, VT);
4102           Tmp3 = DAG.getSetCC(TLI.getSetCCResultType(Node->getOperand(0)),
4103                             Node->getOperand(0), Tmp2, ISD::SETLT);
4104           True = DAG.getNode(ISD::FP_TO_SINT, NVT, Node->getOperand(0));
4105           False = DAG.getNode(ISD::FP_TO_SINT, NVT,
4106                               DAG.getNode(ISD::FSUB, VT, Node->getOperand(0),
4107                                           Tmp2));
4108           False = DAG.getNode(ISD::XOR, NVT, False, 
4109                               DAG.getConstant(x, NVT));
4110           Result = DAG.getNode(ISD::SELECT, NVT, Tmp3, True, False);
4111           break;
4112         } else {
4113           assert(0 && "Do not know how to expand FP_TO_SINT yet!");
4114         }
4115         break;
4116       }
4117       break;
4118     case Expand: {
4119       MVT VT = Op.getValueType();
4120       MVT OVT = Node->getOperand(0).getValueType();
4121       // Convert ppcf128 to i32
4122       if (OVT == MVT::ppcf128 && VT == MVT::i32) {
4123         if (Node->getOpcode() == ISD::FP_TO_SINT) {
4124           Result = DAG.getNode(ISD::FP_ROUND_INREG, MVT::ppcf128, 
4125                                Node->getOperand(0), DAG.getValueType(MVT::f64));
4126           Result = DAG.getNode(ISD::FP_ROUND, MVT::f64, Result, 
4127                                DAG.getIntPtrConstant(1));
4128           Result = DAG.getNode(ISD::FP_TO_SINT, VT, Result);
4129         } else {
4130           const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
4131           APFloat apf = APFloat(APInt(128, 2, TwoE31));
4132           Tmp2 = DAG.getConstantFP(apf, OVT);
4133           //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
4134           // FIXME: generated code sucks.
4135           Result = DAG.getNode(ISD::SELECT_CC, VT, Node->getOperand(0), Tmp2,
4136                                DAG.getNode(ISD::ADD, MVT::i32,
4137                                  DAG.getNode(ISD::FP_TO_SINT, VT,
4138                                    DAG.getNode(ISD::FSUB, OVT,
4139                                                  Node->getOperand(0), Tmp2)),
4140                                  DAG.getConstant(0x80000000, MVT::i32)),
4141                                DAG.getNode(ISD::FP_TO_SINT, VT, 
4142                                            Node->getOperand(0)),
4143                                DAG.getCondCode(ISD::SETGE));
4144         }
4145         break;
4146       }
4147       // Convert f32 / f64 to i32 / i64 / i128.
4148       RTLIB::Libcall LC = (Node->getOpcode() == ISD::FP_TO_SINT) ?
4149         RTLIB::getFPTOSINT(OVT, VT) : RTLIB::getFPTOUINT(OVT, VT);
4150       assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpectd fp-to-int conversion!");
4151       SDValue Dummy;
4152       Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
4153       break;
4154     }
4155     case Promote:
4156       Tmp1 = PromoteOp(Node->getOperand(0));
4157       Result = DAG.UpdateNodeOperands(Result, LegalizeOp(Tmp1));
4158       Result = LegalizeOp(Result);
4159       break;
4160     }
4161     break;
4162
4163   case ISD::FP_EXTEND: {
4164     MVT DstVT = Op.getValueType();
4165     MVT SrcVT = Op.getOperand(0).getValueType();
4166     if (TLI.getConvertAction(SrcVT, DstVT) == TargetLowering::Expand) {
4167       // The only other way we can lower this is to turn it into a STORE,
4168       // LOAD pair, targetting a temporary location (a stack slot).
4169       Result = EmitStackConvert(Node->getOperand(0), SrcVT, DstVT);
4170       break;
4171     }
4172     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4173     case Expand: assert(0 && "Shouldn't need to expand other operators here!");
4174     case Legal:
4175       Tmp1 = LegalizeOp(Node->getOperand(0));
4176       Result = DAG.UpdateNodeOperands(Result, Tmp1);
4177       break;
4178     case Promote:
4179       Tmp1 = PromoteOp(Node->getOperand(0));
4180       Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Tmp1);
4181       break;
4182     }
4183     break;
4184   }
4185   case ISD::FP_ROUND: {
4186     MVT DstVT = Op.getValueType();
4187     MVT SrcVT = Op.getOperand(0).getValueType();
4188     if (TLI.getConvertAction(SrcVT, DstVT) == TargetLowering::Expand) {
4189       if (SrcVT == MVT::ppcf128) {
4190         SDValue Lo;
4191         ExpandOp(Node->getOperand(0), Lo, Result);
4192         // Round it the rest of the way (e.g. to f32) if needed.
4193         if (DstVT!=MVT::f64)
4194           Result = DAG.getNode(ISD::FP_ROUND, DstVT, Result, Op.getOperand(1));
4195         break;
4196       }
4197       // The only other way we can lower this is to turn it into a STORE,
4198       // LOAD pair, targetting a temporary location (a stack slot).
4199       Result = EmitStackConvert(Node->getOperand(0), DstVT, DstVT);
4200       break;
4201     }
4202     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4203     case Expand: assert(0 && "Shouldn't need to expand other operators here!");
4204     case Legal:
4205       Tmp1 = LegalizeOp(Node->getOperand(0));
4206       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
4207       break;
4208     case Promote:
4209       Tmp1 = PromoteOp(Node->getOperand(0));
4210       Result = DAG.getNode(ISD::FP_ROUND, Op.getValueType(), Tmp1,
4211                            Node->getOperand(1));
4212       break;
4213     }
4214     break;
4215   }
4216   case ISD::ANY_EXTEND:
4217   case ISD::ZERO_EXTEND:
4218   case ISD::SIGN_EXTEND:
4219     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4220     case Expand: assert(0 && "Shouldn't need to expand other operators here!");
4221     case Legal:
4222       Tmp1 = LegalizeOp(Node->getOperand(0));
4223       Result = DAG.UpdateNodeOperands(Result, Tmp1);
4224       if (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)) ==
4225           TargetLowering::Custom) {
4226         Tmp1 = TLI.LowerOperation(Result, DAG);
4227         if (Tmp1.getNode()) Result = Tmp1;
4228       }
4229       break;
4230     case Promote:
4231       switch (Node->getOpcode()) {
4232       case ISD::ANY_EXTEND:
4233         Tmp1 = PromoteOp(Node->getOperand(0));
4234         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Tmp1);
4235         break;
4236       case ISD::ZERO_EXTEND:
4237         Result = PromoteOp(Node->getOperand(0));
4238         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
4239         Result = DAG.getZeroExtendInReg(Result,
4240                                         Node->getOperand(0).getValueType());
4241         break;
4242       case ISD::SIGN_EXTEND:
4243         Result = PromoteOp(Node->getOperand(0));
4244         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
4245         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
4246                              Result,
4247                           DAG.getValueType(Node->getOperand(0).getValueType()));
4248         break;
4249       }
4250     }
4251     break;
4252   case ISD::FP_ROUND_INREG:
4253   case ISD::SIGN_EXTEND_INREG: {
4254     Tmp1 = LegalizeOp(Node->getOperand(0));
4255     MVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
4256
4257     // If this operation is not supported, convert it to a shl/shr or load/store
4258     // pair.
4259     switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
4260     default: assert(0 && "This action not supported for this op yet!");
4261     case TargetLowering::Legal:
4262       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
4263       break;
4264     case TargetLowering::Expand:
4265       // If this is an integer extend and shifts are supported, do that.
4266       if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
4267         // NOTE: we could fall back on load/store here too for targets without
4268         // SAR.  However, it is doubtful that any exist.
4269         unsigned BitsDiff = Node->getValueType(0).getSizeInBits() -
4270                             ExtraVT.getSizeInBits();
4271         SDValue ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
4272         Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
4273                              Node->getOperand(0), ShiftCst);
4274         Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
4275                              Result, ShiftCst);
4276       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
4277         // The only way we can lower this is to turn it into a TRUNCSTORE,
4278         // EXTLOAD pair, targetting a temporary location (a stack slot).
4279
4280         // NOTE: there is a choice here between constantly creating new stack
4281         // slots and always reusing the same one.  We currently always create
4282         // new ones, as reuse may inhibit scheduling.
4283         Result = EmitStackConvert(Node->getOperand(0), ExtraVT, 
4284                                   Node->getValueType(0));
4285       } else {
4286         assert(0 && "Unknown op");
4287       }
4288       break;
4289     }
4290     break;
4291   }
4292   case ISD::TRAMPOLINE: {
4293     SDValue Ops[6];
4294     for (unsigned i = 0; i != 6; ++i)
4295       Ops[i] = LegalizeOp(Node->getOperand(i));
4296     Result = DAG.UpdateNodeOperands(Result, Ops, 6);
4297     // The only option for this node is to custom lower it.
4298     Result = TLI.LowerOperation(Result, DAG);
4299     assert(Result.getNode() && "Should always custom lower!");
4300
4301     // Since trampoline produces two values, make sure to remember that we
4302     // legalized both of them.
4303     Tmp1 = LegalizeOp(Result.getValue(1));
4304     Result = LegalizeOp(Result);
4305     AddLegalizedOperand(SDValue(Node, 0), Result);
4306     AddLegalizedOperand(SDValue(Node, 1), Tmp1);
4307     return Op.getResNo() ? Tmp1 : Result;
4308   }
4309   case ISD::FLT_ROUNDS_: {
4310     MVT VT = Node->getValueType(0);
4311     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4312     default: assert(0 && "This action not supported for this op yet!");
4313     case TargetLowering::Custom:
4314       Result = TLI.LowerOperation(Op, DAG);
4315       if (Result.getNode()) break;
4316       // Fall Thru
4317     case TargetLowering::Legal:
4318       // If this operation is not supported, lower it to constant 1
4319       Result = DAG.getConstant(1, VT);
4320       break;
4321     }
4322     break;
4323   }
4324   case ISD::TRAP: {
4325     MVT VT = Node->getValueType(0);
4326     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4327     default: assert(0 && "This action not supported for this op yet!");
4328     case TargetLowering::Legal:
4329       Tmp1 = LegalizeOp(Node->getOperand(0));
4330       Result = DAG.UpdateNodeOperands(Result, Tmp1);
4331       break;
4332     case TargetLowering::Custom:
4333       Result = TLI.LowerOperation(Op, DAG);
4334       if (Result.getNode()) break;
4335       // Fall Thru
4336     case TargetLowering::Expand:
4337       // If this operation is not supported, lower it to 'abort()' call
4338       Tmp1 = LegalizeOp(Node->getOperand(0));
4339       TargetLowering::ArgListTy Args;
4340       std::pair<SDValue,SDValue> CallResult =
4341         TLI.LowerCallTo(Tmp1, Type::VoidTy,
4342                         false, false, false, false, CallingConv::C, false,
4343                         DAG.getExternalSymbol("abort", TLI.getPointerTy()),
4344                         Args, DAG);
4345       Result = CallResult.second;
4346       break;
4347     }
4348     break;
4349   }
4350
4351   case ISD::SADDO:
4352   case ISD::SSUBO: {
4353     MVT VT = Node->getValueType(0);
4354     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4355     default: assert(0 && "This action not supported for this op yet!");
4356     case TargetLowering::Custom:
4357       Result = TLI.LowerOperation(Op, DAG);
4358       if (Result.getNode()) break;
4359       // FALLTHROUGH
4360     case TargetLowering::Legal: {
4361       SDValue LHS = LegalizeOp(Node->getOperand(0));
4362       SDValue RHS = LegalizeOp(Node->getOperand(1));
4363
4364       SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ? 
4365                                 ISD::ADD : ISD::SUB, LHS.getValueType(),
4366                                 LHS, RHS);
4367       MVT OType = Node->getValueType(1);
4368
4369       SDValue Zero = DAG.getConstant(0, LHS.getValueType());
4370
4371       //   LHSSign -> LHS >= 0
4372       //   RHSSign -> RHS >= 0
4373       //   SumSign -> Sum >= 0
4374       //
4375       //   Add:
4376       //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
4377       //   Sub:
4378       //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
4379       //
4380       SDValue LHSSign = DAG.getSetCC(OType, LHS, Zero, ISD::SETGE);
4381       SDValue RHSSign = DAG.getSetCC(OType, RHS, Zero, ISD::SETGE);
4382       SDValue SignsMatch = DAG.getSetCC(OType, LHSSign, RHSSign, 
4383                                         Node->getOpcode() == ISD::SADDO ? 
4384                                         ISD::SETEQ : ISD::SETNE);
4385
4386       SDValue SumSign = DAG.getSetCC(OType, Sum, Zero, ISD::SETGE);
4387       SDValue SumSignNE = DAG.getSetCC(OType, LHSSign, SumSign, ISD::SETNE);
4388
4389       SDValue Cmp = DAG.getNode(ISD::AND, OType, SignsMatch, SumSignNE);
4390
4391       MVT ValueVTs[] = { LHS.getValueType(), OType };
4392       SDValue Ops[] = { Sum, Cmp };
4393
4394       Result = DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(&ValueVTs[0], 2),
4395                            &Ops[0], 2);
4396       SDNode *RNode = Result.getNode();
4397       DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), SDValue(RNode, 0));
4398       DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(RNode, 1));
4399       break;
4400     }
4401     }
4402
4403     break;
4404   }
4405   case ISD::UADDO:
4406   case ISD::USUBO: {
4407     MVT VT = Node->getValueType(0);
4408     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4409     default: assert(0 && "This action not supported for this op yet!");
4410     case TargetLowering::Custom:
4411       Result = TLI.LowerOperation(Op, DAG);
4412       if (Result.getNode()) break;
4413       // FALLTHROUGH
4414     case TargetLowering::Legal: {
4415       SDValue LHS = LegalizeOp(Node->getOperand(0));
4416       SDValue RHS = LegalizeOp(Node->getOperand(1));
4417
4418       SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
4419                                 ISD::ADD : ISD::SUB, LHS.getValueType(),
4420                                 LHS, RHS);
4421       MVT OType = Node->getValueType(1);
4422       SDValue Cmp = DAG.getSetCC(OType, Sum, LHS,
4423                                  Node->getOpcode () == ISD::UADDO ? 
4424                                  ISD::SETULT : ISD::SETUGT);
4425
4426       MVT ValueVTs[] = { LHS.getValueType(), OType };
4427       SDValue Ops[] = { Sum, Cmp };
4428
4429       Result = DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(&ValueVTs[0], 2),
4430                            &Ops[0], 2);
4431       SDNode *RNode = Result.getNode();
4432       DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), SDValue(RNode, 0));
4433       DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(RNode, 1));
4434       break;
4435     }
4436     }
4437
4438     break;
4439   }
4440   case ISD::SMULO:
4441   case ISD::UMULO: {
4442     MVT VT = Node->getValueType(0);
4443     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4444     default: assert(0 && "This action is not supported at all!");
4445     case TargetLowering::Custom:
4446       Result = TLI.LowerOperation(Op, DAG);
4447       if (Result.getNode()) break;
4448       // Fall Thru
4449     case TargetLowering::Legal:
4450       // FIXME: According to Hacker's Delight, this can be implemented in
4451       // target independent lowering, but it would be inefficient, since it
4452       // requires a division + a branch.
4453       assert(0 && "Target independent lowering is not supported for SMULO/UMULO!");     
4454     break;
4455     }
4456     break;
4457   }
4458
4459   }
4460   
4461   assert(Result.getValueType() == Op.getValueType() &&
4462          "Bad legalization!");
4463   
4464   // Make sure that the generated code is itself legal.
4465   if (Result != Op)
4466     Result = LegalizeOp(Result);
4467
4468   // Note that LegalizeOp may be reentered even from single-use nodes, which
4469   // means that we always must cache transformed nodes.
4470   AddLegalizedOperand(Op, Result);
4471   return Result;
4472 }
4473
4474 /// PromoteOp - Given an operation that produces a value in an invalid type,
4475 /// promote it to compute the value into a larger type.  The produced value will
4476 /// have the correct bits for the low portion of the register, but no guarantee
4477 /// is made about the top bits: it may be zero, sign-extended, or garbage.
4478 SDValue SelectionDAGLegalize::PromoteOp(SDValue Op) {
4479   MVT VT = Op.getValueType();
4480   MVT NVT = TLI.getTypeToTransformTo(VT);
4481   assert(getTypeAction(VT) == Promote &&
4482          "Caller should expand or legalize operands that are not promotable!");
4483   assert(NVT.bitsGT(VT) && NVT.isInteger() == VT.isInteger() &&
4484          "Cannot promote to smaller type!");
4485
4486   SDValue Tmp1, Tmp2, Tmp3;
4487   SDValue Result;
4488   SDNode *Node = Op.getNode();
4489
4490   DenseMap<SDValue, SDValue>::iterator I = PromotedNodes.find(Op);
4491   if (I != PromotedNodes.end()) return I->second;
4492
4493   switch (Node->getOpcode()) {
4494   case ISD::CopyFromReg:
4495     assert(0 && "CopyFromReg must be legal!");
4496   default:
4497 #ifndef NDEBUG
4498     cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
4499 #endif
4500     assert(0 && "Do not know how to promote this operator!");
4501     abort();
4502   case ISD::UNDEF:
4503     Result = DAG.getNode(ISD::UNDEF, NVT);
4504     break;
4505   case ISD::Constant:
4506     if (VT != MVT::i1)
4507       Result = DAG.getNode(ISD::SIGN_EXTEND, NVT, Op);
4508     else
4509       Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
4510     assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
4511     break;
4512   case ISD::ConstantFP:
4513     Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
4514     assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
4515     break;
4516
4517   case ISD::SETCC:
4518     assert(isTypeLegal(TLI.getSetCCResultType(Node->getOperand(0)))
4519            && "SetCC type is not legal??");
4520     Result = DAG.getNode(ISD::SETCC,
4521                          TLI.getSetCCResultType(Node->getOperand(0)),
4522                          Node->getOperand(0), Node->getOperand(1),
4523                          Node->getOperand(2));
4524     break;
4525     
4526   case ISD::TRUNCATE:
4527     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4528     case Legal:
4529       Result = LegalizeOp(Node->getOperand(0));
4530       assert(Result.getValueType().bitsGE(NVT) &&
4531              "This truncation doesn't make sense!");
4532       if (Result.getValueType().bitsGT(NVT))    // Truncate to NVT instead of VT
4533         Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
4534       break;
4535     case Promote:
4536       // The truncation is not required, because we don't guarantee anything
4537       // about high bits anyway.
4538       Result = PromoteOp(Node->getOperand(0));
4539       break;
4540     case Expand:
4541       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
4542       // Truncate the low part of the expanded value to the result type
4543       Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
4544     }
4545     break;
4546   case ISD::SIGN_EXTEND:
4547   case ISD::ZERO_EXTEND:
4548   case ISD::ANY_EXTEND:
4549     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4550     case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
4551     case Legal:
4552       // Input is legal?  Just do extend all the way to the larger type.
4553       Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
4554       break;
4555     case Promote:
4556       // Promote the reg if it's smaller.
4557       Result = PromoteOp(Node->getOperand(0));
4558       // The high bits are not guaranteed to be anything.  Insert an extend.
4559       if (Node->getOpcode() == ISD::SIGN_EXTEND)
4560         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
4561                          DAG.getValueType(Node->getOperand(0).getValueType()));
4562       else if (Node->getOpcode() == ISD::ZERO_EXTEND)
4563         Result = DAG.getZeroExtendInReg(Result,
4564                                         Node->getOperand(0).getValueType());
4565       break;
4566     }
4567     break;
4568   case ISD::CONVERT_RNDSAT: {
4569     ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(Node)->getCvtCode();
4570     assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
4571              CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
4572              CvtCode == ISD::CVT_SF || CvtCode == ISD::CVT_UF) &&
4573             "can only promote integers");
4574     Result = DAG.getConvertRndSat(NVT, Node->getOperand(0),
4575                                   Node->getOperand(1), Node->getOperand(2),
4576                                   Node->getOperand(3), Node->getOperand(4),
4577                                   CvtCode);
4578     break;
4579
4580   }
4581   case ISD::BIT_CONVERT:
4582     Result = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
4583                               Node->getValueType(0));
4584     Result = PromoteOp(Result);
4585     break;
4586     
4587   case ISD::FP_EXTEND:
4588     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
4589   case ISD::FP_ROUND:
4590     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4591     case Expand: assert(0 && "BUG: Cannot expand FP regs!");
4592     case Promote:  assert(0 && "Unreachable with 2 FP types!");
4593     case Legal:
4594       if (Node->getConstantOperandVal(1) == 0) {
4595         // Input is legal?  Do an FP_ROUND_INREG.
4596         Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Node->getOperand(0),
4597                              DAG.getValueType(VT));
4598       } else {
4599         // Just remove the truncate, it isn't affecting the value.
4600         Result = DAG.getNode(ISD::FP_ROUND, NVT, Node->getOperand(0), 
4601                              Node->getOperand(1));
4602       }
4603       break;
4604     }
4605     break;
4606   case ISD::SINT_TO_FP:
4607   case ISD::UINT_TO_FP:
4608     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4609     case Legal:
4610       // No extra round required here.
4611       Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
4612       break;
4613
4614     case Promote:
4615       Result = PromoteOp(Node->getOperand(0));
4616       if (Node->getOpcode() == ISD::SINT_TO_FP)
4617         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
4618                              Result,
4619                          DAG.getValueType(Node->getOperand(0).getValueType()));
4620       else
4621         Result = DAG.getZeroExtendInReg(Result,
4622                                         Node->getOperand(0).getValueType());
4623       // No extra round required here.
4624       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
4625       break;
4626     case Expand:
4627       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
4628                              Node->getOperand(0));
4629       // Round if we cannot tolerate excess precision.
4630       if (NoExcessFPPrecision)
4631         Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4632                              DAG.getValueType(VT));
4633       break;
4634     }
4635     break;
4636
4637   case ISD::SIGN_EXTEND_INREG:
4638     Result = PromoteOp(Node->getOperand(0));
4639     Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result, 
4640                          Node->getOperand(1));
4641     break;
4642   case ISD::FP_TO_SINT:
4643   case ISD::FP_TO_UINT:
4644     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4645     case Legal:
4646     case Expand:
4647       Tmp1 = Node->getOperand(0);
4648       break;
4649     case Promote:
4650       // The input result is prerounded, so we don't have to do anything
4651       // special.
4652       Tmp1 = PromoteOp(Node->getOperand(0));
4653       break;
4654     }
4655     // If we're promoting a UINT to a larger size, check to see if the new node
4656     // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
4657     // we can use that instead.  This allows us to generate better code for
4658     // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
4659     // legal, such as PowerPC.
4660     if (Node->getOpcode() == ISD::FP_TO_UINT && 
4661         !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
4662         (TLI.isOperationLegal(ISD::FP_TO_SINT, NVT) ||
4663          TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
4664       Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
4665     } else {
4666       Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4667     }
4668     break;
4669
4670   case ISD::FABS:
4671   case ISD::FNEG:
4672     Tmp1 = PromoteOp(Node->getOperand(0));
4673     assert(Tmp1.getValueType() == NVT);
4674     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4675     // NOTE: we do not have to do any extra rounding here for
4676     // NoExcessFPPrecision, because we know the input will have the appropriate
4677     // precision, and these operations don't modify precision at all.
4678     break;
4679
4680   case ISD::FLOG:
4681   case ISD::FLOG2:
4682   case ISD::FLOG10:
4683   case ISD::FEXP:
4684   case ISD::FEXP2:
4685   case ISD::FSQRT:
4686   case ISD::FSIN:
4687   case ISD::FCOS:
4688   case ISD::FTRUNC:
4689   case ISD::FFLOOR:
4690   case ISD::FCEIL:
4691   case ISD::FRINT:
4692   case ISD::FNEARBYINT:
4693     Tmp1 = PromoteOp(Node->getOperand(0));
4694     assert(Tmp1.getValueType() == NVT);
4695     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4696     if (NoExcessFPPrecision)
4697       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4698                            DAG.getValueType(VT));
4699     break;
4700
4701   case ISD::FPOW:
4702   case ISD::FPOWI: {
4703     // Promote f32 pow(i) to f64 pow(i).  Note that this could insert a libcall
4704     // directly as well, which may be better.
4705     Tmp1 = PromoteOp(Node->getOperand(0));
4706     Tmp2 = Node->getOperand(1);
4707     if (Node->getOpcode() == ISD::FPOW)
4708       Tmp2 = PromoteOp(Tmp2);
4709     assert(Tmp1.getValueType() == NVT);
4710     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4711     if (NoExcessFPPrecision)
4712       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4713                            DAG.getValueType(VT));
4714     break;
4715   }
4716     
4717   case ISD::ATOMIC_CMP_SWAP_8:
4718   case ISD::ATOMIC_CMP_SWAP_16:
4719   case ISD::ATOMIC_CMP_SWAP_32:
4720   case ISD::ATOMIC_CMP_SWAP_64: {
4721     AtomicSDNode* AtomNode = cast<AtomicSDNode>(Node);
4722     Tmp2 = PromoteOp(Node->getOperand(2));
4723     Tmp3 = PromoteOp(Node->getOperand(3));
4724     Result = DAG.getAtomic(Node->getOpcode(), AtomNode->getChain(), 
4725                            AtomNode->getBasePtr(), Tmp2, Tmp3,
4726                            AtomNode->getSrcValue(),
4727                            AtomNode->getAlignment());
4728     // Remember that we legalized the chain.
4729     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4730     break;
4731   }
4732   case ISD::ATOMIC_LOAD_ADD_8:
4733   case ISD::ATOMIC_LOAD_SUB_8:
4734   case ISD::ATOMIC_LOAD_AND_8:
4735   case ISD::ATOMIC_LOAD_OR_8:
4736   case ISD::ATOMIC_LOAD_XOR_8:
4737   case ISD::ATOMIC_LOAD_NAND_8:
4738   case ISD::ATOMIC_LOAD_MIN_8:
4739   case ISD::ATOMIC_LOAD_MAX_8:
4740   case ISD::ATOMIC_LOAD_UMIN_8:
4741   case ISD::ATOMIC_LOAD_UMAX_8:
4742   case ISD::ATOMIC_SWAP_8: 
4743   case ISD::ATOMIC_LOAD_ADD_16:
4744   case ISD::ATOMIC_LOAD_SUB_16:
4745   case ISD::ATOMIC_LOAD_AND_16:
4746   case ISD::ATOMIC_LOAD_OR_16:
4747   case ISD::ATOMIC_LOAD_XOR_16:
4748   case ISD::ATOMIC_LOAD_NAND_16:
4749   case ISD::ATOMIC_LOAD_MIN_16:
4750   case ISD::ATOMIC_LOAD_MAX_16:
4751   case ISD::ATOMIC_LOAD_UMIN_16:
4752   case ISD::ATOMIC_LOAD_UMAX_16:
4753   case ISD::ATOMIC_SWAP_16:
4754   case ISD::ATOMIC_LOAD_ADD_32:
4755   case ISD::ATOMIC_LOAD_SUB_32:
4756   case ISD::ATOMIC_LOAD_AND_32:
4757   case ISD::ATOMIC_LOAD_OR_32:
4758   case ISD::ATOMIC_LOAD_XOR_32:
4759   case ISD::ATOMIC_LOAD_NAND_32:
4760   case ISD::ATOMIC_LOAD_MIN_32:
4761   case ISD::ATOMIC_LOAD_MAX_32:
4762   case ISD::ATOMIC_LOAD_UMIN_32:
4763   case ISD::ATOMIC_LOAD_UMAX_32:
4764   case ISD::ATOMIC_SWAP_32:
4765   case ISD::ATOMIC_LOAD_ADD_64:
4766   case ISD::ATOMIC_LOAD_SUB_64:
4767   case ISD::ATOMIC_LOAD_AND_64:
4768   case ISD::ATOMIC_LOAD_OR_64:
4769   case ISD::ATOMIC_LOAD_XOR_64:
4770   case ISD::ATOMIC_LOAD_NAND_64:
4771   case ISD::ATOMIC_LOAD_MIN_64:
4772   case ISD::ATOMIC_LOAD_MAX_64:
4773   case ISD::ATOMIC_LOAD_UMIN_64:
4774   case ISD::ATOMIC_LOAD_UMAX_64:
4775   case ISD::ATOMIC_SWAP_64: {
4776     AtomicSDNode* AtomNode = cast<AtomicSDNode>(Node);
4777     Tmp2 = PromoteOp(Node->getOperand(2));
4778     Result = DAG.getAtomic(Node->getOpcode(), AtomNode->getChain(), 
4779                            AtomNode->getBasePtr(), Tmp2,
4780                            AtomNode->getSrcValue(),
4781                            AtomNode->getAlignment());
4782     // Remember that we legalized the chain.
4783     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4784     break;
4785   }
4786
4787   case ISD::AND:
4788   case ISD::OR:
4789   case ISD::XOR:
4790   case ISD::ADD:
4791   case ISD::SUB:
4792   case ISD::MUL:
4793     // The input may have strange things in the top bits of the registers, but
4794     // these operations don't care.  They may have weird bits going out, but
4795     // that too is okay if they are integer operations.
4796     Tmp1 = PromoteOp(Node->getOperand(0));
4797     Tmp2 = PromoteOp(Node->getOperand(1));
4798     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
4799     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4800     break;
4801   case ISD::FADD:
4802   case ISD::FSUB:
4803   case ISD::FMUL:
4804     Tmp1 = PromoteOp(Node->getOperand(0));
4805     Tmp2 = PromoteOp(Node->getOperand(1));
4806     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
4807     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4808     
4809     // Floating point operations will give excess precision that we may not be
4810     // able to tolerate.  If we DO allow excess precision, just leave it,
4811     // otherwise excise it.
4812     // FIXME: Why would we need to round FP ops more than integer ones?
4813     //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
4814     if (NoExcessFPPrecision)
4815       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4816                            DAG.getValueType(VT));
4817     break;
4818
4819   case ISD::SDIV:
4820   case ISD::SREM:
4821     // These operators require that their input be sign extended.
4822     Tmp1 = PromoteOp(Node->getOperand(0));
4823     Tmp2 = PromoteOp(Node->getOperand(1));
4824     if (NVT.isInteger()) {
4825       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
4826                          DAG.getValueType(VT));
4827       Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
4828                          DAG.getValueType(VT));
4829     }
4830     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4831
4832     // Perform FP_ROUND: this is probably overly pessimistic.
4833     if (NVT.isFloatingPoint() && NoExcessFPPrecision)
4834       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4835                            DAG.getValueType(VT));
4836     break;
4837   case ISD::FDIV:
4838   case ISD::FREM:
4839   case ISD::FCOPYSIGN:
4840     // These operators require that their input be fp extended.
4841     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4842     case Expand: assert(0 && "not implemented");
4843     case Legal:   Tmp1 = LegalizeOp(Node->getOperand(0)); break;
4844     case Promote: Tmp1 = PromoteOp(Node->getOperand(0));  break;
4845     }
4846     switch (getTypeAction(Node->getOperand(1).getValueType())) {
4847     case Expand: assert(0 && "not implemented");
4848     case Legal:   Tmp2 = LegalizeOp(Node->getOperand(1)); break;
4849     case Promote: Tmp2 = PromoteOp(Node->getOperand(1)); break;
4850     }
4851     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4852     
4853     // Perform FP_ROUND: this is probably overly pessimistic.
4854     if (NoExcessFPPrecision && Node->getOpcode() != ISD::FCOPYSIGN)
4855       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4856                            DAG.getValueType(VT));
4857     break;
4858
4859   case ISD::UDIV:
4860   case ISD::UREM:
4861     // These operators require that their input be zero extended.
4862     Tmp1 = PromoteOp(Node->getOperand(0));
4863     Tmp2 = PromoteOp(Node->getOperand(1));
4864     assert(NVT.isInteger() && "Operators don't apply to FP!");
4865     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
4866     Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
4867     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4868     break;
4869
4870   case ISD::SHL:
4871     Tmp1 = PromoteOp(Node->getOperand(0));
4872     Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Node->getOperand(1));
4873     break;
4874   case ISD::SRA:
4875     // The input value must be properly sign extended.
4876     Tmp1 = PromoteOp(Node->getOperand(0));
4877     Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
4878                        DAG.getValueType(VT));
4879     Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Node->getOperand(1));
4880     break;
4881   case ISD::SRL:
4882     // The input value must be properly zero extended.
4883     Tmp1 = PromoteOp(Node->getOperand(0));
4884     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
4885     Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Node->getOperand(1));
4886     break;
4887
4888   case ISD::VAARG:
4889     Tmp1 = Node->getOperand(0);   // Get the chain.
4890     Tmp2 = Node->getOperand(1);   // Get the pointer.
4891     if (TLI.getOperationAction(ISD::VAARG, VT) == TargetLowering::Custom) {
4892       Tmp3 = DAG.getVAArg(VT, Tmp1, Tmp2, Node->getOperand(2));
4893       Result = TLI.LowerOperation(Tmp3, DAG);
4894     } else {
4895       const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
4896       SDValue VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2, V, 0);
4897       // Increment the pointer, VAList, to the next vaarg
4898       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList, 
4899                          DAG.getConstant(VT.getSizeInBits()/8,
4900                                          TLI.getPointerTy()));
4901       // Store the incremented VAList to the legalized pointer
4902       Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Tmp2, V, 0);
4903       // Load the actual argument out of the pointer VAList
4904       Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp3, VAList, NULL, 0, VT);
4905     }
4906     // Remember that we legalized the chain.
4907     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4908     break;
4909
4910   case ISD::LOAD: {
4911     LoadSDNode *LD = cast<LoadSDNode>(Node);
4912     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(Node)
4913       ? ISD::EXTLOAD : LD->getExtensionType();
4914     Result = DAG.getExtLoad(ExtType, NVT,
4915                             LD->getChain(), LD->getBasePtr(),
4916                             LD->getSrcValue(), LD->getSrcValueOffset(),
4917                             LD->getMemoryVT(),
4918                             LD->isVolatile(),
4919                             LD->getAlignment());
4920     // Remember that we legalized the chain.
4921     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4922     break;
4923   }
4924   case ISD::SELECT: {
4925     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
4926     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
4927
4928     MVT VT2 = Tmp2.getValueType();
4929     assert(VT2 == Tmp3.getValueType()
4930            && "PromoteOp SELECT: Operands 2 and 3 ValueTypes don't match");
4931     // Ensure that the resulting node is at least the same size as the operands'
4932     // value types, because we cannot assume that TLI.getSetCCValueType() is
4933     // constant.
4934     Result = DAG.getNode(ISD::SELECT, VT2, Node->getOperand(0), Tmp2, Tmp3);
4935     break;
4936   }
4937   case ISD::SELECT_CC:
4938     Tmp2 = PromoteOp(Node->getOperand(2));   // True
4939     Tmp3 = PromoteOp(Node->getOperand(3));   // False
4940     Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4941                          Node->getOperand(1), Tmp2, Tmp3, Node->getOperand(4));
4942     break;
4943   case ISD::BSWAP:
4944     Tmp1 = Node->getOperand(0);
4945     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
4946     Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
4947     Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
4948                          DAG.getConstant(NVT.getSizeInBits() -
4949                                          VT.getSizeInBits(),
4950                                          TLI.getShiftAmountTy()));
4951     break;
4952   case ISD::CTPOP:
4953   case ISD::CTTZ:
4954   case ISD::CTLZ:
4955     // Zero extend the argument
4956     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
4957     // Perform the larger operation, then subtract if needed.
4958     Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4959     switch(Node->getOpcode()) {
4960     case ISD::CTPOP:
4961       Result = Tmp1;
4962       break;
4963     case ISD::CTTZ:
4964       // if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
4965       Tmp2 = DAG.getSetCC(TLI.getSetCCResultType(Tmp1), Tmp1,
4966                           DAG.getConstant(NVT.getSizeInBits(), NVT),
4967                           ISD::SETEQ);
4968       Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
4969                            DAG.getConstant(VT.getSizeInBits(), NVT), Tmp1);
4970       break;
4971     case ISD::CTLZ:
4972       //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4973       Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
4974                            DAG.getConstant(NVT.getSizeInBits() -
4975                                            VT.getSizeInBits(), NVT));
4976       break;
4977     }
4978     break;
4979   case ISD::EXTRACT_SUBVECTOR:
4980     Result = PromoteOp(ExpandEXTRACT_SUBVECTOR(Op));
4981     break;
4982   case ISD::EXTRACT_VECTOR_ELT:
4983     Result = PromoteOp(ExpandEXTRACT_VECTOR_ELT(Op));
4984     break;
4985   }
4986
4987   assert(Result.getNode() && "Didn't set a result!");
4988
4989   // Make sure the result is itself legal.
4990   Result = LegalizeOp(Result);
4991   
4992   // Remember that we promoted this!
4993   AddPromotedOperand(Op, Result);
4994   return Result;
4995 }
4996
4997 /// ExpandEXTRACT_VECTOR_ELT - Expand an EXTRACT_VECTOR_ELT operation into
4998 /// a legal EXTRACT_VECTOR_ELT operation, scalar code, or memory traffic,
4999 /// based on the vector type. The return type of this matches the element type
5000 /// of the vector, which may not be legal for the target.
5001 SDValue SelectionDAGLegalize::ExpandEXTRACT_VECTOR_ELT(SDValue Op) {
5002   // We know that operand #0 is the Vec vector.  If the index is a constant
5003   // or if the invec is a supported hardware type, we can use it.  Otherwise,
5004   // lower to a store then an indexed load.
5005   SDValue Vec = Op.getOperand(0);
5006   SDValue Idx = Op.getOperand(1);
5007   
5008   MVT TVT = Vec.getValueType();
5009   unsigned NumElems = TVT.getVectorNumElements();
5010   
5011   switch (TLI.getOperationAction(ISD::EXTRACT_VECTOR_ELT, TVT)) {
5012   default: assert(0 && "This action is not supported yet!");
5013   case TargetLowering::Custom: {
5014     Vec = LegalizeOp(Vec);
5015     Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
5016     SDValue Tmp3 = TLI.LowerOperation(Op, DAG);
5017     if (Tmp3.getNode())
5018       return Tmp3;
5019     break;
5020   }
5021   case TargetLowering::Legal:
5022     if (isTypeLegal(TVT)) {
5023       Vec = LegalizeOp(Vec);
5024       Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
5025       return Op;
5026     }
5027     break;
5028   case TargetLowering::Promote:
5029     assert(TVT.isVector() && "not vector type");
5030     // fall thru to expand since vectors are by default are promote
5031   case TargetLowering::Expand:
5032     break;
5033   }
5034
5035   if (NumElems == 1) {
5036     // This must be an access of the only element.  Return it.
5037     Op = ScalarizeVectorOp(Vec);
5038   } else if (!TLI.isTypeLegal(TVT) && isa<ConstantSDNode>(Idx)) {
5039     unsigned NumLoElts =  1 << Log2_32(NumElems-1);
5040     ConstantSDNode *CIdx = cast<ConstantSDNode>(Idx);
5041     SDValue Lo, Hi;
5042     SplitVectorOp(Vec, Lo, Hi);
5043     if (CIdx->getZExtValue() < NumLoElts) {
5044       Vec = Lo;
5045     } else {
5046       Vec = Hi;
5047       Idx = DAG.getConstant(CIdx->getZExtValue() - NumLoElts,
5048                             Idx.getValueType());
5049     }
5050   
5051     // It's now an extract from the appropriate high or low part.  Recurse.
5052     Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
5053     Op = ExpandEXTRACT_VECTOR_ELT(Op);
5054   } else {
5055     // Store the value to a temporary stack slot, then LOAD the scalar
5056     // element back out.
5057     SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
5058     SDValue Ch = DAG.getStore(DAG.getEntryNode(), Vec, StackPtr, NULL, 0);
5059
5060     // Add the offset to the index.
5061     unsigned EltSize = Op.getValueType().getSizeInBits()/8;
5062     Idx = DAG.getNode(ISD::MUL, Idx.getValueType(), Idx,
5063                       DAG.getConstant(EltSize, Idx.getValueType()));
5064
5065     if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
5066       Idx = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), Idx);
5067     else
5068       Idx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), Idx);
5069
5070     StackPtr = DAG.getNode(ISD::ADD, Idx.getValueType(), Idx, StackPtr);
5071
5072     Op = DAG.getLoad(Op.getValueType(), Ch, StackPtr, NULL, 0);
5073   }
5074   return Op;
5075 }
5076
5077 /// ExpandEXTRACT_SUBVECTOR - Expand a EXTRACT_SUBVECTOR operation.  For now
5078 /// we assume the operation can be split if it is not already legal.
5079 SDValue SelectionDAGLegalize::ExpandEXTRACT_SUBVECTOR(SDValue Op) {
5080   // We know that operand #0 is the Vec vector.  For now we assume the index
5081   // is a constant and that the extracted result is a supported hardware type.
5082   SDValue Vec = Op.getOperand(0);
5083   SDValue Idx = LegalizeOp(Op.getOperand(1));
5084   
5085   unsigned NumElems = Vec.getValueType().getVectorNumElements();
5086   
5087   if (NumElems == Op.getValueType().getVectorNumElements()) {
5088     // This must be an access of the desired vector length.  Return it.
5089     return Vec;
5090   }
5091
5092   ConstantSDNode *CIdx = cast<ConstantSDNode>(Idx);
5093   SDValue Lo, Hi;
5094   SplitVectorOp(Vec, Lo, Hi);
5095   if (CIdx->getZExtValue() < NumElems/2) {
5096     Vec = Lo;
5097   } else {
5098     Vec = Hi;
5099     Idx = DAG.getConstant(CIdx->getZExtValue() - NumElems/2,
5100                           Idx.getValueType());
5101   }
5102   
5103   // It's now an extract from the appropriate high or low part.  Recurse.
5104   Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
5105   return ExpandEXTRACT_SUBVECTOR(Op);
5106 }
5107
5108 /// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
5109 /// with condition CC on the current target.  This usually involves legalizing
5110 /// or promoting the arguments.  In the case where LHS and RHS must be expanded,
5111 /// there may be no choice but to create a new SetCC node to represent the
5112 /// legalized value of setcc lhs, rhs.  In this case, the value is returned in
5113 /// LHS, and the SDValue returned in RHS has a nil SDNode value.
5114 void SelectionDAGLegalize::LegalizeSetCCOperands(SDValue &LHS,
5115                                                  SDValue &RHS,
5116                                                  SDValue &CC) {
5117   SDValue Tmp1, Tmp2, Tmp3, Result;    
5118   
5119   switch (getTypeAction(LHS.getValueType())) {
5120   case Legal:
5121     Tmp1 = LegalizeOp(LHS);   // LHS
5122     Tmp2 = LegalizeOp(RHS);   // RHS
5123     break;
5124   case Promote:
5125     Tmp1 = PromoteOp(LHS);   // LHS
5126     Tmp2 = PromoteOp(RHS);   // RHS
5127
5128     // If this is an FP compare, the operands have already been extended.
5129     if (LHS.getValueType().isInteger()) {
5130       MVT VT = LHS.getValueType();
5131       MVT NVT = TLI.getTypeToTransformTo(VT);
5132
5133       // Otherwise, we have to insert explicit sign or zero extends.  Note
5134       // that we could insert sign extends for ALL conditions, but zero extend
5135       // is cheaper on many machines (an AND instead of two shifts), so prefer
5136       // it.
5137       switch (cast<CondCodeSDNode>(CC)->get()) {
5138       default: assert(0 && "Unknown integer comparison!");
5139       case ISD::SETEQ:
5140       case ISD::SETNE:
5141       case ISD::SETUGE:
5142       case ISD::SETUGT:
5143       case ISD::SETULE:
5144       case ISD::SETULT:
5145         // ALL of these operations will work if we either sign or zero extend
5146         // the operands (including the unsigned comparisons!).  Zero extend is
5147         // usually a simpler/cheaper operation, so prefer it.
5148         Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
5149         Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
5150         break;
5151       case ISD::SETGE:
5152       case ISD::SETGT:
5153       case ISD::SETLT:
5154       case ISD::SETLE:
5155         Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
5156                            DAG.getValueType(VT));
5157         Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
5158                            DAG.getValueType(VT));
5159         Tmp1 = LegalizeOp(Tmp1); // Relegalize new nodes.
5160         Tmp2 = LegalizeOp(Tmp2); // Relegalize new nodes.
5161         break;
5162       }
5163     }
5164     break;
5165   case Expand: {
5166     MVT VT = LHS.getValueType();
5167     if (VT == MVT::f32 || VT == MVT::f64) {
5168       // Expand into one or more soft-fp libcall(s).
5169       RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
5170       switch (cast<CondCodeSDNode>(CC)->get()) {
5171       case ISD::SETEQ:
5172       case ISD::SETOEQ:
5173         LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
5174         break;
5175       case ISD::SETNE:
5176       case ISD::SETUNE:
5177         LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : RTLIB::UNE_F64;
5178         break;
5179       case ISD::SETGE:
5180       case ISD::SETOGE:
5181         LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : RTLIB::OGE_F64;
5182         break;
5183       case ISD::SETLT:
5184       case ISD::SETOLT:
5185         LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
5186         break;
5187       case ISD::SETLE:
5188       case ISD::SETOLE:
5189         LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : RTLIB::OLE_F64;
5190         break;
5191       case ISD::SETGT:
5192       case ISD::SETOGT:
5193         LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : RTLIB::OGT_F64;
5194         break;
5195       case ISD::SETUO:
5196         LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : RTLIB::UO_F64;
5197         break;
5198       case ISD::SETO:
5199         LC1 = (VT == MVT::f32) ? RTLIB::O_F32 : RTLIB::O_F64;
5200         break;
5201       default:
5202         LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : RTLIB::UO_F64;
5203         switch (cast<CondCodeSDNode>(CC)->get()) {
5204         case ISD::SETONE:
5205           // SETONE = SETOLT | SETOGT
5206           LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
5207           // Fallthrough
5208         case ISD::SETUGT:
5209           LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 : RTLIB::OGT_F64;
5210           break;
5211         case ISD::SETUGE:
5212           LC2 = (VT == MVT::f32) ? RTLIB::OGE_F32 : RTLIB::OGE_F64;
5213           break;
5214         case ISD::SETULT:
5215           LC2 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
5216           break;
5217         case ISD::SETULE:
5218           LC2 = (VT == MVT::f32) ? RTLIB::OLE_F32 : RTLIB::OLE_F64;
5219           break;
5220         case ISD::SETUEQ:
5221           LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
5222           break;
5223         default: assert(0 && "Unsupported FP setcc!");
5224         }
5225       }
5226
5227       SDValue Dummy;
5228       SDValue Ops[2] = { LHS, RHS };
5229       Tmp1 = ExpandLibCall(LC1, DAG.getMergeValues(Ops, 2).getNode(),
5230                            false /*sign irrelevant*/, Dummy);
5231       Tmp2 = DAG.getConstant(0, MVT::i32);
5232       CC = DAG.getCondCode(TLI.getCmpLibcallCC(LC1));
5233       if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
5234         Tmp1 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(Tmp1), Tmp1, Tmp2,
5235                            CC);
5236         LHS = ExpandLibCall(LC2, DAG.getMergeValues(Ops, 2).getNode(),
5237                             false /*sign irrelevant*/, Dummy);
5238         Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(LHS), LHS, Tmp2,
5239                            DAG.getCondCode(TLI.getCmpLibcallCC(LC2)));
5240         Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
5241         Tmp2 = SDValue();
5242       }
5243       LHS = LegalizeOp(Tmp1);
5244       RHS = Tmp2;
5245       return;
5246     }
5247
5248     SDValue LHSLo, LHSHi, RHSLo, RHSHi;
5249     ExpandOp(LHS, LHSLo, LHSHi);
5250     ExpandOp(RHS, RHSLo, RHSHi);
5251     ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
5252
5253     if (VT==MVT::ppcf128) {
5254       // FIXME:  This generated code sucks.  We want to generate
5255       //         FCMPU crN, hi1, hi2
5256       //         BNE crN, L:
5257       //         FCMPU crN, lo1, lo2
5258       // The following can be improved, but not that much.
5259       Tmp1 = DAG.getSetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi, 
5260                                                          ISD::SETOEQ);
5261       Tmp2 = DAG.getSetCC(TLI.getSetCCResultType(LHSLo), LHSLo, RHSLo, CCCode);
5262       Tmp3 = DAG.getNode(ISD::AND, Tmp1.getValueType(), Tmp1, Tmp2);
5263       Tmp1 = DAG.getSetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi, 
5264                                                          ISD::SETUNE);
5265       Tmp2 = DAG.getSetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi, CCCode);
5266       Tmp1 = DAG.getNode(ISD::AND, Tmp1.getValueType(), Tmp1, Tmp2);
5267       Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp3);
5268       Tmp2 = SDValue();
5269       break;
5270     }
5271
5272     switch (CCCode) {
5273     case ISD::SETEQ:
5274     case ISD::SETNE:
5275       if (RHSLo == RHSHi)
5276         if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
5277           if (RHSCST->isAllOnesValue()) {
5278             // Comparison to -1.
5279             Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
5280             Tmp2 = RHSLo;
5281             break;
5282           }
5283
5284       Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
5285       Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
5286       Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
5287       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
5288       break;
5289     default:
5290       // If this is a comparison of the sign bit, just look at the top part.
5291       // X > -1,  x < 0
5292       if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(RHS))
5293         if ((cast<CondCodeSDNode>(CC)->get() == ISD::SETLT && 
5294              CST->isNullValue()) ||               // X < 0
5295             (cast<CondCodeSDNode>(CC)->get() == ISD::SETGT &&
5296              CST->isAllOnesValue())) {            // X > -1
5297           Tmp1 = LHSHi;
5298           Tmp2 = RHSHi;
5299           break;
5300         }
5301
5302       // FIXME: This generated code sucks.
5303       ISD::CondCode LowCC;
5304       switch (CCCode) {
5305       default: assert(0 && "Unknown integer setcc!");
5306       case ISD::SETLT:
5307       case ISD::SETULT: LowCC = ISD::SETULT; break;
5308       case ISD::SETGT:
5309       case ISD::SETUGT: LowCC = ISD::SETUGT; break;
5310       case ISD::SETLE:
5311       case ISD::SETULE: LowCC = ISD::SETULE; break;
5312       case ISD::SETGE:
5313       case ISD::SETUGE: LowCC = ISD::SETUGE; break;
5314       }
5315
5316       // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
5317       // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
5318       // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
5319
5320       // NOTE: on targets without efficient SELECT of bools, we can always use
5321       // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
5322       TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, false, true, NULL);
5323       Tmp1 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSLo), LHSLo, RHSLo,
5324                                LowCC, false, DagCombineInfo);
5325       if (!Tmp1.getNode())
5326         Tmp1 = DAG.getSetCC(TLI.getSetCCResultType(LHSLo), LHSLo, RHSLo, LowCC);
5327       Tmp2 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi,
5328                                CCCode, false, DagCombineInfo);
5329       if (!Tmp2.getNode())
5330         Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(LHSHi), LHSHi,
5331                            RHSHi,CC);
5332       
5333       ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.getNode());
5334       ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.getNode());
5335       if ((Tmp1C && Tmp1C->isNullValue()) ||
5336           (Tmp2C && Tmp2C->isNullValue() &&
5337            (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
5338             CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
5339           (Tmp2C && Tmp2C->getAPIntValue() == 1 &&
5340            (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
5341             CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
5342         // low part is known false, returns high part.
5343         // For LE / GE, if high part is known false, ignore the low part.
5344         // For LT / GT, if high part is known true, ignore the low part.
5345         Tmp1 = Tmp2;
5346         Tmp2 = SDValue();
5347       } else {
5348         Result = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi,
5349                                    ISD::SETEQ, false, DagCombineInfo);
5350         if (!Result.getNode())
5351           Result=DAG.getSetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi,
5352                               ISD::SETEQ);
5353         Result = LegalizeOp(DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
5354                                         Result, Tmp1, Tmp2));
5355         Tmp1 = Result;
5356         Tmp2 = SDValue();
5357       }
5358     }
5359   }
5360   }
5361   LHS = Tmp1;
5362   RHS = Tmp2;
5363 }
5364
5365 /// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
5366 /// condition code CC on the current target. This routine assumes LHS and rHS
5367 /// have already been legalized by LegalizeSetCCOperands. It expands SETCC with
5368 /// illegal condition code into AND / OR of multiple SETCC values.
5369 void SelectionDAGLegalize::LegalizeSetCCCondCode(MVT VT,
5370                                                  SDValue &LHS, SDValue &RHS,
5371                                                  SDValue &CC) {
5372   MVT OpVT = LHS.getValueType();
5373   ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
5374   switch (TLI.getCondCodeAction(CCCode, OpVT)) {
5375   default: assert(0 && "Unknown condition code action!");
5376   case TargetLowering::Legal:
5377     // Nothing to do.
5378     break;
5379   case TargetLowering::Expand: {
5380     ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
5381     unsigned Opc = 0;
5382     switch (CCCode) {
5383     default: assert(0 && "Don't know how to expand this condition!"); abort();
5384     case ISD::SETOEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5385     case ISD::SETOGT: CC1 = ISD::SETGT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5386     case ISD::SETOGE: CC1 = ISD::SETGE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5387     case ISD::SETOLT: CC1 = ISD::SETLT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5388     case ISD::SETOLE: CC1 = ISD::SETLE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5389     case ISD::SETONE: CC1 = ISD::SETNE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5390     case ISD::SETUEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5391     case ISD::SETUGT: CC1 = ISD::SETGT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5392     case ISD::SETUGE: CC1 = ISD::SETGE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5393     case ISD::SETULT: CC1 = ISD::SETLT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5394     case ISD::SETULE: CC1 = ISD::SETLE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5395     case ISD::SETUNE: CC1 = ISD::SETNE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5396     // FIXME: Implement more expansions.
5397     }
5398
5399     SDValue SetCC1 = DAG.getSetCC(VT, LHS, RHS, CC1);
5400     SDValue SetCC2 = DAG.getSetCC(VT, LHS, RHS, CC2);
5401     LHS = DAG.getNode(Opc, VT, SetCC1, SetCC2);
5402     RHS = SDValue();
5403     CC  = SDValue();
5404     break;
5405   }
5406   }
5407 }
5408
5409 /// EmitStackConvert - Emit a store/load combination to the stack.  This stores
5410 /// SrcOp to a stack slot of type SlotVT, truncating it if needed.  It then does
5411 /// a load from the stack slot to DestVT, extending it if needed.
5412 /// The resultant code need not be legal.
5413 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
5414                                                MVT SlotVT,
5415                                                MVT DestVT) {
5416   // Create the stack frame object.
5417   unsigned SrcAlign = TLI.getTargetData()->getPrefTypeAlignment(
5418                                           SrcOp.getValueType().getTypeForMVT());
5419   SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
5420   
5421   FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
5422   int SPFI = StackPtrFI->getIndex();
5423   
5424   unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
5425   unsigned SlotSize = SlotVT.getSizeInBits();
5426   unsigned DestSize = DestVT.getSizeInBits();
5427   unsigned DestAlign = TLI.getTargetData()->getPrefTypeAlignment(
5428                                                         DestVT.getTypeForMVT());
5429   
5430   // Emit a store to the stack slot.  Use a truncstore if the input value is
5431   // later than DestVT.
5432   SDValue Store;
5433   
5434   if (SrcSize > SlotSize)
5435     Store = DAG.getTruncStore(DAG.getEntryNode(), SrcOp, FIPtr,
5436                               PseudoSourceValue::getFixedStack(SPFI), 0,
5437                               SlotVT, false, SrcAlign);
5438   else {
5439     assert(SrcSize == SlotSize && "Invalid store");
5440     Store = DAG.getStore(DAG.getEntryNode(), SrcOp, FIPtr,
5441                          PseudoSourceValue::getFixedStack(SPFI), 0,
5442                          false, SrcAlign);
5443   }
5444   
5445   // Result is a load from the stack slot.
5446   if (SlotSize == DestSize)
5447     return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0, false, DestAlign);
5448   
5449   assert(SlotSize < DestSize && "Unknown extension!");
5450   return DAG.getExtLoad(ISD::EXTLOAD, DestVT, Store, FIPtr, NULL, 0, SlotVT,
5451                         false, DestAlign);
5452 }
5453
5454 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
5455   // Create a vector sized/aligned stack slot, store the value to element #0,
5456   // then load the whole vector back out.
5457   SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
5458
5459   FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
5460   int SPFI = StackPtrFI->getIndex();
5461
5462   SDValue Ch = DAG.getStore(DAG.getEntryNode(), Node->getOperand(0), StackPtr,
5463                               PseudoSourceValue::getFixedStack(SPFI), 0);
5464   return DAG.getLoad(Node->getValueType(0), Ch, StackPtr,
5465                      PseudoSourceValue::getFixedStack(SPFI), 0);
5466 }
5467
5468
5469 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
5470 /// support the operation, but do support the resultant vector type.
5471 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
5472   
5473   // If the only non-undef value is the low element, turn this into a 
5474   // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
5475   unsigned NumElems = Node->getNumOperands();
5476   bool isOnlyLowElement = true;
5477   SDValue SplatValue = Node->getOperand(0);
5478   
5479   // FIXME: it would be far nicer to change this into map<SDValue,uint64_t>
5480   // and use a bitmask instead of a list of elements.
5481   std::map<SDValue, std::vector<unsigned> > Values;
5482   Values[SplatValue].push_back(0);
5483   bool isConstant = true;
5484   if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
5485       SplatValue.getOpcode() != ISD::UNDEF)
5486     isConstant = false;
5487   
5488   for (unsigned i = 1; i < NumElems; ++i) {
5489     SDValue V = Node->getOperand(i);
5490     Values[V].push_back(i);
5491     if (V.getOpcode() != ISD::UNDEF)
5492       isOnlyLowElement = false;
5493     if (SplatValue != V)
5494       SplatValue = SDValue(0,0);
5495
5496     // If this isn't a constant element or an undef, we can't use a constant
5497     // pool load.
5498     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
5499         V.getOpcode() != ISD::UNDEF)
5500       isConstant = false;
5501   }
5502   
5503   if (isOnlyLowElement) {
5504     // If the low element is an undef too, then this whole things is an undef.
5505     if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
5506       return DAG.getNode(ISD::UNDEF, Node->getValueType(0));
5507     // Otherwise, turn this into a scalar_to_vector node.
5508     return DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
5509                        Node->getOperand(0));
5510   }
5511   
5512   // If all elements are constants, create a load from the constant pool.
5513   if (isConstant) {
5514     MVT VT = Node->getValueType(0);
5515     std::vector<Constant*> CV;
5516     for (unsigned i = 0, e = NumElems; i != e; ++i) {
5517       if (ConstantFPSDNode *V = 
5518           dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
5519         CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
5520       } else if (ConstantSDNode *V = 
5521                    dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
5522         CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
5523       } else {
5524         assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
5525         const Type *OpNTy = 
5526           Node->getOperand(0).getValueType().getTypeForMVT();
5527         CV.push_back(UndefValue::get(OpNTy));
5528       }
5529     }
5530     Constant *CP = ConstantVector::get(CV);
5531     SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
5532     unsigned Alignment = 1 << cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
5533     return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
5534                        PseudoSourceValue::getConstantPool(), 0,
5535                        false, Alignment);
5536   }
5537   
5538   if (SplatValue.getNode()) {   // Splat of one value?
5539     // Build the shuffle constant vector: <0, 0, 0, 0>
5540     MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
5541     SDValue Zero = DAG.getConstant(0, MaskVT.getVectorElementType());
5542     std::vector<SDValue> ZeroVec(NumElems, Zero);
5543     SDValue SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
5544                                       &ZeroVec[0], ZeroVec.size());
5545
5546     // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
5547     if (isShuffleLegal(Node->getValueType(0), SplatMask)) {
5548       // Get the splatted value into the low element of a vector register.
5549       SDValue LowValVec = 
5550         DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), SplatValue);
5551     
5552       // Return shuffle(LowValVec, undef, <0,0,0,0>)
5553       return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), LowValVec,
5554                          DAG.getNode(ISD::UNDEF, Node->getValueType(0)),
5555                          SplatMask);
5556     }
5557   }
5558   
5559   // If there are only two unique elements, we may be able to turn this into a
5560   // vector shuffle.
5561   if (Values.size() == 2) {
5562     // Get the two values in deterministic order.
5563     SDValue Val1 = Node->getOperand(1);
5564     SDValue Val2;
5565     std::map<SDValue, std::vector<unsigned> >::iterator MI = Values.begin();
5566     if (MI->first != Val1)
5567       Val2 = MI->first;
5568     else
5569       Val2 = (++MI)->first;
5570     
5571     // If Val1 is an undef, make sure end ends up as Val2, to ensure that our 
5572     // vector shuffle has the undef vector on the RHS.
5573     if (Val1.getOpcode() == ISD::UNDEF)
5574       std::swap(Val1, Val2);
5575     
5576     // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
5577     MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
5578     MVT MaskEltVT = MaskVT.getVectorElementType();
5579     std::vector<SDValue> MaskVec(NumElems);
5580
5581     // Set elements of the shuffle mask for Val1.
5582     std::vector<unsigned> &Val1Elts = Values[Val1];
5583     for (unsigned i = 0, e = Val1Elts.size(); i != e; ++i)
5584       MaskVec[Val1Elts[i]] = DAG.getConstant(0, MaskEltVT);
5585
5586     // Set elements of the shuffle mask for Val2.
5587     std::vector<unsigned> &Val2Elts = Values[Val2];
5588     for (unsigned i = 0, e = Val2Elts.size(); i != e; ++i)
5589       if (Val2.getOpcode() != ISD::UNDEF)
5590         MaskVec[Val2Elts[i]] = DAG.getConstant(NumElems, MaskEltVT);
5591       else
5592         MaskVec[Val2Elts[i]] = DAG.getNode(ISD::UNDEF, MaskEltVT);
5593     
5594     SDValue ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
5595                                         &MaskVec[0], MaskVec.size());
5596
5597     // If the target supports SCALAR_TO_VECTOR and this shuffle mask, use it.
5598     if (TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0)) &&
5599         isShuffleLegal(Node->getValueType(0), ShuffleMask)) {
5600       Val1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), Val1);
5601       Val2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), Val2);
5602       SDValue Ops[] = { Val1, Val2, ShuffleMask };
5603
5604       // Return shuffle(LoValVec, HiValVec, <0,1,0,1>)
5605       return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), Ops, 3);
5606     }
5607   }
5608   
5609   // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
5610   // aligned object on the stack, store each element into it, then load
5611   // the result as a vector.
5612   MVT VT = Node->getValueType(0);
5613   // Create the stack frame object.
5614   SDValue FIPtr = DAG.CreateStackTemporary(VT);
5615   
5616   // Emit a store of each element to the stack slot.
5617   SmallVector<SDValue, 8> Stores;
5618   unsigned TypeByteSize = Node->getOperand(0).getValueType().getSizeInBits()/8;
5619   // Store (in the right endianness) the elements to memory.
5620   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
5621     // Ignore undef elements.
5622     if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
5623     
5624     unsigned Offset = TypeByteSize*i;
5625     
5626     SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
5627     Idx = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr, Idx);
5628     
5629     Stores.push_back(DAG.getStore(DAG.getEntryNode(), Node->getOperand(i), Idx, 
5630                                   NULL, 0));
5631   }
5632   
5633   SDValue StoreChain;
5634   if (!Stores.empty())    // Not all undef elements?
5635     StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5636                              &Stores[0], Stores.size());
5637   else
5638     StoreChain = DAG.getEntryNode();
5639   
5640   // Result is a load from the stack slot.
5641   return DAG.getLoad(VT, StoreChain, FIPtr, NULL, 0);
5642 }
5643
5644 void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
5645                                             SDValue Op, SDValue Amt,
5646                                             SDValue &Lo, SDValue &Hi) {
5647   // Expand the subcomponents.
5648   SDValue LHSL, LHSH;
5649   ExpandOp(Op, LHSL, LHSH);
5650
5651   SDValue Ops[] = { LHSL, LHSH, Amt };
5652   MVT VT = LHSL.getValueType();
5653   Lo = DAG.getNode(NodeOp, DAG.getNodeValueTypes(VT, VT), 2, Ops, 3);
5654   Hi = Lo.getValue(1);
5655 }
5656
5657
5658 /// ExpandShift - Try to find a clever way to expand this shift operation out to
5659 /// smaller elements.  If we can't find a way that is more efficient than a
5660 /// libcall on this target, return false.  Otherwise, return true with the
5661 /// low-parts expanded into Lo and Hi.
5662 bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDValue Op,SDValue Amt,
5663                                        SDValue &Lo, SDValue &Hi) {
5664   assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
5665          "This is not a shift!");
5666
5667   MVT NVT = TLI.getTypeToTransformTo(Op.getValueType());
5668   SDValue ShAmt = LegalizeOp(Amt);
5669   MVT ShTy = ShAmt.getValueType();
5670   unsigned ShBits = ShTy.getSizeInBits();
5671   unsigned VTBits = Op.getValueType().getSizeInBits();
5672   unsigned NVTBits = NVT.getSizeInBits();
5673
5674   // Handle the case when Amt is an immediate.
5675   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.getNode())) {
5676     unsigned Cst = CN->getZExtValue();
5677     // Expand the incoming operand to be shifted, so that we have its parts
5678     SDValue InL, InH;
5679     ExpandOp(Op, InL, InH);
5680     switch(Opc) {
5681     case ISD::SHL:
5682       if (Cst > VTBits) {
5683         Lo = DAG.getConstant(0, NVT);
5684         Hi = DAG.getConstant(0, NVT);
5685       } else if (Cst > NVTBits) {
5686         Lo = DAG.getConstant(0, NVT);
5687         Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
5688       } else if (Cst == NVTBits) {
5689         Lo = DAG.getConstant(0, NVT);
5690         Hi = InL;
5691       } else {
5692         Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
5693         Hi = DAG.getNode(ISD::OR, NVT,
5694            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
5695            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
5696       }
5697       return true;
5698     case ISD::SRL:
5699       if (Cst > VTBits) {
5700         Lo = DAG.getConstant(0, NVT);
5701         Hi = DAG.getConstant(0, NVT);
5702       } else if (Cst > NVTBits) {
5703         Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
5704         Hi = DAG.getConstant(0, NVT);
5705       } else if (Cst == NVTBits) {
5706         Lo = InH;
5707         Hi = DAG.getConstant(0, NVT);
5708       } else {
5709         Lo = DAG.getNode(ISD::OR, NVT,
5710            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
5711            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
5712         Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
5713       }
5714       return true;
5715     case ISD::SRA:
5716       if (Cst > VTBits) {
5717         Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
5718                               DAG.getConstant(NVTBits-1, ShTy));
5719       } else if (Cst > NVTBits) {
5720         Lo = DAG.getNode(ISD::SRA, NVT, InH,
5721                            DAG.getConstant(Cst-NVTBits, ShTy));
5722         Hi = DAG.getNode(ISD::SRA, NVT, InH,
5723                               DAG.getConstant(NVTBits-1, ShTy));
5724       } else if (Cst == NVTBits) {
5725         Lo = InH;
5726         Hi = DAG.getNode(ISD::SRA, NVT, InH,
5727                               DAG.getConstant(NVTBits-1, ShTy));
5728       } else {
5729         Lo = DAG.getNode(ISD::OR, NVT,
5730            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
5731            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
5732         Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
5733       }
5734       return true;
5735     }
5736   }
5737   
5738   // Okay, the shift amount isn't constant.  However, if we can tell that it is
5739   // >= 32 or < 32, we can still simplify it, without knowing the actual value.
5740   APInt Mask = APInt::getHighBitsSet(ShBits, ShBits - Log2_32(NVTBits));
5741   APInt KnownZero, KnownOne;
5742   DAG.ComputeMaskedBits(Amt, Mask, KnownZero, KnownOne);
5743   
5744   // If we know that if any of the high bits of the shift amount are one, then
5745   // we can do this as a couple of simple shifts.
5746   if (KnownOne.intersects(Mask)) {
5747     // Mask out the high bit, which we know is set.
5748     Amt = DAG.getNode(ISD::AND, Amt.getValueType(), Amt,
5749                       DAG.getConstant(~Mask, Amt.getValueType()));
5750     
5751     // Expand the incoming operand to be shifted, so that we have its parts
5752     SDValue InL, InH;
5753     ExpandOp(Op, InL, InH);
5754     switch(Opc) {
5755     case ISD::SHL:
5756       Lo = DAG.getConstant(0, NVT);              // Low part is zero.
5757       Hi = DAG.getNode(ISD::SHL, NVT, InL, Amt); // High part from Lo part.
5758       return true;
5759     case ISD::SRL:
5760       Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
5761       Lo = DAG.getNode(ISD::SRL, NVT, InH, Amt); // Lo part from Hi part.
5762       return true;
5763     case ISD::SRA:
5764       Hi = DAG.getNode(ISD::SRA, NVT, InH,       // Sign extend high part.
5765                        DAG.getConstant(NVTBits-1, Amt.getValueType()));
5766       Lo = DAG.getNode(ISD::SRA, NVT, InH, Amt); // Lo part from Hi part.
5767       return true;
5768     }
5769   }
5770   
5771   // If we know that the high bits of the shift amount are all zero, then we can
5772   // do this as a couple of simple shifts.
5773   if ((KnownZero & Mask) == Mask) {
5774     // Compute 32-amt.
5775     SDValue Amt2 = DAG.getNode(ISD::SUB, Amt.getValueType(),
5776                                  DAG.getConstant(NVTBits, Amt.getValueType()),
5777                                  Amt);
5778     
5779     // Expand the incoming operand to be shifted, so that we have its parts
5780     SDValue InL, InH;
5781     ExpandOp(Op, InL, InH);
5782     switch(Opc) {
5783     case ISD::SHL:
5784       Lo = DAG.getNode(ISD::SHL, NVT, InL, Amt);
5785       Hi = DAG.getNode(ISD::OR, NVT,
5786                        DAG.getNode(ISD::SHL, NVT, InH, Amt),
5787                        DAG.getNode(ISD::SRL, NVT, InL, Amt2));
5788       return true;
5789     case ISD::SRL:
5790       Hi = DAG.getNode(ISD::SRL, NVT, InH, Amt);
5791       Lo = DAG.getNode(ISD::OR, NVT,
5792                        DAG.getNode(ISD::SRL, NVT, InL, Amt),
5793                        DAG.getNode(ISD::SHL, NVT, InH, Amt2));
5794       return true;
5795     case ISD::SRA:
5796       Hi = DAG.getNode(ISD::SRA, NVT, InH, Amt);
5797       Lo = DAG.getNode(ISD::OR, NVT,
5798                        DAG.getNode(ISD::SRL, NVT, InL, Amt),
5799                        DAG.getNode(ISD::SHL, NVT, InH, Amt2));
5800       return true;
5801     }
5802   }
5803   
5804   return false;
5805 }
5806
5807
5808 // ExpandLibCall - Expand a node into a call to a libcall.  If the result value
5809 // does not fit into a register, return the lo part and set the hi part to the
5810 // by-reg argument.  If it does fit into a single register, return the result
5811 // and leave the Hi part unset.
5812 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
5813                                             bool isSigned, SDValue &Hi) {
5814   assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
5815   // The input chain to this libcall is the entry node of the function. 
5816   // Legalizing the call will automatically add the previous call to the
5817   // dependence.
5818   SDValue InChain = DAG.getEntryNode();
5819   
5820   TargetLowering::ArgListTy Args;
5821   TargetLowering::ArgListEntry Entry;
5822   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
5823     MVT ArgVT = Node->getOperand(i).getValueType();
5824     const Type *ArgTy = ArgVT.getTypeForMVT();
5825     Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy; 
5826     Entry.isSExt = isSigned;
5827     Entry.isZExt = !isSigned;
5828     Args.push_back(Entry);
5829   }
5830   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
5831                                          TLI.getPointerTy());
5832
5833   // Splice the libcall in wherever FindInputOutputChains tells us to.
5834   const Type *RetTy = Node->getValueType(0).getTypeForMVT();
5835   std::pair<SDValue,SDValue> CallInfo =
5836     TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
5837                     CallingConv::C, false, Callee, Args, DAG);
5838
5839   // Legalize the call sequence, starting with the chain.  This will advance
5840   // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
5841   // was added by LowerCallTo (guaranteeing proper serialization of calls).
5842   LegalizeOp(CallInfo.second);
5843   SDValue Result;
5844   switch (getTypeAction(CallInfo.first.getValueType())) {
5845   default: assert(0 && "Unknown thing");
5846   case Legal:
5847     Result = CallInfo.first;
5848     break;
5849   case Expand:
5850     ExpandOp(CallInfo.first, Result, Hi);
5851     break;
5852   }
5853   return Result;
5854 }
5855
5856 /// LegalizeINT_TO_FP - Legalize a [US]INT_TO_FP operation.
5857 ///
5858 SDValue SelectionDAGLegalize::
5859 LegalizeINT_TO_FP(SDValue Result, bool isSigned, MVT DestTy, SDValue Op) {
5860   bool isCustom = false;
5861   SDValue Tmp1;
5862   switch (getTypeAction(Op.getValueType())) {
5863   case Legal:
5864     switch (TLI.getOperationAction(isSigned ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
5865                                    Op.getValueType())) {
5866     default: assert(0 && "Unknown operation action!");
5867     case TargetLowering::Custom:
5868       isCustom = true;
5869       // FALLTHROUGH
5870     case TargetLowering::Legal:
5871       Tmp1 = LegalizeOp(Op);
5872       if (Result.getNode())
5873         Result = DAG.UpdateNodeOperands(Result, Tmp1);
5874       else
5875         Result = DAG.getNode(isSigned ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
5876                              DestTy, Tmp1);
5877       if (isCustom) {
5878         Tmp1 = TLI.LowerOperation(Result, DAG);
5879         if (Tmp1.getNode()) Result = Tmp1;
5880       }
5881       break;
5882     case TargetLowering::Expand:
5883       Result = ExpandLegalINT_TO_FP(isSigned, LegalizeOp(Op), DestTy);
5884       break;
5885     case TargetLowering::Promote:
5886       Result = PromoteLegalINT_TO_FP(LegalizeOp(Op), DestTy, isSigned);
5887       break;
5888     }
5889     break;
5890   case Expand:
5891     Result = ExpandIntToFP(isSigned, DestTy, Op);
5892     break;
5893   case Promote:
5894     Tmp1 = PromoteOp(Op);
5895     if (isSigned) {
5896       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp1.getValueType(),
5897                Tmp1, DAG.getValueType(Op.getValueType()));
5898     } else {
5899       Tmp1 = DAG.getZeroExtendInReg(Tmp1,
5900                                     Op.getValueType());
5901     }
5902     if (Result.getNode())
5903       Result = DAG.UpdateNodeOperands(Result, Tmp1);
5904     else
5905       Result = DAG.getNode(isSigned ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
5906                            DestTy, Tmp1);
5907     Result = LegalizeOp(Result);  // The 'op' is not necessarily legal!
5908     break;
5909   }
5910   return Result;
5911 }
5912
5913 /// ExpandIntToFP - Expand a [US]INT_TO_FP operation.
5914 ///
5915 SDValue SelectionDAGLegalize::
5916 ExpandIntToFP(bool isSigned, MVT DestTy, SDValue Source) {
5917   MVT SourceVT = Source.getValueType();
5918   bool ExpandSource = getTypeAction(SourceVT) == Expand;
5919
5920   // Expand unsupported int-to-fp vector casts by unrolling them.
5921   if (DestTy.isVector()) {
5922     if (!ExpandSource)
5923       return LegalizeOp(UnrollVectorOp(Source));
5924     MVT DestEltTy = DestTy.getVectorElementType();
5925     if (DestTy.getVectorNumElements() == 1) {
5926       SDValue Scalar = ScalarizeVectorOp(Source);
5927       SDValue Result = LegalizeINT_TO_FP(SDValue(), isSigned,
5928                                          DestEltTy, Scalar);
5929       return DAG.getNode(ISD::BUILD_VECTOR, DestTy, Result);
5930     }
5931     SDValue Lo, Hi;
5932     SplitVectorOp(Source, Lo, Hi);
5933     MVT SplitDestTy = MVT::getVectorVT(DestEltTy,
5934                                        DestTy.getVectorNumElements() / 2);
5935     SDValue LoResult = LegalizeINT_TO_FP(SDValue(), isSigned, SplitDestTy, Lo);
5936     SDValue HiResult = LegalizeINT_TO_FP(SDValue(), isSigned, SplitDestTy, Hi);
5937     return LegalizeOp(DAG.getNode(ISD::CONCAT_VECTORS, DestTy, LoResult,
5938                                   HiResult));
5939   }
5940
5941   // Special case for i32 source to take advantage of UINTTOFP_I32_F32, etc.
5942   if (!isSigned && SourceVT != MVT::i32) {
5943     // The integer value loaded will be incorrectly if the 'sign bit' of the
5944     // incoming integer is set.  To handle this, we dynamically test to see if
5945     // it is set, and, if so, add a fudge factor.
5946     SDValue Hi;
5947     if (ExpandSource) {
5948       SDValue Lo;
5949       ExpandOp(Source, Lo, Hi);
5950       Source = DAG.getNode(ISD::BUILD_PAIR, SourceVT, Lo, Hi);
5951     } else {
5952       // The comparison for the sign bit will use the entire operand.
5953       Hi = Source;
5954     }
5955
5956     // Check to see if the target has a custom way to lower this.  If so, use
5957     // it.  (Note we've already expanded the operand in this case.)
5958     switch (TLI.getOperationAction(ISD::UINT_TO_FP, SourceVT)) {
5959     default: assert(0 && "This action not implemented for this operation!");
5960     case TargetLowering::Legal:
5961     case TargetLowering::Expand:
5962       break;   // This case is handled below.
5963     case TargetLowering::Custom: {
5964       SDValue NV = TLI.LowerOperation(DAG.getNode(ISD::UINT_TO_FP, DestTy,
5965                                                     Source), DAG);
5966       if (NV.getNode())
5967         return LegalizeOp(NV);
5968       break;   // The target decided this was legal after all
5969     }
5970     }
5971
5972     // If this is unsigned, and not supported, first perform the conversion to
5973     // signed, then adjust the result if the sign bit is set.
5974     SDValue SignedConv = ExpandIntToFP(true, DestTy, Source);
5975
5976     SDValue SignSet = DAG.getSetCC(TLI.getSetCCResultType(Hi), Hi,
5977                                      DAG.getConstant(0, Hi.getValueType()),
5978                                      ISD::SETLT);
5979     SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
5980     SDValue CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
5981                                       SignSet, Four, Zero);
5982     uint64_t FF = 0x5f800000ULL;
5983     if (TLI.isLittleEndian()) FF <<= 32;
5984     static Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
5985
5986     SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
5987     unsigned Alignment = 1 << cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
5988     CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
5989     Alignment = std::min(Alignment, 4u);
5990     SDValue FudgeInReg;
5991     if (DestTy == MVT::f32)
5992       FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
5993                                PseudoSourceValue::getConstantPool(), 0,
5994                                false, Alignment);
5995     else if (DestTy.bitsGT(MVT::f32))
5996       // FIXME: Avoid the extend by construction the right constantpool?
5997       FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, DestTy, DAG.getEntryNode(),
5998                                   CPIdx,
5999                                   PseudoSourceValue::getConstantPool(), 0,
6000                                   MVT::f32, false, Alignment);
6001     else 
6002       assert(0 && "Unexpected conversion");
6003
6004     MVT SCVT = SignedConv.getValueType();
6005     if (SCVT != DestTy) {
6006       // Destination type needs to be expanded as well. The FADD now we are
6007       // constructing will be expanded into a libcall.
6008       if (SCVT.getSizeInBits() != DestTy.getSizeInBits()) {
6009         assert(SCVT.getSizeInBits() * 2 == DestTy.getSizeInBits());
6010         SignedConv = DAG.getNode(ISD::BUILD_PAIR, DestTy,
6011                                  SignedConv, SignedConv.getValue(1));
6012       }
6013       SignedConv = DAG.getNode(ISD::BIT_CONVERT, DestTy, SignedConv);
6014     }
6015     return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
6016   }
6017
6018   // Check to see if the target has a custom way to lower this.  If so, use it.
6019   switch (TLI.getOperationAction(ISD::SINT_TO_FP, SourceVT)) {
6020   default: assert(0 && "This action not implemented for this operation!");
6021   case TargetLowering::Legal:
6022   case TargetLowering::Expand:
6023     break;   // This case is handled below.
6024   case TargetLowering::Custom: {
6025     SDValue NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
6026                                                   Source), DAG);
6027     if (NV.getNode())
6028       return LegalizeOp(NV);
6029     break;   // The target decided this was legal after all
6030   }
6031   }
6032
6033   // Expand the source, then glue it back together for the call.  We must expand
6034   // the source in case it is shared (this pass of legalize must traverse it).
6035   if (ExpandSource) {
6036     SDValue SrcLo, SrcHi;
6037     ExpandOp(Source, SrcLo, SrcHi);
6038     Source = DAG.getNode(ISD::BUILD_PAIR, SourceVT, SrcLo, SrcHi);
6039   }
6040
6041   RTLIB::Libcall LC = isSigned ?
6042     RTLIB::getSINTTOFP(SourceVT, DestTy) :
6043     RTLIB::getUINTTOFP(SourceVT, DestTy);
6044   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unknown int value type");
6045
6046   Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
6047   SDValue HiPart;
6048   SDValue Result = ExpandLibCall(LC, Source.getNode(), isSigned, HiPart);
6049   if (Result.getValueType() != DestTy && HiPart.getNode())
6050     Result = DAG.getNode(ISD::BUILD_PAIR, DestTy, Result, HiPart);
6051   return Result;
6052 }
6053
6054 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
6055 /// INT_TO_FP operation of the specified operand when the target requests that
6056 /// we expand it.  At this point, we know that the result and operand types are
6057 /// legal for the target.
6058 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
6059                                                    SDValue Op0,
6060                                                    MVT DestVT) {
6061   if (Op0.getValueType() == MVT::i32) {
6062     // simple 32-bit [signed|unsigned] integer to float/double expansion
6063     
6064     // Get the stack frame index of a 8 byte buffer.
6065     SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
6066     
6067     // word offset constant for Hi/Lo address computation
6068     SDValue WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
6069     // set up Hi and Lo (into buffer) address based on endian
6070     SDValue Hi = StackSlot;
6071     SDValue Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot,WordOff);
6072     if (TLI.isLittleEndian())
6073       std::swap(Hi, Lo);
6074     
6075     // if signed map to unsigned space
6076     SDValue Op0Mapped;
6077     if (isSigned) {
6078       // constant used to invert sign bit (signed to unsigned mapping)
6079       SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
6080       Op0Mapped = DAG.getNode(ISD::XOR, MVT::i32, Op0, SignBit);
6081     } else {
6082       Op0Mapped = Op0;
6083     }
6084     // store the lo of the constructed double - based on integer input
6085     SDValue Store1 = DAG.getStore(DAG.getEntryNode(),
6086                                     Op0Mapped, Lo, NULL, 0);
6087     // initial hi portion of constructed double
6088     SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
6089     // store the hi of the constructed double - biased exponent
6090     SDValue Store2=DAG.getStore(Store1, InitialHi, Hi, NULL, 0);
6091     // load the constructed double
6092     SDValue Load = DAG.getLoad(MVT::f64, Store2, StackSlot, NULL, 0);
6093     // FP constant to bias correct the final result
6094     SDValue Bias = DAG.getConstantFP(isSigned ?
6095                                             BitsToDouble(0x4330000080000000ULL)
6096                                           : BitsToDouble(0x4330000000000000ULL),
6097                                      MVT::f64);
6098     // subtract the bias
6099     SDValue Sub = DAG.getNode(ISD::FSUB, MVT::f64, Load, Bias);
6100     // final result
6101     SDValue Result;
6102     // handle final rounding
6103     if (DestVT == MVT::f64) {
6104       // do nothing
6105       Result = Sub;
6106     } else if (DestVT.bitsLT(MVT::f64)) {
6107       Result = DAG.getNode(ISD::FP_ROUND, DestVT, Sub,
6108                            DAG.getIntPtrConstant(0));
6109     } else if (DestVT.bitsGT(MVT::f64)) {
6110       Result = DAG.getNode(ISD::FP_EXTEND, DestVT, Sub);
6111     }
6112     return Result;
6113   }
6114   assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
6115   SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
6116
6117   SDValue SignSet = DAG.getSetCC(TLI.getSetCCResultType(Op0), Op0,
6118                                    DAG.getConstant(0, Op0.getValueType()),
6119                                    ISD::SETLT);
6120   SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
6121   SDValue CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
6122                                     SignSet, Four, Zero);
6123
6124   // If the sign bit of the integer is set, the large number will be treated
6125   // as a negative number.  To counteract this, the dynamic code adds an
6126   // offset depending on the data type.
6127   uint64_t FF;
6128   switch (Op0.getValueType().getSimpleVT()) {
6129   default: assert(0 && "Unsupported integer type!");
6130   case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
6131   case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
6132   case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
6133   case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
6134   }
6135   if (TLI.isLittleEndian()) FF <<= 32;
6136   static Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
6137
6138   SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
6139   unsigned Alignment = 1 << cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
6140   CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
6141   Alignment = std::min(Alignment, 4u);
6142   SDValue FudgeInReg;
6143   if (DestVT == MVT::f32)
6144     FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
6145                              PseudoSourceValue::getConstantPool(), 0,
6146                              false, Alignment);
6147   else {
6148     FudgeInReg =
6149       LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, DestVT,
6150                                 DAG.getEntryNode(), CPIdx,
6151                                 PseudoSourceValue::getConstantPool(), 0,
6152                                 MVT::f32, false, Alignment));
6153   }
6154
6155   return DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg);
6156 }
6157
6158 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
6159 /// *INT_TO_FP operation of the specified operand when the target requests that
6160 /// we promote it.  At this point, we know that the result and operand types are
6161 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
6162 /// operation that takes a larger input.
6163 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
6164                                                     MVT DestVT,
6165                                                     bool isSigned) {
6166   // First step, figure out the appropriate *INT_TO_FP operation to use.
6167   MVT NewInTy = LegalOp.getValueType();
6168
6169   unsigned OpToUse = 0;
6170
6171   // Scan for the appropriate larger type to use.
6172   while (1) {
6173     NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT()+1);
6174     assert(NewInTy.isInteger() && "Ran out of possibilities!");
6175
6176     // If the target supports SINT_TO_FP of this type, use it.
6177     switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
6178       default: break;
6179       case TargetLowering::Legal:
6180         if (!TLI.isTypeLegal(NewInTy))
6181           break;  // Can't use this datatype.
6182         // FALL THROUGH.
6183       case TargetLowering::Custom:
6184         OpToUse = ISD::SINT_TO_FP;
6185         break;
6186     }
6187     if (OpToUse) break;
6188     if (isSigned) continue;
6189
6190     // If the target supports UINT_TO_FP of this type, use it.
6191     switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
6192       default: break;
6193       case TargetLowering::Legal:
6194         if (!TLI.isTypeLegal(NewInTy))
6195           break;  // Can't use this datatype.
6196         // FALL THROUGH.
6197       case TargetLowering::Custom:
6198         OpToUse = ISD::UINT_TO_FP;
6199         break;
6200     }
6201     if (OpToUse) break;
6202
6203     // Otherwise, try a larger type.
6204   }
6205
6206   // Okay, we found the operation and type to use.  Zero extend our input to the
6207   // desired type then run the operation on it.
6208   return DAG.getNode(OpToUse, DestVT,
6209                      DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
6210                                  NewInTy, LegalOp));
6211 }
6212
6213 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
6214 /// FP_TO_*INT operation of the specified operand when the target requests that
6215 /// we promote it.  At this point, we know that the result and operand types are
6216 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
6217 /// operation that returns a larger result.
6218 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
6219                                                     MVT DestVT,
6220                                                     bool isSigned) {
6221   // First step, figure out the appropriate FP_TO*INT operation to use.
6222   MVT NewOutTy = DestVT;
6223
6224   unsigned OpToUse = 0;
6225
6226   // Scan for the appropriate larger type to use.
6227   while (1) {
6228     NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT()+1);
6229     assert(NewOutTy.isInteger() && "Ran out of possibilities!");
6230
6231     // If the target supports FP_TO_SINT returning this type, use it.
6232     switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
6233     default: break;
6234     case TargetLowering::Legal:
6235       if (!TLI.isTypeLegal(NewOutTy))
6236         break;  // Can't use this datatype.
6237       // FALL THROUGH.
6238     case TargetLowering::Custom:
6239       OpToUse = ISD::FP_TO_SINT;
6240       break;
6241     }
6242     if (OpToUse) break;
6243
6244     // If the target supports FP_TO_UINT of this type, use it.
6245     switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
6246     default: break;
6247     case TargetLowering::Legal:
6248       if (!TLI.isTypeLegal(NewOutTy))
6249         break;  // Can't use this datatype.
6250       // FALL THROUGH.
6251     case TargetLowering::Custom:
6252       OpToUse = ISD::FP_TO_UINT;
6253       break;
6254     }
6255     if (OpToUse) break;
6256
6257     // Otherwise, try a larger type.
6258   }
6259
6260   
6261   // Okay, we found the operation and type to use.
6262   SDValue Operation = DAG.getNode(OpToUse, NewOutTy, LegalOp);
6263
6264   // If the operation produces an invalid type, it must be custom lowered.  Use
6265   // the target lowering hooks to expand it.  Just keep the low part of the
6266   // expanded operation, we know that we're truncating anyway.
6267   if (getTypeAction(NewOutTy) == Expand) {
6268     SmallVector<SDValue, 2> Results;
6269     TLI.ReplaceNodeResults(Operation.getNode(), Results, DAG);
6270     assert(Results.size() == 1 && "Incorrect FP_TO_XINT lowering!");
6271     Operation = Results[0];
6272   }
6273
6274   // Truncate the result of the extended FP_TO_*INT operation to the desired
6275   // size.
6276   return DAG.getNode(ISD::TRUNCATE, DestVT, Operation);
6277 }
6278
6279 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
6280 ///
6281 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op) {
6282   MVT VT = Op.getValueType();
6283   MVT SHVT = TLI.getShiftAmountTy();
6284   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
6285   switch (VT.getSimpleVT()) {
6286   default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
6287   case MVT::i16:
6288     Tmp2 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
6289     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
6290     return DAG.getNode(ISD::OR, VT, Tmp1, Tmp2);
6291   case MVT::i32:
6292     Tmp4 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
6293     Tmp3 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
6294     Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
6295     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
6296     Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
6297     Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(0xFF00, VT));
6298     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
6299     Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
6300     return DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
6301   case MVT::i64:
6302     Tmp8 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(56, SHVT));
6303     Tmp7 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(40, SHVT));
6304     Tmp6 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
6305     Tmp5 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
6306     Tmp4 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
6307     Tmp3 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
6308     Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(40, SHVT));
6309     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(56, SHVT));
6310     Tmp7 = DAG.getNode(ISD::AND, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
6311     Tmp6 = DAG.getNode(ISD::AND, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
6312     Tmp5 = DAG.getNode(ISD::AND, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
6313     Tmp4 = DAG.getNode(ISD::AND, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
6314     Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
6315     Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
6316     Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp7);
6317     Tmp6 = DAG.getNode(ISD::OR, VT, Tmp6, Tmp5);
6318     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
6319     Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
6320     Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp6);
6321     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
6322     return DAG.getNode(ISD::OR, VT, Tmp8, Tmp4);
6323   }
6324 }
6325
6326 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
6327 ///
6328 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op) {
6329   switch (Opc) {
6330   default: assert(0 && "Cannot expand this yet!");
6331   case ISD::CTPOP: {
6332     static const uint64_t mask[6] = {
6333       0x5555555555555555ULL, 0x3333333333333333ULL,
6334       0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
6335       0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
6336     };
6337     MVT VT = Op.getValueType();
6338     MVT ShVT = TLI.getShiftAmountTy();
6339     unsigned len = VT.getSizeInBits();
6340     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
6341       //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
6342       SDValue Tmp2 = DAG.getConstant(mask[i], VT);
6343       SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
6344       Op = DAG.getNode(ISD::ADD, VT, DAG.getNode(ISD::AND, VT, Op, Tmp2),
6345                        DAG.getNode(ISD::AND, VT,
6346                                    DAG.getNode(ISD::SRL, VT, Op, Tmp3),Tmp2));
6347     }
6348     return Op;
6349   }
6350   case ISD::CTLZ: {
6351     // for now, we do this:
6352     // x = x | (x >> 1);
6353     // x = x | (x >> 2);
6354     // ...
6355     // x = x | (x >>16);
6356     // x = x | (x >>32); // for 64-bit input
6357     // return popcount(~x);
6358     //
6359     // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
6360     MVT VT = Op.getValueType();
6361     MVT ShVT = TLI.getShiftAmountTy();
6362     unsigned len = VT.getSizeInBits();
6363     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
6364       SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
6365       Op = DAG.getNode(ISD::OR, VT, Op, DAG.getNode(ISD::SRL, VT, Op, Tmp3));
6366     }
6367     Op = DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(~0ULL, VT));
6368     return DAG.getNode(ISD::CTPOP, VT, Op);
6369   }
6370   case ISD::CTTZ: {
6371     // for now, we use: { return popcount(~x & (x - 1)); }
6372     // unless the target has ctlz but not ctpop, in which case we use:
6373     // { return 32 - nlz(~x & (x-1)); }
6374     // see also http://www.hackersdelight.org/HDcode/ntz.cc
6375     MVT VT = Op.getValueType();
6376     SDValue Tmp2 = DAG.getConstant(~0ULL, VT);
6377     SDValue Tmp3 = DAG.getNode(ISD::AND, VT,
6378                        DAG.getNode(ISD::XOR, VT, Op, Tmp2),
6379                        DAG.getNode(ISD::SUB, VT, Op, DAG.getConstant(1, VT)));
6380     // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
6381     if (!TLI.isOperationLegal(ISD::CTPOP, VT) &&
6382         TLI.isOperationLegal(ISD::CTLZ, VT))
6383       return DAG.getNode(ISD::SUB, VT,
6384                          DAG.getConstant(VT.getSizeInBits(), VT),
6385                          DAG.getNode(ISD::CTLZ, VT, Tmp3));
6386     return DAG.getNode(ISD::CTPOP, VT, Tmp3);
6387   }
6388   }
6389 }
6390
6391 /// ExpandOp - Expand the specified SDValue into its two component pieces
6392 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
6393 /// LegalizedNodes map is filled in for any results that are not expanded, the
6394 /// ExpandedNodes map is filled in for any results that are expanded, and the
6395 /// Lo/Hi values are returned.
6396 void SelectionDAGLegalize::ExpandOp(SDValue Op, SDValue &Lo, SDValue &Hi){
6397   MVT VT = Op.getValueType();
6398   MVT NVT = TLI.getTypeToTransformTo(VT);
6399   SDNode *Node = Op.getNode();
6400   assert(getTypeAction(VT) == Expand && "Not an expanded type!");
6401   assert(((NVT.isInteger() && NVT.bitsLT(VT)) || VT.isFloatingPoint() ||
6402          VT.isVector()) && "Cannot expand to FP value or to larger int value!");
6403
6404   // See if we already expanded it.
6405   DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator I
6406     = ExpandedNodes.find(Op);
6407   if (I != ExpandedNodes.end()) {
6408     Lo = I->second.first;
6409     Hi = I->second.second;
6410     return;
6411   }
6412
6413   switch (Node->getOpcode()) {
6414   case ISD::CopyFromReg:
6415     assert(0 && "CopyFromReg must be legal!");
6416   case ISD::FP_ROUND_INREG:
6417     if (VT == MVT::ppcf128 && 
6418         TLI.getOperationAction(ISD::FP_ROUND_INREG, VT) == 
6419             TargetLowering::Custom) {
6420       SDValue SrcLo, SrcHi, Src;
6421       ExpandOp(Op.getOperand(0), SrcLo, SrcHi);
6422       Src = DAG.getNode(ISD::BUILD_PAIR, VT, SrcLo, SrcHi);
6423       SDValue Result = TLI.LowerOperation(
6424         DAG.getNode(ISD::FP_ROUND_INREG, VT, Src, Op.getOperand(1)), DAG);
6425       assert(Result.getNode()->getOpcode() == ISD::BUILD_PAIR);
6426       Lo = Result.getNode()->getOperand(0);
6427       Hi = Result.getNode()->getOperand(1);
6428       break;
6429     }
6430     // fall through
6431   default:
6432 #ifndef NDEBUG
6433     cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
6434 #endif
6435     assert(0 && "Do not know how to expand this operator!");
6436     abort();
6437   case ISD::EXTRACT_ELEMENT:
6438     ExpandOp(Node->getOperand(0), Lo, Hi);
6439     if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue())
6440       return ExpandOp(Hi, Lo, Hi);
6441     return ExpandOp(Lo, Lo, Hi);
6442   case ISD::EXTRACT_VECTOR_ELT:
6443     // ExpandEXTRACT_VECTOR_ELT tolerates invalid result types.
6444     Lo  = ExpandEXTRACT_VECTOR_ELT(Op);
6445     return ExpandOp(Lo, Lo, Hi);
6446   case ISD::UNDEF:
6447     Lo = DAG.getNode(ISD::UNDEF, NVT);
6448     Hi = DAG.getNode(ISD::UNDEF, NVT);
6449     break;
6450   case ISD::Constant: {
6451     unsigned NVTBits = NVT.getSizeInBits();
6452     const APInt &Cst = cast<ConstantSDNode>(Node)->getAPIntValue();
6453     Lo = DAG.getConstant(APInt(Cst).trunc(NVTBits), NVT);
6454     Hi = DAG.getConstant(Cst.lshr(NVTBits).trunc(NVTBits), NVT);
6455     break;
6456   }
6457   case ISD::ConstantFP: {
6458     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
6459     if (CFP->getValueType(0) == MVT::ppcf128) {
6460       APInt api = CFP->getValueAPF().bitcastToAPInt();
6461       Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &api.getRawData()[1])),
6462                              MVT::f64);
6463       Hi = DAG.getConstantFP(APFloat(APInt(64, 1, &api.getRawData()[0])), 
6464                              MVT::f64);
6465       break;
6466     }
6467     Lo = ExpandConstantFP(CFP, false, DAG, TLI);
6468     if (getTypeAction(Lo.getValueType()) == Expand)
6469       ExpandOp(Lo, Lo, Hi);
6470     break;
6471   }
6472   case ISD::BUILD_PAIR:
6473     // Return the operands.
6474     Lo = Node->getOperand(0);
6475     Hi = Node->getOperand(1);
6476     break;
6477       
6478   case ISD::MERGE_VALUES:
6479     if (Node->getNumValues() == 1) {
6480       ExpandOp(Op.getOperand(0), Lo, Hi);
6481       break;
6482     }
6483     // FIXME: For now only expand i64,chain = MERGE_VALUES (x, y)
6484     assert(Op.getResNo() == 0 && Node->getNumValues() == 2 &&
6485            Op.getValue(1).getValueType() == MVT::Other &&
6486            "unhandled MERGE_VALUES");
6487     ExpandOp(Op.getOperand(0), Lo, Hi);
6488     // Remember that we legalized the chain.
6489     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Op.getOperand(1)));
6490     break;
6491     
6492   case ISD::SIGN_EXTEND_INREG:
6493     ExpandOp(Node->getOperand(0), Lo, Hi);
6494     // sext_inreg the low part if needed.
6495     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
6496     
6497     // The high part gets the sign extension from the lo-part.  This handles
6498     // things like sextinreg V:i64 from i8.
6499     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
6500                      DAG.getConstant(NVT.getSizeInBits()-1,
6501                                      TLI.getShiftAmountTy()));
6502     break;
6503
6504   case ISD::BSWAP: {
6505     ExpandOp(Node->getOperand(0), Lo, Hi);
6506     SDValue TempLo = DAG.getNode(ISD::BSWAP, NVT, Hi);
6507     Hi = DAG.getNode(ISD::BSWAP, NVT, Lo);
6508     Lo = TempLo;
6509     break;
6510   }
6511     
6512   case ISD::CTPOP:
6513     ExpandOp(Node->getOperand(0), Lo, Hi);
6514     Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
6515                      DAG.getNode(ISD::CTPOP, NVT, Lo),
6516                      DAG.getNode(ISD::CTPOP, NVT, Hi));
6517     Hi = DAG.getConstant(0, NVT);
6518     break;
6519
6520   case ISD::CTLZ: {
6521     // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
6522     ExpandOp(Node->getOperand(0), Lo, Hi);
6523     SDValue BitsC = DAG.getConstant(NVT.getSizeInBits(), NVT);
6524     SDValue HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
6525     SDValue TopNotZero = DAG.getSetCC(TLI.getSetCCResultType(HLZ), HLZ, BitsC,
6526                                         ISD::SETNE);
6527     SDValue LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
6528     LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
6529
6530     Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
6531     Hi = DAG.getConstant(0, NVT);
6532     break;
6533   }
6534
6535   case ISD::CTTZ: {
6536     // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
6537     ExpandOp(Node->getOperand(0), Lo, Hi);
6538     SDValue BitsC = DAG.getConstant(NVT.getSizeInBits(), NVT);
6539     SDValue LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
6540     SDValue BotNotZero = DAG.getSetCC(TLI.getSetCCResultType(LTZ), LTZ, BitsC,
6541                                         ISD::SETNE);
6542     SDValue HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
6543     HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
6544
6545     Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
6546     Hi = DAG.getConstant(0, NVT);
6547     break;
6548   }
6549
6550   case ISD::VAARG: {
6551     SDValue Ch = Node->getOperand(0);   // Legalize the chain.
6552     SDValue Ptr = Node->getOperand(1);  // Legalize the pointer.
6553     Lo = DAG.getVAArg(NVT, Ch, Ptr, Node->getOperand(2));
6554     Hi = DAG.getVAArg(NVT, Lo.getValue(1), Ptr, Node->getOperand(2));
6555
6556     // Remember that we legalized the chain.
6557     Hi = LegalizeOp(Hi);
6558     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
6559     if (TLI.isBigEndian())
6560       std::swap(Lo, Hi);
6561     break;
6562   }
6563     
6564   case ISD::LOAD: {
6565     LoadSDNode *LD = cast<LoadSDNode>(Node);
6566     SDValue Ch  = LD->getChain();    // Legalize the chain.
6567     SDValue Ptr = LD->getBasePtr();  // Legalize the pointer.
6568     ISD::LoadExtType ExtType = LD->getExtensionType();
6569     const Value *SV = LD->getSrcValue();
6570     int SVOffset = LD->getSrcValueOffset();
6571     unsigned Alignment = LD->getAlignment();
6572     bool isVolatile = LD->isVolatile();
6573
6574     if (ExtType == ISD::NON_EXTLOAD) {
6575       Lo = DAG.getLoad(NVT, Ch, Ptr, SV, SVOffset,
6576                        isVolatile, Alignment);
6577       if (VT == MVT::f32 || VT == MVT::f64) {
6578         // f32->i32 or f64->i64 one to one expansion.
6579         // Remember that we legalized the chain.
6580         AddLegalizedOperand(SDValue(Node, 1), LegalizeOp(Lo.getValue(1)));
6581         // Recursively expand the new load.
6582         if (getTypeAction(NVT) == Expand)
6583           ExpandOp(Lo, Lo, Hi);
6584         break;
6585       }
6586
6587       // Increment the pointer to the other half.
6588       unsigned IncrementSize = Lo.getValueType().getSizeInBits()/8;
6589       Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
6590                         DAG.getIntPtrConstant(IncrementSize));
6591       SVOffset += IncrementSize;
6592       Alignment = MinAlign(Alignment, IncrementSize);
6593       Hi = DAG.getLoad(NVT, Ch, Ptr, SV, SVOffset,
6594                        isVolatile, Alignment);
6595
6596       // Build a factor node to remember that this load is independent of the
6597       // other one.
6598       SDValue TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
6599                                  Hi.getValue(1));
6600
6601       // Remember that we legalized the chain.
6602       AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
6603       if (TLI.isBigEndian())
6604         std::swap(Lo, Hi);
6605     } else {
6606       MVT EVT = LD->getMemoryVT();
6607
6608       if ((VT == MVT::f64 && EVT == MVT::f32) ||
6609           (VT == MVT::ppcf128 && (EVT==MVT::f64 || EVT==MVT::f32))) {
6610         // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
6611         SDValue Load = DAG.getLoad(EVT, Ch, Ptr, SV,
6612                                      SVOffset, isVolatile, Alignment);
6613         // Remember that we legalized the chain.
6614         AddLegalizedOperand(SDValue(Node, 1), LegalizeOp(Load.getValue(1)));
6615         ExpandOp(DAG.getNode(ISD::FP_EXTEND, VT, Load), Lo, Hi);
6616         break;
6617       }
6618     
6619       if (EVT == NVT)
6620         Lo = DAG.getLoad(NVT, Ch, Ptr, SV,
6621                          SVOffset, isVolatile, Alignment);
6622       else
6623         Lo = DAG.getExtLoad(ExtType, NVT, Ch, Ptr, SV,
6624                             SVOffset, EVT, isVolatile,
6625                             Alignment);
6626     
6627       // Remember that we legalized the chain.
6628       AddLegalizedOperand(SDValue(Node, 1), LegalizeOp(Lo.getValue(1)));
6629
6630       if (ExtType == ISD::SEXTLOAD) {
6631         // The high part is obtained by SRA'ing all but one of the bits of the
6632         // lo part.
6633         unsigned LoSize = Lo.getValueType().getSizeInBits();
6634         Hi = DAG.getNode(ISD::SRA, NVT, Lo,
6635                          DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
6636       } else if (ExtType == ISD::ZEXTLOAD) {
6637         // The high part is just a zero.
6638         Hi = DAG.getConstant(0, NVT);
6639       } else /* if (ExtType == ISD::EXTLOAD) */ {
6640         // The high part is undefined.
6641         Hi = DAG.getNode(ISD::UNDEF, NVT);
6642       }
6643     }
6644     break;
6645   }
6646   case ISD::AND:
6647   case ISD::OR:
6648   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
6649     SDValue LL, LH, RL, RH;
6650     ExpandOp(Node->getOperand(0), LL, LH);
6651     ExpandOp(Node->getOperand(1), RL, RH);
6652     Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
6653     Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
6654     break;
6655   }
6656   case ISD::SELECT: {
6657     SDValue LL, LH, RL, RH;
6658     ExpandOp(Node->getOperand(1), LL, LH);
6659     ExpandOp(Node->getOperand(2), RL, RH);
6660     if (getTypeAction(NVT) == Expand)
6661       NVT = TLI.getTypeToExpandTo(NVT);
6662     Lo = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LL, RL);
6663     if (VT != MVT::f32)
6664       Hi = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LH, RH);
6665     break;
6666   }
6667   case ISD::SELECT_CC: {
6668     SDValue TL, TH, FL, FH;
6669     ExpandOp(Node->getOperand(2), TL, TH);
6670     ExpandOp(Node->getOperand(3), FL, FH);
6671     if (getTypeAction(NVT) == Expand)
6672       NVT = TLI.getTypeToExpandTo(NVT);
6673     Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
6674                      Node->getOperand(1), TL, FL, Node->getOperand(4));
6675     if (VT != MVT::f32)
6676       Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
6677                        Node->getOperand(1), TH, FH, Node->getOperand(4));
6678     break;
6679   }
6680   case ISD::ANY_EXTEND:
6681     // The low part is any extension of the input (which degenerates to a copy).
6682     Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, Node->getOperand(0));
6683     // The high part is undefined.
6684     Hi = DAG.getNode(ISD::UNDEF, NVT);
6685     break;
6686   case ISD::SIGN_EXTEND: {
6687     // The low part is just a sign extension of the input (which degenerates to
6688     // a copy).
6689     Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, Node->getOperand(0));
6690
6691     // The high part is obtained by SRA'ing all but one of the bits of the lo
6692     // part.
6693     unsigned LoSize = Lo.getValueType().getSizeInBits();
6694     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
6695                      DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
6696     break;
6697   }
6698   case ISD::ZERO_EXTEND:
6699     // The low part is just a zero extension of the input (which degenerates to
6700     // a copy).
6701     Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
6702
6703     // The high part is just a zero.
6704     Hi = DAG.getConstant(0, NVT);
6705     break;
6706     
6707   case ISD::TRUNCATE: {
6708     // The input value must be larger than this value.  Expand *it*.
6709     SDValue NewLo;
6710     ExpandOp(Node->getOperand(0), NewLo, Hi);
6711     
6712     // The low part is now either the right size, or it is closer.  If not the
6713     // right size, make an illegal truncate so we recursively expand it.
6714     if (NewLo.getValueType() != Node->getValueType(0))
6715       NewLo = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), NewLo);
6716     ExpandOp(NewLo, Lo, Hi);
6717     break;
6718   }
6719     
6720   case ISD::BIT_CONVERT: {
6721     SDValue Tmp;
6722     if (TLI.getOperationAction(ISD::BIT_CONVERT, VT) == TargetLowering::Custom){
6723       // If the target wants to, allow it to lower this itself.
6724       switch (getTypeAction(Node->getOperand(0).getValueType())) {
6725       case Expand: assert(0 && "cannot expand FP!");
6726       case Legal:   Tmp = LegalizeOp(Node->getOperand(0)); break;
6727       case Promote: Tmp = PromoteOp (Node->getOperand(0)); break;
6728       }
6729       Tmp = TLI.LowerOperation(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp), DAG);
6730     }
6731
6732     // f32 / f64 must be expanded to i32 / i64.
6733     if (VT == MVT::f32 || VT == MVT::f64) {
6734       Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
6735       if (getTypeAction(NVT) == Expand)
6736         ExpandOp(Lo, Lo, Hi);
6737       break;
6738     }
6739
6740     // If source operand will be expanded to the same type as VT, i.e.
6741     // i64 <- f64, i32 <- f32, expand the source operand instead.
6742     MVT VT0 = Node->getOperand(0).getValueType();
6743     if (getTypeAction(VT0) == Expand && TLI.getTypeToTransformTo(VT0) == VT) {
6744       ExpandOp(Node->getOperand(0), Lo, Hi);
6745       break;
6746     }
6747
6748     // Turn this into a load/store pair by default.
6749     if (Tmp.getNode() == 0)
6750       Tmp = EmitStackConvert(Node->getOperand(0), VT, VT);
6751     
6752     ExpandOp(Tmp, Lo, Hi);
6753     break;
6754   }
6755
6756   case ISD::READCYCLECOUNTER: {
6757     assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) == 
6758                  TargetLowering::Custom &&
6759            "Must custom expand ReadCycleCounter");
6760     SDValue Tmp = TLI.LowerOperation(Op, DAG);
6761     assert(Tmp.getNode() && "Node must be custom expanded!");
6762     ExpandOp(Tmp.getValue(0), Lo, Hi);
6763     AddLegalizedOperand(SDValue(Node, 1), // Remember we legalized the chain.
6764                         LegalizeOp(Tmp.getValue(1)));
6765     break;
6766   }
6767
6768   case ISD::ATOMIC_CMP_SWAP_64: {
6769     // This operation does not need a loop.
6770     SDValue Tmp = TLI.LowerOperation(Op, DAG);
6771     assert(Tmp.getNode() && "Node must be custom expanded!");
6772     ExpandOp(Tmp.getValue(0), Lo, Hi);
6773     AddLegalizedOperand(SDValue(Node, 1), // Remember we legalized the chain.
6774                         LegalizeOp(Tmp.getValue(1)));
6775     break;
6776   }
6777
6778   case ISD::ATOMIC_LOAD_ADD_64:
6779   case ISD::ATOMIC_LOAD_SUB_64:
6780   case ISD::ATOMIC_LOAD_AND_64:
6781   case ISD::ATOMIC_LOAD_OR_64:
6782   case ISD::ATOMIC_LOAD_XOR_64:
6783   case ISD::ATOMIC_LOAD_NAND_64:
6784   case ISD::ATOMIC_SWAP_64: {
6785     // These operations require a loop to be generated.  We can't do that yet,
6786     // so substitute a target-dependent pseudo and expand that later.
6787     SDValue In2Lo, In2Hi, In2;
6788     ExpandOp(Op.getOperand(2), In2Lo, In2Hi);
6789     In2 = DAG.getNode(ISD::BUILD_PAIR, VT, In2Lo, In2Hi);
6790     AtomicSDNode* Anode = cast<AtomicSDNode>(Node);
6791     SDValue Replace = 
6792       DAG.getAtomic(Op.getOpcode(), Op.getOperand(0), Op.getOperand(1), In2,
6793                     Anode->getSrcValue(), Anode->getAlignment());
6794     SDValue Result = TLI.LowerOperation(Replace, DAG);
6795     ExpandOp(Result.getValue(0), Lo, Hi);
6796     // Remember that we legalized the chain.
6797     AddLegalizedOperand(SDValue(Node,1), LegalizeOp(Result.getValue(1)));
6798     break;
6799   }
6800
6801     // These operators cannot be expanded directly, emit them as calls to
6802     // library functions.
6803   case ISD::FP_TO_SINT: {
6804     if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
6805       SDValue Op;
6806       switch (getTypeAction(Node->getOperand(0).getValueType())) {
6807       case Expand: assert(0 && "cannot expand FP!");
6808       case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
6809       case Promote: Op = PromoteOp (Node->getOperand(0)); break;
6810       }
6811
6812       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
6813
6814       // Now that the custom expander is done, expand the result, which is still
6815       // VT.
6816       if (Op.getNode()) {
6817         ExpandOp(Op, Lo, Hi);
6818         break;
6819       }
6820     }
6821
6822     RTLIB::Libcall LC = RTLIB::getFPTOSINT(Node->getOperand(0).getValueType(),
6823                                            VT);
6824     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected uint-to-fp conversion!");
6825     Lo = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Hi);
6826     break;
6827   }
6828
6829   case ISD::FP_TO_UINT: {
6830     if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
6831       SDValue Op;
6832       switch (getTypeAction(Node->getOperand(0).getValueType())) {
6833         case Expand: assert(0 && "cannot expand FP!");
6834         case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
6835         case Promote: Op = PromoteOp (Node->getOperand(0)); break;
6836       }
6837         
6838       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_UINT, VT, Op), DAG);
6839
6840       // Now that the custom expander is done, expand the result.
6841       if (Op.getNode()) {
6842         ExpandOp(Op, Lo, Hi);
6843         break;
6844       }
6845     }
6846
6847     RTLIB::Libcall LC = RTLIB::getFPTOUINT(Node->getOperand(0).getValueType(),
6848                                            VT);
6849     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-uint conversion!");
6850     Lo = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Hi);
6851     break;
6852   }
6853
6854   case ISD::SHL: {
6855     // If the target wants custom lowering, do so.
6856     SDValue ShiftAmt = LegalizeOp(Node->getOperand(1));
6857     if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
6858       SDValue Op = DAG.getNode(ISD::SHL, VT, Node->getOperand(0), ShiftAmt);
6859       Op = TLI.LowerOperation(Op, DAG);
6860       if (Op.getNode()) {
6861         // Now that the custom expander is done, expand the result, which is
6862         // still VT.
6863         ExpandOp(Op, Lo, Hi);
6864         break;
6865       }
6866     }
6867     
6868     // If ADDC/ADDE are supported and if the shift amount is a constant 1, emit 
6869     // this X << 1 as X+X.
6870     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(ShiftAmt)) {
6871       if (ShAmt->getAPIntValue() == 1 && TLI.isOperationLegal(ISD::ADDC, NVT) && 
6872           TLI.isOperationLegal(ISD::ADDE, NVT)) {
6873         SDValue LoOps[2], HiOps[3];
6874         ExpandOp(Node->getOperand(0), LoOps[0], HiOps[0]);
6875         SDVTList VTList = DAG.getVTList(LoOps[0].getValueType(), MVT::Flag);
6876         LoOps[1] = LoOps[0];
6877         Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
6878
6879         HiOps[1] = HiOps[0];
6880         HiOps[2] = Lo.getValue(1);
6881         Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
6882         break;
6883       }
6884     }
6885     
6886     // If we can emit an efficient shift operation, do so now.
6887     if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi))
6888       break;
6889
6890     // If this target supports SHL_PARTS, use it.
6891     TargetLowering::LegalizeAction Action =
6892       TLI.getOperationAction(ISD::SHL_PARTS, NVT);
6893     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6894         Action == TargetLowering::Custom) {
6895       ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
6896       break;
6897     }
6898
6899     // Otherwise, emit a libcall.
6900     Lo = ExpandLibCall(RTLIB::SHL_I64, Node, false/*left shift=unsigned*/, Hi);
6901     break;
6902   }
6903
6904   case ISD::SRA: {
6905     // If the target wants custom lowering, do so.
6906     SDValue ShiftAmt = LegalizeOp(Node->getOperand(1));
6907     if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
6908       SDValue Op = DAG.getNode(ISD::SRA, VT, Node->getOperand(0), ShiftAmt);
6909       Op = TLI.LowerOperation(Op, DAG);
6910       if (Op.getNode()) {
6911         // Now that the custom expander is done, expand the result, which is
6912         // still VT.
6913         ExpandOp(Op, Lo, Hi);
6914         break;
6915       }
6916     }
6917     
6918     // If we can emit an efficient shift operation, do so now.
6919     if (ExpandShift(ISD::SRA, Node->getOperand(0), ShiftAmt, Lo, Hi))
6920       break;
6921
6922     // If this target supports SRA_PARTS, use it.
6923     TargetLowering::LegalizeAction Action =
6924       TLI.getOperationAction(ISD::SRA_PARTS, NVT);
6925     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6926         Action == TargetLowering::Custom) {
6927       ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
6928       break;
6929     }
6930
6931     // Otherwise, emit a libcall.
6932     Lo = ExpandLibCall(RTLIB::SRA_I64, Node, true/*ashr is signed*/, Hi);
6933     break;
6934   }
6935
6936   case ISD::SRL: {
6937     // If the target wants custom lowering, do so.
6938     SDValue ShiftAmt = LegalizeOp(Node->getOperand(1));
6939     if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
6940       SDValue Op = DAG.getNode(ISD::SRL, VT, Node->getOperand(0), ShiftAmt);
6941       Op = TLI.LowerOperation(Op, DAG);
6942       if (Op.getNode()) {
6943         // Now that the custom expander is done, expand the result, which is
6944         // still VT.
6945         ExpandOp(Op, Lo, Hi);
6946         break;
6947       }
6948     }
6949
6950     // If we can emit an efficient shift operation, do so now.
6951     if (ExpandShift(ISD::SRL, Node->getOperand(0), ShiftAmt, Lo, Hi))
6952       break;
6953
6954     // If this target supports SRL_PARTS, use it.
6955     TargetLowering::LegalizeAction Action =
6956       TLI.getOperationAction(ISD::SRL_PARTS, NVT);
6957     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6958         Action == TargetLowering::Custom) {
6959       ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
6960       break;
6961     }
6962
6963     // Otherwise, emit a libcall.
6964     Lo = ExpandLibCall(RTLIB::SRL_I64, Node, false/*lshr is unsigned*/, Hi);
6965     break;
6966   }
6967
6968   case ISD::ADD:
6969   case ISD::SUB: {
6970     // If the target wants to custom expand this, let them.
6971     if (TLI.getOperationAction(Node->getOpcode(), VT) ==
6972             TargetLowering::Custom) {
6973       SDValue Result = TLI.LowerOperation(Op, DAG);
6974       if (Result.getNode()) {
6975         ExpandOp(Result, Lo, Hi);
6976         break;
6977       }
6978     }
6979     // Expand the subcomponents.
6980     SDValue LHSL, LHSH, RHSL, RHSH;
6981     ExpandOp(Node->getOperand(0), LHSL, LHSH);
6982     ExpandOp(Node->getOperand(1), RHSL, RHSH);
6983     SDValue LoOps[2], HiOps[3];
6984     LoOps[0] = LHSL;
6985     LoOps[1] = RHSL;
6986     HiOps[0] = LHSH;
6987     HiOps[1] = RHSH;
6988
6989     //cascaded check to see if any smaller size has a a carry flag.
6990     unsigned OpV = Node->getOpcode() == ISD::ADD ? ISD::ADDC : ISD::SUBC;
6991     bool hasCarry = false;
6992     for (unsigned BitSize = NVT.getSizeInBits(); BitSize != 0; BitSize /= 2) {
6993       MVT AVT = MVT::getIntegerVT(BitSize);
6994       if (TLI.isOperationLegal(OpV, AVT)) {
6995         hasCarry = true;
6996         break;
6997       }
6998     }
6999
7000     if(hasCarry) {
7001       SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
7002       if (Node->getOpcode() == ISD::ADD) {
7003         Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
7004         HiOps[2] = Lo.getValue(1);
7005         Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
7006       } else {
7007         Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
7008         HiOps[2] = Lo.getValue(1);
7009         Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
7010       }
7011       break;
7012     } else {
7013       if (Node->getOpcode() == ISD::ADD) {
7014         Lo = DAG.getNode(ISD::ADD, NVT, LoOps, 2);
7015         Hi = DAG.getNode(ISD::ADD, NVT, HiOps, 2);
7016         SDValue Cmp1 = DAG.getSetCC(TLI.getSetCCResultType(Lo),
7017                                     Lo, LoOps[0], ISD::SETULT);
7018         SDValue Carry1 = DAG.getNode(ISD::SELECT, NVT, Cmp1,
7019                                      DAG.getConstant(1, NVT), 
7020                                      DAG.getConstant(0, NVT));
7021         SDValue Cmp2 = DAG.getSetCC(TLI.getSetCCResultType(Lo),
7022                                     Lo, LoOps[1], ISD::SETULT);
7023         SDValue Carry2 = DAG.getNode(ISD::SELECT, NVT, Cmp2,
7024                                     DAG.getConstant(1, NVT), 
7025                                     Carry1);
7026         Hi = DAG.getNode(ISD::ADD, NVT, Hi, Carry2);
7027       } else {
7028         Lo = DAG.getNode(ISD::SUB, NVT, LoOps, 2);
7029         Hi = DAG.getNode(ISD::SUB, NVT, HiOps, 2);
7030         SDValue Cmp = DAG.getSetCC(NVT, LoOps[0], LoOps[1], ISD::SETULT);
7031         SDValue Borrow = DAG.getNode(ISD::SELECT, NVT, Cmp,
7032                                      DAG.getConstant(1, NVT), 
7033                                      DAG.getConstant(0, NVT));
7034         Hi = DAG.getNode(ISD::SUB, NVT, Hi, Borrow);
7035       }
7036       break;
7037     }
7038   }
7039     
7040   case ISD::ADDC:
7041   case ISD::SUBC: {
7042     // Expand the subcomponents.
7043     SDValue LHSL, LHSH, RHSL, RHSH;
7044     ExpandOp(Node->getOperand(0), LHSL, LHSH);
7045     ExpandOp(Node->getOperand(1), RHSL, RHSH);
7046     SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
7047     SDValue LoOps[2] = { LHSL, RHSL };
7048     SDValue HiOps[3] = { LHSH, RHSH };
7049     
7050     if (Node->getOpcode() == ISD::ADDC) {
7051       Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
7052       HiOps[2] = Lo.getValue(1);
7053       Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
7054     } else {
7055       Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
7056       HiOps[2] = Lo.getValue(1);
7057       Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
7058     }
7059     // Remember that we legalized the flag.
7060     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Hi.getValue(1)));
7061     break;
7062   }
7063   case ISD::ADDE:
7064   case ISD::SUBE: {
7065     // Expand the subcomponents.
7066     SDValue LHSL, LHSH, RHSL, RHSH;
7067     ExpandOp(Node->getOperand(0), LHSL, LHSH);
7068     ExpandOp(Node->getOperand(1), RHSL, RHSH);
7069     SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
7070     SDValue LoOps[3] = { LHSL, RHSL, Node->getOperand(2) };
7071     SDValue HiOps[3] = { LHSH, RHSH };
7072     
7073     Lo = DAG.getNode(Node->getOpcode(), VTList, LoOps, 3);
7074     HiOps[2] = Lo.getValue(1);
7075     Hi = DAG.getNode(Node->getOpcode(), VTList, HiOps, 3);
7076     
7077     // Remember that we legalized the flag.
7078     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Hi.getValue(1)));
7079     break;
7080   }
7081   case ISD::MUL: {
7082     // If the target wants to custom expand this, let them.
7083     if (TLI.getOperationAction(ISD::MUL, VT) == TargetLowering::Custom) {
7084       SDValue New = TLI.LowerOperation(Op, DAG);
7085       if (New.getNode()) {
7086         ExpandOp(New, Lo, Hi);
7087         break;
7088       }
7089     }
7090     
7091     bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, NVT);
7092     bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, NVT);
7093     bool HasSMUL_LOHI = TLI.isOperationLegal(ISD::SMUL_LOHI, NVT);
7094     bool HasUMUL_LOHI = TLI.isOperationLegal(ISD::UMUL_LOHI, NVT);
7095     if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
7096       SDValue LL, LH, RL, RH;
7097       ExpandOp(Node->getOperand(0), LL, LH);
7098       ExpandOp(Node->getOperand(1), RL, RH);
7099       unsigned OuterBitSize = Op.getValueSizeInBits();
7100       unsigned InnerBitSize = RH.getValueSizeInBits();
7101       unsigned LHSSB = DAG.ComputeNumSignBits(Op.getOperand(0));
7102       unsigned RHSSB = DAG.ComputeNumSignBits(Op.getOperand(1));
7103       APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
7104       if (DAG.MaskedValueIsZero(Node->getOperand(0), HighMask) &&
7105           DAG.MaskedValueIsZero(Node->getOperand(1), HighMask)) {
7106         // The inputs are both zero-extended.
7107         if (HasUMUL_LOHI) {
7108           // We can emit a umul_lohi.
7109           Lo = DAG.getNode(ISD::UMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
7110           Hi = SDValue(Lo.getNode(), 1);
7111           break;
7112         }
7113         if (HasMULHU) {
7114           // We can emit a mulhu+mul.
7115           Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
7116           Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
7117           break;
7118         }
7119       }
7120       if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
7121         // The input values are both sign-extended.
7122         if (HasSMUL_LOHI) {
7123           // We can emit a smul_lohi.
7124           Lo = DAG.getNode(ISD::SMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
7125           Hi = SDValue(Lo.getNode(), 1);
7126           break;
7127         }
7128         if (HasMULHS) {
7129           // We can emit a mulhs+mul.
7130           Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
7131           Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
7132           break;
7133         }
7134       }
7135       if (HasUMUL_LOHI) {
7136         // Lo,Hi = umul LHS, RHS.
7137         SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI,
7138                                          DAG.getVTList(NVT, NVT), LL, RL);
7139         Lo = UMulLOHI;
7140         Hi = UMulLOHI.getValue(1);
7141         RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
7142         LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
7143         Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
7144         Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
7145         break;
7146       }
7147       if (HasMULHU) {
7148         Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
7149         Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
7150         RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
7151         LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
7152         Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
7153         Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
7154         break;
7155       }
7156     }
7157
7158     // If nothing else, we can make a libcall.
7159     Lo = ExpandLibCall(RTLIB::MUL_I64, Node, false/*sign irrelevant*/, Hi);
7160     break;
7161   }
7162   case ISD::SDIV:
7163     Lo = ExpandLibCall(RTLIB::SDIV_I64, Node, true, Hi);
7164     break;
7165   case ISD::UDIV:
7166     Lo = ExpandLibCall(RTLIB::UDIV_I64, Node, true, Hi);
7167     break;
7168   case ISD::SREM:
7169     Lo = ExpandLibCall(RTLIB::SREM_I64, Node, true, Hi);
7170     break;
7171   case ISD::UREM:
7172     Lo = ExpandLibCall(RTLIB::UREM_I64, Node, true, Hi);
7173     break;
7174
7175   case ISD::FADD:
7176     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::ADD_F32,
7177                                         RTLIB::ADD_F64,
7178                                         RTLIB::ADD_F80,
7179                                         RTLIB::ADD_PPCF128),
7180                        Node, false, Hi);
7181     break;
7182   case ISD::FSUB:
7183     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::SUB_F32,
7184                                         RTLIB::SUB_F64,
7185                                         RTLIB::SUB_F80,
7186                                         RTLIB::SUB_PPCF128),
7187                        Node, false, Hi);
7188     break;
7189   case ISD::FMUL:
7190     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::MUL_F32,
7191                                         RTLIB::MUL_F64,
7192                                         RTLIB::MUL_F80,
7193                                         RTLIB::MUL_PPCF128),
7194                        Node, false, Hi);
7195     break;
7196   case ISD::FDIV:
7197     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::DIV_F32,
7198                                         RTLIB::DIV_F64,
7199                                         RTLIB::DIV_F80,
7200                                         RTLIB::DIV_PPCF128),
7201                        Node, false, Hi);
7202     break;
7203   case ISD::FP_EXTEND: {
7204     if (VT == MVT::ppcf128) {
7205       assert(Node->getOperand(0).getValueType()==MVT::f32 ||
7206              Node->getOperand(0).getValueType()==MVT::f64);
7207       const uint64_t zero = 0;
7208       if (Node->getOperand(0).getValueType()==MVT::f32)
7209         Hi = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Node->getOperand(0));
7210       else
7211         Hi = Node->getOperand(0);
7212       Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
7213       break;
7214     }
7215     RTLIB::Libcall LC = RTLIB::getFPEXT(Node->getOperand(0).getValueType(), VT);
7216     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported FP_EXTEND!");
7217     Lo = ExpandLibCall(LC, Node, true, Hi);
7218     break;
7219   }
7220   case ISD::FP_ROUND: {
7221     RTLIB::Libcall LC = RTLIB::getFPROUND(Node->getOperand(0).getValueType(),
7222                                           VT);
7223     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported FP_ROUND!");
7224     Lo = ExpandLibCall(LC, Node, true, Hi);
7225     break;
7226   }
7227   case ISD::FSQRT:
7228   case ISD::FSIN:
7229   case ISD::FCOS: 
7230   case ISD::FLOG:
7231   case ISD::FLOG2:
7232   case ISD::FLOG10:
7233   case ISD::FEXP:
7234   case ISD::FEXP2:
7235   case ISD::FTRUNC:
7236   case ISD::FFLOOR:
7237   case ISD::FCEIL:
7238   case ISD::FRINT:
7239   case ISD::FNEARBYINT:
7240   case ISD::FPOW:
7241   case ISD::FPOWI: {
7242     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
7243     switch(Node->getOpcode()) {
7244     case ISD::FSQRT:
7245       LC = GetFPLibCall(VT, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
7246                         RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128);
7247       break;
7248     case ISD::FSIN:
7249       LC = GetFPLibCall(VT, RTLIB::SIN_F32, RTLIB::SIN_F64,
7250                         RTLIB::SIN_F80, RTLIB::SIN_PPCF128);
7251       break;
7252     case ISD::FCOS:
7253       LC = GetFPLibCall(VT, RTLIB::COS_F32, RTLIB::COS_F64,
7254                         RTLIB::COS_F80, RTLIB::COS_PPCF128);
7255       break;
7256     case ISD::FLOG:
7257       LC = GetFPLibCall(VT, RTLIB::LOG_F32, RTLIB::LOG_F64,
7258                         RTLIB::LOG_F80, RTLIB::LOG_PPCF128);
7259       break;
7260     case ISD::FLOG2:
7261       LC = GetFPLibCall(VT, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
7262                         RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128);
7263       break;
7264     case ISD::FLOG10:
7265       LC = GetFPLibCall(VT, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
7266                         RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128);
7267       break;
7268     case ISD::FEXP:
7269       LC = GetFPLibCall(VT, RTLIB::EXP_F32, RTLIB::EXP_F64,
7270                         RTLIB::EXP_F80, RTLIB::EXP_PPCF128);
7271       break;
7272     case ISD::FEXP2:
7273       LC = GetFPLibCall(VT, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
7274                         RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128);
7275       break;
7276     case ISD::FTRUNC:
7277       LC = GetFPLibCall(VT, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
7278                         RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128);
7279       break;
7280     case ISD::FFLOOR:
7281       LC = GetFPLibCall(VT, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
7282                         RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128);
7283       break;
7284     case ISD::FCEIL:
7285       LC = GetFPLibCall(VT, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
7286                         RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128);
7287       break;
7288     case ISD::FRINT:
7289       LC = GetFPLibCall(VT, RTLIB::RINT_F32, RTLIB::RINT_F64,
7290                         RTLIB::RINT_F80, RTLIB::RINT_PPCF128);
7291       break;
7292     case ISD::FNEARBYINT:
7293       LC = GetFPLibCall(VT, RTLIB::NEARBYINT_F32, RTLIB::NEARBYINT_F64,
7294                         RTLIB::NEARBYINT_F80, RTLIB::NEARBYINT_PPCF128);
7295       break;
7296     case ISD::FPOW:
7297       LC = GetFPLibCall(VT, RTLIB::POW_F32, RTLIB::POW_F64, RTLIB::POW_F80,
7298                         RTLIB::POW_PPCF128);
7299       break;
7300     case ISD::FPOWI:
7301       LC = GetFPLibCall(VT, RTLIB::POWI_F32, RTLIB::POWI_F64, RTLIB::POWI_F80,
7302                         RTLIB::POWI_PPCF128);
7303       break;
7304     default: assert(0 && "Unreachable!");
7305     }
7306     Lo = ExpandLibCall(LC, Node, false, Hi);
7307     break;
7308   }
7309   case ISD::FABS: {
7310     if (VT == MVT::ppcf128) {
7311       SDValue Tmp;
7312       ExpandOp(Node->getOperand(0), Lo, Tmp);
7313       Hi = DAG.getNode(ISD::FABS, NVT, Tmp);
7314       // lo = hi==fabs(hi) ? lo : -lo;
7315       Lo = DAG.getNode(ISD::SELECT_CC, NVT, Hi, Tmp,
7316                     Lo, DAG.getNode(ISD::FNEG, NVT, Lo),
7317                     DAG.getCondCode(ISD::SETEQ));
7318       break;
7319     }
7320     SDValue Mask = (VT == MVT::f64)
7321       ? DAG.getConstantFP(BitsToDouble(~(1ULL << 63)), VT)
7322       : DAG.getConstantFP(BitsToFloat(~(1U << 31)), VT);
7323     Mask = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask);
7324     Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
7325     Lo = DAG.getNode(ISD::AND, NVT, Lo, Mask);
7326     if (getTypeAction(NVT) == Expand)
7327       ExpandOp(Lo, Lo, Hi);
7328     break;
7329   }
7330   case ISD::FNEG: {
7331     if (VT == MVT::ppcf128) {
7332       ExpandOp(Node->getOperand(0), Lo, Hi);
7333       Lo = DAG.getNode(ISD::FNEG, MVT::f64, Lo);
7334       Hi = DAG.getNode(ISD::FNEG, MVT::f64, Hi);
7335       break;
7336     }
7337     SDValue Mask = (VT == MVT::f64)
7338       ? DAG.getConstantFP(BitsToDouble(1ULL << 63), VT)
7339       : DAG.getConstantFP(BitsToFloat(1U << 31), VT);
7340     Mask = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask);
7341     Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
7342     Lo = DAG.getNode(ISD::XOR, NVT, Lo, Mask);
7343     if (getTypeAction(NVT) == Expand)
7344       ExpandOp(Lo, Lo, Hi);
7345     break;
7346   }
7347   case ISD::FCOPYSIGN: {
7348     Lo = ExpandFCOPYSIGNToBitwiseOps(Node, NVT, DAG, TLI);
7349     if (getTypeAction(NVT) == Expand)
7350       ExpandOp(Lo, Lo, Hi);
7351     break;
7352   }
7353   case ISD::SINT_TO_FP:
7354   case ISD::UINT_TO_FP: {
7355     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
7356     MVT SrcVT = Node->getOperand(0).getValueType();
7357
7358     // Promote the operand if needed.  Do this before checking for
7359     // ppcf128 so conversions of i16 and i8 work.
7360     if (getTypeAction(SrcVT) == Promote) {
7361       SDValue Tmp = PromoteOp(Node->getOperand(0));
7362       Tmp = isSigned
7363         ? DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp.getValueType(), Tmp,
7364                       DAG.getValueType(SrcVT))
7365         : DAG.getZeroExtendInReg(Tmp, SrcVT);
7366       Node = DAG.UpdateNodeOperands(Op, Tmp).getNode();
7367       SrcVT = Node->getOperand(0).getValueType();
7368     }
7369
7370     if (VT == MVT::ppcf128 && SrcVT == MVT::i32) {
7371       static const uint64_t zero = 0;
7372       if (isSigned) {
7373         Hi = LegalizeOp(DAG.getNode(ISD::SINT_TO_FP, MVT::f64, 
7374                                     Node->getOperand(0)));
7375         Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
7376       } else {
7377         static const uint64_t TwoE32[] = { 0x41f0000000000000LL, 0 };
7378         Hi = LegalizeOp(DAG.getNode(ISD::SINT_TO_FP, MVT::f64, 
7379                                     Node->getOperand(0)));
7380         Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
7381         Hi = DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
7382         // X>=0 ? {(f64)x, 0} : {(f64)x, 0} + 2^32
7383         ExpandOp(DAG.getNode(ISD::SELECT_CC, MVT::ppcf128, Node->getOperand(0),
7384                              DAG.getConstant(0, MVT::i32), 
7385                              DAG.getNode(ISD::FADD, MVT::ppcf128, Hi,
7386                                          DAG.getConstantFP(
7387                                             APFloat(APInt(128, 2, TwoE32)),
7388                                             MVT::ppcf128)),
7389                              Hi,
7390                              DAG.getCondCode(ISD::SETLT)),
7391                  Lo, Hi);
7392       }
7393       break;
7394     }
7395     if (VT == MVT::ppcf128 && SrcVT == MVT::i64 && !isSigned) {
7396       // si64->ppcf128 done by libcall, below
7397       static const uint64_t TwoE64[] = { 0x43f0000000000000LL, 0 };
7398       ExpandOp(DAG.getNode(ISD::SINT_TO_FP, MVT::ppcf128, Node->getOperand(0)),
7399                Lo, Hi);
7400       Hi = DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
7401       // x>=0 ? (ppcf128)(i64)x : (ppcf128)(i64)x + 2^64
7402       ExpandOp(DAG.getNode(ISD::SELECT_CC, MVT::ppcf128, Node->getOperand(0),
7403                            DAG.getConstant(0, MVT::i64), 
7404                            DAG.getNode(ISD::FADD, MVT::ppcf128, Hi,
7405                                        DAG.getConstantFP(
7406                                           APFloat(APInt(128, 2, TwoE64)),
7407                                           MVT::ppcf128)),
7408                            Hi,
7409                            DAG.getCondCode(ISD::SETLT)),
7410                Lo, Hi);
7411       break;
7412     }
7413
7414     Lo = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, VT,
7415                        Node->getOperand(0));
7416     if (getTypeAction(Lo.getValueType()) == Expand)
7417       // float to i32 etc. can be 'expanded' to a single node.
7418       ExpandOp(Lo, Lo, Hi);
7419     break;
7420   }
7421   }
7422
7423   // Make sure the resultant values have been legalized themselves, unless this
7424   // is a type that requires multi-step expansion.
7425   if (getTypeAction(NVT) != Expand && NVT != MVT::isVoid) {
7426     Lo = LegalizeOp(Lo);
7427     if (Hi.getNode())
7428       // Don't legalize the high part if it is expanded to a single node.
7429       Hi = LegalizeOp(Hi);
7430   }
7431
7432   // Remember in a map if the values will be reused later.
7433   bool isNew =
7434     ExpandedNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
7435   assert(isNew && "Value already expanded?!?");
7436   isNew = isNew;
7437 }
7438
7439 /// SplitVectorOp - Given an operand of vector type, break it down into
7440 /// two smaller values, still of vector type.
7441 void SelectionDAGLegalize::SplitVectorOp(SDValue Op, SDValue &Lo,
7442                                          SDValue &Hi) {
7443   assert(Op.getValueType().isVector() && "Cannot split non-vector type!");
7444   SDNode *Node = Op.getNode();
7445   unsigned NumElements = Op.getValueType().getVectorNumElements();
7446   assert(NumElements > 1 && "Cannot split a single element vector!");
7447
7448   MVT NewEltVT = Op.getValueType().getVectorElementType();
7449
7450   unsigned NewNumElts_Lo = 1 << Log2_32(NumElements-1);
7451   unsigned NewNumElts_Hi = NumElements - NewNumElts_Lo;
7452
7453   MVT NewVT_Lo = MVT::getVectorVT(NewEltVT, NewNumElts_Lo);
7454   MVT NewVT_Hi = MVT::getVectorVT(NewEltVT, NewNumElts_Hi);
7455
7456   // See if we already split it.
7457   std::map<SDValue, std::pair<SDValue, SDValue> >::iterator I
7458     = SplitNodes.find(Op);
7459   if (I != SplitNodes.end()) {
7460     Lo = I->second.first;
7461     Hi = I->second.second;
7462     return;
7463   }
7464   
7465   switch (Node->getOpcode()) {
7466   default: 
7467 #ifndef NDEBUG
7468     Node->dump(&DAG);
7469 #endif
7470     assert(0 && "Unhandled operation in SplitVectorOp!");
7471   case ISD::UNDEF:
7472     Lo = DAG.getNode(ISD::UNDEF, NewVT_Lo);
7473     Hi = DAG.getNode(ISD::UNDEF, NewVT_Hi);
7474     break;
7475   case ISD::BUILD_PAIR:
7476     Lo = Node->getOperand(0);
7477     Hi = Node->getOperand(1);
7478     break;
7479   case ISD::INSERT_VECTOR_ELT: {
7480     if (ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Node->getOperand(2))) {
7481       SplitVectorOp(Node->getOperand(0), Lo, Hi);
7482       unsigned Index = Idx->getZExtValue();
7483       SDValue ScalarOp = Node->getOperand(1);
7484       if (Index < NewNumElts_Lo)
7485         Lo = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT_Lo, Lo, ScalarOp,
7486                          DAG.getIntPtrConstant(Index));
7487       else
7488         Hi = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT_Hi, Hi, ScalarOp,
7489                          DAG.getIntPtrConstant(Index - NewNumElts_Lo));
7490       break;
7491     }
7492     SDValue Tmp = PerformInsertVectorEltInMemory(Node->getOperand(0),
7493                                                    Node->getOperand(1),
7494                                                    Node->getOperand(2));
7495     SplitVectorOp(Tmp, Lo, Hi);
7496     break;
7497   }
7498   case ISD::VECTOR_SHUFFLE: {
7499     // Build the low part.
7500     SDValue Mask = Node->getOperand(2);
7501     SmallVector<SDValue, 8> Ops;
7502     MVT PtrVT = TLI.getPointerTy();
7503     
7504     // Insert all of the elements from the input that are needed.  We use 
7505     // buildvector of extractelement here because the input vectors will have
7506     // to be legalized, so this makes the code simpler.
7507     for (unsigned i = 0; i != NewNumElts_Lo; ++i) {
7508       SDValue IdxNode = Mask.getOperand(i);
7509       if (IdxNode.getOpcode() == ISD::UNDEF) {
7510         Ops.push_back(DAG.getNode(ISD::UNDEF, NewEltVT));
7511         continue;
7512       }
7513       unsigned Idx = cast<ConstantSDNode>(IdxNode)->getZExtValue();
7514       SDValue InVec = Node->getOperand(0);
7515       if (Idx >= NumElements) {
7516         InVec = Node->getOperand(1);
7517         Idx -= NumElements;
7518       }
7519       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, NewEltVT, InVec,
7520                                 DAG.getConstant(Idx, PtrVT)));
7521     }
7522     Lo = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Lo, &Ops[0], Ops.size());
7523     Ops.clear();
7524     
7525     for (unsigned i = NewNumElts_Lo; i != NumElements; ++i) {
7526       SDValue IdxNode = Mask.getOperand(i);
7527       if (IdxNode.getOpcode() == ISD::UNDEF) {
7528         Ops.push_back(DAG.getNode(ISD::UNDEF, NewEltVT));
7529         continue;
7530       }
7531       unsigned Idx = cast<ConstantSDNode>(IdxNode)->getZExtValue();
7532       SDValue InVec = Node->getOperand(0);
7533       if (Idx >= NumElements) {
7534         InVec = Node->getOperand(1);
7535         Idx -= NumElements;
7536       }
7537       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, NewEltVT, InVec,
7538                                 DAG.getConstant(Idx, PtrVT)));
7539     }
7540     Hi = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Hi, &Ops[0], Ops.size());
7541     break;
7542   }
7543   case ISD::BUILD_VECTOR: {
7544     SmallVector<SDValue, 8> LoOps(Node->op_begin(), 
7545                                     Node->op_begin()+NewNumElts_Lo);
7546     Lo = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Lo, &LoOps[0], LoOps.size());
7547
7548     SmallVector<SDValue, 8> HiOps(Node->op_begin()+NewNumElts_Lo, 
7549                                     Node->op_end());
7550     Hi = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Hi, &HiOps[0], HiOps.size());
7551     break;
7552   }
7553   case ISD::CONCAT_VECTORS: {
7554     // FIXME: Handle non-power-of-two vectors?
7555     unsigned NewNumSubvectors = Node->getNumOperands() / 2;
7556     if (NewNumSubvectors == 1) {
7557       Lo = Node->getOperand(0);
7558       Hi = Node->getOperand(1);
7559     } else {
7560       SmallVector<SDValue, 8> LoOps(Node->op_begin(),
7561                                     Node->op_begin()+NewNumSubvectors);
7562       Lo = DAG.getNode(ISD::CONCAT_VECTORS, NewVT_Lo, &LoOps[0], LoOps.size());
7563
7564       SmallVector<SDValue, 8> HiOps(Node->op_begin()+NewNumSubvectors,
7565                                       Node->op_end());
7566       Hi = DAG.getNode(ISD::CONCAT_VECTORS, NewVT_Hi, &HiOps[0], HiOps.size());
7567     }
7568     break;
7569   }
7570   case ISD::EXTRACT_SUBVECTOR: {
7571     SDValue Vec = Op.getOperand(0);
7572     SDValue Idx = Op.getOperand(1);
7573     MVT     IdxVT = Idx.getValueType();
7574
7575     Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, NewVT_Lo, Vec, Idx);
7576     ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx);
7577     if (CIdx) {
7578       Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, NewVT_Hi, Vec, 
7579                        DAG.getConstant(CIdx->getZExtValue() + NewNumElts_Lo,
7580                                        IdxVT));
7581     } else {
7582       Idx = DAG.getNode(ISD::ADD, IdxVT, Idx,
7583                         DAG.getConstant(NewNumElts_Lo, IdxVT));
7584       Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, NewVT_Hi, Vec, Idx);
7585     }
7586     break;
7587   }
7588   case ISD::SELECT: {
7589     SDValue Cond = Node->getOperand(0);
7590
7591     SDValue LL, LH, RL, RH;
7592     SplitVectorOp(Node->getOperand(1), LL, LH);
7593     SplitVectorOp(Node->getOperand(2), RL, RH);
7594
7595     if (Cond.getValueType().isVector()) {
7596       // Handle a vector merge.
7597       SDValue CL, CH;
7598       SplitVectorOp(Cond, CL, CH);
7599       Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, CL, LL, RL);
7600       Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, CH, LH, RH);
7601     } else {
7602       // Handle a simple select with vector operands.
7603       Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, Cond, LL, RL);
7604       Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, Cond, LH, RH);
7605     }
7606     break;
7607   }
7608   case ISD::SELECT_CC: {
7609     SDValue CondLHS = Node->getOperand(0);
7610     SDValue CondRHS = Node->getOperand(1);
7611     SDValue CondCode = Node->getOperand(4);
7612     
7613     SDValue LL, LH, RL, RH;
7614     SplitVectorOp(Node->getOperand(2), LL, LH);
7615     SplitVectorOp(Node->getOperand(3), RL, RH);
7616     
7617     // Handle a simple select with vector operands.
7618     Lo = DAG.getNode(ISD::SELECT_CC, NewVT_Lo, CondLHS, CondRHS,
7619                      LL, RL, CondCode);
7620     Hi = DAG.getNode(ISD::SELECT_CC, NewVT_Hi, CondLHS, CondRHS, 
7621                      LH, RH, CondCode);
7622     break;
7623   }
7624   case ISD::VSETCC: {
7625     SDValue LL, LH, RL, RH;
7626     SplitVectorOp(Node->getOperand(0), LL, LH);
7627     SplitVectorOp(Node->getOperand(1), RL, RH);
7628     Lo = DAG.getNode(ISD::VSETCC, NewVT_Lo, LL, RL, Node->getOperand(2));
7629     Hi = DAG.getNode(ISD::VSETCC, NewVT_Hi, LH, RH, Node->getOperand(2));
7630     break;
7631   }
7632   case ISD::ADD:
7633   case ISD::SUB:
7634   case ISD::MUL:
7635   case ISD::FADD:
7636   case ISD::FSUB:
7637   case ISD::FMUL:
7638   case ISD::SDIV:
7639   case ISD::UDIV:
7640   case ISD::FDIV:
7641   case ISD::FPOW:
7642   case ISD::AND:
7643   case ISD::OR:
7644   case ISD::XOR:
7645   case ISD::UREM:
7646   case ISD::SREM:
7647   case ISD::FREM: {
7648     SDValue LL, LH, RL, RH;
7649     SplitVectorOp(Node->getOperand(0), LL, LH);
7650     SplitVectorOp(Node->getOperand(1), RL, RH);
7651     
7652     Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, LL, RL);
7653     Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, LH, RH);
7654     break;
7655   }
7656   case ISD::FP_ROUND:
7657   case ISD::FPOWI: {
7658     SDValue L, H;
7659     SplitVectorOp(Node->getOperand(0), L, H);
7660
7661     Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, L, Node->getOperand(1));
7662     Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, H, Node->getOperand(1));
7663     break;
7664   }
7665   case ISD::CTTZ:
7666   case ISD::CTLZ:
7667   case ISD::CTPOP:
7668   case ISD::FNEG:
7669   case ISD::FABS:
7670   case ISD::FSQRT:
7671   case ISD::FSIN:
7672   case ISD::FCOS:
7673   case ISD::FLOG:
7674   case ISD::FLOG2:
7675   case ISD::FLOG10:
7676   case ISD::FEXP:
7677   case ISD::FEXP2:
7678   case ISD::FP_TO_SINT:
7679   case ISD::FP_TO_UINT:
7680   case ISD::SINT_TO_FP:
7681   case ISD::UINT_TO_FP:
7682   case ISD::TRUNCATE:
7683   case ISD::ANY_EXTEND:
7684   case ISD::SIGN_EXTEND:
7685   case ISD::ZERO_EXTEND:
7686   case ISD::FP_EXTEND: {
7687     SDValue L, H;
7688     SplitVectorOp(Node->getOperand(0), L, H);
7689
7690     Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, L);
7691     Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, H);
7692     break;
7693   }
7694   case ISD::CONVERT_RNDSAT: {
7695     ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(Node)->getCvtCode();
7696     SDValue L, H;
7697     SplitVectorOp(Node->getOperand(0), L, H);
7698     SDValue DTyOpL =  DAG.getValueType(NewVT_Lo);
7699     SDValue DTyOpH =  DAG.getValueType(NewVT_Hi);
7700     SDValue STyOpL =  DAG.getValueType(L.getValueType());
7701     SDValue STyOpH =  DAG.getValueType(H.getValueType());
7702
7703     SDValue RndOp = Node->getOperand(3);
7704     SDValue SatOp = Node->getOperand(4);
7705
7706     Lo = DAG.getConvertRndSat(NewVT_Lo, L, DTyOpL, STyOpL,
7707                               RndOp, SatOp, CvtCode);
7708     Hi = DAG.getConvertRndSat(NewVT_Hi, H, DTyOpH, STyOpH,
7709                               RndOp, SatOp, CvtCode);
7710     break;
7711   }
7712   case ISD::LOAD: {
7713     LoadSDNode *LD = cast<LoadSDNode>(Node);
7714     SDValue Ch = LD->getChain();
7715     SDValue Ptr = LD->getBasePtr();
7716     ISD::LoadExtType ExtType = LD->getExtensionType();
7717     const Value *SV = LD->getSrcValue();
7718     int SVOffset = LD->getSrcValueOffset();
7719     MVT MemoryVT = LD->getMemoryVT();
7720     unsigned Alignment = LD->getAlignment();
7721     bool isVolatile = LD->isVolatile();
7722
7723     assert(LD->isUnindexed() && "Indexed vector loads are not supported yet!");
7724     SDValue Offset = DAG.getNode(ISD::UNDEF, Ptr.getValueType());
7725
7726     MVT MemNewEltVT = MemoryVT.getVectorElementType();
7727     MVT MemNewVT_Lo = MVT::getVectorVT(MemNewEltVT, NewNumElts_Lo);
7728     MVT MemNewVT_Hi = MVT::getVectorVT(MemNewEltVT, NewNumElts_Hi);
7729
7730     Lo = DAG.getLoad(ISD::UNINDEXED, ExtType,
7731                      NewVT_Lo, Ch, Ptr, Offset,
7732                      SV, SVOffset, MemNewVT_Lo, isVolatile, Alignment);
7733     unsigned IncrementSize = NewNumElts_Lo * MemNewEltVT.getSizeInBits()/8;
7734     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
7735                       DAG.getIntPtrConstant(IncrementSize));
7736     SVOffset += IncrementSize;
7737     Alignment = MinAlign(Alignment, IncrementSize);
7738     Hi = DAG.getLoad(ISD::UNINDEXED, ExtType,
7739                      NewVT_Hi, Ch, Ptr, Offset,
7740                      SV, SVOffset, MemNewVT_Hi, isVolatile, Alignment);
7741     
7742     // Build a factor node to remember that this load is independent of the
7743     // other one.
7744     SDValue TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
7745                                Hi.getValue(1));
7746     
7747     // Remember that we legalized the chain.
7748     AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
7749     break;
7750   }
7751   case ISD::BIT_CONVERT: {
7752     // We know the result is a vector.  The input may be either a vector or a
7753     // scalar value.
7754     SDValue InOp = Node->getOperand(0);
7755     if (!InOp.getValueType().isVector() ||
7756         InOp.getValueType().getVectorNumElements() == 1) {
7757       // The input is a scalar or single-element vector.
7758       // Lower to a store/load so that it can be split.
7759       // FIXME: this could be improved probably.
7760       unsigned LdAlign = TLI.getTargetData()->getPrefTypeAlignment(
7761                                             Op.getValueType().getTypeForMVT());
7762       SDValue Ptr = DAG.CreateStackTemporary(InOp.getValueType(), LdAlign);
7763       int FI = cast<FrameIndexSDNode>(Ptr.getNode())->getIndex();
7764
7765       SDValue St = DAG.getStore(DAG.getEntryNode(),
7766                                   InOp, Ptr,
7767                                   PseudoSourceValue::getFixedStack(FI), 0);
7768       InOp = DAG.getLoad(Op.getValueType(), St, Ptr,
7769                          PseudoSourceValue::getFixedStack(FI), 0);
7770     }
7771     // Split the vector and convert each of the pieces now.
7772     SplitVectorOp(InOp, Lo, Hi);
7773     Lo = DAG.getNode(ISD::BIT_CONVERT, NewVT_Lo, Lo);
7774     Hi = DAG.getNode(ISD::BIT_CONVERT, NewVT_Hi, Hi);
7775     break;
7776   }
7777   }
7778       
7779   // Remember in a map if the values will be reused later.
7780   bool isNew = 
7781     SplitNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
7782   assert(isNew && "Value already split?!?");
7783   isNew = isNew;
7784 }
7785
7786
7787 /// ScalarizeVectorOp - Given an operand of single-element vector type
7788 /// (e.g. v1f32), convert it into the equivalent operation that returns a
7789 /// scalar (e.g. f32) value.
7790 SDValue SelectionDAGLegalize::ScalarizeVectorOp(SDValue Op) {
7791   assert(Op.getValueType().isVector() && "Bad ScalarizeVectorOp invocation!");
7792   SDNode *Node = Op.getNode();
7793   MVT NewVT = Op.getValueType().getVectorElementType();
7794   assert(Op.getValueType().getVectorNumElements() == 1);
7795   
7796   // See if we already scalarized it.
7797   std::map<SDValue, SDValue>::iterator I = ScalarizedNodes.find(Op);
7798   if (I != ScalarizedNodes.end()) return I->second;
7799   
7800   SDValue Result;
7801   switch (Node->getOpcode()) {
7802   default: 
7803 #ifndef NDEBUG
7804     Node->dump(&DAG); cerr << "\n";
7805 #endif
7806     assert(0 && "Unknown vector operation in ScalarizeVectorOp!");
7807   case ISD::ADD:
7808   case ISD::FADD:
7809   case ISD::SUB:
7810   case ISD::FSUB:
7811   case ISD::MUL:
7812   case ISD::FMUL:
7813   case ISD::SDIV:
7814   case ISD::UDIV:
7815   case ISD::FDIV:
7816   case ISD::SREM:
7817   case ISD::UREM:
7818   case ISD::FREM:
7819   case ISD::FPOW:
7820   case ISD::AND:
7821   case ISD::OR:
7822   case ISD::XOR:
7823     Result = DAG.getNode(Node->getOpcode(),
7824                          NewVT, 
7825                          ScalarizeVectorOp(Node->getOperand(0)),
7826                          ScalarizeVectorOp(Node->getOperand(1)));
7827     break;
7828   case ISD::FNEG:
7829   case ISD::FABS:
7830   case ISD::FSQRT:
7831   case ISD::FSIN:
7832   case ISD::FCOS:
7833   case ISD::FLOG:
7834   case ISD::FLOG2:
7835   case ISD::FLOG10:
7836   case ISD::FEXP:
7837   case ISD::FEXP2:
7838   case ISD::FP_TO_SINT:
7839   case ISD::FP_TO_UINT:
7840   case ISD::SINT_TO_FP:
7841   case ISD::UINT_TO_FP:
7842   case ISD::SIGN_EXTEND:
7843   case ISD::ZERO_EXTEND:
7844   case ISD::ANY_EXTEND:
7845   case ISD::TRUNCATE:
7846   case ISD::FP_EXTEND:
7847     Result = DAG.getNode(Node->getOpcode(),
7848                          NewVT, 
7849                          ScalarizeVectorOp(Node->getOperand(0)));
7850     break;
7851   case ISD::CONVERT_RNDSAT: {
7852     SDValue Op0 = ScalarizeVectorOp(Node->getOperand(0));
7853     Result = DAG.getConvertRndSat(NewVT, Op0,
7854                                   DAG.getValueType(NewVT),
7855                                   DAG.getValueType(Op0.getValueType()),
7856                                   Node->getOperand(3),
7857                                   Node->getOperand(4),
7858                                   cast<CvtRndSatSDNode>(Node)->getCvtCode());
7859     break;
7860   }
7861   case ISD::FPOWI:
7862   case ISD::FP_ROUND:
7863     Result = DAG.getNode(Node->getOpcode(),
7864                          NewVT, 
7865                          ScalarizeVectorOp(Node->getOperand(0)),
7866                          Node->getOperand(1));
7867     break;
7868   case ISD::LOAD: {
7869     LoadSDNode *LD = cast<LoadSDNode>(Node);
7870     SDValue Ch = LegalizeOp(LD->getChain());     // Legalize the chain.
7871     SDValue Ptr = LegalizeOp(LD->getBasePtr());  // Legalize the pointer.
7872     ISD::LoadExtType ExtType = LD->getExtensionType();
7873     const Value *SV = LD->getSrcValue();
7874     int SVOffset = LD->getSrcValueOffset();
7875     MVT MemoryVT = LD->getMemoryVT();
7876     unsigned Alignment = LD->getAlignment();
7877     bool isVolatile = LD->isVolatile();
7878
7879     assert(LD->isUnindexed() && "Indexed vector loads are not supported yet!");
7880     SDValue Offset = DAG.getNode(ISD::UNDEF, Ptr.getValueType());
7881     
7882     Result = DAG.getLoad(ISD::UNINDEXED, ExtType,
7883                          NewVT, Ch, Ptr, Offset, SV, SVOffset,
7884                          MemoryVT.getVectorElementType(),
7885                          isVolatile, Alignment);
7886
7887     // Remember that we legalized the chain.
7888     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
7889     break;
7890   }
7891   case ISD::BUILD_VECTOR:
7892     Result = Node->getOperand(0);
7893     break;
7894   case ISD::INSERT_VECTOR_ELT:
7895     // Returning the inserted scalar element.
7896     Result = Node->getOperand(1);
7897     break;
7898   case ISD::CONCAT_VECTORS:
7899     assert(Node->getOperand(0).getValueType() == NewVT &&
7900            "Concat of non-legal vectors not yet supported!");
7901     Result = Node->getOperand(0);
7902     break;
7903   case ISD::VECTOR_SHUFFLE: {
7904     // Figure out if the scalar is the LHS or RHS and return it.
7905     SDValue EltNum = Node->getOperand(2).getOperand(0);
7906     if (cast<ConstantSDNode>(EltNum)->getZExtValue())
7907       Result = ScalarizeVectorOp(Node->getOperand(1));
7908     else
7909       Result = ScalarizeVectorOp(Node->getOperand(0));
7910     break;
7911   }
7912   case ISD::EXTRACT_SUBVECTOR:
7913     Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, NewVT, Node->getOperand(0),
7914                          Node->getOperand(1));
7915     break;
7916   case ISD::BIT_CONVERT: {
7917     SDValue Op0 = Op.getOperand(0);
7918     if (Op0.getValueType().getVectorNumElements() == 1)
7919       Op0 = ScalarizeVectorOp(Op0);
7920     Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, Op0);
7921     break;
7922   }
7923   case ISD::SELECT:
7924     Result = DAG.getNode(ISD::SELECT, NewVT, Op.getOperand(0),
7925                          ScalarizeVectorOp(Op.getOperand(1)),
7926                          ScalarizeVectorOp(Op.getOperand(2)));
7927     break;
7928   case ISD::SELECT_CC:
7929     Result = DAG.getNode(ISD::SELECT_CC, NewVT, Node->getOperand(0), 
7930                          Node->getOperand(1),
7931                          ScalarizeVectorOp(Op.getOperand(2)),
7932                          ScalarizeVectorOp(Op.getOperand(3)),
7933                          Node->getOperand(4));
7934     break;
7935   case ISD::VSETCC: {
7936     SDValue Op0 = ScalarizeVectorOp(Op.getOperand(0));
7937     SDValue Op1 = ScalarizeVectorOp(Op.getOperand(1));
7938     Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(Op0), Op0, Op1,
7939                          Op.getOperand(2));
7940     Result = DAG.getNode(ISD::SELECT, NewVT, Result,
7941                          DAG.getConstant(-1ULL, NewVT),
7942                          DAG.getConstant(0ULL, NewVT));
7943     break;
7944   }
7945   }
7946
7947   if (TLI.isTypeLegal(NewVT))
7948     Result = LegalizeOp(Result);
7949   bool isNew = ScalarizedNodes.insert(std::make_pair(Op, Result)).second;
7950   assert(isNew && "Value already scalarized?");
7951   isNew = isNew;
7952   return Result;
7953 }
7954
7955
7956 SDValue SelectionDAGLegalize::WidenVectorOp(SDValue Op, MVT WidenVT) {
7957   std::map<SDValue, SDValue>::iterator I = WidenNodes.find(Op);
7958   if (I != WidenNodes.end()) return I->second;
7959   
7960   MVT VT = Op.getValueType();
7961   assert(VT.isVector() && "Cannot widen non-vector type!");
7962
7963   SDValue Result;
7964   SDNode *Node = Op.getNode();
7965   MVT EVT = VT.getVectorElementType();
7966
7967   unsigned NumElts = VT.getVectorNumElements();
7968   unsigned NewNumElts = WidenVT.getVectorNumElements();
7969   assert(NewNumElts > NumElts  && "Cannot widen to smaller type!");
7970   assert(NewNumElts < 17);
7971
7972   // When widen is called, it is assumed that it is more efficient to use a
7973   // wide type.  The default action is to widen to operation to a wider legal
7974   // vector type and then do the operation if it is legal by calling LegalizeOp
7975   // again.  If there is no vector equivalent, we will unroll the operation, do
7976   // it, and rebuild the vector.  If most of the operations are vectorizible to
7977   // the legal type, the resulting code will be more efficient.  If this is not
7978   // the case, the resulting code will preform badly as we end up generating
7979   // code to pack/unpack the results. It is the function that calls widen
7980   // that is responsible for seeing this doesn't happen.
7981   switch (Node->getOpcode()) {
7982   default: 
7983 #ifndef NDEBUG
7984       Node->dump(&DAG);
7985 #endif
7986       assert(0 && "Unexpected operation in WidenVectorOp!");
7987       break;
7988   case ISD::CopyFromReg:
7989     assert(0 && "CopyFromReg doesn't need widening!");
7990   case ISD::Constant:
7991   case ISD::ConstantFP:
7992     // To build a vector of these elements, clients should call BuildVector
7993     // and with each element instead of creating a node with a vector type
7994     assert(0 && "Unexpected operation in WidenVectorOp!");
7995   case ISD::VAARG:
7996     // Variable Arguments with vector types doesn't make any sense to me
7997     assert(0 && "Unexpected operation in WidenVectorOp!");
7998     break;
7999   case ISD::UNDEF:
8000     Result = DAG.getNode(ISD::UNDEF, WidenVT);
8001     break;
8002   case ISD::BUILD_VECTOR: {
8003     // Build a vector with undefined for the new nodes
8004     SDValueVector NewOps(Node->op_begin(), Node->op_end());
8005     for (unsigned i = NumElts; i < NewNumElts; ++i) {
8006       NewOps.push_back(DAG.getNode(ISD::UNDEF,EVT));
8007     }
8008     Result = DAG.getNode(ISD::BUILD_VECTOR, WidenVT, &NewOps[0], NewOps.size());    
8009     break;
8010   }
8011   case ISD::INSERT_VECTOR_ELT: {
8012     SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8013     Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, WidenVT, Tmp1,
8014                          Node->getOperand(1), Node->getOperand(2));
8015     break;
8016   }
8017   case ISD::VECTOR_SHUFFLE: {
8018     SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8019     SDValue Tmp2 = WidenVectorOp(Node->getOperand(1), WidenVT);
8020     // VECTOR_SHUFFLE 3rd operand must be a constant build vector that is
8021     // used as permutation array. We build the vector here instead of widening
8022     // because we don't want to legalize and have it turned to something else.
8023     SDValue PermOp = Node->getOperand(2);
8024     SDValueVector NewOps;
8025     MVT PVT = PermOp.getValueType().getVectorElementType();
8026     for (unsigned i = 0; i < NumElts; ++i) {
8027       if (PermOp.getOperand(i).getOpcode() == ISD::UNDEF) {
8028         NewOps.push_back(PermOp.getOperand(i));
8029       } else {
8030         unsigned Idx =
8031           cast<ConstantSDNode>(PermOp.getOperand(i))->getZExtValue();
8032         if (Idx < NumElts) {
8033           NewOps.push_back(PermOp.getOperand(i));
8034         }
8035         else {
8036           NewOps.push_back(DAG.getConstant(Idx + NewNumElts - NumElts,
8037                                            PermOp.getOperand(i).getValueType()));
8038         } 
8039       }
8040     }
8041     for (unsigned i = NumElts; i < NewNumElts; ++i) {
8042       NewOps.push_back(DAG.getNode(ISD::UNDEF,PVT));
8043     }
8044     
8045     SDValue Tmp3 = DAG.getNode(ISD::BUILD_VECTOR, 
8046                                MVT::getVectorVT(PVT, NewOps.size()),
8047                                &NewOps[0], NewOps.size()); 
8048     
8049     Result = DAG.getNode(ISD::VECTOR_SHUFFLE, WidenVT, Tmp1, Tmp2, Tmp3);    
8050     break;
8051   }
8052   case ISD::LOAD: {
8053     // If the load widen returns true, we can use a single load for the
8054     // vector.  Otherwise, it is returning a token factor for multiple
8055     // loads.
8056     SDValue TFOp;
8057     if (LoadWidenVectorOp(Result, TFOp, Op, WidenVT))
8058       AddLegalizedOperand(Op.getValue(1), LegalizeOp(TFOp.getValue(1)));
8059     else
8060       AddLegalizedOperand(Op.getValue(1), LegalizeOp(TFOp.getValue(0)));
8061     break;
8062   }
8063
8064   case ISD::BIT_CONVERT: {
8065     SDValue Tmp1 = Node->getOperand(0);
8066     // Converts between two different types so we need to determine
8067     // the correct widen type for the input operand.
8068     MVT TVT = Tmp1.getValueType();
8069     assert(TVT.isVector() && "can not widen non vector type");
8070     MVT TEVT = TVT.getVectorElementType();
8071     assert(WidenVT.getSizeInBits() % EVT.getSizeInBits() == 0 &&
8072          "can not widen bit bit convert that are not multiple of element type");
8073     MVT TWidenVT =  MVT::getVectorVT(TEVT,
8074                                    WidenVT.getSizeInBits()/EVT.getSizeInBits());
8075     Tmp1 = WidenVectorOp(Tmp1, TWidenVT);
8076     assert(Tmp1.getValueType().getSizeInBits() == WidenVT.getSizeInBits());
8077     Result = DAG.getNode(Node->getOpcode(), WidenVT, Tmp1);
8078
8079     TargetLowering::LegalizeAction action =
8080       TLI.getOperationAction(Node->getOpcode(), WidenVT);
8081     switch (action)  {
8082     default: assert(0 && "action not supported");
8083     case TargetLowering::Legal:
8084         break;
8085     case TargetLowering::Promote:
8086         // We defer the promotion to when we legalize the op
8087       break;
8088     case TargetLowering::Expand:
8089       // Expand the operation into a bunch of nasty scalar code.
8090       Result = LegalizeOp(UnrollVectorOp(Result));
8091       break;
8092     }
8093     break;
8094   }
8095
8096   case ISD::SINT_TO_FP:
8097   case ISD::UINT_TO_FP:
8098   case ISD::FP_TO_SINT:
8099   case ISD::FP_TO_UINT: {
8100     SDValue Tmp1 = Node->getOperand(0);
8101     // Converts between two different types so we need to determine
8102     // the correct widen type for the input operand.
8103     MVT TVT = Tmp1.getValueType();
8104     assert(TVT.isVector() && "can not widen non vector type");
8105     MVT TEVT = TVT.getVectorElementType();
8106     MVT TWidenVT =  MVT::getVectorVT(TEVT, NewNumElts);
8107     Tmp1 = WidenVectorOp(Tmp1, TWidenVT);
8108     assert(Tmp1.getValueType().getVectorNumElements() == NewNumElts);
8109     Result = DAG.getNode(Node->getOpcode(), WidenVT, Tmp1);
8110     break;
8111   }
8112
8113   case ISD::FP_EXTEND:
8114     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
8115   case ISD::TRUNCATE:
8116   case ISD::SIGN_EXTEND:
8117   case ISD::ZERO_EXTEND:
8118   case ISD::ANY_EXTEND:
8119   case ISD::FP_ROUND:
8120   case ISD::SIGN_EXTEND_INREG:
8121   case ISD::FABS:
8122   case ISD::FNEG:
8123   case ISD::FSQRT:
8124   case ISD::FSIN:
8125   case ISD::FCOS:
8126   case ISD::CTPOP:
8127   case ISD::CTTZ:
8128   case ISD::CTLZ: {
8129     // Unary op widening
8130     SDValue Tmp1;    
8131     Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8132     assert(Tmp1.getValueType() == WidenVT);
8133     Result = DAG.getNode(Node->getOpcode(), WidenVT, Tmp1);
8134     break;
8135   }
8136   case ISD::CONVERT_RNDSAT: {
8137     SDValue RndOp = Node->getOperand(3);
8138     SDValue SatOp = Node->getOperand(4);
8139     SDValue SrcOp = Node->getOperand(0);
8140
8141     // Converts between two different types so we need to determine
8142     // the correct widen type for the input operand.
8143     MVT SVT = SrcOp.getValueType();
8144     assert(SVT.isVector() && "can not widen non vector type");
8145     MVT SEVT = SVT.getVectorElementType();
8146     MVT SWidenVT =  MVT::getVectorVT(SEVT, NewNumElts);
8147
8148     SrcOp = WidenVectorOp(SrcOp, SWidenVT);
8149     assert(SrcOp.getValueType() == WidenVT);
8150     SDValue DTyOp = DAG.getValueType(WidenVT);
8151     SDValue STyOp = DAG.getValueType(SrcOp.getValueType());
8152     ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(Node)->getCvtCode();
8153
8154     Result = DAG.getConvertRndSat(WidenVT, SrcOp, DTyOp, STyOp,
8155                                   RndOp, SatOp, CvtCode);
8156     break;
8157   }
8158   case ISD::FPOW:
8159   case ISD::FPOWI: 
8160   case ISD::ADD:
8161   case ISD::SUB:
8162   case ISD::MUL:
8163   case ISD::MULHS:
8164   case ISD::MULHU:
8165   case ISD::AND:
8166   case ISD::OR:
8167   case ISD::XOR:
8168   case ISD::FADD:
8169   case ISD::FSUB:
8170   case ISD::FMUL:
8171   case ISD::SDIV:
8172   case ISD::SREM:
8173   case ISD::FDIV:
8174   case ISD::FREM:
8175   case ISD::FCOPYSIGN:
8176   case ISD::UDIV:
8177   case ISD::UREM:
8178   case ISD::BSWAP: {
8179     // Binary op widening
8180     SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8181     SDValue Tmp2 = WidenVectorOp(Node->getOperand(1), WidenVT);
8182     assert(Tmp1.getValueType() == WidenVT && Tmp2.getValueType() == WidenVT);
8183     Result = DAG.getNode(Node->getOpcode(), WidenVT, Tmp1, Tmp2);
8184     break;
8185   }
8186
8187   case ISD::SHL:
8188   case ISD::SRA:
8189   case ISD::SRL: {
8190     SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8191     assert(Tmp1.getValueType() == WidenVT);
8192     SDValue ShOp = Node->getOperand(1);
8193     MVT ShVT = ShOp.getValueType();
8194     MVT NewShVT = MVT::getVectorVT(ShVT.getVectorElementType(),
8195                                    WidenVT.getVectorNumElements());
8196     ShOp = WidenVectorOp(ShOp, NewShVT);
8197     assert(ShOp.getValueType() == NewShVT);
8198     Result = DAG.getNode(Node->getOpcode(), WidenVT, Tmp1, ShOp);
8199     break;
8200   }
8201
8202   case ISD::EXTRACT_VECTOR_ELT: {
8203     SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8204     assert(Tmp1.getValueType() == WidenVT);
8205     Result = DAG.getNode(Node->getOpcode(), EVT, Tmp1, Node->getOperand(1));
8206     break;
8207   }
8208   case ISD::CONCAT_VECTORS: {
8209     // We concurrently support only widen on a multiple of the incoming vector.
8210     // We could widen on a multiple of the incoming operand if necessary.
8211     unsigned NumConcat = NewNumElts / NumElts;
8212     assert(NewNumElts % NumElts == 0 && "Can widen only a multiple of vector");
8213     SDValue UndefVal = DAG.getNode(ISD::UNDEF, VT);
8214     SmallVector<SDValue, 8> MOps;
8215     MOps.push_back(Op);
8216     for (unsigned i = 1; i != NumConcat; ++i) {
8217       MOps.push_back(UndefVal);
8218     }
8219     Result = LegalizeOp(DAG.getNode(ISD::CONCAT_VECTORS, WidenVT,
8220                                     &MOps[0], MOps.size()));
8221     break;
8222   }
8223   case ISD::EXTRACT_SUBVECTOR: {
8224     SDValue Tmp1 = Node->getOperand(0);
8225     SDValue Idx = Node->getOperand(1);
8226     ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx);
8227     if (CIdx && CIdx->getZExtValue() == 0) {
8228       // Since we are access the start of the vector, the incoming
8229       // vector type might be the proper.
8230       MVT Tmp1VT = Tmp1.getValueType();
8231       if (Tmp1VT == WidenVT)
8232         return Tmp1;
8233       else {
8234         unsigned Tmp1VTNumElts = Tmp1VT.getVectorNumElements();
8235         if (Tmp1VTNumElts < NewNumElts)
8236           Result = WidenVectorOp(Tmp1, WidenVT);
8237         else
8238           Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, WidenVT, Tmp1, Idx);
8239       }
8240     } else if (NewNumElts % NumElts == 0) {
8241       // Widen the extracted subvector.
8242       unsigned NumConcat = NewNumElts / NumElts;
8243       SDValue UndefVal = DAG.getNode(ISD::UNDEF, VT);
8244       SmallVector<SDValue, 8> MOps;
8245       MOps.push_back(Op);
8246       for (unsigned i = 1; i != NumConcat; ++i) {
8247         MOps.push_back(UndefVal);
8248       }
8249       Result = LegalizeOp(DAG.getNode(ISD::CONCAT_VECTORS, WidenVT,
8250                                       &MOps[0], MOps.size()));
8251     } else {
8252       assert(0 && "can not widen extract subvector");
8253      // This could be implemented using insert and build vector but I would
8254      // like to see when this happens.
8255     }
8256     break;
8257   }
8258
8259   case ISD::SELECT: {
8260     // Determine new condition widen type and widen
8261     SDValue Cond1 = Node->getOperand(0);
8262     MVT CondVT = Cond1.getValueType();
8263     assert(CondVT.isVector() && "can not widen non vector type");
8264     MVT CondEVT = CondVT.getVectorElementType();
8265     MVT CondWidenVT =  MVT::getVectorVT(CondEVT, NewNumElts);
8266     Cond1 = WidenVectorOp(Cond1, CondWidenVT);
8267     assert(Cond1.getValueType() == CondWidenVT && "Condition not widen");
8268
8269     SDValue Tmp1 = WidenVectorOp(Node->getOperand(1), WidenVT);
8270     SDValue Tmp2 = WidenVectorOp(Node->getOperand(2), WidenVT);
8271     assert(Tmp1.getValueType() == WidenVT && Tmp2.getValueType() == WidenVT);
8272     Result = DAG.getNode(Node->getOpcode(), WidenVT, Cond1, Tmp1, Tmp2);
8273     break;
8274   }
8275   
8276   case ISD::SELECT_CC: {
8277     // Determine new condition widen type and widen
8278     SDValue Cond1 = Node->getOperand(0);
8279     SDValue Cond2 = Node->getOperand(1);
8280     MVT CondVT = Cond1.getValueType();
8281     assert(CondVT.isVector() && "can not widen non vector type");
8282     assert(CondVT == Cond2.getValueType() && "mismatch lhs/rhs");
8283     MVT CondEVT = CondVT.getVectorElementType();
8284     MVT CondWidenVT =  MVT::getVectorVT(CondEVT, NewNumElts);
8285     Cond1 = WidenVectorOp(Cond1, CondWidenVT);
8286     Cond2 = WidenVectorOp(Cond2, CondWidenVT);
8287     assert(Cond1.getValueType() == CondWidenVT &&
8288            Cond2.getValueType() == CondWidenVT && "condition not widen");
8289
8290     SDValue Tmp1 = WidenVectorOp(Node->getOperand(2), WidenVT);
8291     SDValue Tmp2 = WidenVectorOp(Node->getOperand(3), WidenVT);
8292     assert(Tmp1.getValueType() == WidenVT && Tmp2.getValueType() == WidenVT &&
8293            "operands not widen");
8294     Result = DAG.getNode(Node->getOpcode(), WidenVT, Cond1, Cond2, Tmp1,
8295                          Tmp2, Node->getOperand(4));
8296     break;
8297   }
8298   case ISD::VSETCC: {
8299     // Determine widen for the operand
8300     SDValue Tmp1 = Node->getOperand(0);
8301     MVT TmpVT = Tmp1.getValueType();
8302     assert(TmpVT.isVector() && "can not widen non vector type");
8303     MVT TmpEVT = TmpVT.getVectorElementType();
8304     MVT TmpWidenVT =  MVT::getVectorVT(TmpEVT, NewNumElts);
8305     Tmp1 = WidenVectorOp(Tmp1, TmpWidenVT);
8306     SDValue Tmp2 = WidenVectorOp(Node->getOperand(1), TmpWidenVT);
8307     Result = DAG.getNode(Node->getOpcode(), WidenVT, Tmp1, Tmp2, 
8308                          Node->getOperand(2));
8309     break;
8310   }
8311   case ISD::ATOMIC_CMP_SWAP_8:
8312   case ISD::ATOMIC_CMP_SWAP_16:
8313   case ISD::ATOMIC_CMP_SWAP_32:
8314   case ISD::ATOMIC_CMP_SWAP_64:
8315   case ISD::ATOMIC_LOAD_ADD_8:
8316   case ISD::ATOMIC_LOAD_SUB_8:
8317   case ISD::ATOMIC_LOAD_AND_8:
8318   case ISD::ATOMIC_LOAD_OR_8:
8319   case ISD::ATOMIC_LOAD_XOR_8:
8320   case ISD::ATOMIC_LOAD_NAND_8:
8321   case ISD::ATOMIC_LOAD_MIN_8:
8322   case ISD::ATOMIC_LOAD_MAX_8:
8323   case ISD::ATOMIC_LOAD_UMIN_8:
8324   case ISD::ATOMIC_LOAD_UMAX_8:
8325   case ISD::ATOMIC_SWAP_8: 
8326   case ISD::ATOMIC_LOAD_ADD_16:
8327   case ISD::ATOMIC_LOAD_SUB_16:
8328   case ISD::ATOMIC_LOAD_AND_16:
8329   case ISD::ATOMIC_LOAD_OR_16:
8330   case ISD::ATOMIC_LOAD_XOR_16:
8331   case ISD::ATOMIC_LOAD_NAND_16:
8332   case ISD::ATOMIC_LOAD_MIN_16:
8333   case ISD::ATOMIC_LOAD_MAX_16:
8334   case ISD::ATOMIC_LOAD_UMIN_16:
8335   case ISD::ATOMIC_LOAD_UMAX_16:
8336   case ISD::ATOMIC_SWAP_16:
8337   case ISD::ATOMIC_LOAD_ADD_32:
8338   case ISD::ATOMIC_LOAD_SUB_32:
8339   case ISD::ATOMIC_LOAD_AND_32:
8340   case ISD::ATOMIC_LOAD_OR_32:
8341   case ISD::ATOMIC_LOAD_XOR_32:
8342   case ISD::ATOMIC_LOAD_NAND_32:
8343   case ISD::ATOMIC_LOAD_MIN_32:
8344   case ISD::ATOMIC_LOAD_MAX_32:
8345   case ISD::ATOMIC_LOAD_UMIN_32:
8346   case ISD::ATOMIC_LOAD_UMAX_32:
8347   case ISD::ATOMIC_SWAP_32:
8348   case ISD::ATOMIC_LOAD_ADD_64:
8349   case ISD::ATOMIC_LOAD_SUB_64:
8350   case ISD::ATOMIC_LOAD_AND_64:
8351   case ISD::ATOMIC_LOAD_OR_64:
8352   case ISD::ATOMIC_LOAD_XOR_64:
8353   case ISD::ATOMIC_LOAD_NAND_64:
8354   case ISD::ATOMIC_LOAD_MIN_64:
8355   case ISD::ATOMIC_LOAD_MAX_64:
8356   case ISD::ATOMIC_LOAD_UMIN_64:
8357   case ISD::ATOMIC_LOAD_UMAX_64:
8358   case ISD::ATOMIC_SWAP_64: {
8359     // For now, we assume that using vectors for these operations don't make
8360     // much sense so we just split it.  We return an empty result
8361     SDValue X, Y;
8362     SplitVectorOp(Op, X, Y);
8363     return Result;
8364     break;
8365   }
8366
8367   } // end switch (Node->getOpcode())
8368
8369   assert(Result.getNode() && "Didn't set a result!");  
8370   if (Result != Op)
8371     Result = LegalizeOp(Result);
8372
8373   AddWidenedOperand(Op, Result);
8374   return Result;
8375 }
8376
8377 // Utility function to find a legal vector type and its associated element
8378 // type from a preferred width and whose vector type must be the same size
8379 // as the VVT.
8380 //  TLI:   Target lowering used to determine legal types
8381 //  Width: Preferred width of element type
8382 //  VVT:   Vector value type whose size we must match.
8383 // Returns VecEVT and EVT - the vector type and its associated element type
8384 static void FindWidenVecType(TargetLowering &TLI, unsigned Width, MVT VVT,
8385                              MVT& EVT, MVT& VecEVT) {
8386   // We start with the preferred width, make it a power of 2 and see if
8387   // we can find a vector type of that width. If not, we reduce it by
8388   // another power of 2.  If we have widen the type, a vector of bytes should
8389   // always be legal.
8390   assert(TLI.isTypeLegal(VVT));
8391   unsigned EWidth = Width + 1;
8392   do {
8393     assert(EWidth > 0);
8394     EWidth =  (1 << Log2_32(EWidth-1));
8395     EVT = MVT::getIntegerVT(EWidth);
8396     unsigned NumEVT = VVT.getSizeInBits()/EWidth;
8397     VecEVT = MVT::getVectorVT(EVT, NumEVT);
8398   } while (!TLI.isTypeLegal(VecEVT) ||
8399            VVT.getSizeInBits() != VecEVT.getSizeInBits());
8400 }
8401
8402 SDValue SelectionDAGLegalize::genWidenVectorLoads(SDValueVector& LdChain,
8403                                                     SDValue   Chain,
8404                                                     SDValue   BasePtr,
8405                                                     const Value *SV,
8406                                                     int         SVOffset,
8407                                                     unsigned    Alignment,
8408                                                     bool        isVolatile,
8409                                                     unsigned    LdWidth,
8410                                                     MVT         ResType) {
8411   // We assume that we have good rules to handle loading power of two loads so
8412   // we break down the operations to power of 2 loads.  The strategy is to
8413   // load the largest power of 2 that we can easily transform to a legal vector
8414   // and then insert into that vector, and the cast the result into the legal
8415   // vector that we want.  This avoids unnecessary stack converts.
8416   // TODO: If the Ldwidth is legal, alignment is the same as the LdWidth, and
8417   //       the load is nonvolatile, we an use a wider load for the value.
8418   // Find a vector length we can load a large chunk
8419   MVT EVT, VecEVT;
8420   unsigned EVTWidth;
8421   FindWidenVecType(TLI, LdWidth, ResType, EVT, VecEVT);
8422   EVTWidth = EVT.getSizeInBits();
8423
8424   SDValue LdOp = DAG.getLoad(EVT, Chain, BasePtr, SV, SVOffset,
8425                                isVolatile, Alignment);
8426   SDValue VecOp = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecEVT, LdOp);
8427   LdChain.push_back(LdOp.getValue(1));
8428   
8429   // Check if we can load the element with one instruction
8430   if (LdWidth == EVTWidth) {
8431     return DAG.getNode(ISD::BIT_CONVERT, ResType, VecOp);
8432   }
8433
8434   // The vector element order is endianness dependent.
8435   unsigned Idx = 1;
8436   LdWidth -= EVTWidth;
8437   unsigned Offset = 0;
8438     
8439   while (LdWidth > 0) {
8440     unsigned Increment = EVTWidth / 8;
8441     Offset += Increment;
8442     BasePtr = DAG.getNode(ISD::ADD, BasePtr.getValueType(), BasePtr,
8443                           DAG.getIntPtrConstant(Increment));
8444
8445     if (LdWidth < EVTWidth) {
8446       // Our current type we are using is too large, use a smaller size by
8447       // using a smaller power of 2
8448       unsigned oEVTWidth = EVTWidth;
8449       FindWidenVecType(TLI, LdWidth, ResType, EVT, VecEVT);
8450       EVTWidth = EVT.getSizeInBits();
8451       // Readjust position and vector position based on new load type
8452       Idx = Idx * (oEVTWidth/EVTWidth);
8453       VecOp = DAG.getNode(ISD::BIT_CONVERT, VecEVT, VecOp);
8454     }
8455       
8456     SDValue LdOp = DAG.getLoad(EVT, Chain, BasePtr, SV,
8457                                  SVOffset+Offset, isVolatile,
8458                                  MinAlign(Alignment, Offset));
8459     LdChain.push_back(LdOp.getValue(1));
8460     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, VecEVT, VecOp, LdOp,
8461                         DAG.getIntPtrConstant(Idx++));
8462     
8463     LdWidth -= EVTWidth;
8464   }
8465
8466   return DAG.getNode(ISD::BIT_CONVERT, ResType, VecOp);
8467 }
8468
8469 bool SelectionDAGLegalize::LoadWidenVectorOp(SDValue& Result,
8470                                              SDValue& TFOp,
8471                                              SDValue Op,
8472                                              MVT NVT) {
8473   // TODO: Add support for ConcatVec and the ability to load many vector
8474   //       types (e.g., v4i8).  This will not work when a vector register
8475   //       to memory mapping is strange (e.g., vector elements are not
8476   //       stored in some sequential order).
8477
8478   // It must be true that the widen vector type is bigger than where 
8479   // we need to load from.
8480   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
8481   MVT LdVT = LD->getMemoryVT();
8482   assert(LdVT.isVector() && NVT.isVector());
8483   assert(LdVT.getVectorElementType() == NVT.getVectorElementType());
8484   
8485   // Load information
8486   SDValue Chain = LD->getChain();
8487   SDValue BasePtr = LD->getBasePtr();
8488   int       SVOffset = LD->getSrcValueOffset();
8489   unsigned  Alignment = LD->getAlignment();
8490   bool      isVolatile = LD->isVolatile();
8491   const Value *SV = LD->getSrcValue();
8492   unsigned int LdWidth = LdVT.getSizeInBits();
8493   
8494   // Load value as a large register
8495   SDValueVector LdChain;
8496   Result = genWidenVectorLoads(LdChain, Chain, BasePtr, SV, SVOffset,
8497                                Alignment, isVolatile, LdWidth, NVT);
8498
8499   if (LdChain.size() == 1) {
8500     TFOp = LdChain[0];
8501     return true;
8502   }
8503   else {
8504     TFOp=DAG.getNode(ISD::TokenFactor, MVT::Other, &LdChain[0], LdChain.size());
8505     return false;
8506   }
8507 }
8508
8509
8510 void SelectionDAGLegalize::genWidenVectorStores(SDValueVector& StChain,
8511                                                 SDValue   Chain,
8512                                                 SDValue   BasePtr,
8513                                                 const Value *SV,
8514                                                 int         SVOffset,
8515                                                 unsigned    Alignment,
8516                                                 bool        isVolatile,
8517                                                 SDValue     ValOp,
8518                                                 unsigned    StWidth) {
8519   // Breaks the stores into a series of power of 2 width stores.  For any
8520   // width, we convert the vector to the vector of element size that we
8521   // want to store.  This avoids requiring a stack convert.
8522   
8523   // Find a width of the element type we can store with
8524   MVT VVT = ValOp.getValueType();
8525   MVT EVT, VecEVT;
8526   unsigned EVTWidth;
8527   FindWidenVecType(TLI, StWidth, VVT, EVT, VecEVT);
8528   EVTWidth = EVT.getSizeInBits();
8529
8530   SDValue VecOp = DAG.getNode(ISD::BIT_CONVERT, VecEVT, ValOp);
8531   SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EVT, VecOp,
8532                             DAG.getIntPtrConstant(0));
8533   SDValue StOp = DAG.getStore(Chain, EOp, BasePtr, SV, SVOffset,
8534                                isVolatile, Alignment);
8535   StChain.push_back(StOp);
8536
8537   // Check if we are done
8538   if (StWidth == EVTWidth) {
8539     return;
8540   }
8541   
8542   unsigned Idx = 1;
8543   StWidth -= EVTWidth;
8544   unsigned Offset = 0;
8545     
8546   while (StWidth > 0) {
8547     unsigned Increment = EVTWidth / 8;
8548     Offset += Increment;
8549     BasePtr = DAG.getNode(ISD::ADD, BasePtr.getValueType(), BasePtr,
8550                           DAG.getIntPtrConstant(Increment));
8551                           
8552     if (StWidth < EVTWidth) {
8553       // Our current type we are using is too large, use a smaller size by
8554       // using a smaller power of 2
8555       unsigned oEVTWidth = EVTWidth;
8556       FindWidenVecType(TLI, StWidth, VVT, EVT, VecEVT);
8557       EVTWidth = EVT.getSizeInBits();
8558       // Readjust position and vector position based on new load type
8559       Idx = Idx * (oEVTWidth/EVTWidth);
8560       VecOp = DAG.getNode(ISD::BIT_CONVERT, VecEVT, VecOp);
8561     }
8562     
8563     EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EVT, VecOp,
8564                       DAG.getIntPtrConstant(Idx++));
8565     StChain.push_back(DAG.getStore(Chain, EOp, BasePtr, SV,
8566                                    SVOffset + Offset, isVolatile,
8567                                    MinAlign(Alignment, Offset)));
8568     StWidth -= EVTWidth;
8569   }
8570 }
8571
8572
8573 SDValue SelectionDAGLegalize::StoreWidenVectorOp(StoreSDNode *ST,
8574                                                    SDValue Chain,
8575                                                    SDValue BasePtr) {
8576   // TODO: It might be cleaner if we can use SplitVector and have more legal
8577   //        vector types that can be stored into memory (e.g., v4xi8 can
8578   //        be stored as a word). This will not work when a vector register
8579   //        to memory mapping is strange (e.g., vector elements are not
8580   //        stored in some sequential order).
8581   
8582   MVT StVT = ST->getMemoryVT();
8583   SDValue ValOp = ST->getValue();
8584
8585   // Check if we have widen this node with another value
8586   std::map<SDValue, SDValue>::iterator I = WidenNodes.find(ValOp);
8587   if (I != WidenNodes.end())
8588     ValOp = I->second;
8589     
8590   MVT VVT = ValOp.getValueType();
8591
8592   // It must be true that we the widen vector type is bigger than where
8593   // we need to store.
8594   assert(StVT.isVector() && VVT.isVector());
8595   assert(StVT.getSizeInBits() < VVT.getSizeInBits());
8596   assert(StVT.getVectorElementType() == VVT.getVectorElementType());
8597
8598   // Store value
8599   SDValueVector StChain;
8600   genWidenVectorStores(StChain, Chain, BasePtr, ST->getSrcValue(),
8601                        ST->getSrcValueOffset(), ST->getAlignment(),
8602                        ST->isVolatile(), ValOp, StVT.getSizeInBits());
8603   if (StChain.size() == 1)
8604     return StChain[0];
8605   else 
8606     return DAG.getNode(ISD::TokenFactor, MVT::Other,&StChain[0],StChain.size());
8607 }
8608
8609
8610 // SelectionDAG::Legalize - This is the entry point for the file.
8611 //
8612 void SelectionDAG::Legalize(bool TypesNeedLegalizing) {
8613   /// run - This is the main entry point to this class.
8614   ///
8615   SelectionDAGLegalize(*this, TypesNeedLegalizing).LegalizeDAG();
8616 }
8617