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