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