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