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