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