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