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