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 "MCTargetDesc/SparcMCExpr.h"
17 #include "SparcMachineFunctionInfo.h"
18 #include "SparcRegisterInfo.h"
19 #include "SparcTargetMachine.h"
20 #include "SparcTargetObjectFile.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/SelectionDAG.h"
28 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/KnownBits.h"
34 using namespace llvm;
35 
36 
37 //===----------------------------------------------------------------------===//
38 // Calling Convention Implementation
39 //===----------------------------------------------------------------------===//
40 
CC_Sparc_Assign_SRet(unsigned & ValNo,MVT & ValVT,MVT & LocVT,CCValAssign::LocInfo & LocInfo,ISD::ArgFlagsTy & ArgFlags,CCState & State)41 static bool CC_Sparc_Assign_SRet(unsigned &ValNo, MVT &ValVT,
42                                  MVT &LocVT, CCValAssign::LocInfo &LocInfo,
43                                  ISD::ArgFlagsTy &ArgFlags, CCState &State)
44 {
45   assert (ArgFlags.isSRet());
46 
47   // Assign SRet argument.
48   State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
49                                          0,
50                                          LocVT, LocInfo));
51   return true;
52 }
53 
CC_Sparc_Assign_Split_64(unsigned & ValNo,MVT & ValVT,MVT & LocVT,CCValAssign::LocInfo & LocInfo,ISD::ArgFlagsTy & ArgFlags,CCState & State)54 static bool CC_Sparc_Assign_Split_64(unsigned &ValNo, MVT &ValVT,
55                                      MVT &LocVT, CCValAssign::LocInfo &LocInfo,
56                                      ISD::ArgFlagsTy &ArgFlags, CCState &State)
57 {
58   static const MCPhysReg RegList[] = {
59     SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
60   };
61   // Try to get first reg.
62   if (unsigned Reg = State.AllocateReg(RegList)) {
63     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
64   } else {
65     // Assign whole thing in stack.
66     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
67                                            State.AllocateStack(8,4),
68                                            LocVT, LocInfo));
69     return true;
70   }
71 
72   // Try to get second reg.
73   if (unsigned Reg = State.AllocateReg(RegList))
74     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
75   else
76     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
77                                            State.AllocateStack(4,4),
78                                            LocVT, LocInfo));
79   return true;
80 }
81 
CC_Sparc_Assign_Ret_Split_64(unsigned & ValNo,MVT & ValVT,MVT & LocVT,CCValAssign::LocInfo & LocInfo,ISD::ArgFlagsTy & ArgFlags,CCState & State)82 static bool CC_Sparc_Assign_Ret_Split_64(unsigned &ValNo, MVT &ValVT,
83                                          MVT &LocVT, CCValAssign::LocInfo &LocInfo,
84                                          ISD::ArgFlagsTy &ArgFlags, CCState &State)
85 {
86   static const MCPhysReg RegList[] = {
87     SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
88   };
89 
90   // Try to get first reg.
91   if (unsigned Reg = State.AllocateReg(RegList))
92     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
93   else
94     return false;
95 
96   // Try to get second reg.
97   if (unsigned Reg = State.AllocateReg(RegList))
98     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
99   else
100     return false;
101 
102   return true;
103 }
104 
105 // Allocate a full-sized argument for the 64-bit ABI.
CC_Sparc64_Full(unsigned & ValNo,MVT & ValVT,MVT & LocVT,CCValAssign::LocInfo & LocInfo,ISD::ArgFlagsTy & ArgFlags,CCState & State)106 static bool CC_Sparc64_Full(unsigned &ValNo, MVT &ValVT,
107                             MVT &LocVT, CCValAssign::LocInfo &LocInfo,
108                             ISD::ArgFlagsTy &ArgFlags, CCState &State) {
109   assert((LocVT == MVT::f32 || LocVT == MVT::f128
110           || LocVT.getSizeInBits() == 64) &&
111          "Can't handle non-64 bits locations");
112 
113   // Stack space is allocated for all arguments starting from [%fp+BIAS+128].
114   unsigned size      = (LocVT == MVT::f128) ? 16 : 8;
115   unsigned alignment = (LocVT == MVT::f128) ? 16 : 8;
116   unsigned Offset = State.AllocateStack(size, alignment);
117   unsigned Reg = 0;
118 
119   if (LocVT == MVT::i64 && Offset < 6*8)
120     // Promote integers to %i0-%i5.
121     Reg = SP::I0 + Offset/8;
122   else if (LocVT == MVT::f64 && Offset < 16*8)
123     // Promote doubles to %d0-%d30. (Which LLVM calls D0-D15).
124     Reg = SP::D0 + Offset/8;
125   else if (LocVT == MVT::f32 && Offset < 16*8)
126     // Promote floats to %f1, %f3, ...
127     Reg = SP::F1 + Offset/4;
128   else if (LocVT == MVT::f128 && Offset < 16*8)
129     // Promote long doubles to %q0-%q28. (Which LLVM calls Q0-Q7).
130     Reg = SP::Q0 + Offset/16;
131 
132   // Promote to register when possible, otherwise use the stack slot.
133   if (Reg) {
134     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
135     return true;
136   }
137 
138   // This argument goes on the stack in an 8-byte slot.
139   // When passing floats, LocVT is smaller than 8 bytes. Adjust the offset to
140   // the right-aligned float. The first 4 bytes of the stack slot are undefined.
141   if (LocVT == MVT::f32)
142     Offset += 4;
143 
144   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
145   return true;
146 }
147 
148 // Allocate a half-sized argument for the 64-bit ABI.
149 //
150 // This is used when passing { float, int } structs by value in registers.
CC_Sparc64_Half(unsigned & ValNo,MVT & ValVT,MVT & LocVT,CCValAssign::LocInfo & LocInfo,ISD::ArgFlagsTy & ArgFlags,CCState & State)151 static bool CC_Sparc64_Half(unsigned &ValNo, MVT &ValVT,
152                             MVT &LocVT, CCValAssign::LocInfo &LocInfo,
153                             ISD::ArgFlagsTy &ArgFlags, CCState &State) {
154   assert(LocVT.getSizeInBits() == 32 && "Can't handle non-32 bits locations");
155   unsigned Offset = State.AllocateStack(4, 4);
156 
157   if (LocVT == MVT::f32 && Offset < 16*8) {
158     // Promote floats to %f0-%f31.
159     State.addLoc(CCValAssign::getReg(ValNo, ValVT, SP::F0 + Offset/4,
160                                      LocVT, LocInfo));
161     return true;
162   }
163 
164   if (LocVT == MVT::i32 && Offset < 6*8) {
165     // Promote integers to %i0-%i5, using half the register.
166     unsigned Reg = SP::I0 + Offset/8;
167     LocVT = MVT::i64;
168     LocInfo = CCValAssign::AExt;
169 
170     // Set the Custom bit if this i32 goes in the high bits of a register.
171     if (Offset % 8 == 0)
172       State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg,
173                                              LocVT, LocInfo));
174     else
175       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
176     return true;
177   }
178 
179   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
180   return true;
181 }
182 
183 #include "SparcGenCallingConv.inc"
184 
185 // The calling conventions in SparcCallingConv.td are described in terms of the
186 // callee's register window. This function translates registers to the
187 // corresponding caller window %o register.
toCallerWindow(unsigned Reg)188 static unsigned toCallerWindow(unsigned Reg) {
189   static_assert(SP::I0 + 7 == SP::I7 && SP::O0 + 7 == SP::O7,
190                 "Unexpected enum");
191   if (Reg >= SP::I0 && Reg <= SP::I7)
192     return Reg - SP::I0 + SP::O0;
193   return Reg;
194 }
195 
196 SDValue
LowerReturn(SDValue Chain,CallingConv::ID CallConv,bool IsVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SDLoc & DL,SelectionDAG & DAG) const197 SparcTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
198                                  bool IsVarArg,
199                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
200                                  const SmallVectorImpl<SDValue> &OutVals,
201                                  const SDLoc &DL, SelectionDAG &DAG) const {
202   if (Subtarget->is64Bit())
203     return LowerReturn_64(Chain, CallConv, IsVarArg, Outs, OutVals, DL, DAG);
204   return LowerReturn_32(Chain, CallConv, IsVarArg, Outs, OutVals, DL, DAG);
205 }
206 
207 SDValue
LowerReturn_32(SDValue Chain,CallingConv::ID CallConv,bool IsVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SDLoc & DL,SelectionDAG & DAG) const208 SparcTargetLowering::LowerReturn_32(SDValue Chain, CallingConv::ID CallConv,
209                                     bool IsVarArg,
210                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
211                                     const SmallVectorImpl<SDValue> &OutVals,
212                                     const SDLoc &DL, SelectionDAG &DAG) const {
213   MachineFunction &MF = DAG.getMachineFunction();
214 
215   // CCValAssign - represent the assignment of the return value to locations.
216   SmallVector<CCValAssign, 16> RVLocs;
217 
218   // CCState - Info about the registers and stack slot.
219   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
220                  *DAG.getContext());
221 
222   // Analyze return values.
223   CCInfo.AnalyzeReturn(Outs, RetCC_Sparc32);
224 
225   SDValue Flag;
226   SmallVector<SDValue, 4> RetOps(1, Chain);
227   // Make room for the return address offset.
228   RetOps.push_back(SDValue());
229 
230   // Copy the result values into the output registers.
231   for (unsigned i = 0, realRVLocIdx = 0;
232        i != RVLocs.size();
233        ++i, ++realRVLocIdx) {
234     CCValAssign &VA = RVLocs[i];
235     assert(VA.isRegLoc() && "Can only return in registers!");
236 
237     SDValue Arg = OutVals[realRVLocIdx];
238 
239     if (VA.needsCustom()) {
240       assert(VA.getLocVT() == MVT::v2i32);
241       // Legalize ret v2i32 -> ret 2 x i32 (Basically: do what would
242       // happen by default if this wasn't a legal type)
243 
244       SDValue Part0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
245                                   Arg,
246                                   DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout())));
247       SDValue Part1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
248                                   Arg,
249                                   DAG.getConstant(1, DL, getVectorIdxTy(DAG.getDataLayout())));
250 
251       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Part0, Flag);
252       Flag = Chain.getValue(1);
253       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
254       VA = RVLocs[++i]; // skip ahead to next loc
255       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Part1,
256                                Flag);
257     } else
258       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
259 
260     // Guarantee that all emitted copies are stuck together with flags.
261     Flag = Chain.getValue(1);
262     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
263   }
264 
265   unsigned RetAddrOffset = 8; // Call Inst + Delay Slot
266   // If the function returns a struct, copy the SRetReturnReg to I0
267   if (MF.getFunction().hasStructRetAttr()) {
268     SparcMachineFunctionInfo *SFI = MF.getInfo<SparcMachineFunctionInfo>();
269     unsigned Reg = SFI->getSRetReturnReg();
270     if (!Reg)
271       llvm_unreachable("sret virtual register not created in the entry block");
272     auto PtrVT = getPointerTy(DAG.getDataLayout());
273     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, PtrVT);
274     Chain = DAG.getCopyToReg(Chain, DL, SP::I0, Val, Flag);
275     Flag = Chain.getValue(1);
276     RetOps.push_back(DAG.getRegister(SP::I0, PtrVT));
277     RetAddrOffset = 12; // CallInst + Delay Slot + Unimp
278   }
279 
280   RetOps[0] = Chain;  // Update chain.
281   RetOps[1] = DAG.getConstant(RetAddrOffset, DL, MVT::i32);
282 
283   // Add the flag if we have it.
284   if (Flag.getNode())
285     RetOps.push_back(Flag);
286 
287   return DAG.getNode(SPISD::RET_FLAG, DL, MVT::Other, RetOps);
288 }
289 
290 // Lower return values for the 64-bit ABI.
291 // Return values are passed the exactly the same way as function arguments.
292 SDValue
LowerReturn_64(SDValue Chain,CallingConv::ID CallConv,bool IsVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SDLoc & DL,SelectionDAG & DAG) const293 SparcTargetLowering::LowerReturn_64(SDValue Chain, CallingConv::ID CallConv,
294                                     bool IsVarArg,
295                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
296                                     const SmallVectorImpl<SDValue> &OutVals,
297                                     const SDLoc &DL, SelectionDAG &DAG) const {
298   // CCValAssign - represent the assignment of the return value to locations.
299   SmallVector<CCValAssign, 16> RVLocs;
300 
301   // CCState - Info about the registers and stack slot.
302   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
303                  *DAG.getContext());
304 
305   // Analyze return values.
306   CCInfo.AnalyzeReturn(Outs, RetCC_Sparc64);
307 
308   SDValue Flag;
309   SmallVector<SDValue, 4> RetOps(1, Chain);
310 
311   // The second operand on the return instruction is the return address offset.
312   // The return address is always %i7+8 with the 64-bit ABI.
313   RetOps.push_back(DAG.getConstant(8, DL, MVT::i32));
314 
315   // Copy the result values into the output registers.
316   for (unsigned i = 0; i != RVLocs.size(); ++i) {
317     CCValAssign &VA = RVLocs[i];
318     assert(VA.isRegLoc() && "Can only return in registers!");
319     SDValue OutVal = OutVals[i];
320 
321     // Integer return values must be sign or zero extended by the callee.
322     switch (VA.getLocInfo()) {
323     case CCValAssign::Full: break;
324     case CCValAssign::SExt:
325       OutVal = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), OutVal);
326       break;
327     case CCValAssign::ZExt:
328       OutVal = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), OutVal);
329       break;
330     case CCValAssign::AExt:
331       OutVal = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), OutVal);
332       break;
333     default:
334       llvm_unreachable("Unknown loc info!");
335     }
336 
337     // The custom bit on an i32 return value indicates that it should be passed
338     // in the high bits of the register.
339     if (VA.getValVT() == MVT::i32 && VA.needsCustom()) {
340       OutVal = DAG.getNode(ISD::SHL, DL, MVT::i64, OutVal,
341                            DAG.getConstant(32, DL, MVT::i32));
342 
343       // The next value may go in the low bits of the same register.
344       // Handle both at once.
345       if (i+1 < RVLocs.size() && RVLocs[i+1].getLocReg() == VA.getLocReg()) {
346         SDValue NV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, OutVals[i+1]);
347         OutVal = DAG.getNode(ISD::OR, DL, MVT::i64, OutVal, NV);
348         // Skip the next value, it's already done.
349         ++i;
350       }
351     }
352 
353     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVal, Flag);
354 
355     // Guarantee that all emitted copies are stuck together with flags.
356     Flag = Chain.getValue(1);
357     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
358   }
359 
360   RetOps[0] = Chain;  // Update chain.
361 
362   // Add the flag if we have it.
363   if (Flag.getNode())
364     RetOps.push_back(Flag);
365 
366   return DAG.getNode(SPISD::RET_FLAG, DL, MVT::Other, RetOps);
367 }
368 
LowerFormalArguments(SDValue Chain,CallingConv::ID CallConv,bool IsVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & DL,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const369 SDValue SparcTargetLowering::LowerFormalArguments(
370     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
371     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
372     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
373   if (Subtarget->is64Bit())
374     return LowerFormalArguments_64(Chain, CallConv, IsVarArg, Ins,
375                                    DL, DAG, InVals);
376   return LowerFormalArguments_32(Chain, CallConv, IsVarArg, Ins,
377                                  DL, DAG, InVals);
378 }
379 
380 /// LowerFormalArguments32 - V8 uses a very simple ABI, where all values are
381 /// passed in either one or two GPRs, including FP values.  TODO: we should
382 /// pass FP values in FP registers for fastcc functions.
LowerFormalArguments_32(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const383 SDValue SparcTargetLowering::LowerFormalArguments_32(
384     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
385     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
386     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
387   MachineFunction &MF = DAG.getMachineFunction();
388   MachineRegisterInfo &RegInfo = MF.getRegInfo();
389   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
390 
391   // Assign locations to all of the incoming arguments.
392   SmallVector<CCValAssign, 16> ArgLocs;
393   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
394                  *DAG.getContext());
395   CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc32);
396 
397   const unsigned StackOffset = 92;
398   bool IsLittleEndian = DAG.getDataLayout().isLittleEndian();
399 
400   unsigned InIdx = 0;
401   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i, ++InIdx) {
402     CCValAssign &VA = ArgLocs[i];
403 
404     if (Ins[InIdx].Flags.isSRet()) {
405       if (InIdx != 0)
406         report_fatal_error("sparc only supports sret on the first parameter");
407       // Get SRet from [%fp+64].
408       int FrameIdx = MF.getFrameInfo().CreateFixedObject(4, 64, true);
409       SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
410       SDValue Arg =
411           DAG.getLoad(MVT::i32, dl, Chain, FIPtr, MachinePointerInfo());
412       InVals.push_back(Arg);
413       continue;
414     }
415 
416     if (VA.isRegLoc()) {
417       if (VA.needsCustom()) {
418         assert(VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2i32);
419 
420         unsigned VRegHi = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
421         MF.getRegInfo().addLiveIn(VA.getLocReg(), VRegHi);
422         SDValue HiVal = DAG.getCopyFromReg(Chain, dl, VRegHi, MVT::i32);
423 
424         assert(i+1 < e);
425         CCValAssign &NextVA = ArgLocs[++i];
426 
427         SDValue LoVal;
428         if (NextVA.isMemLoc()) {
429           int FrameIdx = MF.getFrameInfo().
430             CreateFixedObject(4, StackOffset+NextVA.getLocMemOffset(),true);
431           SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
432           LoVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr, MachinePointerInfo());
433         } else {
434           unsigned loReg = MF.addLiveIn(NextVA.getLocReg(),
435                                         &SP::IntRegsRegClass);
436           LoVal = DAG.getCopyFromReg(Chain, dl, loReg, MVT::i32);
437         }
438 
439         if (IsLittleEndian)
440           std::swap(LoVal, HiVal);
441 
442         SDValue WholeValue =
443           DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
444         WholeValue = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), WholeValue);
445         InVals.push_back(WholeValue);
446         continue;
447       }
448       unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
449       MF.getRegInfo().addLiveIn(VA.getLocReg(), VReg);
450       SDValue Arg = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
451       if (VA.getLocVT() == MVT::f32)
452         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Arg);
453       else if (VA.getLocVT() != MVT::i32) {
454         Arg = DAG.getNode(ISD::AssertSext, dl, MVT::i32, Arg,
455                           DAG.getValueType(VA.getLocVT()));
456         Arg = DAG.getNode(ISD::TRUNCATE, dl, VA.getLocVT(), Arg);
457       }
458       InVals.push_back(Arg);
459       continue;
460     }
461 
462     assert(VA.isMemLoc());
463 
464     unsigned Offset = VA.getLocMemOffset()+StackOffset;
465     auto PtrVT = getPointerTy(DAG.getDataLayout());
466 
467     if (VA.needsCustom()) {
468       assert(VA.getValVT() == MVT::f64 || VA.getValVT() == MVT::v2i32);
469       // If it is double-word aligned, just load.
470       if (Offset % 8 == 0) {
471         int FI = MF.getFrameInfo().CreateFixedObject(8,
472                                                      Offset,
473                                                      true);
474         SDValue FIPtr = DAG.getFrameIndex(FI, PtrVT);
475         SDValue Load =
476             DAG.getLoad(VA.getValVT(), dl, Chain, FIPtr, MachinePointerInfo());
477         InVals.push_back(Load);
478         continue;
479       }
480 
481       int FI = MF.getFrameInfo().CreateFixedObject(4,
482                                                    Offset,
483                                                    true);
484       SDValue FIPtr = DAG.getFrameIndex(FI, PtrVT);
485       SDValue HiVal =
486           DAG.getLoad(MVT::i32, dl, Chain, FIPtr, MachinePointerInfo());
487       int FI2 = MF.getFrameInfo().CreateFixedObject(4,
488                                                     Offset+4,
489                                                     true);
490       SDValue FIPtr2 = DAG.getFrameIndex(FI2, PtrVT);
491 
492       SDValue LoVal =
493           DAG.getLoad(MVT::i32, dl, Chain, FIPtr2, MachinePointerInfo());
494 
495       if (IsLittleEndian)
496         std::swap(LoVal, HiVal);
497 
498       SDValue WholeValue =
499         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
500       WholeValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), WholeValue);
501       InVals.push_back(WholeValue);
502       continue;
503     }
504 
505     int FI = MF.getFrameInfo().CreateFixedObject(4,
506                                                  Offset,
507                                                  true);
508     SDValue FIPtr = DAG.getFrameIndex(FI, PtrVT);
509     SDValue Load ;
510     if (VA.getValVT() == MVT::i32 || VA.getValVT() == MVT::f32) {
511       Load = DAG.getLoad(VA.getValVT(), dl, Chain, FIPtr, MachinePointerInfo());
512     } else if (VA.getValVT() == MVT::f128) {
513       report_fatal_error("SPARCv8 does not handle f128 in calls; "
514                          "pass indirectly");
515     } else {
516       // We shouldn't see any other value types here.
517       llvm_unreachable("Unexpected ValVT encountered in frame lowering.");
518     }
519     InVals.push_back(Load);
520   }
521 
522   if (MF.getFunction().hasStructRetAttr()) {
523     // Copy the SRet Argument to SRetReturnReg.
524     SparcMachineFunctionInfo *SFI = MF.getInfo<SparcMachineFunctionInfo>();
525     unsigned Reg = SFI->getSRetReturnReg();
526     if (!Reg) {
527       Reg = MF.getRegInfo().createVirtualRegister(&SP::IntRegsRegClass);
528       SFI->setSRetReturnReg(Reg);
529     }
530     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
531     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
532   }
533 
534   // Store remaining ArgRegs to the stack if this is a varargs function.
535   if (isVarArg) {
536     static const MCPhysReg ArgRegs[] = {
537       SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
538     };
539     unsigned NumAllocated = CCInfo.getFirstUnallocated(ArgRegs);
540     const MCPhysReg *CurArgReg = ArgRegs+NumAllocated, *ArgRegEnd = ArgRegs+6;
541     unsigned ArgOffset = CCInfo.getNextStackOffset();
542     if (NumAllocated == 6)
543       ArgOffset += StackOffset;
544     else {
545       assert(!ArgOffset);
546       ArgOffset = 68+4*NumAllocated;
547     }
548 
549     // Remember the vararg offset for the va_start implementation.
550     FuncInfo->setVarArgsFrameOffset(ArgOffset);
551 
552     std::vector<SDValue> OutChains;
553 
554     for (; CurArgReg != ArgRegEnd; ++CurArgReg) {
555       unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
556       MF.getRegInfo().addLiveIn(*CurArgReg, VReg);
557       SDValue Arg = DAG.getCopyFromReg(DAG.getRoot(), dl, VReg, MVT::i32);
558 
559       int FrameIdx = MF.getFrameInfo().CreateFixedObject(4, ArgOffset,
560                                                          true);
561       SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
562 
563       OutChains.push_back(
564           DAG.getStore(DAG.getRoot(), dl, Arg, FIPtr, MachinePointerInfo()));
565       ArgOffset += 4;
566     }
567 
568     if (!OutChains.empty()) {
569       OutChains.push_back(Chain);
570       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
571     }
572   }
573 
574   return Chain;
575 }
576 
577 // Lower formal arguments for the 64 bit ABI.
LowerFormalArguments_64(SDValue Chain,CallingConv::ID CallConv,bool IsVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & DL,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const578 SDValue SparcTargetLowering::LowerFormalArguments_64(
579     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
580     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
581     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
582   MachineFunction &MF = DAG.getMachineFunction();
583 
584   // Analyze arguments according to CC_Sparc64.
585   SmallVector<CCValAssign, 16> ArgLocs;
586   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
587                  *DAG.getContext());
588   CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc64);
589 
590   // The argument array begins at %fp+BIAS+128, after the register save area.
591   const unsigned ArgArea = 128;
592 
593   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
594     CCValAssign &VA = ArgLocs[i];
595     if (VA.isRegLoc()) {
596       // This argument is passed in a register.
597       // All integer register arguments are promoted by the caller to i64.
598 
599       // Create a virtual register for the promoted live-in value.
600       unsigned VReg = MF.addLiveIn(VA.getLocReg(),
601                                    getRegClassFor(VA.getLocVT()));
602       SDValue Arg = DAG.getCopyFromReg(Chain, DL, VReg, VA.getLocVT());
603 
604       // Get the high bits for i32 struct elements.
605       if (VA.getValVT() == MVT::i32 && VA.needsCustom())
606         Arg = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Arg,
607                           DAG.getConstant(32, DL, MVT::i32));
608 
609       // The caller promoted the argument, so insert an Assert?ext SDNode so we
610       // won't promote the value again in this function.
611       switch (VA.getLocInfo()) {
612       case CCValAssign::SExt:
613         Arg = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Arg,
614                           DAG.getValueType(VA.getValVT()));
615         break;
616       case CCValAssign::ZExt:
617         Arg = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Arg,
618                           DAG.getValueType(VA.getValVT()));
619         break;
620       default:
621         break;
622       }
623 
624       // Truncate the register down to the argument type.
625       if (VA.isExtInLoc())
626         Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
627 
628       InVals.push_back(Arg);
629       continue;
630     }
631 
632     // The registers are exhausted. This argument was passed on the stack.
633     assert(VA.isMemLoc());
634     // The CC_Sparc64_Full/Half functions compute stack offsets relative to the
635     // beginning of the arguments area at %fp+BIAS+128.
636     unsigned Offset = VA.getLocMemOffset() + ArgArea;
637     unsigned ValSize = VA.getValVT().getSizeInBits() / 8;
638     // Adjust offset for extended arguments, SPARC is big-endian.
639     // The caller will have written the full slot with extended bytes, but we
640     // prefer our own extending loads.
641     if (VA.isExtInLoc())
642       Offset += 8 - ValSize;
643     int FI = MF.getFrameInfo().CreateFixedObject(ValSize, Offset, true);
644     InVals.push_back(
645         DAG.getLoad(VA.getValVT(), DL, Chain,
646                     DAG.getFrameIndex(FI, getPointerTy(MF.getDataLayout())),
647                     MachinePointerInfo::getFixedStack(MF, FI)));
648   }
649 
650   if (!IsVarArg)
651     return Chain;
652 
653   // This function takes variable arguments, some of which may have been passed
654   // in registers %i0-%i5. Variable floating point arguments are never passed
655   // in floating point registers. They go on %i0-%i5 or on the stack like
656   // integer arguments.
657   //
658   // The va_start intrinsic needs to know the offset to the first variable
659   // argument.
660   unsigned ArgOffset = CCInfo.getNextStackOffset();
661   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
662   // Skip the 128 bytes of register save area.
663   FuncInfo->setVarArgsFrameOffset(ArgOffset + ArgArea +
664                                   Subtarget->getStackPointerBias());
665 
666   // Save the variable arguments that were passed in registers.
667   // The caller is required to reserve stack space for 6 arguments regardless
668   // of how many arguments were actually passed.
669   SmallVector<SDValue, 8> OutChains;
670   for (; ArgOffset < 6*8; ArgOffset += 8) {
671     unsigned VReg = MF.addLiveIn(SP::I0 + ArgOffset/8, &SP::I64RegsRegClass);
672     SDValue VArg = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
673     int FI = MF.getFrameInfo().CreateFixedObject(8, ArgOffset + ArgArea, true);
674     auto PtrVT = getPointerTy(MF.getDataLayout());
675     OutChains.push_back(
676         DAG.getStore(Chain, DL, VArg, DAG.getFrameIndex(FI, PtrVT),
677                      MachinePointerInfo::getFixedStack(MF, FI)));
678   }
679 
680   if (!OutChains.empty())
681     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
682 
683   return Chain;
684 }
685 
686 SDValue
LowerCall(TargetLowering::CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const687 SparcTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
688                                SmallVectorImpl<SDValue> &InVals) const {
689   if (Subtarget->is64Bit())
690     return LowerCall_64(CLI, InVals);
691   return LowerCall_32(CLI, InVals);
692 }
693 
hasReturnsTwiceAttr(SelectionDAG & DAG,SDValue Callee,ImmutableCallSite CS)694 static bool hasReturnsTwiceAttr(SelectionDAG &DAG, SDValue Callee,
695                                 ImmutableCallSite CS) {
696   if (CS)
697     return CS.hasFnAttr(Attribute::ReturnsTwice);
698 
699   const Function *CalleeFn = nullptr;
700   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
701     CalleeFn = dyn_cast<Function>(G->getGlobal());
702   } else if (ExternalSymbolSDNode *E =
703              dyn_cast<ExternalSymbolSDNode>(Callee)) {
704     const Function &Fn = DAG.getMachineFunction().getFunction();
705     const Module *M = Fn.getParent();
706     const char *CalleeName = E->getSymbol();
707     CalleeFn = M->getFunction(CalleeName);
708   }
709 
710   if (!CalleeFn)
711     return false;
712   return CalleeFn->hasFnAttribute(Attribute::ReturnsTwice);
713 }
714 
715 // Lower a call for the 32-bit ABI.
716 SDValue
LowerCall_32(TargetLowering::CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const717 SparcTargetLowering::LowerCall_32(TargetLowering::CallLoweringInfo &CLI,
718                                   SmallVectorImpl<SDValue> &InVals) const {
719   SelectionDAG &DAG                     = CLI.DAG;
720   SDLoc &dl                             = CLI.DL;
721   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
722   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
723   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
724   SDValue Chain                         = CLI.Chain;
725   SDValue Callee                        = CLI.Callee;
726   bool &isTailCall                      = CLI.IsTailCall;
727   CallingConv::ID CallConv              = CLI.CallConv;
728   bool isVarArg                         = CLI.IsVarArg;
729 
730   // Sparc target does not yet support tail call optimization.
731   isTailCall = false;
732 
733   // Analyze operands of the call, assigning locations to each operand.
734   SmallVector<CCValAssign, 16> ArgLocs;
735   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
736                  *DAG.getContext());
737   CCInfo.AnalyzeCallOperands(Outs, CC_Sparc32);
738 
739   // Get the size of the outgoing arguments stack space requirement.
740   unsigned ArgsSize = CCInfo.getNextStackOffset();
741 
742   // Keep stack frames 8-byte aligned.
743   ArgsSize = (ArgsSize+7) & ~7;
744 
745   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
746 
747   // Create local copies for byval args.
748   SmallVector<SDValue, 8> ByValArgs;
749   for (unsigned i = 0,  e = Outs.size(); i != e; ++i) {
750     ISD::ArgFlagsTy Flags = Outs[i].Flags;
751     if (!Flags.isByVal())
752       continue;
753 
754     SDValue Arg = OutVals[i];
755     unsigned Size = Flags.getByValSize();
756     unsigned Align = Flags.getByValAlign();
757 
758     if (Size > 0U) {
759       int FI = MFI.CreateStackObject(Size, Align, false);
760       SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
761       SDValue SizeNode = DAG.getConstant(Size, dl, MVT::i32);
762 
763       Chain = DAG.getMemcpy(Chain, dl, FIPtr, Arg, SizeNode, Align,
764                             false,        // isVolatile,
765                             (Size <= 32), // AlwaysInline if size <= 32,
766                             false,        // isTailCall
767                             MachinePointerInfo(), MachinePointerInfo());
768       ByValArgs.push_back(FIPtr);
769     }
770     else {
771       SDValue nullVal;
772       ByValArgs.push_back(nullVal);
773     }
774   }
775 
776   Chain = DAG.getCALLSEQ_START(Chain, ArgsSize, 0, dl);
777 
778   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
779   SmallVector<SDValue, 8> MemOpChains;
780 
781   const unsigned StackOffset = 92;
782   bool hasStructRetAttr = false;
783   // Walk the register/memloc assignments, inserting copies/loads.
784   for (unsigned i = 0, realArgIdx = 0, byvalArgIdx = 0, e = ArgLocs.size();
785        i != e;
786        ++i, ++realArgIdx) {
787     CCValAssign &VA = ArgLocs[i];
788     SDValue Arg = OutVals[realArgIdx];
789 
790     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
791 
792     // Use local copy if it is a byval arg.
793     if (Flags.isByVal()) {
794       Arg = ByValArgs[byvalArgIdx++];
795       if (!Arg) {
796         continue;
797       }
798     }
799 
800     // Promote the value if needed.
801     switch (VA.getLocInfo()) {
802     default: llvm_unreachable("Unknown loc info!");
803     case CCValAssign::Full: break;
804     case CCValAssign::SExt:
805       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
806       break;
807     case CCValAssign::ZExt:
808       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
809       break;
810     case CCValAssign::AExt:
811       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
812       break;
813     case CCValAssign::BCvt:
814       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
815       break;
816     }
817 
818     if (Flags.isSRet()) {
819       assert(VA.needsCustom());
820       // store SRet argument in %sp+64
821       SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
822       SDValue PtrOff = DAG.getIntPtrConstant(64, dl);
823       PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
824       MemOpChains.push_back(
825           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
826       hasStructRetAttr = true;
827       continue;
828     }
829 
830     if (VA.needsCustom()) {
831       assert(VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2i32);
832 
833       if (VA.isMemLoc()) {
834         unsigned Offset = VA.getLocMemOffset() + StackOffset;
835         // if it is double-word aligned, just store.
836         if (Offset % 8 == 0) {
837           SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
838           SDValue PtrOff = DAG.getIntPtrConstant(Offset, dl);
839           PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
840           MemOpChains.push_back(
841               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
842           continue;
843         }
844       }
845 
846       if (VA.getLocVT() == MVT::f64) {
847         // Move from the float value from float registers into the
848         // integer registers.
849 
850         // TODO: The f64 -> v2i32 conversion is super-inefficient for
851         // constants: it sticks them in the constant pool, then loads
852         // to a fp register, then stores to temp memory, then loads to
853         // integer registers.
854         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::v2i32, Arg);
855       }
856 
857       SDValue Part0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
858                                   Arg,
859                                   DAG.getConstant(0, dl, getVectorIdxTy(DAG.getDataLayout())));
860       SDValue Part1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
861                                   Arg,
862                                   DAG.getConstant(1, dl, getVectorIdxTy(DAG.getDataLayout())));
863 
864       if (VA.isRegLoc()) {
865         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Part0));
866         assert(i+1 != e);
867         CCValAssign &NextVA = ArgLocs[++i];
868         if (NextVA.isRegLoc()) {
869           RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Part1));
870         } else {
871           // Store the second part in stack.
872           unsigned Offset = NextVA.getLocMemOffset() + StackOffset;
873           SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
874           SDValue PtrOff = DAG.getIntPtrConstant(Offset, dl);
875           PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
876           MemOpChains.push_back(
877               DAG.getStore(Chain, dl, Part1, PtrOff, MachinePointerInfo()));
878         }
879       } else {
880         unsigned Offset = VA.getLocMemOffset() + StackOffset;
881         // Store the first part.
882         SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
883         SDValue PtrOff = DAG.getIntPtrConstant(Offset, dl);
884         PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
885         MemOpChains.push_back(
886             DAG.getStore(Chain, dl, Part0, PtrOff, MachinePointerInfo()));
887         // Store the second part.
888         PtrOff = DAG.getIntPtrConstant(Offset + 4, dl);
889         PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
890         MemOpChains.push_back(
891             DAG.getStore(Chain, dl, Part1, PtrOff, MachinePointerInfo()));
892       }
893       continue;
894     }
895 
896     // Arguments that can be passed on register must be kept at
897     // RegsToPass vector
898     if (VA.isRegLoc()) {
899       if (VA.getLocVT() != MVT::f32) {
900         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
901         continue;
902       }
903       Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
904       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
905       continue;
906     }
907 
908     assert(VA.isMemLoc());
909 
910     // Create a store off the stack pointer for this argument.
911     SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
912     SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset() + StackOffset,
913                                            dl);
914     PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
915     MemOpChains.push_back(
916         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
917   }
918 
919 
920   // Emit all stores, make sure the occur before any copies into physregs.
921   if (!MemOpChains.empty())
922     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
923 
924   // Build a sequence of copy-to-reg nodes chained together with token
925   // chain and flag operands which copy the outgoing args into registers.
926   // The InFlag in necessary since all emitted instructions must be
927   // stuck together.
928   SDValue InFlag;
929   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
930     unsigned Reg = toCallerWindow(RegsToPass[i].first);
931     Chain = DAG.getCopyToReg(Chain, dl, Reg, RegsToPass[i].second, InFlag);
932     InFlag = Chain.getValue(1);
933   }
934 
935   unsigned SRetArgSize = (hasStructRetAttr)? getSRetArgSize(DAG, Callee):0;
936   bool hasReturnsTwice = hasReturnsTwiceAttr(DAG, Callee, CLI.CS);
937 
938   // If the callee is a GlobalAddress node (quite common, every direct call is)
939   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
940   // Likewise ExternalSymbol -> TargetExternalSymbol.
941   unsigned TF = isPositionIndependent() ? SparcMCExpr::VK_Sparc_WPLT30 : 0;
942   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
943     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32, 0, TF);
944   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
945     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32, TF);
946 
947   // Returns a chain & a flag for retval copy to use
948   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
949   SmallVector<SDValue, 8> Ops;
950   Ops.push_back(Chain);
951   Ops.push_back(Callee);
952   if (hasStructRetAttr)
953     Ops.push_back(DAG.getTargetConstant(SRetArgSize, dl, MVT::i32));
954   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
955     Ops.push_back(DAG.getRegister(toCallerWindow(RegsToPass[i].first),
956                                   RegsToPass[i].second.getValueType()));
957 
958   // Add a register mask operand representing the call-preserved registers.
959   const SparcRegisterInfo *TRI = Subtarget->getRegisterInfo();
960   const uint32_t *Mask =
961       ((hasReturnsTwice)
962            ? TRI->getRTCallPreservedMask(CallConv)
963            : TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv));
964   assert(Mask && "Missing call preserved mask for calling convention");
965   Ops.push_back(DAG.getRegisterMask(Mask));
966 
967   if (InFlag.getNode())
968     Ops.push_back(InFlag);
969 
970   Chain = DAG.getNode(SPISD::CALL, dl, NodeTys, Ops);
971   InFlag = Chain.getValue(1);
972 
973   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, dl, true),
974                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
975   InFlag = Chain.getValue(1);
976 
977   // Assign locations to each value returned by this call.
978   SmallVector<CCValAssign, 16> RVLocs;
979   CCState RVInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
980                  *DAG.getContext());
981 
982   RVInfo.AnalyzeCallResult(Ins, RetCC_Sparc32);
983 
984   // Copy all of the result registers out of their specified physreg.
985   for (unsigned i = 0; i != RVLocs.size(); ++i) {
986     if (RVLocs[i].getLocVT() == MVT::v2i32) {
987       SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2i32);
988       SDValue Lo = DAG.getCopyFromReg(
989           Chain, dl, toCallerWindow(RVLocs[i++].getLocReg()), MVT::i32, InFlag);
990       Chain = Lo.getValue(1);
991       InFlag = Lo.getValue(2);
992       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2i32, Vec, Lo,
993                         DAG.getConstant(0, dl, MVT::i32));
994       SDValue Hi = DAG.getCopyFromReg(
995           Chain, dl, toCallerWindow(RVLocs[i].getLocReg()), MVT::i32, InFlag);
996       Chain = Hi.getValue(1);
997       InFlag = Hi.getValue(2);
998       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2i32, Vec, Hi,
999                         DAG.getConstant(1, dl, MVT::i32));
1000       InVals.push_back(Vec);
1001     } else {
1002       Chain =
1003           DAG.getCopyFromReg(Chain, dl, toCallerWindow(RVLocs[i].getLocReg()),
1004                              RVLocs[i].getValVT(), InFlag)
1005               .getValue(1);
1006       InFlag = Chain.getValue(2);
1007       InVals.push_back(Chain.getValue(0));
1008     }
1009   }
1010 
1011   return Chain;
1012 }
1013 
1014 // FIXME? Maybe this could be a TableGen attribute on some registers and
1015 // this table could be generated automatically from RegInfo.
getRegisterByName(const char * RegName,EVT VT,SelectionDAG & DAG) const1016 unsigned SparcTargetLowering::getRegisterByName(const char* RegName, EVT VT,
1017                                                SelectionDAG &DAG) const {
1018   unsigned Reg = StringSwitch<unsigned>(RegName)
1019     .Case("i0", SP::I0).Case("i1", SP::I1).Case("i2", SP::I2).Case("i3", SP::I3)
1020     .Case("i4", SP::I4).Case("i5", SP::I5).Case("i6", SP::I6).Case("i7", SP::I7)
1021     .Case("o0", SP::O0).Case("o1", SP::O1).Case("o2", SP::O2).Case("o3", SP::O3)
1022     .Case("o4", SP::O4).Case("o5", SP::O5).Case("o6", SP::O6).Case("o7", SP::O7)
1023     .Case("l0", SP::L0).Case("l1", SP::L1).Case("l2", SP::L2).Case("l3", SP::L3)
1024     .Case("l4", SP::L4).Case("l5", SP::L5).Case("l6", SP::L6).Case("l7", SP::L7)
1025     .Case("g0", SP::G0).Case("g1", SP::G1).Case("g2", SP::G2).Case("g3", SP::G3)
1026     .Case("g4", SP::G4).Case("g5", SP::G5).Case("g6", SP::G6).Case("g7", SP::G7)
1027     .Default(0);
1028 
1029   if (Reg)
1030     return Reg;
1031 
1032   report_fatal_error("Invalid register name global variable");
1033 }
1034 
1035 // This functions returns true if CalleeName is a ABI function that returns
1036 // a long double (fp128).
isFP128ABICall(const char * CalleeName)1037 static bool isFP128ABICall(const char *CalleeName)
1038 {
1039   static const char *const ABICalls[] =
1040     {  "_Q_add", "_Q_sub", "_Q_mul", "_Q_div",
1041        "_Q_sqrt", "_Q_neg",
1042        "_Q_itoq", "_Q_stoq", "_Q_dtoq", "_Q_utoq",
1043        "_Q_lltoq", "_Q_ulltoq",
1044        nullptr
1045     };
1046   for (const char * const *I = ABICalls; *I != nullptr; ++I)
1047     if (strcmp(CalleeName, *I) == 0)
1048       return true;
1049   return false;
1050 }
1051 
1052 unsigned
getSRetArgSize(SelectionDAG & DAG,SDValue Callee) const1053 SparcTargetLowering::getSRetArgSize(SelectionDAG &DAG, SDValue Callee) const
1054 {
1055   const Function *CalleeFn = nullptr;
1056   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1057     CalleeFn = dyn_cast<Function>(G->getGlobal());
1058   } else if (ExternalSymbolSDNode *E =
1059              dyn_cast<ExternalSymbolSDNode>(Callee)) {
1060     const Function &F = DAG.getMachineFunction().getFunction();
1061     const Module *M = F.getParent();
1062     const char *CalleeName = E->getSymbol();
1063     CalleeFn = M->getFunction(CalleeName);
1064     if (!CalleeFn && isFP128ABICall(CalleeName))
1065       return 16; // Return sizeof(fp128)
1066   }
1067 
1068   if (!CalleeFn)
1069     return 0;
1070 
1071   // It would be nice to check for the sret attribute on CalleeFn here,
1072   // but since it is not part of the function type, any check will misfire.
1073 
1074   PointerType *Ty = cast<PointerType>(CalleeFn->arg_begin()->getType());
1075   Type *ElementTy = Ty->getElementType();
1076   return DAG.getDataLayout().getTypeAllocSize(ElementTy);
1077 }
1078 
1079 
1080 // Fixup floating point arguments in the ... part of a varargs call.
1081 //
1082 // The SPARC v9 ABI requires that floating point arguments are treated the same
1083 // as integers when calling a varargs function. This does not apply to the
1084 // fixed arguments that are part of the function's prototype.
1085 //
1086 // This function post-processes a CCValAssign array created by
1087 // AnalyzeCallOperands().
fixupVariableFloatArgs(SmallVectorImpl<CCValAssign> & ArgLocs,ArrayRef<ISD::OutputArg> Outs)1088 static void fixupVariableFloatArgs(SmallVectorImpl<CCValAssign> &ArgLocs,
1089                                    ArrayRef<ISD::OutputArg> Outs) {
1090   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1091     const CCValAssign &VA = ArgLocs[i];
1092     MVT ValTy = VA.getLocVT();
1093     // FIXME: What about f32 arguments? C promotes them to f64 when calling
1094     // varargs functions.
1095     if (!VA.isRegLoc() || (ValTy != MVT::f64 && ValTy != MVT::f128))
1096       continue;
1097     // The fixed arguments to a varargs function still go in FP registers.
1098     if (Outs[VA.getValNo()].IsFixed)
1099       continue;
1100 
1101     // This floating point argument should be reassigned.
1102     CCValAssign NewVA;
1103 
1104     // Determine the offset into the argument array.
1105     unsigned firstReg = (ValTy == MVT::f64) ? SP::D0 : SP::Q0;
1106     unsigned argSize  = (ValTy == MVT::f64) ? 8 : 16;
1107     unsigned Offset = argSize * (VA.getLocReg() - firstReg);
1108     assert(Offset < 16*8 && "Offset out of range, bad register enum?");
1109 
1110     if (Offset < 6*8) {
1111       // This argument should go in %i0-%i5.
1112       unsigned IReg = SP::I0 + Offset/8;
1113       if (ValTy == MVT::f64)
1114         // Full register, just bitconvert into i64.
1115         NewVA = CCValAssign::getReg(VA.getValNo(), VA.getValVT(),
1116                                     IReg, MVT::i64, CCValAssign::BCvt);
1117       else {
1118         assert(ValTy == MVT::f128 && "Unexpected type!");
1119         // Full register, just bitconvert into i128 -- We will lower this into
1120         // two i64s in LowerCall_64.
1121         NewVA = CCValAssign::getCustomReg(VA.getValNo(), VA.getValVT(),
1122                                           IReg, MVT::i128, CCValAssign::BCvt);
1123       }
1124     } else {
1125       // This needs to go to memory, we're out of integer registers.
1126       NewVA = CCValAssign::getMem(VA.getValNo(), VA.getValVT(),
1127                                   Offset, VA.getLocVT(), VA.getLocInfo());
1128     }
1129     ArgLocs[i] = NewVA;
1130   }
1131 }
1132 
1133 // Lower a call for the 64-bit ABI.
1134 SDValue
LowerCall_64(TargetLowering::CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const1135 SparcTargetLowering::LowerCall_64(TargetLowering::CallLoweringInfo &CLI,
1136                                   SmallVectorImpl<SDValue> &InVals) const {
1137   SelectionDAG &DAG = CLI.DAG;
1138   SDLoc DL = CLI.DL;
1139   SDValue Chain = CLI.Chain;
1140   auto PtrVT = getPointerTy(DAG.getDataLayout());
1141 
1142   // Sparc target does not yet support tail call optimization.
1143   CLI.IsTailCall = false;
1144 
1145   // Analyze operands of the call, assigning locations to each operand.
1146   SmallVector<CCValAssign, 16> ArgLocs;
1147   CCState CCInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(), ArgLocs,
1148                  *DAG.getContext());
1149   CCInfo.AnalyzeCallOperands(CLI.Outs, CC_Sparc64);
1150 
1151   // Get the size of the outgoing arguments stack space requirement.
1152   // The stack offset computed by CC_Sparc64 includes all arguments.
1153   // Called functions expect 6 argument words to exist in the stack frame, used
1154   // or not.
1155   unsigned ArgsSize = std::max(6*8u, CCInfo.getNextStackOffset());
1156 
1157   // Keep stack frames 16-byte aligned.
1158   ArgsSize = alignTo(ArgsSize, 16);
1159 
1160   // Varargs calls require special treatment.
1161   if (CLI.IsVarArg)
1162     fixupVariableFloatArgs(ArgLocs, CLI.Outs);
1163 
1164   // Adjust the stack pointer to make room for the arguments.
1165   // FIXME: Use hasReservedCallFrame to avoid %sp adjustments around all calls
1166   // with more than 6 arguments.
1167   Chain = DAG.getCALLSEQ_START(Chain, ArgsSize, 0, DL);
1168 
1169   // Collect the set of registers to pass to the function and their values.
1170   // This will be emitted as a sequence of CopyToReg nodes glued to the call
1171   // instruction.
1172   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1173 
1174   // Collect chains from all the memory opeations that copy arguments to the
1175   // stack. They must follow the stack pointer adjustment above and precede the
1176   // call instruction itself.
1177   SmallVector<SDValue, 8> MemOpChains;
1178 
1179   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1180     const CCValAssign &VA = ArgLocs[i];
1181     SDValue Arg = CLI.OutVals[i];
1182 
1183     // Promote the value if needed.
1184     switch (VA.getLocInfo()) {
1185     default:
1186       llvm_unreachable("Unknown location info!");
1187     case CCValAssign::Full:
1188       break;
1189     case CCValAssign::SExt:
1190       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
1191       break;
1192     case CCValAssign::ZExt:
1193       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
1194       break;
1195     case CCValAssign::AExt:
1196       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
1197       break;
1198     case CCValAssign::BCvt:
1199       // fixupVariableFloatArgs() may create bitcasts from f128 to i128. But
1200       // SPARC does not support i128 natively. Lower it into two i64, see below.
1201       if (!VA.needsCustom() || VA.getValVT() != MVT::f128
1202           || VA.getLocVT() != MVT::i128)
1203         Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1204       break;
1205     }
1206 
1207     if (VA.isRegLoc()) {
1208       if (VA.needsCustom() && VA.getValVT() == MVT::f128
1209           && VA.getLocVT() == MVT::i128) {
1210         // Store and reload into the integer register reg and reg+1.
1211         unsigned Offset = 8 * (VA.getLocReg() - SP::I0);
1212         unsigned StackOffset = Offset + Subtarget->getStackPointerBias() + 128;
1213         SDValue StackPtr = DAG.getRegister(SP::O6, PtrVT);
1214         SDValue HiPtrOff = DAG.getIntPtrConstant(StackOffset, DL);
1215         HiPtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, HiPtrOff);
1216         SDValue LoPtrOff = DAG.getIntPtrConstant(StackOffset + 8, DL);
1217         LoPtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, LoPtrOff);
1218 
1219         // Store to %sp+BIAS+128+Offset
1220         SDValue Store =
1221             DAG.getStore(Chain, DL, Arg, HiPtrOff, MachinePointerInfo());
1222         // Load into Reg and Reg+1
1223         SDValue Hi64 =
1224             DAG.getLoad(MVT::i64, DL, Store, HiPtrOff, MachinePointerInfo());
1225         SDValue Lo64 =
1226             DAG.getLoad(MVT::i64, DL, Store, LoPtrOff, MachinePointerInfo());
1227         RegsToPass.push_back(std::make_pair(toCallerWindow(VA.getLocReg()),
1228                                             Hi64));
1229         RegsToPass.push_back(std::make_pair(toCallerWindow(VA.getLocReg()+1),
1230                                             Lo64));
1231         continue;
1232       }
1233 
1234       // The custom bit on an i32 return value indicates that it should be
1235       // passed in the high bits of the register.
1236       if (VA.getValVT() == MVT::i32 && VA.needsCustom()) {
1237         Arg = DAG.getNode(ISD::SHL, DL, MVT::i64, Arg,
1238                           DAG.getConstant(32, DL, MVT::i32));
1239 
1240         // The next value may go in the low bits of the same register.
1241         // Handle both at once.
1242         if (i+1 < ArgLocs.size() && ArgLocs[i+1].isRegLoc() &&
1243             ArgLocs[i+1].getLocReg() == VA.getLocReg()) {
1244           SDValue NV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64,
1245                                    CLI.OutVals[i+1]);
1246           Arg = DAG.getNode(ISD::OR, DL, MVT::i64, Arg, NV);
1247           // Skip the next value, it's already done.
1248           ++i;
1249         }
1250       }
1251       RegsToPass.push_back(std::make_pair(toCallerWindow(VA.getLocReg()), Arg));
1252       continue;
1253     }
1254 
1255     assert(VA.isMemLoc());
1256 
1257     // Create a store off the stack pointer for this argument.
1258     SDValue StackPtr = DAG.getRegister(SP::O6, PtrVT);
1259     // The argument area starts at %fp+BIAS+128 in the callee frame,
1260     // %sp+BIAS+128 in ours.
1261     SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset() +
1262                                            Subtarget->getStackPointerBias() +
1263                                            128, DL);
1264     PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
1265     MemOpChains.push_back(
1266         DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo()));
1267   }
1268 
1269   // Emit all stores, make sure they occur before the call.
1270   if (!MemOpChains.empty())
1271     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1272 
1273   // Build a sequence of CopyToReg nodes glued together with token chain and
1274   // glue operands which copy the outgoing args into registers. The InGlue is
1275   // necessary since all emitted instructions must be stuck together in order
1276   // to pass the live physical registers.
1277   SDValue InGlue;
1278   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1279     Chain = DAG.getCopyToReg(Chain, DL,
1280                              RegsToPass[i].first, RegsToPass[i].second, InGlue);
1281     InGlue = Chain.getValue(1);
1282   }
1283 
1284   // If the callee is a GlobalAddress node (quite common, every direct call is)
1285   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1286   // Likewise ExternalSymbol -> TargetExternalSymbol.
1287   SDValue Callee = CLI.Callee;
1288   bool hasReturnsTwice = hasReturnsTwiceAttr(DAG, Callee, CLI.CS);
1289   unsigned TF = isPositionIndependent() ? SparcMCExpr::VK_Sparc_WPLT30 : 0;
1290   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1291     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT, 0, TF);
1292   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1293     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT, TF);
1294 
1295   // Build the operands for the call instruction itself.
1296   SmallVector<SDValue, 8> Ops;
1297   Ops.push_back(Chain);
1298   Ops.push_back(Callee);
1299   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1300     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1301                                   RegsToPass[i].second.getValueType()));
1302 
1303   // Add a register mask operand representing the call-preserved registers.
1304   const SparcRegisterInfo *TRI = Subtarget->getRegisterInfo();
1305   const uint32_t *Mask =
1306       ((hasReturnsTwice) ? TRI->getRTCallPreservedMask(CLI.CallConv)
1307                          : TRI->getCallPreservedMask(DAG.getMachineFunction(),
1308                                                      CLI.CallConv));
1309   assert(Mask && "Missing call preserved mask for calling convention");
1310   Ops.push_back(DAG.getRegisterMask(Mask));
1311 
1312   // Make sure the CopyToReg nodes are glued to the call instruction which
1313   // consumes the registers.
1314   if (InGlue.getNode())
1315     Ops.push_back(InGlue);
1316 
1317   // Now the call itself.
1318   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1319   Chain = DAG.getNode(SPISD::CALL, DL, NodeTys, Ops);
1320   InGlue = Chain.getValue(1);
1321 
1322   // Revert the stack pointer immediately after the call.
1323   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, DL, true),
1324                              DAG.getIntPtrConstant(0, DL, true), InGlue, DL);
1325   InGlue = Chain.getValue(1);
1326 
1327   // Now extract the return values. This is more or less the same as
1328   // LowerFormalArguments_64.
1329 
1330   // Assign locations to each value returned by this call.
1331   SmallVector<CCValAssign, 16> RVLocs;
1332   CCState RVInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(), RVLocs,
1333                  *DAG.getContext());
1334 
1335   // Set inreg flag manually for codegen generated library calls that
1336   // return float.
1337   if (CLI.Ins.size() == 1 && CLI.Ins[0].VT == MVT::f32 && !CLI.CS)
1338     CLI.Ins[0].Flags.setInReg();
1339 
1340   RVInfo.AnalyzeCallResult(CLI.Ins, RetCC_Sparc64);
1341 
1342   // Copy all of the result registers out of their specified physreg.
1343   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1344     CCValAssign &VA = RVLocs[i];
1345     unsigned Reg = toCallerWindow(VA.getLocReg());
1346 
1347     // When returning 'inreg {i32, i32 }', two consecutive i32 arguments can
1348     // reside in the same register in the high and low bits. Reuse the
1349     // CopyFromReg previous node to avoid duplicate copies.
1350     SDValue RV;
1351     if (RegisterSDNode *SrcReg = dyn_cast<RegisterSDNode>(Chain.getOperand(1)))
1352       if (SrcReg->getReg() == Reg && Chain->getOpcode() == ISD::CopyFromReg)
1353         RV = Chain.getValue(0);
1354 
1355     // But usually we'll create a new CopyFromReg for a different register.
1356     if (!RV.getNode()) {
1357       RV = DAG.getCopyFromReg(Chain, DL, Reg, RVLocs[i].getLocVT(), InGlue);
1358       Chain = RV.getValue(1);
1359       InGlue = Chain.getValue(2);
1360     }
1361 
1362     // Get the high bits for i32 struct elements.
1363     if (VA.getValVT() == MVT::i32 && VA.needsCustom())
1364       RV = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), RV,
1365                        DAG.getConstant(32, DL, MVT::i32));
1366 
1367     // The callee promoted the return value, so insert an Assert?ext SDNode so
1368     // we won't promote the value again in this function.
1369     switch (VA.getLocInfo()) {
1370     case CCValAssign::SExt:
1371       RV = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), RV,
1372                        DAG.getValueType(VA.getValVT()));
1373       break;
1374     case CCValAssign::ZExt:
1375       RV = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), RV,
1376                        DAG.getValueType(VA.getValVT()));
1377       break;
1378     default:
1379       break;
1380     }
1381 
1382     // Truncate the register down to the return value type.
1383     if (VA.isExtInLoc())
1384       RV = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), RV);
1385 
1386     InVals.push_back(RV);
1387   }
1388 
1389   return Chain;
1390 }
1391 
1392 //===----------------------------------------------------------------------===//
1393 // TargetLowering Implementation
1394 //===----------------------------------------------------------------------===//
1395 
shouldExpandAtomicRMWInIR(AtomicRMWInst * AI) const1396 TargetLowering::AtomicExpansionKind SparcTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
1397   if (AI->getOperation() == AtomicRMWInst::Xchg &&
1398       AI->getType()->getPrimitiveSizeInBits() == 32)
1399     return AtomicExpansionKind::None; // Uses xchg instruction
1400 
1401   return AtomicExpansionKind::CmpXChg;
1402 }
1403 
1404 /// IntCondCCodeToICC - Convert a DAG integer condition code to a SPARC ICC
1405 /// condition.
IntCondCCodeToICC(ISD::CondCode CC)1406 static SPCC::CondCodes IntCondCCodeToICC(ISD::CondCode CC) {
1407   switch (CC) {
1408   default: llvm_unreachable("Unknown integer condition code!");
1409   case ISD::SETEQ:  return SPCC::ICC_E;
1410   case ISD::SETNE:  return SPCC::ICC_NE;
1411   case ISD::SETLT:  return SPCC::ICC_L;
1412   case ISD::SETGT:  return SPCC::ICC_G;
1413   case ISD::SETLE:  return SPCC::ICC_LE;
1414   case ISD::SETGE:  return SPCC::ICC_GE;
1415   case ISD::SETULT: return SPCC::ICC_CS;
1416   case ISD::SETULE: return SPCC::ICC_LEU;
1417   case ISD::SETUGT: return SPCC::ICC_GU;
1418   case ISD::SETUGE: return SPCC::ICC_CC;
1419   }
1420 }
1421 
1422 /// FPCondCCodeToFCC - Convert a DAG floatingp oint condition code to a SPARC
1423 /// FCC condition.
FPCondCCodeToFCC(ISD::CondCode CC)1424 static SPCC::CondCodes FPCondCCodeToFCC(ISD::CondCode CC) {
1425   switch (CC) {
1426   default: llvm_unreachable("Unknown fp condition code!");
1427   case ISD::SETEQ:
1428   case ISD::SETOEQ: return SPCC::FCC_E;
1429   case ISD::SETNE:
1430   case ISD::SETUNE: return SPCC::FCC_NE;
1431   case ISD::SETLT:
1432   case ISD::SETOLT: return SPCC::FCC_L;
1433   case ISD::SETGT:
1434   case ISD::SETOGT: return SPCC::FCC_G;
1435   case ISD::SETLE:
1436   case ISD::SETOLE: return SPCC::FCC_LE;
1437   case ISD::SETGE:
1438   case ISD::SETOGE: return SPCC::FCC_GE;
1439   case ISD::SETULT: return SPCC::FCC_UL;
1440   case ISD::SETULE: return SPCC::FCC_ULE;
1441   case ISD::SETUGT: return SPCC::FCC_UG;
1442   case ISD::SETUGE: return SPCC::FCC_UGE;
1443   case ISD::SETUO:  return SPCC::FCC_U;
1444   case ISD::SETO:   return SPCC::FCC_O;
1445   case ISD::SETONE: return SPCC::FCC_LG;
1446   case ISD::SETUEQ: return SPCC::FCC_UE;
1447   }
1448 }
1449 
SparcTargetLowering(const TargetMachine & TM,const SparcSubtarget & STI)1450 SparcTargetLowering::SparcTargetLowering(const TargetMachine &TM,
1451                                          const SparcSubtarget &STI)
1452     : TargetLowering(TM), Subtarget(&STI) {
1453   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize(0));
1454 
1455   // Instructions which use registers as conditionals examine all the
1456   // bits (as does the pseudo SELECT_CC expansion). I don't think it
1457   // matters much whether it's ZeroOrOneBooleanContent, or
1458   // ZeroOrNegativeOneBooleanContent, so, arbitrarily choose the
1459   // former.
1460   setBooleanContents(ZeroOrOneBooleanContent);
1461   setBooleanVectorContents(ZeroOrOneBooleanContent);
1462 
1463   // Set up the register classes.
1464   addRegisterClass(MVT::i32, &SP::IntRegsRegClass);
1465   if (!Subtarget->useSoftFloat()) {
1466     addRegisterClass(MVT::f32, &SP::FPRegsRegClass);
1467     addRegisterClass(MVT::f64, &SP::DFPRegsRegClass);
1468     addRegisterClass(MVT::f128, &SP::QFPRegsRegClass);
1469   }
1470   if (Subtarget->is64Bit()) {
1471     addRegisterClass(MVT::i64, &SP::I64RegsRegClass);
1472   } else {
1473     // On 32bit sparc, we define a double-register 32bit register
1474     // class, as well. This is modeled in LLVM as a 2-vector of i32.
1475     addRegisterClass(MVT::v2i32, &SP::IntPairRegClass);
1476 
1477     // ...but almost all operations must be expanded, so set that as
1478     // the default.
1479     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
1480       setOperationAction(Op, MVT::v2i32, Expand);
1481     }
1482     // Truncating/extending stores/loads are also not supported.
1483     for (MVT VT : MVT::integer_vector_valuetypes()) {
1484       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Expand);
1485       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::v2i32, Expand);
1486       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Expand);
1487 
1488       setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, VT, Expand);
1489       setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i32, VT, Expand);
1490       setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, VT, Expand);
1491 
1492       setTruncStoreAction(VT, MVT::v2i32, Expand);
1493       setTruncStoreAction(MVT::v2i32, VT, Expand);
1494     }
1495     // However, load and store *are* legal.
1496     setOperationAction(ISD::LOAD, MVT::v2i32, Legal);
1497     setOperationAction(ISD::STORE, MVT::v2i32, Legal);
1498     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i32, Legal);
1499     setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Legal);
1500 
1501     // And we need to promote i64 loads/stores into vector load/store
1502     setOperationAction(ISD::LOAD, MVT::i64, Custom);
1503     setOperationAction(ISD::STORE, MVT::i64, Custom);
1504 
1505     // Sadly, this doesn't work:
1506     //    AddPromotedToType(ISD::LOAD, MVT::i64, MVT::v2i32);
1507     //    AddPromotedToType(ISD::STORE, MVT::i64, MVT::v2i32);
1508   }
1509 
1510   // Turn FP extload into load/fpextend
1511   for (MVT VT : MVT::fp_valuetypes()) {
1512     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1513     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
1514   }
1515 
1516   // Sparc doesn't have i1 sign extending load
1517   for (MVT VT : MVT::integer_valuetypes())
1518     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
1519 
1520   // Turn FP truncstore into trunc + store.
1521   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1522   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1523   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1524 
1525   // Custom legalize GlobalAddress nodes into LO/HI parts.
1526   setOperationAction(ISD::GlobalAddress, PtrVT, Custom);
1527   setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
1528   setOperationAction(ISD::ConstantPool, PtrVT, Custom);
1529   setOperationAction(ISD::BlockAddress, PtrVT, Custom);
1530 
1531   // Sparc doesn't have sext_inreg, replace them with shl/sra
1532   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1533   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
1534   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
1535 
1536   // Sparc has no REM or DIVREM operations.
1537   setOperationAction(ISD::UREM, MVT::i32, Expand);
1538   setOperationAction(ISD::SREM, MVT::i32, Expand);
1539   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1540   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1541 
1542   // ... nor does SparcV9.
1543   if (Subtarget->is64Bit()) {
1544     setOperationAction(ISD::UREM, MVT::i64, Expand);
1545     setOperationAction(ISD::SREM, MVT::i64, Expand);
1546     setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
1547     setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
1548   }
1549 
1550   // Custom expand fp<->sint
1551   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
1552   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
1553   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
1554   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
1555 
1556   // Custom Expand fp<->uint
1557   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
1558   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
1559   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
1560   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
1561 
1562   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
1563   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
1564 
1565   // Sparc has no select or setcc: expand to SELECT_CC.
1566   setOperationAction(ISD::SELECT, MVT::i32, Expand);
1567   setOperationAction(ISD::SELECT, MVT::f32, Expand);
1568   setOperationAction(ISD::SELECT, MVT::f64, Expand);
1569   setOperationAction(ISD::SELECT, MVT::f128, Expand);
1570 
1571   setOperationAction(ISD::SETCC, MVT::i32, Expand);
1572   setOperationAction(ISD::SETCC, MVT::f32, Expand);
1573   setOperationAction(ISD::SETCC, MVT::f64, Expand);
1574   setOperationAction(ISD::SETCC, MVT::f128, Expand);
1575 
1576   // Sparc doesn't have BRCOND either, it has BR_CC.
1577   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
1578   setOperationAction(ISD::BRIND, MVT::Other, Expand);
1579   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
1580   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1581   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1582   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1583   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
1584 
1585   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1586   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1587   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1588   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1589 
1590   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1591   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1592 
1593   setOperationAction(ISD::ADDC, MVT::i32, Custom);
1594   setOperationAction(ISD::ADDE, MVT::i32, Custom);
1595   setOperationAction(ISD::SUBC, MVT::i32, Custom);
1596   setOperationAction(ISD::SUBE, MVT::i32, Custom);
1597 
1598   if (Subtarget->is64Bit()) {
1599     setOperationAction(ISD::ADDC, MVT::i64, Custom);
1600     setOperationAction(ISD::ADDE, MVT::i64, Custom);
1601     setOperationAction(ISD::SUBC, MVT::i64, Custom);
1602     setOperationAction(ISD::SUBE, MVT::i64, Custom);
1603     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
1604     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
1605     setOperationAction(ISD::SELECT, MVT::i64, Expand);
1606     setOperationAction(ISD::SETCC, MVT::i64, Expand);
1607     setOperationAction(ISD::BR_CC, MVT::i64, Custom);
1608     setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
1609 
1610     setOperationAction(ISD::CTPOP, MVT::i64,
1611                        Subtarget->usePopc() ? Legal : Expand);
1612     setOperationAction(ISD::CTTZ , MVT::i64, Expand);
1613     setOperationAction(ISD::CTLZ , MVT::i64, Expand);
1614     setOperationAction(ISD::BSWAP, MVT::i64, Expand);
1615     setOperationAction(ISD::ROTL , MVT::i64, Expand);
1616     setOperationAction(ISD::ROTR , MVT::i64, Expand);
1617     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
1618   }
1619 
1620   // ATOMICs.
1621   // Atomics are supported on SparcV9. 32-bit atomics are also
1622   // supported by some Leon SparcV8 variants. Otherwise, atomics
1623   // are unsupported.
1624   if (Subtarget->isV9())
1625     setMaxAtomicSizeInBitsSupported(64);
1626   else if (Subtarget->hasLeonCasa())
1627     setMaxAtomicSizeInBitsSupported(32);
1628   else
1629     setMaxAtomicSizeInBitsSupported(0);
1630 
1631   setMinCmpXchgSizeInBits(32);
1632 
1633   setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Legal);
1634 
1635   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Legal);
1636 
1637   // Custom Lower Atomic LOAD/STORE
1638   setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1639   setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1640 
1641   if (Subtarget->is64Bit()) {
1642     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Legal);
1643     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Legal);
1644     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
1645     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Custom);
1646   }
1647 
1648   if (!Subtarget->is64Bit()) {
1649     // These libcalls are not available in 32-bit.
1650     setLibcallName(RTLIB::SHL_I128, nullptr);
1651     setLibcallName(RTLIB::SRL_I128, nullptr);
1652     setLibcallName(RTLIB::SRA_I128, nullptr);
1653   }
1654 
1655   if (!Subtarget->isV9()) {
1656     // SparcV8 does not have FNEGD and FABSD.
1657     setOperationAction(ISD::FNEG, MVT::f64, Custom);
1658     setOperationAction(ISD::FABS, MVT::f64, Custom);
1659   }
1660 
1661   setOperationAction(ISD::FSIN , MVT::f128, Expand);
1662   setOperationAction(ISD::FCOS , MVT::f128, Expand);
1663   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
1664   setOperationAction(ISD::FREM , MVT::f128, Expand);
1665   setOperationAction(ISD::FMA  , MVT::f128, Expand);
1666   setOperationAction(ISD::FSIN , MVT::f64, Expand);
1667   setOperationAction(ISD::FCOS , MVT::f64, Expand);
1668   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1669   setOperationAction(ISD::FREM , MVT::f64, Expand);
1670   setOperationAction(ISD::FMA  , MVT::f64, Expand);
1671   setOperationAction(ISD::FSIN , MVT::f32, Expand);
1672   setOperationAction(ISD::FCOS , MVT::f32, Expand);
1673   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1674   setOperationAction(ISD::FREM , MVT::f32, Expand);
1675   setOperationAction(ISD::FMA  , MVT::f32, Expand);
1676   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
1677   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
1678   setOperationAction(ISD::ROTL , MVT::i32, Expand);
1679   setOperationAction(ISD::ROTR , MVT::i32, Expand);
1680   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1681   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1682   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
1683   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
1684   setOperationAction(ISD::FPOW , MVT::f128, Expand);
1685   setOperationAction(ISD::FPOW , MVT::f64, Expand);
1686   setOperationAction(ISD::FPOW , MVT::f32, Expand);
1687 
1688   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1689   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1690   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1691 
1692   // Expands to [SU]MUL_LOHI.
1693   setOperationAction(ISD::MULHU,     MVT::i32, Expand);
1694   setOperationAction(ISD::MULHS,     MVT::i32, Expand);
1695   setOperationAction(ISD::MUL,       MVT::i32, Expand);
1696 
1697   if (Subtarget->useSoftMulDiv()) {
1698     // .umul works for both signed and unsigned
1699     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1700     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1701     setLibcallName(RTLIB::MUL_I32, ".umul");
1702 
1703     setOperationAction(ISD::SDIV, MVT::i32, Expand);
1704     setLibcallName(RTLIB::SDIV_I32, ".div");
1705 
1706     setOperationAction(ISD::UDIV, MVT::i32, Expand);
1707     setLibcallName(RTLIB::UDIV_I32, ".udiv");
1708 
1709     setLibcallName(RTLIB::SREM_I32, ".rem");
1710     setLibcallName(RTLIB::UREM_I32, ".urem");
1711   }
1712 
1713   if (Subtarget->is64Bit()) {
1714     setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
1715     setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
1716     setOperationAction(ISD::MULHU,     MVT::i64, Expand);
1717     setOperationAction(ISD::MULHS,     MVT::i64, Expand);
1718 
1719     setOperationAction(ISD::UMULO,     MVT::i64, Custom);
1720     setOperationAction(ISD::SMULO,     MVT::i64, Custom);
1721 
1722     setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
1723     setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
1724     setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
1725   }
1726 
1727   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
1728   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
1729   // VAARG needs to be lowered to not do unaligned accesses for doubles.
1730   setOperationAction(ISD::VAARG             , MVT::Other, Custom);
1731 
1732   setOperationAction(ISD::TRAP              , MVT::Other, Legal);
1733   setOperationAction(ISD::DEBUGTRAP         , MVT::Other, Legal);
1734 
1735   // Use the default implementation.
1736   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
1737   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
1738   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
1739   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
1740   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
1741 
1742   setStackPointerRegisterToSaveRestore(SP::O6);
1743 
1744   setOperationAction(ISD::CTPOP, MVT::i32,
1745                      Subtarget->usePopc() ? Legal : Expand);
1746 
1747   if (Subtarget->isV9() && Subtarget->hasHardQuad()) {
1748     setOperationAction(ISD::LOAD, MVT::f128, Legal);
1749     setOperationAction(ISD::STORE, MVT::f128, Legal);
1750   } else {
1751     setOperationAction(ISD::LOAD, MVT::f128, Custom);
1752     setOperationAction(ISD::STORE, MVT::f128, Custom);
1753   }
1754 
1755   if (Subtarget->hasHardQuad()) {
1756     setOperationAction(ISD::FADD,  MVT::f128, Legal);
1757     setOperationAction(ISD::FSUB,  MVT::f128, Legal);
1758     setOperationAction(ISD::FMUL,  MVT::f128, Legal);
1759     setOperationAction(ISD::FDIV,  MVT::f128, Legal);
1760     setOperationAction(ISD::FSQRT, MVT::f128, Legal);
1761     setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1762     setOperationAction(ISD::FP_ROUND,  MVT::f64, Legal);
1763     if (Subtarget->isV9()) {
1764       setOperationAction(ISD::FNEG, MVT::f128, Legal);
1765       setOperationAction(ISD::FABS, MVT::f128, Legal);
1766     } else {
1767       setOperationAction(ISD::FNEG, MVT::f128, Custom);
1768       setOperationAction(ISD::FABS, MVT::f128, Custom);
1769     }
1770 
1771     if (!Subtarget->is64Bit()) {
1772       setLibcallName(RTLIB::FPTOSINT_F128_I64, "_Q_qtoll");
1773       setLibcallName(RTLIB::FPTOUINT_F128_I64, "_Q_qtoull");
1774       setLibcallName(RTLIB::SINTTOFP_I64_F128, "_Q_lltoq");
1775       setLibcallName(RTLIB::UINTTOFP_I64_F128, "_Q_ulltoq");
1776     }
1777 
1778   } else {
1779     // Custom legalize f128 operations.
1780 
1781     setOperationAction(ISD::FADD,  MVT::f128, Custom);
1782     setOperationAction(ISD::FSUB,  MVT::f128, Custom);
1783     setOperationAction(ISD::FMUL,  MVT::f128, Custom);
1784     setOperationAction(ISD::FDIV,  MVT::f128, Custom);
1785     setOperationAction(ISD::FSQRT, MVT::f128, Custom);
1786     setOperationAction(ISD::FNEG,  MVT::f128, Custom);
1787     setOperationAction(ISD::FABS,  MVT::f128, Custom);
1788 
1789     setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
1790     setOperationAction(ISD::FP_ROUND,  MVT::f64, Custom);
1791     setOperationAction(ISD::FP_ROUND,  MVT::f32, Custom);
1792 
1793     // Setup Runtime library names.
1794     if (Subtarget->is64Bit() && !Subtarget->useSoftFloat()) {
1795       setLibcallName(RTLIB::ADD_F128,  "_Qp_add");
1796       setLibcallName(RTLIB::SUB_F128,  "_Qp_sub");
1797       setLibcallName(RTLIB::MUL_F128,  "_Qp_mul");
1798       setLibcallName(RTLIB::DIV_F128,  "_Qp_div");
1799       setLibcallName(RTLIB::SQRT_F128, "_Qp_sqrt");
1800       setLibcallName(RTLIB::FPTOSINT_F128_I32, "_Qp_qtoi");
1801       setLibcallName(RTLIB::FPTOUINT_F128_I32, "_Qp_qtoui");
1802       setLibcallName(RTLIB::SINTTOFP_I32_F128, "_Qp_itoq");
1803       setLibcallName(RTLIB::UINTTOFP_I32_F128, "_Qp_uitoq");
1804       setLibcallName(RTLIB::FPTOSINT_F128_I64, "_Qp_qtox");
1805       setLibcallName(RTLIB::FPTOUINT_F128_I64, "_Qp_qtoux");
1806       setLibcallName(RTLIB::SINTTOFP_I64_F128, "_Qp_xtoq");
1807       setLibcallName(RTLIB::UINTTOFP_I64_F128, "_Qp_uxtoq");
1808       setLibcallName(RTLIB::FPEXT_F32_F128, "_Qp_stoq");
1809       setLibcallName(RTLIB::FPEXT_F64_F128, "_Qp_dtoq");
1810       setLibcallName(RTLIB::FPROUND_F128_F32, "_Qp_qtos");
1811       setLibcallName(RTLIB::FPROUND_F128_F64, "_Qp_qtod");
1812     } else if (!Subtarget->useSoftFloat()) {
1813       setLibcallName(RTLIB::ADD_F128,  "_Q_add");
1814       setLibcallName(RTLIB::SUB_F128,  "_Q_sub");
1815       setLibcallName(RTLIB::MUL_F128,  "_Q_mul");
1816       setLibcallName(RTLIB::DIV_F128,  "_Q_div");
1817       setLibcallName(RTLIB::SQRT_F128, "_Q_sqrt");
1818       setLibcallName(RTLIB::FPTOSINT_F128_I32, "_Q_qtoi");
1819       setLibcallName(RTLIB::FPTOUINT_F128_I32, "_Q_qtou");
1820       setLibcallName(RTLIB::SINTTOFP_I32_F128, "_Q_itoq");
1821       setLibcallName(RTLIB::UINTTOFP_I32_F128, "_Q_utoq");
1822       setLibcallName(RTLIB::FPTOSINT_F128_I64, "_Q_qtoll");
1823       setLibcallName(RTLIB::FPTOUINT_F128_I64, "_Q_qtoull");
1824       setLibcallName(RTLIB::SINTTOFP_I64_F128, "_Q_lltoq");
1825       setLibcallName(RTLIB::UINTTOFP_I64_F128, "_Q_ulltoq");
1826       setLibcallName(RTLIB::FPEXT_F32_F128, "_Q_stoq");
1827       setLibcallName(RTLIB::FPEXT_F64_F128, "_Q_dtoq");
1828       setLibcallName(RTLIB::FPROUND_F128_F32, "_Q_qtos");
1829       setLibcallName(RTLIB::FPROUND_F128_F64, "_Q_qtod");
1830     }
1831   }
1832 
1833   if (Subtarget->fixAllFDIVSQRT()) {
1834     // Promote FDIVS and FSQRTS to FDIVD and FSQRTD instructions instead as
1835     // the former instructions generate errata on LEON processors.
1836     setOperationAction(ISD::FDIV, MVT::f32, Promote);
1837     setOperationAction(ISD::FSQRT, MVT::f32, Promote);
1838   }
1839 
1840   if (Subtarget->hasNoFMULS()) {
1841     setOperationAction(ISD::FMUL, MVT::f32, Promote);
1842   }
1843 
1844   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1845 
1846   setMinFunctionAlignment(2);
1847 
1848   computeRegisterProperties(Subtarget->getRegisterInfo());
1849 }
1850 
useSoftFloat() const1851 bool SparcTargetLowering::useSoftFloat() const {
1852   return Subtarget->useSoftFloat();
1853 }
1854 
getTargetNodeName(unsigned Opcode) const1855 const char *SparcTargetLowering::getTargetNodeName(unsigned Opcode) const {
1856   switch ((SPISD::NodeType)Opcode) {
1857   case SPISD::FIRST_NUMBER:    break;
1858   case SPISD::CMPICC:          return "SPISD::CMPICC";
1859   case SPISD::CMPFCC:          return "SPISD::CMPFCC";
1860   case SPISD::BRICC:           return "SPISD::BRICC";
1861   case SPISD::BRXCC:           return "SPISD::BRXCC";
1862   case SPISD::BRFCC:           return "SPISD::BRFCC";
1863   case SPISD::SELECT_ICC:      return "SPISD::SELECT_ICC";
1864   case SPISD::SELECT_XCC:      return "SPISD::SELECT_XCC";
1865   case SPISD::SELECT_FCC:      return "SPISD::SELECT_FCC";
1866   case SPISD::EH_SJLJ_SETJMP:  return "SPISD::EH_SJLJ_SETJMP";
1867   case SPISD::EH_SJLJ_LONGJMP: return "SPISD::EH_SJLJ_LONGJMP";
1868   case SPISD::Hi:              return "SPISD::Hi";
1869   case SPISD::Lo:              return "SPISD::Lo";
1870   case SPISD::FTOI:            return "SPISD::FTOI";
1871   case SPISD::ITOF:            return "SPISD::ITOF";
1872   case SPISD::FTOX:            return "SPISD::FTOX";
1873   case SPISD::XTOF:            return "SPISD::XTOF";
1874   case SPISD::CALL:            return "SPISD::CALL";
1875   case SPISD::RET_FLAG:        return "SPISD::RET_FLAG";
1876   case SPISD::GLOBAL_BASE_REG: return "SPISD::GLOBAL_BASE_REG";
1877   case SPISD::FLUSHW:          return "SPISD::FLUSHW";
1878   case SPISD::TLS_ADD:         return "SPISD::TLS_ADD";
1879   case SPISD::TLS_LD:          return "SPISD::TLS_LD";
1880   case SPISD::TLS_CALL:        return "SPISD::TLS_CALL";
1881   }
1882   return nullptr;
1883 }
1884 
getSetCCResultType(const DataLayout &,LLVMContext &,EVT VT) const1885 EVT SparcTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
1886                                             EVT VT) const {
1887   if (!VT.isVector())
1888     return MVT::i32;
1889   return VT.changeVectorElementTypeToInteger();
1890 }
1891 
1892 /// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
1893 /// be zero. Op is expected to be a target specific node. Used by DAG
1894 /// combiner.
computeKnownBitsForTargetNode(const SDValue Op,KnownBits & Known,const APInt & DemandedElts,const SelectionDAG & DAG,unsigned Depth) const1895 void SparcTargetLowering::computeKnownBitsForTargetNode
1896                                 (const SDValue Op,
1897                                  KnownBits &Known,
1898                                  const APInt &DemandedElts,
1899                                  const SelectionDAG &DAG,
1900                                  unsigned Depth) const {
1901   KnownBits Known2;
1902   Known.resetAll();
1903 
1904   switch (Op.getOpcode()) {
1905   default: break;
1906   case SPISD::SELECT_ICC:
1907   case SPISD::SELECT_XCC:
1908   case SPISD::SELECT_FCC:
1909     DAG.computeKnownBits(Op.getOperand(1), Known, Depth+1);
1910     DAG.computeKnownBits(Op.getOperand(0), Known2, Depth+1);
1911 
1912     // Only known if known in both the LHS and RHS.
1913     Known.One &= Known2.One;
1914     Known.Zero &= Known2.Zero;
1915     break;
1916   }
1917 }
1918 
1919 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
1920 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
LookThroughSetCC(SDValue & LHS,SDValue & RHS,ISD::CondCode CC,unsigned & SPCC)1921 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
1922                              ISD::CondCode CC, unsigned &SPCC) {
1923   if (isNullConstant(RHS) &&
1924       CC == ISD::SETNE &&
1925       (((LHS.getOpcode() == SPISD::SELECT_ICC ||
1926          LHS.getOpcode() == SPISD::SELECT_XCC) &&
1927         LHS.getOperand(3).getOpcode() == SPISD::CMPICC) ||
1928        (LHS.getOpcode() == SPISD::SELECT_FCC &&
1929         LHS.getOperand(3).getOpcode() == SPISD::CMPFCC)) &&
1930       isOneConstant(LHS.getOperand(0)) &&
1931       isNullConstant(LHS.getOperand(1))) {
1932     SDValue CMPCC = LHS.getOperand(3);
1933     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
1934     LHS = CMPCC.getOperand(0);
1935     RHS = CMPCC.getOperand(1);
1936   }
1937 }
1938 
1939 // Convert to a target node and set target flags.
withTargetFlags(SDValue Op,unsigned TF,SelectionDAG & DAG) const1940 SDValue SparcTargetLowering::withTargetFlags(SDValue Op, unsigned TF,
1941                                              SelectionDAG &DAG) const {
1942   if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op))
1943     return DAG.getTargetGlobalAddress(GA->getGlobal(),
1944                                       SDLoc(GA),
1945                                       GA->getValueType(0),
1946                                       GA->getOffset(), TF);
1947 
1948   if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op))
1949     return DAG.getTargetConstantPool(CP->getConstVal(),
1950                                      CP->getValueType(0),
1951                                      CP->getAlignment(),
1952                                      CP->getOffset(), TF);
1953 
1954   if (const BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op))
1955     return DAG.getTargetBlockAddress(BA->getBlockAddress(),
1956                                      Op.getValueType(),
1957                                      0,
1958                                      TF);
1959 
1960   if (const ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op))
1961     return DAG.getTargetExternalSymbol(ES->getSymbol(),
1962                                        ES->getValueType(0), TF);
1963 
1964   llvm_unreachable("Unhandled address SDNode");
1965 }
1966 
1967 // Split Op into high and low parts according to HiTF and LoTF.
1968 // Return an ADD node combining the parts.
makeHiLoPair(SDValue Op,unsigned HiTF,unsigned LoTF,SelectionDAG & DAG) const1969 SDValue SparcTargetLowering::makeHiLoPair(SDValue Op,
1970                                           unsigned HiTF, unsigned LoTF,
1971                                           SelectionDAG &DAG) const {
1972   SDLoc DL(Op);
1973   EVT VT = Op.getValueType();
1974   SDValue Hi = DAG.getNode(SPISD::Hi, DL, VT, withTargetFlags(Op, HiTF, DAG));
1975   SDValue Lo = DAG.getNode(SPISD::Lo, DL, VT, withTargetFlags(Op, LoTF, DAG));
1976   return DAG.getNode(ISD::ADD, DL, VT, Hi, Lo);
1977 }
1978 
1979 // Build SDNodes for producing an address from a GlobalAddress, ConstantPool,
1980 // or ExternalSymbol SDNode.
makeAddress(SDValue Op,SelectionDAG & DAG) const1981 SDValue SparcTargetLowering::makeAddress(SDValue Op, SelectionDAG &DAG) const {
1982   SDLoc DL(Op);
1983   EVT VT = getPointerTy(DAG.getDataLayout());
1984 
1985   // Handle PIC mode first. SPARC needs a got load for every variable!
1986   if (isPositionIndependent()) {
1987     const Module *M = DAG.getMachineFunction().getFunction().getParent();
1988     PICLevel::Level picLevel = M->getPICLevel();
1989     SDValue Idx;
1990 
1991     if (picLevel == PICLevel::SmallPIC) {
1992       // This is the pic13 code model, the GOT is known to be smaller than 8KiB.
1993       Idx = DAG.getNode(SPISD::Lo, DL, Op.getValueType(),
1994                         withTargetFlags(Op, SparcMCExpr::VK_Sparc_GOT13, DAG));
1995     } else {
1996       // This is the pic32 code model, the GOT is known to be smaller than 4GB.
1997       Idx = makeHiLoPair(Op, SparcMCExpr::VK_Sparc_GOT22,
1998                          SparcMCExpr::VK_Sparc_GOT10, DAG);
1999     }
2000 
2001     SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, DL, VT);
2002     SDValue AbsAddr = DAG.getNode(ISD::ADD, DL, VT, GlobalBase, Idx);
2003     // GLOBAL_BASE_REG codegen'ed with call. Inform MFI that this
2004     // function has calls.
2005     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2006     MFI.setHasCalls(true);
2007     return DAG.getLoad(VT, DL, DAG.getEntryNode(), AbsAddr,
2008                        MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2009   }
2010 
2011   // This is one of the absolute code models.
2012   switch(getTargetMachine().getCodeModel()) {
2013   default:
2014     llvm_unreachable("Unsupported absolute code model");
2015   case CodeModel::Small:
2016     // abs32.
2017     return makeHiLoPair(Op, SparcMCExpr::VK_Sparc_HI,
2018                         SparcMCExpr::VK_Sparc_LO, DAG);
2019   case CodeModel::Medium: {
2020     // abs44.
2021     SDValue H44 = makeHiLoPair(Op, SparcMCExpr::VK_Sparc_H44,
2022                                SparcMCExpr::VK_Sparc_M44, DAG);
2023     H44 = DAG.getNode(ISD::SHL, DL, VT, H44, DAG.getConstant(12, DL, MVT::i32));
2024     SDValue L44 = withTargetFlags(Op, SparcMCExpr::VK_Sparc_L44, DAG);
2025     L44 = DAG.getNode(SPISD::Lo, DL, VT, L44);
2026     return DAG.getNode(ISD::ADD, DL, VT, H44, L44);
2027   }
2028   case CodeModel::Large: {
2029     // abs64.
2030     SDValue Hi = makeHiLoPair(Op, SparcMCExpr::VK_Sparc_HH,
2031                               SparcMCExpr::VK_Sparc_HM, DAG);
2032     Hi = DAG.getNode(ISD::SHL, DL, VT, Hi, DAG.getConstant(32, DL, MVT::i32));
2033     SDValue Lo = makeHiLoPair(Op, SparcMCExpr::VK_Sparc_HI,
2034                               SparcMCExpr::VK_Sparc_LO, DAG);
2035     return DAG.getNode(ISD::ADD, DL, VT, Hi, Lo);
2036   }
2037   }
2038 }
2039 
LowerGlobalAddress(SDValue Op,SelectionDAG & DAG) const2040 SDValue SparcTargetLowering::LowerGlobalAddress(SDValue Op,
2041                                                 SelectionDAG &DAG) const {
2042   return makeAddress(Op, DAG);
2043 }
2044 
LowerConstantPool(SDValue Op,SelectionDAG & DAG) const2045 SDValue SparcTargetLowering::LowerConstantPool(SDValue Op,
2046                                                SelectionDAG &DAG) const {
2047   return makeAddress(Op, DAG);
2048 }
2049 
LowerBlockAddress(SDValue Op,SelectionDAG & DAG) const2050 SDValue SparcTargetLowering::LowerBlockAddress(SDValue Op,
2051                                                SelectionDAG &DAG) const {
2052   return makeAddress(Op, DAG);
2053 }
2054 
LowerGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const2055 SDValue SparcTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2056                                                    SelectionDAG &DAG) const {
2057 
2058   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2059   if (DAG.getTarget().useEmulatedTLS())
2060     return LowerToTLSEmulatedModel(GA, DAG);
2061 
2062   SDLoc DL(GA);
2063   const GlobalValue *GV = GA->getGlobal();
2064   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2065 
2066   TLSModel::Model model = getTargetMachine().getTLSModel(GV);
2067 
2068   if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
2069     unsigned HiTF = ((model == TLSModel::GeneralDynamic)
2070                      ? SparcMCExpr::VK_Sparc_TLS_GD_HI22
2071                      : SparcMCExpr::VK_Sparc_TLS_LDM_HI22);
2072     unsigned LoTF = ((model == TLSModel::GeneralDynamic)
2073                      ? SparcMCExpr::VK_Sparc_TLS_GD_LO10
2074                      : SparcMCExpr::VK_Sparc_TLS_LDM_LO10);
2075     unsigned addTF = ((model == TLSModel::GeneralDynamic)
2076                       ? SparcMCExpr::VK_Sparc_TLS_GD_ADD
2077                       : SparcMCExpr::VK_Sparc_TLS_LDM_ADD);
2078     unsigned callTF = ((model == TLSModel::GeneralDynamic)
2079                        ? SparcMCExpr::VK_Sparc_TLS_GD_CALL
2080                        : SparcMCExpr::VK_Sparc_TLS_LDM_CALL);
2081 
2082     SDValue HiLo = makeHiLoPair(Op, HiTF, LoTF, DAG);
2083     SDValue Base = DAG.getNode(SPISD::GLOBAL_BASE_REG, DL, PtrVT);
2084     SDValue Argument = DAG.getNode(SPISD::TLS_ADD, DL, PtrVT, Base, HiLo,
2085                                withTargetFlags(Op, addTF, DAG));
2086 
2087     SDValue Chain = DAG.getEntryNode();
2088     SDValue InFlag;
2089 
2090     Chain = DAG.getCALLSEQ_START(Chain, 1, 0, DL);
2091     Chain = DAG.getCopyToReg(Chain, DL, SP::O0, Argument, InFlag);
2092     InFlag = Chain.getValue(1);
2093     SDValue Callee = DAG.getTargetExternalSymbol("__tls_get_addr", PtrVT);
2094     SDValue Symbol = withTargetFlags(Op, callTF, DAG);
2095 
2096     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2097     const uint32_t *Mask = Subtarget->getRegisterInfo()->getCallPreservedMask(
2098         DAG.getMachineFunction(), CallingConv::C);
2099     assert(Mask && "Missing call preserved mask for calling convention");
2100     SDValue Ops[] = {Chain,
2101                      Callee,
2102                      Symbol,
2103                      DAG.getRegister(SP::O0, PtrVT),
2104                      DAG.getRegisterMask(Mask),
2105                      InFlag};
2106     Chain = DAG.getNode(SPISD::TLS_CALL, DL, NodeTys, Ops);
2107     InFlag = Chain.getValue(1);
2108     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(1, DL, true),
2109                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
2110     InFlag = Chain.getValue(1);
2111     SDValue Ret = DAG.getCopyFromReg(Chain, DL, SP::O0, PtrVT, InFlag);
2112 
2113     if (model != TLSModel::LocalDynamic)
2114       return Ret;
2115 
2116     SDValue Hi = DAG.getNode(SPISD::Hi, DL, PtrVT,
2117                  withTargetFlags(Op, SparcMCExpr::VK_Sparc_TLS_LDO_HIX22, DAG));
2118     SDValue Lo = DAG.getNode(SPISD::Lo, DL, PtrVT,
2119                  withTargetFlags(Op, SparcMCExpr::VK_Sparc_TLS_LDO_LOX10, DAG));
2120     HiLo =  DAG.getNode(ISD::XOR, DL, PtrVT, Hi, Lo);
2121     return DAG.getNode(SPISD::TLS_ADD, DL, PtrVT, Ret, HiLo,
2122                    withTargetFlags(Op, SparcMCExpr::VK_Sparc_TLS_LDO_ADD, DAG));
2123   }
2124 
2125   if (model == TLSModel::InitialExec) {
2126     unsigned ldTF     = ((PtrVT == MVT::i64)? SparcMCExpr::VK_Sparc_TLS_IE_LDX
2127                          : SparcMCExpr::VK_Sparc_TLS_IE_LD);
2128 
2129     SDValue Base = DAG.getNode(SPISD::GLOBAL_BASE_REG, DL, PtrVT);
2130 
2131     // GLOBAL_BASE_REG codegen'ed with call. Inform MFI that this
2132     // function has calls.
2133     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2134     MFI.setHasCalls(true);
2135 
2136     SDValue TGA = makeHiLoPair(Op,
2137                                SparcMCExpr::VK_Sparc_TLS_IE_HI22,
2138                                SparcMCExpr::VK_Sparc_TLS_IE_LO10, DAG);
2139     SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, Base, TGA);
2140     SDValue Offset = DAG.getNode(SPISD::TLS_LD,
2141                                  DL, PtrVT, Ptr,
2142                                  withTargetFlags(Op, ldTF, DAG));
2143     return DAG.getNode(SPISD::TLS_ADD, DL, PtrVT,
2144                        DAG.getRegister(SP::G7, PtrVT), Offset,
2145                        withTargetFlags(Op,
2146                                        SparcMCExpr::VK_Sparc_TLS_IE_ADD, DAG));
2147   }
2148 
2149   assert(model == TLSModel::LocalExec);
2150   SDValue Hi = DAG.getNode(SPISD::Hi, DL, PtrVT,
2151                   withTargetFlags(Op, SparcMCExpr::VK_Sparc_TLS_LE_HIX22, DAG));
2152   SDValue Lo = DAG.getNode(SPISD::Lo, DL, PtrVT,
2153                   withTargetFlags(Op, SparcMCExpr::VK_Sparc_TLS_LE_LOX10, DAG));
2154   SDValue Offset =  DAG.getNode(ISD::XOR, DL, PtrVT, Hi, Lo);
2155 
2156   return DAG.getNode(ISD::ADD, DL, PtrVT,
2157                      DAG.getRegister(SP::G7, PtrVT), Offset);
2158 }
2159 
LowerF128_LibCallArg(SDValue Chain,ArgListTy & Args,SDValue Arg,const SDLoc & DL,SelectionDAG & DAG) const2160 SDValue SparcTargetLowering::LowerF128_LibCallArg(SDValue Chain,
2161                                                   ArgListTy &Args, SDValue Arg,
2162                                                   const SDLoc &DL,
2163                                                   SelectionDAG &DAG) const {
2164   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2165   EVT ArgVT = Arg.getValueType();
2166   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2167 
2168   ArgListEntry Entry;
2169   Entry.Node = Arg;
2170   Entry.Ty   = ArgTy;
2171 
2172   if (ArgTy->isFP128Ty()) {
2173     // Create a stack object and pass the pointer to the library function.
2174     int FI = MFI.CreateStackObject(16, 8, false);
2175     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2176     Chain = DAG.getStore(Chain, DL, Entry.Node, FIPtr, MachinePointerInfo(),
2177                          /* Alignment = */ 8);
2178 
2179     Entry.Node = FIPtr;
2180     Entry.Ty   = PointerType::getUnqual(ArgTy);
2181   }
2182   Args.push_back(Entry);
2183   return Chain;
2184 }
2185 
2186 SDValue
LowerF128Op(SDValue Op,SelectionDAG & DAG,const char * LibFuncName,unsigned numArgs) const2187 SparcTargetLowering::LowerF128Op(SDValue Op, SelectionDAG &DAG,
2188                                  const char *LibFuncName,
2189                                  unsigned numArgs) const {
2190 
2191   ArgListTy Args;
2192 
2193   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2194   auto PtrVT = getPointerTy(DAG.getDataLayout());
2195 
2196   SDValue Callee = DAG.getExternalSymbol(LibFuncName, PtrVT);
2197   Type *RetTy = Op.getValueType().getTypeForEVT(*DAG.getContext());
2198   Type *RetTyABI = RetTy;
2199   SDValue Chain = DAG.getEntryNode();
2200   SDValue RetPtr;
2201 
2202   if (RetTy->isFP128Ty()) {
2203     // Create a Stack Object to receive the return value of type f128.
2204     ArgListEntry Entry;
2205     int RetFI = MFI.CreateStackObject(16, 8, false);
2206     RetPtr = DAG.getFrameIndex(RetFI, PtrVT);
2207     Entry.Node = RetPtr;
2208     Entry.Ty   = PointerType::getUnqual(RetTy);
2209     if (!Subtarget->is64Bit())
2210       Entry.IsSRet = true;
2211     Entry.IsReturned = false;
2212     Args.push_back(Entry);
2213     RetTyABI = Type::getVoidTy(*DAG.getContext());
2214   }
2215 
2216   assert(Op->getNumOperands() >= numArgs && "Not enough operands!");
2217   for (unsigned i = 0, e = numArgs; i != e; ++i) {
2218     Chain = LowerF128_LibCallArg(Chain, Args, Op.getOperand(i), SDLoc(Op), DAG);
2219   }
2220   TargetLowering::CallLoweringInfo CLI(DAG);
2221   CLI.setDebugLoc(SDLoc(Op)).setChain(Chain)
2222     .setCallee(CallingConv::C, RetTyABI, Callee, std::move(Args));
2223 
2224   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
2225 
2226   // chain is in second result.
2227   if (RetTyABI == RetTy)
2228     return CallInfo.first;
2229 
2230   assert (RetTy->isFP128Ty() && "Unexpected return type!");
2231 
2232   Chain = CallInfo.second;
2233 
2234   // Load RetPtr to get the return value.
2235   return DAG.getLoad(Op.getValueType(), SDLoc(Op), Chain, RetPtr,
2236                      MachinePointerInfo(), /* Alignment = */ 8);
2237 }
2238 
LowerF128Compare(SDValue LHS,SDValue RHS,unsigned & SPCC,const SDLoc & DL,SelectionDAG & DAG) const2239 SDValue SparcTargetLowering::LowerF128Compare(SDValue LHS, SDValue RHS,
2240                                               unsigned &SPCC, const SDLoc &DL,
2241                                               SelectionDAG &DAG) const {
2242 
2243   const char *LibCall = nullptr;
2244   bool is64Bit = Subtarget->is64Bit();
2245   switch(SPCC) {
2246   default: llvm_unreachable("Unhandled conditional code!");
2247   case SPCC::FCC_E  : LibCall = is64Bit? "_Qp_feq" : "_Q_feq"; break;
2248   case SPCC::FCC_NE : LibCall = is64Bit? "_Qp_fne" : "_Q_fne"; break;
2249   case SPCC::FCC_L  : LibCall = is64Bit? "_Qp_flt" : "_Q_flt"; break;
2250   case SPCC::FCC_G  : LibCall = is64Bit? "_Qp_fgt" : "_Q_fgt"; break;
2251   case SPCC::FCC_LE : LibCall = is64Bit? "_Qp_fle" : "_Q_fle"; break;
2252   case SPCC::FCC_GE : LibCall = is64Bit? "_Qp_fge" : "_Q_fge"; break;
2253   case SPCC::FCC_UL :
2254   case SPCC::FCC_ULE:
2255   case SPCC::FCC_UG :
2256   case SPCC::FCC_UGE:
2257   case SPCC::FCC_U  :
2258   case SPCC::FCC_O  :
2259   case SPCC::FCC_LG :
2260   case SPCC::FCC_UE : LibCall = is64Bit? "_Qp_cmp" : "_Q_cmp"; break;
2261   }
2262 
2263   auto PtrVT = getPointerTy(DAG.getDataLayout());
2264   SDValue Callee = DAG.getExternalSymbol(LibCall, PtrVT);
2265   Type *RetTy = Type::getInt32Ty(*DAG.getContext());
2266   ArgListTy Args;
2267   SDValue Chain = DAG.getEntryNode();
2268   Chain = LowerF128_LibCallArg(Chain, Args, LHS, DL, DAG);
2269   Chain = LowerF128_LibCallArg(Chain, Args, RHS, DL, DAG);
2270 
2271   TargetLowering::CallLoweringInfo CLI(DAG);
2272   CLI.setDebugLoc(DL).setChain(Chain)
2273     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args));
2274 
2275   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
2276 
2277   // result is in first, and chain is in second result.
2278   SDValue Result =  CallInfo.first;
2279 
2280   switch(SPCC) {
2281   default: {
2282     SDValue RHS = DAG.getTargetConstant(0, DL, Result.getValueType());
2283     SPCC = SPCC::ICC_NE;
2284     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2285   }
2286   case SPCC::FCC_UL : {
2287     SDValue Mask   = DAG.getTargetConstant(1, DL, Result.getValueType());
2288     Result = DAG.getNode(ISD::AND, DL, Result.getValueType(), Result, Mask);
2289     SDValue RHS    = DAG.getTargetConstant(0, DL, Result.getValueType());
2290     SPCC = SPCC::ICC_NE;
2291     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2292   }
2293   case SPCC::FCC_ULE: {
2294     SDValue RHS = DAG.getTargetConstant(2, DL, Result.getValueType());
2295     SPCC = SPCC::ICC_NE;
2296     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2297   }
2298   case SPCC::FCC_UG :  {
2299     SDValue RHS = DAG.getTargetConstant(1, DL, Result.getValueType());
2300     SPCC = SPCC::ICC_G;
2301     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2302   }
2303   case SPCC::FCC_UGE: {
2304     SDValue RHS = DAG.getTargetConstant(1, DL, Result.getValueType());
2305     SPCC = SPCC::ICC_NE;
2306     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2307   }
2308 
2309   case SPCC::FCC_U  :  {
2310     SDValue RHS = DAG.getTargetConstant(3, DL, Result.getValueType());
2311     SPCC = SPCC::ICC_E;
2312     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2313   }
2314   case SPCC::FCC_O  :  {
2315     SDValue RHS = DAG.getTargetConstant(3, DL, Result.getValueType());
2316     SPCC = SPCC::ICC_NE;
2317     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2318   }
2319   case SPCC::FCC_LG :  {
2320     SDValue Mask   = DAG.getTargetConstant(3, DL, Result.getValueType());
2321     Result = DAG.getNode(ISD::AND, DL, Result.getValueType(), Result, Mask);
2322     SDValue RHS    = DAG.getTargetConstant(0, DL, Result.getValueType());
2323     SPCC = SPCC::ICC_NE;
2324     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2325   }
2326   case SPCC::FCC_UE : {
2327     SDValue Mask   = DAG.getTargetConstant(3, DL, Result.getValueType());
2328     Result = DAG.getNode(ISD::AND, DL, Result.getValueType(), Result, Mask);
2329     SDValue RHS    = DAG.getTargetConstant(0, DL, Result.getValueType());
2330     SPCC = SPCC::ICC_E;
2331     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2332   }
2333   }
2334 }
2335 
2336 static SDValue
LowerF128_FPEXTEND(SDValue Op,SelectionDAG & DAG,const SparcTargetLowering & TLI)2337 LowerF128_FPEXTEND(SDValue Op, SelectionDAG &DAG,
2338                    const SparcTargetLowering &TLI) {
2339 
2340   if (Op.getOperand(0).getValueType() == MVT::f64)
2341     return TLI.LowerF128Op(Op, DAG,
2342                            TLI.getLibcallName(RTLIB::FPEXT_F64_F128), 1);
2343 
2344   if (Op.getOperand(0).getValueType() == MVT::f32)
2345     return TLI.LowerF128Op(Op, DAG,
2346                            TLI.getLibcallName(RTLIB::FPEXT_F32_F128), 1);
2347 
2348   llvm_unreachable("fpextend with non-float operand!");
2349   return SDValue();
2350 }
2351 
2352 static SDValue
LowerF128_FPROUND(SDValue Op,SelectionDAG & DAG,const SparcTargetLowering & TLI)2353 LowerF128_FPROUND(SDValue Op, SelectionDAG &DAG,
2354                   const SparcTargetLowering &TLI) {
2355   // FP_ROUND on f64 and f32 are legal.
2356   if (Op.getOperand(0).getValueType() != MVT::f128)
2357     return Op;
2358 
2359   if (Op.getValueType() == MVT::f64)
2360     return TLI.LowerF128Op(Op, DAG,
2361                            TLI.getLibcallName(RTLIB::FPROUND_F128_F64), 1);
2362   if (Op.getValueType() == MVT::f32)
2363     return TLI.LowerF128Op(Op, DAG,
2364                            TLI.getLibcallName(RTLIB::FPROUND_F128_F32), 1);
2365 
2366   llvm_unreachable("fpround to non-float!");
2367   return SDValue();
2368 }
2369 
LowerFP_TO_SINT(SDValue Op,SelectionDAG & DAG,const SparcTargetLowering & TLI,bool hasHardQuad)2370 static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG,
2371                                const SparcTargetLowering &TLI,
2372                                bool hasHardQuad) {
2373   SDLoc dl(Op);
2374   EVT VT = Op.getValueType();
2375   assert(VT == MVT::i32 || VT == MVT::i64);
2376 
2377   // Expand f128 operations to fp128 abi calls.
2378   if (Op.getOperand(0).getValueType() == MVT::f128
2379       && (!hasHardQuad || !TLI.isTypeLegal(VT))) {
2380     const char *libName = TLI.getLibcallName(VT == MVT::i32
2381                                              ? RTLIB::FPTOSINT_F128_I32
2382                                              : RTLIB::FPTOSINT_F128_I64);
2383     return TLI.LowerF128Op(Op, DAG, libName, 1);
2384   }
2385 
2386   // Expand if the resulting type is illegal.
2387   if (!TLI.isTypeLegal(VT))
2388     return SDValue();
2389 
2390   // Otherwise, Convert the fp value to integer in an FP register.
2391   if (VT == MVT::i32)
2392     Op = DAG.getNode(SPISD::FTOI, dl, MVT::f32, Op.getOperand(0));
2393   else
2394     Op = DAG.getNode(SPISD::FTOX, dl, MVT::f64, Op.getOperand(0));
2395 
2396   return DAG.getNode(ISD::BITCAST, dl, VT, Op);
2397 }
2398 
LowerSINT_TO_FP(SDValue Op,SelectionDAG & DAG,const SparcTargetLowering & TLI,bool hasHardQuad)2399 static SDValue LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2400                                const SparcTargetLowering &TLI,
2401                                bool hasHardQuad) {
2402   SDLoc dl(Op);
2403   EVT OpVT = Op.getOperand(0).getValueType();
2404   assert(OpVT == MVT::i32 || (OpVT == MVT::i64));
2405 
2406   EVT floatVT = (OpVT == MVT::i32) ? MVT::f32 : MVT::f64;
2407 
2408   // Expand f128 operations to fp128 ABI calls.
2409   if (Op.getValueType() == MVT::f128
2410       && (!hasHardQuad || !TLI.isTypeLegal(OpVT))) {
2411     const char *libName = TLI.getLibcallName(OpVT == MVT::i32
2412                                              ? RTLIB::SINTTOFP_I32_F128
2413                                              : RTLIB::SINTTOFP_I64_F128);
2414     return TLI.LowerF128Op(Op, DAG, libName, 1);
2415   }
2416 
2417   // Expand if the operand type is illegal.
2418   if (!TLI.isTypeLegal(OpVT))
2419     return SDValue();
2420 
2421   // Otherwise, Convert the int value to FP in an FP register.
2422   SDValue Tmp = DAG.getNode(ISD::BITCAST, dl, floatVT, Op.getOperand(0));
2423   unsigned opcode = (OpVT == MVT::i32)? SPISD::ITOF : SPISD::XTOF;
2424   return DAG.getNode(opcode, dl, Op.getValueType(), Tmp);
2425 }
2426 
LowerFP_TO_UINT(SDValue Op,SelectionDAG & DAG,const SparcTargetLowering & TLI,bool hasHardQuad)2427 static SDValue LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG,
2428                                const SparcTargetLowering &TLI,
2429                                bool hasHardQuad) {
2430   SDLoc dl(Op);
2431   EVT VT = Op.getValueType();
2432 
2433   // Expand if it does not involve f128 or the target has support for
2434   // quad floating point instructions and the resulting type is legal.
2435   if (Op.getOperand(0).getValueType() != MVT::f128 ||
2436       (hasHardQuad && TLI.isTypeLegal(VT)))
2437     return SDValue();
2438 
2439   assert(VT == MVT::i32 || VT == MVT::i64);
2440 
2441   return TLI.LowerF128Op(Op, DAG,
2442                          TLI.getLibcallName(VT == MVT::i32
2443                                             ? RTLIB::FPTOUINT_F128_I32
2444                                             : RTLIB::FPTOUINT_F128_I64),
2445                          1);
2446 }
2447 
LowerUINT_TO_FP(SDValue Op,SelectionDAG & DAG,const SparcTargetLowering & TLI,bool hasHardQuad)2448 static SDValue LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2449                                const SparcTargetLowering &TLI,
2450                                bool hasHardQuad) {
2451   SDLoc dl(Op);
2452   EVT OpVT = Op.getOperand(0).getValueType();
2453   assert(OpVT == MVT::i32 || OpVT == MVT::i64);
2454 
2455   // Expand if it does not involve f128 or the target has support for
2456   // quad floating point instructions and the operand type is legal.
2457   if (Op.getValueType() != MVT::f128 || (hasHardQuad && TLI.isTypeLegal(OpVT)))
2458     return SDValue();
2459 
2460   return TLI.LowerF128Op(Op, DAG,
2461                          TLI.getLibcallName(OpVT == MVT::i32
2462                                             ? RTLIB::UINTTOFP_I32_F128
2463                                             : RTLIB::UINTTOFP_I64_F128),
2464                          1);
2465 }
2466 
LowerBR_CC(SDValue Op,SelectionDAG & DAG,const SparcTargetLowering & TLI,bool hasHardQuad)2467 static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG,
2468                           const SparcTargetLowering &TLI,
2469                           bool hasHardQuad) {
2470   SDValue Chain = Op.getOperand(0);
2471   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2472   SDValue LHS = Op.getOperand(2);
2473   SDValue RHS = Op.getOperand(3);
2474   SDValue Dest = Op.getOperand(4);
2475   SDLoc dl(Op);
2476   unsigned Opc, SPCC = ~0U;
2477 
2478   // If this is a br_cc of a "setcc", and if the setcc got lowered into
2479   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
2480   LookThroughSetCC(LHS, RHS, CC, SPCC);
2481 
2482   // Get the condition flag.
2483   SDValue CompareFlag;
2484   if (LHS.getValueType().isInteger()) {
2485     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, MVT::Glue, LHS, RHS);
2486     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
2487     // 32-bit compares use the icc flags, 64-bit uses the xcc flags.
2488     Opc = LHS.getValueType() == MVT::i32 ? SPISD::BRICC : SPISD::BRXCC;
2489   } else {
2490     if (!hasHardQuad && LHS.getValueType() == MVT::f128) {
2491       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
2492       CompareFlag = TLI.LowerF128Compare(LHS, RHS, SPCC, dl, DAG);
2493       Opc = SPISD::BRICC;
2494     } else {
2495       CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
2496       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
2497       Opc = SPISD::BRFCC;
2498     }
2499   }
2500   return DAG.getNode(Opc, dl, MVT::Other, Chain, Dest,
2501                      DAG.getConstant(SPCC, dl, MVT::i32), CompareFlag);
2502 }
2503 
LowerSELECT_CC(SDValue Op,SelectionDAG & DAG,const SparcTargetLowering & TLI,bool hasHardQuad)2504 static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG,
2505                               const SparcTargetLowering &TLI,
2506                               bool hasHardQuad) {
2507   SDValue LHS = Op.getOperand(0);
2508   SDValue RHS = Op.getOperand(1);
2509   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2510   SDValue TrueVal = Op.getOperand(2);
2511   SDValue FalseVal = Op.getOperand(3);
2512   SDLoc dl(Op);
2513   unsigned Opc, SPCC = ~0U;
2514 
2515   // If this is a select_cc of a "setcc", and if the setcc got lowered into
2516   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
2517   LookThroughSetCC(LHS, RHS, CC, SPCC);
2518 
2519   SDValue CompareFlag;
2520   if (LHS.getValueType().isInteger()) {
2521     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, MVT::Glue, LHS, RHS);
2522     Opc = LHS.getValueType() == MVT::i32 ?
2523           SPISD::SELECT_ICC : SPISD::SELECT_XCC;
2524     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
2525   } else {
2526     if (!hasHardQuad && LHS.getValueType() == MVT::f128) {
2527       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
2528       CompareFlag = TLI.LowerF128Compare(LHS, RHS, SPCC, dl, DAG);
2529       Opc = SPISD::SELECT_ICC;
2530     } else {
2531       CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
2532       Opc = SPISD::SELECT_FCC;
2533       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
2534     }
2535   }
2536   return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
2537                      DAG.getConstant(SPCC, dl, MVT::i32), CompareFlag);
2538 }
2539 
LowerEH_SJLJ_SETJMP(SDValue Op,SelectionDAG & DAG,const SparcTargetLowering & TLI) const2540 SDValue SparcTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG,
2541     const SparcTargetLowering &TLI) const {
2542   SDLoc DL(Op);
2543   return DAG.getNode(SPISD::EH_SJLJ_SETJMP, DL,
2544       DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), Op.getOperand(1));
2545 
2546 }
2547 
LowerEH_SJLJ_LONGJMP(SDValue Op,SelectionDAG & DAG,const SparcTargetLowering & TLI) const2548 SDValue SparcTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG,
2549     const SparcTargetLowering &TLI) const {
2550   SDLoc DL(Op);
2551   return DAG.getNode(SPISD::EH_SJLJ_LONGJMP, DL, MVT::Other, Op.getOperand(0), Op.getOperand(1));
2552 }
2553 
LowerVASTART(SDValue Op,SelectionDAG & DAG,const SparcTargetLowering & TLI)2554 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
2555                             const SparcTargetLowering &TLI) {
2556   MachineFunction &MF = DAG.getMachineFunction();
2557   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
2558   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
2559 
2560   // Need frame address to find the address of VarArgsFrameIndex.
2561   MF.getFrameInfo().setFrameAddressIsTaken(true);
2562 
2563   // vastart just stores the address of the VarArgsFrameIndex slot into the
2564   // memory location argument.
2565   SDLoc DL(Op);
2566   SDValue Offset =
2567       DAG.getNode(ISD::ADD, DL, PtrVT, DAG.getRegister(SP::I6, PtrVT),
2568                   DAG.getIntPtrConstant(FuncInfo->getVarArgsFrameOffset(), DL));
2569   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2570   return DAG.getStore(Op.getOperand(0), DL, Offset, Op.getOperand(1),
2571                       MachinePointerInfo(SV));
2572 }
2573 
LowerVAARG(SDValue Op,SelectionDAG & DAG)2574 static SDValue LowerVAARG(SDValue Op, SelectionDAG &DAG) {
2575   SDNode *Node = Op.getNode();
2576   EVT VT = Node->getValueType(0);
2577   SDValue InChain = Node->getOperand(0);
2578   SDValue VAListPtr = Node->getOperand(1);
2579   EVT PtrVT = VAListPtr.getValueType();
2580   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2581   SDLoc DL(Node);
2582   SDValue VAList =
2583       DAG.getLoad(PtrVT, DL, InChain, VAListPtr, MachinePointerInfo(SV));
2584   // Increment the pointer, VAList, to the next vaarg.
2585   SDValue NextPtr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
2586                                 DAG.getIntPtrConstant(VT.getSizeInBits()/8,
2587                                                       DL));
2588   // Store the incremented VAList to the legalized pointer.
2589   InChain = DAG.getStore(VAList.getValue(1), DL, NextPtr, VAListPtr,
2590                          MachinePointerInfo(SV));
2591   // Load the actual argument out of the pointer VAList.
2592   // We can't count on greater alignment than the word size.
2593   return DAG.getLoad(VT, DL, InChain, VAList, MachinePointerInfo(),
2594                      std::min(PtrVT.getSizeInBits(), VT.getSizeInBits()) / 8);
2595 }
2596 
LowerDYNAMIC_STACKALLOC(SDValue Op,SelectionDAG & DAG,const SparcSubtarget * Subtarget)2597 static SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG,
2598                                        const SparcSubtarget *Subtarget) {
2599   SDValue Chain = Op.getOperand(0);  // Legalize the chain.
2600   SDValue Size  = Op.getOperand(1);  // Legalize the size.
2601   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2602   unsigned StackAlign = Subtarget->getFrameLowering()->getStackAlignment();
2603   EVT VT = Size->getValueType(0);
2604   SDLoc dl(Op);
2605 
2606   // TODO: implement over-aligned alloca. (Note: also implies
2607   // supporting support for overaligned function frames + dynamic
2608   // allocations, at all, which currently isn't supported)
2609   if (Align > StackAlign) {
2610     const MachineFunction &MF = DAG.getMachineFunction();
2611     report_fatal_error("Function \"" + Twine(MF.getName()) + "\": "
2612                        "over-aligned dynamic alloca not supported.");
2613   }
2614 
2615   // The resultant pointer needs to be above the register spill area
2616   // at the bottom of the stack.
2617   unsigned regSpillArea;
2618   if (Subtarget->is64Bit()) {
2619     regSpillArea = 128;
2620   } else {
2621     // On Sparc32, the size of the spill area is 92. Unfortunately,
2622     // that's only 4-byte aligned, not 8-byte aligned (the stack
2623     // pointer is 8-byte aligned). So, if the user asked for an 8-byte
2624     // aligned dynamic allocation, we actually need to add 96 to the
2625     // bottom of the stack, instead of 92, to ensure 8-byte alignment.
2626 
2627     // That also means adding 4 to the size of the allocation --
2628     // before applying the 8-byte rounding. Unfortunately, we the
2629     // value we get here has already had rounding applied. So, we need
2630     // to add 8, instead, wasting a bit more memory.
2631 
2632     // Further, this only actually needs to be done if the required
2633     // alignment is > 4, but, we've lost that info by this point, too,
2634     // so we always apply it.
2635 
2636     // (An alternative approach would be to always reserve 96 bytes
2637     // instead of the required 92, but then we'd waste 4 extra bytes
2638     // in every frame, not just those with dynamic stack allocations)
2639 
2640     // TODO: modify code in SelectionDAGBuilder to make this less sad.
2641 
2642     Size = DAG.getNode(ISD::ADD, dl, VT, Size,
2643                        DAG.getConstant(8, dl, VT));
2644     regSpillArea = 96;
2645   }
2646 
2647   unsigned SPReg = SP::O6;
2648   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
2649   SDValue NewSP = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
2650   Chain = DAG.getCopyToReg(SP.getValue(1), dl, SPReg, NewSP);    // Output chain
2651 
2652   regSpillArea += Subtarget->getStackPointerBias();
2653 
2654   SDValue NewVal = DAG.getNode(ISD::ADD, dl, VT, NewSP,
2655                                DAG.getConstant(regSpillArea, dl, VT));
2656   SDValue Ops[2] = { NewVal, Chain };
2657   return DAG.getMergeValues(Ops, dl);
2658 }
2659 
2660 
getFLUSHW(SDValue Op,SelectionDAG & DAG)2661 static SDValue getFLUSHW(SDValue Op, SelectionDAG &DAG) {
2662   SDLoc dl(Op);
2663   SDValue Chain = DAG.getNode(SPISD::FLUSHW,
2664                               dl, MVT::Other, DAG.getEntryNode());
2665   return Chain;
2666 }
2667 
getFRAMEADDR(uint64_t depth,SDValue Op,SelectionDAG & DAG,const SparcSubtarget * Subtarget)2668 static SDValue getFRAMEADDR(uint64_t depth, SDValue Op, SelectionDAG &DAG,
2669                             const SparcSubtarget *Subtarget) {
2670   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2671   MFI.setFrameAddressIsTaken(true);
2672 
2673   EVT VT = Op.getValueType();
2674   SDLoc dl(Op);
2675   unsigned FrameReg = SP::I6;
2676   unsigned stackBias = Subtarget->getStackPointerBias();
2677 
2678   SDValue FrameAddr;
2679 
2680   if (depth == 0) {
2681     FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
2682     if (Subtarget->is64Bit())
2683       FrameAddr = DAG.getNode(ISD::ADD, dl, VT, FrameAddr,
2684                               DAG.getIntPtrConstant(stackBias, dl));
2685     return FrameAddr;
2686   }
2687 
2688   // flush first to make sure the windowed registers' values are in stack
2689   SDValue Chain = getFLUSHW(Op, DAG);
2690   FrameAddr = DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
2691 
2692   unsigned Offset = (Subtarget->is64Bit()) ? (stackBias + 112) : 56;
2693 
2694   while (depth--) {
2695     SDValue Ptr = DAG.getNode(ISD::ADD, dl, VT, FrameAddr,
2696                               DAG.getIntPtrConstant(Offset, dl));
2697     FrameAddr = DAG.getLoad(VT, dl, Chain, Ptr, MachinePointerInfo());
2698   }
2699   if (Subtarget->is64Bit())
2700     FrameAddr = DAG.getNode(ISD::ADD, dl, VT, FrameAddr,
2701                             DAG.getIntPtrConstant(stackBias, dl));
2702   return FrameAddr;
2703 }
2704 
2705 
LowerFRAMEADDR(SDValue Op,SelectionDAG & DAG,const SparcSubtarget * Subtarget)2706 static SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG,
2707                               const SparcSubtarget *Subtarget) {
2708 
2709   uint64_t depth = Op.getConstantOperandVal(0);
2710 
2711   return getFRAMEADDR(depth, Op, DAG, Subtarget);
2712 
2713 }
2714 
LowerRETURNADDR(SDValue Op,SelectionDAG & DAG,const SparcTargetLowering & TLI,const SparcSubtarget * Subtarget)2715 static SDValue LowerRETURNADDR(SDValue Op, SelectionDAG &DAG,
2716                                const SparcTargetLowering &TLI,
2717                                const SparcSubtarget *Subtarget) {
2718   MachineFunction &MF = DAG.getMachineFunction();
2719   MachineFrameInfo &MFI = MF.getFrameInfo();
2720   MFI.setReturnAddressIsTaken(true);
2721 
2722   if (TLI.verifyReturnAddressArgumentIsConstant(Op, DAG))
2723     return SDValue();
2724 
2725   EVT VT = Op.getValueType();
2726   SDLoc dl(Op);
2727   uint64_t depth = Op.getConstantOperandVal(0);
2728 
2729   SDValue RetAddr;
2730   if (depth == 0) {
2731     auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
2732     unsigned RetReg = MF.addLiveIn(SP::I7, TLI.getRegClassFor(PtrVT));
2733     RetAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, RetReg, VT);
2734     return RetAddr;
2735   }
2736 
2737   // Need frame address to find return address of the caller.
2738   SDValue FrameAddr = getFRAMEADDR(depth - 1, Op, DAG, Subtarget);
2739 
2740   unsigned Offset = (Subtarget->is64Bit()) ? 120 : 60;
2741   SDValue Ptr = DAG.getNode(ISD::ADD,
2742                             dl, VT,
2743                             FrameAddr,
2744                             DAG.getIntPtrConstant(Offset, dl));
2745   RetAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2746 
2747   return RetAddr;
2748 }
2749 
LowerF64Op(SDValue SrcReg64,const SDLoc & dl,SelectionDAG & DAG,unsigned opcode)2750 static SDValue LowerF64Op(SDValue SrcReg64, const SDLoc &dl, SelectionDAG &DAG,
2751                           unsigned opcode) {
2752   assert(SrcReg64.getValueType() == MVT::f64 && "LowerF64Op called on non-double!");
2753   assert(opcode == ISD::FNEG || opcode == ISD::FABS);
2754 
2755   // Lower fneg/fabs on f64 to fneg/fabs on f32.
2756   // fneg f64 => fneg f32:sub_even, fmov f32:sub_odd.
2757   // fabs f64 => fabs f32:sub_even, fmov f32:sub_odd.
2758 
2759   // Note: in little-endian, the floating-point value is stored in the
2760   // registers are in the opposite order, so the subreg with the sign
2761   // bit is the highest-numbered (odd), rather than the
2762   // lowest-numbered (even).
2763 
2764   SDValue Hi32 = DAG.getTargetExtractSubreg(SP::sub_even, dl, MVT::f32,
2765                                             SrcReg64);
2766   SDValue Lo32 = DAG.getTargetExtractSubreg(SP::sub_odd, dl, MVT::f32,
2767                                             SrcReg64);
2768 
2769   if (DAG.getDataLayout().isLittleEndian())
2770     Lo32 = DAG.getNode(opcode, dl, MVT::f32, Lo32);
2771   else
2772     Hi32 = DAG.getNode(opcode, dl, MVT::f32, Hi32);
2773 
2774   SDValue DstReg64 = SDValue(DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
2775                                                 dl, MVT::f64), 0);
2776   DstReg64 = DAG.getTargetInsertSubreg(SP::sub_even, dl, MVT::f64,
2777                                        DstReg64, Hi32);
2778   DstReg64 = DAG.getTargetInsertSubreg(SP::sub_odd, dl, MVT::f64,
2779                                        DstReg64, Lo32);
2780   return DstReg64;
2781 }
2782 
2783 // Lower a f128 load into two f64 loads.
LowerF128Load(SDValue Op,SelectionDAG & DAG)2784 static SDValue LowerF128Load(SDValue Op, SelectionDAG &DAG)
2785 {
2786   SDLoc dl(Op);
2787   LoadSDNode *LdNode = dyn_cast<LoadSDNode>(Op.getNode());
2788   assert(LdNode && LdNode->getOffset().isUndef()
2789          && "Unexpected node type");
2790 
2791   unsigned alignment = LdNode->getAlignment();
2792   if (alignment > 8)
2793     alignment = 8;
2794 
2795   SDValue Hi64 =
2796       DAG.getLoad(MVT::f64, dl, LdNode->getChain(), LdNode->getBasePtr(),
2797                   LdNode->getPointerInfo(), alignment);
2798   EVT addrVT = LdNode->getBasePtr().getValueType();
2799   SDValue LoPtr = DAG.getNode(ISD::ADD, dl, addrVT,
2800                               LdNode->getBasePtr(),
2801                               DAG.getConstant(8, dl, addrVT));
2802   SDValue Lo64 = DAG.getLoad(MVT::f64, dl, LdNode->getChain(), LoPtr,
2803                              LdNode->getPointerInfo(), alignment);
2804 
2805   SDValue SubRegEven = DAG.getTargetConstant(SP::sub_even64, dl, MVT::i32);
2806   SDValue SubRegOdd  = DAG.getTargetConstant(SP::sub_odd64, dl, MVT::i32);
2807 
2808   SDNode *InFP128 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
2809                                        dl, MVT::f128);
2810   InFP128 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl,
2811                                MVT::f128,
2812                                SDValue(InFP128, 0),
2813                                Hi64,
2814                                SubRegEven);
2815   InFP128 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl,
2816                                MVT::f128,
2817                                SDValue(InFP128, 0),
2818                                Lo64,
2819                                SubRegOdd);
2820   SDValue OutChains[2] = { SDValue(Hi64.getNode(), 1),
2821                            SDValue(Lo64.getNode(), 1) };
2822   SDValue OutChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
2823   SDValue Ops[2] = {SDValue(InFP128,0), OutChain};
2824   return DAG.getMergeValues(Ops, dl);
2825 }
2826 
LowerLOAD(SDValue Op,SelectionDAG & DAG)2827 static SDValue LowerLOAD(SDValue Op, SelectionDAG &DAG)
2828 {
2829   LoadSDNode *LdNode = cast<LoadSDNode>(Op.getNode());
2830 
2831   EVT MemVT = LdNode->getMemoryVT();
2832   if (MemVT == MVT::f128)
2833     return LowerF128Load(Op, DAG);
2834 
2835   return Op;
2836 }
2837 
2838 // Lower a f128 store into two f64 stores.
LowerF128Store(SDValue Op,SelectionDAG & DAG)2839 static SDValue LowerF128Store(SDValue Op, SelectionDAG &DAG) {
2840   SDLoc dl(Op);
2841   StoreSDNode *StNode = dyn_cast<StoreSDNode>(Op.getNode());
2842   assert(StNode && StNode->getOffset().isUndef()
2843          && "Unexpected node type");
2844   SDValue SubRegEven = DAG.getTargetConstant(SP::sub_even64, dl, MVT::i32);
2845   SDValue SubRegOdd  = DAG.getTargetConstant(SP::sub_odd64, dl, MVT::i32);
2846 
2847   SDNode *Hi64 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG,
2848                                     dl,
2849                                     MVT::f64,
2850                                     StNode->getValue(),
2851                                     SubRegEven);
2852   SDNode *Lo64 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG,
2853                                     dl,
2854                                     MVT::f64,
2855                                     StNode->getValue(),
2856                                     SubRegOdd);
2857 
2858   unsigned alignment = StNode->getAlignment();
2859   if (alignment > 8)
2860     alignment = 8;
2861 
2862   SDValue OutChains[2];
2863   OutChains[0] =
2864       DAG.getStore(StNode->getChain(), dl, SDValue(Hi64, 0),
2865                    StNode->getBasePtr(), MachinePointerInfo(), alignment);
2866   EVT addrVT = StNode->getBasePtr().getValueType();
2867   SDValue LoPtr = DAG.getNode(ISD::ADD, dl, addrVT,
2868                               StNode->getBasePtr(),
2869                               DAG.getConstant(8, dl, addrVT));
2870   OutChains[1] = DAG.getStore(StNode->getChain(), dl, SDValue(Lo64, 0), LoPtr,
2871                               MachinePointerInfo(), alignment);
2872   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
2873 }
2874 
LowerSTORE(SDValue Op,SelectionDAG & DAG)2875 static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG)
2876 {
2877   SDLoc dl(Op);
2878   StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
2879 
2880   EVT MemVT = St->getMemoryVT();
2881   if (MemVT == MVT::f128)
2882     return LowerF128Store(Op, DAG);
2883 
2884   if (MemVT == MVT::i64) {
2885     // Custom handling for i64 stores: turn it into a bitcast and a
2886     // v2i32 store.
2887     SDValue Val = DAG.getNode(ISD::BITCAST, dl, MVT::v2i32, St->getValue());
2888     SDValue Chain = DAG.getStore(
2889         St->getChain(), dl, Val, St->getBasePtr(), St->getPointerInfo(),
2890         St->getAlignment(), St->getMemOperand()->getFlags(), St->getAAInfo());
2891     return Chain;
2892   }
2893 
2894   return SDValue();
2895 }
2896 
LowerFNEGorFABS(SDValue Op,SelectionDAG & DAG,bool isV9)2897 static SDValue LowerFNEGorFABS(SDValue Op, SelectionDAG &DAG, bool isV9) {
2898   assert((Op.getOpcode() == ISD::FNEG || Op.getOpcode() == ISD::FABS)
2899          && "invalid opcode");
2900 
2901   SDLoc dl(Op);
2902 
2903   if (Op.getValueType() == MVT::f64)
2904     return LowerF64Op(Op.getOperand(0), dl, DAG, Op.getOpcode());
2905   if (Op.getValueType() != MVT::f128)
2906     return Op;
2907 
2908   // Lower fabs/fneg on f128 to fabs/fneg on f64
2909   // fabs/fneg f128 => fabs/fneg f64:sub_even64, fmov f64:sub_odd64
2910   // (As with LowerF64Op, on little-endian, we need to negate the odd
2911   // subreg)
2912 
2913   SDValue SrcReg128 = Op.getOperand(0);
2914   SDValue Hi64 = DAG.getTargetExtractSubreg(SP::sub_even64, dl, MVT::f64,
2915                                             SrcReg128);
2916   SDValue Lo64 = DAG.getTargetExtractSubreg(SP::sub_odd64, dl, MVT::f64,
2917                                             SrcReg128);
2918 
2919   if (DAG.getDataLayout().isLittleEndian()) {
2920     if (isV9)
2921       Lo64 = DAG.getNode(Op.getOpcode(), dl, MVT::f64, Lo64);
2922     else
2923       Lo64 = LowerF64Op(Lo64, dl, DAG, Op.getOpcode());
2924   } else {
2925     if (isV9)
2926       Hi64 = DAG.getNode(Op.getOpcode(), dl, MVT::f64, Hi64);
2927     else
2928       Hi64 = LowerF64Op(Hi64, dl, DAG, Op.getOpcode());
2929   }
2930 
2931   SDValue DstReg128 = SDValue(DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
2932                                                  dl, MVT::f128), 0);
2933   DstReg128 = DAG.getTargetInsertSubreg(SP::sub_even64, dl, MVT::f128,
2934                                         DstReg128, Hi64);
2935   DstReg128 = DAG.getTargetInsertSubreg(SP::sub_odd64, dl, MVT::f128,
2936                                         DstReg128, Lo64);
2937   return DstReg128;
2938 }
2939 
LowerADDC_ADDE_SUBC_SUBE(SDValue Op,SelectionDAG & DAG)2940 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2941 
2942   if (Op.getValueType() != MVT::i64)
2943     return Op;
2944 
2945   SDLoc dl(Op);
2946   SDValue Src1 = Op.getOperand(0);
2947   SDValue Src1Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src1);
2948   SDValue Src1Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Src1,
2949                                DAG.getConstant(32, dl, MVT::i64));
2950   Src1Hi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src1Hi);
2951 
2952   SDValue Src2 = Op.getOperand(1);
2953   SDValue Src2Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src2);
2954   SDValue Src2Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Src2,
2955                                DAG.getConstant(32, dl, MVT::i64));
2956   Src2Hi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src2Hi);
2957 
2958 
2959   bool hasChain = false;
2960   unsigned hiOpc = Op.getOpcode();
2961   switch (Op.getOpcode()) {
2962   default: llvm_unreachable("Invalid opcode");
2963   case ISD::ADDC: hiOpc = ISD::ADDE; break;
2964   case ISD::ADDE: hasChain = true; break;
2965   case ISD::SUBC: hiOpc = ISD::SUBE; break;
2966   case ISD::SUBE: hasChain = true; break;
2967   }
2968   SDValue Lo;
2969   SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Glue);
2970   if (hasChain) {
2971     Lo = DAG.getNode(Op.getOpcode(), dl, VTs, Src1Lo, Src2Lo,
2972                      Op.getOperand(2));
2973   } else {
2974     Lo = DAG.getNode(Op.getOpcode(), dl, VTs, Src1Lo, Src2Lo);
2975   }
2976   SDValue Hi = DAG.getNode(hiOpc, dl, VTs, Src1Hi, Src2Hi, Lo.getValue(1));
2977   SDValue Carry = Hi.getValue(1);
2978 
2979   Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Lo);
2980   Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Hi);
2981   Hi = DAG.getNode(ISD::SHL, dl, MVT::i64, Hi,
2982                    DAG.getConstant(32, dl, MVT::i64));
2983 
2984   SDValue Dst = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, Lo);
2985   SDValue Ops[2] = { Dst, Carry };
2986   return DAG.getMergeValues(Ops, dl);
2987 }
2988 
2989 // Custom lower UMULO/SMULO for SPARC. This code is similar to ExpandNode()
2990 // in LegalizeDAG.cpp except the order of arguments to the library function.
LowerUMULO_SMULO(SDValue Op,SelectionDAG & DAG,const SparcTargetLowering & TLI)2991 static SDValue LowerUMULO_SMULO(SDValue Op, SelectionDAG &DAG,
2992                                 const SparcTargetLowering &TLI)
2993 {
2994   unsigned opcode = Op.getOpcode();
2995   assert((opcode == ISD::UMULO || opcode == ISD::SMULO) && "Invalid Opcode.");
2996 
2997   bool isSigned = (opcode == ISD::SMULO);
2998   EVT VT = MVT::i64;
2999   EVT WideVT = MVT::i128;
3000   SDLoc dl(Op);
3001   SDValue LHS = Op.getOperand(0);
3002 
3003   if (LHS.getValueType() != VT)
3004     return Op;
3005 
3006   SDValue ShiftAmt = DAG.getConstant(63, dl, VT);
3007 
3008   SDValue RHS = Op.getOperand(1);
3009   SDValue HiLHS = DAG.getNode(ISD::SRA, dl, VT, LHS, ShiftAmt);
3010   SDValue HiRHS = DAG.getNode(ISD::SRA, dl, MVT::i64, RHS, ShiftAmt);
3011   SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
3012 
3013   SDValue MulResult = TLI.makeLibCall(DAG,
3014                                       RTLIB::MUL_I128, WideVT,
3015                                       Args, isSigned, dl).first;
3016   SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT,
3017                                    MulResult, DAG.getIntPtrConstant(0, dl));
3018   SDValue TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT,
3019                                 MulResult, DAG.getIntPtrConstant(1, dl));
3020   if (isSigned) {
3021     SDValue Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
3022     TopHalf = DAG.getSetCC(dl, MVT::i32, TopHalf, Tmp1, ISD::SETNE);
3023   } else {
3024     TopHalf = DAG.getSetCC(dl, MVT::i32, TopHalf, DAG.getConstant(0, dl, VT),
3025                            ISD::SETNE);
3026   }
3027   // MulResult is a node with an illegal type. Because such things are not
3028   // generally permitted during this phase of legalization, ensure that
3029   // nothing is left using the node. The above EXTRACT_ELEMENT nodes should have
3030   // been folded.
3031   assert(MulResult->use_empty() && "Illegally typed node still in use!");
3032 
3033   SDValue Ops[2] = { BottomHalf, TopHalf } ;
3034   return DAG.getMergeValues(Ops, dl);
3035 }
3036 
LowerATOMIC_LOAD_STORE(SDValue Op,SelectionDAG & DAG)3037 static SDValue LowerATOMIC_LOAD_STORE(SDValue Op, SelectionDAG &DAG) {
3038   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
3039   // Expand with a fence.
3040   return SDValue();
3041 
3042   // Monotonic load/stores are legal.
3043   return Op;
3044 }
3045 
LowerINTRINSIC_WO_CHAIN(SDValue Op,SelectionDAG & DAG) const3046 SDValue SparcTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3047                                                      SelectionDAG &DAG) const {
3048   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3049   SDLoc dl(Op);
3050   switch (IntNo) {
3051   default: return SDValue();    // Don't custom lower most intrinsics.
3052   case Intrinsic::thread_pointer: {
3053     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3054     return DAG.getRegister(SP::G7, PtrVT);
3055   }
3056   }
3057 }
3058 
3059 SDValue SparcTargetLowering::
LowerOperation(SDValue Op,SelectionDAG & DAG) const3060 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3061 
3062   bool hasHardQuad = Subtarget->hasHardQuad();
3063   bool isV9        = Subtarget->isV9();
3064 
3065   switch (Op.getOpcode()) {
3066   default: llvm_unreachable("Should not custom lower this!");
3067 
3068   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG, *this,
3069                                                        Subtarget);
3070   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG,
3071                                                       Subtarget);
3072   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
3073   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
3074   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
3075   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
3076   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG, *this,
3077                                                        hasHardQuad);
3078   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG, *this,
3079                                                        hasHardQuad);
3080   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG, *this,
3081                                                        hasHardQuad);
3082   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG, *this,
3083                                                        hasHardQuad);
3084   case ISD::BR_CC:              return LowerBR_CC(Op, DAG, *this,
3085                                                   hasHardQuad);
3086   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG, *this,
3087                                                       hasHardQuad);
3088   case ISD::EH_SJLJ_SETJMP:     return LowerEH_SJLJ_SETJMP(Op, DAG, *this);
3089   case ISD::EH_SJLJ_LONGJMP:    return LowerEH_SJLJ_LONGJMP(Op, DAG, *this);
3090   case ISD::VASTART:            return LowerVASTART(Op, DAG, *this);
3091   case ISD::VAARG:              return LowerVAARG(Op, DAG);
3092   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG,
3093                                                                Subtarget);
3094 
3095   case ISD::LOAD:               return LowerLOAD(Op, DAG);
3096   case ISD::STORE:              return LowerSTORE(Op, DAG);
3097   case ISD::FADD:               return LowerF128Op(Op, DAG,
3098                                        getLibcallName(RTLIB::ADD_F128), 2);
3099   case ISD::FSUB:               return LowerF128Op(Op, DAG,
3100                                        getLibcallName(RTLIB::SUB_F128), 2);
3101   case ISD::FMUL:               return LowerF128Op(Op, DAG,
3102                                        getLibcallName(RTLIB::MUL_F128), 2);
3103   case ISD::FDIV:               return LowerF128Op(Op, DAG,
3104                                        getLibcallName(RTLIB::DIV_F128), 2);
3105   case ISD::FSQRT:              return LowerF128Op(Op, DAG,
3106                                        getLibcallName(RTLIB::SQRT_F128),1);
3107   case ISD::FABS:
3108   case ISD::FNEG:               return LowerFNEGorFABS(Op, DAG, isV9);
3109   case ISD::FP_EXTEND:          return LowerF128_FPEXTEND(Op, DAG, *this);
3110   case ISD::FP_ROUND:           return LowerF128_FPROUND(Op, DAG, *this);
3111   case ISD::ADDC:
3112   case ISD::ADDE:
3113   case ISD::SUBC:
3114   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
3115   case ISD::UMULO:
3116   case ISD::SMULO:              return LowerUMULO_SMULO(Op, DAG, *this);
3117   case ISD::ATOMIC_LOAD:
3118   case ISD::ATOMIC_STORE:       return LowerATOMIC_LOAD_STORE(Op, DAG);
3119   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3120   }
3121 }
3122 
3123 MachineBasicBlock *
EmitInstrWithCustomInserter(MachineInstr & MI,MachineBasicBlock * BB) const3124 SparcTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
3125                                                  MachineBasicBlock *BB) const {
3126   switch (MI.getOpcode()) {
3127   default: llvm_unreachable("Unknown SELECT_CC!");
3128   case SP::SELECT_CC_Int_ICC:
3129   case SP::SELECT_CC_FP_ICC:
3130   case SP::SELECT_CC_DFP_ICC:
3131   case SP::SELECT_CC_QFP_ICC:
3132     return expandSelectCC(MI, BB, SP::BCOND);
3133   case SP::SELECT_CC_Int_FCC:
3134   case SP::SELECT_CC_FP_FCC:
3135   case SP::SELECT_CC_DFP_FCC:
3136   case SP::SELECT_CC_QFP_FCC:
3137     return expandSelectCC(MI, BB, SP::FBCOND);
3138   case SP::EH_SJLJ_SETJMP32ri:
3139   case SP::EH_SJLJ_SETJMP32rr:
3140     return emitEHSjLjSetJmp(MI, BB);
3141   case SP::EH_SJLJ_LONGJMP32rr:
3142   case SP::EH_SJLJ_LONGJMP32ri:
3143     return emitEHSjLjLongJmp(MI, BB);
3144 
3145   }
3146 }
3147 
3148 MachineBasicBlock *
expandSelectCC(MachineInstr & MI,MachineBasicBlock * BB,unsigned BROpcode) const3149 SparcTargetLowering::expandSelectCC(MachineInstr &MI, MachineBasicBlock *BB,
3150                                     unsigned BROpcode) const {
3151   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
3152   DebugLoc dl = MI.getDebugLoc();
3153   unsigned CC = (SPCC::CondCodes)MI.getOperand(3).getImm();
3154 
3155   // To "insert" a SELECT_CC instruction, we actually have to insert the
3156   // triangle control-flow pattern. The incoming instruction knows the
3157   // destination vreg to set, the condition code register to branch on, the
3158   // true/false values to select between, and the condition code for the branch.
3159   //
3160   // We produce the following control flow:
3161   //     ThisMBB
3162   //     |  \
3163   //     |  IfFalseMBB
3164   //     | /
3165   //    SinkMBB
3166   const BasicBlock *LLVM_BB = BB->getBasicBlock();
3167   MachineFunction::iterator It = ++BB->getIterator();
3168 
3169   MachineBasicBlock *ThisMBB = BB;
3170   MachineFunction *F = BB->getParent();
3171   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
3172   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
3173   F->insert(It, IfFalseMBB);
3174   F->insert(It, SinkMBB);
3175 
3176   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
3177   SinkMBB->splice(SinkMBB->begin(), ThisMBB,
3178                   std::next(MachineBasicBlock::iterator(MI)), ThisMBB->end());
3179   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
3180 
3181   // Set the new successors for ThisMBB.
3182   ThisMBB->addSuccessor(IfFalseMBB);
3183   ThisMBB->addSuccessor(SinkMBB);
3184 
3185   BuildMI(ThisMBB, dl, TII.get(BROpcode))
3186     .addMBB(SinkMBB)
3187     .addImm(CC);
3188 
3189   // IfFalseMBB just falls through to SinkMBB.
3190   IfFalseMBB->addSuccessor(SinkMBB);
3191 
3192   // %Result = phi [ %TrueValue, ThisMBB ], [ %FalseValue, IfFalseMBB ]
3193   BuildMI(*SinkMBB, SinkMBB->begin(), dl, TII.get(SP::PHI),
3194           MI.getOperand(0).getReg())
3195       .addReg(MI.getOperand(1).getReg())
3196       .addMBB(ThisMBB)
3197       .addReg(MI.getOperand(2).getReg())
3198       .addMBB(IfFalseMBB);
3199 
3200   MI.eraseFromParent(); // The pseudo instruction is gone now.
3201   return SinkMBB;
3202 }
3203 
3204 MachineBasicBlock *
emitEHSjLjLongJmp(MachineInstr & MI,MachineBasicBlock * MBB) const3205 SparcTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
3206                                        MachineBasicBlock *MBB) const {
3207   DebugLoc DL = MI.getDebugLoc();
3208   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
3209 
3210   MachineFunction *MF = MBB->getParent();
3211   MachineRegisterInfo &MRI = MF->getRegInfo();
3212   MachineInstrBuilder MIB;
3213 
3214   MVT PVT = getPointerTy(MF->getDataLayout());
3215   unsigned RegSize = PVT.getStoreSize();
3216   assert(PVT == MVT::i32 && "Invalid Pointer Size!");
3217 
3218   unsigned Buf = MI.getOperand(0).getReg();
3219   unsigned JmpLoc = MRI.createVirtualRegister(&SP::IntRegsRegClass);
3220 
3221   // TO DO: If we do 64-bit handling, this perhaps should be FLUSHW, not TA 3
3222   MIB = BuildMI(*MBB, MI, DL, TII->get(SP::TRAPri), SP::G0).addImm(3).addImm(SPCC::ICC_A);
3223 
3224   // Instruction to restore FP
3225   const unsigned FP  = SP::I6;
3226   MIB = BuildMI(*MBB, MI, DL, TII->get(SP::LDri))
3227             .addReg(FP)
3228             .addReg(Buf)
3229             .addImm(0);
3230 
3231   // Instruction to load jmp location
3232   MIB = BuildMI(*MBB, MI, DL, TII->get(SP::LDri))
3233             .addReg(JmpLoc, RegState::Define)
3234             .addReg(Buf)
3235             .addImm(RegSize);
3236 
3237   // Instruction to restore SP
3238   const unsigned SP  = SP::O6;
3239   MIB = BuildMI(*MBB, MI, DL, TII->get(SP::LDri))
3240             .addReg(SP)
3241             .addReg(Buf)
3242             .addImm(2 * RegSize);
3243 
3244   // Instruction to restore I7
3245   MIB = BuildMI(*MBB, MI, DL, TII->get(SP::LDri))
3246             .addReg(SP::I7)
3247             .addReg(Buf, RegState::Kill)
3248             .addImm(3 * RegSize);
3249 
3250   // Jump to JmpLoc
3251   BuildMI(*MBB, MI, DL, TII->get(SP::JMPLrr)).addReg(SP::G0).addReg(JmpLoc, RegState::Kill).addReg(SP::G0);
3252 
3253   MI.eraseFromParent();
3254   return MBB;
3255 }
3256 
3257 MachineBasicBlock *
emitEHSjLjSetJmp(MachineInstr & MI,MachineBasicBlock * MBB) const3258 SparcTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
3259                                       MachineBasicBlock *MBB) const {
3260   DebugLoc DL = MI.getDebugLoc();
3261   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
3262   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3263 
3264   MachineFunction *MF = MBB->getParent();
3265   MachineRegisterInfo &MRI = MF->getRegInfo();
3266   MachineInstrBuilder MIB;
3267 
3268   MVT PVT = getPointerTy(MF->getDataLayout());
3269   unsigned RegSize = PVT.getStoreSize();
3270   assert(PVT == MVT::i32 && "Invalid Pointer Size!");
3271 
3272   unsigned DstReg = MI.getOperand(0).getReg();
3273   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
3274   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
3275   (void)TRI;
3276   unsigned mainDstReg = MRI.createVirtualRegister(RC);
3277   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
3278 
3279   // For v = setjmp(buf), we generate
3280   //
3281   // thisMBB:
3282   //  buf[0] = FP
3283   //  buf[RegSize] = restoreMBB <-- takes address of restoreMBB
3284   //  buf[RegSize * 2] = O6
3285   //  buf[RegSize * 3] = I7
3286   //  Ensure restoreMBB remains in the relocations list (done using a bn instruction)
3287   //  b mainMBB
3288   //
3289   // mainMBB:
3290   //  v_main = 0
3291   //  b sinkMBB
3292   //
3293   // restoreMBB:
3294   //  v_restore = 1
3295   //  --fall through--
3296   //
3297   // sinkMBB:
3298   //  v = phi(main, restore)
3299 
3300   const BasicBlock *BB = MBB->getBasicBlock();
3301   MachineFunction::iterator It = ++MBB->getIterator();
3302   MachineBasicBlock *thisMBB = MBB;
3303   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
3304   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
3305   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
3306 
3307   MF->insert(It, mainMBB);
3308   MF->insert(It, restoreMBB);
3309   MF->insert(It, sinkMBB);
3310   restoreMBB->setHasAddressTaken();
3311 
3312   // Transfer the remainder of BB and its successor edges to sinkMBB.
3313   sinkMBB->splice(sinkMBB->begin(), MBB,
3314                   std::next(MachineBasicBlock::iterator(MI)),
3315                   MBB->end());
3316   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
3317 
3318   unsigned LabelReg = MRI.createVirtualRegister(&SP::IntRegsRegClass);
3319   unsigned LabelReg2 = MRI.createVirtualRegister(&SP::IntRegsRegClass);
3320   unsigned BufReg = MI.getOperand(1).getReg();
3321 
3322   // Instruction to store FP
3323   const unsigned FP  = SP::I6;
3324   MIB = BuildMI(thisMBB, DL, TII->get(SP::STri))
3325             .addReg(BufReg)
3326             .addImm(0)
3327             .addReg(FP);
3328 
3329   // Instructions to store jmp location
3330   MIB = BuildMI(thisMBB, DL, TII->get(SP::SETHIi))
3331             .addReg(LabelReg, RegState::Define)
3332             .addMBB(restoreMBB, SparcMCExpr::VK_Sparc_HI);
3333 
3334   MIB = BuildMI(thisMBB, DL, TII->get(SP::ORri))
3335             .addReg(LabelReg2, RegState::Define)
3336             .addReg(LabelReg, RegState::Kill)
3337             .addMBB(restoreMBB, SparcMCExpr::VK_Sparc_LO);
3338 
3339   MIB = BuildMI(thisMBB, DL, TII->get(SP::STri))
3340             .addReg(BufReg)
3341             .addImm(RegSize)
3342             .addReg(LabelReg2, RegState::Kill);
3343 
3344   // Instruction to store SP
3345   const unsigned SP  = SP::O6;
3346   MIB = BuildMI(thisMBB, DL, TII->get(SP::STri))
3347             .addReg(BufReg)
3348             .addImm(2 * RegSize)
3349             .addReg(SP);
3350 
3351   // Instruction to store I7
3352   MIB = BuildMI(thisMBB, DL, TII->get(SP::STri))
3353             .addReg(BufReg)
3354             .addImm(3 * RegSize)
3355             .addReg(SP::I7);
3356 
3357 
3358   // FIX ME: This next instruction ensures that the restoreMBB block address remains
3359   // valid through optimization passes and serves no other purpose. The ICC_N ensures
3360   // that the branch is never taken. This commented-out code here was an alternative
3361   // attempt to achieve this which brought myriad problems.
3362   //MIB = BuildMI(thisMBB, DL, TII->get(SP::EH_SjLj_Setup)).addMBB(restoreMBB, SparcMCExpr::VK_Sparc_None);
3363   MIB = BuildMI(thisMBB, DL, TII->get(SP::BCOND))
3364               .addMBB(restoreMBB)
3365               .addImm(SPCC::ICC_N);
3366 
3367   MIB = BuildMI(thisMBB, DL, TII->get(SP::BCOND))
3368               .addMBB(mainMBB)
3369               .addImm(SPCC::ICC_A);
3370 
3371   thisMBB->addSuccessor(mainMBB);
3372   thisMBB->addSuccessor(restoreMBB);
3373 
3374 
3375   // mainMBB:
3376   MIB = BuildMI(mainMBB, DL, TII->get(SP::ORrr))
3377              .addReg(mainDstReg, RegState::Define)
3378              .addReg(SP::G0)
3379              .addReg(SP::G0);
3380   MIB = BuildMI(mainMBB, DL, TII->get(SP::BCOND)).addMBB(sinkMBB).addImm(SPCC::ICC_A);
3381 
3382   mainMBB->addSuccessor(sinkMBB);
3383 
3384 
3385   // restoreMBB:
3386   MIB = BuildMI(restoreMBB, DL, TII->get(SP::ORri))
3387               .addReg(restoreDstReg, RegState::Define)
3388               .addReg(SP::G0)
3389               .addImm(1);
3390   //MIB = BuildMI(restoreMBB, DL, TII->get(SP::BCOND)).addMBB(sinkMBB).addImm(SPCC::ICC_A);
3391   restoreMBB->addSuccessor(sinkMBB);
3392 
3393   // sinkMBB:
3394   MIB = BuildMI(*sinkMBB, sinkMBB->begin(), DL,
3395                 TII->get(SP::PHI), DstReg)
3396              .addReg(mainDstReg).addMBB(mainMBB)
3397              .addReg(restoreDstReg).addMBB(restoreMBB);
3398 
3399   MI.eraseFromParent();
3400   return sinkMBB;
3401 }
3402 
3403 //===----------------------------------------------------------------------===//
3404 //                         Sparc Inline Assembly Support
3405 //===----------------------------------------------------------------------===//
3406 
3407 /// getConstraintType - Given a constraint letter, return the type of
3408 /// constraint it is for this target.
3409 SparcTargetLowering::ConstraintType
getConstraintType(StringRef Constraint) const3410 SparcTargetLowering::getConstraintType(StringRef Constraint) const {
3411   if (Constraint.size() == 1) {
3412     switch (Constraint[0]) {
3413     default:  break;
3414     case 'r':
3415     case 'f':
3416     case 'e':
3417       return C_RegisterClass;
3418     case 'I': // SIMM13
3419       return C_Other;
3420     }
3421   }
3422 
3423   return TargetLowering::getConstraintType(Constraint);
3424 }
3425 
3426 TargetLowering::ConstraintWeight SparcTargetLowering::
getSingleConstraintMatchWeight(AsmOperandInfo & info,const char * constraint) const3427 getSingleConstraintMatchWeight(AsmOperandInfo &info,
3428                                const char *constraint) const {
3429   ConstraintWeight weight = CW_Invalid;
3430   Value *CallOperandVal = info.CallOperandVal;
3431   // If we don't have a value, we can't do a match,
3432   // but allow it at the lowest weight.
3433   if (!CallOperandVal)
3434     return CW_Default;
3435 
3436   // Look at the constraint type.
3437   switch (*constraint) {
3438   default:
3439     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3440     break;
3441   case 'I': // SIMM13
3442     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
3443       if (isInt<13>(C->getSExtValue()))
3444         weight = CW_Constant;
3445     }
3446     break;
3447   }
3448   return weight;
3449 }
3450 
3451 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3452 /// vector.  If it is invalid, don't add anything to Ops.
3453 void SparcTargetLowering::
LowerAsmOperandForConstraint(SDValue Op,std::string & Constraint,std::vector<SDValue> & Ops,SelectionDAG & DAG) const3454 LowerAsmOperandForConstraint(SDValue Op,
3455                              std::string &Constraint,
3456                              std::vector<SDValue> &Ops,
3457                              SelectionDAG &DAG) const {
3458   SDValue Result(nullptr, 0);
3459 
3460   // Only support length 1 constraints for now.
3461   if (Constraint.length() > 1)
3462     return;
3463 
3464   char ConstraintLetter = Constraint[0];
3465   switch (ConstraintLetter) {
3466   default: break;
3467   case 'I':
3468     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3469       if (isInt<13>(C->getSExtValue())) {
3470         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
3471                                        Op.getValueType());
3472         break;
3473       }
3474       return;
3475     }
3476   }
3477 
3478   if (Result.getNode()) {
3479     Ops.push_back(Result);
3480     return;
3481   }
3482   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3483 }
3484 
3485 std::pair<unsigned, const TargetRegisterClass *>
getRegForInlineAsmConstraint(const TargetRegisterInfo * TRI,StringRef Constraint,MVT VT) const3486 SparcTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3487                                                   StringRef Constraint,
3488                                                   MVT VT) const {
3489   if (Constraint.size() == 1) {
3490     switch (Constraint[0]) {
3491     case 'r':
3492       if (VT == MVT::v2i32)
3493         return std::make_pair(0U, &SP::IntPairRegClass);
3494       else
3495         return std::make_pair(0U, &SP::IntRegsRegClass);
3496     case 'f':
3497       if (VT == MVT::f32)
3498         return std::make_pair(0U, &SP::FPRegsRegClass);
3499       else if (VT == MVT::f64)
3500         return std::make_pair(0U, &SP::LowDFPRegsRegClass);
3501       else if (VT == MVT::f128)
3502         return std::make_pair(0U, &SP::LowQFPRegsRegClass);
3503       llvm_unreachable("Unknown ValueType for f-register-type!");
3504       break;
3505     case 'e':
3506       if (VT == MVT::f32)
3507         return std::make_pair(0U, &SP::FPRegsRegClass);
3508       else if (VT == MVT::f64)
3509         return std::make_pair(0U, &SP::DFPRegsRegClass);
3510       else if (VT == MVT::f128)
3511         return std::make_pair(0U, &SP::QFPRegsRegClass);
3512       llvm_unreachable("Unknown ValueType for e-register-type!");
3513       break;
3514     }
3515   } else if (!Constraint.empty() && Constraint.size() <= 5
3516               && Constraint[0] == '{' && *(Constraint.end()-1) == '}') {
3517     // constraint = '{r<d>}'
3518     // Remove the braces from around the name.
3519     StringRef name(Constraint.data()+1, Constraint.size()-2);
3520     // Handle register aliases:
3521     //       r0-r7   -> g0-g7
3522     //       r8-r15  -> o0-o7
3523     //       r16-r23 -> l0-l7
3524     //       r24-r31 -> i0-i7
3525     uint64_t intVal = 0;
3526     if (name.substr(0, 1).equals("r")
3527         && !name.substr(1).getAsInteger(10, intVal) && intVal <= 31) {
3528       const char regTypes[] = { 'g', 'o', 'l', 'i' };
3529       char regType = regTypes[intVal/8];
3530       char regIdx = '0' + (intVal % 8);
3531       char tmp[] = { '{', regType, regIdx, '}', 0 };
3532       std::string newConstraint = std::string(tmp);
3533       return TargetLowering::getRegForInlineAsmConstraint(TRI, newConstraint,
3534                                                           VT);
3535     }
3536     if (name.substr(0, 1).equals("f") &&
3537         !name.substr(1).getAsInteger(10, intVal) && intVal <= 63) {
3538       std::string newConstraint;
3539 
3540       if (VT == MVT::f32 || VT == MVT::Other) {
3541         newConstraint = "{f" + utostr(intVal) + "}";
3542       } else if (VT == MVT::f64 && (intVal % 2 == 0)) {
3543         newConstraint = "{d" + utostr(intVal / 2) + "}";
3544       } else if (VT == MVT::f128 && (intVal % 4 == 0)) {
3545         newConstraint = "{q" + utostr(intVal / 4) + "}";
3546       } else {
3547         return std::make_pair(0U, nullptr);
3548       }
3549       return TargetLowering::getRegForInlineAsmConstraint(TRI, newConstraint,
3550                                                           VT);
3551     }
3552   }
3553 
3554   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3555 }
3556 
3557 bool
isOffsetFoldingLegal(const GlobalAddressSDNode * GA) const3558 SparcTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3559   // The Sparc target isn't yet aware of offsets.
3560   return false;
3561 }
3562 
ReplaceNodeResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const3563 void SparcTargetLowering::ReplaceNodeResults(SDNode *N,
3564                                              SmallVectorImpl<SDValue>& Results,
3565                                              SelectionDAG &DAG) const {
3566 
3567   SDLoc dl(N);
3568 
3569   RTLIB::Libcall libCall = RTLIB::UNKNOWN_LIBCALL;
3570 
3571   switch (N->getOpcode()) {
3572   default:
3573     llvm_unreachable("Do not know how to custom type legalize this operation!");
3574 
3575   case ISD::FP_TO_SINT:
3576   case ISD::FP_TO_UINT:
3577     // Custom lower only if it involves f128 or i64.
3578     if (N->getOperand(0).getValueType() != MVT::f128
3579         || N->getValueType(0) != MVT::i64)
3580       return;
3581     libCall = ((N->getOpcode() == ISD::FP_TO_SINT)
3582                ? RTLIB::FPTOSINT_F128_I64
3583                : RTLIB::FPTOUINT_F128_I64);
3584 
3585     Results.push_back(LowerF128Op(SDValue(N, 0),
3586                                   DAG,
3587                                   getLibcallName(libCall),
3588                                   1));
3589     return;
3590 
3591   case ISD::SINT_TO_FP:
3592   case ISD::UINT_TO_FP:
3593     // Custom lower only if it involves f128 or i64.
3594     if (N->getValueType(0) != MVT::f128
3595         || N->getOperand(0).getValueType() != MVT::i64)
3596       return;
3597 
3598     libCall = ((N->getOpcode() == ISD::SINT_TO_FP)
3599                ? RTLIB::SINTTOFP_I64_F128
3600                : RTLIB::UINTTOFP_I64_F128);
3601 
3602     Results.push_back(LowerF128Op(SDValue(N, 0),
3603                                   DAG,
3604                                   getLibcallName(libCall),
3605                                   1));
3606     return;
3607   case ISD::LOAD: {
3608     LoadSDNode *Ld = cast<LoadSDNode>(N);
3609     // Custom handling only for i64: turn i64 load into a v2i32 load,
3610     // and a bitcast.
3611     if (Ld->getValueType(0) != MVT::i64 || Ld->getMemoryVT() != MVT::i64)
3612       return;
3613 
3614     SDLoc dl(N);
3615     SDValue LoadRes = DAG.getExtLoad(
3616         Ld->getExtensionType(), dl, MVT::v2i32, Ld->getChain(),
3617         Ld->getBasePtr(), Ld->getPointerInfo(), MVT::v2i32, Ld->getAlignment(),
3618         Ld->getMemOperand()->getFlags(), Ld->getAAInfo());
3619 
3620     SDValue Res = DAG.getNode(ISD::BITCAST, dl, MVT::i64, LoadRes);
3621     Results.push_back(Res);
3622     Results.push_back(LoadRes.getValue(1));
3623     return;
3624   }
3625   }
3626 }
3627 
3628 // Override to enable LOAD_STACK_GUARD lowering on Linux.
useLoadStackGuardNode() const3629 bool SparcTargetLowering::useLoadStackGuardNode() const {
3630   if (!Subtarget->isTargetLinux())
3631     return TargetLowering::useLoadStackGuardNode();
3632   return true;
3633 }
3634 
3635 // Override to disable global variable loading on Linux.
insertSSPDeclarations(Module & M) const3636 void SparcTargetLowering::insertSSPDeclarations(Module &M) const {
3637   if (!Subtarget->isTargetLinux())
3638     return TargetLowering::insertSSPDeclarations(M);
3639 }
3640