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