Make tblgen a little smarter about constants smaller than i32. Currently,
[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     switch (TLI.getOperationAction(ISD::ConstantFP, CFP->getValueType(0))) {
1159     default: assert(0 && "This action is not supported yet!");
1160     case TargetLowering::Legal:
1161       break;
1162     case TargetLowering::Custom:
1163       Tmp3 = TLI.LowerOperation(Result, DAG);
1164       if (Tmp3.Val) {
1165         Result = Tmp3;
1166         break;
1167       }
1168       // FALLTHROUGH
1169     case TargetLowering::Expand: {
1170       // Check to see if this FP immediate is already legal.
1171       bool isLegal = false;
1172       for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
1173              E = TLI.legal_fpimm_end(); I != E; ++I) {
1174         if (CFP->isExactlyValue(*I)) {
1175           isLegal = true;
1176           break;
1177         }
1178       }
1179       // If this is a legal constant, turn it into a TargetConstantFP node.
1180       if (isLegal)
1181         break;
1182       Result = ExpandConstantFP(CFP, true, DAG, TLI);
1183     }
1184     }
1185     break;
1186   }
1187   case ISD::TokenFactor:
1188     if (Node->getNumOperands() == 2) {
1189       Tmp1 = LegalizeOp(Node->getOperand(0));
1190       Tmp2 = LegalizeOp(Node->getOperand(1));
1191       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1192     } else if (Node->getNumOperands() == 3) {
1193       Tmp1 = LegalizeOp(Node->getOperand(0));
1194       Tmp2 = LegalizeOp(Node->getOperand(1));
1195       Tmp3 = LegalizeOp(Node->getOperand(2));
1196       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1197     } else {
1198       SmallVector<SDOperand, 8> Ops;
1199       // Legalize the operands.
1200       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1201         Ops.push_back(LegalizeOp(Node->getOperand(i)));
1202       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1203     }
1204     break;
1205     
1206   case ISD::FORMAL_ARGUMENTS:
1207   case ISD::CALL:
1208     // The only option for this is to custom lower it.
1209     Tmp3 = TLI.LowerOperation(Result.getValue(0), DAG);
1210     assert(Tmp3.Val && "Target didn't custom lower this node!");
1211
1212     // The number of incoming and outgoing values should match; unless the final
1213     // outgoing value is a flag.
1214     assert((Tmp3.Val->getNumValues() == Result.Val->getNumValues() ||
1215             (Tmp3.Val->getNumValues() == Result.Val->getNumValues() + 1 &&
1216              Tmp3.Val->getValueType(Tmp3.Val->getNumValues() - 1) ==
1217                MVT::Flag)) &&
1218            "Lowering call/formal_arguments produced unexpected # results!");
1219     
1220     // Since CALL/FORMAL_ARGUMENTS nodes produce multiple values, make sure to
1221     // remember that we legalized all of them, so it doesn't get relegalized.
1222     for (unsigned i = 0, e = Tmp3.Val->getNumValues(); i != e; ++i) {
1223       if (Tmp3.Val->getValueType(i) == MVT::Flag)
1224         continue;
1225       Tmp1 = LegalizeOp(Tmp3.getValue(i));
1226       if (Op.ResNo == i)
1227         Tmp2 = Tmp1;
1228       AddLegalizedOperand(SDOperand(Node, i), Tmp1);
1229     }
1230     return Tmp2;
1231    case ISD::EXTRACT_SUBREG: {
1232       Tmp1 = LegalizeOp(Node->getOperand(0));
1233       ConstantSDNode *idx = dyn_cast<ConstantSDNode>(Node->getOperand(1));
1234       assert(idx && "Operand must be a constant");
1235       Tmp2 = DAG.getTargetConstant(idx->getValue(), idx->getValueType(0));
1236       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1237     }
1238     break;
1239   case ISD::INSERT_SUBREG: {
1240       Tmp1 = LegalizeOp(Node->getOperand(0));
1241       Tmp2 = LegalizeOp(Node->getOperand(1));      
1242       ConstantSDNode *idx = dyn_cast<ConstantSDNode>(Node->getOperand(2));
1243       assert(idx && "Operand must be a constant");
1244       Tmp3 = DAG.getTargetConstant(idx->getValue(), idx->getValueType(0));
1245       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1246     }
1247     break;      
1248   case ISD::BUILD_VECTOR:
1249     switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
1250     default: assert(0 && "This action is not supported yet!");
1251     case TargetLowering::Custom:
1252       Tmp3 = TLI.LowerOperation(Result, DAG);
1253       if (Tmp3.Val) {
1254         Result = Tmp3;
1255         break;
1256       }
1257       // FALLTHROUGH
1258     case TargetLowering::Expand:
1259       Result = ExpandBUILD_VECTOR(Result.Val);
1260       break;
1261     }
1262     break;
1263   case ISD::INSERT_VECTOR_ELT:
1264     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVec
1265     Tmp3 = LegalizeOp(Node->getOperand(2));  // InEltNo
1266
1267     // The type of the value to insert may not be legal, even though the vector
1268     // type is legal.  Legalize/Promote accordingly.  We do not handle Expand
1269     // here.
1270     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1271     default: assert(0 && "Cannot expand insert element operand");
1272     case Legal:   Tmp2 = LegalizeOp(Node->getOperand(1)); break;
1273     case Promote: Tmp2 = PromoteOp(Node->getOperand(1));  break;
1274     }
1275     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1276     
1277     switch (TLI.getOperationAction(ISD::INSERT_VECTOR_ELT,
1278                                    Node->getValueType(0))) {
1279     default: assert(0 && "This action is not supported yet!");
1280     case TargetLowering::Legal:
1281       break;
1282     case TargetLowering::Custom:
1283       Tmp4 = TLI.LowerOperation(Result, DAG);
1284       if (Tmp4.Val) {
1285         Result = Tmp4;
1286         break;
1287       }
1288       // FALLTHROUGH
1289     case TargetLowering::Expand: {
1290       // If the insert index is a constant, codegen this as a scalar_to_vector,
1291       // then a shuffle that inserts it into the right position in the vector.
1292       if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Tmp3)) {
1293         // SCALAR_TO_VECTOR requires that the type of the value being inserted
1294         // match the element type of the vector being created.
1295         if (Tmp2.getValueType() == 
1296             MVT::getVectorElementType(Op.getValueType())) {
1297           SDOperand ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, 
1298                                         Tmp1.getValueType(), Tmp2);
1299           
1300           unsigned NumElts = MVT::getVectorNumElements(Tmp1.getValueType());
1301           MVT::ValueType ShufMaskVT = MVT::getIntVectorWithNumElements(NumElts);
1302           MVT::ValueType ShufMaskEltVT = MVT::getVectorElementType(ShufMaskVT);
1303           
1304           // We generate a shuffle of InVec and ScVec, so the shuffle mask
1305           // should be 0,1,2,3,4,5... with the appropriate element replaced with
1306           // elt 0 of the RHS.
1307           SmallVector<SDOperand, 8> ShufOps;
1308           for (unsigned i = 0; i != NumElts; ++i) {
1309             if (i != InsertPos->getValue())
1310               ShufOps.push_back(DAG.getConstant(i, ShufMaskEltVT));
1311             else
1312               ShufOps.push_back(DAG.getConstant(NumElts, ShufMaskEltVT));
1313           }
1314           SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMaskVT,
1315                                            &ShufOps[0], ShufOps.size());
1316           
1317           Result = DAG.getNode(ISD::VECTOR_SHUFFLE, Tmp1.getValueType(),
1318                                Tmp1, ScVec, ShufMask);
1319           Result = LegalizeOp(Result);
1320           break;
1321         }
1322       }
1323       
1324       // If the target doesn't support this, we have to spill the input vector
1325       // to a temporary stack slot, update the element, then reload it.  This is
1326       // badness.  We could also load the value into a vector register (either
1327       // with a "move to register" or "extload into register" instruction, then
1328       // permute it into place, if the idx is a constant and if the idx is
1329       // supported by the target.
1330       MVT::ValueType VT    = Tmp1.getValueType();
1331       MVT::ValueType EltVT = MVT::getVectorElementType(VT);
1332       MVT::ValueType IdxVT = Tmp3.getValueType();
1333       MVT::ValueType PtrVT = TLI.getPointerTy();
1334       SDOperand StackPtr = DAG.CreateStackTemporary(VT);
1335
1336       FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr.Val);
1337       int SPFI = StackPtrFI->getIndex();
1338
1339       // Store the vector.
1340       SDOperand Ch = DAG.getStore(DAG.getEntryNode(), Tmp1, StackPtr,
1341                                   PseudoSourceValue::getFixedStack(),
1342                                   SPFI);
1343
1344       // Truncate or zero extend offset to target pointer type.
1345       unsigned CastOpc = (IdxVT > PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
1346       Tmp3 = DAG.getNode(CastOpc, PtrVT, Tmp3);
1347       // Add the offset to the index.
1348       unsigned EltSize = MVT::getSizeInBits(EltVT)/8;
1349       Tmp3 = DAG.getNode(ISD::MUL, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
1350       SDOperand StackPtr2 = DAG.getNode(ISD::ADD, IdxVT, Tmp3, StackPtr);
1351       // Store the scalar value.
1352       Ch = DAG.getTruncStore(Ch, Tmp2, StackPtr2,
1353                              PseudoSourceValue::getFixedStack(), SPFI, EltVT);
1354       // Load the updated vector.
1355       Result = DAG.getLoad(VT, Ch, StackPtr,
1356                            PseudoSourceValue::getFixedStack(), SPFI);
1357       break;
1358     }
1359     }
1360     break;
1361   case ISD::SCALAR_TO_VECTOR:
1362     if (!TLI.isTypeLegal(Node->getOperand(0).getValueType())) {
1363       Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
1364       break;
1365     }
1366     
1367     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVal
1368     Result = DAG.UpdateNodeOperands(Result, Tmp1);
1369     switch (TLI.getOperationAction(ISD::SCALAR_TO_VECTOR,
1370                                    Node->getValueType(0))) {
1371     default: assert(0 && "This action is not supported yet!");
1372     case TargetLowering::Legal:
1373       break;
1374     case TargetLowering::Custom:
1375       Tmp3 = TLI.LowerOperation(Result, DAG);
1376       if (Tmp3.Val) {
1377         Result = Tmp3;
1378         break;
1379       }
1380       // FALLTHROUGH
1381     case TargetLowering::Expand:
1382       Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
1383       break;
1384     }
1385     break;
1386   case ISD::VECTOR_SHUFFLE:
1387     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the input vectors,
1388     Tmp2 = LegalizeOp(Node->getOperand(1));   // but not the shuffle mask.
1389     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1390
1391     // Allow targets to custom lower the SHUFFLEs they support.
1392     switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE,Result.getValueType())) {
1393     default: assert(0 && "Unknown operation action!");
1394     case TargetLowering::Legal:
1395       assert(isShuffleLegal(Result.getValueType(), Node->getOperand(2)) &&
1396              "vector shuffle should not be created if not legal!");
1397       break;
1398     case TargetLowering::Custom:
1399       Tmp3 = TLI.LowerOperation(Result, DAG);
1400       if (Tmp3.Val) {
1401         Result = Tmp3;
1402         break;
1403       }
1404       // FALLTHROUGH
1405     case TargetLowering::Expand: {
1406       MVT::ValueType VT = Node->getValueType(0);
1407       MVT::ValueType EltVT = MVT::getVectorElementType(VT);
1408       MVT::ValueType PtrVT = TLI.getPointerTy();
1409       SDOperand Mask = Node->getOperand(2);
1410       unsigned NumElems = Mask.getNumOperands();
1411       SmallVector<SDOperand,8> Ops;
1412       for (unsigned i = 0; i != NumElems; ++i) {
1413         SDOperand Arg = Mask.getOperand(i);
1414         if (Arg.getOpcode() == ISD::UNDEF) {
1415           Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
1416         } else {
1417           assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1418           unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
1419           if (Idx < NumElems)
1420             Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1,
1421                                       DAG.getConstant(Idx, PtrVT)));
1422           else
1423             Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2,
1424                                       DAG.getConstant(Idx - NumElems, PtrVT)));
1425         }
1426       }
1427       Result = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1428       break;
1429     }
1430     case TargetLowering::Promote: {
1431       // Change base type to a different vector type.
1432       MVT::ValueType OVT = Node->getValueType(0);
1433       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
1434
1435       // Cast the two input vectors.
1436       Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
1437       Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
1438       
1439       // Convert the shuffle mask to the right # elements.
1440       Tmp3 = SDOperand(isShuffleLegal(OVT, Node->getOperand(2)), 0);
1441       assert(Tmp3.Val && "Shuffle not legal?");
1442       Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NVT, Tmp1, Tmp2, Tmp3);
1443       Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
1444       break;
1445     }
1446     }
1447     break;
1448   
1449   case ISD::EXTRACT_VECTOR_ELT:
1450     Tmp1 = Node->getOperand(0);
1451     Tmp2 = LegalizeOp(Node->getOperand(1));
1452     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1453     Result = ExpandEXTRACT_VECTOR_ELT(Result);
1454     break;
1455
1456   case ISD::EXTRACT_SUBVECTOR: 
1457     Tmp1 = Node->getOperand(0);
1458     Tmp2 = LegalizeOp(Node->getOperand(1));
1459     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1460     Result = ExpandEXTRACT_SUBVECTOR(Result);
1461     break;
1462     
1463   case ISD::CALLSEQ_START: {
1464     SDNode *CallEnd = FindCallEndFromCallStart(Node);
1465     
1466     // Recursively Legalize all of the inputs of the call end that do not lead
1467     // to this call start.  This ensures that any libcalls that need be inserted
1468     // are inserted *before* the CALLSEQ_START.
1469     {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
1470     for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1471       LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).Val, Node,
1472                                    NodesLeadingTo);
1473     }
1474
1475     // Now that we legalized all of the inputs (which may have inserted
1476     // libcalls) create the new CALLSEQ_START node.
1477     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1478
1479     // Merge in the last call, to ensure that this call start after the last
1480     // call ended.
1481     if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
1482       Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1483       Tmp1 = LegalizeOp(Tmp1);
1484     }
1485       
1486     // Do not try to legalize the target-specific arguments (#1+).
1487     if (Tmp1 != Node->getOperand(0)) {
1488       SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
1489       Ops[0] = Tmp1;
1490       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1491     }
1492     
1493     // Remember that the CALLSEQ_START is legalized.
1494     AddLegalizedOperand(Op.getValue(0), Result);
1495     if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
1496       AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1497     
1498     // Now that the callseq_start and all of the non-call nodes above this call
1499     // sequence have been legalized, legalize the call itself.  During this 
1500     // process, no libcalls can/will be inserted, guaranteeing that no calls
1501     // can overlap.
1502     assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1503     SDOperand InCallSEQ = LastCALLSEQ_END;
1504     // Note that we are selecting this call!
1505     LastCALLSEQ_END = SDOperand(CallEnd, 0);
1506     IsLegalizingCall = true;
1507     
1508     // Legalize the call, starting from the CALLSEQ_END.
1509     LegalizeOp(LastCALLSEQ_END);
1510     assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1511     return Result;
1512   }
1513   case ISD::CALLSEQ_END:
1514     // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1515     // will cause this node to be legalized as well as handling libcalls right.
1516     if (LastCALLSEQ_END.Val != Node) {
1517       LegalizeOp(SDOperand(FindCallStartFromCallEnd(Node), 0));
1518       DenseMap<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
1519       assert(I != LegalizedNodes.end() &&
1520              "Legalizing the call start should have legalized this node!");
1521       return I->second;
1522     }
1523     
1524     // Otherwise, the call start has been legalized and everything is going 
1525     // according to plan.  Just legalize ourselves normally here.
1526     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1527     // Do not try to legalize the target-specific arguments (#1+), except for
1528     // an optional flag input.
1529     if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1530       if (Tmp1 != Node->getOperand(0)) {
1531         SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
1532         Ops[0] = Tmp1;
1533         Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1534       }
1535     } else {
1536       Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1537       if (Tmp1 != Node->getOperand(0) ||
1538           Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1539         SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
1540         Ops[0] = Tmp1;
1541         Ops.back() = Tmp2;
1542         Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1543       }
1544     }
1545     assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1546     // This finishes up call legalization.
1547     IsLegalizingCall = false;
1548     
1549     // If the CALLSEQ_END node has a flag, remember that we legalized it.
1550     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1551     if (Node->getNumValues() == 2)
1552       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1553     return Result.getValue(Op.ResNo);
1554   case ISD::DYNAMIC_STACKALLOC: {
1555     MVT::ValueType VT = Node->getValueType(0);
1556     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1557     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
1558     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
1559     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1560
1561     Tmp1 = Result.getValue(0);
1562     Tmp2 = Result.getValue(1);
1563     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1564     default: assert(0 && "This action is not supported yet!");
1565     case TargetLowering::Expand: {
1566       unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1567       assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1568              " not tell us which reg is the stack pointer!");
1569       SDOperand Chain = Tmp1.getOperand(0);
1570
1571       // Chain the dynamic stack allocation so that it doesn't modify the stack
1572       // pointer when other instructions are using the stack.
1573       Chain = DAG.getCALLSEQ_START(Chain,
1574                                    DAG.getConstant(0, TLI.getPointerTy()));
1575
1576       SDOperand Size  = Tmp2.getOperand(1);
1577       SDOperand SP = DAG.getCopyFromReg(Chain, SPReg, VT);
1578       Chain = SP.getValue(1);
1579       unsigned Align = cast<ConstantSDNode>(Tmp3)->getValue();
1580       unsigned StackAlign =
1581         TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1582       if (Align > StackAlign)
1583         SP = DAG.getNode(ISD::AND, VT, SP,
1584                          DAG.getConstant(-(uint64_t)Align, VT));
1585       Tmp1 = DAG.getNode(ISD::SUB, VT, SP, Size);       // Value
1586       Chain = DAG.getCopyToReg(Chain, SPReg, Tmp1);     // Output chain
1587
1588       Tmp2 =
1589         DAG.getCALLSEQ_END(Chain,
1590                            DAG.getConstant(0, TLI.getPointerTy()),
1591                            DAG.getConstant(0, TLI.getPointerTy()),
1592                            SDOperand());
1593
1594       Tmp1 = LegalizeOp(Tmp1);
1595       Tmp2 = LegalizeOp(Tmp2);
1596       break;
1597     }
1598     case TargetLowering::Custom:
1599       Tmp3 = TLI.LowerOperation(Tmp1, DAG);
1600       if (Tmp3.Val) {
1601         Tmp1 = LegalizeOp(Tmp3);
1602         Tmp2 = LegalizeOp(Tmp3.getValue(1));
1603       }
1604       break;
1605     case TargetLowering::Legal:
1606       break;
1607     }
1608     // Since this op produce two values, make sure to remember that we
1609     // legalized both of them.
1610     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1611     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1612     return Op.ResNo ? Tmp2 : Tmp1;
1613   }
1614   case ISD::INLINEASM: {
1615     SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
1616     bool Changed = false;
1617     // Legalize all of the operands of the inline asm, in case they are nodes
1618     // that need to be expanded or something.  Note we skip the asm string and
1619     // all of the TargetConstant flags.
1620     SDOperand Op = LegalizeOp(Ops[0]);
1621     Changed = Op != Ops[0];
1622     Ops[0] = Op;
1623
1624     bool HasInFlag = Ops.back().getValueType() == MVT::Flag;
1625     for (unsigned i = 2, e = Ops.size()-HasInFlag; i < e; ) {
1626       unsigned NumVals = cast<ConstantSDNode>(Ops[i])->getValue() >> 3;
1627       for (++i; NumVals; ++i, --NumVals) {
1628         SDOperand Op = LegalizeOp(Ops[i]);
1629         if (Op != Ops[i]) {
1630           Changed = true;
1631           Ops[i] = Op;
1632         }
1633       }
1634     }
1635
1636     if (HasInFlag) {
1637       Op = LegalizeOp(Ops.back());
1638       Changed |= Op != Ops.back();
1639       Ops.back() = Op;
1640     }
1641     
1642     if (Changed)
1643       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1644       
1645     // INLINE asm returns a chain and flag, make sure to add both to the map.
1646     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1647     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1648     return Result.getValue(Op.ResNo);
1649   }
1650   case ISD::BR:
1651     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1652     // Ensure that libcalls are emitted before a branch.
1653     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1654     Tmp1 = LegalizeOp(Tmp1);
1655     LastCALLSEQ_END = DAG.getEntryNode();
1656     
1657     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1658     break;
1659   case ISD::BRIND:
1660     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1661     // Ensure that libcalls are emitted before a branch.
1662     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1663     Tmp1 = LegalizeOp(Tmp1);
1664     LastCALLSEQ_END = DAG.getEntryNode();
1665     
1666     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1667     default: assert(0 && "Indirect target must be legal type (pointer)!");
1668     case Legal:
1669       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
1670       break;
1671     }
1672     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1673     break;
1674   case ISD::BR_JT:
1675     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1676     // Ensure that libcalls are emitted before a branch.
1677     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1678     Tmp1 = LegalizeOp(Tmp1);
1679     LastCALLSEQ_END = DAG.getEntryNode();
1680
1681     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the jumptable node.
1682     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1683
1684     switch (TLI.getOperationAction(ISD::BR_JT, MVT::Other)) {  
1685     default: assert(0 && "This action is not supported yet!");
1686     case TargetLowering::Legal: break;
1687     case TargetLowering::Custom:
1688       Tmp1 = TLI.LowerOperation(Result, DAG);
1689       if (Tmp1.Val) Result = Tmp1;
1690       break;
1691     case TargetLowering::Expand: {
1692       SDOperand Chain = Result.getOperand(0);
1693       SDOperand Table = Result.getOperand(1);
1694       SDOperand Index = Result.getOperand(2);
1695
1696       MVT::ValueType PTy = TLI.getPointerTy();
1697       MachineFunction &MF = DAG.getMachineFunction();
1698       unsigned EntrySize = MF.getJumpTableInfo()->getEntrySize();
1699       Index= DAG.getNode(ISD::MUL, PTy, Index, DAG.getConstant(EntrySize, PTy));
1700       SDOperand Addr = DAG.getNode(ISD::ADD, PTy, Index, Table);
1701       
1702       SDOperand LD;
1703       switch (EntrySize) {
1704       default: assert(0 && "Size of jump table not supported yet."); break;
1705       case 4: LD = DAG.getLoad(MVT::i32, Chain, Addr,
1706                                PseudoSourceValue::getJumpTable(), 0); break;
1707       case 8: LD = DAG.getLoad(MVT::i64, Chain, Addr,
1708                                PseudoSourceValue::getJumpTable(), 0); break;
1709       }
1710
1711       Addr = LD;
1712       if (TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1713         // For PIC, the sequence is:
1714         // BRIND(load(Jumptable + index) + RelocBase)
1715         // RelocBase can be JumpTable, GOT or some sort of global base.
1716         if (PTy != MVT::i32)
1717           Addr = DAG.getNode(ISD::SIGN_EXTEND, PTy, Addr);
1718         Addr = DAG.getNode(ISD::ADD, PTy, Addr,
1719                            TLI.getPICJumpTableRelocBase(Table, DAG));
1720       }
1721       Result = DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), Addr);
1722     }
1723     }
1724     break;
1725   case ISD::BRCOND:
1726     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1727     // Ensure that libcalls are emitted before a return.
1728     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1729     Tmp1 = LegalizeOp(Tmp1);
1730     LastCALLSEQ_END = DAG.getEntryNode();
1731
1732     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1733     case Expand: assert(0 && "It's impossible to expand bools");
1734     case Legal:
1735       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
1736       break;
1737     case Promote:
1738       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
1739       
1740       // The top bits of the promoted condition are not necessarily zero, ensure
1741       // that the value is properly zero extended.
1742       if (!DAG.MaskedValueIsZero(Tmp2, 
1743                                  MVT::getIntVTBitMask(Tmp2.getValueType())^1))
1744         Tmp2 = DAG.getZeroExtendInReg(Tmp2, MVT::i1);
1745       break;
1746     }
1747
1748     // Basic block destination (Op#2) is always legal.
1749     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1750       
1751     switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {  
1752     default: assert(0 && "This action is not supported yet!");
1753     case TargetLowering::Legal: break;
1754     case TargetLowering::Custom:
1755       Tmp1 = TLI.LowerOperation(Result, DAG);
1756       if (Tmp1.Val) Result = Tmp1;
1757       break;
1758     case TargetLowering::Expand:
1759       // Expand brcond's setcc into its constituent parts and create a BR_CC
1760       // Node.
1761       if (Tmp2.getOpcode() == ISD::SETCC) {
1762         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
1763                              Tmp2.getOperand(0), Tmp2.getOperand(1),
1764                              Node->getOperand(2));
1765       } else {
1766         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, 
1767                              DAG.getCondCode(ISD::SETNE), Tmp2,
1768                              DAG.getConstant(0, Tmp2.getValueType()),
1769                              Node->getOperand(2));
1770       }
1771       break;
1772     }
1773     break;
1774   case ISD::BR_CC:
1775     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1776     // Ensure that libcalls are emitted before a branch.
1777     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1778     Tmp1 = LegalizeOp(Tmp1);
1779     Tmp2 = Node->getOperand(2);              // LHS 
1780     Tmp3 = Node->getOperand(3);              // RHS
1781     Tmp4 = Node->getOperand(1);              // CC
1782
1783     LegalizeSetCCOperands(Tmp2, Tmp3, Tmp4);
1784     LastCALLSEQ_END = DAG.getEntryNode();
1785
1786     // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
1787     // the LHS is a legal SETCC itself.  In this case, we need to compare
1788     // the result against zero to select between true and false values.
1789     if (Tmp3.Val == 0) {
1790       Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
1791       Tmp4 = DAG.getCondCode(ISD::SETNE);
1792     }
1793     
1794     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp4, Tmp2, Tmp3, 
1795                                     Node->getOperand(4));
1796       
1797     switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
1798     default: assert(0 && "Unexpected action for BR_CC!");
1799     case TargetLowering::Legal: break;
1800     case TargetLowering::Custom:
1801       Tmp4 = TLI.LowerOperation(Result, DAG);
1802       if (Tmp4.Val) Result = Tmp4;
1803       break;
1804     }
1805     break;
1806   case ISD::LOAD: {
1807     LoadSDNode *LD = cast<LoadSDNode>(Node);
1808     Tmp1 = LegalizeOp(LD->getChain());   // Legalize the chain.
1809     Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
1810
1811     ISD::LoadExtType ExtType = LD->getExtensionType();
1812     if (ExtType == ISD::NON_EXTLOAD) {
1813       MVT::ValueType VT = Node->getValueType(0);
1814       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
1815       Tmp3 = Result.getValue(0);
1816       Tmp4 = Result.getValue(1);
1817     
1818       switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1819       default: assert(0 && "This action is not supported yet!");
1820       case TargetLowering::Legal:
1821         // If this is an unaligned load and the target doesn't support it,
1822         // expand it.
1823         if (!TLI.allowsUnalignedMemoryAccesses()) {
1824           unsigned ABIAlignment = TLI.getTargetData()->
1825             getABITypeAlignment(MVT::getTypeForValueType(LD->getMemoryVT()));
1826           if (LD->getAlignment() < ABIAlignment){
1827             Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.Val), DAG,
1828                                          TLI);
1829             Tmp3 = Result.getOperand(0);
1830             Tmp4 = Result.getOperand(1);
1831             Tmp3 = LegalizeOp(Tmp3);
1832             Tmp4 = LegalizeOp(Tmp4);
1833           }
1834         }
1835         break;
1836       case TargetLowering::Custom:
1837         Tmp1 = TLI.LowerOperation(Tmp3, DAG);
1838         if (Tmp1.Val) {
1839           Tmp3 = LegalizeOp(Tmp1);
1840           Tmp4 = LegalizeOp(Tmp1.getValue(1));
1841         }
1842         break;
1843       case TargetLowering::Promote: {
1844         // Only promote a load of vector type to another.
1845         assert(MVT::isVector(VT) && "Cannot promote this load!");
1846         // Change base type to a different vector type.
1847         MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
1848
1849         Tmp1 = DAG.getLoad(NVT, Tmp1, Tmp2, LD->getSrcValue(),
1850                            LD->getSrcValueOffset(),
1851                            LD->isVolatile(), LD->getAlignment());
1852         Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp1));
1853         Tmp4 = LegalizeOp(Tmp1.getValue(1));
1854         break;
1855       }
1856       }
1857       // Since loads produce two values, make sure to remember that we 
1858       // legalized both of them.
1859       AddLegalizedOperand(SDOperand(Node, 0), Tmp3);
1860       AddLegalizedOperand(SDOperand(Node, 1), Tmp4);
1861       return Op.ResNo ? Tmp4 : Tmp3;
1862     } else {
1863       MVT::ValueType SrcVT = LD->getMemoryVT();
1864       unsigned SrcWidth = MVT::getSizeInBits(SrcVT);
1865       int SVOffset = LD->getSrcValueOffset();
1866       unsigned Alignment = LD->getAlignment();
1867       bool isVolatile = LD->isVolatile();
1868
1869       if (SrcWidth != MVT::getStoreSizeInBits(SrcVT) &&
1870           // Some targets pretend to have an i1 loading operation, and actually
1871           // load an i8.  This trick is correct for ZEXTLOAD because the top 7
1872           // bits are guaranteed to be zero; it helps the optimizers understand
1873           // that these bits are zero.  It is also useful for EXTLOAD, since it
1874           // tells the optimizers that those bits are undefined.  It would be
1875           // nice to have an effective generic way of getting these benefits...
1876           // Until such a way is found, don't insist on promoting i1 here.
1877           (SrcVT != MVT::i1 ||
1878            TLI.getLoadXAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
1879         // Promote to a byte-sized load if not loading an integral number of
1880         // bytes.  For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
1881         unsigned NewWidth = MVT::getStoreSizeInBits(SrcVT);
1882         MVT::ValueType NVT = MVT::getIntegerType(NewWidth);
1883         SDOperand Ch;
1884
1885         // The extra bits are guaranteed to be zero, since we stored them that
1886         // way.  A zext load from NVT thus automatically gives zext from SrcVT.
1887
1888         ISD::LoadExtType NewExtType =
1889           ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
1890
1891         Result = DAG.getExtLoad(NewExtType, Node->getValueType(0),
1892                                 Tmp1, Tmp2, LD->getSrcValue(), SVOffset,
1893                                 NVT, isVolatile, Alignment);
1894
1895         Ch = Result.getValue(1); // The chain.
1896
1897         if (ExtType == ISD::SEXTLOAD)
1898           // Having the top bits zero doesn't help when sign extending.
1899           Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1900                                Result, DAG.getValueType(SrcVT));
1901         else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
1902           // All the top bits are guaranteed to be zero - inform the optimizers.
1903           Result = DAG.getNode(ISD::AssertZext, Result.getValueType(), Result,
1904                                DAG.getValueType(SrcVT));
1905
1906         Tmp1 = LegalizeOp(Result);
1907         Tmp2 = LegalizeOp(Ch);
1908       } else if (SrcWidth & (SrcWidth - 1)) {
1909         // If not loading a power-of-2 number of bits, expand as two loads.
1910         assert(MVT::isExtendedVT(SrcVT) && !MVT::isVector(SrcVT) &&
1911                "Unsupported extload!");
1912         unsigned RoundWidth = 1 << Log2_32(SrcWidth);
1913         assert(RoundWidth < SrcWidth);
1914         unsigned ExtraWidth = SrcWidth - RoundWidth;
1915         assert(ExtraWidth < RoundWidth);
1916         assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1917                "Load size not an integral number of bytes!");
1918         MVT::ValueType RoundVT = MVT::getIntegerType(RoundWidth);
1919         MVT::ValueType ExtraVT = MVT::getIntegerType(ExtraWidth);
1920         SDOperand Lo, Hi, Ch;
1921         unsigned IncrementSize;
1922
1923         if (TLI.isLittleEndian()) {
1924           // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
1925           // Load the bottom RoundWidth bits.
1926           Lo = DAG.getExtLoad(ISD::ZEXTLOAD, Node->getValueType(0), Tmp1, Tmp2,
1927                               LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
1928                               Alignment);
1929
1930           // Load the remaining ExtraWidth bits.
1931           IncrementSize = RoundWidth / 8;
1932           Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
1933                              DAG.getIntPtrConstant(IncrementSize));
1934           Hi = DAG.getExtLoad(ExtType, Node->getValueType(0), Tmp1, Tmp2,
1935                               LD->getSrcValue(), SVOffset + IncrementSize,
1936                               ExtraVT, isVolatile,
1937                               MinAlign(Alignment, IncrementSize));
1938
1939           // Build a factor node to remember that this load is independent of the
1940           // other one.
1941           Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
1942                            Hi.getValue(1));
1943
1944           // Move the top bits to the right place.
1945           Hi = DAG.getNode(ISD::SHL, Hi.getValueType(), Hi,
1946                            DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1947
1948           // Join the hi and lo parts.
1949           Result = DAG.getNode(ISD::OR, Node->getValueType(0), Lo, Hi);
1950         } else {
1951           // Big endian - avoid unaligned loads.
1952           // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
1953           // Load the top RoundWidth bits.
1954           Hi = DAG.getExtLoad(ExtType, Node->getValueType(0), Tmp1, Tmp2,
1955                               LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
1956                               Alignment);
1957
1958           // Load the remaining ExtraWidth bits.
1959           IncrementSize = RoundWidth / 8;
1960           Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
1961                              DAG.getIntPtrConstant(IncrementSize));
1962           Lo = DAG.getExtLoad(ISD::ZEXTLOAD, Node->getValueType(0), Tmp1, Tmp2,
1963                               LD->getSrcValue(), SVOffset + IncrementSize,
1964                               ExtraVT, isVolatile,
1965                               MinAlign(Alignment, IncrementSize));
1966
1967           // Build a factor node to remember that this load is independent of the
1968           // other one.
1969           Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
1970                            Hi.getValue(1));
1971
1972           // Move the top bits to the right place.
1973           Hi = DAG.getNode(ISD::SHL, Hi.getValueType(), Hi,
1974                            DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1975
1976           // Join the hi and lo parts.
1977           Result = DAG.getNode(ISD::OR, Node->getValueType(0), Lo, Hi);
1978         }
1979
1980         Tmp1 = LegalizeOp(Result);
1981         Tmp2 = LegalizeOp(Ch);
1982       } else {
1983         switch (TLI.getLoadXAction(ExtType, SrcVT)) {
1984         default: assert(0 && "This action is not supported yet!");
1985         case TargetLowering::Custom:
1986           isCustom = true;
1987           // FALLTHROUGH
1988         case TargetLowering::Legal:
1989           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
1990           Tmp1 = Result.getValue(0);
1991           Tmp2 = Result.getValue(1);
1992
1993           if (isCustom) {
1994             Tmp3 = TLI.LowerOperation(Result, DAG);
1995             if (Tmp3.Val) {
1996               Tmp1 = LegalizeOp(Tmp3);
1997               Tmp2 = LegalizeOp(Tmp3.getValue(1));
1998             }
1999           } else {
2000             // If this is an unaligned load and the target doesn't support it,
2001             // expand it.
2002             if (!TLI.allowsUnalignedMemoryAccesses()) {
2003               unsigned ABIAlignment = TLI.getTargetData()->
2004                 getABITypeAlignment(MVT::getTypeForValueType(LD->getMemoryVT()));
2005               if (LD->getAlignment() < ABIAlignment){
2006                 Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.Val), DAG,
2007                                              TLI);
2008                 Tmp1 = Result.getOperand(0);
2009                 Tmp2 = Result.getOperand(1);
2010                 Tmp1 = LegalizeOp(Tmp1);
2011                 Tmp2 = LegalizeOp(Tmp2);
2012               }
2013             }
2014           }
2015           break;
2016         case TargetLowering::Expand:
2017           // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
2018           if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
2019             SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, LD->getSrcValue(),
2020                                          LD->getSrcValueOffset(),
2021                                          LD->isVolatile(), LD->getAlignment());
2022             Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
2023             Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
2024             Tmp2 = LegalizeOp(Load.getValue(1));
2025             break;
2026           }
2027           assert(ExtType != ISD::EXTLOAD &&"EXTLOAD should always be supported!");
2028           // Turn the unsupported load into an EXTLOAD followed by an explicit
2029           // zero/sign extend inreg.
2030           Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
2031                                   Tmp1, Tmp2, LD->getSrcValue(),
2032                                   LD->getSrcValueOffset(), SrcVT,
2033                                   LD->isVolatile(), LD->getAlignment());
2034           SDOperand ValRes;
2035           if (ExtType == ISD::SEXTLOAD)
2036             ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2037                                  Result, DAG.getValueType(SrcVT));
2038           else
2039             ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
2040           Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
2041           Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
2042           break;
2043         }
2044       }
2045
2046       // Since loads produce two values, make sure to remember that we legalized
2047       // both of them.
2048       AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
2049       AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
2050       return Op.ResNo ? Tmp2 : Tmp1;
2051     }
2052   }
2053   case ISD::EXTRACT_ELEMENT: {
2054     MVT::ValueType OpTy = Node->getOperand(0).getValueType();
2055     switch (getTypeAction(OpTy)) {
2056     default: assert(0 && "EXTRACT_ELEMENT action for type unimplemented!");
2057     case Legal:
2058       if (cast<ConstantSDNode>(Node->getOperand(1))->getValue()) {
2059         // 1 -> Hi
2060         Result = DAG.getNode(ISD::SRL, OpTy, Node->getOperand(0),
2061                              DAG.getConstant(MVT::getSizeInBits(OpTy)/2, 
2062                                              TLI.getShiftAmountTy()));
2063         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Result);
2064       } else {
2065         // 0 -> Lo
2066         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), 
2067                              Node->getOperand(0));
2068       }
2069       break;
2070     case Expand:
2071       // Get both the low and high parts.
2072       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2073       if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
2074         Result = Tmp2;  // 1 -> Hi
2075       else
2076         Result = Tmp1;  // 0 -> Lo
2077       break;
2078     }
2079     break;
2080   }
2081
2082   case ISD::CopyToReg:
2083     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2084
2085     assert(isTypeLegal(Node->getOperand(2).getValueType()) &&
2086            "Register type must be legal!");
2087     // Legalize the incoming value (must be a legal type).
2088     Tmp2 = LegalizeOp(Node->getOperand(2));
2089     if (Node->getNumValues() == 1) {
2090       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2);
2091     } else {
2092       assert(Node->getNumValues() == 2 && "Unknown CopyToReg");
2093       if (Node->getNumOperands() == 4) {
2094         Tmp3 = LegalizeOp(Node->getOperand(3));
2095         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2,
2096                                         Tmp3);
2097       } else {
2098         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
2099       }
2100       
2101       // Since this produces two values, make sure to remember that we legalized
2102       // both of them.
2103       AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2104       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2105       return Result;
2106     }
2107     break;
2108
2109   case ISD::RET:
2110     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2111
2112     // Ensure that libcalls are emitted before a return.
2113     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
2114     Tmp1 = LegalizeOp(Tmp1);
2115     LastCALLSEQ_END = DAG.getEntryNode();
2116       
2117     switch (Node->getNumOperands()) {
2118     case 3:  // ret val
2119       Tmp2 = Node->getOperand(1);
2120       Tmp3 = Node->getOperand(2);  // Signness
2121       switch (getTypeAction(Tmp2.getValueType())) {
2122       case Legal:
2123         Result = DAG.UpdateNodeOperands(Result, Tmp1, LegalizeOp(Tmp2), Tmp3);
2124         break;
2125       case Expand:
2126         if (!MVT::isVector(Tmp2.getValueType())) {
2127           SDOperand Lo, Hi;
2128           ExpandOp(Tmp2, Lo, Hi);
2129
2130           // Big endian systems want the hi reg first.
2131           if (TLI.isBigEndian())
2132             std::swap(Lo, Hi);
2133           
2134           if (Hi.Val)
2135             Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3, Hi,Tmp3);
2136           else
2137             Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3);
2138           Result = LegalizeOp(Result);
2139         } else {
2140           SDNode *InVal = Tmp2.Val;
2141           int InIx = Tmp2.ResNo;
2142           unsigned NumElems = MVT::getVectorNumElements(InVal->getValueType(InIx));
2143           MVT::ValueType EVT = MVT::getVectorElementType(InVal->getValueType(InIx));
2144           
2145           // Figure out if there is a simple type corresponding to this Vector
2146           // type.  If so, convert to the vector type.
2147           MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
2148           if (TLI.isTypeLegal(TVT)) {
2149             // Turn this into a return of the vector type.
2150             Tmp2 = LegalizeOp(Tmp2);
2151             Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2152           } else if (NumElems == 1) {
2153             // Turn this into a return of the scalar type.
2154             Tmp2 = ScalarizeVectorOp(Tmp2);
2155             Tmp2 = LegalizeOp(Tmp2);
2156             Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2157             
2158             // FIXME: Returns of gcc generic vectors smaller than a legal type
2159             // should be returned in integer registers!
2160             
2161             // The scalarized value type may not be legal, e.g. it might require
2162             // promotion or expansion.  Relegalize the return.
2163             Result = LegalizeOp(Result);
2164           } else {
2165             // FIXME: Returns of gcc generic vectors larger than a legal vector
2166             // type should be returned by reference!
2167             SDOperand Lo, Hi;
2168             SplitVectorOp(Tmp2, Lo, Hi);
2169             Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3, Hi,Tmp3);
2170             Result = LegalizeOp(Result);
2171           }
2172         }
2173         break;
2174       case Promote:
2175         Tmp2 = PromoteOp(Node->getOperand(1));
2176         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2177         Result = LegalizeOp(Result);
2178         break;
2179       }
2180       break;
2181     case 1:  // ret void
2182       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2183       break;
2184     default: { // ret <values>
2185       SmallVector<SDOperand, 8> NewValues;
2186       NewValues.push_back(Tmp1);
2187       for (unsigned i = 1, e = Node->getNumOperands(); i < e; i += 2)
2188         switch (getTypeAction(Node->getOperand(i).getValueType())) {
2189         case Legal:
2190           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
2191           NewValues.push_back(Node->getOperand(i+1));
2192           break;
2193         case Expand: {
2194           SDOperand Lo, Hi;
2195           assert(!MVT::isExtendedVT(Node->getOperand(i).getValueType()) &&
2196                  "FIXME: TODO: implement returning non-legal vector types!");
2197           ExpandOp(Node->getOperand(i), Lo, Hi);
2198           NewValues.push_back(Lo);
2199           NewValues.push_back(Node->getOperand(i+1));
2200           if (Hi.Val) {
2201             NewValues.push_back(Hi);
2202             NewValues.push_back(Node->getOperand(i+1));
2203           }
2204           break;
2205         }
2206         case Promote:
2207           assert(0 && "Can't promote multiple return value yet!");
2208         }
2209           
2210       if (NewValues.size() == Node->getNumOperands())
2211         Result = DAG.UpdateNodeOperands(Result, &NewValues[0],NewValues.size());
2212       else
2213         Result = DAG.getNode(ISD::RET, MVT::Other,
2214                              &NewValues[0], NewValues.size());
2215       break;
2216     }
2217     }
2218
2219     if (Result.getOpcode() == ISD::RET) {
2220       switch (TLI.getOperationAction(Result.getOpcode(), MVT::Other)) {
2221       default: assert(0 && "This action is not supported yet!");
2222       case TargetLowering::Legal: break;
2223       case TargetLowering::Custom:
2224         Tmp1 = TLI.LowerOperation(Result, DAG);
2225         if (Tmp1.Val) Result = Tmp1;
2226         break;
2227       }
2228     }
2229     break;
2230   case ISD::STORE: {
2231     StoreSDNode *ST = cast<StoreSDNode>(Node);
2232     Tmp1 = LegalizeOp(ST->getChain());    // Legalize the chain.
2233     Tmp2 = LegalizeOp(ST->getBasePtr());  // Legalize the pointer.
2234     int SVOffset = ST->getSrcValueOffset();
2235     unsigned Alignment = ST->getAlignment();
2236     bool isVolatile = ST->isVolatile();
2237
2238     if (!ST->isTruncatingStore()) {
2239       // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
2240       // FIXME: We shouldn't do this for TargetConstantFP's.
2241       // FIXME: move this to the DAG Combiner!  Note that we can't regress due
2242       // to phase ordering between legalized code and the dag combiner.  This
2243       // probably means that we need to integrate dag combiner and legalizer
2244       // together.
2245       // We generally can't do this one for long doubles.
2246       if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
2247         if (CFP->getValueType(0) == MVT::f32 && 
2248             getTypeAction(MVT::i32) == Legal) {
2249           Tmp3 = DAG.getConstant((uint32_t)CFP->getValueAPF().
2250                                           convertToAPInt().getZExtValue(),
2251                                   MVT::i32);
2252           Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2253                                 SVOffset, isVolatile, Alignment);
2254           break;
2255         } else if (CFP->getValueType(0) == MVT::f64) {
2256           // If this target supports 64-bit registers, do a single 64-bit store.
2257           if (getTypeAction(MVT::i64) == Legal) {
2258             Tmp3 = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
2259                                      getZExtValue(), MVT::i64);
2260             Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2261                                   SVOffset, isVolatile, Alignment);
2262             break;
2263           } else if (getTypeAction(MVT::i32) == Legal) {
2264             // Otherwise, if the target supports 32-bit registers, use 2 32-bit
2265             // stores.  If the target supports neither 32- nor 64-bits, this
2266             // xform is certainly not worth it.
2267             uint64_t IntVal =CFP->getValueAPF().convertToAPInt().getZExtValue();
2268             SDOperand Lo = DAG.getConstant(uint32_t(IntVal), MVT::i32);
2269             SDOperand Hi = DAG.getConstant(uint32_t(IntVal >>32), MVT::i32);
2270             if (TLI.isBigEndian()) std::swap(Lo, Hi);
2271
2272             Lo = DAG.getStore(Tmp1, Lo, Tmp2, ST->getSrcValue(),
2273                               SVOffset, isVolatile, Alignment);
2274             Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2275                                DAG.getIntPtrConstant(4));
2276             Hi = DAG.getStore(Tmp1, Hi, Tmp2, ST->getSrcValue(), SVOffset+4,
2277                               isVolatile, MinAlign(Alignment, 4U));
2278
2279             Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2280             break;
2281           }
2282         }
2283       }
2284       
2285       switch (getTypeAction(ST->getMemoryVT())) {
2286       case Legal: {
2287         Tmp3 = LegalizeOp(ST->getValue());
2288         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
2289                                         ST->getOffset());
2290
2291         MVT::ValueType VT = Tmp3.getValueType();
2292         switch (TLI.getOperationAction(ISD::STORE, VT)) {
2293         default: assert(0 && "This action is not supported yet!");
2294         case TargetLowering::Legal:
2295           // If this is an unaligned store and the target doesn't support it,
2296           // expand it.
2297           if (!TLI.allowsUnalignedMemoryAccesses()) {
2298             unsigned ABIAlignment = TLI.getTargetData()->
2299               getABITypeAlignment(MVT::getTypeForValueType(ST->getMemoryVT()));
2300             if (ST->getAlignment() < ABIAlignment)
2301               Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.Val), DAG,
2302                                             TLI);
2303           }
2304           break;
2305         case TargetLowering::Custom:
2306           Tmp1 = TLI.LowerOperation(Result, DAG);
2307           if (Tmp1.Val) Result = Tmp1;
2308           break;
2309         case TargetLowering::Promote:
2310           assert(MVT::isVector(VT) && "Unknown legal promote case!");
2311           Tmp3 = DAG.getNode(ISD::BIT_CONVERT, 
2312                              TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
2313           Result = DAG.getStore(Tmp1, Tmp3, Tmp2,
2314                                 ST->getSrcValue(), SVOffset, isVolatile,
2315                                 Alignment);
2316           break;
2317         }
2318         break;
2319       }
2320       case Promote:
2321         // Truncate the value and store the result.
2322         Tmp3 = PromoteOp(ST->getValue());
2323         Result = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2324                                    SVOffset, ST->getMemoryVT(),
2325                                    isVolatile, Alignment);
2326         break;
2327
2328       case Expand:
2329         unsigned IncrementSize = 0;
2330         SDOperand Lo, Hi;
2331       
2332         // If this is a vector type, then we have to calculate the increment as
2333         // the product of the element size in bytes, and the number of elements
2334         // in the high half of the vector.
2335         if (MVT::isVector(ST->getValue().getValueType())) {
2336           SDNode *InVal = ST->getValue().Val;
2337           int InIx = ST->getValue().ResNo;
2338           MVT::ValueType InVT = InVal->getValueType(InIx);
2339           unsigned NumElems = MVT::getVectorNumElements(InVT);
2340           MVT::ValueType EVT = MVT::getVectorElementType(InVT);
2341
2342           // Figure out if there is a simple type corresponding to this Vector
2343           // type.  If so, convert to the vector type.
2344           MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
2345           if (TLI.isTypeLegal(TVT)) {
2346             // Turn this into a normal store of the vector type.
2347             Tmp3 = LegalizeOp(ST->getValue());
2348             Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2349                                   SVOffset, isVolatile, Alignment);
2350             Result = LegalizeOp(Result);
2351             break;
2352           } else if (NumElems == 1) {
2353             // Turn this into a normal store of the scalar type.
2354             Tmp3 = ScalarizeVectorOp(ST->getValue());
2355             Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2356                                   SVOffset, isVolatile, Alignment);
2357             // The scalarized value type may not be legal, e.g. it might require
2358             // promotion or expansion.  Relegalize the scalar store.
2359             Result = LegalizeOp(Result);
2360             break;
2361           } else {
2362             SplitVectorOp(ST->getValue(), Lo, Hi);
2363             IncrementSize = MVT::getVectorNumElements(Lo.Val->getValueType(0)) * 
2364                             MVT::getSizeInBits(EVT)/8;
2365           }
2366         } else {
2367           ExpandOp(ST->getValue(), Lo, Hi);
2368           IncrementSize = Hi.Val ? MVT::getSizeInBits(Hi.getValueType())/8 : 0;
2369
2370           if (TLI.isBigEndian())
2371             std::swap(Lo, Hi);
2372         }
2373
2374         Lo = DAG.getStore(Tmp1, Lo, Tmp2, ST->getSrcValue(),
2375                           SVOffset, isVolatile, Alignment);
2376
2377         if (Hi.Val == NULL) {
2378           // Must be int <-> float one-to-one expansion.
2379           Result = Lo;
2380           break;
2381         }
2382
2383         Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2384                            DAG.getIntPtrConstant(IncrementSize));
2385         assert(isTypeLegal(Tmp2.getValueType()) &&
2386                "Pointers must be legal!");
2387         SVOffset += IncrementSize;
2388         Alignment = MinAlign(Alignment, IncrementSize);
2389         Hi = DAG.getStore(Tmp1, Hi, Tmp2, ST->getSrcValue(),
2390                           SVOffset, isVolatile, Alignment);
2391         Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2392         break;
2393       }
2394     } else {
2395       switch (getTypeAction(ST->getValue().getValueType())) {
2396       case Legal:
2397         Tmp3 = LegalizeOp(ST->getValue());
2398         break;
2399       case Promote:
2400         // We can promote the value, the truncstore will still take care of it.
2401         Tmp3 = PromoteOp(ST->getValue());
2402         break;
2403       case Expand:
2404         // Just store the low part.  This may become a non-trunc store, so make
2405         // sure to use getTruncStore, not UpdateNodeOperands below.
2406         ExpandOp(ST->getValue(), Tmp3, Tmp4);
2407         return DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2408                                  SVOffset, MVT::i8, isVolatile, Alignment);
2409       }
2410
2411       MVT::ValueType StVT = ST->getMemoryVT();
2412       unsigned StWidth = MVT::getSizeInBits(StVT);
2413
2414       if (StWidth != MVT::getStoreSizeInBits(StVT)) {
2415         // Promote to a byte-sized store with upper bits zero if not
2416         // storing an integral number of bytes.  For example, promote
2417         // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
2418         MVT::ValueType NVT = MVT::getIntegerType(MVT::getStoreSizeInBits(StVT));
2419         Tmp3 = DAG.getZeroExtendInReg(Tmp3, StVT);
2420         Result = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2421                                    SVOffset, NVT, isVolatile, Alignment);
2422       } else if (StWidth & (StWidth - 1)) {
2423         // If not storing a power-of-2 number of bits, expand as two stores.
2424         assert(MVT::isExtendedVT(StVT) && !MVT::isVector(StVT) &&
2425                "Unsupported truncstore!");
2426         unsigned RoundWidth = 1 << Log2_32(StWidth);
2427         assert(RoundWidth < StWidth);
2428         unsigned ExtraWidth = StWidth - RoundWidth;
2429         assert(ExtraWidth < RoundWidth);
2430         assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
2431                "Store size not an integral number of bytes!");
2432         MVT::ValueType RoundVT = MVT::getIntegerType(RoundWidth);
2433         MVT::ValueType ExtraVT = MVT::getIntegerType(ExtraWidth);
2434         SDOperand Lo, Hi;
2435         unsigned IncrementSize;
2436
2437         if (TLI.isLittleEndian()) {
2438           // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
2439           // Store the bottom RoundWidth bits.
2440           Lo = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2441                                  SVOffset, RoundVT,
2442                                  isVolatile, Alignment);
2443
2444           // Store the remaining ExtraWidth bits.
2445           IncrementSize = RoundWidth / 8;
2446           Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2447                              DAG.getIntPtrConstant(IncrementSize));
2448           Hi = DAG.getNode(ISD::SRL, Tmp3.getValueType(), Tmp3,
2449                            DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
2450           Hi = DAG.getTruncStore(Tmp1, Hi, Tmp2, ST->getSrcValue(),
2451                                  SVOffset + IncrementSize, ExtraVT, isVolatile,
2452                                  MinAlign(Alignment, IncrementSize));
2453         } else {
2454           // Big endian - avoid unaligned stores.
2455           // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
2456           // Store the top RoundWidth bits.
2457           Hi = DAG.getNode(ISD::SRL, Tmp3.getValueType(), Tmp3,
2458                            DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
2459           Hi = DAG.getTruncStore(Tmp1, Hi, Tmp2, ST->getSrcValue(), SVOffset,
2460                                  RoundVT, isVolatile, Alignment);
2461
2462           // Store the remaining ExtraWidth bits.
2463           IncrementSize = RoundWidth / 8;
2464           Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2465                              DAG.getIntPtrConstant(IncrementSize));
2466           Lo = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2467                                  SVOffset + IncrementSize, ExtraVT, isVolatile,
2468                                  MinAlign(Alignment, IncrementSize));
2469         }
2470
2471         // The order of the stores doesn't matter.
2472         Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2473       } else {
2474         if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
2475             Tmp2 != ST->getBasePtr())
2476           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
2477                                           ST->getOffset());
2478
2479         switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
2480         default: assert(0 && "This action is not supported yet!");
2481         case TargetLowering::Legal:
2482           // If this is an unaligned store and the target doesn't support it,
2483           // expand it.
2484           if (!TLI.allowsUnalignedMemoryAccesses()) {
2485             unsigned ABIAlignment = TLI.getTargetData()->
2486               getABITypeAlignment(MVT::getTypeForValueType(ST->getMemoryVT()));
2487             if (ST->getAlignment() < ABIAlignment)
2488               Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.Val), DAG,
2489                                             TLI);
2490           }
2491           break;
2492         case TargetLowering::Custom:
2493           Result = TLI.LowerOperation(Result, DAG);
2494           break;
2495         case Expand:
2496           // TRUNCSTORE:i16 i32 -> STORE i16
2497           assert(isTypeLegal(StVT) && "Do not know how to expand this store!");
2498           Tmp3 = DAG.getNode(ISD::TRUNCATE, StVT, Tmp3);
2499           Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(), SVOffset,
2500                                 isVolatile, Alignment);
2501           break;
2502         }
2503       }
2504     }
2505     break;
2506   }
2507   case ISD::PCMARKER:
2508     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2509     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
2510     break;
2511   case ISD::STACKSAVE:
2512     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2513     Result = DAG.UpdateNodeOperands(Result, Tmp1);
2514     Tmp1 = Result.getValue(0);
2515     Tmp2 = Result.getValue(1);
2516     
2517     switch (TLI.getOperationAction(ISD::STACKSAVE, MVT::Other)) {
2518     default: assert(0 && "This action is not supported yet!");
2519     case TargetLowering::Legal: break;
2520     case TargetLowering::Custom:
2521       Tmp3 = TLI.LowerOperation(Result, DAG);
2522       if (Tmp3.Val) {
2523         Tmp1 = LegalizeOp(Tmp3);
2524         Tmp2 = LegalizeOp(Tmp3.getValue(1));
2525       }
2526       break;
2527     case TargetLowering::Expand:
2528       // Expand to CopyFromReg if the target set 
2529       // StackPointerRegisterToSaveRestore.
2530       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2531         Tmp1 = DAG.getCopyFromReg(Result.getOperand(0), SP,
2532                                   Node->getValueType(0));
2533         Tmp2 = Tmp1.getValue(1);
2534       } else {
2535         Tmp1 = DAG.getNode(ISD::UNDEF, Node->getValueType(0));
2536         Tmp2 = Node->getOperand(0);
2537       }
2538       break;
2539     }
2540
2541     // Since stacksave produce two values, make sure to remember that we
2542     // legalized both of them.
2543     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
2544     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
2545     return Op.ResNo ? Tmp2 : Tmp1;
2546
2547   case ISD::STACKRESTORE:
2548     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2549     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2550     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2551       
2552     switch (TLI.getOperationAction(ISD::STACKRESTORE, MVT::Other)) {
2553     default: assert(0 && "This action is not supported yet!");
2554     case TargetLowering::Legal: break;
2555     case TargetLowering::Custom:
2556       Tmp1 = TLI.LowerOperation(Result, DAG);
2557       if (Tmp1.Val) Result = Tmp1;
2558       break;
2559     case TargetLowering::Expand:
2560       // Expand to CopyToReg if the target set 
2561       // StackPointerRegisterToSaveRestore.
2562       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2563         Result = DAG.getCopyToReg(Tmp1, SP, Tmp2);
2564       } else {
2565         Result = Tmp1;
2566       }
2567       break;
2568     }
2569     break;
2570
2571   case ISD::READCYCLECOUNTER:
2572     Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
2573     Result = DAG.UpdateNodeOperands(Result, Tmp1);
2574     switch (TLI.getOperationAction(ISD::READCYCLECOUNTER,
2575                                    Node->getValueType(0))) {
2576     default: assert(0 && "This action is not supported yet!");
2577     case TargetLowering::Legal:
2578       Tmp1 = Result.getValue(0);
2579       Tmp2 = Result.getValue(1);
2580       break;
2581     case TargetLowering::Custom:
2582       Result = TLI.LowerOperation(Result, DAG);
2583       Tmp1 = LegalizeOp(Result.getValue(0));
2584       Tmp2 = LegalizeOp(Result.getValue(1));
2585       break;
2586     }
2587
2588     // Since rdcc produce two values, make sure to remember that we legalized
2589     // both of them.
2590     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
2591     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
2592     return Result;
2593
2594   case ISD::SELECT:
2595     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2596     case Expand: assert(0 && "It's impossible to expand bools");
2597     case Legal:
2598       Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
2599       break;
2600     case Promote:
2601       Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
2602       // Make sure the condition is either zero or one.
2603       if (!DAG.MaskedValueIsZero(Tmp1,
2604                                  MVT::getIntVTBitMask(Tmp1.getValueType())^1))
2605         Tmp1 = DAG.getZeroExtendInReg(Tmp1, MVT::i1);
2606       break;
2607     }
2608     Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
2609     Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
2610
2611     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2612       
2613     switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
2614     default: assert(0 && "This action is not supported yet!");
2615     case TargetLowering::Legal: break;
2616     case TargetLowering::Custom: {
2617       Tmp1 = TLI.LowerOperation(Result, DAG);
2618       if (Tmp1.Val) Result = Tmp1;
2619       break;
2620     }
2621     case TargetLowering::Expand:
2622       if (Tmp1.getOpcode() == ISD::SETCC) {
2623         Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1), 
2624                               Tmp2, Tmp3,
2625                               cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
2626       } else {
2627         Result = DAG.getSelectCC(Tmp1, 
2628                                  DAG.getConstant(0, Tmp1.getValueType()),
2629                                  Tmp2, Tmp3, ISD::SETNE);
2630       }
2631       break;
2632     case TargetLowering::Promote: {
2633       MVT::ValueType NVT =
2634         TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
2635       unsigned ExtOp, TruncOp;
2636       if (MVT::isVector(Tmp2.getValueType())) {
2637         ExtOp   = ISD::BIT_CONVERT;
2638         TruncOp = ISD::BIT_CONVERT;
2639       } else if (MVT::isInteger(Tmp2.getValueType())) {
2640         ExtOp   = ISD::ANY_EXTEND;
2641         TruncOp = ISD::TRUNCATE;
2642       } else {
2643         ExtOp   = ISD::FP_EXTEND;
2644         TruncOp = ISD::FP_ROUND;
2645       }
2646       // Promote each of the values to the new type.
2647       Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
2648       Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
2649       // Perform the larger operation, then round down.
2650       Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
2651       if (TruncOp != ISD::FP_ROUND)
2652         Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
2653       else
2654         Result = DAG.getNode(TruncOp, Node->getValueType(0), Result,
2655                              DAG.getIntPtrConstant(0));
2656       break;
2657     }
2658     }
2659     break;
2660   case ISD::SELECT_CC: {
2661     Tmp1 = Node->getOperand(0);               // LHS
2662     Tmp2 = Node->getOperand(1);               // RHS
2663     Tmp3 = LegalizeOp(Node->getOperand(2));   // True
2664     Tmp4 = LegalizeOp(Node->getOperand(3));   // False
2665     SDOperand CC = Node->getOperand(4);
2666     
2667     LegalizeSetCCOperands(Tmp1, Tmp2, CC);
2668     
2669     // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
2670     // the LHS is a legal SETCC itself.  In this case, we need to compare
2671     // the result against zero to select between true and false values.
2672     if (Tmp2.Val == 0) {
2673       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
2674       CC = DAG.getCondCode(ISD::SETNE);
2675     }
2676     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, CC);
2677
2678     // Everything is legal, see if we should expand this op or something.
2679     switch (TLI.getOperationAction(ISD::SELECT_CC, Tmp3.getValueType())) {
2680     default: assert(0 && "This action is not supported yet!");
2681     case TargetLowering::Legal: break;
2682     case TargetLowering::Custom:
2683       Tmp1 = TLI.LowerOperation(Result, DAG);
2684       if (Tmp1.Val) Result = Tmp1;
2685       break;
2686     }
2687     break;
2688   }
2689   case ISD::SETCC:
2690     Tmp1 = Node->getOperand(0);
2691     Tmp2 = Node->getOperand(1);
2692     Tmp3 = Node->getOperand(2);
2693     LegalizeSetCCOperands(Tmp1, Tmp2, Tmp3);
2694     
2695     // If we had to Expand the SetCC operands into a SELECT node, then it may 
2696     // not always be possible to return a true LHS & RHS.  In this case, just 
2697     // return the value we legalized, returned in the LHS
2698     if (Tmp2.Val == 0) {
2699       Result = Tmp1;
2700       break;
2701     }
2702
2703     switch (TLI.getOperationAction(ISD::SETCC, Tmp1.getValueType())) {
2704     default: assert(0 && "Cannot handle this action for SETCC yet!");
2705     case TargetLowering::Custom:
2706       isCustom = true;
2707       // FALLTHROUGH.
2708     case TargetLowering::Legal:
2709       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2710       if (isCustom) {
2711         Tmp4 = TLI.LowerOperation(Result, DAG);
2712         if (Tmp4.Val) Result = Tmp4;
2713       }
2714       break;
2715     case TargetLowering::Promote: {
2716       // First step, figure out the appropriate operation to use.
2717       // Allow SETCC to not be supported for all legal data types
2718       // Mostly this targets FP
2719       MVT::ValueType NewInTy = Node->getOperand(0).getValueType();
2720       MVT::ValueType OldVT = NewInTy; OldVT = OldVT;
2721
2722       // Scan for the appropriate larger type to use.
2723       while (1) {
2724         NewInTy = (MVT::ValueType)(NewInTy+1);
2725
2726         assert(MVT::isInteger(NewInTy) == MVT::isInteger(OldVT) &&
2727                "Fell off of the edge of the integer world");
2728         assert(MVT::isFloatingPoint(NewInTy) == MVT::isFloatingPoint(OldVT) &&
2729                "Fell off of the edge of the floating point world");
2730           
2731         // If the target supports SETCC of this type, use it.
2732         if (TLI.isOperationLegal(ISD::SETCC, NewInTy))
2733           break;
2734       }
2735       if (MVT::isInteger(NewInTy))
2736         assert(0 && "Cannot promote Legal Integer SETCC yet");
2737       else {
2738         Tmp1 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp1);
2739         Tmp2 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp2);
2740       }
2741       Tmp1 = LegalizeOp(Tmp1);
2742       Tmp2 = LegalizeOp(Tmp2);
2743       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2744       Result = LegalizeOp(Result);
2745       break;
2746     }
2747     case TargetLowering::Expand:
2748       // Expand a setcc node into a select_cc of the same condition, lhs, and
2749       // rhs that selects between const 1 (true) and const 0 (false).
2750       MVT::ValueType VT = Node->getValueType(0);
2751       Result = DAG.getNode(ISD::SELECT_CC, VT, Tmp1, Tmp2, 
2752                            DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2753                            Tmp3);
2754       break;
2755     }
2756     break;
2757   case ISD::MEMSET:
2758   case ISD::MEMCPY:
2759   case ISD::MEMMOVE: {
2760     Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
2761     Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
2762
2763     if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
2764       switch (getTypeAction(Node->getOperand(2).getValueType())) {
2765       case Expand: assert(0 && "Cannot expand a byte!");
2766       case Legal:
2767         Tmp3 = LegalizeOp(Node->getOperand(2));
2768         break;
2769       case Promote:
2770         Tmp3 = PromoteOp(Node->getOperand(2));
2771         break;
2772       }
2773     } else {
2774       Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
2775     }
2776
2777     SDOperand Tmp4;
2778     switch (getTypeAction(Node->getOperand(3).getValueType())) {
2779     case Expand: {
2780       // Length is too big, just take the lo-part of the length.
2781       SDOperand HiPart;
2782       ExpandOp(Node->getOperand(3), Tmp4, HiPart);
2783       break;
2784     }
2785     case Legal:
2786       Tmp4 = LegalizeOp(Node->getOperand(3));
2787       break;
2788     case Promote:
2789       Tmp4 = PromoteOp(Node->getOperand(3));
2790       break;
2791     }
2792
2793     SDOperand Tmp5;
2794     switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
2795     case Expand: assert(0 && "Cannot expand this yet!");
2796     case Legal:
2797       Tmp5 = LegalizeOp(Node->getOperand(4));
2798       break;
2799     case Promote:
2800       Tmp5 = PromoteOp(Node->getOperand(4));
2801       break;
2802     }
2803
2804     SDOperand Tmp6;
2805     switch (getTypeAction(Node->getOperand(5).getValueType())) {  // bool
2806     case Expand: assert(0 && "Cannot expand this yet!");
2807     case Legal:
2808       Tmp6 = LegalizeOp(Node->getOperand(5));
2809       break;
2810     case Promote:
2811       Tmp6 = PromoteOp(Node->getOperand(5));
2812       break;
2813     }
2814
2815     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
2816     default: assert(0 && "This action not implemented for this operation!");
2817     case TargetLowering::Custom:
2818       isCustom = true;
2819       // FALLTHROUGH
2820     case TargetLowering::Legal: {
2821       SDOperand Ops[] = { Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6 };
2822       Result = DAG.UpdateNodeOperands(Result, Ops, 6);
2823       if (isCustom) {
2824         Tmp1 = TLI.LowerOperation(Result, DAG);
2825         if (Tmp1.Val) Result = Tmp1;
2826       }
2827       break;
2828     }
2829     case TargetLowering::Expand: {
2830       // Otherwise, the target does not support this operation.  Lower the
2831       // operation to an explicit libcall as appropriate.
2832       MVT::ValueType IntPtr = TLI.getPointerTy();
2833       const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
2834       TargetLowering::ArgListTy Args;
2835       TargetLowering::ArgListEntry Entry;
2836
2837       const char *FnName = 0;
2838       if (Node->getOpcode() == ISD::MEMSET) {
2839         Entry.Node = Tmp2; Entry.Ty = IntPtrTy;
2840         Args.push_back(Entry);
2841         // Extend the (previously legalized) ubyte argument to be an int value
2842         // for the call.
2843         if (Tmp3.getValueType() > MVT::i32)
2844           Tmp3 = DAG.getNode(ISD::TRUNCATE, MVT::i32, Tmp3);
2845         else
2846           Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
2847         Entry.Node = Tmp3; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
2848         Args.push_back(Entry);
2849         Entry.Node = Tmp4; Entry.Ty = IntPtrTy; Entry.isSExt = false;
2850         Args.push_back(Entry);
2851
2852         FnName = "memset";
2853       } else if (Node->getOpcode() == ISD::MEMCPY ||
2854                  Node->getOpcode() == ISD::MEMMOVE) {
2855         Entry.Ty = IntPtrTy;
2856         Entry.Node = Tmp2; Args.push_back(Entry);
2857         Entry.Node = Tmp3; Args.push_back(Entry);
2858         Entry.Node = Tmp4; Args.push_back(Entry);
2859         FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
2860       } else {
2861         assert(0 && "Unknown op!");
2862       }
2863
2864       std::pair<SDOperand,SDOperand> CallResult =
2865         TLI.LowerCallTo(Tmp1, Type::VoidTy,
2866                         false, 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       if (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)) ==
3856           TargetLowering::Custom) {
3857         Tmp2 = TLI.LowerOperation(Result, DAG);
3858         if (Tmp2.Val) {
3859           Tmp1 = Tmp2;
3860         }
3861       }
3862       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3863       break;
3864     case Promote:
3865       switch (Node->getOpcode()) {
3866       case ISD::ANY_EXTEND:
3867         Tmp1 = PromoteOp(Node->getOperand(0));
3868         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Tmp1);
3869         break;
3870       case ISD::ZERO_EXTEND:
3871         Result = PromoteOp(Node->getOperand(0));
3872         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
3873         Result = DAG.getZeroExtendInReg(Result,
3874                                         Node->getOperand(0).getValueType());
3875         break;
3876       case ISD::SIGN_EXTEND:
3877         Result = PromoteOp(Node->getOperand(0));
3878         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
3879         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
3880                              Result,
3881                           DAG.getValueType(Node->getOperand(0).getValueType()));
3882         break;
3883       }
3884     }
3885     break;
3886   case ISD::FP_ROUND_INREG:
3887   case ISD::SIGN_EXTEND_INREG: {
3888     Tmp1 = LegalizeOp(Node->getOperand(0));
3889     MVT::ValueType ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3890
3891     // If this operation is not supported, convert it to a shl/shr or load/store
3892     // pair.
3893     switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
3894     default: assert(0 && "This action not supported for this op yet!");
3895     case TargetLowering::Legal:
3896       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
3897       break;
3898     case TargetLowering::Expand:
3899       // If this is an integer extend and shifts are supported, do that.
3900       if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
3901         // NOTE: we could fall back on load/store here too for targets without
3902         // SAR.  However, it is doubtful that any exist.
3903         unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
3904                             MVT::getSizeInBits(ExtraVT);
3905         SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
3906         Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
3907                              Node->getOperand(0), ShiftCst);
3908         Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
3909                              Result, ShiftCst);
3910       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
3911         // The only way we can lower this is to turn it into a TRUNCSTORE,
3912         // EXTLOAD pair, targetting a temporary location (a stack slot).
3913
3914         // NOTE: there is a choice here between constantly creating new stack
3915         // slots and always reusing the same one.  We currently always create
3916         // new ones, as reuse may inhibit scheduling.
3917         Result = EmitStackConvert(Node->getOperand(0), ExtraVT, 
3918                                   Node->getValueType(0));
3919       } else {
3920         assert(0 && "Unknown op");
3921       }
3922       break;
3923     }
3924     break;
3925   }
3926   case ISD::TRAMPOLINE: {
3927     SDOperand Ops[6];
3928     for (unsigned i = 0; i != 6; ++i)
3929       Ops[i] = LegalizeOp(Node->getOperand(i));
3930     Result = DAG.UpdateNodeOperands(Result, Ops, 6);
3931     // The only option for this node is to custom lower it.
3932     Result = TLI.LowerOperation(Result, DAG);
3933     assert(Result.Val && "Should always custom lower!");
3934
3935     // Since trampoline produces two values, make sure to remember that we
3936     // legalized both of them.
3937     Tmp1 = LegalizeOp(Result.getValue(1));
3938     Result = LegalizeOp(Result);
3939     AddLegalizedOperand(SDOperand(Node, 0), Result);
3940     AddLegalizedOperand(SDOperand(Node, 1), Tmp1);
3941     return Op.ResNo ? Tmp1 : Result;
3942   }
3943    case ISD::FLT_ROUNDS_: {
3944     MVT::ValueType VT = Node->getValueType(0);
3945     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
3946     default: assert(0 && "This action not supported for this op yet!");
3947     case TargetLowering::Custom:
3948       Result = TLI.LowerOperation(Op, DAG);
3949       if (Result.Val) break;
3950       // Fall Thru
3951     case TargetLowering::Legal:
3952       // If this operation is not supported, lower it to constant 1
3953       Result = DAG.getConstant(1, VT);
3954       break;
3955     }
3956   }
3957   case ISD::TRAP: {
3958     MVT::ValueType VT = Node->getValueType(0);
3959     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
3960     default: assert(0 && "This action not supported for this op yet!");
3961     case TargetLowering::Legal:
3962       Tmp1 = LegalizeOp(Node->getOperand(0));
3963       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3964       break;
3965     case TargetLowering::Custom:
3966       Result = TLI.LowerOperation(Op, DAG);
3967       if (Result.Val) break;
3968       // Fall Thru
3969     case TargetLowering::Expand:
3970       // If this operation is not supported, lower it to 'abort()' call
3971       Tmp1 = LegalizeOp(Node->getOperand(0));
3972       TargetLowering::ArgListTy Args;
3973       std::pair<SDOperand,SDOperand> CallResult =
3974         TLI.LowerCallTo(Tmp1, Type::VoidTy,
3975                         false, false, false, CallingConv::C, false,
3976                         DAG.getExternalSymbol("abort", TLI.getPointerTy()),
3977                         Args, DAG);
3978       Result = CallResult.second;
3979       break;
3980     }
3981     break;
3982   }
3983   }
3984   
3985   assert(Result.getValueType() == Op.getValueType() &&
3986          "Bad legalization!");
3987   
3988   // Make sure that the generated code is itself legal.
3989   if (Result != Op)
3990     Result = LegalizeOp(Result);
3991
3992   // Note that LegalizeOp may be reentered even from single-use nodes, which
3993   // means that we always must cache transformed nodes.
3994   AddLegalizedOperand(Op, Result);
3995   return Result;
3996 }
3997
3998 /// PromoteOp - Given an operation that produces a value in an invalid type,
3999 /// promote it to compute the value into a larger type.  The produced value will
4000 /// have the correct bits for the low portion of the register, but no guarantee
4001 /// is made about the top bits: it may be zero, sign-extended, or garbage.
4002 SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
4003   MVT::ValueType VT = Op.getValueType();
4004   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
4005   assert(getTypeAction(VT) == Promote &&
4006          "Caller should expand or legalize operands that are not promotable!");
4007   assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
4008          "Cannot promote to smaller type!");
4009
4010   SDOperand Tmp1, Tmp2, Tmp3;
4011   SDOperand Result;
4012   SDNode *Node = Op.Val;
4013
4014   DenseMap<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
4015   if (I != PromotedNodes.end()) return I->second;
4016
4017   switch (Node->getOpcode()) {
4018   case ISD::CopyFromReg:
4019     assert(0 && "CopyFromReg must be legal!");
4020   default:
4021 #ifndef NDEBUG
4022     cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
4023 #endif
4024     assert(0 && "Do not know how to promote this operator!");
4025     abort();
4026   case ISD::UNDEF:
4027     Result = DAG.getNode(ISD::UNDEF, NVT);
4028     break;
4029   case ISD::Constant:
4030     if (VT != MVT::i1)
4031       Result = DAG.getNode(ISD::SIGN_EXTEND, NVT, Op);
4032     else
4033       Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
4034     assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
4035     break;
4036   case ISD::ConstantFP:
4037     Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
4038     assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
4039     break;
4040
4041   case ISD::SETCC:
4042     assert(isTypeLegal(TLI.getSetCCResultTy()) && "SetCC type is not legal??");
4043     Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),Node->getOperand(0),
4044                          Node->getOperand(1), Node->getOperand(2));
4045     break;
4046     
4047   case ISD::TRUNCATE:
4048     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4049     case Legal:
4050       Result = LegalizeOp(Node->getOperand(0));
4051       assert(Result.getValueType() >= NVT &&
4052              "This truncation doesn't make sense!");
4053       if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
4054         Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
4055       break;
4056     case Promote:
4057       // The truncation is not required, because we don't guarantee anything
4058       // about high bits anyway.
4059       Result = PromoteOp(Node->getOperand(0));
4060       break;
4061     case Expand:
4062       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
4063       // Truncate the low part of the expanded value to the result type
4064       Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
4065     }
4066     break;
4067   case ISD::SIGN_EXTEND:
4068   case ISD::ZERO_EXTEND:
4069   case ISD::ANY_EXTEND:
4070     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4071     case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
4072     case Legal:
4073       // Input is legal?  Just do extend all the way to the larger type.
4074       Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
4075       break;
4076     case Promote:
4077       // Promote the reg if it's smaller.
4078       Result = PromoteOp(Node->getOperand(0));
4079       // The high bits are not guaranteed to be anything.  Insert an extend.
4080       if (Node->getOpcode() == ISD::SIGN_EXTEND)
4081         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
4082                          DAG.getValueType(Node->getOperand(0).getValueType()));
4083       else if (Node->getOpcode() == ISD::ZERO_EXTEND)
4084         Result = DAG.getZeroExtendInReg(Result,
4085                                         Node->getOperand(0).getValueType());
4086       break;
4087     }
4088     break;
4089   case ISD::BIT_CONVERT:
4090     Result = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
4091                               Node->getValueType(0));
4092     Result = PromoteOp(Result);
4093     break;
4094     
4095   case ISD::FP_EXTEND:
4096     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
4097   case ISD::FP_ROUND:
4098     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4099     case Expand: assert(0 && "BUG: Cannot expand FP regs!");
4100     case Promote:  assert(0 && "Unreachable with 2 FP types!");
4101     case Legal:
4102       if (Node->getConstantOperandVal(1) == 0) {
4103         // Input is legal?  Do an FP_ROUND_INREG.
4104         Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Node->getOperand(0),
4105                              DAG.getValueType(VT));
4106       } else {
4107         // Just remove the truncate, it isn't affecting the value.
4108         Result = DAG.getNode(ISD::FP_ROUND, NVT, Node->getOperand(0), 
4109                              Node->getOperand(1));
4110       }
4111       break;
4112     }
4113     break;
4114   case ISD::SINT_TO_FP:
4115   case ISD::UINT_TO_FP:
4116     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4117     case Legal:
4118       // No extra round required here.
4119       Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
4120       break;
4121
4122     case Promote:
4123       Result = PromoteOp(Node->getOperand(0));
4124       if (Node->getOpcode() == ISD::SINT_TO_FP)
4125         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
4126                              Result,
4127                          DAG.getValueType(Node->getOperand(0).getValueType()));
4128       else
4129         Result = DAG.getZeroExtendInReg(Result,
4130                                         Node->getOperand(0).getValueType());
4131       // No extra round required here.
4132       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
4133       break;
4134     case Expand:
4135       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
4136                              Node->getOperand(0));
4137       // Round if we cannot tolerate excess precision.
4138       if (NoExcessFPPrecision)
4139         Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4140                              DAG.getValueType(VT));
4141       break;
4142     }
4143     break;
4144
4145   case ISD::SIGN_EXTEND_INREG:
4146     Result = PromoteOp(Node->getOperand(0));
4147     Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result, 
4148                          Node->getOperand(1));
4149     break;
4150   case ISD::FP_TO_SINT:
4151   case ISD::FP_TO_UINT:
4152     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4153     case Legal:
4154     case Expand:
4155       Tmp1 = Node->getOperand(0);
4156       break;
4157     case Promote:
4158       // The input result is prerounded, so we don't have to do anything
4159       // special.
4160       Tmp1 = PromoteOp(Node->getOperand(0));
4161       break;
4162     }
4163     // If we're promoting a UINT to a larger size, check to see if the new node
4164     // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
4165     // we can use that instead.  This allows us to generate better code for
4166     // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
4167     // legal, such as PowerPC.
4168     if (Node->getOpcode() == ISD::FP_TO_UINT && 
4169         !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
4170         (TLI.isOperationLegal(ISD::FP_TO_SINT, NVT) ||
4171          TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
4172       Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
4173     } else {
4174       Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4175     }
4176     break;
4177
4178   case ISD::FABS:
4179   case ISD::FNEG:
4180     Tmp1 = PromoteOp(Node->getOperand(0));
4181     assert(Tmp1.getValueType() == NVT);
4182     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4183     // NOTE: we do not have to do any extra rounding here for
4184     // NoExcessFPPrecision, because we know the input will have the appropriate
4185     // precision, and these operations don't modify precision at all.
4186     break;
4187
4188   case ISD::FSQRT:
4189   case ISD::FSIN:
4190   case ISD::FCOS:
4191     Tmp1 = PromoteOp(Node->getOperand(0));
4192     assert(Tmp1.getValueType() == NVT);
4193     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4194     if (NoExcessFPPrecision)
4195       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4196                            DAG.getValueType(VT));
4197     break;
4198
4199   case ISD::FPOWI: {
4200     // Promote f32 powi to f64 powi.  Note that this could insert a libcall
4201     // directly as well, which may be better.
4202     Tmp1 = PromoteOp(Node->getOperand(0));
4203     assert(Tmp1.getValueType() == NVT);
4204     Result = DAG.getNode(ISD::FPOWI, NVT, Tmp1, Node->getOperand(1));
4205     if (NoExcessFPPrecision)
4206       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4207                            DAG.getValueType(VT));
4208     break;
4209   }
4210     
4211   case ISD::AND:
4212   case ISD::OR:
4213   case ISD::XOR:
4214   case ISD::ADD:
4215   case ISD::SUB:
4216   case ISD::MUL:
4217     // The input may have strange things in the top bits of the registers, but
4218     // these operations don't care.  They may have weird bits going out, but
4219     // that too is okay if they are integer operations.
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     break;
4225   case ISD::FADD:
4226   case ISD::FSUB:
4227   case ISD::FMUL:
4228     Tmp1 = PromoteOp(Node->getOperand(0));
4229     Tmp2 = PromoteOp(Node->getOperand(1));
4230     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
4231     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4232     
4233     // Floating point operations will give excess precision that we may not be
4234     // able to tolerate.  If we DO allow excess precision, just leave it,
4235     // otherwise excise it.
4236     // FIXME: Why would we need to round FP ops more than integer ones?
4237     //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
4238     if (NoExcessFPPrecision)
4239       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4240                            DAG.getValueType(VT));
4241     break;
4242
4243   case ISD::SDIV:
4244   case ISD::SREM:
4245     // These operators require that their input be sign extended.
4246     Tmp1 = PromoteOp(Node->getOperand(0));
4247     Tmp2 = PromoteOp(Node->getOperand(1));
4248     if (MVT::isInteger(NVT)) {
4249       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
4250                          DAG.getValueType(VT));
4251       Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
4252                          DAG.getValueType(VT));
4253     }
4254     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4255
4256     // Perform FP_ROUND: this is probably overly pessimistic.
4257     if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
4258       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4259                            DAG.getValueType(VT));
4260     break;
4261   case ISD::FDIV:
4262   case ISD::FREM:
4263   case ISD::FCOPYSIGN:
4264     // These operators require that their input be fp extended.
4265     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4266     case Expand: assert(0 && "not implemented");
4267     case Legal:   Tmp1 = LegalizeOp(Node->getOperand(0)); break;
4268     case Promote: Tmp1 = PromoteOp(Node->getOperand(0));  break;
4269     }
4270     switch (getTypeAction(Node->getOperand(1).getValueType())) {
4271     case Expand: assert(0 && "not implemented");
4272     case Legal:   Tmp2 = LegalizeOp(Node->getOperand(1)); break;
4273     case Promote: Tmp2 = PromoteOp(Node->getOperand(1)); break;
4274     }
4275     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4276     
4277     // Perform FP_ROUND: this is probably overly pessimistic.
4278     if (NoExcessFPPrecision && Node->getOpcode() != ISD::FCOPYSIGN)
4279       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4280                            DAG.getValueType(VT));
4281     break;
4282
4283   case ISD::UDIV:
4284   case ISD::UREM:
4285     // These operators require that their input be zero extended.
4286     Tmp1 = PromoteOp(Node->getOperand(0));
4287     Tmp2 = PromoteOp(Node->getOperand(1));
4288     assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
4289     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
4290     Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
4291     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4292     break;
4293
4294   case ISD::SHL:
4295     Tmp1 = PromoteOp(Node->getOperand(0));
4296     Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Node->getOperand(1));
4297     break;
4298   case ISD::SRA:
4299     // The input value must be properly sign extended.
4300     Tmp1 = PromoteOp(Node->getOperand(0));
4301     Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
4302                        DAG.getValueType(VT));
4303     Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Node->getOperand(1));
4304     break;
4305   case ISD::SRL:
4306     // The input value must be properly zero extended.
4307     Tmp1 = PromoteOp(Node->getOperand(0));
4308     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
4309     Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Node->getOperand(1));
4310     break;
4311
4312   case ISD::VAARG:
4313     Tmp1 = Node->getOperand(0);   // Get the chain.
4314     Tmp2 = Node->getOperand(1);   // Get the pointer.
4315     if (TLI.getOperationAction(ISD::VAARG, VT) == TargetLowering::Custom) {
4316       Tmp3 = DAG.getVAArg(VT, Tmp1, Tmp2, Node->getOperand(2));
4317       Result = TLI.CustomPromoteOperation(Tmp3, DAG);
4318     } else {
4319       const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
4320       SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2, V, 0);
4321       // Increment the pointer, VAList, to the next vaarg
4322       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList, 
4323                          DAG.getConstant(MVT::getSizeInBits(VT)/8, 
4324                                          TLI.getPointerTy()));
4325       // Store the incremented VAList to the legalized pointer
4326       Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Tmp2, V, 0);
4327       // Load the actual argument out of the pointer VAList
4328       Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp3, VAList, NULL, 0, VT);
4329     }
4330     // Remember that we legalized the chain.
4331     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4332     break;
4333
4334   case ISD::LOAD: {
4335     LoadSDNode *LD = cast<LoadSDNode>(Node);
4336     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(Node)
4337       ? ISD::EXTLOAD : LD->getExtensionType();
4338     Result = DAG.getExtLoad(ExtType, NVT,
4339                             LD->getChain(), LD->getBasePtr(),
4340                             LD->getSrcValue(), LD->getSrcValueOffset(),
4341                             LD->getMemoryVT(),
4342                             LD->isVolatile(),
4343                             LD->getAlignment());
4344     // Remember that we legalized the chain.
4345     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4346     break;
4347   }
4348   case ISD::SELECT:
4349     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
4350     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
4351     Result = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), Tmp2, Tmp3);
4352     break;
4353   case ISD::SELECT_CC:
4354     Tmp2 = PromoteOp(Node->getOperand(2));   // True
4355     Tmp3 = PromoteOp(Node->getOperand(3));   // False
4356     Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4357                          Node->getOperand(1), Tmp2, Tmp3, Node->getOperand(4));
4358     break;
4359   case ISD::BSWAP:
4360     Tmp1 = Node->getOperand(0);
4361     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
4362     Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
4363     Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
4364                          DAG.getConstant(MVT::getSizeInBits(NVT) -
4365                                          MVT::getSizeInBits(VT),
4366                                          TLI.getShiftAmountTy()));
4367     break;
4368   case ISD::CTPOP:
4369   case ISD::CTTZ:
4370   case ISD::CTLZ:
4371     // Zero extend the argument
4372     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
4373     // Perform the larger operation, then subtract if needed.
4374     Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4375     switch(Node->getOpcode()) {
4376     case ISD::CTPOP:
4377       Result = Tmp1;
4378       break;
4379     case ISD::CTTZ:
4380       // if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
4381       Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
4382                           DAG.getConstant(MVT::getSizeInBits(NVT), NVT),
4383                           ISD::SETEQ);
4384       Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
4385                            DAG.getConstant(MVT::getSizeInBits(VT), NVT), Tmp1);
4386       break;
4387     case ISD::CTLZ:
4388       //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4389       Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
4390                            DAG.getConstant(MVT::getSizeInBits(NVT) -
4391                                            MVT::getSizeInBits(VT), NVT));
4392       break;
4393     }
4394     break;
4395   case ISD::EXTRACT_SUBVECTOR:
4396     Result = PromoteOp(ExpandEXTRACT_SUBVECTOR(Op));
4397     break;
4398   case ISD::EXTRACT_VECTOR_ELT:
4399     Result = PromoteOp(ExpandEXTRACT_VECTOR_ELT(Op));
4400     break;
4401   }
4402
4403   assert(Result.Val && "Didn't set a result!");
4404
4405   // Make sure the result is itself legal.
4406   Result = LegalizeOp(Result);
4407   
4408   // Remember that we promoted this!
4409   AddPromotedOperand(Op, Result);
4410   return Result;
4411 }
4412
4413 /// ExpandEXTRACT_VECTOR_ELT - Expand an EXTRACT_VECTOR_ELT operation into
4414 /// a legal EXTRACT_VECTOR_ELT operation, scalar code, or memory traffic,
4415 /// based on the vector type. The return type of this matches the element type
4416 /// of the vector, which may not be legal for the target.
4417 SDOperand SelectionDAGLegalize::ExpandEXTRACT_VECTOR_ELT(SDOperand Op) {
4418   // We know that operand #0 is the Vec vector.  If the index is a constant
4419   // or if the invec is a supported hardware type, we can use it.  Otherwise,
4420   // lower to a store then an indexed load.
4421   SDOperand Vec = Op.getOperand(0);
4422   SDOperand Idx = Op.getOperand(1);
4423   
4424   MVT::ValueType TVT = Vec.getValueType();
4425   unsigned NumElems = MVT::getVectorNumElements(TVT);
4426   
4427   switch (TLI.getOperationAction(ISD::EXTRACT_VECTOR_ELT, TVT)) {
4428   default: assert(0 && "This action is not supported yet!");
4429   case TargetLowering::Custom: {
4430     Vec = LegalizeOp(Vec);
4431     Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
4432     SDOperand Tmp3 = TLI.LowerOperation(Op, DAG);
4433     if (Tmp3.Val)
4434       return Tmp3;
4435     break;
4436   }
4437   case TargetLowering::Legal:
4438     if (isTypeLegal(TVT)) {
4439       Vec = LegalizeOp(Vec);
4440       Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
4441       return Op;
4442     }
4443     break;
4444   case TargetLowering::Expand:
4445     break;
4446   }
4447
4448   if (NumElems == 1) {
4449     // This must be an access of the only element.  Return it.
4450     Op = ScalarizeVectorOp(Vec);
4451   } else if (!TLI.isTypeLegal(TVT) && isa<ConstantSDNode>(Idx)) {
4452     unsigned NumLoElts =  1 << Log2_32(NumElems-1);
4453     ConstantSDNode *CIdx = cast<ConstantSDNode>(Idx);
4454     SDOperand Lo, Hi;
4455     SplitVectorOp(Vec, Lo, Hi);
4456     if (CIdx->getValue() < NumLoElts) {
4457       Vec = Lo;
4458     } else {
4459       Vec = Hi;
4460       Idx = DAG.getConstant(CIdx->getValue() - NumLoElts,
4461                             Idx.getValueType());
4462     }
4463   
4464     // It's now an extract from the appropriate high or low part.  Recurse.
4465     Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
4466     Op = ExpandEXTRACT_VECTOR_ELT(Op);
4467   } else {
4468     // Store the value to a temporary stack slot, then LOAD the scalar
4469     // element back out.
4470     SDOperand StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
4471     SDOperand Ch = DAG.getStore(DAG.getEntryNode(), Vec, StackPtr, NULL, 0);
4472
4473     // Add the offset to the index.
4474     unsigned EltSize = MVT::getSizeInBits(Op.getValueType())/8;
4475     Idx = DAG.getNode(ISD::MUL, Idx.getValueType(), Idx,
4476                       DAG.getConstant(EltSize, Idx.getValueType()));
4477
4478     if (MVT::getSizeInBits(Idx.getValueType()) >
4479         MVT::getSizeInBits(TLI.getPointerTy()))
4480       Idx = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), Idx);
4481     else
4482       Idx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), Idx);
4483
4484     StackPtr = DAG.getNode(ISD::ADD, Idx.getValueType(), Idx, StackPtr);
4485
4486     Op = DAG.getLoad(Op.getValueType(), Ch, StackPtr, NULL, 0);
4487   }
4488   return Op;
4489 }
4490
4491 /// ExpandEXTRACT_SUBVECTOR - Expand a EXTRACT_SUBVECTOR operation.  For now
4492 /// we assume the operation can be split if it is not already legal.
4493 SDOperand SelectionDAGLegalize::ExpandEXTRACT_SUBVECTOR(SDOperand Op) {
4494   // We know that operand #0 is the Vec vector.  For now we assume the index
4495   // is a constant and that the extracted result is a supported hardware type.
4496   SDOperand Vec = Op.getOperand(0);
4497   SDOperand Idx = LegalizeOp(Op.getOperand(1));
4498   
4499   unsigned NumElems = MVT::getVectorNumElements(Vec.getValueType());
4500   
4501   if (NumElems == MVT::getVectorNumElements(Op.getValueType())) {
4502     // This must be an access of the desired vector length.  Return it.
4503     return Vec;
4504   }
4505
4506   ConstantSDNode *CIdx = cast<ConstantSDNode>(Idx);
4507   SDOperand Lo, Hi;
4508   SplitVectorOp(Vec, Lo, Hi);
4509   if (CIdx->getValue() < NumElems/2) {
4510     Vec = Lo;
4511   } else {
4512     Vec = Hi;
4513     Idx = DAG.getConstant(CIdx->getValue() - NumElems/2, Idx.getValueType());
4514   }
4515   
4516   // It's now an extract from the appropriate high or low part.  Recurse.
4517   Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
4518   return ExpandEXTRACT_SUBVECTOR(Op);
4519 }
4520
4521 /// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
4522 /// with condition CC on the current target.  This usually involves legalizing
4523 /// or promoting the arguments.  In the case where LHS and RHS must be expanded,
4524 /// there may be no choice but to create a new SetCC node to represent the
4525 /// legalized value of setcc lhs, rhs.  In this case, the value is returned in
4526 /// LHS, and the SDOperand returned in RHS has a nil SDNode value.
4527 void SelectionDAGLegalize::LegalizeSetCCOperands(SDOperand &LHS,
4528                                                  SDOperand &RHS,
4529                                                  SDOperand &CC) {
4530   SDOperand Tmp1, Tmp2, Tmp3, Result;    
4531   
4532   switch (getTypeAction(LHS.getValueType())) {
4533   case Legal:
4534     Tmp1 = LegalizeOp(LHS);   // LHS
4535     Tmp2 = LegalizeOp(RHS);   // RHS
4536     break;
4537   case Promote:
4538     Tmp1 = PromoteOp(LHS);   // LHS
4539     Tmp2 = PromoteOp(RHS);   // RHS
4540
4541     // If this is an FP compare, the operands have already been extended.
4542     if (MVT::isInteger(LHS.getValueType())) {
4543       MVT::ValueType VT = LHS.getValueType();
4544       MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
4545
4546       // Otherwise, we have to insert explicit sign or zero extends.  Note
4547       // that we could insert sign extends for ALL conditions, but zero extend
4548       // is cheaper on many machines (an AND instead of two shifts), so prefer
4549       // it.
4550       switch (cast<CondCodeSDNode>(CC)->get()) {
4551       default: assert(0 && "Unknown integer comparison!");
4552       case ISD::SETEQ:
4553       case ISD::SETNE:
4554       case ISD::SETUGE:
4555       case ISD::SETUGT:
4556       case ISD::SETULE:
4557       case ISD::SETULT:
4558         // ALL of these operations will work if we either sign or zero extend
4559         // the operands (including the unsigned comparisons!).  Zero extend is
4560         // usually a simpler/cheaper operation, so prefer it.
4561         Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
4562         Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
4563         break;
4564       case ISD::SETGE:
4565       case ISD::SETGT:
4566       case ISD::SETLT:
4567       case ISD::SETLE:
4568         Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
4569                            DAG.getValueType(VT));
4570         Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
4571                            DAG.getValueType(VT));
4572         break;
4573       }
4574     }
4575     break;
4576   case Expand: {
4577     MVT::ValueType VT = LHS.getValueType();
4578     if (VT == MVT::f32 || VT == MVT::f64) {
4579       // Expand into one or more soft-fp libcall(s).
4580       RTLIB::Libcall LC1, LC2 = RTLIB::UNKNOWN_LIBCALL;
4581       switch (cast<CondCodeSDNode>(CC)->get()) {
4582       case ISD::SETEQ:
4583       case ISD::SETOEQ:
4584         LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
4585         break;
4586       case ISD::SETNE:
4587       case ISD::SETUNE:
4588         LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : RTLIB::UNE_F64;
4589         break;
4590       case ISD::SETGE:
4591       case ISD::SETOGE:
4592         LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : RTLIB::OGE_F64;
4593         break;
4594       case ISD::SETLT:
4595       case ISD::SETOLT:
4596         LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
4597         break;
4598       case ISD::SETLE:
4599       case ISD::SETOLE:
4600         LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : RTLIB::OLE_F64;
4601         break;
4602       case ISD::SETGT:
4603       case ISD::SETOGT:
4604         LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : RTLIB::OGT_F64;
4605         break;
4606       case ISD::SETUO:
4607         LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : RTLIB::UO_F64;
4608         break;
4609       case ISD::SETO:
4610         LC1 = (VT == MVT::f32) ? RTLIB::O_F32 : RTLIB::O_F64;
4611         break;
4612       default:
4613         LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : RTLIB::UO_F64;
4614         switch (cast<CondCodeSDNode>(CC)->get()) {
4615         case ISD::SETONE:
4616           // SETONE = SETOLT | SETOGT
4617           LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
4618           // Fallthrough
4619         case ISD::SETUGT:
4620           LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 : RTLIB::OGT_F64;
4621           break;
4622         case ISD::SETUGE:
4623           LC2 = (VT == MVT::f32) ? RTLIB::OGE_F32 : RTLIB::OGE_F64;
4624           break;
4625         case ISD::SETULT:
4626           LC2 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
4627           break;
4628         case ISD::SETULE:
4629           LC2 = (VT == MVT::f32) ? RTLIB::OLE_F32 : RTLIB::OLE_F64;
4630           break;
4631         case ISD::SETUEQ:
4632           LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
4633           break;
4634         default: assert(0 && "Unsupported FP setcc!");
4635         }
4636       }
4637       
4638       SDOperand Dummy;
4639       Tmp1 = ExpandLibCall(TLI.getLibcallName(LC1),
4640                            DAG.getNode(ISD::MERGE_VALUES, VT, LHS, RHS).Val, 
4641                            false /*sign irrelevant*/, Dummy);
4642       Tmp2 = DAG.getConstant(0, MVT::i32);
4643       CC = DAG.getCondCode(TLI.getCmpLibcallCC(LC1));
4644       if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
4645         Tmp1 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), Tmp1, Tmp2, CC);
4646         LHS = ExpandLibCall(TLI.getLibcallName(LC2),
4647                             DAG.getNode(ISD::MERGE_VALUES, VT, LHS, RHS).Val, 
4648                             false /*sign irrelevant*/, Dummy);
4649         Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), LHS, Tmp2,
4650                            DAG.getCondCode(TLI.getCmpLibcallCC(LC2)));
4651         Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
4652         Tmp2 = SDOperand();
4653       }
4654       LHS = Tmp1;
4655       RHS = Tmp2;
4656       return;
4657     }
4658
4659     SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
4660     ExpandOp(LHS, LHSLo, LHSHi);
4661     ExpandOp(RHS, RHSLo, RHSHi);
4662     ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
4663
4664     if (VT==MVT::ppcf128) {
4665       // FIXME:  This generated code sucks.  We want to generate
4666       //         FCMP crN, hi1, hi2
4667       //         BNE crN, L:
4668       //         FCMP crN, lo1, lo2
4669       // The following can be improved, but not that much.
4670       Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
4671       Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, CCCode);
4672       Tmp3 = DAG.getNode(ISD::AND, Tmp1.getValueType(), Tmp1, Tmp2);
4673       Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETNE);
4674       Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, CCCode);
4675       Tmp1 = DAG.getNode(ISD::AND, Tmp1.getValueType(), Tmp1, Tmp2);
4676       Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp3);
4677       Tmp2 = SDOperand();
4678       break;
4679     }
4680
4681     switch (CCCode) {
4682     case ISD::SETEQ:
4683     case ISD::SETNE:
4684       if (RHSLo == RHSHi)
4685         if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
4686           if (RHSCST->isAllOnesValue()) {
4687             // Comparison to -1.
4688             Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
4689             Tmp2 = RHSLo;
4690             break;
4691           }
4692
4693       Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
4694       Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
4695       Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
4696       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
4697       break;
4698     default:
4699       // If this is a comparison of the sign bit, just look at the top part.
4700       // X > -1,  x < 0
4701       if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(RHS))
4702         if ((cast<CondCodeSDNode>(CC)->get() == ISD::SETLT && 
4703              CST->getValue() == 0) ||             // X < 0
4704             (cast<CondCodeSDNode>(CC)->get() == ISD::SETGT &&
4705              CST->isAllOnesValue())) {            // X > -1
4706           Tmp1 = LHSHi;
4707           Tmp2 = RHSHi;
4708           break;
4709         }
4710
4711       // FIXME: This generated code sucks.
4712       ISD::CondCode LowCC;
4713       switch (CCCode) {
4714       default: assert(0 && "Unknown integer setcc!");
4715       case ISD::SETLT:
4716       case ISD::SETULT: LowCC = ISD::SETULT; break;
4717       case ISD::SETGT:
4718       case ISD::SETUGT: LowCC = ISD::SETUGT; break;
4719       case ISD::SETLE:
4720       case ISD::SETULE: LowCC = ISD::SETULE; break;
4721       case ISD::SETGE:
4722       case ISD::SETUGE: LowCC = ISD::SETUGE; break;
4723       }
4724
4725       // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
4726       // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
4727       // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
4728
4729       // NOTE: on targets without efficient SELECT of bools, we can always use
4730       // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
4731       TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, false, true, NULL);
4732       Tmp1 = TLI.SimplifySetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC,
4733                                false, DagCombineInfo);
4734       if (!Tmp1.Val)
4735         Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC);
4736       Tmp2 = TLI.SimplifySetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi,
4737                                CCCode, false, DagCombineInfo);
4738       if (!Tmp2.Val)
4739         Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), LHSHi, RHSHi,CC);
4740       
4741       ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.Val);
4742       ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.Val);
4743       if ((Tmp1C && Tmp1C->getValue() == 0) ||
4744           (Tmp2C && Tmp2C->getValue() == 0 &&
4745            (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
4746             CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
4747           (Tmp2C && Tmp2C->getValue() == 1 &&
4748            (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
4749             CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
4750         // low part is known false, returns high part.
4751         // For LE / GE, if high part is known false, ignore the low part.
4752         // For LT / GT, if high part is known true, ignore the low part.
4753         Tmp1 = Tmp2;
4754         Tmp2 = SDOperand();
4755       } else {
4756         Result = TLI.SimplifySetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi,
4757                                    ISD::SETEQ, false, DagCombineInfo);
4758         if (!Result.Val)
4759           Result=DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
4760         Result = LegalizeOp(DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
4761                                         Result, Tmp1, Tmp2));
4762         Tmp1 = Result;
4763         Tmp2 = SDOperand();
4764       }
4765     }
4766   }
4767   }
4768   LHS = Tmp1;
4769   RHS = Tmp2;
4770 }
4771
4772 /// EmitStackConvert - Emit a store/load combination to the stack.  This stores
4773 /// SrcOp to a stack slot of type SlotVT, truncating it if needed.  It then does
4774 /// a load from the stack slot to DestVT, extending it if needed.
4775 /// The resultant code need not be legal.
4776 SDOperand SelectionDAGLegalize::EmitStackConvert(SDOperand SrcOp,
4777                                                  MVT::ValueType SlotVT, 
4778                                                  MVT::ValueType DestVT) {
4779   // Create the stack frame object.
4780   SDOperand FIPtr = DAG.CreateStackTemporary(SlotVT);
4781
4782   FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
4783   int SPFI = StackPtrFI->getIndex();
4784
4785   unsigned SrcSize = MVT::getSizeInBits(SrcOp.getValueType());
4786   unsigned SlotSize = MVT::getSizeInBits(SlotVT);
4787   unsigned DestSize = MVT::getSizeInBits(DestVT);
4788   
4789   // Emit a store to the stack slot.  Use a truncstore if the input value is
4790   // later than DestVT.
4791   SDOperand Store;
4792   if (SrcSize > SlotSize)
4793     Store = DAG.getTruncStore(DAG.getEntryNode(), SrcOp, FIPtr,
4794                               PseudoSourceValue::getFixedStack(),
4795                               SPFI, SlotVT);
4796   else {
4797     assert(SrcSize == SlotSize && "Invalid store");
4798     Store = DAG.getStore(DAG.getEntryNode(), SrcOp, FIPtr,
4799                          PseudoSourceValue::getFixedStack(),
4800                          SPFI, SlotVT);
4801   }
4802   
4803   // Result is a load from the stack slot.
4804   if (SlotSize == DestSize)
4805     return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
4806   
4807   assert(SlotSize < DestSize && "Unknown extension!");
4808   return DAG.getExtLoad(ISD::EXTLOAD, DestVT, Store, FIPtr, NULL, 0, SlotVT);
4809 }
4810
4811 SDOperand SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
4812   // Create a vector sized/aligned stack slot, store the value to element #0,
4813   // then load the whole vector back out.
4814   SDOperand StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
4815
4816   FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
4817   int SPFI = StackPtrFI->getIndex();
4818
4819   SDOperand Ch = DAG.getStore(DAG.getEntryNode(), Node->getOperand(0), StackPtr,
4820                               PseudoSourceValue::getFixedStack(), SPFI);
4821   return DAG.getLoad(Node->getValueType(0), Ch, StackPtr,
4822                      PseudoSourceValue::getFixedStack(), SPFI);
4823 }
4824
4825
4826 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
4827 /// support the operation, but do support the resultant vector type.
4828 SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
4829   
4830   // If the only non-undef value is the low element, turn this into a 
4831   // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
4832   unsigned NumElems = Node->getNumOperands();
4833   bool isOnlyLowElement = true;
4834   SDOperand SplatValue = Node->getOperand(0);
4835   std::map<SDOperand, std::vector<unsigned> > Values;
4836   Values[SplatValue].push_back(0);
4837   bool isConstant = true;
4838   if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
4839       SplatValue.getOpcode() != ISD::UNDEF)
4840     isConstant = false;
4841   
4842   for (unsigned i = 1; i < NumElems; ++i) {
4843     SDOperand V = Node->getOperand(i);
4844     Values[V].push_back(i);
4845     if (V.getOpcode() != ISD::UNDEF)
4846       isOnlyLowElement = false;
4847     if (SplatValue != V)
4848       SplatValue = SDOperand(0,0);
4849
4850     // If this isn't a constant element or an undef, we can't use a constant
4851     // pool load.
4852     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
4853         V.getOpcode() != ISD::UNDEF)
4854       isConstant = false;
4855   }
4856   
4857   if (isOnlyLowElement) {
4858     // If the low element is an undef too, then this whole things is an undef.
4859     if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
4860       return DAG.getNode(ISD::UNDEF, Node->getValueType(0));
4861     // Otherwise, turn this into a scalar_to_vector node.
4862     return DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
4863                        Node->getOperand(0));
4864   }
4865   
4866   // If all elements are constants, create a load from the constant pool.
4867   if (isConstant) {
4868     MVT::ValueType VT = Node->getValueType(0);
4869     const Type *OpNTy = 
4870       MVT::getTypeForValueType(Node->getOperand(0).getValueType());
4871     std::vector<Constant*> CV;
4872     for (unsigned i = 0, e = NumElems; i != e; ++i) {
4873       if (ConstantFPSDNode *V = 
4874           dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
4875         CV.push_back(ConstantFP::get(OpNTy, V->getValueAPF()));
4876       } else if (ConstantSDNode *V = 
4877                  dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
4878         CV.push_back(ConstantInt::get(OpNTy, V->getValue()));
4879       } else {
4880         assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
4881         CV.push_back(UndefValue::get(OpNTy));
4882       }
4883     }
4884     Constant *CP = ConstantVector::get(CV);
4885     SDOperand CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
4886     return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4887                        PseudoSourceValue::getConstantPool(), 0);
4888   }
4889   
4890   if (SplatValue.Val) {   // Splat of one value?
4891     // Build the shuffle constant vector: <0, 0, 0, 0>
4892     MVT::ValueType MaskVT = 
4893       MVT::getIntVectorWithNumElements(NumElems);
4894     SDOperand Zero = DAG.getConstant(0, MVT::getVectorElementType(MaskVT));
4895     std::vector<SDOperand> ZeroVec(NumElems, Zero);
4896     SDOperand SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4897                                       &ZeroVec[0], ZeroVec.size());
4898
4899     // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
4900     if (isShuffleLegal(Node->getValueType(0), SplatMask)) {
4901       // Get the splatted value into the low element of a vector register.
4902       SDOperand LowValVec = 
4903         DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), SplatValue);
4904     
4905       // Return shuffle(LowValVec, undef, <0,0,0,0>)
4906       return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), LowValVec,
4907                          DAG.getNode(ISD::UNDEF, Node->getValueType(0)),
4908                          SplatMask);
4909     }
4910   }
4911   
4912   // If there are only two unique elements, we may be able to turn this into a
4913   // vector shuffle.
4914   if (Values.size() == 2) {
4915     // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
4916     MVT::ValueType MaskVT = 
4917       MVT::getIntVectorWithNumElements(NumElems);
4918     std::vector<SDOperand> MaskVec(NumElems);
4919     unsigned i = 0;
4920     for (std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
4921            E = Values.end(); I != E; ++I) {
4922       for (std::vector<unsigned>::iterator II = I->second.begin(),
4923              EE = I->second.end(); II != EE; ++II)
4924         MaskVec[*II] = DAG.getConstant(i, MVT::getVectorElementType(MaskVT));
4925       i += NumElems;
4926     }
4927     SDOperand ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4928                                         &MaskVec[0], MaskVec.size());
4929
4930     // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
4931     if (TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0)) &&
4932         isShuffleLegal(Node->getValueType(0), ShuffleMask)) {
4933       SmallVector<SDOperand, 8> Ops;
4934       for(std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
4935             E = Values.end(); I != E; ++I) {
4936         SDOperand Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
4937                                    I->first);
4938         Ops.push_back(Op);
4939       }
4940       Ops.push_back(ShuffleMask);
4941
4942       // Return shuffle(LoValVec, HiValVec, <0,1,0,1>)
4943       return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), 
4944                          &Ops[0], Ops.size());
4945     }
4946   }
4947   
4948   // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
4949   // aligned object on the stack, store each element into it, then load
4950   // the result as a vector.
4951   MVT::ValueType VT = Node->getValueType(0);
4952   // Create the stack frame object.
4953   SDOperand FIPtr = DAG.CreateStackTemporary(VT);
4954   
4955   // Emit a store of each element to the stack slot.
4956   SmallVector<SDOperand, 8> Stores;
4957   unsigned TypeByteSize = 
4958     MVT::getSizeInBits(Node->getOperand(0).getValueType())/8;
4959   // Store (in the right endianness) the elements to memory.
4960   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
4961     // Ignore undef elements.
4962     if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4963     
4964     unsigned Offset = TypeByteSize*i;
4965     
4966     SDOperand Idx = DAG.getConstant(Offset, FIPtr.getValueType());
4967     Idx = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr, Idx);
4968     
4969     Stores.push_back(DAG.getStore(DAG.getEntryNode(), Node->getOperand(i), Idx, 
4970                                   NULL, 0));
4971   }
4972   
4973   SDOperand StoreChain;
4974   if (!Stores.empty())    // Not all undef elements?
4975     StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4976                              &Stores[0], Stores.size());
4977   else
4978     StoreChain = DAG.getEntryNode();
4979   
4980   // Result is a load from the stack slot.
4981   return DAG.getLoad(VT, StoreChain, FIPtr, NULL, 0);
4982 }
4983
4984 void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
4985                                             SDOperand Op, SDOperand Amt,
4986                                             SDOperand &Lo, SDOperand &Hi) {
4987   // Expand the subcomponents.
4988   SDOperand LHSL, LHSH;
4989   ExpandOp(Op, LHSL, LHSH);
4990
4991   SDOperand Ops[] = { LHSL, LHSH, Amt };
4992   MVT::ValueType VT = LHSL.getValueType();
4993   Lo = DAG.getNode(NodeOp, DAG.getNodeValueTypes(VT, VT), 2, Ops, 3);
4994   Hi = Lo.getValue(1);
4995 }
4996
4997
4998 /// ExpandShift - Try to find a clever way to expand this shift operation out to
4999 /// smaller elements.  If we can't find a way that is more efficient than a
5000 /// libcall on this target, return false.  Otherwise, return true with the
5001 /// low-parts expanded into Lo and Hi.
5002 bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
5003                                        SDOperand &Lo, SDOperand &Hi) {
5004   assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
5005          "This is not a shift!");
5006
5007   MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
5008   SDOperand ShAmt = LegalizeOp(Amt);
5009   MVT::ValueType ShTy = ShAmt.getValueType();
5010   unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
5011   unsigned NVTBits = MVT::getSizeInBits(NVT);
5012
5013   // Handle the case when Amt is an immediate.
5014   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
5015     unsigned Cst = CN->getValue();
5016     // Expand the incoming operand to be shifted, so that we have its parts
5017     SDOperand InL, InH;
5018     ExpandOp(Op, InL, InH);
5019     switch(Opc) {
5020     case ISD::SHL:
5021       if (Cst > VTBits) {
5022         Lo = DAG.getConstant(0, NVT);
5023         Hi = DAG.getConstant(0, NVT);
5024       } else if (Cst > NVTBits) {
5025         Lo = DAG.getConstant(0, NVT);
5026         Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
5027       } else if (Cst == NVTBits) {
5028         Lo = DAG.getConstant(0, NVT);
5029         Hi = InL;
5030       } else {
5031         Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
5032         Hi = DAG.getNode(ISD::OR, NVT,
5033            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
5034            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
5035       }
5036       return true;
5037     case ISD::SRL:
5038       if (Cst > VTBits) {
5039         Lo = DAG.getConstant(0, NVT);
5040         Hi = DAG.getConstant(0, NVT);
5041       } else if (Cst > NVTBits) {
5042         Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
5043         Hi = DAG.getConstant(0, NVT);
5044       } else if (Cst == NVTBits) {
5045         Lo = InH;
5046         Hi = DAG.getConstant(0, NVT);
5047       } else {
5048         Lo = DAG.getNode(ISD::OR, NVT,
5049            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
5050            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
5051         Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
5052       }
5053       return true;
5054     case ISD::SRA:
5055       if (Cst > VTBits) {
5056         Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
5057                               DAG.getConstant(NVTBits-1, ShTy));
5058       } else if (Cst > NVTBits) {
5059         Lo = DAG.getNode(ISD::SRA, NVT, InH,
5060                            DAG.getConstant(Cst-NVTBits, ShTy));
5061         Hi = DAG.getNode(ISD::SRA, NVT, InH,
5062                               DAG.getConstant(NVTBits-1, ShTy));
5063       } else if (Cst == NVTBits) {
5064         Lo = InH;
5065         Hi = DAG.getNode(ISD::SRA, NVT, InH,
5066                               DAG.getConstant(NVTBits-1, ShTy));
5067       } else {
5068         Lo = DAG.getNode(ISD::OR, NVT,
5069            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
5070            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
5071         Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
5072       }
5073       return true;
5074     }
5075   }
5076   
5077   // Okay, the shift amount isn't constant.  However, if we can tell that it is
5078   // >= 32 or < 32, we can still simplify it, without knowing the actual value.
5079   uint64_t Mask = NVTBits, KnownZero, KnownOne;
5080   DAG.ComputeMaskedBits(Amt, Mask, KnownZero, KnownOne);
5081   
5082   // If we know that the high bit of the shift amount is one, then we can do
5083   // this as a couple of simple shifts.
5084   if (KnownOne & Mask) {
5085     // Mask out the high bit, which we know is set.
5086     Amt = DAG.getNode(ISD::AND, Amt.getValueType(), Amt,
5087                       DAG.getConstant(NVTBits-1, Amt.getValueType()));
5088     
5089     // Expand the incoming operand to be shifted, so that we have its parts
5090     SDOperand InL, InH;
5091     ExpandOp(Op, InL, InH);
5092     switch(Opc) {
5093     case ISD::SHL:
5094       Lo = DAG.getConstant(0, NVT);              // Low part is zero.
5095       Hi = DAG.getNode(ISD::SHL, NVT, InL, Amt); // High part from Lo part.
5096       return true;
5097     case ISD::SRL:
5098       Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
5099       Lo = DAG.getNode(ISD::SRL, NVT, InH, Amt); // Lo part from Hi part.
5100       return true;
5101     case ISD::SRA:
5102       Hi = DAG.getNode(ISD::SRA, NVT, InH,       // Sign extend high part.
5103                        DAG.getConstant(NVTBits-1, Amt.getValueType()));
5104       Lo = DAG.getNode(ISD::SRA, NVT, InH, Amt); // Lo part from Hi part.
5105       return true;
5106     }
5107   }
5108   
5109   // If we know that the high bit of the shift amount is zero, then we can do
5110   // this as a couple of simple shifts.
5111   if (KnownZero & Mask) {
5112     // Compute 32-amt.
5113     SDOperand Amt2 = DAG.getNode(ISD::SUB, Amt.getValueType(),
5114                                  DAG.getConstant(NVTBits, Amt.getValueType()),
5115                                  Amt);
5116     
5117     // Expand the incoming operand to be shifted, so that we have its parts
5118     SDOperand InL, InH;
5119     ExpandOp(Op, InL, InH);
5120     switch(Opc) {
5121     case ISD::SHL:
5122       Lo = DAG.getNode(ISD::SHL, NVT, InL, Amt);
5123       Hi = DAG.getNode(ISD::OR, NVT,
5124                        DAG.getNode(ISD::SHL, NVT, InH, Amt),
5125                        DAG.getNode(ISD::SRL, NVT, InL, Amt2));
5126       return true;
5127     case ISD::SRL:
5128       Hi = DAG.getNode(ISD::SRL, NVT, InH, Amt);
5129       Lo = DAG.getNode(ISD::OR, NVT,
5130                        DAG.getNode(ISD::SRL, NVT, InL, Amt),
5131                        DAG.getNode(ISD::SHL, NVT, InH, Amt2));
5132       return true;
5133     case ISD::SRA:
5134       Hi = DAG.getNode(ISD::SRA, NVT, InH, Amt);
5135       Lo = DAG.getNode(ISD::OR, NVT,
5136                        DAG.getNode(ISD::SRL, NVT, InL, Amt),
5137                        DAG.getNode(ISD::SHL, NVT, InH, Amt2));
5138       return true;
5139     }
5140   }
5141   
5142   return false;
5143 }
5144
5145
5146 // ExpandLibCall - Expand a node into a call to a libcall.  If the result value
5147 // does not fit into a register, return the lo part and set the hi part to the
5148 // by-reg argument.  If it does fit into a single register, return the result
5149 // and leave the Hi part unset.
5150 SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
5151                                               bool isSigned, SDOperand &Hi) {
5152   assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
5153   // The input chain to this libcall is the entry node of the function. 
5154   // Legalizing the call will automatically add the previous call to the
5155   // dependence.
5156   SDOperand InChain = DAG.getEntryNode();
5157   
5158   TargetLowering::ArgListTy Args;
5159   TargetLowering::ArgListEntry Entry;
5160   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
5161     MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
5162     const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
5163     Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy; 
5164     Entry.isSExt = isSigned;
5165     Entry.isZExt = !isSigned;
5166     Args.push_back(Entry);
5167   }
5168   SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
5169
5170   // Splice the libcall in wherever FindInputOutputChains tells us to.
5171   const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
5172   std::pair<SDOperand,SDOperand> CallInfo =
5173     TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, CallingConv::C,
5174                     false, Callee, Args, DAG);
5175
5176   // Legalize the call sequence, starting with the chain.  This will advance
5177   // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
5178   // was added by LowerCallTo (guaranteeing proper serialization of calls).
5179   LegalizeOp(CallInfo.second);
5180   SDOperand Result;
5181   switch (getTypeAction(CallInfo.first.getValueType())) {
5182   default: assert(0 && "Unknown thing");
5183   case Legal:
5184     Result = CallInfo.first;
5185     break;
5186   case Expand:
5187     ExpandOp(CallInfo.first, Result, Hi);
5188     break;
5189   }
5190   return Result;
5191 }
5192
5193
5194 /// ExpandIntToFP - Expand a [US]INT_TO_FP operation.
5195 ///
5196 SDOperand SelectionDAGLegalize::
5197 ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
5198   assert(getTypeAction(Source.getValueType()) == Expand &&
5199          "This is not an expansion!");
5200   assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
5201
5202   if (!isSigned) {
5203     assert(Source.getValueType() == MVT::i64 &&
5204            "This only works for 64-bit -> FP");
5205     // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
5206     // incoming integer is set.  To handle this, we dynamically test to see if
5207     // it is set, and, if so, add a fudge factor.
5208     SDOperand Lo, Hi;
5209     ExpandOp(Source, Lo, Hi);
5210
5211     // If this is unsigned, and not supported, first perform the conversion to
5212     // signed, then adjust the result if the sign bit is set.
5213     SDOperand SignedConv = ExpandIntToFP(true, DestTy,
5214                    DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), Lo, Hi));
5215
5216     SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
5217                                      DAG.getConstant(0, Hi.getValueType()),
5218                                      ISD::SETLT);
5219     SDOperand Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
5220     SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
5221                                       SignSet, Four, Zero);
5222     uint64_t FF = 0x5f800000ULL;
5223     if (TLI.isLittleEndian()) FF <<= 32;
5224     static Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
5225
5226     SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
5227     CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
5228     SDOperand FudgeInReg;
5229     if (DestTy == MVT::f32)
5230       FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
5231                                PseudoSourceValue::getConstantPool(), 0);
5232     else if (MVT::getSizeInBits(DestTy) > MVT::getSizeInBits(MVT::f32))
5233       // FIXME: Avoid the extend by construction the right constantpool?
5234       FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, DestTy, DAG.getEntryNode(),
5235                                   CPIdx,
5236                                   PseudoSourceValue::getConstantPool(), 0,
5237                                   MVT::f32);
5238     else 
5239       assert(0 && "Unexpected conversion");
5240
5241     MVT::ValueType SCVT = SignedConv.getValueType();
5242     if (SCVT != DestTy) {
5243       // Destination type needs to be expanded as well. The FADD now we are
5244       // constructing will be expanded into a libcall.
5245       if (MVT::getSizeInBits(SCVT) != MVT::getSizeInBits(DestTy)) {
5246         assert(SCVT == MVT::i32 && DestTy == MVT::f64);
5247         SignedConv = DAG.getNode(ISD::BUILD_PAIR, MVT::i64,
5248                                  SignedConv, SignedConv.getValue(1));
5249       }
5250       SignedConv = DAG.getNode(ISD::BIT_CONVERT, DestTy, SignedConv);
5251     }
5252     return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
5253   }
5254
5255   // Check to see if the target has a custom way to lower this.  If so, use it.
5256   switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
5257   default: assert(0 && "This action not implemented for this operation!");
5258   case TargetLowering::Legal:
5259   case TargetLowering::Expand:
5260     break;   // This case is handled below.
5261   case TargetLowering::Custom: {
5262     SDOperand NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
5263                                                   Source), DAG);
5264     if (NV.Val)
5265       return LegalizeOp(NV);
5266     break;   // The target decided this was legal after all
5267   }
5268   }
5269
5270   // Expand the source, then glue it back together for the call.  We must expand
5271   // the source in case it is shared (this pass of legalize must traverse it).
5272   SDOperand SrcLo, SrcHi;
5273   ExpandOp(Source, SrcLo, SrcHi);
5274   Source = DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), SrcLo, SrcHi);
5275
5276   RTLIB::Libcall LC;
5277   if (DestTy == MVT::f32)
5278     LC = RTLIB::SINTTOFP_I64_F32;
5279   else {
5280     assert(DestTy == MVT::f64 && "Unknown fp value type!");
5281     LC = RTLIB::SINTTOFP_I64_F64;
5282   }
5283   
5284   assert(TLI.getLibcallName(LC) && "Don't know how to expand this SINT_TO_FP!");
5285   Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
5286   SDOperand UnusedHiPart;
5287   return ExpandLibCall(TLI.getLibcallName(LC), Source.Val, isSigned,
5288                        UnusedHiPart);
5289 }
5290
5291 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
5292 /// INT_TO_FP operation of the specified operand when the target requests that
5293 /// we expand it.  At this point, we know that the result and operand types are
5294 /// legal for the target.
5295 SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
5296                                                      SDOperand Op0,
5297                                                      MVT::ValueType DestVT) {
5298   if (Op0.getValueType() == MVT::i32) {
5299     // simple 32-bit [signed|unsigned] integer to float/double expansion
5300     
5301     // Get the stack frame index of a 8 byte buffer.
5302     SDOperand StackSlot = DAG.CreateStackTemporary(MVT::f64);
5303     
5304     // word offset constant for Hi/Lo address computation
5305     SDOperand WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
5306     // set up Hi and Lo (into buffer) address based on endian
5307     SDOperand Hi = StackSlot;
5308     SDOperand Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot,WordOff);
5309     if (TLI.isLittleEndian())
5310       std::swap(Hi, Lo);
5311     
5312     // if signed map to unsigned space
5313     SDOperand Op0Mapped;
5314     if (isSigned) {
5315       // constant used to invert sign bit (signed to unsigned mapping)
5316       SDOperand SignBit = DAG.getConstant(0x80000000u, MVT::i32);
5317       Op0Mapped = DAG.getNode(ISD::XOR, MVT::i32, Op0, SignBit);
5318     } else {
5319       Op0Mapped = Op0;
5320     }
5321     // store the lo of the constructed double - based on integer input
5322     SDOperand Store1 = DAG.getStore(DAG.getEntryNode(),
5323                                     Op0Mapped, Lo, NULL, 0);
5324     // initial hi portion of constructed double
5325     SDOperand InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
5326     // store the hi of the constructed double - biased exponent
5327     SDOperand Store2=DAG.getStore(Store1, InitialHi, Hi, NULL, 0);
5328     // load the constructed double
5329     SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot, NULL, 0);
5330     // FP constant to bias correct the final result
5331     SDOperand Bias = DAG.getConstantFP(isSigned ?
5332                                             BitsToDouble(0x4330000080000000ULL)
5333                                           : BitsToDouble(0x4330000000000000ULL),
5334                                      MVT::f64);
5335     // subtract the bias
5336     SDOperand Sub = DAG.getNode(ISD::FSUB, MVT::f64, Load, Bias);
5337     // final result
5338     SDOperand Result;
5339     // handle final rounding
5340     if (DestVT == MVT::f64) {
5341       // do nothing
5342       Result = Sub;
5343     } else if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(MVT::f64)) {
5344       Result = DAG.getNode(ISD::FP_ROUND, DestVT, Sub,
5345                            DAG.getIntPtrConstant(0));
5346     } else if (MVT::getSizeInBits(DestVT) > MVT::getSizeInBits(MVT::f64)) {
5347       Result = DAG.getNode(ISD::FP_EXTEND, DestVT, Sub);
5348     }
5349     return Result;
5350   }
5351   assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
5352   SDOperand Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
5353
5354   SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Op0,
5355                                    DAG.getConstant(0, Op0.getValueType()),
5356                                    ISD::SETLT);
5357   SDOperand Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
5358   SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
5359                                     SignSet, Four, Zero);
5360
5361   // If the sign bit of the integer is set, the large number will be treated
5362   // as a negative number.  To counteract this, the dynamic code adds an
5363   // offset depending on the data type.
5364   uint64_t FF;
5365   switch (Op0.getValueType()) {
5366   default: assert(0 && "Unsupported integer type!");
5367   case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
5368   case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
5369   case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
5370   case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
5371   }
5372   if (TLI.isLittleEndian()) FF <<= 32;
5373   static Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
5374
5375   SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
5376   CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
5377   SDOperand FudgeInReg;
5378   if (DestVT == MVT::f32)
5379     FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
5380                              PseudoSourceValue::getConstantPool(), 0);
5381   else {
5382     FudgeInReg =
5383       LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, DestVT,
5384                                 DAG.getEntryNode(), CPIdx,
5385                                 PseudoSourceValue::getConstantPool(), 0,
5386                                 MVT::f32));
5387   }
5388
5389   return DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg);
5390 }
5391
5392 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
5393 /// *INT_TO_FP operation of the specified operand when the target requests that
5394 /// we promote it.  At this point, we know that the result and operand types are
5395 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
5396 /// operation that takes a larger input.
5397 SDOperand SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDOperand LegalOp,
5398                                                       MVT::ValueType DestVT,
5399                                                       bool isSigned) {
5400   // First step, figure out the appropriate *INT_TO_FP operation to use.
5401   MVT::ValueType NewInTy = LegalOp.getValueType();
5402
5403   unsigned OpToUse = 0;
5404
5405   // Scan for the appropriate larger type to use.
5406   while (1) {
5407     NewInTy = (MVT::ValueType)(NewInTy+1);
5408     assert(MVT::isInteger(NewInTy) && "Ran out of possibilities!");
5409
5410     // If the target supports SINT_TO_FP of this type, use it.
5411     switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
5412       default: break;
5413       case TargetLowering::Legal:
5414         if (!TLI.isTypeLegal(NewInTy))
5415           break;  // Can't use this datatype.
5416         // FALL THROUGH.
5417       case TargetLowering::Custom:
5418         OpToUse = ISD::SINT_TO_FP;
5419         break;
5420     }
5421     if (OpToUse) break;
5422     if (isSigned) continue;
5423
5424     // If the target supports UINT_TO_FP of this type, use it.
5425     switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
5426       default: break;
5427       case TargetLowering::Legal:
5428         if (!TLI.isTypeLegal(NewInTy))
5429           break;  // Can't use this datatype.
5430         // FALL THROUGH.
5431       case TargetLowering::Custom:
5432         OpToUse = ISD::UINT_TO_FP;
5433         break;
5434     }
5435     if (OpToUse) break;
5436
5437     // Otherwise, try a larger type.
5438   }
5439
5440   // Okay, we found the operation and type to use.  Zero extend our input to the
5441   // desired type then run the operation on it.
5442   return DAG.getNode(OpToUse, DestVT,
5443                      DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5444                                  NewInTy, LegalOp));
5445 }
5446
5447 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
5448 /// FP_TO_*INT operation of the specified operand when the target requests that
5449 /// we promote it.  At this point, we know that the result and operand types are
5450 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
5451 /// operation that returns a larger result.
5452 SDOperand SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDOperand LegalOp,
5453                                                       MVT::ValueType DestVT,
5454                                                       bool isSigned) {
5455   // First step, figure out the appropriate FP_TO*INT operation to use.
5456   MVT::ValueType NewOutTy = DestVT;
5457
5458   unsigned OpToUse = 0;
5459
5460   // Scan for the appropriate larger type to use.
5461   while (1) {
5462     NewOutTy = (MVT::ValueType)(NewOutTy+1);
5463     assert(MVT::isInteger(NewOutTy) && "Ran out of possibilities!");
5464
5465     // If the target supports FP_TO_SINT returning this type, use it.
5466     switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
5467     default: break;
5468     case TargetLowering::Legal:
5469       if (!TLI.isTypeLegal(NewOutTy))
5470         break;  // Can't use this datatype.
5471       // FALL THROUGH.
5472     case TargetLowering::Custom:
5473       OpToUse = ISD::FP_TO_SINT;
5474       break;
5475     }
5476     if (OpToUse) break;
5477
5478     // If the target supports FP_TO_UINT of this type, use it.
5479     switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
5480     default: break;
5481     case TargetLowering::Legal:
5482       if (!TLI.isTypeLegal(NewOutTy))
5483         break;  // Can't use this datatype.
5484       // FALL THROUGH.
5485     case TargetLowering::Custom:
5486       OpToUse = ISD::FP_TO_UINT;
5487       break;
5488     }
5489     if (OpToUse) break;
5490
5491     // Otherwise, try a larger type.
5492   }
5493
5494   
5495   // Okay, we found the operation and type to use.
5496   SDOperand Operation = DAG.getNode(OpToUse, NewOutTy, LegalOp);
5497   
5498   // If the operation produces an invalid type, it must be custom lowered.  Use
5499   // the target lowering hooks to expand it.  Just keep the low part of the
5500   // expanded operation, we know that we're truncating anyway.
5501   if (getTypeAction(NewOutTy) == Expand) {
5502     Operation = SDOperand(TLI.ExpandOperationResult(Operation.Val, DAG), 0);
5503     assert(Operation.Val && "Didn't return anything");
5504   }
5505   
5506   // Truncate the result of the extended FP_TO_*INT operation to the desired
5507   // size.
5508   return DAG.getNode(ISD::TRUNCATE, DestVT, Operation);
5509 }
5510
5511 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
5512 ///
5513 SDOperand SelectionDAGLegalize::ExpandBSWAP(SDOperand Op) {
5514   MVT::ValueType VT = Op.getValueType();
5515   MVT::ValueType SHVT = TLI.getShiftAmountTy();
5516   SDOperand Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
5517   switch (VT) {
5518   default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
5519   case MVT::i16:
5520     Tmp2 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
5521     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
5522     return DAG.getNode(ISD::OR, VT, Tmp1, Tmp2);
5523   case MVT::i32:
5524     Tmp4 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
5525     Tmp3 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
5526     Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
5527     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
5528     Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
5529     Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(0xFF00, VT));
5530     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
5531     Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
5532     return DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
5533   case MVT::i64:
5534     Tmp8 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(56, SHVT));
5535     Tmp7 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(40, SHVT));
5536     Tmp6 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
5537     Tmp5 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
5538     Tmp4 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
5539     Tmp3 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
5540     Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(40, SHVT));
5541     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(56, SHVT));
5542     Tmp7 = DAG.getNode(ISD::AND, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
5543     Tmp6 = DAG.getNode(ISD::AND, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
5544     Tmp5 = DAG.getNode(ISD::AND, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
5545     Tmp4 = DAG.getNode(ISD::AND, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
5546     Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
5547     Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
5548     Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp7);
5549     Tmp6 = DAG.getNode(ISD::OR, VT, Tmp6, Tmp5);
5550     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
5551     Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
5552     Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp6);
5553     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
5554     return DAG.getNode(ISD::OR, VT, Tmp8, Tmp4);
5555   }
5556 }
5557
5558 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
5559 ///
5560 SDOperand SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDOperand Op) {
5561   switch (Opc) {
5562   default: assert(0 && "Cannot expand this yet!");
5563   case ISD::CTPOP: {
5564     static const uint64_t mask[6] = {
5565       0x5555555555555555ULL, 0x3333333333333333ULL,
5566       0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
5567       0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
5568     };
5569     MVT::ValueType VT = Op.getValueType();
5570     MVT::ValueType ShVT = TLI.getShiftAmountTy();
5571     unsigned len = MVT::getSizeInBits(VT);
5572     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
5573       //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
5574       SDOperand Tmp2 = DAG.getConstant(mask[i], VT);
5575       SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
5576       Op = DAG.getNode(ISD::ADD, VT, DAG.getNode(ISD::AND, VT, Op, Tmp2),
5577                        DAG.getNode(ISD::AND, VT,
5578                                    DAG.getNode(ISD::SRL, VT, Op, Tmp3),Tmp2));
5579     }
5580     return Op;
5581   }
5582   case ISD::CTLZ: {
5583     // for now, we do this:
5584     // x = x | (x >> 1);
5585     // x = x | (x >> 2);
5586     // ...
5587     // x = x | (x >>16);
5588     // x = x | (x >>32); // for 64-bit input
5589     // return popcount(~x);
5590     //
5591     // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
5592     MVT::ValueType VT = Op.getValueType();
5593     MVT::ValueType ShVT = TLI.getShiftAmountTy();
5594     unsigned len = MVT::getSizeInBits(VT);
5595     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
5596       SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
5597       Op = DAG.getNode(ISD::OR, VT, Op, DAG.getNode(ISD::SRL, VT, Op, Tmp3));
5598     }
5599     Op = DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(~0ULL, VT));
5600     return DAG.getNode(ISD::CTPOP, VT, Op);
5601   }
5602   case ISD::CTTZ: {
5603     // for now, we use: { return popcount(~x & (x - 1)); }
5604     // unless the target has ctlz but not ctpop, in which case we use:
5605     // { return 32 - nlz(~x & (x-1)); }
5606     // see also http://www.hackersdelight.org/HDcode/ntz.cc
5607     MVT::ValueType VT = Op.getValueType();
5608     SDOperand Tmp2 = DAG.getConstant(~0ULL, VT);
5609     SDOperand Tmp3 = DAG.getNode(ISD::AND, VT,
5610                        DAG.getNode(ISD::XOR, VT, Op, Tmp2),
5611                        DAG.getNode(ISD::SUB, VT, Op, DAG.getConstant(1, VT)));
5612     // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
5613     if (!TLI.isOperationLegal(ISD::CTPOP, VT) &&
5614         TLI.isOperationLegal(ISD::CTLZ, VT))
5615       return DAG.getNode(ISD::SUB, VT,
5616                          DAG.getConstant(MVT::getSizeInBits(VT), VT),
5617                          DAG.getNode(ISD::CTLZ, VT, Tmp3));
5618     return DAG.getNode(ISD::CTPOP, VT, Tmp3);
5619   }
5620   }
5621 }
5622
5623 /// ExpandOp - Expand the specified SDOperand into its two component pieces
5624 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
5625 /// LegalizeNodes map is filled in for any results that are not expanded, the
5626 /// ExpandedNodes map is filled in for any results that are expanded, and the
5627 /// Lo/Hi values are returned.
5628 void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
5629   MVT::ValueType VT = Op.getValueType();
5630   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
5631   SDNode *Node = Op.Val;
5632   assert(getTypeAction(VT) == Expand && "Not an expanded type!");
5633   assert(((MVT::isInteger(NVT) && NVT < VT) || MVT::isFloatingPoint(VT) ||
5634          MVT::isVector(VT)) &&
5635          "Cannot expand to FP value or to larger int value!");
5636
5637   // See if we already expanded it.
5638   DenseMap<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
5639     = ExpandedNodes.find(Op);
5640   if (I != ExpandedNodes.end()) {
5641     Lo = I->second.first;
5642     Hi = I->second.second;
5643     return;
5644   }
5645
5646   switch (Node->getOpcode()) {
5647   case ISD::CopyFromReg:
5648     assert(0 && "CopyFromReg must be legal!");
5649   case ISD::FP_ROUND_INREG:
5650     if (VT == MVT::ppcf128 && 
5651         TLI.getOperationAction(ISD::FP_ROUND_INREG, VT) == 
5652             TargetLowering::Custom) {
5653       SDOperand SrcLo, SrcHi, Src;
5654       ExpandOp(Op.getOperand(0), SrcLo, SrcHi);
5655       Src = DAG.getNode(ISD::BUILD_PAIR, VT, SrcLo, SrcHi);
5656       SDOperand Result = TLI.LowerOperation(
5657         DAG.getNode(ISD::FP_ROUND_INREG, VT, Src, Op.getOperand(1)), DAG);
5658       assert(Result.Val->getOpcode() == ISD::BUILD_PAIR);
5659       Lo = Result.Val->getOperand(0);
5660       Hi = Result.Val->getOperand(1);
5661       break;
5662     }
5663     // fall through
5664   default:
5665 #ifndef NDEBUG
5666     cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
5667 #endif
5668     assert(0 && "Do not know how to expand this operator!");
5669     abort();
5670   case ISD::EXTRACT_VECTOR_ELT:
5671     assert(VT==MVT::i64 && "Do not know how to expand this operator!");
5672     // ExpandEXTRACT_VECTOR_ELT tolerates invalid result types.
5673     Lo  = ExpandEXTRACT_VECTOR_ELT(Op);
5674     return ExpandOp(Lo, Lo, Hi);
5675   case ISD::UNDEF:
5676     NVT = TLI.getTypeToExpandTo(VT);
5677     Lo = DAG.getNode(ISD::UNDEF, NVT);
5678     Hi = DAG.getNode(ISD::UNDEF, NVT);
5679     break;
5680   case ISD::Constant: {
5681     uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
5682     Lo = DAG.getConstant(Cst, NVT);
5683     Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
5684     break;
5685   }
5686   case ISD::ConstantFP: {
5687     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
5688     if (CFP->getValueType(0) == MVT::ppcf128) {
5689       APInt api = CFP->getValueAPF().convertToAPInt();
5690       Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &api.getRawData()[1])),
5691                              MVT::f64);
5692       Hi = DAG.getConstantFP(APFloat(APInt(64, 1, &api.getRawData()[0])), 
5693                              MVT::f64);
5694       break;
5695     }
5696     Lo = ExpandConstantFP(CFP, false, DAG, TLI);
5697     if (getTypeAction(Lo.getValueType()) == Expand)
5698       ExpandOp(Lo, Lo, Hi);
5699     break;
5700   }
5701   case ISD::BUILD_PAIR:
5702     // Return the operands.
5703     Lo = Node->getOperand(0);
5704     Hi = Node->getOperand(1);
5705     break;
5706       
5707   case ISD::MERGE_VALUES:
5708     if (Node->getNumValues() == 1) {
5709       ExpandOp(Op.getOperand(0), Lo, Hi);
5710       break;
5711     }
5712     // FIXME: For now only expand i64,chain = MERGE_VALUES (x, y)
5713     assert(Op.ResNo == 0 && Node->getNumValues() == 2 &&
5714            Op.getValue(1).getValueType() == MVT::Other &&
5715            "unhandled MERGE_VALUES");
5716     ExpandOp(Op.getOperand(0), Lo, Hi);
5717     // Remember that we legalized the chain.
5718     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Op.getOperand(1)));
5719     break;
5720     
5721   case ISD::SIGN_EXTEND_INREG:
5722     ExpandOp(Node->getOperand(0), Lo, Hi);
5723     // sext_inreg the low part if needed.
5724     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
5725     
5726     // The high part gets the sign extension from the lo-part.  This handles
5727     // things like sextinreg V:i64 from i8.
5728     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
5729                      DAG.getConstant(MVT::getSizeInBits(NVT)-1,
5730                                      TLI.getShiftAmountTy()));
5731     break;
5732
5733   case ISD::BSWAP: {
5734     ExpandOp(Node->getOperand(0), Lo, Hi);
5735     SDOperand TempLo = DAG.getNode(ISD::BSWAP, NVT, Hi);
5736     Hi = DAG.getNode(ISD::BSWAP, NVT, Lo);
5737     Lo = TempLo;
5738     break;
5739   }
5740     
5741   case ISD::CTPOP:
5742     ExpandOp(Node->getOperand(0), Lo, Hi);
5743     Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
5744                      DAG.getNode(ISD::CTPOP, NVT, Lo),
5745                      DAG.getNode(ISD::CTPOP, NVT, Hi));
5746     Hi = DAG.getConstant(0, NVT);
5747     break;
5748
5749   case ISD::CTLZ: {
5750     // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
5751     ExpandOp(Node->getOperand(0), Lo, Hi);
5752     SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
5753     SDOperand HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
5754     SDOperand TopNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), HLZ, BitsC,
5755                                         ISD::SETNE);
5756     SDOperand LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
5757     LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
5758
5759     Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
5760     Hi = DAG.getConstant(0, NVT);
5761     break;
5762   }
5763
5764   case ISD::CTTZ: {
5765     // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
5766     ExpandOp(Node->getOperand(0), Lo, Hi);
5767     SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
5768     SDOperand LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
5769     SDOperand BotNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), LTZ, BitsC,
5770                                         ISD::SETNE);
5771     SDOperand HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
5772     HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
5773
5774     Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
5775     Hi = DAG.getConstant(0, NVT);
5776     break;
5777   }
5778
5779   case ISD::VAARG: {
5780     SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
5781     SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
5782     Lo = DAG.getVAArg(NVT, Ch, Ptr, Node->getOperand(2));
5783     Hi = DAG.getVAArg(NVT, Lo.getValue(1), Ptr, Node->getOperand(2));
5784
5785     // Remember that we legalized the chain.
5786     Hi = LegalizeOp(Hi);
5787     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
5788     if (TLI.isBigEndian())
5789       std::swap(Lo, Hi);
5790     break;
5791   }
5792     
5793   case ISD::LOAD: {
5794     LoadSDNode *LD = cast<LoadSDNode>(Node);
5795     SDOperand Ch  = LD->getChain();    // Legalize the chain.
5796     SDOperand Ptr = LD->getBasePtr();  // Legalize the pointer.
5797     ISD::LoadExtType ExtType = LD->getExtensionType();
5798     int SVOffset = LD->getSrcValueOffset();
5799     unsigned Alignment = LD->getAlignment();
5800     bool isVolatile = LD->isVolatile();
5801
5802     if (ExtType == ISD::NON_EXTLOAD) {
5803       Lo = DAG.getLoad(NVT, Ch, Ptr, LD->getSrcValue(), SVOffset,
5804                        isVolatile, Alignment);
5805       if (VT == MVT::f32 || VT == MVT::f64) {
5806         // f32->i32 or f64->i64 one to one expansion.
5807         // Remember that we legalized the chain.
5808         AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
5809         // Recursively expand the new load.
5810         if (getTypeAction(NVT) == Expand)
5811           ExpandOp(Lo, Lo, Hi);
5812         break;
5813       }
5814
5815       // Increment the pointer to the other half.
5816       unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
5817       Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
5818                         DAG.getIntPtrConstant(IncrementSize));
5819       SVOffset += IncrementSize;
5820       Alignment = MinAlign(Alignment, IncrementSize);
5821       Hi = DAG.getLoad(NVT, Ch, Ptr, LD->getSrcValue(), SVOffset,
5822                        isVolatile, Alignment);
5823
5824       // Build a factor node to remember that this load is independent of the
5825       // other one.
5826       SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
5827                                  Hi.getValue(1));
5828
5829       // Remember that we legalized the chain.
5830       AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
5831       if (TLI.isBigEndian())
5832         std::swap(Lo, Hi);
5833     } else {
5834       MVT::ValueType EVT = LD->getMemoryVT();
5835
5836       if ((VT == MVT::f64 && EVT == MVT::f32) ||
5837           (VT == MVT::ppcf128 && (EVT==MVT::f64 || EVT==MVT::f32))) {
5838         // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
5839         SDOperand Load = DAG.getLoad(EVT, Ch, Ptr, LD->getSrcValue(),
5840                                      SVOffset, isVolatile, Alignment);
5841         // Remember that we legalized the chain.
5842         AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Load.getValue(1)));
5843         ExpandOp(DAG.getNode(ISD::FP_EXTEND, VT, Load), Lo, Hi);
5844         break;
5845       }
5846     
5847       if (EVT == NVT)
5848         Lo = DAG.getLoad(NVT, Ch, Ptr, LD->getSrcValue(),
5849                          SVOffset, isVolatile, Alignment);
5850       else
5851         Lo = DAG.getExtLoad(ExtType, NVT, Ch, Ptr, LD->getSrcValue(),
5852                             SVOffset, EVT, isVolatile,
5853                             Alignment);
5854     
5855       // Remember that we legalized the chain.
5856       AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
5857
5858       if (ExtType == ISD::SEXTLOAD) {
5859         // The high part is obtained by SRA'ing all but one of the bits of the
5860         // lo part.
5861         unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
5862         Hi = DAG.getNode(ISD::SRA, NVT, Lo,
5863                          DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
5864       } else if (ExtType == ISD::ZEXTLOAD) {
5865         // The high part is just a zero.
5866         Hi = DAG.getConstant(0, NVT);
5867       } else /* if (ExtType == ISD::EXTLOAD) */ {
5868         // The high part is undefined.
5869         Hi = DAG.getNode(ISD::UNDEF, NVT);
5870       }
5871     }
5872     break;
5873   }
5874   case ISD::AND:
5875   case ISD::OR:
5876   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
5877     SDOperand LL, LH, RL, RH;
5878     ExpandOp(Node->getOperand(0), LL, LH);
5879     ExpandOp(Node->getOperand(1), RL, RH);
5880     Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
5881     Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
5882     break;
5883   }
5884   case ISD::SELECT: {
5885     SDOperand LL, LH, RL, RH;
5886     ExpandOp(Node->getOperand(1), LL, LH);
5887     ExpandOp(Node->getOperand(2), RL, RH);
5888     if (getTypeAction(NVT) == Expand)
5889       NVT = TLI.getTypeToExpandTo(NVT);
5890     Lo = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LL, RL);
5891     if (VT != MVT::f32)
5892       Hi = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LH, RH);
5893     break;
5894   }
5895   case ISD::SELECT_CC: {
5896     SDOperand TL, TH, FL, FH;
5897     ExpandOp(Node->getOperand(2), TL, TH);
5898     ExpandOp(Node->getOperand(3), FL, FH);
5899     if (getTypeAction(NVT) == Expand)
5900       NVT = TLI.getTypeToExpandTo(NVT);
5901     Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
5902                      Node->getOperand(1), TL, FL, Node->getOperand(4));
5903     if (VT != MVT::f32)
5904       Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
5905                        Node->getOperand(1), TH, FH, Node->getOperand(4));
5906     break;
5907   }
5908   case ISD::ANY_EXTEND:
5909     // The low part is any extension of the input (which degenerates to a copy).
5910     Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, Node->getOperand(0));
5911     // The high part is undefined.
5912     Hi = DAG.getNode(ISD::UNDEF, NVT);
5913     break;
5914   case ISD::SIGN_EXTEND: {
5915     // The low part is just a sign extension of the input (which degenerates to
5916     // a copy).
5917     Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, Node->getOperand(0));
5918
5919     // The high part is obtained by SRA'ing all but one of the bits of the lo
5920     // part.
5921     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
5922     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
5923                      DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
5924     break;
5925   }
5926   case ISD::ZERO_EXTEND:
5927     // The low part is just a zero extension of the input (which degenerates to
5928     // a copy).
5929     Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
5930
5931     // The high part is just a zero.
5932     Hi = DAG.getConstant(0, NVT);
5933     break;
5934     
5935   case ISD::TRUNCATE: {
5936     // The input value must be larger than this value.  Expand *it*.
5937     SDOperand NewLo;
5938     ExpandOp(Node->getOperand(0), NewLo, Hi);
5939     
5940     // The low part is now either the right size, or it is closer.  If not the
5941     // right size, make an illegal truncate so we recursively expand it.
5942     if (NewLo.getValueType() != Node->getValueType(0))
5943       NewLo = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), NewLo);
5944     ExpandOp(NewLo, Lo, Hi);
5945     break;
5946   }
5947     
5948   case ISD::BIT_CONVERT: {
5949     SDOperand Tmp;
5950     if (TLI.getOperationAction(ISD::BIT_CONVERT, VT) == TargetLowering::Custom){
5951       // If the target wants to, allow it to lower this itself.
5952       switch (getTypeAction(Node->getOperand(0).getValueType())) {
5953       case Expand: assert(0 && "cannot expand FP!");
5954       case Legal:   Tmp = LegalizeOp(Node->getOperand(0)); break;
5955       case Promote: Tmp = PromoteOp (Node->getOperand(0)); break;
5956       }
5957       Tmp = TLI.LowerOperation(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp), DAG);
5958     }
5959
5960     // f32 / f64 must be expanded to i32 / i64.
5961     if (VT == MVT::f32 || VT == MVT::f64) {
5962       Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
5963       if (getTypeAction(NVT) == Expand)
5964         ExpandOp(Lo, Lo, Hi);
5965       break;
5966     }
5967
5968     // If source operand will be expanded to the same type as VT, i.e.
5969     // i64 <- f64, i32 <- f32, expand the source operand instead.
5970     MVT::ValueType VT0 = Node->getOperand(0).getValueType();
5971     if (getTypeAction(VT0) == Expand && TLI.getTypeToTransformTo(VT0) == VT) {
5972       ExpandOp(Node->getOperand(0), Lo, Hi);
5973       break;
5974     }
5975
5976     // Turn this into a load/store pair by default.
5977     if (Tmp.Val == 0)
5978       Tmp = EmitStackConvert(Node->getOperand(0), VT, VT);
5979     
5980     ExpandOp(Tmp, Lo, Hi);
5981     break;
5982   }
5983
5984   case ISD::READCYCLECOUNTER: {
5985     assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) == 
5986                  TargetLowering::Custom &&
5987            "Must custom expand ReadCycleCounter");
5988     SDOperand Tmp = TLI.LowerOperation(Op, DAG);
5989     assert(Tmp.Val && "Node must be custom expanded!");
5990     ExpandOp(Tmp.getValue(0), Lo, Hi);
5991     AddLegalizedOperand(SDOperand(Node, 1), // Remember we legalized the chain.
5992                         LegalizeOp(Tmp.getValue(1)));
5993     break;
5994   }
5995
5996     // These operators cannot be expanded directly, emit them as calls to
5997     // library functions.
5998   case ISD::FP_TO_SINT: {
5999     if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
6000       SDOperand Op;
6001       switch (getTypeAction(Node->getOperand(0).getValueType())) {
6002       case Expand: assert(0 && "cannot expand FP!");
6003       case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
6004       case Promote: Op = PromoteOp (Node->getOperand(0)); break;
6005       }
6006
6007       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
6008
6009       // Now that the custom expander is done, expand the result, which is still
6010       // VT.
6011       if (Op.Val) {
6012         ExpandOp(Op, Lo, Hi);
6013         break;
6014       }
6015     }
6016
6017     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
6018     if (Node->getOperand(0).getValueType() == MVT::f32)
6019       LC = RTLIB::FPTOSINT_F32_I64;
6020     else if (Node->getOperand(0).getValueType() == MVT::f64)
6021       LC = RTLIB::FPTOSINT_F64_I64;
6022     else if (Node->getOperand(0).getValueType() == MVT::f80)
6023       LC = RTLIB::FPTOSINT_F80_I64;
6024     else if (Node->getOperand(0).getValueType() == MVT::ppcf128)
6025       LC = RTLIB::FPTOSINT_PPCF128_I64;
6026     Lo = ExpandLibCall(TLI.getLibcallName(LC), Node,
6027                        false/*sign irrelevant*/, Hi);
6028     break;
6029   }
6030
6031   case ISD::FP_TO_UINT: {
6032     if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
6033       SDOperand Op;
6034       switch (getTypeAction(Node->getOperand(0).getValueType())) {
6035         case Expand: assert(0 && "cannot expand FP!");
6036         case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
6037         case Promote: Op = PromoteOp (Node->getOperand(0)); break;
6038       }
6039         
6040       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_UINT, VT, Op), DAG);
6041
6042       // Now that the custom expander is done, expand the result.
6043       if (Op.Val) {
6044         ExpandOp(Op, Lo, Hi);
6045         break;
6046       }
6047     }
6048
6049     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
6050     if (Node->getOperand(0).getValueType() == MVT::f32)
6051       LC = RTLIB::FPTOUINT_F32_I64;
6052     else if (Node->getOperand(0).getValueType() == MVT::f64)
6053       LC = RTLIB::FPTOUINT_F64_I64;
6054     else if (Node->getOperand(0).getValueType() == MVT::f80)
6055       LC = RTLIB::FPTOUINT_F80_I64;
6056     else if (Node->getOperand(0).getValueType() == MVT::ppcf128)
6057       LC = RTLIB::FPTOUINT_PPCF128_I64;
6058     Lo = ExpandLibCall(TLI.getLibcallName(LC), Node,
6059                        false/*sign irrelevant*/, Hi);
6060     break;
6061   }
6062
6063   case ISD::SHL: {
6064     // If the target wants custom lowering, do so.
6065     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
6066     if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
6067       SDOperand Op = DAG.getNode(ISD::SHL, VT, Node->getOperand(0), ShiftAmt);
6068       Op = TLI.LowerOperation(Op, DAG);
6069       if (Op.Val) {
6070         // Now that the custom expander is done, expand the result, which is
6071         // still VT.
6072         ExpandOp(Op, Lo, Hi);
6073         break;
6074       }
6075     }
6076     
6077     // If ADDC/ADDE are supported and if the shift amount is a constant 1, emit 
6078     // this X << 1 as X+X.
6079     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(ShiftAmt)) {
6080       if (ShAmt->getValue() == 1 && TLI.isOperationLegal(ISD::ADDC, NVT) && 
6081           TLI.isOperationLegal(ISD::ADDE, NVT)) {
6082         SDOperand LoOps[2], HiOps[3];
6083         ExpandOp(Node->getOperand(0), LoOps[0], HiOps[0]);
6084         SDVTList VTList = DAG.getVTList(LoOps[0].getValueType(), MVT::Flag);
6085         LoOps[1] = LoOps[0];
6086         Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
6087
6088         HiOps[1] = HiOps[0];
6089         HiOps[2] = Lo.getValue(1);
6090         Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
6091         break;
6092       }
6093     }
6094     
6095     // If we can emit an efficient shift operation, do so now.
6096     if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi))
6097       break;
6098
6099     // If this target supports SHL_PARTS, use it.
6100     TargetLowering::LegalizeAction Action =
6101       TLI.getOperationAction(ISD::SHL_PARTS, NVT);
6102     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6103         Action == TargetLowering::Custom) {
6104       ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
6105       break;
6106     }
6107
6108     // Otherwise, emit a libcall.
6109     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SHL_I64), Node,
6110                        false/*left shift=unsigned*/, Hi);
6111     break;
6112   }
6113
6114   case ISD::SRA: {
6115     // If the target wants custom lowering, do so.
6116     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
6117     if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
6118       SDOperand Op = DAG.getNode(ISD::SRA, VT, Node->getOperand(0), ShiftAmt);
6119       Op = TLI.LowerOperation(Op, DAG);
6120       if (Op.Val) {
6121         // Now that the custom expander is done, expand the result, which is
6122         // still VT.
6123         ExpandOp(Op, Lo, Hi);
6124         break;
6125       }
6126     }
6127     
6128     // If we can emit an efficient shift operation, do so now.
6129     if (ExpandShift(ISD::SRA, Node->getOperand(0), ShiftAmt, Lo, Hi))
6130       break;
6131
6132     // If this target supports SRA_PARTS, use it.
6133     TargetLowering::LegalizeAction Action =
6134       TLI.getOperationAction(ISD::SRA_PARTS, NVT);
6135     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6136         Action == TargetLowering::Custom) {
6137       ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
6138       break;
6139     }
6140
6141     // Otherwise, emit a libcall.
6142     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SRA_I64), Node,
6143                        true/*ashr is signed*/, Hi);
6144     break;
6145   }
6146
6147   case ISD::SRL: {
6148     // If the target wants custom lowering, do so.
6149     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
6150     if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
6151       SDOperand Op = DAG.getNode(ISD::SRL, VT, Node->getOperand(0), ShiftAmt);
6152       Op = TLI.LowerOperation(Op, DAG);
6153       if (Op.Val) {
6154         // Now that the custom expander is done, expand the result, which is
6155         // still VT.
6156         ExpandOp(Op, Lo, Hi);
6157         break;
6158       }
6159     }
6160
6161     // If we can emit an efficient shift operation, do so now.
6162     if (ExpandShift(ISD::SRL, Node->getOperand(0), ShiftAmt, Lo, Hi))
6163       break;
6164
6165     // If this target supports SRL_PARTS, use it.
6166     TargetLowering::LegalizeAction Action =
6167       TLI.getOperationAction(ISD::SRL_PARTS, NVT);
6168     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6169         Action == TargetLowering::Custom) {
6170       ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
6171       break;
6172     }
6173
6174     // Otherwise, emit a libcall.
6175     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SRL_I64), Node,
6176                        false/*lshr is unsigned*/, Hi);
6177     break;
6178   }
6179
6180   case ISD::ADD:
6181   case ISD::SUB: {
6182     // If the target wants to custom expand this, let them.
6183     if (TLI.getOperationAction(Node->getOpcode(), VT) ==
6184             TargetLowering::Custom) {
6185       Op = TLI.LowerOperation(Op, DAG);
6186       if (Op.Val) {
6187         ExpandOp(Op, Lo, Hi);
6188         break;
6189       }
6190     }
6191     
6192     // Expand the subcomponents.
6193     SDOperand LHSL, LHSH, RHSL, RHSH;
6194     ExpandOp(Node->getOperand(0), LHSL, LHSH);
6195     ExpandOp(Node->getOperand(1), RHSL, RHSH);
6196     SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
6197     SDOperand LoOps[2], HiOps[3];
6198     LoOps[0] = LHSL;
6199     LoOps[1] = RHSL;
6200     HiOps[0] = LHSH;
6201     HiOps[1] = RHSH;
6202     if (Node->getOpcode() == ISD::ADD) {
6203       Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
6204       HiOps[2] = Lo.getValue(1);
6205       Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
6206     } else {
6207       Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
6208       HiOps[2] = Lo.getValue(1);
6209       Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
6210     }
6211     break;
6212   }
6213     
6214   case ISD::ADDC:
6215   case ISD::SUBC: {
6216     // Expand the subcomponents.
6217     SDOperand LHSL, LHSH, RHSL, RHSH;
6218     ExpandOp(Node->getOperand(0), LHSL, LHSH);
6219     ExpandOp(Node->getOperand(1), RHSL, RHSH);
6220     SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
6221     SDOperand LoOps[2] = { LHSL, RHSL };
6222     SDOperand HiOps[3] = { LHSH, RHSH };
6223     
6224     if (Node->getOpcode() == ISD::ADDC) {
6225       Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
6226       HiOps[2] = Lo.getValue(1);
6227       Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
6228     } else {
6229       Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
6230       HiOps[2] = Lo.getValue(1);
6231       Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
6232     }
6233     // Remember that we legalized the flag.
6234     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Hi.getValue(1)));
6235     break;
6236   }
6237   case ISD::ADDE:
6238   case ISD::SUBE: {
6239     // Expand the subcomponents.
6240     SDOperand LHSL, LHSH, RHSL, RHSH;
6241     ExpandOp(Node->getOperand(0), LHSL, LHSH);
6242     ExpandOp(Node->getOperand(1), RHSL, RHSH);
6243     SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
6244     SDOperand LoOps[3] = { LHSL, RHSL, Node->getOperand(2) };
6245     SDOperand HiOps[3] = { LHSH, RHSH };
6246     
6247     Lo = DAG.getNode(Node->getOpcode(), VTList, LoOps, 3);
6248     HiOps[2] = Lo.getValue(1);
6249     Hi = DAG.getNode(Node->getOpcode(), VTList, HiOps, 3);
6250     
6251     // Remember that we legalized the flag.
6252     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Hi.getValue(1)));
6253     break;
6254   }
6255   case ISD::MUL: {
6256     // If the target wants to custom expand this, let them.
6257     if (TLI.getOperationAction(ISD::MUL, VT) == TargetLowering::Custom) {
6258       SDOperand New = TLI.LowerOperation(Op, DAG);
6259       if (New.Val) {
6260         ExpandOp(New, Lo, Hi);
6261         break;
6262       }
6263     }
6264     
6265     bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, NVT);
6266     bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, NVT);
6267     bool HasSMUL_LOHI = TLI.isOperationLegal(ISD::SMUL_LOHI, NVT);
6268     bool HasUMUL_LOHI = TLI.isOperationLegal(ISD::UMUL_LOHI, NVT);
6269     if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
6270       SDOperand LL, LH, RL, RH;
6271       ExpandOp(Node->getOperand(0), LL, LH);
6272       ExpandOp(Node->getOperand(1), RL, RH);
6273       unsigned BitSize = MVT::getSizeInBits(RH.getValueType());
6274       unsigned LHSSB = DAG.ComputeNumSignBits(Op.getOperand(0));
6275       unsigned RHSSB = DAG.ComputeNumSignBits(Op.getOperand(1));
6276       // FIXME: generalize this to handle other bit sizes
6277       if (LHSSB == 32 && RHSSB == 32 &&
6278           DAG.MaskedValueIsZero(Op.getOperand(0), 0xFFFFFFFF00000000ULL) &&
6279           DAG.MaskedValueIsZero(Op.getOperand(1), 0xFFFFFFFF00000000ULL)) {
6280         // The inputs are both zero-extended.
6281         if (HasUMUL_LOHI) {
6282           // We can emit a umul_lohi.
6283           Lo = DAG.getNode(ISD::UMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
6284           Hi = SDOperand(Lo.Val, 1);
6285           break;
6286         }
6287         if (HasMULHU) {
6288           // We can emit a mulhu+mul.
6289           Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
6290           Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
6291           break;
6292         }
6293       }
6294       if (LHSSB > BitSize && RHSSB > BitSize) {
6295         // The input values are both sign-extended.
6296         if (HasSMUL_LOHI) {
6297           // We can emit a smul_lohi.
6298           Lo = DAG.getNode(ISD::SMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
6299           Hi = SDOperand(Lo.Val, 1);
6300           break;
6301         }
6302         if (HasMULHS) {
6303           // We can emit a mulhs+mul.
6304           Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
6305           Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
6306           break;
6307         }
6308       }
6309       if (HasUMUL_LOHI) {
6310         // Lo,Hi = umul LHS, RHS.
6311         SDOperand UMulLOHI = DAG.getNode(ISD::UMUL_LOHI,
6312                                          DAG.getVTList(NVT, NVT), LL, RL);
6313         Lo = UMulLOHI;
6314         Hi = UMulLOHI.getValue(1);
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       if (HasMULHU) {
6322         Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
6323         Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
6324         RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
6325         LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
6326         Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
6327         Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
6328         break;
6329       }
6330     }
6331
6332     // If nothing else, we can make a libcall.
6333     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::MUL_I64), Node,
6334                        false/*sign irrelevant*/, Hi);
6335     break;
6336   }
6337   case ISD::SDIV:
6338     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SDIV_I64), Node, true, Hi);
6339     break;
6340   case ISD::UDIV:
6341     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::UDIV_I64), Node, true, Hi);
6342     break;
6343   case ISD::SREM:
6344     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SREM_I64), Node, true, Hi);
6345     break;
6346   case ISD::UREM:
6347     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::UREM_I64), Node, true, Hi);
6348     break;
6349
6350   case ISD::FADD:
6351     Lo = ExpandLibCall(TLI.getLibcallName(GetFPLibCall(VT, RTLIB::ADD_F32,
6352                                                        RTLIB::ADD_F64,
6353                                                        RTLIB::ADD_F80,
6354                                                        RTLIB::ADD_PPCF128)),
6355                        Node, false, Hi);
6356     break;
6357   case ISD::FSUB:
6358     Lo = ExpandLibCall(TLI.getLibcallName(GetFPLibCall(VT, RTLIB::SUB_F32,
6359                                                        RTLIB::SUB_F64,
6360                                                        RTLIB::SUB_F80,
6361                                                        RTLIB::SUB_PPCF128)),
6362                        Node, false, Hi);
6363     break;
6364   case ISD::FMUL:
6365     Lo = ExpandLibCall(TLI.getLibcallName(GetFPLibCall(VT, RTLIB::MUL_F32,
6366                                                        RTLIB::MUL_F64,
6367                                                        RTLIB::MUL_F80,
6368                                                        RTLIB::MUL_PPCF128)),
6369                        Node, false, Hi);
6370     break;
6371   case ISD::FDIV:
6372     Lo = ExpandLibCall(TLI.getLibcallName(GetFPLibCall(VT, RTLIB::DIV_F32,
6373                                                        RTLIB::DIV_F64,
6374                                                        RTLIB::DIV_F80,
6375                                                        RTLIB::DIV_PPCF128)),
6376                        Node, false, Hi);
6377     break;
6378   case ISD::FP_EXTEND:
6379     if (VT == MVT::ppcf128) {
6380       assert(Node->getOperand(0).getValueType()==MVT::f32 ||
6381              Node->getOperand(0).getValueType()==MVT::f64);
6382       const uint64_t zero = 0;
6383       if (Node->getOperand(0).getValueType()==MVT::f32)
6384         Hi = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Node->getOperand(0));
6385       else
6386         Hi = Node->getOperand(0);
6387       Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
6388       break;
6389     }
6390     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::FPEXT_F32_F64), Node, true,Hi);
6391     break;
6392   case ISD::FP_ROUND:
6393     Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::FPROUND_F64_F32),Node,true,Hi);
6394     break;
6395   case ISD::FPOWI:
6396     Lo = ExpandLibCall(TLI.getLibcallName(GetFPLibCall(VT, RTLIB::POWI_F32,
6397                                                        RTLIB::POWI_F64,
6398                                                        RTLIB::POWI_F80,
6399                                                        RTLIB::POWI_PPCF128)),
6400                        Node, false, Hi);
6401     break;
6402   case ISD::FSQRT:
6403   case ISD::FSIN:
6404   case ISD::FCOS: {
6405     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
6406     switch(Node->getOpcode()) {
6407     case ISD::FSQRT:
6408       LC = GetFPLibCall(VT, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
6409                         RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128);
6410       break;
6411     case ISD::FSIN:
6412       LC = GetFPLibCall(VT, RTLIB::SIN_F32, RTLIB::SIN_F64,
6413                         RTLIB::SIN_F80, RTLIB::SIN_PPCF128);
6414       break;
6415     case ISD::FCOS:
6416       LC = GetFPLibCall(VT, RTLIB::COS_F32, RTLIB::COS_F64,
6417                         RTLIB::COS_F80, RTLIB::COS_PPCF128);
6418       break;
6419     default: assert(0 && "Unreachable!");
6420     }
6421     Lo = ExpandLibCall(TLI.getLibcallName(LC), Node, false, Hi);
6422     break;
6423   }
6424   case ISD::FABS: {
6425     if (VT == MVT::ppcf128) {
6426       SDOperand Tmp;
6427       ExpandOp(Node->getOperand(0), Lo, Tmp);
6428       Hi = DAG.getNode(ISD::FABS, NVT, Tmp);
6429       // lo = hi==fabs(hi) ? lo : -lo;
6430       Lo = DAG.getNode(ISD::SELECT_CC, NVT, Hi, Tmp,
6431                     Lo, DAG.getNode(ISD::FNEG, NVT, Lo),
6432                     DAG.getCondCode(ISD::SETEQ));
6433       break;
6434     }
6435     SDOperand Mask = (VT == MVT::f64)
6436       ? DAG.getConstantFP(BitsToDouble(~(1ULL << 63)), VT)
6437       : DAG.getConstantFP(BitsToFloat(~(1U << 31)), VT);
6438     Mask = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask);
6439     Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
6440     Lo = DAG.getNode(ISD::AND, NVT, Lo, Mask);
6441     if (getTypeAction(NVT) == Expand)
6442       ExpandOp(Lo, Lo, Hi);
6443     break;
6444   }
6445   case ISD::FNEG: {
6446     if (VT == MVT::ppcf128) {
6447       ExpandOp(Node->getOperand(0), Lo, Hi);
6448       Lo = DAG.getNode(ISD::FNEG, MVT::f64, Lo);
6449       Hi = DAG.getNode(ISD::FNEG, MVT::f64, Hi);
6450       break;
6451     }
6452     SDOperand Mask = (VT == MVT::f64)
6453       ? DAG.getConstantFP(BitsToDouble(1ULL << 63), VT)
6454       : DAG.getConstantFP(BitsToFloat(1U << 31), VT);
6455     Mask = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask);
6456     Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
6457     Lo = DAG.getNode(ISD::XOR, NVT, Lo, Mask);
6458     if (getTypeAction(NVT) == Expand)
6459       ExpandOp(Lo, Lo, Hi);
6460     break;
6461   }
6462   case ISD::FCOPYSIGN: {
6463     Lo = ExpandFCOPYSIGNToBitwiseOps(Node, NVT, DAG, TLI);
6464     if (getTypeAction(NVT) == Expand)
6465       ExpandOp(Lo, Lo, Hi);
6466     break;
6467   }
6468   case ISD::SINT_TO_FP:
6469   case ISD::UINT_TO_FP: {
6470     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
6471     MVT::ValueType SrcVT = Node->getOperand(0).getValueType();
6472     if (VT == MVT::ppcf128 && SrcVT != MVT::i64) {
6473       static uint64_t zero = 0;
6474       if (isSigned) {
6475         Hi = LegalizeOp(DAG.getNode(ISD::SINT_TO_FP, MVT::f64, 
6476                                     Node->getOperand(0)));
6477         Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
6478       } else {
6479         static uint64_t TwoE32[] = { 0x41f0000000000000LL, 0 };
6480         Hi = LegalizeOp(DAG.getNode(ISD::SINT_TO_FP, MVT::f64, 
6481                                     Node->getOperand(0)));
6482         Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
6483         Hi = DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
6484         // X>=0 ? {(f64)x, 0} : {(f64)x, 0} + 2^32
6485         ExpandOp(DAG.getNode(ISD::SELECT_CC, MVT::ppcf128, Node->getOperand(0),
6486                              DAG.getConstant(0, MVT::i32), 
6487                              DAG.getNode(ISD::FADD, MVT::ppcf128, Hi,
6488                                          DAG.getConstantFP(
6489                                             APFloat(APInt(128, 2, TwoE32)),
6490                                             MVT::ppcf128)),
6491                              Hi,
6492                              DAG.getCondCode(ISD::SETLT)),
6493                  Lo, Hi);
6494       }
6495       break;
6496     }
6497     if (VT == MVT::ppcf128 && SrcVT == MVT::i64 && !isSigned) {
6498       // si64->ppcf128 done by libcall, below
6499       static uint64_t TwoE64[] = { 0x43f0000000000000LL, 0 };
6500       ExpandOp(DAG.getNode(ISD::SINT_TO_FP, MVT::ppcf128, Node->getOperand(0)),
6501                Lo, Hi);
6502       Hi = DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
6503       // x>=0 ? (ppcf128)(i64)x : (ppcf128)(i64)x + 2^64
6504       ExpandOp(DAG.getNode(ISD::SELECT_CC, MVT::ppcf128, Node->getOperand(0),
6505                            DAG.getConstant(0, MVT::i64), 
6506                            DAG.getNode(ISD::FADD, MVT::ppcf128, Hi,
6507                                        DAG.getConstantFP(
6508                                           APFloat(APInt(128, 2, TwoE64)),
6509                                           MVT::ppcf128)),
6510                            Hi,
6511                            DAG.getCondCode(ISD::SETLT)),
6512                Lo, Hi);
6513       break;
6514     }
6515     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
6516     if (Node->getOperand(0).getValueType() == MVT::i64) {
6517       if (VT == MVT::f32)
6518         LC = isSigned ? RTLIB::SINTTOFP_I64_F32 : RTLIB::UINTTOFP_I64_F32;
6519       else if (VT == MVT::f64)
6520         LC = isSigned ? RTLIB::SINTTOFP_I64_F64 : RTLIB::UINTTOFP_I64_F64;
6521       else if (VT == MVT::f80) {
6522         assert(isSigned);
6523         LC = RTLIB::SINTTOFP_I64_F80;
6524       }
6525       else if (VT == MVT::ppcf128) {
6526         assert(isSigned);
6527         LC = RTLIB::SINTTOFP_I64_PPCF128;
6528       }
6529     } else {
6530       if (VT == MVT::f32)
6531         LC = isSigned ? RTLIB::SINTTOFP_I32_F32 : RTLIB::UINTTOFP_I32_F32;
6532       else
6533         LC = isSigned ? RTLIB::SINTTOFP_I32_F64 : RTLIB::UINTTOFP_I32_F64;
6534     }
6535
6536     // Promote the operand if needed.
6537     if (getTypeAction(SrcVT) == Promote) {
6538       SDOperand Tmp = PromoteOp(Node->getOperand(0));
6539       Tmp = isSigned
6540         ? DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp.getValueType(), Tmp,
6541                       DAG.getValueType(SrcVT))
6542         : DAG.getZeroExtendInReg(Tmp, SrcVT);
6543       Node = DAG.UpdateNodeOperands(Op, Tmp).Val;
6544     }
6545
6546     const char *LibCall = TLI.getLibcallName(LC);
6547     if (LibCall)
6548       Lo = ExpandLibCall(TLI.getLibcallName(LC), Node, isSigned, Hi);
6549     else  {
6550       Lo = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, VT,
6551                          Node->getOperand(0));
6552       if (getTypeAction(Lo.getValueType()) == Expand)
6553         ExpandOp(Lo, Lo, Hi);
6554     }
6555     break;
6556   }
6557   }
6558
6559   // Make sure the resultant values have been legalized themselves, unless this
6560   // is a type that requires multi-step expansion.
6561   if (getTypeAction(NVT) != Expand && NVT != MVT::isVoid) {
6562     Lo = LegalizeOp(Lo);
6563     if (Hi.Val)
6564       // Don't legalize the high part if it is expanded to a single node.
6565       Hi = LegalizeOp(Hi);
6566   }
6567
6568   // Remember in a map if the values will be reused later.
6569   bool isNew = ExpandedNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi)));
6570   assert(isNew && "Value already expanded?!?");
6571 }
6572
6573 /// SplitVectorOp - Given an operand of vector type, break it down into
6574 /// two smaller values, still of vector type.
6575 void SelectionDAGLegalize::SplitVectorOp(SDOperand Op, SDOperand &Lo,
6576                                          SDOperand &Hi) {
6577   assert(MVT::isVector(Op.getValueType()) && "Cannot split non-vector type!");
6578   SDNode *Node = Op.Val;
6579   unsigned NumElements = MVT::getVectorNumElements(Op.getValueType());
6580   assert(NumElements > 1 && "Cannot split a single element vector!");
6581
6582   MVT::ValueType NewEltVT = MVT::getVectorElementType(Op.getValueType());
6583
6584   unsigned NewNumElts_Lo = 1 << Log2_32(NumElements-1);
6585   unsigned NewNumElts_Hi = NumElements - NewNumElts_Lo;
6586
6587   MVT::ValueType NewVT_Lo = MVT::getVectorType(NewEltVT, NewNumElts_Lo);
6588   MVT::ValueType NewVT_Hi = MVT::getVectorType(NewEltVT, NewNumElts_Hi);
6589
6590   // See if we already split it.
6591   std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
6592     = SplitNodes.find(Op);
6593   if (I != SplitNodes.end()) {
6594     Lo = I->second.first;
6595     Hi = I->second.second;
6596     return;
6597   }
6598   
6599   switch (Node->getOpcode()) {
6600   default: 
6601 #ifndef NDEBUG
6602     Node->dump(&DAG);
6603 #endif
6604     assert(0 && "Unhandled operation in SplitVectorOp!");
6605   case ISD::UNDEF:
6606     Lo = DAG.getNode(ISD::UNDEF, NewVT_Lo);
6607     Hi = DAG.getNode(ISD::UNDEF, NewVT_Hi);
6608     break;
6609   case ISD::BUILD_PAIR:
6610     Lo = Node->getOperand(0);
6611     Hi = Node->getOperand(1);
6612     break;
6613   case ISD::INSERT_VECTOR_ELT: {
6614     SplitVectorOp(Node->getOperand(0), Lo, Hi);
6615     unsigned Index = cast<ConstantSDNode>(Node->getOperand(2))->getValue();
6616     SDOperand ScalarOp = Node->getOperand(1);
6617     if (Index < NewNumElts_Lo)
6618       Lo = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT_Lo, Lo, ScalarOp,
6619                        DAG.getConstant(Index, TLI.getPointerTy()));
6620     else
6621       Hi = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT_Hi, Hi, ScalarOp,
6622                        DAG.getConstant(Index - NewNumElts_Lo,
6623                                        TLI.getPointerTy()));
6624     break;
6625   }
6626   case ISD::VECTOR_SHUFFLE: {
6627     // Build the low part.
6628     SDOperand Mask = Node->getOperand(2);
6629     SmallVector<SDOperand, 8> Ops;
6630     MVT::ValueType PtrVT = TLI.getPointerTy();
6631     
6632     // Insert all of the elements from the input that are needed.  We use 
6633     // buildvector of extractelement here because the input vectors will have
6634     // to be legalized, so this makes the code simpler.
6635     for (unsigned i = 0; i != NewNumElts_Lo; ++i) {
6636       unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getValue();
6637       SDOperand InVec = Node->getOperand(0);
6638       if (Idx >= NumElements) {
6639         InVec = Node->getOperand(1);
6640         Idx -= NumElements;
6641       }
6642       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, NewEltVT, InVec,
6643                                 DAG.getConstant(Idx, PtrVT)));
6644     }
6645     Lo = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Lo, &Ops[0], Ops.size());
6646     Ops.clear();
6647     
6648     for (unsigned i = NewNumElts_Lo; i != NumElements; ++i) {
6649       unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getValue();
6650       SDOperand InVec = Node->getOperand(0);
6651       if (Idx >= NumElements) {
6652         InVec = Node->getOperand(1);
6653         Idx -= NumElements;
6654       }
6655       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, NewEltVT, InVec,
6656                                 DAG.getConstant(Idx, PtrVT)));
6657     }
6658     Hi = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Lo, &Ops[0], Ops.size());
6659     break;
6660   }
6661   case ISD::BUILD_VECTOR: {
6662     SmallVector<SDOperand, 8> LoOps(Node->op_begin(), 
6663                                     Node->op_begin()+NewNumElts_Lo);
6664     Lo = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Lo, &LoOps[0], LoOps.size());
6665
6666     SmallVector<SDOperand, 8> HiOps(Node->op_begin()+NewNumElts_Lo, 
6667                                     Node->op_end());
6668     Hi = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Hi, &HiOps[0], HiOps.size());
6669     break;
6670   }
6671   case ISD::CONCAT_VECTORS: {
6672     // FIXME: Handle non-power-of-two vectors?
6673     unsigned NewNumSubvectors = Node->getNumOperands() / 2;
6674     if (NewNumSubvectors == 1) {
6675       Lo = Node->getOperand(0);
6676       Hi = Node->getOperand(1);
6677     } else {
6678       SmallVector<SDOperand, 8> LoOps(Node->op_begin(), 
6679                                       Node->op_begin()+NewNumSubvectors);
6680       Lo = DAG.getNode(ISD::CONCAT_VECTORS, NewVT_Lo, &LoOps[0], LoOps.size());
6681
6682       SmallVector<SDOperand, 8> HiOps(Node->op_begin()+NewNumSubvectors, 
6683                                       Node->op_end());
6684       Hi = DAG.getNode(ISD::CONCAT_VECTORS, NewVT_Hi, &HiOps[0], HiOps.size());
6685     }
6686     break;
6687   }
6688   case ISD::SELECT: {
6689     SDOperand Cond = Node->getOperand(0);
6690
6691     SDOperand LL, LH, RL, RH;
6692     SplitVectorOp(Node->getOperand(1), LL, LH);
6693     SplitVectorOp(Node->getOperand(2), RL, RH);
6694
6695     if (MVT::isVector(Cond.getValueType())) {
6696       // Handle a vector merge.
6697       SDOperand CL, CH;
6698       SplitVectorOp(Cond, CL, CH);
6699       Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, CL, LL, RL);
6700       Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, CH, LH, RH);
6701     } else {
6702       // Handle a simple select with vector operands.
6703       Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, Cond, LL, RL);
6704       Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, Cond, LH, RH);
6705     }
6706     break;
6707   }
6708   case ISD::ADD:
6709   case ISD::SUB:
6710   case ISD::MUL:
6711   case ISD::FADD:
6712   case ISD::FSUB:
6713   case ISD::FMUL:
6714   case ISD::SDIV:
6715   case ISD::UDIV:
6716   case ISD::FDIV:
6717   case ISD::FPOW:
6718   case ISD::AND:
6719   case ISD::OR:
6720   case ISD::XOR:
6721   case ISD::UREM:
6722   case ISD::SREM:
6723   case ISD::FREM: {
6724     SDOperand LL, LH, RL, RH;
6725     SplitVectorOp(Node->getOperand(0), LL, LH);
6726     SplitVectorOp(Node->getOperand(1), RL, RH);
6727     
6728     Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, LL, RL);
6729     Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, LH, RH);
6730     break;
6731   }
6732   case ISD::FPOWI: {
6733     SDOperand L, H;
6734     SplitVectorOp(Node->getOperand(0), L, H);
6735
6736     Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, L, Node->getOperand(1));
6737     Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, H, Node->getOperand(1));
6738     break;
6739   }
6740   case ISD::CTTZ:
6741   case ISD::CTLZ:
6742   case ISD::CTPOP:
6743   case ISD::FNEG:
6744   case ISD::FABS:
6745   case ISD::FSQRT:
6746   case ISD::FSIN:
6747   case ISD::FCOS:
6748   case ISD::FP_TO_SINT:
6749   case ISD::FP_TO_UINT:
6750   case ISD::SINT_TO_FP:
6751   case ISD::UINT_TO_FP: {
6752     SDOperand L, H;
6753     SplitVectorOp(Node->getOperand(0), L, H);
6754
6755     Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, L);
6756     Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, H);
6757     break;
6758   }
6759   case ISD::LOAD: {
6760     LoadSDNode *LD = cast<LoadSDNode>(Node);
6761     SDOperand Ch = LD->getChain();
6762     SDOperand Ptr = LD->getBasePtr();
6763     const Value *SV = LD->getSrcValue();
6764     int SVOffset = LD->getSrcValueOffset();
6765     unsigned Alignment = LD->getAlignment();
6766     bool isVolatile = LD->isVolatile();
6767
6768     Lo = DAG.getLoad(NewVT_Lo, Ch, Ptr, SV, SVOffset, isVolatile, Alignment);
6769     unsigned IncrementSize = NewNumElts_Lo * MVT::getSizeInBits(NewEltVT)/8;
6770     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
6771                       DAG.getIntPtrConstant(IncrementSize));
6772     SVOffset += IncrementSize;
6773     Alignment = MinAlign(Alignment, IncrementSize);
6774     Hi = DAG.getLoad(NewVT_Hi, Ch, Ptr, SV, SVOffset, isVolatile, Alignment);
6775     
6776     // Build a factor node to remember that this load is independent of the
6777     // other one.
6778     SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
6779                                Hi.getValue(1));
6780     
6781     // Remember that we legalized the chain.
6782     AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
6783     break;
6784   }
6785   case ISD::BIT_CONVERT: {
6786     // We know the result is a vector.  The input may be either a vector or a
6787     // scalar value.
6788     SDOperand InOp = Node->getOperand(0);
6789     if (!MVT::isVector(InOp.getValueType()) ||
6790         MVT::getVectorNumElements(InOp.getValueType()) == 1) {
6791       // The input is a scalar or single-element vector.
6792       // Lower to a store/load so that it can be split.
6793       // FIXME: this could be improved probably.
6794       SDOperand Ptr = DAG.CreateStackTemporary(InOp.getValueType());
6795       FrameIndexSDNode *FI = cast<FrameIndexSDNode>(Ptr.Val);
6796
6797       SDOperand St = DAG.getStore(DAG.getEntryNode(),
6798                                   InOp, Ptr,
6799                                   PseudoSourceValue::getFixedStack(),
6800                                   FI->getIndex());
6801       InOp = DAG.getLoad(Op.getValueType(), St, Ptr,
6802                          PseudoSourceValue::getFixedStack(),
6803                          FI->getIndex());
6804     }
6805     // Split the vector and convert each of the pieces now.
6806     SplitVectorOp(InOp, Lo, Hi);
6807     Lo = DAG.getNode(ISD::BIT_CONVERT, NewVT_Lo, Lo);
6808     Hi = DAG.getNode(ISD::BIT_CONVERT, NewVT_Hi, Hi);
6809     break;
6810   }
6811   }
6812       
6813   // Remember in a map if the values will be reused later.
6814   bool isNew = 
6815     SplitNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
6816   assert(isNew && "Value already split?!?");
6817 }
6818
6819
6820 /// ScalarizeVectorOp - Given an operand of single-element vector type
6821 /// (e.g. v1f32), convert it into the equivalent operation that returns a
6822 /// scalar (e.g. f32) value.
6823 SDOperand SelectionDAGLegalize::ScalarizeVectorOp(SDOperand Op) {
6824   assert(MVT::isVector(Op.getValueType()) &&
6825          "Bad ScalarizeVectorOp invocation!");
6826   SDNode *Node = Op.Val;
6827   MVT::ValueType NewVT = MVT::getVectorElementType(Op.getValueType());
6828   assert(MVT::getVectorNumElements(Op.getValueType()) == 1);
6829   
6830   // See if we already scalarized it.
6831   std::map<SDOperand, SDOperand>::iterator I = ScalarizedNodes.find(Op);
6832   if (I != ScalarizedNodes.end()) return I->second;
6833   
6834   SDOperand Result;
6835   switch (Node->getOpcode()) {
6836   default: 
6837 #ifndef NDEBUG
6838     Node->dump(&DAG); cerr << "\n";
6839 #endif
6840     assert(0 && "Unknown vector operation in ScalarizeVectorOp!");
6841   case ISD::ADD:
6842   case ISD::FADD:
6843   case ISD::SUB:
6844   case ISD::FSUB:
6845   case ISD::MUL:
6846   case ISD::FMUL:
6847   case ISD::SDIV:
6848   case ISD::UDIV:
6849   case ISD::FDIV:
6850   case ISD::SREM:
6851   case ISD::UREM:
6852   case ISD::FREM:
6853   case ISD::FPOW:
6854   case ISD::AND:
6855   case ISD::OR:
6856   case ISD::XOR:
6857     Result = DAG.getNode(Node->getOpcode(),
6858                          NewVT, 
6859                          ScalarizeVectorOp(Node->getOperand(0)),
6860                          ScalarizeVectorOp(Node->getOperand(1)));
6861     break;
6862   case ISD::FNEG:
6863   case ISD::FABS:
6864   case ISD::FSQRT:
6865   case ISD::FSIN:
6866   case ISD::FCOS:
6867     Result = DAG.getNode(Node->getOpcode(),
6868                          NewVT, 
6869                          ScalarizeVectorOp(Node->getOperand(0)));
6870     break;
6871   case ISD::FPOWI:
6872     Result = DAG.getNode(Node->getOpcode(),
6873                          NewVT, 
6874                          ScalarizeVectorOp(Node->getOperand(0)),
6875                          Node->getOperand(1));
6876     break;
6877   case ISD::LOAD: {
6878     LoadSDNode *LD = cast<LoadSDNode>(Node);
6879     SDOperand Ch = LegalizeOp(LD->getChain());     // Legalize the chain.
6880     SDOperand Ptr = LegalizeOp(LD->getBasePtr());  // Legalize the pointer.
6881     
6882     const Value *SV = LD->getSrcValue();
6883     int SVOffset = LD->getSrcValueOffset();
6884     Result = DAG.getLoad(NewVT, Ch, Ptr, SV, SVOffset,
6885                          LD->isVolatile(), LD->getAlignment());
6886
6887     // Remember that we legalized the chain.
6888     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
6889     break;
6890   }
6891   case ISD::BUILD_VECTOR:
6892     Result = Node->getOperand(0);
6893     break;
6894   case ISD::INSERT_VECTOR_ELT:
6895     // Returning the inserted scalar element.
6896     Result = Node->getOperand(1);
6897     break;
6898   case ISD::CONCAT_VECTORS:
6899     assert(Node->getOperand(0).getValueType() == NewVT &&
6900            "Concat of non-legal vectors not yet supported!");
6901     Result = Node->getOperand(0);
6902     break;
6903   case ISD::VECTOR_SHUFFLE: {
6904     // Figure out if the scalar is the LHS or RHS and return it.
6905     SDOperand EltNum = Node->getOperand(2).getOperand(0);
6906     if (cast<ConstantSDNode>(EltNum)->getValue())
6907       Result = ScalarizeVectorOp(Node->getOperand(1));
6908     else
6909       Result = ScalarizeVectorOp(Node->getOperand(0));
6910     break;
6911   }
6912   case ISD::EXTRACT_SUBVECTOR:
6913     Result = Node->getOperand(0);
6914     assert(Result.getValueType() == NewVT);
6915     break;
6916   case ISD::BIT_CONVERT:
6917     Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, Op.getOperand(0));
6918     break;
6919   case ISD::SELECT:
6920     Result = DAG.getNode(ISD::SELECT, NewVT, Op.getOperand(0),
6921                          ScalarizeVectorOp(Op.getOperand(1)),
6922                          ScalarizeVectorOp(Op.getOperand(2)));
6923     break;
6924   }
6925
6926   if (TLI.isTypeLegal(NewVT))
6927     Result = LegalizeOp(Result);
6928   bool isNew = ScalarizedNodes.insert(std::make_pair(Op, Result)).second;
6929   assert(isNew && "Value already scalarized?");
6930   return Result;
6931 }
6932
6933
6934 // SelectionDAG::Legalize - This is the entry point for the file.
6935 //
6936 void SelectionDAG::Legalize() {
6937   if (ViewLegalizeDAGs) viewGraph();
6938
6939   /// run - This is the main entry point to this class.
6940   ///
6941   SelectionDAGLegalize(*this).LegalizeDAG();
6942 }
6943