LLVM 22.0.0git
AMDGPUCallLowering.cpp
Go to the documentation of this file.
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"
19#include "SIRegisterInfo.h"
25#include "llvm/IR/IntrinsicsAMDGPU.h"
26
27#define DEBUG_TYPE "amdgpu-call-lowering"
28
29using namespace llvm;
30
31namespace {
32
33/// Wrapper around extendRegister to ensure we extend to a full 32-bit register.
34static Register extendRegisterMin32(CallLowering::ValueHandler &Handler,
35 Register ValVReg, const CCValAssign &VA) {
36 if (VA.getLocVT().getSizeInBits() < 32) {
37 // 16-bit types are reported as legal for 32-bit registers. We need to
38 // extend and do a 32-bit copy to avoid the verifier complaining about it.
39 return Handler.MIRBuilder.buildAnyExt(LLT::scalar(32), ValVReg).getReg(0);
40 }
41
42 return Handler.extendRegister(ValVReg, VA);
43}
44
45struct AMDGPUOutgoingValueHandler : public CallLowering::OutgoingValueHandler {
46 AMDGPUOutgoingValueHandler(MachineIRBuilder &B, MachineRegisterInfo &MRI,
48 : OutgoingValueHandler(B, MRI), MIB(MIB) {}
49
51
52 Register getStackAddress(uint64_t Size, int64_t Offset,
54 ISD::ArgFlagsTy Flags) override {
55 llvm_unreachable("not implemented");
56 }
57
58 void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,
59 const MachinePointerInfo &MPO,
60 const CCValAssign &VA) override {
61 llvm_unreachable("not implemented");
62 }
63
64 void assignValueToReg(Register ValVReg, Register PhysReg,
65 const CCValAssign &VA) override {
66 Register ExtReg = extendRegisterMin32(*this, ValVReg, VA);
67
68 // If this is a scalar return, insert a readfirstlane just in case the value
69 // ends up in a VGPR.
70 // FIXME: Assert this is a shader return.
71 const SIRegisterInfo *TRI
72 = static_cast<const SIRegisterInfo *>(MRI.getTargetRegisterInfo());
73 if (TRI->isSGPRReg(MRI, PhysReg)) {
74 LLT Ty = MRI.getType(ExtReg);
75 LLT S32 = LLT::scalar(32);
76 if (Ty != S32) {
77 // FIXME: We should probably support readfirstlane intrinsics with all
78 // legal 32-bit types.
79 assert(Ty.getSizeInBits() == 32);
80 if (Ty.isPointer())
81 ExtReg = MIRBuilder.buildPtrToInt(S32, ExtReg).getReg(0);
82 else
83 ExtReg = MIRBuilder.buildBitcast(S32, ExtReg).getReg(0);
84 }
85
86 auto ToSGPR = MIRBuilder
87 .buildIntrinsic(Intrinsic::amdgcn_readfirstlane,
88 {MRI.getType(ExtReg)})
89 .addReg(ExtReg);
90 ExtReg = ToSGPR.getReg(0);
91 }
92
93 MIRBuilder.buildCopy(PhysReg, ExtReg);
94 MIB.addUse(PhysReg, RegState::Implicit);
95 }
96};
97
98struct AMDGPUIncomingArgHandler : public CallLowering::IncomingValueHandler {
99 uint64_t StackUsed = 0;
100
101 AMDGPUIncomingArgHandler(MachineIRBuilder &B, MachineRegisterInfo &MRI)
102 : IncomingValueHandler(B, MRI) {}
103
104 Register getStackAddress(uint64_t Size, int64_t Offset,
106 ISD::ArgFlagsTy Flags) override {
107 auto &MFI = MIRBuilder.getMF().getFrameInfo();
108
109 // Byval is assumed to be writable memory, but other stack passed arguments
110 // are not.
111 const bool IsImmutable = !Flags.isByVal();
112 int FI = MFI.CreateFixedObject(Size, Offset, IsImmutable);
113 MPO = MachinePointerInfo::getFixedStack(MIRBuilder.getMF(), FI);
114 auto AddrReg = MIRBuilder.buildFrameIndex(
116 StackUsed = std::max(StackUsed, Size + Offset);
117 return AddrReg.getReg(0);
118 }
119
120 void assignValueToReg(Register ValVReg, Register PhysReg,
121 const CCValAssign &VA) override {
122 markPhysRegUsed(PhysReg);
123
124 if (VA.getLocVT().getSizeInBits() < 32) {
125 // 16-bit types are reported as legal for 32-bit registers. We need to do
126 // a 32-bit copy, and truncate to avoid the verifier complaining about it.
127 auto Copy = MIRBuilder.buildCopy(LLT::scalar(32), PhysReg);
128
129 // If we have signext/zeroext, it applies to the whole 32-bit register
130 // before truncation.
131 auto Extended =
132 buildExtensionHint(VA, Copy.getReg(0), LLT(VA.getLocVT()));
133 MIRBuilder.buildTrunc(ValVReg, Extended);
134 return;
135 }
136
137 IncomingValueHandler::assignValueToReg(ValVReg, PhysReg, VA);
138 }
139
140 void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,
141 const MachinePointerInfo &MPO,
142 const CCValAssign &VA) override {
143 MachineFunction &MF = MIRBuilder.getMF();
144
145 auto *MMO = MF.getMachineMemOperand(
147 inferAlignFromPtrInfo(MF, MPO));
148 MIRBuilder.buildLoad(ValVReg, Addr, *MMO);
149 }
150
151 /// How the physical register gets marked varies between formal
152 /// parameters (it's a basic-block live-in), and a call instruction
153 /// (it's an implicit-def of the BL).
154 virtual void markPhysRegUsed(unsigned PhysReg) = 0;
155};
156
157struct FormalArgHandler : public AMDGPUIncomingArgHandler {
158 FormalArgHandler(MachineIRBuilder &B, MachineRegisterInfo &MRI)
159 : AMDGPUIncomingArgHandler(B, MRI) {}
160
161 void markPhysRegUsed(unsigned PhysReg) override {
162 MIRBuilder.getMBB().addLiveIn(PhysReg);
163 }
164};
165
166struct CallReturnHandler : public AMDGPUIncomingArgHandler {
167 CallReturnHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
169 : AMDGPUIncomingArgHandler(MIRBuilder, MRI), MIB(MIB) {}
170
171 void markPhysRegUsed(unsigned PhysReg) override {
172 MIB.addDef(PhysReg, RegState::Implicit);
173 }
174
176};
177
178struct AMDGPUOutgoingArgHandler : public AMDGPUOutgoingValueHandler {
179 /// For tail calls, the byte offset of the call's argument area from the
180 /// callee's. Unused elsewhere.
181 int FPDiff;
182
183 // Cache the SP register vreg if we need it more than once in this call site.
185
186 bool IsTailCall;
187
188 AMDGPUOutgoingArgHandler(MachineIRBuilder &MIRBuilder,
190 bool IsTailCall = false, int FPDiff = 0)
191 : AMDGPUOutgoingValueHandler(MIRBuilder, MRI, MIB), FPDiff(FPDiff),
192 IsTailCall(IsTailCall) {}
193
194 Register getStackAddress(uint64_t Size, int64_t Offset,
196 ISD::ArgFlagsTy Flags) override {
197 MachineFunction &MF = MIRBuilder.getMF();
198 const LLT PtrTy = LLT::pointer(AMDGPUAS::PRIVATE_ADDRESS, 32);
199 const LLT S32 = LLT::scalar(32);
200
201 if (IsTailCall) {
202 Offset += FPDiff;
203 int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);
204 auto FIReg = MIRBuilder.buildFrameIndex(PtrTy, FI);
206 return FIReg.getReg(0);
207 }
208
210
211 if (!SPReg) {
212 const GCNSubtarget &ST = MIRBuilder.getMF().getSubtarget<GCNSubtarget>();
213 if (ST.enableFlatScratch()) {
214 // The stack is accessed unswizzled, so we can use a regular copy.
215 SPReg = MIRBuilder.buildCopy(PtrTy,
216 MFI->getStackPtrOffsetReg()).getReg(0);
217 } else {
218 // The address we produce here, without knowing the use context, is going
219 // to be interpreted as a vector address, so we need to convert to a
220 // swizzled address.
221 SPReg = MIRBuilder.buildInstr(AMDGPU::G_AMDGPU_WAVE_ADDRESS, {PtrTy},
222 {MFI->getStackPtrOffsetReg()}).getReg(0);
223 }
224 }
225
226 auto OffsetReg = MIRBuilder.buildConstant(S32, Offset);
227
228 auto AddrReg = MIRBuilder.buildPtrAdd(PtrTy, SPReg, OffsetReg);
230 return AddrReg.getReg(0);
231 }
232
233 void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,
234 const MachinePointerInfo &MPO,
235 const CCValAssign &VA) override {
236 MachineFunction &MF = MIRBuilder.getMF();
237 uint64_t LocMemOffset = VA.getLocMemOffset();
238 const auto &ST = MF.getSubtarget<GCNSubtarget>();
239
240 auto *MMO = MF.getMachineMemOperand(
241 MPO, MachineMemOperand::MOStore, MemTy,
242 commonAlignment(ST.getStackAlignment(), LocMemOffset));
243 MIRBuilder.buildStore(ValVReg, Addr, *MMO);
244 }
245
246 void assignValueToAddress(const CallLowering::ArgInfo &Arg,
247 unsigned ValRegIndex, Register Addr, LLT MemTy,
248 const MachinePointerInfo &MPO,
249 const CCValAssign &VA) override {
251 ? extendRegister(Arg.Regs[ValRegIndex], VA)
252 : Arg.Regs[ValRegIndex];
253 assignValueToAddress(ValVReg, Addr, MemTy, MPO, VA);
254 }
255};
256} // anonymous namespace
257
261
262// FIXME: Compatibility shim
264 switch (MIOpc) {
265 case TargetOpcode::G_SEXT:
266 return ISD::SIGN_EXTEND;
267 case TargetOpcode::G_ZEXT:
268 return ISD::ZERO_EXTEND;
269 case TargetOpcode::G_ANYEXT:
270 return ISD::ANY_EXTEND;
271 default:
272 llvm_unreachable("not an extend opcode");
273 }
274}
275
276bool AMDGPUCallLowering::canLowerReturn(MachineFunction &MF,
277 CallingConv::ID CallConv,
279 bool IsVarArg) const {
280 // For shaders. Vector types should be explicitly handled by CC.
281 if (AMDGPU::isEntryFunctionCC(CallConv))
282 return true;
283
285 const SITargetLowering &TLI = *getTLI<SITargetLowering>();
286 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs,
287 MF.getFunction().getContext());
288
289 return checkReturn(CCInfo, Outs, TLI.CCAssignFnForReturn(CallConv, IsVarArg));
290}
291
292/// Lower the return value for the already existing \p Ret. This assumes that
293/// \p B's insertion point is correct.
294bool AMDGPUCallLowering::lowerReturnVal(MachineIRBuilder &B,
295 const Value *Val, ArrayRef<Register> VRegs,
296 MachineInstrBuilder &Ret) const {
297 if (!Val)
298 return true;
299
300 auto &MF = B.getMF();
301 const auto &F = MF.getFunction();
302 const DataLayout &DL = MF.getDataLayout();
303 MachineRegisterInfo *MRI = B.getMRI();
304 LLVMContext &Ctx = F.getContext();
305
306 CallingConv::ID CC = F.getCallingConv();
307 const SITargetLowering &TLI = *getTLI<SITargetLowering>();
308
309 SmallVector<EVT, 8> SplitEVTs;
310 ComputeValueVTs(TLI, DL, Val->getType(), SplitEVTs);
311 assert(VRegs.size() == SplitEVTs.size() &&
312 "For each split Type there should be exactly one VReg.");
313
314 SmallVector<ArgInfo, 8> SplitRetInfos;
315
316 for (unsigned i = 0; i < SplitEVTs.size(); ++i) {
317 EVT VT = SplitEVTs[i];
318 Register Reg = VRegs[i];
319 ArgInfo RetInfo(Reg, VT.getTypeForEVT(Ctx), 0);
320 setArgFlags(RetInfo, AttributeList::ReturnIndex, DL, F);
321
322 if (VT.isScalarInteger()) {
323 unsigned ExtendOp = TargetOpcode::G_ANYEXT;
324 if (RetInfo.Flags[0].isSExt()) {
325 assert(RetInfo.Regs.size() == 1 && "expect only simple return values");
326 ExtendOp = TargetOpcode::G_SEXT;
327 } else if (RetInfo.Flags[0].isZExt()) {
328 assert(RetInfo.Regs.size() == 1 && "expect only simple return values");
329 ExtendOp = TargetOpcode::G_ZEXT;
330 }
331
332 EVT ExtVT = TLI.getTypeForExtReturn(Ctx, VT,
333 extOpcodeToISDExtOpcode(ExtendOp));
334 if (ExtVT != VT) {
335 RetInfo.Ty = ExtVT.getTypeForEVT(Ctx);
336 LLT ExtTy = getLLTForType(*RetInfo.Ty, DL);
337 Reg = B.buildInstr(ExtendOp, {ExtTy}, {Reg}).getReg(0);
338 }
339 }
340
341 if (Reg != RetInfo.Regs[0]) {
342 RetInfo.Regs[0] = Reg;
343 // Reset the arg flags after modifying Reg.
344 setArgFlags(RetInfo, AttributeList::ReturnIndex, DL, F);
345 }
346
347 splitToValueTypes(RetInfo, SplitRetInfos, DL, CC);
348 }
349
350 CCAssignFn *AssignFn = TLI.CCAssignFnForReturn(CC, F.isVarArg());
351
352 OutgoingValueAssigner Assigner(AssignFn);
353 AMDGPUOutgoingValueHandler RetHandler(B, *MRI, Ret);
354 return determineAndHandleAssignments(RetHandler, Assigner, SplitRetInfos, B,
355 CC, F.isVarArg());
356}
357
359 ArrayRef<Register> VRegs,
360 FunctionLoweringInfo &FLI) const {
361
362 MachineFunction &MF = B.getMF();
364 MFI->setIfReturnsVoid(!Val);
365
366 assert(!Val == VRegs.empty() && "Return value without a vreg");
367
368 CallingConv::ID CC = B.getMF().getFunction().getCallingConv();
369 const bool IsShader = AMDGPU::isShader(CC);
370 const bool IsWaveEnd =
371 (IsShader && MFI->returnsVoid()) || AMDGPU::isKernel(CC);
372 if (IsWaveEnd) {
373 B.buildInstr(AMDGPU::S_ENDPGM)
374 .addImm(0);
375 return true;
376 }
377
378 const bool IsWholeWave = MFI->isWholeWaveFunction();
379 unsigned ReturnOpc = IsWholeWave ? AMDGPU::G_AMDGPU_WHOLE_WAVE_FUNC_RETURN
380 : IsShader ? AMDGPU::SI_RETURN_TO_EPILOG
381 : AMDGPU::SI_RETURN;
382 auto Ret = B.buildInstrNoInsert(ReturnOpc);
383
384 if (!FLI.CanLowerReturn)
385 insertSRetStores(B, Val->getType(), VRegs, FLI.DemoteRegister);
386 else if (!lowerReturnVal(B, Val, VRegs, Ret))
387 return false;
388
389 if (IsWholeWave)
390 addOriginalExecToReturn(B.getMF(), Ret);
391
392 // TODO: Handle CalleeSavedRegsViaCopy.
393
394 B.insertInstr(Ret);
395 return true;
396}
397
398void AMDGPUCallLowering::lowerParameterPtr(Register DstReg, MachineIRBuilder &B,
399 uint64_t Offset) const {
400 MachineFunction &MF = B.getMF();
403 Register KernArgSegmentPtr =
405 Register KernArgSegmentVReg = MRI.getLiveInVirtReg(KernArgSegmentPtr);
406
407 auto OffsetReg = B.buildConstant(LLT::scalar(64), Offset);
408
409 B.buildPtrAdd(DstReg, KernArgSegmentVReg, OffsetReg);
410}
411
412void AMDGPUCallLowering::lowerParameter(MachineIRBuilder &B, ArgInfo &OrigArg,
414 Align Alignment) const {
415 MachineFunction &MF = B.getMF();
416 const Function &F = MF.getFunction();
417 const DataLayout &DL = F.getDataLayout();
420
422
423 SmallVector<ArgInfo, 32> SplitArgs;
424 SmallVector<uint64_t> FieldOffsets;
425 splitToValueTypes(OrigArg, SplitArgs, DL, F.getCallingConv(), &FieldOffsets);
426
427 unsigned Idx = 0;
428 for (ArgInfo &SplitArg : SplitArgs) {
429 Register PtrReg = B.getMRI()->createGenericVirtualRegister(PtrTy);
430 lowerParameterPtr(PtrReg, B, Offset + FieldOffsets[Idx]);
431
432 LLT ArgTy = getLLTForType(*SplitArg.Ty, DL);
433 if (SplitArg.Flags[0].isPointer()) {
434 // Compensate for losing pointeriness in splitValueTypes.
435 LLT PtrTy = LLT::pointer(SplitArg.Flags[0].getPointerAddrSpace(),
436 ArgTy.getScalarSizeInBits());
437 ArgTy = ArgTy.isVector() ? LLT::vector(ArgTy.getElementCount(), PtrTy)
438 : PtrTy;
439 }
440
441 MachineMemOperand *MMO = MF.getMachineMemOperand(
442 PtrInfo,
445 ArgTy, commonAlignment(Alignment, FieldOffsets[Idx]));
446
447 assert(SplitArg.Regs.size() == 1);
448
449 B.buildLoad(SplitArg.Regs[0], PtrReg, *MMO);
450 ++Idx;
451 }
452}
453
454// Allocate special inputs passed in user SGPRs.
455static void allocateHSAUserSGPRs(CCState &CCInfo,
457 MachineFunction &MF,
458 const SIRegisterInfo &TRI,
460 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
461 const GCNUserSGPRUsageInfo &UserSGPRInfo = Info.getUserSGPRInfo();
462 if (UserSGPRInfo.hasPrivateSegmentBuffer()) {
463 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
464 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
465 CCInfo.AllocateReg(PrivateSegmentBufferReg);
466 }
467
468 if (UserSGPRInfo.hasDispatchPtr()) {
469 Register DispatchPtrReg = Info.addDispatchPtr(TRI);
470 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
471 CCInfo.AllocateReg(DispatchPtrReg);
472 }
473
474 if (UserSGPRInfo.hasQueuePtr()) {
475 Register QueuePtrReg = Info.addQueuePtr(TRI);
476 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
477 CCInfo.AllocateReg(QueuePtrReg);
478 }
479
480 if (UserSGPRInfo.hasKernargSegmentPtr()) {
482 Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
484 Register VReg = MRI.createGenericVirtualRegister(P4);
485 MRI.addLiveIn(InputPtrReg, VReg);
486 B.getMBB().addLiveIn(InputPtrReg);
487 B.buildCopy(VReg, InputPtrReg);
488 CCInfo.AllocateReg(InputPtrReg);
489 }
490
491 if (UserSGPRInfo.hasDispatchID()) {
492 Register DispatchIDReg = Info.addDispatchID(TRI);
493 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
494 CCInfo.AllocateReg(DispatchIDReg);
495 }
496
497 if (UserSGPRInfo.hasFlatScratchInit()) {
498 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
499 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
500 CCInfo.AllocateReg(FlatScratchInitReg);
501 }
502
503 if (UserSGPRInfo.hasPrivateSegmentSize()) {
504 Register PrivateSegmentSizeReg = Info.addPrivateSegmentSize(TRI);
505 MF.addLiveIn(PrivateSegmentSizeReg, &AMDGPU::SGPR_32RegClass);
506 CCInfo.AllocateReg(PrivateSegmentSizeReg);
507 }
508
509 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
510 // these from the dispatch pointer.
511}
512
514 MachineIRBuilder &B, const Function &F,
515 ArrayRef<ArrayRef<Register>> VRegs) const {
516 MachineFunction &MF = B.getMF();
517 const GCNSubtarget *Subtarget = &MF.getSubtarget<GCNSubtarget>();
520 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
522 const DataLayout &DL = F.getDataLayout();
523
525 CCState CCInfo(F.getCallingConv(), F.isVarArg(), MF, ArgLocs, F.getContext());
526
527 allocateHSAUserSGPRs(CCInfo, B, MF, *TRI, *Info);
528
529 unsigned i = 0;
530 const Align KernArgBaseAlign(16);
531 const unsigned BaseOffset = Subtarget->getExplicitKernelArgOffset();
532 uint64_t ExplicitArgOffset = 0;
533
534 // TODO: Align down to dword alignment and extract bits for extending loads.
535 for (auto &Arg : F.args()) {
536 // TODO: Add support for kernarg preload.
537 if (Arg.hasAttribute("amdgpu-hidden-argument")) {
538 LLVM_DEBUG(dbgs() << "Preloading hidden arguments is not supported\n");
539 return false;
540 }
541
542 const bool IsByRef = Arg.hasByRefAttr();
543 Type *ArgTy = IsByRef ? Arg.getParamByRefType() : Arg.getType();
544 unsigned AllocSize = DL.getTypeAllocSize(ArgTy);
545 if (AllocSize == 0)
546 continue;
547
548 MaybeAlign ParamAlign = IsByRef ? Arg.getParamAlign() : std::nullopt;
549 Align ABIAlign = DL.getValueOrABITypeAlignment(ParamAlign, ArgTy);
550
551 uint64_t ArgOffset = alignTo(ExplicitArgOffset, ABIAlign) + BaseOffset;
552 ExplicitArgOffset = alignTo(ExplicitArgOffset, ABIAlign) + AllocSize;
553
554 if (Arg.use_empty()) {
555 ++i;
556 continue;
557 }
558
559 Align Alignment = commonAlignment(KernArgBaseAlign, ArgOffset);
560
561 if (IsByRef) {
562 unsigned ByRefAS = cast<PointerType>(Arg.getType())->getAddressSpace();
563
564 assert(VRegs[i].size() == 1 &&
565 "expected only one register for byval pointers");
566 if (ByRefAS == AMDGPUAS::CONSTANT_ADDRESS) {
567 lowerParameterPtr(VRegs[i][0], B, ArgOffset);
568 } else {
569 const LLT ConstPtrTy = LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64);
570 Register PtrReg = MRI.createGenericVirtualRegister(ConstPtrTy);
571 lowerParameterPtr(PtrReg, B, ArgOffset);
572
573 B.buildAddrSpaceCast(VRegs[i][0], PtrReg);
574 }
575 } else {
576 ArgInfo OrigArg(VRegs[i], Arg, i);
577 const unsigned OrigArgIdx = i + AttributeList::FirstArgIndex;
578 setArgFlags(OrigArg, OrigArgIdx, DL, F);
579 lowerParameter(B, OrigArg, ArgOffset, Alignment);
580 }
581
582 ++i;
583 }
584
585 if (Info->getNumKernargPreloadedSGPRs())
586 Info->setNumWaveDispatchSGPRs(Info->getNumUserSGPRs());
587
588 TLI.allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
589 TLI.allocateSystemSGPRs(CCInfo, MF, *Info, F.getCallingConv(), false);
590 return true;
591}
592
595 FunctionLoweringInfo &FLI) const {
596 CallingConv::ID CC = F.getCallingConv();
597
598 // The infrastructure for normal calling convention lowering is essentially
599 // useless for kernels. We want to avoid any kind of legalization or argument
600 // splitting.
602 return lowerFormalArgumentsKernel(B, F, VRegs);
603
604 const bool IsGraphics = AMDGPU::isGraphics(CC);
605 const bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CC);
606
607 MachineFunction &MF = B.getMF();
608 MachineBasicBlock &MBB = B.getMBB();
611 const GCNSubtarget &Subtarget = MF.getSubtarget<GCNSubtarget>();
612 const SIRegisterInfo *TRI = Subtarget.getRegisterInfo();
613 const DataLayout &DL = F.getDataLayout();
614
616 CCState CCInfo(CC, F.isVarArg(), MF, ArgLocs, F.getContext());
617 const GCNUserSGPRUsageInfo &UserSGPRInfo = Info->getUserSGPRInfo();
618
619 if (UserSGPRInfo.hasImplicitBufferPtr()) {
620 Register ImplicitBufferPtrReg = Info->addImplicitBufferPtr(*TRI);
621 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
622 CCInfo.AllocateReg(ImplicitBufferPtrReg);
623 }
624
625 // FIXME: This probably isn't defined for mesa
626 if (UserSGPRInfo.hasFlatScratchInit() && !Subtarget.isAmdPalOS()) {
627 Register FlatScratchInitReg = Info->addFlatScratchInit(*TRI);
628 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
629 CCInfo.AllocateReg(FlatScratchInitReg);
630 }
631
632 SmallVector<ArgInfo, 32> SplitArgs;
633 unsigned Idx = 0;
634 unsigned PSInputNum = 0;
635
636 // Insert the hidden sret parameter if the return value won't fit in the
637 // return registers.
638 if (!FLI.CanLowerReturn)
640
641 for (auto &Arg : F.args()) {
642 if (DL.getTypeStoreSize(Arg.getType()) == 0)
643 continue;
644
645 if (Info->isWholeWaveFunction() && Idx == 0) {
646 assert(VRegs[Idx].size() == 1 && "Expected only one register");
647
648 // The first argument for whole wave functions is the original EXEC value.
649 B.buildInstr(AMDGPU::G_AMDGPU_WHOLE_WAVE_FUNC_SETUP)
650 .addDef(VRegs[Idx][0]);
651
652 ++Idx;
653 continue;
654 }
655
656 const bool InReg = Arg.hasAttribute(Attribute::InReg);
657
658 if (Arg.hasAttribute(Attribute::SwiftSelf) ||
659 Arg.hasAttribute(Attribute::SwiftError) ||
660 Arg.hasAttribute(Attribute::Nest))
661 return false;
662
663 if (CC == CallingConv::AMDGPU_PS && !InReg && PSInputNum <= 15) {
664 const bool ArgUsed = !Arg.use_empty();
665 bool SkipArg = !ArgUsed && !Info->isPSInputAllocated(PSInputNum);
666
667 if (!SkipArg) {
668 Info->markPSInputAllocated(PSInputNum);
669 if (ArgUsed)
670 Info->markPSInputEnabled(PSInputNum);
671 }
672
673 ++PSInputNum;
674
675 if (SkipArg) {
676 for (Register R : VRegs[Idx])
677 B.buildUndef(R);
678
679 ++Idx;
680 continue;
681 }
682 }
683
684 ArgInfo OrigArg(VRegs[Idx], Arg, Idx);
685 const unsigned OrigArgIdx = Idx + AttributeList::FirstArgIndex;
686 setArgFlags(OrigArg, OrigArgIdx, DL, F);
687
688 splitToValueTypes(OrigArg, SplitArgs, DL, CC);
689 ++Idx;
690 }
691
692 // At least one interpolation mode must be enabled or else the GPU will
693 // hang.
694 //
695 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
696 // set PSInputAddr, the user wants to enable some bits after the compilation
697 // based on run-time states. Since we can't know what the final PSInputEna
698 // will look like, so we shouldn't do anything here and the user should take
699 // responsibility for the correct programming.
700 //
701 // Otherwise, the following restrictions apply:
702 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
703 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
704 // enabled too.
705 if (CC == CallingConv::AMDGPU_PS) {
706 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
707 ((Info->getPSInputAddr() & 0xF) == 0 &&
708 Info->isPSInputAllocated(11))) {
709 CCInfo.AllocateReg(AMDGPU::VGPR0);
710 CCInfo.AllocateReg(AMDGPU::VGPR1);
711 Info->markPSInputAllocated(0);
712 Info->markPSInputEnabled(0);
713 }
714
715 if (Subtarget.isAmdPalOS()) {
716 // For isAmdPalOS, the user does not enable some bits after compilation
717 // based on run-time states; the register values being generated here are
718 // the final ones set in hardware. Therefore we need to apply the
719 // workaround to PSInputAddr and PSInputEnable together. (The case where
720 // a bit is set in PSInputAddr but not PSInputEnable is where the frontend
721 // set up an input arg for a particular interpolation mode, but nothing
722 // uses that input arg. Really we should have an earlier pass that removes
723 // such an arg.)
724 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
725 if ((PsInputBits & 0x7F) == 0 ||
726 ((PsInputBits & 0xF) == 0 &&
727 (PsInputBits >> 11 & 1)))
728 Info->markPSInputEnabled(llvm::countr_zero(Info->getPSInputAddr()));
729 }
730 }
731
733 CCAssignFn *AssignFn = TLI.CCAssignFnForCall(CC, F.isVarArg());
734
735 if (!MBB.empty())
736 B.setInstr(*MBB.begin());
737
738 if (!IsEntryFunc && !IsGraphics) {
739 // For the fixed ABI, pass workitem IDs in the last argument register.
740 TLI.allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
741
742 if (!Subtarget.enableFlatScratch())
743 CCInfo.AllocateReg(Info->getScratchRSrcReg());
744 TLI.allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
745 }
746
747 IncomingValueAssigner Assigner(AssignFn);
748 if (!determineAssignments(Assigner, SplitArgs, CCInfo))
749 return false;
750
751 if (IsEntryFunc) {
752 // This assumes the registers are allocated by CCInfo in ascending order
753 // with no gaps.
754 Info->setNumWaveDispatchSGPRs(
755 CCInfo.getFirstUnallocated(AMDGPU::SGPR_32RegClass.getRegisters()));
756 Info->setNumWaveDispatchVGPRs(
757 CCInfo.getFirstUnallocated(AMDGPU::VGPR_32RegClass.getRegisters()));
758 }
759
760 FormalArgHandler Handler(B, MRI);
761 if (!handleAssignments(Handler, SplitArgs, CCInfo, ArgLocs, B))
762 return false;
763
764 uint64_t StackSize = Assigner.StackSize;
765
766 // Start adding system SGPRs.
767 if (IsEntryFunc)
768 TLI.allocateSystemSGPRs(CCInfo, MF, *Info, CC, IsGraphics);
769
770 // When we tail call, we need to check if the callee's arguments will fit on
771 // the caller's stack. So, whenever we lower formal arguments, we should keep
772 // track of this information, since we might lower a tail call in this
773 // function later.
774 Info->setBytesInStackArgArea(StackSize);
775
776 // Move back to the end of the basic block.
777 B.setMBB(MBB);
778
779 return true;
780}
781
783 CCState &CCInfo,
784 SmallVectorImpl<std::pair<MCRegister, Register>> &ArgRegs,
785 CallLoweringInfo &Info) const {
786 MachineFunction &MF = MIRBuilder.getMF();
787
788 // If there's no call site, this doesn't correspond to a call from the IR and
789 // doesn't need implicit inputs.
790 if (!Info.CB)
791 return true;
792
793 const AMDGPUFunctionArgInfo *CalleeArgInfo
795
797 const AMDGPUFunctionArgInfo &CallerArgInfo = MFI->getArgInfo();
798
799
800 // TODO: Unify with private memory register handling. This is complicated by
801 // the fact that at least in kernels, the input argument is not necessarily
802 // in the same location as the input.
812 };
813
814 static constexpr StringLiteral ImplicitAttrNames[][2] = {
815 {"amdgpu-no-dispatch-ptr", ""},
816 {"amdgpu-no-queue-ptr", ""},
817 {"amdgpu-no-implicitarg-ptr", ""},
818 {"amdgpu-no-dispatch-id", ""},
819 {"amdgpu-no-workgroup-id-x", "amdgpu-no-cluster-id-x"},
820 {"amdgpu-no-workgroup-id-y", "amdgpu-no-cluster-id-y"},
821 {"amdgpu-no-workgroup-id-z", "amdgpu-no-cluster-id-z"},
822 {"amdgpu-no-lds-kernel-id", ""},
823 };
824
826
827 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
828 const AMDGPULegalizerInfo *LI
829 = static_cast<const AMDGPULegalizerInfo*>(ST.getLegalizerInfo());
830
831 unsigned I = 0;
832 for (auto InputID : InputRegs) {
833 const ArgDescriptor *OutgoingArg;
834 const TargetRegisterClass *ArgRC;
835 LLT ArgTy;
836
837 // If the callee does not use the attribute value, skip copying the value.
838 if (all_of(ImplicitAttrNames[I++], [&](StringRef AttrName) {
839 return AttrName.empty() || Info.CB->hasFnAttr(AttrName);
840 }))
841 continue;
842
843 std::tie(OutgoingArg, ArgRC, ArgTy) =
844 CalleeArgInfo->getPreloadedValue(InputID);
845 if (!OutgoingArg)
846 continue;
847
848 const ArgDescriptor *IncomingArg;
849 const TargetRegisterClass *IncomingArgRC;
850 std::tie(IncomingArg, IncomingArgRC, ArgTy) =
851 CallerArgInfo.getPreloadedValue(InputID);
852 assert(IncomingArgRC == ArgRC);
853
854 Register InputReg = MRI.createGenericVirtualRegister(ArgTy);
855
856 if (IncomingArg) {
857 LI->buildLoadInputValue(InputReg, MIRBuilder, IncomingArg, ArgRC, ArgTy);
858 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
859 LI->getImplicitArgPtr(InputReg, MRI, MIRBuilder);
860 } else if (InputID == AMDGPUFunctionArgInfo::LDS_KERNEL_ID) {
861 std::optional<uint32_t> Id =
863 if (Id) {
864 MIRBuilder.buildConstant(InputReg, *Id);
865 } else {
866 MIRBuilder.buildUndef(InputReg);
867 }
868 } else {
869 // We may have proven the input wasn't needed, although the ABI is
870 // requiring it. We just need to allocate the register appropriately.
871 MIRBuilder.buildUndef(InputReg);
872 }
873
874 if (OutgoingArg->isRegister()) {
875 ArgRegs.emplace_back(OutgoingArg->getRegister(), InputReg);
876 if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
877 report_fatal_error("failed to allocate implicit input argument");
878 } else {
879 LLVM_DEBUG(dbgs() << "Unhandled stack passed implicit input argument\n");
880 return false;
881 }
882 }
883
884 // Pack workitem IDs into a single register or pass it as is if already
885 // packed.
886 const ArgDescriptor *OutgoingArg;
887 const TargetRegisterClass *ArgRC;
888 LLT ArgTy;
889
890 std::tie(OutgoingArg, ArgRC, ArgTy) =
892 if (!OutgoingArg)
893 std::tie(OutgoingArg, ArgRC, ArgTy) =
895 if (!OutgoingArg)
896 std::tie(OutgoingArg, ArgRC, ArgTy) =
898 if (!OutgoingArg)
899 return false;
900
901 auto WorkitemIDX =
902 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
903 auto WorkitemIDY =
904 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
905 auto WorkitemIDZ =
906 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
907
908 const ArgDescriptor *IncomingArgX = std::get<0>(WorkitemIDX);
909 const ArgDescriptor *IncomingArgY = std::get<0>(WorkitemIDY);
910 const ArgDescriptor *IncomingArgZ = std::get<0>(WorkitemIDZ);
911 const LLT S32 = LLT::scalar(32);
912
913 const bool NeedWorkItemIDX = !Info.CB->hasFnAttr("amdgpu-no-workitem-id-x");
914 const bool NeedWorkItemIDY = !Info.CB->hasFnAttr("amdgpu-no-workitem-id-y");
915 const bool NeedWorkItemIDZ = !Info.CB->hasFnAttr("amdgpu-no-workitem-id-z");
916
917 // If incoming ids are not packed we need to pack them.
918 // FIXME: Should consider known workgroup size to eliminate known 0 cases.
919 Register InputReg;
920 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
921 NeedWorkItemIDX) {
922 if (ST.getMaxWorkitemID(MF.getFunction(), 0) != 0) {
923 InputReg = MRI.createGenericVirtualRegister(S32);
924 LI->buildLoadInputValue(InputReg, MIRBuilder, IncomingArgX,
925 std::get<1>(WorkitemIDX),
926 std::get<2>(WorkitemIDX));
927 } else {
928 InputReg = MIRBuilder.buildConstant(S32, 0).getReg(0);
929 }
930 }
931
932 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
933 NeedWorkItemIDY && ST.getMaxWorkitemID(MF.getFunction(), 1) != 0) {
934 Register Y = MRI.createGenericVirtualRegister(S32);
935 LI->buildLoadInputValue(Y, MIRBuilder, IncomingArgY,
936 std::get<1>(WorkitemIDY), std::get<2>(WorkitemIDY));
937
938 Y = MIRBuilder.buildShl(S32, Y, MIRBuilder.buildConstant(S32, 10)).getReg(0);
939 InputReg = InputReg ? MIRBuilder.buildOr(S32, InputReg, Y).getReg(0) : Y;
940 }
941
942 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
943 NeedWorkItemIDZ && ST.getMaxWorkitemID(MF.getFunction(), 2) != 0) {
944 Register Z = MRI.createGenericVirtualRegister(S32);
945 LI->buildLoadInputValue(Z, MIRBuilder, IncomingArgZ,
946 std::get<1>(WorkitemIDZ), std::get<2>(WorkitemIDZ));
947
948 Z = MIRBuilder.buildShl(S32, Z, MIRBuilder.buildConstant(S32, 20)).getReg(0);
949 InputReg = InputReg ? MIRBuilder.buildOr(S32, InputReg, Z).getReg(0) : Z;
950 }
951
952 if (!InputReg &&
953 (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
954 InputReg = MRI.createGenericVirtualRegister(S32);
955 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
956 // We're in a situation where the outgoing function requires the workitem
957 // ID, but the calling function does not have it (e.g a graphics function
958 // calling a C calling convention function). This is illegal, but we need
959 // to produce something.
960 MIRBuilder.buildUndef(InputReg);
961 } else {
962 // Workitem ids are already packed, any of present incoming arguments will
963 // carry all required fields.
965 IncomingArgX ? *IncomingArgX :
966 IncomingArgY ? *IncomingArgY : *IncomingArgZ, ~0u);
967 LI->buildLoadInputValue(InputReg, MIRBuilder, &IncomingArg,
968 &AMDGPU::VGPR_32RegClass, S32);
969 }
970 }
971
972 if (OutgoingArg->isRegister()) {
973 if (InputReg)
974 ArgRegs.emplace_back(OutgoingArg->getRegister(), InputReg);
975
976 if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
977 report_fatal_error("failed to allocate implicit input argument");
978 } else {
979 LLVM_DEBUG(dbgs() << "Unhandled stack passed implicit input argument\n");
980 return false;
981 }
982
983 return true;
984}
985
986/// Returns a pair containing the fixed CCAssignFn and the vararg CCAssignFn for
987/// CC.
988static std::pair<CCAssignFn *, CCAssignFn *>
990 return {TLI.CCAssignFnForCall(CC, false), TLI.CCAssignFnForCall(CC, true)};
991}
992
993static unsigned getCallOpcode(const MachineFunction &CallerF, bool IsIndirect,
994 bool IsTailCall, bool IsWave32,
996 bool IsDynamicVGPRChainCall = false) {
997 // For calls to amdgpu_cs_chain functions, the address is known to be uniform.
998 assert((AMDGPU::isChainCC(CC) || !IsIndirect || !IsTailCall) &&
999 "Indirect calls can't be tail calls, "
1000 "because the address can be divergent");
1001 if (!IsTailCall)
1002 return AMDGPU::G_SI_CALL;
1003
1004 if (AMDGPU::isChainCC(CC)) {
1005 if (IsDynamicVGPRChainCall)
1006 return IsWave32 ? AMDGPU::SI_CS_CHAIN_TC_W32_DVGPR
1007 : AMDGPU::SI_CS_CHAIN_TC_W64_DVGPR;
1008 return IsWave32 ? AMDGPU::SI_CS_CHAIN_TC_W32 : AMDGPU::SI_CS_CHAIN_TC_W64;
1009 }
1010
1011 if (CallerF.getFunction().getCallingConv() ==
1013 return AMDGPU::SI_TCRETURN_GFX_WholeWave;
1014
1016 return AMDGPU::SI_TCRETURN_GFX;
1017
1018 return AMDGPU::SI_TCRETURN;
1019}
1020
1021// Add operands to call instruction to track the callee.
1023 MachineIRBuilder &MIRBuilder,
1025 bool IsDynamicVGPRChainCall = false) {
1026 if (Info.Callee.isReg()) {
1027 CallInst.addReg(Info.Callee.getReg());
1028 CallInst.addImm(0);
1029 } else if (Info.Callee.isGlobal() && Info.Callee.getOffset() == 0) {
1030 // The call lowering lightly assumed we can directly encode a call target in
1031 // the instruction, which is not the case. Materialize the address here.
1032 const GlobalValue *GV = Info.Callee.getGlobal();
1033 auto Ptr = MIRBuilder.buildGlobalValue(
1034 LLT::pointer(GV->getAddressSpace(), 64), GV);
1035 CallInst.addReg(Ptr.getReg(0));
1036
1037 if (IsDynamicVGPRChainCall) {
1038 // DynamicVGPR chain calls are always indirect.
1039 CallInst.addImm(0);
1040 } else
1041 CallInst.add(Info.Callee);
1042 } else
1043 return false;
1044
1045 return true;
1046}
1047
1050 SmallVectorImpl<ArgInfo> &InArgs) const {
1051 const Function &CallerF = MF.getFunction();
1052 CallingConv::ID CalleeCC = Info.CallConv;
1053 CallingConv::ID CallerCC = CallerF.getCallingConv();
1054
1055 // If the calling conventions match, then everything must be the same.
1056 if (CalleeCC == CallerCC)
1057 return true;
1058
1059 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1060
1061 // Make sure that the caller and callee preserve all of the same registers.
1062 const auto *TRI = ST.getRegisterInfo();
1063
1064 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
1065 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
1066 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
1067 return false;
1068
1069 // Check if the caller and callee will handle arguments in the same way.
1071 CCAssignFn *CalleeAssignFnFixed;
1072 CCAssignFn *CalleeAssignFnVarArg;
1073 std::tie(CalleeAssignFnFixed, CalleeAssignFnVarArg) =
1074 getAssignFnsForCC(CalleeCC, TLI);
1075
1076 CCAssignFn *CallerAssignFnFixed;
1077 CCAssignFn *CallerAssignFnVarArg;
1078 std::tie(CallerAssignFnFixed, CallerAssignFnVarArg) =
1079 getAssignFnsForCC(CallerCC, TLI);
1080
1081 // FIXME: We are not accounting for potential differences in implicitly passed
1082 // inputs, but only the fixed ABI is supported now anyway.
1083 IncomingValueAssigner CalleeAssigner(CalleeAssignFnFixed,
1084 CalleeAssignFnVarArg);
1085 IncomingValueAssigner CallerAssigner(CallerAssignFnFixed,
1086 CallerAssignFnVarArg);
1087 return resultsCompatible(Info, MF, InArgs, CalleeAssigner, CallerAssigner);
1088}
1089
1092 SmallVectorImpl<ArgInfo> &OutArgs) const {
1093 // If there are no outgoing arguments, then we are done.
1094 if (OutArgs.empty())
1095 return true;
1096
1097 const Function &CallerF = MF.getFunction();
1098 CallingConv::ID CalleeCC = Info.CallConv;
1099 CallingConv::ID CallerCC = CallerF.getCallingConv();
1101
1102 CCAssignFn *AssignFnFixed;
1103 CCAssignFn *AssignFnVarArg;
1104 std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
1105
1106 // We have outgoing arguments. Make sure that we can tail call with them.
1108 CCState OutInfo(CalleeCC, false, MF, OutLocs, CallerF.getContext());
1109 OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg);
1110
1111 if (!determineAssignments(Assigner, OutArgs, OutInfo)) {
1112 LLVM_DEBUG(dbgs() << "... Could not analyze call operands.\n");
1113 return false;
1114 }
1115
1116 // Make sure that they can fit on the caller's stack.
1117 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
1118 if (OutInfo.getStackSize() > FuncInfo->getBytesInStackArgArea()) {
1119 LLVM_DEBUG(dbgs() << "... Cannot fit call operands on caller's stack.\n");
1120 return false;
1121 }
1122
1123 // Verify that the parameters in callee-saved registers match.
1124 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1125 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1126 const uint32_t *CallerPreservedMask = TRI->getCallPreservedMask(MF, CallerCC);
1128 return parametersInCSRMatch(MRI, CallerPreservedMask, OutLocs, OutArgs);
1129}
1130
1133 SmallVectorImpl<ArgInfo> &InArgs, SmallVectorImpl<ArgInfo> &OutArgs) const {
1134 // Must pass all target-independent checks in order to tail call optimize.
1135 if (!Info.IsTailCall)
1136 return false;
1137
1138 // Indirect calls can't be tail calls, because the address can be divergent.
1139 // TODO Check divergence info if the call really is divergent.
1140 if (Info.Callee.isReg())
1141 return false;
1142
1143 MachineFunction &MF = B.getMF();
1144 const Function &CallerF = MF.getFunction();
1145 CallingConv::ID CalleeCC = Info.CallConv;
1146 CallingConv::ID CallerCC = CallerF.getCallingConv();
1147
1148 const SIRegisterInfo *TRI = MF.getSubtarget<GCNSubtarget>().getRegisterInfo();
1149 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
1150 // Kernels aren't callable, and don't have a live in return address so it
1151 // doesn't make sense to do a tail call with entry functions.
1152 if (!CallerPreserved)
1153 return false;
1154
1155 if (!AMDGPU::mayTailCallThisCC(CalleeCC)) {
1156 LLVM_DEBUG(dbgs() << "... Calling convention cannot be tail called.\n");
1157 return false;
1158 }
1159
1160 if (any_of(CallerF.args(), [](const Argument &A) {
1161 return A.hasByValAttr() || A.hasSwiftErrorAttr();
1162 })) {
1163 LLVM_DEBUG(dbgs() << "... Cannot tail call from callers with byval "
1164 "or swifterror arguments\n");
1165 return false;
1166 }
1167
1168 // If we have -tailcallopt, then we're done.
1170 return AMDGPU::canGuaranteeTCO(CalleeCC) &&
1171 CalleeCC == CallerF.getCallingConv();
1172 }
1173
1174 // Verify that the incoming and outgoing arguments from the callee are
1175 // safe to tail call.
1176 if (!doCallerAndCalleePassArgsTheSameWay(Info, MF, InArgs)) {
1177 LLVM_DEBUG(
1178 dbgs()
1179 << "... Caller and callee have incompatible calling conventions.\n");
1180 return false;
1181 }
1182
1183 // FIXME: We need to check if any arguments passed in SGPR are uniform. If
1184 // they are not, this cannot be a tail call. If they are uniform, but may be
1185 // VGPR, we need to insert readfirstlanes.
1186 if (!areCalleeOutgoingArgsTailCallable(Info, MF, OutArgs))
1187 return false;
1188
1189 LLVM_DEBUG(dbgs() << "... Call is eligible for tail call optimization.\n");
1190 return true;
1191}
1192
1193// Insert outgoing implicit arguments for a call, by inserting copies to the
1194// implicit argument registers and adding the necessary implicit uses to the
1195// call instruction.
1198 const GCNSubtarget &ST, const SIMachineFunctionInfo &FuncInfo,
1199 CallingConv::ID CalleeCC,
1200 ArrayRef<std::pair<MCRegister, Register>> ImplicitArgRegs) const {
1201 if (!ST.enableFlatScratch()) {
1202 // Insert copies for the SRD. In the HSA case, this should be an identity
1203 // copy.
1204 auto ScratchRSrcReg = MIRBuilder.buildCopy(LLT::fixed_vector(4, 32),
1205 FuncInfo.getScratchRSrcReg());
1206
1207 auto CalleeRSrcReg = AMDGPU::isChainCC(CalleeCC)
1208 ? AMDGPU::SGPR48_SGPR49_SGPR50_SGPR51
1209 : AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3;
1210
1211 MIRBuilder.buildCopy(CalleeRSrcReg, ScratchRSrcReg);
1212 CallInst.addReg(CalleeRSrcReg, RegState::Implicit);
1213 }
1214
1215 for (std::pair<MCRegister, Register> ArgReg : ImplicitArgRegs) {
1216 MIRBuilder.buildCopy((Register)ArgReg.first, ArgReg.second);
1217 CallInst.addReg(ArgReg.first, RegState::Implicit);
1218 }
1219}
1220
1221namespace {
1222// Chain calls have special arguments that we need to handle. These have the
1223// same index as they do in the llvm.amdgcn.cs.chain intrinsic.
1224enum ChainCallArgIdx {
1225 Exec = 1,
1226 Flags = 4,
1227 NumVGPRs = 5,
1228 FallbackExec = 6,
1229 FallbackCallee = 7,
1230};
1231} // anonymous namespace
1232
1234 MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info,
1235 SmallVectorImpl<ArgInfo> &OutArgs) const {
1236 MachineFunction &MF = MIRBuilder.getMF();
1237 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1239 const Function &F = MF.getFunction();
1241 const SIInstrInfo *TII = ST.getInstrInfo();
1242 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1244
1245 // True when we're tail calling, but without -tailcallopt.
1246 bool IsSibCall = !MF.getTarget().Options.GuaranteedTailCallOpt;
1247
1248 // Find out which ABI gets to decide where things go.
1249 CallingConv::ID CalleeCC = Info.CallConv;
1250 CCAssignFn *AssignFnFixed;
1251 CCAssignFn *AssignFnVarArg;
1252 std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);
1253
1254 MachineInstrBuilder CallSeqStart;
1255 if (!IsSibCall)
1256 CallSeqStart = MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKUP);
1257
1258 bool IsChainCall = AMDGPU::isChainCC(Info.CallConv);
1259 bool IsDynamicVGPRChainCall = false;
1260
1261 if (IsChainCall) {
1262 ArgInfo FlagsArg = Info.OrigArgs[ChainCallArgIdx::Flags];
1263 const APInt &FlagsValue = cast<ConstantInt>(FlagsArg.OrigValue)->getValue();
1264 if (FlagsValue.isZero()) {
1265 if (Info.OrigArgs.size() != 5) {
1266 LLVM_DEBUG(dbgs() << "No additional args allowed if flags == 0\n");
1267 return false;
1268 }
1269 } else if (FlagsValue.isOneBitSet(0)) {
1270 IsDynamicVGPRChainCall = true;
1271
1272 if (Info.OrigArgs.size() != 8) {
1273 LLVM_DEBUG(dbgs() << "Expected 3 additional args\n");
1274 return false;
1275 }
1276
1277 // On GFX12, we can only change the VGPR allocation for wave32.
1278 if (!ST.isWave32()) {
1279 F.getContext().diagnose(DiagnosticInfoUnsupported(
1280 F, "dynamic VGPR mode is only supported for wave32"));
1281 return false;
1282 }
1283
1284 ArgInfo FallbackExecArg = Info.OrigArgs[ChainCallArgIdx::FallbackExec];
1285 assert(FallbackExecArg.Regs.size() == 1 &&
1286 "Expected single register for fallback EXEC");
1287 if (!FallbackExecArg.Ty->isIntegerTy(ST.getWavefrontSize())) {
1288 LLVM_DEBUG(dbgs() << "Bad type for fallback EXEC\n");
1289 return false;
1290 }
1291 }
1292 }
1293
1294 unsigned Opc = getCallOpcode(MF, Info.Callee.isReg(), /*IsTailCall*/ true,
1295 ST.isWave32(), CalleeCC, IsDynamicVGPRChainCall);
1296 auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
1297
1298 if (FuncInfo->isWholeWaveFunction())
1299 addOriginalExecToReturn(MF, MIB);
1300
1301 // Keep track of the index of the next operand to be added to the call
1302 unsigned CalleeIdx = MIB->getNumOperands();
1303
1304 if (!addCallTargetOperands(MIB, MIRBuilder, Info, IsDynamicVGPRChainCall))
1305 return false;
1306
1307 // Byte offset for the tail call. When we are sibcalling, this will always
1308 // be 0.
1309 MIB.addImm(0);
1310
1311 // If this is a chain call, we need to pass in the EXEC mask as well as any
1312 // other special args.
1313 if (IsChainCall) {
1314 auto AddRegOrImm = [&](const ArgInfo &Arg) {
1315 if (auto CI = dyn_cast<ConstantInt>(Arg.OrigValue)) {
1316 MIB.addImm(CI->getSExtValue());
1317 } else {
1318 MIB.addReg(Arg.Regs[0]);
1319 unsigned Idx = MIB->getNumOperands() - 1;
1320 MIB->getOperand(Idx).setReg(constrainOperandRegClass(
1321 MF, *TRI, MRI, *TII, *ST.getRegBankInfo(), *MIB, MIB->getDesc(),
1322 MIB->getOperand(Idx), Idx));
1323 }
1324 };
1325
1326 ArgInfo ExecArg = Info.OrigArgs[ChainCallArgIdx::Exec];
1327 assert(ExecArg.Regs.size() == 1 && "Too many regs for EXEC");
1328
1329 if (!ExecArg.Ty->isIntegerTy(ST.getWavefrontSize())) {
1330 LLVM_DEBUG(dbgs() << "Bad type for EXEC");
1331 return false;
1332 }
1333
1334 AddRegOrImm(ExecArg);
1335 if (IsDynamicVGPRChainCall)
1336 std::for_each(Info.OrigArgs.begin() + ChainCallArgIdx::NumVGPRs,
1337 Info.OrigArgs.end(), AddRegOrImm);
1338 }
1339
1340 // Tell the call which registers are clobbered.
1341 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CalleeCC);
1342 MIB.addRegMask(Mask);
1343
1344 // FPDiff is the byte offset of the call's argument area from the callee's.
1345 // Stores to callee stack arguments will be placed in FixedStackSlots offset
1346 // by this amount for a tail call. In a sibling call it must be 0 because the
1347 // caller will deallocate the entire stack and the callee still expects its
1348 // arguments to begin at SP+0.
1349 int FPDiff = 0;
1350
1351 // This will be 0 for sibcalls, potentially nonzero for tail calls produced
1352 // by -tailcallopt. For sibcalls, the memory operands for the call are
1353 // already available in the caller's incoming argument space.
1354 unsigned NumBytes = 0;
1355 if (!IsSibCall) {
1356 // We aren't sibcalling, so we need to compute FPDiff. We need to do this
1357 // before handling assignments, because FPDiff must be known for memory
1358 // arguments.
1359 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
1361 CCState OutInfo(CalleeCC, false, MF, OutLocs, F.getContext());
1362
1363 // FIXME: Not accounting for callee implicit inputs
1364 OutgoingValueAssigner CalleeAssigner(AssignFnFixed, AssignFnVarArg);
1365 if (!determineAssignments(CalleeAssigner, OutArgs, OutInfo))
1366 return false;
1367
1368 // The callee will pop the argument stack as a tail call. Thus, we must
1369 // keep it 16-byte aligned.
1370 NumBytes = alignTo(OutInfo.getStackSize(), ST.getStackAlignment());
1371
1372 // FPDiff will be negative if this tail call requires more space than we
1373 // would automatically have in our incoming argument space. Positive if we
1374 // actually shrink the stack.
1375 FPDiff = NumReusableBytes - NumBytes;
1376
1377 // The stack pointer must be 16-byte aligned at all times it's used for a
1378 // memory operation, which in practice means at *all* times and in
1379 // particular across call boundaries. Therefore our own arguments started at
1380 // a 16-byte aligned SP and the delta applied for the tail call should
1381 // satisfy the same constraint.
1382 assert(isAligned(ST.getStackAlignment(), FPDiff) &&
1383 "unaligned stack on tail call");
1384 }
1385
1387 CCState CCInfo(Info.CallConv, Info.IsVarArg, MF, ArgLocs, F.getContext());
1388
1389 // We could pass MIB and directly add the implicit uses to the call
1390 // now. However, as an aesthetic choice, place implicit argument operands
1391 // after the ordinary user argument registers.
1393
1394 if (Info.CallConv != CallingConv::AMDGPU_Gfx &&
1395 Info.CallConv != CallingConv::AMDGPU_Gfx_WholeWave &&
1396 !AMDGPU::isChainCC(Info.CallConv)) {
1397 // With a fixed ABI, allocate fixed registers before user arguments.
1398 if (!passSpecialInputs(MIRBuilder, CCInfo, ImplicitArgRegs, Info))
1399 return false;
1400 }
1401
1402 OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg);
1403
1404 if (!determineAssignments(Assigner, OutArgs, CCInfo))
1405 return false;
1406
1407 // Do the actual argument marshalling.
1408 AMDGPUOutgoingArgHandler Handler(MIRBuilder, MRI, MIB, true, FPDiff);
1409 if (!handleAssignments(Handler, OutArgs, CCInfo, ArgLocs, MIRBuilder))
1410 return false;
1411
1412 if (Info.ConvergenceCtrlToken) {
1413 MIB.addUse(Info.ConvergenceCtrlToken, RegState::Implicit);
1414 }
1415 handleImplicitCallArguments(MIRBuilder, MIB, ST, *FuncInfo, CalleeCC,
1416 ImplicitArgRegs);
1417
1418 // If we have -tailcallopt, we need to adjust the stack. We'll do the call
1419 // sequence start and end here.
1420 if (!IsSibCall) {
1421 MIB->getOperand(CalleeIdx + 1).setImm(FPDiff);
1422 CallSeqStart.addImm(NumBytes).addImm(0);
1423 // End the call sequence *before* emitting the call. Normally, we would
1424 // tidy the frame up after the call. However, here, we've laid out the
1425 // parameters so that when SP is reset, they will be in the correct
1426 // location.
1427 MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKDOWN).addImm(NumBytes).addImm(0);
1428 }
1429
1430 // Now we can add the actual call instruction to the correct basic block.
1431 MIRBuilder.insertInstr(MIB);
1432
1433 // If this is a whole wave tail call, we need to constrain the register for
1434 // the original EXEC.
1435 if (MIB->getOpcode() == AMDGPU::SI_TCRETURN_GFX_WholeWave) {
1436 MIB->getOperand(0).setReg(
1437 constrainOperandRegClass(MF, *TRI, MRI, *TII, *ST.getRegBankInfo(),
1438 *MIB, MIB->getDesc(), MIB->getOperand(0), 0));
1439 }
1440
1441 // If Callee is a reg, since it is used by a target specific
1442 // instruction, it must have a register class matching the
1443 // constraint of that instruction.
1444
1445 // FIXME: We should define regbankselectable call instructions to handle
1446 // divergent call targets.
1447 if (MIB->getOperand(CalleeIdx).isReg()) {
1448 MIB->getOperand(CalleeIdx).setReg(constrainOperandRegClass(
1449 MF, *TRI, MRI, *TII, *ST.getRegBankInfo(), *MIB, MIB->getDesc(),
1450 MIB->getOperand(CalleeIdx), CalleeIdx));
1451 }
1452
1454 Info.LoweredTailCall = true;
1455 return true;
1456}
1457
1458/// Lower a call to the @llvm.amdgcn.cs.chain intrinsic.
1460 CallLoweringInfo &Info) const {
1461 ArgInfo Callee = Info.OrigArgs[0];
1462 ArgInfo SGPRArgs = Info.OrigArgs[2];
1463 ArgInfo VGPRArgs = Info.OrigArgs[3];
1464
1465 MachineFunction &MF = MIRBuilder.getMF();
1466 const Function &F = MF.getFunction();
1467 const DataLayout &DL = F.getDataLayout();
1468
1469 // The function to jump to is actually the first argument, so we'll change the
1470 // Callee and other info to match that before using our existing helper.
1471 const Value *CalleeV = Callee.OrigValue->stripPointerCasts();
1472 if (const Function *F = dyn_cast<Function>(CalleeV)) {
1473 Info.Callee = MachineOperand::CreateGA(F, 0);
1474 Info.CallConv = F->getCallingConv();
1475 } else {
1476 assert(Callee.Regs.size() == 1 && "Too many regs for the callee");
1477 Info.Callee = MachineOperand::CreateReg(Callee.Regs[0], false);
1478 Info.CallConv = CallingConv::AMDGPU_CS_Chain; // amdgpu_cs_chain_preserve
1479 // behaves the same here.
1480 }
1481
1482 // The function that we're calling cannot be vararg (only the intrinsic is).
1483 Info.IsVarArg = false;
1484
1485 assert(
1486 all_of(SGPRArgs.Flags, [](ISD::ArgFlagsTy F) { return F.isInReg(); }) &&
1487 "SGPR arguments should be marked inreg");
1488 assert(
1489 none_of(VGPRArgs.Flags, [](ISD::ArgFlagsTy F) { return F.isInReg(); }) &&
1490 "VGPR arguments should not be marked inreg");
1491
1493 splitToValueTypes(SGPRArgs, OutArgs, DL, Info.CallConv);
1494 splitToValueTypes(VGPRArgs, OutArgs, DL, Info.CallConv);
1495
1496 Info.IsMustTailCall = true;
1497 return lowerTailCall(MIRBuilder, Info, OutArgs);
1498}
1499
1501 CallLoweringInfo &Info) const {
1502 if (Function *F = Info.CB->getCalledFunction())
1503 if (F->isIntrinsic()) {
1504 switch (F->getIntrinsicID()) {
1505 case Intrinsic::amdgcn_cs_chain:
1506 return lowerChainCall(MIRBuilder, Info);
1507 case Intrinsic::amdgcn_call_whole_wave:
1508 Info.CallConv = CallingConv::AMDGPU_Gfx_WholeWave;
1509
1510 // Get the callee from the original instruction, so it doesn't look like
1511 // this is an indirect call.
1512 Info.Callee = MachineOperand::CreateGA(
1513 cast<GlobalValue>(Info.CB->getOperand(0)), /*Offset=*/0);
1514 Info.OrigArgs.erase(Info.OrigArgs.begin());
1515 Info.IsVarArg = false;
1516 break;
1517 default:
1518 llvm_unreachable("Unexpected intrinsic call");
1519 }
1520 }
1521
1522 if (Info.IsVarArg) {
1523 LLVM_DEBUG(dbgs() << "Variadic functions not implemented\n");
1524 return false;
1525 }
1526
1527 MachineFunction &MF = MIRBuilder.getMF();
1528 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1529 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1530
1531 const Function &F = MF.getFunction();
1534 const DataLayout &DL = F.getDataLayout();
1535
1537 for (auto &OrigArg : Info.OrigArgs)
1538 splitToValueTypes(OrigArg, OutArgs, DL, Info.CallConv);
1539
1541 if (Info.CanLowerReturn && !Info.OrigRet.Ty->isVoidTy())
1542 splitToValueTypes(Info.OrigRet, InArgs, DL, Info.CallConv);
1543
1544 // If we can lower as a tail call, do that instead.
1545 bool CanTailCallOpt =
1546 isEligibleForTailCallOptimization(MIRBuilder, Info, InArgs, OutArgs);
1547
1548 // We must emit a tail call if we have musttail.
1549 if (Info.IsMustTailCall && !CanTailCallOpt) {
1550 LLVM_DEBUG(dbgs() << "Failed to lower musttail call as tail call\n");
1551 return false;
1552 }
1553
1554 Info.IsTailCall = CanTailCallOpt;
1555 if (CanTailCallOpt)
1556 return lowerTailCall(MIRBuilder, Info, OutArgs);
1557
1558 // Find out which ABI gets to decide where things go.
1559 CCAssignFn *AssignFnFixed;
1560 CCAssignFn *AssignFnVarArg;
1561 std::tie(AssignFnFixed, AssignFnVarArg) =
1562 getAssignFnsForCC(Info.CallConv, TLI);
1563
1564 MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKUP)
1565 .addImm(0)
1566 .addImm(0);
1567
1568 // Create a temporarily-floating call instruction so we can add the implicit
1569 // uses of arg registers.
1570 unsigned Opc = getCallOpcode(MF, Info.Callee.isReg(), false, ST.isWave32(),
1571 Info.CallConv);
1572
1573 auto MIB = MIRBuilder.buildInstrNoInsert(Opc);
1574 MIB.addDef(TRI->getReturnAddressReg(MF));
1575
1576 if (!Info.IsConvergent)
1578
1579 if (!addCallTargetOperands(MIB, MIRBuilder, Info))
1580 return false;
1581
1582 // Tell the call which registers are clobbered.
1583 const uint32_t *Mask = TRI->getCallPreservedMask(MF, Info.CallConv);
1584 MIB.addRegMask(Mask);
1585
1587 CCState CCInfo(Info.CallConv, Info.IsVarArg, MF, ArgLocs, F.getContext());
1588
1589 // We could pass MIB and directly add the implicit uses to the call
1590 // now. However, as an aesthetic choice, place implicit argument operands
1591 // after the ordinary user argument registers.
1593
1594 if (Info.CallConv != CallingConv::AMDGPU_Gfx &&
1595 Info.CallConv != CallingConv::AMDGPU_Gfx_WholeWave) {
1596 // With a fixed ABI, allocate fixed registers before user arguments.
1597 if (!passSpecialInputs(MIRBuilder, CCInfo, ImplicitArgRegs, Info))
1598 return false;
1599 }
1600
1601 // Do the actual argument marshalling.
1602 OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg);
1603 if (!determineAssignments(Assigner, OutArgs, CCInfo))
1604 return false;
1605
1606 AMDGPUOutgoingArgHandler Handler(MIRBuilder, MRI, MIB, false);
1607 if (!handleAssignments(Handler, OutArgs, CCInfo, ArgLocs, MIRBuilder))
1608 return false;
1609
1611
1612 if (Info.ConvergenceCtrlToken) {
1613 MIB.addUse(Info.ConvergenceCtrlToken, RegState::Implicit);
1614 }
1615 handleImplicitCallArguments(MIRBuilder, MIB, ST, *MFI, Info.CallConv,
1616 ImplicitArgRegs);
1617
1618 // Get a count of how many bytes are to be pushed on the stack.
1619 unsigned NumBytes = CCInfo.getStackSize();
1620
1621 // If Callee is a reg, since it is used by a target specific
1622 // instruction, it must have a register class matching the
1623 // constraint of that instruction.
1624
1625 // FIXME: We should define regbankselectable call instructions to handle
1626 // divergent call targets.
1627 if (MIB->getOperand(1).isReg()) {
1628 MIB->getOperand(1).setReg(constrainOperandRegClass(
1629 MF, *TRI, MRI, *ST.getInstrInfo(),
1630 *ST.getRegBankInfo(), *MIB, MIB->getDesc(), MIB->getOperand(1),
1631 1));
1632 }
1633
1634 // Now we can add the actual call instruction to the correct position.
1635 MIRBuilder.insertInstr(MIB);
1636
1637 // Finally we can copy the returned value back into its virtual-register. In
1638 // symmetry with the arguments, the physical register must be an
1639 // implicit-define of the call instruction.
1640 if (Info.CanLowerReturn && !Info.OrigRet.Ty->isVoidTy()) {
1641 CCAssignFn *RetAssignFn = TLI.CCAssignFnForReturn(Info.CallConv,
1642 Info.IsVarArg);
1643 IncomingValueAssigner Assigner(RetAssignFn);
1644 CallReturnHandler Handler(MIRBuilder, MRI, MIB);
1645 if (!determineAndHandleAssignments(Handler, Assigner, InArgs, MIRBuilder,
1646 Info.CallConv, Info.IsVarArg))
1647 return false;
1648 }
1649
1650 uint64_t CalleePopBytes = NumBytes;
1651
1652 MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKDOWN)
1653 .addImm(0)
1654 .addImm(CalleePopBytes);
1655
1656 if (!Info.CanLowerReturn) {
1657 insertSRetLoads(MIRBuilder, Info.OrigRet.Ty, Info.OrigRet.Regs,
1658 Info.DemoteRegister, Info.DemoteStackIndex);
1659 }
1660
1661 return true;
1662}
1663
1664void AMDGPUCallLowering::addOriginalExecToReturn(
1665 MachineFunction &MF, MachineInstrBuilder &Ret) const {
1666 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1667 const SIInstrInfo *TII = ST.getInstrInfo();
1668 const MachineInstr *Setup = TII->getWholeWaveFunctionSetup(MF);
1669 Ret.addReg(Setup->getOperand(0).getReg());
1670}
unsigned const MachineRegisterInfo * MRI
static unsigned getCallOpcode(const MachineFunction &CallerF, bool IsIndirect, bool IsTailCall, std::optional< CallLowering::PtrAuthInfo > &PAI, MachineRegisterInfo &MRI)
static std::pair< CCAssignFn *, CCAssignFn * > getAssignFnsForCC(CallingConv::ID CC, const AArch64TargetLowering &TLI)
Returns a pair containing the fixed CCAssignFn and the vararg CCAssignFn for CC.
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const TargetInstrInfo & TII
static ISD::NodeType extOpcodeToISDExtOpcode(unsigned MIOpc)
static void allocateHSAUserSGPRs(CCState &CCInfo, MachineIRBuilder &B, MachineFunction &MF, const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info)
static bool addCallTargetOperands(MachineInstrBuilder &CallInst, MachineIRBuilder &MIRBuilder, AMDGPUCallLowering::CallLoweringInfo &Info, bool IsDynamicVGPRChainCall=false)
This file describes how to lower LLVM calls to machine code calls.
constexpr LLT S32
This file declares the targeting of the Machinelegalizer class for AMDGPU.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file declares the MachineIRBuilder class.
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static constexpr MCPhysReg SPReg
Interface definition for SIRegisterInfo.
#define LLVM_DEBUG(...)
Definition Debug.h:114
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static const AMDGPUFunctionArgInfo FixedABIFunctionInfo
bool lowerTailCall(MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info, SmallVectorImpl< ArgInfo > &OutArgs) const
bool isEligibleForTailCallOptimization(MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info, SmallVectorImpl< ArgInfo > &InArgs, SmallVectorImpl< ArgInfo > &OutArgs) const
Returns true if the call can be lowered as a tail call.
bool lowerFormalArgumentsKernel(MachineIRBuilder &B, const Function &F, ArrayRef< ArrayRef< Register > > VRegs) const
bool lowerReturn(MachineIRBuilder &B, const Value *Val, ArrayRef< Register > VRegs, FunctionLoweringInfo &FLI) const override
This hook behaves as the extended lowerReturn function, but for targets that do not support swifterro...
void handleImplicitCallArguments(MachineIRBuilder &MIRBuilder, MachineInstrBuilder &CallInst, const GCNSubtarget &ST, const SIMachineFunctionInfo &MFI, CallingConv::ID CalleeCC, ArrayRef< std::pair< MCRegister, Register > > ImplicitArgRegs) const
bool areCalleeOutgoingArgsTailCallable(CallLoweringInfo &Info, MachineFunction &MF, SmallVectorImpl< ArgInfo > &OutArgs) const
bool lowerChainCall(MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info) const
Lower a call to the @llvm.amdgcn.cs.chain intrinsic.
AMDGPUCallLowering(const AMDGPUTargetLowering &TLI)
bool passSpecialInputs(MachineIRBuilder &MIRBuilder, CCState &CCInfo, SmallVectorImpl< std::pair< MCRegister, Register > > &ArgRegs, CallLoweringInfo &Info) const
bool lowerFormalArguments(MachineIRBuilder &B, const Function &F, ArrayRef< ArrayRef< Register > > VRegs, FunctionLoweringInfo &FLI) const override
This hook must be implemented to lower the incoming (formal) arguments, described by VRegs,...
bool lowerCall(MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info) const override
This hook must be implemented to lower the given call instruction, including argument and return valu...
bool doCallerAndCalleePassArgsTheSameWay(CallLoweringInfo &Info, MachineFunction &MF, SmallVectorImpl< ArgInfo > &InArgs) const
static std::optional< uint32_t > getLDSKernelIdMetadata(const Function &F)
unsigned getExplicitKernelArgOffset() const
Returns the offset in bytes from the start of the input buffer of the first explicit kernel argument.
static CCAssignFn * CCAssignFnForCall(CallingConv::ID CC, bool IsVarArg)
Selects the correct CCAssignFn for a given CallingConvention value.
Class for arbitrary precision integers.
Definition APInt.h:78
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
bool isOneBitSet(unsigned BitNo) const
Determine if this APInt Value only has the specified bit set.
Definition APInt.h:367
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
CCState - This class holds information needed while lowering arguments and return values.
unsigned getFirstUnallocated(ArrayRef< MCPhysReg > Regs) const
getFirstUnallocated - Return the index of the first unallocated register in the set,...
MCRegister AllocateReg(MCPhysReg Reg)
AllocateReg - Attempt to allocate one register.
uint64_t getStackSize() const
Returns the size of the currently allocated portion of the stack.
CCValAssign - Represent assignment of one arg/retval to a location.
LocInfo getLocInfo() const
int64_t getLocMemOffset() const
This class represents a function call, abstracting a target machine's calling convention.
void insertSRetLoads(MachineIRBuilder &MIRBuilder, Type *RetTy, ArrayRef< Register > VRegs, Register DemoteReg, int FI) const
Load the returned value from the stack into virtual registers in VRegs.
bool handleAssignments(ValueHandler &Handler, SmallVectorImpl< ArgInfo > &Args, CCState &CCState, SmallVectorImpl< CCValAssign > &ArgLocs, MachineIRBuilder &MIRBuilder, ArrayRef< Register > ThisReturnRegs={}) const
Use Handler to insert code to handle the argument/return values represented by Args.
bool resultsCompatible(CallLoweringInfo &Info, MachineFunction &MF, SmallVectorImpl< ArgInfo > &InArgs, ValueAssigner &CalleeAssigner, ValueAssigner &CallerAssigner) const
void splitToValueTypes(const ArgInfo &OrigArgInfo, SmallVectorImpl< ArgInfo > &SplitArgs, const DataLayout &DL, CallingConv::ID CallConv, SmallVectorImpl< uint64_t > *Offsets=nullptr) const
Break OrigArgInfo into one or more pieces the calling convention can process, returned in SplitArgs.
void insertSRetIncomingArgument(const Function &F, SmallVectorImpl< ArgInfo > &SplitArgs, Register &DemoteReg, MachineRegisterInfo &MRI, const DataLayout &DL) const
Insert the hidden sret ArgInfo to the beginning of SplitArgs.
bool determineAndHandleAssignments(ValueHandler &Handler, ValueAssigner &Assigner, SmallVectorImpl< ArgInfo > &Args, MachineIRBuilder &MIRBuilder, CallingConv::ID CallConv, bool IsVarArg, ArrayRef< Register > ThisReturnRegs={}) const
Invoke ValueAssigner::assignArg on each of the given Args and then use Handler to move them to the as...
void insertSRetStores(MachineIRBuilder &MIRBuilder, Type *RetTy, ArrayRef< Register > VRegs, Register DemoteReg) const
Store the return value given by VRegs into stack starting at the offset specified in DemoteReg.
bool parametersInCSRMatch(const MachineRegisterInfo &MRI, const uint32_t *CallerPreservedMask, const SmallVectorImpl< CCValAssign > &ArgLocs, const SmallVectorImpl< ArgInfo > &OutVals) const
Check whether parameters to a call that are passed in callee saved registers are the same as from the...
bool determineAssignments(ValueAssigner &Assigner, SmallVectorImpl< ArgInfo > &Args, CCState &CCInfo) const
Analyze the argument list in Args, using Assigner to populate CCInfo.
bool checkReturn(CCState &CCInfo, SmallVectorImpl< BaseArgInfo > &Outs, CCAssignFn *Fn) const
CallLowering(const TargetLowering *TLI)
const TargetLowering * getTLI() const
Getter for generic TargetLowering class.
void setArgFlags(ArgInfo &Arg, unsigned OpIdx, const DataLayout &DL, const FuncInfoTy &FuncInfo) const
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
Diagnostic information for unsupported feature in backend.
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
Register DemoteRegister
DemoteRegister - if CanLowerReturn is false, DemoteRegister is a vreg allocated to hold a pointer to ...
bool CanLowerReturn
CanLowerReturn - true iff the function's return value can be lowered to registers.
iterator_range< arg_iterator > args()
Definition Function.h:890
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:270
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:359
const SIRegisterInfo * getRegisterInfo() const override
bool hasPrivateSegmentBuffer() const
unsigned getAddressSpace() const
constexpr unsigned getScalarSizeInBits() const
static constexpr LLT vector(ElementCount EC, unsigned ScalarSizeInBits)
Get a low-level vector of some number of elements and element width.
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
constexpr bool isVector() const
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
constexpr ElementCount getElementCount() const
static constexpr LLT fixed_vector(unsigned NumElements, unsigned ScalarSizeInBits)
Get a low-level fixed-width vector of some number of elements and element width.
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
void setHasTailCall(bool V=true)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy, Align base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Helper class to build MachineInstr.
MachineInstrBuilder insertInstr(MachineInstrBuilder MIB)
Insert an existing instruction at the insertion point.
MachineInstrBuilder buildGlobalValue(const DstOp &Res, const GlobalValue *GV)
Build and insert Res = G_GLOBAL_VALUE GV.
MachineInstrBuilder buildUndef(const DstOp &Res)
Build and insert Res = IMPLICIT_DEF.
MachineInstrBuilder buildPtrAdd(const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_PTR_ADD Op0, Op1.
MachineInstrBuilder buildShl(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
MachineInstrBuilder buildStore(const SrcOp &Val, const SrcOp &Addr, MachineMemOperand &MMO)
Build and insert G_STORE Val, Addr, MMO.
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
MachineInstrBuilder buildFrameIndex(const DstOp &Res, int Idx)
Build and insert Res = G_FRAME_INDEX Idx.
MachineFunction & getMF()
Getter for the function we currently build.
MachineInstrBuilder buildAnyExt(const DstOp &Res, const SrcOp &Op)
Build and insert Res = G_ANYEXT Op0.
MachineInstrBuilder buildOr(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_OR Op0, Op1.
MachineInstrBuilder buildInstrNoInsert(unsigned Opcode)
Build but don't insert <empty> = Opcode <empty>.
MachineInstrBuilder buildCopy(const DstOp &Res, const SrcOp &Op)
Build and insert Res = COPY Op.
virtual MachineInstrBuilder buildConstant(const DstOp &Res, const ConstantInt &Val)
Build and insert Res = G_CONSTANT Val.
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addUse(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
static MachineOperand CreateGA(const GlobalValue *GV, int64_t Offset, unsigned TargetFlags=0)
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
Register getScratchRSrcReg() const
Returns the physical register reserved for use as the resource descriptor for scratch accesses.
MCRegister getPreloadedReg(AMDGPUFunctionArgInfo::PreloadedValue Value) const
AMDGPUFunctionArgInfo & getArgInfo()
MachinePointerInfo getKernargSegmentPtrInfo(MachineFunction &MF) const
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:854
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
TargetOptions Options
unsigned GuaranteedTailCallOpt
GuaranteedTailCallOpt - This flag is enabled when -tailcallopt is specified on the commandline.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ CONSTANT_ADDRESS
Address space for constant memory (VTX2).
@ PRIVATE_ADDRESS
Address space for private memory.
LLVM_READNONE constexpr bool isShader(CallingConv::ID CC)
LLVM_READNONE constexpr bool mayTailCallThisCC(CallingConv::ID CC)
Return true if we might ever do TCO for calls with this calling convention.
LLVM_READNONE constexpr bool isKernel(CallingConv::ID CC)
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
LLVM_READNONE constexpr bool isChainCC(CallingConv::ID CC)
LLVM_READNONE constexpr bool canGuaranteeTCO(CallingConv::ID CC)
LLVM_READNONE constexpr bool isGraphics(CallingConv::ID CC)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:41
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:841
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:832
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:838
@ Implicit
Not emitted register (e.g. carry, or temporary result).
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:532
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1737
LLVM_ABI Register constrainOperandRegClass(const MachineFunction &MF, const TargetRegisterInfo &TRI, MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const RegisterBankInfo &RBI, MachineInstr &InsertPt, const TargetRegisterClass &RegClass, MachineOperand &RegMO)
Constrain the Register operand OpIdx, so that it is now constrained to the TargetRegisterClass passed...
Definition Utils.cpp:56
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1667
void ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL, Type *Ty, SmallVectorImpl< EVT > &ValueVTs, SmallVectorImpl< EVT > *MemVTs=nullptr, SmallVectorImpl< TypeSize > *Offsets=nullptr, TypeSize StartingOffset=TypeSize::getZero())
ComputeValueVTs - Given an LLVM IR type, compute a sequence of EVTs that represent all the individual...
Definition Analysis.cpp:119
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool CCAssignFn(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
CCAssignFn - This function assigns a location for Val, updating State to reflect the change.
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:134
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:202
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1744
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1751
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:167
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
LLVM_ABI LLT getLLTForType(Type &Ty, const DataLayout &DL)
Construct a low-level type based on an LLVM type.
LLVM_ABI Align inferAlignFromPtrInfo(MachineFunction &MF, const MachinePointerInfo &MPO)
Definition Utils.cpp:903
std::tuple< const ArgDescriptor *, const TargetRegisterClass *, LLT > getPreloadedValue(PreloadedValue Value) const
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
MCRegister getRegister() const
static ArgDescriptor createArg(const ArgDescriptor &Arg, unsigned Mask)
Helper struct shared between Function Specialization and SCCP Solver.
Definition SCCPSolver.h:42
const Value * OrigValue
Optionally track the original IR value for the argument.
SmallVector< Register, 4 > Regs
SmallVector< ISD::ArgFlagsTy, 4 > Flags
Base class for ValueHandlers used for arguments coming into the current function, or for return value...
Base class for ValueHandlers used for arguments passed to a function call, or for return values.
uint64_t StackSize
The size of the currently allocated portion of the stack.
Register extendRegister(Register ValReg, const CCValAssign &VA, unsigned MaxSizeBits=0)
Extend a register to the location type given in VA, capped at extending to at most MaxSize bits.
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:157
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106