SparcISelLowering.cpp revision 0b8c9a80f20772c3793201ab5b251d3520b9cea3
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 "SparcTargetMachine.h"
18#include "llvm/CodeGen/CallingConvLower.h"
19#include "llvm/CodeGen/MachineFrameInfo.h"
20#include "llvm/CodeGen/MachineFunction.h"
21#include "llvm/CodeGen/MachineInstrBuilder.h"
22#include "llvm/CodeGen/MachineRegisterInfo.h"
23#include "llvm/CodeGen/SelectionDAG.h"
24#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
25#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/Module.h"
28#include "llvm/Support/ErrorHandling.h"
29using namespace llvm;
30
31
32//===----------------------------------------------------------------------===//
33// Calling Convention Implementation
34//===----------------------------------------------------------------------===//
35
36static bool CC_Sparc_Assign_SRet(unsigned &ValNo, MVT &ValVT,
37                                 MVT &LocVT, CCValAssign::LocInfo &LocInfo,
38                                 ISD::ArgFlagsTy &ArgFlags, CCState &State)
39{
40  assert (ArgFlags.isSRet());
41
42  //Assign SRet argument
43  State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
44                                         0,
45                                         LocVT, LocInfo));
46  return true;
47}
48
49static bool CC_Sparc_Assign_f64(unsigned &ValNo, MVT &ValVT,
50                                MVT &LocVT, CCValAssign::LocInfo &LocInfo,
51                                ISD::ArgFlagsTy &ArgFlags, CCState &State)
52{
53  static const uint16_t RegList[] = {
54    SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
55  };
56  //Try to get first reg
57  if (unsigned Reg = State.AllocateReg(RegList, 6)) {
58    State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
59  } else {
60    //Assign whole thing in stack
61    State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
62                                           State.AllocateStack(8,4),
63                                           LocVT, LocInfo));
64    return true;
65  }
66
67  //Try to get second reg
68  if (unsigned Reg = State.AllocateReg(RegList, 6))
69    State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
70  else
71    State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
72                                           State.AllocateStack(4,4),
73                                           LocVT, LocInfo));
74  return true;
75}
76
77#include "SparcGenCallingConv.inc"
78
79SDValue
80SparcTargetLowering::LowerReturn(SDValue Chain,
81                                 CallingConv::ID CallConv, bool isVarArg,
82                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
83                                 const SmallVectorImpl<SDValue> &OutVals,
84                                 DebugLoc dl, SelectionDAG &DAG) const {
85
86  MachineFunction &MF = DAG.getMachineFunction();
87
88  // CCValAssign - represent the assignment of the return value to locations.
89  SmallVector<CCValAssign, 16> RVLocs;
90
91  // CCState - Info about the registers and stack slot.
92  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
93                 DAG.getTarget(), RVLocs, *DAG.getContext());
94
95  // Analize return values.
96  CCInfo.AnalyzeReturn(Outs, RetCC_Sparc32);
97
98  // If this is the first return lowered for this function, add the regs to the
99  // liveout set for the function.
100  if (MF.getRegInfo().liveout_empty()) {
101    for (unsigned i = 0; i != RVLocs.size(); ++i)
102      if (RVLocs[i].isRegLoc())
103        MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
104  }
105
106  SDValue Flag;
107
108  // Copy the result values into the output registers.
109  for (unsigned i = 0; i != RVLocs.size(); ++i) {
110    CCValAssign &VA = RVLocs[i];
111    assert(VA.isRegLoc() && "Can only return in registers!");
112
113    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
114                             OutVals[i], Flag);
115
116    // Guarantee that all emitted copies are stuck together with flags.
117    Flag = Chain.getValue(1);
118  }
119
120  unsigned RetAddrOffset = 8; //Call Inst + Delay Slot
121  // If the function returns a struct, copy the SRetReturnReg to I0
122  if (MF.getFunction()->hasStructRetAttr()) {
123    SparcMachineFunctionInfo *SFI = MF.getInfo<SparcMachineFunctionInfo>();
124    unsigned Reg = SFI->getSRetReturnReg();
125    if (!Reg)
126      llvm_unreachable("sret virtual register not created in the entry block");
127    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
128    Chain = DAG.getCopyToReg(Chain, dl, SP::I0, Val, Flag);
129    Flag = Chain.getValue(1);
130    if (MF.getRegInfo().liveout_empty())
131      MF.getRegInfo().addLiveOut(SP::I0);
132    RetAddrOffset = 12; // CallInst + Delay Slot + Unimp
133  }
134
135  SDValue RetAddrOffsetNode = DAG.getConstant(RetAddrOffset, MVT::i32);
136
137  if (Flag.getNode())
138    return DAG.getNode(SPISD::RET_FLAG, dl, MVT::Other, Chain,
139                       RetAddrOffsetNode, Flag);
140  return DAG.getNode(SPISD::RET_FLAG, dl, MVT::Other, Chain,
141                     RetAddrOffsetNode);
142}
143
144/// LowerFormalArguments - V8 uses a very simple ABI, where all values are
145/// passed in either one or two GPRs, including FP values.  TODO: we should
146/// pass FP values in FP registers for fastcc functions.
147SDValue
148SparcTargetLowering::LowerFormalArguments(SDValue Chain,
149                                          CallingConv::ID CallConv, bool isVarArg,
150                                          const SmallVectorImpl<ISD::InputArg>
151                                            &Ins,
152                                          DebugLoc dl, SelectionDAG &DAG,
153                                          SmallVectorImpl<SDValue> &InVals)
154                                            const {
155
156  MachineFunction &MF = DAG.getMachineFunction();
157  MachineRegisterInfo &RegInfo = MF.getRegInfo();
158  SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
159
160  // Assign locations to all of the incoming arguments.
161  SmallVector<CCValAssign, 16> ArgLocs;
162  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
163                 getTargetMachine(), ArgLocs, *DAG.getContext());
164  CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc32);
165
166  const unsigned StackOffset = 92;
167
168  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
169    CCValAssign &VA = ArgLocs[i];
170
171    if (i == 0  && Ins[i].Flags.isSRet()) {
172      //Get SRet from [%fp+64]
173      int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, 64, true);
174      SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
175      SDValue Arg = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
176                                MachinePointerInfo(),
177                                false, false, false, 0);
178      InVals.push_back(Arg);
179      continue;
180    }
181
182    if (VA.isRegLoc()) {
183      if (VA.needsCustom()) {
184        assert(VA.getLocVT() == MVT::f64);
185        unsigned VRegHi = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
186        MF.getRegInfo().addLiveIn(VA.getLocReg(), VRegHi);
187        SDValue HiVal = DAG.getCopyFromReg(Chain, dl, VRegHi, MVT::i32);
188
189        assert(i+1 < e);
190        CCValAssign &NextVA = ArgLocs[++i];
191
192        SDValue LoVal;
193        if (NextVA.isMemLoc()) {
194          int FrameIdx = MF.getFrameInfo()->
195            CreateFixedObject(4, StackOffset+NextVA.getLocMemOffset(),true);
196          SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
197          LoVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
198                              MachinePointerInfo(),
199                              false, false, false, 0);
200        } else {
201          unsigned loReg = MF.addLiveIn(NextVA.getLocReg(),
202                                        &SP::IntRegsRegClass);
203          LoVal = DAG.getCopyFromReg(Chain, dl, loReg, MVT::i32);
204        }
205        SDValue WholeValue =
206          DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
207        WholeValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, WholeValue);
208        InVals.push_back(WholeValue);
209        continue;
210      }
211      unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
212      MF.getRegInfo().addLiveIn(VA.getLocReg(), VReg);
213      SDValue Arg = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
214      if (VA.getLocVT() == MVT::f32)
215        Arg = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Arg);
216      else if (VA.getLocVT() != MVT::i32) {
217        Arg = DAG.getNode(ISD::AssertSext, dl, MVT::i32, Arg,
218                          DAG.getValueType(VA.getLocVT()));
219        Arg = DAG.getNode(ISD::TRUNCATE, dl, VA.getLocVT(), Arg);
220      }
221      InVals.push_back(Arg);
222      continue;
223    }
224
225    assert(VA.isMemLoc());
226
227    unsigned Offset = VA.getLocMemOffset()+StackOffset;
228
229    if (VA.needsCustom()) {
230      assert(VA.getValVT() == MVT::f64);
231      //If it is double-word aligned, just load.
232      if (Offset % 8 == 0) {
233        int FI = MF.getFrameInfo()->CreateFixedObject(8,
234                                                      Offset,
235                                                      true);
236        SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
237        SDValue Load = DAG.getLoad(VA.getValVT(), dl, Chain, FIPtr,
238                                   MachinePointerInfo(),
239                                   false,false, false, 0);
240        InVals.push_back(Load);
241        continue;
242      }
243
244      int FI = MF.getFrameInfo()->CreateFixedObject(4,
245                                                    Offset,
246                                                    true);
247      SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
248      SDValue HiVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
249                                  MachinePointerInfo(),
250                                  false, false, false, 0);
251      int FI2 = MF.getFrameInfo()->CreateFixedObject(4,
252                                                     Offset+4,
253                                                     true);
254      SDValue FIPtr2 = DAG.getFrameIndex(FI2, getPointerTy());
255
256      SDValue LoVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr2,
257                                  MachinePointerInfo(),
258                                  false, false, false, 0);
259
260      SDValue WholeValue =
261        DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
262      WholeValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, WholeValue);
263      InVals.push_back(WholeValue);
264      continue;
265    }
266
267    int FI = MF.getFrameInfo()->CreateFixedObject(4,
268                                                  Offset,
269                                                  true);
270    SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
271    SDValue Load ;
272    if (VA.getValVT() == MVT::i32 || VA.getValVT() == MVT::f32) {
273      Load = DAG.getLoad(VA.getValVT(), dl, Chain, FIPtr,
274                         MachinePointerInfo(),
275                         false, false, false, 0);
276    } else {
277      ISD::LoadExtType LoadOp = ISD::SEXTLOAD;
278      // Sparc is big endian, so add an offset based on the ObjectVT.
279      unsigned Offset = 4-std::max(1U, VA.getValVT().getSizeInBits()/8);
280      FIPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIPtr,
281                          DAG.getConstant(Offset, MVT::i32));
282      Load = DAG.getExtLoad(LoadOp, dl, MVT::i32, Chain, FIPtr,
283                            MachinePointerInfo(),
284                            VA.getValVT(), false, false,0);
285      Load = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Load);
286    }
287    InVals.push_back(Load);
288  }
289
290  if (MF.getFunction()->hasStructRetAttr()) {
291    //Copy the SRet Argument to SRetReturnReg
292    SparcMachineFunctionInfo *SFI = MF.getInfo<SparcMachineFunctionInfo>();
293    unsigned Reg = SFI->getSRetReturnReg();
294    if (!Reg) {
295      Reg = MF.getRegInfo().createVirtualRegister(&SP::IntRegsRegClass);
296      SFI->setSRetReturnReg(Reg);
297    }
298    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
299    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
300  }
301
302  // Store remaining ArgRegs to the stack if this is a varargs function.
303  if (isVarArg) {
304    static const uint16_t ArgRegs[] = {
305      SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
306    };
307    unsigned NumAllocated = CCInfo.getFirstUnallocated(ArgRegs, 6);
308    const uint16_t *CurArgReg = ArgRegs+NumAllocated, *ArgRegEnd = ArgRegs+6;
309    unsigned ArgOffset = CCInfo.getNextStackOffset();
310    if (NumAllocated == 6)
311      ArgOffset += StackOffset;
312    else {
313      assert(!ArgOffset);
314      ArgOffset = 68+4*NumAllocated;
315    }
316
317    // Remember the vararg offset for the va_start implementation.
318    FuncInfo->setVarArgsFrameOffset(ArgOffset);
319
320    std::vector<SDValue> OutChains;
321
322    for (; CurArgReg != ArgRegEnd; ++CurArgReg) {
323      unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
324      MF.getRegInfo().addLiveIn(*CurArgReg, VReg);
325      SDValue Arg = DAG.getCopyFromReg(DAG.getRoot(), dl, VReg, MVT::i32);
326
327      int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
328                                                          true);
329      SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
330
331      OutChains.push_back(DAG.getStore(DAG.getRoot(), dl, Arg, FIPtr,
332                                       MachinePointerInfo(),
333                                       false, false, 0));
334      ArgOffset += 4;
335    }
336
337    if (!OutChains.empty()) {
338      OutChains.push_back(Chain);
339      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
340                          &OutChains[0], OutChains.size());
341    }
342  }
343
344  return Chain;
345}
346
347SDValue
348SparcTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
349                               SmallVectorImpl<SDValue> &InVals) const {
350  SelectionDAG &DAG                     = CLI.DAG;
351  DebugLoc &dl                          = CLI.DL;
352  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
353  SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
354  SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
355  SDValue Chain                         = CLI.Chain;
356  SDValue Callee                        = CLI.Callee;
357  bool &isTailCall                      = CLI.IsTailCall;
358  CallingConv::ID CallConv              = CLI.CallConv;
359  bool isVarArg                         = CLI.IsVarArg;
360
361  // Sparc target does not yet support tail call optimization.
362  isTailCall = false;
363
364  // Analyze operands of the call, assigning locations to each operand.
365  SmallVector<CCValAssign, 16> ArgLocs;
366  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
367                 DAG.getTarget(), ArgLocs, *DAG.getContext());
368  CCInfo.AnalyzeCallOperands(Outs, CC_Sparc32);
369
370  // Get the size of the outgoing arguments stack space requirement.
371  unsigned ArgsSize = CCInfo.getNextStackOffset();
372
373  // Keep stack frames 8-byte aligned.
374  ArgsSize = (ArgsSize+7) & ~7;
375
376  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
377
378  //Create local copies for byval args.
379  SmallVector<SDValue, 8> ByValArgs;
380  for (unsigned i = 0,  e = Outs.size(); i != e; ++i) {
381    ISD::ArgFlagsTy Flags = Outs[i].Flags;
382    if (!Flags.isByVal())
383      continue;
384
385    SDValue Arg = OutVals[i];
386    unsigned Size = Flags.getByValSize();
387    unsigned Align = Flags.getByValAlign();
388
389    int FI = MFI->CreateStackObject(Size, Align, false);
390    SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
391    SDValue SizeNode = DAG.getConstant(Size, MVT::i32);
392
393    Chain = DAG.getMemcpy(Chain, dl, FIPtr, Arg, SizeNode, Align,
394                          false,        //isVolatile,
395                          (Size <= 32), //AlwaysInline if size <= 32
396                          MachinePointerInfo(), MachinePointerInfo());
397    ByValArgs.push_back(FIPtr);
398  }
399
400  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(ArgsSize, true));
401
402  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
403  SmallVector<SDValue, 8> MemOpChains;
404
405  const unsigned StackOffset = 92;
406  bool hasStructRetAttr = false;
407  // Walk the register/memloc assignments, inserting copies/loads.
408  for (unsigned i = 0, realArgIdx = 0, byvalArgIdx = 0, e = ArgLocs.size();
409       i != e;
410       ++i, ++realArgIdx) {
411    CCValAssign &VA = ArgLocs[i];
412    SDValue Arg = OutVals[realArgIdx];
413
414    ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
415
416    //Use local copy if it is a byval arg.
417    if (Flags.isByVal())
418      Arg = ByValArgs[byvalArgIdx++];
419
420    // Promote the value if needed.
421    switch (VA.getLocInfo()) {
422    default: llvm_unreachable("Unknown loc info!");
423    case CCValAssign::Full: break;
424    case CCValAssign::SExt:
425      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
426      break;
427    case CCValAssign::ZExt:
428      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
429      break;
430    case CCValAssign::AExt:
431      Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
432      break;
433    case CCValAssign::BCvt:
434      Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
435      break;
436    }
437
438    if (Flags.isSRet()) {
439      assert(VA.needsCustom());
440      // store SRet argument in %sp+64
441      SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
442      SDValue PtrOff = DAG.getIntPtrConstant(64);
443      PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
444      MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
445                                         MachinePointerInfo(),
446                                         false, false, 0));
447      hasStructRetAttr = true;
448      continue;
449    }
450
451    if (VA.needsCustom()) {
452      assert(VA.getLocVT() == MVT::f64);
453
454      if (VA.isMemLoc()) {
455        unsigned Offset = VA.getLocMemOffset() + StackOffset;
456        //if it is double-word aligned, just store.
457        if (Offset % 8 == 0) {
458          SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
459          SDValue PtrOff = DAG.getIntPtrConstant(Offset);
460          PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
461          MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
462                                             MachinePointerInfo(),
463                                             false, false, 0));
464          continue;
465        }
466      }
467
468      SDValue StackPtr = DAG.CreateStackTemporary(MVT::f64, MVT::i32);
469      SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
470                                   Arg, StackPtr, MachinePointerInfo(),
471                                   false, false, 0);
472      // Sparc is big-endian, so the high part comes first.
473      SDValue Hi = DAG.getLoad(MVT::i32, dl, Store, StackPtr,
474                               MachinePointerInfo(), false, false, false, 0);
475      // Increment the pointer to the other half.
476      StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
477                             DAG.getIntPtrConstant(4));
478      // Load the low part.
479      SDValue Lo = DAG.getLoad(MVT::i32, dl, Store, StackPtr,
480                               MachinePointerInfo(), false, false, false, 0);
481
482      if (VA.isRegLoc()) {
483        RegsToPass.push_back(std::make_pair(VA.getLocReg(), Hi));
484        assert(i+1 != e);
485        CCValAssign &NextVA = ArgLocs[++i];
486        if (NextVA.isRegLoc()) {
487          RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Lo));
488        } else {
489          //Store the low part in stack.
490          unsigned Offset = NextVA.getLocMemOffset() + StackOffset;
491          SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
492          SDValue PtrOff = DAG.getIntPtrConstant(Offset);
493          PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
494          MemOpChains.push_back(DAG.getStore(Chain, dl, Lo, PtrOff,
495                                             MachinePointerInfo(),
496                                             false, false, 0));
497        }
498      } else {
499        unsigned Offset = VA.getLocMemOffset() + StackOffset;
500        // Store the high part.
501        SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
502        SDValue PtrOff = DAG.getIntPtrConstant(Offset);
503        PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
504        MemOpChains.push_back(DAG.getStore(Chain, dl, Hi, PtrOff,
505                                           MachinePointerInfo(),
506                                           false, false, 0));
507        // Store the low part.
508        PtrOff = DAG.getIntPtrConstant(Offset+4);
509        PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
510        MemOpChains.push_back(DAG.getStore(Chain, dl, Lo, PtrOff,
511                                           MachinePointerInfo(),
512                                           false, false, 0));
513      }
514      continue;
515    }
516
517    // Arguments that can be passed on register must be kept at
518    // RegsToPass vector
519    if (VA.isRegLoc()) {
520      if (VA.getLocVT() != MVT::f32) {
521        RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
522        continue;
523      }
524      Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
525      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
526      continue;
527    }
528
529    assert(VA.isMemLoc());
530
531    // Create a store off the stack pointer for this argument.
532    SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
533    SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset()+StackOffset);
534    PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
535    MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
536                                       MachinePointerInfo(),
537                                       false, false, 0));
538  }
539
540
541  // Emit all stores, make sure the occur before any copies into physregs.
542  if (!MemOpChains.empty())
543    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
544                        &MemOpChains[0], MemOpChains.size());
545
546  // Build a sequence of copy-to-reg nodes chained together with token
547  // chain and flag operands which copy the outgoing args into registers.
548  // The InFlag in necessary since all emitted instructions must be
549  // stuck together.
550  SDValue InFlag;
551  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
552    unsigned Reg = RegsToPass[i].first;
553    // Remap I0->I7 -> O0->O7.
554    if (Reg >= SP::I0 && Reg <= SP::I7)
555      Reg = Reg-SP::I0+SP::O0;
556
557    Chain = DAG.getCopyToReg(Chain, dl, Reg, RegsToPass[i].second, InFlag);
558    InFlag = Chain.getValue(1);
559  }
560
561  unsigned SRetArgSize = (hasStructRetAttr)? getSRetArgSize(DAG, Callee):0;
562
563  // If the callee is a GlobalAddress node (quite common, every direct call is)
564  // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
565  // Likewise ExternalSymbol -> TargetExternalSymbol.
566  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
567    Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
568  else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
569    Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
570
571  // Returns a chain & a flag for retval copy to use
572  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
573  SmallVector<SDValue, 8> Ops;
574  Ops.push_back(Chain);
575  Ops.push_back(Callee);
576  if (hasStructRetAttr)
577    Ops.push_back(DAG.getTargetConstant(SRetArgSize, MVT::i32));
578  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
579    unsigned Reg = RegsToPass[i].first;
580    if (Reg >= SP::I0 && Reg <= SP::I7)
581      Reg = Reg-SP::I0+SP::O0;
582
583    Ops.push_back(DAG.getRegister(Reg, RegsToPass[i].second.getValueType()));
584  }
585  if (InFlag.getNode())
586    Ops.push_back(InFlag);
587
588  Chain = DAG.getNode(SPISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
589  InFlag = Chain.getValue(1);
590
591  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, true),
592                             DAG.getIntPtrConstant(0, true), InFlag);
593  InFlag = Chain.getValue(1);
594
595  // Assign locations to each value returned by this call.
596  SmallVector<CCValAssign, 16> RVLocs;
597  CCState RVInfo(CallConv, isVarArg, DAG.getMachineFunction(),
598                 DAG.getTarget(), RVLocs, *DAG.getContext());
599
600  RVInfo.AnalyzeCallResult(Ins, RetCC_Sparc32);
601
602  // Copy all of the result registers out of their specified physreg.
603  for (unsigned i = 0; i != RVLocs.size(); ++i) {
604    unsigned Reg = RVLocs[i].getLocReg();
605
606    // Remap I0->I7 -> O0->O7.
607    if (Reg >= SP::I0 && Reg <= SP::I7)
608      Reg = Reg-SP::I0+SP::O0;
609
610    Chain = DAG.getCopyFromReg(Chain, dl, Reg,
611                               RVLocs[i].getValVT(), InFlag).getValue(1);
612    InFlag = Chain.getValue(2);
613    InVals.push_back(Chain.getValue(0));
614  }
615
616  return Chain;
617}
618
619unsigned
620SparcTargetLowering::getSRetArgSize(SelectionDAG &DAG, SDValue Callee) const
621{
622  const Function *CalleeFn = 0;
623  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
624    CalleeFn = dyn_cast<Function>(G->getGlobal());
625  } else if (ExternalSymbolSDNode *E =
626             dyn_cast<ExternalSymbolSDNode>(Callee)) {
627    const Function *Fn = DAG.getMachineFunction().getFunction();
628    const Module *M = Fn->getParent();
629    CalleeFn = M->getFunction(E->getSymbol());
630  }
631
632  if (!CalleeFn)
633    return 0;
634
635  assert(CalleeFn->hasStructRetAttr() &&
636         "Callee does not have the StructRet attribute.");
637
638  PointerType *Ty = cast<PointerType>(CalleeFn->arg_begin()->getType());
639  Type *ElementTy = Ty->getElementType();
640  return getDataLayout()->getTypeAllocSize(ElementTy);
641}
642
643//===----------------------------------------------------------------------===//
644// TargetLowering Implementation
645//===----------------------------------------------------------------------===//
646
647/// IntCondCCodeToICC - Convert a DAG integer condition code to a SPARC ICC
648/// condition.
649static SPCC::CondCodes IntCondCCodeToICC(ISD::CondCode CC) {
650  switch (CC) {
651  default: llvm_unreachable("Unknown integer condition code!");
652  case ISD::SETEQ:  return SPCC::ICC_E;
653  case ISD::SETNE:  return SPCC::ICC_NE;
654  case ISD::SETLT:  return SPCC::ICC_L;
655  case ISD::SETGT:  return SPCC::ICC_G;
656  case ISD::SETLE:  return SPCC::ICC_LE;
657  case ISD::SETGE:  return SPCC::ICC_GE;
658  case ISD::SETULT: return SPCC::ICC_CS;
659  case ISD::SETULE: return SPCC::ICC_LEU;
660  case ISD::SETUGT: return SPCC::ICC_GU;
661  case ISD::SETUGE: return SPCC::ICC_CC;
662  }
663}
664
665/// FPCondCCodeToFCC - Convert a DAG floatingp oint condition code to a SPARC
666/// FCC condition.
667static SPCC::CondCodes FPCondCCodeToFCC(ISD::CondCode CC) {
668  switch (CC) {
669  default: llvm_unreachable("Unknown fp condition code!");
670  case ISD::SETEQ:
671  case ISD::SETOEQ: return SPCC::FCC_E;
672  case ISD::SETNE:
673  case ISD::SETUNE: return SPCC::FCC_NE;
674  case ISD::SETLT:
675  case ISD::SETOLT: return SPCC::FCC_L;
676  case ISD::SETGT:
677  case ISD::SETOGT: return SPCC::FCC_G;
678  case ISD::SETLE:
679  case ISD::SETOLE: return SPCC::FCC_LE;
680  case ISD::SETGE:
681  case ISD::SETOGE: return SPCC::FCC_GE;
682  case ISD::SETULT: return SPCC::FCC_UL;
683  case ISD::SETULE: return SPCC::FCC_ULE;
684  case ISD::SETUGT: return SPCC::FCC_UG;
685  case ISD::SETUGE: return SPCC::FCC_UGE;
686  case ISD::SETUO:  return SPCC::FCC_U;
687  case ISD::SETO:   return SPCC::FCC_O;
688  case ISD::SETONE: return SPCC::FCC_LG;
689  case ISD::SETUEQ: return SPCC::FCC_UE;
690  }
691}
692
693SparcTargetLowering::SparcTargetLowering(TargetMachine &TM)
694  : TargetLowering(TM, new TargetLoweringObjectFileELF()) {
695
696  // Set up the register classes.
697  addRegisterClass(MVT::i32, &SP::IntRegsRegClass);
698  addRegisterClass(MVT::f32, &SP::FPRegsRegClass);
699  addRegisterClass(MVT::f64, &SP::DFPRegsRegClass);
700
701  // Turn FP extload into load/fextend
702  setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
703  // Sparc doesn't have i1 sign extending load
704  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
705  // Turn FP truncstore into trunc + store.
706  setTruncStoreAction(MVT::f64, MVT::f32, Expand);
707
708  // Custom legalize GlobalAddress nodes into LO/HI parts.
709  setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
710  setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
711  setOperationAction(ISD::ConstantPool , MVT::i32, Custom);
712
713  // Sparc doesn't have sext_inreg, replace them with shl/sra
714  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
715  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
716  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
717
718  // Sparc has no REM or DIVREM operations.
719  setOperationAction(ISD::UREM, MVT::i32, Expand);
720  setOperationAction(ISD::SREM, MVT::i32, Expand);
721  setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
722  setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
723
724  // Custom expand fp<->sint
725  setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
726  setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
727
728  // Expand fp<->uint
729  setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
730  setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
731
732  setOperationAction(ISD::BITCAST, MVT::f32, Expand);
733  setOperationAction(ISD::BITCAST, MVT::i32, Expand);
734
735  // Sparc has no select or setcc: expand to SELECT_CC.
736  setOperationAction(ISD::SELECT, MVT::i32, Expand);
737  setOperationAction(ISD::SELECT, MVT::f32, Expand);
738  setOperationAction(ISD::SELECT, MVT::f64, Expand);
739  setOperationAction(ISD::SETCC, MVT::i32, Expand);
740  setOperationAction(ISD::SETCC, MVT::f32, Expand);
741  setOperationAction(ISD::SETCC, MVT::f64, Expand);
742
743  // Sparc doesn't have BRCOND either, it has BR_CC.
744  setOperationAction(ISD::BRCOND, MVT::Other, Expand);
745  setOperationAction(ISD::BRIND, MVT::Other, Expand);
746  setOperationAction(ISD::BR_JT, MVT::Other, Expand);
747  setOperationAction(ISD::BR_CC, MVT::i32, Custom);
748  setOperationAction(ISD::BR_CC, MVT::f32, Custom);
749  setOperationAction(ISD::BR_CC, MVT::f64, Custom);
750
751  setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
752  setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
753  setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
754
755  // FIXME: There are instructions available for ATOMIC_FENCE
756  // on SparcV8 and later.
757  setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
758  setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
759
760  setOperationAction(ISD::FSIN , MVT::f64, Expand);
761  setOperationAction(ISD::FCOS , MVT::f64, Expand);
762  setOperationAction(ISD::FREM , MVT::f64, Expand);
763  setOperationAction(ISD::FMA  , MVT::f64, Expand);
764  setOperationAction(ISD::FSIN , MVT::f32, Expand);
765  setOperationAction(ISD::FCOS , MVT::f32, Expand);
766  setOperationAction(ISD::FREM , MVT::f32, Expand);
767  setOperationAction(ISD::FMA  , MVT::f32, Expand);
768  setOperationAction(ISD::CTPOP, MVT::i32, Expand);
769  setOperationAction(ISD::CTTZ , MVT::i32, Expand);
770  setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
771  setOperationAction(ISD::CTLZ , MVT::i32, Expand);
772  setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
773  setOperationAction(ISD::ROTL , MVT::i32, Expand);
774  setOperationAction(ISD::ROTR , MVT::i32, Expand);
775  setOperationAction(ISD::BSWAP, MVT::i32, Expand);
776  setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
777  setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
778  setOperationAction(ISD::FPOW , MVT::f64, Expand);
779  setOperationAction(ISD::FPOW , MVT::f32, Expand);
780
781  setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
782  setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
783  setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
784
785  // FIXME: Sparc provides these multiplies, but we don't have them yet.
786  setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
787  setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
788
789  setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
790
791  // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
792  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
793  // VAARG needs to be lowered to not do unaligned accesses for doubles.
794  setOperationAction(ISD::VAARG             , MVT::Other, Custom);
795
796  // Use the default implementation.
797  setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
798  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
799  setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
800  setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
801  setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
802
803  // No debug info support yet.
804  setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
805
806  setStackPointerRegisterToSaveRestore(SP::O6);
807
808  if (TM.getSubtarget<SparcSubtarget>().isV9())
809    setOperationAction(ISD::CTPOP, MVT::i32, Legal);
810
811  setMinFunctionAlignment(2);
812
813  computeRegisterProperties();
814}
815
816const char *SparcTargetLowering::getTargetNodeName(unsigned Opcode) const {
817  switch (Opcode) {
818  default: return 0;
819  case SPISD::CMPICC:     return "SPISD::CMPICC";
820  case SPISD::CMPFCC:     return "SPISD::CMPFCC";
821  case SPISD::BRICC:      return "SPISD::BRICC";
822  case SPISD::BRFCC:      return "SPISD::BRFCC";
823  case SPISD::SELECT_ICC: return "SPISD::SELECT_ICC";
824  case SPISD::SELECT_FCC: return "SPISD::SELECT_FCC";
825  case SPISD::Hi:         return "SPISD::Hi";
826  case SPISD::Lo:         return "SPISD::Lo";
827  case SPISD::FTOI:       return "SPISD::FTOI";
828  case SPISD::ITOF:       return "SPISD::ITOF";
829  case SPISD::CALL:       return "SPISD::CALL";
830  case SPISD::RET_FLAG:   return "SPISD::RET_FLAG";
831  case SPISD::GLOBAL_BASE_REG: return "SPISD::GLOBAL_BASE_REG";
832  case SPISD::FLUSHW:     return "SPISD::FLUSHW";
833  }
834}
835
836/// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
837/// be zero. Op is expected to be a target specific node. Used by DAG
838/// combiner.
839void SparcTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
840                                                         APInt &KnownZero,
841                                                         APInt &KnownOne,
842                                                         const SelectionDAG &DAG,
843                                                         unsigned Depth) const {
844  APInt KnownZero2, KnownOne2;
845  KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
846
847  switch (Op.getOpcode()) {
848  default: break;
849  case SPISD::SELECT_ICC:
850  case SPISD::SELECT_FCC:
851    DAG.ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
852    DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
853    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
854    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
855
856    // Only known if known in both the LHS and RHS.
857    KnownOne &= KnownOne2;
858    KnownZero &= KnownZero2;
859    break;
860  }
861}
862
863// Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
864// set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
865static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
866                             ISD::CondCode CC, unsigned &SPCC) {
867  if (isa<ConstantSDNode>(RHS) &&
868      cast<ConstantSDNode>(RHS)->isNullValue() &&
869      CC == ISD::SETNE &&
870      ((LHS.getOpcode() == SPISD::SELECT_ICC &&
871        LHS.getOperand(3).getOpcode() == SPISD::CMPICC) ||
872       (LHS.getOpcode() == SPISD::SELECT_FCC &&
873        LHS.getOperand(3).getOpcode() == SPISD::CMPFCC)) &&
874      isa<ConstantSDNode>(LHS.getOperand(0)) &&
875      isa<ConstantSDNode>(LHS.getOperand(1)) &&
876      cast<ConstantSDNode>(LHS.getOperand(0))->isOne() &&
877      cast<ConstantSDNode>(LHS.getOperand(1))->isNullValue()) {
878    SDValue CMPCC = LHS.getOperand(3);
879    SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
880    LHS = CMPCC.getOperand(0);
881    RHS = CMPCC.getOperand(1);
882  }
883}
884
885SDValue SparcTargetLowering::LowerGlobalAddress(SDValue Op,
886                                                SelectionDAG &DAG) const {
887  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
888  // FIXME there isn't really any debug info here
889  DebugLoc dl = Op.getDebugLoc();
890  SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
891  SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, GA);
892  SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, GA);
893
894  if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
895    return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
896
897  SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
898                                   getPointerTy());
899  SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
900  SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
901                                GlobalBase, RelAddr);
902  return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
903                     AbsAddr, MachinePointerInfo(), false, false, false, 0);
904}
905
906SDValue SparcTargetLowering::LowerConstantPool(SDValue Op,
907                                               SelectionDAG &DAG) const {
908  ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
909  // FIXME there isn't really any debug info here
910  DebugLoc dl = Op.getDebugLoc();
911  const Constant *C = N->getConstVal();
912  SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment());
913  SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, CP);
914  SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, CP);
915  if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
916    return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
917
918  SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
919                                   getPointerTy());
920  SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
921  SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
922                                GlobalBase, RelAddr);
923  return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
924                     AbsAddr, MachinePointerInfo(), false, false, false, 0);
925}
926
927static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
928  DebugLoc dl = Op.getDebugLoc();
929  // Convert the fp value to integer in an FP register.
930  assert(Op.getValueType() == MVT::i32);
931  Op = DAG.getNode(SPISD::FTOI, dl, MVT::f32, Op.getOperand(0));
932  return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
933}
934
935static SDValue LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
936  DebugLoc dl = Op.getDebugLoc();
937  assert(Op.getOperand(0).getValueType() == MVT::i32);
938  SDValue Tmp = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
939  // Convert the int value to FP in an FP register.
940  return DAG.getNode(SPISD::ITOF, dl, Op.getValueType(), Tmp);
941}
942
943static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
944  SDValue Chain = Op.getOperand(0);
945  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
946  SDValue LHS = Op.getOperand(2);
947  SDValue RHS = Op.getOperand(3);
948  SDValue Dest = Op.getOperand(4);
949  DebugLoc dl = Op.getDebugLoc();
950  unsigned Opc, SPCC = ~0U;
951
952  // If this is a br_cc of a "setcc", and if the setcc got lowered into
953  // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
954  LookThroughSetCC(LHS, RHS, CC, SPCC);
955
956  // Get the condition flag.
957  SDValue CompareFlag;
958  if (LHS.getValueType() == MVT::i32) {
959    std::vector<EVT> VTs;
960    VTs.push_back(MVT::i32);
961    VTs.push_back(MVT::Glue);
962    SDValue Ops[2] = { LHS, RHS };
963    CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
964    if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
965    Opc = SPISD::BRICC;
966  } else {
967    CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
968    if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
969    Opc = SPISD::BRFCC;
970  }
971  return DAG.getNode(Opc, dl, MVT::Other, Chain, Dest,
972                     DAG.getConstant(SPCC, MVT::i32), CompareFlag);
973}
974
975static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
976  SDValue LHS = Op.getOperand(0);
977  SDValue RHS = Op.getOperand(1);
978  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
979  SDValue TrueVal = Op.getOperand(2);
980  SDValue FalseVal = Op.getOperand(3);
981  DebugLoc dl = Op.getDebugLoc();
982  unsigned Opc, SPCC = ~0U;
983
984  // If this is a select_cc of a "setcc", and if the setcc got lowered into
985  // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
986  LookThroughSetCC(LHS, RHS, CC, SPCC);
987
988  SDValue CompareFlag;
989  if (LHS.getValueType() == MVT::i32) {
990    std::vector<EVT> VTs;
991    VTs.push_back(LHS.getValueType());   // subcc returns a value
992    VTs.push_back(MVT::Glue);
993    SDValue Ops[2] = { LHS, RHS };
994    CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
995    Opc = SPISD::SELECT_ICC;
996    if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
997  } else {
998    CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
999    Opc = SPISD::SELECT_FCC;
1000    if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
1001  }
1002  return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
1003                     DAG.getConstant(SPCC, MVT::i32), CompareFlag);
1004}
1005
1006static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
1007                            const SparcTargetLowering &TLI) {
1008  MachineFunction &MF = DAG.getMachineFunction();
1009  SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
1010
1011  // vastart just stores the address of the VarArgsFrameIndex slot into the
1012  // memory location argument.
1013  DebugLoc dl = Op.getDebugLoc();
1014  SDValue Offset =
1015    DAG.getNode(ISD::ADD, dl, MVT::i32,
1016                DAG.getRegister(SP::I6, MVT::i32),
1017                DAG.getConstant(FuncInfo->getVarArgsFrameOffset(),
1018                                MVT::i32));
1019  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1020  return DAG.getStore(Op.getOperand(0), dl, Offset, Op.getOperand(1),
1021                      MachinePointerInfo(SV), false, false, 0);
1022}
1023
1024static SDValue LowerVAARG(SDValue Op, SelectionDAG &DAG) {
1025  SDNode *Node = Op.getNode();
1026  EVT VT = Node->getValueType(0);
1027  SDValue InChain = Node->getOperand(0);
1028  SDValue VAListPtr = Node->getOperand(1);
1029  const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1030  DebugLoc dl = Node->getDebugLoc();
1031  SDValue VAList = DAG.getLoad(MVT::i32, dl, InChain, VAListPtr,
1032                               MachinePointerInfo(SV), false, false, false, 0);
1033  // Increment the pointer, VAList, to the next vaarg
1034  SDValue NextPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, VAList,
1035                                  DAG.getConstant(VT.getSizeInBits()/8,
1036                                                  MVT::i32));
1037  // Store the incremented VAList to the legalized pointer
1038  InChain = DAG.getStore(VAList.getValue(1), dl, NextPtr,
1039                         VAListPtr, MachinePointerInfo(SV), false, false, 0);
1040  // Load the actual argument out of the pointer VAList, unless this is an
1041  // f64 load.
1042  if (VT != MVT::f64)
1043    return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
1044                       false, false, false, 0);
1045
1046  // Otherwise, load it as i64, then do a bitconvert.
1047  SDValue V = DAG.getLoad(MVT::i64, dl, InChain, VAList, MachinePointerInfo(),
1048                          false, false, false, 0);
1049
1050  // Bit-Convert the value to f64.
1051  SDValue Ops[2] = {
1052    DAG.getNode(ISD::BITCAST, dl, MVT::f64, V),
1053    V.getValue(1)
1054  };
1055  return DAG.getMergeValues(Ops, 2, dl);
1056}
1057
1058static SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) {
1059  SDValue Chain = Op.getOperand(0);  // Legalize the chain.
1060  SDValue Size  = Op.getOperand(1);  // Legalize the size.
1061  DebugLoc dl = Op.getDebugLoc();
1062
1063  unsigned SPReg = SP::O6;
1064  SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, MVT::i32);
1065  SDValue NewSP = DAG.getNode(ISD::SUB, dl, MVT::i32, SP, Size); // Value
1066  Chain = DAG.getCopyToReg(SP.getValue(1), dl, SPReg, NewSP);    // Output chain
1067
1068  // The resultant pointer is actually 16 words from the bottom of the stack,
1069  // to provide a register spill area.
1070  SDValue NewVal = DAG.getNode(ISD::ADD, dl, MVT::i32, NewSP,
1071                                 DAG.getConstant(96, MVT::i32));
1072  SDValue Ops[2] = { NewVal, Chain };
1073  return DAG.getMergeValues(Ops, 2, dl);
1074}
1075
1076
1077static SDValue getFLUSHW(SDValue Op, SelectionDAG &DAG) {
1078  DebugLoc dl = Op.getDebugLoc();
1079  SDValue Chain = DAG.getNode(SPISD::FLUSHW,
1080                              dl, MVT::Other, DAG.getEntryNode());
1081  return Chain;
1082}
1083
1084static SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
1085  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1086  MFI->setFrameAddressIsTaken(true);
1087
1088  EVT VT = Op.getValueType();
1089  DebugLoc dl = Op.getDebugLoc();
1090  unsigned FrameReg = SP::I6;
1091
1092  uint64_t depth = Op.getConstantOperandVal(0);
1093
1094  SDValue FrameAddr;
1095  if (depth == 0)
1096    FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
1097  else {
1098    // flush first to make sure the windowed registers' values are in stack
1099    SDValue Chain = getFLUSHW(Op, DAG);
1100    FrameAddr = DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
1101
1102    for (uint64_t i = 0; i != depth; ++i) {
1103      SDValue Ptr = DAG.getNode(ISD::ADD,
1104                                dl, MVT::i32,
1105                                FrameAddr, DAG.getIntPtrConstant(56));
1106      FrameAddr = DAG.getLoad(MVT::i32, dl,
1107                              Chain,
1108                              Ptr,
1109                              MachinePointerInfo(), false, false, false, 0);
1110    }
1111  }
1112  return FrameAddr;
1113}
1114
1115static SDValue LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
1116  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1117  MFI->setReturnAddressIsTaken(true);
1118
1119  EVT VT = Op.getValueType();
1120  DebugLoc dl = Op.getDebugLoc();
1121  unsigned RetReg = SP::I7;
1122
1123  uint64_t depth = Op.getConstantOperandVal(0);
1124
1125  SDValue RetAddr;
1126  if (depth == 0)
1127    RetAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, RetReg, VT);
1128  else {
1129    // flush first to make sure the windowed registers' values are in stack
1130    SDValue Chain = getFLUSHW(Op, DAG);
1131    RetAddr = DAG.getCopyFromReg(Chain, dl, SP::I6, VT);
1132
1133    for (uint64_t i = 0; i != depth; ++i) {
1134      SDValue Ptr = DAG.getNode(ISD::ADD,
1135                                dl, MVT::i32,
1136                                RetAddr,
1137                                DAG.getIntPtrConstant((i == depth-1)?60:56));
1138      RetAddr = DAG.getLoad(MVT::i32, dl,
1139                            Chain,
1140                            Ptr,
1141                            MachinePointerInfo(), false, false, false, 0);
1142    }
1143  }
1144  return RetAddr;
1145}
1146
1147SDValue SparcTargetLowering::
1148LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1149  switch (Op.getOpcode()) {
1150  default: llvm_unreachable("Should not custom lower this!");
1151  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
1152  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
1153  case ISD::GlobalTLSAddress:
1154    llvm_unreachable("TLS not implemented for Sparc.");
1155  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
1156  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
1157  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
1158  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
1159  case ISD::BR_CC:              return LowerBR_CC(Op, DAG);
1160  case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
1161  case ISD::VASTART:            return LowerVASTART(Op, DAG, *this);
1162  case ISD::VAARG:              return LowerVAARG(Op, DAG);
1163  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
1164  }
1165}
1166
1167MachineBasicBlock *
1168SparcTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1169                                                 MachineBasicBlock *BB) const {
1170  const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1171  unsigned BROpcode;
1172  unsigned CC;
1173  DebugLoc dl = MI->getDebugLoc();
1174  // Figure out the conditional branch opcode to use for this select_cc.
1175  switch (MI->getOpcode()) {
1176  default: llvm_unreachable("Unknown SELECT_CC!");
1177  case SP::SELECT_CC_Int_ICC:
1178  case SP::SELECT_CC_FP_ICC:
1179  case SP::SELECT_CC_DFP_ICC:
1180    BROpcode = SP::BCOND;
1181    break;
1182  case SP::SELECT_CC_Int_FCC:
1183  case SP::SELECT_CC_FP_FCC:
1184  case SP::SELECT_CC_DFP_FCC:
1185    BROpcode = SP::FBCOND;
1186    break;
1187  }
1188
1189  CC = (SPCC::CondCodes)MI->getOperand(3).getImm();
1190
1191  // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1192  // control-flow pattern.  The incoming instruction knows the destination vreg
1193  // to set, the condition code register to branch on, the true/false values to
1194  // select between, and a branch opcode to use.
1195  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1196  MachineFunction::iterator It = BB;
1197  ++It;
1198
1199  //  thisMBB:
1200  //  ...
1201  //   TrueVal = ...
1202  //   [f]bCC copy1MBB
1203  //   fallthrough --> copy0MBB
1204  MachineBasicBlock *thisMBB = BB;
1205  MachineFunction *F = BB->getParent();
1206  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1207  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1208  F->insert(It, copy0MBB);
1209  F->insert(It, sinkMBB);
1210
1211  // Transfer the remainder of BB and its successor edges to sinkMBB.
1212  sinkMBB->splice(sinkMBB->begin(), BB,
1213                  llvm::next(MachineBasicBlock::iterator(MI)),
1214                  BB->end());
1215  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1216
1217  // Add the true and fallthrough blocks as its successors.
1218  BB->addSuccessor(copy0MBB);
1219  BB->addSuccessor(sinkMBB);
1220
1221  BuildMI(BB, dl, TII.get(BROpcode)).addMBB(sinkMBB).addImm(CC);
1222
1223  //  copy0MBB:
1224  //   %FalseValue = ...
1225  //   # fallthrough to sinkMBB
1226  BB = copy0MBB;
1227
1228  // Update machine-CFG edges
1229  BB->addSuccessor(sinkMBB);
1230
1231  //  sinkMBB:
1232  //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1233  //  ...
1234  BB = sinkMBB;
1235  BuildMI(*BB, BB->begin(), dl, TII.get(SP::PHI), MI->getOperand(0).getReg())
1236    .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1237    .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1238
1239  MI->eraseFromParent();   // The pseudo instruction is gone now.
1240  return BB;
1241}
1242
1243//===----------------------------------------------------------------------===//
1244//                         Sparc Inline Assembly Support
1245//===----------------------------------------------------------------------===//
1246
1247/// getConstraintType - Given a constraint letter, return the type of
1248/// constraint it is for this target.
1249SparcTargetLowering::ConstraintType
1250SparcTargetLowering::getConstraintType(const std::string &Constraint) const {
1251  if (Constraint.size() == 1) {
1252    switch (Constraint[0]) {
1253    default:  break;
1254    case 'r': return C_RegisterClass;
1255    }
1256  }
1257
1258  return TargetLowering::getConstraintType(Constraint);
1259}
1260
1261std::pair<unsigned, const TargetRegisterClass*>
1262SparcTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
1263                                                  EVT VT) const {
1264  if (Constraint.size() == 1) {
1265    switch (Constraint[0]) {
1266    case 'r':
1267      return std::make_pair(0U, &SP::IntRegsRegClass);
1268    }
1269  }
1270
1271  return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1272}
1273
1274bool
1275SparcTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1276  // The Sparc target isn't yet aware of offsets.
1277  return false;
1278}
1279