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