Fix some serious bugs in promotion.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeDAG.cpp
1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SelectionDAG::Legalize method.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/CodeGen/MachineConstantPool.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/Target/TargetLowering.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Target/TargetOptions.h"
21 #include "llvm/Constants.h"
22 #include <iostream>
23 using namespace llvm;
24
25 //===----------------------------------------------------------------------===//
26 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
27 /// hacks on it until the target machine can handle it.  This involves
28 /// eliminating value sizes the machine cannot handle (promoting small sizes to
29 /// large sizes or splitting up large values into small values) as well as
30 /// eliminating operations the machine cannot handle.
31 ///
32 /// This code also does a small amount of optimization and recognition of idioms
33 /// as part of its processing.  For example, if a target does not support a
34 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
35 /// will attempt merge setcc and brc instructions into brcc's.
36 ///
37 namespace {
38 class SelectionDAGLegalize {
39   TargetLowering &TLI;
40   SelectionDAG &DAG;
41
42   /// LegalizeAction - This enum indicates what action we should take for each
43   /// value type the can occur in the program.
44   enum LegalizeAction {
45     Legal,            // The target natively supports this value type.
46     Promote,          // This should be promoted to the next larger type.
47     Expand,           // This integer type should be broken into smaller pieces.
48   };
49
50   /// TransformToType - For any value types we are promoting or expanding, this
51   /// contains the value type that we are changing to.  For Expanded types, this
52   /// contains one step of the expand (e.g. i64 -> i32), even if there are
53   /// multiple steps required (e.g. i64 -> i16)
54   MVT::ValueType TransformToType[MVT::LAST_VALUETYPE];
55
56   /// ValueTypeActions - This is a bitvector that contains two bits for each
57   /// value type, where the two bits correspond to the LegalizeAction enum.
58   /// This can be queried with "getTypeAction(VT)".
59   unsigned ValueTypeActions;
60
61   /// NeedsAnotherIteration - This is set when we expand a large integer
62   /// operation into smaller integer operations, but the smaller operations are
63   /// not set.  This occurs only rarely in practice, for targets that don't have
64   /// 32-bit or larger integer registers.
65   bool NeedsAnotherIteration;
66
67   /// LegalizedNodes - For nodes that are of legal width, and that have more
68   /// than one use, this map indicates what regularized operand to use.  This
69   /// allows us to avoid legalizing the same thing more than once.
70   std::map<SDOperand, SDOperand> LegalizedNodes;
71
72   /// PromotedNodes - For nodes that are below legal width, and that have more
73   /// than one use, this map indicates what promoted value to use.  This allows
74   /// us to avoid promoting the same thing more than once.
75   std::map<SDOperand, SDOperand> PromotedNodes;
76
77   /// ExpandedNodes - For nodes that need to be expanded, and which have more
78   /// than one use, this map indicates which which operands are the expanded
79   /// version of the input.  This allows us to avoid expanding the same node
80   /// more than once.
81   std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
82
83   void AddLegalizedOperand(SDOperand From, SDOperand To) {
84     bool isNew = LegalizedNodes.insert(std::make_pair(From, To)).second;
85     assert(isNew && "Got into the map somehow?");
86   }
87   void AddPromotedOperand(SDOperand From, SDOperand To) {
88     bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
89     assert(isNew && "Got into the map somehow?");
90   }
91
92   /// setValueTypeAction - Set the action for a particular value type.  This
93   /// assumes an action has not already been set for this value type.
94   void setValueTypeAction(MVT::ValueType VT, LegalizeAction A) {
95     ValueTypeActions |= A << (VT*2);
96     if (A == Promote) {
97       MVT::ValueType PromoteTo;
98       if (VT == MVT::f32)
99         PromoteTo = MVT::f64;
100       else {
101         unsigned LargerReg = VT+1;
102         while (!TLI.hasNativeSupportFor((MVT::ValueType)LargerReg)) {
103           ++LargerReg;
104           assert(MVT::isInteger((MVT::ValueType)LargerReg) &&
105                  "Nothing to promote to??");
106         }
107         PromoteTo = (MVT::ValueType)LargerReg;
108       }
109
110       assert(MVT::isInteger(VT) == MVT::isInteger(PromoteTo) &&
111              MVT::isFloatingPoint(VT) == MVT::isFloatingPoint(PromoteTo) &&
112              "Can only promote from int->int or fp->fp!");
113       assert(VT < PromoteTo && "Must promote to a larger type!");
114       TransformToType[VT] = PromoteTo;
115     } else if (A == Expand) {
116       assert(MVT::isInteger(VT) && VT > MVT::i8 &&
117              "Cannot expand this type: target must support SOME integer reg!");
118       // Expand to the next smaller integer type!
119       TransformToType[VT] = (MVT::ValueType)(VT-1);
120     }
121   }
122
123 public:
124
125   SelectionDAGLegalize(TargetLowering &TLI, SelectionDAG &DAG);
126
127   /// Run - While there is still lowering to do, perform a pass over the DAG.
128   /// Most regularization can be done in a single pass, but targets that require
129   /// large values to be split into registers multiple times (e.g. i64 -> 4x
130   /// i16) require iteration for these values (the first iteration will demote
131   /// to i32, the second will demote to i16).
132   void Run() {
133     do {
134       NeedsAnotherIteration = false;
135       LegalizeDAG();
136     } while (NeedsAnotherIteration);
137   }
138
139   /// getTypeAction - Return how we should legalize values of this type, either
140   /// it is already legal or we need to expand it into multiple registers of
141   /// smaller integer type, or we need to promote it to a larger type.
142   LegalizeAction getTypeAction(MVT::ValueType VT) const {
143     return (LegalizeAction)((ValueTypeActions >> (2*VT)) & 3);
144   }
145
146   /// isTypeLegal - Return true if this type is legal on this target.
147   ///
148   bool isTypeLegal(MVT::ValueType VT) const {
149     return getTypeAction(VT) == Legal;
150   }
151
152 private:
153   void LegalizeDAG();
154
155   SDOperand LegalizeOp(SDOperand O);
156   void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
157   SDOperand PromoteOp(SDOperand O);
158
159   SDOperand getIntPtrConstant(uint64_t Val) {
160     return DAG.getConstant(Val, TLI.getPointerTy());
161   }
162 };
163 }
164
165
166 SelectionDAGLegalize::SelectionDAGLegalize(TargetLowering &tli,
167                                            SelectionDAG &dag)
168   : TLI(tli), DAG(dag), ValueTypeActions(0) {
169
170   assert(MVT::LAST_VALUETYPE <= 16 &&
171          "Too many value types for ValueTypeActions to hold!");
172   
173   // Inspect all of the ValueType's possible, deciding how to process them.
174   for (unsigned IntReg = MVT::i1; IntReg <= MVT::i128; ++IntReg)
175     // If TLI says we are expanding this type, expand it!
176     if (TLI.getNumElements((MVT::ValueType)IntReg) != 1)
177       setValueTypeAction((MVT::ValueType)IntReg, Expand);
178     else if (!TLI.hasNativeSupportFor((MVT::ValueType)IntReg))
179       // Otherwise, if we don't have native support, we must promote to a
180       // larger type.
181       setValueTypeAction((MVT::ValueType)IntReg, Promote);
182   
183   // If the target does not have native support for F32, promote it to F64.
184   if (!TLI.hasNativeSupportFor(MVT::f32))
185     setValueTypeAction(MVT::f32, Promote);
186 }
187
188 void SelectionDAGLegalize::LegalizeDAG() {
189   SDOperand OldRoot = DAG.getRoot();
190   SDOperand NewRoot = LegalizeOp(OldRoot);
191   DAG.setRoot(NewRoot);
192
193   ExpandedNodes.clear();
194   LegalizedNodes.clear();
195
196   // Remove dead nodes now.
197   DAG.RemoveDeadNodes(OldRoot.Val);
198 }
199
200 SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
201   assert(getTypeAction(Op.getValueType()) == Legal &&
202          "Caller should expand or promote operands that are not legal!");
203
204   // If this operation defines any values that cannot be represented in a
205   // register on this target, make sure to expand or promote them.
206   if (Op.Val->getNumValues() > 1) {
207     for (unsigned i = 0, e = Op.Val->getNumValues(); i != e; ++i)
208       switch (getTypeAction(Op.Val->getValueType(i))) {
209       case Legal: break;  // Nothing to do.
210       case Expand: {
211         SDOperand T1, T2;
212         ExpandOp(Op.getValue(i), T1, T2);
213         assert(LegalizedNodes.count(Op) &&
214                "Expansion didn't add legal operands!");
215         return LegalizedNodes[Op];
216       }
217       case Promote:
218         PromoteOp(Op.getValue(i));
219         assert(LegalizedNodes.count(Op) &&
220                "Expansion didn't add legal operands!");
221         return LegalizedNodes[Op];
222       }
223   }
224
225   std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
226   if (I != LegalizedNodes.end()) return I->second;
227
228   SDOperand Tmp1, Tmp2, Tmp3;
229
230   SDOperand Result = Op;
231   SDNode *Node = Op.Val;
232
233   switch (Node->getOpcode()) {
234   default:
235     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
236     assert(0 && "Do not know how to legalize this operator!");
237     abort();
238   case ISD::EntryToken:
239   case ISD::FrameIndex:
240   case ISD::GlobalAddress:
241   case ISD::ExternalSymbol:
242   case ISD::ConstantPool:           // Nothing to do.
243     assert(getTypeAction(Node->getValueType(0)) == Legal &&
244            "This must be legal!");
245     break;
246   case ISD::CopyFromReg:
247     Tmp1 = LegalizeOp(Node->getOperand(0));
248     if (Tmp1 != Node->getOperand(0))
249       Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(),
250                                   Node->getValueType(0), Tmp1);
251     break;
252   case ISD::ImplicitDef:
253     Tmp1 = LegalizeOp(Node->getOperand(0));
254     if (Tmp1 != Node->getOperand(0))
255       Result = DAG.getImplicitDef(Tmp1, cast<RegSDNode>(Node)->getReg());
256     break;
257   case ISD::Constant:
258     // We know we don't need to expand constants here, constants only have one
259     // value and we check that it is fine above.
260
261     // FIXME: Maybe we should handle things like targets that don't support full
262     // 32-bit immediates?
263     break;
264   case ISD::ConstantFP: {
265     // Spill FP immediates to the constant pool if the target cannot directly
266     // codegen them.  Targets often have some immediate values that can be
267     // efficiently generated into an FP register without a load.  We explicitly
268     // leave these constants as ConstantFP nodes for the target to deal with.
269
270     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
271
272     // Check to see if this FP immediate is already legal.
273     bool isLegal = false;
274     for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
275            E = TLI.legal_fpimm_end(); I != E; ++I)
276       if (CFP->isExactlyValue(*I)) {
277         isLegal = true;
278         break;
279       }
280
281     if (!isLegal) {
282       // Otherwise we need to spill the constant to memory.
283       MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
284
285       bool Extend = false;
286
287       // If a FP immediate is precise when represented as a float, we put it
288       // into the constant pool as a float, even if it's is statically typed
289       // as a double.
290       MVT::ValueType VT = CFP->getValueType(0);
291       bool isDouble = VT == MVT::f64;
292       ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
293                                              Type::FloatTy, CFP->getValue());
294       if (isDouble && CFP->isExactlyValue((float)CFP->getValue())) {
295         LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
296         VT = MVT::f32;
297         Extend = true;
298       }
299       
300       SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(LLVMC),
301                                             TLI.getPointerTy());
302       Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx);
303       
304       if (Extend) Result = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Result);
305     }
306     break;
307   }
308   case ISD::TokenFactor: {
309     std::vector<SDOperand> Ops;
310     bool Changed = false;
311     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
312       Ops.push_back(LegalizeOp(Node->getOperand(i)));  // Legalize the operands
313       Changed |= Ops[i] != Node->getOperand(i);
314     }
315     if (Changed)
316       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
317     break;
318   }
319
320   case ISD::ADJCALLSTACKDOWN:
321   case ISD::ADJCALLSTACKUP:
322     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
323     // There is no need to legalize the size argument (Operand #1)
324     if (Tmp1 != Node->getOperand(0))
325       Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1,
326                            Node->getOperand(1));
327     break;
328   case ISD::DYNAMIC_STACKALLOC:
329     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
330     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
331     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
332     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
333         Tmp3 != Node->getOperand(2))
334       Result = DAG.getNode(ISD::DYNAMIC_STACKALLOC, Node->getValueType(0),
335                            Tmp1, Tmp2, Tmp3);
336     else
337       Result = Op.getValue(0);
338
339     // Since this op produces two values, make sure to remember that we
340     // legalized both of them.
341     AddLegalizedOperand(SDOperand(Node, 0), Result);
342     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
343     return Result.getValue(Op.ResNo);
344
345   case ISD::CALL:
346     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
347     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
348     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
349       std::vector<MVT::ValueType> RetTyVTs;
350       RetTyVTs.reserve(Node->getNumValues());
351       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
352         RetTyVTs.push_back(Node->getValueType(i));
353       Result = SDOperand(DAG.getCall(RetTyVTs, Tmp1, Tmp2), 0);
354     } else {
355       Result = Result.getValue(0);
356     }
357     // Since calls produce multiple values, make sure to remember that we
358     // legalized all of them.
359     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
360       AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
361     return Result.getValue(Op.ResNo);
362
363   case ISD::BR:
364     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
365     if (Tmp1 != Node->getOperand(0))
366       Result = DAG.getNode(ISD::BR, MVT::Other, Tmp1, Node->getOperand(1));
367     break;
368
369   case ISD::BRCOND:
370     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
371     // FIXME: booleans might not be legal!
372     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the condition.
373     // Basic block destination (Op#2) is always legal.
374     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
375       Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
376                            Node->getOperand(2));
377     break;
378
379   case ISD::LOAD:
380     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
381     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
382     if (Tmp1 != Node->getOperand(0) ||
383         Tmp2 != Node->getOperand(1))
384       Result = DAG.getLoad(Node->getValueType(0), Tmp1, Tmp2);
385     else
386       Result = SDOperand(Node, 0);
387     
388     // Since loads produce two values, make sure to remember that we legalized
389     // both of them.
390     AddLegalizedOperand(SDOperand(Node, 0), Result);
391     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
392     return Result.getValue(Op.ResNo);
393
394   case ISD::EXTLOAD:
395   case ISD::SEXTLOAD:
396   case ISD::ZEXTLOAD:
397     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
398     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
399     if (Tmp1 != Node->getOperand(0) ||
400         Tmp2 != Node->getOperand(1))
401       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1, Tmp2,
402                            cast<MVTSDNode>(Node)->getExtraValueType());
403     else
404       Result = SDOperand(Node, 0);
405     
406     // Since loads produce two values, make sure to remember that we legalized
407     // both of them.
408     AddLegalizedOperand(SDOperand(Node, 0), Result);
409     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
410     return Result.getValue(Op.ResNo);
411
412   case ISD::EXTRACT_ELEMENT:
413     // Get both the low and high parts.
414     ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
415     if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
416       Result = Tmp2;  // 1 -> Hi
417     else
418       Result = Tmp1;  // 0 -> Lo
419     break;
420
421   case ISD::CopyToReg:
422     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
423     
424     switch (getTypeAction(Node->getOperand(1).getValueType())) {
425     case Legal:
426       // Legalize the incoming value (must be legal).
427       Tmp2 = LegalizeOp(Node->getOperand(1));
428       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
429         Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
430       break;
431     case Expand: {
432       SDOperand Lo, Hi;
433       ExpandOp(Node->getOperand(1), Lo, Hi);      
434       unsigned Reg = cast<RegSDNode>(Node)->getReg();
435       Result = DAG.getCopyToReg(Tmp1, Lo, Reg);
436       Result = DAG.getCopyToReg(Result, Hi, Reg+1);
437       assert(isTypeLegal(Result.getValueType()) &&
438              "Cannot expand multiple times yet (i64 -> i16)");
439       break;
440     }
441     case Promote:
442       assert(0 && "Don't know what it means to promote this!");
443       abort();
444     }
445     break;
446
447   case ISD::RET:
448     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
449     switch (Node->getNumOperands()) {
450     case 2:  // ret val
451       switch (getTypeAction(Node->getOperand(1).getValueType())) {
452       case Legal:
453         Tmp2 = LegalizeOp(Node->getOperand(1));
454         if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
455           Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
456         break;
457       case Expand: {
458         SDOperand Lo, Hi;
459         ExpandOp(Node->getOperand(1), Lo, Hi);
460         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
461         break;                             
462       }
463       case Promote:
464         Tmp2 = PromoteOp(Node->getOperand(1));
465         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
466         break;
467       }
468       break;
469     case 1:  // ret void
470       if (Tmp1 != Node->getOperand(0))
471         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1);
472       break;
473     default: { // ret <values>
474       std::vector<SDOperand> NewValues;
475       NewValues.push_back(Tmp1);
476       for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
477         switch (getTypeAction(Node->getOperand(i).getValueType())) {
478         case Legal:
479           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
480           break;
481         case Expand: {
482           SDOperand Lo, Hi;
483           ExpandOp(Node->getOperand(i), Lo, Hi);
484           NewValues.push_back(Lo);
485           NewValues.push_back(Hi);
486           break;                             
487         }
488         case Promote:
489           assert(0 && "Can't promote multiple return value yet!");
490         }
491       Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
492       break;
493     }
494     }
495     break;
496   case ISD::STORE:
497     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
498     Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
499
500     // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
501     if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
502       if (CFP->getValueType(0) == MVT::f32) {
503         union {
504           unsigned I;
505           float    F;
506         } V;
507         V.F = CFP->getValue();
508         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
509                              DAG.getConstant(V.I, MVT::i32), Tmp2);
510       } else {
511         assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
512         union {
513           uint64_t I;
514           double   F;
515         } V;
516         V.F = CFP->getValue();
517         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
518                              DAG.getConstant(V.I, MVT::i64), Tmp2);
519       }
520       Op = Result;
521       Node = Op.Val;
522     }
523
524     switch (getTypeAction(Node->getOperand(1).getValueType())) {
525     case Legal: {
526       SDOperand Val = LegalizeOp(Node->getOperand(1));
527       if (Val != Node->getOperand(1) || Tmp1 != Node->getOperand(0) ||
528           Tmp2 != Node->getOperand(2))
529         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Val, Tmp2);
530       break;
531     }
532     case Promote:
533       // Truncate the value and store the result.
534       Tmp3 = PromoteOp(Node->getOperand(1));
535       Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
536                            Node->getOperand(1).getValueType());
537       break;
538
539     case Expand:
540       SDOperand Lo, Hi;
541       ExpandOp(Node->getOperand(1), Lo, Hi);
542
543       if (!TLI.isLittleEndian())
544         std::swap(Lo, Hi);
545
546       // FIXME: These two stores are independent of each other!
547       Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2);
548
549       unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
550       Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
551                          getIntPtrConstant(IncrementSize));
552       assert(isTypeLegal(Tmp2.getValueType()) &&
553              "Pointers must be legal!");
554       Result = DAG.getNode(ISD::STORE, MVT::Other, Result, Hi, Tmp2);
555     }
556     break;
557   case ISD::TRUNCSTORE:
558     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
559     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
560
561     switch (getTypeAction(Node->getOperand(1).getValueType())) {
562     case Legal:
563       Tmp2 = LegalizeOp(Node->getOperand(1));
564       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
565           Tmp3 != Node->getOperand(2))
566         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
567                              cast<MVTSDNode>(Node)->getExtraValueType());
568       break;
569     case Promote:
570     case Expand:
571       assert(0 && "Cannot handle illegal TRUNCSTORE yet!");
572     }
573     break;
574   case ISD::SELECT:
575     // FIXME: BOOLS MAY REQUIRE PROMOTION!
576     Tmp1 = LegalizeOp(Node->getOperand(0));   // Cond
577     Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
578     Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
579     
580     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
581         Tmp3 != Node->getOperand(2))
582       Result = DAG.getNode(ISD::SELECT, Node->getValueType(0), Tmp1, Tmp2,Tmp3);
583     break;
584   case ISD::SETCC:
585     switch (getTypeAction(Node->getOperand(0).getValueType())) {
586     case Legal:
587       Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
588       Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
589       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
590         Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
591                               Tmp1, Tmp2);
592       break;
593     case Promote:
594       Tmp1 = PromoteOp(Node->getOperand(0));   // LHS
595       Tmp2 = PromoteOp(Node->getOperand(1));   // RHS
596
597       // If this is an FP compare, the operands have already been extended.
598       if (MVT::isInteger(Node->getOperand(0).getValueType())) {
599         MVT::ValueType VT = Node->getOperand(0).getValueType();
600         MVT::ValueType NVT = TransformToType[VT];
601
602         // Otherwise, we have to insert explicit sign or zero extends.  Note
603         // that we could insert sign extends for ALL conditions, but zero extend
604         // is cheaper on many machines (an AND instead of two shifts), so prefer
605         // it.
606         switch (cast<SetCCSDNode>(Node)->getCondition()) {
607         default: assert(0 && "Unknown integer comparison!");
608         case ISD::SETEQ:
609         case ISD::SETNE:
610         case ISD::SETUGE:
611         case ISD::SETUGT:
612         case ISD::SETULE:
613         case ISD::SETULT:
614           // ALL of these operations will work if we either sign or zero extend
615           // the operands (including the unsigned comparisons!).  Zero extend is
616           // usually a simpler/cheaper operation, so prefer it.
617           Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
618           Tmp2 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp2, VT);
619           break;
620         case ISD::SETGE:
621         case ISD::SETGT:
622         case ISD::SETLT:
623         case ISD::SETLE:
624           Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
625           Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2, VT);
626           break;
627         }
628
629       }
630       Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
631                             Tmp1, Tmp2);
632       break;
633     case Expand: 
634       SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
635       ExpandOp(Node->getOperand(0), LHSLo, LHSHi);
636       ExpandOp(Node->getOperand(1), RHSLo, RHSHi);
637       switch (cast<SetCCSDNode>(Node)->getCondition()) {
638       case ISD::SETEQ:
639       case ISD::SETNE:
640         Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
641         Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
642         Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
643         Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(), Tmp1,
644                               DAG.getConstant(0, Tmp1.getValueType()));
645         break;
646       default:
647         // FIXME: This generated code sucks.
648         ISD::CondCode LowCC;
649         switch (cast<SetCCSDNode>(Node)->getCondition()) {
650         default: assert(0 && "Unknown integer setcc!");
651         case ISD::SETLT:
652         case ISD::SETULT: LowCC = ISD::SETULT; break;
653         case ISD::SETGT:
654         case ISD::SETUGT: LowCC = ISD::SETUGT; break;
655         case ISD::SETLE:
656         case ISD::SETULE: LowCC = ISD::SETULE; break;
657         case ISD::SETGE:
658         case ISD::SETUGE: LowCC = ISD::SETUGE; break;
659         }
660         
661         // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
662         // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
663         // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
664
665         // NOTE: on targets without efficient SELECT of bools, we can always use
666         // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
667         Tmp1 = DAG.getSetCC(LowCC, LHSLo, RHSLo);
668         Tmp2 = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
669                             LHSHi, RHSHi);
670         Result = DAG.getSetCC(ISD::SETEQ, LHSHi, RHSHi);
671         Result = DAG.getNode(ISD::SELECT, MVT::i1, Result, Tmp1, Tmp2);
672         break;
673       }
674     }
675     break;
676
677   case ISD::MEMSET:
678   case ISD::MEMCPY:
679   case ISD::MEMMOVE: {
680     Tmp1 = LegalizeOp(Node->getOperand(0));
681     Tmp2 = LegalizeOp(Node->getOperand(1));
682     Tmp3 = LegalizeOp(Node->getOperand(2));
683     SDOperand Tmp4 = LegalizeOp(Node->getOperand(3));
684     SDOperand Tmp5 = LegalizeOp(Node->getOperand(4));
685     if (TLI.isOperationSupported(Node->getOpcode(), MVT::Other)) {
686       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
687           Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3) ||
688           Tmp5 != Node->getOperand(4)) {
689         std::vector<SDOperand> Ops;
690         Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
691         Ops.push_back(Tmp4); Ops.push_back(Tmp5);
692         Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
693       }
694     } else {
695       // Otherwise, the target does not support this operation.  Lower the
696       // operation to an explicit libcall as appropriate.
697       MVT::ValueType IntPtr = TLI.getPointerTy();
698       const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
699       std::vector<std::pair<SDOperand, const Type*> > Args;
700
701       const char *FnName = 0;
702       if (Node->getOpcode() == ISD::MEMSET) {
703         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
704         // Extend the ubyte argument to be an int value for the call.
705         Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
706         Args.push_back(std::make_pair(Tmp3, Type::IntTy));
707         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
708
709         FnName = "memset";
710       } else if (Node->getOpcode() == ISD::MEMCPY ||
711                  Node->getOpcode() == ISD::MEMMOVE) {
712         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
713         Args.push_back(std::make_pair(Tmp3, IntPtrTy));
714         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
715         FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
716       } else {
717         assert(0 && "Unknown op!");
718       }
719       std::pair<SDOperand,SDOperand> CallResult =
720         TLI.LowerCallTo(Tmp1, Type::VoidTy,
721                         DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
722       Result = LegalizeOp(CallResult.second);
723     }
724     break;
725   }
726   case ISD::ADD:
727   case ISD::SUB:
728   case ISD::MUL:
729   case ISD::UDIV:
730   case ISD::SDIV:
731   case ISD::UREM:
732   case ISD::SREM:
733   case ISD::AND:
734   case ISD::OR:
735   case ISD::XOR:
736   case ISD::SHL:
737   case ISD::SRL:
738   case ISD::SRA:
739     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
740     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
741     if (Tmp1 != Node->getOperand(0) ||
742         Tmp2 != Node->getOperand(1))
743       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
744     break;
745   case ISD::ZERO_EXTEND:
746   case ISD::SIGN_EXTEND:
747   case ISD::TRUNCATE:
748   case ISD::FP_EXTEND:
749   case ISD::FP_ROUND:
750   case ISD::FP_TO_SINT:
751   case ISD::FP_TO_UINT:
752   case ISD::SINT_TO_FP:
753   case ISD::UINT_TO_FP:
754
755     switch (getTypeAction(Node->getOperand(0).getValueType())) {
756     case Legal:
757       Tmp1 = LegalizeOp(Node->getOperand(0));
758       if (Tmp1 != Node->getOperand(0))
759         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
760       break;
761     case Expand:
762       assert(Node->getOpcode() != ISD::SINT_TO_FP &&
763              Node->getOpcode() != ISD::UINT_TO_FP &&
764              "Cannot lower Xint_to_fp to a call yet!");
765
766       // In the expand case, we must be dealing with a truncate, because
767       // otherwise the result would be larger than the source.
768       assert(Node->getOpcode() == ISD::TRUNCATE &&
769              "Shouldn't need to expand other operators here!");
770       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
771
772       // Since the result is legal, we should just be able to truncate the low
773       // part of the source.
774       Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
775       break;
776
777     case Promote:
778       switch (Node->getOpcode()) {
779       case ISD::ZERO_EXTEND: {
780         // Mask out the high bits.
781         uint64_t MaskCst =
782           1ULL << (MVT::getSizeInBits(Node->getOperand(0).getValueType()))-1;
783         Tmp1 = PromoteOp(Node->getOperand(0));
784         Result = DAG.getNode(ISD::AND, Node->getValueType(0), Tmp1,
785                              DAG.getConstant(MaskCst, Node->getValueType(0)));
786         break;
787       }
788       case ISD::SIGN_EXTEND:
789       case ISD::TRUNCATE:
790       case ISD::FP_EXTEND:
791       case ISD::FP_ROUND:
792       case ISD::FP_TO_SINT:
793       case ISD::FP_TO_UINT:
794       case ISD::SINT_TO_FP:
795       case ISD::UINT_TO_FP:
796         Node->dump();
797         assert(0 && "Do not know how to promote this yet!");
798       }
799     }
800     break;
801   case ISD::FP_ROUND_INREG:
802   case ISD::SIGN_EXTEND_INREG:
803   case ISD::ZERO_EXTEND_INREG: {
804     Tmp1 = LegalizeOp(Node->getOperand(0));
805     MVT::ValueType ExtraVT = cast<MVTSDNode>(Node)->getExtraValueType();
806
807     // If this operation is not supported, convert it to a shl/shr or load/store
808     // pair.
809     if (!TLI.isOperationSupported(Node->getOpcode(), ExtraVT)) {
810       // If this is an integer extend and shifts are supported, do that.
811       if (Node->getOpcode() == ISD::ZERO_EXTEND_INREG) {
812         // NOTE: we could fall back on load/store here too for targets without
813         // AND.  However, it is doubtful that any exist.
814         // AND out the appropriate bits.
815         SDOperand Mask =
816           DAG.getConstant((1ULL << MVT::getSizeInBits(ExtraVT))-1,
817                           Node->getValueType(0));
818         Result = DAG.getNode(ISD::AND, Node->getValueType(0),
819                              Node->getOperand(0), Mask);
820       } else if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
821         // NOTE: we could fall back on load/store here too for targets without
822         // SAR.  However, it is doubtful that any exist.
823         unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
824                             MVT::getSizeInBits(ExtraVT);
825         SDOperand ShiftCst = DAG.getConstant(BitsDiff, MVT::i8);
826         Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
827                              Node->getOperand(0), ShiftCst);
828         Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
829                              Result, ShiftCst);
830       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
831         // The only way we can lower this is to turn it into a STORETRUNC,
832         // EXTLOAD pair, targetting a temporary location (a stack slot).
833
834         // NOTE: there is a choice here between constantly creating new stack
835         // slots and always reusing the same one.  We currently always create
836         // new ones, as reuse may inhibit scheduling.
837         const Type *Ty = MVT::getTypeForValueType(ExtraVT);
838         unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
839         unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
840         MachineFunction &MF = DAG.getMachineFunction();
841         int SSFI = 
842           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
843         SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
844         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
845                              Node->getOperand(0), StackSlot, ExtraVT);
846         Result = DAG.getNode(ISD::EXTLOAD, Node->getValueType(0),
847                              Result, StackSlot, ExtraVT);
848       } else {
849         assert(0 && "Unknown op");
850       }
851       Result = LegalizeOp(Result);
852     } else {
853       if (Tmp1 != Node->getOperand(0))
854         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
855                              ExtraVT);
856     }
857     break;
858   }
859   }
860
861   if (!Op.Val->hasOneUse())
862     AddLegalizedOperand(Op, Result);
863
864   return Result;
865 }
866
867 /// PromoteOp - Given an operation that produces a value in an invalid type,
868 /// promote it to compute the value into a larger type.  The produced value will
869 /// have the correct bits for the low portion of the register, but no guarantee
870 /// is made about the top bits: it may be zero, sign-extended, or garbage.
871 SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
872   MVT::ValueType VT = Op.getValueType();
873   MVT::ValueType NVT = TransformToType[VT];
874   assert(getTypeAction(VT) == Promote &&
875          "Caller should expand or legalize operands that are not promotable!");
876   assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
877          "Cannot promote to smaller type!");
878
879   std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
880   if (I != PromotedNodes.end()) return I->second;
881
882   SDOperand Tmp1, Tmp2, Tmp3;
883
884   SDOperand Result;
885   SDNode *Node = Op.Val;
886
887   // Promotion needs an optimization step to clean up after it, and is not
888   // careful to avoid operations the target does not support.  Make sure that
889   // all generated operations are legalized in the next iteration.
890   NeedsAnotherIteration = true;
891
892   switch (Node->getOpcode()) {
893   default:
894     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
895     assert(0 && "Do not know how to promote this operator!");
896     abort();
897   case ISD::CALL:
898     assert(0 && "Target's LowerCallTo implementation is buggy, returning value"
899            " types that are not supported by the target!");
900   case ISD::Constant:
901     Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
902     assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
903     break;
904   case ISD::ConstantFP:
905     Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
906     assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
907     break;
908
909   case ISD::TRUNCATE:
910     switch (getTypeAction(Node->getOperand(0).getValueType())) {
911     case Legal:
912       Result = LegalizeOp(Node->getOperand(0));
913       assert(Result.getValueType() >= NVT &&
914              "This truncation doesn't make sense!");
915       if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
916         Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
917       break;
918     case Expand:
919       assert(0 && "Cannot handle expand yet");
920     case Promote:
921       assert(0 && "Cannot handle promote-promote yet");
922     }
923     break;
924   case ISD::SIGN_EXTEND:
925   case ISD::ZERO_EXTEND:
926     switch (getTypeAction(Node->getOperand(0).getValueType())) {
927     case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
928     case Legal:
929       // Input is legal?  Just do extend all the way to the larger type.
930       Result = LegalizeOp(Node->getOperand(0));
931       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
932       break;
933     case Promote:
934       // Promote the reg if it's smaller.
935       Result = PromoteOp(Node->getOperand(0));
936       // The high bits are not guaranteed to be anything.  Insert an extend.
937       if (Node->getOpcode() == ISD::SIGN_EXTEND)
938         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result, VT);
939       else
940         Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Result, VT);
941       break;
942     }
943     break;
944
945   case ISD::FP_EXTEND:
946     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
947   case ISD::FP_ROUND:
948     switch (getTypeAction(Node->getOperand(0).getValueType())) {
949     case Expand: assert(0 && "BUG: Cannot expand FP regs!");
950     case Promote:  assert(0 && "Unreachable with 2 FP types!");
951     case Legal:
952       // Input is legal?  Do an FP_ROUND_INREG.
953       Result = LegalizeOp(Node->getOperand(0));
954       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
955       break;
956     }
957     break;
958
959   case ISD::SINT_TO_FP:
960   case ISD::UINT_TO_FP:
961     switch (getTypeAction(Node->getOperand(0).getValueType())) {
962     case Legal:
963       Result = LegalizeOp(Node->getOperand(0));
964       break;
965
966     case Promote:
967       Result = PromoteOp(Node->getOperand(0));
968       if (Node->getOpcode() == ISD::SINT_TO_FP)
969         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
970                              Result, Node->getOperand(0).getValueType());
971       else
972         Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Result.getValueType(),
973                              Result, Node->getOperand(0).getValueType());
974       break;
975     case Expand:
976       assert(0 && "Unimplemented");
977     }
978     // No extra round required here.
979     Result = DAG.getNode(Node->getOpcode(), NVT, Result);
980     break;
981
982   case ISD::FP_TO_SINT:
983   case ISD::FP_TO_UINT:
984     switch (getTypeAction(Node->getOperand(0).getValueType())) {
985     case Legal:
986       Tmp1 = LegalizeOp(Node->getOperand(0));
987       break;
988     case Promote:
989       // The input result is prerounded, so we don't have to do anything
990       // special.
991       Tmp1 = PromoteOp(Node->getOperand(0));
992       break;
993     case Expand:
994       assert(0 && "not implemented");
995     }
996     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
997     break;
998
999   case ISD::AND:
1000   case ISD::OR:
1001   case ISD::XOR:
1002   case ISD::ADD:
1003   case ISD::SUB:
1004   case ISD::MUL:
1005     // The input may have strange things in the top bits of the registers, but
1006     // these operations don't care.  They may have wierd bits going out, but
1007     // that too is okay if they are integer operations.
1008     Tmp1 = PromoteOp(Node->getOperand(0));
1009     Tmp2 = PromoteOp(Node->getOperand(1));
1010     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
1011     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1012
1013     // However, if this is a floating point operation, they will give excess
1014     // precision that we may not be able to tolerate.  If we DO allow excess
1015     // precision, just leave it, otherwise excise it.
1016     // FIXME: Why would we need to round FP ops more than integer ones?
1017     //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
1018     if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1019       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1020     break;
1021
1022   case ISD::SDIV:
1023   case ISD::SREM:
1024     // These operators require that their input be sign extended.
1025     Tmp1 = PromoteOp(Node->getOperand(0));
1026     Tmp2 = PromoteOp(Node->getOperand(1));
1027     if (MVT::isInteger(NVT)) {
1028       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
1029       Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2, VT);
1030     }
1031     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1032
1033     // Perform FP_ROUND: this is probably overly pessimistic.
1034     if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1035       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1036     break;
1037
1038   case ISD::UDIV:
1039   case ISD::UREM:
1040     // These operators require that their input be zero extended.
1041     Tmp1 = PromoteOp(Node->getOperand(0));
1042     Tmp2 = PromoteOp(Node->getOperand(1));
1043     assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
1044     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
1045     Tmp2 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp2, VT);
1046     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1047     break;
1048
1049   case ISD::SHL:
1050     Tmp1 = PromoteOp(Node->getOperand(0));
1051     Tmp2 = LegalizeOp(Node->getOperand(1));
1052     Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Tmp2);
1053     break;
1054   case ISD::SRA:
1055     // The input value must be properly sign extended.
1056     Tmp1 = PromoteOp(Node->getOperand(0));
1057     Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
1058     Tmp2 = LegalizeOp(Node->getOperand(1));
1059     Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Tmp2);
1060     break;
1061   case ISD::SRL:
1062     // The input value must be properly zero extended.
1063     Tmp1 = PromoteOp(Node->getOperand(0));
1064     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
1065     Tmp2 = LegalizeOp(Node->getOperand(1));
1066     Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Tmp2);
1067     break;
1068   case ISD::LOAD:
1069     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
1070     Tmp2 = LegalizeOp(Node->getOperand(1));   // Legalize the pointer.
1071     Result = DAG.getNode(ISD::EXTLOAD, NVT, Tmp1, Tmp2, VT);
1072
1073     // Remember that we legalized the chain.
1074     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1075     break;
1076   case ISD::SELECT:
1077     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the condition
1078     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
1079     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
1080     Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2, Tmp3);
1081     break;
1082   }
1083
1084   assert(Result.Val && "Didn't set a result!");
1085   AddPromotedOperand(Op, Result);
1086   return Result;
1087 }
1088
1089 /// ExpandOp - Expand the specified SDOperand into its two component pieces
1090 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
1091 /// LegalizeNodes map is filled in for any results that are not expanded, the
1092 /// ExpandedNodes map is filled in for any results that are expanded, and the
1093 /// Lo/Hi values are returned.
1094 void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
1095   MVT::ValueType VT = Op.getValueType();
1096   MVT::ValueType NVT = TransformToType[VT];
1097   SDNode *Node = Op.Val;
1098   assert(getTypeAction(VT) == Expand && "Not an expanded type!");
1099   assert(MVT::isInteger(VT) && "Cannot expand FP values!");
1100   assert(MVT::isInteger(NVT) && NVT < VT &&
1101          "Cannot expand to FP value or to larger int value!");
1102
1103   // If there is more than one use of this, see if we already expanded it.
1104   // There is no use remembering values that only have a single use, as the map
1105   // entries will never be reused.
1106   if (!Node->hasOneUse()) {
1107     std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
1108       = ExpandedNodes.find(Op);
1109     if (I != ExpandedNodes.end()) {
1110       Lo = I->second.first;
1111       Hi = I->second.second;
1112       return;
1113     }
1114   }
1115
1116   // Expanding to multiple registers needs to perform an optimization step, and
1117   // is not careful to avoid operations the target does not support.  Make sure
1118   // that all generated operations are legalized in the next iteration.
1119   NeedsAnotherIteration = true;
1120   const char *LibCallName = 0;
1121
1122   switch (Node->getOpcode()) {
1123   default:
1124     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
1125     assert(0 && "Do not know how to expand this operator!");
1126     abort();
1127   case ISD::Constant: {
1128     uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
1129     Lo = DAG.getConstant(Cst, NVT);
1130     Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
1131     break;
1132   }
1133
1134   case ISD::CopyFromReg: {
1135     unsigned Reg = cast<RegSDNode>(Node)->getReg();
1136     // Aggregate register values are always in consequtive pairs.
1137     Lo = DAG.getCopyFromReg(Reg, NVT, Node->getOperand(0));
1138     Hi = DAG.getCopyFromReg(Reg+1, NVT, Lo.getValue(1));
1139     
1140     // Remember that we legalized the chain.
1141     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
1142
1143     assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
1144     break;
1145   }
1146
1147   case ISD::LOAD: {
1148     SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
1149     SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1150     Lo = DAG.getLoad(NVT, Ch, Ptr);
1151
1152     // Increment the pointer to the other half.
1153     unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
1154     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
1155                       getIntPtrConstant(IncrementSize));
1156     // FIXME: This load is independent of the first one.
1157     Hi = DAG.getLoad(NVT, Lo.getValue(1), Ptr);
1158     
1159     // Remember that we legalized the chain.
1160     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
1161     if (!TLI.isLittleEndian())
1162       std::swap(Lo, Hi);
1163     break;
1164   }
1165   case ISD::CALL: {
1166     SDOperand Chain  = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1167     SDOperand Callee = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
1168
1169     assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
1170            "Can only expand a call once so far, not i64 -> i16!");
1171
1172     std::vector<MVT::ValueType> RetTyVTs;
1173     RetTyVTs.reserve(3);
1174     RetTyVTs.push_back(NVT);
1175     RetTyVTs.push_back(NVT);
1176     RetTyVTs.push_back(MVT::Other);
1177     SDNode *NC = DAG.getCall(RetTyVTs, Chain, Callee);
1178     Lo = SDOperand(NC, 0);
1179     Hi = SDOperand(NC, 1);
1180
1181     // Insert the new chain mapping.
1182     AddLegalizedOperand(Op.getValue(1), Hi.getValue(2));
1183     break;
1184   }
1185   case ISD::AND:
1186   case ISD::OR:
1187   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
1188     SDOperand LL, LH, RL, RH;
1189     ExpandOp(Node->getOperand(0), LL, LH);
1190     ExpandOp(Node->getOperand(1), RL, RH);
1191     Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
1192     Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
1193     break;
1194   }
1195   case ISD::SELECT: {
1196     SDOperand C, LL, LH, RL, RH;
1197     // FIXME: BOOLS MAY REQUIRE PROMOTION!
1198     C = LegalizeOp(Node->getOperand(0));
1199     ExpandOp(Node->getOperand(1), LL, LH);
1200     ExpandOp(Node->getOperand(2), RL, RH);
1201     Lo = DAG.getNode(ISD::SELECT, NVT, C, LL, RL);
1202     Hi = DAG.getNode(ISD::SELECT, NVT, C, LH, RH);
1203     break;
1204   }
1205   case ISD::SIGN_EXTEND: {
1206     // The low part is just a sign extension of the input (which degenerates to
1207     // a copy).
1208     Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, LegalizeOp(Node->getOperand(0)));
1209     
1210     // The high part is obtained by SRA'ing all but one of the bits of the lo
1211     // part.
1212     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
1213     Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1, MVT::i8));
1214     break;
1215   }
1216   case ISD::ZERO_EXTEND:
1217     // The low part is just a zero extension of the input (which degenerates to
1218     // a copy).
1219     Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, LegalizeOp(Node->getOperand(0)));
1220     
1221     // The high part is just a zero.
1222     Hi = DAG.getConstant(0, NVT);
1223     break;
1224
1225     // These operators cannot be expanded directly, emit them as calls to
1226     // library functions.
1227   case ISD::FP_TO_SINT:
1228     if (Node->getOperand(0).getValueType() == MVT::f32)
1229       LibCallName = "__fixsfdi";
1230     else
1231       LibCallName = "__fixdfdi";
1232     break;
1233   case ISD::FP_TO_UINT:
1234     if (Node->getOperand(0).getValueType() == MVT::f32)
1235       LibCallName = "__fixunssfdi";
1236     else
1237       LibCallName = "__fixunsdfdi";
1238     break;
1239
1240   case ISD::ADD:  LibCallName = "__adddi3"; break;
1241   case ISD::SUB:  LibCallName = "__subdi3"; break;
1242   case ISD::MUL:  LibCallName = "__muldi3"; break;
1243   case ISD::SDIV: LibCallName = "__divdi3"; break;
1244   case ISD::UDIV: LibCallName = "__udivdi3"; break;
1245   case ISD::SREM: LibCallName = "__moddi3"; break;
1246   case ISD::UREM: LibCallName = "__umoddi3"; break;
1247   case ISD::SHL:  LibCallName = "__ashldi3"; break;
1248   case ISD::SRA:  LibCallName = "__ashrdi3"; break;
1249   case ISD::SRL:  LibCallName = "__lshrdi3"; break;
1250   }
1251
1252   // Int2FP -> __floatdisf/__floatdidf
1253
1254   // If this is to be expanded into a libcall... do so now.
1255   if (LibCallName) {
1256     TargetLowering::ArgListTy Args;
1257     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1258       Args.push_back(std::make_pair(Node->getOperand(i),
1259                  MVT::getTypeForValueType(Node->getOperand(i).getValueType())));
1260     SDOperand Callee = DAG.getExternalSymbol(LibCallName, TLI.getPointerTy());
1261
1262     // We don't care about token chains for libcalls.  We just use the entry
1263     // node as our input and ignore the output chain.  This allows us to place
1264     // calls wherever we need them to satisfy data dependences.
1265     SDOperand Result = TLI.LowerCallTo(DAG.getEntryNode(),
1266                            MVT::getTypeForValueType(Op.getValueType()), Callee,
1267                                        Args, DAG).first;
1268     ExpandOp(Result, Lo, Hi);
1269   }
1270
1271   // Remember in a map if the values will be reused later.
1272   if (!Node->hasOneUse()) {
1273     bool isNew = ExpandedNodes.insert(std::make_pair(Op,
1274                                             std::make_pair(Lo, Hi))).second;
1275     assert(isNew && "Value already expanded?!?");
1276   }
1277 }
1278
1279
1280 // SelectionDAG::Legalize - This is the entry point for the file.
1281 //
1282 void SelectionDAG::Legalize(TargetLowering &TLI) {
1283   /// run - This is the main entry point to this class.
1284   ///
1285   SelectionDAGLegalize(TLI, *this).Run();
1286 }
1287