LLVM 22.0.0git
SPIRVCallLowering.cpp
Go to the documentation of this file.
1//===--- SPIRVCallLowering.cpp - Call lowering ------------------*- C++ -*-===//
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// This file implements the lowering of LLVM calls to machine code calls for
10// GlobalISel.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SPIRVCallLowering.h"
16#include "SPIRV.h"
17#include "SPIRVBuiltins.h"
18#include "SPIRVGlobalRegistry.h"
19#include "SPIRVISelLowering.h"
20#include "SPIRVMetadata.h"
21#include "SPIRVRegisterInfo.h"
22#include "SPIRVSubtarget.h"
23#include "SPIRVUtils.h"
26#include "llvm/IR/IntrinsicsSPIRV.h"
27#include "llvm/Support/ModRef.h"
28
29using namespace llvm;
30
34
36 const Value *Val, ArrayRef<Register> VRegs,
38 Register SwiftErrorVReg) const {
39 // Ignore if called from the internal service function
40 if (MIRBuilder.getMF()
43 .isValid())
44 return true;
45
46 // Maybe run postponed production of types for function pointers
47 if (IndirectCalls.size() > 0) {
48 produceIndirectPtrTypes(MIRBuilder);
49 IndirectCalls.clear();
50 }
51
52 // Currently all return types should use a single register.
53 // TODO: handle the case of multiple registers.
54 if (VRegs.size() > 1)
55 return false;
56 if (Val) {
57 const auto &STI = MIRBuilder.getMF().getSubtarget();
58 return MIRBuilder.buildInstr(SPIRV::OpReturnValue)
59 .addUse(VRegs[0])
60 .constrainAllUses(MIRBuilder.getTII(), *STI.getRegisterInfo(),
61 *STI.getRegBankInfo());
62 }
63 MIRBuilder.buildInstr(SPIRV::OpReturn);
64 return true;
65}
66
67// Based on the LLVM function attributes, get a SPIR-V FunctionControl.
69 const SPIRVSubtarget *ST) {
70 MemoryEffects MemEffects = F.getMemoryEffects();
71
72 uint32_t FuncControl = static_cast<uint32_t>(SPIRV::FunctionControl::None);
73
74 if (F.hasFnAttribute(Attribute::AttrKind::NoInline))
75 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::DontInline);
76 else if (F.hasFnAttribute(Attribute::AttrKind::AlwaysInline))
77 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::Inline);
78
79 if (MemEffects.doesNotAccessMemory())
80 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::Pure);
81 else if (MemEffects.onlyReadsMemory())
82 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::Const);
83
84 if (ST->canUseExtension(SPIRV::Extension::SPV_INTEL_optnone) ||
85 ST->canUseExtension(SPIRV::Extension::SPV_EXT_optnone))
86 if (F.hasFnAttribute(Attribute::OptimizeNone))
87 FuncControl |= static_cast<uint32_t>(SPIRV::FunctionControl::OptNoneEXT);
88
89 return FuncControl;
90}
91
92static ConstantInt *getConstInt(MDNode *MD, unsigned NumOp) {
93 if (MD->getNumOperands() > NumOp) {
94 auto *CMeta = dyn_cast<ConstantAsMetadata>(MD->getOperand(NumOp));
95 if (CMeta)
96 return dyn_cast<ConstantInt>(CMeta->getValue());
97 }
98 return nullptr;
99}
100
101// If the function has pointer arguments, we are forced to re-create this
102// function type from the very beginning, changing PointerType by
103// TypedPointerType for each pointer argument. Otherwise, the same `Type*`
104// potentially corresponds to different SPIR-V function type, effectively
105// invalidating logic behind global registry and duplicates tracker.
106static FunctionType *
108 FunctionType *FTy, const SPIRVType *SRetTy,
109 const SmallVector<SPIRVType *, 4> &SArgTys) {
110 bool hasArgPtrs = false;
111 for (auto &Arg : F.args()) {
112 // check if it's an instance of a non-typed PointerType
113 if (Arg.getType()->isPointerTy()) {
114 hasArgPtrs = true;
115 break;
116 }
117 }
118 if (!hasArgPtrs) {
119 Type *RetTy = FTy->getReturnType();
120 // check if it's an instance of a non-typed PointerType
121 if (!RetTy->isPointerTy())
122 return FTy;
123 }
124
125 // re-create function type, using TypedPointerType instead of PointerType to
126 // properly trace argument types
127 const Type *RetTy = GR->getTypeForSPIRVType(SRetTy);
129 for (auto SArgTy : SArgTys)
130 ArgTys.push_back(const_cast<Type *>(GR->getTypeForSPIRVType(SArgTy)));
131 return FunctionType::get(const_cast<Type *>(RetTy), ArgTys, false);
132}
133
134static SPIRV::AccessQualifier::AccessQualifier
135getArgAccessQual(const Function &F, unsigned ArgIdx) {
136 if (F.getCallingConv() != CallingConv::SPIR_KERNEL)
137 return SPIRV::AccessQualifier::ReadWrite;
138
139 MDString *ArgAttribute = getOCLKernelArgAccessQual(F, ArgIdx);
140 if (!ArgAttribute)
141 return SPIRV::AccessQualifier::ReadWrite;
142
143 if (ArgAttribute->getString() == "read_only")
144 return SPIRV::AccessQualifier::ReadOnly;
145 if (ArgAttribute->getString() == "write_only")
146 return SPIRV::AccessQualifier::WriteOnly;
147 return SPIRV::AccessQualifier::ReadWrite;
148}
149
150static std::vector<SPIRV::Decoration::Decoration>
151getKernelArgTypeQual(const Function &F, unsigned ArgIdx) {
152 MDString *ArgAttribute = getOCLKernelArgTypeQual(F, ArgIdx);
153 if (ArgAttribute && ArgAttribute->getString() == "volatile")
154 return {SPIRV::Decoration::Volatile};
155 return {};
156}
157
158static SPIRVType *getArgSPIRVType(const Function &F, unsigned ArgIdx,
160 MachineIRBuilder &MIRBuilder,
161 const SPIRVSubtarget &ST) {
162 // Read argument's access qualifier from metadata or default.
163 SPIRV::AccessQualifier::AccessQualifier ArgAccessQual =
164 getArgAccessQual(F, ArgIdx);
165
166 Type *OriginalArgType =
168
169 // If OriginalArgType is non-pointer, use the OriginalArgType (the type cannot
170 // be legally reassigned later).
171 if (!isPointerTy(OriginalArgType))
172 return GR->getOrCreateSPIRVType(OriginalArgType, MIRBuilder, ArgAccessQual,
173 true);
174
175 Argument *Arg = F.getArg(ArgIdx);
176 Type *ArgType = Arg->getType();
177 if (isTypedPointerTy(ArgType)) {
179 cast<TypedPointerType>(ArgType)->getElementType(), MIRBuilder,
181 }
182
183 // In case OriginalArgType is of untyped pointer type, there are three
184 // possibilities:
185 // 1) This is a pointer of an LLVM IR element type, passed byval/byref.
186 // 2) This is an OpenCL/SPIR-V builtin type if there is spv_assign_type
187 // intrinsic assigning a TargetExtType.
188 // 3) This is a pointer, try to retrieve pointer element type from a
189 // spv_assign_ptr_type intrinsic or otherwise use default pointer element
190 // type.
191 if (hasPointeeTypeAttr(Arg)) {
193 getPointeeTypeByAttr(Arg), MIRBuilder,
195 }
196
197 for (auto User : Arg->users()) {
199 // Check if this is spv_assign_type assigning OpenCL/SPIR-V builtin type.
200 if (II && II->getIntrinsicID() == Intrinsic::spv_assign_type) {
201 MetadataAsValue *VMD = cast<MetadataAsValue>(II->getOperand(1));
202 Type *BuiltinType =
203 cast<ConstantAsMetadata>(VMD->getMetadata())->getType();
204 assert(BuiltinType->isTargetExtTy() && "Expected TargetExtType");
205 return GR->getOrCreateSPIRVType(BuiltinType, MIRBuilder, ArgAccessQual,
206 true);
207 }
208
209 // Check if this is spv_assign_ptr_type assigning pointer element type.
210 if (!II || II->getIntrinsicID() != Intrinsic::spv_assign_ptr_type)
211 continue;
212
213 MetadataAsValue *VMD = cast<MetadataAsValue>(II->getOperand(1));
214 Type *ElementTy =
217 ElementTy, MIRBuilder,
219 cast<ConstantInt>(II->getOperand(2))->getZExtValue(), ST));
220 }
221
222 // Replace PointerType with TypedPointerType to be able to map SPIR-V types to
223 // LLVM types in a consistent manner
224 return GR->getOrCreateSPIRVType(toTypedPointer(OriginalArgType), MIRBuilder,
225 ArgAccessQual, true);
226}
227
228static SPIRV::ExecutionModel::ExecutionModel
230 if (STI.isKernel())
231 return SPIRV::ExecutionModel::Kernel;
232
233 if (STI.isShader()) {
234 auto attribute = F.getFnAttribute("hlsl.shader");
235 if (!attribute.isValid()) {
237 "This entry point lacks mandatory hlsl.shader attribute.");
238 }
239
240 const auto value = attribute.getValueAsString();
241 if (value == "compute")
242 return SPIRV::ExecutionModel::GLCompute;
243 if (value == "vertex")
244 return SPIRV::ExecutionModel::Vertex;
245 if (value == "pixel")
246 return SPIRV::ExecutionModel::Fragment;
247
249 "This HLSL entry point is not supported by this backend.");
250 }
251
253 // "hlsl.shader" attribute is mandatory for Vulkan, so we can set Env to
254 // Shader whenever we find it, and to Kernel otherwise.
255
256 // We will now change the Env based on the attribute, so we need to strip
257 // `const` out of the ref to STI.
258 SPIRVSubtarget *NonConstSTI = const_cast<SPIRVSubtarget *>(&STI);
259 auto attribute = F.getFnAttribute("hlsl.shader");
260 if (!attribute.isValid()) {
261 NonConstSTI->setEnv(SPIRVSubtarget::Kernel);
262 return SPIRV::ExecutionModel::Kernel;
263 }
264 NonConstSTI->setEnv(SPIRVSubtarget::Shader);
265
266 const auto value = attribute.getValueAsString();
267 if (value == "compute")
268 return SPIRV::ExecutionModel::GLCompute;
269 if (value == "vertex")
270 return SPIRV::ExecutionModel::Vertex;
271 if (value == "pixel")
272 return SPIRV::ExecutionModel::Fragment;
273
274 report_fatal_error("This HLSL entry point is not supported by this backend.");
275}
276
278 const Function &F,
280 FunctionLoweringInfo &FLI) const {
281 // Discard the internal service function
282 if (F.getFnAttribute(SPIRV_BACKEND_SERVICE_FUN_NAME).isValid())
283 return true;
284
285 assert(GR && "Must initialize the SPIRV type registry before lowering args.");
286 GR->setCurrentFunc(MIRBuilder.getMF());
287
288 // Get access to information about available extensions
289 const SPIRVSubtarget *ST =
290 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
291
292 // Assign types and names to all args, and store their types for later.
293 SmallVector<SPIRVType *, 4> ArgTypeVRegs;
294 if (VRegs.size() > 0) {
295 unsigned i = 0;
296 for (const auto &Arg : F.args()) {
297 // Currently formal args should use single registers.
298 // TODO: handle the case of multiple registers.
299 if (VRegs[i].size() > 1)
300 return false;
301 auto *SpirvTy = getArgSPIRVType(F, i, GR, MIRBuilder, *ST);
302 GR->assignSPIRVTypeToVReg(SpirvTy, VRegs[i][0], MIRBuilder.getMF());
303 ArgTypeVRegs.push_back(SpirvTy);
304
305 if (Arg.hasName())
306 buildOpName(VRegs[i][0], Arg.getName(), MIRBuilder);
307 if (isPointerTyOrWrapper(Arg.getType())) {
308 auto DerefBytes = static_cast<unsigned>(Arg.getDereferenceableBytes());
309 if (DerefBytes != 0)
310 buildOpDecorate(VRegs[i][0], MIRBuilder,
311 SPIRV::Decoration::MaxByteOffset, {DerefBytes});
312 }
313 if (Arg.hasAttribute(Attribute::Alignment) && !ST->isShader()) {
314 auto Alignment = static_cast<unsigned>(
315 Arg.getAttribute(Attribute::Alignment).getValueAsInt());
316 buildOpDecorate(VRegs[i][0], MIRBuilder, SPIRV::Decoration::Alignment,
317 {Alignment});
318 }
319 if (Arg.hasAttribute(Attribute::ReadOnly)) {
320 auto Attr =
321 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::NoWrite);
322 buildOpDecorate(VRegs[i][0], MIRBuilder,
323 SPIRV::Decoration::FuncParamAttr, {Attr});
324 }
325 if (Arg.hasAttribute(Attribute::ZExt)) {
326 auto Attr =
327 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Zext);
328 buildOpDecorate(VRegs[i][0], MIRBuilder,
329 SPIRV::Decoration::FuncParamAttr, {Attr});
330 }
331 if (Arg.hasAttribute(Attribute::NoAlias)) {
332 auto Attr =
333 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::NoAlias);
334 buildOpDecorate(VRegs[i][0], MIRBuilder,
335 SPIRV::Decoration::FuncParamAttr, {Attr});
336 }
337 // TODO: the AMDGPU BE only supports ByRef argument passing, thus for
338 // AMDGCN flavoured SPIRV we CodeGen for ByRef, but lower it to
339 // ByVal, handling the impedance mismatch during reverse
340 // translation from SPIRV to LLVM IR; the vendor check should be
341 // removed once / if SPIRV adds ByRef support.
342 if (Arg.hasAttribute(Attribute::ByVal) ||
343 (Arg.hasAttribute(Attribute::ByRef) &&
344 F.getParent()->getTargetTriple().getVendor() ==
346 auto Attr =
347 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::ByVal);
348 buildOpDecorate(VRegs[i][0], MIRBuilder,
349 SPIRV::Decoration::FuncParamAttr, {Attr});
350 }
351 if (Arg.hasAttribute(Attribute::StructRet)) {
352 auto Attr =
353 static_cast<unsigned>(SPIRV::FunctionParameterAttribute::Sret);
354 buildOpDecorate(VRegs[i][0], MIRBuilder,
355 SPIRV::Decoration::FuncParamAttr, {Attr});
356 }
357
358 if (F.getCallingConv() == CallingConv::SPIR_KERNEL) {
359 std::vector<SPIRV::Decoration::Decoration> ArgTypeQualDecs =
361 for (SPIRV::Decoration::Decoration Decoration : ArgTypeQualDecs)
362 buildOpDecorate(VRegs[i][0], MIRBuilder, Decoration, {});
363 }
364
365 MDNode *Node = F.getMetadata("spirv.ParameterDecorations");
366 if (Node && i < Node->getNumOperands() &&
367 isa<MDNode>(Node->getOperand(i))) {
368 MDNode *MD = cast<MDNode>(Node->getOperand(i));
369 for (const MDOperand &MDOp : MD->operands()) {
370 MDNode *MD2 = dyn_cast<MDNode>(MDOp);
371 assert(MD2 && "Metadata operand is expected");
372 ConstantInt *Const = getConstInt(MD2, 0);
373 assert(Const && "MDOperand should be ConstantInt");
374 auto Dec =
375 static_cast<SPIRV::Decoration::Decoration>(Const->getZExtValue());
376 std::vector<uint32_t> DecVec;
377 for (unsigned j = 1; j < MD2->getNumOperands(); j++) {
378 ConstantInt *Const = getConstInt(MD2, j);
379 assert(Const && "MDOperand should be ConstantInt");
380 DecVec.push_back(static_cast<uint32_t>(Const->getZExtValue()));
381 }
382 buildOpDecorate(VRegs[i][0], MIRBuilder, Dec, DecVec);
383 }
384 }
385 ++i;
386 }
387 }
388
389 auto MRI = MIRBuilder.getMRI();
390 Register FuncVReg = MRI->createGenericVirtualRegister(LLT::scalar(64));
391 MRI->setRegClass(FuncVReg, &SPIRV::iIDRegClass);
393 Type *FRetTy = FTy->getReturnType();
394 if (isUntypedPointerTy(FRetTy)) {
395 if (Type *FRetElemTy = GR->findDeducedElementType(&F)) {
397 toTypedPointer(FRetElemTy), getPointerAddressSpace(FRetTy));
398 GR->addReturnType(&F, DerivedTy);
399 FRetTy = DerivedTy;
400 }
401 }
402 SPIRVType *RetTy = GR->getOrCreateSPIRVType(
403 FRetTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
404 FTy = fixFunctionTypeIfPtrArgs(GR, F, FTy, RetTy, ArgTypeVRegs);
405 SPIRVType *FuncTy = GR->getOrCreateOpTypeFunctionWithArgs(
406 FTy, RetTy, ArgTypeVRegs, MIRBuilder);
407 uint32_t FuncControl = getFunctionControl(F, ST);
408
409 // Add OpFunction instruction
410 MachineInstrBuilder MB = MIRBuilder.buildInstr(SPIRV::OpFunction)
411 .addDef(FuncVReg)
412 .addUse(GR->getSPIRVTypeID(RetTy))
413 .addImm(FuncControl)
414 .addUse(GR->getSPIRVTypeID(FuncTy));
415 GR->recordFunctionDefinition(&F, &MB.getInstr()->getOperand(0));
416 GR->addGlobalObject(&F, &MIRBuilder.getMF(), FuncVReg);
417 if (F.isDeclaration())
418 GR->add(&F, MB);
419
420 // Add OpFunctionParameter instructions
421 int i = 0;
422 for (const auto &Arg : F.args()) {
423 assert(VRegs[i].size() == 1 && "Formal arg has multiple vregs");
424 Register ArgReg = VRegs[i][0];
425 MRI->setRegClass(ArgReg, GR->getRegClass(ArgTypeVRegs[i]));
426 MRI->setType(ArgReg, GR->getRegType(ArgTypeVRegs[i]));
427 auto MIB = MIRBuilder.buildInstr(SPIRV::OpFunctionParameter)
428 .addDef(ArgReg)
429 .addUse(GR->getSPIRVTypeID(ArgTypeVRegs[i]));
430 if (F.isDeclaration())
431 GR->add(&Arg, MIB);
432 GR->addGlobalObject(&Arg, &MIRBuilder.getMF(), ArgReg);
433 i++;
434 }
435 // Name the function.
436 if (F.hasName())
437 buildOpName(FuncVReg, F.getName(), MIRBuilder);
438
439 // Handle entry points and function linkage.
440 if (isEntryPoint(F)) {
441 // EntryPoints can help us to determine the environment we're working on.
442 // Therefore, we need a non-const pointer to SPIRVSubtarget to update the
443 // environment if we need to.
444 const SPIRVSubtarget *ST =
445 static_cast<const SPIRVSubtarget *>(&MIRBuilder.getMF().getSubtarget());
446 auto MIB = MIRBuilder.buildInstr(SPIRV::OpEntryPoint)
447 .addImm(static_cast<uint32_t>(getExecutionModel(*ST, F)))
448 .addUse(FuncVReg);
449 addStringImm(F.getName(), MIB);
450 } else if (const auto LnkTy = getSpirvLinkageTypeFor(*ST, F)) {
451 buildOpDecorate(FuncVReg, MIRBuilder, SPIRV::Decoration::LinkageAttributes,
452 {static_cast<uint32_t>(*LnkTy)}, F.getName());
453 }
454
455 // Handle function pointers decoration
456 bool hasFunctionPointers =
457 ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers);
458 if (hasFunctionPointers) {
459 if (F.hasFnAttribute("referenced-indirectly")) {
460 assert((F.getCallingConv() != CallingConv::SPIR_KERNEL) &&
461 "Unexpected 'referenced-indirectly' attribute of the kernel "
462 "function");
463 buildOpDecorate(FuncVReg, MIRBuilder,
464 SPIRV::Decoration::ReferencedIndirectlyINTEL, {});
465 }
466 }
467
468 return true;
469}
470
471// Used to postpone producing of indirect function pointer types after all
472// indirect calls info is collected
473// TODO:
474// - add a topological sort of IndirectCalls to ensure the best types knowledge
475// - we may need to fix function formal parameter types if they are opaque
476// pointers used as function pointers in these indirect calls
477// - defaulting to StorageClass::Function in the absence of the
478// SPV_INTEL_function_pointers extension seems wrong, as that might not be
479// able to hold a full width pointer to function, and it also does not model
480// the semantics of a pointer to function in a generic fashion.
481void SPIRVCallLowering::produceIndirectPtrTypes(
482 MachineIRBuilder &MIRBuilder) const {
483 // Create indirect call data types if any
484 MachineFunction &MF = MIRBuilder.getMF();
486 for (auto const &IC : IndirectCalls) {
487 SPIRVType *SpirvRetTy = GR->getOrCreateSPIRVType(
488 IC.RetTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
489 SmallVector<SPIRVType *, 4> SpirvArgTypes;
490 for (size_t i = 0; i < IC.ArgTys.size(); ++i) {
491 SPIRVType *SPIRVTy = GR->getOrCreateSPIRVType(
492 IC.ArgTys[i], MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
493 SpirvArgTypes.push_back(SPIRVTy);
494 if (!GR->getSPIRVTypeForVReg(IC.ArgRegs[i]))
495 GR->assignSPIRVTypeToVReg(SPIRVTy, IC.ArgRegs[i], MF);
496 }
497 // SPIR-V function type:
498 FunctionType *FTy =
499 FunctionType::get(const_cast<Type *>(IC.RetTy), IC.ArgTys, false);
501 FTy, SpirvRetTy, SpirvArgTypes, MIRBuilder);
502 // SPIR-V pointer to function type:
503 auto SC = ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers)
504 ? SPIRV::StorageClass::CodeSectionINTEL
505 : SPIRV::StorageClass::Function;
506 SPIRVType *IndirectFuncPtrTy =
507 GR->getOrCreateSPIRVPointerType(SpirvFuncTy, MIRBuilder, SC);
508 // Correct the Callee type
509 GR->assignSPIRVTypeToVReg(IndirectFuncPtrTy, IC.Callee, MF);
510 }
511}
512
514 CallLoweringInfo &Info) const {
515 // Currently call returns should have single vregs.
516 // TODO: handle the case of multiple registers.
517 if (Info.OrigRet.Regs.size() > 1)
518 return false;
519 MachineFunction &MF = MIRBuilder.getMF();
520 GR->setCurrentFunc(MF);
521 const Function *CF = nullptr;
522 std::string DemangledName;
523 const Type *OrigRetTy = Info.OrigRet.Ty;
524
525 // Emit a regular OpFunctionCall. If it's an externally declared function,
526 // be sure to emit its type and function declaration here. It will be hoisted
527 // globally later.
528 if (Info.Callee.isGlobal()) {
529 std::string FuncName = Info.Callee.getGlobal()->getName().str();
530 DemangledName = getOclOrSpirvBuiltinDemangledName(FuncName);
531 CF = dyn_cast_or_null<const Function>(Info.Callee.getGlobal());
532 // TODO: support constexpr casts and indirect calls.
533 if (CF == nullptr)
534 return false;
535
537 OrigRetTy = FTy->getReturnType();
538 if (isUntypedPointerTy(OrigRetTy)) {
539 if (auto *DerivedRetTy = GR->findReturnType(CF))
540 OrigRetTy = DerivedRetTy;
541 }
542 }
543
544 MachineRegisterInfo *MRI = MIRBuilder.getMRI();
545 Register ResVReg =
546 Info.OrigRet.Regs.empty() ? Register(0) : Info.OrigRet.Regs[0];
547 const auto *ST = static_cast<const SPIRVSubtarget *>(&MF.getSubtarget());
548
549 bool isFunctionDecl = CF && CF->isDeclaration();
550 if (isFunctionDecl && !DemangledName.empty()) {
551 if (ResVReg.isValid()) {
552 if (!GR->getSPIRVTypeForVReg(ResVReg)) {
553 const Type *RetTy = OrigRetTy;
554 if (auto *PtrRetTy = dyn_cast<PointerType>(OrigRetTy)) {
555 const Value *OrigValue = Info.OrigRet.OrigValue;
556 if (!OrigValue)
557 OrigValue = Info.CB;
558 if (OrigValue)
559 if (Type *ElemTy = GR->findDeducedElementType(OrigValue))
560 RetTy =
561 TypedPointerType::get(ElemTy, PtrRetTy->getAddressSpace());
562 }
563 setRegClassType(ResVReg, RetTy, GR, MIRBuilder,
564 SPIRV::AccessQualifier::ReadWrite, true);
565 }
566 } else {
567 ResVReg = createVirtualRegister(OrigRetTy, GR, MIRBuilder,
568 SPIRV::AccessQualifier::ReadWrite, true);
569 }
571 for (auto Arg : Info.OrigArgs) {
572 assert(Arg.Regs.size() == 1 && "Call arg has multiple VRegs");
573 Register ArgReg = Arg.Regs[0];
574 ArgVRegs.push_back(ArgReg);
575 SPIRVType *SpvType = GR->getSPIRVTypeForVReg(ArgReg);
576 if (!SpvType) {
577 Type *ArgTy = nullptr;
578 if (auto *PtrArgTy = dyn_cast<PointerType>(Arg.Ty)) {
579 // If Arg.Ty is an untyped pointer (i.e., ptr [addrspace(...)]) and we
580 // don't have access to original value in LLVM IR or info about
581 // deduced pointee type, then we should wait with setting the type for
582 // the virtual register until pre-legalizer step when we access
583 // @llvm.spv.assign.ptr.type.p...(...)'s info.
584 if (Arg.OrigValue)
585 if (Type *ElemTy = GR->findDeducedElementType(Arg.OrigValue))
586 ArgTy =
587 TypedPointerType::get(ElemTy, PtrArgTy->getAddressSpace());
588 } else {
589 ArgTy = Arg.Ty;
590 }
591 if (ArgTy) {
592 SpvType = GR->getOrCreateSPIRVType(
593 ArgTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
594 GR->assignSPIRVTypeToVReg(SpvType, ArgReg, MF);
595 }
596 }
597 if (!MRI->getRegClassOrNull(ArgReg)) {
598 // Either we have SpvType created, or Arg.Ty is an untyped pointer and
599 // we know its virtual register's class and type even if we don't know
600 // pointee type.
601 MRI->setRegClass(ArgReg, SpvType ? GR->getRegClass(SpvType)
602 : &SPIRV::pIDRegClass);
603 MRI->setType(
604 ArgReg,
605 SpvType ? GR->getRegType(SpvType)
606 : LLT::pointer(cast<PointerType>(Arg.Ty)->getAddressSpace(),
607 GR->getPointerSize()));
608 }
609 }
610 if (auto Res = SPIRV::lowerBuiltin(
611 DemangledName, ST->getPreferredInstructionSet(), MIRBuilder,
612 ResVReg, OrigRetTy, ArgVRegs, GR, *Info.CB))
613 return *Res;
614 }
615
616 if (isFunctionDecl && !GR->find(CF, &MF).isValid()) {
617 // Emit the type info and forward function declaration to the first MBB
618 // to ensure VReg definition dependencies are valid across all MBBs.
619 MachineIRBuilder FirstBlockBuilder;
620 FirstBlockBuilder.setMF(MF);
621 FirstBlockBuilder.setMBB(*MF.getBlockNumbered(0));
622
625 for (const Argument &Arg : CF->args()) {
626 if (MIRBuilder.getDataLayout().getTypeStoreSize(Arg.getType()).isZero())
627 continue; // Don't handle zero sized types.
628 Register Reg = MRI->createGenericVirtualRegister(LLT::scalar(64));
629 MRI->setRegClass(Reg, &SPIRV::iIDRegClass);
630 ToInsert.push_back({Reg});
631 VRegArgs.push_back(ToInsert.back());
632 }
633 // TODO: Reuse FunctionLoweringInfo
634 FunctionLoweringInfo FuncInfo;
635 lowerFormalArguments(FirstBlockBuilder, *CF, VRegArgs, FuncInfo);
636 }
637
638 // Ignore the call if it's called from the internal service function
639 if (MIRBuilder.getMF()
640 .getFunction()
642 .isValid()) {
643 // insert a no-op
644 MIRBuilder.buildTrap();
645 return true;
646 }
647
648 unsigned CallOp;
649 if (Info.CB->isIndirectCall()) {
650 if (!ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers))
651 report_fatal_error("An indirect call is encountered but SPIR-V without "
652 "extensions does not support it",
653 false);
654 // Set instruction operation according to SPV_INTEL_function_pointers
655 CallOp = SPIRV::OpFunctionPointerCallINTEL;
656 // Collect information about the indirect call to support possible
657 // specification of opaque ptr types of parent function's parameters
658 Register CalleeReg = Info.Callee.getReg();
659 if (CalleeReg.isValid()) {
660 SPIRVCallLowering::SPIRVIndirectCall IndirectCall;
661 IndirectCall.Callee = CalleeReg;
663 IndirectCall.RetTy = OrigRetTy = FTy->getReturnType();
664 assert(FTy->getNumParams() == Info.OrigArgs.size() &&
665 "Function types mismatch");
666 for (unsigned I = 0; I != Info.OrigArgs.size(); ++I) {
667 assert(Info.OrigArgs[I].Regs.size() == 1 &&
668 "Call arg has multiple VRegs");
669 IndirectCall.ArgTys.push_back(FTy->getParamType(I));
670 IndirectCall.ArgRegs.push_back(Info.OrigArgs[I].Regs[0]);
671 }
672 IndirectCalls.push_back(IndirectCall);
673 }
674 } else {
675 // Emit a regular OpFunctionCall
676 CallOp = SPIRV::OpFunctionCall;
677 }
678
679 // Make sure there's a valid return reg, even for functions returning void.
680 if (!ResVReg.isValid())
681 ResVReg = MIRBuilder.getMRI()->createVirtualRegister(&SPIRV::iIDRegClass);
682 SPIRVType *RetType = GR->assignTypeToVReg(
683 OrigRetTy, ResVReg, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true);
684
685 // Emit the call instruction and its args.
686 auto MIB = MIRBuilder.buildInstr(CallOp)
687 .addDef(ResVReg)
688 .addUse(GR->getSPIRVTypeID(RetType))
689 .add(Info.Callee);
690
691 for (const auto &Arg : Info.OrigArgs) {
692 // Currently call args should have single vregs.
693 if (Arg.Regs.size() > 1)
694 return false;
695 MIB.addUse(Arg.Regs[0]);
696 }
697
698 if (ST->canUseExtension(SPIRV::Extension::SPV_INTEL_memory_access_aliasing)) {
699 // Process aliasing metadata.
700 const CallBase *CI = Info.CB;
701 if (CI && CI->hasMetadata()) {
702 if (MDNode *MD = CI->getMetadata(LLVMContext::MD_alias_scope))
703 GR->buildMemAliasingOpDecorate(ResVReg, MIRBuilder,
704 SPIRV::Decoration::AliasScopeINTEL, MD);
705 if (MDNode *MD = CI->getMetadata(LLVMContext::MD_noalias))
706 GR->buildMemAliasingOpDecorate(ResVReg, MIRBuilder,
707 SPIRV::Decoration::NoAliasINTEL, MD);
708 }
709 }
710
711 return MIB.constrainAllUses(MIRBuilder.getTII(), *ST->getRegisterInfo(),
712 *ST->getRegBankInfo());
713}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
static ConstantInt * getConstInt(MDNode *MD, unsigned NumOp)
static SPIRV::ExecutionModel::ExecutionModel getExecutionModel(const SPIRVSubtarget &STI, const Function &F)
static uint32_t getFunctionControl(const Function &F, const SPIRVSubtarget *ST)
static SPIRV::AccessQualifier::AccessQualifier getArgAccessQual(const Function &F, unsigned ArgIdx)
static SPIRVType * getArgSPIRVType(const Function &F, unsigned ArgIdx, SPIRVGlobalRegistry *GR, MachineIRBuilder &MIRBuilder, const SPIRVSubtarget &ST)
static FunctionType * fixFunctionTypeIfPtrArgs(SPIRVGlobalRegistry *GR, const Function &F, FunctionType *FTy, const SPIRVType *SRetTy, const SmallVector< SPIRVType *, 4 > &SArgTys)
static std::vector< SPIRV::Decoration::Decoration > getKernelArgTypeQual(const Function &F, unsigned ArgIdx)
#define SPIRV_BACKEND_SERVICE_FUN_NAME
Definition SPIRVUtils.h:523
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 isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:223
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
CallLowering(const TargetLowering *TLI)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:557
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
Class to represent function types.
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Type * getParamType(unsigned i) const
Parameter type accessors.
Type * getReturnType() const
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
iterator_range< arg_iterator > args()
Definition Function.h:890
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:765
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:328
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
Metadata node.
Definition Metadata.h:1078
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1442
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1440
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1448
Tracking metadata reference owned by Metadata.
Definition Metadata.h:900
A single uniqued string.
Definition Metadata.h:721
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:618
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineBasicBlock * getBlockNumbered(unsigned N) const
getBlockNumbered - MachineBasicBlocks are automatically numbered when they are inserted into the mach...
Function & getFunction()
Return the LLVM function that this machine code represents.
Helper class to build MachineInstr.
const TargetInstrInfo & getTII()
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
MachineFunction & getMF()
Getter for the function we currently build.
void setMBB(MachineBasicBlock &MBB)
Set the insertion point to the end of MBB.
MachineInstrBuilder buildTrap(bool Debug=false)
Build and insert G_TRAP or G_DEBUGTRAP.
MachineRegisterInfo * getMRI()
Getter for MRI.
const DataLayout & getDataLayout() const
void setMF(MachineFunction &MF)
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
bool constrainAllUses(const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI) const
const MachineInstrBuilder & addUse(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
const MachineInstrBuilder & addDef(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineOperand & getOperand(unsigned i) const
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:220
bool onlyReadsMemory() const
Whether this function only (at most) reads memory.
Definition ModRef.h:223
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:183
Metadata * getMetadata() const
Definition Metadata.h:201
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:112
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 lowerReturn(MachineIRBuilder &MIRBuiler, const Value *Val, ArrayRef< Register > VRegs, FunctionLoweringInfo &FLI, Register SwiftErrorVReg) const override
This hook must be implemented to lower outgoing return values, described by Val, into the specified v...
SPIRVCallLowering(const SPIRVTargetLowering &TLI, SPIRVGlobalRegistry *GR)
bool lowerFormalArguments(MachineIRBuilder &MIRBuilder, 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,...
SPIRVType * getSPIRVTypeForVReg(Register VReg, const MachineFunction *MF=nullptr) const
void assignSPIRVTypeToVReg(SPIRVType *Type, Register VReg, const MachineFunction &MF)
const Type * getTypeForSPIRVType(const SPIRVType *Ty) const
SPIRVType * getOrCreateSPIRVType(const Type *Type, MachineInstr &I, SPIRV::AccessQualifier::AccessQualifier AQ, bool EmitIR)
SPIRVType * getOrCreateSPIRVPointerType(const Type *BaseType, MachineIRBuilder &MIRBuilder, SPIRV::StorageClass::StorageClass SC)
SPIRVType * getOrCreateOpTypeFunctionWithArgs(const Type *Ty, SPIRVType *RetType, const SmallVectorImpl< SPIRVType * > &ArgTypes, MachineIRBuilder &MIRBuilder)
SPIRVEnvType getEnv() const
void setEnv(SPIRVEnvType E)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
const TargetRegisterInfo & getRegisterInfo() const
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
A few GPU targets, such as DXIL and SPIR-V, have typed pointers.
static LLVM_ABI TypedPointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
iterator_range< user_iterator > users()
Definition Value.h:426
constexpr bool isZero() const
Definition TypeSize.h:153
@ SPIR_KERNEL
Used for SPIR kernel functions.
std::optional< bool > lowerBuiltin(const StringRef DemangledCall, SPIRV::InstructionSet::InstructionSet Set, MachineIRBuilder &MIRBuilder, const Register OrigRet, const Type *OrigRetTy, const SmallVectorImpl< Register > &Args, SPIRVGlobalRegistry *GR, const CallBase &CB)
FunctionType * getOriginalFunctionType(const Function &F)
This is an optimization pass for GlobalISel generic memory operations.
void buildOpName(Register Target, const StringRef &Name, MachineIRBuilder &MIRBuilder)
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
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:365
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:301
MDString * getOCLKernelArgAccessQual(const Function &F, unsigned ArgIdx)
std::string getOclOrSpirvBuiltinDemangledName(StringRef Name)
bool isTypedPointerTy(const Type *T)
Definition SPIRVUtils.h:349
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void buildOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, const std::vector< uint32_t > &DecArgs, StringRef StrImm)
Register createVirtualRegister(SPIRVType *SpvType, SPIRVGlobalRegistry *GR, MachineRegisterInfo *MRI, const MachineFunction &MF)
Type * toTypedPointer(Type *Ty)
Definition SPIRVUtils.h:456
void setRegClassType(Register Reg, SPIRVType *SpvType, SPIRVGlobalRegistry *GR, MachineRegisterInfo *MRI, const MachineFunction &MF, bool Force)
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:359
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:167
const MachineInstr SPIRVType
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
std::optional< SPIRV::LinkageType::LinkageType > getSpirvLinkageTypeFor(const SPIRVSubtarget &ST, const GlobalValue &GV)
bool isEntryPoint(const Function &F)
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
MDString * getOCLKernelArgTypeQual(const Function &F, unsigned ArgIdx)
Type * getPointeeTypeByAttr(Argument *Arg)
Definition SPIRVUtils.h:378
bool hasPointeeTypeAttr(Argument *Arg)
Definition SPIRVUtils.h:373
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool isPointerTyOrWrapper(const Type *Ty)
Definition SPIRVUtils.h:408
void addStringImm(const StringRef &Str, MCInst &Inst)
bool isUntypedPointerTy(const Type *T)
Definition SPIRVUtils.h:354