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