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