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