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