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