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