Alpha doesn't have a native f32 extload instruction.
[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   /// ValueTypeActions - This is a bitvector that contains two bits for each
51   /// value type, where the two bits correspond to the LegalizeAction enum.
52   /// This can be queried with "getTypeAction(VT)".
53   unsigned ValueTypeActions;
54
55   /// NeedsAnotherIteration - This is set when we expand a large integer
56   /// operation into smaller integer operations, but the smaller operations are
57   /// not set.  This occurs only rarely in practice, for targets that don't have
58   /// 32-bit or larger integer registers.
59   bool NeedsAnotherIteration;
60
61   /// LegalizedNodes - For nodes that are of legal width, and that have more
62   /// than one use, this map indicates what regularized operand to use.  This
63   /// allows us to avoid legalizing the same thing more than once.
64   std::map<SDOperand, SDOperand> LegalizedNodes;
65
66   /// PromotedNodes - For nodes that are below legal width, and that have more
67   /// than one use, this map indicates what promoted value to use.  This allows
68   /// us to avoid promoting the same thing more than once.
69   std::map<SDOperand, SDOperand> PromotedNodes;
70
71   /// ExpandedNodes - For nodes that need to be expanded, and which have more
72   /// than one use, this map indicates which which operands are the expanded
73   /// version of the input.  This allows us to avoid expanding the same node
74   /// more than once.
75   std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
76
77   void AddLegalizedOperand(SDOperand From, SDOperand To) {
78     bool isNew = LegalizedNodes.insert(std::make_pair(From, To)).second;
79     assert(isNew && "Got into the map somehow?");
80   }
81   void AddPromotedOperand(SDOperand From, SDOperand To) {
82     bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
83     assert(isNew && "Got into the map somehow?");
84   }
85
86 public:
87
88   SelectionDAGLegalize(SelectionDAG &DAG);
89
90   /// Run - While there is still lowering to do, perform a pass over the DAG.
91   /// Most regularization can be done in a single pass, but targets that require
92   /// large values to be split into registers multiple times (e.g. i64 -> 4x
93   /// i16) require iteration for these values (the first iteration will demote
94   /// to i32, the second will demote to i16).
95   void Run() {
96     do {
97       NeedsAnotherIteration = false;
98       LegalizeDAG();
99     } while (NeedsAnotherIteration);
100   }
101
102   /// getTypeAction - Return how we should legalize values of this type, either
103   /// it is already legal or we need to expand it into multiple registers of
104   /// smaller integer type, or we need to promote it to a larger type.
105   LegalizeAction getTypeAction(MVT::ValueType VT) const {
106     return (LegalizeAction)((ValueTypeActions >> (2*VT)) & 3);
107   }
108
109   /// isTypeLegal - Return true if this type is legal on this target.
110   ///
111   bool isTypeLegal(MVT::ValueType VT) const {
112     return getTypeAction(VT) == Legal;
113   }
114
115 private:
116   void LegalizeDAG();
117
118   SDOperand LegalizeOp(SDOperand O);
119   void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
120   SDOperand PromoteOp(SDOperand O);
121
122   SDOperand ExpandLibCall(const char *Name, SDNode *Node,
123                           SDOperand &Hi);
124   SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
125                           SDOperand Source);
126   bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
127                    SDOperand &Lo, SDOperand &Hi);
128   void ExpandAddSub(bool isAdd, SDOperand Op, SDOperand Amt,
129                     SDOperand &Lo, SDOperand &Hi);
130
131   SDOperand getIntPtrConstant(uint64_t Val) {
132     return DAG.getConstant(Val, TLI.getPointerTy());
133   }
134 };
135 }
136
137
138 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
139   : TLI(dag.getTargetLoweringInfo()), DAG(dag),
140     ValueTypeActions(TLI.getValueTypeActions()) {
141   assert(MVT::LAST_VALUETYPE <= 16 &&
142          "Too many value types for ValueTypeActions to hold!");
143 }
144
145 void SelectionDAGLegalize::LegalizeDAG() {
146   SDOperand OldRoot = DAG.getRoot();
147   SDOperand NewRoot = LegalizeOp(OldRoot);
148   DAG.setRoot(NewRoot);
149
150   ExpandedNodes.clear();
151   LegalizedNodes.clear();
152   PromotedNodes.clear();
153
154   // Remove dead nodes now.
155   DAG.RemoveDeadNodes(OldRoot.Val);
156 }
157
158 SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
159   assert(getTypeAction(Op.getValueType()) == Legal &&
160          "Caller should expand or promote operands that are not legal!");
161
162   // If this operation defines any values that cannot be represented in a
163   // register on this target, make sure to expand or promote them.
164   if (Op.Val->getNumValues() > 1) {
165     for (unsigned i = 0, e = Op.Val->getNumValues(); i != e; ++i)
166       switch (getTypeAction(Op.Val->getValueType(i))) {
167       case Legal: break;  // Nothing to do.
168       case Expand: {
169         SDOperand T1, T2;
170         ExpandOp(Op.getValue(i), T1, T2);
171         assert(LegalizedNodes.count(Op) &&
172                "Expansion didn't add legal operands!");
173         return LegalizedNodes[Op];
174       }
175       case Promote:
176         PromoteOp(Op.getValue(i));
177         assert(LegalizedNodes.count(Op) &&
178                "Expansion didn't add legal operands!");
179         return LegalizedNodes[Op];
180       }
181   }
182
183   std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
184   if (I != LegalizedNodes.end()) return I->second;
185
186   SDOperand Tmp1, Tmp2, Tmp3;
187
188   SDOperand Result = Op;
189   SDNode *Node = Op.Val;
190
191   switch (Node->getOpcode()) {
192   default:
193     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
194     assert(0 && "Do not know how to legalize this operator!");
195     abort();
196   case ISD::EntryToken:
197   case ISD::FrameIndex:
198   case ISD::GlobalAddress:
199   case ISD::ExternalSymbol:
200   case ISD::ConstantPool:           // Nothing to do.
201     assert(getTypeAction(Node->getValueType(0)) == Legal &&
202            "This must be legal!");
203     break;
204   case ISD::CopyFromReg:
205     Tmp1 = LegalizeOp(Node->getOperand(0));
206     if (Tmp1 != Node->getOperand(0))
207       Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(),
208                                   Node->getValueType(0), Tmp1);
209     else
210       Result = Op.getValue(0);
211
212     // Since CopyFromReg produces two values, make sure to remember that we
213     // legalized both of them.
214     AddLegalizedOperand(Op.getValue(0), Result);
215     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
216     return Result.getValue(Op.ResNo);
217   case ISD::ImplicitDef:
218     Tmp1 = LegalizeOp(Node->getOperand(0));
219     if (Tmp1 != Node->getOperand(0))
220       Result = DAG.getImplicitDef(Tmp1, cast<RegSDNode>(Node)->getReg());
221     break;
222   case ISD::Constant:
223     // We know we don't need to expand constants here, constants only have one
224     // value and we check that it is fine above.
225
226     // FIXME: Maybe we should handle things like targets that don't support full
227     // 32-bit immediates?
228     break;
229   case ISD::ConstantFP: {
230     // Spill FP immediates to the constant pool if the target cannot directly
231     // codegen them.  Targets often have some immediate values that can be
232     // efficiently generated into an FP register without a load.  We explicitly
233     // leave these constants as ConstantFP nodes for the target to deal with.
234
235     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
236
237     // Check to see if this FP immediate is already legal.
238     bool isLegal = false;
239     for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
240            E = TLI.legal_fpimm_end(); I != E; ++I)
241       if (CFP->isExactlyValue(*I)) {
242         isLegal = true;
243         break;
244       }
245
246     if (!isLegal) {
247       // Otherwise we need to spill the constant to memory.
248       MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
249
250       bool Extend = false;
251
252       // If a FP immediate is precise when represented as a float, we put it
253       // into the constant pool as a float, even if it's is statically typed
254       // as a double.
255       MVT::ValueType VT = CFP->getValueType(0);
256       bool isDouble = VT == MVT::f64;
257       ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
258                                              Type::FloatTy, CFP->getValue());
259       if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
260           // Only do this if the target has a native EXTLOAD instruction from
261           // f32.
262           TLI.getOperationAction(ISD::EXTLOAD,
263                                  MVT::f32) == TargetLowering::Legal) {
264         LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
265         VT = MVT::f32;
266         Extend = true;
267       }
268       
269       SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(LLVMC),
270                                             TLI.getPointerTy());
271       if (Extend) {
272         Result = DAG.getNode(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(), CPIdx,
273                              MVT::f32);
274       } else {
275         Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx);
276       }
277     }
278     break;
279   }
280   case ISD::TokenFactor: {
281     std::vector<SDOperand> Ops;
282     bool Changed = false;
283     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
284       SDOperand Op = Node->getOperand(i);
285       // Fold single-use TokenFactor nodes into this token factor as we go.
286       if (Op.getOpcode() == ISD::TokenFactor && Op.hasOneUse()) {
287         Changed = true;
288         for (unsigned j = 0, e = Op.getNumOperands(); j != e; ++j)
289           Ops.push_back(LegalizeOp(Op.getOperand(j)));
290       } else {
291         Ops.push_back(LegalizeOp(Op));  // Legalize the operands
292         Changed |= Ops[i] != Op;
293       }
294     }
295     if (Changed)
296       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
297     break;
298   }
299
300   case ISD::ADJCALLSTACKDOWN:
301   case ISD::ADJCALLSTACKUP:
302     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
303     // There is no need to legalize the size argument (Operand #1)
304     if (Tmp1 != Node->getOperand(0))
305       Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1,
306                            Node->getOperand(1));
307     break;
308   case ISD::DYNAMIC_STACKALLOC:
309     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
310     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
311     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
312     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
313         Tmp3 != Node->getOperand(2))
314       Result = DAG.getNode(ISD::DYNAMIC_STACKALLOC, Node->getValueType(0),
315                            Tmp1, Tmp2, Tmp3);
316     else
317       Result = Op.getValue(0);
318
319     // Since this op produces two values, make sure to remember that we
320     // legalized both of them.
321     AddLegalizedOperand(SDOperand(Node, 0), Result);
322     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
323     return Result.getValue(Op.ResNo);
324
325   case ISD::CALL: {
326     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
327     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
328
329     bool Changed = false;
330     std::vector<SDOperand> Ops;
331     for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
332       Ops.push_back(LegalizeOp(Node->getOperand(i)));
333       Changed |= Ops.back() != Node->getOperand(i);
334     }
335
336     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) || Changed) {
337       std::vector<MVT::ValueType> RetTyVTs;
338       RetTyVTs.reserve(Node->getNumValues());
339       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
340         RetTyVTs.push_back(Node->getValueType(i));
341       Result = SDOperand(DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops), 0);
342     } else {
343       Result = Result.getValue(0);
344     }
345     // Since calls produce multiple values, make sure to remember that we
346     // legalized all of them.
347     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
348       AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
349     return Result.getValue(Op.ResNo);
350   }
351   case ISD::BR:
352     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
353     if (Tmp1 != Node->getOperand(0))
354       Result = DAG.getNode(ISD::BR, MVT::Other, Tmp1, Node->getOperand(1));
355     break;
356
357   case ISD::BRCOND:
358     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
359
360     switch (getTypeAction(Node->getOperand(1).getValueType())) {
361     case Expand: assert(0 && "It's impossible to expand bools");
362     case Legal:
363       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
364       break;
365     case Promote:
366       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
367       break;
368     }
369     // Basic block destination (Op#2) is always legal.
370     if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
371       Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
372                            Node->getOperand(2));
373     break;
374
375   case ISD::LOAD:
376     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
377     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
378     if (Tmp1 != Node->getOperand(0) ||
379         Tmp2 != Node->getOperand(1))
380       Result = DAG.getLoad(Node->getValueType(0), Tmp1, Tmp2);
381     else
382       Result = SDOperand(Node, 0);
383     
384     // Since loads produce two values, make sure to remember that we legalized
385     // both of them.
386     AddLegalizedOperand(SDOperand(Node, 0), Result);
387     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
388     return Result.getValue(Op.ResNo);
389
390   case ISD::EXTLOAD:
391   case ISD::SEXTLOAD:
392   case ISD::ZEXTLOAD:
393     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
394     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
395     if (Tmp1 != Node->getOperand(0) ||
396         Tmp2 != Node->getOperand(1))
397       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1, Tmp2,
398                            cast<MVTSDNode>(Node)->getExtraValueType());
399     else
400       Result = SDOperand(Node, 0);
401     
402     // Since loads produce two values, make sure to remember that we legalized
403     // both of them.
404     AddLegalizedOperand(SDOperand(Node, 0), Result);
405     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
406     return Result.getValue(Op.ResNo);
407
408   case ISD::EXTRACT_ELEMENT:
409     // Get both the low and high parts.
410     ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
411     if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
412       Result = Tmp2;  // 1 -> Hi
413     else
414       Result = Tmp1;  // 0 -> Lo
415     break;
416
417   case ISD::CopyToReg:
418     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
419     
420     switch (getTypeAction(Node->getOperand(1).getValueType())) {
421     case Legal:
422       // Legalize the incoming value (must be legal).
423       Tmp2 = LegalizeOp(Node->getOperand(1));
424       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
425         Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
426       break;
427     case Promote:
428       Tmp2 = PromoteOp(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       Lo = DAG.getCopyToReg(Tmp1, Lo, Reg);
436       Hi = DAG.getCopyToReg(Tmp1, Hi, Reg+1);
437       // Note that the copytoreg nodes are independent of each other.
438       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
439       assert(isTypeLegal(Result.getValueType()) &&
440              "Cannot expand multiple times yet (i64 -> i16)");
441       break;
442     }
443     break;
444
445   case ISD::RET:
446     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
447     switch (Node->getNumOperands()) {
448     case 2:  // ret val
449       switch (getTypeAction(Node->getOperand(1).getValueType())) {
450       case Legal:
451         Tmp2 = LegalizeOp(Node->getOperand(1));
452         if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
453           Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
454         break;
455       case Expand: {
456         SDOperand Lo, Hi;
457         ExpandOp(Node->getOperand(1), Lo, Hi);
458         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
459         break;                             
460       }
461       case Promote:
462         Tmp2 = PromoteOp(Node->getOperand(1));
463         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
464         break;
465       }
466       break;
467     case 1:  // ret void
468       if (Tmp1 != Node->getOperand(0))
469         Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1);
470       break;
471     default: { // ret <values>
472       std::vector<SDOperand> NewValues;
473       NewValues.push_back(Tmp1);
474       for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
475         switch (getTypeAction(Node->getOperand(i).getValueType())) {
476         case Legal:
477           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
478           break;
479         case Expand: {
480           SDOperand Lo, Hi;
481           ExpandOp(Node->getOperand(i), Lo, Hi);
482           NewValues.push_back(Lo);
483           NewValues.push_back(Hi);
484           break;                             
485         }
486         case Promote:
487           assert(0 && "Can't promote multiple return value yet!");
488         }
489       Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
490       break;
491     }
492     }
493     break;
494   case ISD::STORE:
495     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
496     Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
497
498     // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
499     if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
500       if (CFP->getValueType(0) == MVT::f32) {
501         union {
502           unsigned I;
503           float    F;
504         } V;
505         V.F = CFP->getValue();
506         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
507                              DAG.getConstant(V.I, MVT::i32), Tmp2);
508       } else {
509         assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
510         union {
511           uint64_t I;
512           double   F;
513         } V;
514         V.F = CFP->getValue();
515         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
516                              DAG.getConstant(V.I, MVT::i64), Tmp2);
517       }
518       Op = Result;
519       Node = Op.Val;
520     }
521
522     switch (getTypeAction(Node->getOperand(1).getValueType())) {
523     case Legal: {
524       SDOperand Val = LegalizeOp(Node->getOperand(1));
525       if (Val != Node->getOperand(1) || Tmp1 != Node->getOperand(0) ||
526           Tmp2 != Node->getOperand(2))
527         Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Val, Tmp2);
528       break;
529     }
530     case Promote:
531       // Truncate the value and store the result.
532       Tmp3 = PromoteOp(Node->getOperand(1));
533       Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
534                            Node->getOperand(1).getValueType());
535       break;
536
537     case Expand:
538       SDOperand Lo, Hi;
539       ExpandOp(Node->getOperand(1), Lo, Hi);
540
541       if (!TLI.isLittleEndian())
542         std::swap(Lo, Hi);
543
544       Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2);
545
546       unsigned IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
547       Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
548                          getIntPtrConstant(IncrementSize));
549       assert(isTypeLegal(Tmp2.getValueType()) &&
550              "Pointers must be legal!");
551       Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2);
552       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
553       break;
554     }
555     break;
556   case ISD::TRUNCSTORE:
557     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
558     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
559
560     switch (getTypeAction(Node->getOperand(1).getValueType())) {
561     case Legal:
562       Tmp2 = LegalizeOp(Node->getOperand(1));
563       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
564           Tmp3 != Node->getOperand(2))
565         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
566                              cast<MVTSDNode>(Node)->getExtraValueType());
567       break;
568     case Promote:
569     case Expand:
570       assert(0 && "Cannot handle illegal TRUNCSTORE yet!");
571     }
572     break;
573   case ISD::SELECT:
574     switch (getTypeAction(Node->getOperand(0).getValueType())) {
575     case Expand: assert(0 && "It's impossible to expand bools");
576     case Legal:
577       Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
578       break;
579     case Promote:
580       Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
581       break;
582     }
583     Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
584     Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
585
586     switch (TLI.getOperationAction(Node->getOpcode(), Tmp2.getValueType())) {
587     default: assert(0 && "This action is not supported yet!");
588     case TargetLowering::Legal:
589       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
590           Tmp3 != Node->getOperand(2))
591         Result = DAG.getNode(ISD::SELECT, Node->getValueType(0),
592                              Tmp1, Tmp2, Tmp3);
593       break;
594     case TargetLowering::Promote: {
595       MVT::ValueType NVT =
596         TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
597       unsigned ExtOp, TruncOp;
598       if (MVT::isInteger(Tmp2.getValueType())) {
599         ExtOp = ISD::ZERO_EXTEND;
600         TruncOp  = ISD::TRUNCATE;
601       } else {
602         ExtOp = ISD::FP_EXTEND;
603         TruncOp  = ISD::FP_ROUND;
604       }
605       // Promote each of the values to the new type.
606       Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
607       Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
608       // Perform the larger operation, then round down.
609       Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
610       Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
611       break;
612     }
613     }
614     break;
615   case ISD::SETCC:
616     switch (getTypeAction(Node->getOperand(0).getValueType())) {
617     case Legal:
618       Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
619       Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
620       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
621         Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
622                               Node->getValueType(0), Tmp1, Tmp2);
623       break;
624     case Promote:
625       Tmp1 = PromoteOp(Node->getOperand(0));   // LHS
626       Tmp2 = PromoteOp(Node->getOperand(1));   // RHS
627
628       // If this is an FP compare, the operands have already been extended.
629       if (MVT::isInteger(Node->getOperand(0).getValueType())) {
630         MVT::ValueType VT = Node->getOperand(0).getValueType();
631         MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
632
633         // Otherwise, we have to insert explicit sign or zero extends.  Note
634         // that we could insert sign extends for ALL conditions, but zero extend
635         // is cheaper on many machines (an AND instead of two shifts), so prefer
636         // it.
637         switch (cast<SetCCSDNode>(Node)->getCondition()) {
638         default: assert(0 && "Unknown integer comparison!");
639         case ISD::SETEQ:
640         case ISD::SETNE:
641         case ISD::SETUGE:
642         case ISD::SETUGT:
643         case ISD::SETULE:
644         case ISD::SETULT:
645           // ALL of these operations will work if we either sign or zero extend
646           // the operands (including the unsigned comparisons!).  Zero extend is
647           // usually a simpler/cheaper operation, so prefer it.
648           Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
649           Tmp2 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp2, VT);
650           break;
651         case ISD::SETGE:
652         case ISD::SETGT:
653         case ISD::SETLT:
654         case ISD::SETLE:
655           Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
656           Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2, VT);
657           break;
658         }
659
660       }
661       Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
662                             Node->getValueType(0), Tmp1, Tmp2);
663       break;
664     case Expand: 
665       SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
666       ExpandOp(Node->getOperand(0), LHSLo, LHSHi);
667       ExpandOp(Node->getOperand(1), RHSLo, RHSHi);
668       switch (cast<SetCCSDNode>(Node)->getCondition()) {
669       case ISD::SETEQ:
670       case ISD::SETNE:
671         Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
672         Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
673         Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
674         Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(), 
675                               Node->getValueType(0), Tmp1,
676                               DAG.getConstant(0, Tmp1.getValueType()));
677         break;
678       default:
679         // FIXME: This generated code sucks.
680         ISD::CondCode LowCC;
681         switch (cast<SetCCSDNode>(Node)->getCondition()) {
682         default: assert(0 && "Unknown integer setcc!");
683         case ISD::SETLT:
684         case ISD::SETULT: LowCC = ISD::SETULT; break;
685         case ISD::SETGT:
686         case ISD::SETUGT: LowCC = ISD::SETUGT; break;
687         case ISD::SETLE:
688         case ISD::SETULE: LowCC = ISD::SETULE; break;
689         case ISD::SETGE:
690         case ISD::SETUGE: LowCC = ISD::SETUGE; break;
691         }
692         
693         // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
694         // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
695         // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
696
697         // NOTE: on targets without efficient SELECT of bools, we can always use
698         // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
699         Tmp1 = DAG.getSetCC(LowCC, Node->getValueType(0), LHSLo, RHSLo);
700         Tmp2 = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
701                             Node->getValueType(0), LHSHi, RHSHi);
702         Result = DAG.getSetCC(ISD::SETEQ, Node->getValueType(0), LHSHi, RHSHi);
703         Result = DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
704                              Result, Tmp1, Tmp2);
705         break;
706       }
707     }
708     break;
709
710   case ISD::MEMSET:
711   case ISD::MEMCPY:
712   case ISD::MEMMOVE: {
713     Tmp1 = LegalizeOp(Node->getOperand(0));      // Function
714     Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
715
716     if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
717       switch (getTypeAction(Node->getOperand(2).getValueType())) {
718       case Expand: assert(0 && "Cannot expand a byte!");
719       case Legal:
720         Tmp3 = LegalizeOp(Node->getOperand(1));
721         break;
722       case Promote:
723         Tmp3 = PromoteOp(Node->getOperand(1));
724         break;
725       }
726     } else {
727       Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer, 
728     }
729     SDOperand Tmp4, Tmp5;
730     
731     switch (getTypeAction(Node->getOperand(3).getValueType())) {  // uint
732     case Expand: assert(0 && "Cannot expand this yet!");
733     case Legal:
734       Tmp4 = LegalizeOp(Node->getOperand(3));
735       Tmp5 = LegalizeOp(Node->getOperand(4));
736       break;
737     case Promote:
738       Tmp4 = PromoteOp(Node->getOperand(3));
739       Tmp5 = PromoteOp(Node->getOperand(4));
740       break;
741     }
742
743     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
744     default: assert(0 && "This action not implemented for this operation!");
745     case TargetLowering::Legal:
746       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
747           Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3) ||
748           Tmp5 != Node->getOperand(4)) {
749         std::vector<SDOperand> Ops;
750         Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
751         Ops.push_back(Tmp4); Ops.push_back(Tmp5);
752         Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
753       }
754       break;
755     case TargetLowering::Expand: {
756       // Otherwise, the target does not support this operation.  Lower the
757       // operation to an explicit libcall as appropriate.
758       MVT::ValueType IntPtr = TLI.getPointerTy();
759       const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
760       std::vector<std::pair<SDOperand, const Type*> > Args;
761
762       const char *FnName = 0;
763       if (Node->getOpcode() == ISD::MEMSET) {
764         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
765         // Extend the ubyte argument to be an int value for the call.
766         Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
767         Args.push_back(std::make_pair(Tmp3, Type::IntTy));
768         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
769
770         FnName = "memset";
771       } else if (Node->getOpcode() == ISD::MEMCPY ||
772                  Node->getOpcode() == ISD::MEMMOVE) {
773         Args.push_back(std::make_pair(Tmp2, IntPtrTy));
774         Args.push_back(std::make_pair(Tmp3, IntPtrTy));
775         Args.push_back(std::make_pair(Tmp4, IntPtrTy));
776         FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
777       } else {
778         assert(0 && "Unknown op!");
779       }
780       std::pair<SDOperand,SDOperand> CallResult =
781         TLI.LowerCallTo(Tmp1, Type::VoidTy,
782                         DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
783       Result = LegalizeOp(CallResult.second);
784       break;
785     }
786     case TargetLowering::Custom:
787       std::vector<SDOperand> Ops;
788       Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
789       Ops.push_back(Tmp4); Ops.push_back(Tmp5);
790       Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
791       Result = TLI.LowerOperation(Result);
792       Result = LegalizeOp(Result);
793       break;
794     }
795     break;
796   }
797   case ISD::ADD_PARTS:
798   case ISD::SUB_PARTS: {
799     std::vector<SDOperand> Ops;
800     bool Changed = false;
801     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
802       Ops.push_back(LegalizeOp(Node->getOperand(i)));
803       Changed |= Ops.back() != Node->getOperand(i);
804     }
805     if (Changed)
806       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
807     break;
808   }
809   case ISD::ADD:
810   case ISD::SUB:
811   case ISD::MUL:
812   case ISD::UDIV:
813   case ISD::SDIV:
814   case ISD::UREM:
815   case ISD::SREM:
816   case ISD::AND:
817   case ISD::OR:
818   case ISD::XOR:
819   case ISD::SHL:
820   case ISD::SRL:
821   case ISD::SRA:
822     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
823     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
824     if (Tmp1 != Node->getOperand(0) ||
825         Tmp2 != Node->getOperand(1))
826       Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
827     break;
828   case ISD::ZERO_EXTEND:
829   case ISD::SIGN_EXTEND:
830   case ISD::TRUNCATE:
831   case ISD::FP_EXTEND:
832   case ISD::FP_ROUND:
833   case ISD::FP_TO_SINT:
834   case ISD::FP_TO_UINT:
835   case ISD::SINT_TO_FP:
836   case ISD::UINT_TO_FP:
837     switch (getTypeAction(Node->getOperand(0).getValueType())) {
838     case Legal:
839       Tmp1 = LegalizeOp(Node->getOperand(0));
840       if (Tmp1 != Node->getOperand(0))
841         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
842       break;
843     case Expand:
844       if (Node->getOpcode() == ISD::SINT_TO_FP ||
845           Node->getOpcode() == ISD::UINT_TO_FP) {
846         Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
847                                Node->getValueType(0), Node->getOperand(0));
848         Result = LegalizeOp(Result);
849         break;
850       }
851       // In the expand case, we must be dealing with a truncate, because
852       // otherwise the result would be larger than the source.
853       assert(Node->getOpcode() == ISD::TRUNCATE &&
854              "Shouldn't need to expand other operators here!");
855       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
856
857       // Since the result is legal, we should just be able to truncate the low
858       // part of the source.
859       Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
860       break;
861
862     case Promote:
863       switch (Node->getOpcode()) {
864       case ISD::ZERO_EXTEND:
865         Result = PromoteOp(Node->getOperand(0));
866         // NOTE: Any extend would work here...
867         Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
868         Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Op.getValueType(),
869                              Result, Node->getOperand(0).getValueType());
870         break;
871       case ISD::SIGN_EXTEND:
872         Result = PromoteOp(Node->getOperand(0));
873         // NOTE: Any extend would work here...
874         Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
875         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
876                              Result, Node->getOperand(0).getValueType());
877         break;
878       case ISD::TRUNCATE:
879         Result = PromoteOp(Node->getOperand(0));
880         Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
881         break;
882       case ISD::FP_EXTEND:
883         Result = PromoteOp(Node->getOperand(0));
884         if (Result.getValueType() != Op.getValueType())
885           // Dynamically dead while we have only 2 FP types.
886           Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
887         break;
888       case ISD::FP_ROUND:
889       case ISD::FP_TO_SINT:
890       case ISD::FP_TO_UINT:
891         Result = PromoteOp(Node->getOperand(0));
892         Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
893         break;
894       case ISD::SINT_TO_FP:
895         Result = PromoteOp(Node->getOperand(0));
896         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
897                              Result, Node->getOperand(0).getValueType());
898         Result = DAG.getNode(ISD::SINT_TO_FP, Op.getValueType(), Result);
899         break;
900       case ISD::UINT_TO_FP:
901         Result = PromoteOp(Node->getOperand(0));
902         Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Result.getValueType(),
903                              Result, Node->getOperand(0).getValueType());
904         Result = DAG.getNode(ISD::UINT_TO_FP, Op.getValueType(), Result);
905         break;
906       }
907     }
908     break;
909   case ISD::FP_ROUND_INREG:
910   case ISD::SIGN_EXTEND_INREG:
911   case ISD::ZERO_EXTEND_INREG: {
912     Tmp1 = LegalizeOp(Node->getOperand(0));
913     MVT::ValueType ExtraVT = cast<MVTSDNode>(Node)->getExtraValueType();
914
915     // If this operation is not supported, convert it to a shl/shr or load/store
916     // pair.
917     switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
918     default: assert(0 && "This action not supported for this op yet!");
919     case TargetLowering::Legal:
920       if (Tmp1 != Node->getOperand(0))
921         Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
922                              ExtraVT);
923       break;
924     case TargetLowering::Expand:
925       // If this is an integer extend and shifts are supported, do that.
926       if (Node->getOpcode() == ISD::ZERO_EXTEND_INREG) {
927         // NOTE: we could fall back on load/store here too for targets without
928         // AND.  However, it is doubtful that any exist.
929         // AND out the appropriate bits.
930         SDOperand Mask =
931           DAG.getConstant((1ULL << MVT::getSizeInBits(ExtraVT))-1,
932                           Node->getValueType(0));
933         Result = DAG.getNode(ISD::AND, Node->getValueType(0),
934                              Node->getOperand(0), Mask);
935       } else if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
936         // NOTE: we could fall back on load/store here too for targets without
937         // SAR.  However, it is doubtful that any exist.
938         unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
939                             MVT::getSizeInBits(ExtraVT);
940         SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
941         Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
942                              Node->getOperand(0), ShiftCst);
943         Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
944                              Result, ShiftCst);
945       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
946         // The only way we can lower this is to turn it into a STORETRUNC,
947         // EXTLOAD pair, targetting a temporary location (a stack slot).
948
949         // NOTE: there is a choice here between constantly creating new stack
950         // slots and always reusing the same one.  We currently always create
951         // new ones, as reuse may inhibit scheduling.
952         const Type *Ty = MVT::getTypeForValueType(ExtraVT);
953         unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
954         unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
955         MachineFunction &MF = DAG.getMachineFunction();
956         int SSFI = 
957           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
958         SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
959         Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
960                              Node->getOperand(0), StackSlot, ExtraVT);
961         Result = DAG.getNode(ISD::EXTLOAD, Node->getValueType(0),
962                              Result, StackSlot, ExtraVT);
963       } else {
964         assert(0 && "Unknown op");
965       }
966       Result = LegalizeOp(Result);
967       break;
968     }
969     break;
970   }
971   }
972
973   if (!Op.Val->hasOneUse())
974     AddLegalizedOperand(Op, Result);
975
976   return Result;
977 }
978
979 /// PromoteOp - Given an operation that produces a value in an invalid type,
980 /// promote it to compute the value into a larger type.  The produced value will
981 /// have the correct bits for the low portion of the register, but no guarantee
982 /// is made about the top bits: it may be zero, sign-extended, or garbage.
983 SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
984   MVT::ValueType VT = Op.getValueType();
985   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
986   assert(getTypeAction(VT) == Promote &&
987          "Caller should expand or legalize operands that are not promotable!");
988   assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
989          "Cannot promote to smaller type!");
990
991   std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
992   if (I != PromotedNodes.end()) return I->second;
993
994   SDOperand Tmp1, Tmp2, Tmp3;
995
996   SDOperand Result;
997   SDNode *Node = Op.Val;
998
999   // Promotion needs an optimization step to clean up after it, and is not
1000   // careful to avoid operations the target does not support.  Make sure that
1001   // all generated operations are legalized in the next iteration.
1002   NeedsAnotherIteration = true;
1003
1004   switch (Node->getOpcode()) {
1005   default:
1006     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
1007     assert(0 && "Do not know how to promote this operator!");
1008     abort();
1009   case ISD::Constant:
1010     Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
1011     assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
1012     break;
1013   case ISD::ConstantFP:
1014     Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
1015     assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
1016     break;
1017   case ISD::CopyFromReg:
1018     Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(), NVT,
1019                                 Node->getOperand(0));
1020     // Remember that we legalized the chain.
1021     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1022     break;
1023
1024   case ISD::SETCC:
1025     assert(getTypeAction(TLI.getSetCCResultTy()) == Legal &&
1026            "SetCC type is not legal??");
1027     Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
1028                           TLI.getSetCCResultTy(), Node->getOperand(0),
1029                           Node->getOperand(1));
1030     Result = LegalizeOp(Result);
1031     break;
1032
1033   case ISD::TRUNCATE:
1034     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1035     case Legal:
1036       Result = LegalizeOp(Node->getOperand(0));
1037       assert(Result.getValueType() >= NVT &&
1038              "This truncation doesn't make sense!");
1039       if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
1040         Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
1041       break;
1042     case Promote:
1043       // The truncation is not required, because we don't guarantee anything
1044       // about high bits anyway.
1045       Result = PromoteOp(Node->getOperand(0));
1046       break;
1047     case Expand:
1048       assert(0 && "Cannot handle expand yet");
1049     }
1050     break;
1051   case ISD::SIGN_EXTEND:
1052   case ISD::ZERO_EXTEND:
1053     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1054     case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
1055     case Legal:
1056       // Input is legal?  Just do extend all the way to the larger type.
1057       Result = LegalizeOp(Node->getOperand(0));
1058       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1059       break;
1060     case Promote:
1061       // Promote the reg if it's smaller.
1062       Result = PromoteOp(Node->getOperand(0));
1063       // The high bits are not guaranteed to be anything.  Insert an extend.
1064       if (Node->getOpcode() == ISD::SIGN_EXTEND)
1065         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result, VT);
1066       else
1067         Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Result, VT);
1068       break;
1069     }
1070     break;
1071
1072   case ISD::FP_EXTEND:
1073     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
1074   case ISD::FP_ROUND:
1075     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1076     case Expand: assert(0 && "BUG: Cannot expand FP regs!");
1077     case Promote:  assert(0 && "Unreachable with 2 FP types!");
1078     case Legal:
1079       // Input is legal?  Do an FP_ROUND_INREG.
1080       Result = LegalizeOp(Node->getOperand(0));
1081       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1082       break;
1083     }
1084     break;
1085
1086   case ISD::SINT_TO_FP:
1087   case ISD::UINT_TO_FP:
1088     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1089     case Legal:
1090       Result = LegalizeOp(Node->getOperand(0));
1091       // No extra round required here.
1092       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1093       break;
1094
1095     case Promote:
1096       Result = PromoteOp(Node->getOperand(0));
1097       if (Node->getOpcode() == ISD::SINT_TO_FP)
1098         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1099                              Result, Node->getOperand(0).getValueType());
1100       else
1101         Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Result.getValueType(),
1102                              Result, Node->getOperand(0).getValueType());
1103       // No extra round required here.
1104       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1105       break;
1106     case Expand:
1107       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
1108                              Node->getOperand(0));
1109       Result = LegalizeOp(Result);
1110
1111       // Round if we cannot tolerate excess precision.
1112       if (NoExcessFPPrecision)
1113         Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1114       break;
1115     }
1116     break;
1117
1118   case ISD::FP_TO_SINT:
1119   case ISD::FP_TO_UINT:
1120     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1121     case Legal:
1122       Tmp1 = LegalizeOp(Node->getOperand(0));
1123       break;
1124     case Promote:
1125       // The input result is prerounded, so we don't have to do anything
1126       // special.
1127       Tmp1 = PromoteOp(Node->getOperand(0));
1128       break;
1129     case Expand:
1130       assert(0 && "not implemented");
1131     }
1132     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
1133     break;
1134
1135   case ISD::AND:
1136   case ISD::OR:
1137   case ISD::XOR:
1138   case ISD::ADD:
1139   case ISD::SUB:
1140   case ISD::MUL:
1141     // The input may have strange things in the top bits of the registers, but
1142     // these operations don't care.  They may have wierd bits going out, but
1143     // that too is okay if they are integer operations.
1144     Tmp1 = PromoteOp(Node->getOperand(0));
1145     Tmp2 = PromoteOp(Node->getOperand(1));
1146     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
1147     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1148
1149     // However, if this is a floating point operation, they will give excess
1150     // precision that we may not be able to tolerate.  If we DO allow excess
1151     // precision, just leave it, otherwise excise it.
1152     // FIXME: Why would we need to round FP ops more than integer ones?
1153     //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
1154     if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1155       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1156     break;
1157
1158   case ISD::SDIV:
1159   case ISD::SREM:
1160     // These operators require that their input be sign extended.
1161     Tmp1 = PromoteOp(Node->getOperand(0));
1162     Tmp2 = PromoteOp(Node->getOperand(1));
1163     if (MVT::isInteger(NVT)) {
1164       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
1165       Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2, VT);
1166     }
1167     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1168
1169     // Perform FP_ROUND: this is probably overly pessimistic.
1170     if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1171       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1172     break;
1173
1174   case ISD::UDIV:
1175   case ISD::UREM:
1176     // These operators require that their input be zero extended.
1177     Tmp1 = PromoteOp(Node->getOperand(0));
1178     Tmp2 = PromoteOp(Node->getOperand(1));
1179     assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
1180     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
1181     Tmp2 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp2, VT);
1182     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1183     break;
1184
1185   case ISD::SHL:
1186     Tmp1 = PromoteOp(Node->getOperand(0));
1187     Tmp2 = LegalizeOp(Node->getOperand(1));
1188     Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Tmp2);
1189     break;
1190   case ISD::SRA:
1191     // The input value must be properly sign extended.
1192     Tmp1 = PromoteOp(Node->getOperand(0));
1193     Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
1194     Tmp2 = LegalizeOp(Node->getOperand(1));
1195     Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Tmp2);
1196     break;
1197   case ISD::SRL:
1198     // The input value must be properly zero extended.
1199     Tmp1 = PromoteOp(Node->getOperand(0));
1200     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
1201     Tmp2 = LegalizeOp(Node->getOperand(1));
1202     Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Tmp2);
1203     break;
1204   case ISD::LOAD:
1205     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
1206     Tmp2 = LegalizeOp(Node->getOperand(1));   // Legalize the pointer.
1207     Result = DAG.getNode(ISD::EXTLOAD, NVT, Tmp1, Tmp2, VT);
1208
1209     // Remember that we legalized the chain.
1210     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1211     break;
1212   case ISD::SELECT:
1213     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1214     case Expand: assert(0 && "It's impossible to expand bools");
1215     case Legal:
1216       Tmp1 = LegalizeOp(Node->getOperand(0));// Legalize the condition.
1217       break;
1218     case Promote:
1219       Tmp1 = PromoteOp(Node->getOperand(0)); // Promote the condition.
1220       break;
1221     }
1222     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
1223     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
1224     Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2, Tmp3);
1225     break;
1226   case ISD::CALL: {
1227     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1228     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
1229
1230     std::vector<SDOperand> Ops;
1231     for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i)
1232       Ops.push_back(LegalizeOp(Node->getOperand(i)));
1233
1234     assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
1235            "Can only promote single result calls");
1236     std::vector<MVT::ValueType> RetTyVTs;
1237     RetTyVTs.reserve(2);
1238     RetTyVTs.push_back(NVT);
1239     RetTyVTs.push_back(MVT::Other);
1240     SDNode *NC = DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops);
1241     Result = SDOperand(NC, 0);
1242
1243     // Insert the new chain mapping.
1244     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1245     break;
1246   } 
1247   }
1248
1249   assert(Result.Val && "Didn't set a result!");
1250   AddPromotedOperand(Op, Result);
1251   return Result;
1252 }
1253
1254 /// ExpandAddSub - Find a clever way to expand this add operation into
1255 /// subcomponents.
1256 void SelectionDAGLegalize::ExpandAddSub(bool isAdd, SDOperand LHS,SDOperand RHS,
1257                                         SDOperand &Lo, SDOperand &Hi) {
1258   // Expand the subcomponents.
1259   SDOperand LHSL, LHSH, RHSL, RHSH;
1260   ExpandOp(LHS, LHSL, LHSH);
1261   ExpandOp(RHS, RHSL, RHSH);
1262
1263   // Convert this add to the appropriate ADDC pair.  The low part has no carry
1264   // in.
1265   unsigned Opc = isAdd ? ISD::ADD_PARTS : ISD::SUB_PARTS;
1266   std::vector<SDOperand> Ops;
1267   Ops.push_back(LHSL);
1268   Ops.push_back(LHSH);
1269   Ops.push_back(RHSL);
1270   Ops.push_back(RHSH);
1271   Lo = DAG.getNode(Opc, LHSL.getValueType(), Ops);
1272   Hi = Lo.getValue(1);
1273 }
1274
1275 /// ExpandShift - Try to find a clever way to expand this shift operation out to
1276 /// smaller elements.  If we can't find a way that is more efficient than a
1277 /// libcall on this target, return false.  Otherwise, return true with the
1278 /// low-parts expanded into Lo and Hi.
1279 bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
1280                                        SDOperand &Lo, SDOperand &Hi) {
1281   assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
1282          "This is not a shift!");
1283   MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
1284
1285   // If we have an efficient select operation (or if the selects will all fold
1286   // away), lower to some complex code, otherwise just emit the libcall.
1287   if (TLI.getOperationAction(ISD::SELECT, NVT) != TargetLowering::Legal &&
1288       !isa<ConstantSDNode>(Amt))
1289     return false;
1290
1291   SDOperand InL, InH;
1292   ExpandOp(Op, InL, InH);
1293   SDOperand ShAmt = LegalizeOp(Amt);
1294   MVT::ValueType ShTy = ShAmt.getValueType();
1295   
1296   unsigned NVTBits = MVT::getSizeInBits(NVT);
1297   SDOperand NAmt = DAG.getNode(ISD::SUB, ShTy,           // NAmt = 32-ShAmt
1298                                DAG.getConstant(NVTBits, ShTy), ShAmt);
1299
1300   // Compare the unmasked shift amount against 32.
1301   SDOperand Cond = DAG.getSetCC(ISD::SETGE, TLI.getSetCCResultTy(), ShAmt,
1302                                 DAG.getConstant(NVTBits, ShTy));
1303
1304   if (TLI.getShiftAmountFlavor() != TargetLowering::Mask) {
1305     ShAmt = DAG.getNode(ISD::AND, ShTy, ShAmt,             // ShAmt &= 31
1306                         DAG.getConstant(NVTBits-1, ShTy));
1307     NAmt  = DAG.getNode(ISD::AND, ShTy, NAmt,              // NAmt &= 31
1308                         DAG.getConstant(NVTBits-1, ShTy));
1309   }
1310
1311   if (Opc == ISD::SHL) {
1312     SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << Amt) | (Lo >> NAmt)
1313                                DAG.getNode(ISD::SHL, NVT, InH, ShAmt),
1314                                DAG.getNode(ISD::SRL, NVT, InL, NAmt));
1315     SDOperand T2 = DAG.getNode(ISD::SHL, NVT, InL, ShAmt); // T2 = Lo << Amt&31
1316     
1317     Hi = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
1318     Lo = DAG.getNode(ISD::SELECT, NVT, Cond, DAG.getConstant(0, NVT), T2);
1319   } else {
1320     SDOperand HiLoPart = DAG.getNode(ISD::SELECT, NVT,
1321                                      DAG.getSetCC(ISD::SETEQ,
1322                                                   TLI.getSetCCResultTy(), NAmt,
1323                                                   DAG.getConstant(32, ShTy)),
1324                                      DAG.getConstant(0, NVT),
1325                                      DAG.getNode(ISD::SHL, NVT, InH, NAmt));
1326     SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << NAmt) | (Lo >> Amt)
1327                                HiLoPart,
1328                                DAG.getNode(ISD::SRL, NVT, InL, ShAmt));
1329     SDOperand T2 = DAG.getNode(Opc, NVT, InH, ShAmt);  // T2 = InH >> ShAmt&31
1330
1331     SDOperand HiPart;
1332     if (Opc == ISD::SRA)
1333       HiPart = DAG.getNode(ISD::SRA, NVT, InH,
1334                            DAG.getConstant(NVTBits-1, ShTy));
1335     else
1336       HiPart = DAG.getConstant(0, NVT);
1337     Lo = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
1338     Hi = DAG.getNode(ISD::SELECT, NVT, Cond, HiPart, T2);
1339   }
1340   return true;
1341 }
1342
1343 /// FindLatestAdjCallStackDown - Scan up the dag to find the latest (highest
1344 /// NodeDepth) node that is an AdjCallStackDown operation and occurs later than
1345 /// Found.
1346 static void FindLatestAdjCallStackDown(SDNode *Node, SDNode *&Found) {
1347   if (Node->getNodeDepth() <= Found->getNodeDepth()) return;
1348
1349   // If we found an ADJCALLSTACKDOWN, we already know this node occurs later
1350   // than the Found node. Just remember this node and return.
1351   if (Node->getOpcode() == ISD::ADJCALLSTACKDOWN) {
1352     Found = Node;
1353     return;
1354   }
1355
1356   // Otherwise, scan the operands of Node to see if any of them is a call.
1357   assert(Node->getNumOperands() != 0 &&
1358          "All leaves should have depth equal to the entry node!");
1359   for (unsigned i = 0, e = Node->getNumOperands()-1; i != e; ++i)
1360     FindLatestAdjCallStackDown(Node->getOperand(i).Val, Found);
1361
1362   // Tail recurse for the last iteration.
1363   FindLatestAdjCallStackDown(Node->getOperand(Node->getNumOperands()-1).Val,
1364                              Found);
1365 }
1366
1367
1368 /// FindEarliestAdjCallStackUp - Scan down the dag to find the earliest (lowest
1369 /// NodeDepth) node that is an AdjCallStackUp operation and occurs more recent
1370 /// than Found.
1371 static void FindEarliestAdjCallStackUp(SDNode *Node, SDNode *&Found) {
1372   if (Found && Node->getNodeDepth() >= Found->getNodeDepth()) return;
1373
1374   // If we found an ADJCALLSTACKUP, we already know this node occurs earlier
1375   // than the Found node. Just remember this node and return.
1376   if (Node->getOpcode() == ISD::ADJCALLSTACKUP) {
1377     Found = Node;
1378     return;
1379   }
1380
1381   // Otherwise, scan the operands of Node to see if any of them is a call.
1382   SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
1383   if (UI == E) return;
1384   for (--E; UI != E; ++UI)
1385     FindEarliestAdjCallStackUp(*UI, Found);
1386
1387   // Tail recurse for the last iteration.
1388   FindEarliestAdjCallStackUp(*UI, Found);
1389 }
1390
1391 /// FindAdjCallStackUp - Given a chained node that is part of a call sequence,
1392 /// find the ADJCALLSTACKUP node that terminates the call sequence.
1393 static SDNode *FindAdjCallStackUp(SDNode *Node) {
1394   if (Node->getOpcode() == ISD::ADJCALLSTACKUP)
1395     return Node;
1396   assert(!Node->use_empty() && "Could not find ADJCALLSTACKUP!");
1397
1398   if (Node->hasOneUse())  // Simple case, only has one user to check.
1399     return FindAdjCallStackUp(*Node->use_begin());
1400   
1401   SDOperand TheChain(Node, Node->getNumValues()-1);
1402   assert(TheChain.getValueType() == MVT::Other && "Is not a token chain!");
1403   
1404   for (SDNode::use_iterator UI = Node->use_begin(), 
1405          E = Node->use_end(); ; ++UI) {
1406     assert(UI != E && "Didn't find a user of the tokchain, no ADJCALLSTACKUP!");
1407     
1408     // Make sure to only follow users of our token chain.
1409     SDNode *User = *UI;
1410     for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
1411       if (User->getOperand(i) == TheChain)
1412         return FindAdjCallStackUp(User);
1413   }
1414   assert(0 && "Unreachable");
1415   abort();
1416 }
1417
1418 /// FindInputOutputChains - If we are replacing an operation with a call we need
1419 /// to find the call that occurs before and the call that occurs after it to
1420 /// properly serialize the calls in the block.
1421 static SDOperand FindInputOutputChains(SDNode *OpNode, SDNode *&OutChain,
1422                                        SDOperand Entry) {
1423   SDNode *LatestAdjCallStackDown = Entry.Val;
1424   FindLatestAdjCallStackDown(OpNode, LatestAdjCallStackDown);
1425   //std::cerr << "Found node: "; LatestAdjCallStackDown->dump(); std::cerr <<"\n";
1426
1427   SDNode *LatestAdjCallStackUp = FindAdjCallStackUp(LatestAdjCallStackDown);
1428
1429
1430   SDNode *EarliestAdjCallStackUp = 0;
1431   FindEarliestAdjCallStackUp(OpNode, EarliestAdjCallStackUp);
1432
1433   if (EarliestAdjCallStackUp) {
1434     //std::cerr << "Found node: "; 
1435     //EarliestAdjCallStackUp->dump(); std::cerr <<"\n";
1436   }
1437
1438   return SDOperand(LatestAdjCallStackUp, 0);
1439 }
1440
1441
1442
1443 // ExpandLibCall - Expand a node into a call to a libcall.  If the result value
1444 // does not fit into a register, return the lo part and set the hi part to the
1445 // by-reg argument.  If it does fit into a single register, return the result
1446 // and leave the Hi part unset.
1447 SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
1448                                               SDOperand &Hi) {
1449   SDNode *OutChain;
1450   SDOperand InChain = FindInputOutputChains(Node, OutChain,
1451                                             DAG.getEntryNode());
1452   // TODO.  Link in chains.
1453
1454   TargetLowering::ArgListTy Args;
1455   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1456     MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
1457     const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
1458     Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
1459   }
1460   SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
1461   
1462   // We don't care about token chains for libcalls.  We just use the entry
1463   // node as our input and ignore the output chain.  This allows us to place
1464   // calls wherever we need them to satisfy data dependences.
1465   const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
1466   SDOperand Result = TLI.LowerCallTo(InChain, RetTy, Callee,
1467                                      Args, DAG).first;
1468   switch (getTypeAction(Result.getValueType())) {
1469   default: assert(0 && "Unknown thing");
1470   case Legal:
1471     return Result;
1472   case Promote:
1473     assert(0 && "Cannot promote this yet!");
1474   case Expand:
1475     SDOperand Lo;
1476     ExpandOp(Result, Lo, Hi);
1477     return Lo;
1478   }
1479 }
1480
1481
1482 /// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
1483 /// destination type is legal.
1484 SDOperand SelectionDAGLegalize::
1485 ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
1486   assert(getTypeAction(DestTy) == Legal && "Destination type is not legal!");
1487   assert(getTypeAction(Source.getValueType()) == Expand &&
1488          "This is not an expansion!");
1489   assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
1490
1491   SDNode *OutChain;
1492   SDOperand InChain = FindInputOutputChains(Source.Val, OutChain,
1493                                             DAG.getEntryNode());
1494
1495   const char *FnName = 0;
1496   if (isSigned) {
1497     if (DestTy == MVT::f32)
1498       FnName = "__floatdisf";
1499     else {
1500       assert(DestTy == MVT::f64 && "Unknown fp value type!");
1501       FnName = "__floatdidf";
1502     }
1503   } else {
1504     // If this is unsigned, and not supported, first perform the conversion to
1505     // signed, then adjust the result if the sign bit is set.
1506     SDOperand SignedConv = ExpandIntToFP(false, DestTy, Source);
1507
1508     assert(0 && "Unsigned casts not supported yet!");
1509   }
1510   SDOperand Callee = DAG.getExternalSymbol(FnName, TLI.getPointerTy());
1511
1512   TargetLowering::ArgListTy Args;
1513   const Type *ArgTy = MVT::getTypeForValueType(Source.getValueType());
1514   Args.push_back(std::make_pair(Source, ArgTy));
1515
1516   // We don't care about token chains for libcalls.  We just use the entry
1517   // node as our input and ignore the output chain.  This allows us to place
1518   // calls wherever we need them to satisfy data dependences.
1519   const Type *RetTy = MVT::getTypeForValueType(DestTy);
1520   return TLI.LowerCallTo(InChain, RetTy, Callee, Args, DAG).first;
1521                          
1522 }
1523                    
1524
1525
1526 /// ExpandOp - Expand the specified SDOperand into its two component pieces
1527 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
1528 /// LegalizeNodes map is filled in for any results that are not expanded, the
1529 /// ExpandedNodes map is filled in for any results that are expanded, and the
1530 /// Lo/Hi values are returned.
1531 void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
1532   MVT::ValueType VT = Op.getValueType();
1533   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1534   SDNode *Node = Op.Val;
1535   assert(getTypeAction(VT) == Expand && "Not an expanded type!");
1536   assert(MVT::isInteger(VT) && "Cannot expand FP values!");
1537   assert(MVT::isInteger(NVT) && NVT < VT &&
1538          "Cannot expand to FP value or to larger int value!");
1539
1540   // If there is more than one use of this, see if we already expanded it.
1541   // There is no use remembering values that only have a single use, as the map
1542   // entries will never be reused.
1543   if (!Node->hasOneUse()) {
1544     std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
1545       = ExpandedNodes.find(Op);
1546     if (I != ExpandedNodes.end()) {
1547       Lo = I->second.first;
1548       Hi = I->second.second;
1549       return;
1550     }
1551   }
1552
1553   // Expanding to multiple registers needs to perform an optimization step, and
1554   // is not careful to avoid operations the target does not support.  Make sure
1555   // that all generated operations are legalized in the next iteration.
1556   NeedsAnotherIteration = true;
1557
1558   switch (Node->getOpcode()) {
1559   default:
1560     std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
1561     assert(0 && "Do not know how to expand this operator!");
1562     abort();
1563   case ISD::Constant: {
1564     uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
1565     Lo = DAG.getConstant(Cst, NVT);
1566     Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
1567     break;
1568   }
1569
1570   case ISD::CopyFromReg: {
1571     unsigned Reg = cast<RegSDNode>(Node)->getReg();
1572     // Aggregate register values are always in consequtive pairs.
1573     Lo = DAG.getCopyFromReg(Reg, NVT, Node->getOperand(0));
1574     Hi = DAG.getCopyFromReg(Reg+1, NVT, Lo.getValue(1));
1575     
1576     // Remember that we legalized the chain.
1577     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
1578
1579     assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
1580     break;
1581   }
1582
1583   case ISD::LOAD: {
1584     SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
1585     SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1586     Lo = DAG.getLoad(NVT, Ch, Ptr);
1587
1588     // Increment the pointer to the other half.
1589     unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
1590     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
1591                       getIntPtrConstant(IncrementSize));
1592     Hi = DAG.getLoad(NVT, Ch, Ptr);
1593
1594     // Build a factor node to remember that this load is independent of the
1595     // other one.
1596     SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
1597                                Hi.getValue(1));
1598     
1599     // Remember that we legalized the chain.
1600     AddLegalizedOperand(Op.getValue(1), TF);
1601     if (!TLI.isLittleEndian())
1602       std::swap(Lo, Hi);
1603     break;
1604   }
1605   case ISD::CALL: {
1606     SDOperand Chain  = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1607     SDOperand Callee = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
1608
1609     bool Changed = false;
1610     std::vector<SDOperand> Ops;
1611     for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
1612       Ops.push_back(LegalizeOp(Node->getOperand(i)));
1613       Changed |= Ops.back() != Node->getOperand(i);
1614     }
1615
1616     assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
1617            "Can only expand a call once so far, not i64 -> i16!");
1618
1619     std::vector<MVT::ValueType> RetTyVTs;
1620     RetTyVTs.reserve(3);
1621     RetTyVTs.push_back(NVT);
1622     RetTyVTs.push_back(NVT);
1623     RetTyVTs.push_back(MVT::Other);
1624     SDNode *NC = DAG.getCall(RetTyVTs, Chain, Callee, Ops);
1625     Lo = SDOperand(NC, 0);
1626     Hi = SDOperand(NC, 1);
1627
1628     // Insert the new chain mapping.
1629     AddLegalizedOperand(Op.getValue(1), Hi.getValue(2));
1630     break;
1631   }
1632   case ISD::AND:
1633   case ISD::OR:
1634   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
1635     SDOperand LL, LH, RL, RH;
1636     ExpandOp(Node->getOperand(0), LL, LH);
1637     ExpandOp(Node->getOperand(1), RL, RH);
1638     Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
1639     Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
1640     break;
1641   }
1642   case ISD::SELECT: {
1643     SDOperand C, LL, LH, RL, RH;
1644
1645     switch (getTypeAction(Node->getOperand(0).getValueType())) {
1646     case Expand: assert(0 && "It's impossible to expand bools");
1647     case Legal:
1648       C = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1649       break;
1650     case Promote:
1651       C = PromoteOp(Node->getOperand(0));  // Promote the condition.
1652       break;
1653     }
1654     ExpandOp(Node->getOperand(1), LL, LH);
1655     ExpandOp(Node->getOperand(2), RL, RH);
1656     Lo = DAG.getNode(ISD::SELECT, NVT, C, LL, RL);
1657     Hi = DAG.getNode(ISD::SELECT, NVT, C, LH, RH);
1658     break;
1659   }
1660   case ISD::SIGN_EXTEND: {
1661     // The low part is just a sign extension of the input (which degenerates to
1662     // a copy).
1663     Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, LegalizeOp(Node->getOperand(0)));
1664     
1665     // The high part is obtained by SRA'ing all but one of the bits of the lo
1666     // part.
1667     unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
1668     Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
1669                                                        TLI.getShiftAmountTy()));
1670     break;
1671   }
1672   case ISD::ZERO_EXTEND:
1673     // The low part is just a zero extension of the input (which degenerates to
1674     // a copy).
1675     Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, LegalizeOp(Node->getOperand(0)));
1676     
1677     // The high part is just a zero.
1678     Hi = DAG.getConstant(0, NVT);
1679     break;
1680
1681     // These operators cannot be expanded directly, emit them as calls to
1682     // library functions.
1683   case ISD::FP_TO_SINT:
1684     if (Node->getOperand(0).getValueType() == MVT::f32)
1685       Lo = ExpandLibCall("__fixsfdi", Node, Hi);
1686     else
1687       Lo = ExpandLibCall("__fixdfdi", Node, Hi);
1688     break;
1689   case ISD::FP_TO_UINT:
1690     if (Node->getOperand(0).getValueType() == MVT::f32)
1691       Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
1692     else
1693       Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
1694     break;
1695
1696   case ISD::SHL:
1697     // If we can emit an efficient shift operation, do so now.
1698     if (ExpandShift(ISD::SHL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
1699       break;
1700     // Otherwise, emit a libcall.
1701     Lo = ExpandLibCall("__ashldi3", Node, Hi);
1702     break;
1703
1704   case ISD::SRA:
1705     // If we can emit an efficient shift operation, do so now.
1706     if (ExpandShift(ISD::SRA, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
1707       break;
1708     // Otherwise, emit a libcall.
1709     Lo = ExpandLibCall("__ashrdi3", Node, Hi);
1710     break;
1711   case ISD::SRL:
1712     // If we can emit an efficient shift operation, do so now.
1713     if (ExpandShift(ISD::SRL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
1714       break;
1715     // Otherwise, emit a libcall.
1716     Lo = ExpandLibCall("__lshrdi3", Node, Hi);
1717     break;
1718
1719   case ISD::ADD:
1720     ExpandAddSub(true, Node->getOperand(0), Node->getOperand(1), Lo, Hi);
1721     break;
1722   case ISD::SUB:
1723     ExpandAddSub(false, Node->getOperand(0), Node->getOperand(1), Lo, Hi);
1724     break;
1725   case ISD::MUL:  Lo = ExpandLibCall("__muldi3" , Node, Hi); break;
1726   case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
1727   case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
1728   case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
1729   case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
1730   }
1731
1732   // Remember in a map if the values will be reused later.
1733   if (!Node->hasOneUse()) {
1734     bool isNew = ExpandedNodes.insert(std::make_pair(Op,
1735                                             std::make_pair(Lo, Hi))).second;
1736     assert(isNew && "Value already expanded?!?");
1737   }
1738 }
1739
1740
1741 // SelectionDAG::Legalize - This is the entry point for the file.
1742 //
1743 void SelectionDAG::Legalize() {
1744   /// run - This is the main entry point to this class.
1745   ///
1746   SelectionDAGLegalize(*this).Run();
1747 }
1748