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