1 //===-- llvm/lib/Target/AMDGPU/AMDGPUCallLowering.cpp - Call lowering -----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements the lowering of LLVM calls to machine code calls for
11 /// GlobalISel.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "AMDGPUCallLowering.h"
16 #include "AMDGPU.h"
17 #include "AMDGPULegalizerInfo.h"
18 #include "AMDGPUTargetMachine.h"
19 #include "SIMachineFunctionInfo.h"
20 #include "SIRegisterInfo.h"
21 #include "llvm/CodeGen/Analysis.h"
22 #include "llvm/CodeGen/FunctionLoweringInfo.h"
23 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
24 #include "llvm/IR/IntrinsicsAMDGPU.h"
25 
26 #define DEBUG_TYPE "amdgpu-call-lowering"
27 
28 using namespace llvm;
29 
30 namespace {
31 
32 /// Wrapper around extendRegister to ensure we extend to a full 32-bit register.
33 static Register extendRegisterMin32(CallLowering::ValueHandler &Handler,
34                                     Register ValVReg, CCValAssign &VA) {
35   if (VA.getLocVT().getSizeInBits() < 32) {
36     // 16-bit types are reported as legal for 32-bit registers. We need to
37     // extend and do a 32-bit copy to avoid the verifier complaining about it.
38     return Handler.MIRBuilder.buildAnyExt(LLT::scalar(32), ValVReg).getReg(0);
39   }
40 
41   return Handler.extendRegister(ValVReg, VA);
42 }
43 
44 struct AMDGPUOutgoingValueHandler : public CallLowering::OutgoingValueHandler {
45   AMDGPUOutgoingValueHandler(MachineIRBuilder &B, MachineRegisterInfo &MRI,
46                              MachineInstrBuilder MIB)
47       : OutgoingValueHandler(B, MRI), MIB(MIB) {}
48 
49   MachineInstrBuilder MIB;
50 
51   Register getStackAddress(uint64_t Size, int64_t Offset,
52                            MachinePointerInfo &MPO,
53                            ISD::ArgFlagsTy Flags) override {
54     llvm_unreachable("not implemented");
55   }
56 
57   void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,
58                             MachinePointerInfo &MPO, CCValAssign &VA) override {
59     llvm_unreachable("not implemented");
60   }
61 
62   void assignValueToReg(Register ValVReg, Register PhysReg,
63                         CCValAssign &VA) override {
64     Register ExtReg = extendRegisterMin32(*this, ValVReg, VA);
65 
66     // If this is a scalar return, insert a readfirstlane just in case the value
67     // ends up in a VGPR.
68     // FIXME: Assert this is a shader return.
69     const SIRegisterInfo *TRI
70       = static_cast<const SIRegisterInfo *>(MRI.getTargetRegisterInfo());
71     if (TRI->isSGPRReg(MRI, PhysReg)) {
72       auto ToSGPR = MIRBuilder.buildIntrinsic(Intrinsic::amdgcn_readfirstlane,
73                                               {MRI.getType(ExtReg)}, false)
74         .addReg(ExtReg);
75       ExtReg = ToSGPR.getReg(0);
76     }
77 
78     MIRBuilder.buildCopy(PhysReg, ExtReg);
79     MIB.addUse(PhysReg, RegState::Implicit);
80   }
81 };
82 
83 struct AMDGPUIncomingArgHandler : public CallLowering::IncomingValueHandler {
84   uint64_t StackUsed = 0;
85 
86   AMDGPUIncomingArgHandler(MachineIRBuilder &B, MachineRegisterInfo &MRI)
87       : IncomingValueHandler(B, MRI) {}
88 
89   Register getStackAddress(uint64_t Size, int64_t Offset,
90                            MachinePointerInfo &MPO,
91                            ISD::ArgFlagsTy Flags) override {
92     auto &MFI = MIRBuilder.getMF().getFrameInfo();
93 
94     // Byval is assumed to be writable memory, but other stack passed arguments
95     // are not.
96     const bool IsImmutable = !Flags.isByVal();
97     int FI = MFI.CreateFixedObject(Size, Offset, IsImmutable);
98     MPO = MachinePointerInfo::getFixedStack(MIRBuilder.getMF(), FI);
99     auto AddrReg = MIRBuilder.buildFrameIndex(
100         LLT::pointer(AMDGPUAS::PRIVATE_ADDRESS, 32), FI);
101     StackUsed = std::max(StackUsed, Size + Offset);
102     return AddrReg.getReg(0);
103   }
104 
105   void assignValueToReg(Register ValVReg, Register PhysReg,
106                         CCValAssign &VA) override {
107     markPhysRegUsed(PhysReg);
108 
109     if (VA.getLocVT().getSizeInBits() < 32) {
110       // 16-bit types are reported as legal for 32-bit registers. We need to do
111       // a 32-bit copy, and truncate to avoid the verifier complaining about it.
112       auto Copy = MIRBuilder.buildCopy(LLT::scalar(32), PhysReg);
113 
114       // If we have signext/zeroext, it applies to the whole 32-bit register
115       // before truncation.
116       auto Extended =
117           buildExtensionHint(VA, Copy.getReg(0), LLT(VA.getLocVT()));
118       MIRBuilder.buildTrunc(ValVReg, Extended);
119       return;
120     }
121 
122     IncomingValueHandler::assignValueToReg(ValVReg, PhysReg, VA);
123   }
124 
125   void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,
126                             MachinePointerInfo &MPO, CCValAssign &VA) override {
127     MachineFunction &MF = MIRBuilder.getMF();
128 
129     auto MMO = MF.getMachineMemOperand(
130         MPO, MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant, MemTy,
131         inferAlignFromPtrInfo(MF, MPO));
132     MIRBuilder.buildLoad(ValVReg, Addr, *MMO);
133   }
134 
135   /// How the physical register gets marked varies between formal
136   /// parameters (it's a basic-block live-in), and a call instruction
137   /// (it's an implicit-def of the BL).
138   virtual void markPhysRegUsed(unsigned PhysReg) = 0;
139 };
140 
141 struct FormalArgHandler : public AMDGPUIncomingArgHandler {
142   FormalArgHandler(MachineIRBuilder &B, MachineRegisterInfo &MRI)
143       : AMDGPUIncomingArgHandler(B, MRI) {}
144 
145   void markPhysRegUsed(unsigned PhysReg) override {
146     MIRBuilder.getMBB().addLiveIn(PhysReg);
147   }
148 };
149 
150 struct CallReturnHandler : public AMDGPUIncomingArgHandler {
151   CallReturnHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
152                     MachineInstrBuilder MIB)
153       : AMDGPUIncomingArgHandler(MIRBuilder, MRI), MIB(MIB) {}
154 
155   void markPhysRegUsed(unsigned PhysReg) override {
156     MIB.addDef(PhysReg, RegState::Implicit);
157   }
158 
159   MachineInstrBuilder MIB;
160 };
161 
162 struct AMDGPUOutgoingArgHandler : public AMDGPUOutgoingValueHandler {
163   /// For tail calls, the byte offset of the call's argument area from the
164   /// callee's. Unused elsewhere.
165   int FPDiff;
166 
167   // Cache the SP register vreg if we need it more than once in this call site.
168   Register SPReg;
169 
170   bool IsTailCall;
171 
172   AMDGPUOutgoingArgHandler(MachineIRBuilder &MIRBuilder,
173                            MachineRegisterInfo &MRI, MachineInstrBuilder MIB,
174                            bool IsTailCall = false, int FPDiff = 0)
175       : AMDGPUOutgoingValueHandler(MIRBuilder, MRI, MIB), FPDiff(FPDiff),
176         IsTailCall(IsTailCall) {}
177 
178   Register getStackAddress(uint64_t Size, int64_t Offset,
179                            MachinePointerInfo &MPO,
180                            ISD::ArgFlagsTy Flags) override {
181     MachineFunction &MF = MIRBuilder.getMF();
182     const LLT PtrTy = LLT::pointer(AMDGPUAS::PRIVATE_ADDRESS, 32);
183     const LLT S32 = LLT::scalar(32);
184 
185     if (IsTailCall) {
186       Offset += FPDiff;
187       int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
188       auto FIReg = MIRBuilder.buildFrameIndex(PtrTy, FI);
189       MPO = MachinePointerInfo::getFixedStack(MF, FI);
190       return FIReg.getReg(0);
191     }
192 
193     const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
194 
195     if (!SPReg)
196       SPReg = MIRBuilder.buildCopy(PtrTy, MFI->getStackPtrOffsetReg()).getReg(0);
197 
198     auto OffsetReg = MIRBuilder.buildConstant(S32, Offset);
199 
200     auto AddrReg = MIRBuilder.buildPtrAdd(PtrTy, SPReg, OffsetReg);
201     MPO = MachinePointerInfo::getStack(MF, Offset);
202     return AddrReg.getReg(0);
203   }
204 
205   void assignValueToReg(Register ValVReg, Register PhysReg,
206                         CCValAssign &VA) override {
207     MIB.addUse(PhysReg, RegState::Implicit);
208     Register ExtReg = extendRegisterMin32(*this, ValVReg, VA);
209     MIRBuilder.buildCopy(PhysReg, ExtReg);
210   }
211 
212   void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,
213                             MachinePointerInfo &MPO, CCValAssign &VA) override {
214     MachineFunction &MF = MIRBuilder.getMF();
215     uint64_t LocMemOffset = VA.getLocMemOffset();
216     const auto &ST = MF.getSubtarget<GCNSubtarget>();
217 
218     auto MMO = MF.getMachineMemOperand(
219         MPO, MachineMemOperand::MOStore, MemTy,
220         commonAlignment(ST.getStackAlignment(), LocMemOffset));
221     MIRBuilder.buildStore(ValVReg, Addr, *MMO);
222   }
223 
224   void assignValueToAddress(const CallLowering::ArgInfo &Arg,
225                             unsigned ValRegIndex, Register Addr, LLT MemTy,
226                             MachinePointerInfo &MPO, CCValAssign &VA) override {
227     Register ValVReg = VA.getLocInfo() != CCValAssign::LocInfo::FPExt
228                            ? extendRegister(Arg.Regs[ValRegIndex], VA)
229                            : Arg.Regs[ValRegIndex];
230     assignValueToAddress(ValVReg, Addr, MemTy, MPO, VA);
231   }
232 };
233 }
234 
235 AMDGPUCallLowering::AMDGPUCallLowering(const AMDGPUTargetLowering &TLI)
236   : CallLowering(&TLI) {
237 }
238 
239 // FIXME: Compatability shim
240 static ISD::NodeType extOpcodeToISDExtOpcode(unsigned MIOpc) {
241   switch (MIOpc) {
242   case TargetOpcode::G_SEXT:
243     return ISD::SIGN_EXTEND;
244   case TargetOpcode::G_ZEXT:
245     return ISD::ZERO_EXTEND;
246   case TargetOpcode::G_ANYEXT:
247     return ISD::ANY_EXTEND;
248   default:
249     llvm_unreachable("not an extend opcode");
250   }
251 }
252 
253 bool AMDGPUCallLowering::canLowerReturn(MachineFunction &MF,
254                                         CallingConv::ID CallConv,
255                                         SmallVectorImpl<BaseArgInfo> &Outs,
256                                         bool IsVarArg) const {
257   // For shaders. Vector types should be explicitly handled by CC.
258   if (AMDGPU::isEntryFunctionCC(CallConv))
259     return true;
260 
261   SmallVector<CCValAssign, 16> ArgLocs;
262   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
263   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs,
264                  MF.getFunction().getContext());
265 
266   return checkReturn(CCInfo, Outs, TLI.CCAssignFnForReturn(CallConv, IsVarArg));
267 }
268 
269 /// Lower the return value for the already existing \p Ret. This assumes that
270 /// \p B's insertion point is correct.
271 bool AMDGPUCallLowering::lowerReturnVal(MachineIRBuilder &B,
272                                         const Value *Val, ArrayRef<Register> VRegs,
273                                         MachineInstrBuilder &Ret) const {
274   if (!Val)
275     return true;
276 
277   auto &MF = B.getMF();
278   const auto &F = MF.getFunction();
279   const DataLayout &DL = MF.getDataLayout();
280   MachineRegisterInfo *MRI = B.getMRI();
281   LLVMContext &Ctx = F.getContext();
282 
283   CallingConv::ID CC = F.getCallingConv();
284   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
285 
286   SmallVector<EVT, 8> SplitEVTs;
287   ComputeValueVTs(TLI, DL, Val->getType(), SplitEVTs);
288   assert(VRegs.size() == SplitEVTs.size() &&
289          "For each split Type there should be exactly one VReg.");
290 
291   SmallVector<ArgInfo, 8> SplitRetInfos;
292 
293   for (unsigned i = 0; i < SplitEVTs.size(); ++i) {
294     EVT VT = SplitEVTs[i];
295     Register Reg = VRegs[i];
296     ArgInfo RetInfo(Reg, VT.getTypeForEVT(Ctx));
297     setArgFlags(RetInfo, AttributeList::ReturnIndex, DL, F);
298 
299     if (VT.isScalarInteger()) {
300       unsigned ExtendOp = TargetOpcode::G_ANYEXT;
301       if (RetInfo.Flags[0].isSExt()) {
302         assert(RetInfo.Regs.size() == 1 && "expect only simple return values");
303         ExtendOp = TargetOpcode::G_SEXT;
304       } else if (RetInfo.Flags[0].isZExt()) {
305         assert(RetInfo.Regs.size() == 1 && "expect only simple return values");
306         ExtendOp = TargetOpcode::G_ZEXT;
307       }
308 
309       EVT ExtVT = TLI.getTypeForExtReturn(Ctx, VT,
310                                           extOpcodeToISDExtOpcode(ExtendOp));
311       if (ExtVT != VT) {
312         RetInfo.Ty = ExtVT.getTypeForEVT(Ctx);
313         LLT ExtTy = getLLTForType(*RetInfo.Ty, DL);
314         Reg = B.buildInstr(ExtendOp, {ExtTy}, {Reg}).getReg(0);
315       }
316     }
317 
318     if (Reg != RetInfo.Regs[0]) {
319       RetInfo.Regs[0] = Reg;
320       // Reset the arg flags after modifying Reg.
321       setArgFlags(RetInfo, AttributeList::ReturnIndex, DL, F);
322     }
323 
324     splitToValueTypes(RetInfo, SplitRetInfos, DL, CC);
325   }
326 
327   CCAssignFn *AssignFn = TLI.CCAssignFnForReturn(CC, F.isVarArg());
328 
329   OutgoingValueAssigner Assigner(AssignFn);
330   AMDGPUOutgoingValueHandler RetHandler(B, *MRI, Ret);
331   return determineAndHandleAssignments(RetHandler, Assigner, SplitRetInfos, B,
332                                        CC, F.isVarArg());
333 }
334 
335 bool AMDGPUCallLowering::lowerReturn(MachineIRBuilder &B, const Value *Val,
336                                      ArrayRef<Register> VRegs,
337                                      FunctionLoweringInfo &FLI) const {
338 
339   MachineFunction &MF = B.getMF();
340   MachineRegisterInfo &MRI = MF.getRegInfo();
341   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
342   MFI->setIfReturnsVoid(!Val);
343 
344   assert(!Val == VRegs.empty() && "Return value without a vreg");
345 
346   CallingConv::ID CC = B.getMF().getFunction().getCallingConv();
347   const bool IsShader = AMDGPU::isShader(CC);
348   const bool IsWaveEnd =
349       (IsShader && MFI->returnsVoid()) || AMDGPU::isKernel(CC);
350   if (IsWaveEnd) {
351     B.buildInstr(AMDGPU::S_ENDPGM)
352       .addImm(0);
353     return true;
354   }
355 
356   auto const &ST = MF.getSubtarget<GCNSubtarget>();
357 
358   unsigned ReturnOpc =
359       IsShader ? AMDGPU::SI_RETURN_TO_EPILOG : AMDGPU::S_SETPC_B64_return;
360 
361   auto Ret = B.buildInstrNoInsert(ReturnOpc);
362   Register ReturnAddrVReg;
363   if (ReturnOpc == AMDGPU::S_SETPC_B64_return) {
364     ReturnAddrVReg = MRI.createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass);
365     Ret.addUse(ReturnAddrVReg);
366   }
367 
368   if (!FLI.CanLowerReturn)
369     insertSRetStores(B, Val->getType(), VRegs, FLI.DemoteRegister);
370   else if (!lowerReturnVal(B, Val, VRegs, Ret))
371     return false;
372 
373   if (ReturnOpc == AMDGPU::S_SETPC_B64_return) {
374     const SIRegisterInfo *TRI = ST.getRegisterInfo();
375     Register LiveInReturn = MF.addLiveIn(TRI->getReturnAddressReg(MF),
376                                          &AMDGPU::SGPR_64RegClass);
377     B.buildCopy(ReturnAddrVReg, LiveInReturn);
378   }
379 
380   // TODO: Handle CalleeSavedRegsViaCopy.
381 
382   B.insertInstr(Ret);
383   return true;
384 }
385 
386 void AMDGPUCallLowering::lowerParameterPtr(Register DstReg, MachineIRBuilder &B,
387                                            Type *ParamTy,
388                                            uint64_t Offset) const {
389   MachineFunction &MF = B.getMF();
390   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
391   MachineRegisterInfo &MRI = MF.getRegInfo();
392   Register KernArgSegmentPtr =
393     MFI->getPreloadedReg(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
394   Register KernArgSegmentVReg = MRI.getLiveInVirtReg(KernArgSegmentPtr);
395 
396   auto OffsetReg = B.buildConstant(LLT::scalar(64), Offset);
397 
398   B.buildPtrAdd(DstReg, KernArgSegmentVReg, OffsetReg);
399 }
400 
401 void AMDGPUCallLowering::lowerParameter(MachineIRBuilder &B, Type *ParamTy,
402                                         uint64_t Offset, Align Alignment,
403                                         Register DstReg) const {
404   MachineFunction &MF = B.getMF();
405   const Function &F = MF.getFunction();
406   const DataLayout &DL = F.getParent()->getDataLayout();
407   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
408   unsigned TypeSize = DL.getTypeStoreSize(ParamTy);
409 
410   LLT PtrTy = LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64);
411   Register PtrReg = B.getMRI()->createGenericVirtualRegister(PtrTy);
412   lowerParameterPtr(PtrReg, B, ParamTy, Offset);
413 
414   MachineMemOperand *MMO = MF.getMachineMemOperand(
415       PtrInfo,
416       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
417           MachineMemOperand::MOInvariant,
418       TypeSize, Alignment);
419 
420   B.buildLoad(DstReg, PtrReg, *MMO);
421 }
422 
423 // Allocate special inputs passed in user SGPRs.
424 static void allocateHSAUserSGPRs(CCState &CCInfo,
425                                  MachineIRBuilder &B,
426                                  MachineFunction &MF,
427                                  const SIRegisterInfo &TRI,
428                                  SIMachineFunctionInfo &Info) {
429   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
430   if (Info.hasPrivateSegmentBuffer()) {
431     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
432     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
433     CCInfo.AllocateReg(PrivateSegmentBufferReg);
434   }
435 
436   if (Info.hasDispatchPtr()) {
437     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
438     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
439     CCInfo.AllocateReg(DispatchPtrReg);
440   }
441 
442   if (Info.hasQueuePtr()) {
443     Register QueuePtrReg = Info.addQueuePtr(TRI);
444     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
445     CCInfo.AllocateReg(QueuePtrReg);
446   }
447 
448   if (Info.hasKernargSegmentPtr()) {
449     MachineRegisterInfo &MRI = MF.getRegInfo();
450     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
451     const LLT P4 = LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64);
452     Register VReg = MRI.createGenericVirtualRegister(P4);
453     MRI.addLiveIn(InputPtrReg, VReg);
454     B.getMBB().addLiveIn(InputPtrReg);
455     B.buildCopy(VReg, InputPtrReg);
456     CCInfo.AllocateReg(InputPtrReg);
457   }
458 
459   if (Info.hasDispatchID()) {
460     Register DispatchIDReg = Info.addDispatchID(TRI);
461     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
462     CCInfo.AllocateReg(DispatchIDReg);
463   }
464 
465   if (Info.hasFlatScratchInit()) {
466     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
467     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
468     CCInfo.AllocateReg(FlatScratchInitReg);
469   }
470 
471   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
472   // these from the dispatch pointer.
473 }
474 
475 bool AMDGPUCallLowering::lowerFormalArgumentsKernel(
476     MachineIRBuilder &B, const Function &F,
477     ArrayRef<ArrayRef<Register>> VRegs) const {
478   MachineFunction &MF = B.getMF();
479   const GCNSubtarget *Subtarget = &MF.getSubtarget<GCNSubtarget>();
480   MachineRegisterInfo &MRI = MF.getRegInfo();
481   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
482   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
483   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
484   const DataLayout &DL = F.getParent()->getDataLayout();
485 
486   Info->allocateModuleLDSGlobal(F.getParent());
487 
488   SmallVector<CCValAssign, 16> ArgLocs;
489   CCState CCInfo(F.getCallingConv(), F.isVarArg(), MF, ArgLocs, F.getContext());
490 
491   allocateHSAUserSGPRs(CCInfo, B, MF, *TRI, *Info);
492 
493   unsigned i = 0;
494   const Align KernArgBaseAlign(16);
495   const unsigned BaseOffset = Subtarget->getExplicitKernelArgOffset(F);
496   uint64_t ExplicitArgOffset = 0;
497 
498   // TODO: Align down to dword alignment and extract bits for extending loads.
499   for (auto &Arg : F.args()) {
500     const bool IsByRef = Arg.hasByRefAttr();
501     Type *ArgTy = IsByRef ? Arg.getParamByRefType() : Arg.getType();
502     unsigned AllocSize = DL.getTypeAllocSize(ArgTy);
503     if (AllocSize == 0)
504       continue;
505 
506     MaybeAlign ABIAlign = IsByRef ? Arg.getParamAlign() : None;
507     if (!ABIAlign)
508       ABIAlign = DL.getABITypeAlign(ArgTy);
509 
510     uint64_t ArgOffset = alignTo(ExplicitArgOffset, ABIAlign) + BaseOffset;
511     ExplicitArgOffset = alignTo(ExplicitArgOffset, ABIAlign) + AllocSize;
512 
513     if (Arg.use_empty()) {
514       ++i;
515       continue;
516     }
517 
518     Align Alignment = commonAlignment(KernArgBaseAlign, ArgOffset);
519 
520     if (IsByRef) {
521       unsigned ByRefAS = cast<PointerType>(Arg.getType())->getAddressSpace();
522 
523       assert(VRegs[i].size() == 1 &&
524              "expected only one register for byval pointers");
525       if (ByRefAS == AMDGPUAS::CONSTANT_ADDRESS) {
526         lowerParameterPtr(VRegs[i][0], B, ArgTy, ArgOffset);
527       } else {
528         const LLT ConstPtrTy = LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64);
529         Register PtrReg = MRI.createGenericVirtualRegister(ConstPtrTy);
530         lowerParameterPtr(PtrReg, B, ArgTy, ArgOffset);
531 
532         B.buildAddrSpaceCast(VRegs[i][0], PtrReg);
533       }
534     } else {
535       ArrayRef<Register> OrigArgRegs = VRegs[i];
536       Register ArgReg =
537         OrigArgRegs.size() == 1
538         ? OrigArgRegs[0]
539         : MRI.createGenericVirtualRegister(getLLTForType(*ArgTy, DL));
540 
541       lowerParameter(B, ArgTy, ArgOffset, Alignment, ArgReg);
542       if (OrigArgRegs.size() > 1)
543         unpackRegs(OrigArgRegs, ArgReg, ArgTy, B);
544     }
545 
546     ++i;
547   }
548 
549   TLI.allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
550   TLI.allocateSystemSGPRs(CCInfo, MF, *Info, F.getCallingConv(), false);
551   return true;
552 }
553 
554 bool AMDGPUCallLowering::lowerFormalArguments(
555     MachineIRBuilder &B, const Function &F, ArrayRef<ArrayRef<Register>> VRegs,
556     FunctionLoweringInfo &FLI) const {
557   CallingConv::ID CC = F.getCallingConv();
558 
559   // The infrastructure for normal calling convention lowering is essentially
560   // useless for kernels. We want to avoid any kind of legalization or argument
561   // splitting.
562   if (CC == CallingConv::AMDGPU_KERNEL)
563     return lowerFormalArgumentsKernel(B, F, VRegs);
564 
565   const bool IsGraphics = AMDGPU::isGraphics(CC);
566   const bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CC);
567 
568   MachineFunction &MF = B.getMF();
569   MachineBasicBlock &MBB = B.getMBB();
570   MachineRegisterInfo &MRI = MF.getRegInfo();
571   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
572   const GCNSubtarget &Subtarget = MF.getSubtarget<GCNSubtarget>();
573   const SIRegisterInfo *TRI = Subtarget.getRegisterInfo();
574   const DataLayout &DL = F.getParent()->getDataLayout();
575 
576   Info->allocateModuleLDSGlobal(F.getParent());
577 
578   SmallVector<CCValAssign, 16> ArgLocs;
579   CCState CCInfo(CC, F.isVarArg(), MF, ArgLocs, F.getContext());
580 
581   if (!IsEntryFunc) {
582     Register ReturnAddrReg = TRI->getReturnAddressReg(MF);
583     Register LiveInReturn = MF.addLiveIn(ReturnAddrReg,
584                                          &AMDGPU::SGPR_64RegClass);
585     MBB.addLiveIn(ReturnAddrReg);
586     B.buildCopy(LiveInReturn, ReturnAddrReg);
587   }
588 
589   if (Info->hasImplicitBufferPtr()) {
590     Register ImplicitBufferPtrReg = Info->addImplicitBufferPtr(*TRI);
591     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
592     CCInfo.AllocateReg(ImplicitBufferPtrReg);
593   }
594 
595   SmallVector<ArgInfo, 32> SplitArgs;
596   unsigned Idx = 0;
597   unsigned PSInputNum = 0;
598 
599   // Insert the hidden sret parameter if the return value won't fit in the
600   // return registers.
601   if (!FLI.CanLowerReturn)
602     insertSRetIncomingArgument(F, SplitArgs, FLI.DemoteRegister, MRI, DL);
603 
604   for (auto &Arg : F.args()) {
605     if (DL.getTypeStoreSize(Arg.getType()) == 0)
606       continue;
607 
608     const bool InReg = Arg.hasAttribute(Attribute::InReg);
609 
610     // SGPR arguments to functions not implemented.
611     if (!IsGraphics && InReg)
612       return false;
613 
614     if (Arg.hasAttribute(Attribute::SwiftSelf) ||
615         Arg.hasAttribute(Attribute::SwiftError) ||
616         Arg.hasAttribute(Attribute::Nest))
617       return false;
618 
619     if (CC == CallingConv::AMDGPU_PS && !InReg && PSInputNum <= 15) {
620       const bool ArgUsed = !Arg.use_empty();
621       bool SkipArg = !ArgUsed && !Info->isPSInputAllocated(PSInputNum);
622 
623       if (!SkipArg) {
624         Info->markPSInputAllocated(PSInputNum);
625         if (ArgUsed)
626           Info->markPSInputEnabled(PSInputNum);
627       }
628 
629       ++PSInputNum;
630 
631       if (SkipArg) {
632         for (int I = 0, E = VRegs[Idx].size(); I != E; ++I)
633           B.buildUndef(VRegs[Idx][I]);
634 
635         ++Idx;
636         continue;
637       }
638     }
639 
640     ArgInfo OrigArg(VRegs[Idx], Arg);
641     const unsigned OrigArgIdx = Idx + AttributeList::FirstArgIndex;
642     setArgFlags(OrigArg, OrigArgIdx, DL, F);
643 
644     splitToValueTypes(OrigArg, SplitArgs, DL, CC);
645     ++Idx;
646   }
647 
648   // At least one interpolation mode must be enabled or else the GPU will
649   // hang.
650   //
651   // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
652   // set PSInputAddr, the user wants to enable some bits after the compilation
653   // based on run-time states. Since we can't know what the final PSInputEna
654   // will look like, so we shouldn't do anything here and the user should take
655   // responsibility for the correct programming.
656   //
657   // Otherwise, the following restrictions apply:
658   // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
659   // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
660   //   enabled too.
661   if (CC == CallingConv::AMDGPU_PS) {
662     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
663         ((Info->getPSInputAddr() & 0xF) == 0 &&
664          Info->isPSInputAllocated(11))) {
665       CCInfo.AllocateReg(AMDGPU::VGPR0);
666       CCInfo.AllocateReg(AMDGPU::VGPR1);
667       Info->markPSInputAllocated(0);
668       Info->markPSInputEnabled(0);
669     }
670 
671     if (Subtarget.isAmdPalOS()) {
672       // For isAmdPalOS, the user does not enable some bits after compilation
673       // based on run-time states; the register values being generated here are
674       // the final ones set in hardware. Therefore we need to apply the
675       // workaround to PSInputAddr and PSInputEnable together.  (The case where
676       // a bit is set in PSInputAddr but not PSInputEnable is where the frontend
677       // set up an input arg for a particular interpolation mode, but nothing
678       // uses that input arg. Really we should have an earlier pass that removes
679       // such an arg.)
680       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
681       if ((PsInputBits & 0x7F) == 0 ||
682           ((PsInputBits & 0xF) == 0 &&
683            (PsInputBits >> 11 & 1)))
684         Info->markPSInputEnabled(
685           countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
686     }
687   }
688 
689   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
690   CCAssignFn *AssignFn = TLI.CCAssignFnForCall(CC, F.isVarArg());
691 
692   if (!MBB.empty())
693     B.setInstr(*MBB.begin());
694 
695   if (!IsEntryFunc) {
696     // For the fixed ABI, pass workitem IDs in the last argument register.
697     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
698       TLI.allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
699   }
700 
701   IncomingValueAssigner Assigner(AssignFn);
702   if (!determineAssignments(Assigner, SplitArgs, CCInfo))
703     return false;
704 
705   FormalArgHandler Handler(B, MRI);
706   if (!handleAssignments(Handler, SplitArgs, CCInfo, ArgLocs, B))
707     return false;
708 
709   uint64_t StackOffset = Assigner.StackOffset;
710 
711   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
712     // Special inputs come after user arguments.
713     TLI.allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
714   }
715 
716   // Start adding system SGPRs.
717   if (IsEntryFunc) {
718     TLI.allocateSystemSGPRs(CCInfo, MF, *Info, CC, IsGraphics);
719   } else {
720     if (!Subtarget.enableFlatScratch())
721       CCInfo.AllocateReg(Info->getScratchRSrcReg());
722     TLI.allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
723   }
724 
725   // When we tail call, we need to check if the callee's arguments will fit on
726   // the caller's stack. So, whenever we lower formal arguments, we should keep
727   // track of this information, since we might lower a tail call in this
728   // function later.
729   Info->setBytesInStackArgArea(StackOffset);
730 
731   // Move back to the end of the basic block.
732   B.setMBB(MBB);
733 
734   return true;
735 }
736 
737 bool AMDGPUCallLowering::passSpecialInputs(MachineIRBuilder &MIRBuilder,
738                                            CCState &CCInfo,
739                                            SmallVectorImpl<std::pair<MCRegister, Register>> &ArgRegs,
740                                            CallLoweringInfo &Info) const {
741   MachineFunction &MF = MIRBuilder.getMF();
742 
743   const AMDGPUFunctionArgInfo *CalleeArgInfo
744     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
745 
746   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
747   const AMDGPUFunctionArgInfo &CallerArgInfo = MFI->getArgInfo();
748 
749 
750   // TODO: Unify with private memory register handling. This is complicated by
751   // the fact that at least in kernels, the input argument is not necessarily
752   // in the same location as the input.
753   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
754     AMDGPUFunctionArgInfo::DISPATCH_PTR,
755     AMDGPUFunctionArgInfo::QUEUE_PTR,
756     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
757     AMDGPUFunctionArgInfo::DISPATCH_ID,
758     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
759     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
760     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
761   };
762 
763   MachineRegisterInfo &MRI = MF.getRegInfo();
764 
765   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
766   const AMDGPULegalizerInfo *LI
767     = static_cast<const AMDGPULegalizerInfo*>(ST.getLegalizerInfo());
768 
769   for (auto InputID : InputRegs) {
770     const ArgDescriptor *OutgoingArg;
771     const TargetRegisterClass *ArgRC;
772     LLT ArgTy;
773 
774     std::tie(OutgoingArg, ArgRC, ArgTy) =
775         CalleeArgInfo->getPreloadedValue(InputID);
776     if (!OutgoingArg)
777       continue;
778 
779     const ArgDescriptor *IncomingArg;
780     const TargetRegisterClass *IncomingArgRC;
781     std::tie(IncomingArg, IncomingArgRC, ArgTy) =
782         CallerArgInfo.getPreloadedValue(InputID);
783     assert(IncomingArgRC == ArgRC);
784 
785     Register InputReg = MRI.createGenericVirtualRegister(ArgTy);
786 
787     if (IncomingArg) {
788       LI->loadInputValue(InputReg, MIRBuilder, IncomingArg, ArgRC, ArgTy);
789     } else {
790       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
791       LI->getImplicitArgPtr(InputReg, MRI, MIRBuilder);
792     }
793 
794     if (OutgoingArg->isRegister()) {
795       ArgRegs.emplace_back(OutgoingArg->getRegister(), InputReg);
796       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
797         report_fatal_error("failed to allocate implicit input argument");
798     } else {
799       LLVM_DEBUG(dbgs() << "Unhandled stack passed implicit input argument\n");
800       return false;
801     }
802   }
803 
804   // Pack workitem IDs into a single register or pass it as is if already
805   // packed.
806   const ArgDescriptor *OutgoingArg;
807   const TargetRegisterClass *ArgRC;
808   LLT ArgTy;
809 
810   std::tie(OutgoingArg, ArgRC, ArgTy) =
811       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
812   if (!OutgoingArg)
813     std::tie(OutgoingArg, ArgRC, ArgTy) =
814         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
815   if (!OutgoingArg)
816     std::tie(OutgoingArg, ArgRC, ArgTy) =
817         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
818   if (!OutgoingArg)
819     return false;
820 
821   auto WorkitemIDX =
822       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
823   auto WorkitemIDY =
824       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
825   auto WorkitemIDZ =
826       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
827 
828   const ArgDescriptor *IncomingArgX = std::get<0>(WorkitemIDX);
829   const ArgDescriptor *IncomingArgY = std::get<0>(WorkitemIDY);
830   const ArgDescriptor *IncomingArgZ = std::get<0>(WorkitemIDZ);
831   const LLT S32 = LLT::scalar(32);
832 
833   // If incoming ids are not packed we need to pack them.
834   // FIXME: Should consider known workgroup size to eliminate known 0 cases.
835   Register InputReg;
836   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) {
837     InputReg = MRI.createGenericVirtualRegister(S32);
838     LI->loadInputValue(InputReg, MIRBuilder, IncomingArgX,
839                        std::get<1>(WorkitemIDX), std::get<2>(WorkitemIDX));
840   }
841 
842   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
843     Register Y = MRI.createGenericVirtualRegister(S32);
844     LI->loadInputValue(Y, MIRBuilder, IncomingArgY, std::get<1>(WorkitemIDY),
845                        std::get<2>(WorkitemIDY));
846 
847     Y = MIRBuilder.buildShl(S32, Y, MIRBuilder.buildConstant(S32, 10)).getReg(0);
848     InputReg = InputReg ? MIRBuilder.buildOr(S32, InputReg, Y).getReg(0) : Y;
849   }
850 
851   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
852     Register Z = MRI.createGenericVirtualRegister(S32);
853     LI->loadInputValue(Z, MIRBuilder, IncomingArgZ, std::get<1>(WorkitemIDZ),
854                        std::get<2>(WorkitemIDZ));
855 
856     Z = MIRBuilder.buildShl(S32, Z, MIRBuilder.buildConstant(S32, 20)).getReg(0);
857     InputReg = InputReg ? MIRBuilder.buildOr(S32, InputReg, Z).getReg(0) : Z;
858   }
859 
860   if (!InputReg) {
861     InputReg = MRI.createGenericVirtualRegister(S32);
862 
863     // Workitem ids are already packed, any of present incoming arguments will
864     // carry all required fields.
865     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
866       IncomingArgX ? *IncomingArgX :
867         IncomingArgY ? *IncomingArgY : *IncomingArgZ, ~0u);
868     LI->loadInputValue(InputReg, MIRBuilder, &IncomingArg,
869                        &AMDGPU::VGPR_32RegClass, S32);
870   }
871 
872   if (OutgoingArg->isRegister()) {
873     ArgRegs.emplace_back(OutgoingArg->getRegister(), InputReg);
874     if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
875       report_fatal_error("failed to allocate implicit input argument");
876   } else {
877     LLVM_DEBUG(dbgs() << "Unhandled stack passed implicit input argument\n");
878     return false;
879   }
880 
881   return true;
882 }
883 
884 /// Returns a pair containing the fixed CCAssignFn and the vararg CCAssignFn for
885 /// CC.
886 static std::pair<CCAssignFn *, CCAssignFn *>
887 getAssignFnsForCC(CallingConv::ID CC, const SITargetLowering &TLI) {
888   return {TLI.CCAssignFnForCall(CC, false), TLI.CCAssignFnForCall(CC, true)};
889 }
890 
891 static unsigned getCallOpcode(const MachineFunction &CallerF, bool IsIndirect,
892                               bool IsTailCall) {
893   return IsTailCall ? AMDGPU::SI_TCRETURN : AMDGPU::SI_CALL;
894 }
895 
896 // Add operands to call instruction to track the callee.
897 static bool addCallTargetOperands(MachineInstrBuilder &CallInst,
898                                   MachineIRBuilder &MIRBuilder,
899                                   AMDGPUCallLowering::CallLoweringInfo &Info) {
900   if (Info.Callee.isReg()) {
901     CallInst.addReg(Info.Callee.getReg());
902     CallInst.addImm(0);
903   } else if (Info.Callee.isGlobal() && Info.Callee.getOffset() == 0) {
904     // The call lowering lightly assumed we can directly encode a call target in
905     // the instruction, which is not the case. Materialize the address here.
906     const GlobalValue *GV = Info.Callee.getGlobal();
907     auto Ptr = MIRBuilder.buildGlobalValue(
908       LLT::pointer(GV->getAddressSpace(), 64), GV);
909     CallInst.addReg(Ptr.getReg(0));
910     CallInst.add(Info.Callee);
911   } else
912     return false;
913 
914   return true;
915 }
916 
917 bool AMDGPUCallLowering::doCallerAndCalleePassArgsTheSameWay(
918     CallLoweringInfo &Info, MachineFunction &MF,
919     SmallVectorImpl<ArgInfo> &InArgs) const {
920   const Function &CallerF = MF.getFunction();
921   CallingConv::ID CalleeCC = Info.CallConv;
922   CallingConv::ID CallerCC = CallerF.getCallingConv();
923 
924   // If the calling conventions match, then everything must be the same.
925   if (CalleeCC == CallerCC)
926     return true;
927 
928   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
929 
930   // Make sure that the caller and callee preserve all of the same registers.
931   auto TRI = ST.getRegisterInfo();
932 
933   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
934   const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
935   if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
936     return false;
937 
938   // Check if the caller and callee will handle arguments in the same way.
939   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
940   CCAssignFn *CalleeAssignFnFixed;
941   CCAssignFn *CalleeAssignFnVarArg;
942   std::tie(CalleeAssignFnFixed, CalleeAssignFnVarArg) =
943       getAssignFnsForCC(CalleeCC, TLI);
944 
945   CCAssignFn *CallerAssignFnFixed;
946   CCAssignFn *CallerAssignFnVarArg;
947   std::tie(CallerAssignFnFixed, CallerAssignFnVarArg) =
948       getAssignFnsForCC(CallerCC, TLI);
949 
950   // FIXME: We are not accounting for potential differences in implicitly passed
951   // inputs, but only the fixed ABI is supported now anyway.
952   IncomingValueAssigner CalleeAssigner(CalleeAssignFnFixed,
953                                        CalleeAssignFnVarArg);
954   IncomingValueAssigner CallerAssigner(CallerAssignFnFixed,
955                                        CallerAssignFnVarArg);
956   return resultsCompatible(Info, MF, InArgs, CalleeAssigner, CallerAssigner);
957 }
958 
959 bool AMDGPUCallLowering::areCalleeOutgoingArgsTailCallable(
960     CallLoweringInfo &Info, MachineFunction &MF,
961     SmallVectorImpl<ArgInfo> &OutArgs) const {
962   // If there are no outgoing arguments, then we are done.
963   if (OutArgs.empty())
964     return true;
965 
966   const Function &CallerF = MF.getFunction();
967   CallingConv::ID CalleeCC = Info.CallConv;
968   CallingConv::ID CallerCC = CallerF.getCallingConv();
969   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
970 
971   CCAssignFn *AssignFnFixed;
972   CCAssignFn *AssignFnVarArg;
973   std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
974 
975   // We have outgoing arguments. Make sure that we can tail call with them.
976   SmallVector<CCValAssign, 16> OutLocs;
977   CCState OutInfo(CalleeCC, false, MF, OutLocs, CallerF.getContext());
978   OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg);
979 
980   if (!determineAssignments(Assigner, OutArgs, OutInfo)) {
981     LLVM_DEBUG(dbgs() << "... Could not analyze call operands.\n");
982     return false;
983   }
984 
985   // Make sure that they can fit on the caller's stack.
986   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
987   if (OutInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) {
988     LLVM_DEBUG(dbgs() << "... Cannot fit call operands on caller's stack.\n");
989     return false;
990   }
991 
992   // Verify that the parameters in callee-saved registers match.
993   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
994   const SIRegisterInfo *TRI = ST.getRegisterInfo();
995   const uint32_t *CallerPreservedMask = TRI->getCallPreservedMask(MF, CallerCC);
996   MachineRegisterInfo &MRI = MF.getRegInfo();
997   return parametersInCSRMatch(MRI, CallerPreservedMask, OutLocs, OutArgs);
998 }
999 
1000 /// Return true if the calling convention is one that we can guarantee TCO for.
1001 static bool canGuaranteeTCO(CallingConv::ID CC) {
1002   return CC == CallingConv::Fast;
1003 }
1004 
1005 /// Return true if we might ever do TCO for calls with this calling convention.
1006 static bool mayTailCallThisCC(CallingConv::ID CC) {
1007   switch (CC) {
1008   case CallingConv::C:
1009   case CallingConv::AMDGPU_Gfx:
1010     return true;
1011   default:
1012     return canGuaranteeTCO(CC);
1013   }
1014 }
1015 
1016 bool AMDGPUCallLowering::isEligibleForTailCallOptimization(
1017     MachineIRBuilder &B, CallLoweringInfo &Info,
1018     SmallVectorImpl<ArgInfo> &InArgs, SmallVectorImpl<ArgInfo> &OutArgs) const {
1019   // Must pass all target-independent checks in order to tail call optimize.
1020   if (!Info.IsTailCall)
1021     return false;
1022 
1023   MachineFunction &MF = B.getMF();
1024   const Function &CallerF = MF.getFunction();
1025   CallingConv::ID CalleeCC = Info.CallConv;
1026   CallingConv::ID CallerCC = CallerF.getCallingConv();
1027 
1028   const SIRegisterInfo *TRI = MF.getSubtarget<GCNSubtarget>().getRegisterInfo();
1029   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
1030   // Kernels aren't callable, and don't have a live in return address so it
1031   // doesn't make sense to do a tail call with entry functions.
1032   if (!CallerPreserved)
1033     return false;
1034 
1035   if (!mayTailCallThisCC(CalleeCC)) {
1036     LLVM_DEBUG(dbgs() << "... Calling convention cannot be tail called.\n");
1037     return false;
1038   }
1039 
1040   if (any_of(CallerF.args(), [](const Argument &A) {
1041         return A.hasByValAttr() || A.hasSwiftErrorAttr();
1042       })) {
1043     LLVM_DEBUG(dbgs() << "... Cannot tail call from callers with byval "
1044                          "or swifterror arguments\n");
1045     return false;
1046   }
1047 
1048   // If we have -tailcallopt, then we're done.
1049   if (MF.getTarget().Options.GuaranteedTailCallOpt)
1050     return canGuaranteeTCO(CalleeCC) && CalleeCC == CallerF.getCallingConv();
1051 
1052   // Verify that the incoming and outgoing arguments from the callee are
1053   // safe to tail call.
1054   if (!doCallerAndCalleePassArgsTheSameWay(Info, MF, InArgs)) {
1055     LLVM_DEBUG(
1056         dbgs()
1057         << "... Caller and callee have incompatible calling conventions.\n");
1058     return false;
1059   }
1060 
1061   if (!areCalleeOutgoingArgsTailCallable(Info, MF, OutArgs))
1062     return false;
1063 
1064   LLVM_DEBUG(dbgs() << "... Call is eligible for tail call optimization.\n");
1065   return true;
1066 }
1067 
1068 // Insert outgoing implicit arguments for a call, by inserting copies to the
1069 // implicit argument registers and adding the necessary implicit uses to the
1070 // call instruction.
1071 void AMDGPUCallLowering::handleImplicitCallArguments(
1072     MachineIRBuilder &MIRBuilder, MachineInstrBuilder &CallInst,
1073     const GCNSubtarget &ST, const SIMachineFunctionInfo &FuncInfo,
1074     ArrayRef<std::pair<MCRegister, Register>> ImplicitArgRegs) const {
1075   if (!ST.enableFlatScratch()) {
1076     // Insert copies for the SRD. In the HSA case, this should be an identity
1077     // copy.
1078     auto ScratchRSrcReg = MIRBuilder.buildCopy(LLT::fixed_vector(4, 32),
1079                                                FuncInfo.getScratchRSrcReg());
1080     MIRBuilder.buildCopy(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
1081     CallInst.addReg(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, RegState::Implicit);
1082   }
1083 
1084   for (std::pair<MCRegister, Register> ArgReg : ImplicitArgRegs) {
1085     MIRBuilder.buildCopy((Register)ArgReg.first, ArgReg.second);
1086     CallInst.addReg(ArgReg.first, RegState::Implicit);
1087   }
1088 }
1089 
1090 bool AMDGPUCallLowering::lowerTailCall(
1091     MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info,
1092     SmallVectorImpl<ArgInfo> &OutArgs) const {
1093   MachineFunction &MF = MIRBuilder.getMF();
1094   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1095   SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
1096   const Function &F = MF.getFunction();
1097   MachineRegisterInfo &MRI = MF.getRegInfo();
1098   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
1099 
1100   // True when we're tail calling, but without -tailcallopt.
1101   bool IsSibCall = !MF.getTarget().Options.GuaranteedTailCallOpt;
1102 
1103   // Find out which ABI gets to decide where things go.
1104   CallingConv::ID CalleeCC = Info.CallConv;
1105   CCAssignFn *AssignFnFixed;
1106   CCAssignFn *AssignFnVarArg;
1107   std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
1108 
1109   MachineInstrBuilder CallSeqStart;
1110   if (!IsSibCall)
1111     CallSeqStart = MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKUP);
1112 
1113   unsigned Opc = getCallOpcode(MF, Info.Callee.isReg(), true);
1114   auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
1115   if (!addCallTargetOperands(MIB, MIRBuilder, Info))
1116     return false;
1117 
1118   // Byte offset for the tail call. When we are sibcalling, this will always
1119   // be 0.
1120   MIB.addImm(0);
1121 
1122   // Tell the call which registers are clobbered.
1123   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1124   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CalleeCC);
1125   MIB.addRegMask(Mask);
1126 
1127   // FPDiff is the byte offset of the call's argument area from the callee's.
1128   // Stores to callee stack arguments will be placed in FixedStackSlots offset
1129   // by this amount for a tail call. In a sibling call it must be 0 because the
1130   // caller will deallocate the entire stack and the callee still expects its
1131   // arguments to begin at SP+0.
1132   int FPDiff = 0;
1133 
1134   // This will be 0 for sibcalls, potentially nonzero for tail calls produced
1135   // by -tailcallopt. For sibcalls, the memory operands for the call are
1136   // already available in the caller's incoming argument space.
1137   unsigned NumBytes = 0;
1138   if (!IsSibCall) {
1139     // We aren't sibcalling, so we need to compute FPDiff. We need to do this
1140     // before handling assignments, because FPDiff must be known for memory
1141     // arguments.
1142     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
1143     SmallVector<CCValAssign, 16> OutLocs;
1144     CCState OutInfo(CalleeCC, false, MF, OutLocs, F.getContext());
1145 
1146     // FIXME: Not accounting for callee implicit inputs
1147     OutgoingValueAssigner CalleeAssigner(AssignFnFixed, AssignFnVarArg);
1148     if (!determineAssignments(CalleeAssigner, OutArgs, OutInfo))
1149       return false;
1150 
1151     // The callee will pop the argument stack as a tail call. Thus, we must
1152     // keep it 16-byte aligned.
1153     NumBytes = alignTo(OutInfo.getNextStackOffset(), ST.getStackAlignment());
1154 
1155     // FPDiff will be negative if this tail call requires more space than we
1156     // would automatically have in our incoming argument space. Positive if we
1157     // actually shrink the stack.
1158     FPDiff = NumReusableBytes - NumBytes;
1159 
1160     // The stack pointer must be 16-byte aligned at all times it's used for a
1161     // memory operation, which in practice means at *all* times and in
1162     // particular across call boundaries. Therefore our own arguments started at
1163     // a 16-byte aligned SP and the delta applied for the tail call should
1164     // satisfy the same constraint.
1165     assert(isAligned(ST.getStackAlignment(), FPDiff) &&
1166            "unaligned stack on tail call");
1167   }
1168 
1169   SmallVector<CCValAssign, 16> ArgLocs;
1170   CCState CCInfo(Info.CallConv, Info.IsVarArg, MF, ArgLocs, F.getContext());
1171 
1172   // We could pass MIB and directly add the implicit uses to the call
1173   // now. However, as an aesthetic choice, place implicit argument operands
1174   // after the ordinary user argument registers.
1175   SmallVector<std::pair<MCRegister, Register>, 12> ImplicitArgRegs;
1176 
1177   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
1178       Info.CallConv != CallingConv::AMDGPU_Gfx) {
1179     // With a fixed ABI, allocate fixed registers before user arguments.
1180     if (!passSpecialInputs(MIRBuilder, CCInfo, ImplicitArgRegs, Info))
1181       return false;
1182   }
1183 
1184   OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg);
1185 
1186   if (!determineAssignments(Assigner, OutArgs, CCInfo))
1187     return false;
1188 
1189   // Do the actual argument marshalling.
1190   AMDGPUOutgoingArgHandler Handler(MIRBuilder, MRI, MIB, true, FPDiff);
1191   if (!handleAssignments(Handler, OutArgs, CCInfo, ArgLocs, MIRBuilder))
1192     return false;
1193 
1194   handleImplicitCallArguments(MIRBuilder, MIB, ST, *FuncInfo, ImplicitArgRegs);
1195 
1196   // If we have -tailcallopt, we need to adjust the stack. We'll do the call
1197   // sequence start and end here.
1198   if (!IsSibCall) {
1199     MIB->getOperand(1).setImm(FPDiff);
1200     CallSeqStart.addImm(NumBytes).addImm(0);
1201     // End the call sequence *before* emitting the call. Normally, we would
1202     // tidy the frame up after the call. However, here, we've laid out the
1203     // parameters so that when SP is reset, they will be in the correct
1204     // location.
1205     MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKDOWN).addImm(NumBytes).addImm(0);
1206   }
1207 
1208   // Now we can add the actual call instruction to the correct basic block.
1209   MIRBuilder.insertInstr(MIB);
1210 
1211   // If Callee is a reg, since it is used by a target specific
1212   // instruction, it must have a register class matching the
1213   // constraint of that instruction.
1214 
1215   // FIXME: We should define regbankselectable call instructions to handle
1216   // divergent call targets.
1217   if (MIB->getOperand(0).isReg()) {
1218     MIB->getOperand(0).setReg(constrainOperandRegClass(
1219         MF, *TRI, MRI, *ST.getInstrInfo(), *ST.getRegBankInfo(), *MIB,
1220         MIB->getDesc(), MIB->getOperand(0), 0));
1221   }
1222 
1223   MF.getFrameInfo().setHasTailCall();
1224   Info.LoweredTailCall = true;
1225   return true;
1226 }
1227 
1228 bool AMDGPUCallLowering::lowerCall(MachineIRBuilder &MIRBuilder,
1229                                    CallLoweringInfo &Info) const {
1230   if (Info.IsVarArg) {
1231     LLVM_DEBUG(dbgs() << "Variadic functions not implemented\n");
1232     return false;
1233   }
1234 
1235   MachineFunction &MF = MIRBuilder.getMF();
1236   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1237   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1238 
1239   const Function &F = MF.getFunction();
1240   MachineRegisterInfo &MRI = MF.getRegInfo();
1241   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
1242   const DataLayout &DL = F.getParent()->getDataLayout();
1243 
1244   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
1245       Info.CallConv != CallingConv::AMDGPU_Gfx) {
1246     LLVM_DEBUG(dbgs() << "Variable function ABI not implemented\n");
1247     return false;
1248   }
1249 
1250   SmallVector<ArgInfo, 8> OutArgs;
1251   for (auto &OrigArg : Info.OrigArgs)
1252     splitToValueTypes(OrigArg, OutArgs, DL, Info.CallConv);
1253 
1254   SmallVector<ArgInfo, 8> InArgs;
1255   if (Info.CanLowerReturn && !Info.OrigRet.Ty->isVoidTy())
1256     splitToValueTypes(Info.OrigRet, InArgs, DL, Info.CallConv);
1257 
1258   // If we can lower as a tail call, do that instead.
1259   bool CanTailCallOpt =
1260       isEligibleForTailCallOptimization(MIRBuilder, Info, InArgs, OutArgs);
1261 
1262   // We must emit a tail call if we have musttail.
1263   if (Info.IsMustTailCall && !CanTailCallOpt) {
1264     LLVM_DEBUG(dbgs() << "Failed to lower musttail call as tail call\n");
1265     return false;
1266   }
1267 
1268   if (CanTailCallOpt)
1269     return lowerTailCall(MIRBuilder, Info, OutArgs);
1270 
1271   // Find out which ABI gets to decide where things go.
1272   CCAssignFn *AssignFnFixed;
1273   CCAssignFn *AssignFnVarArg;
1274   std::tie(AssignFnFixed, AssignFnVarArg) =
1275       getAssignFnsForCC(Info.CallConv, TLI);
1276 
1277   MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKUP)
1278     .addImm(0)
1279     .addImm(0);
1280 
1281   // Create a temporarily-floating call instruction so we can add the implicit
1282   // uses of arg registers.
1283   unsigned Opc = getCallOpcode(MF, Info.Callee.isReg(), false);
1284 
1285   auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
1286   MIB.addDef(TRI->getReturnAddressReg(MF));
1287 
1288   if (!addCallTargetOperands(MIB, MIRBuilder, Info))
1289     return false;
1290 
1291   // Tell the call which registers are clobbered.
1292   const uint32_t *Mask = TRI->getCallPreservedMask(MF, Info.CallConv);
1293   MIB.addRegMask(Mask);
1294 
1295   SmallVector<CCValAssign, 16> ArgLocs;
1296   CCState CCInfo(Info.CallConv, Info.IsVarArg, MF, ArgLocs, F.getContext());
1297 
1298   // We could pass MIB and directly add the implicit uses to the call
1299   // now. However, as an aesthetic choice, place implicit argument operands
1300   // after the ordinary user argument registers.
1301   SmallVector<std::pair<MCRegister, Register>, 12> ImplicitArgRegs;
1302 
1303   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
1304       Info.CallConv != CallingConv::AMDGPU_Gfx) {
1305     // With a fixed ABI, allocate fixed registers before user arguments.
1306     if (!passSpecialInputs(MIRBuilder, CCInfo, ImplicitArgRegs, Info))
1307       return false;
1308   }
1309 
1310   // Do the actual argument marshalling.
1311   SmallVector<Register, 8> PhysRegs;
1312 
1313   OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg);
1314   if (!determineAssignments(Assigner, OutArgs, CCInfo))
1315     return false;
1316 
1317   AMDGPUOutgoingArgHandler Handler(MIRBuilder, MRI, MIB, false);
1318   if (!handleAssignments(Handler, OutArgs, CCInfo, ArgLocs, MIRBuilder))
1319     return false;
1320 
1321   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1322 
1323   handleImplicitCallArguments(MIRBuilder, MIB, ST, *MFI, ImplicitArgRegs);
1324 
1325   // Get a count of how many bytes are to be pushed on the stack.
1326   unsigned NumBytes = CCInfo.getNextStackOffset();
1327 
1328   // If Callee is a reg, since it is used by a target specific
1329   // instruction, it must have a register class matching the
1330   // constraint of that instruction.
1331 
1332   // FIXME: We should define regbankselectable call instructions to handle
1333   // divergent call targets.
1334   if (MIB->getOperand(1).isReg()) {
1335     MIB->getOperand(1).setReg(constrainOperandRegClass(
1336         MF, *TRI, MRI, *ST.getInstrInfo(),
1337         *ST.getRegBankInfo(), *MIB, MIB->getDesc(), MIB->getOperand(1),
1338         1));
1339   }
1340 
1341   // Now we can add the actual call instruction to the correct position.
1342   MIRBuilder.insertInstr(MIB);
1343 
1344   // Finally we can copy the returned value back into its virtual-register. In
1345   // symmetry with the arguments, the physical register must be an
1346   // implicit-define of the call instruction.
1347   if (Info.CanLowerReturn && !Info.OrigRet.Ty->isVoidTy()) {
1348     CCAssignFn *RetAssignFn = TLI.CCAssignFnForReturn(Info.CallConv,
1349                                                       Info.IsVarArg);
1350     IncomingValueAssigner Assigner(RetAssignFn);
1351     CallReturnHandler Handler(MIRBuilder, MRI, MIB);
1352     if (!determineAndHandleAssignments(Handler, Assigner, InArgs, MIRBuilder,
1353                                        Info.CallConv, Info.IsVarArg))
1354       return false;
1355   }
1356 
1357   uint64_t CalleePopBytes = NumBytes;
1358 
1359   MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKDOWN)
1360             .addImm(0)
1361             .addImm(CalleePopBytes);
1362 
1363   if (!Info.CanLowerReturn) {
1364     insertSRetLoads(MIRBuilder, Info.OrigRet.Ty, Info.OrigRet.Regs,
1365                     Info.DemoteRegister, Info.DemoteStackIndex);
1366   }
1367 
1368   return true;
1369 }
1370