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