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