Refactor function that checks that __builtin_returnaddress's argument is constant.
[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 "SparcMachineFunctionInfo.h"
17 #include "SparcRegisterInfo.h"
18 #include "SparcTargetMachine.h"
19 #include "MCTargetDesc/SparcBaseInfo.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.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 uint16_t 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,
239                      &RetOps[0], RetOps.size());
240 }
241
242 // Lower return values for the 64-bit ABI.
243 // Return values are passed the exactly the same way as function arguments.
244 SDValue
245 SparcTargetLowering::LowerReturn_64(SDValue Chain,
246                                     CallingConv::ID CallConv, bool IsVarArg,
247                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
248                                     const SmallVectorImpl<SDValue> &OutVals,
249                                     SDLoc DL, SelectionDAG &DAG) const {
250   // CCValAssign - represent the assignment of the return value to locations.
251   SmallVector<CCValAssign, 16> RVLocs;
252
253   // CCState - Info about the registers and stack slot.
254   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
255                  DAG.getTarget(), RVLocs, *DAG.getContext());
256
257   // Analyze return values.
258   CCInfo.AnalyzeReturn(Outs, CC_Sparc64);
259
260   SDValue Flag;
261   SmallVector<SDValue, 4> RetOps(1, Chain);
262
263   // The second operand on the return instruction is the return address offset.
264   // The return address is always %i7+8 with the 64-bit ABI.
265   RetOps.push_back(DAG.getConstant(8, MVT::i32));
266
267   // Copy the result values into the output registers.
268   for (unsigned i = 0; i != RVLocs.size(); ++i) {
269     CCValAssign &VA = RVLocs[i];
270     assert(VA.isRegLoc() && "Can only return in registers!");
271     SDValue OutVal = OutVals[i];
272
273     // Integer return values must be sign or zero extended by the callee.
274     switch (VA.getLocInfo()) {
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     default:
284       break;
285     }
286
287     // The custom bit on an i32 return value indicates that it should be passed
288     // in the high bits of the register.
289     if (VA.getValVT() == MVT::i32 && VA.needsCustom()) {
290       OutVal = DAG.getNode(ISD::SHL, DL, MVT::i64, OutVal,
291                            DAG.getConstant(32, MVT::i32));
292
293       // The next value may go in the low bits of the same register.
294       // Handle both at once.
295       if (i+1 < RVLocs.size() && RVLocs[i+1].getLocReg() == VA.getLocReg()) {
296         SDValue NV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, OutVals[i+1]);
297         OutVal = DAG.getNode(ISD::OR, DL, MVT::i64, OutVal, NV);
298         // Skip the next value, it's already done.
299         ++i;
300       }
301     }
302
303     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVal, Flag);
304
305     // Guarantee that all emitted copies are stuck together with flags.
306     Flag = Chain.getValue(1);
307     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
308   }
309
310   RetOps[0] = Chain;  // Update chain.
311
312   // Add the flag if we have it.
313   if (Flag.getNode())
314     RetOps.push_back(Flag);
315
316   return DAG.getNode(SPISD::RET_FLAG, DL, MVT::Other,
317                      &RetOps[0], RetOps.size());
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 uint16_t ArgRegs[] = {
495       SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
496     };
497     unsigned NumAllocated = CCInfo.getFirstUnallocated(ArgRegs, 6);
498     const uint16_t *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,
530                           &OutChains[0], OutChains.size());
531     }
532   }
533
534   return Chain;
535 }
536
537 // Lower formal arguments for the 64 bit ABI.
538 SDValue SparcTargetLowering::
539 LowerFormalArguments_64(SDValue Chain,
540                         CallingConv::ID CallConv,
541                         bool IsVarArg,
542                         const SmallVectorImpl<ISD::InputArg> &Ins,
543                         SDLoc DL,
544                         SelectionDAG &DAG,
545                         SmallVectorImpl<SDValue> &InVals) const {
546   MachineFunction &MF = DAG.getMachineFunction();
547
548   // Analyze arguments according to CC_Sparc64.
549   SmallVector<CCValAssign, 16> ArgLocs;
550   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
551                  getTargetMachine(), ArgLocs, *DAG.getContext());
552   CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc64);
553
554   // The argument array begins at %fp+BIAS+128, after the register save area.
555   const unsigned ArgArea = 128;
556
557   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
558     CCValAssign &VA = ArgLocs[i];
559     if (VA.isRegLoc()) {
560       // This argument is passed in a register.
561       // All integer register arguments are promoted by the caller to i64.
562
563       // Create a virtual register for the promoted live-in value.
564       unsigned VReg = MF.addLiveIn(VA.getLocReg(),
565                                    getRegClassFor(VA.getLocVT()));
566       SDValue Arg = DAG.getCopyFromReg(Chain, DL, VReg, VA.getLocVT());
567
568       // Get the high bits for i32 struct elements.
569       if (VA.getValVT() == MVT::i32 && VA.needsCustom())
570         Arg = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Arg,
571                           DAG.getConstant(32, MVT::i32));
572
573       // The caller promoted the argument, so insert an Assert?ext SDNode so we
574       // won't promote the value again in this function.
575       switch (VA.getLocInfo()) {
576       case CCValAssign::SExt:
577         Arg = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Arg,
578                           DAG.getValueType(VA.getValVT()));
579         break;
580       case CCValAssign::ZExt:
581         Arg = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Arg,
582                           DAG.getValueType(VA.getValVT()));
583         break;
584       default:
585         break;
586       }
587
588       // Truncate the register down to the argument type.
589       if (VA.isExtInLoc())
590         Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
591
592       InVals.push_back(Arg);
593       continue;
594     }
595
596     // The registers are exhausted. This argument was passed on the stack.
597     assert(VA.isMemLoc());
598     // The CC_Sparc64_Full/Half functions compute stack offsets relative to the
599     // beginning of the arguments area at %fp+BIAS+128.
600     unsigned Offset = VA.getLocMemOffset() + ArgArea;
601     unsigned ValSize = VA.getValVT().getSizeInBits() / 8;
602     // Adjust offset for extended arguments, SPARC is big-endian.
603     // The caller will have written the full slot with extended bytes, but we
604     // prefer our own extending loads.
605     if (VA.isExtInLoc())
606       Offset += 8 - ValSize;
607     int FI = MF.getFrameInfo()->CreateFixedObject(ValSize, Offset, true);
608     InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain,
609                                  DAG.getFrameIndex(FI, getPointerTy()),
610                                  MachinePointerInfo::getFixedStack(FI),
611                                  false, false, false, 0));
612   }
613
614   if (!IsVarArg)
615     return Chain;
616
617   // This function takes variable arguments, some of which may have been passed
618   // in registers %i0-%i5. Variable floating point arguments are never passed
619   // in floating point registers. They go on %i0-%i5 or on the stack like
620   // integer arguments.
621   //
622   // The va_start intrinsic needs to know the offset to the first variable
623   // argument.
624   unsigned ArgOffset = CCInfo.getNextStackOffset();
625   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
626   // Skip the 128 bytes of register save area.
627   FuncInfo->setVarArgsFrameOffset(ArgOffset + ArgArea +
628                                   Subtarget->getStackPointerBias());
629
630   // Save the variable arguments that were passed in registers.
631   // The caller is required to reserve stack space for 6 arguments regardless
632   // of how many arguments were actually passed.
633   SmallVector<SDValue, 8> OutChains;
634   for (; ArgOffset < 6*8; ArgOffset += 8) {
635     unsigned VReg = MF.addLiveIn(SP::I0 + ArgOffset/8, &SP::I64RegsRegClass);
636     SDValue VArg = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
637     int FI = MF.getFrameInfo()->CreateFixedObject(8, ArgOffset + ArgArea, true);
638     OutChains.push_back(DAG.getStore(Chain, DL, VArg,
639                                      DAG.getFrameIndex(FI, getPointerTy()),
640                                      MachinePointerInfo::getFixedStack(FI),
641                                      false, false, 0));
642   }
643
644   if (!OutChains.empty())
645     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
646                         &OutChains[0], OutChains.size());
647
648   return Chain;
649 }
650
651 SDValue
652 SparcTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
653                                SmallVectorImpl<SDValue> &InVals) const {
654   if (Subtarget->is64Bit())
655     return LowerCall_64(CLI, InVals);
656   return LowerCall_32(CLI, InVals);
657 }
658
659 static bool hasReturnsTwiceAttr(SelectionDAG &DAG, SDValue Callee,
660                                      ImmutableCallSite *CS) {
661   if (CS)
662     return CS->hasFnAttr(Attribute::ReturnsTwice);
663
664   const Function *CalleeFn = 0;
665   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
666     CalleeFn = dyn_cast<Function>(G->getGlobal());
667   } else if (ExternalSymbolSDNode *E =
668              dyn_cast<ExternalSymbolSDNode>(Callee)) {
669     const Function *Fn = DAG.getMachineFunction().getFunction();
670     const Module *M = Fn->getParent();
671     const char *CalleeName = E->getSymbol();
672     CalleeFn = M->getFunction(CalleeName);
673   }
674
675   if (!CalleeFn)
676     return false;
677   return CalleeFn->hasFnAttribute(Attribute::ReturnsTwice);
678 }
679
680 // Lower a call for the 32-bit ABI.
681 SDValue
682 SparcTargetLowering::LowerCall_32(TargetLowering::CallLoweringInfo &CLI,
683                                   SmallVectorImpl<SDValue> &InVals) const {
684   SelectionDAG &DAG                     = CLI.DAG;
685   SDLoc &dl                             = CLI.DL;
686   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
687   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
688   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
689   SDValue Chain                         = CLI.Chain;
690   SDValue Callee                        = CLI.Callee;
691   bool &isTailCall                      = CLI.IsTailCall;
692   CallingConv::ID CallConv              = CLI.CallConv;
693   bool isVarArg                         = CLI.IsVarArg;
694
695   // Sparc target does not yet support tail call optimization.
696   isTailCall = false;
697
698   // Analyze operands of the call, assigning locations to each operand.
699   SmallVector<CCValAssign, 16> ArgLocs;
700   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
701                  DAG.getTarget(), ArgLocs, *DAG.getContext());
702   CCInfo.AnalyzeCallOperands(Outs, CC_Sparc32);
703
704   // Get the size of the outgoing arguments stack space requirement.
705   unsigned ArgsSize = CCInfo.getNextStackOffset();
706
707   // Keep stack frames 8-byte aligned.
708   ArgsSize = (ArgsSize+7) & ~7;
709
710   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
711
712   // Create local copies for byval args.
713   SmallVector<SDValue, 8> ByValArgs;
714   for (unsigned i = 0,  e = Outs.size(); i != e; ++i) {
715     ISD::ArgFlagsTy Flags = Outs[i].Flags;
716     if (!Flags.isByVal())
717       continue;
718
719     SDValue Arg = OutVals[i];
720     unsigned Size = Flags.getByValSize();
721     unsigned Align = Flags.getByValAlign();
722
723     int FI = MFI->CreateStackObject(Size, Align, false);
724     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
725     SDValue SizeNode = DAG.getConstant(Size, MVT::i32);
726
727     Chain = DAG.getMemcpy(Chain, dl, FIPtr, Arg, SizeNode, Align,
728                           false,        // isVolatile,
729                           (Size <= 32), // AlwaysInline if size <= 32
730                           MachinePointerInfo(), MachinePointerInfo());
731     ByValArgs.push_back(FIPtr);
732   }
733
734   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(ArgsSize, true),
735                                dl);
736
737   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
738   SmallVector<SDValue, 8> MemOpChains;
739
740   const unsigned StackOffset = 92;
741   bool hasStructRetAttr = false;
742   // Walk the register/memloc assignments, inserting copies/loads.
743   for (unsigned i = 0, realArgIdx = 0, byvalArgIdx = 0, e = ArgLocs.size();
744        i != e;
745        ++i, ++realArgIdx) {
746     CCValAssign &VA = ArgLocs[i];
747     SDValue Arg = OutVals[realArgIdx];
748
749     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
750
751     // Use local copy if it is a byval arg.
752     if (Flags.isByVal())
753       Arg = ByValArgs[byvalArgIdx++];
754
755     // Promote the value if needed.
756     switch (VA.getLocInfo()) {
757     default: llvm_unreachable("Unknown loc info!");
758     case CCValAssign::Full: break;
759     case CCValAssign::SExt:
760       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
761       break;
762     case CCValAssign::ZExt:
763       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
764       break;
765     case CCValAssign::AExt:
766       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
767       break;
768     case CCValAssign::BCvt:
769       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
770       break;
771     }
772
773     if (Flags.isSRet()) {
774       assert(VA.needsCustom());
775       // store SRet argument in %sp+64
776       SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
777       SDValue PtrOff = DAG.getIntPtrConstant(64);
778       PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
779       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
780                                          MachinePointerInfo(),
781                                          false, false, 0));
782       hasStructRetAttr = true;
783       continue;
784     }
785
786     if (VA.needsCustom()) {
787       assert(VA.getLocVT() == MVT::f64);
788
789       if (VA.isMemLoc()) {
790         unsigned Offset = VA.getLocMemOffset() + StackOffset;
791         // if it is double-word aligned, just store.
792         if (Offset % 8 == 0) {
793           SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
794           SDValue PtrOff = DAG.getIntPtrConstant(Offset);
795           PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
796           MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
797                                              MachinePointerInfo(),
798                                              false, false, 0));
799           continue;
800         }
801       }
802
803       SDValue StackPtr = DAG.CreateStackTemporary(MVT::f64, MVT::i32);
804       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
805                                    Arg, StackPtr, MachinePointerInfo(),
806                                    false, false, 0);
807       // Sparc is big-endian, so the high part comes first.
808       SDValue Hi = DAG.getLoad(MVT::i32, dl, Store, StackPtr,
809                                MachinePointerInfo(), false, false, false, 0);
810       // Increment the pointer to the other half.
811       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
812                              DAG.getIntPtrConstant(4));
813       // Load the low part.
814       SDValue Lo = DAG.getLoad(MVT::i32, dl, Store, StackPtr,
815                                MachinePointerInfo(), false, false, false, 0);
816
817       if (VA.isRegLoc()) {
818         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Hi));
819         assert(i+1 != e);
820         CCValAssign &NextVA = ArgLocs[++i];
821         if (NextVA.isRegLoc()) {
822           RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Lo));
823         } else {
824           // Store the low part in stack.
825           unsigned Offset = NextVA.getLocMemOffset() + StackOffset;
826           SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
827           SDValue PtrOff = DAG.getIntPtrConstant(Offset);
828           PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
829           MemOpChains.push_back(DAG.getStore(Chain, dl, Lo, PtrOff,
830                                              MachinePointerInfo(),
831                                              false, false, 0));
832         }
833       } else {
834         unsigned Offset = VA.getLocMemOffset() + StackOffset;
835         // Store the high part.
836         SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
837         SDValue PtrOff = DAG.getIntPtrConstant(Offset);
838         PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
839         MemOpChains.push_back(DAG.getStore(Chain, dl, Hi, PtrOff,
840                                            MachinePointerInfo(),
841                                            false, false, 0));
842         // Store the low part.
843         PtrOff = DAG.getIntPtrConstant(Offset+4);
844         PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
845         MemOpChains.push_back(DAG.getStore(Chain, dl, Lo, PtrOff,
846                                            MachinePointerInfo(),
847                                            false, false, 0));
848       }
849       continue;
850     }
851
852     // Arguments that can be passed on register must be kept at
853     // RegsToPass vector
854     if (VA.isRegLoc()) {
855       if (VA.getLocVT() != MVT::f32) {
856         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
857         continue;
858       }
859       Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
860       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
861       continue;
862     }
863
864     assert(VA.isMemLoc());
865
866     // Create a store off the stack pointer for this argument.
867     SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
868     SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset()+StackOffset);
869     PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
870     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
871                                        MachinePointerInfo(),
872                                        false, false, 0));
873   }
874
875
876   // Emit all stores, make sure the occur before any copies into physregs.
877   if (!MemOpChains.empty())
878     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
879                         &MemOpChains[0], MemOpChains.size());
880
881   // Build a sequence of copy-to-reg nodes chained together with token
882   // chain and flag operands which copy the outgoing args into registers.
883   // The InFlag in necessary since all emitted instructions must be
884   // stuck together.
885   SDValue InFlag;
886   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
887     unsigned Reg = toCallerWindow(RegsToPass[i].first);
888     Chain = DAG.getCopyToReg(Chain, dl, Reg, RegsToPass[i].second, InFlag);
889     InFlag = Chain.getValue(1);
890   }
891
892   unsigned SRetArgSize = (hasStructRetAttr)? getSRetArgSize(DAG, Callee):0;
893   bool hasReturnsTwice = hasReturnsTwiceAttr(DAG, Callee, CLI.CS);
894
895   // If the callee is a GlobalAddress node (quite common, every direct call is)
896   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
897   // Likewise ExternalSymbol -> TargetExternalSymbol.
898   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
899     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
900   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
901     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
902
903   // Returns a chain & a flag for retval copy to use
904   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
905   SmallVector<SDValue, 8> Ops;
906   Ops.push_back(Chain);
907   Ops.push_back(Callee);
908   if (hasStructRetAttr)
909     Ops.push_back(DAG.getTargetConstant(SRetArgSize, MVT::i32));
910   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
911     Ops.push_back(DAG.getRegister(toCallerWindow(RegsToPass[i].first),
912                                   RegsToPass[i].second.getValueType()));
913
914   // Add a register mask operand representing the call-preserved registers.
915   const SparcRegisterInfo *TRI =
916     ((const SparcTargetMachine&)getTargetMachine()).getRegisterInfo();
917   const uint32_t *Mask = ((hasReturnsTwice)
918                           ? TRI->getRTCallPreservedMask(CallConv)
919                           : TRI->getCallPreservedMask(CallConv));
920   assert(Mask && "Missing call preserved mask for calling convention");
921   Ops.push_back(DAG.getRegisterMask(Mask));
922
923   if (InFlag.getNode())
924     Ops.push_back(InFlag);
925
926   Chain = DAG.getNode(SPISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
927   InFlag = Chain.getValue(1);
928
929   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, true),
930                              DAG.getIntPtrConstant(0, true), InFlag, dl);
931   InFlag = Chain.getValue(1);
932
933   // Assign locations to each value returned by this call.
934   SmallVector<CCValAssign, 16> RVLocs;
935   CCState RVInfo(CallConv, isVarArg, DAG.getMachineFunction(),
936                  DAG.getTarget(), RVLocs, *DAG.getContext());
937
938   RVInfo.AnalyzeCallResult(Ins, RetCC_Sparc32);
939
940   // Copy all of the result registers out of their specified physreg.
941   for (unsigned i = 0; i != RVLocs.size(); ++i) {
942     Chain = DAG.getCopyFromReg(Chain, dl, toCallerWindow(RVLocs[i].getLocReg()),
943                                RVLocs[i].getValVT(), InFlag).getValue(1);
944     InFlag = Chain.getValue(2);
945     InVals.push_back(Chain.getValue(0));
946   }
947
948   return Chain;
949 }
950
951 // This functions returns true if CalleeName is a ABI function that returns
952 // a long double (fp128).
953 static bool isFP128ABICall(const char *CalleeName)
954 {
955   static const char *const ABICalls[] =
956     {  "_Q_add", "_Q_sub", "_Q_mul", "_Q_div",
957        "_Q_sqrt", "_Q_neg",
958        "_Q_itoq", "_Q_stoq", "_Q_dtoq", "_Q_utoq",
959        "_Q_lltoq", "_Q_ulltoq",
960        0
961     };
962   for (const char * const *I = ABICalls; *I != 0; ++I)
963     if (strcmp(CalleeName, *I) == 0)
964       return true;
965   return false;
966 }
967
968 unsigned
969 SparcTargetLowering::getSRetArgSize(SelectionDAG &DAG, SDValue Callee) const
970 {
971   const Function *CalleeFn = 0;
972   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
973     CalleeFn = dyn_cast<Function>(G->getGlobal());
974   } else if (ExternalSymbolSDNode *E =
975              dyn_cast<ExternalSymbolSDNode>(Callee)) {
976     const Function *Fn = DAG.getMachineFunction().getFunction();
977     const Module *M = Fn->getParent();
978     const char *CalleeName = E->getSymbol();
979     CalleeFn = M->getFunction(CalleeName);
980     if (!CalleeFn && isFP128ABICall(CalleeName))
981       return 16; // Return sizeof(fp128)
982   }
983
984   if (!CalleeFn)
985     return 0;
986
987   assert(CalleeFn->hasStructRetAttr() &&
988          "Callee does not have the StructRet attribute.");
989
990   PointerType *Ty = cast<PointerType>(CalleeFn->arg_begin()->getType());
991   Type *ElementTy = Ty->getElementType();
992   return getDataLayout()->getTypeAllocSize(ElementTy);
993 }
994
995
996 // Fixup floating point arguments in the ... part of a varargs call.
997 //
998 // The SPARC v9 ABI requires that floating point arguments are treated the same
999 // as integers when calling a varargs function. This does not apply to the
1000 // fixed arguments that are part of the function's prototype.
1001 //
1002 // This function post-processes a CCValAssign array created by
1003 // AnalyzeCallOperands().
1004 static void fixupVariableFloatArgs(SmallVectorImpl<CCValAssign> &ArgLocs,
1005                                    ArrayRef<ISD::OutputArg> Outs) {
1006   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1007     const CCValAssign &VA = ArgLocs[i];
1008     MVT ValTy = VA.getLocVT();
1009     // FIXME: What about f32 arguments? C promotes them to f64 when calling
1010     // varargs functions.
1011     if (!VA.isRegLoc() || (ValTy != MVT::f64 && ValTy != MVT::f128))
1012       continue;
1013     // The fixed arguments to a varargs function still go in FP registers.
1014     if (Outs[VA.getValNo()].IsFixed)
1015       continue;
1016
1017     // This floating point argument should be reassigned.
1018     CCValAssign NewVA;
1019
1020     // Determine the offset into the argument array.
1021     unsigned firstReg = (ValTy == MVT::f64) ? SP::D0 : SP::Q0;
1022     unsigned argSize  = (ValTy == MVT::f64) ? 8 : 16;
1023     unsigned Offset = argSize * (VA.getLocReg() - firstReg);
1024     assert(Offset < 16*8 && "Offset out of range, bad register enum?");
1025
1026     if (Offset < 6*8) {
1027       // This argument should go in %i0-%i5.
1028       unsigned IReg = SP::I0 + Offset/8;
1029       if (ValTy == MVT::f64)
1030         // Full register, just bitconvert into i64.
1031         NewVA = CCValAssign::getReg(VA.getValNo(), VA.getValVT(),
1032                                     IReg, MVT::i64, CCValAssign::BCvt);
1033       else {
1034         assert(ValTy == MVT::f128 && "Unexpected type!");
1035         // Full register, just bitconvert into i128 -- We will lower this into
1036         // two i64s in LowerCall_64.
1037         NewVA = CCValAssign::getCustomReg(VA.getValNo(), VA.getValVT(),
1038                                           IReg, MVT::i128, CCValAssign::BCvt);
1039       }
1040     } else {
1041       // This needs to go to memory, we're out of integer registers.
1042       NewVA = CCValAssign::getMem(VA.getValNo(), VA.getValVT(),
1043                                   Offset, VA.getLocVT(), VA.getLocInfo());
1044     }
1045     ArgLocs[i] = NewVA;
1046   }
1047 }
1048
1049 // Lower a call for the 64-bit ABI.
1050 SDValue
1051 SparcTargetLowering::LowerCall_64(TargetLowering::CallLoweringInfo &CLI,
1052                                   SmallVectorImpl<SDValue> &InVals) const {
1053   SelectionDAG &DAG = CLI.DAG;
1054   SDLoc DL = CLI.DL;
1055   SDValue Chain = CLI.Chain;
1056
1057   // Sparc target does not yet support tail call optimization.
1058   CLI.IsTailCall = false;
1059
1060   // Analyze operands of the call, assigning locations to each operand.
1061   SmallVector<CCValAssign, 16> ArgLocs;
1062   CCState CCInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(),
1063                  DAG.getTarget(), ArgLocs, *DAG.getContext());
1064   CCInfo.AnalyzeCallOperands(CLI.Outs, CC_Sparc64);
1065
1066   // Get the size of the outgoing arguments stack space requirement.
1067   // The stack offset computed by CC_Sparc64 includes all arguments.
1068   // Called functions expect 6 argument words to exist in the stack frame, used
1069   // or not.
1070   unsigned ArgsSize = std::max(6*8u, CCInfo.getNextStackOffset());
1071
1072   // Keep stack frames 16-byte aligned.
1073   ArgsSize = RoundUpToAlignment(ArgsSize, 16);
1074
1075   // Varargs calls require special treatment.
1076   if (CLI.IsVarArg)
1077     fixupVariableFloatArgs(ArgLocs, CLI.Outs);
1078
1079   // Adjust the stack pointer to make room for the arguments.
1080   // FIXME: Use hasReservedCallFrame to avoid %sp adjustments around all calls
1081   // with more than 6 arguments.
1082   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(ArgsSize, true),
1083                                DL);
1084
1085   // Collect the set of registers to pass to the function and their values.
1086   // This will be emitted as a sequence of CopyToReg nodes glued to the call
1087   // instruction.
1088   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1089
1090   // Collect chains from all the memory opeations that copy arguments to the
1091   // stack. They must follow the stack pointer adjustment above and precede the
1092   // call instruction itself.
1093   SmallVector<SDValue, 8> MemOpChains;
1094
1095   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1096     const CCValAssign &VA = ArgLocs[i];
1097     SDValue Arg = CLI.OutVals[i];
1098
1099     // Promote the value if needed.
1100     switch (VA.getLocInfo()) {
1101     default:
1102       llvm_unreachable("Unknown location info!");
1103     case CCValAssign::Full:
1104       break;
1105     case CCValAssign::SExt:
1106       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
1107       break;
1108     case CCValAssign::ZExt:
1109       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
1110       break;
1111     case CCValAssign::AExt:
1112       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
1113       break;
1114     case CCValAssign::BCvt:
1115       // fixupVariableFloatArgs() may create bitcasts from f128 to i128. But
1116       // SPARC does not support i128 natively. Lower it into two i64, see below.
1117       if (!VA.needsCustom() || VA.getValVT() != MVT::f128
1118           || VA.getLocVT() != MVT::i128)
1119         Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1120       break;
1121     }
1122
1123     if (VA.isRegLoc()) {
1124       if (VA.needsCustom() && VA.getValVT() == MVT::f128
1125           && VA.getLocVT() == MVT::i128) {
1126         // Store and reload into the interger register reg and reg+1.
1127         unsigned Offset = 8 * (VA.getLocReg() - SP::I0);
1128         unsigned StackOffset = Offset + Subtarget->getStackPointerBias() + 128;
1129         SDValue StackPtr = DAG.getRegister(SP::O6, getPointerTy());
1130         SDValue HiPtrOff = DAG.getIntPtrConstant(StackOffset);
1131         HiPtrOff         = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
1132                                        HiPtrOff);
1133         SDValue LoPtrOff = DAG.getIntPtrConstant(StackOffset + 8);
1134         LoPtrOff         = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
1135                                        LoPtrOff);
1136
1137         // Store to %sp+BIAS+128+Offset
1138         SDValue Store = DAG.getStore(Chain, DL, Arg, HiPtrOff,
1139                                      MachinePointerInfo(),
1140                                      false, false, 0);
1141         // Load into Reg and Reg+1
1142         SDValue Hi64 = DAG.getLoad(MVT::i64, DL, Store, HiPtrOff,
1143                                    MachinePointerInfo(),
1144                                    false, false, false, 0);
1145         SDValue Lo64 = DAG.getLoad(MVT::i64, DL, Store, LoPtrOff,
1146                                    MachinePointerInfo(),
1147                                    false, false, false, 0);
1148         RegsToPass.push_back(std::make_pair(toCallerWindow(VA.getLocReg()),
1149                                             Hi64));
1150         RegsToPass.push_back(std::make_pair(toCallerWindow(VA.getLocReg()+1),
1151                                             Lo64));
1152         continue;
1153       }
1154
1155       // The custom bit on an i32 return value indicates that it should be
1156       // passed in the high bits of the register.
1157       if (VA.getValVT() == MVT::i32 && VA.needsCustom()) {
1158         Arg = DAG.getNode(ISD::SHL, DL, MVT::i64, Arg,
1159                           DAG.getConstant(32, MVT::i32));
1160
1161         // The next value may go in the low bits of the same register.
1162         // Handle both at once.
1163         if (i+1 < ArgLocs.size() && ArgLocs[i+1].isRegLoc() &&
1164             ArgLocs[i+1].getLocReg() == VA.getLocReg()) {
1165           SDValue NV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64,
1166                                    CLI.OutVals[i+1]);
1167           Arg = DAG.getNode(ISD::OR, DL, MVT::i64, Arg, NV);
1168           // Skip the next value, it's already done.
1169           ++i;
1170         }
1171       }
1172       RegsToPass.push_back(std::make_pair(toCallerWindow(VA.getLocReg()), Arg));
1173       continue;
1174     }
1175
1176     assert(VA.isMemLoc());
1177
1178     // Create a store off the stack pointer for this argument.
1179     SDValue StackPtr = DAG.getRegister(SP::O6, getPointerTy());
1180     // The argument area starts at %fp+BIAS+128 in the callee frame,
1181     // %sp+BIAS+128 in ours.
1182     SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset() +
1183                                            Subtarget->getStackPointerBias() +
1184                                            128);
1185     PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
1186     MemOpChains.push_back(DAG.getStore(Chain, DL, Arg, PtrOff,
1187                                        MachinePointerInfo(),
1188                                        false, false, 0));
1189   }
1190
1191   // Emit all stores, make sure they occur before the call.
1192   if (!MemOpChains.empty())
1193     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
1194                         &MemOpChains[0], MemOpChains.size());
1195
1196   // Build a sequence of CopyToReg nodes glued together with token chain and
1197   // glue operands which copy the outgoing args into registers. The InGlue is
1198   // necessary since all emitted instructions must be stuck together in order
1199   // to pass the live physical registers.
1200   SDValue InGlue;
1201   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1202     Chain = DAG.getCopyToReg(Chain, DL,
1203                              RegsToPass[i].first, RegsToPass[i].second, InGlue);
1204     InGlue = Chain.getValue(1);
1205   }
1206
1207   // If the callee is a GlobalAddress node (quite common, every direct call is)
1208   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1209   // Likewise ExternalSymbol -> TargetExternalSymbol.
1210   SDValue Callee = CLI.Callee;
1211   bool hasReturnsTwice = hasReturnsTwiceAttr(DAG, Callee, CLI.CS);
1212   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1213     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy());
1214   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1215     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), getPointerTy());
1216
1217   // Build the operands for the call instruction itself.
1218   SmallVector<SDValue, 8> Ops;
1219   Ops.push_back(Chain);
1220   Ops.push_back(Callee);
1221   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1222     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1223                                   RegsToPass[i].second.getValueType()));
1224
1225   // Add a register mask operand representing the call-preserved registers.
1226   const SparcRegisterInfo *TRI =
1227     ((const SparcTargetMachine&)getTargetMachine()).getRegisterInfo();
1228   const uint32_t *Mask = ((hasReturnsTwice)
1229                           ? TRI->getRTCallPreservedMask(CLI.CallConv)
1230                           : TRI->getCallPreservedMask(CLI.CallConv));
1231   assert(Mask && "Missing call preserved mask for calling convention");
1232   Ops.push_back(DAG.getRegisterMask(Mask));
1233
1234   // Make sure the CopyToReg nodes are glued to the call instruction which
1235   // consumes the registers.
1236   if (InGlue.getNode())
1237     Ops.push_back(InGlue);
1238
1239   // Now the call itself.
1240   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1241   Chain = DAG.getNode(SPISD::CALL, DL, NodeTys, &Ops[0], Ops.size());
1242   InGlue = Chain.getValue(1);
1243
1244   // Revert the stack pointer immediately after the call.
1245   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, true),
1246                              DAG.getIntPtrConstant(0, true), InGlue, DL);
1247   InGlue = Chain.getValue(1);
1248
1249   // Now extract the return values. This is more or less the same as
1250   // LowerFormalArguments_64.
1251
1252   // Assign locations to each value returned by this call.
1253   SmallVector<CCValAssign, 16> RVLocs;
1254   CCState RVInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(),
1255                  DAG.getTarget(), RVLocs, *DAG.getContext());
1256
1257   // Set inreg flag manually for codegen generated library calls that
1258   // return float.
1259   if (CLI.Ins.size() == 1 && CLI.Ins[0].VT == MVT::f32 && CLI.CS == 0)
1260     CLI.Ins[0].Flags.setInReg();
1261
1262   RVInfo.AnalyzeCallResult(CLI.Ins, CC_Sparc64);
1263
1264   // Copy all of the result registers out of their specified physreg.
1265   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1266     CCValAssign &VA = RVLocs[i];
1267     unsigned Reg = toCallerWindow(VA.getLocReg());
1268
1269     // When returning 'inreg {i32, i32 }', two consecutive i32 arguments can
1270     // reside in the same register in the high and low bits. Reuse the
1271     // CopyFromReg previous node to avoid duplicate copies.
1272     SDValue RV;
1273     if (RegisterSDNode *SrcReg = dyn_cast<RegisterSDNode>(Chain.getOperand(1)))
1274       if (SrcReg->getReg() == Reg && Chain->getOpcode() == ISD::CopyFromReg)
1275         RV = Chain.getValue(0);
1276
1277     // But usually we'll create a new CopyFromReg for a different register.
1278     if (!RV.getNode()) {
1279       RV = DAG.getCopyFromReg(Chain, DL, Reg, RVLocs[i].getLocVT(), InGlue);
1280       Chain = RV.getValue(1);
1281       InGlue = Chain.getValue(2);
1282     }
1283
1284     // Get the high bits for i32 struct elements.
1285     if (VA.getValVT() == MVT::i32 && VA.needsCustom())
1286       RV = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), RV,
1287                        DAG.getConstant(32, MVT::i32));
1288
1289     // The callee promoted the return value, so insert an Assert?ext SDNode so
1290     // we won't promote the value again in this function.
1291     switch (VA.getLocInfo()) {
1292     case CCValAssign::SExt:
1293       RV = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), RV,
1294                        DAG.getValueType(VA.getValVT()));
1295       break;
1296     case CCValAssign::ZExt:
1297       RV = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), RV,
1298                        DAG.getValueType(VA.getValVT()));
1299       break;
1300     default:
1301       break;
1302     }
1303
1304     // Truncate the register down to the return value type.
1305     if (VA.isExtInLoc())
1306       RV = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), RV);
1307
1308     InVals.push_back(RV);
1309   }
1310
1311   return Chain;
1312 }
1313
1314 //===----------------------------------------------------------------------===//
1315 // TargetLowering Implementation
1316 //===----------------------------------------------------------------------===//
1317
1318 /// IntCondCCodeToICC - Convert a DAG integer condition code to a SPARC ICC
1319 /// condition.
1320 static SPCC::CondCodes IntCondCCodeToICC(ISD::CondCode CC) {
1321   switch (CC) {
1322   default: llvm_unreachable("Unknown integer condition code!");
1323   case ISD::SETEQ:  return SPCC::ICC_E;
1324   case ISD::SETNE:  return SPCC::ICC_NE;
1325   case ISD::SETLT:  return SPCC::ICC_L;
1326   case ISD::SETGT:  return SPCC::ICC_G;
1327   case ISD::SETLE:  return SPCC::ICC_LE;
1328   case ISD::SETGE:  return SPCC::ICC_GE;
1329   case ISD::SETULT: return SPCC::ICC_CS;
1330   case ISD::SETULE: return SPCC::ICC_LEU;
1331   case ISD::SETUGT: return SPCC::ICC_GU;
1332   case ISD::SETUGE: return SPCC::ICC_CC;
1333   }
1334 }
1335
1336 /// FPCondCCodeToFCC - Convert a DAG floatingp oint condition code to a SPARC
1337 /// FCC condition.
1338 static SPCC::CondCodes FPCondCCodeToFCC(ISD::CondCode CC) {
1339   switch (CC) {
1340   default: llvm_unreachable("Unknown fp condition code!");
1341   case ISD::SETEQ:
1342   case ISD::SETOEQ: return SPCC::FCC_E;
1343   case ISD::SETNE:
1344   case ISD::SETUNE: return SPCC::FCC_NE;
1345   case ISD::SETLT:
1346   case ISD::SETOLT: return SPCC::FCC_L;
1347   case ISD::SETGT:
1348   case ISD::SETOGT: return SPCC::FCC_G;
1349   case ISD::SETLE:
1350   case ISD::SETOLE: return SPCC::FCC_LE;
1351   case ISD::SETGE:
1352   case ISD::SETOGE: return SPCC::FCC_GE;
1353   case ISD::SETULT: return SPCC::FCC_UL;
1354   case ISD::SETULE: return SPCC::FCC_ULE;
1355   case ISD::SETUGT: return SPCC::FCC_UG;
1356   case ISD::SETUGE: return SPCC::FCC_UGE;
1357   case ISD::SETUO:  return SPCC::FCC_U;
1358   case ISD::SETO:   return SPCC::FCC_O;
1359   case ISD::SETONE: return SPCC::FCC_LG;
1360   case ISD::SETUEQ: return SPCC::FCC_UE;
1361   }
1362 }
1363
1364 SparcTargetLowering::SparcTargetLowering(TargetMachine &TM)
1365   : TargetLowering(TM, new TargetLoweringObjectFileELF()) {
1366   Subtarget = &TM.getSubtarget<SparcSubtarget>();
1367
1368   // Set up the register classes.
1369   addRegisterClass(MVT::i32, &SP::IntRegsRegClass);
1370   addRegisterClass(MVT::f32, &SP::FPRegsRegClass);
1371   addRegisterClass(MVT::f64, &SP::DFPRegsRegClass);
1372   addRegisterClass(MVT::f128, &SP::QFPRegsRegClass);
1373   if (Subtarget->is64Bit())
1374     addRegisterClass(MVT::i64, &SP::I64RegsRegClass);
1375
1376   // Turn FP extload into load/fextend
1377   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
1378   setLoadExtAction(ISD::EXTLOAD, MVT::f64, Expand);
1379
1380   // Sparc doesn't have i1 sign extending load
1381   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
1382
1383   // Turn FP truncstore into trunc + store.
1384   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1385   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1386   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1387
1388   // Custom legalize GlobalAddress nodes into LO/HI parts.
1389   setOperationAction(ISD::GlobalAddress, getPointerTy(), Custom);
1390   setOperationAction(ISD::GlobalTLSAddress, getPointerTy(), Custom);
1391   setOperationAction(ISD::ConstantPool, getPointerTy(), Custom);
1392   setOperationAction(ISD::BlockAddress, getPointerTy(), Custom);
1393
1394   // Sparc doesn't have sext_inreg, replace them with shl/sra
1395   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1396   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
1397   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
1398
1399   // Sparc has no REM or DIVREM operations.
1400   setOperationAction(ISD::UREM, MVT::i32, Expand);
1401   setOperationAction(ISD::SREM, MVT::i32, Expand);
1402   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1403   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1404
1405   // ... nor does SparcV9.
1406   if (Subtarget->is64Bit()) {
1407     setOperationAction(ISD::UREM, MVT::i64, Expand);
1408     setOperationAction(ISD::SREM, MVT::i64, Expand);
1409     setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
1410     setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
1411   }
1412
1413   // Custom expand fp<->sint
1414   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
1415   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
1416   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
1417   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
1418
1419   // Custom Expand fp<->uint
1420   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
1421   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
1422   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
1423   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
1424
1425   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
1426   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
1427
1428   // Sparc has no select or setcc: expand to SELECT_CC.
1429   setOperationAction(ISD::SELECT, MVT::i32, Expand);
1430   setOperationAction(ISD::SELECT, MVT::f32, Expand);
1431   setOperationAction(ISD::SELECT, MVT::f64, Expand);
1432   setOperationAction(ISD::SELECT, MVT::f128, Expand);
1433
1434   setOperationAction(ISD::SETCC, MVT::i32, Expand);
1435   setOperationAction(ISD::SETCC, MVT::f32, Expand);
1436   setOperationAction(ISD::SETCC, MVT::f64, Expand);
1437   setOperationAction(ISD::SETCC, MVT::f128, Expand);
1438
1439   // Sparc doesn't have BRCOND either, it has BR_CC.
1440   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
1441   setOperationAction(ISD::BRIND, MVT::Other, Expand);
1442   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
1443   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1444   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1445   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1446   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
1447
1448   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1449   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1450   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1451   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1452
1453   if (Subtarget->is64Bit()) {
1454     setOperationAction(ISD::ADDC, MVT::i64, Custom);
1455     setOperationAction(ISD::ADDE, MVT::i64, Custom);
1456     setOperationAction(ISD::SUBC, MVT::i64, Custom);
1457     setOperationAction(ISD::SUBE, MVT::i64, Custom);
1458     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
1459     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
1460     setOperationAction(ISD::SELECT, MVT::i64, Expand);
1461     setOperationAction(ISD::SETCC, MVT::i64, Expand);
1462     setOperationAction(ISD::BR_CC, MVT::i64, Custom);
1463     setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
1464
1465     setOperationAction(ISD::CTPOP, MVT::i64, Legal);
1466     setOperationAction(ISD::CTTZ , MVT::i64, Expand);
1467     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
1468     setOperationAction(ISD::CTLZ , MVT::i64, Expand);
1469     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
1470     setOperationAction(ISD::BSWAP, MVT::i64, Expand);
1471     setOperationAction(ISD::ROTL , MVT::i64, Expand);
1472     setOperationAction(ISD::ROTR , MVT::i64, Expand);
1473     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
1474   }
1475
1476   // ATOMICs.
1477   // FIXME: We insert fences for each atomics and generate sub-optimal code
1478   // for PSO/TSO. Also, implement other atomicrmw operations.
1479
1480   setInsertFencesForAtomic(true);
1481
1482   setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Legal);
1483   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32,
1484                      (Subtarget->isV9() ? Legal: Expand));
1485
1486
1487   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Legal);
1488
1489   // Custom Lower Atomic LOAD/STORE
1490   setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1491   setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1492
1493   if (Subtarget->is64Bit()) {
1494     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Legal);
1495     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Expand);
1496     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
1497     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Custom);
1498   }
1499
1500   if (!Subtarget->isV9()) {
1501     // SparcV8 does not have FNEGD and FABSD.
1502     setOperationAction(ISD::FNEG, MVT::f64, Custom);
1503     setOperationAction(ISD::FABS, MVT::f64, Custom);
1504   }
1505
1506   setOperationAction(ISD::FSIN , MVT::f128, Expand);
1507   setOperationAction(ISD::FCOS , MVT::f128, Expand);
1508   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
1509   setOperationAction(ISD::FREM , MVT::f128, Expand);
1510   setOperationAction(ISD::FMA  , MVT::f128, Expand);
1511   setOperationAction(ISD::FSIN , MVT::f64, Expand);
1512   setOperationAction(ISD::FCOS , MVT::f64, Expand);
1513   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1514   setOperationAction(ISD::FREM , MVT::f64, Expand);
1515   setOperationAction(ISD::FMA  , MVT::f64, Expand);
1516   setOperationAction(ISD::FSIN , MVT::f32, Expand);
1517   setOperationAction(ISD::FCOS , MVT::f32, Expand);
1518   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1519   setOperationAction(ISD::FREM , MVT::f32, Expand);
1520   setOperationAction(ISD::FMA  , MVT::f32, Expand);
1521   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1522   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
1523   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
1524   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
1525   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
1526   setOperationAction(ISD::ROTL , MVT::i32, Expand);
1527   setOperationAction(ISD::ROTR , MVT::i32, Expand);
1528   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1529   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1530   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
1531   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
1532   setOperationAction(ISD::FPOW , MVT::f128, Expand);
1533   setOperationAction(ISD::FPOW , MVT::f64, Expand);
1534   setOperationAction(ISD::FPOW , MVT::f32, Expand);
1535
1536   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1537   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1538   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1539
1540   // FIXME: Sparc provides these multiplies, but we don't have them yet.
1541   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1542   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1543
1544   if (Subtarget->is64Bit()) {
1545     setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
1546     setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
1547     setOperationAction(ISD::MULHU,     MVT::i64, Expand);
1548     setOperationAction(ISD::MULHS,     MVT::i64, Expand);
1549
1550     setOperationAction(ISD::UMULO,     MVT::i64, Custom);
1551     setOperationAction(ISD::SMULO,     MVT::i64, Custom);
1552   }
1553
1554   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
1555   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
1556   // VAARG needs to be lowered to not do unaligned accesses for doubles.
1557   setOperationAction(ISD::VAARG             , MVT::Other, Custom);
1558
1559   // Use the default implementation.
1560   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
1561   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
1562   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
1563   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
1564   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
1565
1566   setExceptionPointerRegister(SP::I0);
1567   setExceptionSelectorRegister(SP::I1);
1568
1569   setStackPointerRegisterToSaveRestore(SP::O6);
1570
1571   if (Subtarget->isV9())
1572     setOperationAction(ISD::CTPOP, MVT::i32, Legal);
1573
1574   if (Subtarget->isV9() && Subtarget->hasHardQuad()) {
1575     setOperationAction(ISD::LOAD, MVT::f128, Legal);
1576     setOperationAction(ISD::STORE, MVT::f128, Legal);
1577   } else {
1578     setOperationAction(ISD::LOAD, MVT::f128, Custom);
1579     setOperationAction(ISD::STORE, MVT::f128, Custom);
1580   }
1581
1582   if (Subtarget->hasHardQuad()) {
1583     setOperationAction(ISD::FADD,  MVT::f128, Legal);
1584     setOperationAction(ISD::FSUB,  MVT::f128, Legal);
1585     setOperationAction(ISD::FMUL,  MVT::f128, Legal);
1586     setOperationAction(ISD::FDIV,  MVT::f128, Legal);
1587     setOperationAction(ISD::FSQRT, MVT::f128, Legal);
1588     setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1589     setOperationAction(ISD::FP_ROUND,  MVT::f64, Legal);
1590     if (Subtarget->isV9()) {
1591       setOperationAction(ISD::FNEG, MVT::f128, Legal);
1592       setOperationAction(ISD::FABS, MVT::f128, Legal);
1593     } else {
1594       setOperationAction(ISD::FNEG, MVT::f128, Custom);
1595       setOperationAction(ISD::FABS, MVT::f128, Custom);
1596     }
1597
1598     if (!Subtarget->is64Bit()) {
1599       setLibcallName(RTLIB::FPTOSINT_F128_I64, "_Q_qtoll");
1600       setLibcallName(RTLIB::FPTOUINT_F128_I64, "_Q_qtoull");
1601       setLibcallName(RTLIB::SINTTOFP_I64_F128, "_Q_lltoq");
1602       setLibcallName(RTLIB::UINTTOFP_I64_F128, "_Q_ulltoq");
1603     }
1604
1605   } else {
1606     // Custom legalize f128 operations.
1607
1608     setOperationAction(ISD::FADD,  MVT::f128, Custom);
1609     setOperationAction(ISD::FSUB,  MVT::f128, Custom);
1610     setOperationAction(ISD::FMUL,  MVT::f128, Custom);
1611     setOperationAction(ISD::FDIV,  MVT::f128, Custom);
1612     setOperationAction(ISD::FSQRT, MVT::f128, Custom);
1613     setOperationAction(ISD::FNEG,  MVT::f128, Custom);
1614     setOperationAction(ISD::FABS,  MVT::f128, Custom);
1615
1616     setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
1617     setOperationAction(ISD::FP_ROUND,  MVT::f64, Custom);
1618     setOperationAction(ISD::FP_ROUND,  MVT::f32, Custom);
1619
1620     // Setup Runtime library names.
1621     if (Subtarget->is64Bit()) {
1622       setLibcallName(RTLIB::ADD_F128,  "_Qp_add");
1623       setLibcallName(RTLIB::SUB_F128,  "_Qp_sub");
1624       setLibcallName(RTLIB::MUL_F128,  "_Qp_mul");
1625       setLibcallName(RTLIB::DIV_F128,  "_Qp_div");
1626       setLibcallName(RTLIB::SQRT_F128, "_Qp_sqrt");
1627       setLibcallName(RTLIB::FPTOSINT_F128_I32, "_Qp_qtoi");
1628       setLibcallName(RTLIB::FPTOUINT_F128_I32, "_Qp_qtoui");
1629       setLibcallName(RTLIB::SINTTOFP_I32_F128, "_Qp_itoq");
1630       setLibcallName(RTLIB::UINTTOFP_I32_F128, "_Qp_uitoq");
1631       setLibcallName(RTLIB::FPTOSINT_F128_I64, "_Qp_qtox");
1632       setLibcallName(RTLIB::FPTOUINT_F128_I64, "_Qp_qtoux");
1633       setLibcallName(RTLIB::SINTTOFP_I64_F128, "_Qp_xtoq");
1634       setLibcallName(RTLIB::UINTTOFP_I64_F128, "_Qp_uxtoq");
1635       setLibcallName(RTLIB::FPEXT_F32_F128, "_Qp_stoq");
1636       setLibcallName(RTLIB::FPEXT_F64_F128, "_Qp_dtoq");
1637       setLibcallName(RTLIB::FPROUND_F128_F32, "_Qp_qtos");
1638       setLibcallName(RTLIB::FPROUND_F128_F64, "_Qp_qtod");
1639     } else {
1640       setLibcallName(RTLIB::ADD_F128,  "_Q_add");
1641       setLibcallName(RTLIB::SUB_F128,  "_Q_sub");
1642       setLibcallName(RTLIB::MUL_F128,  "_Q_mul");
1643       setLibcallName(RTLIB::DIV_F128,  "_Q_div");
1644       setLibcallName(RTLIB::SQRT_F128, "_Q_sqrt");
1645       setLibcallName(RTLIB::FPTOSINT_F128_I32, "_Q_qtoi");
1646       setLibcallName(RTLIB::FPTOUINT_F128_I32, "_Q_qtou");
1647       setLibcallName(RTLIB::SINTTOFP_I32_F128, "_Q_itoq");
1648       setLibcallName(RTLIB::UINTTOFP_I32_F128, "_Q_utoq");
1649       setLibcallName(RTLIB::FPTOSINT_F128_I64, "_Q_qtoll");
1650       setLibcallName(RTLIB::FPTOUINT_F128_I64, "_Q_qtoull");
1651       setLibcallName(RTLIB::SINTTOFP_I64_F128, "_Q_lltoq");
1652       setLibcallName(RTLIB::UINTTOFP_I64_F128, "_Q_ulltoq");
1653       setLibcallName(RTLIB::FPEXT_F32_F128, "_Q_stoq");
1654       setLibcallName(RTLIB::FPEXT_F64_F128, "_Q_dtoq");
1655       setLibcallName(RTLIB::FPROUND_F128_F32, "_Q_qtos");
1656       setLibcallName(RTLIB::FPROUND_F128_F64, "_Q_qtod");
1657     }
1658   }
1659
1660   setMinFunctionAlignment(2);
1661
1662   computeRegisterProperties();
1663 }
1664
1665 const char *SparcTargetLowering::getTargetNodeName(unsigned Opcode) const {
1666   switch (Opcode) {
1667   default: return 0;
1668   case SPISD::CMPICC:     return "SPISD::CMPICC";
1669   case SPISD::CMPFCC:     return "SPISD::CMPFCC";
1670   case SPISD::BRICC:      return "SPISD::BRICC";
1671   case SPISD::BRXCC:      return "SPISD::BRXCC";
1672   case SPISD::BRFCC:      return "SPISD::BRFCC";
1673   case SPISD::SELECT_ICC: return "SPISD::SELECT_ICC";
1674   case SPISD::SELECT_XCC: return "SPISD::SELECT_XCC";
1675   case SPISD::SELECT_FCC: return "SPISD::SELECT_FCC";
1676   case SPISD::Hi:         return "SPISD::Hi";
1677   case SPISD::Lo:         return "SPISD::Lo";
1678   case SPISD::FTOI:       return "SPISD::FTOI";
1679   case SPISD::ITOF:       return "SPISD::ITOF";
1680   case SPISD::FTOX:       return "SPISD::FTOX";
1681   case SPISD::XTOF:       return "SPISD::XTOF";
1682   case SPISD::CALL:       return "SPISD::CALL";
1683   case SPISD::RET_FLAG:   return "SPISD::RET_FLAG";
1684   case SPISD::GLOBAL_BASE_REG: return "SPISD::GLOBAL_BASE_REG";
1685   case SPISD::FLUSHW:     return "SPISD::FLUSHW";
1686   case SPISD::TLS_ADD:    return "SPISD::TLS_ADD";
1687   case SPISD::TLS_LD:     return "SPISD::TLS_LD";
1688   case SPISD::TLS_CALL:   return "SPISD::TLS_CALL";
1689   }
1690 }
1691
1692 EVT SparcTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1693   if (!VT.isVector())
1694     return MVT::i32;
1695   return VT.changeVectorElementTypeToInteger();
1696 }
1697
1698 /// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
1699 /// be zero. Op is expected to be a target specific node. Used by DAG
1700 /// combiner.
1701 void SparcTargetLowering::computeMaskedBitsForTargetNode
1702                                 (const SDValue Op,
1703                                  APInt &KnownZero,
1704                                  APInt &KnownOne,
1705                                  const SelectionDAG &DAG,
1706                                  unsigned Depth) const {
1707   APInt KnownZero2, KnownOne2;
1708   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1709
1710   switch (Op.getOpcode()) {
1711   default: break;
1712   case SPISD::SELECT_ICC:
1713   case SPISD::SELECT_XCC:
1714   case SPISD::SELECT_FCC:
1715     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1716     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1717     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1718     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1719
1720     // Only known if known in both the LHS and RHS.
1721     KnownOne &= KnownOne2;
1722     KnownZero &= KnownZero2;
1723     break;
1724   }
1725 }
1726
1727 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
1728 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
1729 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
1730                              ISD::CondCode CC, unsigned &SPCC) {
1731   if (isa<ConstantSDNode>(RHS) &&
1732       cast<ConstantSDNode>(RHS)->isNullValue() &&
1733       CC == ISD::SETNE &&
1734       (((LHS.getOpcode() == SPISD::SELECT_ICC ||
1735          LHS.getOpcode() == SPISD::SELECT_XCC) &&
1736         LHS.getOperand(3).getOpcode() == SPISD::CMPICC) ||
1737        (LHS.getOpcode() == SPISD::SELECT_FCC &&
1738         LHS.getOperand(3).getOpcode() == SPISD::CMPFCC)) &&
1739       isa<ConstantSDNode>(LHS.getOperand(0)) &&
1740       isa<ConstantSDNode>(LHS.getOperand(1)) &&
1741       cast<ConstantSDNode>(LHS.getOperand(0))->isOne() &&
1742       cast<ConstantSDNode>(LHS.getOperand(1))->isNullValue()) {
1743     SDValue CMPCC = LHS.getOperand(3);
1744     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
1745     LHS = CMPCC.getOperand(0);
1746     RHS = CMPCC.getOperand(1);
1747   }
1748 }
1749
1750 // Convert to a target node and set target flags.
1751 SDValue SparcTargetLowering::withTargetFlags(SDValue Op, unsigned TF,
1752                                              SelectionDAG &DAG) const {
1753   if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op))
1754     return DAG.getTargetGlobalAddress(GA->getGlobal(),
1755                                       SDLoc(GA),
1756                                       GA->getValueType(0),
1757                                       GA->getOffset(), TF);
1758
1759   if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op))
1760     return DAG.getTargetConstantPool(CP->getConstVal(),
1761                                      CP->getValueType(0),
1762                                      CP->getAlignment(),
1763                                      CP->getOffset(), TF);
1764
1765   if (const BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op))
1766     return DAG.getTargetBlockAddress(BA->getBlockAddress(),
1767                                      Op.getValueType(),
1768                                      0,
1769                                      TF);
1770
1771   if (const ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op))
1772     return DAG.getTargetExternalSymbol(ES->getSymbol(),
1773                                        ES->getValueType(0), TF);
1774
1775   llvm_unreachable("Unhandled address SDNode");
1776 }
1777
1778 // Split Op into high and low parts according to HiTF and LoTF.
1779 // Return an ADD node combining the parts.
1780 SDValue SparcTargetLowering::makeHiLoPair(SDValue Op,
1781                                           unsigned HiTF, unsigned LoTF,
1782                                           SelectionDAG &DAG) const {
1783   SDLoc DL(Op);
1784   EVT VT = Op.getValueType();
1785   SDValue Hi = DAG.getNode(SPISD::Hi, DL, VT, withTargetFlags(Op, HiTF, DAG));
1786   SDValue Lo = DAG.getNode(SPISD::Lo, DL, VT, withTargetFlags(Op, LoTF, DAG));
1787   return DAG.getNode(ISD::ADD, DL, VT, Hi, Lo);
1788 }
1789
1790 // Build SDNodes for producing an address from a GlobalAddress, ConstantPool,
1791 // or ExternalSymbol SDNode.
1792 SDValue SparcTargetLowering::makeAddress(SDValue Op, SelectionDAG &DAG) const {
1793   SDLoc DL(Op);
1794   EVT VT = getPointerTy();
1795
1796   // Handle PIC mode first.
1797   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1798     // This is the pic32 code model, the GOT is known to be smaller than 4GB.
1799     SDValue HiLo = makeHiLoPair(Op, SPII::MO_HI, SPII::MO_LO, DAG);
1800     SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, DL, VT);
1801     SDValue AbsAddr = DAG.getNode(ISD::ADD, DL, VT, GlobalBase, HiLo);
1802     // GLOBAL_BASE_REG codegen'ed with call. Inform MFI that this
1803     // function has calls.
1804     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1805     MFI->setHasCalls(true);
1806     return DAG.getLoad(VT, DL, DAG.getEntryNode(), AbsAddr,
1807                        MachinePointerInfo::getGOT(), false, false, false, 0);
1808   }
1809
1810   // This is one of the absolute code models.
1811   switch(getTargetMachine().getCodeModel()) {
1812   default:
1813     llvm_unreachable("Unsupported absolute code model");
1814   case CodeModel::JITDefault:
1815   case CodeModel::Small:
1816     // abs32.
1817     return makeHiLoPair(Op, SPII::MO_HI, SPII::MO_LO, DAG);
1818   case CodeModel::Medium: {
1819     // abs44.
1820     SDValue H44 = makeHiLoPair(Op, SPII::MO_H44, SPII::MO_M44, DAG);
1821     H44 = DAG.getNode(ISD::SHL, DL, VT, H44, DAG.getConstant(12, MVT::i32));
1822     SDValue L44 = withTargetFlags(Op, SPII::MO_L44, DAG);
1823     L44 = DAG.getNode(SPISD::Lo, DL, VT, L44);
1824     return DAG.getNode(ISD::ADD, DL, VT, H44, L44);
1825   }
1826   case CodeModel::Large: {
1827     // abs64.
1828     SDValue Hi = makeHiLoPair(Op, SPII::MO_HH, SPII::MO_HM, DAG);
1829     Hi = DAG.getNode(ISD::SHL, DL, VT, Hi, DAG.getConstant(32, MVT::i32));
1830     SDValue Lo = makeHiLoPair(Op, SPII::MO_HI, SPII::MO_LO, DAG);
1831     return DAG.getNode(ISD::ADD, DL, VT, Hi, Lo);
1832   }
1833   }
1834 }
1835
1836 SDValue SparcTargetLowering::LowerGlobalAddress(SDValue Op,
1837                                                 SelectionDAG &DAG) const {
1838   return makeAddress(Op, DAG);
1839 }
1840
1841 SDValue SparcTargetLowering::LowerConstantPool(SDValue Op,
1842                                                SelectionDAG &DAG) const {
1843   return makeAddress(Op, DAG);
1844 }
1845
1846 SDValue SparcTargetLowering::LowerBlockAddress(SDValue Op,
1847                                                SelectionDAG &DAG) const {
1848   return makeAddress(Op, DAG);
1849 }
1850
1851 SDValue SparcTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1852                                                    SelectionDAG &DAG) const {
1853
1854   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1855   SDLoc DL(GA);
1856   const GlobalValue *GV = GA->getGlobal();
1857   EVT PtrVT = getPointerTy();
1858
1859   TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1860
1861   if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1862     unsigned HiTF = ((model == TLSModel::GeneralDynamic)? SPII::MO_TLS_GD_HI22
1863                      : SPII::MO_TLS_LDM_HI22);
1864     unsigned LoTF = ((model == TLSModel::GeneralDynamic)? SPII::MO_TLS_GD_LO10
1865                      : SPII::MO_TLS_LDM_LO10);
1866     unsigned addTF = ((model == TLSModel::GeneralDynamic)? SPII::MO_TLS_GD_ADD
1867                       : SPII::MO_TLS_LDM_ADD);
1868     unsigned callTF = ((model == TLSModel::GeneralDynamic)? SPII::MO_TLS_GD_CALL
1869                        : SPII::MO_TLS_LDM_CALL);
1870
1871     SDValue HiLo = makeHiLoPair(Op, HiTF, LoTF, DAG);
1872     SDValue Base = DAG.getNode(SPISD::GLOBAL_BASE_REG, DL, PtrVT);
1873     SDValue Argument = DAG.getNode(SPISD::TLS_ADD, DL, PtrVT, Base, HiLo,
1874                                withTargetFlags(Op, addTF, DAG));
1875
1876     SDValue Chain = DAG.getEntryNode();
1877     SDValue InFlag;
1878
1879     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(1, true), DL);
1880     Chain = DAG.getCopyToReg(Chain, DL, SP::O0, Argument, InFlag);
1881     InFlag = Chain.getValue(1);
1882     SDValue Callee = DAG.getTargetExternalSymbol("__tls_get_addr", PtrVT);
1883     SDValue Symbol = withTargetFlags(Op, callTF, DAG);
1884
1885     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1886     SmallVector<SDValue, 4> Ops;
1887     Ops.push_back(Chain);
1888     Ops.push_back(Callee);
1889     Ops.push_back(Symbol);
1890     Ops.push_back(DAG.getRegister(SP::O0, PtrVT));
1891     const uint32_t *Mask = getTargetMachine()
1892       .getRegisterInfo()->getCallPreservedMask(CallingConv::C);
1893     assert(Mask && "Missing call preserved mask for calling convention");
1894     Ops.push_back(DAG.getRegisterMask(Mask));
1895     Ops.push_back(InFlag);
1896     Chain = DAG.getNode(SPISD::TLS_CALL, DL, NodeTys, &Ops[0], Ops.size());
1897     InFlag = Chain.getValue(1);
1898     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(1, true),
1899                                DAG.getIntPtrConstant(0, true), InFlag, DL);
1900     InFlag = Chain.getValue(1);
1901     SDValue Ret = DAG.getCopyFromReg(Chain, DL, SP::O0, PtrVT, InFlag);
1902
1903     if (model != TLSModel::LocalDynamic)
1904       return Ret;
1905
1906     SDValue Hi = DAG.getNode(SPISD::Hi, DL, PtrVT,
1907                              withTargetFlags(Op, SPII::MO_TLS_LDO_HIX22, DAG));
1908     SDValue Lo = DAG.getNode(SPISD::Lo, DL, PtrVT,
1909                              withTargetFlags(Op, SPII::MO_TLS_LDO_LOX10, DAG));
1910     HiLo =  DAG.getNode(ISD::XOR, DL, PtrVT, Hi, Lo);
1911     return DAG.getNode(SPISD::TLS_ADD, DL, PtrVT, Ret, HiLo,
1912                        withTargetFlags(Op, SPII::MO_TLS_LDO_ADD, DAG));
1913   }
1914
1915   if (model == TLSModel::InitialExec) {
1916     unsigned ldTF     = ((PtrVT == MVT::i64)? SPII::MO_TLS_IE_LDX
1917                          : SPII::MO_TLS_IE_LD);
1918
1919     SDValue Base = DAG.getNode(SPISD::GLOBAL_BASE_REG, DL, PtrVT);
1920
1921     // GLOBAL_BASE_REG codegen'ed with call. Inform MFI that this
1922     // function has calls.
1923     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1924     MFI->setHasCalls(true);
1925
1926     SDValue TGA = makeHiLoPair(Op,
1927                                SPII::MO_TLS_IE_HI22, SPII::MO_TLS_IE_LO10, DAG);
1928     SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, Base, TGA);
1929     SDValue Offset = DAG.getNode(SPISD::TLS_LD,
1930                                  DL, PtrVT, Ptr,
1931                                  withTargetFlags(Op, ldTF, DAG));
1932     return DAG.getNode(SPISD::TLS_ADD, DL, PtrVT,
1933                        DAG.getRegister(SP::G7, PtrVT), Offset,
1934                        withTargetFlags(Op, SPII::MO_TLS_IE_ADD, DAG));
1935   }
1936
1937   assert(model == TLSModel::LocalExec);
1938   SDValue Hi = DAG.getNode(SPISD::Hi, DL, PtrVT,
1939                            withTargetFlags(Op, SPII::MO_TLS_LE_HIX22, DAG));
1940   SDValue Lo = DAG.getNode(SPISD::Lo, DL, PtrVT,
1941                            withTargetFlags(Op, SPII::MO_TLS_LE_LOX10, DAG));
1942   SDValue Offset =  DAG.getNode(ISD::XOR, DL, PtrVT, Hi, Lo);
1943
1944   return DAG.getNode(ISD::ADD, DL, PtrVT,
1945                      DAG.getRegister(SP::G7, PtrVT), Offset);
1946 }
1947
1948 SDValue
1949 SparcTargetLowering::LowerF128_LibCallArg(SDValue Chain, ArgListTy &Args,
1950                                           SDValue Arg, SDLoc DL,
1951                                           SelectionDAG &DAG) const {
1952   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1953   EVT ArgVT = Arg.getValueType();
1954   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1955
1956   ArgListEntry Entry;
1957   Entry.Node = Arg;
1958   Entry.Ty   = ArgTy;
1959
1960   if (ArgTy->isFP128Ty()) {
1961     // Create a stack object and pass the pointer to the library function.
1962     int FI = MFI->CreateStackObject(16, 8, false);
1963     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
1964     Chain = DAG.getStore(Chain,
1965                          DL,
1966                          Entry.Node,
1967                          FIPtr,
1968                          MachinePointerInfo(),
1969                          false,
1970                          false,
1971                          8);
1972
1973     Entry.Node = FIPtr;
1974     Entry.Ty   = PointerType::getUnqual(ArgTy);
1975   }
1976   Args.push_back(Entry);
1977   return Chain;
1978 }
1979
1980 SDValue
1981 SparcTargetLowering::LowerF128Op(SDValue Op, SelectionDAG &DAG,
1982                                  const char *LibFuncName,
1983                                  unsigned numArgs) const {
1984
1985   ArgListTy Args;
1986
1987   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1988
1989   SDValue Callee = DAG.getExternalSymbol(LibFuncName, getPointerTy());
1990   Type *RetTy = Op.getValueType().getTypeForEVT(*DAG.getContext());
1991   Type *RetTyABI = RetTy;
1992   SDValue Chain = DAG.getEntryNode();
1993   SDValue RetPtr;
1994
1995   if (RetTy->isFP128Ty()) {
1996     // Create a Stack Object to receive the return value of type f128.
1997     ArgListEntry Entry;
1998     int RetFI = MFI->CreateStackObject(16, 8, false);
1999     RetPtr = DAG.getFrameIndex(RetFI, getPointerTy());
2000     Entry.Node = RetPtr;
2001     Entry.Ty   = PointerType::getUnqual(RetTy);
2002     if (!Subtarget->is64Bit())
2003       Entry.isSRet = true;
2004     Entry.isReturned = false;
2005     Args.push_back(Entry);
2006     RetTyABI = Type::getVoidTy(*DAG.getContext());
2007   }
2008
2009   assert(Op->getNumOperands() >= numArgs && "Not enough operands!");
2010   for (unsigned i = 0, e = numArgs; i != e; ++i) {
2011     Chain = LowerF128_LibCallArg(Chain, Args, Op.getOperand(i), SDLoc(Op), DAG);
2012   }
2013   TargetLowering::
2014     CallLoweringInfo CLI(Chain,
2015                          RetTyABI,
2016                          false, false, false, false,
2017                          0, CallingConv::C,
2018                          false, false, true,
2019                          Callee, Args, DAG, SDLoc(Op));
2020   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
2021
2022   // chain is in second result.
2023   if (RetTyABI == RetTy)
2024     return CallInfo.first;
2025
2026   assert (RetTy->isFP128Ty() && "Unexpected return type!");
2027
2028   Chain = CallInfo.second;
2029
2030   // Load RetPtr to get the return value.
2031   return DAG.getLoad(Op.getValueType(),
2032                      SDLoc(Op),
2033                      Chain,
2034                      RetPtr,
2035                      MachinePointerInfo(),
2036                      false, false, false, 8);
2037 }
2038
2039 SDValue
2040 SparcTargetLowering::LowerF128Compare(SDValue LHS, SDValue RHS,
2041                                       unsigned &SPCC,
2042                                       SDLoc DL,
2043                                       SelectionDAG &DAG) const {
2044
2045   const char *LibCall = 0;
2046   bool is64Bit = Subtarget->is64Bit();
2047   switch(SPCC) {
2048   default: llvm_unreachable("Unhandled conditional code!");
2049   case SPCC::FCC_E  : LibCall = is64Bit? "_Qp_feq" : "_Q_feq"; break;
2050   case SPCC::FCC_NE : LibCall = is64Bit? "_Qp_fne" : "_Q_fne"; break;
2051   case SPCC::FCC_L  : LibCall = is64Bit? "_Qp_flt" : "_Q_flt"; break;
2052   case SPCC::FCC_G  : LibCall = is64Bit? "_Qp_fgt" : "_Q_fgt"; break;
2053   case SPCC::FCC_LE : LibCall = is64Bit? "_Qp_fle" : "_Q_fle"; break;
2054   case SPCC::FCC_GE : LibCall = is64Bit? "_Qp_fge" : "_Q_fge"; break;
2055   case SPCC::FCC_UL :
2056   case SPCC::FCC_ULE:
2057   case SPCC::FCC_UG :
2058   case SPCC::FCC_UGE:
2059   case SPCC::FCC_U  :
2060   case SPCC::FCC_O  :
2061   case SPCC::FCC_LG :
2062   case SPCC::FCC_UE : LibCall = is64Bit? "_Qp_cmp" : "_Q_cmp"; break;
2063   }
2064
2065   SDValue Callee = DAG.getExternalSymbol(LibCall, getPointerTy());
2066   Type *RetTy = Type::getInt32Ty(*DAG.getContext());
2067   ArgListTy Args;
2068   SDValue Chain = DAG.getEntryNode();
2069   Chain = LowerF128_LibCallArg(Chain, Args, LHS, DL, DAG);
2070   Chain = LowerF128_LibCallArg(Chain, Args, RHS, DL, DAG);
2071
2072   TargetLowering::
2073     CallLoweringInfo CLI(Chain,
2074                          RetTy,
2075                          false, false, false, false,
2076                          0, CallingConv::C,
2077                          false, false, true,
2078                          Callee, Args, DAG, DL);
2079
2080   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
2081
2082   // result is in first, and chain is in second result.
2083   SDValue Result =  CallInfo.first;
2084
2085   switch(SPCC) {
2086   default: {
2087     SDValue RHS = DAG.getTargetConstant(0, Result.getValueType());
2088     SPCC = SPCC::ICC_NE;
2089     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2090   }
2091   case SPCC::FCC_UL : {
2092     SDValue Mask   = DAG.getTargetConstant(1, Result.getValueType());
2093     Result = DAG.getNode(ISD::AND, DL, Result.getValueType(), Result, Mask);
2094     SDValue RHS    = DAG.getTargetConstant(0, Result.getValueType());
2095     SPCC = SPCC::ICC_NE;
2096     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2097   }
2098   case SPCC::FCC_ULE: {
2099     SDValue RHS = DAG.getTargetConstant(2, Result.getValueType());
2100     SPCC = SPCC::ICC_NE;
2101     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2102   }
2103   case SPCC::FCC_UG :  {
2104     SDValue RHS = DAG.getTargetConstant(1, Result.getValueType());
2105     SPCC = SPCC::ICC_G;
2106     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2107   }
2108   case SPCC::FCC_UGE: {
2109     SDValue RHS = DAG.getTargetConstant(1, Result.getValueType());
2110     SPCC = SPCC::ICC_NE;
2111     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2112   }
2113
2114   case SPCC::FCC_U  :  {
2115     SDValue RHS = DAG.getTargetConstant(3, Result.getValueType());
2116     SPCC = SPCC::ICC_E;
2117     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2118   }
2119   case SPCC::FCC_O  :  {
2120     SDValue RHS = DAG.getTargetConstant(3, Result.getValueType());
2121     SPCC = SPCC::ICC_NE;
2122     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2123   }
2124   case SPCC::FCC_LG :  {
2125     SDValue Mask   = DAG.getTargetConstant(3, Result.getValueType());
2126     Result = DAG.getNode(ISD::AND, DL, Result.getValueType(), Result, Mask);
2127     SDValue RHS    = DAG.getTargetConstant(0, Result.getValueType());
2128     SPCC = SPCC::ICC_NE;
2129     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2130   }
2131   case SPCC::FCC_UE : {
2132     SDValue Mask   = DAG.getTargetConstant(3, Result.getValueType());
2133     Result = DAG.getNode(ISD::AND, DL, Result.getValueType(), Result, Mask);
2134     SDValue RHS    = DAG.getTargetConstant(0, Result.getValueType());
2135     SPCC = SPCC::ICC_E;
2136     return DAG.getNode(SPISD::CMPICC, DL, MVT::Glue, Result, RHS);
2137   }
2138   }
2139 }
2140
2141 static SDValue
2142 LowerF128_FPEXTEND(SDValue Op, SelectionDAG &DAG,
2143                    const SparcTargetLowering &TLI) {
2144
2145   if (Op.getOperand(0).getValueType() == MVT::f64)
2146     return TLI.LowerF128Op(Op, DAG,
2147                            TLI.getLibcallName(RTLIB::FPEXT_F64_F128), 1);
2148
2149   if (Op.getOperand(0).getValueType() == MVT::f32)
2150     return TLI.LowerF128Op(Op, DAG,
2151                            TLI.getLibcallName(RTLIB::FPEXT_F32_F128), 1);
2152
2153   llvm_unreachable("fpextend with non-float operand!");
2154   return SDValue(0, 0);
2155 }
2156
2157 static SDValue
2158 LowerF128_FPROUND(SDValue Op, SelectionDAG &DAG,
2159                   const SparcTargetLowering &TLI) {
2160   // FP_ROUND on f64 and f32 are legal.
2161   if (Op.getOperand(0).getValueType() != MVT::f128)
2162     return Op;
2163
2164   if (Op.getValueType() == MVT::f64)
2165     return TLI.LowerF128Op(Op, DAG,
2166                            TLI.getLibcallName(RTLIB::FPROUND_F128_F64), 1);
2167   if (Op.getValueType() == MVT::f32)
2168     return TLI.LowerF128Op(Op, DAG,
2169                            TLI.getLibcallName(RTLIB::FPROUND_F128_F32), 1);
2170
2171   llvm_unreachable("fpround to non-float!");
2172   return SDValue(0, 0);
2173 }
2174
2175 static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG,
2176                                const SparcTargetLowering &TLI,
2177                                bool hasHardQuad) {
2178   SDLoc dl(Op);
2179   EVT VT = Op.getValueType();
2180   assert(VT == MVT::i32 || VT == MVT::i64);
2181
2182   // Expand f128 operations to fp128 abi calls.
2183   if (Op.getOperand(0).getValueType() == MVT::f128
2184       && (!hasHardQuad || !TLI.isTypeLegal(VT))) {
2185     const char *libName = TLI.getLibcallName(VT == MVT::i32
2186                                              ? RTLIB::FPTOSINT_F128_I32
2187                                              : RTLIB::FPTOSINT_F128_I64);
2188     return TLI.LowerF128Op(Op, DAG, libName, 1);
2189   }
2190
2191   // Expand if the resulting type is illegal.
2192   if (!TLI.isTypeLegal(VT))
2193     return SDValue(0, 0);
2194
2195   // Otherwise, Convert the fp value to integer in an FP register.
2196   if (VT == MVT::i32)
2197     Op = DAG.getNode(SPISD::FTOI, dl, MVT::f32, Op.getOperand(0));
2198   else
2199     Op = DAG.getNode(SPISD::FTOX, dl, MVT::f64, Op.getOperand(0));
2200
2201   return DAG.getNode(ISD::BITCAST, dl, VT, Op);
2202 }
2203
2204 static SDValue LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2205                                const SparcTargetLowering &TLI,
2206                                bool hasHardQuad) {
2207   SDLoc dl(Op);
2208   EVT OpVT = Op.getOperand(0).getValueType();
2209   assert(OpVT == MVT::i32 || (OpVT == MVT::i64));
2210
2211   EVT floatVT = (OpVT == MVT::i32) ? MVT::f32 : MVT::f64;
2212
2213   // Expand f128 operations to fp128 ABI calls.
2214   if (Op.getValueType() == MVT::f128
2215       && (!hasHardQuad || !TLI.isTypeLegal(OpVT))) {
2216     const char *libName = TLI.getLibcallName(OpVT == MVT::i32
2217                                              ? RTLIB::SINTTOFP_I32_F128
2218                                              : RTLIB::SINTTOFP_I64_F128);
2219     return TLI.LowerF128Op(Op, DAG, libName, 1);
2220   }
2221
2222   // Expand if the operand type is illegal.
2223   if (!TLI.isTypeLegal(OpVT))
2224     return SDValue(0, 0);
2225
2226   // Otherwise, Convert the int value to FP in an FP register.
2227   SDValue Tmp = DAG.getNode(ISD::BITCAST, dl, floatVT, Op.getOperand(0));
2228   unsigned opcode = (OpVT == MVT::i32)? SPISD::ITOF : SPISD::XTOF;
2229   return DAG.getNode(opcode, dl, Op.getValueType(), Tmp);
2230 }
2231
2232 static SDValue LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG,
2233                                const SparcTargetLowering &TLI,
2234                                bool hasHardQuad) {
2235   SDLoc dl(Op);
2236   EVT VT = Op.getValueType();
2237
2238   // Expand if it does not involve f128 or the target has support for
2239   // quad floating point instructions and the resulting type is legal.
2240   if (Op.getOperand(0).getValueType() != MVT::f128 ||
2241       (hasHardQuad && TLI.isTypeLegal(VT)))
2242     return SDValue(0, 0);
2243
2244   assert(VT == MVT::i32 || VT == MVT::i64);
2245
2246   return TLI.LowerF128Op(Op, DAG,
2247                          TLI.getLibcallName(VT == MVT::i32
2248                                             ? RTLIB::FPTOUINT_F128_I32
2249                                             : RTLIB::FPTOUINT_F128_I64),
2250                          1);
2251 }
2252
2253 static SDValue LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2254                                const SparcTargetLowering &TLI,
2255                                bool hasHardQuad) {
2256   SDLoc dl(Op);
2257   EVT OpVT = Op.getOperand(0).getValueType();
2258   assert(OpVT == MVT::i32 || OpVT == MVT::i64);
2259
2260   // Expand if it does not involve f128 or the target has support for
2261   // quad floating point instructions and the operand type is legal.
2262   if (Op.getValueType() != MVT::f128 || (hasHardQuad && TLI.isTypeLegal(OpVT)))
2263     return SDValue(0, 0);
2264
2265   return TLI.LowerF128Op(Op, DAG,
2266                          TLI.getLibcallName(OpVT == MVT::i32
2267                                             ? RTLIB::UINTTOFP_I32_F128
2268                                             : RTLIB::UINTTOFP_I64_F128),
2269                          1);
2270 }
2271
2272 static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG,
2273                           const SparcTargetLowering &TLI,
2274                           bool hasHardQuad) {
2275   SDValue Chain = Op.getOperand(0);
2276   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2277   SDValue LHS = Op.getOperand(2);
2278   SDValue RHS = Op.getOperand(3);
2279   SDValue Dest = Op.getOperand(4);
2280   SDLoc dl(Op);
2281   unsigned Opc, SPCC = ~0U;
2282
2283   // If this is a br_cc of a "setcc", and if the setcc got lowered into
2284   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
2285   LookThroughSetCC(LHS, RHS, CC, SPCC);
2286
2287   // Get the condition flag.
2288   SDValue CompareFlag;
2289   if (LHS.getValueType().isInteger()) {
2290     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, MVT::Glue, LHS, RHS);
2291     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
2292     // 32-bit compares use the icc flags, 64-bit uses the xcc flags.
2293     Opc = LHS.getValueType() == MVT::i32 ? SPISD::BRICC : SPISD::BRXCC;
2294   } else {
2295     if (!hasHardQuad && LHS.getValueType() == MVT::f128) {
2296       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
2297       CompareFlag = TLI.LowerF128Compare(LHS, RHS, SPCC, dl, DAG);
2298       Opc = SPISD::BRICC;
2299     } else {
2300       CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
2301       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
2302       Opc = SPISD::BRFCC;
2303     }
2304   }
2305   return DAG.getNode(Opc, dl, MVT::Other, Chain, Dest,
2306                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
2307 }
2308
2309 static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG,
2310                               const SparcTargetLowering &TLI,
2311                               bool hasHardQuad) {
2312   SDValue LHS = Op.getOperand(0);
2313   SDValue RHS = Op.getOperand(1);
2314   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2315   SDValue TrueVal = Op.getOperand(2);
2316   SDValue FalseVal = Op.getOperand(3);
2317   SDLoc dl(Op);
2318   unsigned Opc, SPCC = ~0U;
2319
2320   // If this is a select_cc of a "setcc", and if the setcc got lowered into
2321   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
2322   LookThroughSetCC(LHS, RHS, CC, SPCC);
2323
2324   SDValue CompareFlag;
2325   if (LHS.getValueType().isInteger()) {
2326     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, MVT::Glue, LHS, RHS);
2327     Opc = LHS.getValueType() == MVT::i32 ?
2328           SPISD::SELECT_ICC : SPISD::SELECT_XCC;
2329     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
2330   } else {
2331     if (!hasHardQuad && LHS.getValueType() == MVT::f128) {
2332       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
2333       CompareFlag = TLI.LowerF128Compare(LHS, RHS, SPCC, dl, DAG);
2334       Opc = SPISD::SELECT_ICC;
2335     } else {
2336       CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
2337       Opc = SPISD::SELECT_FCC;
2338       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
2339     }
2340   }
2341   return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
2342                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
2343 }
2344
2345 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
2346                             const SparcTargetLowering &TLI) {
2347   MachineFunction &MF = DAG.getMachineFunction();
2348   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
2349
2350   // Need frame address to find the address of VarArgsFrameIndex.
2351   MF.getFrameInfo()->setFrameAddressIsTaken(true);
2352
2353   // vastart just stores the address of the VarArgsFrameIndex slot into the
2354   // memory location argument.
2355   SDLoc DL(Op);
2356   SDValue Offset =
2357     DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(),
2358                 DAG.getRegister(SP::I6, TLI.getPointerTy()),
2359                 DAG.getIntPtrConstant(FuncInfo->getVarArgsFrameOffset()));
2360   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2361   return DAG.getStore(Op.getOperand(0), DL, Offset, Op.getOperand(1),
2362                       MachinePointerInfo(SV), false, false, 0);
2363 }
2364
2365 static SDValue LowerVAARG(SDValue Op, SelectionDAG &DAG) {
2366   SDNode *Node = Op.getNode();
2367   EVT VT = Node->getValueType(0);
2368   SDValue InChain = Node->getOperand(0);
2369   SDValue VAListPtr = Node->getOperand(1);
2370   EVT PtrVT = VAListPtr.getValueType();
2371   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2372   SDLoc DL(Node);
2373   SDValue VAList = DAG.getLoad(PtrVT, DL, InChain, VAListPtr,
2374                                MachinePointerInfo(SV), false, false, false, 0);
2375   // Increment the pointer, VAList, to the next vaarg.
2376   SDValue NextPtr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
2377                                 DAG.getIntPtrConstant(VT.getSizeInBits()/8));
2378   // Store the incremented VAList to the legalized pointer.
2379   InChain = DAG.getStore(VAList.getValue(1), DL, NextPtr,
2380                          VAListPtr, MachinePointerInfo(SV), false, false, 0);
2381   // Load the actual argument out of the pointer VAList.
2382   // We can't count on greater alignment than the word size.
2383   return DAG.getLoad(VT, DL, InChain, VAList, MachinePointerInfo(),
2384                      false, false, false,
2385                      std::min(PtrVT.getSizeInBits(), VT.getSizeInBits())/8);
2386 }
2387
2388 static SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG,
2389                                        const SparcSubtarget *Subtarget) {
2390   SDValue Chain = Op.getOperand(0);  // Legalize the chain.
2391   SDValue Size  = Op.getOperand(1);  // Legalize the size.
2392   EVT VT = Size->getValueType(0);
2393   SDLoc dl(Op);
2394
2395   unsigned SPReg = SP::O6;
2396   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
2397   SDValue NewSP = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
2398   Chain = DAG.getCopyToReg(SP.getValue(1), dl, SPReg, NewSP);    // Output chain
2399
2400   // The resultant pointer is actually 16 words from the bottom of the stack,
2401   // to provide a register spill area.
2402   unsigned regSpillArea = Subtarget->is64Bit() ? 128 : 96;
2403   regSpillArea += Subtarget->getStackPointerBias();
2404
2405   SDValue NewVal = DAG.getNode(ISD::ADD, dl, VT, NewSP,
2406                                DAG.getConstant(regSpillArea, VT));
2407   SDValue Ops[2] = { NewVal, Chain };
2408   return DAG.getMergeValues(Ops, 2, dl);
2409 }
2410
2411
2412 static SDValue getFLUSHW(SDValue Op, SelectionDAG &DAG) {
2413   SDLoc dl(Op);
2414   SDValue Chain = DAG.getNode(SPISD::FLUSHW,
2415                               dl, MVT::Other, DAG.getEntryNode());
2416   return Chain;
2417 }
2418
2419 static SDValue getFRAMEADDR(uint64_t depth, SDValue Op, SelectionDAG &DAG,
2420                             const SparcSubtarget *Subtarget) {
2421   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2422   MFI->setFrameAddressIsTaken(true);
2423
2424   EVT VT = Op.getValueType();
2425   SDLoc dl(Op);
2426   unsigned FrameReg = SP::I6;
2427   unsigned stackBias = Subtarget->getStackPointerBias();
2428
2429   SDValue FrameAddr;
2430
2431   if (depth == 0) {
2432     FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
2433     if (Subtarget->is64Bit())
2434       FrameAddr = DAG.getNode(ISD::ADD, dl, VT, FrameAddr,
2435                               DAG.getIntPtrConstant(stackBias));
2436     return FrameAddr;
2437   }
2438
2439   // flush first to make sure the windowed registers' values are in stack
2440   SDValue Chain = getFLUSHW(Op, DAG);
2441   FrameAddr = DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
2442
2443   unsigned Offset = (Subtarget->is64Bit()) ? (stackBias + 112) : 56;
2444
2445   while (depth--) {
2446     SDValue Ptr = DAG.getNode(ISD::ADD, dl, VT, FrameAddr,
2447                               DAG.getIntPtrConstant(Offset));
2448     FrameAddr = DAG.getLoad(VT, dl, Chain, Ptr, MachinePointerInfo(),
2449                             false, false, false, 0);
2450   }
2451   if (Subtarget->is64Bit())
2452     FrameAddr = DAG.getNode(ISD::ADD, dl, VT, FrameAddr,
2453                             DAG.getIntPtrConstant(stackBias));
2454   return FrameAddr;
2455 }
2456
2457
2458 static SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG,
2459                               const SparcSubtarget *Subtarget) {
2460
2461   uint64_t depth = Op.getConstantOperandVal(0);
2462
2463   return getFRAMEADDR(depth, Op, DAG, Subtarget);
2464
2465 }
2466
2467 static SDValue LowerRETURNADDR(SDValue Op, SelectionDAG &DAG,
2468                                const SparcTargetLowering &TLI,
2469                                const SparcSubtarget *Subtarget) {
2470   MachineFunction &MF = DAG.getMachineFunction();
2471   MachineFrameInfo *MFI = MF.getFrameInfo();
2472   MFI->setReturnAddressIsTaken(true);
2473
2474   if (TLI.verifyReturnAddressArgumentIsConstant(Op, DAG))
2475     return SDValue();
2476
2477   EVT VT = Op.getValueType();
2478   SDLoc dl(Op);
2479   uint64_t depth = Op.getConstantOperandVal(0);
2480
2481   SDValue RetAddr;
2482   if (depth == 0) {
2483     unsigned RetReg = MF.addLiveIn(SP::I7,
2484                                    TLI.getRegClassFor(TLI.getPointerTy()));
2485     RetAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, RetReg, VT);
2486     return RetAddr;
2487   }
2488
2489   // Need frame address to find return address of the caller.
2490   SDValue FrameAddr = getFRAMEADDR(depth - 1, Op, DAG, Subtarget);
2491
2492   unsigned Offset = (Subtarget->is64Bit()) ? 120 : 60;
2493   SDValue Ptr = DAG.getNode(ISD::ADD,
2494                             dl, VT,
2495                             FrameAddr,
2496                             DAG.getIntPtrConstant(Offset));
2497   RetAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), Ptr,
2498                         MachinePointerInfo(), false, false, false, 0);
2499
2500   return RetAddr;
2501 }
2502
2503 static SDValue LowerF64Op(SDValue Op, SelectionDAG &DAG, unsigned opcode)
2504 {
2505   SDLoc dl(Op);
2506
2507   assert(Op.getValueType() == MVT::f64 && "LowerF64Op called on non-double!");
2508   assert(opcode == ISD::FNEG || opcode == ISD::FABS);
2509
2510   // Lower fneg/fabs on f64 to fneg/fabs on f32.
2511   // fneg f64 => fneg f32:sub_even, fmov f32:sub_odd.
2512   // fabs f64 => fabs f32:sub_even, fmov f32:sub_odd.
2513
2514   SDValue SrcReg64 = Op.getOperand(0);
2515   SDValue Hi32 = DAG.getTargetExtractSubreg(SP::sub_even, dl, MVT::f32,
2516                                             SrcReg64);
2517   SDValue Lo32 = DAG.getTargetExtractSubreg(SP::sub_odd, dl, MVT::f32,
2518                                             SrcReg64);
2519
2520   Hi32 = DAG.getNode(opcode, dl, MVT::f32, Hi32);
2521
2522   SDValue DstReg64 = SDValue(DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
2523                                                 dl, MVT::f64), 0);
2524   DstReg64 = DAG.getTargetInsertSubreg(SP::sub_even, dl, MVT::f64,
2525                                        DstReg64, Hi32);
2526   DstReg64 = DAG.getTargetInsertSubreg(SP::sub_odd, dl, MVT::f64,
2527                                        DstReg64, Lo32);
2528   return DstReg64;
2529 }
2530
2531 // Lower a f128 load into two f64 loads.
2532 static SDValue LowerF128Load(SDValue Op, SelectionDAG &DAG)
2533 {
2534   SDLoc dl(Op);
2535   LoadSDNode *LdNode = dyn_cast<LoadSDNode>(Op.getNode());
2536   assert(LdNode && LdNode->getOffset().getOpcode() == ISD::UNDEF
2537          && "Unexpected node type");
2538
2539   unsigned alignment = LdNode->getAlignment();
2540   if (alignment > 8)
2541     alignment = 8;
2542
2543   SDValue Hi64 = DAG.getLoad(MVT::f64,
2544                              dl,
2545                              LdNode->getChain(),
2546                              LdNode->getBasePtr(),
2547                              LdNode->getPointerInfo(),
2548                              false, false, false, alignment);
2549   EVT addrVT = LdNode->getBasePtr().getValueType();
2550   SDValue LoPtr = DAG.getNode(ISD::ADD, dl, addrVT,
2551                               LdNode->getBasePtr(),
2552                               DAG.getConstant(8, addrVT));
2553   SDValue Lo64 = DAG.getLoad(MVT::f64,
2554                              dl,
2555                              LdNode->getChain(),
2556                              LoPtr,
2557                              LdNode->getPointerInfo(),
2558                              false, false, false, alignment);
2559
2560   SDValue SubRegEven = DAG.getTargetConstant(SP::sub_even64, MVT::i32);
2561   SDValue SubRegOdd  = DAG.getTargetConstant(SP::sub_odd64, MVT::i32);
2562
2563   SDNode *InFP128 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
2564                                        dl, MVT::f128);
2565   InFP128 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl,
2566                                MVT::f128,
2567                                SDValue(InFP128, 0),
2568                                Hi64,
2569                                SubRegEven);
2570   InFP128 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl,
2571                                MVT::f128,
2572                                SDValue(InFP128, 0),
2573                                Lo64,
2574                                SubRegOdd);
2575   SDValue OutChains[2] = { SDValue(Hi64.getNode(), 1),
2576                            SDValue(Lo64.getNode(), 1) };
2577   SDValue OutChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2578                                  &OutChains[0], 2);
2579   SDValue Ops[2] = {SDValue(InFP128,0), OutChain};
2580   return DAG.getMergeValues(Ops, 2, dl);
2581 }
2582
2583 // Lower a f128 store into two f64 stores.
2584 static SDValue LowerF128Store(SDValue Op, SelectionDAG &DAG) {
2585   SDLoc dl(Op);
2586   StoreSDNode *StNode = dyn_cast<StoreSDNode>(Op.getNode());
2587   assert(StNode && StNode->getOffset().getOpcode() == ISD::UNDEF
2588          && "Unexpected node type");
2589   SDValue SubRegEven = DAG.getTargetConstant(SP::sub_even64, MVT::i32);
2590   SDValue SubRegOdd  = DAG.getTargetConstant(SP::sub_odd64, MVT::i32);
2591
2592   SDNode *Hi64 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG,
2593                                     dl,
2594                                     MVT::f64,
2595                                     StNode->getValue(),
2596                                     SubRegEven);
2597   SDNode *Lo64 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG,
2598                                     dl,
2599                                     MVT::f64,
2600                                     StNode->getValue(),
2601                                     SubRegOdd);
2602
2603   unsigned alignment = StNode->getAlignment();
2604   if (alignment > 8)
2605     alignment = 8;
2606
2607   SDValue OutChains[2];
2608   OutChains[0] = DAG.getStore(StNode->getChain(),
2609                               dl,
2610                               SDValue(Hi64, 0),
2611                               StNode->getBasePtr(),
2612                               MachinePointerInfo(),
2613                               false, false, alignment);
2614   EVT addrVT = StNode->getBasePtr().getValueType();
2615   SDValue LoPtr = DAG.getNode(ISD::ADD, dl, addrVT,
2616                               StNode->getBasePtr(),
2617                               DAG.getConstant(8, addrVT));
2618   OutChains[1] = DAG.getStore(StNode->getChain(),
2619                              dl,
2620                              SDValue(Lo64, 0),
2621                              LoPtr,
2622                              MachinePointerInfo(),
2623                              false, false, alignment);
2624   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2625                      &OutChains[0], 2);
2626 }
2627
2628 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG,
2629                          const SparcTargetLowering &TLI,
2630                          bool is64Bit) {
2631   if (Op.getValueType() == MVT::f64)
2632     return LowerF64Op(Op, DAG, ISD::FNEG);
2633   if (Op.getValueType() == MVT::f128)
2634     return TLI.LowerF128Op(Op, DAG, ((is64Bit) ? "_Qp_neg" : "_Q_neg"), 1);
2635   return Op;
2636 }
2637
2638 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG, bool isV9) {
2639   if (Op.getValueType() == MVT::f64)
2640     return LowerF64Op(Op, DAG, ISD::FABS);
2641   if (Op.getValueType() != MVT::f128)
2642     return Op;
2643
2644   // Lower fabs on f128 to fabs on f64
2645   // fabs f128 => fabs f64:sub_even64, fmov f64:sub_odd64
2646
2647   SDLoc dl(Op);
2648   SDValue SrcReg128 = Op.getOperand(0);
2649   SDValue Hi64 = DAG.getTargetExtractSubreg(SP::sub_even64, dl, MVT::f64,
2650                                             SrcReg128);
2651   SDValue Lo64 = DAG.getTargetExtractSubreg(SP::sub_odd64, dl, MVT::f64,
2652                                             SrcReg128);
2653   if (isV9)
2654     Hi64 = DAG.getNode(Op.getOpcode(), dl, MVT::f64, Hi64);
2655   else
2656     Hi64 = LowerF64Op(Hi64, DAG, ISD::FABS);
2657
2658   SDValue DstReg128 = SDValue(DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
2659                                                  dl, MVT::f128), 0);
2660   DstReg128 = DAG.getTargetInsertSubreg(SP::sub_even64, dl, MVT::f128,
2661                                         DstReg128, Hi64);
2662   DstReg128 = DAG.getTargetInsertSubreg(SP::sub_odd64, dl, MVT::f128,
2663                                         DstReg128, Lo64);
2664   return DstReg128;
2665 }
2666
2667 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2668
2669   if (Op.getValueType() != MVT::i64)
2670     return Op;
2671
2672   SDLoc dl(Op);
2673   SDValue Src1 = Op.getOperand(0);
2674   SDValue Src1Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src1);
2675   SDValue Src1Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Src1,
2676                                DAG.getConstant(32, MVT::i64));
2677   Src1Hi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src1Hi);
2678
2679   SDValue Src2 = Op.getOperand(1);
2680   SDValue Src2Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src2);
2681   SDValue Src2Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Src2,
2682                                DAG.getConstant(32, MVT::i64));
2683   Src2Hi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src2Hi);
2684
2685
2686   bool hasChain = false;
2687   unsigned hiOpc = Op.getOpcode();
2688   switch (Op.getOpcode()) {
2689   default: llvm_unreachable("Invalid opcode");
2690   case ISD::ADDC: hiOpc = ISD::ADDE; break;
2691   case ISD::ADDE: hasChain = true; break;
2692   case ISD::SUBC: hiOpc = ISD::SUBE; break;
2693   case ISD::SUBE: hasChain = true; break;
2694   }
2695   SDValue Lo;
2696   SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Glue);
2697   if (hasChain) {
2698     Lo = DAG.getNode(Op.getOpcode(), dl, VTs, Src1Lo, Src2Lo,
2699                      Op.getOperand(2));
2700   } else {
2701     Lo = DAG.getNode(Op.getOpcode(), dl, VTs, Src1Lo, Src2Lo);
2702   }
2703   SDValue Hi = DAG.getNode(hiOpc, dl, VTs, Src1Hi, Src2Hi, Lo.getValue(1));
2704   SDValue Carry = Hi.getValue(1);
2705
2706   Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Lo);
2707   Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Hi);
2708   Hi = DAG.getNode(ISD::SHL, dl, MVT::i64, Hi,
2709                    DAG.getConstant(32, MVT::i64));
2710
2711   SDValue Dst = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, Lo);
2712   SDValue Ops[2] = { Dst, Carry };
2713   return DAG.getMergeValues(Ops, 2, dl);
2714 }
2715
2716 // Custom lower UMULO/SMULO for SPARC. This code is similar to ExpandNode()
2717 // in LegalizeDAG.cpp except the order of arguments to the library function.
2718 static SDValue LowerUMULO_SMULO(SDValue Op, SelectionDAG &DAG,
2719                                 const SparcTargetLowering &TLI)
2720 {
2721   unsigned opcode = Op.getOpcode();
2722   assert((opcode == ISD::UMULO || opcode == ISD::SMULO) && "Invalid Opcode.");
2723
2724   bool isSigned = (opcode == ISD::SMULO);
2725   EVT VT = MVT::i64;
2726   EVT WideVT = MVT::i128;
2727   SDLoc dl(Op);
2728   SDValue LHS = Op.getOperand(0);
2729
2730   if (LHS.getValueType() != VT)
2731     return Op;
2732
2733   SDValue ShiftAmt = DAG.getConstant(63, VT);
2734
2735   SDValue RHS = Op.getOperand(1);
2736   SDValue HiLHS = DAG.getNode(ISD::SRA, dl, VT, LHS, ShiftAmt);
2737   SDValue HiRHS = DAG.getNode(ISD::SRA, dl, MVT::i64, RHS, ShiftAmt);
2738   SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
2739
2740   SDValue MulResult = TLI.makeLibCall(DAG,
2741                                       RTLIB::MUL_I128, WideVT,
2742                                       Args, 4, isSigned, dl).first;
2743   SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT,
2744                                    MulResult, DAG.getIntPtrConstant(0));
2745   SDValue TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT,
2746                                 MulResult, DAG.getIntPtrConstant(1));
2747   if (isSigned) {
2748     SDValue Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
2749     TopHalf = DAG.getSetCC(dl, MVT::i32, TopHalf, Tmp1, ISD::SETNE);
2750   } else {
2751     TopHalf = DAG.getSetCC(dl, MVT::i32, TopHalf, DAG.getConstant(0, VT),
2752                            ISD::SETNE);
2753   }
2754   // MulResult is a node with an illegal type. Because such things are not
2755   // generally permitted during this phase of legalization, delete the
2756   // node. The above EXTRACT_ELEMENT nodes should have been folded.
2757   DAG.DeleteNode(MulResult.getNode());
2758
2759   SDValue Ops[2] = { BottomHalf, TopHalf } ;
2760   return DAG.getMergeValues(Ops, 2, dl);
2761 }
2762
2763 static SDValue LowerATOMIC_LOAD_STORE(SDValue Op, SelectionDAG &DAG) {
2764   // Monotonic load/stores are legal.
2765   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
2766     return Op;
2767
2768   // Otherwise, expand with a fence.
2769   return SDValue();
2770 }
2771
2772
2773 SDValue SparcTargetLowering::
2774 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2775
2776   bool hasHardQuad = Subtarget->hasHardQuad();
2777   bool is64Bit     = Subtarget->is64Bit();
2778   bool isV9        = Subtarget->isV9();
2779
2780   switch (Op.getOpcode()) {
2781   default: llvm_unreachable("Should not custom lower this!");
2782
2783   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG, *this,
2784                                                        Subtarget);
2785   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG,
2786                                                       Subtarget);
2787   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
2788   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
2789   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
2790   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
2791   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG, *this,
2792                                                        hasHardQuad);
2793   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG, *this,
2794                                                        hasHardQuad);
2795   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG, *this,
2796                                                        hasHardQuad);
2797   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG, *this,
2798                                                        hasHardQuad);
2799   case ISD::BR_CC:              return LowerBR_CC(Op, DAG, *this,
2800                                                   hasHardQuad);
2801   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG, *this,
2802                                                       hasHardQuad);
2803   case ISD::VASTART:            return LowerVASTART(Op, DAG, *this);
2804   case ISD::VAARG:              return LowerVAARG(Op, DAG);
2805   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG,
2806                                                                Subtarget);
2807
2808   case ISD::LOAD:               return LowerF128Load(Op, DAG);
2809   case ISD::STORE:              return LowerF128Store(Op, DAG);
2810   case ISD::FADD:               return LowerF128Op(Op, DAG,
2811                                        getLibcallName(RTLIB::ADD_F128), 2);
2812   case ISD::FSUB:               return LowerF128Op(Op, DAG,
2813                                        getLibcallName(RTLIB::SUB_F128), 2);
2814   case ISD::FMUL:               return LowerF128Op(Op, DAG,
2815                                        getLibcallName(RTLIB::MUL_F128), 2);
2816   case ISD::FDIV:               return LowerF128Op(Op, DAG,
2817                                        getLibcallName(RTLIB::DIV_F128), 2);
2818   case ISD::FSQRT:              return LowerF128Op(Op, DAG,
2819                                        getLibcallName(RTLIB::SQRT_F128),1);
2820   case ISD::FNEG:               return LowerFNEG(Op, DAG, *this, is64Bit);
2821   case ISD::FABS:               return LowerFABS(Op, DAG, isV9);
2822   case ISD::FP_EXTEND:          return LowerF128_FPEXTEND(Op, DAG, *this);
2823   case ISD::FP_ROUND:           return LowerF128_FPROUND(Op, DAG, *this);
2824   case ISD::ADDC:
2825   case ISD::ADDE:
2826   case ISD::SUBC:
2827   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2828   case ISD::UMULO:
2829   case ISD::SMULO:              return LowerUMULO_SMULO(Op, DAG, *this);
2830   case ISD::ATOMIC_LOAD:
2831   case ISD::ATOMIC_STORE:       return LowerATOMIC_LOAD_STORE(Op, DAG);
2832   }
2833 }
2834
2835 MachineBasicBlock *
2836 SparcTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
2837                                                  MachineBasicBlock *BB) const {
2838   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
2839   unsigned BROpcode;
2840   unsigned CC;
2841   DebugLoc dl = MI->getDebugLoc();
2842   // Figure out the conditional branch opcode to use for this select_cc.
2843   switch (MI->getOpcode()) {
2844   default: llvm_unreachable("Unknown SELECT_CC!");
2845   case SP::SELECT_CC_Int_ICC:
2846   case SP::SELECT_CC_FP_ICC:
2847   case SP::SELECT_CC_DFP_ICC:
2848   case SP::SELECT_CC_QFP_ICC:
2849     BROpcode = SP::BCOND;
2850     break;
2851   case SP::SELECT_CC_Int_FCC:
2852   case SP::SELECT_CC_FP_FCC:
2853   case SP::SELECT_CC_DFP_FCC:
2854   case SP::SELECT_CC_QFP_FCC:
2855     BROpcode = SP::FBCOND;
2856     break;
2857   }
2858
2859   CC = (SPCC::CondCodes)MI->getOperand(3).getImm();
2860
2861   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
2862   // control-flow pattern.  The incoming instruction knows the destination vreg
2863   // to set, the condition code register to branch on, the true/false values to
2864   // select between, and a branch opcode to use.
2865   const BasicBlock *LLVM_BB = BB->getBasicBlock();
2866   MachineFunction::iterator It = BB;
2867   ++It;
2868
2869   //  thisMBB:
2870   //  ...
2871   //   TrueVal = ...
2872   //   [f]bCC copy1MBB
2873   //   fallthrough --> copy0MBB
2874   MachineBasicBlock *thisMBB = BB;
2875   MachineFunction *F = BB->getParent();
2876   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
2877   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
2878   F->insert(It, copy0MBB);
2879   F->insert(It, sinkMBB);
2880
2881   // Transfer the remainder of BB and its successor edges to sinkMBB.
2882   sinkMBB->splice(sinkMBB->begin(), BB,
2883                   llvm::next(MachineBasicBlock::iterator(MI)),
2884                   BB->end());
2885   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
2886
2887   // Add the true and fallthrough blocks as its successors.
2888   BB->addSuccessor(copy0MBB);
2889   BB->addSuccessor(sinkMBB);
2890
2891   BuildMI(BB, dl, TII.get(BROpcode)).addMBB(sinkMBB).addImm(CC);
2892
2893   //  copy0MBB:
2894   //   %FalseValue = ...
2895   //   # fallthrough to sinkMBB
2896   BB = copy0MBB;
2897
2898   // Update machine-CFG edges
2899   BB->addSuccessor(sinkMBB);
2900
2901   //  sinkMBB:
2902   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
2903   //  ...
2904   BB = sinkMBB;
2905   BuildMI(*BB, BB->begin(), dl, TII.get(SP::PHI), MI->getOperand(0).getReg())
2906     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
2907     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
2908
2909   MI->eraseFromParent();   // The pseudo instruction is gone now.
2910   return BB;
2911 }
2912
2913 //===----------------------------------------------------------------------===//
2914 //                         Sparc Inline Assembly Support
2915 //===----------------------------------------------------------------------===//
2916
2917 /// getConstraintType - Given a constraint letter, return the type of
2918 /// constraint it is for this target.
2919 SparcTargetLowering::ConstraintType
2920 SparcTargetLowering::getConstraintType(const std::string &Constraint) const {
2921   if (Constraint.size() == 1) {
2922     switch (Constraint[0]) {
2923     default:  break;
2924     case 'r': return C_RegisterClass;
2925     }
2926   }
2927
2928   return TargetLowering::getConstraintType(Constraint);
2929 }
2930
2931 std::pair<unsigned, const TargetRegisterClass*>
2932 SparcTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
2933                                                   MVT VT) const {
2934   if (Constraint.size() == 1) {
2935     switch (Constraint[0]) {
2936     case 'r':
2937       return std::make_pair(0U, &SP::IntRegsRegClass);
2938     }
2939   }
2940
2941   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2942 }
2943
2944 bool
2945 SparcTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2946   // The Sparc target isn't yet aware of offsets.
2947   return false;
2948 }
2949
2950 void SparcTargetLowering::ReplaceNodeResults(SDNode *N,
2951                                              SmallVectorImpl<SDValue>& Results,
2952                                              SelectionDAG &DAG) const {
2953
2954   SDLoc dl(N);
2955
2956   RTLIB::Libcall libCall = RTLIB::UNKNOWN_LIBCALL;
2957
2958   switch (N->getOpcode()) {
2959   default:
2960     llvm_unreachable("Do not know how to custom type legalize this operation!");
2961
2962   case ISD::FP_TO_SINT:
2963   case ISD::FP_TO_UINT:
2964     // Custom lower only if it involves f128 or i64.
2965     if (N->getOperand(0).getValueType() != MVT::f128
2966         || N->getValueType(0) != MVT::i64)
2967       return;
2968     libCall = ((N->getOpcode() == ISD::FP_TO_SINT)
2969                ? RTLIB::FPTOSINT_F128_I64
2970                : RTLIB::FPTOUINT_F128_I64);
2971
2972     Results.push_back(LowerF128Op(SDValue(N, 0),
2973                                   DAG,
2974                                   getLibcallName(libCall),
2975                                   1));
2976     return;
2977
2978   case ISD::SINT_TO_FP:
2979   case ISD::UINT_TO_FP:
2980     // Custom lower only if it involves f128 or i64.
2981     if (N->getValueType(0) != MVT::f128
2982         || N->getOperand(0).getValueType() != MVT::i64)
2983       return;
2984
2985     libCall = ((N->getOpcode() == ISD::SINT_TO_FP)
2986                ? RTLIB::SINTTOFP_I64_F128
2987                : RTLIB::UINTTOFP_I64_F128);
2988
2989     Results.push_back(LowerF128Op(SDValue(N, 0),
2990                                   DAG,
2991                                   getLibcallName(libCall),
2992                                   1));
2993     return;
2994   }
2995 }