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