9dc5c1ffffdc7980505c13006e189106bc08f4fd
[oota-llvm.git] / lib / Target / Sparc / SparcISelLowering.cpp
1 //===-- SparcISelLowering.cpp - Sparc DAG Lowering Implementation ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the interfaces that Sparc uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "SparcISelLowering.h"
16 #include "SparcMachineFunctionInfo.h"
17 #include "SparcTargetMachine.h"
18 #include "llvm/CodeGen/CallingConvLower.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/SelectionDAG.h"
24 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/Support/ErrorHandling.h"
29 using namespace llvm;
30
31
32 //===----------------------------------------------------------------------===//
33 // Calling Convention Implementation
34 //===----------------------------------------------------------------------===//
35
36 static bool CC_Sparc_Assign_SRet(unsigned &ValNo, MVT &ValVT,
37                                  MVT &LocVT, CCValAssign::LocInfo &LocInfo,
38                                  ISD::ArgFlagsTy &ArgFlags, CCState &State)
39 {
40   assert (ArgFlags.isSRet());
41
42   //Assign SRet argument
43   State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
44                                          0,
45                                          LocVT, LocInfo));
46   return true;
47 }
48
49 static bool CC_Sparc_Assign_f64(unsigned &ValNo, MVT &ValVT,
50                                 MVT &LocVT, CCValAssign::LocInfo &LocInfo,
51                                 ISD::ArgFlagsTy &ArgFlags, CCState &State)
52 {
53   static const uint16_t RegList[] = {
54     SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
55   };
56   //Try to get first reg
57   if (unsigned Reg = State.AllocateReg(RegList, 6)) {
58     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
59   } else {
60     //Assign whole thing in stack
61     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
62                                            State.AllocateStack(8,4),
63                                            LocVT, LocInfo));
64     return true;
65   }
66
67   //Try to get second reg
68   if (unsigned Reg = State.AllocateReg(RegList, 6))
69     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
70   else
71     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
72                                            State.AllocateStack(4,4),
73                                            LocVT, LocInfo));
74   return true;
75 }
76
77 // Allocate a full-sized argument for the 64-bit ABI.
78 static bool CC_Sparc64_Full(unsigned &ValNo, MVT &ValVT,
79                             MVT &LocVT, CCValAssign::LocInfo &LocInfo,
80                             ISD::ArgFlagsTy &ArgFlags, CCState &State) {
81   assert((LocVT == MVT::f32 || LocVT.getSizeInBits() == 64) &&
82          "Can't handle non-64 bits locations");
83
84   // Stack space is allocated for all arguments starting from [%fp+BIAS+128].
85   unsigned Offset = State.AllocateStack(8, 8);
86   unsigned Reg = 0;
87
88   if (LocVT == MVT::i64 && Offset < 6*8)
89     // Promote integers to %i0-%i5.
90     Reg = SP::I0 + Offset/8;
91   else if (LocVT == MVT::f64 && Offset < 16*8)
92     // Promote doubles to %d0-%d30. (Which LLVM calls D0-D15).
93     Reg = SP::D0 + Offset/8;
94   else if (LocVT == MVT::f32 && Offset < 16*8)
95     // Promote floats to %f1, %f3, ...
96     Reg = SP::F1 + Offset/4;
97
98   // Promote to register when possible, otherwise use the stack slot.
99   if (Reg) {
100     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
101     return true;
102   }
103
104   // This argument goes on the stack in an 8-byte slot.
105   // When passing floats, LocVT is smaller than 8 bytes. Adjust the offset to
106   // the right-aligned float. The first 4 bytes of the stack slot are undefined.
107   if (LocVT == MVT::f32)
108     Offset += 4;
109
110   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
111   return true;
112 }
113
114 // Allocate a half-sized argument for the 64-bit ABI.
115 //
116 // This is used when passing { float, int } structs by value in registers.
117 static bool CC_Sparc64_Half(unsigned &ValNo, MVT &ValVT,
118                             MVT &LocVT, CCValAssign::LocInfo &LocInfo,
119                             ISD::ArgFlagsTy &ArgFlags, CCState &State) {
120   assert(LocVT.getSizeInBits() == 32 && "Can't handle non-32 bits locations");
121   unsigned Offset = State.AllocateStack(4, 4);
122
123   if (LocVT == MVT::f32 && Offset < 16*8) {
124     // Promote floats to %f0-%f31.
125     State.addLoc(CCValAssign::getReg(ValNo, ValVT, SP::F0 + Offset/4,
126                                      LocVT, LocInfo));
127     return true;
128   }
129
130   if (LocVT == MVT::i32 && Offset < 6*8) {
131     // Promote integers to %i0-%i5, using half the register.
132     unsigned Reg = SP::I0 + Offset/8;
133     LocVT = MVT::i64;
134     LocInfo = CCValAssign::AExt;
135
136     // Set the Custom bit if this i32 goes in the high bits of a register.
137     if (Offset % 8 == 0)
138       State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg,
139                                              LocVT, LocInfo));
140     else
141       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
142     return true;
143   }
144
145   State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
146   return true;
147 }
148
149 #include "SparcGenCallingConv.inc"
150
151 SDValue
152 SparcTargetLowering::LowerReturn(SDValue Chain,
153                                  CallingConv::ID CallConv, bool IsVarArg,
154                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
155                                  const SmallVectorImpl<SDValue> &OutVals,
156                                  DebugLoc DL, SelectionDAG &DAG) const {
157   if (Subtarget->is64Bit())
158     return LowerReturn_64(Chain, CallConv, IsVarArg, Outs, OutVals, DL, DAG);
159   return LowerReturn_32(Chain, CallConv, IsVarArg, Outs, OutVals, DL, DAG);
160 }
161
162 SDValue
163 SparcTargetLowering::LowerReturn_32(SDValue Chain,
164                                     CallingConv::ID CallConv, bool IsVarArg,
165                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
166                                     const SmallVectorImpl<SDValue> &OutVals,
167                                     DebugLoc DL, SelectionDAG &DAG) const {
168   MachineFunction &MF = DAG.getMachineFunction();
169
170   // CCValAssign - represent the assignment of the return value to locations.
171   SmallVector<CCValAssign, 16> RVLocs;
172
173   // CCState - Info about the registers and stack slot.
174   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
175                  DAG.getTarget(), RVLocs, *DAG.getContext());
176
177   // Analyze return values.
178   CCInfo.AnalyzeReturn(Outs, RetCC_Sparc32);
179
180   SDValue Flag;
181   SmallVector<SDValue, 4> RetOps(1, Chain);
182   // Make room for the return address offset.
183   RetOps.push_back(SDValue());
184
185   // Copy the result values into the output registers.
186   for (unsigned i = 0; i != RVLocs.size(); ++i) {
187     CCValAssign &VA = RVLocs[i];
188     assert(VA.isRegLoc() && "Can only return in registers!");
189
190     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(),
191                              OutVals[i], Flag);
192
193     // Guarantee that all emitted copies are stuck together with flags.
194     Flag = Chain.getValue(1);
195     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
196   }
197
198   unsigned RetAddrOffset = 8; //Call Inst + Delay Slot
199   // If the function returns a struct, copy the SRetReturnReg to I0
200   if (MF.getFunction()->hasStructRetAttr()) {
201     SparcMachineFunctionInfo *SFI = MF.getInfo<SparcMachineFunctionInfo>();
202     unsigned Reg = SFI->getSRetReturnReg();
203     if (!Reg)
204       llvm_unreachable("sret virtual register not created in the entry block");
205     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
206     Chain = DAG.getCopyToReg(Chain, DL, SP::I0, Val, Flag);
207     Flag = Chain.getValue(1);
208     RetOps.push_back(DAG.getRegister(SP::I0, getPointerTy()));
209     RetAddrOffset = 12; // CallInst + Delay Slot + Unimp
210   }
211
212   RetOps[0] = Chain;  // Update chain.
213   RetOps[1] = DAG.getConstant(RetAddrOffset, MVT::i32);
214
215   // Add the flag if we have it.
216   if (Flag.getNode())
217     RetOps.push_back(Flag);
218
219   return DAG.getNode(SPISD::RET_FLAG, DL, MVT::Other,
220                      &RetOps[0], RetOps.size());
221 }
222
223 // Lower return values for the 64-bit ABI.
224 // Return values are passed the exactly the same way as function arguments.
225 SDValue
226 SparcTargetLowering::LowerReturn_64(SDValue Chain,
227                                     CallingConv::ID CallConv, bool IsVarArg,
228                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
229                                     const SmallVectorImpl<SDValue> &OutVals,
230                                     DebugLoc DL, SelectionDAG &DAG) const {
231   // CCValAssign - represent the assignment of the return value to locations.
232   SmallVector<CCValAssign, 16> RVLocs;
233
234   // CCState - Info about the registers and stack slot.
235   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
236                  DAG.getTarget(), RVLocs, *DAG.getContext());
237
238   // Analyze return values.
239   CCInfo.AnalyzeReturn(Outs, CC_Sparc64);
240
241   SDValue Flag;
242   SmallVector<SDValue, 4> RetOps(1, Chain);
243
244   // The second operand on the return instruction is the return address offset.
245   // The return address is always %i7+8 with the 64-bit ABI.
246   RetOps.push_back(DAG.getConstant(8, MVT::i32));
247
248   // Copy the result values into the output registers.
249   for (unsigned i = 0; i != RVLocs.size(); ++i) {
250     CCValAssign &VA = RVLocs[i];
251     assert(VA.isRegLoc() && "Can only return in registers!");
252     SDValue OutVal = OutVals[i];
253
254     // Integer return values must be sign or zero extended by the callee.
255     switch (VA.getLocInfo()) {
256     case CCValAssign::SExt:
257       OutVal = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), OutVal);
258       break;
259     case CCValAssign::ZExt:
260       OutVal = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), OutVal);
261       break;
262     case CCValAssign::AExt:
263       OutVal = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), OutVal);
264     default:
265       break;
266     }
267
268     // The custom bit on an i32 return value indicates that it should be passed
269     // in the high bits of the register.
270     if (VA.getValVT() == MVT::i32 && VA.needsCustom()) {
271       OutVal = DAG.getNode(ISD::SHL, DL, MVT::i64, OutVal,
272                            DAG.getConstant(32, MVT::i32));
273
274       // The next value may go in the low bits of the same register.
275       // Handle both at once.
276       if (i+1 < RVLocs.size() && RVLocs[i+1].getLocReg() == VA.getLocReg()) {
277         SDValue NV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, OutVals[i+1]);
278         OutVal = DAG.getNode(ISD::OR, DL, MVT::i64, OutVal, NV);
279         // Skip the next value, it's already done.
280         ++i;
281       }
282     }
283
284     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVal, Flag);
285
286     // Guarantee that all emitted copies are stuck together with flags.
287     Flag = Chain.getValue(1);
288     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
289   }
290
291   RetOps[0] = Chain;  // Update chain.
292
293   // Add the flag if we have it.
294   if (Flag.getNode())
295     RetOps.push_back(Flag);
296
297   return DAG.getNode(SPISD::RET_FLAG, DL, MVT::Other,
298                      &RetOps[0], RetOps.size());
299 }
300
301 SDValue SparcTargetLowering::
302 LowerFormalArguments(SDValue Chain,
303                      CallingConv::ID CallConv,
304                      bool IsVarArg,
305                      const SmallVectorImpl<ISD::InputArg> &Ins,
306                      DebugLoc DL,
307                      SelectionDAG &DAG,
308                      SmallVectorImpl<SDValue> &InVals) const {
309   if (Subtarget->is64Bit())
310     return LowerFormalArguments_64(Chain, CallConv, IsVarArg, Ins,
311                                    DL, DAG, InVals);
312   return LowerFormalArguments_32(Chain, CallConv, IsVarArg, Ins,
313                                  DL, DAG, InVals);
314 }
315
316 /// LowerFormalArguments32 - V8 uses a very simple ABI, where all values are
317 /// passed in either one or two GPRs, including FP values.  TODO: we should
318 /// pass FP values in FP registers for fastcc functions.
319 SDValue SparcTargetLowering::
320 LowerFormalArguments_32(SDValue Chain,
321                         CallingConv::ID CallConv,
322                         bool isVarArg,
323                         const SmallVectorImpl<ISD::InputArg> &Ins,
324                         DebugLoc dl,
325                         SelectionDAG &DAG,
326                         SmallVectorImpl<SDValue> &InVals) const {
327   MachineFunction &MF = DAG.getMachineFunction();
328   MachineRegisterInfo &RegInfo = MF.getRegInfo();
329   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
330
331   // Assign locations to all of the incoming arguments.
332   SmallVector<CCValAssign, 16> ArgLocs;
333   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
334                  getTargetMachine(), ArgLocs, *DAG.getContext());
335   CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc32);
336
337   const unsigned StackOffset = 92;
338
339   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
340     CCValAssign &VA = ArgLocs[i];
341
342     if (i == 0  && Ins[i].Flags.isSRet()) {
343       //Get SRet from [%fp+64]
344       int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, 64, true);
345       SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
346       SDValue Arg = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
347                                 MachinePointerInfo(),
348                                 false, false, false, 0);
349       InVals.push_back(Arg);
350       continue;
351     }
352
353     if (VA.isRegLoc()) {
354       if (VA.needsCustom()) {
355         assert(VA.getLocVT() == MVT::f64);
356         unsigned VRegHi = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
357         MF.getRegInfo().addLiveIn(VA.getLocReg(), VRegHi);
358         SDValue HiVal = DAG.getCopyFromReg(Chain, dl, VRegHi, MVT::i32);
359
360         assert(i+1 < e);
361         CCValAssign &NextVA = ArgLocs[++i];
362
363         SDValue LoVal;
364         if (NextVA.isMemLoc()) {
365           int FrameIdx = MF.getFrameInfo()->
366             CreateFixedObject(4, StackOffset+NextVA.getLocMemOffset(),true);
367           SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
368           LoVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
369                               MachinePointerInfo(),
370                               false, false, false, 0);
371         } else {
372           unsigned loReg = MF.addLiveIn(NextVA.getLocReg(),
373                                         &SP::IntRegsRegClass);
374           LoVal = DAG.getCopyFromReg(Chain, dl, loReg, MVT::i32);
375         }
376         SDValue WholeValue =
377           DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
378         WholeValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, WholeValue);
379         InVals.push_back(WholeValue);
380         continue;
381       }
382       unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
383       MF.getRegInfo().addLiveIn(VA.getLocReg(), VReg);
384       SDValue Arg = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
385       if (VA.getLocVT() == MVT::f32)
386         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Arg);
387       else if (VA.getLocVT() != MVT::i32) {
388         Arg = DAG.getNode(ISD::AssertSext, dl, MVT::i32, Arg,
389                           DAG.getValueType(VA.getLocVT()));
390         Arg = DAG.getNode(ISD::TRUNCATE, dl, VA.getLocVT(), Arg);
391       }
392       InVals.push_back(Arg);
393       continue;
394     }
395
396     assert(VA.isMemLoc());
397
398     unsigned Offset = VA.getLocMemOffset()+StackOffset;
399
400     if (VA.needsCustom()) {
401       assert(VA.getValVT() == MVT::f64);
402       //If it is double-word aligned, just load.
403       if (Offset % 8 == 0) {
404         int FI = MF.getFrameInfo()->CreateFixedObject(8,
405                                                       Offset,
406                                                       true);
407         SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
408         SDValue Load = DAG.getLoad(VA.getValVT(), dl, Chain, FIPtr,
409                                    MachinePointerInfo(),
410                                    false,false, false, 0);
411         InVals.push_back(Load);
412         continue;
413       }
414
415       int FI = MF.getFrameInfo()->CreateFixedObject(4,
416                                                     Offset,
417                                                     true);
418       SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
419       SDValue HiVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
420                                   MachinePointerInfo(),
421                                   false, false, false, 0);
422       int FI2 = MF.getFrameInfo()->CreateFixedObject(4,
423                                                      Offset+4,
424                                                      true);
425       SDValue FIPtr2 = DAG.getFrameIndex(FI2, getPointerTy());
426
427       SDValue LoVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr2,
428                                   MachinePointerInfo(),
429                                   false, false, false, 0);
430
431       SDValue WholeValue =
432         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
433       WholeValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, WholeValue);
434       InVals.push_back(WholeValue);
435       continue;
436     }
437
438     int FI = MF.getFrameInfo()->CreateFixedObject(4,
439                                                   Offset,
440                                                   true);
441     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
442     SDValue Load ;
443     if (VA.getValVT() == MVT::i32 || VA.getValVT() == MVT::f32) {
444       Load = DAG.getLoad(VA.getValVT(), dl, Chain, FIPtr,
445                          MachinePointerInfo(),
446                          false, false, false, 0);
447     } else {
448       ISD::LoadExtType LoadOp = ISD::SEXTLOAD;
449       // Sparc is big endian, so add an offset based on the ObjectVT.
450       unsigned Offset = 4-std::max(1U, VA.getValVT().getSizeInBits()/8);
451       FIPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIPtr,
452                           DAG.getConstant(Offset, MVT::i32));
453       Load = DAG.getExtLoad(LoadOp, dl, MVT::i32, Chain, FIPtr,
454                             MachinePointerInfo(),
455                             VA.getValVT(), false, false,0);
456       Load = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Load);
457     }
458     InVals.push_back(Load);
459   }
460
461   if (MF.getFunction()->hasStructRetAttr()) {
462     //Copy the SRet Argument to SRetReturnReg
463     SparcMachineFunctionInfo *SFI = MF.getInfo<SparcMachineFunctionInfo>();
464     unsigned Reg = SFI->getSRetReturnReg();
465     if (!Reg) {
466       Reg = MF.getRegInfo().createVirtualRegister(&SP::IntRegsRegClass);
467       SFI->setSRetReturnReg(Reg);
468     }
469     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
470     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
471   }
472
473   // Store remaining ArgRegs to the stack if this is a varargs function.
474   if (isVarArg) {
475     static const uint16_t ArgRegs[] = {
476       SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
477     };
478     unsigned NumAllocated = CCInfo.getFirstUnallocated(ArgRegs, 6);
479     const uint16_t *CurArgReg = ArgRegs+NumAllocated, *ArgRegEnd = ArgRegs+6;
480     unsigned ArgOffset = CCInfo.getNextStackOffset();
481     if (NumAllocated == 6)
482       ArgOffset += StackOffset;
483     else {
484       assert(!ArgOffset);
485       ArgOffset = 68+4*NumAllocated;
486     }
487
488     // Remember the vararg offset for the va_start implementation.
489     FuncInfo->setVarArgsFrameOffset(ArgOffset);
490
491     std::vector<SDValue> OutChains;
492
493     for (; CurArgReg != ArgRegEnd; ++CurArgReg) {
494       unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
495       MF.getRegInfo().addLiveIn(*CurArgReg, VReg);
496       SDValue Arg = DAG.getCopyFromReg(DAG.getRoot(), dl, VReg, MVT::i32);
497
498       int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
499                                                           true);
500       SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
501
502       OutChains.push_back(DAG.getStore(DAG.getRoot(), dl, Arg, FIPtr,
503                                        MachinePointerInfo(),
504                                        false, false, 0));
505       ArgOffset += 4;
506     }
507
508     if (!OutChains.empty()) {
509       OutChains.push_back(Chain);
510       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
511                           &OutChains[0], OutChains.size());
512     }
513   }
514
515   return Chain;
516 }
517
518 // Lower formal arguments for the 64 bit ABI.
519 SDValue SparcTargetLowering::
520 LowerFormalArguments_64(SDValue Chain,
521                         CallingConv::ID CallConv,
522                         bool IsVarArg,
523                         const SmallVectorImpl<ISD::InputArg> &Ins,
524                         DebugLoc DL,
525                         SelectionDAG &DAG,
526                         SmallVectorImpl<SDValue> &InVals) const {
527   MachineFunction &MF = DAG.getMachineFunction();
528
529   // Analyze arguments according to CC_Sparc64.
530   SmallVector<CCValAssign, 16> ArgLocs;
531   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
532                  getTargetMachine(), ArgLocs, *DAG.getContext());
533   CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc64);
534
535   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
536     CCValAssign &VA = ArgLocs[i];
537     if (VA.isRegLoc()) {
538       // This argument is passed in a register.
539       // All integer register arguments are promoted by the caller to i64.
540
541       // Create a virtual register for the promoted live-in value.
542       unsigned VReg = MF.addLiveIn(VA.getLocReg(),
543                                    getRegClassFor(VA.getLocVT()));
544       SDValue Arg = DAG.getCopyFromReg(Chain, DL, VReg, VA.getLocVT());
545
546       // Get the high bits for i32 struct elements.
547       if (VA.getValVT() == MVT::i32 && VA.needsCustom())
548         Arg = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Arg,
549                           DAG.getConstant(32, MVT::i32));
550
551       // The caller promoted the argument, so insert an Assert?ext SDNode so we
552       // won't promote the value again in this function.
553       switch (VA.getLocInfo()) {
554       case CCValAssign::SExt:
555         Arg = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Arg,
556                           DAG.getValueType(VA.getValVT()));
557         break;
558       case CCValAssign::ZExt:
559         Arg = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Arg,
560                           DAG.getValueType(VA.getValVT()));
561         break;
562       default:
563         break;
564       }
565
566       // Truncate the register down to the argument type.
567       if (VA.isExtInLoc())
568         Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
569
570       InVals.push_back(Arg);
571       continue;
572     }
573
574     // The registers are exhausted. This argument was passed on the stack.
575     assert(VA.isMemLoc());
576     // The CC_Sparc64_Full/Half functions compute stack offsets relative to the
577     // beginning of the arguments area at %fp+BIAS+128.
578     unsigned Offset = VA.getLocMemOffset() + 128;
579     unsigned ValSize = VA.getValVT().getSizeInBits() / 8;
580     // Adjust offset for extended arguments, SPARC is big-endian.
581     // The caller will have written the full slot with extended bytes, but we
582     // prefer our own extending loads.
583     if (VA.isExtInLoc())
584       Offset += 8 - ValSize;
585     int FI = MF.getFrameInfo()->CreateFixedObject(ValSize, Offset, true);
586     InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain,
587                                  DAG.getFrameIndex(FI, getPointerTy()),
588                                  MachinePointerInfo::getFixedStack(FI),
589                                  false, false, false, 0));
590   }
591   return Chain;
592 }
593
594 SDValue
595 SparcTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
596                                SmallVectorImpl<SDValue> &InVals) const {
597   if (Subtarget->is64Bit())
598     return LowerCall_64(CLI, InVals);
599   return LowerCall_32(CLI, InVals);
600 }
601
602 // Lower a call for the 32-bit ABI.
603 SDValue
604 SparcTargetLowering::LowerCall_32(TargetLowering::CallLoweringInfo &CLI,
605                                   SmallVectorImpl<SDValue> &InVals) const {
606   SelectionDAG &DAG                     = CLI.DAG;
607   DebugLoc &dl                          = CLI.DL;
608   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
609   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
610   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
611   SDValue Chain                         = CLI.Chain;
612   SDValue Callee                        = CLI.Callee;
613   bool &isTailCall                      = CLI.IsTailCall;
614   CallingConv::ID CallConv              = CLI.CallConv;
615   bool isVarArg                         = CLI.IsVarArg;
616
617   // Sparc target does not yet support tail call optimization.
618   isTailCall = false;
619
620   // Analyze operands of the call, assigning locations to each operand.
621   SmallVector<CCValAssign, 16> ArgLocs;
622   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
623                  DAG.getTarget(), ArgLocs, *DAG.getContext());
624   CCInfo.AnalyzeCallOperands(Outs, CC_Sparc32);
625
626   // Get the size of the outgoing arguments stack space requirement.
627   unsigned ArgsSize = CCInfo.getNextStackOffset();
628
629   // Keep stack frames 8-byte aligned.
630   ArgsSize = (ArgsSize+7) & ~7;
631
632   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
633
634   //Create local copies for byval args.
635   SmallVector<SDValue, 8> ByValArgs;
636   for (unsigned i = 0,  e = Outs.size(); i != e; ++i) {
637     ISD::ArgFlagsTy Flags = Outs[i].Flags;
638     if (!Flags.isByVal())
639       continue;
640
641     SDValue Arg = OutVals[i];
642     unsigned Size = Flags.getByValSize();
643     unsigned Align = Flags.getByValAlign();
644
645     int FI = MFI->CreateStackObject(Size, Align, false);
646     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
647     SDValue SizeNode = DAG.getConstant(Size, MVT::i32);
648
649     Chain = DAG.getMemcpy(Chain, dl, FIPtr, Arg, SizeNode, Align,
650                           false,        //isVolatile,
651                           (Size <= 32), //AlwaysInline if size <= 32
652                           MachinePointerInfo(), MachinePointerInfo());
653     ByValArgs.push_back(FIPtr);
654   }
655
656   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(ArgsSize, true));
657
658   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
659   SmallVector<SDValue, 8> MemOpChains;
660
661   const unsigned StackOffset = 92;
662   bool hasStructRetAttr = false;
663   // Walk the register/memloc assignments, inserting copies/loads.
664   for (unsigned i = 0, realArgIdx = 0, byvalArgIdx = 0, e = ArgLocs.size();
665        i != e;
666        ++i, ++realArgIdx) {
667     CCValAssign &VA = ArgLocs[i];
668     SDValue Arg = OutVals[realArgIdx];
669
670     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
671
672     //Use local copy if it is a byval arg.
673     if (Flags.isByVal())
674       Arg = ByValArgs[byvalArgIdx++];
675
676     // Promote the value if needed.
677     switch (VA.getLocInfo()) {
678     default: llvm_unreachable("Unknown loc info!");
679     case CCValAssign::Full: break;
680     case CCValAssign::SExt:
681       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
682       break;
683     case CCValAssign::ZExt:
684       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
685       break;
686     case CCValAssign::AExt:
687       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
688       break;
689     case CCValAssign::BCvt:
690       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
691       break;
692     }
693
694     if (Flags.isSRet()) {
695       assert(VA.needsCustom());
696       // store SRet argument in %sp+64
697       SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
698       SDValue PtrOff = DAG.getIntPtrConstant(64);
699       PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
700       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
701                                          MachinePointerInfo(),
702                                          false, false, 0));
703       hasStructRetAttr = true;
704       continue;
705     }
706
707     if (VA.needsCustom()) {
708       assert(VA.getLocVT() == MVT::f64);
709
710       if (VA.isMemLoc()) {
711         unsigned Offset = VA.getLocMemOffset() + StackOffset;
712         //if it is double-word aligned, just store.
713         if (Offset % 8 == 0) {
714           SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
715           SDValue PtrOff = DAG.getIntPtrConstant(Offset);
716           PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
717           MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
718                                              MachinePointerInfo(),
719                                              false, false, 0));
720           continue;
721         }
722       }
723
724       SDValue StackPtr = DAG.CreateStackTemporary(MVT::f64, MVT::i32);
725       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
726                                    Arg, StackPtr, MachinePointerInfo(),
727                                    false, false, 0);
728       // Sparc is big-endian, so the high part comes first.
729       SDValue Hi = DAG.getLoad(MVT::i32, dl, Store, StackPtr,
730                                MachinePointerInfo(), false, false, false, 0);
731       // Increment the pointer to the other half.
732       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
733                              DAG.getIntPtrConstant(4));
734       // Load the low part.
735       SDValue Lo = DAG.getLoad(MVT::i32, dl, Store, StackPtr,
736                                MachinePointerInfo(), false, false, false, 0);
737
738       if (VA.isRegLoc()) {
739         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Hi));
740         assert(i+1 != e);
741         CCValAssign &NextVA = ArgLocs[++i];
742         if (NextVA.isRegLoc()) {
743           RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Lo));
744         } else {
745           //Store the low part in stack.
746           unsigned Offset = NextVA.getLocMemOffset() + StackOffset;
747           SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
748           SDValue PtrOff = DAG.getIntPtrConstant(Offset);
749           PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
750           MemOpChains.push_back(DAG.getStore(Chain, dl, Lo, PtrOff,
751                                              MachinePointerInfo(),
752                                              false, false, 0));
753         }
754       } else {
755         unsigned Offset = VA.getLocMemOffset() + StackOffset;
756         // Store the high part.
757         SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
758         SDValue PtrOff = DAG.getIntPtrConstant(Offset);
759         PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
760         MemOpChains.push_back(DAG.getStore(Chain, dl, Hi, PtrOff,
761                                            MachinePointerInfo(),
762                                            false, false, 0));
763         // Store the low part.
764         PtrOff = DAG.getIntPtrConstant(Offset+4);
765         PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
766         MemOpChains.push_back(DAG.getStore(Chain, dl, Lo, PtrOff,
767                                            MachinePointerInfo(),
768                                            false, false, 0));
769       }
770       continue;
771     }
772
773     // Arguments that can be passed on register must be kept at
774     // RegsToPass vector
775     if (VA.isRegLoc()) {
776       if (VA.getLocVT() != MVT::f32) {
777         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
778         continue;
779       }
780       Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
781       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
782       continue;
783     }
784
785     assert(VA.isMemLoc());
786
787     // Create a store off the stack pointer for this argument.
788     SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
789     SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset()+StackOffset);
790     PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
791     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
792                                        MachinePointerInfo(),
793                                        false, false, 0));
794   }
795
796
797   // Emit all stores, make sure the occur before any copies into physregs.
798   if (!MemOpChains.empty())
799     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
800                         &MemOpChains[0], MemOpChains.size());
801
802   // Build a sequence of copy-to-reg nodes chained together with token
803   // chain and flag operands which copy the outgoing args into registers.
804   // The InFlag in necessary since all emitted instructions must be
805   // stuck together.
806   SDValue InFlag;
807   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
808     unsigned Reg = RegsToPass[i].first;
809     // Remap I0->I7 -> O0->O7.
810     if (Reg >= SP::I0 && Reg <= SP::I7)
811       Reg = Reg-SP::I0+SP::O0;
812
813     Chain = DAG.getCopyToReg(Chain, dl, Reg, RegsToPass[i].second, InFlag);
814     InFlag = Chain.getValue(1);
815   }
816
817   unsigned SRetArgSize = (hasStructRetAttr)? getSRetArgSize(DAG, Callee):0;
818
819   // If the callee is a GlobalAddress node (quite common, every direct call is)
820   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
821   // Likewise ExternalSymbol -> TargetExternalSymbol.
822   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
823     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
824   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
825     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
826
827   // Returns a chain & a flag for retval copy to use
828   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
829   SmallVector<SDValue, 8> Ops;
830   Ops.push_back(Chain);
831   Ops.push_back(Callee);
832   if (hasStructRetAttr)
833     Ops.push_back(DAG.getTargetConstant(SRetArgSize, MVT::i32));
834   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
835     unsigned Reg = RegsToPass[i].first;
836     if (Reg >= SP::I0 && Reg <= SP::I7)
837       Reg = Reg-SP::I0+SP::O0;
838
839     Ops.push_back(DAG.getRegister(Reg, RegsToPass[i].second.getValueType()));
840   }
841   if (InFlag.getNode())
842     Ops.push_back(InFlag);
843
844   Chain = DAG.getNode(SPISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
845   InFlag = Chain.getValue(1);
846
847   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, true),
848                              DAG.getIntPtrConstant(0, true), InFlag);
849   InFlag = Chain.getValue(1);
850
851   // Assign locations to each value returned by this call.
852   SmallVector<CCValAssign, 16> RVLocs;
853   CCState RVInfo(CallConv, isVarArg, DAG.getMachineFunction(),
854                  DAG.getTarget(), RVLocs, *DAG.getContext());
855
856   RVInfo.AnalyzeCallResult(Ins, RetCC_Sparc32);
857
858   // Copy all of the result registers out of their specified physreg.
859   for (unsigned i = 0; i != RVLocs.size(); ++i) {
860     unsigned Reg = RVLocs[i].getLocReg();
861
862     // Remap I0->I7 -> O0->O7.
863     if (Reg >= SP::I0 && Reg <= SP::I7)
864       Reg = Reg-SP::I0+SP::O0;
865
866     Chain = DAG.getCopyFromReg(Chain, dl, Reg,
867                                RVLocs[i].getValVT(), InFlag).getValue(1);
868     InFlag = Chain.getValue(2);
869     InVals.push_back(Chain.getValue(0));
870   }
871
872   return Chain;
873 }
874
875 unsigned
876 SparcTargetLowering::getSRetArgSize(SelectionDAG &DAG, SDValue Callee) const
877 {
878   const Function *CalleeFn = 0;
879   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
880     CalleeFn = dyn_cast<Function>(G->getGlobal());
881   } else if (ExternalSymbolSDNode *E =
882              dyn_cast<ExternalSymbolSDNode>(Callee)) {
883     const Function *Fn = DAG.getMachineFunction().getFunction();
884     const Module *M = Fn->getParent();
885     CalleeFn = M->getFunction(E->getSymbol());
886   }
887
888   if (!CalleeFn)
889     return 0;
890
891   assert(CalleeFn->hasStructRetAttr() &&
892          "Callee does not have the StructRet attribute.");
893
894   PointerType *Ty = cast<PointerType>(CalleeFn->arg_begin()->getType());
895   Type *ElementTy = Ty->getElementType();
896   return getDataLayout()->getTypeAllocSize(ElementTy);
897 }
898
899 // Lower a call for the 64-bit ABI.
900 SDValue
901 SparcTargetLowering::LowerCall_64(TargetLowering::CallLoweringInfo &CLI,
902                                   SmallVectorImpl<SDValue> &InVals) const {
903   SelectionDAG &DAG = CLI.DAG;
904   DebugLoc DL = CLI.DL;
905   SDValue Chain = CLI.Chain;
906
907   // Analyze operands of the call, assigning locations to each operand.
908   SmallVector<CCValAssign, 16> ArgLocs;
909   CCState CCInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(),
910                  DAG.getTarget(), ArgLocs, *DAG.getContext());
911   CCInfo.AnalyzeCallOperands(CLI.Outs, CC_Sparc64);
912
913   // Get the size of the outgoing arguments stack space requirement.
914   // The stack offset computed by CC_Sparc64 includes all arguments.
915   // Called functions expect 6 argument words to exist in the stack frame, used
916   // or not.
917   unsigned ArgsSize = std::max(6*8u, CCInfo.getNextStackOffset());
918
919   // Keep stack frames 16-byte aligned.
920   ArgsSize = RoundUpToAlignment(ArgsSize, 16);
921
922   // Adjust the stack pointer to make room for the arguments.
923   // FIXME: Use hasReservedCallFrame to avoid %sp adjustments around all calls
924   // with more than 6 arguments.
925   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(ArgsSize, true));
926
927   // Collect the set of registers to pass to the function and their values.
928   // This will be emitted as a sequence of CopyToReg nodes glued to the call
929   // instruction.
930   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
931
932   // Collect chains from all the memory opeations that copy arguments to the
933   // stack. They must follow the stack pointer adjustment above and precede the
934   // call instruction itself.
935   SmallVector<SDValue, 8> MemOpChains;
936
937   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
938     const CCValAssign &VA = ArgLocs[i];
939     SDValue Arg = CLI.OutVals[i];
940
941     // Promote the value if needed.
942     switch (VA.getLocInfo()) {
943     default:
944       llvm_unreachable("Unknown location info!");
945     case CCValAssign::Full:
946       break;
947     case CCValAssign::SExt:
948       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
949       break;
950     case CCValAssign::ZExt:
951       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
952       break;
953     case CCValAssign::AExt:
954       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
955       break;
956     case CCValAssign::BCvt:
957       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
958       break;
959     }
960
961     if (VA.isRegLoc()) {
962       // The custom bit on an i32 return value indicates that it should be
963       // passed in the high bits of the register.
964       if (VA.getValVT() == MVT::i32 && VA.needsCustom()) {
965         Arg = DAG.getNode(ISD::SHL, DL, MVT::i64, Arg,
966                           DAG.getConstant(32, MVT::i32));
967
968         // The next value may go in the low bits of the same register.
969         // Handle both at once.
970         if (i+1 < ArgLocs.size() && ArgLocs[i+1].isRegLoc() &&
971             ArgLocs[i+1].getLocReg() == VA.getLocReg()) {
972           SDValue NV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64,
973                                    CLI.OutVals[i+1]);
974           Arg = DAG.getNode(ISD::OR, DL, MVT::i64, Arg, NV);
975           // Skip the next value, it's already done.
976           ++i;
977         }
978       }
979
980       // The argument registers are described in term of the callee's register
981       // window, so translate I0-I7 -> O0-O7.
982       unsigned Reg = VA.getLocReg();
983       if (Reg >= SP::I0 && Reg <= SP::I7)
984         Reg = Reg - SP::I0 + SP::O0;
985       RegsToPass.push_back(std::make_pair(Reg, Arg));
986       continue;
987     }
988
989     assert(VA.isMemLoc());
990
991     // Create a store off the stack pointer for this argument.
992     SDValue StackPtr = DAG.getRegister(SP::O6, getPointerTy());
993     // The argument area starts at %fp+BIAS+128 in the callee frame,
994     // %sp+BIAS+128 in ours.
995     SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset() +
996                                            Subtarget->getStackPointerBias() +
997                                            128);
998     PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
999     MemOpChains.push_back(DAG.getStore(Chain, DL, Arg, PtrOff,
1000                                        MachinePointerInfo(),
1001                                        false, false, 0));
1002   }
1003
1004   // Emit all stores, make sure they occur before the call.
1005   if (!MemOpChains.empty())
1006     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
1007                         &MemOpChains[0], MemOpChains.size());
1008
1009   // Build a sequence of CopyToReg nodes glued together with token chain and
1010   // glue operands which copy the outgoing args into registers. The InGlue is
1011   // necessary since all emitted instructions must be stuck together in order
1012   // to pass the live physical registers.
1013   SDValue InGlue;
1014   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1015     Chain = DAG.getCopyToReg(Chain, DL,
1016                              RegsToPass[i].first, RegsToPass[i].second, InGlue);
1017     InGlue = Chain.getValue(1);
1018   }
1019
1020   // If the callee is a GlobalAddress node (quite common, every direct call is)
1021   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1022   // Likewise ExternalSymbol -> TargetExternalSymbol.
1023   SDValue Callee = CLI.Callee;
1024   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1025     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy());
1026   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1027     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), getPointerTy());
1028
1029   // Build the operands for the call instruction itself.
1030   SmallVector<SDValue, 8> Ops;
1031   Ops.push_back(Chain);
1032   Ops.push_back(Callee);
1033   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1034     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1035                                   RegsToPass[i].second.getValueType()));
1036
1037   // Make sure the CopyToReg nodes are glued to the call instruction which
1038   // consumes the registers.
1039   if (InGlue.getNode())
1040     Ops.push_back(InGlue);
1041
1042   // Now the call itself.
1043   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1044   Chain = DAG.getNode(SPISD::CALL, DL, NodeTys, &Ops[0], Ops.size());
1045   InGlue = Chain.getValue(1);
1046
1047   // Revert the stack pointer immediately after the call.
1048   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, true),
1049                              DAG.getIntPtrConstant(0, true), InGlue);
1050   InGlue = Chain.getValue(1);
1051
1052   // Now extract the return values. This is more or less the same as
1053   // LowerFormalArguments_64.
1054
1055   // Assign locations to each value returned by this call.
1056   SmallVector<CCValAssign, 16> RVLocs;
1057   CCState RVInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(),
1058                  DAG.getTarget(), RVLocs, *DAG.getContext());
1059   RVInfo.AnalyzeCallResult(CLI.Ins, CC_Sparc64);
1060
1061   // Copy all of the result registers out of their specified physreg.
1062   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1063     CCValAssign &VA = RVLocs[i];
1064     unsigned Reg = VA.getLocReg();
1065
1066     // Remap I0-I7 -> O0-O7.
1067     if (Reg >= SP::I0 && Reg <= SP::I7)
1068       Reg = Reg - SP::I0 + SP::O0;
1069
1070     // When returning 'inreg {i32, i32 }', two consecutive i32 arguments can
1071     // reside in the same register in the high and low bits. Reuse the
1072     // CopyFromReg previous node to avoid duplicate copies.
1073     SDValue RV;
1074     if (RegisterSDNode *SrcReg = dyn_cast<RegisterSDNode>(Chain.getOperand(1)))
1075       if (SrcReg->getReg() == Reg && Chain->getOpcode() == ISD::CopyFromReg)
1076         RV = Chain.getValue(0);
1077
1078     // But usually we'll create a new CopyFromReg for a different register.
1079     if (!RV.getNode()) {
1080       RV = DAG.getCopyFromReg(Chain, DL, Reg, RVLocs[i].getLocVT(), InGlue);
1081       Chain = RV.getValue(1);
1082       InGlue = Chain.getValue(2);
1083     }
1084
1085     // Get the high bits for i32 struct elements.
1086     if (VA.getValVT() == MVT::i32 && VA.needsCustom())
1087       RV = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), RV,
1088                        DAG.getConstant(32, MVT::i32));
1089
1090     // The callee promoted the return value, so insert an Assert?ext SDNode so
1091     // we won't promote the value again in this function.
1092     switch (VA.getLocInfo()) {
1093     case CCValAssign::SExt:
1094       RV = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), RV,
1095                        DAG.getValueType(VA.getValVT()));
1096       break;
1097     case CCValAssign::ZExt:
1098       RV = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), RV,
1099                        DAG.getValueType(VA.getValVT()));
1100       break;
1101     default:
1102       break;
1103     }
1104
1105     // Truncate the register down to the return value type.
1106     if (VA.isExtInLoc())
1107       RV = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), RV);
1108
1109     InVals.push_back(RV);
1110   }
1111
1112   return Chain;
1113 }
1114
1115 //===----------------------------------------------------------------------===//
1116 // TargetLowering Implementation
1117 //===----------------------------------------------------------------------===//
1118
1119 /// IntCondCCodeToICC - Convert a DAG integer condition code to a SPARC ICC
1120 /// condition.
1121 static SPCC::CondCodes IntCondCCodeToICC(ISD::CondCode CC) {
1122   switch (CC) {
1123   default: llvm_unreachable("Unknown integer condition code!");
1124   case ISD::SETEQ:  return SPCC::ICC_E;
1125   case ISD::SETNE:  return SPCC::ICC_NE;
1126   case ISD::SETLT:  return SPCC::ICC_L;
1127   case ISD::SETGT:  return SPCC::ICC_G;
1128   case ISD::SETLE:  return SPCC::ICC_LE;
1129   case ISD::SETGE:  return SPCC::ICC_GE;
1130   case ISD::SETULT: return SPCC::ICC_CS;
1131   case ISD::SETULE: return SPCC::ICC_LEU;
1132   case ISD::SETUGT: return SPCC::ICC_GU;
1133   case ISD::SETUGE: return SPCC::ICC_CC;
1134   }
1135 }
1136
1137 /// FPCondCCodeToFCC - Convert a DAG floatingp oint condition code to a SPARC
1138 /// FCC condition.
1139 static SPCC::CondCodes FPCondCCodeToFCC(ISD::CondCode CC) {
1140   switch (CC) {
1141   default: llvm_unreachable("Unknown fp condition code!");
1142   case ISD::SETEQ:
1143   case ISD::SETOEQ: return SPCC::FCC_E;
1144   case ISD::SETNE:
1145   case ISD::SETUNE: return SPCC::FCC_NE;
1146   case ISD::SETLT:
1147   case ISD::SETOLT: return SPCC::FCC_L;
1148   case ISD::SETGT:
1149   case ISD::SETOGT: return SPCC::FCC_G;
1150   case ISD::SETLE:
1151   case ISD::SETOLE: return SPCC::FCC_LE;
1152   case ISD::SETGE:
1153   case ISD::SETOGE: return SPCC::FCC_GE;
1154   case ISD::SETULT: return SPCC::FCC_UL;
1155   case ISD::SETULE: return SPCC::FCC_ULE;
1156   case ISD::SETUGT: return SPCC::FCC_UG;
1157   case ISD::SETUGE: return SPCC::FCC_UGE;
1158   case ISD::SETUO:  return SPCC::FCC_U;
1159   case ISD::SETO:   return SPCC::FCC_O;
1160   case ISD::SETONE: return SPCC::FCC_LG;
1161   case ISD::SETUEQ: return SPCC::FCC_UE;
1162   }
1163 }
1164
1165 SparcTargetLowering::SparcTargetLowering(TargetMachine &TM)
1166   : TargetLowering(TM, new TargetLoweringObjectFileELF()) {
1167   Subtarget = &TM.getSubtarget<SparcSubtarget>();
1168
1169   // Set up the register classes.
1170   addRegisterClass(MVT::i32, &SP::IntRegsRegClass);
1171   addRegisterClass(MVT::f32, &SP::FPRegsRegClass);
1172   addRegisterClass(MVT::f64, &SP::DFPRegsRegClass);
1173   if (Subtarget->is64Bit())
1174     addRegisterClass(MVT::i64, &SP::I64RegsRegClass);
1175
1176   // Turn FP extload into load/fextend
1177   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
1178   // Sparc doesn't have i1 sign extending load
1179   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
1180   // Turn FP truncstore into trunc + store.
1181   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1182
1183   // Custom legalize GlobalAddress nodes into LO/HI parts.
1184   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1185   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1186   setOperationAction(ISD::ConstantPool , MVT::i32, Custom);
1187
1188   // Sparc doesn't have sext_inreg, replace them with shl/sra
1189   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1190   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
1191   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
1192
1193   // Sparc has no REM or DIVREM operations.
1194   setOperationAction(ISD::UREM, MVT::i32, Expand);
1195   setOperationAction(ISD::SREM, MVT::i32, Expand);
1196   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1197   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1198
1199   // Custom expand fp<->sint
1200   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
1201   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
1202
1203   // Expand fp<->uint
1204   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
1205   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
1206
1207   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
1208   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
1209
1210   // Sparc has no select or setcc: expand to SELECT_CC.
1211   setOperationAction(ISD::SELECT, MVT::i32, Expand);
1212   setOperationAction(ISD::SELECT, MVT::f32, Expand);
1213   setOperationAction(ISD::SELECT, MVT::f64, Expand);
1214   setOperationAction(ISD::SETCC, MVT::i32, Expand);
1215   setOperationAction(ISD::SETCC, MVT::f32, Expand);
1216   setOperationAction(ISD::SETCC, MVT::f64, Expand);
1217
1218   // Sparc doesn't have BRCOND either, it has BR_CC.
1219   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
1220   setOperationAction(ISD::BRIND, MVT::Other, Expand);
1221   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
1222   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1223   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1224   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1225
1226   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1227   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1228   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1229
1230   if (Subtarget->is64Bit()) {
1231     setOperationAction(ISD::BR_CC, MVT::i64, Custom);
1232     setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
1233   }
1234
1235   // FIXME: There are instructions available for ATOMIC_FENCE
1236   // on SparcV8 and later.
1237   setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
1238   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
1239
1240   setOperationAction(ISD::FSIN , MVT::f64, Expand);
1241   setOperationAction(ISD::FCOS , MVT::f64, Expand);
1242   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1243   setOperationAction(ISD::FREM , MVT::f64, Expand);
1244   setOperationAction(ISD::FMA  , MVT::f64, Expand);
1245   setOperationAction(ISD::FSIN , MVT::f32, Expand);
1246   setOperationAction(ISD::FCOS , MVT::f32, Expand);
1247   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1248   setOperationAction(ISD::FREM , MVT::f32, Expand);
1249   setOperationAction(ISD::FMA  , MVT::f32, Expand);
1250   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1251   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
1252   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
1253   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
1254   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
1255   setOperationAction(ISD::ROTL , MVT::i32, Expand);
1256   setOperationAction(ISD::ROTR , MVT::i32, Expand);
1257   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1258   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
1259   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
1260   setOperationAction(ISD::FPOW , MVT::f64, Expand);
1261   setOperationAction(ISD::FPOW , MVT::f32, Expand);
1262
1263   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1264   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1265   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1266
1267   // FIXME: Sparc provides these multiplies, but we don't have them yet.
1268   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1269   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1270
1271   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
1272
1273   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
1274   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
1275   // VAARG needs to be lowered to not do unaligned accesses for doubles.
1276   setOperationAction(ISD::VAARG             , MVT::Other, Custom);
1277
1278   // Use the default implementation.
1279   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
1280   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
1281   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
1282   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
1283   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
1284
1285   // No debug info support yet.
1286   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
1287
1288   setStackPointerRegisterToSaveRestore(SP::O6);
1289
1290   if (TM.getSubtarget<SparcSubtarget>().isV9())
1291     setOperationAction(ISD::CTPOP, MVT::i32, Legal);
1292
1293   setMinFunctionAlignment(2);
1294
1295   computeRegisterProperties();
1296 }
1297
1298 const char *SparcTargetLowering::getTargetNodeName(unsigned Opcode) const {
1299   switch (Opcode) {
1300   default: return 0;
1301   case SPISD::CMPICC:     return "SPISD::CMPICC";
1302   case SPISD::CMPFCC:     return "SPISD::CMPFCC";
1303   case SPISD::BRICC:      return "SPISD::BRICC";
1304   case SPISD::BRXCC:      return "SPISD::BRXCC";
1305   case SPISD::BRFCC:      return "SPISD::BRFCC";
1306   case SPISD::SELECT_ICC: return "SPISD::SELECT_ICC";
1307   case SPISD::SELECT_XCC: return "SPISD::SELECT_XCC";
1308   case SPISD::SELECT_FCC: return "SPISD::SELECT_FCC";
1309   case SPISD::Hi:         return "SPISD::Hi";
1310   case SPISD::Lo:         return "SPISD::Lo";
1311   case SPISD::FTOI:       return "SPISD::FTOI";
1312   case SPISD::ITOF:       return "SPISD::ITOF";
1313   case SPISD::CALL:       return "SPISD::CALL";
1314   case SPISD::RET_FLAG:   return "SPISD::RET_FLAG";
1315   case SPISD::GLOBAL_BASE_REG: return "SPISD::GLOBAL_BASE_REG";
1316   case SPISD::FLUSHW:     return "SPISD::FLUSHW";
1317   }
1318 }
1319
1320 /// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
1321 /// be zero. Op is expected to be a target specific node. Used by DAG
1322 /// combiner.
1323 void SparcTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1324                                                          APInt &KnownZero,
1325                                                          APInt &KnownOne,
1326                                                          const SelectionDAG &DAG,
1327                                                          unsigned Depth) const {
1328   APInt KnownZero2, KnownOne2;
1329   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1330
1331   switch (Op.getOpcode()) {
1332   default: break;
1333   case SPISD::SELECT_ICC:
1334   case SPISD::SELECT_XCC:
1335   case SPISD::SELECT_FCC:
1336     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1337     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1338     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1339     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1340
1341     // Only known if known in both the LHS and RHS.
1342     KnownOne &= KnownOne2;
1343     KnownZero &= KnownZero2;
1344     break;
1345   }
1346 }
1347
1348 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
1349 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
1350 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
1351                              ISD::CondCode CC, unsigned &SPCC) {
1352   if (isa<ConstantSDNode>(RHS) &&
1353       cast<ConstantSDNode>(RHS)->isNullValue() &&
1354       CC == ISD::SETNE &&
1355       (((LHS.getOpcode() == SPISD::SELECT_ICC ||
1356          LHS.getOpcode() == SPISD::SELECT_XCC) &&
1357         LHS.getOperand(3).getOpcode() == SPISD::CMPICC) ||
1358        (LHS.getOpcode() == SPISD::SELECT_FCC &&
1359         LHS.getOperand(3).getOpcode() == SPISD::CMPFCC)) &&
1360       isa<ConstantSDNode>(LHS.getOperand(0)) &&
1361       isa<ConstantSDNode>(LHS.getOperand(1)) &&
1362       cast<ConstantSDNode>(LHS.getOperand(0))->isOne() &&
1363       cast<ConstantSDNode>(LHS.getOperand(1))->isNullValue()) {
1364     SDValue CMPCC = LHS.getOperand(3);
1365     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
1366     LHS = CMPCC.getOperand(0);
1367     RHS = CMPCC.getOperand(1);
1368   }
1369 }
1370
1371 SDValue SparcTargetLowering::LowerGlobalAddress(SDValue Op,
1372                                                 SelectionDAG &DAG) const {
1373   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1374   // FIXME there isn't really any debug info here
1375   DebugLoc dl = Op.getDebugLoc();
1376   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
1377   SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, GA);
1378   SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, GA);
1379
1380   if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
1381     return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
1382
1383   SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
1384                                    getPointerTy());
1385   SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
1386   SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
1387                                 GlobalBase, RelAddr);
1388   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1389                      AbsAddr, MachinePointerInfo(), false, false, false, 0);
1390 }
1391
1392 SDValue SparcTargetLowering::LowerConstantPool(SDValue Op,
1393                                                SelectionDAG &DAG) const {
1394   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1395   // FIXME there isn't really any debug info here
1396   DebugLoc dl = Op.getDebugLoc();
1397   const Constant *C = N->getConstVal();
1398   SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment());
1399   SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, CP);
1400   SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, CP);
1401   if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
1402     return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
1403
1404   SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
1405                                    getPointerTy());
1406   SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
1407   SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
1408                                 GlobalBase, RelAddr);
1409   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1410                      AbsAddr, MachinePointerInfo(), false, false, false, 0);
1411 }
1412
1413 static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
1414   DebugLoc dl = Op.getDebugLoc();
1415   // Convert the fp value to integer in an FP register.
1416   assert(Op.getValueType() == MVT::i32);
1417   Op = DAG.getNode(SPISD::FTOI, dl, MVT::f32, Op.getOperand(0));
1418   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
1419 }
1420
1421 static SDValue LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1422   DebugLoc dl = Op.getDebugLoc();
1423   assert(Op.getOperand(0).getValueType() == MVT::i32);
1424   SDValue Tmp = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
1425   // Convert the int value to FP in an FP register.
1426   return DAG.getNode(SPISD::ITOF, dl, Op.getValueType(), Tmp);
1427 }
1428
1429 static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
1430   SDValue Chain = Op.getOperand(0);
1431   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1432   SDValue LHS = Op.getOperand(2);
1433   SDValue RHS = Op.getOperand(3);
1434   SDValue Dest = Op.getOperand(4);
1435   DebugLoc dl = Op.getDebugLoc();
1436   unsigned Opc, SPCC = ~0U;
1437
1438   // If this is a br_cc of a "setcc", and if the setcc got lowered into
1439   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1440   LookThroughSetCC(LHS, RHS, CC, SPCC);
1441
1442   // Get the condition flag.
1443   SDValue CompareFlag;
1444   if (LHS.getValueType().isInteger()) {
1445     EVT VTs[] = { LHS.getValueType(), MVT::Glue };
1446     SDValue Ops[2] = { LHS, RHS };
1447     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
1448     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
1449     // 32-bit compares use the icc flags, 64-bit uses the xcc flags.
1450     Opc = LHS.getValueType() == MVT::i32 ? SPISD::BRICC : SPISD::BRXCC;
1451   } else {
1452     CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
1453     if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
1454     Opc = SPISD::BRFCC;
1455   }
1456   return DAG.getNode(Opc, dl, MVT::Other, Chain, Dest,
1457                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
1458 }
1459
1460 static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
1461   SDValue LHS = Op.getOperand(0);
1462   SDValue RHS = Op.getOperand(1);
1463   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1464   SDValue TrueVal = Op.getOperand(2);
1465   SDValue FalseVal = Op.getOperand(3);
1466   DebugLoc dl = Op.getDebugLoc();
1467   unsigned Opc, SPCC = ~0U;
1468
1469   // If this is a select_cc of a "setcc", and if the setcc got lowered into
1470   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1471   LookThroughSetCC(LHS, RHS, CC, SPCC);
1472
1473   SDValue CompareFlag;
1474   if (LHS.getValueType().isInteger()) {
1475     // subcc returns a value
1476     EVT VTs[] = { LHS.getValueType(), MVT::Glue };
1477     SDValue Ops[2] = { LHS, RHS };
1478     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
1479     Opc = LHS.getValueType() == MVT::i32 ?
1480           SPISD::SELECT_ICC : SPISD::SELECT_XCC;
1481     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
1482   } else {
1483     CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
1484     Opc = SPISD::SELECT_FCC;
1485     if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
1486   }
1487   return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
1488                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
1489 }
1490
1491 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
1492                             const SparcTargetLowering &TLI) {
1493   MachineFunction &MF = DAG.getMachineFunction();
1494   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
1495
1496   // vastart just stores the address of the VarArgsFrameIndex slot into the
1497   // memory location argument.
1498   DebugLoc dl = Op.getDebugLoc();
1499   SDValue Offset =
1500     DAG.getNode(ISD::ADD, dl, MVT::i32,
1501                 DAG.getRegister(SP::I6, MVT::i32),
1502                 DAG.getConstant(FuncInfo->getVarArgsFrameOffset(),
1503                                 MVT::i32));
1504   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1505   return DAG.getStore(Op.getOperand(0), dl, Offset, Op.getOperand(1),
1506                       MachinePointerInfo(SV), false, false, 0);
1507 }
1508
1509 static SDValue LowerVAARG(SDValue Op, SelectionDAG &DAG) {
1510   SDNode *Node = Op.getNode();
1511   EVT VT = Node->getValueType(0);
1512   SDValue InChain = Node->getOperand(0);
1513   SDValue VAListPtr = Node->getOperand(1);
1514   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1515   DebugLoc dl = Node->getDebugLoc();
1516   SDValue VAList = DAG.getLoad(MVT::i32, dl, InChain, VAListPtr,
1517                                MachinePointerInfo(SV), false, false, false, 0);
1518   // Increment the pointer, VAList, to the next vaarg
1519   SDValue NextPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, VAList,
1520                                   DAG.getConstant(VT.getSizeInBits()/8,
1521                                                   MVT::i32));
1522   // Store the incremented VAList to the legalized pointer
1523   InChain = DAG.getStore(VAList.getValue(1), dl, NextPtr,
1524                          VAListPtr, MachinePointerInfo(SV), false, false, 0);
1525   // Load the actual argument out of the pointer VAList, unless this is an
1526   // f64 load.
1527   if (VT != MVT::f64)
1528     return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
1529                        false, false, false, 0);
1530
1531   // Otherwise, load it as i64, then do a bitconvert.
1532   SDValue V = DAG.getLoad(MVT::i64, dl, InChain, VAList, MachinePointerInfo(),
1533                           false, false, false, 0);
1534
1535   // Bit-Convert the value to f64.
1536   SDValue Ops[2] = {
1537     DAG.getNode(ISD::BITCAST, dl, MVT::f64, V),
1538     V.getValue(1)
1539   };
1540   return DAG.getMergeValues(Ops, 2, dl);
1541 }
1542
1543 static SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) {
1544   SDValue Chain = Op.getOperand(0);  // Legalize the chain.
1545   SDValue Size  = Op.getOperand(1);  // Legalize the size.
1546   DebugLoc dl = Op.getDebugLoc();
1547
1548   unsigned SPReg = SP::O6;
1549   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, MVT::i32);
1550   SDValue NewSP = DAG.getNode(ISD::SUB, dl, MVT::i32, SP, Size); // Value
1551   Chain = DAG.getCopyToReg(SP.getValue(1), dl, SPReg, NewSP);    // Output chain
1552
1553   // The resultant pointer is actually 16 words from the bottom of the stack,
1554   // to provide a register spill area.
1555   SDValue NewVal = DAG.getNode(ISD::ADD, dl, MVT::i32, NewSP,
1556                                  DAG.getConstant(96, MVT::i32));
1557   SDValue Ops[2] = { NewVal, Chain };
1558   return DAG.getMergeValues(Ops, 2, dl);
1559 }
1560
1561
1562 static SDValue getFLUSHW(SDValue Op, SelectionDAG &DAG) {
1563   DebugLoc dl = Op.getDebugLoc();
1564   SDValue Chain = DAG.getNode(SPISD::FLUSHW,
1565                               dl, MVT::Other, DAG.getEntryNode());
1566   return Chain;
1567 }
1568
1569 static SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
1570   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1571   MFI->setFrameAddressIsTaken(true);
1572
1573   EVT VT = Op.getValueType();
1574   DebugLoc dl = Op.getDebugLoc();
1575   unsigned FrameReg = SP::I6;
1576
1577   uint64_t depth = Op.getConstantOperandVal(0);
1578
1579   SDValue FrameAddr;
1580   if (depth == 0)
1581     FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
1582   else {
1583     // flush first to make sure the windowed registers' values are in stack
1584     SDValue Chain = getFLUSHW(Op, DAG);
1585     FrameAddr = DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
1586
1587     for (uint64_t i = 0; i != depth; ++i) {
1588       SDValue Ptr = DAG.getNode(ISD::ADD,
1589                                 dl, MVT::i32,
1590                                 FrameAddr, DAG.getIntPtrConstant(56));
1591       FrameAddr = DAG.getLoad(MVT::i32, dl,
1592                               Chain,
1593                               Ptr,
1594                               MachinePointerInfo(), false, false, false, 0);
1595     }
1596   }
1597   return FrameAddr;
1598 }
1599
1600 static SDValue LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
1601   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1602   MFI->setReturnAddressIsTaken(true);
1603
1604   EVT VT = Op.getValueType();
1605   DebugLoc dl = Op.getDebugLoc();
1606   unsigned RetReg = SP::I7;
1607
1608   uint64_t depth = Op.getConstantOperandVal(0);
1609
1610   SDValue RetAddr;
1611   if (depth == 0)
1612     RetAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, RetReg, VT);
1613   else {
1614     // flush first to make sure the windowed registers' values are in stack
1615     SDValue Chain = getFLUSHW(Op, DAG);
1616     RetAddr = DAG.getCopyFromReg(Chain, dl, SP::I6, VT);
1617
1618     for (uint64_t i = 0; i != depth; ++i) {
1619       SDValue Ptr = DAG.getNode(ISD::ADD,
1620                                 dl, MVT::i32,
1621                                 RetAddr,
1622                                 DAG.getIntPtrConstant((i == depth-1)?60:56));
1623       RetAddr = DAG.getLoad(MVT::i32, dl,
1624                             Chain,
1625                             Ptr,
1626                             MachinePointerInfo(), false, false, false, 0);
1627     }
1628   }
1629   return RetAddr;
1630 }
1631
1632 SDValue SparcTargetLowering::
1633 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1634   switch (Op.getOpcode()) {
1635   default: llvm_unreachable("Should not custom lower this!");
1636   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
1637   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
1638   case ISD::GlobalTLSAddress:
1639     llvm_unreachable("TLS not implemented for Sparc.");
1640   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
1641   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
1642   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
1643   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
1644   case ISD::BR_CC:              return LowerBR_CC(Op, DAG);
1645   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
1646   case ISD::VASTART:            return LowerVASTART(Op, DAG, *this);
1647   case ISD::VAARG:              return LowerVAARG(Op, DAG);
1648   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
1649   }
1650 }
1651
1652 MachineBasicBlock *
1653 SparcTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1654                                                  MachineBasicBlock *BB) const {
1655   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1656   unsigned BROpcode;
1657   unsigned CC;
1658   DebugLoc dl = MI->getDebugLoc();
1659   // Figure out the conditional branch opcode to use for this select_cc.
1660   switch (MI->getOpcode()) {
1661   default: llvm_unreachable("Unknown SELECT_CC!");
1662   case SP::SELECT_CC_Int_ICC:
1663   case SP::SELECT_CC_FP_ICC:
1664   case SP::SELECT_CC_DFP_ICC:
1665     BROpcode = SP::BCOND;
1666     break;
1667   case SP::SELECT_CC_Int_FCC:
1668   case SP::SELECT_CC_FP_FCC:
1669   case SP::SELECT_CC_DFP_FCC:
1670     BROpcode = SP::FBCOND;
1671     break;
1672   }
1673
1674   CC = (SPCC::CondCodes)MI->getOperand(3).getImm();
1675
1676   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1677   // control-flow pattern.  The incoming instruction knows the destination vreg
1678   // to set, the condition code register to branch on, the true/false values to
1679   // select between, and a branch opcode to use.
1680   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1681   MachineFunction::iterator It = BB;
1682   ++It;
1683
1684   //  thisMBB:
1685   //  ...
1686   //   TrueVal = ...
1687   //   [f]bCC copy1MBB
1688   //   fallthrough --> copy0MBB
1689   MachineBasicBlock *thisMBB = BB;
1690   MachineFunction *F = BB->getParent();
1691   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1692   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1693   F->insert(It, copy0MBB);
1694   F->insert(It, sinkMBB);
1695
1696   // Transfer the remainder of BB and its successor edges to sinkMBB.
1697   sinkMBB->splice(sinkMBB->begin(), BB,
1698                   llvm::next(MachineBasicBlock::iterator(MI)),
1699                   BB->end());
1700   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1701
1702   // Add the true and fallthrough blocks as its successors.
1703   BB->addSuccessor(copy0MBB);
1704   BB->addSuccessor(sinkMBB);
1705
1706   BuildMI(BB, dl, TII.get(BROpcode)).addMBB(sinkMBB).addImm(CC);
1707
1708   //  copy0MBB:
1709   //   %FalseValue = ...
1710   //   # fallthrough to sinkMBB
1711   BB = copy0MBB;
1712
1713   // Update machine-CFG edges
1714   BB->addSuccessor(sinkMBB);
1715
1716   //  sinkMBB:
1717   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1718   //  ...
1719   BB = sinkMBB;
1720   BuildMI(*BB, BB->begin(), dl, TII.get(SP::PHI), MI->getOperand(0).getReg())
1721     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1722     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1723
1724   MI->eraseFromParent();   // The pseudo instruction is gone now.
1725   return BB;
1726 }
1727
1728 //===----------------------------------------------------------------------===//
1729 //                         Sparc Inline Assembly Support
1730 //===----------------------------------------------------------------------===//
1731
1732 /// getConstraintType - Given a constraint letter, return the type of
1733 /// constraint it is for this target.
1734 SparcTargetLowering::ConstraintType
1735 SparcTargetLowering::getConstraintType(const std::string &Constraint) const {
1736   if (Constraint.size() == 1) {
1737     switch (Constraint[0]) {
1738     default:  break;
1739     case 'r': return C_RegisterClass;
1740     }
1741   }
1742
1743   return TargetLowering::getConstraintType(Constraint);
1744 }
1745
1746 std::pair<unsigned, const TargetRegisterClass*>
1747 SparcTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
1748                                                   EVT VT) const {
1749   if (Constraint.size() == 1) {
1750     switch (Constraint[0]) {
1751     case 'r':
1752       return std::make_pair(0U, &SP::IntRegsRegClass);
1753     }
1754   }
1755
1756   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1757 }
1758
1759 bool
1760 SparcTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1761   // The Sparc target isn't yet aware of offsets.
1762   return false;
1763 }