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