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