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