]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/Sparc/SparcISelLowering.cpp
Merge sendmail 8.14.7 to HEAD
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / Sparc / SparcISelLowering.cpp
1 //===-- SparcISelLowering.cpp - Sparc DAG Lowering Implementation ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the interfaces that Sparc uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "SparcISelLowering.h"
16 #include "SparcMachineFunctionInfo.h"
17 #include "SparcTargetMachine.h"
18 #include "llvm/CodeGen/CallingConvLower.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/SelectionDAG.h"
24 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/Support/ErrorHandling.h"
29 using namespace llvm;
30
31
32 //===----------------------------------------------------------------------===//
33 // Calling Convention Implementation
34 //===----------------------------------------------------------------------===//
35
36 static bool CC_Sparc_Assign_SRet(unsigned &ValNo, MVT &ValVT,
37                                  MVT &LocVT, CCValAssign::LocInfo &LocInfo,
38                                  ISD::ArgFlagsTy &ArgFlags, CCState &State)
39 {
40   assert (ArgFlags.isSRet());
41
42   //Assign SRet argument
43   State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
44                                          0,
45                                          LocVT, LocInfo));
46   return true;
47 }
48
49 static bool CC_Sparc_Assign_f64(unsigned &ValNo, MVT &ValVT,
50                                 MVT &LocVT, CCValAssign::LocInfo &LocInfo,
51                                 ISD::ArgFlagsTy &ArgFlags, CCState &State)
52 {
53   static const uint16_t RegList[] = {
54     SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
55   };
56   //Try to get first reg
57   if (unsigned Reg = State.AllocateReg(RegList, 6)) {
58     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
59   } else {
60     //Assign whole thing in stack
61     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
62                                            State.AllocateStack(8,4),
63                                            LocVT, LocInfo));
64     return true;
65   }
66
67   //Try to get second reg
68   if (unsigned Reg = State.AllocateReg(RegList, 6))
69     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
70   else
71     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
72                                            State.AllocateStack(4,4),
73                                            LocVT, LocInfo));
74   return true;
75 }
76
77 #include "SparcGenCallingConv.inc"
78
79 SDValue
80 SparcTargetLowering::LowerReturn(SDValue Chain,
81                                  CallingConv::ID CallConv, bool isVarArg,
82                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
83                                  const SmallVectorImpl<SDValue> &OutVals,
84                                  DebugLoc dl, SelectionDAG &DAG) const {
85
86   MachineFunction &MF = DAG.getMachineFunction();
87
88   // CCValAssign - represent the assignment of the return value to locations.
89   SmallVector<CCValAssign, 16> RVLocs;
90
91   // CCState - Info about the registers and stack slot.
92   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
93                  DAG.getTarget(), RVLocs, *DAG.getContext());
94
95   // Analize return values.
96   CCInfo.AnalyzeReturn(Outs, Subtarget->is64Bit() ?
97                              RetCC_Sparc64 : RetCC_Sparc32);
98
99   SDValue Flag;
100   SmallVector<SDValue, 4> RetOps(1, Chain);
101   // Make room for the return address offset.
102   RetOps.push_back(SDValue());
103
104   // Copy the result values into the output registers.
105   for (unsigned i = 0; i != RVLocs.size(); ++i) {
106     CCValAssign &VA = RVLocs[i];
107     assert(VA.isRegLoc() && "Can only return in registers!");
108
109     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
110                              OutVals[i], Flag);
111
112     // Guarantee that all emitted copies are stuck together with flags.
113     Flag = Chain.getValue(1);
114     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
115   }
116
117   unsigned RetAddrOffset = 8; //Call Inst + Delay Slot
118   // If the function returns a struct, copy the SRetReturnReg to I0
119   if (MF.getFunction()->hasStructRetAttr()) {
120     SparcMachineFunctionInfo *SFI = MF.getInfo<SparcMachineFunctionInfo>();
121     unsigned Reg = SFI->getSRetReturnReg();
122     if (!Reg)
123       llvm_unreachable("sret virtual register not created in the entry block");
124     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
125     Chain = DAG.getCopyToReg(Chain, dl, SP::I0, Val, Flag);
126     Flag = Chain.getValue(1);
127     RetOps.push_back(DAG.getRegister(SP::I0, getPointerTy()));
128     RetAddrOffset = 12; // CallInst + Delay Slot + Unimp
129   }
130
131   RetOps[0] = Chain;  // Update chain.
132   RetOps[1] = DAG.getConstant(RetAddrOffset, MVT::i32);
133
134   // Add the flag if we have it.
135   if (Flag.getNode())
136     RetOps.push_back(Flag);
137
138   return DAG.getNode(SPISD::RET_FLAG, dl, MVT::Other,
139                      &RetOps[0], RetOps.size());
140 }
141
142 SDValue SparcTargetLowering::
143 LowerFormalArguments(SDValue Chain,
144                      CallingConv::ID CallConv,
145                      bool IsVarArg,
146                      const SmallVectorImpl<ISD::InputArg> &Ins,
147                      DebugLoc DL,
148                      SelectionDAG &DAG,
149                      SmallVectorImpl<SDValue> &InVals) const {
150   if (Subtarget->is64Bit())
151     return LowerFormalArguments_64(Chain, CallConv, IsVarArg, Ins,
152                                    DL, DAG, InVals);
153   return LowerFormalArguments_32(Chain, CallConv, IsVarArg, Ins,
154                                  DL, DAG, InVals);
155 }
156
157 /// LowerFormalArguments32 - V8 uses a very simple ABI, where all values are
158 /// passed in either one or two GPRs, including FP values.  TODO: we should
159 /// pass FP values in FP registers for fastcc functions.
160 SDValue SparcTargetLowering::
161 LowerFormalArguments_32(SDValue Chain,
162                         CallingConv::ID CallConv,
163                         bool isVarArg,
164                         const SmallVectorImpl<ISD::InputArg> &Ins,
165                         DebugLoc dl,
166                         SelectionDAG &DAG,
167                         SmallVectorImpl<SDValue> &InVals) const {
168   MachineFunction &MF = DAG.getMachineFunction();
169   MachineRegisterInfo &RegInfo = MF.getRegInfo();
170   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
171
172   // Assign locations to all of the incoming arguments.
173   SmallVector<CCValAssign, 16> ArgLocs;
174   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
175                  getTargetMachine(), ArgLocs, *DAG.getContext());
176   CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc32);
177
178   const unsigned StackOffset = 92;
179
180   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
181     CCValAssign &VA = ArgLocs[i];
182
183     if (i == 0  && Ins[i].Flags.isSRet()) {
184       //Get SRet from [%fp+64]
185       int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, 64, true);
186       SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
187       SDValue Arg = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
188                                 MachinePointerInfo(),
189                                 false, false, false, 0);
190       InVals.push_back(Arg);
191       continue;
192     }
193
194     if (VA.isRegLoc()) {
195       if (VA.needsCustom()) {
196         assert(VA.getLocVT() == MVT::f64);
197         unsigned VRegHi = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
198         MF.getRegInfo().addLiveIn(VA.getLocReg(), VRegHi);
199         SDValue HiVal = DAG.getCopyFromReg(Chain, dl, VRegHi, MVT::i32);
200
201         assert(i+1 < e);
202         CCValAssign &NextVA = ArgLocs[++i];
203
204         SDValue LoVal;
205         if (NextVA.isMemLoc()) {
206           int FrameIdx = MF.getFrameInfo()->
207             CreateFixedObject(4, StackOffset+NextVA.getLocMemOffset(),true);
208           SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
209           LoVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
210                               MachinePointerInfo(),
211                               false, false, false, 0);
212         } else {
213           unsigned loReg = MF.addLiveIn(NextVA.getLocReg(),
214                                         &SP::IntRegsRegClass);
215           LoVal = DAG.getCopyFromReg(Chain, dl, loReg, MVT::i32);
216         }
217         SDValue WholeValue =
218           DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
219         WholeValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, WholeValue);
220         InVals.push_back(WholeValue);
221         continue;
222       }
223       unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
224       MF.getRegInfo().addLiveIn(VA.getLocReg(), VReg);
225       SDValue Arg = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
226       if (VA.getLocVT() == MVT::f32)
227         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Arg);
228       else if (VA.getLocVT() != MVT::i32) {
229         Arg = DAG.getNode(ISD::AssertSext, dl, MVT::i32, Arg,
230                           DAG.getValueType(VA.getLocVT()));
231         Arg = DAG.getNode(ISD::TRUNCATE, dl, VA.getLocVT(), Arg);
232       }
233       InVals.push_back(Arg);
234       continue;
235     }
236
237     assert(VA.isMemLoc());
238
239     unsigned Offset = VA.getLocMemOffset()+StackOffset;
240
241     if (VA.needsCustom()) {
242       assert(VA.getValVT() == MVT::f64);
243       //If it is double-word aligned, just load.
244       if (Offset % 8 == 0) {
245         int FI = MF.getFrameInfo()->CreateFixedObject(8,
246                                                       Offset,
247                                                       true);
248         SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
249         SDValue Load = DAG.getLoad(VA.getValVT(), dl, Chain, FIPtr,
250                                    MachinePointerInfo(),
251                                    false,false, false, 0);
252         InVals.push_back(Load);
253         continue;
254       }
255
256       int FI = MF.getFrameInfo()->CreateFixedObject(4,
257                                                     Offset,
258                                                     true);
259       SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
260       SDValue HiVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
261                                   MachinePointerInfo(),
262                                   false, false, false, 0);
263       int FI2 = MF.getFrameInfo()->CreateFixedObject(4,
264                                                      Offset+4,
265                                                      true);
266       SDValue FIPtr2 = DAG.getFrameIndex(FI2, getPointerTy());
267
268       SDValue LoVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr2,
269                                   MachinePointerInfo(),
270                                   false, false, false, 0);
271
272       SDValue WholeValue =
273         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
274       WholeValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, WholeValue);
275       InVals.push_back(WholeValue);
276       continue;
277     }
278
279     int FI = MF.getFrameInfo()->CreateFixedObject(4,
280                                                   Offset,
281                                                   true);
282     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
283     SDValue Load ;
284     if (VA.getValVT() == MVT::i32 || VA.getValVT() == MVT::f32) {
285       Load = DAG.getLoad(VA.getValVT(), dl, Chain, FIPtr,
286                          MachinePointerInfo(),
287                          false, false, false, 0);
288     } else {
289       ISD::LoadExtType LoadOp = ISD::SEXTLOAD;
290       // Sparc is big endian, so add an offset based on the ObjectVT.
291       unsigned Offset = 4-std::max(1U, VA.getValVT().getSizeInBits()/8);
292       FIPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIPtr,
293                           DAG.getConstant(Offset, MVT::i32));
294       Load = DAG.getExtLoad(LoadOp, dl, MVT::i32, Chain, FIPtr,
295                             MachinePointerInfo(),
296                             VA.getValVT(), false, false,0);
297       Load = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Load);
298     }
299     InVals.push_back(Load);
300   }
301
302   if (MF.getFunction()->hasStructRetAttr()) {
303     //Copy the SRet Argument to SRetReturnReg
304     SparcMachineFunctionInfo *SFI = MF.getInfo<SparcMachineFunctionInfo>();
305     unsigned Reg = SFI->getSRetReturnReg();
306     if (!Reg) {
307       Reg = MF.getRegInfo().createVirtualRegister(&SP::IntRegsRegClass);
308       SFI->setSRetReturnReg(Reg);
309     }
310     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
311     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
312   }
313
314   // Store remaining ArgRegs to the stack if this is a varargs function.
315   if (isVarArg) {
316     static const uint16_t ArgRegs[] = {
317       SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
318     };
319     unsigned NumAllocated = CCInfo.getFirstUnallocated(ArgRegs, 6);
320     const uint16_t *CurArgReg = ArgRegs+NumAllocated, *ArgRegEnd = ArgRegs+6;
321     unsigned ArgOffset = CCInfo.getNextStackOffset();
322     if (NumAllocated == 6)
323       ArgOffset += StackOffset;
324     else {
325       assert(!ArgOffset);
326       ArgOffset = 68+4*NumAllocated;
327     }
328
329     // Remember the vararg offset for the va_start implementation.
330     FuncInfo->setVarArgsFrameOffset(ArgOffset);
331
332     std::vector<SDValue> OutChains;
333
334     for (; CurArgReg != ArgRegEnd; ++CurArgReg) {
335       unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
336       MF.getRegInfo().addLiveIn(*CurArgReg, VReg);
337       SDValue Arg = DAG.getCopyFromReg(DAG.getRoot(), dl, VReg, MVT::i32);
338
339       int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
340                                                           true);
341       SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
342
343       OutChains.push_back(DAG.getStore(DAG.getRoot(), dl, Arg, FIPtr,
344                                        MachinePointerInfo(),
345                                        false, false, 0));
346       ArgOffset += 4;
347     }
348
349     if (!OutChains.empty()) {
350       OutChains.push_back(Chain);
351       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
352                           &OutChains[0], OutChains.size());
353     }
354   }
355
356   return Chain;
357 }
358
359 // Lower formal arguments for the 64 bit ABI.
360 SDValue SparcTargetLowering::
361 LowerFormalArguments_64(SDValue Chain,
362                         CallingConv::ID CallConv,
363                         bool IsVarArg,
364                         const SmallVectorImpl<ISD::InputArg> &Ins,
365                         DebugLoc DL,
366                         SelectionDAG &DAG,
367                         SmallVectorImpl<SDValue> &InVals) const {
368   MachineFunction &MF = DAG.getMachineFunction();
369
370   // Analyze arguments according to CC_Sparc64.
371   SmallVector<CCValAssign, 16> ArgLocs;
372   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
373                  getTargetMachine(), ArgLocs, *DAG.getContext());
374   CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc64);
375
376   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
377     CCValAssign &VA = ArgLocs[i];
378     if (VA.isRegLoc()) {
379       // This argument is passed in a register.
380       // All integer register arguments are promoted by the caller to i64.
381
382       // Create a virtual register for the promoted live-in value.
383       unsigned VReg = MF.addLiveIn(VA.getLocReg(),
384                                    getRegClassFor(VA.getLocVT()));
385       SDValue Arg = DAG.getCopyFromReg(Chain, DL, VReg, VA.getLocVT());
386
387       // The caller promoted the argument, so insert an Assert?ext SDNode so we
388       // won't promote the value again in this function.
389       switch (VA.getLocInfo()) {
390       case CCValAssign::SExt:
391         Arg = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Arg,
392                           DAG.getValueType(VA.getValVT()));
393         break;
394       case CCValAssign::ZExt:
395         Arg = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Arg,
396                           DAG.getValueType(VA.getValVT()));
397         break;
398       default:
399         break;
400       }
401
402       // Truncate the register down to the argument type.
403       if (VA.isExtInLoc())
404         Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
405
406       InVals.push_back(Arg);
407       continue;
408     }
409
410     // The registers are exhausted. This argument was passed on the stack.
411     assert(VA.isMemLoc());
412   }
413   return Chain;
414 }
415
416 SDValue
417 SparcTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
418                                SmallVectorImpl<SDValue> &InVals) const {
419   SelectionDAG &DAG                     = CLI.DAG;
420   DebugLoc &dl                          = CLI.DL;
421   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
422   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
423   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
424   SDValue Chain                         = CLI.Chain;
425   SDValue Callee                        = CLI.Callee;
426   bool &isTailCall                      = CLI.IsTailCall;
427   CallingConv::ID CallConv              = CLI.CallConv;
428   bool isVarArg                         = CLI.IsVarArg;
429
430   // Sparc target does not yet support tail call optimization.
431   isTailCall = false;
432
433   // Analyze operands of the call, assigning locations to each operand.
434   SmallVector<CCValAssign, 16> ArgLocs;
435   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
436                  DAG.getTarget(), ArgLocs, *DAG.getContext());
437   CCInfo.AnalyzeCallOperands(Outs, CC_Sparc32);
438
439   // Get the size of the outgoing arguments stack space requirement.
440   unsigned ArgsSize = CCInfo.getNextStackOffset();
441
442   // Keep stack frames 8-byte aligned.
443   ArgsSize = (ArgsSize+7) & ~7;
444
445   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
446
447   //Create local copies for byval args.
448   SmallVector<SDValue, 8> ByValArgs;
449   for (unsigned i = 0,  e = Outs.size(); i != e; ++i) {
450     ISD::ArgFlagsTy Flags = Outs[i].Flags;
451     if (!Flags.isByVal())
452       continue;
453
454     SDValue Arg = OutVals[i];
455     unsigned Size = Flags.getByValSize();
456     unsigned Align = Flags.getByValAlign();
457
458     int FI = MFI->CreateStackObject(Size, Align, false);
459     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
460     SDValue SizeNode = DAG.getConstant(Size, MVT::i32);
461
462     Chain = DAG.getMemcpy(Chain, dl, FIPtr, Arg, SizeNode, Align,
463                           false,        //isVolatile,
464                           (Size <= 32), //AlwaysInline if size <= 32
465                           MachinePointerInfo(), MachinePointerInfo());
466     ByValArgs.push_back(FIPtr);
467   }
468
469   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(ArgsSize, true));
470
471   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
472   SmallVector<SDValue, 8> MemOpChains;
473
474   const unsigned StackOffset = 92;
475   bool hasStructRetAttr = false;
476   // Walk the register/memloc assignments, inserting copies/loads.
477   for (unsigned i = 0, realArgIdx = 0, byvalArgIdx = 0, e = ArgLocs.size();
478        i != e;
479        ++i, ++realArgIdx) {
480     CCValAssign &VA = ArgLocs[i];
481     SDValue Arg = OutVals[realArgIdx];
482
483     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
484
485     //Use local copy if it is a byval arg.
486     if (Flags.isByVal())
487       Arg = ByValArgs[byvalArgIdx++];
488
489     // Promote the value if needed.
490     switch (VA.getLocInfo()) {
491     default: llvm_unreachable("Unknown loc info!");
492     case CCValAssign::Full: break;
493     case CCValAssign::SExt:
494       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
495       break;
496     case CCValAssign::ZExt:
497       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
498       break;
499     case CCValAssign::AExt:
500       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
501       break;
502     case CCValAssign::BCvt:
503       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
504       break;
505     }
506
507     if (Flags.isSRet()) {
508       assert(VA.needsCustom());
509       // store SRet argument in %sp+64
510       SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
511       SDValue PtrOff = DAG.getIntPtrConstant(64);
512       PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
513       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
514                                          MachinePointerInfo(),
515                                          false, false, 0));
516       hasStructRetAttr = true;
517       continue;
518     }
519
520     if (VA.needsCustom()) {
521       assert(VA.getLocVT() == MVT::f64);
522
523       if (VA.isMemLoc()) {
524         unsigned Offset = VA.getLocMemOffset() + StackOffset;
525         //if it is double-word aligned, just store.
526         if (Offset % 8 == 0) {
527           SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
528           SDValue PtrOff = DAG.getIntPtrConstant(Offset);
529           PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
530           MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
531                                              MachinePointerInfo(),
532                                              false, false, 0));
533           continue;
534         }
535       }
536
537       SDValue StackPtr = DAG.CreateStackTemporary(MVT::f64, MVT::i32);
538       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
539                                    Arg, StackPtr, MachinePointerInfo(),
540                                    false, false, 0);
541       // Sparc is big-endian, so the high part comes first.
542       SDValue Hi = DAG.getLoad(MVT::i32, dl, Store, StackPtr,
543                                MachinePointerInfo(), false, false, false, 0);
544       // Increment the pointer to the other half.
545       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
546                              DAG.getIntPtrConstant(4));
547       // Load the low part.
548       SDValue Lo = DAG.getLoad(MVT::i32, dl, Store, StackPtr,
549                                MachinePointerInfo(), false, false, false, 0);
550
551       if (VA.isRegLoc()) {
552         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Hi));
553         assert(i+1 != e);
554         CCValAssign &NextVA = ArgLocs[++i];
555         if (NextVA.isRegLoc()) {
556           RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Lo));
557         } else {
558           //Store the low part in stack.
559           unsigned Offset = NextVA.getLocMemOffset() + StackOffset;
560           SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
561           SDValue PtrOff = DAG.getIntPtrConstant(Offset);
562           PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
563           MemOpChains.push_back(DAG.getStore(Chain, dl, Lo, PtrOff,
564                                              MachinePointerInfo(),
565                                              false, false, 0));
566         }
567       } else {
568         unsigned Offset = VA.getLocMemOffset() + StackOffset;
569         // Store the high part.
570         SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
571         SDValue PtrOff = DAG.getIntPtrConstant(Offset);
572         PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
573         MemOpChains.push_back(DAG.getStore(Chain, dl, Hi, PtrOff,
574                                            MachinePointerInfo(),
575                                            false, false, 0));
576         // Store the low part.
577         PtrOff = DAG.getIntPtrConstant(Offset+4);
578         PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
579         MemOpChains.push_back(DAG.getStore(Chain, dl, Lo, PtrOff,
580                                            MachinePointerInfo(),
581                                            false, false, 0));
582       }
583       continue;
584     }
585
586     // Arguments that can be passed on register must be kept at
587     // RegsToPass vector
588     if (VA.isRegLoc()) {
589       if (VA.getLocVT() != MVT::f32) {
590         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
591         continue;
592       }
593       Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
594       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
595       continue;
596     }
597
598     assert(VA.isMemLoc());
599
600     // Create a store off the stack pointer for this argument.
601     SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
602     SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset()+StackOffset);
603     PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
604     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
605                                        MachinePointerInfo(),
606                                        false, false, 0));
607   }
608
609
610   // Emit all stores, make sure the occur before any copies into physregs.
611   if (!MemOpChains.empty())
612     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
613                         &MemOpChains[0], MemOpChains.size());
614
615   // Build a sequence of copy-to-reg nodes chained together with token
616   // chain and flag operands which copy the outgoing args into registers.
617   // The InFlag in necessary since all emitted instructions must be
618   // stuck together.
619   SDValue InFlag;
620   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
621     unsigned Reg = RegsToPass[i].first;
622     // Remap I0->I7 -> O0->O7.
623     if (Reg >= SP::I0 && Reg <= SP::I7)
624       Reg = Reg-SP::I0+SP::O0;
625
626     Chain = DAG.getCopyToReg(Chain, dl, Reg, RegsToPass[i].second, InFlag);
627     InFlag = Chain.getValue(1);
628   }
629
630   unsigned SRetArgSize = (hasStructRetAttr)? getSRetArgSize(DAG, Callee):0;
631
632   // If the callee is a GlobalAddress node (quite common, every direct call is)
633   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
634   // Likewise ExternalSymbol -> TargetExternalSymbol.
635   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
636     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
637   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
638     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
639
640   // Returns a chain & a flag for retval copy to use
641   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
642   SmallVector<SDValue, 8> Ops;
643   Ops.push_back(Chain);
644   Ops.push_back(Callee);
645   if (hasStructRetAttr)
646     Ops.push_back(DAG.getTargetConstant(SRetArgSize, MVT::i32));
647   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
648     unsigned Reg = RegsToPass[i].first;
649     if (Reg >= SP::I0 && Reg <= SP::I7)
650       Reg = Reg-SP::I0+SP::O0;
651
652     Ops.push_back(DAG.getRegister(Reg, RegsToPass[i].second.getValueType()));
653   }
654   if (InFlag.getNode())
655     Ops.push_back(InFlag);
656
657   Chain = DAG.getNode(SPISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
658   InFlag = Chain.getValue(1);
659
660   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, true),
661                              DAG.getIntPtrConstant(0, true), InFlag);
662   InFlag = Chain.getValue(1);
663
664   // Assign locations to each value returned by this call.
665   SmallVector<CCValAssign, 16> RVLocs;
666   CCState RVInfo(CallConv, isVarArg, DAG.getMachineFunction(),
667                  DAG.getTarget(), RVLocs, *DAG.getContext());
668
669   RVInfo.AnalyzeCallResult(Ins, RetCC_Sparc32);
670
671   // Copy all of the result registers out of their specified physreg.
672   for (unsigned i = 0; i != RVLocs.size(); ++i) {
673     unsigned Reg = RVLocs[i].getLocReg();
674
675     // Remap I0->I7 -> O0->O7.
676     if (Reg >= SP::I0 && Reg <= SP::I7)
677       Reg = Reg-SP::I0+SP::O0;
678
679     Chain = DAG.getCopyFromReg(Chain, dl, Reg,
680                                RVLocs[i].getValVT(), InFlag).getValue(1);
681     InFlag = Chain.getValue(2);
682     InVals.push_back(Chain.getValue(0));
683   }
684
685   return Chain;
686 }
687
688 unsigned
689 SparcTargetLowering::getSRetArgSize(SelectionDAG &DAG, SDValue Callee) const
690 {
691   const Function *CalleeFn = 0;
692   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
693     CalleeFn = dyn_cast<Function>(G->getGlobal());
694   } else if (ExternalSymbolSDNode *E =
695              dyn_cast<ExternalSymbolSDNode>(Callee)) {
696     const Function *Fn = DAG.getMachineFunction().getFunction();
697     const Module *M = Fn->getParent();
698     CalleeFn = M->getFunction(E->getSymbol());
699   }
700
701   if (!CalleeFn)
702     return 0;
703
704   assert(CalleeFn->hasStructRetAttr() &&
705          "Callee does not have the StructRet attribute.");
706
707   PointerType *Ty = cast<PointerType>(CalleeFn->arg_begin()->getType());
708   Type *ElementTy = Ty->getElementType();
709   return getDataLayout()->getTypeAllocSize(ElementTy);
710 }
711
712 //===----------------------------------------------------------------------===//
713 // TargetLowering Implementation
714 //===----------------------------------------------------------------------===//
715
716 /// IntCondCCodeToICC - Convert a DAG integer condition code to a SPARC ICC
717 /// condition.
718 static SPCC::CondCodes IntCondCCodeToICC(ISD::CondCode CC) {
719   switch (CC) {
720   default: llvm_unreachable("Unknown integer condition code!");
721   case ISD::SETEQ:  return SPCC::ICC_E;
722   case ISD::SETNE:  return SPCC::ICC_NE;
723   case ISD::SETLT:  return SPCC::ICC_L;
724   case ISD::SETGT:  return SPCC::ICC_G;
725   case ISD::SETLE:  return SPCC::ICC_LE;
726   case ISD::SETGE:  return SPCC::ICC_GE;
727   case ISD::SETULT: return SPCC::ICC_CS;
728   case ISD::SETULE: return SPCC::ICC_LEU;
729   case ISD::SETUGT: return SPCC::ICC_GU;
730   case ISD::SETUGE: return SPCC::ICC_CC;
731   }
732 }
733
734 /// FPCondCCodeToFCC - Convert a DAG floatingp oint condition code to a SPARC
735 /// FCC condition.
736 static SPCC::CondCodes FPCondCCodeToFCC(ISD::CondCode CC) {
737   switch (CC) {
738   default: llvm_unreachable("Unknown fp condition code!");
739   case ISD::SETEQ:
740   case ISD::SETOEQ: return SPCC::FCC_E;
741   case ISD::SETNE:
742   case ISD::SETUNE: return SPCC::FCC_NE;
743   case ISD::SETLT:
744   case ISD::SETOLT: return SPCC::FCC_L;
745   case ISD::SETGT:
746   case ISD::SETOGT: return SPCC::FCC_G;
747   case ISD::SETLE:
748   case ISD::SETOLE: return SPCC::FCC_LE;
749   case ISD::SETGE:
750   case ISD::SETOGE: return SPCC::FCC_GE;
751   case ISD::SETULT: return SPCC::FCC_UL;
752   case ISD::SETULE: return SPCC::FCC_ULE;
753   case ISD::SETUGT: return SPCC::FCC_UG;
754   case ISD::SETUGE: return SPCC::FCC_UGE;
755   case ISD::SETUO:  return SPCC::FCC_U;
756   case ISD::SETO:   return SPCC::FCC_O;
757   case ISD::SETONE: return SPCC::FCC_LG;
758   case ISD::SETUEQ: return SPCC::FCC_UE;
759   }
760 }
761
762 SparcTargetLowering::SparcTargetLowering(TargetMachine &TM)
763   : TargetLowering(TM, new TargetLoweringObjectFileELF()) {
764   Subtarget = &TM.getSubtarget<SparcSubtarget>();
765
766   // Set up the register classes.
767   addRegisterClass(MVT::i32, &SP::IntRegsRegClass);
768   addRegisterClass(MVT::f32, &SP::FPRegsRegClass);
769   addRegisterClass(MVT::f64, &SP::DFPRegsRegClass);
770   if (Subtarget->is64Bit())
771     addRegisterClass(MVT::i64, &SP::I64RegsRegClass);
772
773   // Turn FP extload into load/fextend
774   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
775   // Sparc doesn't have i1 sign extending load
776   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
777   // Turn FP truncstore into trunc + store.
778   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
779
780   // Custom legalize GlobalAddress nodes into LO/HI parts.
781   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
782   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
783   setOperationAction(ISD::ConstantPool , MVT::i32, Custom);
784
785   // Sparc doesn't have sext_inreg, replace them with shl/sra
786   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
787   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
788   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
789
790   // Sparc has no REM or DIVREM operations.
791   setOperationAction(ISD::UREM, MVT::i32, Expand);
792   setOperationAction(ISD::SREM, MVT::i32, Expand);
793   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
794   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
795
796   // Custom expand fp<->sint
797   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
798   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
799
800   // Expand fp<->uint
801   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
802   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
803
804   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
805   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
806
807   // Sparc has no select or setcc: expand to SELECT_CC.
808   setOperationAction(ISD::SELECT, MVT::i32, Expand);
809   setOperationAction(ISD::SELECT, MVT::f32, Expand);
810   setOperationAction(ISD::SELECT, MVT::f64, Expand);
811   setOperationAction(ISD::SETCC, MVT::i32, Expand);
812   setOperationAction(ISD::SETCC, MVT::f32, Expand);
813   setOperationAction(ISD::SETCC, MVT::f64, Expand);
814
815   // Sparc doesn't have BRCOND either, it has BR_CC.
816   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
817   setOperationAction(ISD::BRIND, MVT::Other, Expand);
818   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
819   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
820   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
821   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
822
823   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
824   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
825   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
826
827   if (Subtarget->is64Bit()) {
828     setOperationAction(ISD::BR_CC, MVT::i64, Custom);
829     setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
830   }
831
832   // FIXME: There are instructions available for ATOMIC_FENCE
833   // on SparcV8 and later.
834   setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
835   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
836
837   setOperationAction(ISD::FSIN , MVT::f64, Expand);
838   setOperationAction(ISD::FCOS , MVT::f64, Expand);
839   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
840   setOperationAction(ISD::FREM , MVT::f64, Expand);
841   setOperationAction(ISD::FMA  , MVT::f64, Expand);
842   setOperationAction(ISD::FSIN , MVT::f32, Expand);
843   setOperationAction(ISD::FCOS , MVT::f32, Expand);
844   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
845   setOperationAction(ISD::FREM , MVT::f32, Expand);
846   setOperationAction(ISD::FMA  , MVT::f32, Expand);
847   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
848   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
849   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
850   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
851   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
852   setOperationAction(ISD::ROTL , MVT::i32, Expand);
853   setOperationAction(ISD::ROTR , MVT::i32, Expand);
854   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
855   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
856   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
857   setOperationAction(ISD::FPOW , MVT::f64, Expand);
858   setOperationAction(ISD::FPOW , MVT::f32, Expand);
859
860   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
861   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
862   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
863
864   // FIXME: Sparc provides these multiplies, but we don't have them yet.
865   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
866   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
867
868   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
869
870   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
871   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
872   // VAARG needs to be lowered to not do unaligned accesses for doubles.
873   setOperationAction(ISD::VAARG             , MVT::Other, Custom);
874
875   // Use the default implementation.
876   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
877   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
878   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
879   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
880   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
881
882   // No debug info support yet.
883   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
884
885   setStackPointerRegisterToSaveRestore(SP::O6);
886
887   if (TM.getSubtarget<SparcSubtarget>().isV9())
888     setOperationAction(ISD::CTPOP, MVT::i32, Legal);
889
890   setMinFunctionAlignment(2);
891
892   computeRegisterProperties();
893 }
894
895 const char *SparcTargetLowering::getTargetNodeName(unsigned Opcode) const {
896   switch (Opcode) {
897   default: return 0;
898   case SPISD::CMPICC:     return "SPISD::CMPICC";
899   case SPISD::CMPFCC:     return "SPISD::CMPFCC";
900   case SPISD::BRICC:      return "SPISD::BRICC";
901   case SPISD::BRXCC:      return "SPISD::BRXCC";
902   case SPISD::BRFCC:      return "SPISD::BRFCC";
903   case SPISD::SELECT_ICC: return "SPISD::SELECT_ICC";
904   case SPISD::SELECT_XCC: return "SPISD::SELECT_XCC";
905   case SPISD::SELECT_FCC: return "SPISD::SELECT_FCC";
906   case SPISD::Hi:         return "SPISD::Hi";
907   case SPISD::Lo:         return "SPISD::Lo";
908   case SPISD::FTOI:       return "SPISD::FTOI";
909   case SPISD::ITOF:       return "SPISD::ITOF";
910   case SPISD::CALL:       return "SPISD::CALL";
911   case SPISD::RET_FLAG:   return "SPISD::RET_FLAG";
912   case SPISD::GLOBAL_BASE_REG: return "SPISD::GLOBAL_BASE_REG";
913   case SPISD::FLUSHW:     return "SPISD::FLUSHW";
914   }
915 }
916
917 /// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
918 /// be zero. Op is expected to be a target specific node. Used by DAG
919 /// combiner.
920 void SparcTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
921                                                          APInt &KnownZero,
922                                                          APInt &KnownOne,
923                                                          const SelectionDAG &DAG,
924                                                          unsigned Depth) const {
925   APInt KnownZero2, KnownOne2;
926   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
927
928   switch (Op.getOpcode()) {
929   default: break;
930   case SPISD::SELECT_ICC:
931   case SPISD::SELECT_XCC:
932   case SPISD::SELECT_FCC:
933     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
934     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
935     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
936     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
937
938     // Only known if known in both the LHS and RHS.
939     KnownOne &= KnownOne2;
940     KnownZero &= KnownZero2;
941     break;
942   }
943 }
944
945 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
946 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
947 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
948                              ISD::CondCode CC, unsigned &SPCC) {
949   if (isa<ConstantSDNode>(RHS) &&
950       cast<ConstantSDNode>(RHS)->isNullValue() &&
951       CC == ISD::SETNE &&
952       (((LHS.getOpcode() == SPISD::SELECT_ICC ||
953          LHS.getOpcode() == SPISD::SELECT_XCC) &&
954         LHS.getOperand(3).getOpcode() == SPISD::CMPICC) ||
955        (LHS.getOpcode() == SPISD::SELECT_FCC &&
956         LHS.getOperand(3).getOpcode() == SPISD::CMPFCC)) &&
957       isa<ConstantSDNode>(LHS.getOperand(0)) &&
958       isa<ConstantSDNode>(LHS.getOperand(1)) &&
959       cast<ConstantSDNode>(LHS.getOperand(0))->isOne() &&
960       cast<ConstantSDNode>(LHS.getOperand(1))->isNullValue()) {
961     SDValue CMPCC = LHS.getOperand(3);
962     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
963     LHS = CMPCC.getOperand(0);
964     RHS = CMPCC.getOperand(1);
965   }
966 }
967
968 SDValue SparcTargetLowering::LowerGlobalAddress(SDValue Op,
969                                                 SelectionDAG &DAG) const {
970   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
971   // FIXME there isn't really any debug info here
972   DebugLoc dl = Op.getDebugLoc();
973   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
974   SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, GA);
975   SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, GA);
976
977   if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
978     return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
979
980   SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
981                                    getPointerTy());
982   SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
983   SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
984                                 GlobalBase, RelAddr);
985   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
986                      AbsAddr, MachinePointerInfo(), false, false, false, 0);
987 }
988
989 SDValue SparcTargetLowering::LowerConstantPool(SDValue Op,
990                                                SelectionDAG &DAG) const {
991   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
992   // FIXME there isn't really any debug info here
993   DebugLoc dl = Op.getDebugLoc();
994   const Constant *C = N->getConstVal();
995   SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment());
996   SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, CP);
997   SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, CP);
998   if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
999     return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
1000
1001   SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
1002                                    getPointerTy());
1003   SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
1004   SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
1005                                 GlobalBase, RelAddr);
1006   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1007                      AbsAddr, MachinePointerInfo(), false, false, false, 0);
1008 }
1009
1010 static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
1011   DebugLoc dl = Op.getDebugLoc();
1012   // Convert the fp value to integer in an FP register.
1013   assert(Op.getValueType() == MVT::i32);
1014   Op = DAG.getNode(SPISD::FTOI, dl, MVT::f32, Op.getOperand(0));
1015   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
1016 }
1017
1018 static SDValue LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1019   DebugLoc dl = Op.getDebugLoc();
1020   assert(Op.getOperand(0).getValueType() == MVT::i32);
1021   SDValue Tmp = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
1022   // Convert the int value to FP in an FP register.
1023   return DAG.getNode(SPISD::ITOF, dl, Op.getValueType(), Tmp);
1024 }
1025
1026 static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
1027   SDValue Chain = Op.getOperand(0);
1028   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1029   SDValue LHS = Op.getOperand(2);
1030   SDValue RHS = Op.getOperand(3);
1031   SDValue Dest = Op.getOperand(4);
1032   DebugLoc dl = Op.getDebugLoc();
1033   unsigned Opc, SPCC = ~0U;
1034
1035   // If this is a br_cc of a "setcc", and if the setcc got lowered into
1036   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1037   LookThroughSetCC(LHS, RHS, CC, SPCC);
1038
1039   // Get the condition flag.
1040   SDValue CompareFlag;
1041   if (LHS.getValueType().isInteger()) {
1042     EVT VTs[] = { LHS.getValueType(), MVT::Glue };
1043     SDValue Ops[2] = { LHS, RHS };
1044     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
1045     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
1046     // 32-bit compares use the icc flags, 64-bit uses the xcc flags.
1047     Opc = LHS.getValueType() == MVT::i32 ? SPISD::BRICC : SPISD::BRXCC;
1048   } else {
1049     CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
1050     if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
1051     Opc = SPISD::BRFCC;
1052   }
1053   return DAG.getNode(Opc, dl, MVT::Other, Chain, Dest,
1054                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
1055 }
1056
1057 static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
1058   SDValue LHS = Op.getOperand(0);
1059   SDValue RHS = Op.getOperand(1);
1060   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1061   SDValue TrueVal = Op.getOperand(2);
1062   SDValue FalseVal = Op.getOperand(3);
1063   DebugLoc dl = Op.getDebugLoc();
1064   unsigned Opc, SPCC = ~0U;
1065
1066   // If this is a select_cc of a "setcc", and if the setcc got lowered into
1067   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1068   LookThroughSetCC(LHS, RHS, CC, SPCC);
1069
1070   SDValue CompareFlag;
1071   if (LHS.getValueType().isInteger()) {
1072     // subcc returns a value
1073     EVT VTs[] = { LHS.getValueType(), MVT::Glue };
1074     SDValue Ops[2] = { LHS, RHS };
1075     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
1076     Opc = LHS.getValueType() == MVT::i32 ?
1077           SPISD::SELECT_ICC : SPISD::SELECT_XCC;
1078     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
1079   } else {
1080     CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
1081     Opc = SPISD::SELECT_FCC;
1082     if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
1083   }
1084   return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
1085                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
1086 }
1087
1088 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
1089                             const SparcTargetLowering &TLI) {
1090   MachineFunction &MF = DAG.getMachineFunction();
1091   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
1092
1093   // vastart just stores the address of the VarArgsFrameIndex slot into the
1094   // memory location argument.
1095   DebugLoc dl = Op.getDebugLoc();
1096   SDValue Offset =
1097     DAG.getNode(ISD::ADD, dl, MVT::i32,
1098                 DAG.getRegister(SP::I6, MVT::i32),
1099                 DAG.getConstant(FuncInfo->getVarArgsFrameOffset(),
1100                                 MVT::i32));
1101   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1102   return DAG.getStore(Op.getOperand(0), dl, Offset, Op.getOperand(1),
1103                       MachinePointerInfo(SV), false, false, 0);
1104 }
1105
1106 static SDValue LowerVAARG(SDValue Op, SelectionDAG &DAG) {
1107   SDNode *Node = Op.getNode();
1108   EVT VT = Node->getValueType(0);
1109   SDValue InChain = Node->getOperand(0);
1110   SDValue VAListPtr = Node->getOperand(1);
1111   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1112   DebugLoc dl = Node->getDebugLoc();
1113   SDValue VAList = DAG.getLoad(MVT::i32, dl, InChain, VAListPtr,
1114                                MachinePointerInfo(SV), false, false, false, 0);
1115   // Increment the pointer, VAList, to the next vaarg
1116   SDValue NextPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, VAList,
1117                                   DAG.getConstant(VT.getSizeInBits()/8,
1118                                                   MVT::i32));
1119   // Store the incremented VAList to the legalized pointer
1120   InChain = DAG.getStore(VAList.getValue(1), dl, NextPtr,
1121                          VAListPtr, MachinePointerInfo(SV), false, false, 0);
1122   // Load the actual argument out of the pointer VAList, unless this is an
1123   // f64 load.
1124   if (VT != MVT::f64)
1125     return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
1126                        false, false, false, 0);
1127
1128   // Otherwise, load it as i64, then do a bitconvert.
1129   SDValue V = DAG.getLoad(MVT::i64, dl, InChain, VAList, MachinePointerInfo(),
1130                           false, false, false, 0);
1131
1132   // Bit-Convert the value to f64.
1133   SDValue Ops[2] = {
1134     DAG.getNode(ISD::BITCAST, dl, MVT::f64, V),
1135     V.getValue(1)
1136   };
1137   return DAG.getMergeValues(Ops, 2, dl);
1138 }
1139
1140 static SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) {
1141   SDValue Chain = Op.getOperand(0);  // Legalize the chain.
1142   SDValue Size  = Op.getOperand(1);  // Legalize the size.
1143   DebugLoc dl = Op.getDebugLoc();
1144
1145   unsigned SPReg = SP::O6;
1146   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, MVT::i32);
1147   SDValue NewSP = DAG.getNode(ISD::SUB, dl, MVT::i32, SP, Size); // Value
1148   Chain = DAG.getCopyToReg(SP.getValue(1), dl, SPReg, NewSP);    // Output chain
1149
1150   // The resultant pointer is actually 16 words from the bottom of the stack,
1151   // to provide a register spill area.
1152   SDValue NewVal = DAG.getNode(ISD::ADD, dl, MVT::i32, NewSP,
1153                                  DAG.getConstant(96, MVT::i32));
1154   SDValue Ops[2] = { NewVal, Chain };
1155   return DAG.getMergeValues(Ops, 2, dl);
1156 }
1157
1158
1159 static SDValue getFLUSHW(SDValue Op, SelectionDAG &DAG) {
1160   DebugLoc dl = Op.getDebugLoc();
1161   SDValue Chain = DAG.getNode(SPISD::FLUSHW,
1162                               dl, MVT::Other, DAG.getEntryNode());
1163   return Chain;
1164 }
1165
1166 static SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
1167   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1168   MFI->setFrameAddressIsTaken(true);
1169
1170   EVT VT = Op.getValueType();
1171   DebugLoc dl = Op.getDebugLoc();
1172   unsigned FrameReg = SP::I6;
1173
1174   uint64_t depth = Op.getConstantOperandVal(0);
1175
1176   SDValue FrameAddr;
1177   if (depth == 0)
1178     FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
1179   else {
1180     // flush first to make sure the windowed registers' values are in stack
1181     SDValue Chain = getFLUSHW(Op, DAG);
1182     FrameAddr = DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
1183
1184     for (uint64_t i = 0; i != depth; ++i) {
1185       SDValue Ptr = DAG.getNode(ISD::ADD,
1186                                 dl, MVT::i32,
1187                                 FrameAddr, DAG.getIntPtrConstant(56));
1188       FrameAddr = DAG.getLoad(MVT::i32, dl,
1189                               Chain,
1190                               Ptr,
1191                               MachinePointerInfo(), false, false, false, 0);
1192     }
1193   }
1194   return FrameAddr;
1195 }
1196
1197 static SDValue LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
1198   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1199   MFI->setReturnAddressIsTaken(true);
1200
1201   EVT VT = Op.getValueType();
1202   DebugLoc dl = Op.getDebugLoc();
1203   unsigned RetReg = SP::I7;
1204
1205   uint64_t depth = Op.getConstantOperandVal(0);
1206
1207   SDValue RetAddr;
1208   if (depth == 0)
1209     RetAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, RetReg, VT);
1210   else {
1211     // flush first to make sure the windowed registers' values are in stack
1212     SDValue Chain = getFLUSHW(Op, DAG);
1213     RetAddr = DAG.getCopyFromReg(Chain, dl, SP::I6, VT);
1214
1215     for (uint64_t i = 0; i != depth; ++i) {
1216       SDValue Ptr = DAG.getNode(ISD::ADD,
1217                                 dl, MVT::i32,
1218                                 RetAddr,
1219                                 DAG.getIntPtrConstant((i == depth-1)?60:56));
1220       RetAddr = DAG.getLoad(MVT::i32, dl,
1221                             Chain,
1222                             Ptr,
1223                             MachinePointerInfo(), false, false, false, 0);
1224     }
1225   }
1226   return RetAddr;
1227 }
1228
1229 SDValue SparcTargetLowering::
1230 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1231   switch (Op.getOpcode()) {
1232   default: llvm_unreachable("Should not custom lower this!");
1233   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
1234   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
1235   case ISD::GlobalTLSAddress:
1236     llvm_unreachable("TLS not implemented for Sparc.");
1237   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
1238   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
1239   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
1240   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
1241   case ISD::BR_CC:              return LowerBR_CC(Op, DAG);
1242   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
1243   case ISD::VASTART:            return LowerVASTART(Op, DAG, *this);
1244   case ISD::VAARG:              return LowerVAARG(Op, DAG);
1245   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
1246   }
1247 }
1248
1249 MachineBasicBlock *
1250 SparcTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1251                                                  MachineBasicBlock *BB) const {
1252   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1253   unsigned BROpcode;
1254   unsigned CC;
1255   DebugLoc dl = MI->getDebugLoc();
1256   // Figure out the conditional branch opcode to use for this select_cc.
1257   switch (MI->getOpcode()) {
1258   default: llvm_unreachable("Unknown SELECT_CC!");
1259   case SP::SELECT_CC_Int_ICC:
1260   case SP::SELECT_CC_FP_ICC:
1261   case SP::SELECT_CC_DFP_ICC:
1262     BROpcode = SP::BCOND;
1263     break;
1264   case SP::SELECT_CC_Int_FCC:
1265   case SP::SELECT_CC_FP_FCC:
1266   case SP::SELECT_CC_DFP_FCC:
1267     BROpcode = SP::FBCOND;
1268     break;
1269   }
1270
1271   CC = (SPCC::CondCodes)MI->getOperand(3).getImm();
1272
1273   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1274   // control-flow pattern.  The incoming instruction knows the destination vreg
1275   // to set, the condition code register to branch on, the true/false values to
1276   // select between, and a branch opcode to use.
1277   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1278   MachineFunction::iterator It = BB;
1279   ++It;
1280
1281   //  thisMBB:
1282   //  ...
1283   //   TrueVal = ...
1284   //   [f]bCC copy1MBB
1285   //   fallthrough --> copy0MBB
1286   MachineBasicBlock *thisMBB = BB;
1287   MachineFunction *F = BB->getParent();
1288   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1289   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1290   F->insert(It, copy0MBB);
1291   F->insert(It, sinkMBB);
1292
1293   // Transfer the remainder of BB and its successor edges to sinkMBB.
1294   sinkMBB->splice(sinkMBB->begin(), BB,
1295                   llvm::next(MachineBasicBlock::iterator(MI)),
1296                   BB->end());
1297   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1298
1299   // Add the true and fallthrough blocks as its successors.
1300   BB->addSuccessor(copy0MBB);
1301   BB->addSuccessor(sinkMBB);
1302
1303   BuildMI(BB, dl, TII.get(BROpcode)).addMBB(sinkMBB).addImm(CC);
1304
1305   //  copy0MBB:
1306   //   %FalseValue = ...
1307   //   # fallthrough to sinkMBB
1308   BB = copy0MBB;
1309
1310   // Update machine-CFG edges
1311   BB->addSuccessor(sinkMBB);
1312
1313   //  sinkMBB:
1314   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1315   //  ...
1316   BB = sinkMBB;
1317   BuildMI(*BB, BB->begin(), dl, TII.get(SP::PHI), MI->getOperand(0).getReg())
1318     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1319     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1320
1321   MI->eraseFromParent();   // The pseudo instruction is gone now.
1322   return BB;
1323 }
1324
1325 //===----------------------------------------------------------------------===//
1326 //                         Sparc Inline Assembly Support
1327 //===----------------------------------------------------------------------===//
1328
1329 /// getConstraintType - Given a constraint letter, return the type of
1330 /// constraint it is for this target.
1331 SparcTargetLowering::ConstraintType
1332 SparcTargetLowering::getConstraintType(const std::string &Constraint) const {
1333   if (Constraint.size() == 1) {
1334     switch (Constraint[0]) {
1335     default:  break;
1336     case 'r': return C_RegisterClass;
1337     }
1338   }
1339
1340   return TargetLowering::getConstraintType(Constraint);
1341 }
1342
1343 std::pair<unsigned, const TargetRegisterClass*>
1344 SparcTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
1345                                                   EVT VT) const {
1346   if (Constraint.size() == 1) {
1347     switch (Constraint[0]) {
1348     case 'r':
1349       return std::make_pair(0U, &SP::IntRegsRegClass);
1350     }
1351   }
1352
1353   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1354 }
1355
1356 bool
1357 SparcTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1358   // The Sparc target isn't yet aware of offsets.
1359   return false;
1360 }