Switch targets over to using SelectionDAG::getCALLSEQ_START to create
[oota-llvm.git] / lib / Target / Sparc / SparcISelDAGToDAG.cpp
1 //===-- SparcISelDAGToDAG.cpp - A dag to dag inst selector for Sparc ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines an instruction selector for the SPARC target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Sparc.h"
15 #include "SparcTargetMachine.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/CodeGen/SelectionDAGISel.h"
23 #include "llvm/CodeGen/SSARegMap.h"
24 #include "llvm/Target/TargetLowering.h"
25 #include "llvm/Support/Debug.h"
26 #include <iostream>
27 #include <set>
28 using namespace llvm;
29
30 //===----------------------------------------------------------------------===//
31 // TargetLowering Implementation
32 //===----------------------------------------------------------------------===//
33
34 namespace SPISD {
35   enum {
36     FIRST_NUMBER = ISD::BUILTIN_OP_END+SP::INSTRUCTION_LIST_END,
37     CMPICC,      // Compare two GPR operands, set icc.
38     CMPFCC,      // Compare two FP operands, set fcc.
39     BRICC,       // Branch to dest on icc condition
40     BRFCC,       // Branch to dest on fcc condition
41     SELECT_ICC,  // Select between two values using the current ICC flags.
42     SELECT_FCC,  // Select between two values using the current FCC flags.
43     
44     Hi, Lo,      // Hi/Lo operations, typically on a global address.
45     
46     FTOI,        // FP to Int within a FP register.
47     ITOF,        // Int to FP within a FP register.
48
49     CALL,        // A call instruction.
50     RET_FLAG,    // Return with a flag operand.
51   };
52 }
53
54 /// IntCondCCodeToICC - Convert a DAG integer condition code to a SPARC ICC
55 /// condition.
56 static SPCC::CondCodes IntCondCCodeToICC(ISD::CondCode CC) {
57   switch (CC) {
58   default: assert(0 && "Unknown integer condition code!");
59   case ISD::SETEQ:  return SPCC::ICC_E;
60   case ISD::SETNE:  return SPCC::ICC_NE;
61   case ISD::SETLT:  return SPCC::ICC_L;
62   case ISD::SETGT:  return SPCC::ICC_G;
63   case ISD::SETLE:  return SPCC::ICC_LE;
64   case ISD::SETGE:  return SPCC::ICC_GE;
65   case ISD::SETULT: return SPCC::ICC_CS;
66   case ISD::SETULE: return SPCC::ICC_LEU;
67   case ISD::SETUGT: return SPCC::ICC_GU;
68   case ISD::SETUGE: return SPCC::ICC_CC;
69   }
70 }
71
72 /// FPCondCCodeToFCC - Convert a DAG floatingp oint condition code to a SPARC
73 /// FCC condition.
74 static SPCC::CondCodes FPCondCCodeToFCC(ISD::CondCode CC) {
75   switch (CC) {
76   default: assert(0 && "Unknown fp condition code!");
77   case ISD::SETEQ:  return SPCC::FCC_E;
78   case ISD::SETNE:  return SPCC::FCC_NE;
79   case ISD::SETLT:  return SPCC::FCC_L;
80   case ISD::SETGT:  return SPCC::FCC_G;
81   case ISD::SETLE:  return SPCC::FCC_LE;
82   case ISD::SETGE:  return SPCC::FCC_GE;
83   case ISD::SETULT: return SPCC::FCC_UL;
84   case ISD::SETULE: return SPCC::FCC_ULE;
85   case ISD::SETUGT: return SPCC::FCC_UG;
86   case ISD::SETUGE: return SPCC::FCC_UGE;
87   case ISD::SETUO:  return SPCC::FCC_U;
88   case ISD::SETO:   return SPCC::FCC_O;
89   case ISD::SETONE: return SPCC::FCC_LG;
90   case ISD::SETUEQ: return SPCC::FCC_UE;
91   }
92 }
93
94 namespace {
95   class SparcTargetLowering : public TargetLowering {
96     int VarArgsFrameOffset;   // Frame offset to start of varargs area.
97   public:
98     SparcTargetLowering(TargetMachine &TM);
99     virtual SDOperand LowerOperation(SDOperand Op, SelectionDAG &DAG);
100     
101     /// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
102     /// be zero. Op is expected to be a target specific node. Used by DAG
103     /// combiner.
104     virtual bool isMaskedValueZeroForTargetNode(const SDOperand &Op,
105                                                 uint64_t Mask) const;
106     
107     virtual std::vector<SDOperand>
108       LowerArguments(Function &F, SelectionDAG &DAG);
109     virtual std::pair<SDOperand, SDOperand>
110       LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
111                   unsigned CC,
112                   bool isTailCall, SDOperand Callee, ArgListTy &Args,
113                   SelectionDAG &DAG);
114     virtual MachineBasicBlock *InsertAtEndOfBasicBlock(MachineInstr *MI,
115                                                        MachineBasicBlock *MBB);
116     
117     virtual const char *getTargetNodeName(unsigned Opcode) const;
118   };
119 }
120
121 SparcTargetLowering::SparcTargetLowering(TargetMachine &TM)
122   : TargetLowering(TM) {
123   
124   // Set up the register classes.
125   addRegisterClass(MVT::i32, SP::IntRegsRegisterClass);
126   addRegisterClass(MVT::f32, SP::FPRegsRegisterClass);
127   addRegisterClass(MVT::f64, SP::DFPRegsRegisterClass);
128
129   // Custom legalize GlobalAddress nodes into LO/HI parts.
130   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
131   setOperationAction(ISD::ConstantPool , MVT::i32, Custom);
132   
133   // Sparc doesn't have sext_inreg, replace them with shl/sra
134   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
135   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
136   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
137
138   // Sparc has no REM operation.
139   setOperationAction(ISD::UREM, MVT::i32, Expand);
140   setOperationAction(ISD::SREM, MVT::i32, Expand);
141
142   // Custom expand fp<->sint
143   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
144   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
145
146   // Expand fp<->uint
147   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
148   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
149   
150   setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
151   setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
152   
153   // Turn FP extload into load/fextend
154   setOperationAction(ISD::EXTLOAD, MVT::f32, Expand);
155   
156   // Sparc has no select or setcc: expand to SELECT_CC.
157   setOperationAction(ISD::SELECT, MVT::i32, Expand);
158   setOperationAction(ISD::SELECT, MVT::f32, Expand);
159   setOperationAction(ISD::SELECT, MVT::f64, Expand);
160   setOperationAction(ISD::SETCC, MVT::i32, Expand);
161   setOperationAction(ISD::SETCC, MVT::f32, Expand);
162   setOperationAction(ISD::SETCC, MVT::f64, Expand);
163   
164   // Sparc doesn't have BRCOND either, it has BR_CC.
165   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
166   setOperationAction(ISD::BRCONDTWOWAY, MVT::Other, Expand);
167   setOperationAction(ISD::BRTWOWAY_CC, MVT::Other, Expand);
168   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
169   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
170   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
171   
172   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
173   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
174   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
175   
176   // SPARC has no intrinsics for these particular operations.
177   setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
178   setOperationAction(ISD::MEMSET, MVT::Other, Expand);
179   setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
180   
181   setOperationAction(ISD::FSIN , MVT::f64, Expand);
182   setOperationAction(ISD::FCOS , MVT::f64, Expand);
183   setOperationAction(ISD::FSIN , MVT::f32, Expand);
184   setOperationAction(ISD::FCOS , MVT::f32, Expand);
185   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
186   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
187   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
188   setOperationAction(ISD::ROTL , MVT::i32, Expand);
189   setOperationAction(ISD::ROTR , MVT::i32, Expand);
190   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
191
192   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
193   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
194   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
195
196   // We don't have line number support yet.
197   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
198   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
199   setOperationAction(ISD::DEBUG_LABEL, MVT::Other, Expand);
200
201   // RET must be custom lowered, to meet ABI requirements
202   setOperationAction(ISD::RET               , MVT::Other, Custom);
203   
204   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
205   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
206   // VAARG needs to be lowered to not do unaligned accesses for doubles.
207   setOperationAction(ISD::VAARG             , MVT::Other, Custom);
208   
209   // Use the default implementation.
210   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
211   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
212   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand); 
213   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
214   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Expand);
215
216   setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
217   setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
218   
219   setStackPointerRegisterToSaveRestore(SP::O6);
220
221   if (TM.getSubtarget<SparcSubtarget>().isV9()) {
222     setOperationAction(ISD::CTPOP, MVT::i32, Legal);
223   }
224   
225   computeRegisterProperties();
226 }
227
228 const char *SparcTargetLowering::getTargetNodeName(unsigned Opcode) const {
229   switch (Opcode) {
230   default: return 0;
231   case SPISD::CMPICC:     return "SPISD::CMPICC";
232   case SPISD::CMPFCC:     return "SPISD::CMPFCC";
233   case SPISD::BRICC:      return "SPISD::BRICC";
234   case SPISD::BRFCC:      return "SPISD::BRFCC";
235   case SPISD::SELECT_ICC: return "SPISD::SELECT_ICC";
236   case SPISD::SELECT_FCC: return "SPISD::SELECT_FCC";
237   case SPISD::Hi:         return "SPISD::Hi";
238   case SPISD::Lo:         return "SPISD::Lo";
239   case SPISD::FTOI:       return "SPISD::FTOI";
240   case SPISD::ITOF:       return "SPISD::ITOF";
241   case SPISD::CALL:       return "SPISD::CALL";
242   case SPISD::RET_FLAG:   return "SPISD::RET_FLAG";
243   }
244 }
245
246 /// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
247 /// be zero. Op is expected to be a target specific node. Used by DAG
248 /// combiner.
249 bool SparcTargetLowering::
250 isMaskedValueZeroForTargetNode(const SDOperand &Op, uint64_t Mask) const {
251   switch (Op.getOpcode()) {
252   default: return false; 
253   case SPISD::SELECT_ICC:
254   case SPISD::SELECT_FCC:
255     assert(MVT::isInteger(Op.getValueType()) && "Not an integer select!");
256     // These operations are masked zero if both the left and the right are zero.
257     return MaskedValueIsZero(Op.getOperand(0), Mask) &&
258            MaskedValueIsZero(Op.getOperand(1), Mask);
259   }
260 }
261
262
263 /// LowerArguments - V8 uses a very simple ABI, where all values are passed in
264 /// either one or two GPRs, including FP values.  TODO: we should pass FP values
265 /// in FP registers for fastcc functions.
266 std::vector<SDOperand>
267 SparcTargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
268   MachineFunction &MF = DAG.getMachineFunction();
269   SSARegMap *RegMap = MF.getSSARegMap();
270   std::vector<SDOperand> ArgValues;
271   
272   static const unsigned ArgRegs[] = {
273     SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
274   };
275   
276   const unsigned *CurArgReg = ArgRegs, *ArgRegEnd = ArgRegs+6;
277   unsigned ArgOffset = 68;
278   
279   SDOperand Root = DAG.getRoot();
280   std::vector<SDOperand> OutChains;
281
282   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
283     MVT::ValueType ObjectVT = getValueType(I->getType());
284     
285     switch (ObjectVT) {
286     default: assert(0 && "Unhandled argument type!");
287     case MVT::i1:
288     case MVT::i8:
289     case MVT::i16:
290     case MVT::i32:
291       if (I->use_empty()) {                // Argument is dead.
292         if (CurArgReg < ArgRegEnd) ++CurArgReg;
293         ArgValues.push_back(DAG.getNode(ISD::UNDEF, ObjectVT));
294       } else if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
295         unsigned VReg = RegMap->createVirtualRegister(&SP::IntRegsRegClass);
296         MF.addLiveIn(*CurArgReg++, VReg);
297         SDOperand Arg = DAG.getCopyFromReg(Root, VReg, MVT::i32);
298         if (ObjectVT != MVT::i32) {
299           unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext 
300                                                        : ISD::AssertZext;
301           Arg = DAG.getNode(AssertOp, MVT::i32, Arg, 
302                             DAG.getValueType(ObjectVT));
303           Arg = DAG.getNode(ISD::TRUNCATE, ObjectVT, Arg);
304         }
305         ArgValues.push_back(Arg);
306       } else {
307         int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset);
308         SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
309         SDOperand Load;
310         if (ObjectVT == MVT::i32) {
311           Load = DAG.getLoad(MVT::i32, Root, FIPtr, DAG.getSrcValue(0));
312         } else {
313           unsigned LoadOp =
314             I->getType()->isSigned() ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
315
316           // Sparc is big endian, so add an offset based on the ObjectVT.
317           unsigned Offset = 4-std::max(1U, MVT::getSizeInBits(ObjectVT)/8);
318           FIPtr = DAG.getNode(ISD::ADD, MVT::i32, FIPtr,
319                               DAG.getConstant(Offset, MVT::i32));
320           Load = DAG.getExtLoad(LoadOp, MVT::i32, Root, FIPtr,
321                                 DAG.getSrcValue(0), ObjectVT);
322           Load = DAG.getNode(ISD::TRUNCATE, ObjectVT, Load);
323         }
324         ArgValues.push_back(Load);
325       }
326       
327       ArgOffset += 4;
328       break;
329     case MVT::f32:
330       if (I->use_empty()) {                // Argument is dead.
331         if (CurArgReg < ArgRegEnd) ++CurArgReg;
332         ArgValues.push_back(DAG.getNode(ISD::UNDEF, ObjectVT));
333       } else if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
334         // FP value is passed in an integer register.
335         unsigned VReg = RegMap->createVirtualRegister(&SP::IntRegsRegClass);
336         MF.addLiveIn(*CurArgReg++, VReg);
337         SDOperand Arg = DAG.getCopyFromReg(Root, VReg, MVT::i32);
338
339         Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Arg);
340         ArgValues.push_back(Arg);
341       } else {
342         int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset);
343         SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
344         SDOperand Load = DAG.getLoad(MVT::f32, Root, FIPtr, DAG.getSrcValue(0));
345         ArgValues.push_back(Load);
346       }
347       ArgOffset += 4;
348       break;
349
350     case MVT::i64:
351     case MVT::f64:
352       if (I->use_empty()) {                // Argument is dead.
353         if (CurArgReg < ArgRegEnd) ++CurArgReg;
354         if (CurArgReg < ArgRegEnd) ++CurArgReg;
355         ArgValues.push_back(DAG.getNode(ISD::UNDEF, ObjectVT));
356       } else if (/* FIXME: Apparently this isn't safe?? */
357                  0 && CurArgReg == ArgRegEnd && ObjectVT == MVT::f64 &&
358                  ((CurArgReg-ArgRegs) & 1) == 0) {
359         // If this is a double argument and the whole thing lives on the stack,
360         // and the argument is aligned, load the double straight from the stack.
361         // We can't do a load in cases like void foo([6ints], int,double),
362         // because the double wouldn't be aligned!
363         int FrameIdx = MF.getFrameInfo()->CreateFixedObject(8, ArgOffset);
364         SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
365         ArgValues.push_back(DAG.getLoad(MVT::f64, Root, FIPtr, 
366                                         DAG.getSrcValue(0)));
367       } else {
368         SDOperand HiVal;
369         if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
370           unsigned VRegHi = RegMap->createVirtualRegister(&SP::IntRegsRegClass);
371           MF.addLiveIn(*CurArgReg++, VRegHi);
372           HiVal = DAG.getCopyFromReg(Root, VRegHi, MVT::i32);
373         } else {
374           int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset);
375           SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
376           HiVal = DAG.getLoad(MVT::i32, Root, FIPtr, DAG.getSrcValue(0));
377         }
378         
379         SDOperand LoVal;
380         if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
381           unsigned VRegLo = RegMap->createVirtualRegister(&SP::IntRegsRegClass);
382           MF.addLiveIn(*CurArgReg++, VRegLo);
383           LoVal = DAG.getCopyFromReg(Root, VRegLo, MVT::i32);
384         } else {
385           int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset+4);
386           SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
387           LoVal = DAG.getLoad(MVT::i32, Root, FIPtr, DAG.getSrcValue(0));
388         }
389         
390         // Compose the two halves together into an i64 unit.
391         SDOperand WholeValue = 
392           DAG.getNode(ISD::BUILD_PAIR, MVT::i64, LoVal, HiVal);
393         
394         // If we want a double, do a bit convert.
395         if (ObjectVT == MVT::f64)
396           WholeValue = DAG.getNode(ISD::BIT_CONVERT, MVT::f64, WholeValue);
397         
398         ArgValues.push_back(WholeValue);
399       }
400       ArgOffset += 8;
401       break;
402     }
403   }
404   
405   // Store remaining ArgRegs to the stack if this is a varargs function.
406   if (F.getFunctionType()->isVarArg()) {
407     // Remember the vararg offset for the va_start implementation.
408     VarArgsFrameOffset = ArgOffset;
409     
410     for (; CurArgReg != ArgRegEnd; ++CurArgReg) {
411       unsigned VReg = RegMap->createVirtualRegister(&SP::IntRegsRegClass);
412       MF.addLiveIn(*CurArgReg, VReg);
413       SDOperand Arg = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
414
415       int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset);
416       SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
417
418       OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, DAG.getRoot(),
419                                       Arg, FIPtr, DAG.getSrcValue(0)));
420       ArgOffset += 4;
421     }
422   }
423   
424   if (!OutChains.empty())
425     DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
426   
427   // Finally, inform the code generator which regs we return values in.
428   switch (getValueType(F.getReturnType())) {
429   default: assert(0 && "Unknown type!");
430   case MVT::isVoid: break;
431   case MVT::i1:
432   case MVT::i8:
433   case MVT::i16:
434   case MVT::i32:
435     MF.addLiveOut(SP::I0);
436     break;
437   case MVT::i64:
438     MF.addLiveOut(SP::I0);
439     MF.addLiveOut(SP::I1);
440     break;
441   case MVT::f32:
442     MF.addLiveOut(SP::F0);
443     break;
444   case MVT::f64:
445     MF.addLiveOut(SP::D0);
446     break;
447   }
448   
449   return ArgValues;
450 }
451
452 std::pair<SDOperand, SDOperand>
453 SparcTargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
454                                  bool isVarArg, unsigned CC,
455                                  bool isTailCall, SDOperand Callee, 
456                                  ArgListTy &Args, SelectionDAG &DAG) {
457   MachineFunction &MF = DAG.getMachineFunction();
458   // Count the size of the outgoing arguments.
459   unsigned ArgsSize = 0;
460   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
461     switch (getValueType(Args[i].second)) {
462     default: assert(0 && "Unknown value type!");
463     case MVT::i1:
464     case MVT::i8:
465     case MVT::i16:
466     case MVT::i32:
467     case MVT::f32:
468       ArgsSize += 4;
469       break;
470     case MVT::i64:
471     case MVT::f64:
472       ArgsSize += 8;
473       break;
474     }
475   }
476   if (ArgsSize > 4*6)
477     ArgsSize -= 4*6;    // Space for first 6 arguments is prereserved.
478   else
479     ArgsSize = 0;
480
481   // Keep stack frames 8-byte aligned.
482   ArgsSize = (ArgsSize+7) & ~7;
483
484   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(ArgsSize, getPointerTy()));
485   
486   SDOperand StackPtr, NullSV;
487   std::vector<SDOperand> Stores;
488   std::vector<SDOperand> RegValuesToPass;
489   unsigned ArgOffset = 68;
490   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
491     SDOperand Val = Args[i].first;
492     MVT::ValueType ObjectVT = Val.getValueType();
493     SDOperand ValToStore(0, 0);
494     unsigned ObjSize;
495     switch (ObjectVT) {
496     default: assert(0 && "Unhandled argument type!");
497     case MVT::i1:
498     case MVT::i8:
499     case MVT::i16:
500       // Promote the integer to 32-bits.  If the input type is signed, use a
501       // sign extend, otherwise use a zero extend.
502       if (Args[i].second->isSigned())
503         Val = DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Val);
504       else
505         Val = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Val);
506       // FALL THROUGH
507     case MVT::i32:
508       ObjSize = 4;
509
510       if (RegValuesToPass.size() >= 6) {
511         ValToStore = Val;
512       } else {
513         RegValuesToPass.push_back(Val);
514       }
515       break;
516     case MVT::f32:
517       ObjSize = 4;
518       if (RegValuesToPass.size() >= 6) {
519         ValToStore = Val;
520       } else {
521         // Convert this to a FP value in an int reg.
522         Val = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Val);
523         RegValuesToPass.push_back(Val);
524       }
525       break;
526     case MVT::f64:
527       ObjSize = 8;
528       // If we can store this directly into the outgoing slot, do so.  We can
529       // do this when all ArgRegs are used and if the outgoing slot is aligned.
530       // FIXME: McGill/misr fails with this.
531       if (0 && RegValuesToPass.size() >= 6 && ((ArgOffset-68) & 7) == 0) {
532         ValToStore = Val;
533         break;
534       }
535       
536       // Otherwise, convert this to a FP value in int regs.
537       Val = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Val);
538       // FALL THROUGH
539     case MVT::i64:
540       ObjSize = 8;
541       if (RegValuesToPass.size() >= 6) {
542         ValToStore = Val;    // Whole thing is passed in memory.
543         break;
544       }
545       
546       // Split the value into top and bottom part.  Top part goes in a reg.
547       SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Val, 
548                                  DAG.getConstant(1, MVT::i32));
549       SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Val,
550                                  DAG.getConstant(0, MVT::i32));
551       RegValuesToPass.push_back(Hi);
552       
553       if (RegValuesToPass.size() >= 6) {
554         ValToStore = Lo;
555         ArgOffset += 4;
556         ObjSize = 4;
557       } else {
558         RegValuesToPass.push_back(Lo);
559       }
560       break;
561     }
562     
563     if (ValToStore.Val) {
564       if (!StackPtr.Val) {
565         StackPtr = DAG.getRegister(SP::O6, MVT::i32);
566         NullSV = DAG.getSrcValue(NULL);
567       }
568       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
569       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
570       Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
571                                    ValToStore, PtrOff, NullSV));
572     }
573     ArgOffset += ObjSize;
574   }
575   
576   // Emit all stores, make sure the occur before any copies into physregs.
577   if (!Stores.empty())
578     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
579   
580   static const unsigned ArgRegs[] = {
581     SP::O0, SP::O1, SP::O2, SP::O3, SP::O4, SP::O5
582   };
583   
584   // Build a sequence of copy-to-reg nodes chained together with token chain
585   // and flag operands which copy the outgoing args into O[0-5].
586   SDOperand InFlag;
587   for (unsigned i = 0, e = RegValuesToPass.size(); i != e; ++i) {
588     Chain = DAG.getCopyToReg(Chain, ArgRegs[i], RegValuesToPass[i], InFlag);
589     InFlag = Chain.getValue(1);
590   }
591
592   // If the callee is a GlobalAddress node (quite common, every direct call is)
593   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
594   // Likewise ExternalSymbol -> TargetExternalSymbol.
595   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
596     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
597   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
598     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
599
600   std::vector<MVT::ValueType> NodeTys;
601   NodeTys.push_back(MVT::Other);   // Returns a chain
602   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
603   std::vector<SDOperand> Ops;
604   Ops.push_back(Chain);
605   Ops.push_back(Callee);
606   if (InFlag.Val)
607     Ops.push_back(InFlag);
608   Chain = DAG.getNode(SPISD::CALL, NodeTys, Ops);
609   InFlag = Chain.getValue(1);
610   
611   MVT::ValueType RetTyVT = getValueType(RetTy);
612   SDOperand RetVal;
613   if (RetTyVT != MVT::isVoid) {
614     switch (RetTyVT) {
615     default: assert(0 && "Unknown value type to return!");
616     case MVT::i1:
617     case MVT::i8:
618     case MVT::i16:
619       RetVal = DAG.getCopyFromReg(Chain, SP::O0, MVT::i32, InFlag);
620       Chain = RetVal.getValue(1);
621       
622       // Add a note to keep track of whether it is sign or zero extended.
623       RetVal = DAG.getNode(RetTy->isSigned() ? ISD::AssertSext :ISD::AssertZext,
624                            MVT::i32, RetVal, DAG.getValueType(RetTyVT));
625       RetVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, RetVal);
626       break;
627     case MVT::i32:
628       RetVal = DAG.getCopyFromReg(Chain, SP::O0, MVT::i32, InFlag);
629       Chain = RetVal.getValue(1);
630       break;
631     case MVT::f32:
632       RetVal = DAG.getCopyFromReg(Chain, SP::F0, MVT::f32, InFlag);
633       Chain = RetVal.getValue(1);
634       break;
635     case MVT::f64:
636       RetVal = DAG.getCopyFromReg(Chain, SP::D0, MVT::f64, InFlag);
637       Chain = RetVal.getValue(1);
638       break;
639     case MVT::i64:
640       SDOperand Lo = DAG.getCopyFromReg(Chain, SP::O1, MVT::i32, InFlag);
641       SDOperand Hi = DAG.getCopyFromReg(Lo.getValue(1), SP::O0, MVT::i32, 
642                                         Lo.getValue(2));
643       RetVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi);
644       Chain = Hi.getValue(1);
645       break;
646     }
647   }
648   
649   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, Chain,
650                       DAG.getConstant(ArgsSize, getPointerTy()));
651   
652   return std::make_pair(RetVal, Chain);
653 }
654
655 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
656 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
657 static void LookThroughSetCC(SDOperand &LHS, SDOperand &RHS,
658                              ISD::CondCode CC, unsigned &SPCC) {
659   if (isa<ConstantSDNode>(RHS) && cast<ConstantSDNode>(RHS)->getValue() == 0 &&
660       CC == ISD::SETNE && 
661       ((LHS.getOpcode() == SPISD::SELECT_ICC &&
662         LHS.getOperand(3).getOpcode() == SPISD::CMPICC) ||
663        (LHS.getOpcode() == SPISD::SELECT_FCC &&
664         LHS.getOperand(3).getOpcode() == SPISD::CMPFCC)) &&
665       isa<ConstantSDNode>(LHS.getOperand(0)) &&
666       isa<ConstantSDNode>(LHS.getOperand(1)) &&
667       cast<ConstantSDNode>(LHS.getOperand(0))->getValue() == 1 &&
668       cast<ConstantSDNode>(LHS.getOperand(1))->getValue() == 0) {
669     SDOperand CMPCC = LHS.getOperand(3);
670     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getValue();
671     LHS = CMPCC.getOperand(0);
672     RHS = CMPCC.getOperand(1);
673   }
674 }
675
676
677 SDOperand SparcTargetLowering::
678 LowerOperation(SDOperand Op, SelectionDAG &DAG) {
679   switch (Op.getOpcode()) {
680   default: assert(0 && "Should not custom lower this!");
681   case ISD::GlobalAddress: {
682     GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
683     SDOperand GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
684     SDOperand Hi = DAG.getNode(SPISD::Hi, MVT::i32, GA);
685     SDOperand Lo = DAG.getNode(SPISD::Lo, MVT::i32, GA);
686     return DAG.getNode(ISD::ADD, MVT::i32, Lo, Hi);
687   }
688   case ISD::ConstantPool: {
689     Constant *C = cast<ConstantPoolSDNode>(Op)->get();
690     SDOperand CP = DAG.getTargetConstantPool(C, MVT::i32,
691                                   cast<ConstantPoolSDNode>(Op)->getAlignment());
692     SDOperand Hi = DAG.getNode(SPISD::Hi, MVT::i32, CP);
693     SDOperand Lo = DAG.getNode(SPISD::Lo, MVT::i32, CP);
694     return DAG.getNode(ISD::ADD, MVT::i32, Lo, Hi);
695   }
696   case ISD::FP_TO_SINT:
697     // Convert the fp value to integer in an FP register.
698     assert(Op.getValueType() == MVT::i32);
699     Op = DAG.getNode(SPISD::FTOI, MVT::f32, Op.getOperand(0));
700     return DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
701   case ISD::SINT_TO_FP: {
702     assert(Op.getOperand(0).getValueType() == MVT::i32);
703     SDOperand Tmp = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Op.getOperand(0));
704     // Convert the int value to FP in an FP register.
705     return DAG.getNode(SPISD::ITOF, Op.getValueType(), Tmp);
706   }
707   case ISD::BR_CC: {
708     SDOperand Chain = Op.getOperand(0);
709     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
710     SDOperand LHS = Op.getOperand(2);
711     SDOperand RHS = Op.getOperand(3);
712     SDOperand Dest = Op.getOperand(4);
713     unsigned Opc, SPCC = ~0U;
714     
715     // If this is a br_cc of a "setcc", and if the setcc got lowered into
716     // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
717     LookThroughSetCC(LHS, RHS, CC, SPCC);
718     
719     // Get the condition flag.
720     SDOperand CompareFlag;
721     if (LHS.getValueType() == MVT::i32) {
722       std::vector<MVT::ValueType> VTs;
723       VTs.push_back(MVT::i32);
724       VTs.push_back(MVT::Flag);
725       std::vector<SDOperand> Ops;
726       Ops.push_back(LHS);
727       Ops.push_back(RHS);
728       CompareFlag = DAG.getNode(SPISD::CMPICC, VTs, Ops).getValue(1);
729       if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
730       Opc = SPISD::BRICC;
731     } else {
732       CompareFlag = DAG.getNode(SPISD::CMPFCC, MVT::Flag, LHS, RHS);
733       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
734       Opc = SPISD::BRFCC;
735     }
736     return DAG.getNode(Opc, MVT::Other, Chain, Dest,
737                        DAG.getConstant(SPCC, MVT::i32), CompareFlag);
738   }
739   case ISD::SELECT_CC: {
740     SDOperand LHS = Op.getOperand(0);
741     SDOperand RHS = Op.getOperand(1);
742     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
743     SDOperand TrueVal = Op.getOperand(2);
744     SDOperand FalseVal = Op.getOperand(3);
745     unsigned Opc, SPCC = ~0U;
746
747     // If this is a select_cc of a "setcc", and if the setcc got lowered into
748     // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
749     LookThroughSetCC(LHS, RHS, CC, SPCC);
750     
751     SDOperand CompareFlag;
752     if (LHS.getValueType() == MVT::i32) {
753       std::vector<MVT::ValueType> VTs;
754       VTs.push_back(LHS.getValueType());   // subcc returns a value
755       VTs.push_back(MVT::Flag);
756       std::vector<SDOperand> Ops;
757       Ops.push_back(LHS);
758       Ops.push_back(RHS);
759       CompareFlag = DAG.getNode(SPISD::CMPICC, VTs, Ops).getValue(1);
760       Opc = SPISD::SELECT_ICC;
761       if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
762     } else {
763       CompareFlag = DAG.getNode(SPISD::CMPFCC, MVT::Flag, LHS, RHS);
764       Opc = SPISD::SELECT_FCC;
765       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
766     }
767     return DAG.getNode(Opc, TrueVal.getValueType(), TrueVal, FalseVal, 
768                        DAG.getConstant(SPCC, MVT::i32), CompareFlag);
769   }
770   case ISD::VASTART: {
771     // vastart just stores the address of the VarArgsFrameIndex slot into the
772     // memory location argument.
773     SDOperand Offset = DAG.getNode(ISD::ADD, MVT::i32,
774                                    DAG.getRegister(SP::I6, MVT::i32),
775                                 DAG.getConstant(VarArgsFrameOffset, MVT::i32));
776     return DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), Offset, 
777                        Op.getOperand(1), Op.getOperand(2));
778   }
779   case ISD::VAARG: {
780     SDNode *Node = Op.Val;
781     MVT::ValueType VT = Node->getValueType(0);
782     SDOperand InChain = Node->getOperand(0);
783     SDOperand VAListPtr = Node->getOperand(1);
784     SDOperand VAList = DAG.getLoad(getPointerTy(), InChain, VAListPtr,
785                                    Node->getOperand(2));
786     // Increment the pointer, VAList, to the next vaarg
787     SDOperand NextPtr = DAG.getNode(ISD::ADD, getPointerTy(), VAList, 
788                                     DAG.getConstant(MVT::getSizeInBits(VT)/8, 
789                                                     getPointerTy()));
790     // Store the incremented VAList to the legalized pointer
791     InChain = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), NextPtr,
792                           VAListPtr, Node->getOperand(2));
793     // Load the actual argument out of the pointer VAList, unless this is an
794     // f64 load.
795     if (VT != MVT::f64) {
796       return DAG.getLoad(VT, InChain, VAList, DAG.getSrcValue(0));
797     } else {
798       // Otherwise, load it as i64, then do a bitconvert.
799       SDOperand V = DAG.getLoad(MVT::i64, InChain, VAList, DAG.getSrcValue(0));
800       std::vector<MVT::ValueType> Tys;
801       Tys.push_back(MVT::f64);
802       Tys.push_back(MVT::Other);
803       std::vector<SDOperand> Ops;
804       // Bit-Convert the value to f64.
805       Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, MVT::f64, V));
806       Ops.push_back(V.getValue(1));
807       return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
808     }
809   }
810   case ISD::RET: {
811     SDOperand Copy;
812     
813     switch(Op.getNumOperands()) {
814     default:
815       assert(0 && "Do not know how to return this many arguments!");
816       abort();
817     case 1: 
818       return SDOperand(); // ret void is legal
819     case 2: {
820       unsigned ArgReg;
821       switch(Op.getOperand(1).getValueType()) {
822       default: assert(0 && "Unknown type to return!");
823       case MVT::i32: ArgReg = SP::I0; break;
824       case MVT::f32: ArgReg = SP::F0; break;
825       case MVT::f64: ArgReg = SP::D0; break;
826       }
827       Copy = DAG.getCopyToReg(Op.getOperand(0), ArgReg, Op.getOperand(1),
828                               SDOperand());
829       break;
830     }
831     case 3:
832       Copy = DAG.getCopyToReg(Op.getOperand(0), SP::I0, Op.getOperand(2), 
833                               SDOperand());
834       Copy = DAG.getCopyToReg(Copy, SP::I1, Op.getOperand(1), Copy.getValue(1));
835       break;
836     }
837     return DAG.getNode(SPISD::RET_FLAG, MVT::Other, Copy, Copy.getValue(1));
838   }
839   }
840 }
841
842 MachineBasicBlock *
843 SparcTargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
844                                              MachineBasicBlock *BB) {
845   unsigned BROpcode;
846   unsigned CC;
847   // Figure out the conditional branch opcode to use for this select_cc.
848   switch (MI->getOpcode()) {
849   default: assert(0 && "Unknown SELECT_CC!");
850   case SP::SELECT_CC_Int_ICC:
851   case SP::SELECT_CC_FP_ICC:
852   case SP::SELECT_CC_DFP_ICC:
853     BROpcode = SP::BCOND;
854     break;
855   case SP::SELECT_CC_Int_FCC:
856   case SP::SELECT_CC_FP_FCC:
857   case SP::SELECT_CC_DFP_FCC:
858     BROpcode = SP::FBCOND;
859     break;
860   }
861
862   CC = (SPCC::CondCodes)MI->getOperand(3).getImmedValue();
863   
864   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
865   // control-flow pattern.  The incoming instruction knows the destination vreg
866   // to set, the condition code register to branch on, the true/false values to
867   // select between, and a branch opcode to use.
868   const BasicBlock *LLVM_BB = BB->getBasicBlock();
869   ilist<MachineBasicBlock>::iterator It = BB;
870   ++It;
871   
872   //  thisMBB:
873   //  ...
874   //   TrueVal = ...
875   //   [f]bCC copy1MBB
876   //   fallthrough --> copy0MBB
877   MachineBasicBlock *thisMBB = BB;
878   MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
879   MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
880   BuildMI(BB, BROpcode, 2).addMBB(sinkMBB).addImm(CC);
881   MachineFunction *F = BB->getParent();
882   F->getBasicBlockList().insert(It, copy0MBB);
883   F->getBasicBlockList().insert(It, sinkMBB);
884   // Update machine-CFG edges
885   BB->addSuccessor(copy0MBB);
886   BB->addSuccessor(sinkMBB);
887   
888   //  copy0MBB:
889   //   %FalseValue = ...
890   //   # fallthrough to sinkMBB
891   BB = copy0MBB;
892   
893   // Update machine-CFG edges
894   BB->addSuccessor(sinkMBB);
895   
896   //  sinkMBB:
897   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
898   //  ...
899   BB = sinkMBB;
900   BuildMI(BB, SP::PHI, 4, MI->getOperand(0).getReg())
901     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
902     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
903   
904   delete MI;   // The pseudo instruction is gone now.
905   return BB;
906 }
907   
908 //===----------------------------------------------------------------------===//
909 // Instruction Selector Implementation
910 //===----------------------------------------------------------------------===//
911
912 //===--------------------------------------------------------------------===//
913 /// SparcDAGToDAGISel - SPARC specific code to select SPARC machine
914 /// instructions for SelectionDAG operations.
915 ///
916 namespace {
917 class SparcDAGToDAGISel : public SelectionDAGISel {
918   SparcTargetLowering Lowering;
919
920   /// Subtarget - Keep a pointer to the Sparc Subtarget around so that we can
921   /// make the right decision when generating code for different targets.
922   const SparcSubtarget &Subtarget;
923 public:
924   SparcDAGToDAGISel(TargetMachine &TM)
925     : SelectionDAGISel(Lowering), Lowering(TM),
926       Subtarget(TM.getSubtarget<SparcSubtarget>()) {
927   }
928
929   void Select(SDOperand &Result, SDOperand Op);
930
931   // Complex Pattern Selectors.
932   bool SelectADDRrr(SDOperand N, SDOperand &R1, SDOperand &R2);
933   bool SelectADDRri(SDOperand N, SDOperand &Base, SDOperand &Offset);
934   
935   /// InstructionSelectBasicBlock - This callback is invoked by
936   /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
937   virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
938   
939   virtual const char *getPassName() const {
940     return "SPARC DAG->DAG Pattern Instruction Selection";
941   } 
942   
943   // Include the pieces autogenerated from the target description.
944 #include "SparcGenDAGISel.inc"
945 };
946 }  // end anonymous namespace
947
948 /// InstructionSelectBasicBlock - This callback is invoked by
949 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
950 void SparcDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
951   DEBUG(BB->dump());
952   
953   // Select target instructions for the DAG.
954   DAG.setRoot(SelectRoot(DAG.getRoot()));
955   CodeGenMap.clear();
956   DAG.RemoveDeadNodes();
957   
958   // Emit machine code to BB. 
959   ScheduleAndEmitDAG(DAG);
960 }
961
962 bool SparcDAGToDAGISel::SelectADDRri(SDOperand Addr, SDOperand &Base,
963                                      SDOperand &Offset) {
964   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
965     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
966     Offset = CurDAG->getTargetConstant(0, MVT::i32);
967     return true;
968   }
969   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
970       Addr.getOpcode() == ISD::TargetGlobalAddress)
971     return false;  // direct calls.
972   
973   if (Addr.getOpcode() == ISD::ADD) {
974     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) {
975       if (Predicate_simm13(CN)) {
976         if (FrameIndexSDNode *FIN = 
977                 dyn_cast<FrameIndexSDNode>(Addr.getOperand(0))) {
978           // Constant offset from frame ref.
979           Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
980         } else {
981           Base = Addr.getOperand(0);
982         }
983         Offset = CurDAG->getTargetConstant(CN->getValue(), MVT::i32);
984         return true;
985       }
986     }
987     if (Addr.getOperand(0).getOpcode() == SPISD::Lo) {
988       Base = Addr.getOperand(1);
989       Offset = Addr.getOperand(0).getOperand(0);
990       return true;
991     }
992     if (Addr.getOperand(1).getOpcode() == SPISD::Lo) {
993       Base = Addr.getOperand(0);
994       Offset = Addr.getOperand(1).getOperand(0);
995       return true;
996     }
997   }
998   Base = Addr;
999   Offset = CurDAG->getTargetConstant(0, MVT::i32);
1000   return true;
1001 }
1002
1003 bool SparcDAGToDAGISel::SelectADDRrr(SDOperand Addr, SDOperand &R1, 
1004                                      SDOperand &R2) {
1005   if (Addr.getOpcode() == ISD::FrameIndex) return false;
1006   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
1007       Addr.getOpcode() == ISD::TargetGlobalAddress)
1008     return false;  // direct calls.
1009   
1010   if (Addr.getOpcode() == ISD::ADD) {
1011     if (isa<ConstantSDNode>(Addr.getOperand(1)) &&
1012         Predicate_simm13(Addr.getOperand(1).Val))
1013       return false;  // Let the reg+imm pattern catch this!
1014     if (Addr.getOperand(0).getOpcode() == SPISD::Lo ||
1015         Addr.getOperand(1).getOpcode() == SPISD::Lo)
1016       return false;  // Let the reg+imm pattern catch this!
1017     R1 = Addr.getOperand(0);
1018     R2 = Addr.getOperand(1);
1019     return true;
1020   }
1021
1022   R1 = Addr;
1023   R2 = CurDAG->getRegister(SP::G0, MVT::i32);
1024   return true;
1025 }
1026
1027 void SparcDAGToDAGISel::Select(SDOperand &Result, SDOperand Op) {
1028   SDNode *N = Op.Val;
1029   if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
1030       N->getOpcode() < SPISD::FIRST_NUMBER) {
1031     Result = Op;
1032     return;   // Already selected.
1033   }
1034
1035                  // If this has already been converted, use it.
1036   std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
1037   if (CGMI != CodeGenMap.end()) {
1038     Result = CGMI->second;
1039     return;
1040   }
1041   
1042   switch (N->getOpcode()) {
1043   default: break;
1044   case ISD::ADD_PARTS: {
1045     SDOperand LHSL, LHSH, RHSL, RHSH;
1046     Select(LHSL, N->getOperand(0));
1047     Select(LHSH, N->getOperand(1));
1048     Select(RHSL, N->getOperand(2));
1049     Select(RHSH, N->getOperand(3));
1050     // FIXME, handle immediate RHS.
1051     SDOperand Low =
1052       SDOperand(CurDAG->getTargetNode(SP::ADDCCrr, MVT::i32, MVT::Flag,
1053                                       LHSL, RHSL), 0);
1054     SDOperand Hi =
1055       SDOperand(CurDAG->getTargetNode(SP::ADDXrr, MVT::i32, LHSH, RHSH, 
1056                                       Low.getValue(1)), 0);
1057     CodeGenMap[SDOperand(N, 0)] = Low;
1058     CodeGenMap[SDOperand(N, 1)] = Hi;
1059     Result = Op.ResNo ? Hi : Low;
1060     return;
1061   }
1062   case ISD::SUB_PARTS: {
1063     SDOperand LHSL, LHSH, RHSL, RHSH;
1064     Select(LHSL, N->getOperand(0));
1065     Select(LHSH, N->getOperand(1));
1066     Select(RHSL, N->getOperand(2));
1067     Select(RHSH, N->getOperand(3));
1068     SDOperand Low =
1069       SDOperand(CurDAG->getTargetNode(SP::SUBCCrr, MVT::i32, MVT::Flag,
1070                                       LHSL, RHSL), 0);
1071     SDOperand Hi =
1072       SDOperand(CurDAG->getTargetNode(SP::SUBXrr, MVT::i32, LHSH, RHSH, 
1073                                       Low.getValue(1)), 0);
1074     CodeGenMap[SDOperand(N, 0)] = Low;
1075     CodeGenMap[SDOperand(N, 1)] = Hi;
1076     Result = Op.ResNo ? Hi : Low;
1077     return;
1078   }
1079   case ISD::SDIV:
1080   case ISD::UDIV: {
1081     // FIXME: should use a custom expander to expose the SRA to the dag.
1082     SDOperand DivLHS, DivRHS;
1083     Select(DivLHS, N->getOperand(0));
1084     Select(DivRHS, N->getOperand(1));
1085     
1086     // Set the Y register to the high-part.
1087     SDOperand TopPart;
1088     if (N->getOpcode() == ISD::SDIV) {
1089       TopPart = SDOperand(CurDAG->getTargetNode(SP::SRAri, MVT::i32, DivLHS,
1090                                    CurDAG->getTargetConstant(31, MVT::i32)), 0);
1091     } else {
1092       TopPart = CurDAG->getRegister(SP::G0, MVT::i32);
1093     }
1094     TopPart = SDOperand(CurDAG->getTargetNode(SP::WRYrr, MVT::Flag, TopPart,
1095                                      CurDAG->getRegister(SP::G0, MVT::i32)), 0);
1096
1097     // FIXME: Handle div by immediate.
1098     unsigned Opcode = N->getOpcode() == ISD::SDIV ? SP::SDIVrr : SP::UDIVrr;
1099     Result = CurDAG->SelectNodeTo(N, Opcode, MVT::i32, DivLHS, DivRHS, TopPart);
1100     return;
1101   }    
1102   case ISD::MULHU:
1103   case ISD::MULHS: {
1104     // FIXME: Handle mul by immediate.
1105     SDOperand MulLHS, MulRHS;
1106     Select(MulLHS, N->getOperand(0));
1107     Select(MulRHS, N->getOperand(1));
1108     unsigned Opcode = N->getOpcode() == ISD::MULHU ? SP::UMULrr : SP::SMULrr;
1109     SDNode *Mul = CurDAG->getTargetNode(Opcode, MVT::i32, MVT::Flag,
1110                                         MulLHS, MulRHS);
1111     // The high part is in the Y register.
1112     Result = CurDAG->SelectNodeTo(N, SP::RDY, MVT::i32, SDOperand(Mul, 1));
1113     return;
1114   }
1115   }
1116   
1117   SelectCode(Result, Op);
1118 }
1119
1120
1121 /// createSparcISelDag - This pass converts a legalized DAG into a 
1122 /// SPARC-specific DAG, ready for instruction scheduling.
1123 ///
1124 FunctionPass *llvm::createSparcISelDag(TargetMachine &TM) {
1125   return new SparcDAGToDAGISel(TM);
1126 }