a9ce75a7eb8202e0e6d078db7b464f4dcc9dae81
[oota-llvm.git] / 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   }
830
831   // FIXME: There are instructions available for ATOMIC_FENCE
832   // on SparcV8 and later.
833   setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
834   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
835
836   setOperationAction(ISD::FSIN , MVT::f64, Expand);
837   setOperationAction(ISD::FCOS , MVT::f64, Expand);
838   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
839   setOperationAction(ISD::FREM , MVT::f64, Expand);
840   setOperationAction(ISD::FMA  , MVT::f64, Expand);
841   setOperationAction(ISD::FSIN , MVT::f32, Expand);
842   setOperationAction(ISD::FCOS , MVT::f32, Expand);
843   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
844   setOperationAction(ISD::FREM , MVT::f32, Expand);
845   setOperationAction(ISD::FMA  , MVT::f32, Expand);
846   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
847   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
848   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
849   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
850   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
851   setOperationAction(ISD::ROTL , MVT::i32, Expand);
852   setOperationAction(ISD::ROTR , MVT::i32, Expand);
853   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
854   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
855   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
856   setOperationAction(ISD::FPOW , MVT::f64, Expand);
857   setOperationAction(ISD::FPOW , MVT::f32, Expand);
858
859   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
860   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
861   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
862
863   // FIXME: Sparc provides these multiplies, but we don't have them yet.
864   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
865   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
866
867   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
868
869   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
870   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
871   // VAARG needs to be lowered to not do unaligned accesses for doubles.
872   setOperationAction(ISD::VAARG             , MVT::Other, Custom);
873
874   // Use the default implementation.
875   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
876   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
877   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
878   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
879   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
880
881   // No debug info support yet.
882   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
883
884   setStackPointerRegisterToSaveRestore(SP::O6);
885
886   if (TM.getSubtarget<SparcSubtarget>().isV9())
887     setOperationAction(ISD::CTPOP, MVT::i32, Legal);
888
889   setMinFunctionAlignment(2);
890
891   computeRegisterProperties();
892 }
893
894 const char *SparcTargetLowering::getTargetNodeName(unsigned Opcode) const {
895   switch (Opcode) {
896   default: return 0;
897   case SPISD::CMPICC:     return "SPISD::CMPICC";
898   case SPISD::CMPFCC:     return "SPISD::CMPFCC";
899   case SPISD::BRICC:      return "SPISD::BRICC";
900   case SPISD::BRXCC:      return "SPISD::BRXCC";
901   case SPISD::BRFCC:      return "SPISD::BRFCC";
902   case SPISD::SELECT_ICC: return "SPISD::SELECT_ICC";
903   case SPISD::SELECT_FCC: return "SPISD::SELECT_FCC";
904   case SPISD::Hi:         return "SPISD::Hi";
905   case SPISD::Lo:         return "SPISD::Lo";
906   case SPISD::FTOI:       return "SPISD::FTOI";
907   case SPISD::ITOF:       return "SPISD::ITOF";
908   case SPISD::CALL:       return "SPISD::CALL";
909   case SPISD::RET_FLAG:   return "SPISD::RET_FLAG";
910   case SPISD::GLOBAL_BASE_REG: return "SPISD::GLOBAL_BASE_REG";
911   case SPISD::FLUSHW:     return "SPISD::FLUSHW";
912   }
913 }
914
915 /// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
916 /// be zero. Op is expected to be a target specific node. Used by DAG
917 /// combiner.
918 void SparcTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
919                                                          APInt &KnownZero,
920                                                          APInt &KnownOne,
921                                                          const SelectionDAG &DAG,
922                                                          unsigned Depth) const {
923   APInt KnownZero2, KnownOne2;
924   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
925
926   switch (Op.getOpcode()) {
927   default: break;
928   case SPISD::SELECT_ICC:
929   case SPISD::SELECT_FCC:
930     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
931     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
932     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
933     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
934
935     // Only known if known in both the LHS and RHS.
936     KnownOne &= KnownOne2;
937     KnownZero &= KnownZero2;
938     break;
939   }
940 }
941
942 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
943 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
944 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
945                              ISD::CondCode CC, unsigned &SPCC) {
946   if (isa<ConstantSDNode>(RHS) &&
947       cast<ConstantSDNode>(RHS)->isNullValue() &&
948       CC == ISD::SETNE &&
949       ((LHS.getOpcode() == SPISD::SELECT_ICC &&
950         LHS.getOperand(3).getOpcode() == SPISD::CMPICC) ||
951        (LHS.getOpcode() == SPISD::SELECT_FCC &&
952         LHS.getOperand(3).getOpcode() == SPISD::CMPFCC)) &&
953       isa<ConstantSDNode>(LHS.getOperand(0)) &&
954       isa<ConstantSDNode>(LHS.getOperand(1)) &&
955       cast<ConstantSDNode>(LHS.getOperand(0))->isOne() &&
956       cast<ConstantSDNode>(LHS.getOperand(1))->isNullValue()) {
957     SDValue CMPCC = LHS.getOperand(3);
958     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
959     LHS = CMPCC.getOperand(0);
960     RHS = CMPCC.getOperand(1);
961   }
962 }
963
964 SDValue SparcTargetLowering::LowerGlobalAddress(SDValue Op,
965                                                 SelectionDAG &DAG) const {
966   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
967   // FIXME there isn't really any debug info here
968   DebugLoc dl = Op.getDebugLoc();
969   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
970   SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, GA);
971   SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, GA);
972
973   if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
974     return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
975
976   SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
977                                    getPointerTy());
978   SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
979   SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
980                                 GlobalBase, RelAddr);
981   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
982                      AbsAddr, MachinePointerInfo(), false, false, false, 0);
983 }
984
985 SDValue SparcTargetLowering::LowerConstantPool(SDValue Op,
986                                                SelectionDAG &DAG) const {
987   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
988   // FIXME there isn't really any debug info here
989   DebugLoc dl = Op.getDebugLoc();
990   const Constant *C = N->getConstVal();
991   SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment());
992   SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, CP);
993   SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, CP);
994   if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
995     return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
996
997   SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
998                                    getPointerTy());
999   SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
1000   SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
1001                                 GlobalBase, RelAddr);
1002   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1003                      AbsAddr, MachinePointerInfo(), false, false, false, 0);
1004 }
1005
1006 static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
1007   DebugLoc dl = Op.getDebugLoc();
1008   // Convert the fp value to integer in an FP register.
1009   assert(Op.getValueType() == MVT::i32);
1010   Op = DAG.getNode(SPISD::FTOI, dl, MVT::f32, Op.getOperand(0));
1011   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
1012 }
1013
1014 static SDValue LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1015   DebugLoc dl = Op.getDebugLoc();
1016   assert(Op.getOperand(0).getValueType() == MVT::i32);
1017   SDValue Tmp = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
1018   // Convert the int value to FP in an FP register.
1019   return DAG.getNode(SPISD::ITOF, dl, Op.getValueType(), Tmp);
1020 }
1021
1022 static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
1023   SDValue Chain = Op.getOperand(0);
1024   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1025   SDValue LHS = Op.getOperand(2);
1026   SDValue RHS = Op.getOperand(3);
1027   SDValue Dest = Op.getOperand(4);
1028   DebugLoc dl = Op.getDebugLoc();
1029   unsigned Opc, SPCC = ~0U;
1030
1031   // If this is a br_cc of a "setcc", and if the setcc got lowered into
1032   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1033   LookThroughSetCC(LHS, RHS, CC, SPCC);
1034
1035   // Get the condition flag.
1036   SDValue CompareFlag;
1037   if (LHS.getValueType().isInteger()) {
1038     EVT VTs[] = { LHS.getValueType(), MVT::Glue };
1039     SDValue Ops[2] = { LHS, RHS };
1040     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
1041     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
1042     // 32-bit compares use the icc flags, 64-bit uses the xcc flags.
1043     Opc = LHS.getValueType() == MVT::i32 ? SPISD::BRICC : SPISD::BRXCC;
1044   } else {
1045     CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
1046     if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
1047     Opc = SPISD::BRFCC;
1048   }
1049   return DAG.getNode(Opc, dl, MVT::Other, Chain, Dest,
1050                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
1051 }
1052
1053 static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
1054   SDValue LHS = Op.getOperand(0);
1055   SDValue RHS = Op.getOperand(1);
1056   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1057   SDValue TrueVal = Op.getOperand(2);
1058   SDValue FalseVal = Op.getOperand(3);
1059   DebugLoc dl = Op.getDebugLoc();
1060   unsigned Opc, SPCC = ~0U;
1061
1062   // If this is a select_cc of a "setcc", and if the setcc got lowered into
1063   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1064   LookThroughSetCC(LHS, RHS, CC, SPCC);
1065
1066   SDValue CompareFlag;
1067   if (LHS.getValueType() == MVT::i32) {
1068     // subcc returns a value
1069     EVT VTs[] = { LHS.getValueType(), MVT::Glue };
1070     SDValue Ops[2] = { LHS, RHS };
1071     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
1072     Opc = SPISD::SELECT_ICC;
1073     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
1074   } else {
1075     CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
1076     Opc = SPISD::SELECT_FCC;
1077     if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
1078   }
1079   return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
1080                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
1081 }
1082
1083 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
1084                             const SparcTargetLowering &TLI) {
1085   MachineFunction &MF = DAG.getMachineFunction();
1086   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
1087
1088   // vastart just stores the address of the VarArgsFrameIndex slot into the
1089   // memory location argument.
1090   DebugLoc dl = Op.getDebugLoc();
1091   SDValue Offset =
1092     DAG.getNode(ISD::ADD, dl, MVT::i32,
1093                 DAG.getRegister(SP::I6, MVT::i32),
1094                 DAG.getConstant(FuncInfo->getVarArgsFrameOffset(),
1095                                 MVT::i32));
1096   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1097   return DAG.getStore(Op.getOperand(0), dl, Offset, Op.getOperand(1),
1098                       MachinePointerInfo(SV), false, false, 0);
1099 }
1100
1101 static SDValue LowerVAARG(SDValue Op, SelectionDAG &DAG) {
1102   SDNode *Node = Op.getNode();
1103   EVT VT = Node->getValueType(0);
1104   SDValue InChain = Node->getOperand(0);
1105   SDValue VAListPtr = Node->getOperand(1);
1106   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1107   DebugLoc dl = Node->getDebugLoc();
1108   SDValue VAList = DAG.getLoad(MVT::i32, dl, InChain, VAListPtr,
1109                                MachinePointerInfo(SV), false, false, false, 0);
1110   // Increment the pointer, VAList, to the next vaarg
1111   SDValue NextPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, VAList,
1112                                   DAG.getConstant(VT.getSizeInBits()/8,
1113                                                   MVT::i32));
1114   // Store the incremented VAList to the legalized pointer
1115   InChain = DAG.getStore(VAList.getValue(1), dl, NextPtr,
1116                          VAListPtr, MachinePointerInfo(SV), false, false, 0);
1117   // Load the actual argument out of the pointer VAList, unless this is an
1118   // f64 load.
1119   if (VT != MVT::f64)
1120     return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
1121                        false, false, false, 0);
1122
1123   // Otherwise, load it as i64, then do a bitconvert.
1124   SDValue V = DAG.getLoad(MVT::i64, dl, InChain, VAList, MachinePointerInfo(),
1125                           false, false, false, 0);
1126
1127   // Bit-Convert the value to f64.
1128   SDValue Ops[2] = {
1129     DAG.getNode(ISD::BITCAST, dl, MVT::f64, V),
1130     V.getValue(1)
1131   };
1132   return DAG.getMergeValues(Ops, 2, dl);
1133 }
1134
1135 static SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) {
1136   SDValue Chain = Op.getOperand(0);  // Legalize the chain.
1137   SDValue Size  = Op.getOperand(1);  // Legalize the size.
1138   DebugLoc dl = Op.getDebugLoc();
1139
1140   unsigned SPReg = SP::O6;
1141   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, MVT::i32);
1142   SDValue NewSP = DAG.getNode(ISD::SUB, dl, MVT::i32, SP, Size); // Value
1143   Chain = DAG.getCopyToReg(SP.getValue(1), dl, SPReg, NewSP);    // Output chain
1144
1145   // The resultant pointer is actually 16 words from the bottom of the stack,
1146   // to provide a register spill area.
1147   SDValue NewVal = DAG.getNode(ISD::ADD, dl, MVT::i32, NewSP,
1148                                  DAG.getConstant(96, MVT::i32));
1149   SDValue Ops[2] = { NewVal, Chain };
1150   return DAG.getMergeValues(Ops, 2, dl);
1151 }
1152
1153
1154 static SDValue getFLUSHW(SDValue Op, SelectionDAG &DAG) {
1155   DebugLoc dl = Op.getDebugLoc();
1156   SDValue Chain = DAG.getNode(SPISD::FLUSHW,
1157                               dl, MVT::Other, DAG.getEntryNode());
1158   return Chain;
1159 }
1160
1161 static SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
1162   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1163   MFI->setFrameAddressIsTaken(true);
1164
1165   EVT VT = Op.getValueType();
1166   DebugLoc dl = Op.getDebugLoc();
1167   unsigned FrameReg = SP::I6;
1168
1169   uint64_t depth = Op.getConstantOperandVal(0);
1170
1171   SDValue FrameAddr;
1172   if (depth == 0)
1173     FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
1174   else {
1175     // flush first to make sure the windowed registers' values are in stack
1176     SDValue Chain = getFLUSHW(Op, DAG);
1177     FrameAddr = DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
1178
1179     for (uint64_t i = 0; i != depth; ++i) {
1180       SDValue Ptr = DAG.getNode(ISD::ADD,
1181                                 dl, MVT::i32,
1182                                 FrameAddr, DAG.getIntPtrConstant(56));
1183       FrameAddr = DAG.getLoad(MVT::i32, dl,
1184                               Chain,
1185                               Ptr,
1186                               MachinePointerInfo(), false, false, false, 0);
1187     }
1188   }
1189   return FrameAddr;
1190 }
1191
1192 static SDValue LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
1193   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1194   MFI->setReturnAddressIsTaken(true);
1195
1196   EVT VT = Op.getValueType();
1197   DebugLoc dl = Op.getDebugLoc();
1198   unsigned RetReg = SP::I7;
1199
1200   uint64_t depth = Op.getConstantOperandVal(0);
1201
1202   SDValue RetAddr;
1203   if (depth == 0)
1204     RetAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, RetReg, VT);
1205   else {
1206     // flush first to make sure the windowed registers' values are in stack
1207     SDValue Chain = getFLUSHW(Op, DAG);
1208     RetAddr = DAG.getCopyFromReg(Chain, dl, SP::I6, VT);
1209
1210     for (uint64_t i = 0; i != depth; ++i) {
1211       SDValue Ptr = DAG.getNode(ISD::ADD,
1212                                 dl, MVT::i32,
1213                                 RetAddr,
1214                                 DAG.getIntPtrConstant((i == depth-1)?60:56));
1215       RetAddr = DAG.getLoad(MVT::i32, dl,
1216                             Chain,
1217                             Ptr,
1218                             MachinePointerInfo(), false, false, false, 0);
1219     }
1220   }
1221   return RetAddr;
1222 }
1223
1224 SDValue SparcTargetLowering::
1225 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1226   switch (Op.getOpcode()) {
1227   default: llvm_unreachable("Should not custom lower this!");
1228   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
1229   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
1230   case ISD::GlobalTLSAddress:
1231     llvm_unreachable("TLS not implemented for Sparc.");
1232   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
1233   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
1234   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
1235   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
1236   case ISD::BR_CC:              return LowerBR_CC(Op, DAG);
1237   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
1238   case ISD::VASTART:            return LowerVASTART(Op, DAG, *this);
1239   case ISD::VAARG:              return LowerVAARG(Op, DAG);
1240   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
1241   }
1242 }
1243
1244 MachineBasicBlock *
1245 SparcTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1246                                                  MachineBasicBlock *BB) const {
1247   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1248   unsigned BROpcode;
1249   unsigned CC;
1250   DebugLoc dl = MI->getDebugLoc();
1251   // Figure out the conditional branch opcode to use for this select_cc.
1252   switch (MI->getOpcode()) {
1253   default: llvm_unreachable("Unknown SELECT_CC!");
1254   case SP::SELECT_CC_Int_ICC:
1255   case SP::SELECT_CC_FP_ICC:
1256   case SP::SELECT_CC_DFP_ICC:
1257     BROpcode = SP::BCOND;
1258     break;
1259   case SP::SELECT_CC_Int_FCC:
1260   case SP::SELECT_CC_FP_FCC:
1261   case SP::SELECT_CC_DFP_FCC:
1262     BROpcode = SP::FBCOND;
1263     break;
1264   }
1265
1266   CC = (SPCC::CondCodes)MI->getOperand(3).getImm();
1267
1268   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1269   // control-flow pattern.  The incoming instruction knows the destination vreg
1270   // to set, the condition code register to branch on, the true/false values to
1271   // select between, and a branch opcode to use.
1272   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1273   MachineFunction::iterator It = BB;
1274   ++It;
1275
1276   //  thisMBB:
1277   //  ...
1278   //   TrueVal = ...
1279   //   [f]bCC copy1MBB
1280   //   fallthrough --> copy0MBB
1281   MachineBasicBlock *thisMBB = BB;
1282   MachineFunction *F = BB->getParent();
1283   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1284   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1285   F->insert(It, copy0MBB);
1286   F->insert(It, sinkMBB);
1287
1288   // Transfer the remainder of BB and its successor edges to sinkMBB.
1289   sinkMBB->splice(sinkMBB->begin(), BB,
1290                   llvm::next(MachineBasicBlock::iterator(MI)),
1291                   BB->end());
1292   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1293
1294   // Add the true and fallthrough blocks as its successors.
1295   BB->addSuccessor(copy0MBB);
1296   BB->addSuccessor(sinkMBB);
1297
1298   BuildMI(BB, dl, TII.get(BROpcode)).addMBB(sinkMBB).addImm(CC);
1299
1300   //  copy0MBB:
1301   //   %FalseValue = ...
1302   //   # fallthrough to sinkMBB
1303   BB = copy0MBB;
1304
1305   // Update machine-CFG edges
1306   BB->addSuccessor(sinkMBB);
1307
1308   //  sinkMBB:
1309   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1310   //  ...
1311   BB = sinkMBB;
1312   BuildMI(*BB, BB->begin(), dl, TII.get(SP::PHI), MI->getOperand(0).getReg())
1313     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1314     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1315
1316   MI->eraseFromParent();   // The pseudo instruction is gone now.
1317   return BB;
1318 }
1319
1320 //===----------------------------------------------------------------------===//
1321 //                         Sparc Inline Assembly Support
1322 //===----------------------------------------------------------------------===//
1323
1324 /// getConstraintType - Given a constraint letter, return the type of
1325 /// constraint it is for this target.
1326 SparcTargetLowering::ConstraintType
1327 SparcTargetLowering::getConstraintType(const std::string &Constraint) const {
1328   if (Constraint.size() == 1) {
1329     switch (Constraint[0]) {
1330     default:  break;
1331     case 'r': return C_RegisterClass;
1332     }
1333   }
1334
1335   return TargetLowering::getConstraintType(Constraint);
1336 }
1337
1338 std::pair<unsigned, const TargetRegisterClass*>
1339 SparcTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
1340                                                   EVT VT) const {
1341   if (Constraint.size() == 1) {
1342     switch (Constraint[0]) {
1343     case 'r':
1344       return std::make_pair(0U, &SP::IntRegsRegClass);
1345     }
1346   }
1347
1348   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1349 }
1350
1351 bool
1352 SparcTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1353   // The Sparc target isn't yet aware of offsets.
1354   return false;
1355 }