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