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