xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCallLowering.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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: Compatibility 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), 0);
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 = 0;
359   if (IsShader)
360     ReturnOpc = AMDGPU::SI_RETURN_TO_EPILOG;
361   else if (CC == CallingConv::AMDGPU_Gfx)
362     ReturnOpc = AMDGPU::S_SETPC_B64_return_gfx;
363   else
364     ReturnOpc = AMDGPU::S_SETPC_B64_return;
365 
366   auto Ret = B.buildInstrNoInsert(ReturnOpc);
367   Register ReturnAddrVReg;
368   if (ReturnOpc == AMDGPU::S_SETPC_B64_return) {
369     ReturnAddrVReg = MRI.createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass);
370     Ret.addUse(ReturnAddrVReg);
371   } else if (ReturnOpc == AMDGPU::S_SETPC_B64_return_gfx) {
372     ReturnAddrVReg =
373         MRI.createVirtualRegister(&AMDGPU::Gfx_CCR_SGPR_64RegClass);
374     Ret.addUse(ReturnAddrVReg);
375   }
376 
377   if (!FLI.CanLowerReturn)
378     insertSRetStores(B, Val->getType(), VRegs, FLI.DemoteRegister);
379   else if (!lowerReturnVal(B, Val, VRegs, Ret))
380     return false;
381 
382   if (ReturnOpc == AMDGPU::S_SETPC_B64_return ||
383       ReturnOpc == AMDGPU::S_SETPC_B64_return_gfx) {
384     const SIRegisterInfo *TRI = ST.getRegisterInfo();
385     Register LiveInReturn = MF.addLiveIn(TRI->getReturnAddressReg(MF),
386                                          &AMDGPU::SGPR_64RegClass);
387     B.buildCopy(ReturnAddrVReg, LiveInReturn);
388   }
389 
390   // TODO: Handle CalleeSavedRegsViaCopy.
391 
392   B.insertInstr(Ret);
393   return true;
394 }
395 
396 void AMDGPUCallLowering::lowerParameterPtr(Register DstReg, MachineIRBuilder &B,
397                                            uint64_t Offset) const {
398   MachineFunction &MF = B.getMF();
399   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
400   MachineRegisterInfo &MRI = MF.getRegInfo();
401   Register KernArgSegmentPtr =
402     MFI->getPreloadedReg(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
403   Register KernArgSegmentVReg = MRI.getLiveInVirtReg(KernArgSegmentPtr);
404 
405   auto OffsetReg = B.buildConstant(LLT::scalar(64), Offset);
406 
407   B.buildPtrAdd(DstReg, KernArgSegmentVReg, OffsetReg);
408 }
409 
410 void AMDGPUCallLowering::lowerParameter(MachineIRBuilder &B, ArgInfo &OrigArg,
411                                         uint64_t Offset,
412                                         Align Alignment) const {
413   MachineFunction &MF = B.getMF();
414   const Function &F = MF.getFunction();
415   const DataLayout &DL = F.getParent()->getDataLayout();
416   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
417 
418   LLT PtrTy = LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64);
419 
420   SmallVector<ArgInfo, 32> SplitArgs;
421   SmallVector<uint64_t> FieldOffsets;
422   splitToValueTypes(OrigArg, SplitArgs, DL, F.getCallingConv(), &FieldOffsets);
423 
424   unsigned Idx = 0;
425   for (ArgInfo &SplitArg : SplitArgs) {
426     Register PtrReg = B.getMRI()->createGenericVirtualRegister(PtrTy);
427     lowerParameterPtr(PtrReg, B, Offset + FieldOffsets[Idx]);
428 
429     LLT ArgTy = getLLTForType(*SplitArg.Ty, DL);
430     if (SplitArg.Flags[0].isPointer()) {
431       // Compensate for losing pointeriness in splitValueTypes.
432       LLT PtrTy = LLT::pointer(SplitArg.Flags[0].getPointerAddrSpace(),
433                                ArgTy.getScalarSizeInBits());
434       ArgTy = ArgTy.isVector() ? LLT::vector(ArgTy.getElementCount(), PtrTy)
435                                : PtrTy;
436     }
437 
438     MachineMemOperand *MMO = MF.getMachineMemOperand(
439         PtrInfo,
440         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
441             MachineMemOperand::MOInvariant,
442         ArgTy, commonAlignment(Alignment, FieldOffsets[Idx]));
443 
444     assert(SplitArg.Regs.size() == 1);
445 
446     B.buildLoad(SplitArg.Regs[0], PtrReg, *MMO);
447     ++Idx;
448   }
449 }
450 
451 // Allocate special inputs passed in user SGPRs.
452 static void allocateHSAUserSGPRs(CCState &CCInfo,
453                                  MachineIRBuilder &B,
454                                  MachineFunction &MF,
455                                  const SIRegisterInfo &TRI,
456                                  SIMachineFunctionInfo &Info) {
457   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
458   if (Info.hasPrivateSegmentBuffer()) {
459     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
460     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
461     CCInfo.AllocateReg(PrivateSegmentBufferReg);
462   }
463 
464   if (Info.hasDispatchPtr()) {
465     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
466     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
467     CCInfo.AllocateReg(DispatchPtrReg);
468   }
469 
470   if (Info.hasQueuePtr()) {
471     Register QueuePtrReg = Info.addQueuePtr(TRI);
472     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
473     CCInfo.AllocateReg(QueuePtrReg);
474   }
475 
476   if (Info.hasKernargSegmentPtr()) {
477     MachineRegisterInfo &MRI = MF.getRegInfo();
478     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
479     const LLT P4 = LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64);
480     Register VReg = MRI.createGenericVirtualRegister(P4);
481     MRI.addLiveIn(InputPtrReg, VReg);
482     B.getMBB().addLiveIn(InputPtrReg);
483     B.buildCopy(VReg, InputPtrReg);
484     CCInfo.AllocateReg(InputPtrReg);
485   }
486 
487   if (Info.hasDispatchID()) {
488     Register DispatchIDReg = Info.addDispatchID(TRI);
489     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
490     CCInfo.AllocateReg(DispatchIDReg);
491   }
492 
493   if (Info.hasFlatScratchInit()) {
494     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
495     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
496     CCInfo.AllocateReg(FlatScratchInitReg);
497   }
498 
499   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
500   // these from the dispatch pointer.
501 }
502 
503 bool AMDGPUCallLowering::lowerFormalArgumentsKernel(
504     MachineIRBuilder &B, const Function &F,
505     ArrayRef<ArrayRef<Register>> VRegs) const {
506   MachineFunction &MF = B.getMF();
507   const GCNSubtarget *Subtarget = &MF.getSubtarget<GCNSubtarget>();
508   MachineRegisterInfo &MRI = MF.getRegInfo();
509   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
510   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
511   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
512   const DataLayout &DL = F.getParent()->getDataLayout();
513 
514   Info->allocateModuleLDSGlobal(F.getParent());
515 
516   SmallVector<CCValAssign, 16> ArgLocs;
517   CCState CCInfo(F.getCallingConv(), F.isVarArg(), MF, ArgLocs, F.getContext());
518 
519   allocateHSAUserSGPRs(CCInfo, B, MF, *TRI, *Info);
520 
521   unsigned i = 0;
522   const Align KernArgBaseAlign(16);
523   const unsigned BaseOffset = Subtarget->getExplicitKernelArgOffset(F);
524   uint64_t ExplicitArgOffset = 0;
525 
526   // TODO: Align down to dword alignment and extract bits for extending loads.
527   for (auto &Arg : F.args()) {
528     const bool IsByRef = Arg.hasByRefAttr();
529     Type *ArgTy = IsByRef ? Arg.getParamByRefType() : Arg.getType();
530     unsigned AllocSize = DL.getTypeAllocSize(ArgTy);
531     if (AllocSize == 0)
532       continue;
533 
534     MaybeAlign ABIAlign = IsByRef ? Arg.getParamAlign() : None;
535     if (!ABIAlign)
536       ABIAlign = DL.getABITypeAlign(ArgTy);
537 
538     uint64_t ArgOffset = alignTo(ExplicitArgOffset, ABIAlign) + BaseOffset;
539     ExplicitArgOffset = alignTo(ExplicitArgOffset, ABIAlign) + AllocSize;
540 
541     if (Arg.use_empty()) {
542       ++i;
543       continue;
544     }
545 
546     Align Alignment = commonAlignment(KernArgBaseAlign, ArgOffset);
547 
548     if (IsByRef) {
549       unsigned ByRefAS = cast<PointerType>(Arg.getType())->getAddressSpace();
550 
551       assert(VRegs[i].size() == 1 &&
552              "expected only one register for byval pointers");
553       if (ByRefAS == AMDGPUAS::CONSTANT_ADDRESS) {
554         lowerParameterPtr(VRegs[i][0], B, ArgOffset);
555       } else {
556         const LLT ConstPtrTy = LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64);
557         Register PtrReg = MRI.createGenericVirtualRegister(ConstPtrTy);
558         lowerParameterPtr(PtrReg, B, ArgOffset);
559 
560         B.buildAddrSpaceCast(VRegs[i][0], PtrReg);
561       }
562     } else {
563       ArgInfo OrigArg(VRegs[i], Arg, i);
564       const unsigned OrigArgIdx = i + AttributeList::FirstArgIndex;
565       setArgFlags(OrigArg, OrigArgIdx, DL, F);
566       lowerParameter(B, OrigArg, ArgOffset, Alignment);
567     }
568 
569     ++i;
570   }
571 
572   TLI.allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
573   TLI.allocateSystemSGPRs(CCInfo, MF, *Info, F.getCallingConv(), false);
574   return true;
575 }
576 
577 bool AMDGPUCallLowering::lowerFormalArguments(
578     MachineIRBuilder &B, const Function &F, ArrayRef<ArrayRef<Register>> VRegs,
579     FunctionLoweringInfo &FLI) const {
580   CallingConv::ID CC = F.getCallingConv();
581 
582   // The infrastructure for normal calling convention lowering is essentially
583   // useless for kernels. We want to avoid any kind of legalization or argument
584   // splitting.
585   if (CC == CallingConv::AMDGPU_KERNEL)
586     return lowerFormalArgumentsKernel(B, F, VRegs);
587 
588   const bool IsGraphics = AMDGPU::isGraphics(CC);
589   const bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CC);
590 
591   MachineFunction &MF = B.getMF();
592   MachineBasicBlock &MBB = B.getMBB();
593   MachineRegisterInfo &MRI = MF.getRegInfo();
594   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
595   const GCNSubtarget &Subtarget = MF.getSubtarget<GCNSubtarget>();
596   const SIRegisterInfo *TRI = Subtarget.getRegisterInfo();
597   const DataLayout &DL = F.getParent()->getDataLayout();
598 
599   Info->allocateModuleLDSGlobal(F.getParent());
600 
601   SmallVector<CCValAssign, 16> ArgLocs;
602   CCState CCInfo(CC, F.isVarArg(), MF, ArgLocs, F.getContext());
603 
604   if (!IsEntryFunc) {
605     Register ReturnAddrReg = TRI->getReturnAddressReg(MF);
606     Register LiveInReturn = MF.addLiveIn(ReturnAddrReg,
607                                          &AMDGPU::SGPR_64RegClass);
608     MBB.addLiveIn(ReturnAddrReg);
609     B.buildCopy(LiveInReturn, ReturnAddrReg);
610   }
611 
612   if (Info->hasImplicitBufferPtr()) {
613     Register ImplicitBufferPtrReg = Info->addImplicitBufferPtr(*TRI);
614     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
615     CCInfo.AllocateReg(ImplicitBufferPtrReg);
616   }
617 
618   SmallVector<ArgInfo, 32> SplitArgs;
619   unsigned Idx = 0;
620   unsigned PSInputNum = 0;
621 
622   // Insert the hidden sret parameter if the return value won't fit in the
623   // return registers.
624   if (!FLI.CanLowerReturn)
625     insertSRetIncomingArgument(F, SplitArgs, FLI.DemoteRegister, MRI, DL);
626 
627   for (auto &Arg : F.args()) {
628     if (DL.getTypeStoreSize(Arg.getType()) == 0)
629       continue;
630 
631     const bool InReg = Arg.hasAttribute(Attribute::InReg);
632 
633     // SGPR arguments to functions not implemented.
634     if (!IsGraphics && InReg)
635       return false;
636 
637     if (Arg.hasAttribute(Attribute::SwiftSelf) ||
638         Arg.hasAttribute(Attribute::SwiftError) ||
639         Arg.hasAttribute(Attribute::Nest))
640       return false;
641 
642     if (CC == CallingConv::AMDGPU_PS && !InReg && PSInputNum <= 15) {
643       const bool ArgUsed = !Arg.use_empty();
644       bool SkipArg = !ArgUsed && !Info->isPSInputAllocated(PSInputNum);
645 
646       if (!SkipArg) {
647         Info->markPSInputAllocated(PSInputNum);
648         if (ArgUsed)
649           Info->markPSInputEnabled(PSInputNum);
650       }
651 
652       ++PSInputNum;
653 
654       if (SkipArg) {
655         for (int I = 0, E = VRegs[Idx].size(); I != E; ++I)
656           B.buildUndef(VRegs[Idx][I]);
657 
658         ++Idx;
659         continue;
660       }
661     }
662 
663     ArgInfo OrigArg(VRegs[Idx], Arg, Idx);
664     const unsigned OrigArgIdx = Idx + AttributeList::FirstArgIndex;
665     setArgFlags(OrigArg, OrigArgIdx, DL, F);
666 
667     splitToValueTypes(OrigArg, SplitArgs, DL, CC);
668     ++Idx;
669   }
670 
671   // At least one interpolation mode must be enabled or else the GPU will
672   // hang.
673   //
674   // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
675   // set PSInputAddr, the user wants to enable some bits after the compilation
676   // based on run-time states. Since we can't know what the final PSInputEna
677   // will look like, so we shouldn't do anything here and the user should take
678   // responsibility for the correct programming.
679   //
680   // Otherwise, the following restrictions apply:
681   // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
682   // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
683   //   enabled too.
684   if (CC == CallingConv::AMDGPU_PS) {
685     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
686         ((Info->getPSInputAddr() & 0xF) == 0 &&
687          Info->isPSInputAllocated(11))) {
688       CCInfo.AllocateReg(AMDGPU::VGPR0);
689       CCInfo.AllocateReg(AMDGPU::VGPR1);
690       Info->markPSInputAllocated(0);
691       Info->markPSInputEnabled(0);
692     }
693 
694     if (Subtarget.isAmdPalOS()) {
695       // For isAmdPalOS, the user does not enable some bits after compilation
696       // based on run-time states; the register values being generated here are
697       // the final ones set in hardware. Therefore we need to apply the
698       // workaround to PSInputAddr and PSInputEnable together.  (The case where
699       // a bit is set in PSInputAddr but not PSInputEnable is where the frontend
700       // set up an input arg for a particular interpolation mode, but nothing
701       // uses that input arg. Really we should have an earlier pass that removes
702       // such an arg.)
703       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
704       if ((PsInputBits & 0x7F) == 0 ||
705           ((PsInputBits & 0xF) == 0 &&
706            (PsInputBits >> 11 & 1)))
707         Info->markPSInputEnabled(
708           countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
709     }
710   }
711 
712   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
713   CCAssignFn *AssignFn = TLI.CCAssignFnForCall(CC, F.isVarArg());
714 
715   if (!MBB.empty())
716     B.setInstr(*MBB.begin());
717 
718   if (!IsEntryFunc) {
719     // For the fixed ABI, pass workitem IDs in the last argument register.
720     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
721       TLI.allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
722   }
723 
724   IncomingValueAssigner Assigner(AssignFn);
725   if (!determineAssignments(Assigner, SplitArgs, CCInfo))
726     return false;
727 
728   FormalArgHandler Handler(B, MRI);
729   if (!handleAssignments(Handler, SplitArgs, CCInfo, ArgLocs, B))
730     return false;
731 
732   uint64_t StackOffset = Assigner.StackOffset;
733 
734   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
735     // Special inputs come after user arguments.
736     TLI.allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
737   }
738 
739   // Start adding system SGPRs.
740   if (IsEntryFunc) {
741     TLI.allocateSystemSGPRs(CCInfo, MF, *Info, CC, IsGraphics);
742   } else {
743     if (!Subtarget.enableFlatScratch())
744       CCInfo.AllocateReg(Info->getScratchRSrcReg());
745     TLI.allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
746   }
747 
748   // When we tail call, we need to check if the callee's arguments will fit on
749   // the caller's stack. So, whenever we lower formal arguments, we should keep
750   // track of this information, since we might lower a tail call in this
751   // function later.
752   Info->setBytesInStackArgArea(StackOffset);
753 
754   // Move back to the end of the basic block.
755   B.setMBB(MBB);
756 
757   return true;
758 }
759 
760 bool AMDGPUCallLowering::passSpecialInputs(MachineIRBuilder &MIRBuilder,
761                                            CCState &CCInfo,
762                                            SmallVectorImpl<std::pair<MCRegister, Register>> &ArgRegs,
763                                            CallLoweringInfo &Info) const {
764   MachineFunction &MF = MIRBuilder.getMF();
765 
766   // If there's no call site, this doesn't correspond to a call from the IR and
767   // doesn't need implicit inputs.
768   if (!Info.CB)
769     return true;
770 
771   const AMDGPUFunctionArgInfo *CalleeArgInfo
772     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
773 
774   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
775   const AMDGPUFunctionArgInfo &CallerArgInfo = MFI->getArgInfo();
776 
777 
778   // TODO: Unify with private memory register handling. This is complicated by
779   // the fact that at least in kernels, the input argument is not necessarily
780   // in the same location as the input.
781   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
782     AMDGPUFunctionArgInfo::DISPATCH_PTR,
783     AMDGPUFunctionArgInfo::QUEUE_PTR,
784     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
785     AMDGPUFunctionArgInfo::DISPATCH_ID,
786     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
787     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
788     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
789   };
790 
791   static constexpr StringLiteral ImplicitAttrNames[] = {
792     "amdgpu-no-dispatch-ptr",
793     "amdgpu-no-queue-ptr",
794     "amdgpu-no-implicitarg-ptr",
795     "amdgpu-no-dispatch-id",
796     "amdgpu-no-workgroup-id-x",
797     "amdgpu-no-workgroup-id-y",
798     "amdgpu-no-workgroup-id-z"
799   };
800 
801   MachineRegisterInfo &MRI = MF.getRegInfo();
802 
803   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
804   const AMDGPULegalizerInfo *LI
805     = static_cast<const AMDGPULegalizerInfo*>(ST.getLegalizerInfo());
806 
807   unsigned I = 0;
808   for (auto InputID : InputRegs) {
809     const ArgDescriptor *OutgoingArg;
810     const TargetRegisterClass *ArgRC;
811     LLT ArgTy;
812 
813     // If the callee does not use the attribute value, skip copying the value.
814     if (Info.CB->hasFnAttr(ImplicitAttrNames[I++]))
815       continue;
816 
817     std::tie(OutgoingArg, ArgRC, ArgTy) =
818         CalleeArgInfo->getPreloadedValue(InputID);
819     if (!OutgoingArg)
820       continue;
821 
822     const ArgDescriptor *IncomingArg;
823     const TargetRegisterClass *IncomingArgRC;
824     std::tie(IncomingArg, IncomingArgRC, ArgTy) =
825         CallerArgInfo.getPreloadedValue(InputID);
826     assert(IncomingArgRC == ArgRC);
827 
828     Register InputReg = MRI.createGenericVirtualRegister(ArgTy);
829 
830     if (IncomingArg) {
831       LI->loadInputValue(InputReg, MIRBuilder, IncomingArg, ArgRC, ArgTy);
832     } else {
833       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
834       LI->getImplicitArgPtr(InputReg, MRI, MIRBuilder);
835     }
836 
837     if (OutgoingArg->isRegister()) {
838       ArgRegs.emplace_back(OutgoingArg->getRegister(), InputReg);
839       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
840         report_fatal_error("failed to allocate implicit input argument");
841     } else {
842       LLVM_DEBUG(dbgs() << "Unhandled stack passed implicit input argument\n");
843       return false;
844     }
845   }
846 
847   // Pack workitem IDs into a single register or pass it as is if already
848   // packed.
849   const ArgDescriptor *OutgoingArg;
850   const TargetRegisterClass *ArgRC;
851   LLT ArgTy;
852 
853   std::tie(OutgoingArg, ArgRC, ArgTy) =
854       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
855   if (!OutgoingArg)
856     std::tie(OutgoingArg, ArgRC, ArgTy) =
857         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
858   if (!OutgoingArg)
859     std::tie(OutgoingArg, ArgRC, ArgTy) =
860         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
861   if (!OutgoingArg)
862     return false;
863 
864   auto WorkitemIDX =
865       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
866   auto WorkitemIDY =
867       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
868   auto WorkitemIDZ =
869       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
870 
871   const ArgDescriptor *IncomingArgX = std::get<0>(WorkitemIDX);
872   const ArgDescriptor *IncomingArgY = std::get<0>(WorkitemIDY);
873   const ArgDescriptor *IncomingArgZ = std::get<0>(WorkitemIDZ);
874   const LLT S32 = LLT::scalar(32);
875 
876   const bool NeedWorkItemIDX = !Info.CB->hasFnAttr("amdgpu-no-workitem-id-x");
877   const bool NeedWorkItemIDY = !Info.CB->hasFnAttr("amdgpu-no-workitem-id-y");
878   const bool NeedWorkItemIDZ = !Info.CB->hasFnAttr("amdgpu-no-workitem-id-z");
879 
880   // If incoming ids are not packed we need to pack them.
881   // FIXME: Should consider known workgroup size to eliminate known 0 cases.
882   Register InputReg;
883   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
884       NeedWorkItemIDX) {
885     InputReg = MRI.createGenericVirtualRegister(S32);
886     LI->loadInputValue(InputReg, MIRBuilder, IncomingArgX,
887                        std::get<1>(WorkitemIDX), std::get<2>(WorkitemIDX));
888   }
889 
890   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
891       NeedWorkItemIDY) {
892     Register Y = MRI.createGenericVirtualRegister(S32);
893     LI->loadInputValue(Y, MIRBuilder, IncomingArgY, std::get<1>(WorkitemIDY),
894                        std::get<2>(WorkitemIDY));
895 
896     Y = MIRBuilder.buildShl(S32, Y, MIRBuilder.buildConstant(S32, 10)).getReg(0);
897     InputReg = InputReg ? MIRBuilder.buildOr(S32, InputReg, Y).getReg(0) : Y;
898   }
899 
900   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
901       NeedWorkItemIDZ) {
902     Register Z = MRI.createGenericVirtualRegister(S32);
903     LI->loadInputValue(Z, MIRBuilder, IncomingArgZ, std::get<1>(WorkitemIDZ),
904                        std::get<2>(WorkitemIDZ));
905 
906     Z = MIRBuilder.buildShl(S32, Z, MIRBuilder.buildConstant(S32, 20)).getReg(0);
907     InputReg = InputReg ? MIRBuilder.buildOr(S32, InputReg, Z).getReg(0) : Z;
908   }
909 
910   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
911     InputReg = MRI.createGenericVirtualRegister(S32);
912 
913     // Workitem ids are already packed, any of present incoming arguments will
914     // carry all required fields.
915     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
916       IncomingArgX ? *IncomingArgX :
917         IncomingArgY ? *IncomingArgY : *IncomingArgZ, ~0u);
918     LI->loadInputValue(InputReg, MIRBuilder, &IncomingArg,
919                        &AMDGPU::VGPR_32RegClass, S32);
920   }
921 
922   if (OutgoingArg->isRegister()) {
923     if (InputReg)
924       ArgRegs.emplace_back(OutgoingArg->getRegister(), InputReg);
925 
926     if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
927       report_fatal_error("failed to allocate implicit input argument");
928   } else {
929     LLVM_DEBUG(dbgs() << "Unhandled stack passed implicit input argument\n");
930     return false;
931   }
932 
933   return true;
934 }
935 
936 /// Returns a pair containing the fixed CCAssignFn and the vararg CCAssignFn for
937 /// CC.
938 static std::pair<CCAssignFn *, CCAssignFn *>
939 getAssignFnsForCC(CallingConv::ID CC, const SITargetLowering &TLI) {
940   return {TLI.CCAssignFnForCall(CC, false), TLI.CCAssignFnForCall(CC, true)};
941 }
942 
943 static unsigned getCallOpcode(const MachineFunction &CallerF, bool IsIndirect,
944                               bool IsTailCall) {
945   assert(!(IsIndirect && IsTailCall) && "Indirect calls can't be tail calls, "
946                                         "because the address can be divergent");
947   return IsTailCall ? AMDGPU::SI_TCRETURN : AMDGPU::G_SI_CALL;
948 }
949 
950 // Add operands to call instruction to track the callee.
951 static bool addCallTargetOperands(MachineInstrBuilder &CallInst,
952                                   MachineIRBuilder &MIRBuilder,
953                                   AMDGPUCallLowering::CallLoweringInfo &Info) {
954   if (Info.Callee.isReg()) {
955     CallInst.addReg(Info.Callee.getReg());
956     CallInst.addImm(0);
957   } else if (Info.Callee.isGlobal() && Info.Callee.getOffset() == 0) {
958     // The call lowering lightly assumed we can directly encode a call target in
959     // the instruction, which is not the case. Materialize the address here.
960     const GlobalValue *GV = Info.Callee.getGlobal();
961     auto Ptr = MIRBuilder.buildGlobalValue(
962       LLT::pointer(GV->getAddressSpace(), 64), GV);
963     CallInst.addReg(Ptr.getReg(0));
964     CallInst.add(Info.Callee);
965   } else
966     return false;
967 
968   return true;
969 }
970 
971 bool AMDGPUCallLowering::doCallerAndCalleePassArgsTheSameWay(
972     CallLoweringInfo &Info, MachineFunction &MF,
973     SmallVectorImpl<ArgInfo> &InArgs) const {
974   const Function &CallerF = MF.getFunction();
975   CallingConv::ID CalleeCC = Info.CallConv;
976   CallingConv::ID CallerCC = CallerF.getCallingConv();
977 
978   // If the calling conventions match, then everything must be the same.
979   if (CalleeCC == CallerCC)
980     return true;
981 
982   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
983 
984   // Make sure that the caller and callee preserve all of the same registers.
985   auto TRI = ST.getRegisterInfo();
986 
987   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
988   const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
989   if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
990     return false;
991 
992   // Check if the caller and callee will handle arguments in the same way.
993   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
994   CCAssignFn *CalleeAssignFnFixed;
995   CCAssignFn *CalleeAssignFnVarArg;
996   std::tie(CalleeAssignFnFixed, CalleeAssignFnVarArg) =
997       getAssignFnsForCC(CalleeCC, TLI);
998 
999   CCAssignFn *CallerAssignFnFixed;
1000   CCAssignFn *CallerAssignFnVarArg;
1001   std::tie(CallerAssignFnFixed, CallerAssignFnVarArg) =
1002       getAssignFnsForCC(CallerCC, TLI);
1003 
1004   // FIXME: We are not accounting for potential differences in implicitly passed
1005   // inputs, but only the fixed ABI is supported now anyway.
1006   IncomingValueAssigner CalleeAssigner(CalleeAssignFnFixed,
1007                                        CalleeAssignFnVarArg);
1008   IncomingValueAssigner CallerAssigner(CallerAssignFnFixed,
1009                                        CallerAssignFnVarArg);
1010   return resultsCompatible(Info, MF, InArgs, CalleeAssigner, CallerAssigner);
1011 }
1012 
1013 bool AMDGPUCallLowering::areCalleeOutgoingArgsTailCallable(
1014     CallLoweringInfo &Info, MachineFunction &MF,
1015     SmallVectorImpl<ArgInfo> &OutArgs) const {
1016   // If there are no outgoing arguments, then we are done.
1017   if (OutArgs.empty())
1018     return true;
1019 
1020   const Function &CallerF = MF.getFunction();
1021   CallingConv::ID CalleeCC = Info.CallConv;
1022   CallingConv::ID CallerCC = CallerF.getCallingConv();
1023   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
1024 
1025   CCAssignFn *AssignFnFixed;
1026   CCAssignFn *AssignFnVarArg;
1027   std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
1028 
1029   // We have outgoing arguments. Make sure that we can tail call with them.
1030   SmallVector<CCValAssign, 16> OutLocs;
1031   CCState OutInfo(CalleeCC, false, MF, OutLocs, CallerF.getContext());
1032   OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg);
1033 
1034   if (!determineAssignments(Assigner, OutArgs, OutInfo)) {
1035     LLVM_DEBUG(dbgs() << "... Could not analyze call operands.\n");
1036     return false;
1037   }
1038 
1039   // Make sure that they can fit on the caller's stack.
1040   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
1041   if (OutInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) {
1042     LLVM_DEBUG(dbgs() << "... Cannot fit call operands on caller's stack.\n");
1043     return false;
1044   }
1045 
1046   // Verify that the parameters in callee-saved registers match.
1047   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1048   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1049   const uint32_t *CallerPreservedMask = TRI->getCallPreservedMask(MF, CallerCC);
1050   MachineRegisterInfo &MRI = MF.getRegInfo();
1051   return parametersInCSRMatch(MRI, CallerPreservedMask, OutLocs, OutArgs);
1052 }
1053 
1054 /// Return true if the calling convention is one that we can guarantee TCO for.
1055 static bool canGuaranteeTCO(CallingConv::ID CC) {
1056   return CC == CallingConv::Fast;
1057 }
1058 
1059 /// Return true if we might ever do TCO for calls with this calling convention.
1060 static bool mayTailCallThisCC(CallingConv::ID CC) {
1061   switch (CC) {
1062   case CallingConv::C:
1063   case CallingConv::AMDGPU_Gfx:
1064     return true;
1065   default:
1066     return canGuaranteeTCO(CC);
1067   }
1068 }
1069 
1070 bool AMDGPUCallLowering::isEligibleForTailCallOptimization(
1071     MachineIRBuilder &B, CallLoweringInfo &Info,
1072     SmallVectorImpl<ArgInfo> &InArgs, SmallVectorImpl<ArgInfo> &OutArgs) const {
1073   // Must pass all target-independent checks in order to tail call optimize.
1074   if (!Info.IsTailCall)
1075     return false;
1076 
1077   // Indirect calls can't be tail calls, because the address can be divergent.
1078   // TODO Check divergence info if the call really is divergent.
1079   if (Info.Callee.isReg())
1080     return false;
1081 
1082   MachineFunction &MF = B.getMF();
1083   const Function &CallerF = MF.getFunction();
1084   CallingConv::ID CalleeCC = Info.CallConv;
1085   CallingConv::ID CallerCC = CallerF.getCallingConv();
1086 
1087   const SIRegisterInfo *TRI = MF.getSubtarget<GCNSubtarget>().getRegisterInfo();
1088   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
1089   // Kernels aren't callable, and don't have a live in return address so it
1090   // doesn't make sense to do a tail call with entry functions.
1091   if (!CallerPreserved)
1092     return false;
1093 
1094   if (!mayTailCallThisCC(CalleeCC)) {
1095     LLVM_DEBUG(dbgs() << "... Calling convention cannot be tail called.\n");
1096     return false;
1097   }
1098 
1099   if (any_of(CallerF.args(), [](const Argument &A) {
1100         return A.hasByValAttr() || A.hasSwiftErrorAttr();
1101       })) {
1102     LLVM_DEBUG(dbgs() << "... Cannot tail call from callers with byval "
1103                          "or swifterror arguments\n");
1104     return false;
1105   }
1106 
1107   // If we have -tailcallopt, then we're done.
1108   if (MF.getTarget().Options.GuaranteedTailCallOpt)
1109     return canGuaranteeTCO(CalleeCC) && CalleeCC == CallerF.getCallingConv();
1110 
1111   // Verify that the incoming and outgoing arguments from the callee are
1112   // safe to tail call.
1113   if (!doCallerAndCalleePassArgsTheSameWay(Info, MF, InArgs)) {
1114     LLVM_DEBUG(
1115         dbgs()
1116         << "... Caller and callee have incompatible calling conventions.\n");
1117     return false;
1118   }
1119 
1120   if (!areCalleeOutgoingArgsTailCallable(Info, MF, OutArgs))
1121     return false;
1122 
1123   LLVM_DEBUG(dbgs() << "... Call is eligible for tail call optimization.\n");
1124   return true;
1125 }
1126 
1127 // Insert outgoing implicit arguments for a call, by inserting copies to the
1128 // implicit argument registers and adding the necessary implicit uses to the
1129 // call instruction.
1130 void AMDGPUCallLowering::handleImplicitCallArguments(
1131     MachineIRBuilder &MIRBuilder, MachineInstrBuilder &CallInst,
1132     const GCNSubtarget &ST, const SIMachineFunctionInfo &FuncInfo,
1133     ArrayRef<std::pair<MCRegister, Register>> ImplicitArgRegs) const {
1134   if (!ST.enableFlatScratch()) {
1135     // Insert copies for the SRD. In the HSA case, this should be an identity
1136     // copy.
1137     auto ScratchRSrcReg = MIRBuilder.buildCopy(LLT::fixed_vector(4, 32),
1138                                                FuncInfo.getScratchRSrcReg());
1139     MIRBuilder.buildCopy(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
1140     CallInst.addReg(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, RegState::Implicit);
1141   }
1142 
1143   for (std::pair<MCRegister, Register> ArgReg : ImplicitArgRegs) {
1144     MIRBuilder.buildCopy((Register)ArgReg.first, ArgReg.second);
1145     CallInst.addReg(ArgReg.first, RegState::Implicit);
1146   }
1147 }
1148 
1149 bool AMDGPUCallLowering::lowerTailCall(
1150     MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info,
1151     SmallVectorImpl<ArgInfo> &OutArgs) const {
1152   MachineFunction &MF = MIRBuilder.getMF();
1153   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1154   SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
1155   const Function &F = MF.getFunction();
1156   MachineRegisterInfo &MRI = MF.getRegInfo();
1157   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
1158 
1159   // True when we're tail calling, but without -tailcallopt.
1160   bool IsSibCall = !MF.getTarget().Options.GuaranteedTailCallOpt;
1161 
1162   // Find out which ABI gets to decide where things go.
1163   CallingConv::ID CalleeCC = Info.CallConv;
1164   CCAssignFn *AssignFnFixed;
1165   CCAssignFn *AssignFnVarArg;
1166   std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
1167 
1168   MachineInstrBuilder CallSeqStart;
1169   if (!IsSibCall)
1170     CallSeqStart = MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKUP);
1171 
1172   unsigned Opc = getCallOpcode(MF, Info.Callee.isReg(), true);
1173   auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
1174   if (!addCallTargetOperands(MIB, MIRBuilder, Info))
1175     return false;
1176 
1177   // Byte offset for the tail call. When we are sibcalling, this will always
1178   // be 0.
1179   MIB.addImm(0);
1180 
1181   // Tell the call which registers are clobbered.
1182   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1183   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CalleeCC);
1184   MIB.addRegMask(Mask);
1185 
1186   // FPDiff is the byte offset of the call's argument area from the callee's.
1187   // Stores to callee stack arguments will be placed in FixedStackSlots offset
1188   // by this amount for a tail call. In a sibling call it must be 0 because the
1189   // caller will deallocate the entire stack and the callee still expects its
1190   // arguments to begin at SP+0.
1191   int FPDiff = 0;
1192 
1193   // This will be 0 for sibcalls, potentially nonzero for tail calls produced
1194   // by -tailcallopt. For sibcalls, the memory operands for the call are
1195   // already available in the caller's incoming argument space.
1196   unsigned NumBytes = 0;
1197   if (!IsSibCall) {
1198     // We aren't sibcalling, so we need to compute FPDiff. We need to do this
1199     // before handling assignments, because FPDiff must be known for memory
1200     // arguments.
1201     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
1202     SmallVector<CCValAssign, 16> OutLocs;
1203     CCState OutInfo(CalleeCC, false, MF, OutLocs, F.getContext());
1204 
1205     // FIXME: Not accounting for callee implicit inputs
1206     OutgoingValueAssigner CalleeAssigner(AssignFnFixed, AssignFnVarArg);
1207     if (!determineAssignments(CalleeAssigner, OutArgs, OutInfo))
1208       return false;
1209 
1210     // The callee will pop the argument stack as a tail call. Thus, we must
1211     // keep it 16-byte aligned.
1212     NumBytes = alignTo(OutInfo.getNextStackOffset(), ST.getStackAlignment());
1213 
1214     // FPDiff will be negative if this tail call requires more space than we
1215     // would automatically have in our incoming argument space. Positive if we
1216     // actually shrink the stack.
1217     FPDiff = NumReusableBytes - NumBytes;
1218 
1219     // The stack pointer must be 16-byte aligned at all times it's used for a
1220     // memory operation, which in practice means at *all* times and in
1221     // particular across call boundaries. Therefore our own arguments started at
1222     // a 16-byte aligned SP and the delta applied for the tail call should
1223     // satisfy the same constraint.
1224     assert(isAligned(ST.getStackAlignment(), FPDiff) &&
1225            "unaligned stack on tail call");
1226   }
1227 
1228   SmallVector<CCValAssign, 16> ArgLocs;
1229   CCState CCInfo(Info.CallConv, Info.IsVarArg, MF, ArgLocs, F.getContext());
1230 
1231   // We could pass MIB and directly add the implicit uses to the call
1232   // now. However, as an aesthetic choice, place implicit argument operands
1233   // after the ordinary user argument registers.
1234   SmallVector<std::pair<MCRegister, Register>, 12> ImplicitArgRegs;
1235 
1236   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
1237       Info.CallConv != CallingConv::AMDGPU_Gfx) {
1238     // With a fixed ABI, allocate fixed registers before user arguments.
1239     if (!passSpecialInputs(MIRBuilder, CCInfo, ImplicitArgRegs, Info))
1240       return false;
1241   }
1242 
1243   OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg);
1244 
1245   if (!determineAssignments(Assigner, OutArgs, CCInfo))
1246     return false;
1247 
1248   // Do the actual argument marshalling.
1249   AMDGPUOutgoingArgHandler Handler(MIRBuilder, MRI, MIB, true, FPDiff);
1250   if (!handleAssignments(Handler, OutArgs, CCInfo, ArgLocs, MIRBuilder))
1251     return false;
1252 
1253   handleImplicitCallArguments(MIRBuilder, MIB, ST, *FuncInfo, ImplicitArgRegs);
1254 
1255   // If we have -tailcallopt, we need to adjust the stack. We'll do the call
1256   // sequence start and end here.
1257   if (!IsSibCall) {
1258     MIB->getOperand(1).setImm(FPDiff);
1259     CallSeqStart.addImm(NumBytes).addImm(0);
1260     // End the call sequence *before* emitting the call. Normally, we would
1261     // tidy the frame up after the call. However, here, we've laid out the
1262     // parameters so that when SP is reset, they will be in the correct
1263     // location.
1264     MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKDOWN).addImm(NumBytes).addImm(0);
1265   }
1266 
1267   // Now we can add the actual call instruction to the correct basic block.
1268   MIRBuilder.insertInstr(MIB);
1269 
1270   // If Callee is a reg, since it is used by a target specific
1271   // instruction, it must have a register class matching the
1272   // constraint of that instruction.
1273 
1274   // FIXME: We should define regbankselectable call instructions to handle
1275   // divergent call targets.
1276   if (MIB->getOperand(0).isReg()) {
1277     MIB->getOperand(0).setReg(constrainOperandRegClass(
1278         MF, *TRI, MRI, *ST.getInstrInfo(), *ST.getRegBankInfo(), *MIB,
1279         MIB->getDesc(), MIB->getOperand(0), 0));
1280   }
1281 
1282   MF.getFrameInfo().setHasTailCall();
1283   Info.LoweredTailCall = true;
1284   return true;
1285 }
1286 
1287 bool AMDGPUCallLowering::lowerCall(MachineIRBuilder &MIRBuilder,
1288                                    CallLoweringInfo &Info) const {
1289   if (Info.IsVarArg) {
1290     LLVM_DEBUG(dbgs() << "Variadic functions not implemented\n");
1291     return false;
1292   }
1293 
1294   MachineFunction &MF = MIRBuilder.getMF();
1295   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1296   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1297 
1298   const Function &F = MF.getFunction();
1299   MachineRegisterInfo &MRI = MF.getRegInfo();
1300   const SITargetLowering &TLI = *getTLI<SITargetLowering>();
1301   const DataLayout &DL = F.getParent()->getDataLayout();
1302 
1303   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
1304       Info.CallConv != CallingConv::AMDGPU_Gfx) {
1305     LLVM_DEBUG(dbgs() << "Variable function ABI not implemented\n");
1306     return false;
1307   }
1308 
1309   SmallVector<ArgInfo, 8> OutArgs;
1310   for (auto &OrigArg : Info.OrigArgs)
1311     splitToValueTypes(OrigArg, OutArgs, DL, Info.CallConv);
1312 
1313   SmallVector<ArgInfo, 8> InArgs;
1314   if (Info.CanLowerReturn && !Info.OrigRet.Ty->isVoidTy())
1315     splitToValueTypes(Info.OrigRet, InArgs, DL, Info.CallConv);
1316 
1317   // If we can lower as a tail call, do that instead.
1318   bool CanTailCallOpt =
1319       isEligibleForTailCallOptimization(MIRBuilder, Info, InArgs, OutArgs);
1320 
1321   // We must emit a tail call if we have musttail.
1322   if (Info.IsMustTailCall && !CanTailCallOpt) {
1323     LLVM_DEBUG(dbgs() << "Failed to lower musttail call as tail call\n");
1324     return false;
1325   }
1326 
1327   if (CanTailCallOpt)
1328     return lowerTailCall(MIRBuilder, Info, OutArgs);
1329 
1330   // Find out which ABI gets to decide where things go.
1331   CCAssignFn *AssignFnFixed;
1332   CCAssignFn *AssignFnVarArg;
1333   std::tie(AssignFnFixed, AssignFnVarArg) =
1334       getAssignFnsForCC(Info.CallConv, TLI);
1335 
1336   MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKUP)
1337     .addImm(0)
1338     .addImm(0);
1339 
1340   // Create a temporarily-floating call instruction so we can add the implicit
1341   // uses of arg registers.
1342   unsigned Opc = getCallOpcode(MF, Info.Callee.isReg(), false);
1343 
1344   auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
1345   MIB.addDef(TRI->getReturnAddressReg(MF));
1346 
1347   if (!addCallTargetOperands(MIB, MIRBuilder, Info))
1348     return false;
1349 
1350   // Tell the call which registers are clobbered.
1351   const uint32_t *Mask = TRI->getCallPreservedMask(MF, Info.CallConv);
1352   MIB.addRegMask(Mask);
1353 
1354   SmallVector<CCValAssign, 16> ArgLocs;
1355   CCState CCInfo(Info.CallConv, Info.IsVarArg, MF, ArgLocs, F.getContext());
1356 
1357   // We could pass MIB and directly add the implicit uses to the call
1358   // now. However, as an aesthetic choice, place implicit argument operands
1359   // after the ordinary user argument registers.
1360   SmallVector<std::pair<MCRegister, Register>, 12> ImplicitArgRegs;
1361 
1362   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
1363       Info.CallConv != CallingConv::AMDGPU_Gfx) {
1364     // With a fixed ABI, allocate fixed registers before user arguments.
1365     if (!passSpecialInputs(MIRBuilder, CCInfo, ImplicitArgRegs, Info))
1366       return false;
1367   }
1368 
1369   // Do the actual argument marshalling.
1370   SmallVector<Register, 8> PhysRegs;
1371 
1372   OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg);
1373   if (!determineAssignments(Assigner, OutArgs, CCInfo))
1374     return false;
1375 
1376   AMDGPUOutgoingArgHandler Handler(MIRBuilder, MRI, MIB, false);
1377   if (!handleAssignments(Handler, OutArgs, CCInfo, ArgLocs, MIRBuilder))
1378     return false;
1379 
1380   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1381 
1382   handleImplicitCallArguments(MIRBuilder, MIB, ST, *MFI, ImplicitArgRegs);
1383 
1384   // Get a count of how many bytes are to be pushed on the stack.
1385   unsigned NumBytes = CCInfo.getNextStackOffset();
1386 
1387   // If Callee is a reg, since it is used by a target specific
1388   // instruction, it must have a register class matching the
1389   // constraint of that instruction.
1390 
1391   // FIXME: We should define regbankselectable call instructions to handle
1392   // divergent call targets.
1393   if (MIB->getOperand(1).isReg()) {
1394     MIB->getOperand(1).setReg(constrainOperandRegClass(
1395         MF, *TRI, MRI, *ST.getInstrInfo(),
1396         *ST.getRegBankInfo(), *MIB, MIB->getDesc(), MIB->getOperand(1),
1397         1));
1398   }
1399 
1400   // Now we can add the actual call instruction to the correct position.
1401   MIRBuilder.insertInstr(MIB);
1402 
1403   // Finally we can copy the returned value back into its virtual-register. In
1404   // symmetry with the arguments, the physical register must be an
1405   // implicit-define of the call instruction.
1406   if (Info.CanLowerReturn && !Info.OrigRet.Ty->isVoidTy()) {
1407     CCAssignFn *RetAssignFn = TLI.CCAssignFnForReturn(Info.CallConv,
1408                                                       Info.IsVarArg);
1409     IncomingValueAssigner Assigner(RetAssignFn);
1410     CallReturnHandler Handler(MIRBuilder, MRI, MIB);
1411     if (!determineAndHandleAssignments(Handler, Assigner, InArgs, MIRBuilder,
1412                                        Info.CallConv, Info.IsVarArg))
1413       return false;
1414   }
1415 
1416   uint64_t CalleePopBytes = NumBytes;
1417 
1418   MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKDOWN)
1419             .addImm(0)
1420             .addImm(CalleePopBytes);
1421 
1422   if (!Info.CanLowerReturn) {
1423     insertSRetLoads(MIRBuilder, Info.OrigRet.Ty, Info.OrigRet.Regs,
1424                     Info.DemoteRegister, Info.DemoteStackIndex);
1425   }
1426 
1427   return true;
1428 }
1429