clang 22.0.0git
SPIR.cpp
Go to the documentation of this file.
1//===- SPIR.cpp -----------------------------------------------------------===//
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#include "ABIInfoImpl.h"
11#include "TargetInfo.h"
12
13using namespace clang;
14using namespace clang::CodeGen;
15
16//===----------------------------------------------------------------------===//
17// Base ABI and target codegen info implementation common between SPIR and
18// SPIR-V.
19//===----------------------------------------------------------------------===//
20
21namespace {
22class CommonSPIRABIInfo : public DefaultABIInfo {
23public:
24 CommonSPIRABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) { setCCs(); }
25
26private:
27 void setCCs();
28};
29
30class SPIRVABIInfo : public CommonSPIRABIInfo {
31public:
32 SPIRVABIInfo(CodeGenTypes &CGT) : CommonSPIRABIInfo(CGT) {}
33 void computeInfo(CGFunctionInfo &FI) const override;
34
35private:
36 ABIArgInfo classifyReturnType(QualType RetTy) const;
37 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
38 ABIArgInfo classifyArgumentType(QualType Ty) const;
39};
40} // end anonymous namespace
41namespace {
42class CommonSPIRTargetCodeGenInfo : public TargetCodeGenInfo {
43public:
44 CommonSPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
45 : TargetCodeGenInfo(std::make_unique<CommonSPIRABIInfo>(CGT)) {}
46 CommonSPIRTargetCodeGenInfo(std::unique_ptr<ABIInfo> ABIInfo)
47 : TargetCodeGenInfo(std::move(ABIInfo)) {}
48
49 LangAS getASTAllocaAddressSpace() const override {
51 getABIInfo().getDataLayout().getAllocaAddrSpace());
52 }
53
54 unsigned getDeviceKernelCallingConv() const override;
55 llvm::Type *getOpenCLType(CodeGenModule &CGM, const Type *T) const override;
56 llvm::Type *getHLSLType(CodeGenModule &CGM, const Type *Ty,
57 const CGHLSLOffsetInfo &OffsetInfo) const override;
58
59 llvm::Type *getHLSLPadding(CodeGenModule &CGM,
60 CharUnits NumBytes) const override {
61 unsigned Size = NumBytes.getQuantity();
62 return llvm::TargetExtType::get(CGM.getLLVMContext(), "spirv.Padding", {},
63 {Size});
64 }
65
66 bool isHLSLPadding(llvm::Type *Ty) const override {
67 if (auto *TET = dyn_cast<llvm::TargetExtType>(Ty))
68 return TET->getName() == "spirv.Padding";
69 return false;
70 }
71
72 llvm::Type *getSPIRVImageTypeFromHLSLResource(
73 const HLSLAttributedResourceType::Attributes &attributes,
74 QualType SampledType, CodeGenModule &CGM) const;
75 void
76 setOCLKernelStubCallingConvention(const FunctionType *&FT) const override;
77 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
78 llvm::PointerType *T,
79 QualType QT) const override;
80};
81class SPIRVTargetCodeGenInfo : public CommonSPIRTargetCodeGenInfo {
82public:
83 SPIRVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
84 : CommonSPIRTargetCodeGenInfo(std::make_unique<SPIRVABIInfo>(CGT)) {}
85 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
86 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
87 const VarDecl *D) const override;
88 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
89 CodeGen::CodeGenModule &M) const override;
90 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
91 SyncScope Scope,
92 llvm::AtomicOrdering Ordering,
93 llvm::LLVMContext &Ctx) const override;
94 bool supportsLibCall() const override {
95 return getABIInfo().getTarget().getTriple().getVendor() !=
96 llvm::Triple::AMD;
97 }
98};
99
100inline StringRef mapClangSyncScopeToLLVM(SyncScope Scope) {
101 switch (Scope) {
104 return "singlethread";
108 return "subgroup";
114 return "workgroup";
118 return "device";
122 return "";
123 }
124 return "";
125}
126} // End anonymous namespace.
127
128void CommonSPIRABIInfo::setCCs() {
129 assert(getRuntimeCC() == llvm::CallingConv::C);
130 RuntimeCC = llvm::CallingConv::SPIR_FUNC;
131}
132
133ABIArgInfo SPIRVABIInfo::classifyReturnType(QualType RetTy) const {
134 if (getTarget().getTriple().getVendor() != llvm::Triple::AMD)
136 if (!isAggregateTypeForABI(RetTy) || getRecordArgABI(RetTy, getCXXABI()))
138
139 if (const auto *RD = RetTy->getAsRecordDecl();
140 RD && RD->hasFlexibleArrayMember())
142
143 // TODO: The AMDGPU ABI is non-trivial to represent in SPIR-V; in order to
144 // avoid encoding various architecture specific bits here we return everything
145 // as direct to retain type info for things like aggregates, for later perusal
146 // when translating back to LLVM/lowering in the BE. This is also why we
147 // disable flattening as the outcomes can mismatch between SPIR-V and AMDGPU.
148 // This will be revisited / optimised in the future.
149 return ABIArgInfo::getDirect(CGT.ConvertType(RetTy), 0u, nullptr, false);
150}
151
152ABIArgInfo SPIRVABIInfo::classifyKernelArgumentType(QualType Ty) const {
153 if (getContext().getLangOpts().isTargetDevice()) {
154 // Coerce pointer arguments with default address space to CrossWorkGroup
155 // pointers for target devices as default address space kernel arguments
156 // are not allowed. We use the opencl_global language address space which
157 // always maps to CrossWorkGroup.
158 llvm::Type *LTy = CGT.ConvertType(Ty);
159 auto DefaultAS = getContext().getTargetAddressSpace(LangAS::Default);
160 auto GlobalAS = getContext().getTargetAddressSpace(LangAS::opencl_global);
161 auto *PtrTy = llvm::dyn_cast<llvm::PointerType>(LTy);
162 if (PtrTy && PtrTy->getAddressSpace() == DefaultAS) {
163 LTy = llvm::PointerType::get(PtrTy->getContext(), GlobalAS);
164 return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
165 }
166
167 if (isAggregateTypeForABI(Ty)) {
168 if (getTarget().getTriple().getVendor() == llvm::Triple::AMD)
169 // TODO: The AMDGPU kernel ABI passes aggregates byref, which is not
170 // currently expressible in SPIR-V; SPIR-V passes aggregates byval,
171 // which the AMDGPU kernel ABI does not allow. Passing aggregates as
172 // direct works around this impedance mismatch, as it retains type info
173 // and can be correctly handled, post reverse-translation, by the AMDGPU
174 // BE, which has to support this CC for legacy OpenCL purposes. It can
175 // be brittle and does lead to performance degradation in certain
176 // pathological cases. This will be revisited / optimised in the future,
177 // once a way to deal with the byref/byval impedance mismatch is
178 // identified.
179 return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
180 // Force copying aggregate type in kernel arguments by value when
181 // compiling CUDA targeting SPIR-V. This is required for the object
182 // copied to be valid on the device.
183 // This behavior follows the CUDA spec
184 // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#global-function-argument-processing,
185 // and matches the NVPTX implementation. TODO: hardcoding to 0 should be
186 // revisited if HIPSPV / byval starts making use of the AS of an indirect
187 // arg.
188 return getNaturalAlignIndirect(Ty, /*AddrSpace=*/0, /*byval=*/true);
189 }
190 }
191 return classifyArgumentType(Ty);
192}
193
194ABIArgInfo SPIRVABIInfo::classifyArgumentType(QualType Ty) const {
195 if (getTarget().getTriple().getVendor() != llvm::Triple::AMD)
197 if (!isAggregateTypeForABI(Ty))
199
200 // Records with non-trivial destructors/copy-constructors should not be
201 // passed by value.
202 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
203 return getNaturalAlignIndirect(Ty, getDataLayout().getAllocaAddrSpace(),
205
206 if (const auto *RD = Ty->getAsRecordDecl();
207 RD && RD->hasFlexibleArrayMember())
209
210 return ABIArgInfo::getDirect(CGT.ConvertType(Ty), 0u, nullptr, false);
211}
212
213void SPIRVABIInfo::computeInfo(CGFunctionInfo &FI) const {
214 // The logic is same as in DefaultABIInfo with an exception on the kernel
215 // arguments handling.
216 llvm::CallingConv::ID CC = FI.getCallingConvention();
217
218 if (!getCXXABI().classifyReturnType(FI))
220
221 for (auto &I : FI.arguments()) {
222 if (CC == llvm::CallingConv::SPIR_KERNEL) {
223 I.info = classifyKernelArgumentType(I.type);
224 } else {
225 I.info = classifyArgumentType(I.type);
226 }
227 }
228}
229
230namespace clang {
231namespace CodeGen {
233 if (CGM.getTarget().getTriple().isSPIRV())
234 SPIRVABIInfo(CGM.getTypes()).computeInfo(FI);
235 else
236 CommonSPIRABIInfo(CGM.getTypes()).computeInfo(FI);
237}
238}
239}
240
241unsigned CommonSPIRTargetCodeGenInfo::getDeviceKernelCallingConv() const {
242 return llvm::CallingConv::SPIR_KERNEL;
243}
244
245void SPIRVTargetCodeGenInfo::setCUDAKernelCallingConvention(
246 const FunctionType *&FT) const {
247 // Convert HIP kernels to SPIR-V kernels.
248 if (getABIInfo().getContext().getLangOpts().HIP) {
249 FT = getABIInfo().getContext().adjustFunctionType(
251 return;
252 }
253}
254
255void CommonSPIRTargetCodeGenInfo::setOCLKernelStubCallingConvention(
256 const FunctionType *&FT) const {
257 FT = getABIInfo().getContext().adjustFunctionType(
259}
260
261// LLVM currently assumes a null pointer has the bit pattern 0, but some GPU
262// targets use a non-zero encoding for null in certain address spaces.
263// Because SPIR(-V) is a generic target and the bit pattern of null in
264// non-generic AS is unspecified, materialize null in non-generic AS via an
265// addrspacecast from null in generic AS. This allows later lowering to
266// substitute the target's real sentinel value.
267llvm::Constant *
268CommonSPIRTargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
269 llvm::PointerType *PT,
270 QualType QT) const {
272 ? LangAS::Default
274 unsigned ASAsInt = static_cast<unsigned>(AS);
275 unsigned FirstTargetASAsInt =
276 static_cast<unsigned>(LangAS::FirstTargetAddressSpace);
277 unsigned CodeSectionINTELAS = FirstTargetASAsInt + 9;
278 // As per SPV_INTEL_function_pointers, it is illegal to addrspacecast
279 // function pointers to/from the generic AS.
280 bool IsFunctionPtrAS =
281 CGM.getTriple().isSPIRV() && ASAsInt == CodeSectionINTELAS;
282 if (AS == LangAS::Default || AS == LangAS::opencl_generic ||
283 AS == LangAS::opencl_constant || IsFunctionPtrAS)
284 return llvm::ConstantPointerNull::get(PT);
285
286 auto &Ctx = CGM.getContext();
287 auto NPT = llvm::PointerType::get(
288 PT->getContext(), Ctx.getTargetAddressSpace(LangAS::opencl_generic));
289 return llvm::ConstantExpr::getAddrSpaceCast(
290 llvm::ConstantPointerNull::get(NPT), PT);
291}
292
293LangAS
294SPIRVTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
295 const VarDecl *D) const {
296 assert(!CGM.getLangOpts().OpenCL &&
297 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
298 "Address space agnostic languages only");
299 // If we're here it means that we're using the SPIRDefIsGen ASMap, hence for
300 // the global AS we can rely on either cuda_device or sycl_global to be
301 // correct; however, since this is not a CUDA Device context, we use
302 // sycl_global to prevent confusion with the assertion.
303 LangAS DefaultGlobalAS = getLangASFromTargetAS(
304 CGM.getContext().getTargetAddressSpace(LangAS::sycl_global));
305 if (!D)
306 return DefaultGlobalAS;
307
308 LangAS AddrSpace = D->getType().getAddressSpace();
309 if (AddrSpace != LangAS::Default)
310 return AddrSpace;
311
312 return DefaultGlobalAS;
313}
314
315void SPIRVTargetCodeGenInfo::setTargetAttributes(
316 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
317 if (GV->isDeclaration())
318 return;
319
320 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
321 if (!FD)
322 return;
323
324 llvm::Function *F = dyn_cast<llvm::Function>(GV);
325 assert(F && "Expected GlobalValue to be a Function");
326
327 if (!M.getLangOpts().HIP ||
328 M.getTarget().getTriple().getVendor() != llvm::Triple::AMD)
329 return;
330
331 if (!FD->hasAttr<CUDAGlobalAttr>())
332 return;
333
334 unsigned N = M.getLangOpts().GPUMaxThreadsPerBlock;
335 if (auto FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>())
336 N = FlatWGS->getMax()->EvaluateKnownConstInt(M.getContext()).getExtValue();
337
338 // We encode the maximum flat WG size in the first component of the 3D
339 // max_work_group_size attribute, which will get reverse translated into the
340 // original AMDGPU attribute when targeting AMDGPU.
341 auto Int32Ty = llvm::IntegerType::getInt32Ty(M.getLLVMContext());
342 llvm::Metadata *AttrMDArgs[] = {
343 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, N)),
344 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 1)),
345 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 1))};
346
347 F->setMetadata("max_work_group_size",
348 llvm::MDNode::get(M.getLLVMContext(), AttrMDArgs));
349}
350
351llvm::SyncScope::ID
352SPIRVTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &, SyncScope Scope,
353 llvm::AtomicOrdering,
354 llvm::LLVMContext &Ctx) const {
355 return Ctx.getOrInsertSyncScopeID(mapClangSyncScopeToLLVM(Scope));
356}
357
358/// Construct a SPIR-V target extension type for the given OpenCL image type.
359static llvm::Type *getSPIRVImageType(llvm::LLVMContext &Ctx, StringRef BaseType,
360 StringRef OpenCLName,
361 unsigned AccessQualifier) {
362 // These parameters compare to the operands of OpTypeImage (see
363 // https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#OpTypeImage
364 // for more details). The first 6 integer parameters all default to 0, and
365 // will be changed to 1 only for the image type(s) that set the parameter to
366 // one. The 7th integer parameter is the access qualifier, which is tacked on
367 // at the end.
368 SmallVector<unsigned, 7> IntParams = {0, 0, 0, 0, 0, 0};
369
370 // Choose the dimension of the image--this corresponds to the Dim enum in
371 // SPIR-V (first integer parameter of OpTypeImage).
372 if (OpenCLName.starts_with("image2d"))
373 IntParams[0] = 1;
374 else if (OpenCLName.starts_with("image3d"))
375 IntParams[0] = 2;
376 else if (OpenCLName == "image1d_buffer")
377 IntParams[0] = 5; // Buffer
378 else
379 assert(OpenCLName.starts_with("image1d") && "Unknown image type");
380
381 // Set the other integer parameters of OpTypeImage if necessary. Note that the
382 // OpenCL image types don't provide any information for the Sampled or
383 // Image Format parameters.
384 if (OpenCLName.contains("_depth"))
385 IntParams[1] = 1;
386 if (OpenCLName.contains("_array"))
387 IntParams[2] = 1;
388 if (OpenCLName.contains("_msaa"))
389 IntParams[3] = 1;
390
391 // Access qualifier
392 IntParams.push_back(AccessQualifier);
393
394 return llvm::TargetExtType::get(Ctx, BaseType, {llvm::Type::getVoidTy(Ctx)},
395 IntParams);
396}
397
398llvm::Type *CommonSPIRTargetCodeGenInfo::getOpenCLType(CodeGenModule &CGM,
399 const Type *Ty) const {
400 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
401 if (auto *PipeTy = dyn_cast<PipeType>(Ty))
402 return llvm::TargetExtType::get(Ctx, "spirv.Pipe", {},
403 {!PipeTy->isReadOnly()});
404 if (auto *BuiltinTy = dyn_cast<BuiltinType>(Ty)) {
405 enum AccessQualifier : unsigned { AQ_ro = 0, AQ_wo = 1, AQ_rw = 2 };
406 switch (BuiltinTy->getKind()) {
407#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
408 case BuiltinType::Id: \
409 return getSPIRVImageType(Ctx, "spirv.Image", #ImgType, AQ_##Suffix);
410#include "clang/Basic/OpenCLImageTypes.def"
411 case BuiltinType::OCLSampler:
412 return llvm::TargetExtType::get(Ctx, "spirv.Sampler");
413 case BuiltinType::OCLEvent:
414 return llvm::TargetExtType::get(Ctx, "spirv.Event");
415 case BuiltinType::OCLClkEvent:
416 return llvm::TargetExtType::get(Ctx, "spirv.DeviceEvent");
417 case BuiltinType::OCLQueue:
418 return llvm::TargetExtType::get(Ctx, "spirv.Queue");
419 case BuiltinType::OCLReserveID:
420 return llvm::TargetExtType::get(Ctx, "spirv.ReserveId");
421#define INTEL_SUBGROUP_AVC_TYPE(Name, Id) \
422 case BuiltinType::OCLIntelSubgroupAVC##Id: \
423 return llvm::TargetExtType::get(Ctx, "spirv.Avc" #Id "INTEL");
424#include "clang/Basic/OpenCLExtensionTypes.def"
425 default:
426 return nullptr;
427 }
428 }
429
430 return nullptr;
431}
432
433// Gets a spirv.IntegralConstant or spirv.Literal. If IntegralType is present,
434// returns an IntegralConstant, otherwise returns a Literal.
435static llvm::Type *getInlineSpirvConstant(CodeGenModule &CGM,
436 llvm::Type *IntegralType,
437 llvm::APInt Value) {
438 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
439
440 // Convert the APInt value to an array of uint32_t words
442
443 while (Value.ugt(0)) {
444 uint32_t Word = Value.trunc(32).getZExtValue();
445 Value.lshrInPlace(32);
446
447 Words.push_back(Word);
448 }
449 if (Words.size() == 0)
450 Words.push_back(0);
451
452 if (IntegralType)
453 return llvm::TargetExtType::get(Ctx, "spirv.IntegralConstant",
454 {IntegralType}, Words);
455 return llvm::TargetExtType::get(Ctx, "spirv.Literal", {}, Words);
456}
457
458static llvm::Type *getInlineSpirvType(CodeGenModule &CGM,
459 const HLSLInlineSpirvType *SpirvType) {
460 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
461
463
464 for (auto &Operand : SpirvType->getOperands()) {
465 using SpirvOperandKind = SpirvOperand::SpirvOperandKind;
466
467 llvm::Type *Result = nullptr;
468 switch (Operand.getKind()) {
469 case SpirvOperandKind::ConstantId: {
470 llvm::Type *IntegralType =
471 CGM.getTypes().ConvertType(Operand.getResultType());
472
473 Result = getInlineSpirvConstant(CGM, IntegralType, Operand.getValue());
474 break;
475 }
476 case SpirvOperandKind::Literal: {
477 Result = getInlineSpirvConstant(CGM, nullptr, Operand.getValue());
478 break;
479 }
480 case SpirvOperandKind::TypeId: {
481 QualType TypeOperand = Operand.getResultType();
482 if (const auto *RD = TypeOperand->getAsRecordDecl()) {
483 assert(RD->isCompleteDefinition() &&
484 "Type completion should have been required in Sema");
485
486 const FieldDecl *HandleField = RD->findFirstNamedDataMember();
487 if (HandleField) {
488 QualType ResourceType = HandleField->getType();
489 if (ResourceType->getAs<HLSLAttributedResourceType>()) {
490 TypeOperand = ResourceType;
491 }
492 }
493 }
494 Result = CGM.getTypes().ConvertType(TypeOperand);
495 break;
496 }
497 default:
498 llvm_unreachable("HLSLInlineSpirvType had invalid operand!");
499 break;
500 }
501
502 assert(Result);
503 Operands.push_back(Result);
504 }
505
506 return llvm::TargetExtType::get(Ctx, "spirv.Type", Operands,
507 {SpirvType->getOpcode(), SpirvType->getSize(),
508 SpirvType->getAlignment()});
509}
510
511llvm::Type *CommonSPIRTargetCodeGenInfo::getHLSLType(
512 CodeGenModule &CGM, const Type *Ty,
513 const CGHLSLOffsetInfo &OffsetInfo) const {
514 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
515
516 if (auto *SpirvType = dyn_cast<HLSLInlineSpirvType>(Ty))
517 return getInlineSpirvType(CGM, SpirvType);
518
519 auto *ResType = dyn_cast<HLSLAttributedResourceType>(Ty);
520 if (!ResType)
521 return nullptr;
522
523 const HLSLAttributedResourceType::Attributes &ResAttrs = ResType->getAttrs();
524 switch (ResAttrs.ResourceClass) {
525 case llvm::dxil::ResourceClass::UAV:
526 case llvm::dxil::ResourceClass::SRV: {
527 // TypedBuffer and RawBuffer both need element type
528 QualType ContainedTy = ResType->getContainedType();
529 if (ContainedTy.isNull())
530 return nullptr;
531
532 assert(!ResAttrs.IsROV &&
533 "Rasterizer order views not implemented for SPIR-V yet");
534
535 if (!ResAttrs.RawBuffer) {
536 // convert element type
537 return getSPIRVImageTypeFromHLSLResource(ResAttrs, ContainedTy, CGM);
538 }
539
540 if (ResAttrs.IsCounter) {
541 llvm::Type *ElemType = llvm::Type::getInt32Ty(Ctx);
542 uint32_t StorageClass = /* StorageBuffer storage class */ 12;
543 return llvm::TargetExtType::get(Ctx, "spirv.VulkanBuffer", {ElemType},
544 {StorageClass, true});
545 }
546 llvm::Type *ElemType = CGM.getTypes().ConvertTypeForMem(ContainedTy);
547 llvm::ArrayType *RuntimeArrayType = llvm::ArrayType::get(ElemType, 0);
548 uint32_t StorageClass = /* StorageBuffer storage class */ 12;
549 bool IsWritable = ResAttrs.ResourceClass == llvm::dxil::ResourceClass::UAV;
550 return llvm::TargetExtType::get(Ctx, "spirv.VulkanBuffer",
551 {RuntimeArrayType},
552 {StorageClass, IsWritable});
553 }
554 case llvm::dxil::ResourceClass::CBuffer: {
555 QualType ContainedTy = ResType->getContainedType();
556 if (ContainedTy.isNull() || !ContainedTy->isStructureType())
557 return nullptr;
558
559 llvm::StructType *BufferLayoutTy =
560 HLSLBufferLayoutBuilder(CGM).layOutStruct(
561 ContainedTy->getAsCanonical<RecordType>(), OffsetInfo);
562 uint32_t StorageClass = /* Uniform storage class */ 2;
563 return llvm::TargetExtType::get(Ctx, "spirv.VulkanBuffer", {BufferLayoutTy},
564 {StorageClass, false});
565 break;
566 }
567 case llvm::dxil::ResourceClass::Sampler:
568 return llvm::TargetExtType::get(Ctx, "spirv.Sampler");
569 }
570 return nullptr;
571}
572
573static unsigned
575 const HLSLAttributedResourceType::Attributes &attributes,
576 llvm::Type *SampledType, QualType Ty, unsigned NumChannels) {
577 // For images with `Sampled` operand equal to 2, there are restrictions on
578 // using the Unknown image format. To avoid these restrictions in common
579 // cases, we guess an image format for them based on the sampled type and the
580 // number of channels. This is intended to match the behaviour of DXC.
581 if (LangOpts.HLSLSpvUseUnknownImageFormat ||
582 attributes.ResourceClass != llvm::dxil::ResourceClass::UAV) {
583 return 0; // Unknown
584 }
585
586 if (SampledType->isIntegerTy(32)) {
587 if (Ty->isSignedIntegerType()) {
588 if (NumChannels == 1)
589 return 24; // R32i
590 if (NumChannels == 2)
591 return 25; // Rg32i
592 if (NumChannels == 4)
593 return 21; // Rgba32i
594 } else {
595 if (NumChannels == 1)
596 return 33; // R32ui
597 if (NumChannels == 2)
598 return 35; // Rg32ui
599 if (NumChannels == 4)
600 return 30; // Rgba32ui
601 }
602 } else if (SampledType->isIntegerTy(64)) {
603 if (NumChannels == 1) {
604 if (Ty->isSignedIntegerType()) {
605 return 41; // R64i
606 }
607 return 40; // R64ui
608 }
609 } else if (SampledType->isFloatTy()) {
610 if (NumChannels == 1)
611 return 3; // R32f
612 if (NumChannels == 2)
613 return 6; // Rg32f
614 if (NumChannels == 4)
615 return 1; // Rgba32f
616 }
617
618 return 0; // Unknown
619}
620
621llvm::Type *CommonSPIRTargetCodeGenInfo::getSPIRVImageTypeFromHLSLResource(
622 const HLSLAttributedResourceType::Attributes &attributes, QualType Ty,
623 CodeGenModule &CGM) const {
624 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
625
626 unsigned NumChannels = 1;
628 if (const VectorType *V = dyn_cast<VectorType>(Ty)) {
629 NumChannels = V->getNumElements();
630 Ty = V->getElementType();
631 }
632 assert(!Ty->isVectorType() && "We still have a vector type.");
633
634 llvm::Type *SampledType = CGM.getTypes().ConvertTypeForMem(Ty);
635
636 assert((SampledType->isIntegerTy() || SampledType->isFloatingPointTy()) &&
637 "The element type for a SPIR-V resource must be a scalar integer or "
638 "floating point type.");
639
640 // These parameters correspond to the operands to the OpTypeImage SPIR-V
641 // instruction. See
642 // https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#OpTypeImage.
643 SmallVector<unsigned, 6> IntParams(6, 0);
644
645 const char *Name =
646 Ty->isSignedIntegerType() ? "spirv.SignedImage" : "spirv.Image";
647
648 // Dim
649 // For now we assume everything is a buffer.
650 IntParams[0] = 5;
651
652 // Depth
653 // HLSL does not indicate if it is a depth texture or not, so we use unknown.
654 IntParams[1] = 2;
655
656 // Arrayed
657 IntParams[2] = 0;
658
659 // MS
660 IntParams[3] = 0;
661
662 // Sampled
663 IntParams[4] =
664 attributes.ResourceClass == llvm::dxil::ResourceClass::UAV ? 2 : 1;
665
666 // Image format.
667 IntParams[5] = getImageFormat(CGM.getLangOpts(), attributes, SampledType, Ty,
668 NumChannels);
669
670 llvm::TargetExtType *ImageType =
671 llvm::TargetExtType::get(Ctx, Name, {SampledType}, IntParams);
672 return ImageType;
673}
674
675std::unique_ptr<TargetCodeGenInfo>
677 return std::make_unique<CommonSPIRTargetCodeGenInfo>(CGM.getTypes());
678}
679
680std::unique_ptr<TargetCodeGenInfo>
682 return std::make_unique<SPIRVTargetCodeGenInfo>(CGM.getTypes());
683}
#define V(N, I)
static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM, const FunctionDecl *FD)
Set calling convention for CUDA/HIP kernel.
Definition CGCall.cpp:360
static llvm::Type * getInlineSpirvType(CodeGenModule &CGM, const HLSLInlineSpirvType *SpirvType)
Definition SPIR.cpp:458
static llvm::Type * getSPIRVImageType(llvm::LLVMContext &Ctx, StringRef BaseType, StringRef OpenCLName, unsigned AccessQualifier)
Construct a SPIR-V target extension type for the given OpenCL image type.
Definition SPIR.cpp:359
static unsigned getImageFormat(const LangOptions &LangOpts, const HLSLAttributedResourceType::Attributes &attributes, llvm::Type *SampledType, QualType Ty, unsigned NumChannels)
Definition SPIR.cpp:574
static llvm::Type * getInlineSpirvConstant(CodeGenModule &CGM, llvm::Type *IntegralType, llvm::APInt Value)
Definition SPIR.cpp:435
unsigned getTargetAddressSpace(LangAS AS) const
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static ABIArgInfo getDirect(llvm::Type *T=nullptr, unsigned Offset=0, llvm::Type *Padding=nullptr, bool CanBeFlattened=true, unsigned Align=0)
@ RAA_DirectInMemory
Pass it on the stack using its defined layout.
Definition CGCXXABI.h:158
CGFunctionInfo - Class to encapsulate the information about a function definition.
unsigned getCallingConvention() const
getCallingConvention - Return the user specified calling convention, which has been translated into a...
CanQualType getReturnType() const
MutableArrayRef< ArgInfo > arguments()
This class organizes the cross-function state that is used while generating LLVM code.
const LangOptions & getLangOpts() const
const TargetInfo & getTarget() const
const llvm::Triple & getTriple() const
ASTContext & getContext() const
llvm::LLVMContext & getLLVMContext()
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
DefaultABIInfo - The default implementation for ABI specific details.
Definition ABIInfoImpl.h:21
ABIArgInfo classifyArgumentType(QualType RetTy) const
ABIArgInfo classifyReturnType(QualType RetTy) const
TargetCodeGenInfo - This class organizes various target-specific codegeneration issues,...
Definition TargetInfo.h:49
T * getAttr() const
Definition DeclBase.h:573
bool hasAttr() const
Definition DeclBase.h:577
Represents a member of a struct/union/class.
Definition Decl.h:3160
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4673
ExtInfo getExtInfo() const
Definition TypeBase.h:4806
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8404
bool hasFlexibleArrayMember() const
Definition Decl.h:4354
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool isStructureType() const
Definition Type.cpp:678
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
CanQualType getCanonicalTypeUnqualified() const
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isVectorType() const
Definition TypeBase.h:8654
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:653
bool isNullPtrType() const
Definition TypeBase.h:8908
QualType getType() const
Definition Decl.h:723
ABIArgInfo classifyArgumentType(CodeGenModule &CGM, CanQualType type)
Classify the rules for how to pass a particular type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, CGCXXABI &CXXABI)
bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, const ABIInfo &Info)
void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI)
Definition SPIR.cpp:232
bool isAggregateTypeForABI(QualType T)
std::unique_ptr< TargetCodeGenInfo > createSPIRVTargetCodeGenInfo(CodeGenModule &CGM)
Definition SPIR.cpp:681
std::unique_ptr< TargetCodeGenInfo > createCommonSPIRTargetCodeGenInfo(CodeGenModule &CGM)
Definition SPIR.cpp:676
The JSON file list parser is used to communicate input to InstallAPI.
StorageClass
Storage classes.
Definition Specifiers.h:248
const FunctionProtoType * T
@ Type
The name was classified as a type.
Definition Sema.h:562
LangAS
Defines the address space values used by the address space qualifier of QualType.
SyncScope
Defines sync scope values used internally by clang.
Definition SyncScope.h:42
@ CC_DeviceKernel
Definition Specifiers.h:292
@ CC_SpirFunction
Definition Specifiers.h:291
LangAS getLangASFromTargetAS(unsigned TargetAS)
unsigned int uint32_t