Add bswap, rotl, and rotr nodes
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeDAG.cpp
1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SelectionDAG::Legalize method.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/Support/MathExtras.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 long long 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     LegalizedNodes.insert(std::make_pair(From, To));
81     // If someone requests legalization of the new node, return itself.
82     if (From != To)
83       LegalizedNodes.insert(std::make_pair(To, To));
84   }
85   void AddPromotedOperand(SDOperand From, SDOperand To) {
86     bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
87     assert(isNew && "Got into the map somehow?");
88     // If someone requests legalization of the new node, return itself.
89     LegalizedNodes.insert(std::make_pair(To, To));
90   }
91
92 public:
93
94   SelectionDAGLegalize(SelectionDAG &DAG);
95
96   /// Run - While there is still lowering to do, perform a pass over the DAG.
97   /// Most regularization can be done in a single pass, but targets that require
98   /// large values to be split into registers multiple times (e.g. i64 -> 4x
99   /// i16) require iteration for these values (the first iteration will demote
100   /// to i32, the second will demote to i16).
101   void Run() {
102     do {
103       NeedsAnotherIteration = false;
104       LegalizeDAG();
105     } while (NeedsAnotherIteration);
106   }
107
108   /// getTypeAction - Return how we should legalize values of this type, either
109   /// it is already legal or we need to expand it into multiple registers of
110   /// smaller integer type, or we need to promote it to a larger type.
111   LegalizeAction getTypeAction(MVT::ValueType VT) const {
112     return (LegalizeAction)((ValueTypeActions >> (2*VT)) & 3);
113   }
114
115   /// isTypeLegal - Return true if this type is legal on this target.
116   ///
117   bool isTypeLegal(MVT::ValueType VT) const {
118     return getTypeAction(VT) == Legal;
119   }
120
121 private:
122   void LegalizeDAG();
123
124   SDOperand LegalizeOp(SDOperand O);
125   void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
126   SDOperand PromoteOp(SDOperand O);
127
128   SDOperand ExpandLibCall(const char *Name, SDNode *Node,
129                           SDOperand &Hi);
130   SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
131                           SDOperand Source);
132
133   SDOperand ExpandBIT_CONVERT(MVT::ValueType DestVT, SDOperand SrcOp);
134   SDOperand ExpandLegalINT_TO_FP(bool isSigned,
135                                  SDOperand LegalOp,
136                                  MVT::ValueType DestVT);
137   SDOperand PromoteLegalINT_TO_FP(SDOperand LegalOp, MVT::ValueType DestVT,
138                                   bool isSigned);
139   SDOperand PromoteLegalFP_TO_INT(SDOperand LegalOp, MVT::ValueType DestVT,
140                                   bool isSigned);
141
142   bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
143                    SDOperand &Lo, SDOperand &Hi);
144   void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
145                         SDOperand &Lo, SDOperand &Hi);
146   void ExpandByParts(unsigned NodeOp, SDOperand LHS, SDOperand RHS,
147                      SDOperand &Lo, SDOperand &Hi);
148
149   void SpliceCallInto(const SDOperand &CallResult, SDNode *OutChain);
150
151   SDOperand getIntPtrConstant(uint64_t Val) {
152     return DAG.getConstant(Val, TLI.getPointerTy());
153   }
154 };
155 }
156
157 static unsigned getScalarizedOpcode(unsigned VecOp, MVT::ValueType VT) {
158   switch (VecOp) {
159   default: assert(0 && "Don't know how to scalarize this opcode!");
160   case ISD::VADD: return MVT::isInteger(VT) ? ISD::ADD : ISD::FADD;
161   case ISD::VSUB: return MVT::isInteger(VT) ? ISD::SUB : ISD::FSUB;
162   case ISD::VMUL: return MVT::isInteger(VT) ? ISD::MUL : ISD::FMUL;
163   }
164 }
165
166 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
167   : TLI(dag.getTargetLoweringInfo()), DAG(dag),
168     ValueTypeActions(TLI.getValueTypeActions()) {
169   assert(MVT::LAST_VALUETYPE <= 32 &&
170          "Too many value types for ValueTypeActions to hold!");
171 }
172
173 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
174 /// INT_TO_FP operation of the specified operand when the target requests that
175 /// we expand it.  At this point, we know that the result and operand types are
176 /// legal for the target.
177 SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
178                                                      SDOperand Op0,
179                                                      MVT::ValueType DestVT) {
180   if (Op0.getValueType() == MVT::i32) {
181     // simple 32-bit [signed|unsigned] integer to float/double expansion
182     
183     // get the stack frame index of a 8 byte buffer
184     MachineFunction &MF = DAG.getMachineFunction();
185     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
186     // get address of 8 byte buffer
187     SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
188     // word offset constant for Hi/Lo address computation
189     SDOperand WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
190     // set up Hi and Lo (into buffer) address based on endian
191     SDOperand Hi, Lo;
192     if (TLI.isLittleEndian()) {
193       Hi = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot, WordOff);
194       Lo = StackSlot;
195     } else {
196       Hi = StackSlot;
197       Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot, WordOff);
198     }
199     // if signed map to unsigned space
200     SDOperand Op0Mapped;
201     if (isSigned) {
202       // constant used to invert sign bit (signed to unsigned mapping)
203       SDOperand SignBit = DAG.getConstant(0x80000000u, MVT::i32);
204       Op0Mapped = DAG.getNode(ISD::XOR, MVT::i32, Op0, SignBit);
205     } else {
206       Op0Mapped = Op0;
207     }
208     // store the lo of the constructed double - based on integer input
209     SDOperand Store1 = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
210                                    Op0Mapped, Lo, DAG.getSrcValue(NULL));
211     // initial hi portion of constructed double
212     SDOperand InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
213     // store the hi of the constructed double - biased exponent
214     SDOperand Store2 = DAG.getNode(ISD::STORE, MVT::Other, Store1,
215                                    InitialHi, Hi, DAG.getSrcValue(NULL));
216     // load the constructed double
217     SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot,
218                                DAG.getSrcValue(NULL));
219     // FP constant to bias correct the final result
220     SDOperand Bias = DAG.getConstantFP(isSigned ?
221                                             BitsToDouble(0x4330000080000000ULL)
222                                           : BitsToDouble(0x4330000000000000ULL),
223                                      MVT::f64);
224     // subtract the bias
225     SDOperand Sub = DAG.getNode(ISD::FSUB, MVT::f64, Load, Bias);
226     // final result
227     SDOperand Result;
228     // handle final rounding
229     if (DestVT == MVT::f64) {
230       // do nothing
231       Result = Sub;
232     } else {
233      // if f32 then cast to f32
234       Result = DAG.getNode(ISD::FP_ROUND, MVT::f32, Sub);
235     }
236     return LegalizeOp(Result);
237   }
238   assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
239   SDOperand Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
240
241   SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Op0,
242                                    DAG.getConstant(0, Op0.getValueType()),
243                                    ISD::SETLT);
244   SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
245   SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
246                                     SignSet, Four, Zero);
247
248   // If the sign bit of the integer is set, the large number will be treated
249   // as a negative number.  To counteract this, the dynamic code adds an
250   // offset depending on the data type.
251   uint64_t FF;
252   switch (Op0.getValueType()) {
253   default: assert(0 && "Unsupported integer type!");
254   case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
255   case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
256   case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
257   case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
258   }
259   if (TLI.isLittleEndian()) FF <<= 32;
260   static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
261
262   SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
263   CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
264   SDOperand FudgeInReg;
265   if (DestVT == MVT::f32)
266     FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
267                              DAG.getSrcValue(NULL));
268   else {
269     assert(DestVT == MVT::f64 && "Unexpected conversion");
270     FudgeInReg = LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, MVT::f64,
271                                            DAG.getEntryNode(), CPIdx,
272                                            DAG.getSrcValue(NULL), MVT::f32));
273   }
274
275   return LegalizeOp(DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg));
276 }
277
278 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
279 /// *INT_TO_FP operation of the specified operand when the target requests that
280 /// we promote it.  At this point, we know that the result and operand types are
281 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
282 /// operation that takes a larger input.
283 SDOperand SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDOperand LegalOp,
284                                                       MVT::ValueType DestVT,
285                                                       bool isSigned) {
286   // First step, figure out the appropriate *INT_TO_FP operation to use.
287   MVT::ValueType NewInTy = LegalOp.getValueType();
288
289   unsigned OpToUse = 0;
290
291   // Scan for the appropriate larger type to use.
292   while (1) {
293     NewInTy = (MVT::ValueType)(NewInTy+1);
294     assert(MVT::isInteger(NewInTy) && "Ran out of possibilities!");
295
296     // If the target supports SINT_TO_FP of this type, use it.
297     switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
298       default: break;
299       case TargetLowering::Legal:
300         if (!TLI.isTypeLegal(NewInTy))
301           break;  // Can't use this datatype.
302         // FALL THROUGH.
303       case TargetLowering::Custom:
304         OpToUse = ISD::SINT_TO_FP;
305         break;
306     }
307     if (OpToUse) break;
308     if (isSigned) continue;
309
310     // If the target supports UINT_TO_FP of this type, use it.
311     switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
312       default: break;
313       case TargetLowering::Legal:
314         if (!TLI.isTypeLegal(NewInTy))
315           break;  // Can't use this datatype.
316         // FALL THROUGH.
317       case TargetLowering::Custom:
318         OpToUse = ISD::UINT_TO_FP;
319         break;
320     }
321     if (OpToUse) break;
322
323     // Otherwise, try a larger type.
324   }
325
326   // Okay, we found the operation and type to use.  Zero extend our input to the
327   // desired type then run the operation on it.
328   SDOperand N = DAG.getNode(OpToUse, DestVT,
329                      DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
330                                  NewInTy, LegalOp));
331   // Make sure to legalize any nodes we create here.
332   return LegalizeOp(N);
333 }
334
335 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
336 /// FP_TO_*INT operation of the specified operand when the target requests that
337 /// we promote it.  At this point, we know that the result and operand types are
338 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
339 /// operation that returns a larger result.
340 SDOperand SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDOperand LegalOp,
341                                                       MVT::ValueType DestVT,
342                                                       bool isSigned) {
343   // First step, figure out the appropriate FP_TO*INT operation to use.
344   MVT::ValueType NewOutTy = DestVT;
345
346   unsigned OpToUse = 0;
347
348   // Scan for the appropriate larger type to use.
349   while (1) {
350     NewOutTy = (MVT::ValueType)(NewOutTy+1);
351     assert(MVT::isInteger(NewOutTy) && "Ran out of possibilities!");
352
353     // If the target supports FP_TO_SINT returning this type, use it.
354     switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
355     default: break;
356     case TargetLowering::Legal:
357       if (!TLI.isTypeLegal(NewOutTy))
358         break;  // Can't use this datatype.
359       // FALL THROUGH.
360     case TargetLowering::Custom:
361       OpToUse = ISD::FP_TO_SINT;
362       break;
363     }
364     if (OpToUse) break;
365
366     // If the target supports FP_TO_UINT of this type, use it.
367     switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
368     default: break;
369     case TargetLowering::Legal:
370       if (!TLI.isTypeLegal(NewOutTy))
371         break;  // Can't use this datatype.
372       // FALL THROUGH.
373     case TargetLowering::Custom:
374       OpToUse = ISD::FP_TO_UINT;
375       break;
376     }
377     if (OpToUse) break;
378
379     // Otherwise, try a larger type.
380   }
381
382   // Okay, we found the operation and type to use.  Truncate the result of the
383   // extended FP_TO_*INT operation to the desired size.
384   SDOperand N = DAG.getNode(ISD::TRUNCATE, DestVT,
385                             DAG.getNode(OpToUse, NewOutTy, LegalOp));
386   // Make sure to legalize any nodes we create here in the next pass.
387   return LegalizeOp(N);
388 }
389
390 /// ComputeTopDownOrdering - Add the specified node to the Order list if it has
391 /// not been visited yet and if all of its operands have already been visited.
392 static void ComputeTopDownOrdering(SDNode *N, std::vector<SDNode*> &Order,
393                                    std::map<SDNode*, unsigned> &Visited) {
394   if (++Visited[N] != N->getNumOperands())
395     return;  // Haven't visited all operands yet
396   
397   Order.push_back(N);
398   
399   if (N->hasOneUse()) { // Tail recurse in common case.
400     ComputeTopDownOrdering(*N->use_begin(), Order, Visited);
401     return;
402   }
403   
404   // Now that we have N in, add anything that uses it if all of their operands
405   // are now done.
406   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); UI != E;++UI)
407     ComputeTopDownOrdering(*UI, Order, Visited);
408 }
409
410
411 void SelectionDAGLegalize::LegalizeDAG() {
412   // The legalize process is inherently a bottom-up recursive process (users
413   // legalize their uses before themselves).  Given infinite stack space, we
414   // could just start legalizing on the root and traverse the whole graph.  In
415   // practice however, this causes us to run out of stack space on large basic
416   // blocks.  To avoid this problem, compute an ordering of the nodes where each
417   // node is only legalized after all of its operands are legalized.
418   std::map<SDNode*, unsigned> Visited;
419   std::vector<SDNode*> Order;
420   
421   // Compute ordering from all of the leaves in the graphs, those (like the
422   // entry node) that have no operands.
423   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
424        E = DAG.allnodes_end(); I != E; ++I) {
425     if (I->getNumOperands() == 0) {
426       Visited[I] = 0 - 1U;
427       ComputeTopDownOrdering(I, Order, Visited);
428     }
429   }
430   
431   assert(Order.size() == Visited.size() &&
432          Order.size() == 
433             (unsigned)std::distance(DAG.allnodes_begin(), DAG.allnodes_end()) &&
434          "Error: DAG is cyclic!");
435   Visited.clear();
436   
437   for (unsigned i = 0, e = Order.size(); i != e; ++i) {
438     SDNode *N = Order[i];
439     switch (getTypeAction(N->getValueType(0))) {
440     default: assert(0 && "Bad type action!");
441     case Legal:
442       LegalizeOp(SDOperand(N, 0));
443       break;
444     case Promote:
445       PromoteOp(SDOperand(N, 0));
446       break;
447     case Expand: {
448       SDOperand X, Y;
449       ExpandOp(SDOperand(N, 0), X, Y);
450       break;
451     }
452     }
453   }
454
455   // Finally, it's possible the root changed.  Get the new root.
456   SDOperand OldRoot = DAG.getRoot();
457   assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
458   DAG.setRoot(LegalizedNodes[OldRoot]);
459
460   ExpandedNodes.clear();
461   LegalizedNodes.clear();
462   PromotedNodes.clear();
463
464   // Remove dead nodes now.
465   DAG.RemoveDeadNodes(OldRoot.Val);
466 }
467
468 SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
469   assert(isTypeLegal(Op.getValueType()) &&
470          "Caller should expand or promote operands that are not legal!");
471   SDNode *Node = Op.Val;
472
473   // If this operation defines any values that cannot be represented in a
474   // register on this target, make sure to expand or promote them.
475   if (Node->getNumValues() > 1) {
476     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
477       switch (getTypeAction(Node->getValueType(i))) {
478       case Legal: break;  // Nothing to do.
479       case Expand: {
480         SDOperand T1, T2;
481         ExpandOp(Op.getValue(i), T1, T2);
482         assert(LegalizedNodes.count(Op) &&
483                "Expansion didn't add legal operands!");
484         return LegalizedNodes[Op];
485       }
486       case Promote:
487         PromoteOp(Op.getValue(i));
488         assert(LegalizedNodes.count(Op) &&
489                "Expansion didn't add legal operands!");
490         return LegalizedNodes[Op];
491       }
492   }
493
494   // Note that LegalizeOp may be reentered even from single-use nodes, which
495   // means that we always must cache transformed nodes.
496   std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
497   if (I != LegalizedNodes.end()) return I->second;
498
499   SDOperand Tmp1, Tmp2, Tmp3, Tmp4;
500
501   SDOperand Result = Op;
502
503   switch (Node->getOpcode()) {
504   default:
505     if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
506       // If this is a target node, legalize it by legalizing the operands then
507       // passing it through.
508       std::vector<SDOperand> Ops;
509       bool Changed = false;
510       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
511         Ops.push_back(LegalizeOp(Node->getOperand(i)));
512         Changed = Changed || Node->getOperand(i) != Ops.back();
513       }
514       if (Changed)
515         if (Node->getNumValues() == 1)
516           Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
517         else {
518           std::vector<MVT::ValueType> VTs(Node->value_begin(),
519                                           Node->value_end());
520           Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
521         }
522
523       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
524         AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
525       return Result.getValue(Op.ResNo);
526     }
527     // Otherwise this is an unhandled builtin node.  splat.
528     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
529     assert(0 && "Do not know how to legalize this operator!");
530     abort();
531   case ISD::EntryToken:
532   case ISD::FrameIndex:
533   case ISD::TargetFrameIndex:
534   case ISD::Register:
535   case ISD::TargetConstant:
536   case ISD::TargetConstantPool:
537   case ISD::GlobalAddress:
538   case ISD::TargetGlobalAddress:
539   case ISD::ExternalSymbol:
540   case ISD::TargetExternalSymbol:
541   case ISD::ConstantPool:           // Nothing to do.
542   case ISD::BasicBlock:
543   case ISD::CONDCODE:
544   case ISD::VALUETYPE:
545   case ISD::SRCVALUE:
546   case ISD::STRING:
547     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
548     default: assert(0 && "This action is not supported yet!");
549     case TargetLowering::Custom: {
550       SDOperand Tmp = TLI.LowerOperation(Op, DAG);
551       if (Tmp.Val) {
552         Result = LegalizeOp(Tmp);
553         break;
554       }
555     } // FALLTHROUGH if the target doesn't want to lower this op after all.
556     case TargetLowering::Legal:
557       assert(isTypeLegal(Node->getValueType(0)) && "This must be legal!");
558       break;
559     }
560     break;
561   case ISD::AssertSext:
562   case ISD::AssertZext:
563     Tmp1 = LegalizeOp(Node->getOperand(0));
564     if (Tmp1 != Node->getOperand(0))
565       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
566                            Node->getOperand(1));
567     break;
568   case ISD::MERGE_VALUES:
569     return LegalizeOp(Node->getOperand(Op.ResNo));
570   case ISD::CopyFromReg:
571     Tmp1 = LegalizeOp(Node->getOperand(0));
572     Result = Op.getValue(0);
573     if (Node->getNumValues() == 2) {
574       if (Tmp1 != Node->getOperand(0))
575         Result = DAG.getCopyFromReg(Tmp1, 
576                             cast<RegisterSDNode>(Node->getOperand(1))->getReg(),
577                                     Node->getValueType(0));
578     } else {
579       assert(Node->getNumValues() == 3 && "Invalid copyfromreg!");
580       if (Node->getNumOperands() == 3)
581         Tmp2 = LegalizeOp(Node->getOperand(2));
582       if (Tmp1 != Node->getOperand(0) ||
583           (Node->getNumOperands() == 3 && Tmp2 != Node->getOperand(2)))
584         Result = DAG.getCopyFromReg(Tmp1, 
585                             cast<RegisterSDNode>(Node->getOperand(1))->getReg(),
586                                     Node->getValueType(0), Tmp2);
587       AddLegalizedOperand(Op.getValue(2), Result.getValue(2));
588     }
589     // Since CopyFromReg produces two values, make sure to remember that we
590     // legalized both of them.
591     AddLegalizedOperand(Op.getValue(0), Result);
592     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
593     return Result.getValue(Op.ResNo);
594   case ISD::UNDEF: {
595     MVT::ValueType VT = Op.getValueType();
596     switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
597     default: assert(0 && "This action is not supported yet!");
598     case TargetLowering::Expand:
599     case TargetLowering::Promote:
600       if (MVT::isInteger(VT))
601         Result = DAG.getConstant(0, VT);
602       else if (MVT::isFloatingPoint(VT))
603         Result = DAG.getConstantFP(0, VT);
604       else
605         assert(0 && "Unknown value type!");
606       break;
607     case TargetLowering::Legal:
608       break;
609     }
610     break;
611   }
612
613   case ISD::LOCATION:
614     assert(Node->getNumOperands() == 5 && "Invalid LOCATION node!");
615     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
616     
617     switch (TLI.getOperationAction(ISD::LOCATION, MVT::Other)) {
618     case TargetLowering::Promote:
619     default: assert(0 && "This action is not supported yet!");
620     case TargetLowering::Expand: {
621       MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
622       bool useDEBUG_LOC = TLI.isOperationLegal(ISD::DEBUG_LOC, MVT::Other);
623       bool useDEBUG_LABEL = TLI.isOperationLegal(ISD::DEBUG_LABEL, MVT::Other);
624       
625       if (DebugInfo && (useDEBUG_LOC || useDEBUG_LABEL)) {
626         const std::string &FName =
627           cast<StringSDNode>(Node->getOperand(3))->getValue();
628         const std::string &DirName = 
629           cast<StringSDNode>(Node->getOperand(4))->getValue();
630         unsigned SrcFile = DebugInfo->getUniqueSourceID(FName, DirName);
631
632         std::vector<SDOperand> Ops;
633         Ops.push_back(Tmp1);  // chain
634         SDOperand LineOp = Node->getOperand(1);
635         SDOperand ColOp = Node->getOperand(2);
636         
637         if (useDEBUG_LOC) {
638           Ops.push_back(LineOp);  // line #
639           Ops.push_back(ColOp);  // col #
640           Ops.push_back(DAG.getConstant(SrcFile, MVT::i32));  // source file id
641           Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, Ops);
642         } else {
643           unsigned Line = dyn_cast<ConstantSDNode>(LineOp)->getValue();
644           unsigned Col = dyn_cast<ConstantSDNode>(ColOp)->getValue();
645           unsigned ID = DebugInfo->RecordLabel(Line, Col, SrcFile);
646           Ops.push_back(DAG.getConstant(ID, MVT::i32));
647           Result = DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops);
648         }
649       } else {
650         Result = Tmp1;  // chain
651       }
652       Result = LegalizeOp(Result);  // Relegalize new nodes.
653       break;
654     }
655     case TargetLowering::Legal:
656       if (Tmp1 != Node->getOperand(0) ||
657           getTypeAction(Node->getOperand(1).getValueType()) == Promote) {
658         std::vector<SDOperand> Ops;
659         Ops.push_back(Tmp1);
660         if (getTypeAction(Node->getOperand(1).getValueType()) == Legal) {
661           Ops.push_back(Node->getOperand(1));  // line # must be legal.
662           Ops.push_back(Node->getOperand(2));  // col # must be legal.
663         } else {
664           // Otherwise promote them.
665           Ops.push_back(PromoteOp(Node->getOperand(1)));
666           Ops.push_back(PromoteOp(Node->getOperand(2)));
667         }
668         Ops.push_back(Node->getOperand(3));  // filename must be legal.
669         Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
670         Result = DAG.getNode(ISD::LOCATION, MVT::Other, Ops);
671       }
672       break;
673     }
674     break;
675     
676   case ISD::DEBUG_LOC:
677     assert(Node->getNumOperands() == 4 && "Invalid DEBUG_LOC node!");
678     switch (TLI.getOperationAction(ISD::DEBUG_LOC, MVT::Other)) {
679     case TargetLowering::Promote:
680     case TargetLowering::Expand:
681     default: assert(0 && "This action is not supported yet!");
682     case TargetLowering::Legal:
683       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
684       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the line #.
685       Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the col #.
686       Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize the source file id.
687       
688       if (Tmp1 != Node->getOperand(0) ||
689           Tmp2 != Node->getOperand(1) ||
690           Tmp3 != Node->getOperand(2) ||
691           Tmp4 != Node->getOperand(3)) {
692         Result = DAG.getNode(ISD::DEBUG_LOC,MVT::Other, Tmp1, Tmp2, Tmp3, Tmp4);
693       }
694       break;
695     }
696     break;    
697
698   case ISD::DEBUG_LABEL:
699     assert(Node->getNumOperands() == 2 && "Invalid DEBUG_LABEL node!");
700     switch (TLI.getOperationAction(ISD::DEBUG_LABEL, MVT::Other)) {
701     case TargetLowering::Promote:
702     case TargetLowering::Expand:
703     default: assert(0 && "This action is not supported yet!");
704     case TargetLowering::Legal:
705       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
706       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the label id.
707       
708       if (Tmp1 != Node->getOperand(0) ||
709           Tmp2 != Node->getOperand(1)) {
710         Result = DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Tmp1, Tmp2);
711       }
712       break;
713     }
714     break;    
715
716   case ISD::Constant:
717     // We know we don't need to expand constants here, constants only have one
718     // value and we check that it is fine above.
719
720     // FIXME: Maybe we should handle things like targets that don't support full
721     // 32-bit immediates?
722     break;
723   case ISD::ConstantFP: {
724     // Spill FP immediates to the constant pool if the target cannot directly
725     // codegen them.  Targets often have some immediate values that can be
726     // efficiently generated into an FP register without a load.  We explicitly
727     // leave these constants as ConstantFP nodes for the target to deal with.
728
729     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
730
731     // Check to see if this FP immediate is already legal.
732     bool isLegal = false;
733     for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
734            E = TLI.legal_fpimm_end(); I != E; ++I)
735       if (CFP->isExactlyValue(*I)) {
736         isLegal = true;
737         break;
738       }
739
740     if (!isLegal) {
741       // Otherwise we need to spill the constant to memory.
742       bool Extend = false;
743
744       // If a FP immediate is precise when represented as a float, we put it
745       // into the constant pool as a float, even if it's is statically typed
746       // as a double.
747       MVT::ValueType VT = CFP->getValueType(0);
748       bool isDouble = VT == MVT::f64;
749       ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
750                                              Type::FloatTy, CFP->getValue());
751       if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
752           // Only do this if the target has a native EXTLOAD instruction from
753           // f32.
754           TLI.isOperationLegal(ISD::EXTLOAD, MVT::f32)) {
755         LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
756         VT = MVT::f32;
757         Extend = true;
758       }
759
760       SDOperand CPIdx = 
761         LegalizeOp(DAG.getConstantPool(LLVMC, TLI.getPointerTy()));
762       if (Extend) {
763         Result = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
764                                 CPIdx, DAG.getSrcValue(NULL), MVT::f32);
765       } else {
766         Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
767                              DAG.getSrcValue(NULL));
768       }
769     }
770     break;
771   }
772   case ISD::ConstantVec: {
773     // We assume that vector constants are not legal, and will be immediately
774     // spilled to the constant pool.
775     //
776     // FIXME: revisit this when we have some kind of mechanism by which targets
777     // can decided legality of vector constants, of which there may be very
778     // many.
779     //
780     // Create a ConstantPacked, and put it in the constant pool.
781     std::vector<Constant*> CV;
782     MVT::ValueType VT = Node->getValueType(0);
783     for (unsigned I = 0, E = Node->getNumOperands(); I < E; ++I) {
784       SDOperand OpN = Node->getOperand(I);
785       const Type* OpNTy = MVT::getTypeForValueType(OpN.getValueType());
786       if (MVT::isFloatingPoint(VT))
787         CV.push_back(ConstantFP::get(OpNTy, 
788                                      cast<ConstantFPSDNode>(OpN)->getValue()));
789       else
790         CV.push_back(ConstantUInt::get(OpNTy,
791                                        cast<ConstantSDNode>(OpN)->getValue()));
792     }
793     Constant *CP = ConstantPacked::get(CV);
794     SDOperand CPIdx = LegalizeOp(DAG.getConstantPool(CP, TLI.getPointerTy()));
795     Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, DAG.getSrcValue(NULL));
796     break;
797   }
798   case ISD::TokenFactor:
799     if (Node->getNumOperands() == 2) {
800       bool Changed = false;
801       SDOperand Op0 = LegalizeOp(Node->getOperand(0));
802       SDOperand Op1 = LegalizeOp(Node->getOperand(1));
803       if (Op0 != Node->getOperand(0) || Op1 != Node->getOperand(1))
804         Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);
805     } else {
806       std::vector<SDOperand> Ops;
807       bool Changed = false;
808       // Legalize the operands.
809       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
810         SDOperand Op = Node->getOperand(i);
811         Ops.push_back(LegalizeOp(Op));
812         Changed |= Ops[i] != Op;
813       }
814       if (Changed)
815         Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
816     }
817     break;
818
819   case ISD::CALLSEQ_START:
820   case ISD::CALLSEQ_END:
821     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
822     // Do not try to legalize the target-specific arguments (#1+)
823     Tmp2 = Node->getOperand(0);
824     if (Tmp1 != Tmp2)
825       Node->setAdjCallChain(Tmp1);
826       
827     // Note that we do not create new CALLSEQ_DOWN/UP nodes here.  These
828     // nodes are treated specially and are mutated in place.  This makes the dag
829     // legalization process more efficient and also makes libcall insertion
830     // easier.
831     break;
832   case ISD::DYNAMIC_STACKALLOC:
833     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
834     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
835     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
836     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
837         Tmp3 != Node->getOperand(2)) {
838       std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
839       std::vector<SDOperand> Ops;
840       Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
841       Result = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
842     } else
843       Result = Op.getValue(0);
844
845     // Since this op produces two values, make sure to remember that we
846     // legalized both of them.
847     AddLegalizedOperand(SDOperand(Node, 0), Result);
848     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
849     return Result.getValue(Op.ResNo);
850
851   case ISD::TAILCALL:
852   case ISD::CALL: {
853     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
854     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
855
856     bool Changed = false;
857     std::vector<SDOperand> Ops;
858     for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
859       Ops.push_back(LegalizeOp(Node->getOperand(i)));
860       Changed |= Ops.back() != Node->getOperand(i);
861     }
862
863     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) || Changed) {
864       std::vector<MVT::ValueType> RetTyVTs;
865       RetTyVTs.reserve(Node->getNumValues());
866       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
867         RetTyVTs.push_back(Node->getValueType(i));
868       Result = SDOperand(DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops,
869                                      Node->getOpcode() == ISD::TAILCALL), 0);
870     } else {
871       Result = Result.getValue(0);
872     }
873     // Since calls produce multiple values, make sure to remember that we
874     // legalized all of them.
875     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
876       AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
877     return Result.getValue(Op.ResNo);
878   }
879   case ISD::BR:
880     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
881     if (Tmp1 != Node->getOperand(0))
882       Result = DAG.getNode(ISD::BR, MVT::Other, Tmp1, Node->getOperand(1));
883     break;
884
885   case ISD::BRCOND:
886     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
887     
888     switch (getTypeAction(Node->getOperand(1).getValueType())) {
889     case Expand: assert(0 && "It's impossible to expand bools");
890     case Legal:
891       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
892       break;
893     case Promote:
894       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
895       break;
896     }
897       
898     switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {  
899     default: assert(0 && "This action is not supported yet!");
900     case TargetLowering::Expand:
901       // Expand brcond's setcc into its constituent parts and create a BR_CC
902       // Node.
903       if (Tmp2.getOpcode() == ISD::SETCC) {
904         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
905                              Tmp2.getOperand(0), Tmp2.getOperand(1),
906                              Node->getOperand(2));
907       } else {
908         // Make sure the condition is either zero or one.  It may have been
909         // promoted from something else.
910         Tmp2 = DAG.getZeroExtendInReg(Tmp2, MVT::i1);
911         
912         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, 
913                              DAG.getCondCode(ISD::SETNE), Tmp2,
914                              DAG.getConstant(0, Tmp2.getValueType()),
915                              Node->getOperand(2));
916       }
917       Result = LegalizeOp(Result);  // Relegalize new nodes.
918       break;
919     case TargetLowering::Custom: {
920       SDOperand Tmp =
921         TLI.LowerOperation(DAG.getNode(ISD::BRCOND, Node->getValueType(0),
922                                        Tmp1, Tmp2, Node->getOperand(2)), DAG);
923       if (Tmp.Val) {
924         Result = LegalizeOp(Tmp);
925         break;
926       }
927       // FALLTHROUGH if the target thinks it is legal.
928     }
929     case TargetLowering::Legal:
930       // Basic block destination (Op#2) is always legal.
931       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
932         Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
933                              Node->getOperand(2));
934         break;
935     }
936     break;
937   case ISD::BR_CC:
938     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
939     if (!isTypeLegal(Node->getOperand(2).getValueType())) {
940       Tmp2 = LegalizeOp(DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),
941                                     Node->getOperand(2),  // LHS
942                                     Node->getOperand(3),  // RHS
943                                     Node->getOperand(1)));
944       // If we get a SETCC back from legalizing the SETCC node we just
945       // created, then use its LHS, RHS, and CC directly in creating a new
946       // node.  Otherwise, select between the true and false value based on
947       // comparing the result of the legalized with zero.
948       if (Tmp2.getOpcode() == ISD::SETCC) {
949         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
950                              Tmp2.getOperand(0), Tmp2.getOperand(1),
951                              Node->getOperand(4));
952       } else {
953         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, 
954                              DAG.getCondCode(ISD::SETNE),
955                              Tmp2, DAG.getConstant(0, Tmp2.getValueType()), 
956                              Node->getOperand(4));
957       }
958       break;
959     }
960
961     Tmp2 = LegalizeOp(Node->getOperand(2));   // LHS
962     Tmp3 = LegalizeOp(Node->getOperand(3));   // RHS
963
964     switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
965     default: assert(0 && "Unexpected action for BR_CC!");
966     case TargetLowering::Custom: {
967       Tmp4 = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Node->getOperand(1),
968                          Tmp2, Tmp3, Node->getOperand(4));
969       Tmp4 = TLI.LowerOperation(Tmp4, DAG);
970       if (Tmp4.Val) {
971         Result = LegalizeOp(Tmp4);
972         break;
973       }
974     } // FALLTHROUGH if the target doesn't want to lower this op after all.
975     case TargetLowering::Legal:
976       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(2) ||
977           Tmp3 != Node->getOperand(3)) {
978         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Node->getOperand(1),
979                              Tmp2, Tmp3, Node->getOperand(4));
980       }
981       break;
982     }
983     break;
984   case ISD::BRCONDTWOWAY:
985     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
986     switch (getTypeAction(Node->getOperand(1).getValueType())) {
987     case Expand: assert(0 && "It's impossible to expand bools");
988     case Legal:
989       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
990       break;
991     case Promote:
992       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
993       break;
994     }
995     // If this target does not support BRCONDTWOWAY, lower it to a BRCOND/BR
996     // pair.
997     switch (TLI.getOperationAction(ISD::BRCONDTWOWAY, MVT::Other)) {
998     case TargetLowering::Promote:
999     default: assert(0 && "This action is not supported yet!");
1000     case TargetLowering::Legal:
1001       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
1002         std::vector<SDOperand> Ops;
1003         Ops.push_back(Tmp1);
1004         Ops.push_back(Tmp2);
1005         Ops.push_back(Node->getOperand(2));
1006         Ops.push_back(Node->getOperand(3));
1007         Result = DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops);
1008       }
1009       break;
1010     case TargetLowering::Expand:
1011       // If BRTWOWAY_CC is legal for this target, then simply expand this node
1012       // to that.  Otherwise, skip BRTWOWAY_CC and expand directly to a
1013       // BRCOND/BR pair.
1014       if (TLI.isOperationLegal(ISD::BRTWOWAY_CC, MVT::Other)) {
1015         if (Tmp2.getOpcode() == ISD::SETCC) {
1016           Result = DAG.getBR2Way_CC(Tmp1, Tmp2.getOperand(2),
1017                                     Tmp2.getOperand(0), Tmp2.getOperand(1),
1018                                     Node->getOperand(2), Node->getOperand(3));
1019         } else {
1020           Result = DAG.getBR2Way_CC(Tmp1, DAG.getCondCode(ISD::SETNE), Tmp2, 
1021                                     DAG.getConstant(0, Tmp2.getValueType()),
1022                                     Node->getOperand(2), Node->getOperand(3));
1023         }
1024       } else {
1025         Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
1026                            Node->getOperand(2));
1027         Result = DAG.getNode(ISD::BR, MVT::Other, Result, Node->getOperand(3));
1028       }
1029       Result = LegalizeOp(Result);  // Relegalize new nodes.
1030       break;
1031     }
1032     break;
1033   case ISD::BRTWOWAY_CC:
1034     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1035     if (isTypeLegal(Node->getOperand(2).getValueType())) {
1036       Tmp2 = LegalizeOp(Node->getOperand(2));   // LHS
1037       Tmp3 = LegalizeOp(Node->getOperand(3));   // RHS
1038       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(2) ||
1039           Tmp3 != Node->getOperand(3)) {
1040         Result = DAG.getBR2Way_CC(Tmp1, Node->getOperand(1), Tmp2, Tmp3,
1041                                   Node->getOperand(4), Node->getOperand(5));
1042       }
1043       break;
1044     } else {
1045       Tmp2 = LegalizeOp(DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),
1046                                     Node->getOperand(2),  // LHS
1047                                     Node->getOperand(3),  // RHS
1048                                     Node->getOperand(1)));
1049       // If this target does not support BRTWOWAY_CC, lower it to a BRCOND/BR
1050       // pair.
1051       switch (TLI.getOperationAction(ISD::BRTWOWAY_CC, MVT::Other)) {
1052       default: assert(0 && "This action is not supported yet!");
1053       case TargetLowering::Legal:
1054         // If we get a SETCC back from legalizing the SETCC node we just
1055         // created, then use its LHS, RHS, and CC directly in creating a new
1056         // node.  Otherwise, select between the true and false value based on
1057         // comparing the result of the legalized with zero.
1058         if (Tmp2.getOpcode() == ISD::SETCC) {
1059           Result = DAG.getBR2Way_CC(Tmp1, Tmp2.getOperand(2),
1060                                     Tmp2.getOperand(0), Tmp2.getOperand(1),
1061                                     Node->getOperand(4), Node->getOperand(5));
1062         } else {
1063           Result = DAG.getBR2Way_CC(Tmp1, DAG.getCondCode(ISD::SETNE), Tmp2, 
1064                                     DAG.getConstant(0, Tmp2.getValueType()),
1065                                     Node->getOperand(4), Node->getOperand(5));
1066         }
1067         break;
1068       case TargetLowering::Expand: 
1069         Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
1070                              Node->getOperand(4));
1071         Result = DAG.getNode(ISD::BR, MVT::Other, Result, Node->getOperand(5));
1072         break;
1073       }
1074       Result = LegalizeOp(Result);  // Relegalize new nodes.
1075     }
1076     break;
1077   case ISD::LOAD: {
1078     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1079     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1080
1081     MVT::ValueType VT = Node->getValueType(0);
1082     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1083     default: assert(0 && "This action is not supported yet!");
1084     case TargetLowering::Custom: {
1085       SDOperand Op = DAG.getLoad(Node->getValueType(0),
1086                                  Tmp1, Tmp2, Node->getOperand(2));
1087       SDOperand Tmp = TLI.LowerOperation(Op, DAG);
1088       if (Tmp.Val) {
1089         Result = LegalizeOp(Tmp);
1090         // Since loads produce two values, make sure to remember that we legalized
1091         // both of them.
1092         AddLegalizedOperand(SDOperand(Node, 0), Result);
1093         AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1094         return Result.getValue(Op.ResNo);
1095       }
1096       // FALLTHROUGH if the target thinks it is legal.
1097     }
1098     case TargetLowering::Legal:
1099       if (Tmp1 != Node->getOperand(0) ||
1100           Tmp2 != Node->getOperand(1))
1101         Result = DAG.getLoad(Node->getValueType(0), Tmp1, Tmp2,
1102                              Node->getOperand(2));
1103       else
1104         Result = SDOperand(Node, 0);
1105
1106       // Since loads produce two values, make sure to remember that we legalized
1107       // both of them.
1108       AddLegalizedOperand(SDOperand(Node, 0), Result);
1109       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1110       return Result.getValue(Op.ResNo);
1111     }
1112     assert(0 && "Unreachable");
1113   }
1114   case ISD::EXTLOAD:
1115   case ISD::SEXTLOAD:
1116   case ISD::ZEXTLOAD: {
1117     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1118     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1119
1120     MVT::ValueType SrcVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
1121     switch (TLI.getOperationAction(Node->getOpcode(), SrcVT)) {
1122     default: assert(0 && "This action is not supported yet!");
1123     case TargetLowering::Promote:
1124       assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
1125       Result = DAG.getExtLoad(Node->getOpcode(), Node->getValueType(0),
1126                               Tmp1, Tmp2, Node->getOperand(2), MVT::i8);
1127       // Since loads produce two values, make sure to remember that we legalized
1128       // both of them.
1129       AddLegalizedOperand(SDOperand(Node, 0), Result);
1130       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1131       return Result.getValue(Op.ResNo);
1132
1133     case TargetLowering::Custom: {
1134       SDOperand Op = DAG.getExtLoad(Node->getOpcode(), Node->getValueType(0),
1135                                     Tmp1, Tmp2, Node->getOperand(2),
1136                                     SrcVT);
1137       SDOperand Tmp = TLI.LowerOperation(Op, DAG);
1138       if (Tmp.Val) {
1139         Result = LegalizeOp(Tmp);
1140         // Since loads produce two values, make sure to remember that we legalized
1141         // both of them.
1142         AddLegalizedOperand(SDOperand(Node, 0), Result);
1143         AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1144         return Result.getValue(Op.ResNo);
1145       }
1146       // FALLTHROUGH if the target thinks it is legal.
1147     }
1148     case TargetLowering::Legal:
1149       if (Tmp1 != Node->getOperand(0) ||
1150           Tmp2 != Node->getOperand(1))
1151         Result = DAG.getExtLoad(Node->getOpcode(), Node->getValueType(0),
1152                                 Tmp1, Tmp2, Node->getOperand(2), SrcVT);
1153       else
1154         Result = SDOperand(Node, 0);
1155
1156       // Since loads produce two values, make sure to remember that we legalized
1157       // both of them.
1158       AddLegalizedOperand(SDOperand(Node, 0), Result);
1159       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1160       return Result.getValue(Op.ResNo);
1161     case TargetLowering::Expand:
1162       // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
1163       if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
1164         SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, Node->getOperand(2));
1165         Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
1166         Result = LegalizeOp(Result);  // Relegalize new nodes.
1167         Load = LegalizeOp(Load);
1168         AddLegalizedOperand(SDOperand(Node, 0), Result);
1169         AddLegalizedOperand(SDOperand(Node, 1), Load.getValue(1));
1170         if (Op.ResNo)
1171           return Load.getValue(1);
1172         return Result;
1173       }
1174       assert(Node->getOpcode() != ISD::EXTLOAD &&
1175              "EXTLOAD should always be supported!");
1176       // Turn the unsupported load into an EXTLOAD followed by an explicit
1177       // zero/sign extend inreg.
1178       Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
1179                               Tmp1, Tmp2, Node->getOperand(2), SrcVT);
1180       SDOperand ValRes;
1181       if (Node->getOpcode() == ISD::SEXTLOAD)
1182         ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1183                              Result, DAG.getValueType(SrcVT));
1184       else
1185         ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
1186       Result = LegalizeOp(Result);  // Relegalize new nodes.
1187       ValRes = LegalizeOp(ValRes);  // Relegalize new nodes.
1188       AddLegalizedOperand(SDOperand(Node, 0), ValRes);
1189       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1190       if (Op.ResNo)
1191         return Result.getValue(1);
1192       return ValRes;
1193     }
1194     assert(0 && "Unreachable");
1195   }
1196   case ISD::EXTRACT_ELEMENT: {
1197     MVT::ValueType OpTy = Node->getOperand(0).getValueType();
1198     switch (getTypeAction(OpTy)) {
1199     default:
1200       assert(0 && "EXTRACT_ELEMENT action for type unimplemented!");
1201       break;
1202     case Legal:
1203       if (cast<ConstantSDNode>(Node->getOperand(1))->getValue()) {
1204         // 1 -> Hi
1205         Result = DAG.getNode(ISD::SRL, OpTy, Node->getOperand(0),
1206                              DAG.getConstant(MVT::getSizeInBits(OpTy)/2, 
1207                                              TLI.getShiftAmountTy()));
1208         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Result);
1209       } else {
1210         // 0 -> Lo
1211         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), 
1212                              Node->getOperand(0));
1213       }
1214       Result = LegalizeOp(Result);
1215       break;
1216     case Expand:
1217       // Get both the low and high parts.
1218       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1219       if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
1220         Result = Tmp2;  // 1 -> Hi
1221       else
1222         Result = Tmp1;  // 0 -> Lo
1223       break;
1224     }
1225     break;
1226   }
1227
1228   case ISD::CopyToReg:
1229     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1230
1231     assert(isTypeLegal(Node->getOperand(2).getValueType()) &&
1232            "Register type must be legal!");
1233     // Legalize the incoming value (must be a legal type).
1234     Tmp2 = LegalizeOp(Node->getOperand(2));
1235     if (Node->getNumValues() == 1) {
1236       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(2))
1237         Result = DAG.getNode(ISD::CopyToReg, MVT::Other, Tmp1,
1238                              Node->getOperand(1), Tmp2);
1239     } else {
1240       assert(Node->getNumValues() == 2 && "Unknown CopyToReg");
1241       if (Node->getNumOperands() == 4)
1242         Tmp3 = LegalizeOp(Node->getOperand(3));
1243       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(2) ||
1244           (Node->getNumOperands() == 4 && Tmp3 != Node->getOperand(3))) {
1245         unsigned Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
1246         Result = DAG.getCopyToReg(Tmp1, Reg, Tmp2, Tmp3);
1247       }
1248       
1249       // Since this produces two values, make sure to remember that we legalized
1250       // both of them.
1251       AddLegalizedOperand(SDOperand(Node, 0), Result);
1252       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1253       return Result.getValue(Op.ResNo);
1254     }
1255     break;
1256
1257   case ISD::RET:
1258     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1259     switch (Node->getNumOperands()) {
1260     case 2:  // ret val
1261       switch (getTypeAction(Node->getOperand(1).getValueType())) {
1262       case Legal:
1263         Tmp2 = LegalizeOp(Node->getOperand(1));
1264         if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
1265           Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
1266         break;
1267       case Expand: {
1268         SDOperand Lo, Hi;
1269         ExpandOp(Node->getOperand(1), Lo, Hi);
1270         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
1271         break;
1272       }
1273       case Promote:
1274         Tmp2 = PromoteOp(Node->getOperand(1));
1275         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
1276         break;
1277       }
1278       break;
1279     case 1:  // ret void
1280       if (Tmp1 != Node->getOperand(0))
1281         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1);
1282       break;
1283     default: { // ret <values>
1284       std::vector<SDOperand> NewValues;
1285       NewValues.push_back(Tmp1);
1286       for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1287         switch (getTypeAction(Node->getOperand(i).getValueType())) {
1288         case Legal:
1289           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
1290           break;
1291         case Expand: {
1292           SDOperand Lo, Hi;
1293           ExpandOp(Node->getOperand(i), Lo, Hi);
1294           NewValues.push_back(Lo);
1295           NewValues.push_back(Hi);
1296           break;
1297         }
1298         case Promote:
1299           assert(0 && "Can't promote multiple return value yet!");
1300         }
1301       Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
1302       break;
1303     }
1304     }
1305
1306     switch (TLI.getOperationAction(Node->getOpcode(),
1307                                    Node->getValueType(0))) {
1308     default: assert(0 && "This action is not supported yet!");
1309     case TargetLowering::Custom: {
1310       SDOperand Tmp = TLI.LowerOperation(Result, DAG);
1311       if (Tmp.Val) {
1312         Result = LegalizeOp(Tmp);
1313         break;
1314       }
1315       // FALLTHROUGH if the target thinks it is legal.
1316     }
1317     case TargetLowering::Legal:
1318       // Nothing to do.
1319       break;
1320     }
1321     break;
1322   case ISD::STORE: {
1323     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1324     Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1325
1326     // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
1327     if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
1328       if (CFP->getValueType(0) == MVT::f32) {
1329         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
1330                              DAG.getConstant(FloatToBits(CFP->getValue()),
1331                                              MVT::i32),
1332                              Tmp2,
1333                              Node->getOperand(3));
1334       } else {
1335         assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
1336         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
1337                              DAG.getConstant(DoubleToBits(CFP->getValue()),
1338                                              MVT::i64),
1339                              Tmp2,
1340                              Node->getOperand(3));
1341       }
1342       Node = Result.Val;
1343     }
1344
1345     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1346     case Legal: {
1347       SDOperand Val = LegalizeOp(Node->getOperand(1));
1348       if (Val != Node->getOperand(1) || Tmp1 != Node->getOperand(0) ||
1349           Tmp2 != Node->getOperand(2))
1350         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Val, Tmp2,
1351                              Node->getOperand(3));
1352
1353       MVT::ValueType VT = Result.Val->getOperand(1).getValueType();
1354       switch (TLI.getOperationAction(Result.Val->getOpcode(), VT)) {
1355         default: assert(0 && "This action is not supported yet!");
1356         case TargetLowering::Custom: {
1357           SDOperand Tmp = TLI.LowerOperation(Result, DAG);
1358           if (Tmp.Val) {
1359             Result = LegalizeOp(Tmp);
1360             break;
1361           }
1362           // FALLTHROUGH if the target thinks it is legal.
1363         }
1364         case TargetLowering::Legal:
1365           // Nothing to do.
1366           break;
1367       }
1368       break;
1369     }
1370     case Promote:
1371       // Truncate the value and store the result.
1372       Tmp3 = PromoteOp(Node->getOperand(1));
1373       Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
1374                            Node->getOperand(3),
1375                           DAG.getValueType(Node->getOperand(1).getValueType()));
1376       break;
1377
1378     case Expand:
1379       SDOperand Lo, Hi;
1380       unsigned IncrementSize;
1381       ExpandOp(Node->getOperand(1), Lo, Hi);
1382
1383       if (!TLI.isLittleEndian())
1384         std::swap(Lo, Hi);
1385
1386       Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2,
1387                        Node->getOperand(3));
1388       // If this is a vector type, then we have to calculate the increment as
1389       // the product of the element size in bytes, and the number of elements
1390       // in the high half of the vector.
1391       if (MVT::Vector == Hi.getValueType()) {
1392         unsigned NumElems = cast<ConstantSDNode>(Hi.getOperand(2))->getValue();
1393         MVT::ValueType EVT = cast<VTSDNode>(Hi.getOperand(3))->getVT();
1394         IncrementSize = NumElems * MVT::getSizeInBits(EVT)/8;
1395       } else {
1396         IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
1397       }
1398       Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
1399                          getIntPtrConstant(IncrementSize));
1400       assert(isTypeLegal(Tmp2.getValueType()) &&
1401              "Pointers must be legal!");
1402       //Again, claiming both parts of the store came form the same Instr
1403       Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2,
1404                        Node->getOperand(3));
1405       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
1406       break;
1407     }
1408     break;
1409   }
1410   case ISD::PCMARKER:
1411     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1412     if (Tmp1 != Node->getOperand(0))
1413       Result = DAG.getNode(ISD::PCMARKER, MVT::Other, Tmp1,Node->getOperand(1));
1414     break;
1415   case ISD::READCYCLECOUNTER:
1416     Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
1417     if (Tmp1 != Node->getOperand(0)) {
1418       std::vector<MVT::ValueType> rtypes;
1419       std::vector<SDOperand> rvals;
1420       rtypes.push_back(MVT::i64);
1421       rtypes.push_back(MVT::Other);
1422       rvals.push_back(Tmp1);
1423       Result = DAG.getNode(ISD::READCYCLECOUNTER, rtypes, rvals);
1424     }
1425
1426     // Since rdcc produce two values, make sure to remember that we legalized
1427     // both of them.
1428     AddLegalizedOperand(SDOperand(Node, 0), Result);
1429     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1430     return Result.getValue(Op.ResNo);
1431
1432   case ISD::TRUNCSTORE: {
1433     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1434     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1435
1436     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1437     case Promote:
1438     case Expand:
1439       assert(0 && "Cannot handle illegal TRUNCSTORE yet!");
1440     case Legal:
1441       Tmp2 = LegalizeOp(Node->getOperand(1));
1442       
1443       // The only promote case we handle is TRUNCSTORE:i1 X into
1444       //   -> TRUNCSTORE:i8 (and X, 1)
1445       if (cast<VTSDNode>(Node->getOperand(4))->getVT() == MVT::i1 &&
1446           TLI.getOperationAction(ISD::TRUNCSTORE, MVT::i1) == 
1447                 TargetLowering::Promote) {
1448         // Promote the bool to a mask then store.
1449         Tmp2 = DAG.getNode(ISD::AND, Tmp2.getValueType(), Tmp2,
1450                            DAG.getConstant(1, Tmp2.getValueType()));
1451         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
1452                              Node->getOperand(3), DAG.getValueType(MVT::i8));
1453
1454       } else if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1455                  Tmp3 != Node->getOperand(2)) {
1456         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
1457                              Node->getOperand(3), Node->getOperand(4));
1458       }
1459
1460       MVT::ValueType StVT = cast<VTSDNode>(Result.Val->getOperand(4))->getVT();
1461       switch (TLI.getOperationAction(Result.Val->getOpcode(), StVT)) {
1462         default: assert(0 && "This action is not supported yet!");
1463         case TargetLowering::Custom: {
1464           SDOperand Tmp = TLI.LowerOperation(Result, DAG);
1465           if (Tmp.Val) {
1466             Result = LegalizeOp(Tmp);
1467             break;
1468           }
1469           // FALLTHROUGH if the target thinks it is legal.
1470         }
1471         case TargetLowering::Legal:
1472           // Nothing to do.
1473           break;
1474       }
1475       break;
1476     }
1477     break;
1478   }
1479   case ISD::SELECT:
1480     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1481     case Expand: assert(0 && "It's impossible to expand bools");
1482     case Legal:
1483       Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1484       break;
1485     case Promote:
1486       Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
1487       break;
1488     }
1489     Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
1490     Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
1491
1492     switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
1493     default: assert(0 && "This action is not supported yet!");
1494     case TargetLowering::Expand:
1495       if (Tmp1.getOpcode() == ISD::SETCC) {
1496         Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1), 
1497                               Tmp2, Tmp3,
1498                               cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
1499       } else {
1500         // Make sure the condition is either zero or one.  It may have been
1501         // promoted from something else.
1502         Tmp1 = DAG.getZeroExtendInReg(Tmp1, MVT::i1);
1503         Result = DAG.getSelectCC(Tmp1, 
1504                                  DAG.getConstant(0, Tmp1.getValueType()),
1505                                  Tmp2, Tmp3, ISD::SETNE);
1506       }
1507       Result = LegalizeOp(Result);  // Relegalize new nodes.
1508       break;
1509     case TargetLowering::Custom: {
1510       SDOperand Tmp =
1511         TLI.LowerOperation(DAG.getNode(ISD::SELECT, Node->getValueType(0),
1512                                        Tmp1, Tmp2, Tmp3), DAG);
1513       if (Tmp.Val) {
1514         Result = LegalizeOp(Tmp);
1515         break;
1516       }
1517       // FALLTHROUGH if the target thinks it is legal.
1518     }
1519     case TargetLowering::Legal:
1520       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1521           Tmp3 != Node->getOperand(2))
1522         Result = DAG.getNode(ISD::SELECT, Node->getValueType(0),
1523                              Tmp1, Tmp2, Tmp3);
1524       break;
1525     case TargetLowering::Promote: {
1526       MVT::ValueType NVT =
1527         TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
1528       unsigned ExtOp, TruncOp;
1529       if (MVT::isInteger(Tmp2.getValueType())) {
1530         ExtOp = ISD::ANY_EXTEND;
1531         TruncOp  = ISD::TRUNCATE;
1532       } else {
1533         ExtOp = ISD::FP_EXTEND;
1534         TruncOp  = ISD::FP_ROUND;
1535       }
1536       // Promote each of the values to the new type.
1537       Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
1538       Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
1539       // Perform the larger operation, then round down.
1540       Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
1541       Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
1542       break;
1543     }
1544     }
1545     break;
1546   case ISD::SELECT_CC:
1547     Tmp3 = LegalizeOp(Node->getOperand(2));   // True
1548     Tmp4 = LegalizeOp(Node->getOperand(3));   // False
1549     
1550     if (isTypeLegal(Node->getOperand(0).getValueType())) {
1551       // Everything is legal, see if we should expand this op or something.
1552       switch (TLI.getOperationAction(ISD::SELECT_CC,
1553                                      Node->getOperand(0).getValueType())) {
1554       default: assert(0 && "This action is not supported yet!");
1555       case TargetLowering::Custom: {
1556         SDOperand Tmp =
1557           TLI.LowerOperation(DAG.getNode(ISD::SELECT_CC, Node->getValueType(0),
1558                                          Node->getOperand(0),
1559                                          Node->getOperand(1), Tmp3, Tmp4,
1560                                          Node->getOperand(4)), DAG);
1561         if (Tmp.Val) {
1562           Result = LegalizeOp(Tmp);
1563           break;
1564         }
1565       } // FALLTHROUGH if the target can't lower this operation after all.
1566       case TargetLowering::Legal:
1567         Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1568         Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
1569         if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1570             Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3)) {
1571           Result = DAG.getNode(ISD::SELECT_CC, Node->getValueType(0), Tmp1,Tmp2, 
1572                                Tmp3, Tmp4, Node->getOperand(4));
1573         }
1574         break;
1575       }
1576       break;
1577     } else {
1578       Tmp1 = LegalizeOp(DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),
1579                                     Node->getOperand(0),  // LHS
1580                                     Node->getOperand(1),  // RHS
1581                                     Node->getOperand(4)));
1582       // If we get a SETCC back from legalizing the SETCC node we just
1583       // created, then use its LHS, RHS, and CC directly in creating a new
1584       // node.  Otherwise, select between the true and false value based on
1585       // comparing the result of the legalized with zero.
1586       if (Tmp1.getOpcode() == ISD::SETCC) {
1587         Result = DAG.getNode(ISD::SELECT_CC, Tmp3.getValueType(),
1588                              Tmp1.getOperand(0), Tmp1.getOperand(1),
1589                              Tmp3, Tmp4, Tmp1.getOperand(2));
1590       } else {
1591         Result = DAG.getSelectCC(Tmp1,
1592                                  DAG.getConstant(0, Tmp1.getValueType()), 
1593                                  Tmp3, Tmp4, ISD::SETNE);
1594       }
1595     }
1596     break;
1597   case ISD::SETCC:
1598     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1599     case Legal:
1600       Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1601       Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
1602       break;
1603     case Promote:
1604       Tmp1 = PromoteOp(Node->getOperand(0));   // LHS
1605       Tmp2 = PromoteOp(Node->getOperand(1));   // RHS
1606
1607       // If this is an FP compare, the operands have already been extended.
1608       if (MVT::isInteger(Node->getOperand(0).getValueType())) {
1609         MVT::ValueType VT = Node->getOperand(0).getValueType();
1610         MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1611
1612         // Otherwise, we have to insert explicit sign or zero extends.  Note
1613         // that we could insert sign extends for ALL conditions, but zero extend
1614         // is cheaper on many machines (an AND instead of two shifts), so prefer
1615         // it.
1616         switch (cast<CondCodeSDNode>(Node->getOperand(2))->get()) {
1617         default: assert(0 && "Unknown integer comparison!");
1618         case ISD::SETEQ:
1619         case ISD::SETNE:
1620         case ISD::SETUGE:
1621         case ISD::SETUGT:
1622         case ISD::SETULE:
1623         case ISD::SETULT:
1624           // ALL of these operations will work if we either sign or zero extend
1625           // the operands (including the unsigned comparisons!).  Zero extend is
1626           // usually a simpler/cheaper operation, so prefer it.
1627           Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
1628           Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
1629           break;
1630         case ISD::SETGE:
1631         case ISD::SETGT:
1632         case ISD::SETLT:
1633         case ISD::SETLE:
1634           Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
1635                              DAG.getValueType(VT));
1636           Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
1637                              DAG.getValueType(VT));
1638           break;
1639         }
1640       }
1641       break;
1642     case Expand:
1643       SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
1644       ExpandOp(Node->getOperand(0), LHSLo, LHSHi);
1645       ExpandOp(Node->getOperand(1), RHSLo, RHSHi);
1646       switch (cast<CondCodeSDNode>(Node->getOperand(2))->get()) {
1647       case ISD::SETEQ:
1648       case ISD::SETNE:
1649         if (RHSLo == RHSHi)
1650           if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
1651             if (RHSCST->isAllOnesValue()) {
1652               // Comparison to -1.
1653               Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
1654               Tmp2 = RHSLo;
1655               break;
1656             }
1657
1658         Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
1659         Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
1660         Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
1661         Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
1662         break;
1663       default:
1664         // If this is a comparison of the sign bit, just look at the top part.
1665         // X > -1,  x < 0
1666         if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Node->getOperand(1)))
1667           if ((cast<CondCodeSDNode>(Node->getOperand(2))->get() == ISD::SETLT &&
1668                CST->getValue() == 0) ||              // X < 0
1669               (cast<CondCodeSDNode>(Node->getOperand(2))->get() == ISD::SETGT &&
1670                (CST->isAllOnesValue()))) {            // X > -1
1671             Tmp1 = LHSHi;
1672             Tmp2 = RHSHi;
1673             break;
1674           }
1675
1676         // FIXME: This generated code sucks.
1677         ISD::CondCode LowCC;
1678         switch (cast<CondCodeSDNode>(Node->getOperand(2))->get()) {
1679         default: assert(0 && "Unknown integer setcc!");
1680         case ISD::SETLT:
1681         case ISD::SETULT: LowCC = ISD::SETULT; break;
1682         case ISD::SETGT:
1683         case ISD::SETUGT: LowCC = ISD::SETUGT; break;
1684         case ISD::SETLE:
1685         case ISD::SETULE: LowCC = ISD::SETULE; break;
1686         case ISD::SETGE:
1687         case ISD::SETUGE: LowCC = ISD::SETUGE; break;
1688         }
1689
1690         // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
1691         // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
1692         // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
1693
1694         // NOTE: on targets without efficient SELECT of bools, we can always use
1695         // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
1696         Tmp1 = DAG.getSetCC(Node->getValueType(0), LHSLo, RHSLo, LowCC);
1697         Tmp2 = DAG.getNode(ISD::SETCC, Node->getValueType(0), LHSHi, RHSHi,
1698                            Node->getOperand(2));
1699         Result = DAG.getSetCC(Node->getValueType(0), LHSHi, RHSHi, ISD::SETEQ);
1700         Result = LegalizeOp(DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
1701                                         Result, Tmp1, Tmp2));
1702         AddLegalizedOperand(SDOperand(Node, 0), Result);
1703         return Result;
1704       }
1705     }
1706
1707     switch(TLI.getOperationAction(ISD::SETCC,
1708                                   Node->getOperand(0).getValueType())) {
1709     default: 
1710       assert(0 && "Cannot handle this action for SETCC yet!");
1711       break;
1712     case TargetLowering::Promote: {
1713       // First step, figure out the appropriate operation to use.
1714       // Allow SETCC to not be supported for all legal data types
1715       // Mostly this targets FP
1716       MVT::ValueType NewInTy = Node->getOperand(0).getValueType();
1717       MVT::ValueType OldVT = NewInTy;
1718
1719       // Scan for the appropriate larger type to use.
1720       while (1) {
1721         NewInTy = (MVT::ValueType)(NewInTy+1);
1722
1723         assert(MVT::isInteger(NewInTy) == MVT::isInteger(OldVT) &&
1724                "Fell off of the edge of the integer world");
1725         assert(MVT::isFloatingPoint(NewInTy) == MVT::isFloatingPoint(OldVT) &&
1726                "Fell off of the edge of the floating point world");
1727           
1728         // If the target supports SETCC of this type, use it.
1729         if (TLI.isOperationLegal(ISD::SETCC, NewInTy))
1730           break;
1731       }
1732       if (MVT::isInteger(NewInTy))
1733         assert(0 && "Cannot promote Legal Integer SETCC yet");
1734       else {
1735         Tmp1 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp1);
1736         Tmp2 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp2);
1737       }
1738       
1739       Result = DAG.getNode(ISD::SETCC, Node->getValueType(0), Tmp1, Tmp2,
1740                            Node->getOperand(2));
1741       break;
1742     }
1743     case TargetLowering::Custom: {
1744       SDOperand Tmp =
1745         TLI.LowerOperation(DAG.getNode(ISD::SETCC, Node->getValueType(0),
1746                                        Tmp1, Tmp2, Node->getOperand(2)), DAG);
1747       if (Tmp.Val) {
1748         Result = LegalizeOp(Tmp);
1749         break;
1750       }
1751       // FALLTHROUGH if the target thinks it is legal.
1752     }
1753     case TargetLowering::Legal:
1754       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
1755         Result = DAG.getNode(ISD::SETCC, Node->getValueType(0), Tmp1, Tmp2,
1756                              Node->getOperand(2));
1757       break;
1758     case TargetLowering::Expand:
1759       // Expand a setcc node into a select_cc of the same condition, lhs, and
1760       // rhs that selects between const 1 (true) and const 0 (false).
1761       MVT::ValueType VT = Node->getValueType(0);
1762       Result = DAG.getNode(ISD::SELECT_CC, VT, Tmp1, Tmp2, 
1763                            DAG.getConstant(1, VT), DAG.getConstant(0, VT),
1764                            Node->getOperand(2));
1765       Result = LegalizeOp(Result);
1766       break;
1767     }
1768     break;
1769
1770   case ISD::MEMSET:
1771   case ISD::MEMCPY:
1772   case ISD::MEMMOVE: {
1773     Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
1774     Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
1775
1776     if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
1777       switch (getTypeAction(Node->getOperand(2).getValueType())) {
1778       case Expand: assert(0 && "Cannot expand a byte!");
1779       case Legal:
1780         Tmp3 = LegalizeOp(Node->getOperand(2));
1781         break;
1782       case Promote:
1783         Tmp3 = PromoteOp(Node->getOperand(2));
1784         break;
1785       }
1786     } else {
1787       Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
1788     }
1789
1790     SDOperand Tmp4;
1791     switch (getTypeAction(Node->getOperand(3).getValueType())) {
1792     case Expand: {
1793       // Length is too big, just take the lo-part of the length.
1794       SDOperand HiPart;
1795       ExpandOp(Node->getOperand(3), HiPart, Tmp4);
1796       break;
1797     }
1798     case Legal:
1799       Tmp4 = LegalizeOp(Node->getOperand(3));
1800       break;
1801     case Promote:
1802       Tmp4 = PromoteOp(Node->getOperand(3));
1803       break;
1804     }
1805
1806     SDOperand Tmp5;
1807     switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
1808     case Expand: assert(0 && "Cannot expand this yet!");
1809     case Legal:
1810       Tmp5 = LegalizeOp(Node->getOperand(4));
1811       break;
1812     case Promote:
1813       Tmp5 = PromoteOp(Node->getOperand(4));
1814       break;
1815     }
1816
1817     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1818     default: assert(0 && "This action not implemented for this operation!");
1819     case TargetLowering::Custom: {
1820       SDOperand Tmp =
1821         TLI.LowerOperation(DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1, 
1822                                        Tmp2, Tmp3, Tmp4, Tmp5), DAG);
1823       if (Tmp.Val) {
1824         Result = LegalizeOp(Tmp);
1825         break;
1826       }
1827       // FALLTHROUGH if the target thinks it is legal.
1828     }
1829     case TargetLowering::Legal:
1830       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1831           Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3) ||
1832           Tmp5 != Node->getOperand(4)) {
1833         std::vector<SDOperand> Ops;
1834         Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
1835         Ops.push_back(Tmp4); Ops.push_back(Tmp5);
1836         Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
1837       }
1838       break;
1839     case TargetLowering::Expand: {
1840       // Otherwise, the target does not support this operation.  Lower the
1841       // operation to an explicit libcall as appropriate.
1842       MVT::ValueType IntPtr = TLI.getPointerTy();
1843       const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
1844       std::vector<std::pair<SDOperand, const Type*> > Args;
1845
1846       const char *FnName = 0;
1847       if (Node->getOpcode() == ISD::MEMSET) {
1848         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1849         // Extend the ubyte argument to be an int value for the call.
1850         Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
1851         Args.push_back(std::make_pair(Tmp3, Type::IntTy));
1852         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1853
1854         FnName = "memset";
1855       } else if (Node->getOpcode() == ISD::MEMCPY ||
1856                  Node->getOpcode() == ISD::MEMMOVE) {
1857         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1858         Args.push_back(std::make_pair(Tmp3, IntPtrTy));
1859         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1860         FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
1861       } else {
1862         assert(0 && "Unknown op!");
1863       }
1864
1865       std::pair<SDOperand,SDOperand> CallResult =
1866         TLI.LowerCallTo(Tmp1, Type::VoidTy, false, CallingConv::C, false,
1867                         DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
1868       Result = LegalizeOp(CallResult.second);
1869       break;
1870     }
1871     }
1872     break;
1873   }
1874
1875   case ISD::READPORT:
1876     Tmp1 = LegalizeOp(Node->getOperand(0));
1877     Tmp2 = LegalizeOp(Node->getOperand(1));
1878
1879     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
1880       std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1881       std::vector<SDOperand> Ops;
1882       Ops.push_back(Tmp1);
1883       Ops.push_back(Tmp2);
1884       Result = DAG.getNode(ISD::READPORT, VTs, Ops);
1885     } else
1886       Result = SDOperand(Node, 0);
1887     // Since these produce two values, make sure to remember that we legalized
1888     // both of them.
1889     AddLegalizedOperand(SDOperand(Node, 0), Result);
1890     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1891     return Result.getValue(Op.ResNo);
1892   case ISD::WRITEPORT:
1893     Tmp1 = LegalizeOp(Node->getOperand(0));
1894     Tmp2 = LegalizeOp(Node->getOperand(1));
1895     Tmp3 = LegalizeOp(Node->getOperand(2));
1896     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1897         Tmp3 != Node->getOperand(2))
1898       Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1, Tmp2, Tmp3);
1899     break;
1900
1901   case ISD::READIO:
1902     Tmp1 = LegalizeOp(Node->getOperand(0));
1903     Tmp2 = LegalizeOp(Node->getOperand(1));
1904
1905     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1906     case TargetLowering::Custom:
1907     default: assert(0 && "This action not implemented for this operation!");
1908     case TargetLowering::Legal:
1909       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
1910         std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1911         std::vector<SDOperand> Ops;
1912         Ops.push_back(Tmp1);
1913         Ops.push_back(Tmp2);
1914         Result = DAG.getNode(ISD::READPORT, VTs, Ops);
1915       } else
1916         Result = SDOperand(Node, 0);
1917       break;
1918     case TargetLowering::Expand:
1919       // Replace this with a load from memory.
1920       Result = DAG.getLoad(Node->getValueType(0), Node->getOperand(0),
1921                            Node->getOperand(1), DAG.getSrcValue(NULL));
1922       Result = LegalizeOp(Result);
1923       break;
1924     }
1925
1926     // Since these produce two values, make sure to remember that we legalized
1927     // both of them.
1928     AddLegalizedOperand(SDOperand(Node, 0), Result);
1929     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1930     return Result.getValue(Op.ResNo);
1931
1932   case ISD::WRITEIO:
1933     Tmp1 = LegalizeOp(Node->getOperand(0));
1934     Tmp2 = LegalizeOp(Node->getOperand(1));
1935     Tmp3 = LegalizeOp(Node->getOperand(2));
1936
1937     switch (TLI.getOperationAction(Node->getOpcode(),
1938                                    Node->getOperand(1).getValueType())) {
1939     case TargetLowering::Custom:
1940     default: assert(0 && "This action not implemented for this operation!");
1941     case TargetLowering::Legal:
1942       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1943           Tmp3 != Node->getOperand(2))
1944         Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1, Tmp2, Tmp3);
1945       break;
1946     case TargetLowering::Expand:
1947       // Replace this with a store to memory.
1948       Result = DAG.getNode(ISD::STORE, MVT::Other, Node->getOperand(0),
1949                            Node->getOperand(1), Node->getOperand(2),
1950                            DAG.getSrcValue(NULL));
1951       Result = LegalizeOp(Result);
1952       break;
1953     }
1954     break;
1955
1956   case ISD::ADD_PARTS:
1957   case ISD::SUB_PARTS:
1958   case ISD::SHL_PARTS:
1959   case ISD::SRA_PARTS:
1960   case ISD::SRL_PARTS: {
1961     std::vector<SDOperand> Ops;
1962     bool Changed = false;
1963     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1964       Ops.push_back(LegalizeOp(Node->getOperand(i)));
1965       Changed |= Ops.back() != Node->getOperand(i);
1966     }
1967     if (Changed) {
1968       std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1969       Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
1970     }
1971
1972     switch (TLI.getOperationAction(Node->getOpcode(),
1973                                    Node->getValueType(0))) {
1974     default: assert(0 && "This action is not supported yet!");
1975     case TargetLowering::Custom: {
1976       SDOperand Tmp = TLI.LowerOperation(Result, DAG);
1977       if (Tmp.Val) {
1978         SDOperand Tmp2, RetVal(0,0);
1979         for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
1980           Tmp2 = LegalizeOp(Tmp.getValue(i));
1981           AddLegalizedOperand(SDOperand(Node, i), Tmp2);
1982           if (i == Op.ResNo)
1983             RetVal = Tmp;
1984         }
1985         assert(RetVal.Val && "Illegal result number");
1986         return RetVal;
1987       }
1988       // FALLTHROUGH if the target thinks it is legal.
1989     }
1990     case TargetLowering::Legal:
1991       // Nothing to do.
1992       break;
1993     }
1994
1995     // Since these produce multiple values, make sure to remember that we
1996     // legalized all of them.
1997     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1998       AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
1999     return Result.getValue(Op.ResNo);
2000   }
2001
2002     // Binary operators
2003   case ISD::ADD:
2004   case ISD::SUB:
2005   case ISD::MUL:
2006   case ISD::MULHS:
2007   case ISD::MULHU:
2008   case ISD::UDIV:
2009   case ISD::SDIV:
2010   case ISD::AND:
2011   case ISD::OR:
2012   case ISD::XOR:
2013   case ISD::SHL:
2014   case ISD::SRL:
2015   case ISD::SRA:
2016   case ISD::FADD:
2017   case ISD::FSUB:
2018   case ISD::FMUL:
2019   case ISD::FDIV:
2020     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2021     switch (getTypeAction(Node->getOperand(1).getValueType())) {
2022     case Expand: assert(0 && "Not possible");
2023     case Legal:
2024       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
2025       break;
2026     case Promote:
2027       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
2028       break;
2029     }
2030     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2031     case TargetLowering::Custom: {
2032       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1, Tmp2);
2033       SDOperand Tmp = TLI.LowerOperation(Result, DAG);
2034       if (Tmp.Val) {
2035         Tmp = LegalizeOp(Tmp);  // Relegalize input.
2036         AddLegalizedOperand(Op, Tmp);
2037         return Tmp;
2038       } //else it was considered legal and we fall through
2039     }
2040     case TargetLowering::Legal:
2041       if (Tmp1 != Node->getOperand(0) ||
2042           Tmp2 != Node->getOperand(1))
2043         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
2044       break;
2045     default:
2046       assert(0 && "Operation not supported");
2047     }
2048     break;
2049
2050   case ISD::BUILD_PAIR: {
2051     MVT::ValueType PairTy = Node->getValueType(0);
2052     // TODO: handle the case where the Lo and Hi operands are not of legal type
2053     Tmp1 = LegalizeOp(Node->getOperand(0));   // Lo
2054     Tmp2 = LegalizeOp(Node->getOperand(1));   // Hi
2055     switch (TLI.getOperationAction(ISD::BUILD_PAIR, PairTy)) {
2056     case TargetLowering::Legal:
2057       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
2058         Result = DAG.getNode(ISD::BUILD_PAIR, PairTy, Tmp1, Tmp2);
2059       break;
2060     case TargetLowering::Promote:
2061     case TargetLowering::Custom:
2062       assert(0 && "Cannot promote/custom this yet!");
2063     case TargetLowering::Expand:
2064       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, PairTy, Tmp1);
2065       Tmp2 = DAG.getNode(ISD::ANY_EXTEND, PairTy, Tmp2);
2066       Tmp2 = DAG.getNode(ISD::SHL, PairTy, Tmp2,
2067                          DAG.getConstant(MVT::getSizeInBits(PairTy)/2, 
2068                                          TLI.getShiftAmountTy()));
2069       Result = LegalizeOp(DAG.getNode(ISD::OR, PairTy, Tmp1, Tmp2));
2070       break;
2071     }
2072     break;
2073   }
2074
2075   case ISD::UREM:
2076   case ISD::SREM:
2077   case ISD::FREM:
2078     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2079     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2080     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2081     case TargetLowering::Custom: {
2082       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1, Tmp2);
2083       SDOperand Tmp = TLI.LowerOperation(Result, DAG);
2084       if (Tmp.Val) {
2085         Tmp = LegalizeOp(Tmp);  // Relegalize input.
2086         AddLegalizedOperand(Op, Tmp);
2087         return Tmp;
2088       } //else it was considered legal and we fall through
2089     }
2090     case TargetLowering::Legal:
2091       if (Tmp1 != Node->getOperand(0) ||
2092           Tmp2 != Node->getOperand(1))
2093         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
2094                              Tmp2);
2095       break;
2096     case TargetLowering::Promote:
2097       assert(0 && "Cannot promote handle this yet!");
2098     case TargetLowering::Expand:
2099       if (MVT::isInteger(Node->getValueType(0))) {
2100         MVT::ValueType VT = Node->getValueType(0);
2101         unsigned Opc = (Node->getOpcode() == ISD::UREM) ? ISD::UDIV : ISD::SDIV;
2102         Result = DAG.getNode(Opc, VT, Tmp1, Tmp2);
2103         Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
2104         Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
2105       } else {
2106         // Floating point mod -> fmod libcall.
2107         const char *FnName = Node->getValueType(0) == MVT::f32 ? "fmodf":"fmod";
2108         SDOperand Dummy;
2109         Result = ExpandLibCall(FnName, Node, Dummy);
2110       }
2111       break;
2112     }
2113     break;
2114
2115   case ISD::ROTL:
2116   case ISD::ROTR:
2117     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2118     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2119     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2120     case TargetLowering::Custom:
2121     case TargetLowering::Promote:
2122     case TargetLowering::Expand:
2123       assert(0 && "Cannot handle this yet!");
2124     case TargetLowering::Legal:
2125       if (Tmp1 != Node->getOperand(0) ||
2126           Tmp2 != Node->getOperand(1))
2127         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
2128                              Tmp2);
2129       break;
2130     }
2131     break;
2132     
2133   case ISD::CTPOP:
2134   case ISD::CTTZ:
2135   case ISD::CTLZ:
2136     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2137     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2138     case TargetLowering::Legal:
2139       if (Tmp1 != Node->getOperand(0))
2140         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2141       break;
2142     case TargetLowering::Promote: {
2143       MVT::ValueType OVT = Tmp1.getValueType();
2144       MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2145
2146       // Zero extend the argument.
2147       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2148       // Perform the larger operation, then subtract if needed.
2149       Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2150       switch(Node->getOpcode())
2151       {
2152       case ISD::CTPOP:
2153         Result = Tmp1;
2154         break;
2155       case ISD::CTTZ:
2156         //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2157         Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
2158                             DAG.getConstant(getSizeInBits(NVT), NVT),
2159                             ISD::SETEQ);
2160         Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
2161                            DAG.getConstant(getSizeInBits(OVT),NVT), Tmp1);
2162         break;
2163       case ISD::CTLZ:
2164         //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2165         Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
2166                              DAG.getConstant(getSizeInBits(NVT) -
2167                                              getSizeInBits(OVT), NVT));
2168         break;
2169       }
2170       break;
2171     }
2172     case TargetLowering::Custom:
2173       assert(0 && "Cannot custom handle this yet!");
2174     case TargetLowering::Expand:
2175       switch(Node->getOpcode())
2176       {
2177       case ISD::CTPOP: {
2178         static const uint64_t mask[6] = {
2179           0x5555555555555555ULL, 0x3333333333333333ULL,
2180           0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
2181           0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
2182         };
2183         MVT::ValueType VT = Tmp1.getValueType();
2184         MVT::ValueType ShVT = TLI.getShiftAmountTy();
2185         unsigned len = getSizeInBits(VT);
2186         for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2187           //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
2188           Tmp2 = DAG.getConstant(mask[i], VT);
2189           Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2190           Tmp1 = DAG.getNode(ISD::ADD, VT,
2191                              DAG.getNode(ISD::AND, VT, Tmp1, Tmp2),
2192                              DAG.getNode(ISD::AND, VT,
2193                                          DAG.getNode(ISD::SRL, VT, Tmp1, Tmp3),
2194                                          Tmp2));
2195         }
2196         Result = Tmp1;
2197         break;
2198       }
2199       case ISD::CTLZ: {
2200         /* for now, we do this:
2201            x = x | (x >> 1);
2202            x = x | (x >> 2);
2203            ...
2204            x = x | (x >>16);
2205            x = x | (x >>32); // for 64-bit input
2206            return popcount(~x);
2207
2208            but see also: http://www.hackersdelight.org/HDcode/nlz.cc */
2209         MVT::ValueType VT = Tmp1.getValueType();
2210         MVT::ValueType ShVT = TLI.getShiftAmountTy();
2211         unsigned len = getSizeInBits(VT);
2212         for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2213           Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2214           Tmp1 = DAG.getNode(ISD::OR, VT, Tmp1,
2215                              DAG.getNode(ISD::SRL, VT, Tmp1, Tmp3));
2216         }
2217         Tmp3 = DAG.getNode(ISD::XOR, VT, Tmp1, DAG.getConstant(~0ULL, VT));
2218         Result = LegalizeOp(DAG.getNode(ISD::CTPOP, VT, Tmp3));
2219         break;
2220       }
2221       case ISD::CTTZ: {
2222         // for now, we use: { return popcount(~x & (x - 1)); }
2223         // unless the target has ctlz but not ctpop, in which case we use:
2224         // { return 32 - nlz(~x & (x-1)); }
2225         // see also http://www.hackersdelight.org/HDcode/ntz.cc
2226         MVT::ValueType VT = Tmp1.getValueType();
2227         Tmp2 = DAG.getConstant(~0ULL, VT);
2228         Tmp3 = DAG.getNode(ISD::AND, VT,
2229                            DAG.getNode(ISD::XOR, VT, Tmp1, Tmp2),
2230                            DAG.getNode(ISD::SUB, VT, Tmp1,
2231                                        DAG.getConstant(1, VT)));
2232         // If ISD::CTLZ is legal and CTPOP isn't, then do that instead
2233         if (!TLI.isOperationLegal(ISD::CTPOP, VT) &&
2234             TLI.isOperationLegal(ISD::CTLZ, VT)) {
2235           Result = LegalizeOp(DAG.getNode(ISD::SUB, VT,
2236                                         DAG.getConstant(getSizeInBits(VT), VT),
2237                                         DAG.getNode(ISD::CTLZ, VT, Tmp3)));
2238         } else {
2239           Result = LegalizeOp(DAG.getNode(ISD::CTPOP, VT, Tmp3));
2240         }
2241         break;
2242       }
2243       default:
2244         assert(0 && "Cannot expand this yet!");
2245         break;
2246       }
2247       break;
2248     }
2249     break;
2250
2251     // Unary operators
2252   case ISD::FABS:
2253   case ISD::FNEG:
2254   case ISD::FSQRT:
2255   case ISD::FSIN:
2256   case ISD::FCOS:
2257     Tmp1 = LegalizeOp(Node->getOperand(0));
2258     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2259     case TargetLowering::Legal:
2260       if (Tmp1 != Node->getOperand(0))
2261         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2262       break;
2263     case TargetLowering::Promote:
2264     case TargetLowering::Custom:
2265       assert(0 && "Cannot promote/custom handle this yet!");
2266     case TargetLowering::Expand:
2267       switch(Node->getOpcode()) {
2268       case ISD::FNEG: {
2269         // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
2270         Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2271         Result = LegalizeOp(DAG.getNode(ISD::FSUB, Node->getValueType(0),
2272                                         Tmp2, Tmp1));
2273         break;
2274       }
2275       case ISD::FABS: {
2276         // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2277         MVT::ValueType VT = Node->getValueType(0);
2278         Tmp2 = DAG.getConstantFP(0.0, VT);
2279         Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1, Tmp2, ISD::SETUGT);
2280         Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
2281         Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
2282         Result = LegalizeOp(Result);
2283         break;
2284       }
2285       case ISD::FSQRT:
2286       case ISD::FSIN:
2287       case ISD::FCOS: {
2288         MVT::ValueType VT = Node->getValueType(0);
2289         const char *FnName = 0;
2290         switch(Node->getOpcode()) {
2291         case ISD::FSQRT: FnName = VT == MVT::f32 ? "sqrtf" : "sqrt"; break;
2292         case ISD::FSIN:  FnName = VT == MVT::f32 ? "sinf"  : "sin"; break;
2293         case ISD::FCOS:  FnName = VT == MVT::f32 ? "cosf"  : "cos"; break;
2294         default: assert(0 && "Unreachable!");
2295         }
2296         SDOperand Dummy;
2297         Result = ExpandLibCall(FnName, Node, Dummy);
2298         break;
2299       }
2300       default:
2301         assert(0 && "Unreachable!");
2302       }
2303       break;
2304     }
2305     break;
2306     
2307   case ISD::BIT_CONVERT:
2308     if (!isTypeLegal(Node->getOperand(0).getValueType()))
2309       Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2310     else {
2311       switch (TLI.getOperationAction(ISD::BIT_CONVERT,
2312                                      Node->getOperand(0).getValueType())) {
2313       default: assert(0 && "Unknown operation action!");
2314       case TargetLowering::Expand:
2315         Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2316         break;
2317       case TargetLowering::Legal:
2318         Tmp1 = LegalizeOp(Node->getOperand(0));
2319         if (Tmp1 != Node->getOperand(0))
2320           Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), Tmp1);
2321         break;
2322       }
2323     }
2324     break;
2325     // Conversion operators.  The source and destination have different types.
2326   case ISD::SINT_TO_FP:
2327   case ISD::UINT_TO_FP: {
2328     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
2329     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2330     case Legal:
2331       switch (TLI.getOperationAction(Node->getOpcode(),
2332                                      Node->getOperand(0).getValueType())) {
2333       default: assert(0 && "Unknown operation action!");
2334       case TargetLowering::Expand:
2335         Result = ExpandLegalINT_TO_FP(isSigned,
2336                                       LegalizeOp(Node->getOperand(0)),
2337                                       Node->getValueType(0));
2338         AddLegalizedOperand(Op, Result);
2339         return Result;
2340       case TargetLowering::Promote:
2341         Result = PromoteLegalINT_TO_FP(LegalizeOp(Node->getOperand(0)),
2342                                        Node->getValueType(0),
2343                                        isSigned);
2344         AddLegalizedOperand(Op, Result);
2345         return Result;
2346       case TargetLowering::Legal:
2347         break;
2348       case TargetLowering::Custom: {
2349         Tmp1 = LegalizeOp(Node->getOperand(0));
2350         SDOperand Tmp =
2351           DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2352         Tmp = TLI.LowerOperation(Tmp, DAG);
2353         if (Tmp.Val) {
2354           Tmp = LegalizeOp(Tmp);  // Relegalize input.
2355           AddLegalizedOperand(Op, Tmp);
2356           return Tmp;
2357         } else {
2358           assert(0 && "Target Must Lower this");
2359         }
2360       }
2361       }
2362
2363       Tmp1 = LegalizeOp(Node->getOperand(0));
2364       if (Tmp1 != Node->getOperand(0))
2365         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2366       break;
2367     case Expand:
2368       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
2369                              Node->getValueType(0), Node->getOperand(0));
2370       break;
2371     case Promote:
2372       if (isSigned) {
2373         Result = PromoteOp(Node->getOperand(0));
2374         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2375                  Result, DAG.getValueType(Node->getOperand(0).getValueType()));
2376         Result = DAG.getNode(ISD::SINT_TO_FP, Op.getValueType(), Result);
2377       } else {
2378         Result = PromoteOp(Node->getOperand(0));
2379         Result = DAG.getZeroExtendInReg(Result,
2380                                         Node->getOperand(0).getValueType());
2381         Result = DAG.getNode(ISD::UINT_TO_FP, Op.getValueType(), Result);
2382       }
2383       break;
2384     }
2385     break;
2386   }
2387   case ISD::TRUNCATE:
2388     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2389     case Legal:
2390       Tmp1 = LegalizeOp(Node->getOperand(0));
2391       if (Tmp1 != Node->getOperand(0))
2392         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2393       break;
2394     case Expand:
2395       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2396
2397       // Since the result is legal, we should just be able to truncate the low
2398       // part of the source.
2399       Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
2400       break;
2401     case Promote:
2402       Result = PromoteOp(Node->getOperand(0));
2403       Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
2404       break;
2405     }
2406     break;
2407
2408   case ISD::FP_TO_SINT:
2409   case ISD::FP_TO_UINT:
2410     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2411     case Legal:
2412       Tmp1 = LegalizeOp(Node->getOperand(0));
2413
2414       switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
2415       default: assert(0 && "Unknown operation action!");
2416       case TargetLowering::Expand:
2417         if (Node->getOpcode() == ISD::FP_TO_UINT) {
2418           SDOperand True, False;
2419           MVT::ValueType VT =  Node->getOperand(0).getValueType();
2420           MVT::ValueType NVT = Node->getValueType(0);
2421           unsigned ShiftAmt = MVT::getSizeInBits(Node->getValueType(0))-1;
2422           Tmp2 = DAG.getConstantFP((double)(1ULL << ShiftAmt), VT);
2423           Tmp3 = DAG.getSetCC(TLI.getSetCCResultTy(),
2424                             Node->getOperand(0), Tmp2, ISD::SETLT);
2425           True = DAG.getNode(ISD::FP_TO_SINT, NVT, Node->getOperand(0));
2426           False = DAG.getNode(ISD::FP_TO_SINT, NVT,
2427                               DAG.getNode(ISD::FSUB, VT, Node->getOperand(0),
2428                                           Tmp2));
2429           False = DAG.getNode(ISD::XOR, NVT, False, 
2430                               DAG.getConstant(1ULL << ShiftAmt, NVT));
2431           Result = LegalizeOp(DAG.getNode(ISD::SELECT, NVT, Tmp3, True, False));
2432           AddLegalizedOperand(SDOperand(Node, 0), Result);
2433           return Result;
2434         } else {
2435           assert(0 && "Do not know how to expand FP_TO_SINT yet!");
2436         }
2437         break;
2438       case TargetLowering::Promote:
2439         Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
2440                                        Node->getOpcode() == ISD::FP_TO_SINT);
2441         AddLegalizedOperand(Op, Result);
2442         return Result;
2443       case TargetLowering::Custom: {
2444         SDOperand Tmp =
2445           DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2446         Tmp = TLI.LowerOperation(Tmp, DAG);
2447         if (Tmp.Val) {
2448           Tmp = LegalizeOp(Tmp);
2449           AddLegalizedOperand(Op, Tmp);
2450           return Tmp;
2451         } else {
2452           // The target thinks this is legal afterall.
2453           break;
2454         }
2455       }
2456       case TargetLowering::Legal:
2457         break;
2458       }
2459
2460       if (Tmp1 != Node->getOperand(0))
2461         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2462       break;
2463     case Expand:
2464       assert(0 && "Shouldn't need to expand other operators here!");
2465     case Promote:
2466       Result = PromoteOp(Node->getOperand(0));
2467       Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
2468       break;
2469     }
2470     break;
2471
2472   case ISD::ANY_EXTEND:
2473   case ISD::ZERO_EXTEND:
2474   case ISD::SIGN_EXTEND:
2475   case ISD::FP_EXTEND:
2476   case ISD::FP_ROUND:
2477     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2478     case Legal:
2479       Tmp1 = LegalizeOp(Node->getOperand(0));
2480       if (Tmp1 != Node->getOperand(0))
2481         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2482       break;
2483     case Expand:
2484       assert(0 && "Shouldn't need to expand other operators here!");
2485
2486     case Promote:
2487       switch (Node->getOpcode()) {
2488       case ISD::ANY_EXTEND:
2489         Result = PromoteOp(Node->getOperand(0));
2490         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2491         break;
2492       case ISD::ZERO_EXTEND:
2493         Result = PromoteOp(Node->getOperand(0));
2494         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2495         Result = DAG.getZeroExtendInReg(Result,
2496                                         Node->getOperand(0).getValueType());
2497         break;
2498       case ISD::SIGN_EXTEND:
2499         Result = PromoteOp(Node->getOperand(0));
2500         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2501         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2502                              Result,
2503                           DAG.getValueType(Node->getOperand(0).getValueType()));
2504         break;
2505       case ISD::FP_EXTEND:
2506         Result = PromoteOp(Node->getOperand(0));
2507         if (Result.getValueType() != Op.getValueType())
2508           // Dynamically dead while we have only 2 FP types.
2509           Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
2510         break;
2511       case ISD::FP_ROUND:
2512         Result = PromoteOp(Node->getOperand(0));
2513         Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
2514         break;
2515       }
2516     }
2517     break;
2518   case ISD::FP_ROUND_INREG:
2519   case ISD::SIGN_EXTEND_INREG: {
2520     Tmp1 = LegalizeOp(Node->getOperand(0));
2521     MVT::ValueType ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2522
2523     // If this operation is not supported, convert it to a shl/shr or load/store
2524     // pair.
2525     switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
2526     default: assert(0 && "This action not supported for this op yet!");
2527     case TargetLowering::Legal:
2528       if (Tmp1 != Node->getOperand(0))
2529         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
2530                              DAG.getValueType(ExtraVT));
2531       break;
2532     case TargetLowering::Expand:
2533       // If this is an integer extend and shifts are supported, do that.
2534       if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
2535         // NOTE: we could fall back on load/store here too for targets without
2536         // SAR.  However, it is doubtful that any exist.
2537         unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
2538                             MVT::getSizeInBits(ExtraVT);
2539         SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
2540         Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
2541                              Node->getOperand(0), ShiftCst);
2542         Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
2543                              Result, ShiftCst);
2544       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
2545         // The only way we can lower this is to turn it into a STORETRUNC,
2546         // EXTLOAD pair, targetting a temporary location (a stack slot).
2547
2548         // NOTE: there is a choice here between constantly creating new stack
2549         // slots and always reusing the same one.  We currently always create
2550         // new ones, as reuse may inhibit scheduling.
2551         const Type *Ty = MVT::getTypeForValueType(ExtraVT);
2552         unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
2553         unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
2554         MachineFunction &MF = DAG.getMachineFunction();
2555         int SSFI =
2556           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
2557         SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
2558         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
2559                              Node->getOperand(0), StackSlot,
2560                              DAG.getSrcValue(NULL), DAG.getValueType(ExtraVT));
2561         Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
2562                                 Result, StackSlot, DAG.getSrcValue(NULL),
2563                                 ExtraVT);
2564       } else {
2565         assert(0 && "Unknown op");
2566       }
2567       Result = LegalizeOp(Result);
2568       break;
2569     }
2570     break;
2571   }
2572   }
2573
2574   // Note that LegalizeOp may be reentered even from single-use nodes, which
2575   // means that we always must cache transformed nodes.
2576   AddLegalizedOperand(Op, Result);
2577   return Result;
2578 }
2579
2580 /// PromoteOp - Given an operation that produces a value in an invalid type,
2581 /// promote it to compute the value into a larger type.  The produced value will
2582 /// have the correct bits for the low portion of the register, but no guarantee
2583 /// is made about the top bits: it may be zero, sign-extended, or garbage.
2584 SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
2585   MVT::ValueType VT = Op.getValueType();
2586   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
2587   assert(getTypeAction(VT) == Promote &&
2588          "Caller should expand or legalize operands that are not promotable!");
2589   assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
2590          "Cannot promote to smaller type!");
2591
2592   SDOperand Tmp1, Tmp2, Tmp3;
2593
2594   SDOperand Result;
2595   SDNode *Node = Op.Val;
2596
2597   std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
2598   if (I != PromotedNodes.end()) return I->second;
2599
2600   // Promotion needs an optimization step to clean up after it, and is not
2601   // careful to avoid operations the target does not support.  Make sure that
2602   // all generated operations are legalized in the next iteration.
2603   NeedsAnotherIteration = true;
2604
2605   switch (Node->getOpcode()) {
2606   case ISD::CopyFromReg:
2607     assert(0 && "CopyFromReg must be legal!");
2608   default:
2609     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
2610     assert(0 && "Do not know how to promote this operator!");
2611     abort();
2612   case ISD::UNDEF:
2613     Result = DAG.getNode(ISD::UNDEF, NVT);
2614     break;
2615   case ISD::Constant:
2616     if (VT != MVT::i1)
2617       Result = DAG.getNode(ISD::SIGN_EXTEND, NVT, Op);
2618     else
2619       Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
2620     assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
2621     break;
2622   case ISD::ConstantFP:
2623     Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
2624     assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
2625     break;
2626
2627   case ISD::SETCC:
2628     assert(isTypeLegal(TLI.getSetCCResultTy()) && "SetCC type is not legal??");
2629     Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),Node->getOperand(0),
2630                          Node->getOperand(1), Node->getOperand(2));
2631     Result = LegalizeOp(Result);
2632     break;
2633
2634   case ISD::TRUNCATE:
2635     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2636     case Legal:
2637       Result = LegalizeOp(Node->getOperand(0));
2638       assert(Result.getValueType() >= NVT &&
2639              "This truncation doesn't make sense!");
2640       if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
2641         Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
2642       break;
2643     case Promote:
2644       // The truncation is not required, because we don't guarantee anything
2645       // about high bits anyway.
2646       Result = PromoteOp(Node->getOperand(0));
2647       break;
2648     case Expand:
2649       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2650       // Truncate the low part of the expanded value to the result type
2651       Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
2652     }
2653     break;
2654   case ISD::SIGN_EXTEND:
2655   case ISD::ZERO_EXTEND:
2656   case ISD::ANY_EXTEND:
2657     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2658     case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
2659     case Legal:
2660       // Input is legal?  Just do extend all the way to the larger type.
2661       Result = LegalizeOp(Node->getOperand(0));
2662       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2663       break;
2664     case Promote:
2665       // Promote the reg if it's smaller.
2666       Result = PromoteOp(Node->getOperand(0));
2667       // The high bits are not guaranteed to be anything.  Insert an extend.
2668       if (Node->getOpcode() == ISD::SIGN_EXTEND)
2669         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
2670                          DAG.getValueType(Node->getOperand(0).getValueType()));
2671       else if (Node->getOpcode() == ISD::ZERO_EXTEND)
2672         Result = DAG.getZeroExtendInReg(Result,
2673                                         Node->getOperand(0).getValueType());
2674       break;
2675     }
2676     break;
2677   case ISD::BIT_CONVERT:
2678     Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2679     Result = PromoteOp(Result);
2680     break;
2681     
2682   case ISD::FP_EXTEND:
2683     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
2684   case ISD::FP_ROUND:
2685     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2686     case Expand: assert(0 && "BUG: Cannot expand FP regs!");
2687     case Promote:  assert(0 && "Unreachable with 2 FP types!");
2688     case Legal:
2689       // Input is legal?  Do an FP_ROUND_INREG.
2690       Result = LegalizeOp(Node->getOperand(0));
2691       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2692                            DAG.getValueType(VT));
2693       break;
2694     }
2695     break;
2696
2697   case ISD::SINT_TO_FP:
2698   case ISD::UINT_TO_FP:
2699     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2700     case Legal:
2701       Result = LegalizeOp(Node->getOperand(0));
2702       // No extra round required here.
2703       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2704       break;
2705
2706     case Promote:
2707       Result = PromoteOp(Node->getOperand(0));
2708       if (Node->getOpcode() == ISD::SINT_TO_FP)
2709         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2710                              Result,
2711                          DAG.getValueType(Node->getOperand(0).getValueType()));
2712       else
2713         Result = DAG.getZeroExtendInReg(Result,
2714                                         Node->getOperand(0).getValueType());
2715       // No extra round required here.
2716       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2717       break;
2718     case Expand:
2719       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
2720                              Node->getOperand(0));
2721       // Round if we cannot tolerate excess precision.
2722       if (NoExcessFPPrecision)
2723         Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2724                              DAG.getValueType(VT));
2725       break;
2726     }
2727     break;
2728
2729   case ISD::SIGN_EXTEND_INREG:
2730     Result = PromoteOp(Node->getOperand(0));
2731     Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result, 
2732                          Node->getOperand(1));
2733     break;
2734   case ISD::FP_TO_SINT:
2735   case ISD::FP_TO_UINT:
2736     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2737     case Legal:
2738       Tmp1 = LegalizeOp(Node->getOperand(0));
2739       break;
2740     case Promote:
2741       // The input result is prerounded, so we don't have to do anything
2742       // special.
2743       Tmp1 = PromoteOp(Node->getOperand(0));
2744       break;
2745     case Expand:
2746       assert(0 && "not implemented");
2747     }
2748     // If we're promoting a UINT to a larger size, check to see if the new node
2749     // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
2750     // we can use that instead.  This allows us to generate better code for
2751     // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
2752     // legal, such as PowerPC.
2753     if (Node->getOpcode() == ISD::FP_TO_UINT && 
2754         !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
2755         (TLI.isOperationLegal(ISD::FP_TO_SINT, NVT) ||
2756          TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
2757       Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
2758     } else {
2759       Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2760     }
2761     break;
2762
2763   case ISD::FABS:
2764   case ISD::FNEG:
2765     Tmp1 = PromoteOp(Node->getOperand(0));
2766     assert(Tmp1.getValueType() == NVT);
2767     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2768     // NOTE: we do not have to do any extra rounding here for
2769     // NoExcessFPPrecision, because we know the input will have the appropriate
2770     // precision, and these operations don't modify precision at all.
2771     break;
2772
2773   case ISD::FSQRT:
2774   case ISD::FSIN:
2775   case ISD::FCOS:
2776     Tmp1 = PromoteOp(Node->getOperand(0));
2777     assert(Tmp1.getValueType() == NVT);
2778     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2779     if(NoExcessFPPrecision)
2780       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2781                            DAG.getValueType(VT));
2782     break;
2783
2784   case ISD::AND:
2785   case ISD::OR:
2786   case ISD::XOR:
2787   case ISD::ADD:
2788   case ISD::SUB:
2789   case ISD::MUL:
2790     // The input may have strange things in the top bits of the registers, but
2791     // these operations don't care.  They may have weird bits going out, but
2792     // that too is okay if they are integer operations.
2793     Tmp1 = PromoteOp(Node->getOperand(0));
2794     Tmp2 = PromoteOp(Node->getOperand(1));
2795     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2796     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2797     break;
2798   case ISD::FADD:
2799   case ISD::FSUB:
2800   case ISD::FMUL:
2801     // The input may have strange things in the top bits of the registers, but
2802     // these operations don't care.
2803     Tmp1 = PromoteOp(Node->getOperand(0));
2804     Tmp2 = PromoteOp(Node->getOperand(1));
2805     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2806     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2807     
2808     // Floating point operations will give excess precision that we may not be
2809     // able to tolerate.  If we DO allow excess precision, just leave it,
2810     // otherwise excise it.
2811     // FIXME: Why would we need to round FP ops more than integer ones?
2812     //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
2813     if (NoExcessFPPrecision)
2814       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2815                            DAG.getValueType(VT));
2816     break;
2817
2818   case ISD::SDIV:
2819   case ISD::SREM:
2820     // These operators require that their input be sign extended.
2821     Tmp1 = PromoteOp(Node->getOperand(0));
2822     Tmp2 = PromoteOp(Node->getOperand(1));
2823     if (MVT::isInteger(NVT)) {
2824       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
2825                          DAG.getValueType(VT));
2826       Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
2827                          DAG.getValueType(VT));
2828     }
2829     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2830
2831     // Perform FP_ROUND: this is probably overly pessimistic.
2832     if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
2833       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2834                            DAG.getValueType(VT));
2835     break;
2836   case ISD::FDIV:
2837   case ISD::FREM:
2838     // These operators require that their input be fp extended.
2839     Tmp1 = PromoteOp(Node->getOperand(0));
2840     Tmp2 = PromoteOp(Node->getOperand(1));
2841     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2842     
2843     // Perform FP_ROUND: this is probably overly pessimistic.
2844     if (NoExcessFPPrecision)
2845       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2846                            DAG.getValueType(VT));
2847     break;
2848
2849   case ISD::UDIV:
2850   case ISD::UREM:
2851     // These operators require that their input be zero extended.
2852     Tmp1 = PromoteOp(Node->getOperand(0));
2853     Tmp2 = PromoteOp(Node->getOperand(1));
2854     assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
2855     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
2856     Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
2857     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2858     break;
2859
2860   case ISD::SHL:
2861     Tmp1 = PromoteOp(Node->getOperand(0));
2862     Tmp2 = LegalizeOp(Node->getOperand(1));
2863     Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Tmp2);
2864     break;
2865   case ISD::SRA:
2866     // The input value must be properly sign extended.
2867     Tmp1 = PromoteOp(Node->getOperand(0));
2868     Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
2869                        DAG.getValueType(VT));
2870     Tmp2 = LegalizeOp(Node->getOperand(1));
2871     Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Tmp2);
2872     break;
2873   case ISD::SRL:
2874     // The input value must be properly zero extended.
2875     Tmp1 = PromoteOp(Node->getOperand(0));
2876     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
2877     Tmp2 = LegalizeOp(Node->getOperand(1));
2878     Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Tmp2);
2879     break;
2880   case ISD::LOAD:
2881     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
2882     Tmp2 = LegalizeOp(Node->getOperand(1));   // Legalize the pointer.
2883     Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp1, Tmp2,
2884                             Node->getOperand(2), VT);
2885     // Remember that we legalized the chain.
2886     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
2887     break;
2888   case ISD::SEXTLOAD:
2889   case ISD::ZEXTLOAD:
2890   case ISD::EXTLOAD:
2891     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
2892     Tmp2 = LegalizeOp(Node->getOperand(1));   // Legalize the pointer.
2893     Result = DAG.getExtLoad(Node->getOpcode(), NVT, Tmp1, Tmp2,
2894                          Node->getOperand(2),
2895                             cast<VTSDNode>(Node->getOperand(3))->getVT());
2896     // Remember that we legalized the chain.
2897     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
2898     break;
2899   case ISD::SELECT:
2900     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2901     case Expand: assert(0 && "It's impossible to expand bools");
2902     case Legal:
2903       Tmp1 = LegalizeOp(Node->getOperand(0));// Legalize the condition.
2904       break;
2905     case Promote:
2906       Tmp1 = PromoteOp(Node->getOperand(0)); // Promote the condition.
2907       break;
2908     }
2909     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
2910     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
2911     Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2, Tmp3);
2912     break;
2913   case ISD::SELECT_CC:
2914     Tmp2 = PromoteOp(Node->getOperand(2));   // True
2915     Tmp3 = PromoteOp(Node->getOperand(3));   // False
2916     Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
2917                          Node->getOperand(1), Tmp2, Tmp3,
2918                          Node->getOperand(4));
2919     break;
2920   case ISD::TAILCALL:
2921   case ISD::CALL: {
2922     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2923     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
2924
2925     std::vector<SDOperand> Ops;
2926     for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i)
2927       Ops.push_back(LegalizeOp(Node->getOperand(i)));
2928
2929     assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
2930            "Can only promote single result calls");
2931     std::vector<MVT::ValueType> RetTyVTs;
2932     RetTyVTs.reserve(2);
2933     RetTyVTs.push_back(NVT);
2934     RetTyVTs.push_back(MVT::Other);
2935     SDNode *NC = DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops,
2936                              Node->getOpcode() == ISD::TAILCALL);
2937     Result = SDOperand(NC, 0);
2938
2939     // Insert the new chain mapping.
2940     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
2941     break;
2942   }
2943   case ISD::CTPOP:
2944   case ISD::CTTZ:
2945   case ISD::CTLZ:
2946     Tmp1 = Node->getOperand(0);
2947     //Zero extend the argument
2948     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2949     // Perform the larger operation, then subtract if needed.
2950     Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2951     switch(Node->getOpcode())
2952     {
2953     case ISD::CTPOP:
2954       Result = Tmp1;
2955       break;
2956     case ISD::CTTZ:
2957       //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2958       Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
2959                           DAG.getConstant(getSizeInBits(NVT), NVT), ISD::SETEQ);
2960       Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
2961                            DAG.getConstant(getSizeInBits(VT),NVT), Tmp1);
2962       break;
2963     case ISD::CTLZ:
2964       //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2965       Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
2966                            DAG.getConstant(getSizeInBits(NVT) -
2967                                            getSizeInBits(VT), NVT));
2968       break;
2969     }
2970     break;
2971   }
2972
2973   assert(Result.Val && "Didn't set a result!");
2974   AddPromotedOperand(Op, Result);
2975   return Result;
2976 }
2977
2978 /// ExpandBIT_CONVERT - Expand a BIT_CONVERT node into a store/load combination.
2979 /// The resultant code need not be legal.  Note that SrcOp is the input operand
2980 /// to the BIT_CONVERT, not the BIT_CONVERT node itself.
2981 SDOperand SelectionDAGLegalize::ExpandBIT_CONVERT(MVT::ValueType DestVT, 
2982                                                   SDOperand SrcOp) {
2983   // Create the stack frame object.
2984   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
2985   unsigned ByteSize = MVT::getSizeInBits(DestVT)/8;
2986   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
2987   SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
2988   
2989   // Emit a store to the stack slot.
2990   SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
2991                                 SrcOp, FIPtr, DAG.getSrcValue(NULL));
2992   // Result is a load from the stack slot.
2993   return DAG.getLoad(DestVT, Store, FIPtr, DAG.getSrcValue(0));
2994 }
2995
2996 /// ExpandAddSub - Find a clever way to expand this add operation into
2997 /// subcomponents.
2998 void SelectionDAGLegalize::
2999 ExpandByParts(unsigned NodeOp, SDOperand LHS, SDOperand RHS,
3000               SDOperand &Lo, SDOperand &Hi) {
3001   // Expand the subcomponents.
3002   SDOperand LHSL, LHSH, RHSL, RHSH;
3003   ExpandOp(LHS, LHSL, LHSH);
3004   ExpandOp(RHS, RHSL, RHSH);
3005
3006   std::vector<SDOperand> Ops;
3007   Ops.push_back(LHSL);
3008   Ops.push_back(LHSH);
3009   Ops.push_back(RHSL);
3010   Ops.push_back(RHSH);
3011   std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
3012   Lo = DAG.getNode(NodeOp, VTs, Ops);
3013   Hi = Lo.getValue(1);
3014 }
3015
3016 void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
3017                                             SDOperand Op, SDOperand Amt,
3018                                             SDOperand &Lo, SDOperand &Hi) {
3019   // Expand the subcomponents.
3020   SDOperand LHSL, LHSH;
3021   ExpandOp(Op, LHSL, LHSH);
3022
3023   std::vector<SDOperand> Ops;
3024   Ops.push_back(LHSL);
3025   Ops.push_back(LHSH);
3026   Ops.push_back(Amt);
3027   std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
3028   Lo = DAG.getNode(NodeOp, VTs, Ops);
3029   Hi = Lo.getValue(1);
3030 }
3031
3032
3033 /// ExpandShift - Try to find a clever way to expand this shift operation out to
3034 /// smaller elements.  If we can't find a way that is more efficient than a
3035 /// libcall on this target, return false.  Otherwise, return true with the
3036 /// low-parts expanded into Lo and Hi.
3037 bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
3038                                        SDOperand &Lo, SDOperand &Hi) {
3039   assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
3040          "This is not a shift!");
3041
3042   MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
3043   SDOperand ShAmt = LegalizeOp(Amt);
3044   MVT::ValueType ShTy = ShAmt.getValueType();
3045   unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
3046   unsigned NVTBits = MVT::getSizeInBits(NVT);
3047
3048   // Handle the case when Amt is an immediate.  Other cases are currently broken
3049   // and are disabled.
3050   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
3051     unsigned Cst = CN->getValue();
3052     // Expand the incoming operand to be shifted, so that we have its parts
3053     SDOperand InL, InH;
3054     ExpandOp(Op, InL, InH);
3055     switch(Opc) {
3056     case ISD::SHL:
3057       if (Cst > VTBits) {
3058         Lo = DAG.getConstant(0, NVT);
3059         Hi = DAG.getConstant(0, NVT);
3060       } else if (Cst > NVTBits) {
3061         Lo = DAG.getConstant(0, NVT);
3062         Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
3063       } else if (Cst == NVTBits) {
3064         Lo = DAG.getConstant(0, NVT);
3065         Hi = InL;
3066       } else {
3067         Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
3068         Hi = DAG.getNode(ISD::OR, NVT,
3069            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
3070            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
3071       }
3072       return true;
3073     case ISD::SRL:
3074       if (Cst > VTBits) {
3075         Lo = DAG.getConstant(0, NVT);
3076         Hi = DAG.getConstant(0, NVT);
3077       } else if (Cst > NVTBits) {
3078         Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
3079         Hi = DAG.getConstant(0, NVT);
3080       } else if (Cst == NVTBits) {
3081         Lo = InH;
3082         Hi = DAG.getConstant(0, NVT);
3083       } else {
3084         Lo = DAG.getNode(ISD::OR, NVT,
3085            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
3086            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
3087         Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
3088       }
3089       return true;
3090     case ISD::SRA:
3091       if (Cst > VTBits) {
3092         Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
3093                               DAG.getConstant(NVTBits-1, ShTy));
3094       } else if (Cst > NVTBits) {
3095         Lo = DAG.getNode(ISD::SRA, NVT, InH,
3096                            DAG.getConstant(Cst-NVTBits, ShTy));
3097         Hi = DAG.getNode(ISD::SRA, NVT, InH,
3098                               DAG.getConstant(NVTBits-1, ShTy));
3099       } else if (Cst == NVTBits) {
3100         Lo = InH;
3101         Hi = DAG.getNode(ISD::SRA, NVT, InH,
3102                               DAG.getConstant(NVTBits-1, ShTy));
3103       } else {
3104         Lo = DAG.getNode(ISD::OR, NVT,
3105            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
3106            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
3107         Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
3108       }
3109       return true;
3110     }
3111   }
3112   // FIXME: The following code for expanding shifts using ISD::SELECT is buggy,
3113   // so disable it for now.  Currently targets are handling this via SHL_PARTS
3114   // and friends.
3115   return false;
3116
3117   // If we have an efficient select operation (or if the selects will all fold
3118   // away), lower to some complex code, otherwise just emit the libcall.
3119   if (!TLI.isOperationLegal(ISD::SELECT, NVT) && !isa<ConstantSDNode>(Amt))
3120     return false;
3121
3122   SDOperand InL, InH;
3123   ExpandOp(Op, InL, InH);
3124   SDOperand NAmt = DAG.getNode(ISD::SUB, ShTy,           // NAmt = 32-ShAmt
3125                                DAG.getConstant(NVTBits, ShTy), ShAmt);
3126
3127   // Compare the unmasked shift amount against 32.
3128   SDOperand Cond = DAG.getSetCC(TLI.getSetCCResultTy(), ShAmt,
3129                                 DAG.getConstant(NVTBits, ShTy), ISD::SETGE);
3130
3131   if (TLI.getShiftAmountFlavor() != TargetLowering::Mask) {
3132     ShAmt = DAG.getNode(ISD::AND, ShTy, ShAmt,             // ShAmt &= 31
3133                         DAG.getConstant(NVTBits-1, ShTy));
3134     NAmt  = DAG.getNode(ISD::AND, ShTy, NAmt,              // NAmt &= 31
3135                         DAG.getConstant(NVTBits-1, ShTy));
3136   }
3137
3138   if (Opc == ISD::SHL) {
3139     SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << Amt) | (Lo >> NAmt)
3140                                DAG.getNode(ISD::SHL, NVT, InH, ShAmt),
3141                                DAG.getNode(ISD::SRL, NVT, InL, NAmt));
3142     SDOperand T2 = DAG.getNode(ISD::SHL, NVT, InL, ShAmt); // T2 = Lo << Amt&31
3143
3144     Hi = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
3145     Lo = DAG.getNode(ISD::SELECT, NVT, Cond, DAG.getConstant(0, NVT), T2);
3146   } else {
3147     SDOperand HiLoPart = DAG.getNode(ISD::SELECT, NVT,
3148                                      DAG.getSetCC(TLI.getSetCCResultTy(), NAmt,
3149                                                   DAG.getConstant(32, ShTy),
3150                                                   ISD::SETEQ),
3151                                      DAG.getConstant(0, NVT),
3152                                      DAG.getNode(ISD::SHL, NVT, InH, NAmt));
3153     SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << NAmt) | (Lo >> Amt)
3154                                HiLoPart,
3155                                DAG.getNode(ISD::SRL, NVT, InL, ShAmt));
3156     SDOperand T2 = DAG.getNode(Opc, NVT, InH, ShAmt);  // T2 = InH >> ShAmt&31
3157
3158     SDOperand HiPart;
3159     if (Opc == ISD::SRA)
3160       HiPart = DAG.getNode(ISD::SRA, NVT, InH,
3161                            DAG.getConstant(NVTBits-1, ShTy));
3162     else
3163       HiPart = DAG.getConstant(0, NVT);
3164     Lo = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
3165     Hi = DAG.getNode(ISD::SELECT, NVT, Cond, HiPart, T2);
3166   }
3167   return true;
3168 }
3169
3170 /// FindLatestCallSeqStart - Scan up the dag to find the latest (highest
3171 /// NodeDepth) node that is an CallSeqStart operation and occurs later than
3172 /// Found.
3173 static void FindLatestCallSeqStart(SDNode *Node, SDNode *&Found,
3174                                    std::set<SDNode*> &Visited) {
3175   if (Node->getNodeDepth() <= Found->getNodeDepth() ||
3176       !Visited.insert(Node).second) return;
3177   
3178   // If we found an CALLSEQ_START, we already know this node occurs later
3179   // than the Found node. Just remember this node and return.
3180   if (Node->getOpcode() == ISD::CALLSEQ_START) {
3181     Found = Node;
3182     return;
3183   }
3184
3185   // Otherwise, scan the operands of Node to see if any of them is a call.
3186   assert(Node->getNumOperands() != 0 &&
3187          "All leaves should have depth equal to the entry node!");
3188   for (unsigned i = 0, e = Node->getNumOperands()-1; i != e; ++i)
3189     FindLatestCallSeqStart(Node->getOperand(i).Val, Found, Visited);
3190
3191   // Tail recurse for the last iteration.
3192   FindLatestCallSeqStart(Node->getOperand(Node->getNumOperands()-1).Val,
3193                          Found, Visited);
3194 }
3195
3196
3197 /// FindEarliestCallSeqEnd - Scan down the dag to find the earliest (lowest
3198 /// NodeDepth) node that is an CallSeqEnd operation and occurs more recent
3199 /// than Found.
3200 static void FindEarliestCallSeqEnd(SDNode *Node, SDNode *&Found,
3201                                    std::set<SDNode*> &Visited) {
3202   if ((Found && Node->getNodeDepth() >= Found->getNodeDepth()) ||
3203       !Visited.insert(Node).second) return;
3204
3205   // If we found an CALLSEQ_END, we already know this node occurs earlier
3206   // than the Found node. Just remember this node and return.
3207   if (Node->getOpcode() == ISD::CALLSEQ_END) {
3208     Found = Node;
3209     return;
3210   }
3211
3212   // Otherwise, scan the operands of Node to see if any of them is a call.
3213   SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
3214   if (UI == E) return;
3215   for (--E; UI != E; ++UI)
3216     FindEarliestCallSeqEnd(*UI, Found, Visited);
3217
3218   // Tail recurse for the last iteration.
3219   FindEarliestCallSeqEnd(*UI, Found, Visited);
3220 }
3221
3222 /// FindCallSeqEnd - Given a chained node that is part of a call sequence,
3223 /// find the CALLSEQ_END node that terminates the call sequence.
3224 static SDNode *FindCallSeqEnd(SDNode *Node) {
3225   if (Node->getOpcode() == ISD::CALLSEQ_END)
3226     return Node;
3227   if (Node->use_empty())
3228     return 0;   // No CallSeqEnd
3229
3230   SDOperand TheChain(Node, Node->getNumValues()-1);
3231   if (TheChain.getValueType() != MVT::Other)
3232     TheChain = SDOperand(Node, 0);
3233   if (TheChain.getValueType() != MVT::Other)
3234     return 0;
3235
3236   for (SDNode::use_iterator UI = Node->use_begin(),
3237          E = Node->use_end(); UI != E; ++UI) {
3238
3239     // Make sure to only follow users of our token chain.
3240     SDNode *User = *UI;
3241     for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3242       if (User->getOperand(i) == TheChain)
3243         if (SDNode *Result = FindCallSeqEnd(User))
3244           return Result;
3245   }
3246   return 0;
3247 }
3248
3249 /// FindCallSeqStart - Given a chained node that is part of a call sequence,
3250 /// find the CALLSEQ_START node that initiates the call sequence.
3251 static SDNode *FindCallSeqStart(SDNode *Node) {
3252   assert(Node && "Didn't find callseq_start for a call??");
3253   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
3254
3255   assert(Node->getOperand(0).getValueType() == MVT::Other &&
3256          "Node doesn't have a token chain argument!");
3257   return FindCallSeqStart(Node->getOperand(0).Val);
3258 }
3259
3260
3261 /// FindInputOutputChains - If we are replacing an operation with a call we need
3262 /// to find the call that occurs before and the call that occurs after it to
3263 /// properly serialize the calls in the block.  The returned operand is the
3264 /// input chain value for the new call (e.g. the entry node or the previous
3265 /// call), and OutChain is set to be the chain node to update to point to the
3266 /// end of the call chain.
3267 static SDOperand FindInputOutputChains(SDNode *OpNode, SDNode *&OutChain,
3268                                        SDOperand Entry) {
3269   SDNode *LatestCallSeqStart = Entry.Val;
3270   SDNode *LatestCallSeqEnd = 0;
3271   std::set<SDNode*> Visited;
3272   FindLatestCallSeqStart(OpNode, LatestCallSeqStart, Visited);
3273   Visited.clear();
3274   //std::cerr<<"Found node: "; LatestCallSeqStart->dump(); std::cerr <<"\n";
3275
3276   // It is possible that no ISD::CALLSEQ_START was found because there is no
3277   // previous call in the function.  LatestCallStackDown may in that case be
3278   // the entry node itself.  Do not attempt to find a matching CALLSEQ_END
3279   // unless LatestCallStackDown is an CALLSEQ_START.
3280   if (LatestCallSeqStart->getOpcode() == ISD::CALLSEQ_START) {
3281     LatestCallSeqEnd = FindCallSeqEnd(LatestCallSeqStart);
3282     //std::cerr<<"Found end node: "; LatestCallSeqEnd->dump(); std::cerr <<"\n";
3283   } else {
3284     LatestCallSeqEnd = Entry.Val;
3285   }
3286   assert(LatestCallSeqEnd && "NULL return from FindCallSeqEnd");
3287
3288   // Finally, find the first call that this must come before, first we find the
3289   // CallSeqEnd that ends the call.
3290   OutChain = 0;
3291   FindEarliestCallSeqEnd(OpNode, OutChain, Visited);
3292   Visited.clear();
3293
3294   // If we found one, translate from the adj up to the callseq_start.
3295   if (OutChain)
3296     OutChain = FindCallSeqStart(OutChain);
3297
3298   return SDOperand(LatestCallSeqEnd, 0);
3299 }
3300
3301 /// SpliceCallInto - Given the result chain of a libcall (CallResult), and a
3302 void SelectionDAGLegalize::SpliceCallInto(const SDOperand &CallResult,
3303                                           SDNode *OutChain) {
3304   // Nothing to splice it into?
3305   if (OutChain == 0) return;
3306
3307   assert(OutChain->getOperand(0).getValueType() == MVT::Other);
3308   //OutChain->dump();
3309
3310   // Form a token factor node merging the old inval and the new inval.
3311   SDOperand InToken = DAG.getNode(ISD::TokenFactor, MVT::Other, CallResult,
3312                                   OutChain->getOperand(0));
3313   // Change the node to refer to the new token.
3314   OutChain->setAdjCallChain(InToken);
3315 }
3316
3317
3318 // ExpandLibCall - Expand a node into a call to a libcall.  If the result value
3319 // does not fit into a register, return the lo part and set the hi part to the
3320 // by-reg argument.  If it does fit into a single register, return the result
3321 // and leave the Hi part unset.
3322 SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
3323                                               SDOperand &Hi) {
3324   SDNode *OutChain;
3325   SDOperand InChain = FindInputOutputChains(Node, OutChain,
3326                                             DAG.getEntryNode());
3327   if (InChain.Val == 0)
3328     InChain = DAG.getEntryNode();
3329
3330   TargetLowering::ArgListTy Args;
3331   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3332     MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
3333     const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
3334     Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
3335   }
3336   SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
3337
3338   // Splice the libcall in wherever FindInputOutputChains tells us to.
3339   const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
3340   std::pair<SDOperand,SDOperand> CallInfo =
3341     TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, false,
3342                     Callee, Args, DAG);
3343
3344   SDOperand Result;
3345   switch (getTypeAction(CallInfo.first.getValueType())) {
3346   default: assert(0 && "Unknown thing");
3347   case Legal:
3348     Result = CallInfo.first;
3349     break;
3350   case Promote:
3351     assert(0 && "Cannot promote this yet!");
3352   case Expand:
3353     ExpandOp(CallInfo.first, Result, Hi);
3354     CallInfo.second = LegalizeOp(CallInfo.second);
3355     break;
3356   }
3357   
3358   SpliceCallInto(CallInfo.second, OutChain);
3359   NeedsAnotherIteration = true;
3360   return Result;
3361 }
3362
3363
3364 /// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
3365 /// destination type is legal.
3366 SDOperand SelectionDAGLegalize::
3367 ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
3368   assert(isTypeLegal(DestTy) && "Destination type is not legal!");
3369   assert(getTypeAction(Source.getValueType()) == Expand &&
3370          "This is not an expansion!");
3371   assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
3372
3373   if (!isSigned) {
3374     assert(Source.getValueType() == MVT::i64 &&
3375            "This only works for 64-bit -> FP");
3376     // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
3377     // incoming integer is set.  To handle this, we dynamically test to see if
3378     // it is set, and, if so, add a fudge factor.
3379     SDOperand Lo, Hi;
3380     ExpandOp(Source, Lo, Hi);
3381
3382     // If this is unsigned, and not supported, first perform the conversion to
3383     // signed, then adjust the result if the sign bit is set.
3384     SDOperand SignedConv = ExpandIntToFP(true, DestTy,
3385                    DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), Lo, Hi));
3386
3387     SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
3388                                      DAG.getConstant(0, Hi.getValueType()),
3389                                      ISD::SETLT);
3390     SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
3391     SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
3392                                       SignSet, Four, Zero);
3393     uint64_t FF = 0x5f800000ULL;
3394     if (TLI.isLittleEndian()) FF <<= 32;
3395     static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
3396
3397     SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
3398     CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
3399     SDOperand FudgeInReg;
3400     if (DestTy == MVT::f32)
3401       FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
3402                                DAG.getSrcValue(NULL));
3403     else {
3404       assert(DestTy == MVT::f64 && "Unexpected conversion");
3405       FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
3406                                   CPIdx, DAG.getSrcValue(NULL), MVT::f32);
3407     }
3408     return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
3409   }
3410
3411   // Check to see if the target has a custom way to lower this.  If so, use it.
3412   switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
3413   default: assert(0 && "This action not implemented for this operation!");
3414   case TargetLowering::Legal:
3415   case TargetLowering::Expand:
3416     break;   // This case is handled below.
3417   case TargetLowering::Custom: {
3418     SDOperand NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
3419                                                   Source), DAG);
3420     if (NV.Val)
3421       return LegalizeOp(NV);
3422     break;   // The target decided this was legal after all
3423   }
3424   }
3425
3426   // Expand the source, then glue it back together for the call.  We must expand
3427   // the source in case it is shared (this pass of legalize must traverse it).
3428   SDOperand SrcLo, SrcHi;
3429   ExpandOp(Source, SrcLo, SrcHi);
3430   Source = DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), SrcLo, SrcHi);
3431
3432   SDNode *OutChain = 0;
3433   SDOperand InChain = FindInputOutputChains(Source.Val, OutChain,
3434                                             DAG.getEntryNode());
3435   const char *FnName = 0;
3436   if (DestTy == MVT::f32)
3437     FnName = "__floatdisf";
3438   else {
3439     assert(DestTy == MVT::f64 && "Unknown fp value type!");
3440     FnName = "__floatdidf";
3441   }
3442
3443   SDOperand Callee = DAG.getExternalSymbol(FnName, TLI.getPointerTy());
3444
3445   TargetLowering::ArgListTy Args;
3446   const Type *ArgTy = MVT::getTypeForValueType(Source.getValueType());
3447
3448   Args.push_back(std::make_pair(Source, ArgTy));
3449
3450   // We don't care about token chains for libcalls.  We just use the entry
3451   // node as our input and ignore the output chain.  This allows us to place
3452   // calls wherever we need them to satisfy data dependences.
3453   const Type *RetTy = MVT::getTypeForValueType(DestTy);
3454
3455   std::pair<SDOperand,SDOperand> CallResult =
3456     TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, true,
3457                     Callee, Args, DAG);
3458
3459   SpliceCallInto(CallResult.second, OutChain);
3460   return CallResult.first;
3461 }
3462
3463
3464
3465 /// ExpandOp - Expand the specified SDOperand into its two component pieces
3466 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
3467 /// LegalizeNodes map is filled in for any results that are not expanded, the
3468 /// ExpandedNodes map is filled in for any results that are expanded, and the
3469 /// Lo/Hi values are returned.
3470 void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
3471   MVT::ValueType VT = Op.getValueType();
3472   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
3473   SDNode *Node = Op.Val;
3474   assert(getTypeAction(VT) == Expand && "Not an expanded type!");
3475   assert((MVT::isInteger(VT) || VT == MVT::Vector) && 
3476          "Cannot expand FP values!");
3477   assert(((MVT::isInteger(NVT) && NVT < VT) || VT == MVT::Vector) &&
3478          "Cannot expand to FP value or to larger int value!");
3479
3480   // See if we already expanded it.
3481   std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
3482     = ExpandedNodes.find(Op);
3483   if (I != ExpandedNodes.end()) {
3484     Lo = I->second.first;
3485     Hi = I->second.second;
3486     return;
3487   }
3488
3489   // Expanding to multiple registers needs to perform an optimization step, and
3490   // is not careful to avoid operations the target does not support.  Make sure
3491   // that all generated operations are legalized in the next iteration.
3492   NeedsAnotherIteration = true;
3493
3494   switch (Node->getOpcode()) {
3495    case ISD::CopyFromReg:
3496       assert(0 && "CopyFromReg must be legal!");
3497    default:
3498     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
3499     assert(0 && "Do not know how to expand this operator!");
3500     abort();
3501   case ISD::UNDEF:
3502     Lo = DAG.getNode(ISD::UNDEF, NVT);
3503     Hi = DAG.getNode(ISD::UNDEF, NVT);
3504     break;
3505   case ISD::Constant: {
3506     uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
3507     Lo = DAG.getConstant(Cst, NVT);
3508     Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
3509     break;
3510   }
3511   case ISD::ConstantVec: {
3512     unsigned NumElements = Node->getNumOperands();
3513     // If we only have two elements left in the constant vector, just break it
3514     // apart into the two scalar constants it contains.  Otherwise, bisect the
3515     // ConstantVec, and return each half as a new ConstantVec.
3516     // FIXME: this is hard coded as big endian, it may have to change to support
3517     // SSE and Alpha MVI
3518     if (NumElements == 2) {
3519       Hi = Node->getOperand(0);
3520       Lo = Node->getOperand(1);
3521     } else {
3522       NumElements /= 2; 
3523       std::vector<SDOperand> LoOps, HiOps;
3524       for (unsigned I = 0, E = NumElements; I < E; ++I) {
3525         HiOps.push_back(Node->getOperand(I));
3526         LoOps.push_back(Node->getOperand(I+NumElements));
3527       }
3528       Lo = DAG.getNode(ISD::ConstantVec, MVT::Vector, LoOps);
3529       Hi = DAG.getNode(ISD::ConstantVec, MVT::Vector, HiOps);
3530     }
3531     break;
3532   }
3533
3534   case ISD::BUILD_PAIR:
3535     // Legalize both operands.  FIXME: in the future we should handle the case
3536     // where the two elements are not legal.
3537     assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
3538     Lo = LegalizeOp(Node->getOperand(0));
3539     Hi = LegalizeOp(Node->getOperand(1));
3540     break;
3541     
3542   case ISD::SIGN_EXTEND_INREG:
3543     ExpandOp(Node->getOperand(0), Lo, Hi);
3544     // Sign extend the lo-part.
3545     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
3546                      DAG.getConstant(MVT::getSizeInBits(NVT)-1,
3547                                      TLI.getShiftAmountTy()));
3548     // sext_inreg the low part if needed.
3549     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
3550     break;
3551
3552   case ISD::CTPOP:
3553     ExpandOp(Node->getOperand(0), Lo, Hi);
3554     Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
3555                      DAG.getNode(ISD::CTPOP, NVT, Lo),
3556                      DAG.getNode(ISD::CTPOP, NVT, Hi));
3557     Hi = DAG.getConstant(0, NVT);
3558     break;
3559
3560   case ISD::CTLZ: {
3561     // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
3562     ExpandOp(Node->getOperand(0), Lo, Hi);
3563     SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
3564     SDOperand HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
3565     SDOperand TopNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), HLZ, BitsC,
3566                                         ISD::SETNE);
3567     SDOperand LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
3568     LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
3569
3570     Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
3571     Hi = DAG.getConstant(0, NVT);
3572     break;
3573   }
3574
3575   case ISD::CTTZ: {
3576     // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
3577     ExpandOp(Node->getOperand(0), Lo, Hi);
3578     SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
3579     SDOperand LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
3580     SDOperand BotNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), LTZ, BitsC,
3581                                         ISD::SETNE);
3582     SDOperand HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
3583     HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
3584
3585     Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
3586     Hi = DAG.getConstant(0, NVT);
3587     break;
3588   }
3589
3590   case ISD::LOAD: {
3591     SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
3592     SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3593     Lo = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
3594
3595     // Increment the pointer to the other half.
3596     unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
3597     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
3598                       getIntPtrConstant(IncrementSize));
3599     //Is this safe?  declaring that the two parts of the split load
3600     //are from the same instruction?
3601     Hi = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
3602
3603     // Build a factor node to remember that this load is independent of the
3604     // other one.
3605     SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
3606                                Hi.getValue(1));
3607
3608     // Remember that we legalized the chain.
3609     AddLegalizedOperand(Op.getValue(1), TF);
3610     if (!TLI.isLittleEndian())
3611       std::swap(Lo, Hi);
3612     break;
3613   }
3614   case ISD::VLOAD: {
3615     SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
3616     SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3617     unsigned NumElements =cast<ConstantSDNode>(Node->getOperand(2))->getValue();
3618     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
3619     
3620     // If we only have two elements, turn into a pair of scalar loads.
3621     // FIXME: handle case where a vector of two elements is fine, such as
3622     //   2 x double on SSE2.
3623     if (NumElements == 2) {
3624       Lo = DAG.getLoad(EVT, Ch, Ptr, Node->getOperand(4));
3625       // Increment the pointer to the other half.
3626       unsigned IncrementSize = MVT::getSizeInBits(EVT)/8;
3627       Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
3628                         getIntPtrConstant(IncrementSize));
3629       //Is this safe?  declaring that the two parts of the split load
3630       //are from the same instruction?
3631       Hi = DAG.getLoad(EVT, Ch, Ptr, Node->getOperand(4));
3632     } else {
3633       NumElements /= 2; // Split the vector in half
3634       Lo = DAG.getVecLoad(NumElements, EVT, Ch, Ptr, Node->getOperand(4));
3635       unsigned IncrementSize = NumElements * MVT::getSizeInBits(EVT)/8;
3636       Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
3637                         getIntPtrConstant(IncrementSize));
3638       //Is this safe?  declaring that the two parts of the split load
3639       //are from the same instruction?
3640       Hi = DAG.getVecLoad(NumElements, EVT, Ch, Ptr, Node->getOperand(4));
3641     }
3642     
3643     // Build a factor node to remember that this load is independent of the
3644     // other one.
3645     SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
3646                                Hi.getValue(1));
3647     
3648     // Remember that we legalized the chain.
3649     AddLegalizedOperand(Op.getValue(1), TF);
3650     if (!TLI.isLittleEndian())
3651       std::swap(Lo, Hi);
3652     break;
3653   }
3654   case ISD::VADD:
3655   case ISD::VSUB:
3656   case ISD::VMUL: {
3657     unsigned NumElements =cast<ConstantSDNode>(Node->getOperand(2))->getValue();
3658     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
3659     SDOperand LL, LH, RL, RH;
3660     
3661     ExpandOp(Node->getOperand(0), LL, LH);
3662     ExpandOp(Node->getOperand(1), RL, RH);
3663
3664     // If we only have two elements, turn into a pair of scalar loads.
3665     // FIXME: handle case where a vector of two elements is fine, such as
3666     //   2 x double on SSE2.
3667     if (NumElements == 2) {
3668       unsigned Opc = getScalarizedOpcode(Node->getOpcode(), EVT);
3669       Lo = DAG.getNode(Opc, EVT, LL, RL);
3670       Hi = DAG.getNode(Opc, EVT, LH, RH);
3671     } else {
3672       Lo = DAG.getNode(Node->getOpcode(), MVT::Vector, LL, RL, LL.getOperand(2),
3673                        LL.getOperand(3));
3674       Hi = DAG.getNode(Node->getOpcode(), MVT::Vector, LH, RH, LH.getOperand(2),
3675                        LH.getOperand(3));
3676     }
3677     break;
3678   }
3679   case ISD::TAILCALL:
3680   case ISD::CALL: {
3681     SDOperand Chain  = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3682     SDOperand Callee = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
3683
3684     bool Changed = false;
3685     std::vector<SDOperand> Ops;
3686     for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
3687       Ops.push_back(LegalizeOp(Node->getOperand(i)));
3688       Changed |= Ops.back() != Node->getOperand(i);
3689     }
3690
3691     assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
3692            "Can only expand a call once so far, not i64 -> i16!");
3693
3694     std::vector<MVT::ValueType> RetTyVTs;
3695     RetTyVTs.reserve(3);
3696     RetTyVTs.push_back(NVT);
3697     RetTyVTs.push_back(NVT);
3698     RetTyVTs.push_back(MVT::Other);
3699     SDNode *NC = DAG.getCall(RetTyVTs, Chain, Callee, Ops,
3700                              Node->getOpcode() == ISD::TAILCALL);
3701     Lo = SDOperand(NC, 0);
3702     Hi = SDOperand(NC, 1);
3703
3704     // Insert the new chain mapping.
3705     AddLegalizedOperand(Op.getValue(1), Hi.getValue(2));
3706     break;
3707   }
3708   case ISD::AND:
3709   case ISD::OR:
3710   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
3711     SDOperand LL, LH, RL, RH;
3712     ExpandOp(Node->getOperand(0), LL, LH);
3713     ExpandOp(Node->getOperand(1), RL, RH);
3714     Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
3715     Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
3716     break;
3717   }
3718   case ISD::SELECT: {
3719     SDOperand C, LL, LH, RL, RH;
3720
3721     switch (getTypeAction(Node->getOperand(0).getValueType())) {
3722     case Expand: assert(0 && "It's impossible to expand bools");
3723     case Legal:
3724       C = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
3725       break;
3726     case Promote:
3727       C = PromoteOp(Node->getOperand(0));  // Promote the condition.
3728       break;
3729     }
3730     ExpandOp(Node->getOperand(1), LL, LH);
3731     ExpandOp(Node->getOperand(2), RL, RH);
3732     Lo = DAG.getNode(ISD::SELECT, NVT, C, LL, RL);
3733     Hi = DAG.getNode(ISD::SELECT, NVT, C, LH, RH);
3734     break;
3735   }
3736   case ISD::SELECT_CC: {
3737     SDOperand TL, TH, FL, FH;
3738     ExpandOp(Node->getOperand(2), TL, TH);
3739     ExpandOp(Node->getOperand(3), FL, FH);
3740     Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
3741                      Node->getOperand(1), TL, FL, Node->getOperand(4));
3742     Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
3743                      Node->getOperand(1), TH, FH, Node->getOperand(4));
3744     Lo = LegalizeOp(Lo);
3745     Hi = LegalizeOp(Hi);
3746     break;
3747   }
3748   case ISD::SEXTLOAD: {
3749     SDOperand Chain = LegalizeOp(Node->getOperand(0));
3750     SDOperand Ptr   = LegalizeOp(Node->getOperand(1));
3751     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
3752     
3753     if (EVT == NVT)
3754       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
3755     else
3756       Lo = DAG.getExtLoad(ISD::SEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
3757                           EVT);
3758     
3759     // Remember that we legalized the chain.
3760     AddLegalizedOperand(SDOperand(Node, 1), Lo.getValue(1));
3761     
3762     // The high part is obtained by SRA'ing all but one of the bits of the lo
3763     // part.
3764     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
3765     Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
3766                                                        TLI.getShiftAmountTy()));
3767     Lo = LegalizeOp(Lo);
3768     Hi = LegalizeOp(Hi);
3769     break;
3770   }
3771   case ISD::ZEXTLOAD: {
3772     SDOperand Chain = LegalizeOp(Node->getOperand(0));
3773     SDOperand Ptr   = LegalizeOp(Node->getOperand(1));
3774     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
3775     
3776     if (EVT == NVT)
3777       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
3778     else
3779       Lo = DAG.getExtLoad(ISD::ZEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
3780                           EVT);
3781     
3782     // Remember that we legalized the chain.
3783     AddLegalizedOperand(SDOperand(Node, 1), Lo.getValue(1));
3784
3785     // The high part is just a zero.
3786     Hi = LegalizeOp(DAG.getConstant(0, NVT));
3787     Lo = LegalizeOp(Lo);
3788     break;
3789   }
3790   case ISD::EXTLOAD: {
3791     SDOperand Chain = LegalizeOp(Node->getOperand(0));
3792     SDOperand Ptr   = LegalizeOp(Node->getOperand(1));
3793     MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
3794     
3795     if (EVT == NVT)
3796       Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
3797     else
3798       Lo = DAG.getExtLoad(ISD::EXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
3799                           EVT);
3800     
3801     // Remember that we legalized the chain.
3802     AddLegalizedOperand(SDOperand(Node, 1), Lo.getValue(1));
3803     
3804     // The high part is undefined.
3805     Hi = LegalizeOp(DAG.getNode(ISD::UNDEF, NVT));
3806     Lo = LegalizeOp(Lo);
3807     break;
3808   }
3809   case ISD::ANY_EXTEND: {
3810     SDOperand In;
3811     switch (getTypeAction(Node->getOperand(0).getValueType())) {
3812     case Expand: assert(0 && "expand-expand not implemented yet!");
3813     case Legal: In = LegalizeOp(Node->getOperand(0)); break;
3814     case Promote:
3815       In = PromoteOp(Node->getOperand(0));
3816       break;
3817     }
3818     
3819     // The low part is any extension of the input (which degenerates to a copy).
3820     Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, In);
3821     // The high part is undefined.
3822     Hi = DAG.getNode(ISD::UNDEF, NVT);
3823     break;
3824   }
3825   case ISD::SIGN_EXTEND: {
3826     SDOperand In;
3827     switch (getTypeAction(Node->getOperand(0).getValueType())) {
3828     case Expand: assert(0 && "expand-expand not implemented yet!");
3829     case Legal: In = LegalizeOp(Node->getOperand(0)); break;
3830     case Promote:
3831       In = PromoteOp(Node->getOperand(0));
3832       // Emit the appropriate sign_extend_inreg to get the value we want.
3833       In = DAG.getNode(ISD::SIGN_EXTEND_INREG, In.getValueType(), In,
3834                        DAG.getValueType(Node->getOperand(0).getValueType()));
3835       break;
3836     }
3837
3838     // The low part is just a sign extension of the input (which degenerates to
3839     // a copy).
3840     Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, In);
3841
3842     // The high part is obtained by SRA'ing all but one of the bits of the lo
3843     // part.
3844     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
3845     Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
3846                                                        TLI.getShiftAmountTy()));
3847     break;
3848   }
3849   case ISD::ZERO_EXTEND: {
3850     SDOperand In;
3851     switch (getTypeAction(Node->getOperand(0).getValueType())) {
3852     case Expand: assert(0 && "expand-expand not implemented yet!");
3853     case Legal: In = LegalizeOp(Node->getOperand(0)); break;
3854     case Promote:
3855       In = PromoteOp(Node->getOperand(0));
3856       // Emit the appropriate zero_extend_inreg to get the value we want.
3857       In = DAG.getZeroExtendInReg(In, Node->getOperand(0).getValueType());
3858       break;
3859     }
3860
3861     // The low part is just a zero extension of the input (which degenerates to
3862     // a copy).
3863     Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, In);
3864
3865     // The high part is just a zero.
3866     Hi = DAG.getConstant(0, NVT);
3867     break;
3868   }
3869     
3870   case ISD::BIT_CONVERT: {
3871     SDOperand Tmp = ExpandBIT_CONVERT(Node->getValueType(0), 
3872                                       Node->getOperand(0));
3873     ExpandOp(Tmp, Lo, Hi);
3874     break;
3875   }
3876
3877   case ISD::READCYCLECOUNTER: {
3878     assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) == 
3879                  TargetLowering::Custom &&
3880            "Must custom expand ReadCycleCounter");
3881     SDOperand T = TLI.LowerOperation(Op, DAG);
3882     assert(T.Val && "Node must be custom expanded!");
3883     Lo = LegalizeOp(T.getValue(0));
3884     Hi = LegalizeOp(T.getValue(1));
3885     AddLegalizedOperand(SDOperand(Node, 1), // Remember we legalized the chain.
3886                         LegalizeOp(T.getValue(2)));
3887     break;
3888   }
3889
3890     // These operators cannot be expanded directly, emit them as calls to
3891     // library functions.
3892   case ISD::FP_TO_SINT:
3893     if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
3894       SDOperand Op;
3895       switch (getTypeAction(Node->getOperand(0).getValueType())) {
3896       case Expand: assert(0 && "cannot expand FP!");
3897       case Legal: Op = LegalizeOp(Node->getOperand(0)); break;
3898       case Promote: Op = PromoteOp(Node->getOperand(0)); break;
3899       }
3900
3901       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
3902
3903       // Now that the custom expander is done, expand the result, which is still
3904       // VT.
3905       if (Op.Val) {
3906         ExpandOp(Op, Lo, Hi);
3907         break;
3908       }
3909     }
3910
3911     if (Node->getOperand(0).getValueType() == MVT::f32)
3912       Lo = ExpandLibCall("__fixsfdi", Node, Hi);
3913     else
3914       Lo = ExpandLibCall("__fixdfdi", Node, Hi);
3915     break;
3916
3917   case ISD::FP_TO_UINT:
3918     if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
3919       SDOperand Op = DAG.getNode(ISD::FP_TO_UINT, VT,
3920                                  LegalizeOp(Node->getOperand(0)));
3921       // Now that the custom expander is done, expand the result, which is still
3922       // VT.
3923       Op = TLI.LowerOperation(Op, DAG);
3924       if (Op.Val) {
3925         ExpandOp(Op, Lo, Hi);
3926         break;
3927       }
3928     }
3929
3930     if (Node->getOperand(0).getValueType() == MVT::f32)
3931       Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
3932     else
3933       Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
3934     break;
3935
3936   case ISD::SHL: {
3937     // If the target wants custom lowering, do so.
3938     if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
3939       SDOperand Op = DAG.getNode(ISD::SHL, VT, Node->getOperand(0),
3940                                  LegalizeOp(Node->getOperand(1)));
3941       Op = TLI.LowerOperation(Op, DAG);
3942       if (Op.Val) {
3943         // Now that the custom expander is done, expand the result, which is
3944         // still VT.
3945         ExpandOp(Op, Lo, Hi);
3946         break;
3947       }
3948     }
3949     
3950     // If we can emit an efficient shift operation, do so now.
3951     if (ExpandShift(ISD::SHL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
3952       break;
3953
3954     // If this target supports SHL_PARTS, use it.
3955     TargetLowering::LegalizeAction Action =
3956       TLI.getOperationAction(ISD::SHL_PARTS, NVT);
3957     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
3958         Action == TargetLowering::Custom) {
3959       ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), Node->getOperand(1),
3960                        Lo, Hi);
3961       break;
3962     }
3963
3964     // Otherwise, emit a libcall.
3965     Lo = ExpandLibCall("__ashldi3", Node, Hi);
3966     break;
3967   }
3968
3969   case ISD::SRA: {
3970     // If the target wants custom lowering, do so.
3971     if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
3972       SDOperand Op = DAG.getNode(ISD::SRA, VT, Node->getOperand(0),
3973                                  LegalizeOp(Node->getOperand(1)));
3974       Op = TLI.LowerOperation(Op, DAG);
3975       if (Op.Val) {
3976         // Now that the custom expander is done, expand the result, which is
3977         // still VT.
3978         ExpandOp(Op, Lo, Hi);
3979         break;
3980       }
3981     }
3982     
3983     // If we can emit an efficient shift operation, do so now.
3984     if (ExpandShift(ISD::SRA, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
3985       break;
3986
3987     // If this target supports SRA_PARTS, use it.
3988     TargetLowering::LegalizeAction Action =
3989       TLI.getOperationAction(ISD::SRA_PARTS, NVT);
3990     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
3991         Action == TargetLowering::Custom) {
3992       ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), Node->getOperand(1),
3993                        Lo, Hi);
3994       break;
3995     }
3996
3997     // Otherwise, emit a libcall.
3998     Lo = ExpandLibCall("__ashrdi3", Node, Hi);
3999     break;
4000   }
4001
4002   case ISD::SRL: {
4003     // If the target wants custom lowering, do so.
4004     if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
4005       SDOperand Op = DAG.getNode(ISD::SRL, VT, Node->getOperand(0),
4006                                  LegalizeOp(Node->getOperand(1)));
4007       Op = TLI.LowerOperation(Op, DAG);
4008       if (Op.Val) {
4009         // Now that the custom expander is done, expand the result, which is
4010         // still VT.
4011         ExpandOp(Op, Lo, Hi);
4012         break;
4013       }
4014     }
4015
4016     // If we can emit an efficient shift operation, do so now.
4017     if (ExpandShift(ISD::SRL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
4018       break;
4019
4020     // If this target supports SRL_PARTS, use it.
4021     TargetLowering::LegalizeAction Action =
4022       TLI.getOperationAction(ISD::SRL_PARTS, NVT);
4023     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4024         Action == TargetLowering::Custom) {
4025       ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), Node->getOperand(1),
4026                        Lo, Hi);
4027       break;
4028     }
4029
4030     // Otherwise, emit a libcall.
4031     Lo = ExpandLibCall("__lshrdi3", Node, Hi);
4032     break;
4033   }
4034
4035   case ISD::ADD:
4036     ExpandByParts(ISD::ADD_PARTS, Node->getOperand(0), Node->getOperand(1),
4037                   Lo, Hi);
4038     break;
4039   case ISD::SUB:
4040     ExpandByParts(ISD::SUB_PARTS, Node->getOperand(0), Node->getOperand(1),
4041                   Lo, Hi);
4042     break;
4043   case ISD::MUL: {
4044     if (TLI.isOperationLegal(ISD::MULHU, NVT)) {
4045       SDOperand LL, LH, RL, RH;
4046       ExpandOp(Node->getOperand(0), LL, LH);
4047       ExpandOp(Node->getOperand(1), RL, RH);
4048       unsigned SH = MVT::getSizeInBits(RH.getValueType())-1;
4049       // MULHS implicitly sign extends its inputs.  Check to see if ExpandOp
4050       // extended the sign bit of the low half through the upper half, and if so
4051       // emit a MULHS instead of the alternate sequence that is valid for any
4052       // i64 x i64 multiply.
4053       if (TLI.isOperationLegal(ISD::MULHS, NVT) &&
4054           // is RH an extension of the sign bit of RL?
4055           RH.getOpcode() == ISD::SRA && RH.getOperand(0) == RL &&
4056           RH.getOperand(1).getOpcode() == ISD::Constant &&
4057           cast<ConstantSDNode>(RH.getOperand(1))->getValue() == SH &&
4058           // is LH an extension of the sign bit of LL?
4059           LH.getOpcode() == ISD::SRA && LH.getOperand(0) == LL &&
4060           LH.getOperand(1).getOpcode() == ISD::Constant &&
4061           cast<ConstantSDNode>(LH.getOperand(1))->getValue() == SH) {
4062         Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
4063       } else {
4064         Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
4065         RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
4066         LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
4067         Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
4068         Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
4069       }
4070       Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
4071     } else {
4072       Lo = ExpandLibCall("__muldi3" , Node, Hi); break;
4073     }
4074     break;
4075   }
4076   case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
4077   case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
4078   case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
4079   case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
4080   }
4081
4082   // Make sure the resultant values have been legalized themselves, unless this
4083   // is a type that requires multi-step expansion.
4084   if (getTypeAction(NVT) != Expand && NVT != MVT::isVoid) {
4085     Lo = LegalizeOp(Lo);
4086     Hi = LegalizeOp(Hi);
4087   }
4088
4089   // Remember in a map if the values will be reused later.
4090   bool isNew =
4091     ExpandedNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
4092   assert(isNew && "Value already expanded?!?");
4093 }
4094
4095
4096 // SelectionDAG::Legalize - This is the entry point for the file.
4097 //
4098 void SelectionDAG::Legalize() {
4099   /// run - This is the main entry point to this class.
4100   ///
4101   SelectionDAGLegalize(*this).Run();
4102 }
4103