Implement BR_CC and BRTWOWAY_CC. This allows the removal of a rather nasty
[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/MachineConstantPool.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/Target/TargetLowering.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Target/TargetOptions.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include <iostream>
24 #include <set>
25 using namespace llvm;
26
27 //===----------------------------------------------------------------------===//
28 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
29 /// hacks on it until the target machine can handle it.  This involves
30 /// eliminating value sizes the machine cannot handle (promoting small sizes to
31 /// large sizes or splitting up large values into small values) as well as
32 /// eliminating operations the machine cannot handle.
33 ///
34 /// This code also does a small amount of optimization and recognition of idioms
35 /// as part of its processing.  For example, if a target does not support a
36 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
37 /// will attempt merge setcc and brc instructions into brcc's.
38 ///
39 namespace {
40 class SelectionDAGLegalize {
41   TargetLowering &TLI;
42   SelectionDAG &DAG;
43
44   /// LegalizeAction - This enum indicates what action we should take for each
45   /// value type the can occur in the program.
46   enum LegalizeAction {
47     Legal,            // The target natively supports this value type.
48     Promote,          // This should be promoted to the next larger type.
49     Expand,           // This integer type should be broken into smaller pieces.
50   };
51
52   /// ValueTypeActions - This is a bitvector that contains two bits for each
53   /// value type, where the two bits correspond to the LegalizeAction enum.
54   /// This can be queried with "getTypeAction(VT)".
55   unsigned ValueTypeActions;
56
57   /// NeedsAnotherIteration - This is set when we expand a large integer
58   /// operation into smaller integer operations, but the smaller operations are
59   /// not set.  This occurs only rarely in practice, for targets that don't have
60   /// 32-bit or larger integer registers.
61   bool NeedsAnotherIteration;
62
63   /// LegalizedNodes - For nodes that are of legal width, and that have more
64   /// than one use, this map indicates what regularized operand to use.  This
65   /// allows us to avoid legalizing the same thing more than once.
66   std::map<SDOperand, SDOperand> LegalizedNodes;
67
68   /// PromotedNodes - For nodes that are below legal width, and that have more
69   /// than one use, this map indicates what promoted value to use.  This allows
70   /// us to avoid promoting the same thing more than once.
71   std::map<SDOperand, SDOperand> PromotedNodes;
72
73   /// ExpandedNodes - For nodes that need to be expanded, and which have more
74   /// than one use, this map indicates which which operands are the expanded
75   /// version of the input.  This allows us to avoid expanding the same node
76   /// more than once.
77   std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
78
79   void AddLegalizedOperand(SDOperand From, SDOperand To) {
80     bool isNew = LegalizedNodes.insert(std::make_pair(From, To)).second;
81     assert(isNew && "Got into the map somehow?");
82   }
83   void AddPromotedOperand(SDOperand From, SDOperand To) {
84     bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
85     assert(isNew && "Got into the map somehow?");
86   }
87
88 public:
89
90   SelectionDAGLegalize(SelectionDAG &DAG);
91
92   /// Run - While there is still lowering to do, perform a pass over the DAG.
93   /// Most regularization can be done in a single pass, but targets that require
94   /// large values to be split into registers multiple times (e.g. i64 -> 4x
95   /// i16) require iteration for these values (the first iteration will demote
96   /// to i32, the second will demote to i16).
97   void Run() {
98     do {
99       NeedsAnotherIteration = false;
100       LegalizeDAG();
101     } while (NeedsAnotherIteration);
102   }
103
104   /// getTypeAction - Return how we should legalize values of this type, either
105   /// it is already legal or we need to expand it into multiple registers of
106   /// smaller integer type, or we need to promote it to a larger type.
107   LegalizeAction getTypeAction(MVT::ValueType VT) const {
108     return (LegalizeAction)((ValueTypeActions >> (2*VT)) & 3);
109   }
110
111   /// isTypeLegal - Return true if this type is legal on this target.
112   ///
113   bool isTypeLegal(MVT::ValueType VT) const {
114     return getTypeAction(VT) == Legal;
115   }
116
117 private:
118   void LegalizeDAG();
119
120   SDOperand LegalizeOp(SDOperand O);
121   void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
122   SDOperand PromoteOp(SDOperand O);
123
124   SDOperand ExpandLibCall(const char *Name, SDNode *Node,
125                           SDOperand &Hi);
126   SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
127                           SDOperand Source);
128
129   SDOperand ExpandLegalUINT_TO_FP(SDOperand LegalOp, MVT::ValueType DestVT);
130   SDOperand PromoteLegalINT_TO_FP(SDOperand LegalOp, MVT::ValueType DestVT,
131                                   bool isSigned);
132   SDOperand PromoteLegalFP_TO_INT(SDOperand LegalOp, MVT::ValueType DestVT,
133                                   bool isSigned);
134
135   bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
136                    SDOperand &Lo, SDOperand &Hi);
137   void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
138                         SDOperand &Lo, SDOperand &Hi);
139   void ExpandByParts(unsigned NodeOp, SDOperand LHS, SDOperand RHS,
140                      SDOperand &Lo, SDOperand &Hi);
141
142   void SpliceCallInto(const SDOperand &CallResult, SDNode *OutChain);
143
144   SDOperand getIntPtrConstant(uint64_t Val) {
145     return DAG.getConstant(Val, TLI.getPointerTy());
146   }
147 };
148 }
149
150
151 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
152   : TLI(dag.getTargetLoweringInfo()), DAG(dag),
153     ValueTypeActions(TLI.getValueTypeActions()) {
154   assert(MVT::LAST_VALUETYPE <= 16 &&
155          "Too many value types for ValueTypeActions to hold!");
156 }
157
158 /// ExpandLegalUINT_TO_FP - This function is responsible for legalizing a
159 /// UINT_TO_FP operation of the specified operand when the target requests that
160 /// we expand it.  At this point, we know that the result and operand types are
161 /// legal for the target.
162 SDOperand SelectionDAGLegalize::ExpandLegalUINT_TO_FP(SDOperand Op0,
163                                                       MVT::ValueType DestVT) {
164   SDOperand Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
165
166   SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Op0,
167                                    DAG.getConstant(0, Op0.getValueType()),
168                                    ISD::SETLT);
169   SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
170   SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
171                                     SignSet, Four, Zero);
172
173   // If the sign bit of the integer is set, the large number will be treated as
174   // a negative number.  To counteract this, the dynamic code adds an offset
175   // depending on the data type.
176   uint64_t FF;
177   switch (Op0.getValueType()) {
178   default: assert(0 && "Unsupported integer type!");
179   case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
180   case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
181   case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
182   case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
183   }
184   if (TLI.isLittleEndian()) FF <<= 32;
185   static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
186
187   MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
188   SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(FudgeFactor),
189                                         TLI.getPointerTy());
190   CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
191   SDOperand FudgeInReg;
192   if (DestVT == MVT::f32)
193     FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
194                              DAG.getSrcValue(NULL));
195   else {
196     assert(DestVT == MVT::f64 && "Unexpected conversion");
197     FudgeInReg = LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, MVT::f64,
198                                            DAG.getEntryNode(), CPIdx,
199                                            DAG.getSrcValue(NULL), MVT::f32));
200   }
201
202   NeedsAnotherIteration = true;
203   return DAG.getNode(ISD::ADD, DestVT, Tmp1, FudgeInReg);
204 }
205
206 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
207 /// *INT_TO_FP operation of the specified operand when the target requests that
208 /// we promote it.  At this point, we know that the result and operand types are
209 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
210 /// operation that takes a larger input.
211 SDOperand SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDOperand LegalOp,
212                                                       MVT::ValueType DestVT,
213                                                       bool isSigned) {
214   // First step, figure out the appropriate *INT_TO_FP operation to use.
215   MVT::ValueType NewInTy = LegalOp.getValueType();
216
217   unsigned OpToUse = 0;
218
219   // Scan for the appropriate larger type to use.
220   while (1) {
221     NewInTy = (MVT::ValueType)(NewInTy+1);
222     assert(MVT::isInteger(NewInTy) && "Ran out of possibilities!");
223
224     // If the target supports SINT_TO_FP of this type, use it.
225     switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
226       default: break;
227       case TargetLowering::Legal:
228         if (!TLI.hasNativeSupportFor(NewInTy))
229           break;  // Can't use this datatype.
230         // FALL THROUGH.
231       case TargetLowering::Custom:
232         OpToUse = ISD::SINT_TO_FP;
233         break;
234     }
235     if (OpToUse) break;
236     if (isSigned) continue;
237
238     // If the target supports UINT_TO_FP of this type, use it.
239     switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
240       default: break;
241       case TargetLowering::Legal:
242         if (!TLI.hasNativeSupportFor(NewInTy))
243           break;  // Can't use this datatype.
244         // FALL THROUGH.
245       case TargetLowering::Custom:
246         OpToUse = ISD::UINT_TO_FP;
247         break;
248     }
249     if (OpToUse) break;
250
251     // Otherwise, try a larger type.
252   }
253
254   // Make sure to legalize any nodes we create here in the next pass.
255   NeedsAnotherIteration = true;
256
257   // Okay, we found the operation and type to use.  Zero extend our input to the
258   // desired type then run the operation on it.
259   return DAG.getNode(OpToUse, DestVT,
260                      DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
261                                  NewInTy, LegalOp));
262 }
263
264 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
265 /// FP_TO_*INT operation of the specified operand when the target requests that
266 /// we promote it.  At this point, we know that the result and operand types are
267 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
268 /// operation that returns a larger result.
269 SDOperand SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDOperand LegalOp,
270                                                       MVT::ValueType DestVT,
271                                                       bool isSigned) {
272   // First step, figure out the appropriate FP_TO*INT operation to use.
273   MVT::ValueType NewOutTy = DestVT;
274
275   unsigned OpToUse = 0;
276
277   // Scan for the appropriate larger type to use.
278   while (1) {
279     NewOutTy = (MVT::ValueType)(NewOutTy+1);
280     assert(MVT::isInteger(NewOutTy) && "Ran out of possibilities!");
281
282     // If the target supports FP_TO_SINT returning this type, use it.
283     switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
284     default: break;
285     case TargetLowering::Legal:
286       if (!TLI.hasNativeSupportFor(NewOutTy))
287         break;  // Can't use this datatype.
288       // FALL THROUGH.
289     case TargetLowering::Custom:
290       OpToUse = ISD::FP_TO_SINT;
291       break;
292     }
293     if (OpToUse) break;
294
295     // If the target supports FP_TO_UINT of this type, use it.
296     switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
297     default: break;
298     case TargetLowering::Legal:
299       if (!TLI.hasNativeSupportFor(NewOutTy))
300         break;  // Can't use this datatype.
301       // FALL THROUGH.
302     case TargetLowering::Custom:
303       OpToUse = ISD::FP_TO_UINT;
304       break;
305     }
306     if (OpToUse) break;
307
308     // Otherwise, try a larger type.
309   }
310
311   // Make sure to legalize any nodes we create here in the next pass.
312   NeedsAnotherIteration = true;
313
314   // Okay, we found the operation and type to use.  Truncate the result of the
315   // extended FP_TO_*INT operation to the desired size.
316   return DAG.getNode(ISD::TRUNCATE, DestVT,
317                      DAG.getNode(OpToUse, NewOutTy, LegalOp));
318 }
319
320
321 void SelectionDAGLegalize::LegalizeDAG() {
322   SDOperand OldRoot = DAG.getRoot();
323   SDOperand NewRoot = LegalizeOp(OldRoot);
324   DAG.setRoot(NewRoot);
325
326   ExpandedNodes.clear();
327   LegalizedNodes.clear();
328   PromotedNodes.clear();
329
330   // Remove dead nodes now.
331   DAG.RemoveDeadNodes(OldRoot.Val);
332 }
333
334 SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
335   assert(getTypeAction(Op.getValueType()) == Legal &&
336          "Caller should expand or promote operands that are not legal!");
337   SDNode *Node = Op.Val;
338
339   // If this operation defines any values that cannot be represented in a
340   // register on this target, make sure to expand or promote them.
341   if (Node->getNumValues() > 1) {
342     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
343       switch (getTypeAction(Node->getValueType(i))) {
344       case Legal: break;  // Nothing to do.
345       case Expand: {
346         SDOperand T1, T2;
347         ExpandOp(Op.getValue(i), T1, T2);
348         assert(LegalizedNodes.count(Op) &&
349                "Expansion didn't add legal operands!");
350         return LegalizedNodes[Op];
351       }
352       case Promote:
353         PromoteOp(Op.getValue(i));
354         assert(LegalizedNodes.count(Op) &&
355                "Expansion didn't add legal operands!");
356         return LegalizedNodes[Op];
357       }
358   }
359
360   // Note that LegalizeOp may be reentered even from single-use nodes, which
361   // means that we always must cache transformed nodes.
362   std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
363   if (I != LegalizedNodes.end()) return I->second;
364
365   SDOperand Tmp1, Tmp2, Tmp3, Tmp4;
366
367   SDOperand Result = Op;
368
369   switch (Node->getOpcode()) {
370   default:
371     if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
372       // If this is a target node, legalize it by legalizing the operands then
373       // passing it through.
374       std::vector<SDOperand> Ops;
375       bool Changed = false;
376       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
377         Ops.push_back(LegalizeOp(Node->getOperand(i)));
378         Changed = Changed || Node->getOperand(i) != Ops.back();
379       }
380       if (Changed)
381         if (Node->getNumValues() == 1)
382           Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
383         else {
384           std::vector<MVT::ValueType> VTs(Node->value_begin(),
385                                           Node->value_end());
386           Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
387         }
388
389       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
390         AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
391       return Result.getValue(Op.ResNo);
392     }
393     // Otherwise this is an unhandled builtin node.  splat.
394     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
395     assert(0 && "Do not know how to legalize this operator!");
396     abort();
397   case ISD::EntryToken:
398   case ISD::FrameIndex:
399   case ISD::GlobalAddress:
400   case ISD::ExternalSymbol:
401   case ISD::ConstantPool:           // Nothing to do.
402     assert(getTypeAction(Node->getValueType(0)) == Legal &&
403            "This must be legal!");
404     break;
405   case ISD::CopyFromReg:
406     Tmp1 = LegalizeOp(Node->getOperand(0));
407     if (Tmp1 != Node->getOperand(0))
408       Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(),
409                                   Node->getValueType(0), Tmp1);
410     else
411       Result = Op.getValue(0);
412
413     // Since CopyFromReg produces two values, make sure to remember that we
414     // legalized both of them.
415     AddLegalizedOperand(Op.getValue(0), Result);
416     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
417     return Result.getValue(Op.ResNo);
418   case ISD::ImplicitDef:
419     Tmp1 = LegalizeOp(Node->getOperand(0));
420     if (Tmp1 != Node->getOperand(0))
421       Result = DAG.getImplicitDef(Tmp1, cast<RegSDNode>(Node)->getReg());
422     break;
423   case ISD::UNDEF: {
424     MVT::ValueType VT = Op.getValueType();
425     switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
426     default: assert(0 && "This action is not supported yet!");
427     case TargetLowering::Expand:
428     case TargetLowering::Promote:
429       if (MVT::isInteger(VT))
430         Result = DAG.getConstant(0, VT);
431       else if (MVT::isFloatingPoint(VT))
432         Result = DAG.getConstantFP(0, VT);
433       else
434         assert(0 && "Unknown value type!");
435       break;
436     case TargetLowering::Legal:
437       break;
438     }
439     break;
440   }
441   case ISD::Constant:
442     // We know we don't need to expand constants here, constants only have one
443     // value and we check that it is fine above.
444
445     // FIXME: Maybe we should handle things like targets that don't support full
446     // 32-bit immediates?
447     break;
448   case ISD::ConstantFP: {
449     // Spill FP immediates to the constant pool if the target cannot directly
450     // codegen them.  Targets often have some immediate values that can be
451     // efficiently generated into an FP register without a load.  We explicitly
452     // leave these constants as ConstantFP nodes for the target to deal with.
453
454     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
455
456     // Check to see if this FP immediate is already legal.
457     bool isLegal = false;
458     for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
459            E = TLI.legal_fpimm_end(); I != E; ++I)
460       if (CFP->isExactlyValue(*I)) {
461         isLegal = true;
462         break;
463       }
464
465     if (!isLegal) {
466       // Otherwise we need to spill the constant to memory.
467       MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
468
469       bool Extend = false;
470
471       // If a FP immediate is precise when represented as a float, we put it
472       // into the constant pool as a float, even if it's is statically typed
473       // as a double.
474       MVT::ValueType VT = CFP->getValueType(0);
475       bool isDouble = VT == MVT::f64;
476       ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
477                                              Type::FloatTy, CFP->getValue());
478       if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
479           // Only do this if the target has a native EXTLOAD instruction from
480           // f32.
481           TLI.getOperationAction(ISD::EXTLOAD,
482                                  MVT::f32) == TargetLowering::Legal) {
483         LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
484         VT = MVT::f32;
485         Extend = true;
486       }
487
488       SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(LLVMC),
489                                             TLI.getPointerTy());
490       if (Extend) {
491         Result = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
492                                 CPIdx, DAG.getSrcValue(NULL), MVT::f32);
493       } else {
494         Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
495                              DAG.getSrcValue(NULL));
496       }
497     }
498     break;
499   }
500   case ISD::TokenFactor: {
501     std::vector<SDOperand> Ops;
502     bool Changed = false;
503     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
504       SDOperand Op = Node->getOperand(i);
505       // Fold single-use TokenFactor nodes into this token factor as we go.
506       // FIXME: This is something that the DAGCombiner should do!!
507       if (Op.getOpcode() == ISD::TokenFactor && Op.hasOneUse()) {
508         Changed = true;
509         for (unsigned j = 0, e = Op.getNumOperands(); j != e; ++j)
510           Ops.push_back(LegalizeOp(Op.getOperand(j)));
511       } else {
512         Ops.push_back(LegalizeOp(Op));  // Legalize the operands
513         Changed |= Ops[i] != Op;
514       }
515     }
516     if (Changed)
517       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
518     break;
519   }
520
521   case ISD::CALLSEQ_START:
522   case ISD::CALLSEQ_END:
523     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
524     // Do not try to legalize the target-specific arguments (#1+)
525     Tmp2 = Node->getOperand(0);
526     if (Tmp1 != Tmp2) {
527       Node->setAdjCallChain(Tmp1);
528
529       // If moving the operand from pointing to Tmp2 dropped its use count to 1,
530       // this will cause the maps used to memoize results to get confused.
531       // Create and add a dummy use, just to increase its use count.  This will
532       // be removed at the end of legalize when dead nodes are removed.
533       if (Tmp2.Val->hasOneUse())
534         DAG.getNode(ISD::PCMARKER, MVT::Other, Tmp2,
535                     DAG.getConstant(0, MVT::i32));
536     }
537     // Note that we do not create new CALLSEQ_DOWN/UP nodes here.  These
538     // nodes are treated specially and are mutated in place.  This makes the dag
539     // legalization process more efficient and also makes libcall insertion
540     // easier.
541     break;
542   case ISD::DYNAMIC_STACKALLOC:
543     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
544     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
545     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
546     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
547         Tmp3 != Node->getOperand(2)) {
548       std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
549       std::vector<SDOperand> Ops;
550       Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
551       Result = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
552     } else
553       Result = Op.getValue(0);
554
555     // Since this op produces two values, make sure to remember that we
556     // legalized both of them.
557     AddLegalizedOperand(SDOperand(Node, 0), Result);
558     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
559     return Result.getValue(Op.ResNo);
560
561   case ISD::TAILCALL:
562   case ISD::CALL: {
563     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
564     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
565
566     bool Changed = false;
567     std::vector<SDOperand> Ops;
568     for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
569       Ops.push_back(LegalizeOp(Node->getOperand(i)));
570       Changed |= Ops.back() != Node->getOperand(i);
571     }
572
573     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) || Changed) {
574       std::vector<MVT::ValueType> RetTyVTs;
575       RetTyVTs.reserve(Node->getNumValues());
576       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
577         RetTyVTs.push_back(Node->getValueType(i));
578       Result = SDOperand(DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops,
579                                      Node->getOpcode() == ISD::TAILCALL), 0);
580     } else {
581       Result = Result.getValue(0);
582     }
583     // Since calls produce multiple values, make sure to remember that we
584     // legalized all of them.
585     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
586       AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
587     return Result.getValue(Op.ResNo);
588   }
589   case ISD::BR:
590     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
591     if (Tmp1 != Node->getOperand(0))
592       Result = DAG.getNode(ISD::BR, MVT::Other, Tmp1, Node->getOperand(1));
593     break;
594
595   case ISD::BRCOND:
596     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
597     
598     switch (getTypeAction(Node->getOperand(1).getValueType())) {
599     case Expand: assert(0 && "It's impossible to expand bools");
600     case Legal:
601       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
602       break;
603     case Promote:
604       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
605       break;
606     }
607       
608     switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {  
609     default: assert(0 && "This action is not supported yet!");
610     case TargetLowering::Expand:
611       // Expand brcond's setcc into its constituent parts and create a BR_CC
612       // Node.
613       if (Tmp2.getOpcode() == ISD::SETCC) {
614         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
615                              Tmp2.getOperand(0), Tmp2.getOperand(1),
616                              Node->getOperand(2));
617       } else {
618         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, 
619                              DAG.getCondCode(ISD::SETNE), Tmp2,
620                              DAG.getConstant(0, Tmp2.getValueType()),
621                              Node->getOperand(2));
622       }
623       break;
624     case TargetLowering::Legal:
625       // Basic block destination (Op#2) is always legal.
626       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
627         Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
628                              Node->getOperand(2));
629         break;
630     }
631     break;
632   case ISD::BR_CC:
633     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
634     
635     if (getTypeAction(Node->getOperand(2).getValueType()) == Legal) {
636       Tmp2 = LegalizeOp(Node->getOperand(2));   // LHS
637       Tmp3 = LegalizeOp(Node->getOperand(3));   // RHS
638       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(2) ||
639           Tmp3 != Node->getOperand(3)) {
640         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Node->getOperand(1),
641                              Tmp2, Tmp3, Node->getOperand(4));
642       }
643       break;
644     } else {
645       Tmp2 = LegalizeOp(DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),
646                                     Node->getOperand(2),  // LHS
647                                     Node->getOperand(3),  // RHS
648                                     Node->getOperand(1)));
649       // If we get a SETCC back from legalizing the SETCC node we just
650       // created, then use its LHS, RHS, and CC directly in creating a new
651       // node.  Otherwise, select between the true and false value based on
652       // comparing the result of the legalized with zero.
653       if (Tmp2.getOpcode() == ISD::SETCC) {
654         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
655                              Tmp2.getOperand(0), Tmp2.getOperand(1),
656                              Node->getOperand(4));
657       } else {
658         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, 
659                              DAG.getCondCode(ISD::SETNE),
660                              Tmp2, DAG.getConstant(0, Tmp2.getValueType()), 
661                              Node->getOperand(4));
662       }
663     }
664     break;
665   case ISD::BRCONDTWOWAY:
666     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
667     switch (getTypeAction(Node->getOperand(1).getValueType())) {
668     case Expand: assert(0 && "It's impossible to expand bools");
669     case Legal:
670       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
671       break;
672     case Promote:
673       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
674       break;
675     }
676     // If this target does not support BRCONDTWOWAY, lower it to a BRCOND/BR
677     // pair.
678     switch (TLI.getOperationAction(ISD::BRCONDTWOWAY, MVT::Other)) {
679     case TargetLowering::Promote:
680     default: assert(0 && "This action is not supported yet!");
681     case TargetLowering::Legal:
682       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
683         std::vector<SDOperand> Ops;
684         Ops.push_back(Tmp1);
685         Ops.push_back(Tmp2);
686         Ops.push_back(Node->getOperand(2));
687         Ops.push_back(Node->getOperand(3));
688         Result = DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops);
689       }
690       break;
691     case TargetLowering::Expand:
692       // If BRTWOWAY_CC is legal for this target, then simply expand this node
693       // to that.  Otherwise, skip BRTWOWAY_CC and expand directly to a
694       // BRCOND/BR pair.
695       if (TLI.getOperationAction(ISD::BRTWOWAY_CC, MVT::Other) == 
696           TargetLowering::Legal) {
697         if (Tmp2.getOpcode() == ISD::SETCC) {
698           Result = DAG.getBR2Way_CC(Tmp1, Tmp2.getOperand(2),
699                                     Tmp2.getOperand(0), Tmp2.getOperand(1),
700                                     Node->getOperand(2), Node->getOperand(3));
701         } else {
702           Result = DAG.getBR2Way_CC(Tmp1, DAG.getCondCode(ISD::SETNE), Tmp2, 
703                                     DAG.getConstant(0, Tmp2.getValueType()),
704                                     Node->getOperand(2), Node->getOperand(3));
705         }
706       } else {
707         Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
708                            Node->getOperand(2));
709         Result = DAG.getNode(ISD::BR, MVT::Other, Result, Node->getOperand(3));
710       }
711       break;
712     }
713     break;
714   case ISD::BRTWOWAY_CC:
715     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
716     if (getTypeAction(Node->getOperand(2).getValueType()) == Legal) {
717       Tmp2 = LegalizeOp(Node->getOperand(2));   // LHS
718       Tmp3 = LegalizeOp(Node->getOperand(3));   // RHS
719       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(2) ||
720           Tmp3 != Node->getOperand(3)) {
721         Result = DAG.getBR2Way_CC(Tmp1, Node->getOperand(1), Tmp2, Tmp3,
722                                   Node->getOperand(4), Node->getOperand(5));
723       }
724       break;
725     } else {
726       Tmp2 = LegalizeOp(DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),
727                                     Node->getOperand(2),  // LHS
728                                     Node->getOperand(3),  // RHS
729                                     Node->getOperand(1)));
730       // If this target does not support BRTWOWAY_CC, lower it to a BRCOND/BR
731       // pair.
732       switch (TLI.getOperationAction(ISD::BRTWOWAY_CC, MVT::Other)) {
733       default: assert(0 && "This action is not supported yet!");
734       case TargetLowering::Legal:
735         // If we get a SETCC back from legalizing the SETCC node we just
736         // created, then use its LHS, RHS, and CC directly in creating a new
737         // node.  Otherwise, select between the true and false value based on
738         // comparing the result of the legalized with zero.
739         if (Tmp2.getOpcode() == ISD::SETCC) {
740           Result = DAG.getBR2Way_CC(Tmp1, Tmp2.getOperand(2),
741                                     Tmp2.getOperand(0), Tmp2.getOperand(1),
742                                     Node->getOperand(4), Node->getOperand(5));
743         } else {
744           Result = DAG.getBR2Way_CC(Tmp1, DAG.getCondCode(ISD::SETNE), Tmp2, 
745                                     DAG.getConstant(0, Tmp2.getValueType()),
746                                     Node->getOperand(4), Node->getOperand(5));
747         }
748         break;
749       case TargetLowering::Expand: 
750         Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
751                              Node->getOperand(4));
752         Result = DAG.getNode(ISD::BR, MVT::Other, Result, Node->getOperand(5));
753         break;
754       }
755     }
756     break;
757   case ISD::LOAD:
758     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
759     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
760
761     if (Tmp1 != Node->getOperand(0) ||
762         Tmp2 != Node->getOperand(1))
763       Result = DAG.getLoad(Node->getValueType(0), Tmp1, Tmp2,
764                            Node->getOperand(2));
765     else
766       Result = SDOperand(Node, 0);
767
768     // Since loads produce two values, make sure to remember that we legalized
769     // both of them.
770     AddLegalizedOperand(SDOperand(Node, 0), Result);
771     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
772     return Result.getValue(Op.ResNo);
773
774   case ISD::EXTLOAD:
775   case ISD::SEXTLOAD:
776   case ISD::ZEXTLOAD: {
777     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
778     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
779
780     MVT::ValueType SrcVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
781     switch (TLI.getOperationAction(Node->getOpcode(), SrcVT)) {
782     default: assert(0 && "This action is not supported yet!");
783     case TargetLowering::Promote:
784       assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
785       Result = DAG.getExtLoad(Node->getOpcode(), Node->getValueType(0),
786                               Tmp1, Tmp2, Node->getOperand(2), MVT::i8);
787       // Since loads produce two values, make sure to remember that we legalized
788       // both of them.
789       AddLegalizedOperand(SDOperand(Node, 0), Result);
790       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
791       return Result.getValue(Op.ResNo);
792
793     case TargetLowering::Legal:
794       if (Tmp1 != Node->getOperand(0) ||
795           Tmp2 != Node->getOperand(1))
796         Result = DAG.getExtLoad(Node->getOpcode(), Node->getValueType(0),
797                                 Tmp1, Tmp2, Node->getOperand(2), SrcVT);
798       else
799         Result = SDOperand(Node, 0);
800
801       // Since loads produce two values, make sure to remember that we legalized
802       // both of them.
803       AddLegalizedOperand(SDOperand(Node, 0), Result);
804       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
805       return Result.getValue(Op.ResNo);
806     case TargetLowering::Expand:
807       //f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
808       if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
809         SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, Node->getOperand(2));
810         Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
811         if (Op.ResNo)
812           return Load.getValue(1);
813         return Result;
814       }
815       assert(Node->getOpcode() != ISD::EXTLOAD &&
816              "EXTLOAD should always be supported!");
817       // Turn the unsupported load into an EXTLOAD followed by an explicit
818       // zero/sign extend inreg.
819       Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
820                               Tmp1, Tmp2, Node->getOperand(2), SrcVT);
821       SDOperand ValRes;
822       if (Node->getOpcode() == ISD::SEXTLOAD)
823         ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
824                              Result, DAG.getValueType(SrcVT));
825       else
826         ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
827       AddLegalizedOperand(SDOperand(Node, 0), ValRes);
828       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
829       if (Op.ResNo)
830         return Result.getValue(1);
831       return ValRes;
832     }
833     assert(0 && "Unreachable");
834   }
835   case ISD::EXTRACT_ELEMENT:
836     // Get both the low and high parts.
837     ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
838     if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
839       Result = Tmp2;  // 1 -> Hi
840     else
841       Result = Tmp1;  // 0 -> Lo
842     break;
843
844   case ISD::CopyToReg:
845     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
846
847     switch (getTypeAction(Node->getOperand(1).getValueType())) {
848     case Legal:
849       // Legalize the incoming value (must be legal).
850       Tmp2 = LegalizeOp(Node->getOperand(1));
851       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
852         Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
853       break;
854     case Promote:
855       Tmp2 = PromoteOp(Node->getOperand(1));
856       Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
857       break;
858     case Expand:
859       SDOperand Lo, Hi;
860       ExpandOp(Node->getOperand(1), Lo, Hi);
861       unsigned Reg = cast<RegSDNode>(Node)->getReg();
862       Lo = DAG.getCopyToReg(Tmp1, Lo, Reg);
863       Hi = DAG.getCopyToReg(Tmp1, Hi, Reg+1);
864       // Note that the copytoreg nodes are independent of each other.
865       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
866       assert(isTypeLegal(Result.getValueType()) &&
867              "Cannot expand multiple times yet (i64 -> i16)");
868       break;
869     }
870     break;
871
872   case ISD::RET:
873     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
874     switch (Node->getNumOperands()) {
875     case 2:  // ret val
876       switch (getTypeAction(Node->getOperand(1).getValueType())) {
877       case Legal:
878         Tmp2 = LegalizeOp(Node->getOperand(1));
879         if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
880           Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
881         break;
882       case Expand: {
883         SDOperand Lo, Hi;
884         ExpandOp(Node->getOperand(1), Lo, Hi);
885         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
886         break;
887       }
888       case Promote:
889         Tmp2 = PromoteOp(Node->getOperand(1));
890         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
891         break;
892       }
893       break;
894     case 1:  // ret void
895       if (Tmp1 != Node->getOperand(0))
896         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1);
897       break;
898     default: { // ret <values>
899       std::vector<SDOperand> NewValues;
900       NewValues.push_back(Tmp1);
901       for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
902         switch (getTypeAction(Node->getOperand(i).getValueType())) {
903         case Legal:
904           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
905           break;
906         case Expand: {
907           SDOperand Lo, Hi;
908           ExpandOp(Node->getOperand(i), Lo, Hi);
909           NewValues.push_back(Lo);
910           NewValues.push_back(Hi);
911           break;
912         }
913         case Promote:
914           assert(0 && "Can't promote multiple return value yet!");
915         }
916       Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
917       break;
918     }
919     }
920     break;
921   case ISD::STORE:
922     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
923     Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
924
925     // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
926     if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
927       if (CFP->getValueType(0) == MVT::f32) {
928         union {
929           unsigned I;
930           float    F;
931         } V;
932         V.F = CFP->getValue();
933         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
934                              DAG.getConstant(V.I, MVT::i32), Tmp2,
935                              Node->getOperand(3));
936       } else {
937         assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
938         union {
939           uint64_t I;
940           double   F;
941         } V;
942         V.F = CFP->getValue();
943         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
944                              DAG.getConstant(V.I, MVT::i64), Tmp2,
945                              Node->getOperand(3));
946       }
947       Node = Result.Val;
948     }
949
950     switch (getTypeAction(Node->getOperand(1).getValueType())) {
951     case Legal: {
952       SDOperand Val = LegalizeOp(Node->getOperand(1));
953       if (Val != Node->getOperand(1) || Tmp1 != Node->getOperand(0) ||
954           Tmp2 != Node->getOperand(2))
955         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Val, Tmp2,
956                              Node->getOperand(3));
957       break;
958     }
959     case Promote:
960       // Truncate the value and store the result.
961       Tmp3 = PromoteOp(Node->getOperand(1));
962       Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
963                            Node->getOperand(3),
964                           DAG.getValueType(Node->getOperand(1).getValueType()));
965       break;
966
967     case Expand:
968       SDOperand Lo, Hi;
969       ExpandOp(Node->getOperand(1), Lo, Hi);
970
971       if (!TLI.isLittleEndian())
972         std::swap(Lo, Hi);
973
974       Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2,
975                        Node->getOperand(3));
976       unsigned IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
977       Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
978                          getIntPtrConstant(IncrementSize));
979       assert(isTypeLegal(Tmp2.getValueType()) &&
980              "Pointers must be legal!");
981       //Again, claiming both parts of the store came form the same Instr
982       Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2,
983                        Node->getOperand(3));
984       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
985       break;
986     }
987     break;
988   case ISD::PCMARKER:
989     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
990     if (Tmp1 != Node->getOperand(0))
991       Result = DAG.getNode(ISD::PCMARKER, MVT::Other, Tmp1,Node->getOperand(1));
992     break;
993   case ISD::TRUNCSTORE:
994     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
995     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
996
997     switch (getTypeAction(Node->getOperand(1).getValueType())) {
998     case Legal:
999       Tmp2 = LegalizeOp(Node->getOperand(1));
1000       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1001           Tmp3 != Node->getOperand(2))
1002         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
1003                              Node->getOperand(3), Node->getOperand(4));
1004       break;
1005     case Promote:
1006     case Expand:
1007       assert(0 && "Cannot handle illegal TRUNCSTORE yet!");
1008     }
1009     break;
1010   case ISD::SELECT:
1011     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1012     case Expand: assert(0 && "It's impossible to expand bools");
1013     case Legal:
1014       Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1015       break;
1016     case Promote:
1017       Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
1018       break;
1019     }
1020     Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
1021     Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
1022
1023     switch (TLI.getOperationAction(Node->getOpcode(), Tmp2.getValueType())) {
1024     default: assert(0 && "This action is not supported yet!");
1025     case TargetLowering::Expand:
1026       if (Tmp1.getOpcode() == ISD::SETCC) {
1027         Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1), 
1028                               Tmp2, Tmp3,
1029                               cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
1030       } else {
1031         Result = DAG.getSelectCC(Tmp1, 
1032                                  DAG.getConstant(0, Tmp1.getValueType()),
1033                                  Tmp2, Tmp3, ISD::SETNE);
1034       }
1035       break;
1036     case TargetLowering::Legal:
1037       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1038           Tmp3 != Node->getOperand(2))
1039         Result = DAG.getNode(ISD::SELECT, Node->getValueType(0),
1040                              Tmp1, Tmp2, Tmp3);
1041       break;
1042     case TargetLowering::Promote: {
1043       MVT::ValueType NVT =
1044         TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
1045       unsigned ExtOp, TruncOp;
1046       if (MVT::isInteger(Tmp2.getValueType())) {
1047         ExtOp = ISD::ZERO_EXTEND;
1048         TruncOp  = ISD::TRUNCATE;
1049       } else {
1050         ExtOp = ISD::FP_EXTEND;
1051         TruncOp  = ISD::FP_ROUND;
1052       }
1053       // Promote each of the values to the new type.
1054       Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
1055       Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
1056       // Perform the larger operation, then round down.
1057       Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
1058       Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
1059       break;
1060     }
1061     }
1062     break;
1063   case ISD::SELECT_CC:
1064     Tmp3 = LegalizeOp(Node->getOperand(2));   // True
1065     Tmp4 = LegalizeOp(Node->getOperand(3));   // False
1066     
1067     if (getTypeAction(Node->getOperand(0).getValueType()) == Legal) {
1068       Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1069       Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
1070       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1071           Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3)) {
1072         Result = DAG.getNode(ISD::SELECT_CC, Node->getValueType(0), Tmp1, Tmp2, 
1073                              Tmp3, Tmp4, Node->getOperand(4));
1074       }
1075       break;
1076     } else {
1077       Tmp1 = LegalizeOp(DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),
1078                                     Node->getOperand(0),  // LHS
1079                                     Node->getOperand(1),  // RHS
1080                                     Node->getOperand(4)));
1081       // If we get a SETCC back from legalizing the SETCC node we just
1082       // created, then use its LHS, RHS, and CC directly in creating a new
1083       // node.  Otherwise, select between the true and false value based on
1084       // comparing the result of the legalized with zero.
1085       if (Tmp1.getOpcode() == ISD::SETCC) {
1086         Result = DAG.getNode(ISD::SELECT_CC, Tmp3.getValueType(),
1087                              Tmp1.getOperand(0), Tmp1.getOperand(1),
1088                              Tmp3, Tmp4, Tmp1.getOperand(2));
1089       } else {
1090         Result = DAG.getSelectCC(Tmp1,
1091                                  DAG.getConstant(0, Tmp1.getValueType()), 
1092                                  Tmp3, Tmp4, ISD::SETNE);
1093       }
1094     }
1095     break;
1096   case ISD::SETCC:
1097     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1098     case Legal:
1099       Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1100       Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
1101       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
1102         Result = DAG.getNode(ISD::SETCC, Node->getValueType(0), Tmp1, Tmp2,
1103                              Node->getOperand(2));
1104       break;
1105     case Promote:
1106       Tmp1 = PromoteOp(Node->getOperand(0));   // LHS
1107       Tmp2 = PromoteOp(Node->getOperand(1));   // RHS
1108
1109       // If this is an FP compare, the operands have already been extended.
1110       if (MVT::isInteger(Node->getOperand(0).getValueType())) {
1111         MVT::ValueType VT = Node->getOperand(0).getValueType();
1112         MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1113
1114         // Otherwise, we have to insert explicit sign or zero extends.  Note
1115         // that we could insert sign extends for ALL conditions, but zero extend
1116         // is cheaper on many machines (an AND instead of two shifts), so prefer
1117         // it.
1118         switch (cast<CondCodeSDNode>(Node->getOperand(2))->get()) {
1119         default: assert(0 && "Unknown integer comparison!");
1120         case ISD::SETEQ:
1121         case ISD::SETNE:
1122         case ISD::SETUGE:
1123         case ISD::SETUGT:
1124         case ISD::SETULE:
1125         case ISD::SETULT:
1126           // ALL of these operations will work if we either sign or zero extend
1127           // the operands (including the unsigned comparisons!).  Zero extend is
1128           // usually a simpler/cheaper operation, so prefer it.
1129           Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
1130           Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
1131           break;
1132         case ISD::SETGE:
1133         case ISD::SETGT:
1134         case ISD::SETLT:
1135         case ISD::SETLE:
1136           Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
1137                              DAG.getValueType(VT));
1138           Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
1139                              DAG.getValueType(VT));
1140           break;
1141         }
1142
1143       }
1144       Result = DAG.getNode(ISD::SETCC, Node->getValueType(0), Tmp1, Tmp2,
1145                            Node->getOperand(2));
1146       break;
1147     case Expand:
1148       SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
1149       ExpandOp(Node->getOperand(0), LHSLo, LHSHi);
1150       ExpandOp(Node->getOperand(1), RHSLo, RHSHi);
1151       switch (cast<CondCodeSDNode>(Node->getOperand(2))->get()) {
1152       case ISD::SETEQ:
1153       case ISD::SETNE:
1154         if (RHSLo == RHSHi)
1155           if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
1156             if (RHSCST->isAllOnesValue()) {
1157               // Comparison to -1.
1158               Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
1159               Result = DAG.getNode(ISD::SETCC, Node->getValueType(0), Tmp1,
1160                                    RHSLo, Node->getOperand(2));
1161               break;
1162             }
1163
1164         Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
1165         Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
1166         Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
1167         Result = DAG.getNode(ISD::SETCC, Node->getValueType(0), Tmp1,
1168                              DAG.getConstant(0, Tmp1.getValueType()),
1169                              Node->getOperand(2));
1170         break;
1171       default:
1172         // If this is a comparison of the sign bit, just look at the top part.
1173         // X > -1,  x < 0
1174         if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Node->getOperand(1)))
1175           if ((cast<CondCodeSDNode>(Node->getOperand(2))->get() == ISD::SETLT &&
1176                CST->getValue() == 0) ||              // X < 0
1177               (cast<CondCodeSDNode>(Node->getOperand(2))->get() == ISD::SETGT &&
1178                (CST->isAllOnesValue())))             // X > -1
1179             return DAG.getNode(ISD::SETCC, Node->getValueType(0), LHSHi, RHSHi,
1180                                Node->getOperand(2));
1181
1182         // FIXME: This generated code sucks.
1183         ISD::CondCode LowCC;
1184         switch (cast<CondCodeSDNode>(Node->getOperand(2))->get()) {
1185         default: assert(0 && "Unknown integer setcc!");
1186         case ISD::SETLT:
1187         case ISD::SETULT: LowCC = ISD::SETULT; break;
1188         case ISD::SETGT:
1189         case ISD::SETUGT: LowCC = ISD::SETUGT; break;
1190         case ISD::SETLE:
1191         case ISD::SETULE: LowCC = ISD::SETULE; break;
1192         case ISD::SETGE:
1193         case ISD::SETUGE: LowCC = ISD::SETUGE; break;
1194         }
1195
1196         // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
1197         // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
1198         // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
1199
1200         // NOTE: on targets without efficient SELECT of bools, we can always use
1201         // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
1202         Tmp1 = DAG.getSetCC(Node->getValueType(0), LHSLo, RHSLo, LowCC);
1203         Tmp2 = DAG.getNode(ISD::SETCC, Node->getValueType(0), LHSHi, RHSHi,
1204                            Node->getOperand(2));
1205         Result = DAG.getSetCC(Node->getValueType(0), LHSHi, RHSHi, ISD::SETEQ);
1206         Result = DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
1207                              Result, Tmp1, Tmp2);
1208         break;
1209       }
1210     }
1211     break;
1212
1213   case ISD::MEMSET:
1214   case ISD::MEMCPY:
1215   case ISD::MEMMOVE: {
1216     Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
1217     Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
1218
1219     if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
1220       switch (getTypeAction(Node->getOperand(2).getValueType())) {
1221       case Expand: assert(0 && "Cannot expand a byte!");
1222       case Legal:
1223         Tmp3 = LegalizeOp(Node->getOperand(2));
1224         break;
1225       case Promote:
1226         Tmp3 = PromoteOp(Node->getOperand(2));
1227         break;
1228       }
1229     } else {
1230       Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
1231     }
1232
1233     SDOperand Tmp4;
1234     switch (getTypeAction(Node->getOperand(3).getValueType())) {
1235     case Expand: {
1236       // Length is too big, just take the lo-part of the length.
1237       SDOperand HiPart;
1238       ExpandOp(Node->getOperand(3), HiPart, Tmp4);
1239       break;
1240     }
1241     case Legal:
1242       Tmp4 = LegalizeOp(Node->getOperand(3));
1243       break;
1244     case Promote:
1245       Tmp4 = PromoteOp(Node->getOperand(3));
1246       break;
1247     }
1248
1249     SDOperand Tmp5;
1250     switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
1251     case Expand: assert(0 && "Cannot expand this yet!");
1252     case Legal:
1253       Tmp5 = LegalizeOp(Node->getOperand(4));
1254       break;
1255     case Promote:
1256       Tmp5 = PromoteOp(Node->getOperand(4));
1257       break;
1258     }
1259
1260     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1261     default: assert(0 && "This action not implemented for this operation!");
1262     case TargetLowering::Legal:
1263       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1264           Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3) ||
1265           Tmp5 != Node->getOperand(4)) {
1266         std::vector<SDOperand> Ops;
1267         Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
1268         Ops.push_back(Tmp4); Ops.push_back(Tmp5);
1269         Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
1270       }
1271       break;
1272     case TargetLowering::Expand: {
1273       // Otherwise, the target does not support this operation.  Lower the
1274       // operation to an explicit libcall as appropriate.
1275       MVT::ValueType IntPtr = TLI.getPointerTy();
1276       const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
1277       std::vector<std::pair<SDOperand, const Type*> > Args;
1278
1279       const char *FnName = 0;
1280       if (Node->getOpcode() == ISD::MEMSET) {
1281         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1282         // Extend the ubyte argument to be an int value for the call.
1283         Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
1284         Args.push_back(std::make_pair(Tmp3, Type::IntTy));
1285         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1286
1287         FnName = "memset";
1288       } else if (Node->getOpcode() == ISD::MEMCPY ||
1289                  Node->getOpcode() == ISD::MEMMOVE) {
1290         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1291         Args.push_back(std::make_pair(Tmp3, IntPtrTy));
1292         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1293         FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
1294       } else {
1295         assert(0 && "Unknown op!");
1296       }
1297
1298       std::pair<SDOperand,SDOperand> CallResult =
1299         TLI.LowerCallTo(Tmp1, Type::VoidTy, false, CallingConv::C, false,
1300                         DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
1301       Result = CallResult.second;
1302       NeedsAnotherIteration = true;
1303       break;
1304     }
1305     case TargetLowering::Custom:
1306       std::vector<SDOperand> Ops;
1307       Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
1308       Ops.push_back(Tmp4); Ops.push_back(Tmp5);
1309       Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
1310       Result = TLI.LowerOperation(Result, DAG);
1311       Result = LegalizeOp(Result);
1312       break;
1313     }
1314     break;
1315   }
1316
1317   case ISD::READPORT:
1318     Tmp1 = LegalizeOp(Node->getOperand(0));
1319     Tmp2 = LegalizeOp(Node->getOperand(1));
1320
1321     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
1322       std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1323       std::vector<SDOperand> Ops;
1324       Ops.push_back(Tmp1);
1325       Ops.push_back(Tmp2);
1326       Result = DAG.getNode(ISD::READPORT, VTs, Ops);
1327     } else
1328       Result = SDOperand(Node, 0);
1329     // Since these produce two values, make sure to remember that we legalized
1330     // both of them.
1331     AddLegalizedOperand(SDOperand(Node, 0), Result);
1332     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1333     return Result.getValue(Op.ResNo);
1334   case ISD::WRITEPORT:
1335     Tmp1 = LegalizeOp(Node->getOperand(0));
1336     Tmp2 = LegalizeOp(Node->getOperand(1));
1337     Tmp3 = LegalizeOp(Node->getOperand(2));
1338     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1339         Tmp3 != Node->getOperand(2))
1340       Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1, Tmp2, Tmp3);
1341     break;
1342
1343   case ISD::READIO:
1344     Tmp1 = LegalizeOp(Node->getOperand(0));
1345     Tmp2 = LegalizeOp(Node->getOperand(1));
1346
1347     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1348     case TargetLowering::Custom:
1349     default: assert(0 && "This action not implemented for this operation!");
1350     case TargetLowering::Legal:
1351       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
1352         std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1353         std::vector<SDOperand> Ops;
1354         Ops.push_back(Tmp1);
1355         Ops.push_back(Tmp2);
1356         Result = DAG.getNode(ISD::READPORT, VTs, Ops);
1357       } else
1358         Result = SDOperand(Node, 0);
1359       break;
1360     case TargetLowering::Expand:
1361       // Replace this with a load from memory.
1362       Result = DAG.getLoad(Node->getValueType(0), Node->getOperand(0),
1363                            Node->getOperand(1), DAG.getSrcValue(NULL));
1364       Result = LegalizeOp(Result);
1365       break;
1366     }
1367
1368     // Since these produce two values, make sure to remember that we legalized
1369     // both of them.
1370     AddLegalizedOperand(SDOperand(Node, 0), Result);
1371     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1372     return Result.getValue(Op.ResNo);
1373
1374   case ISD::WRITEIO:
1375     Tmp1 = LegalizeOp(Node->getOperand(0));
1376     Tmp2 = LegalizeOp(Node->getOperand(1));
1377     Tmp3 = LegalizeOp(Node->getOperand(2));
1378
1379     switch (TLI.getOperationAction(Node->getOpcode(),
1380                                    Node->getOperand(1).getValueType())) {
1381     case TargetLowering::Custom:
1382     default: assert(0 && "This action not implemented for this operation!");
1383     case TargetLowering::Legal:
1384       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1385           Tmp3 != Node->getOperand(2))
1386         Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1, Tmp2, Tmp3);
1387       break;
1388     case TargetLowering::Expand:
1389       // Replace this with a store to memory.
1390       Result = DAG.getNode(ISD::STORE, MVT::Other, Node->getOperand(0),
1391                            Node->getOperand(1), Node->getOperand(2),
1392                            DAG.getSrcValue(NULL));
1393       Result = LegalizeOp(Result);
1394       break;
1395     }
1396     break;
1397
1398   case ISD::ADD_PARTS:
1399   case ISD::SUB_PARTS:
1400   case ISD::SHL_PARTS:
1401   case ISD::SRA_PARTS:
1402   case ISD::SRL_PARTS: {
1403     std::vector<SDOperand> Ops;
1404     bool Changed = false;
1405     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1406       Ops.push_back(LegalizeOp(Node->getOperand(i)));
1407       Changed |= Ops.back() != Node->getOperand(i);
1408     }
1409     if (Changed) {
1410       std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1411       Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
1412     }
1413
1414     // Since these produce multiple values, make sure to remember that we
1415     // legalized all of them.
1416     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1417       AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
1418     return Result.getValue(Op.ResNo);
1419   }
1420
1421     // Binary operators
1422   case ISD::ADD:
1423   case ISD::SUB:
1424   case ISD::MUL:
1425   case ISD::MULHS:
1426   case ISD::MULHU:
1427   case ISD::UDIV:
1428   case ISD::SDIV:
1429   case ISD::AND:
1430   case ISD::OR:
1431   case ISD::XOR:
1432   case ISD::SHL:
1433   case ISD::SRL:
1434   case ISD::SRA:
1435     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1436     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1437     case Expand: assert(0 && "Not possible");
1438     case Legal:
1439       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
1440       break;
1441     case Promote:
1442       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
1443       break;
1444     }
1445     if (Tmp1 != Node->getOperand(0) ||
1446         Tmp2 != Node->getOperand(1))
1447       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
1448     break;
1449
1450   case ISD::UREM:
1451   case ISD::SREM:
1452     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1453     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
1454     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1455     case TargetLowering::Legal:
1456       if (Tmp1 != Node->getOperand(0) ||
1457           Tmp2 != Node->getOperand(1))
1458         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
1459                              Tmp2);
1460       break;
1461     case TargetLowering::Promote:
1462     case TargetLowering::Custom:
1463       assert(0 && "Cannot promote/custom handle this yet!");
1464     case TargetLowering::Expand:
1465       if (MVT::isInteger(Node->getValueType(0))) {
1466         MVT::ValueType VT = Node->getValueType(0);
1467         unsigned Opc = (Node->getOpcode() == ISD::UREM) ? ISD::UDIV : ISD::SDIV;
1468         Result = DAG.getNode(Opc, VT, Tmp1, Tmp2);
1469         Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
1470         Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
1471       } else {
1472         // Floating point mod -> fmod libcall.
1473         const char *FnName = Node->getValueType(0) == MVT::f32 ? "fmodf":"fmod";
1474         SDOperand Dummy;
1475         Result = ExpandLibCall(FnName, Node, Dummy);
1476       }
1477       break;
1478     }
1479     break;
1480
1481   case ISD::CTPOP:
1482   case ISD::CTTZ:
1483   case ISD::CTLZ:
1484     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
1485     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1486     case TargetLowering::Legal:
1487       if (Tmp1 != Node->getOperand(0))
1488         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1489       break;
1490     case TargetLowering::Promote: {
1491       MVT::ValueType OVT = Tmp1.getValueType();
1492       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
1493
1494       // Zero extend the argument.
1495       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
1496       // Perform the larger operation, then subtract if needed.
1497       Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1498       switch(Node->getOpcode())
1499       {
1500       case ISD::CTPOP:
1501         Result = Tmp1;
1502         break;
1503       case ISD::CTTZ:
1504         //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
1505         Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
1506                             DAG.getConstant(getSizeInBits(NVT), NVT),
1507                             ISD::SETEQ);
1508         Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
1509                            DAG.getConstant(getSizeInBits(OVT),NVT), Tmp1);
1510         break;
1511       case ISD::CTLZ:
1512         //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
1513         Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
1514                              DAG.getConstant(getSizeInBits(NVT) -
1515                                              getSizeInBits(OVT), NVT));
1516         break;
1517       }
1518       break;
1519     }
1520     case TargetLowering::Custom:
1521       assert(0 && "Cannot custom handle this yet!");
1522     case TargetLowering::Expand:
1523       switch(Node->getOpcode())
1524       {
1525       case ISD::CTPOP: {
1526         static const uint64_t mask[6] = {
1527           0x5555555555555555ULL, 0x3333333333333333ULL,
1528           0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
1529           0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
1530         };
1531         MVT::ValueType VT = Tmp1.getValueType();
1532         MVT::ValueType ShVT = TLI.getShiftAmountTy();
1533         unsigned len = getSizeInBits(VT);
1534         for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
1535           //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
1536           Tmp2 = DAG.getConstant(mask[i], VT);
1537           Tmp3 = DAG.getConstant(1ULL << i, ShVT);
1538           Tmp1 = DAG.getNode(ISD::ADD, VT,
1539                              DAG.getNode(ISD::AND, VT, Tmp1, Tmp2),
1540                              DAG.getNode(ISD::AND, VT,
1541                                          DAG.getNode(ISD::SRL, VT, Tmp1, Tmp3),
1542                                          Tmp2));
1543         }
1544         Result = Tmp1;
1545         break;
1546       }
1547       case ISD::CTLZ: {
1548         /* for now, we do this:
1549            x = x | (x >> 1);
1550            x = x | (x >> 2);
1551            ...
1552            x = x | (x >>16);
1553            x = x | (x >>32); // for 64-bit input
1554            return popcount(~x);
1555
1556            but see also: http://www.hackersdelight.org/HDcode/nlz.cc */
1557         MVT::ValueType VT = Tmp1.getValueType();
1558         MVT::ValueType ShVT = TLI.getShiftAmountTy();
1559         unsigned len = getSizeInBits(VT);
1560         for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
1561           Tmp3 = DAG.getConstant(1ULL << i, ShVT);
1562           Tmp1 = DAG.getNode(ISD::OR, VT, Tmp1,
1563                              DAG.getNode(ISD::SRL, VT, Tmp1, Tmp3));
1564         }
1565         Tmp3 = DAG.getNode(ISD::XOR, VT, Tmp1, DAG.getConstant(~0ULL, VT));
1566         Result = LegalizeOp(DAG.getNode(ISD::CTPOP, VT, Tmp3));
1567         break;
1568       }
1569       case ISD::CTTZ: {
1570         // for now, we use: { return popcount(~x & (x - 1)); }
1571         // unless the target has ctlz but not ctpop, in which case we use:
1572         // { return 32 - nlz(~x & (x-1)); }
1573         // see also http://www.hackersdelight.org/HDcode/ntz.cc
1574         MVT::ValueType VT = Tmp1.getValueType();
1575         Tmp2 = DAG.getConstant(~0ULL, VT);
1576         Tmp3 = DAG.getNode(ISD::AND, VT,
1577                            DAG.getNode(ISD::XOR, VT, Tmp1, Tmp2),
1578                            DAG.getNode(ISD::SUB, VT, Tmp1,
1579                                        DAG.getConstant(1, VT)));
1580         // If ISD::CTLZ is legal and CTPOP isn't, then do that instead
1581         if (TLI.getOperationAction(ISD::CTPOP, VT) != TargetLowering::Legal &&
1582             TLI.getOperationAction(ISD::CTLZ, VT) == TargetLowering::Legal) {
1583           Result = LegalizeOp(DAG.getNode(ISD::SUB, VT,
1584                                         DAG.getConstant(getSizeInBits(VT), VT),
1585                                         DAG.getNode(ISD::CTLZ, VT, Tmp3)));
1586         } else {
1587           Result = LegalizeOp(DAG.getNode(ISD::CTPOP, VT, Tmp3));
1588         }
1589         break;
1590       }
1591       default:
1592         assert(0 && "Cannot expand this yet!");
1593         break;
1594       }
1595       break;
1596     }
1597     break;
1598
1599     // Unary operators
1600   case ISD::FABS:
1601   case ISD::FNEG:
1602   case ISD::FSQRT:
1603   case ISD::FSIN:
1604   case ISD::FCOS:
1605     Tmp1 = LegalizeOp(Node->getOperand(0));
1606     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1607     case TargetLowering::Legal:
1608       if (Tmp1 != Node->getOperand(0))
1609         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1610       break;
1611     case TargetLowering::Promote:
1612     case TargetLowering::Custom:
1613       assert(0 && "Cannot promote/custom handle this yet!");
1614     case TargetLowering::Expand:
1615       switch(Node->getOpcode()) {
1616       case ISD::FNEG: {
1617         // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
1618         Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
1619         Result = LegalizeOp(DAG.getNode(ISD::SUB, Node->getValueType(0),
1620                                         Tmp2, Tmp1));
1621         break;
1622       }
1623       case ISD::FABS: {
1624         // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
1625         MVT::ValueType VT = Node->getValueType(0);
1626         Tmp2 = DAG.getConstantFP(0.0, VT);
1627         Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1, Tmp2, ISD::SETUGT);
1628         Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
1629         Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
1630         Result = LegalizeOp(Result);
1631         break;
1632       }
1633       case ISD::FSQRT:
1634       case ISD::FSIN:
1635       case ISD::FCOS: {
1636         MVT::ValueType VT = Node->getValueType(0);
1637         const char *FnName = 0;
1638         switch(Node->getOpcode()) {
1639         case ISD::FSQRT: FnName = VT == MVT::f32 ? "sqrtf" : "sqrt"; break;
1640         case ISD::FSIN:  FnName = VT == MVT::f32 ? "sinf"  : "sin"; break;
1641         case ISD::FCOS:  FnName = VT == MVT::f32 ? "cosf"  : "cos"; break;
1642         default: assert(0 && "Unreachable!");
1643         }
1644         SDOperand Dummy;
1645         Result = ExpandLibCall(FnName, Node, Dummy);
1646         break;
1647       }
1648       default:
1649         assert(0 && "Unreachable!");
1650       }
1651       break;
1652     }
1653     break;
1654
1655     // Conversion operators.  The source and destination have different types.
1656   case ISD::SINT_TO_FP:
1657   case ISD::UINT_TO_FP: {
1658     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
1659     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1660     case Legal:
1661       switch (TLI.getOperationAction(Node->getOpcode(),
1662                                      Node->getOperand(0).getValueType())) {
1663       default: assert(0 && "Unknown operation action!");
1664       case TargetLowering::Expand:
1665         assert(!isSigned && "Legalize cannot Expand SINT_TO_FP yet");
1666         Result = ExpandLegalUINT_TO_FP(LegalizeOp(Node->getOperand(0)),
1667                                        Node->getValueType(0));
1668         AddLegalizedOperand(Op, Result);
1669         return Result;
1670       case TargetLowering::Promote:
1671         Result = PromoteLegalINT_TO_FP(LegalizeOp(Node->getOperand(0)),
1672                                        Node->getValueType(0),
1673                                        isSigned);
1674         AddLegalizedOperand(Op, Result);
1675         return Result;
1676       case TargetLowering::Legal:
1677         break;
1678       }
1679
1680       Tmp1 = LegalizeOp(Node->getOperand(0));
1681       if (Tmp1 != Node->getOperand(0))
1682         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1683       break;
1684     case Expand:
1685       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
1686                              Node->getValueType(0), Node->getOperand(0));
1687       break;
1688     case Promote:
1689       if (isSigned) {
1690         Result = PromoteOp(Node->getOperand(0));
1691         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1692                  Result, DAG.getValueType(Node->getOperand(0).getValueType()));
1693         Result = DAG.getNode(ISD::SINT_TO_FP, Op.getValueType(), Result);
1694       } else {
1695         Result = PromoteOp(Node->getOperand(0));
1696         Result = DAG.getZeroExtendInReg(Result,
1697                                         Node->getOperand(0).getValueType());
1698         Result = DAG.getNode(ISD::UINT_TO_FP, Op.getValueType(), Result);
1699       }
1700       break;
1701     }
1702     break;
1703   }
1704   case ISD::TRUNCATE:
1705     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1706     case Legal:
1707       Tmp1 = LegalizeOp(Node->getOperand(0));
1708       if (Tmp1 != Node->getOperand(0))
1709         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1710       break;
1711     case Expand:
1712       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1713
1714       // Since the result is legal, we should just be able to truncate the low
1715       // part of the source.
1716       Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
1717       break;
1718     case Promote:
1719       Result = PromoteOp(Node->getOperand(0));
1720       Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
1721       break;
1722     }
1723     break;
1724
1725   case ISD::FP_TO_SINT:
1726   case ISD::FP_TO_UINT:
1727     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1728     case Legal:
1729       Tmp1 = LegalizeOp(Node->getOperand(0));
1730
1731       switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
1732       default: assert(0 && "Unknown operation action!");
1733       case TargetLowering::Expand:
1734         if (Node->getOpcode() == ISD::FP_TO_UINT) {
1735           SDOperand True, False;
1736           MVT::ValueType VT =  Node->getOperand(0).getValueType();
1737           MVT::ValueType NVT = Node->getValueType(0);
1738           unsigned ShiftAmt = MVT::getSizeInBits(Node->getValueType(0))-1;
1739           Tmp2 = DAG.getConstantFP((double)(1ULL << ShiftAmt), VT);
1740           Tmp3 = DAG.getSetCC(TLI.getSetCCResultTy(),
1741                             Node->getOperand(0), Tmp2, ISD::SETLT);
1742           True = DAG.getNode(ISD::FP_TO_SINT, NVT, Node->getOperand(0));
1743           False = DAG.getNode(ISD::FP_TO_SINT, NVT,
1744                               DAG.getNode(ISD::SUB, VT, Node->getOperand(0),
1745                                           Tmp2));
1746           False = DAG.getNode(ISD::XOR, NVT, False, 
1747                               DAG.getConstant(1ULL << ShiftAmt, NVT));
1748           Result = LegalizeOp(DAG.getNode(ISD::SELECT, NVT, Tmp3, True, False));
1749           return Result;
1750         } else {
1751           assert(0 && "Do not know how to expand FP_TO_SINT yet!");
1752         }
1753         break;
1754       case TargetLowering::Promote:
1755         Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
1756                                        Node->getOpcode() == ISD::FP_TO_SINT);
1757         AddLegalizedOperand(Op, Result);
1758         return Result;
1759       case TargetLowering::Legal:
1760         break;
1761       case TargetLowering::Custom:
1762         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1763         Result = TLI.LowerOperation(Result, DAG);
1764         AddLegalizedOperand(Op, Result);
1765         NeedsAnotherIteration = true;
1766         return Result;
1767       }
1768
1769       if (Tmp1 != Node->getOperand(0))
1770         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1771       break;
1772     case Expand:
1773       assert(0 && "Shouldn't need to expand other operators here!");
1774     case Promote:
1775       Result = PromoteOp(Node->getOperand(0));
1776       Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
1777       break;
1778     }
1779     break;
1780
1781   case ISD::ZERO_EXTEND:
1782   case ISD::SIGN_EXTEND:
1783   case ISD::FP_EXTEND:
1784   case ISD::FP_ROUND:
1785     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1786     case Legal:
1787       Tmp1 = LegalizeOp(Node->getOperand(0));
1788       if (Tmp1 != Node->getOperand(0))
1789         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1790       break;
1791     case Expand:
1792       assert(0 && "Shouldn't need to expand other operators here!");
1793
1794     case Promote:
1795       switch (Node->getOpcode()) {
1796       case ISD::ZERO_EXTEND:
1797         Result = PromoteOp(Node->getOperand(0));
1798         // NOTE: Any extend would work here...
1799         Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
1800         Result = DAG.getZeroExtendInReg(Result,
1801                                         Node->getOperand(0).getValueType());
1802         break;
1803       case ISD::SIGN_EXTEND:
1804         Result = PromoteOp(Node->getOperand(0));
1805         // NOTE: Any extend would work here...
1806         Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
1807         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1808                              Result,
1809                           DAG.getValueType(Node->getOperand(0).getValueType()));
1810         break;
1811       case ISD::FP_EXTEND:
1812         Result = PromoteOp(Node->getOperand(0));
1813         if (Result.getValueType() != Op.getValueType())
1814           // Dynamically dead while we have only 2 FP types.
1815           Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
1816         break;
1817       case ISD::FP_ROUND:
1818         Result = PromoteOp(Node->getOperand(0));
1819         Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
1820         break;
1821       }
1822     }
1823     break;
1824   case ISD::FP_ROUND_INREG:
1825   case ISD::SIGN_EXTEND_INREG: {
1826     Tmp1 = LegalizeOp(Node->getOperand(0));
1827     MVT::ValueType ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1828
1829     // If this operation is not supported, convert it to a shl/shr or load/store
1830     // pair.
1831     switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
1832     default: assert(0 && "This action not supported for this op yet!");
1833     case TargetLowering::Legal:
1834       if (Tmp1 != Node->getOperand(0))
1835         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
1836                              DAG.getValueType(ExtraVT));
1837       break;
1838     case TargetLowering::Expand:
1839       // If this is an integer extend and shifts are supported, do that.
1840       if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
1841         // NOTE: we could fall back on load/store here too for targets without
1842         // SAR.  However, it is doubtful that any exist.
1843         unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
1844                             MVT::getSizeInBits(ExtraVT);
1845         SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
1846         Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
1847                              Node->getOperand(0), ShiftCst);
1848         Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
1849                              Result, ShiftCst);
1850       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
1851         // The only way we can lower this is to turn it into a STORETRUNC,
1852         // EXTLOAD pair, targetting a temporary location (a stack slot).
1853
1854         // NOTE: there is a choice here between constantly creating new stack
1855         // slots and always reusing the same one.  We currently always create
1856         // new ones, as reuse may inhibit scheduling.
1857         const Type *Ty = MVT::getTypeForValueType(ExtraVT);
1858         unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
1859         unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
1860         MachineFunction &MF = DAG.getMachineFunction();
1861         int SSFI =
1862           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
1863         SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
1864         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
1865                              Node->getOperand(0), StackSlot,
1866                              DAG.getSrcValue(NULL), DAG.getValueType(ExtraVT));
1867         Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
1868                                 Result, StackSlot, DAG.getSrcValue(NULL),
1869                                 ExtraVT);
1870       } else {
1871         assert(0 && "Unknown op");
1872       }
1873       Result = LegalizeOp(Result);
1874       break;
1875     }
1876     break;
1877   }
1878   }
1879
1880   // Note that LegalizeOp may be reentered even from single-use nodes, which
1881   // means that we always must cache transformed nodes.
1882   AddLegalizedOperand(Op, Result);
1883   return Result;
1884 }
1885
1886 /// PromoteOp - Given an operation that produces a value in an invalid type,
1887 /// promote it to compute the value into a larger type.  The produced value will
1888 /// have the correct bits for the low portion of the register, but no guarantee
1889 /// is made about the top bits: it may be zero, sign-extended, or garbage.
1890 SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
1891   MVT::ValueType VT = Op.getValueType();
1892   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1893   assert(getTypeAction(VT) == Promote &&
1894          "Caller should expand or legalize operands that are not promotable!");
1895   assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
1896          "Cannot promote to smaller type!");
1897
1898   SDOperand Tmp1, Tmp2, Tmp3;
1899
1900   SDOperand Result;
1901   SDNode *Node = Op.Val;
1902
1903   if (!Node->hasOneUse()) {
1904     std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
1905     if (I != PromotedNodes.end()) return I->second;
1906   } else {
1907     assert(!PromotedNodes.count(Op) && "Repromoted this node??");
1908   }
1909
1910   // Promotion needs an optimization step to clean up after it, and is not
1911   // careful to avoid operations the target does not support.  Make sure that
1912   // all generated operations are legalized in the next iteration.
1913   NeedsAnotherIteration = true;
1914
1915   switch (Node->getOpcode()) {
1916   default:
1917     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
1918     assert(0 && "Do not know how to promote this operator!");
1919     abort();
1920   case ISD::UNDEF:
1921     Result = DAG.getNode(ISD::UNDEF, NVT);
1922     break;
1923   case ISD::Constant:
1924     Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
1925     assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
1926     break;
1927   case ISD::ConstantFP:
1928     Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
1929     assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
1930     break;
1931   case ISD::CopyFromReg:
1932     Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(), NVT,
1933                                 Node->getOperand(0));
1934     // Remember that we legalized the chain.
1935     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1936     break;
1937
1938   case ISD::SETCC:
1939     assert(getTypeAction(TLI.getSetCCResultTy()) == Legal &&
1940            "SetCC type is not legal??");
1941     Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),Node->getOperand(0),
1942                          Node->getOperand(1), Node->getOperand(2));
1943     Result = LegalizeOp(Result);
1944     break;
1945
1946   case ISD::TRUNCATE:
1947     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1948     case Legal:
1949       Result = LegalizeOp(Node->getOperand(0));
1950       assert(Result.getValueType() >= NVT &&
1951              "This truncation doesn't make sense!");
1952       if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
1953         Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
1954       break;
1955     case Promote:
1956       // The truncation is not required, because we don't guarantee anything
1957       // about high bits anyway.
1958       Result = PromoteOp(Node->getOperand(0));
1959       break;
1960     case Expand:
1961       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1962       // Truncate the low part of the expanded value to the result type
1963       Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
1964     }
1965     break;
1966   case ISD::SIGN_EXTEND:
1967   case ISD::ZERO_EXTEND:
1968     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1969     case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
1970     case Legal:
1971       // Input is legal?  Just do extend all the way to the larger type.
1972       Result = LegalizeOp(Node->getOperand(0));
1973       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1974       break;
1975     case Promote:
1976       // Promote the reg if it's smaller.
1977       Result = PromoteOp(Node->getOperand(0));
1978       // The high bits are not guaranteed to be anything.  Insert an extend.
1979       if (Node->getOpcode() == ISD::SIGN_EXTEND)
1980         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
1981                          DAG.getValueType(Node->getOperand(0).getValueType()));
1982       else
1983         Result = DAG.getZeroExtendInReg(Result,
1984                                         Node->getOperand(0).getValueType());
1985       break;
1986     }
1987     break;
1988
1989   case ISD::FP_EXTEND:
1990     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
1991   case ISD::FP_ROUND:
1992     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1993     case Expand: assert(0 && "BUG: Cannot expand FP regs!");
1994     case Promote:  assert(0 && "Unreachable with 2 FP types!");
1995     case Legal:
1996       // Input is legal?  Do an FP_ROUND_INREG.
1997       Result = LegalizeOp(Node->getOperand(0));
1998       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
1999                            DAG.getValueType(VT));
2000       break;
2001     }
2002     break;
2003
2004   case ISD::SINT_TO_FP:
2005   case ISD::UINT_TO_FP:
2006     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2007     case Legal:
2008       Result = LegalizeOp(Node->getOperand(0));
2009       // No extra round required here.
2010       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2011       break;
2012
2013     case Promote:
2014       Result = PromoteOp(Node->getOperand(0));
2015       if (Node->getOpcode() == ISD::SINT_TO_FP)
2016         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2017                              Result,
2018                          DAG.getValueType(Node->getOperand(0).getValueType()));
2019       else
2020         Result = DAG.getZeroExtendInReg(Result,
2021                                         Node->getOperand(0).getValueType());
2022       // No extra round required here.
2023       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2024       break;
2025     case Expand:
2026       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
2027                              Node->getOperand(0));
2028       // Round if we cannot tolerate excess precision.
2029       if (NoExcessFPPrecision)
2030         Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2031                              DAG.getValueType(VT));
2032       break;
2033     }
2034     break;
2035
2036   case ISD::FP_TO_SINT:
2037   case ISD::FP_TO_UINT:
2038     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2039     case Legal:
2040       Tmp1 = LegalizeOp(Node->getOperand(0));
2041       break;
2042     case Promote:
2043       // The input result is prerounded, so we don't have to do anything
2044       // special.
2045       Tmp1 = PromoteOp(Node->getOperand(0));
2046       break;
2047     case Expand:
2048       assert(0 && "not implemented");
2049     }
2050     // If we're promoting a UINT to a larger size, check to see if the new node
2051     // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
2052     // we can use that instead.  This allows us to generate better code for
2053     // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
2054     // legal, such as PowerPC.
2055     if (Node->getOpcode() == ISD::FP_TO_UINT && 
2056         TargetLowering::Legal != TLI.getOperationAction(ISD::FP_TO_UINT, NVT) &&
2057         TargetLowering::Legal == TLI.getOperationAction(ISD::FP_TO_SINT, NVT)) {
2058       Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
2059     } else {
2060       Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2061     }
2062     break;
2063
2064   case ISD::FABS:
2065   case ISD::FNEG:
2066     Tmp1 = PromoteOp(Node->getOperand(0));
2067     assert(Tmp1.getValueType() == NVT);
2068     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2069     // NOTE: we do not have to do any extra rounding here for
2070     // NoExcessFPPrecision, because we know the input will have the appropriate
2071     // precision, and these operations don't modify precision at all.
2072     break;
2073
2074   case ISD::FSQRT:
2075   case ISD::FSIN:
2076   case ISD::FCOS:
2077     Tmp1 = PromoteOp(Node->getOperand(0));
2078     assert(Tmp1.getValueType() == NVT);
2079     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2080     if(NoExcessFPPrecision)
2081       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2082                            DAG.getValueType(VT));
2083     break;
2084
2085   case ISD::AND:
2086   case ISD::OR:
2087   case ISD::XOR:
2088   case ISD::ADD:
2089   case ISD::SUB:
2090   case ISD::MUL:
2091     // The input may have strange things in the top bits of the registers, but
2092     // these operations don't care.  They may have wierd bits going out, but
2093     // that too is okay if they are integer operations.
2094     Tmp1 = PromoteOp(Node->getOperand(0));
2095     Tmp2 = PromoteOp(Node->getOperand(1));
2096     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2097     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2098
2099     // However, if this is a floating point operation, they will give excess
2100     // precision that we may not be able to tolerate.  If we DO allow excess
2101     // precision, just leave it, otherwise excise it.
2102     // FIXME: Why would we need to round FP ops more than integer ones?
2103     //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
2104     if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
2105       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2106                            DAG.getValueType(VT));
2107     break;
2108
2109   case ISD::SDIV:
2110   case ISD::SREM:
2111     // These operators require that their input be sign extended.
2112     Tmp1 = PromoteOp(Node->getOperand(0));
2113     Tmp2 = PromoteOp(Node->getOperand(1));
2114     if (MVT::isInteger(NVT)) {
2115       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
2116                          DAG.getValueType(VT));
2117       Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
2118                          DAG.getValueType(VT));
2119     }
2120     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2121
2122     // Perform FP_ROUND: this is probably overly pessimistic.
2123     if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
2124       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2125                            DAG.getValueType(VT));
2126     break;
2127
2128   case ISD::UDIV:
2129   case ISD::UREM:
2130     // These operators require that their input be zero extended.
2131     Tmp1 = PromoteOp(Node->getOperand(0));
2132     Tmp2 = PromoteOp(Node->getOperand(1));
2133     assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
2134     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
2135     Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
2136     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2137     break;
2138
2139   case ISD::SHL:
2140     Tmp1 = PromoteOp(Node->getOperand(0));
2141     Tmp2 = LegalizeOp(Node->getOperand(1));
2142     Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Tmp2);
2143     break;
2144   case ISD::SRA:
2145     // The input value must be properly sign extended.
2146     Tmp1 = PromoteOp(Node->getOperand(0));
2147     Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
2148                        DAG.getValueType(VT));
2149     Tmp2 = LegalizeOp(Node->getOperand(1));
2150     Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Tmp2);
2151     break;
2152   case ISD::SRL:
2153     // The input value must be properly zero extended.
2154     Tmp1 = PromoteOp(Node->getOperand(0));
2155     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
2156     Tmp2 = LegalizeOp(Node->getOperand(1));
2157     Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Tmp2);
2158     break;
2159   case ISD::LOAD:
2160     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
2161     Tmp2 = LegalizeOp(Node->getOperand(1));   // Legalize the pointer.
2162     // FIXME: When the DAG combiner exists, change this to use EXTLOAD!
2163     if (MVT::isInteger(NVT))
2164       Result = DAG.getExtLoad(ISD::ZEXTLOAD, NVT, Tmp1, Tmp2,
2165                               Node->getOperand(2), VT);
2166     else
2167       Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp1, Tmp2,
2168                               Node->getOperand(2), VT);
2169
2170     // Remember that we legalized the chain.
2171     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
2172     break;
2173   case ISD::SELECT:
2174     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2175     case Expand: assert(0 && "It's impossible to expand bools");
2176     case Legal:
2177       Tmp1 = LegalizeOp(Node->getOperand(0));// Legalize the condition.
2178       break;
2179     case Promote:
2180       Tmp1 = PromoteOp(Node->getOperand(0)); // Promote the condition.
2181       break;
2182     }
2183     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
2184     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
2185     Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2, Tmp3);
2186     break;
2187   case ISD::SELECT_CC:
2188     Tmp2 = PromoteOp(Node->getOperand(2));   // True
2189     Tmp3 = PromoteOp(Node->getOperand(3));   // False
2190     Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
2191                          Node->getOperand(1), Tmp2, Tmp3,
2192                          Node->getOperand(4));
2193     break;
2194   case ISD::TAILCALL:
2195   case ISD::CALL: {
2196     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2197     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
2198
2199     std::vector<SDOperand> Ops;
2200     for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i)
2201       Ops.push_back(LegalizeOp(Node->getOperand(i)));
2202
2203     assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
2204            "Can only promote single result calls");
2205     std::vector<MVT::ValueType> RetTyVTs;
2206     RetTyVTs.reserve(2);
2207     RetTyVTs.push_back(NVT);
2208     RetTyVTs.push_back(MVT::Other);
2209     SDNode *NC = DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops,
2210                              Node->getOpcode() == ISD::TAILCALL);
2211     Result = SDOperand(NC, 0);
2212
2213     // Insert the new chain mapping.
2214     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
2215     break;
2216   }
2217   case ISD::CTPOP:
2218   case ISD::CTTZ:
2219   case ISD::CTLZ:
2220     Tmp1 = Node->getOperand(0);
2221     //Zero extend the argument
2222     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2223     // Perform the larger operation, then subtract if needed.
2224     Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2225     switch(Node->getOpcode())
2226     {
2227     case ISD::CTPOP:
2228       Result = Tmp1;
2229       break;
2230     case ISD::CTTZ:
2231       //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2232       Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
2233                           DAG.getConstant(getSizeInBits(NVT), NVT), ISD::SETEQ);
2234       Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
2235                            DAG.getConstant(getSizeInBits(VT),NVT), Tmp1);
2236       break;
2237     case ISD::CTLZ:
2238       //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2239       Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
2240                            DAG.getConstant(getSizeInBits(NVT) -
2241                                            getSizeInBits(VT), NVT));
2242       break;
2243     }
2244     break;
2245   }
2246
2247   assert(Result.Val && "Didn't set a result!");
2248   AddPromotedOperand(Op, Result);
2249   return Result;
2250 }
2251
2252 /// ExpandAddSub - Find a clever way to expand this add operation into
2253 /// subcomponents.
2254 void SelectionDAGLegalize::
2255 ExpandByParts(unsigned NodeOp, SDOperand LHS, SDOperand RHS,
2256               SDOperand &Lo, SDOperand &Hi) {
2257   // Expand the subcomponents.
2258   SDOperand LHSL, LHSH, RHSL, RHSH;
2259   ExpandOp(LHS, LHSL, LHSH);
2260   ExpandOp(RHS, RHSL, RHSH);
2261
2262   // FIXME: this should be moved to the dag combiner someday.
2263   assert(NodeOp == ISD::ADD_PARTS || NodeOp == ISD::SUB_PARTS);
2264   if (LHSL.getValueType() == MVT::i32) {
2265     SDOperand LowEl;
2266     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHSL))
2267       if (C->getValue() == 0)
2268         LowEl = RHSL;
2269     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHSL))
2270       if (C->getValue() == 0)
2271         LowEl = LHSL;
2272     if (LowEl.Val) {
2273       // Turn this into an add/sub of the high part only.
2274       SDOperand HiEl =
2275         DAG.getNode(NodeOp == ISD::ADD_PARTS ? ISD::ADD : ISD::SUB,
2276                     LowEl.getValueType(), LHSH, RHSH);
2277       Lo = LowEl;
2278       Hi = HiEl;
2279       return;
2280     }
2281   }
2282
2283   std::vector<SDOperand> Ops;
2284   Ops.push_back(LHSL);
2285   Ops.push_back(LHSH);
2286   Ops.push_back(RHSL);
2287   Ops.push_back(RHSH);
2288
2289   std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
2290   Lo = DAG.getNode(NodeOp, VTs, Ops);
2291   Hi = Lo.getValue(1);
2292 }
2293
2294 void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
2295                                             SDOperand Op, SDOperand Amt,
2296                                             SDOperand &Lo, SDOperand &Hi) {
2297   // Expand the subcomponents.
2298   SDOperand LHSL, LHSH;
2299   ExpandOp(Op, LHSL, LHSH);
2300
2301   std::vector<SDOperand> Ops;
2302   Ops.push_back(LHSL);
2303   Ops.push_back(LHSH);
2304   Ops.push_back(Amt);
2305   std::vector<MVT::ValueType> VTs;
2306   VTs.push_back(LHSL.getValueType());
2307   VTs.push_back(LHSH.getValueType());
2308   VTs.push_back(Amt.getValueType());
2309   Lo = DAG.getNode(NodeOp, VTs, Ops);
2310   Hi = Lo.getValue(1);
2311 }
2312
2313
2314 /// ExpandShift - Try to find a clever way to expand this shift operation out to
2315 /// smaller elements.  If we can't find a way that is more efficient than a
2316 /// libcall on this target, return false.  Otherwise, return true with the
2317 /// low-parts expanded into Lo and Hi.
2318 bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
2319                                        SDOperand &Lo, SDOperand &Hi) {
2320   assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
2321          "This is not a shift!");
2322
2323   MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
2324   SDOperand ShAmt = LegalizeOp(Amt);
2325   MVT::ValueType ShTy = ShAmt.getValueType();
2326   unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
2327   unsigned NVTBits = MVT::getSizeInBits(NVT);
2328
2329   // Handle the case when Amt is an immediate.  Other cases are currently broken
2330   // and are disabled.
2331   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
2332     unsigned Cst = CN->getValue();
2333     // Expand the incoming operand to be shifted, so that we have its parts
2334     SDOperand InL, InH;
2335     ExpandOp(Op, InL, InH);
2336     switch(Opc) {
2337     case ISD::SHL:
2338       if (Cst > VTBits) {
2339         Lo = DAG.getConstant(0, NVT);
2340         Hi = DAG.getConstant(0, NVT);
2341       } else if (Cst > NVTBits) {
2342         Lo = DAG.getConstant(0, NVT);
2343         Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
2344       } else if (Cst == NVTBits) {
2345         Lo = DAG.getConstant(0, NVT);
2346         Hi = InL;
2347       } else {
2348         Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
2349         Hi = DAG.getNode(ISD::OR, NVT,
2350            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
2351            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
2352       }
2353       return true;
2354     case ISD::SRL:
2355       if (Cst > VTBits) {
2356         Lo = DAG.getConstant(0, NVT);
2357         Hi = DAG.getConstant(0, NVT);
2358       } else if (Cst > NVTBits) {
2359         Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
2360         Hi = DAG.getConstant(0, NVT);
2361       } else if (Cst == NVTBits) {
2362         Lo = InH;
2363         Hi = DAG.getConstant(0, NVT);
2364       } else {
2365         Lo = DAG.getNode(ISD::OR, NVT,
2366            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
2367            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
2368         Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
2369       }
2370       return true;
2371     case ISD::SRA:
2372       if (Cst > VTBits) {
2373         Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
2374                               DAG.getConstant(NVTBits-1, ShTy));
2375       } else if (Cst > NVTBits) {
2376         Lo = DAG.getNode(ISD::SRA, NVT, InH,
2377                            DAG.getConstant(Cst-NVTBits, ShTy));
2378         Hi = DAG.getNode(ISD::SRA, NVT, InH,
2379                               DAG.getConstant(NVTBits-1, ShTy));
2380       } else if (Cst == NVTBits) {
2381         Lo = InH;
2382         Hi = DAG.getNode(ISD::SRA, NVT, InH,
2383                               DAG.getConstant(NVTBits-1, ShTy));
2384       } else {
2385         Lo = DAG.getNode(ISD::OR, NVT,
2386            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
2387            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
2388         Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
2389       }
2390       return true;
2391     }
2392   }
2393   // FIXME: The following code for expanding shifts using ISD::SELECT is buggy,
2394   // so disable it for now.  Currently targets are handling this via SHL_PARTS
2395   // and friends.
2396   return false;
2397
2398   // If we have an efficient select operation (or if the selects will all fold
2399   // away), lower to some complex code, otherwise just emit the libcall.
2400   if (TLI.getOperationAction(ISD::SELECT, NVT) != TargetLowering::Legal &&
2401       !isa<ConstantSDNode>(Amt))
2402     return false;
2403
2404   SDOperand InL, InH;
2405   ExpandOp(Op, InL, InH);
2406   SDOperand NAmt = DAG.getNode(ISD::SUB, ShTy,           // NAmt = 32-ShAmt
2407                                DAG.getConstant(NVTBits, ShTy), ShAmt);
2408
2409   // Compare the unmasked shift amount against 32.
2410   SDOperand Cond = DAG.getSetCC(TLI.getSetCCResultTy(), ShAmt,
2411                                 DAG.getConstant(NVTBits, ShTy), ISD::SETGE);
2412
2413   if (TLI.getShiftAmountFlavor() != TargetLowering::Mask) {
2414     ShAmt = DAG.getNode(ISD::AND, ShTy, ShAmt,             // ShAmt &= 31
2415                         DAG.getConstant(NVTBits-1, ShTy));
2416     NAmt  = DAG.getNode(ISD::AND, ShTy, NAmt,              // NAmt &= 31
2417                         DAG.getConstant(NVTBits-1, ShTy));
2418   }
2419
2420   if (Opc == ISD::SHL) {
2421     SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << Amt) | (Lo >> NAmt)
2422                                DAG.getNode(ISD::SHL, NVT, InH, ShAmt),
2423                                DAG.getNode(ISD::SRL, NVT, InL, NAmt));
2424     SDOperand T2 = DAG.getNode(ISD::SHL, NVT, InL, ShAmt); // T2 = Lo << Amt&31
2425
2426     Hi = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
2427     Lo = DAG.getNode(ISD::SELECT, NVT, Cond, DAG.getConstant(0, NVT), T2);
2428   } else {
2429     SDOperand HiLoPart = DAG.getNode(ISD::SELECT, NVT,
2430                                      DAG.getSetCC(TLI.getSetCCResultTy(), NAmt,
2431                                                   DAG.getConstant(32, ShTy),
2432                                                   ISD::SETEQ),
2433                                      DAG.getConstant(0, NVT),
2434                                      DAG.getNode(ISD::SHL, NVT, InH, NAmt));
2435     SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << NAmt) | (Lo >> Amt)
2436                                HiLoPart,
2437                                DAG.getNode(ISD::SRL, NVT, InL, ShAmt));
2438     SDOperand T2 = DAG.getNode(Opc, NVT, InH, ShAmt);  // T2 = InH >> ShAmt&31
2439
2440     SDOperand HiPart;
2441     if (Opc == ISD::SRA)
2442       HiPart = DAG.getNode(ISD::SRA, NVT, InH,
2443                            DAG.getConstant(NVTBits-1, ShTy));
2444     else
2445       HiPart = DAG.getConstant(0, NVT);
2446     Lo = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
2447     Hi = DAG.getNode(ISD::SELECT, NVT, Cond, HiPart, T2);
2448   }
2449   return true;
2450 }
2451
2452 /// FindLatestCallSeqStart - Scan up the dag to find the latest (highest
2453 /// NodeDepth) node that is an CallSeqStart operation and occurs later than
2454 /// Found.
2455 static void FindLatestCallSeqStart(SDNode *Node, SDNode *&Found) {
2456   if (Node->getNodeDepth() <= Found->getNodeDepth()) return;
2457   
2458   // If we found an CALLSEQ_START, we already know this node occurs later
2459   // than the Found node. Just remember this node and return.
2460   if (Node->getOpcode() == ISD::CALLSEQ_START) {
2461     Found = Node;
2462     return;
2463   }
2464
2465   // Otherwise, scan the operands of Node to see if any of them is a call.
2466   assert(Node->getNumOperands() != 0 &&
2467          "All leaves should have depth equal to the entry node!");
2468   for (unsigned i = 0, e = Node->getNumOperands()-1; i != e; ++i)
2469     FindLatestCallSeqStart(Node->getOperand(i).Val, Found);
2470
2471   // Tail recurse for the last iteration.
2472   FindLatestCallSeqStart(Node->getOperand(Node->getNumOperands()-1).Val,
2473                              Found);
2474 }
2475
2476
2477 /// FindEarliestCallSeqEnd - Scan down the dag to find the earliest (lowest
2478 /// NodeDepth) node that is an CallSeqEnd operation and occurs more recent
2479 /// than Found.
2480 static void FindEarliestCallSeqEnd(SDNode *Node, SDNode *&Found,
2481                                    std::set<SDNode*> &Visited) {
2482   if ((Found && Node->getNodeDepth() >= Found->getNodeDepth()) ||
2483       !Visited.insert(Node).second) return;
2484
2485   // If we found an CALLSEQ_END, we already know this node occurs earlier
2486   // than the Found node. Just remember this node and return.
2487   if (Node->getOpcode() == ISD::CALLSEQ_END) {
2488     Found = Node;
2489     return;
2490   }
2491
2492   // Otherwise, scan the operands of Node to see if any of them is a call.
2493   SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
2494   if (UI == E) return;
2495   for (--E; UI != E; ++UI)
2496     FindEarliestCallSeqEnd(*UI, Found, Visited);
2497
2498   // Tail recurse for the last iteration.
2499   FindEarliestCallSeqEnd(*UI, Found, Visited);
2500 }
2501
2502 /// FindCallSeqEnd - Given a chained node that is part of a call sequence,
2503 /// find the CALLSEQ_END node that terminates the call sequence.
2504 static SDNode *FindCallSeqEnd(SDNode *Node) {
2505   if (Node->getOpcode() == ISD::CALLSEQ_END)
2506     return Node;
2507   if (Node->use_empty())
2508     return 0;   // No CallSeqEnd
2509
2510   if (Node->hasOneUse())  // Simple case, only has one user to check.
2511     return FindCallSeqEnd(*Node->use_begin());
2512
2513   SDOperand TheChain(Node, Node->getNumValues()-1);
2514   if (TheChain.getValueType() != MVT::Other)
2515     TheChain = SDOperand(Node, 0);
2516   assert(TheChain.getValueType() == MVT::Other && "Is not a token chain!");
2517
2518   for (SDNode::use_iterator UI = Node->use_begin(),
2519          E = Node->use_end(); UI != E; ++UI) {
2520
2521     // Make sure to only follow users of our token chain.
2522     SDNode *User = *UI;
2523     for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
2524       if (User->getOperand(i) == TheChain)
2525         if (SDNode *Result = FindCallSeqEnd(User))
2526           return Result;
2527   }
2528   return 0;
2529 }
2530
2531 /// FindCallSeqStart - Given a chained node that is part of a call sequence,
2532 /// find the CALLSEQ_START node that initiates the call sequence.
2533 static SDNode *FindCallSeqStart(SDNode *Node) {
2534   assert(Node && "Didn't find callseq_start for a call??");
2535   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
2536
2537   assert(Node->getOperand(0).getValueType() == MVT::Other &&
2538          "Node doesn't have a token chain argument!");
2539   return FindCallSeqStart(Node->getOperand(0).Val);
2540 }
2541
2542
2543 /// FindInputOutputChains - If we are replacing an operation with a call we need
2544 /// to find the call that occurs before and the call that occurs after it to
2545 /// properly serialize the calls in the block.  The returned operand is the
2546 /// input chain value for the new call (e.g. the entry node or the previous
2547 /// call), and OutChain is set to be the chain node to update to point to the
2548 /// end of the call chain.
2549 static SDOperand FindInputOutputChains(SDNode *OpNode, SDNode *&OutChain,
2550                                        SDOperand Entry) {
2551   SDNode *LatestCallSeqStart = Entry.Val;
2552   SDNode *LatestCallSeqEnd = 0;
2553   FindLatestCallSeqStart(OpNode, LatestCallSeqStart);
2554   //std::cerr<<"Found node: "; LatestCallSeqStart->dump(); std::cerr <<"\n";
2555
2556   // It is possible that no ISD::CALLSEQ_START was found because there is no
2557   // previous call in the function.  LatestCallStackDown may in that case be
2558   // the entry node itself.  Do not attempt to find a matching CALLSEQ_END
2559   // unless LatestCallStackDown is an CALLSEQ_START.
2560   if (LatestCallSeqStart->getOpcode() == ISD::CALLSEQ_START)
2561     LatestCallSeqEnd = FindCallSeqEnd(LatestCallSeqStart);
2562   else
2563     LatestCallSeqEnd = Entry.Val;
2564   assert(LatestCallSeqEnd && "NULL return from FindCallSeqEnd");
2565
2566   // Finally, find the first call that this must come before, first we find the
2567   // CallSeqEnd that ends the call.
2568   OutChain = 0;
2569   std::set<SDNode*> Visited;
2570   FindEarliestCallSeqEnd(OpNode, OutChain, Visited);
2571
2572   // If we found one, translate from the adj up to the callseq_start.
2573   if (OutChain)
2574     OutChain = FindCallSeqStart(OutChain);
2575
2576   return SDOperand(LatestCallSeqEnd, 0);
2577 }
2578
2579 /// SpliceCallInto - Given the result chain of a libcall (CallResult), and a
2580 void SelectionDAGLegalize::SpliceCallInto(const SDOperand &CallResult,
2581                                           SDNode *OutChain) {
2582   // Nothing to splice it into?
2583   if (OutChain == 0) return;
2584
2585   assert(OutChain->getOperand(0).getValueType() == MVT::Other);
2586   //OutChain->dump();
2587
2588   // Form a token factor node merging the old inval and the new inval.
2589   SDOperand InToken = DAG.getNode(ISD::TokenFactor, MVT::Other, CallResult,
2590                                   OutChain->getOperand(0));
2591   // Change the node to refer to the new token.
2592   OutChain->setAdjCallChain(InToken);
2593 }
2594
2595
2596 // ExpandLibCall - Expand a node into a call to a libcall.  If the result value
2597 // does not fit into a register, return the lo part and set the hi part to the
2598 // by-reg argument.  If it does fit into a single register, return the result
2599 // and leave the Hi part unset.
2600 SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
2601                                               SDOperand &Hi) {
2602   SDNode *OutChain;
2603   SDOperand InChain = FindInputOutputChains(Node, OutChain,
2604                                             DAG.getEntryNode());
2605   if (InChain.Val == 0)
2606     InChain = DAG.getEntryNode();
2607
2608   TargetLowering::ArgListTy Args;
2609   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2610     MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
2611     const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
2612     Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
2613   }
2614   SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
2615
2616   // Splice the libcall in wherever FindInputOutputChains tells us to.
2617   const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
2618   std::pair<SDOperand,SDOperand> CallInfo =
2619     TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, false,
2620                     Callee, Args, DAG);
2621   SpliceCallInto(CallInfo.second, OutChain);
2622
2623   NeedsAnotherIteration = true;
2624
2625   switch (getTypeAction(CallInfo.first.getValueType())) {
2626   default: assert(0 && "Unknown thing");
2627   case Legal:
2628     return CallInfo.first;
2629   case Promote:
2630     assert(0 && "Cannot promote this yet!");
2631   case Expand:
2632     SDOperand Lo;
2633     ExpandOp(CallInfo.first, Lo, Hi);
2634     return Lo;
2635   }
2636 }
2637
2638
2639 /// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
2640 /// destination type is legal.
2641 SDOperand SelectionDAGLegalize::
2642 ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
2643   assert(getTypeAction(DestTy) == Legal && "Destination type is not legal!");
2644   assert(getTypeAction(Source.getValueType()) == Expand &&
2645          "This is not an expansion!");
2646   assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
2647
2648   if (!isSigned) {
2649     assert(Source.getValueType() == MVT::i64 &&
2650            "This only works for 64-bit -> FP");
2651     // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
2652     // incoming integer is set.  To handle this, we dynamically test to see if
2653     // it is set, and, if so, add a fudge factor.
2654     SDOperand Lo, Hi;
2655     ExpandOp(Source, Lo, Hi);
2656
2657     // If this is unsigned, and not supported, first perform the conversion to
2658     // signed, then adjust the result if the sign bit is set.
2659     SDOperand SignedConv = ExpandIntToFP(true, DestTy,
2660                    DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), Lo, Hi));
2661
2662     SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
2663                                      DAG.getConstant(0, Hi.getValueType()),
2664                                      ISD::SETLT);
2665     SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
2666     SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
2667                                       SignSet, Four, Zero);
2668     uint64_t FF = 0x5f800000ULL;
2669     if (TLI.isLittleEndian()) FF <<= 32;
2670     static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
2671
2672     MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
2673     SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(FudgeFactor),
2674                                           TLI.getPointerTy());
2675     CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
2676     SDOperand FudgeInReg;
2677     if (DestTy == MVT::f32)
2678       FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
2679                                DAG.getSrcValue(NULL));
2680     else {
2681       assert(DestTy == MVT::f64 && "Unexpected conversion");
2682       FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
2683                                   CPIdx, DAG.getSrcValue(NULL), MVT::f32);
2684     }
2685     return DAG.getNode(ISD::ADD, DestTy, SignedConv, FudgeInReg);
2686   }
2687
2688   // Check to see if the target has a custom way to lower this.  If so, use it.
2689   switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
2690   default: assert(0 && "This action not implemented for this operation!");
2691   case TargetLowering::Legal:
2692   case TargetLowering::Expand:
2693     break;   // This case is handled below.
2694   case TargetLowering::Custom:
2695     Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
2696     return LegalizeOp(TLI.LowerOperation(Source, DAG));
2697   }
2698
2699   // Expand the source, then glue it back together for the call.  We must expand
2700   // the source in case it is shared (this pass of legalize must traverse it).
2701   SDOperand SrcLo, SrcHi;
2702   ExpandOp(Source, SrcLo, SrcHi);
2703   Source = DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), SrcLo, SrcHi);
2704
2705   SDNode *OutChain = 0;
2706   SDOperand InChain = FindInputOutputChains(Source.Val, OutChain,
2707                                             DAG.getEntryNode());
2708   const char *FnName = 0;
2709   if (DestTy == MVT::f32)
2710     FnName = "__floatdisf";
2711   else {
2712     assert(DestTy == MVT::f64 && "Unknown fp value type!");
2713     FnName = "__floatdidf";
2714   }
2715
2716   SDOperand Callee = DAG.getExternalSymbol(FnName, TLI.getPointerTy());
2717
2718   TargetLowering::ArgListTy Args;
2719   const Type *ArgTy = MVT::getTypeForValueType(Source.getValueType());
2720
2721   Args.push_back(std::make_pair(Source, ArgTy));
2722
2723   // We don't care about token chains for libcalls.  We just use the entry
2724   // node as our input and ignore the output chain.  This allows us to place
2725   // calls wherever we need them to satisfy data dependences.
2726   const Type *RetTy = MVT::getTypeForValueType(DestTy);
2727
2728   std::pair<SDOperand,SDOperand> CallResult =
2729     TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, true,
2730                     Callee, Args, DAG);
2731
2732   SpliceCallInto(CallResult.second, OutChain);
2733   return CallResult.first;
2734 }
2735
2736
2737
2738 /// ExpandOp - Expand the specified SDOperand into its two component pieces
2739 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
2740 /// LegalizeNodes map is filled in for any results that are not expanded, the
2741 /// ExpandedNodes map is filled in for any results that are expanded, and the
2742 /// Lo/Hi values are returned.
2743 void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
2744   MVT::ValueType VT = Op.getValueType();
2745   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
2746   SDNode *Node = Op.Val;
2747   assert(getTypeAction(VT) == Expand && "Not an expanded type!");
2748   assert(MVT::isInteger(VT) && "Cannot expand FP values!");
2749   assert(MVT::isInteger(NVT) && NVT < VT &&
2750          "Cannot expand to FP value or to larger int value!");
2751
2752   // If there is more than one use of this, see if we already expanded it.
2753   // There is no use remembering values that only have a single use, as the map
2754   // entries will never be reused.
2755   if (!Node->hasOneUse()) {
2756     std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
2757       = ExpandedNodes.find(Op);
2758     if (I != ExpandedNodes.end()) {
2759       Lo = I->second.first;
2760       Hi = I->second.second;
2761       return;
2762     }
2763   } else {
2764     assert(!ExpandedNodes.count(Op) && "Re-expanding a node!");
2765   }
2766
2767   // Expanding to multiple registers needs to perform an optimization step, and
2768   // is not careful to avoid operations the target does not support.  Make sure
2769   // that all generated operations are legalized in the next iteration.
2770   NeedsAnotherIteration = true;
2771
2772   switch (Node->getOpcode()) {
2773   default:
2774     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
2775     assert(0 && "Do not know how to expand this operator!");
2776     abort();
2777   case ISD::UNDEF:
2778     Lo = DAG.getNode(ISD::UNDEF, NVT);
2779     Hi = DAG.getNode(ISD::UNDEF, NVT);
2780     break;
2781   case ISD::Constant: {
2782     uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
2783     Lo = DAG.getConstant(Cst, NVT);
2784     Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
2785     break;
2786   }
2787
2788   case ISD::CopyFromReg: {
2789     unsigned Reg = cast<RegSDNode>(Node)->getReg();
2790     // Aggregate register values are always in consequtive pairs.
2791     Lo = DAG.getCopyFromReg(Reg, NVT, Node->getOperand(0));
2792     Hi = DAG.getCopyFromReg(Reg+1, NVT, Lo.getValue(1));
2793
2794     // Remember that we legalized the chain.
2795     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
2796
2797     assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
2798     break;
2799   }
2800
2801   case ISD::BUILD_PAIR:
2802     // Legalize both operands.  FIXME: in the future we should handle the case
2803     // where the two elements are not legal.
2804     assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
2805     Lo = LegalizeOp(Node->getOperand(0));
2806     Hi = LegalizeOp(Node->getOperand(1));
2807     break;
2808
2809   case ISD::CTPOP:
2810     ExpandOp(Node->getOperand(0), Lo, Hi);
2811     Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
2812                      DAG.getNode(ISD::CTPOP, NVT, Lo),
2813                      DAG.getNode(ISD::CTPOP, NVT, Hi));
2814     Hi = DAG.getConstant(0, NVT);
2815     break;
2816
2817   case ISD::CTLZ: {
2818     // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
2819     ExpandOp(Node->getOperand(0), Lo, Hi);
2820     SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
2821     SDOperand HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
2822     SDOperand TopNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), HLZ, BitsC,
2823                                         ISD::SETNE);
2824     SDOperand LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
2825     LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
2826
2827     Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
2828     Hi = DAG.getConstant(0, NVT);
2829     break;
2830   }
2831
2832   case ISD::CTTZ: {
2833     // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
2834     ExpandOp(Node->getOperand(0), Lo, Hi);
2835     SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
2836     SDOperand LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
2837     SDOperand BotNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), LTZ, BitsC,
2838                                         ISD::SETNE);
2839     SDOperand HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
2840     HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
2841
2842     Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
2843     Hi = DAG.getConstant(0, NVT);
2844     break;
2845   }
2846
2847   case ISD::LOAD: {
2848     SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
2849     SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2850     Lo = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
2851
2852     // Increment the pointer to the other half.
2853     unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
2854     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
2855                       getIntPtrConstant(IncrementSize));
2856     //Is this safe?  declaring that the two parts of the split load
2857     //are from the same instruction?
2858     Hi = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
2859
2860     // Build a factor node to remember that this load is independent of the
2861     // other one.
2862     SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
2863                                Hi.getValue(1));
2864
2865     // Remember that we legalized the chain.
2866     AddLegalizedOperand(Op.getValue(1), TF);
2867     if (!TLI.isLittleEndian())
2868       std::swap(Lo, Hi);
2869     break;
2870   }
2871   case ISD::TAILCALL:
2872   case ISD::CALL: {
2873     SDOperand Chain  = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2874     SDOperand Callee = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
2875
2876     bool Changed = false;
2877     std::vector<SDOperand> Ops;
2878     for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
2879       Ops.push_back(LegalizeOp(Node->getOperand(i)));
2880       Changed |= Ops.back() != Node->getOperand(i);
2881     }
2882
2883     assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
2884            "Can only expand a call once so far, not i64 -> i16!");
2885
2886     std::vector<MVT::ValueType> RetTyVTs;
2887     RetTyVTs.reserve(3);
2888     RetTyVTs.push_back(NVT);
2889     RetTyVTs.push_back(NVT);
2890     RetTyVTs.push_back(MVT::Other);
2891     SDNode *NC = DAG.getCall(RetTyVTs, Chain, Callee, Ops,
2892                              Node->getOpcode() == ISD::TAILCALL);
2893     Lo = SDOperand(NC, 0);
2894     Hi = SDOperand(NC, 1);
2895
2896     // Insert the new chain mapping.
2897     AddLegalizedOperand(Op.getValue(1), Hi.getValue(2));
2898     break;
2899   }
2900   case ISD::AND:
2901   case ISD::OR:
2902   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
2903     SDOperand LL, LH, RL, RH;
2904     ExpandOp(Node->getOperand(0), LL, LH);
2905     ExpandOp(Node->getOperand(1), RL, RH);
2906     Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
2907     Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
2908     break;
2909   }
2910   case ISD::SELECT: {
2911     SDOperand C, LL, LH, RL, RH;
2912
2913     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2914     case Expand: assert(0 && "It's impossible to expand bools");
2915     case Legal:
2916       C = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
2917       break;
2918     case Promote:
2919       C = PromoteOp(Node->getOperand(0));  // Promote the condition.
2920       break;
2921     }
2922     ExpandOp(Node->getOperand(1), LL, LH);
2923     ExpandOp(Node->getOperand(2), RL, RH);
2924     Lo = DAG.getNode(ISD::SELECT, NVT, C, LL, RL);
2925     Hi = DAG.getNode(ISD::SELECT, NVT, C, LH, RH);
2926     break;
2927   }
2928   case ISD::SELECT_CC: {
2929     SDOperand TL, TH, FL, FH;
2930     ExpandOp(Node->getOperand(2), TL, TH);
2931     ExpandOp(Node->getOperand(3), FL, FH);
2932     Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
2933                      Node->getOperand(1), TL, FL, Node->getOperand(4));
2934     Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
2935                      Node->getOperand(1), TH, FH, Node->getOperand(4));
2936     Lo = LegalizeOp(Lo);
2937     Hi = LegalizeOp(Hi);
2938     break;
2939   }
2940   case ISD::SIGN_EXTEND: {
2941     SDOperand In;
2942     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2943     case Expand: assert(0 && "expand-expand not implemented yet!");
2944     case Legal: In = LegalizeOp(Node->getOperand(0)); break;
2945     case Promote:
2946       In = PromoteOp(Node->getOperand(0));
2947       // Emit the appropriate sign_extend_inreg to get the value we want.
2948       In = DAG.getNode(ISD::SIGN_EXTEND_INREG, In.getValueType(), In,
2949                        DAG.getValueType(Node->getOperand(0).getValueType()));
2950       break;
2951     }
2952
2953     // The low part is just a sign extension of the input (which degenerates to
2954     // a copy).
2955     Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, In);
2956
2957     // The high part is obtained by SRA'ing all but one of the bits of the lo
2958     // part.
2959     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
2960     Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
2961                                                        TLI.getShiftAmountTy()));
2962     break;
2963   }
2964   case ISD::ZERO_EXTEND: {
2965     SDOperand In;
2966     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2967     case Expand: assert(0 && "expand-expand not implemented yet!");
2968     case Legal: In = LegalizeOp(Node->getOperand(0)); break;
2969     case Promote:
2970       In = PromoteOp(Node->getOperand(0));
2971       // Emit the appropriate zero_extend_inreg to get the value we want.
2972       In = DAG.getZeroExtendInReg(In, Node->getOperand(0).getValueType());
2973       break;
2974     }
2975
2976     // The low part is just a zero extension of the input (which degenerates to
2977     // a copy).
2978     Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, In);
2979
2980     // The high part is just a zero.
2981     Hi = DAG.getConstant(0, NVT);
2982     break;
2983   }
2984     // These operators cannot be expanded directly, emit them as calls to
2985     // library functions.
2986   case ISD::FP_TO_SINT:
2987     if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
2988       SDOperand Op;
2989       switch (getTypeAction(Node->getOperand(0).getValueType())) {
2990       case Expand: assert(0 && "cannot expand FP!");
2991       case Legal: Op = LegalizeOp(Node->getOperand(0)); break;
2992       case Promote: Op = PromoteOp(Node->getOperand(0)); break;
2993       }
2994
2995       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
2996
2997       // Now that the custom expander is done, expand the result, which is still
2998       // VT.
2999       ExpandOp(Op, Lo, Hi);
3000       break;
3001     }
3002
3003     if (Node->getOperand(0).getValueType() == MVT::f32)
3004       Lo = ExpandLibCall("__fixsfdi", Node, Hi);
3005     else
3006       Lo = ExpandLibCall("__fixdfdi", Node, Hi);
3007     break;
3008
3009   case ISD::FP_TO_UINT:
3010     if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
3011       SDOperand Op = DAG.getNode(ISD::FP_TO_UINT, VT,
3012                                  LegalizeOp(Node->getOperand(0)));
3013       // Now that the custom expander is done, expand the result, which is still
3014       // VT.
3015       ExpandOp(TLI.LowerOperation(Op, DAG), Lo, Hi);
3016       break;
3017     }
3018
3019     if (Node->getOperand(0).getValueType() == MVT::f32)
3020       Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
3021     else
3022       Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
3023     break;
3024
3025   case ISD::SHL:
3026     // If we can emit an efficient shift operation, do so now.
3027     if (ExpandShift(ISD::SHL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
3028       break;
3029
3030     // If this target supports SHL_PARTS, use it.
3031     if (TLI.getOperationAction(ISD::SHL_PARTS, NVT) == TargetLowering::Legal) {
3032       ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), Node->getOperand(1),
3033                        Lo, Hi);
3034       break;
3035     }
3036
3037     // Otherwise, emit a libcall.
3038     Lo = ExpandLibCall("__ashldi3", Node, Hi);
3039     break;
3040
3041   case ISD::SRA:
3042     // If we can emit an efficient shift operation, do so now.
3043     if (ExpandShift(ISD::SRA, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
3044       break;
3045
3046     // If this target supports SRA_PARTS, use it.
3047     if (TLI.getOperationAction(ISD::SRA_PARTS, NVT) == TargetLowering::Legal) {
3048       ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), Node->getOperand(1),
3049                        Lo, Hi);
3050       break;
3051     }
3052
3053     // Otherwise, emit a libcall.
3054     Lo = ExpandLibCall("__ashrdi3", Node, Hi);
3055     break;
3056   case ISD::SRL:
3057     // If we can emit an efficient shift operation, do so now.
3058     if (ExpandShift(ISD::SRL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
3059       break;
3060
3061     // If this target supports SRL_PARTS, use it.
3062     if (TLI.getOperationAction(ISD::SRL_PARTS, NVT) == TargetLowering::Legal) {
3063       ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), Node->getOperand(1),
3064                        Lo, Hi);
3065       break;
3066     }
3067
3068     // Otherwise, emit a libcall.
3069     Lo = ExpandLibCall("__lshrdi3", Node, Hi);
3070     break;
3071
3072   case ISD::ADD:
3073     ExpandByParts(ISD::ADD_PARTS, Node->getOperand(0), Node->getOperand(1),
3074                   Lo, Hi);
3075     break;
3076   case ISD::SUB:
3077     ExpandByParts(ISD::SUB_PARTS, Node->getOperand(0), Node->getOperand(1),
3078                   Lo, Hi);
3079     break;
3080   case ISD::MUL: {
3081     if (TLI.getOperationAction(ISD::MULHU, NVT) == TargetLowering::Legal) {
3082       SDOperand LL, LH, RL, RH;
3083       ExpandOp(Node->getOperand(0), LL, LH);
3084       ExpandOp(Node->getOperand(1), RL, RH);
3085       Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
3086       RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
3087       LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
3088       Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
3089       Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
3090       Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
3091     } else {
3092       Lo = ExpandLibCall("__muldi3" , Node, Hi); break;
3093     }
3094     break;
3095   }
3096   case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
3097   case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
3098   case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
3099   case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
3100   }
3101
3102   // Remember in a map if the values will be reused later.
3103   if (!Node->hasOneUse()) {
3104     bool isNew = ExpandedNodes.insert(std::make_pair(Op,
3105                                             std::make_pair(Lo, Hi))).second;
3106     assert(isNew && "Value already expanded?!?");
3107   }
3108 }
3109
3110
3111 // SelectionDAG::Legalize - This is the entry point for the file.
3112 //
3113 void SelectionDAG::Legalize() {
3114   /// run - This is the main entry point to this class.
3115   ///
3116   SelectionDAGLegalize(*this).Run();
3117 }
3118