1//===- SemaHLSL.cpp - Semantic Analysis for HLSL constructs ---------------===//
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// This implements Semantic Analysis for HLSL constructs.
9//===----------------------------------------------------------------------===//
10
11#include "clang/Sema/SemaHLSL.h"
12#include "clang/AST/ASTConsumer.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/Attr.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclBase.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/AST/DynamicRecursiveASTVisitor.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/HLSLResource.h"
22#include "clang/AST/MatrixUtils.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeBase.h"
25#include "clang/AST/TypeLoc.h"
26#include "clang/Basic/Builtins.h"
27#include "clang/Basic/DiagnosticSema.h"
28#include "clang/Basic/IdentifierTable.h"
29#include "clang/Basic/LLVM.h"
30#include "clang/Basic/SourceLocation.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Basic/TargetInfo.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedAttr.h"
36#include "clang/Sema/Sema.h"
37#include "clang/Sema/Template.h"
38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/SmallVector.h"
41#include "llvm/ADT/StringExtras.h"
42#include "llvm/ADT/StringRef.h"
43#include "llvm/ADT/Twine.h"
44#include "llvm/Frontend/HLSL/HLSLBinding.h"
45#include "llvm/Frontend/HLSL/RootSignatureValidations.h"
46#include "llvm/Support/Casting.h"
47#include "llvm/Support/DXILABI.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/FormatVariadic.h"
50#include "llvm/Support/raw_ostream.h"
51#include "llvm/TargetParser/Triple.h"
52#include <algorithm>
53#include <cmath>
54#include <cstddef>
55#include <iterator>
56#include <utility>
57
58using namespace clang;
59using namespace clang::hlsl;
60using llvm::hlsl::InterpolationModifier;
61using llvm::hlsl::IOType;
62using llvm::hlsl::SemanticStageInfo;
63using SemanticKind = llvm::dxbc::PSV::SemanticKind;
64using RegisterType = HLSLResourceBindingAttr::RegisterType;
65
66static CXXRecordDecl *createHostLayoutStruct(Sema &S,
67 CXXRecordDecl *StructDecl);
68
69static QualType getScalarComponentType(QualType T) {
70 if (const auto *VT = T->getAs<VectorType>())
71 return VT->getElementType();
72 if (const auto *MT = T->getAs<MatrixType>())
73 return MT->getElementType();
74 return T;
75}
76
77static RegisterType getRegisterType(ResourceClass RC) {
78 switch (RC) {
79 case ResourceClass::SRV:
80 return RegisterType::SRV;
81 case ResourceClass::UAV:
82 return RegisterType::UAV;
83 case ResourceClass::CBuffer:
84 return RegisterType::CBuffer;
85 case ResourceClass::Sampler:
86 return RegisterType::Sampler;
87 }
88 llvm_unreachable("unexpected ResourceClass value");
89}
90
91static RegisterType getRegisterType(const HLSLAttributedResourceType *ResTy) {
92 return getRegisterType(RC: ResTy->getAttrs().ResourceClass);
93}
94
95static LangAS getLangASFromResourceClass(ResourceClass RC) {
96 switch (RC) {
97 case ResourceClass::SRV:
98 case ResourceClass::UAV:
99 return LangAS::hlsl_device;
100 case ResourceClass::CBuffer:
101 return LangAS::hlsl_constant;
102 case ResourceClass::Sampler:
103 return LangAS::hlsl_device;
104 }
105 llvm_unreachable("unexpected ResourceClass value");
106}
107
108// Converts the first letter of string Slot to RegisterType.
109// Returns false if the letter does not correspond to a valid register type.
110static bool convertToRegisterType(StringRef Slot, RegisterType *RT) {
111 assert(RT != nullptr);
112 switch (Slot[0]) {
113 case 't':
114 case 'T':
115 *RT = RegisterType::SRV;
116 return true;
117 case 'u':
118 case 'U':
119 *RT = RegisterType::UAV;
120 return true;
121 case 'b':
122 case 'B':
123 *RT = RegisterType::CBuffer;
124 return true;
125 case 's':
126 case 'S':
127 *RT = RegisterType::Sampler;
128 return true;
129 case 'c':
130 case 'C':
131 *RT = RegisterType::C;
132 return true;
133 case 'i':
134 case 'I':
135 *RT = RegisterType::I;
136 return true;
137 default:
138 return false;
139 }
140}
141
142static char getRegisterTypeChar(RegisterType RT) {
143 switch (RT) {
144 case RegisterType::SRV:
145 return 't';
146 case RegisterType::UAV:
147 return 'u';
148 case RegisterType::CBuffer:
149 return 'b';
150 case RegisterType::Sampler:
151 return 's';
152 case RegisterType::C:
153 return 'c';
154 case RegisterType::I:
155 return 'i';
156 }
157 llvm_unreachable("unexpected RegisterType value");
158}
159
160static ResourceClass getResourceClass(RegisterType RT) {
161 switch (RT) {
162 case RegisterType::SRV:
163 return ResourceClass::SRV;
164 case RegisterType::UAV:
165 return ResourceClass::UAV;
166 case RegisterType::CBuffer:
167 return ResourceClass::CBuffer;
168 case RegisterType::Sampler:
169 return ResourceClass::Sampler;
170 case RegisterType::C:
171 case RegisterType::I:
172 // Deliberately falling through to the unreachable below.
173 break;
174 }
175 llvm_unreachable("unexpected RegisterType value");
176}
177
178static Builtin::ID getSpecConstBuiltinId(const Type *Type) {
179 const auto *BT = dyn_cast<BuiltinType>(Val: Type);
180 if (!BT) {
181 if (!Type->isEnumeralType())
182 return Builtin::NotBuiltin;
183 return Builtin::BI__builtin_get_spirv_spec_constant_int;
184 }
185
186 switch (BT->getKind()) {
187 case BuiltinType::Bool:
188 return Builtin::BI__builtin_get_spirv_spec_constant_bool;
189 case BuiltinType::Short:
190 return Builtin::BI__builtin_get_spirv_spec_constant_short;
191 case BuiltinType::Int:
192 return Builtin::BI__builtin_get_spirv_spec_constant_int;
193 case BuiltinType::LongLong:
194 return Builtin::BI__builtin_get_spirv_spec_constant_longlong;
195 case BuiltinType::UShort:
196 return Builtin::BI__builtin_get_spirv_spec_constant_ushort;
197 case BuiltinType::UInt:
198 return Builtin::BI__builtin_get_spirv_spec_constant_uint;
199 case BuiltinType::ULongLong:
200 return Builtin::BI__builtin_get_spirv_spec_constant_ulonglong;
201 case BuiltinType::Half:
202 return Builtin::BI__builtin_get_spirv_spec_constant_half;
203 case BuiltinType::Float:
204 return Builtin::BI__builtin_get_spirv_spec_constant_float;
205 case BuiltinType::Double:
206 return Builtin::BI__builtin_get_spirv_spec_constant_double;
207 default:
208 return Builtin::NotBuiltin;
209 }
210}
211
212static StringRef createRegisterString(ASTContext &AST, RegisterType RegType,
213 unsigned N) {
214 llvm::SmallString<16> Buffer;
215 llvm::raw_svector_ostream OS(Buffer);
216 OS << getRegisterTypeChar(RT: RegType);
217 OS << N;
218 return AST.backupStr(S: OS.str());
219}
220
221DeclBindingInfo *ResourceBindings::addDeclBindingInfo(const VarDecl *VD,
222 ResourceClass ResClass) {
223 assert(getDeclBindingInfo(VD, ResClass) == nullptr &&
224 "DeclBindingInfo already added");
225 assert(!hasBindingInfoForDecl(VD) || BindingsList.back().Decl == VD);
226 // VarDecl may have multiple entries for different resource classes.
227 // DeclToBindingListIndex stores the index of the first binding we saw
228 // for this decl. If there are any additional ones then that index
229 // shouldn't be updated.
230 DeclToBindingListIndex.try_emplace(Key: VD, Args: BindingsList.size());
231 return &BindingsList.emplace_back(Args&: VD, Args&: ResClass);
232}
233
234DeclBindingInfo *ResourceBindings::getDeclBindingInfo(const VarDecl *VD,
235 ResourceClass ResClass) {
236 auto Entry = DeclToBindingListIndex.find(Val: VD);
237 if (Entry != DeclToBindingListIndex.end()) {
238 for (unsigned Index = Entry->getSecond();
239 Index < BindingsList.size() && BindingsList[Index].Decl == VD;
240 ++Index) {
241 if (BindingsList[Index].ResClass == ResClass)
242 return &BindingsList[Index];
243 }
244 }
245 return nullptr;
246}
247
248bool ResourceBindings::hasBindingInfoForDecl(const VarDecl *VD) const {
249 return DeclToBindingListIndex.contains(Val: VD);
250}
251
252SemaHLSL::SemaHLSL(Sema &S) : SemaBase(S) {}
253
254Decl *SemaHLSL::ActOnStartBuffer(Scope *BufferScope, bool CBuffer,
255 SourceLocation KwLoc, IdentifierInfo *Ident,
256 SourceLocation IdentLoc,
257 SourceLocation LBrace) {
258 // For anonymous namespace, take the location of the left brace.
259 DeclContext *LexicalParent = SemaRef.getCurLexicalContext();
260 HLSLBufferDecl *Result = HLSLBufferDecl::Create(
261 C&: getASTContext(), LexicalParent, CBuffer, KwLoc, ID: Ident, IDLoc: IdentLoc, LBrace);
262
263 // if CBuffer is false, then it's a TBuffer
264 auto RC = CBuffer ? llvm::hlsl::ResourceClass::CBuffer
265 : llvm::hlsl::ResourceClass::SRV;
266 Result->addAttr(A: HLSLResourceClassAttr::CreateImplicit(Ctx&: getASTContext(), ResourceClass: RC));
267
268 SemaRef.PushOnScopeChains(D: Result, S: BufferScope);
269 SemaRef.PushDeclContext(S: BufferScope, DC: Result);
270
271 return Result;
272}
273
274static unsigned calculateLegacyCbufferFieldAlign(const ASTContext &Context,
275 QualType T) {
276 // Arrays, Matrices, and Structs are always aligned to new buffer rows
277 if (T->isArrayType() || T->isStructureType() || T->isConstantMatrixType())
278 return 16;
279
280 // Vectors are aligned to the type they contain
281 if (const VectorType *VT = T->getAs<VectorType>())
282 return calculateLegacyCbufferFieldAlign(Context, T: VT->getElementType());
283
284 assert(Context.getTypeSize(T) <= 64 &&
285 "Scalar bit widths larger than 64 not supported");
286
287 // Scalar types are aligned to their byte width
288 return Context.getTypeSize(T) / 8;
289}
290
291// Calculate the size of a legacy cbuffer type in bytes based on
292// https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-packing-rules
293static unsigned calculateLegacyCbufferSize(const ASTContext &Context,
294 QualType T) {
295 constexpr unsigned CBufferAlign = 16;
296 if (const auto *RD = T->getAsRecordDecl()) {
297 unsigned Size = 0;
298 for (const FieldDecl *Field : RD->fields()) {
299 QualType Ty = Field->getType();
300 unsigned FieldSize = calculateLegacyCbufferSize(Context, T: Ty);
301 unsigned FieldAlign = calculateLegacyCbufferFieldAlign(Context, T: Ty);
302
303 // If the field crosses the row boundary after alignment it drops to the
304 // next row
305 unsigned AlignSize = llvm::alignTo(Value: Size, Align: FieldAlign);
306 if ((AlignSize % CBufferAlign) + FieldSize > CBufferAlign) {
307 FieldAlign = CBufferAlign;
308 }
309
310 Size = llvm::alignTo(Value: Size, Align: FieldAlign);
311 Size += FieldSize;
312 }
313 return Size;
314 }
315
316 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
317 unsigned ElementCount = AT->getSize().getZExtValue();
318 if (ElementCount == 0)
319 return 0;
320
321 unsigned ElementSize =
322 calculateLegacyCbufferSize(Context, T: AT->getElementType());
323 unsigned AlignedElementSize = llvm::alignTo(Value: ElementSize, Align: CBufferAlign);
324 return AlignedElementSize * (ElementCount - 1) + ElementSize;
325 }
326
327 if (const VectorType *VT = T->getAs<VectorType>()) {
328 unsigned ElementCount = VT->getNumElements();
329 unsigned ElementSize =
330 calculateLegacyCbufferSize(Context, T: VT->getElementType());
331 return ElementSize * ElementCount;
332 }
333
334 return Context.getTypeSize(T) / 8;
335}
336
337// Validate packoffset:
338// - if packoffset it used it must be set on all declarations inside the buffer
339// - packoffset ranges must not overlap
340static void validatePackoffset(Sema &S, HLSLBufferDecl *BufDecl) {
341 llvm::SmallVector<std::pair<VarDecl *, HLSLPackOffsetAttr *>> PackOffsetVec;
342
343 // Make sure the packoffset annotations are either on all declarations
344 // or on none.
345 bool HasPackOffset = false;
346 bool HasNonPackOffset = false;
347 for (auto *Field : BufDecl->buffer_decls()) {
348 VarDecl *Var = dyn_cast<VarDecl>(Val: Field);
349 if (!Var)
350 continue;
351 if (Field->hasAttr<HLSLPackOffsetAttr>()) {
352 PackOffsetVec.emplace_back(Args&: Var, Args: Field->getAttr<HLSLPackOffsetAttr>());
353 HasPackOffset = true;
354 } else {
355 HasNonPackOffset = true;
356 }
357 }
358
359 if (!HasPackOffset)
360 return;
361
362 if (HasNonPackOffset)
363 S.Diag(Loc: BufDecl->getLocation(), DiagID: diag::warn_hlsl_packoffset_mix);
364
365 // Make sure there is no overlap in packoffset - sort PackOffsetVec by offset
366 // and compare adjacent values.
367 bool IsValid = true;
368 ASTContext &Context = S.getASTContext();
369 std::sort(first: PackOffsetVec.begin(), last: PackOffsetVec.end(),
370 comp: [](const std::pair<VarDecl *, HLSLPackOffsetAttr *> &LHS,
371 const std::pair<VarDecl *, HLSLPackOffsetAttr *> &RHS) {
372 return LHS.second->getOffsetInBytes() <
373 RHS.second->getOffsetInBytes();
374 });
375 for (unsigned i = 0; i < PackOffsetVec.size() - 1; i++) {
376 VarDecl *Var = PackOffsetVec[i].first;
377 HLSLPackOffsetAttr *Attr = PackOffsetVec[i].second;
378 unsigned Size = calculateLegacyCbufferSize(Context, T: Var->getType());
379 unsigned Begin = Attr->getOffsetInBytes();
380 unsigned End = Begin + Size;
381 unsigned NextBegin = PackOffsetVec[i + 1].second->getOffsetInBytes();
382 if (End > NextBegin) {
383 VarDecl *NextVar = PackOffsetVec[i + 1].first;
384 S.Diag(Loc: NextVar->getLocation(), DiagID: diag::err_hlsl_packoffset_overlap)
385 << NextVar << Var;
386 IsValid = false;
387 }
388 }
389 BufDecl->setHasValidPackoffset(IsValid);
390}
391
392// Returns true if the array has a zero size = if any of the dimensions is 0
393static bool isZeroSizedArray(const ConstantArrayType *CAT) {
394 while (CAT && !CAT->isZeroSize())
395 CAT = dyn_cast<ConstantArrayType>(
396 Val: CAT->getElementType()->getUnqualifiedDesugaredType());
397 return CAT != nullptr;
398}
399
400static bool isResourceRecordTypeOrArrayOf(QualType Ty) {
401 return Ty->isHLSLResourceRecord() || Ty->isHLSLResourceRecordArray();
402}
403
404static bool isResourceRecordTypeOrArrayOf(VarDecl *VD) {
405 return isResourceRecordTypeOrArrayOf(Ty: VD->getType());
406}
407
408static const HLSLAttributedResourceType *
409getResourceArrayHandleType(QualType QT) {
410 assert(QT->isHLSLResourceRecordArray() &&
411 "expected array of resource records");
412 const Type *Ty = QT->getUnqualifiedDesugaredType();
413 while (const ArrayType *AT = dyn_cast<ArrayType>(Val: Ty))
414 Ty = AT->getArrayElementTypeNoTypeQual()->getUnqualifiedDesugaredType();
415 return HLSLAttributedResourceType::findHandleTypeOnResource(RT: Ty);
416}
417
418static const HLSLAttributedResourceType *
419getResourceArrayHandleType(VarDecl *VD) {
420 return getResourceArrayHandleType(QT: VD->getType());
421}
422
423// Returns true if the type is a leaf element type that is not valid to be
424// included in HLSL Buffer, such as a resource class, empty struct, zero-sized
425// array, or a builtin intangible type. Returns false it is a valid leaf element
426// type or if it is a record type that needs to be inspected further.
427static bool isInvalidConstantBufferLeafElementType(const Type *Ty) {
428 Ty = Ty->getUnqualifiedDesugaredType();
429 if (Ty->isHLSLResourceRecord() || Ty->isHLSLResourceRecordArray())
430 return true;
431 if (const auto *RD = Ty->getAsCXXRecordDecl())
432 return RD->isEmpty();
433 if (Ty->isConstantArrayType() &&
434 isZeroSizedArray(CAT: cast<ConstantArrayType>(Val: Ty)))
435 return true;
436 if (Ty->isHLSLBuiltinIntangibleType() || Ty->isHLSLAttributedResourceType())
437 return true;
438 return false;
439}
440
441// Returns true if the struct contains at least one element that prevents it
442// from being included inside HLSL Buffer as is, such as an intangible type,
443// empty struct, or zero-sized array. If it does, a new implicit layout struct
444// needs to be created for HLSL Buffer use that will exclude these unwanted
445// declarations (see createHostLayoutStruct function).
446static bool requiresImplicitBufferLayoutStructure(const CXXRecordDecl *RD) {
447 if (RD->isHLSLIntangible() || RD->isEmpty())
448 return true;
449 // check fields
450 for (const FieldDecl *Field : RD->fields()) {
451 QualType Ty = Field->getType();
452 if (isInvalidConstantBufferLeafElementType(Ty: Ty.getTypePtr()))
453 return true;
454 if (const auto *RD = Ty->getAsCXXRecordDecl();
455 RD && requiresImplicitBufferLayoutStructure(RD))
456 return true;
457 }
458 // check bases
459 for (const CXXBaseSpecifier &Base : RD->bases())
460 if (requiresImplicitBufferLayoutStructure(
461 RD: Base.getType()->castAsCXXRecordDecl()))
462 return true;
463 return false;
464}
465
466static CXXRecordDecl *findRecordDeclInContext(IdentifierInfo *II,
467 DeclContext *DC) {
468 CXXRecordDecl *RD = nullptr;
469 for (NamedDecl *Decl :
470 DC->getNonTransparentContext()->lookup(Name: DeclarationName(II))) {
471 if (CXXRecordDecl *FoundRD = dyn_cast<CXXRecordDecl>(Val: Decl)) {
472 assert(RD == nullptr &&
473 "there should be at most 1 record by a given name in a scope");
474 RD = FoundRD;
475 }
476 }
477 return RD;
478}
479
480// Creates a name for buffer layout struct using the provide name base.
481// If the name must be unique (not previously defined), a suffix is added
482// until a unique name is found.
483static IdentifierInfo *getHostLayoutStructName(Sema &S, NamedDecl *BaseDecl,
484 bool MustBeUnique) {
485 ASTContext &AST = S.getASTContext();
486
487 IdentifierInfo *NameBaseII = BaseDecl->getIdentifier();
488 llvm::SmallString<64> Name("__cblayout_");
489 if (NameBaseII) {
490 Name.append(RHS: NameBaseII->getName());
491 } else {
492 // anonymous struct
493 Name.append(RHS: "anon");
494 MustBeUnique = true;
495 }
496
497 size_t NameLength = Name.size();
498 IdentifierInfo *II = &AST.Idents.get(Name, TokenCode: tok::TokenKind::identifier);
499 if (!MustBeUnique)
500 return II;
501
502 unsigned suffix = 0;
503 while (true) {
504 if (suffix != 0) {
505 Name.append(RHS: "_");
506 Name.append(RHS: llvm::Twine(suffix).str());
507 II = &AST.Idents.get(Name, TokenCode: tok::TokenKind::identifier);
508 }
509 if (!findRecordDeclInContext(II, DC: BaseDecl->getDeclContext()))
510 return II;
511 // declaration with that name already exists - increment suffix and try
512 // again until unique name is found
513 suffix++;
514 Name.truncate(N: NameLength);
515 };
516}
517
518static const Type *createHostLayoutType(Sema &S, const Type *Ty) {
519 ASTContext &AST = S.getASTContext();
520 if (auto *RD = Ty->getAsCXXRecordDecl()) {
521 if (!requiresImplicitBufferLayoutStructure(RD))
522 return Ty;
523 RD = createHostLayoutStruct(S, StructDecl: RD);
524 if (!RD)
525 return nullptr;
526 return AST.getCanonicalTagType(TD: RD)->getTypePtr();
527 }
528
529 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: Ty)) {
530 const Type *ElementTy = createHostLayoutType(
531 S, Ty: CAT->getElementType()->getUnqualifiedDesugaredType());
532 if (!ElementTy)
533 return nullptr;
534 return AST
535 .getConstantArrayType(EltTy: QualType(ElementTy, 0), ArySize: CAT->getSize(), SizeExpr: nullptr,
536 ASM: CAT->getSizeModifier(),
537 IndexTypeQuals: CAT->getIndexTypeCVRQualifiers())
538 .getTypePtr();
539 }
540 return Ty;
541}
542
543// Returns the type to use for a host layout struct field. For most types this
544// is the unqualified desugared type. Matrix types, however, retain their sugar
545// so that the row_major/column_major orientation (carried as an AttributedType)
546// is preserved; the orientation determines the in-memory cbuffer layout.
547static const Type *getHostLayoutFieldType(QualType QT) {
548 const Type *Desugared = QT->getUnqualifiedDesugaredType();
549 if (Desugared->isConstantMatrixType())
550 return QT.getTypePtr();
551 return Desugared;
552}
553
554// Creates a field declaration of given name and type for HLSL buffer layout
555// struct. Returns nullptr if the type cannot be use in HLSL Buffer layout.
556static FieldDecl *createFieldForHostLayoutStruct(Sema &S, const Type *Ty,
557 IdentifierInfo *II,
558 CXXRecordDecl *LayoutStruct) {
559 if (isInvalidConstantBufferLeafElementType(Ty))
560 return nullptr;
561
562 Ty = createHostLayoutType(S, Ty);
563 if (!Ty)
564 return nullptr;
565
566 QualType QT = QualType(Ty, 0);
567 ASTContext &AST = S.getASTContext();
568 TypeSourceInfo *TSI = AST.getTrivialTypeSourceInfo(T: QT, Loc: SourceLocation());
569 auto *Field = FieldDecl::Create(C: AST, DC: LayoutStruct, StartLoc: SourceLocation(),
570 IdLoc: SourceLocation(), Id: II, T: QT, TInfo: TSI, BW: nullptr, Mutable: false,
571 InitStyle: InClassInitStyle::ICIS_NoInit);
572 Field->setAccess(AccessSpecifier::AS_public);
573 return Field;
574}
575
576// Creates host layout struct for a struct included in HLSL Buffer.
577// The layout struct will include only fields that are allowed in HLSL buffer.
578// These fields will be filtered out:
579// - resource classes
580// - empty structs
581// - zero-sized arrays
582// Returns nullptr if the resulting layout struct would be empty.
583static CXXRecordDecl *createHostLayoutStruct(Sema &S,
584 CXXRecordDecl *StructDecl) {
585 assert(requiresImplicitBufferLayoutStructure(StructDecl) &&
586 "struct is already HLSL buffer compatible");
587
588 ASTContext &AST = S.getASTContext();
589 DeclContext *DC = StructDecl->getDeclContext();
590 IdentifierInfo *II = getHostLayoutStructName(S, BaseDecl: StructDecl, MustBeUnique: false);
591
592 // reuse existing if the layout struct if it already exists
593 if (CXXRecordDecl *RD = findRecordDeclInContext(II, DC))
594 return RD;
595
596 CXXRecordDecl *LS =
597 CXXRecordDecl::Create(C: AST, TK: TagDecl::TagKind::Struct, DC, StartLoc: SourceLocation(),
598 IdLoc: SourceLocation(), Id: II);
599 LS->setImplicit(true);
600 LS->addAttr(A: PackedAttr::CreateImplicit(Ctx&: AST));
601 LS->startDefinition();
602
603 // copy base struct, create HLSL Buffer compatible version if needed
604 if (unsigned NumBases = StructDecl->getNumBases()) {
605 assert(NumBases == 1 && "HLSL supports only one base type");
606 (void)NumBases;
607 CXXBaseSpecifier Base = *StructDecl->bases_begin();
608 CXXRecordDecl *BaseDecl = Base.getType()->castAsCXXRecordDecl();
609 if (requiresImplicitBufferLayoutStructure(RD: BaseDecl)) {
610 BaseDecl = createHostLayoutStruct(S, StructDecl: BaseDecl);
611 if (BaseDecl) {
612 TypeSourceInfo *TSI =
613 AST.getTrivialTypeSourceInfo(T: AST.getCanonicalTagType(TD: BaseDecl));
614 Base = CXXBaseSpecifier(SourceRange(), false, StructDecl->isClass(),
615 AS_none, TSI, SourceLocation());
616 }
617 }
618 if (BaseDecl) {
619 const CXXBaseSpecifier *BasesArray[1] = {&Base};
620 LS->setBases(Bases: BasesArray, NumBases: 1);
621 }
622 }
623
624 // filter struct fields
625 for (const FieldDecl *FD : StructDecl->fields()) {
626 const Type *Ty = getHostLayoutFieldType(QT: FD->getType());
627 if (FieldDecl *NewFD =
628 createFieldForHostLayoutStruct(S, Ty, II: FD->getIdentifier(), LayoutStruct: LS))
629 LS->addDecl(D: NewFD);
630 }
631 LS->completeDefinition();
632
633 if (LS->field_empty() && LS->getNumBases() == 0)
634 return nullptr;
635
636 DC->addDecl(D: LS);
637 return LS;
638}
639
640// Creates host layout struct for HLSL Buffer. The struct will include only
641// fields of types that are allowed in HLSL buffer and it will filter out:
642// - static or groupshared variable declarations
643// - resource classes
644// - empty structs
645// - zero-sized arrays
646// - non-variable declarations
647// The layout struct will be added to the HLSLBufferDecl declarations.
648static void createHostLayoutStructForBuffer(Sema &S, HLSLBufferDecl *BufDecl) {
649 ASTContext &AST = S.getASTContext();
650 IdentifierInfo *II = getHostLayoutStructName(S, BaseDecl: BufDecl, MustBeUnique: true);
651
652 CXXRecordDecl *LS =
653 CXXRecordDecl::Create(C: AST, TK: TagDecl::TagKind::Struct, DC: BufDecl,
654 StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: II);
655 LS->addAttr(A: PackedAttr::CreateImplicit(Ctx&: AST));
656 LS->setImplicit(true);
657 LS->startDefinition();
658
659 for (Decl *D : BufDecl->buffer_decls()) {
660 VarDecl *VD = dyn_cast<VarDecl>(Val: D);
661 if (!VD || VD->getStorageClass() == SC_Static ||
662 VD->getType().getAddressSpace() == LangAS::hlsl_groupshared)
663 continue;
664 const Type *Ty = getHostLayoutFieldType(QT: VD->getType());
665
666 FieldDecl *FD =
667 createFieldForHostLayoutStruct(S, Ty, II: VD->getIdentifier(), LayoutStruct: LS);
668 // Declarations collected for the default $Globals constant buffer have
669 // already been checked to have non-empty cbuffer layout, so
670 // createFieldForHostLayoutStruct should always succeed. These declarations
671 // already have their address space set to hlsl_constant.
672 // For declarations in a named cbuffer block
673 // createFieldForHostLayoutStruct can still return nullptr if the type
674 // is empty (does not have a cbuffer layout).
675 assert((FD || VD->getType().getAddressSpace() != LangAS::hlsl_constant) &&
676 "host layout field for $Globals decl failed to be created");
677 if (FD) {
678 // Add the field decl to the layout struct.
679 LS->addDecl(D: FD);
680 if (VD->getType().getAddressSpace() != LangAS::hlsl_constant) {
681 // Update address space of the original decl to hlsl_constant.
682 QualType NewTy =
683 AST.getAddrSpaceQualType(T: VD->getType(), AddressSpace: LangAS::hlsl_constant);
684 VD->setType(NewTy);
685 }
686 }
687 }
688 LS->completeDefinition();
689 BufDecl->addLayoutStruct(LS);
690}
691
692static void addImplicitBindingAttrToDecl(Sema &S, Decl *D, RegisterType RT,
693 uint32_t ImplicitBindingOrderID) {
694 auto *Attr =
695 HLSLResourceBindingAttr::CreateImplicit(Ctx&: S.getASTContext(), Slot: "", Space: "0", Range: {});
696 Attr->setBinding(RT, SlotNum: std::nullopt, SpaceNum: 0);
697 Attr->setImplicitBindingOrderID(ImplicitBindingOrderID);
698 D->addAttr(A: Attr);
699}
700
701// Handle end of cbuffer/tbuffer declaration
702void SemaHLSL::ActOnFinishBuffer(Decl *Dcl, SourceLocation RBrace) {
703 auto *BufDecl = cast<HLSLBufferDecl>(Val: Dcl);
704 BufDecl->setRBraceLoc(RBrace);
705
706 validatePackoffset(S&: SemaRef, BufDecl);
707
708 createHostLayoutStructForBuffer(S&: SemaRef, BufDecl);
709
710 // Handle implicit binding if needed.
711 ResourceBindingAttrs ResourceAttrs(Dcl);
712 if (!ResourceAttrs.isExplicit()) {
713 SemaRef.Diag(Loc: Dcl->getLocation(), DiagID: diag::warn_hlsl_implicit_binding);
714 // Use HLSLResourceBindingAttr to transfer implicit binding order_ID
715 // to codegen. If it does not exist, create an implicit attribute.
716 uint32_t OrderID = getNextImplicitBindingOrderID();
717 if (ResourceAttrs.hasBinding())
718 ResourceAttrs.setImplicitOrderID(OrderID);
719 else
720 addImplicitBindingAttrToDecl(S&: SemaRef, D: BufDecl,
721 RT: BufDecl->isCBuffer() ? RegisterType::CBuffer
722 : RegisterType::SRV,
723 ImplicitBindingOrderID: OrderID);
724 }
725
726 SemaRef.PopDeclContext();
727}
728
729HLSLNumThreadsAttr *SemaHLSL::mergeNumThreadsAttr(Decl *D,
730 const AttributeCommonInfo &AL,
731 int X, int Y, int Z) {
732 if (HLSLNumThreadsAttr *NT = D->getAttr<HLSLNumThreadsAttr>()) {
733 if (NT->getX() != X || NT->getY() != Y || NT->getZ() != Z) {
734 Diag(Loc: NT->getLocation(), DiagID: diag::err_hlsl_attribute_param_mismatch) << AL;
735 Diag(Loc: AL.getLoc(), DiagID: diag::note_conflicting_attribute);
736 }
737 return nullptr;
738 }
739 return ::new (getASTContext())
740 HLSLNumThreadsAttr(getASTContext(), AL, X, Y, Z);
741}
742
743HLSLWaveSizeAttr *SemaHLSL::mergeWaveSizeAttr(Decl *D,
744 const AttributeCommonInfo &AL,
745 int Min, int Max, int Preferred,
746 int SpelledArgsCount) {
747 if (HLSLWaveSizeAttr *WS = D->getAttr<HLSLWaveSizeAttr>()) {
748 if (WS->getMin() != Min || WS->getMax() != Max ||
749 WS->getPreferred() != Preferred ||
750 WS->getSpelledArgsCount() != SpelledArgsCount) {
751 Diag(Loc: WS->getLocation(), DiagID: diag::err_hlsl_attribute_param_mismatch) << AL;
752 Diag(Loc: AL.getLoc(), DiagID: diag::note_conflicting_attribute);
753 }
754 return nullptr;
755 }
756 HLSLWaveSizeAttr *Result = ::new (getASTContext())
757 HLSLWaveSizeAttr(getASTContext(), AL, Min, Max, Preferred);
758 Result->setSpelledArgsCount(SpelledArgsCount);
759 return Result;
760}
761
762HLSLVkConstantIdAttr *
763SemaHLSL::mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL,
764 int Id) {
765
766 auto &TargetInfo = getASTContext().getTargetInfo();
767 if (TargetInfo.getTriple().getArch() != llvm::Triple::spirv) {
768 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_ignored) << AL;
769 return nullptr;
770 }
771
772 auto *VD = cast<VarDecl>(Val: D);
773
774 if (getSpecConstBuiltinId(Type: VD->getType()->getUnqualifiedDesugaredType()) ==
775 Builtin::NotBuiltin) {
776 Diag(Loc: VD->getLocation(), DiagID: diag::err_specialization_const);
777 return nullptr;
778 }
779
780 if (!VD->getType().isConstQualified()) {
781 Diag(Loc: VD->getLocation(), DiagID: diag::err_specialization_const);
782 return nullptr;
783 }
784
785 if (HLSLVkConstantIdAttr *CI = D->getAttr<HLSLVkConstantIdAttr>()) {
786 if (CI->getId() != Id) {
787 Diag(Loc: CI->getLocation(), DiagID: diag::err_hlsl_attribute_param_mismatch) << AL;
788 Diag(Loc: AL.getLoc(), DiagID: diag::note_conflicting_attribute);
789 }
790 return nullptr;
791 }
792
793 HLSLVkConstantIdAttr *Result =
794 ::new (getASTContext()) HLSLVkConstantIdAttr(getASTContext(), AL, Id);
795 return Result;
796}
797
798HLSLShaderAttr *
799SemaHLSL::mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL,
800 llvm::Triple::EnvironmentType ShaderType) {
801 if (HLSLShaderAttr *NT = D->getAttr<HLSLShaderAttr>()) {
802 if (NT->getType() != ShaderType) {
803 Diag(Loc: NT->getLocation(), DiagID: diag::err_hlsl_attribute_param_mismatch) << AL;
804 Diag(Loc: AL.getLoc(), DiagID: diag::note_conflicting_attribute);
805 }
806 return nullptr;
807 }
808 return HLSLShaderAttr::Create(Ctx&: getASTContext(), Type: ShaderType, CommonInfo: AL);
809}
810
811HLSLParamModifierAttr *
812SemaHLSL::mergeParamModifierAttr(Decl *D, const AttributeCommonInfo &AL,
813 HLSLParamModifierAttr::Spelling Spelling) {
814 // We can only merge an `in` attribute with an `out` attribute. All other
815 // combinations of duplicated attributes are ill-formed.
816 if (HLSLParamModifierAttr *PA = D->getAttr<HLSLParamModifierAttr>()) {
817 if ((PA->isIn() && Spelling == HLSLParamModifierAttr::Keyword_out) ||
818 (PA->isOut() && Spelling == HLSLParamModifierAttr::Keyword_in)) {
819 D->dropAttr<HLSLParamModifierAttr>();
820 SourceRange AdjustedRange = {PA->getLocation(), AL.getRange().getEnd()};
821 return HLSLParamModifierAttr::Create(
822 Ctx&: getASTContext(), /*MergedSpelling=*/true, Range: AdjustedRange,
823 S: HLSLParamModifierAttr::Keyword_inout);
824 }
825 Diag(Loc: AL.getLoc(), DiagID: diag::err_hlsl_duplicate_parameter_modifier) << AL;
826 Diag(Loc: PA->getLocation(), DiagID: diag::note_conflicting_attribute);
827 return nullptr;
828 }
829 return HLSLParamModifierAttr::Create(Ctx&: getASTContext(), CommonInfo: AL);
830}
831
832void SemaHLSL::handleInterpolationModifierAttr(Decl *D, const ParsedAttr &AL) {
833 InterpolationModifier Modifier;
834 switch (static_cast<HLSLInterpolationModifierAttr::Spelling>(
835 AL.getSemanticSpelling())) {
836 case HLSLInterpolationModifierAttr::Keyword_nointerpolation:
837 Modifier = InterpolationModifier::NoInterpolation;
838 break;
839 case HLSLInterpolationModifierAttr::Keyword_linear:
840 Modifier = InterpolationModifier::Linear;
841 break;
842 case HLSLInterpolationModifierAttr::Keyword_centroid:
843 Modifier = InterpolationModifier::Centroid;
844 break;
845 case HLSLInterpolationModifierAttr::Keyword_noperspective:
846 Modifier = InterpolationModifier::NoPerspective;
847 break;
848 case HLSLInterpolationModifierAttr::Keyword_sample:
849 Modifier = InterpolationModifier::Sample;
850 break;
851 case HLSLInterpolationModifierAttr::Keyword_center:
852 Modifier = InterpolationModifier::Center;
853 break;
854 case HLSLInterpolationModifierAttr::SpellingNotCalculated:
855 llvm_unreachable("interpolation modifier spelling was not calculated");
856 }
857
858 InterpolationModifier Modifiers = Modifier;
859 if (auto *Previous = D->getAttr<HLSLInterpolationModifierAttr>()) {
860 auto Old = static_cast<InterpolationModifier>(Previous->getModifiers());
861 Modifiers |= Old;
862 if (any(Val: Old & Modifier)) {
863 Diag(Loc: AL.getLoc(), DiagID: diag::warn_hlsl_duplicate_interpolation) << AL;
864 } else if (llvm::hlsl::getInterpolationMode(Modifiers) ==
865 llvm::dxbc::PSV::InterpolationMode::Invalid &&
866 llvm::hlsl::getInterpolationMode(Modifiers: Old) !=
867 llvm::dxbc::PSV::InterpolationMode::Invalid) {
868 Diag(Loc: AL.getLoc(), DiagID: diag::err_hlsl_interpolation_conflict);
869 Diag(Loc: Previous->getLocation(), DiagID: diag::note_conflicting_attribute);
870 D->setInvalidDecl();
871 } else {
872 InterpolationModifier OldLocation =
873 llvm::hlsl::getInterpolationSamplingLocation(Modifiers: Old);
874 InterpolationModifier NewLocation =
875 llvm::hlsl::getInterpolationSamplingLocation(Modifiers: Modifier);
876 if (any(Val: OldLocation) && any(Val: NewLocation)) {
877 Diag(Loc: AL.getLoc(), DiagID: diag::warn_hlsl_interpolation_override)
878 << (std::max(a: OldLocation, b: NewLocation) ==
879 InterpolationModifier::Sample)
880 << (std::min(a: OldLocation, b: NewLocation) ==
881 InterpolationModifier::Centroid);
882 }
883 }
884 D->dropAttr<HLSLInterpolationModifierAttr>();
885 }
886 D->addAttr(A: HLSLInterpolationModifierAttr::Create(
887 Ctx&: getASTContext(), Modifiers: static_cast<unsigned>(Modifiers), CommonInfo: AL));
888}
889
890bool SemaHLSL::checkInterpolationModifiers(
891 const DeclaratorDecl *D, const HLSLInterpolationModifierAttr *Inherited,
892 const HLSLParsedSemanticAttr *Semantic) {
893 if (D->isInvalidDecl())
894 return false;
895 const auto *A = D->getAttr<HLSLInterpolationModifierAttr>();
896 if (!A)
897 A = Inherited;
898 if (!Semantic)
899 Semantic = D->getAttr<HLSLParsedSemanticAttr>();
900
901 const auto *FD = dyn_cast<FunctionDecl>(Val: D);
902 QualType T = FD ? FD->getReturnType() : D->getType();
903 T = getASTContext().getBaseElementType(QT: T.getNonReferenceType());
904 if (T->isDependentType())
905 return true;
906 if (const auto *RT = T->getAs<RecordType>()) {
907 const RecordDecl *RD = RT->getDecl()->getDefinition();
908 if (!RD)
909 return true;
910 bool Valid = true;
911 for (const FieldDecl *Field : RD->fields())
912 Valid &= checkInterpolationModifiers(D: Field, Inherited: A, Semantic);
913 return Valid;
914 }
915 if (!A)
916 return true;
917
918 auto Modifiers = static_cast<InterpolationModifier>(A->getModifiers());
919 if (Modifiers == InterpolationModifier::NoInterpolation) {
920 if (!Semantic)
921 return true;
922 SemanticKind Kind =
923 llvm::hlsl::getSemanticKind(SemanticName: Semantic->getSemanticName());
924 if (Kind != SemanticKind::Position && Kind != SemanticKind::Barycentrics)
925 return true;
926 Diag(Loc: A->getLocation(), DiagID: diag::err_hlsl_interpolation_semantic)
927 << Semantic->getSemanticName();
928 Diag(Loc: Semantic->getLocation(), DiagID: diag::note_conflicting_attribute);
929 return false;
930 }
931
932 T = getScalarComponentType(T);
933 if (T->isIntegerType() ||
934 (T->isRealFloatingType() && getASTContext().getTypeSize(T) > 32)) {
935 Diag(Loc: A->getLocation(), DiagID: diag::err_hlsl_interpolation_type) << T;
936 return false;
937 }
938 return true;
939}
940
941void SemaHLSL::ActOnTopLevelFunction(FunctionDecl *FD) {
942 auto &TargetInfo = getASTContext().getTargetInfo();
943
944 if (FD->getName() != TargetInfo.getTargetOpts().HLSLEntry)
945 return;
946
947 // If we have specified a root signature to override the entry function then
948 // attach it now
949 HLSLRootSignatureDecl *SignatureDecl =
950 lookupRootSignatureOverrideDecl(DC: FD->getDeclContext());
951 if (SignatureDecl) {
952 FD->dropAttr<RootSignatureAttr>();
953 // We could look up the SourceRange of the macro here as well
954 AttributeCommonInfo AL(RootSigOverrideIdent, AttributeScopeInfo(),
955 SourceRange(), ParsedAttr::Form::Microsoft());
956 FD->addAttr(A: ::new (getASTContext()) RootSignatureAttr(
957 getASTContext(), AL, RootSigOverrideIdent, SignatureDecl));
958 }
959
960 llvm::Triple::EnvironmentType Env = TargetInfo.getTriple().getEnvironment();
961 if (HLSLShaderAttr::isValidShaderType(ShaderType: Env) && Env != llvm::Triple::Library) {
962 if (const auto *Shader = FD->getAttr<HLSLShaderAttr>()) {
963 // The entry point is already annotated - check that it matches the
964 // triple.
965 if (Shader->getType() != Env) {
966 Diag(Loc: Shader->getLocation(), DiagID: diag::err_hlsl_entry_shader_attr_mismatch)
967 << Shader;
968 FD->setInvalidDecl();
969 }
970 } else {
971 // Implicitly add the shader attribute if the entry function isn't
972 // explicitly annotated.
973 FD->addAttr(A: HLSLShaderAttr::CreateImplicit(Ctx&: getASTContext(), Type: Env,
974 Range: FD->getBeginLoc()));
975 }
976 } else {
977 switch (Env) {
978 case llvm::Triple::UnknownEnvironment:
979 case llvm::Triple::Library:
980 break;
981 case llvm::Triple::RootSignature:
982 llvm_unreachable("rootsig environment has no functions");
983 default:
984 llvm_unreachable("Unhandled environment in triple");
985 }
986 }
987}
988
989static bool isVkPipelineBuiltin(const ASTContext &AstContext, FunctionDecl *FD,
990 const DeclaratorDecl *D,
991 HLSLAppliedSemanticAttr *Semantic,
992 bool IsInput) {
993 // Explicitly annotated built-ins skip location assignment
994 if (D->hasAttr<HLSLVkBuiltInAttr>())
995 return true;
996
997 if (AstContext.getTargetInfo().getTriple().getOS() != llvm::Triple::Vulkan)
998 return false;
999
1000 const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>();
1001 assert(ShaderAttr && "Entry point has no shader attribute");
1002 llvm::Triple::EnvironmentType ST = ShaderAttr->getType();
1003 SemanticKind Kind = llvm::hlsl::getSemanticKind(SemanticName: Semantic->getSemanticName());
1004
1005 switch (Kind) {
1006 case SemanticKind::Position:
1007 // The SV_Position semantic is lowered to:
1008 // - Position built-in for vertex output.
1009 // - FragCoord built-in for fragment input.
1010 return (ST == llvm::Triple::Vertex && !IsInput) ||
1011 (ST == llvm::Triple::Pixel && IsInput);
1012 case SemanticKind::VertexID:
1013 return true;
1014 case SemanticKind::InstanceID:
1015 return ST == llvm::Triple::Vertex && IsInput;
1016 case SemanticKind::IsFrontFace:
1017 return ST == llvm::Triple::Pixel && IsInput;
1018 case SemanticKind::ShadingRate:
1019 // Lowered to:
1020 // - ShadingRateKHR built-in for fragment input.
1021 // - PrimitiveShadingRateKHR built-in for vertex output.
1022 // TODO: extend to mesh
1023 return (ST == llvm::Triple::Pixel && IsInput) ||
1024 (ST == llvm::Triple::Vertex && !IsInput);
1025 case SemanticKind::Barycentrics:
1026 case SemanticKind::SampleIndex:
1027 case SemanticKind::PrimitiveID:
1028 return ST == llvm::Triple::Pixel && IsInput;
1029 case SemanticKind::StartVertexLocation:
1030 case SemanticKind::StartInstanceLocation:
1031 return ST == llvm::Triple::Vertex && IsInput;
1032 case SemanticKind::ViewID:
1033 return IsInput;
1034 default:
1035 return false;
1036 }
1037}
1038
1039static void validateVkBuiltinUsage(Sema &S, FunctionDecl *FD,
1040 const DeclaratorDecl *D,
1041 const HLSLVkBuiltInAttr *Attr,
1042 IOType CurrentIOType) {
1043 const ASTContext &AstContext = S.getASTContext();
1044 if (AstContext.getTargetInfo().getTriple().getOS() != llvm::Triple::Vulkan)
1045 return;
1046
1047 StringRef BuiltIn = Attr->getBuiltIn();
1048
1049 QualType T =
1050 (D == FD ? FD->getReturnType() : D->getType()).getNonReferenceType();
1051 const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>();
1052 assert(ShaderAttr && "Entry point has no shader attribute");
1053 llvm::Triple::EnvironmentType Stage = ShaderAttr->getType();
1054 bool IsIn = any(Val: CurrentIOType & IOType::In);
1055 bool IsOut = any(Val: CurrentIOType & IOType::Out);
1056
1057 if (BuiltIn == "PointSize") {
1058 // Vulkan requires PointSize to be a 32-bit float
1059 // (VUID-PointSize-PointSize-04317). Without native 16-bit types, `half` is
1060 // lowered to a 32-bit float, so it is accepted as well.
1061 bool Is32BitFloat = T->isSpecificBuiltinType(K: BuiltinType::Float) ||
1062 (T->isSpecificBuiltinType(K: BuiltinType::Half) &&
1063 !AstContext.getLangOpts().NativeHalfType);
1064 if (!Is32BitFloat)
1065 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_hlsl_vk_builtin_wrong_type)
1066 << BuiltIn << S.getASTContext().FloatTy;
1067
1068 // PointSize is a per-vertex value, so patch-constant (hull/domain)
1069 // and per-primitive (mesh) data never carries it.
1070 // Note: Sema does not set this bit yet.
1071 bool IsPatchConstantOrPrimitive =
1072 any(Val: CurrentIOType & IOType::PatchConstantOrPrimitive);
1073 bool LegalStage =
1074 !IsPatchConstantOrPrimitive &&
1075 ((Stage == llvm::Triple::Vertex && IsOut) ||
1076 Stage == llvm::Triple::Hull || Stage == llvm::Triple::Domain ||
1077 Stage == llvm::Triple::Geometry ||
1078 (Stage == llvm::Triple::Mesh && IsOut));
1079 if (!LegalStage) {
1080 StringRef IOTypeName = (IsIn && IsOut) ? "inputs and outputs"
1081 : IsIn ? "inputs"
1082 : "outputs";
1083 S.Diag(Loc: Attr->getLocation(), DiagID: diag::err_hlsl_vk_builtin_wrong_stage)
1084 << BuiltIn << llvm::Triple::getEnvironmentTypeName(Kind: Stage)
1085 << IOTypeName;
1086 }
1087 }
1088}
1089
1090bool SemaHLSL::determineActiveSemanticOnScalar(FunctionDecl *FD,
1091 DeclaratorDecl *OutputDecl,
1092 DeclaratorDecl *D,
1093 SemanticInfo &ActiveSemantic,
1094 SemaHLSL::SemanticContext &SC) {
1095 if (ActiveSemantic.Semantic == nullptr) {
1096 ActiveSemantic.Semantic = D->getAttr<HLSLParsedSemanticAttr>();
1097 if (ActiveSemantic.Semantic)
1098 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1099 }
1100
1101 if (!ActiveSemantic.Semantic) {
1102 Diag(Loc: D->getLocation(), DiagID: diag::err_hlsl_missing_semantic_annotation);
1103 return false;
1104 }
1105
1106 auto *A = ::new (getASTContext())
1107 HLSLAppliedSemanticAttr(getASTContext(), *ActiveSemantic.Semantic,
1108 ActiveSemantic.Semantic->getAttrName()->getName(),
1109 ActiveSemantic.Index.value_or(u: 0));
1110 if (!A)
1111 return false;
1112
1113 // Each array element occupies a separate semantic index.
1114 QualType T = D == FD ? FD->getReturnType() : D->getType();
1115 const ConstantArrayType *AT =
1116 getASTContext().getAsConstantArrayType(T: T.getNonReferenceType());
1117 if (isZeroSizedArray(CAT: AT)) {
1118 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_zero_sized_array)
1119 << A->getAttrName();
1120 return false;
1121 }
1122 unsigned ElementCount = AT ? ASTContext::getConstantArrayElementCount(CA: AT) : 1;
1123
1124 // Each matrix row (or column for column_major) also occupies a separate
1125 // semantic index.
1126 QualType BaseTy = getASTContext().getBaseElementType(QT: T.getNonReferenceType());
1127 if (const auto *MT = BaseTy->getAs<ConstantMatrixType>())
1128 ElementCount *= isMatrixRowMajor(LangOpts: getLangOpts(), T: BaseTy)
1129 ? MT->getNumRows()
1130 : MT->getNumColumns();
1131
1132 checkSemanticAnnotation(EntryPoint: FD, Param: D, SemanticAttr: A, SC, ElementCount);
1133 OutputDecl->addAttr(A);
1134
1135 unsigned Location = ActiveSemantic.Index.value_or(u: 0);
1136
1137 bool IsBuiltin = isVkPipelineBuiltin(AstContext: getASTContext(), FD, D, Semantic: A,
1138 IsInput: any(Val: SC.CurrentIOType & IOType::In));
1139 if (IsBuiltin) {
1140 if (const auto *BuiltInAttr = D->getAttr<HLSLVkBuiltInAttr>())
1141 validateVkBuiltinUsage(S&: SemaRef, FD, D, Attr: BuiltInAttr, CurrentIOType: SC.CurrentIOType);
1142 }
1143
1144 if (!IsBuiltin) {
1145 bool HasVkLocation = false;
1146 if (auto *A = D->getAttr<HLSLVkLocationAttr>()) {
1147 HasVkLocation = true;
1148 Location = A->getLocation();
1149 }
1150
1151 if (SC.UsesExplicitVkLocations.value_or(u&: HasVkLocation) != HasVkLocation) {
1152 Diag(Loc: D->getLocation(), DiagID: diag::err_hlsl_semantic_partial_explicit_indexing);
1153 return false;
1154 }
1155 SC.UsesExplicitVkLocations = HasVkLocation;
1156 }
1157
1158 ActiveSemantic.Index = Location + ElementCount;
1159
1160 StringRef BaseName = ActiveSemantic.Semantic->getAttrName()->getName();
1161 std::string LowerName = BaseName.lower();
1162 for (unsigned I = 0; I < ElementCount; ++I) {
1163 auto [It, Inserted] = SC.ActiveSemantics.try_emplace(
1164 Key: (Twine(LowerName) + Twine(Location + I)).str(), Args: D->getLocation());
1165 if (!Inserted) {
1166 Diag(Loc: D->getLocation(), DiagID: diag::err_hlsl_semantic_index_overlap)
1167 << (BaseName + Twine(Location + I)).str();
1168 Diag(Loc: It->second, DiagID: diag::note_previous_use);
1169 return false;
1170 }
1171 }
1172
1173 return true;
1174}
1175
1176bool SemaHLSL::determineActiveSemantic(FunctionDecl *FD,
1177 DeclaratorDecl *OutputDecl,
1178 DeclaratorDecl *D,
1179 SemanticInfo &ActiveSemantic,
1180 SemaHLSL::SemanticContext &SC) {
1181 if (ActiveSemantic.Semantic == nullptr) {
1182 ActiveSemantic.Semantic = D->getAttr<HLSLParsedSemanticAttr>();
1183 if (ActiveSemantic.Semantic)
1184 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1185 }
1186
1187 const Type *T = D == FD ? &*FD->getReturnType() : &*D->getType();
1188 T = T->getUnqualifiedDesugaredType();
1189
1190 const RecordType *RT = dyn_cast<RecordType>(Val: T);
1191 if (!RT)
1192 return determineActiveSemanticOnScalar(FD, OutputDecl, D, ActiveSemantic,
1193 SC);
1194
1195 const RecordDecl *RD = RT->getDecl();
1196 for (FieldDecl *Field : RD->fields()) {
1197 SemanticInfo Info = ActiveSemantic;
1198 if (!determineActiveSemantic(FD, OutputDecl, D: Field, ActiveSemantic&: Info, SC)) {
1199 Diag(Loc: Field->getLocation(), DiagID: diag::note_hlsl_semantic_used_here) << Field;
1200 return false;
1201 }
1202 if (ActiveSemantic.Semantic)
1203 ActiveSemantic = Info;
1204 }
1205
1206 return true;
1207}
1208
1209void SemaHLSL::CheckEntryPoint(FunctionDecl *FD) {
1210 const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>();
1211 assert(ShaderAttr && "Entry point has no shader attribute");
1212 llvm::Triple::EnvironmentType ST = ShaderAttr->getType();
1213 auto &TargetInfo = getASTContext().getTargetInfo();
1214 VersionTuple Ver = TargetInfo.getTriple().getOSVersion();
1215 switch (ST) {
1216 case llvm::Triple::Pixel:
1217 case llvm::Triple::Vertex:
1218 case llvm::Triple::Geometry:
1219 case llvm::Triple::Hull:
1220 case llvm::Triple::Domain:
1221 case llvm::Triple::RayGeneration:
1222 case llvm::Triple::Intersection:
1223 case llvm::Triple::AnyHit:
1224 case llvm::Triple::ClosestHit:
1225 case llvm::Triple::Miss:
1226 case llvm::Triple::Callable:
1227 if (const auto *NT = FD->getAttr<HLSLNumThreadsAttr>()) {
1228 diagnoseAttrStageMismatch(A: NT, Stage: ST,
1229 AllowedStages: {llvm::Triple::Compute,
1230 llvm::Triple::Amplification,
1231 llvm::Triple::Mesh});
1232 FD->setInvalidDecl();
1233 }
1234 if (const auto *WS = FD->getAttr<HLSLWaveSizeAttr>()) {
1235 diagnoseAttrStageMismatch(A: WS, Stage: ST,
1236 AllowedStages: {llvm::Triple::Compute,
1237 llvm::Triple::Amplification,
1238 llvm::Triple::Mesh});
1239 FD->setInvalidDecl();
1240 }
1241 break;
1242
1243 case llvm::Triple::Compute:
1244 case llvm::Triple::Amplification:
1245 case llvm::Triple::Mesh:
1246 if (!FD->hasAttr<HLSLNumThreadsAttr>()) {
1247 Diag(Loc: FD->getLocation(), DiagID: diag::err_hlsl_missing_numthreads)
1248 << llvm::Triple::getEnvironmentTypeName(Kind: ST);
1249 FD->setInvalidDecl();
1250 }
1251 if (const auto *WS = FD->getAttr<HLSLWaveSizeAttr>()) {
1252 if (TargetInfo.getTriple().isSPIRV()) {
1253 Diag(Loc: WS->getLocation(), DiagID: diag::warn_hlsl_wavesize_unsupported_spirv);
1254 } else if (Ver < VersionTuple(6, 6)) {
1255 Diag(Loc: WS->getLocation(), DiagID: diag::err_hlsl_attribute_in_wrong_shader_model)
1256 << WS << "6.6";
1257 FD->setInvalidDecl();
1258 } else if (WS->getSpelledArgsCount() > 1 && Ver < VersionTuple(6, 8)) {
1259 Diag(
1260 Loc: WS->getLocation(),
1261 DiagID: diag::err_hlsl_attribute_number_arguments_insufficient_shader_model)
1262 << WS << WS->getSpelledArgsCount() << "6.8";
1263 FD->setInvalidDecl();
1264 }
1265 }
1266 break;
1267 case llvm::Triple::RootSignature:
1268 llvm_unreachable("rootsig environment has no function entry point");
1269 default:
1270 llvm_unreachable("Unhandled environment in triple");
1271 }
1272
1273 SemaHLSL::SemanticContext InputSC = {};
1274 InputSC.CurrentIOType = IOType::In;
1275 SemaHLSL::SemanticContext OutputSC = {};
1276 OutputSC.CurrentIOType = IOType::Out;
1277
1278 for (ParmVarDecl *Param : FD->parameters()) {
1279 SemanticInfo ActiveSemantic;
1280 ActiveSemantic.Semantic = Param->getAttr<HLSLParsedSemanticAttr>();
1281 if (ActiveSemantic.Semantic)
1282 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1283
1284 // FIXME: An `inout` parameter is part of both signatures, but it is only
1285 // verified against the output one here.
1286 const auto *MA = Param->getAttr<HLSLParamModifierAttr>();
1287 SemanticContext &SC = MA && MA->isAnyOut() ? OutputSC : InputSC;
1288
1289 // Interpolation applies to pixel inputs and vertex outputs, including the
1290 // corresponding side of inout parameters.
1291 if (((ST == llvm::Triple::Pixel && (!MA || MA->isAnyIn())) ||
1292 (ST == llvm::Triple::Vertex && MA && MA->isAnyOut())) &&
1293 !checkInterpolationModifiers(D: Param, Inherited: nullptr, Semantic: nullptr))
1294 FD->setInvalidDecl();
1295
1296 if (!determineActiveSemantic(FD, OutputDecl: Param, D: Param, ActiveSemantic, SC)) {
1297 Diag(Loc: Param->getLocation(), DiagID: diag::note_previous_decl) << Param;
1298 FD->setInvalidDecl();
1299 }
1300 }
1301
1302 SemanticInfo ActiveSemantic;
1303 ActiveSemantic.Semantic = FD->getAttr<HLSLParsedSemanticAttr>();
1304 if (ActiveSemantic.Semantic)
1305 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1306 if (!FD->getReturnType()->isVoidType()) {
1307 if (ST == llvm::Triple::Vertex &&
1308 !checkInterpolationModifiers(D: FD, Inherited: nullptr, Semantic: nullptr))
1309 FD->setInvalidDecl();
1310 determineActiveSemantic(FD, OutputDecl: FD, D: FD, ActiveSemantic, SC&: OutputSC);
1311 }
1312}
1313
1314void SemaHLSL::checkSemanticAnnotation(
1315 FunctionDecl *EntryPoint, const Decl *Param,
1316 const HLSLAppliedSemanticAttr *SemanticAttr, const SemanticContext &SC,
1317 unsigned ElementCount) {
1318 auto *ShaderAttr = EntryPoint->getAttr<HLSLShaderAttr>();
1319 assert(ShaderAttr && "Entry point has no shader attribute");
1320 llvm::Triple::EnvironmentType ST = ShaderAttr->getType();
1321
1322 SemanticKind Kind =
1323 llvm::hlsl::getSemanticKind(SemanticName: SemanticAttr->getSemanticName());
1324 llvm::hlsl::SemanticInterpretation Interpretation =
1325 llvm::hlsl::getInterpretationKind(SemanticKind: Kind, ShaderStage: ST, IOTy: SC.CurrentIOType);
1326 if (Interpretation == llvm::hlsl::SemanticInterpretation::Invalid) {
1327 diagnoseSemanticStageMismatch(A: SemanticAttr, Stage: ST, CurrentIOType: SC.CurrentIOType, SemanticKind: Kind);
1328 return;
1329 }
1330
1331 // A system-value name can have an arbitrary interpretation, for example
1332 // SV_Position on a vertex input. Only the general type restrictions apply.
1333 if (Interpretation == llvm::hlsl::SemanticInterpretation::Arbitrary) {
1334 diagnoseSemanticType(D: Param, A: SemanticAttr, SemanticKind: SemanticKind::Arbitrary);
1335 return;
1336 }
1337
1338 diagnoseSystemSemanticIndex(A: SemanticAttr, SemanticKind: Kind, ElementCount);
1339 diagnoseSemanticType(D: Param, A: SemanticAttr, SemanticKind: Kind);
1340 diagnoseSemanticShaderModel(A: SemanticAttr, SemanticKind: Kind);
1341}
1342
1343void SemaHLSL::diagnoseSemanticShaderModel(const HLSLAppliedSemanticAttr *A,
1344 SemanticKind Kind) {
1345 const auto &Triple = getASTContext().getTargetInfo().getTriple();
1346 if (!Triple.isDXIL())
1347 return;
1348
1349 switch (Kind) {
1350 case SemanticKind::Barycentrics:
1351 case SemanticKind::ViewID:
1352 if (Triple.getOSVersion() < VersionTuple(6, 1))
1353 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_in_wrong_shader_model)
1354 << A->getAttrName() << "6.1";
1355 return;
1356 case SemanticKind::ShadingRate:
1357 if (Triple.getOSVersion() < VersionTuple(6, 4))
1358 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_in_wrong_shader_model)
1359 << A->getAttrName() << "6.4";
1360 return;
1361 case SemanticKind::StartVertexLocation:
1362 case SemanticKind::StartInstanceLocation:
1363 if (Triple.getOSVersion() < VersionTuple(6, 8))
1364 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_in_wrong_shader_model)
1365 << A->getAttrName() << "6.8";
1366 return;
1367 default:
1368 return;
1369 }
1370}
1371
1372void SemaHLSL::diagnoseSystemSemanticIndex(const HLSLAppliedSemanticAttr *A,
1373 SemanticKind Kind,
1374 unsigned ElementCount) {
1375 assert(Kind != SemanticKind::Invalid && Kind != SemanticKind::Arbitrary &&
1376 "expected a recognized system semantic");
1377 assert(ElementCount > 0 && "a semantic covers at least one element");
1378 // The attribute stores the index in an int. Recover its unsigned value
1379 // before widening the arithmetic to detect overflow of the semantic range.
1380 uint32_t FirstIndex = A->getSemanticIndex();
1381 uint64_t LastIndex = uint64_t(FirstIndex) + ElementCount - 1;
1382 constexpr uint32_t MaxSemanticIndex = std::numeric_limits<uint32_t>::max();
1383 if (LastIndex > MaxSemanticIndex) {
1384 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_index_out_of_range)
1385 << A->getAttrName() << LastIndex << MaxSemanticIndex;
1386 return;
1387 }
1388 if (LastIndex == 0)
1389 return;
1390
1391 switch (Kind) {
1392 // These semantics are limited by signature packing, not semantic indices.
1393 case SemanticKind::ClipDistance:
1394 case SemanticKind::CullDistance:
1395 return;
1396 case SemanticKind::Target: {
1397 constexpr unsigned MaxTargetIndex = 7;
1398 if (LastIndex > MaxTargetIndex)
1399 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_index_out_of_range)
1400 << A->getAttrName() << LastIndex << MaxTargetIndex;
1401 return;
1402 }
1403 default:
1404 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_indexing_not_supported)
1405 << A->getAttrName();
1406 return;
1407 }
1408}
1409
1410static QualType getElementTypeOf(QualType T, bool IncludeMatrix) {
1411 if (const auto *VT = T->getAs<clang::VectorType>())
1412 return VT->getElementType();
1413 if (IncludeMatrix)
1414 if (const auto *MT = T->getAs<clang::MatrixType>())
1415 return MT->getElementType();
1416 return T;
1417}
1418
1419static unsigned getComponentCountOf(QualType T) {
1420 if (const auto *VT = T->getAs<clang::VectorType>())
1421 return VT->getNumElements();
1422 return 1;
1423}
1424
1425static bool isFloatOrHalfElement(QualType Elem) {
1426 return Elem->isHalfType() || Elem->isFloat16Type() || Elem->isFloat32Type();
1427}
1428
1429// System-value integer types exclude bool.
1430static bool isIntElementOfWidth(const ASTContext &Ctx, QualType Elem,
1431 uint64_t Width) {
1432 if (!Elem->isIntegerType() || Elem->isBooleanType())
1433 return false;
1434 return Ctx.getTypeSize(T: Elem) == Width;
1435}
1436
1437static bool isIntUpTo32Element(const ASTContext &Ctx, QualType Elem) {
1438 return isIntElementOfWidth(Ctx, Elem, Width: 16) ||
1439 isIntElementOfWidth(Ctx, Elem, Width: 32);
1440}
1441
1442void SemaHLSL::diagnoseSemanticType(const Decl *D,
1443 const HLSLAppliedSemanticAttr *A,
1444 SemanticKind Kind) {
1445 assert(Kind != SemanticKind::Invalid && "expected a valid semantic");
1446 ASTContext &Ctx = getASTContext();
1447
1448 QualType T;
1449 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
1450 T = FD->getReturnType();
1451 else
1452 T = cast<ValueDecl>(Val: D)->getType();
1453
1454 // `out` and `inout` parameters are passed by reference.
1455 T = T.getNonReferenceType();
1456
1457 // Array semantics constrain each element's type.
1458 QualType DeclaredTy = T;
1459 while (const ConstantArrayType *AT = Ctx.getAsConstantArrayType(T))
1460 T = AT->getElementType();
1461
1462 QualType ElemTy = getElementTypeOf(T, /*IncludeMatrix=*/false);
1463 unsigned Components = getComponentCountOf(T);
1464
1465 bool IsSPIRV = getASTContext().getTargetInfo().getTriple().isSPIRV();
1466
1467 switch (Kind) {
1468 case SemanticKind::Barycentrics:
1469 if (DeclaredTy != T || !isFloatOrHalfElement(Elem: ElemTy) || Components != 3)
1470 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_invalid_type)
1471 << A->getAttrName() << /* vector of */ 2 << 3
1472 << /* 16 or 32 bit floating-point */ 2 << DeclaredTy;
1473 return;
1474 case SemanticKind::DispatchThreadID:
1475 case SemanticKind::GroupID:
1476 case SemanticKind::GroupThreadID:
1477 if (!isIntUpTo32Element(Ctx, Elem: ElemTy) || Components > 3)
1478 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_invalid_type)
1479 << A->getAttrName() << /* scalar or vector of up to */ 1 << 3
1480 << /* 16 or 32 bit integer */ 0 << DeclaredTy;
1481 return;
1482 case SemanticKind::StartVertexLocation:
1483 case SemanticKind::StartInstanceLocation:
1484 case SemanticKind::ViewID:
1485 if (DeclaredTy != T || !T->isScalarType() ||
1486 !isIntElementOfWidth(Ctx, Elem: T, Width: 32))
1487 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_invalid_type)
1488 << A->getAttrName() << /* scalar */ 0 << 1 << /* 32 bit integer */ 1
1489 << DeclaredTy;
1490 return;
1491 case SemanticKind::GroupIndex:
1492 if (!isIntElementOfWidth(Ctx, Elem: ElemTy, Width: 32) || Components != 1)
1493 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_invalid_type)
1494 << A->getAttrName() << /* scalar */ 0 << 1 << /* 32 bit integer */ 1
1495 << DeclaredTy;
1496 return;
1497 case SemanticKind::VertexID:
1498 if (!isIntUpTo32Element(Ctx, Elem: ElemTy) || Components != 1)
1499 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_invalid_type)
1500 << A->getAttrName() << /* scalar */ 0 << 1
1501 << /* 16 or 32 bit integer */ 0 << DeclaredTy;
1502 return;
1503 case SemanticKind::Position:
1504 case SemanticKind::Target:
1505 if (!isFloatOrHalfElement(Elem: ElemTy) || Components > 4)
1506 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_invalid_type)
1507 << A->getAttrName() << /* scalar or vector of up to */ 1 << 4
1508 << /* 16 or 32 bit floating-point */ 2 << DeclaredTy;
1509 return;
1510 case SemanticKind::SampleIndex:
1511 case SemanticKind::PrimitiveID:
1512 // SPIR-V declares these built-ins as 32-bit integers and converts 16-bit
1513 // declarations.
1514 if (!DeclaredTy->isScalarType() || !isIntUpTo32Element(Ctx, Elem: DeclaredTy))
1515 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_invalid_type)
1516 << A->getAttrName() << /* scalar */ 0 << 1
1517 << /* 16 or 32 bit integer */ 0 << DeclaredTy;
1518 return;
1519 case SemanticKind::InstanceID:
1520 case SemanticKind::ShadingRate:
1521 // DXIL permits U32 or U16. SPIR-V requires a 32-bit scalar per:
1522 // - VUID-InstanceIndex-InstanceIndex-04265
1523 // - VUID-ShadingRateKHR-ShadingRateKHR-04492
1524 if (!T->isUnsignedIntegerType() ||
1525 !(isIntElementOfWidth(Ctx, Elem: T, Width: 32) ||
1526 (!IsSPIRV && isIntElementOfWidth(Ctx, Elem: T, Width: 16))))
1527 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_invalid_type)
1528 << A->getAttrName() << /* scalar */ 0 << 1
1529 << /* 16 or 32 bit unsigned integer / 32 bit unsigned integer */
1530 (IsSPIRV ? 4 : 3) << DeclaredTy;
1531 return;
1532 case SemanticKind::IsFrontFace:
1533 // Accept bool or int; SPIR-V FrontFacing BuiltIn is always a bool
1534 // and CodeGen converts it to the declared type.
1535 if (DeclaredTy != T || !T->isScalarType() ||
1536 !(T->isBooleanType() || isIntElementOfWidth(Ctx, Elem: T, Width: 32)))
1537 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_invalid_type)
1538 << A->getAttrName() << /* scalar */ 0 << 1
1539 << /* bool or 32 bit integer */ 5 << DeclaredTy;
1540 return;
1541 default:
1542 // Other semantics only have the general signature type restrictions.
1543 break;
1544 }
1545
1546 // DXIL signatures cannot carry 64-bit components, even for arbitrary
1547 // semantics. SPIR-V interfaces do support these types.
1548 QualType ScalarTy = getElementTypeOf(T, /*IncludeMatrix=*/true);
1549 if (Ctx.getTargetInfo().getTriple().isDXIL() &&
1550 (ScalarTy->isSpecificBuiltinType(K: BuiltinType::Double) ||
1551 isIntElementOfWidth(Ctx, Elem: ScalarTy, Width: 64)))
1552 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_64bit_type)
1553 << A->getAttrName() << DeclaredTy;
1554}
1555
1556void SemaHLSL::diagnoseAttrStageMismatch(
1557 const Attr *A, llvm::Triple::EnvironmentType Stage,
1558 std::initializer_list<llvm::Triple::EnvironmentType> AllowedStages) {
1559 SmallVector<StringRef, 8> StageStrings;
1560 llvm::transform(Range&: AllowedStages, d_first: std::back_inserter(x&: StageStrings),
1561 F: [](llvm::Triple::EnvironmentType ST) {
1562 return StringRef(
1563 HLSLShaderAttr::ConvertEnvironmentTypeToStr(Val: ST));
1564 });
1565 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_attr_unsupported_in_stage)
1566 << A->getAttrName() << llvm::Triple::getEnvironmentTypeName(Kind: Stage)
1567 << (AllowedStages.size() != 1) << join(R&: StageStrings, Separator: ", ");
1568}
1569
1570void SemaHLSL::diagnoseSemanticStageMismatch(
1571 const Attr *A, llvm::Triple::EnvironmentType Stage, IOType CurrentIOType,
1572 SemanticKind Kind) {
1573
1574 ArrayRef<SemanticStageInfo> Allowed = llvm::hlsl::getAvailableStages(SemanticKind: Kind);
1575 auto It = llvm::find_if(Range&: Allowed, P: [&Stage](const SemanticStageInfo &Info) {
1576 return Info.Stage == Stage;
1577 });
1578
1579 StringRef CurrentIOTypeName = "patch constants or primitives";
1580 if (any(Val: CurrentIOType & IOType::In))
1581 CurrentIOTypeName = "inputs";
1582 else if (any(Val: CurrentIOType & IOType::Out))
1583 CurrentIOTypeName = "outputs";
1584
1585 // The semantic is not available in this shader stage at all.
1586 if (It == Allowed.end()) {
1587 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_unsupported_iotype_for_stage)
1588 << A->getAttrName() << llvm::Triple::getEnvironmentTypeName(Kind: Stage)
1589 << CurrentIOTypeName;
1590 return;
1591 }
1592
1593 IOType AllowedIOTypes = It->AllowedIOTypesMask;
1594 if (!(AllowedIOTypes & CurrentIOType)) {
1595 Diag(Loc: A->getLoc(), DiagID: diag::err_hlsl_semantic_unsupported_iotype_for_stage)
1596 << A->getAttrName() << llvm::Triple::getEnvironmentTypeName(Kind: Stage)
1597 << CurrentIOTypeName;
1598 return;
1599 }
1600}
1601
1602template <CastKind Kind>
1603static void castVector(Sema &S, ExprResult &E, QualType &Ty, unsigned Sz) {
1604 if (const auto *VTy = Ty->getAs<VectorType>())
1605 Ty = VTy->getElementType();
1606 Ty = S.getASTContext().getExtVectorType(VectorType: Ty, NumElts: Sz);
1607 E = S.ImpCastExprToType(E: E.get(), Type: Ty, CK: Kind);
1608}
1609
1610template <CastKind Kind>
1611static QualType castElement(Sema &S, ExprResult &E, QualType Ty) {
1612 E = S.ImpCastExprToType(E: E.get(), Type: Ty, CK: Kind);
1613 return Ty;
1614}
1615
1616static QualType handleFloatVectorBinOpConversion(
1617 Sema &SemaRef, ExprResult &LHS, ExprResult &RHS, QualType LHSType,
1618 QualType RHSType, QualType LElTy, QualType RElTy, bool IsCompAssign) {
1619 bool LHSFloat = LElTy->isRealFloatingType();
1620 bool RHSFloat = RElTy->isRealFloatingType();
1621
1622 if (LHSFloat && RHSFloat) {
1623 if (IsCompAssign ||
1624 SemaRef.getASTContext().getFloatingTypeOrder(LHS: LElTy, RHS: RElTy) > 0)
1625 return castElement<CK_FloatingCast>(S&: SemaRef, E&: RHS, Ty: LHSType);
1626
1627 return castElement<CK_FloatingCast>(S&: SemaRef, E&: LHS, Ty: RHSType);
1628 }
1629
1630 if (LHSFloat)
1631 return castElement<CK_IntegralToFloating>(S&: SemaRef, E&: RHS, Ty: LHSType);
1632
1633 assert(RHSFloat);
1634 if (IsCompAssign)
1635 return castElement<clang::CK_FloatingToIntegral>(S&: SemaRef, E&: RHS, Ty: LHSType);
1636
1637 return castElement<CK_IntegralToFloating>(S&: SemaRef, E&: LHS, Ty: RHSType);
1638}
1639
1640static QualType handleIntegerVectorBinOpConversion(
1641 Sema &SemaRef, ExprResult &LHS, ExprResult &RHS, QualType LHSType,
1642 QualType RHSType, QualType LElTy, QualType RElTy, bool IsCompAssign) {
1643
1644 int IntOrder = SemaRef.Context.getIntegerTypeOrder(LHS: LElTy, RHS: RElTy);
1645 bool LHSSigned = LElTy->hasSignedIntegerRepresentation();
1646 bool RHSSigned = RElTy->hasSignedIntegerRepresentation();
1647 auto &Ctx = SemaRef.getASTContext();
1648
1649 // If both types have the same signedness, use the higher ranked type.
1650 if (LHSSigned == RHSSigned) {
1651 if (IsCompAssign || IntOrder >= 0)
1652 return castElement<CK_IntegralCast>(S&: SemaRef, E&: RHS, Ty: LHSType);
1653
1654 return castElement<CK_IntegralCast>(S&: SemaRef, E&: LHS, Ty: RHSType);
1655 }
1656
1657 // If the unsigned type has greater than or equal rank of the signed type, use
1658 // the unsigned type.
1659 if (IntOrder != (LHSSigned ? 1 : -1)) {
1660 if (IsCompAssign || RHSSigned)
1661 return castElement<CK_IntegralCast>(S&: SemaRef, E&: RHS, Ty: LHSType);
1662 return castElement<CK_IntegralCast>(S&: SemaRef, E&: LHS, Ty: RHSType);
1663 }
1664
1665 // At this point the signed type has higher rank than the unsigned type, which
1666 // means it will be the same size or bigger. If the signed type is bigger, it
1667 // can represent all the values of the unsigned type, so select it.
1668 if (Ctx.getIntWidth(T: LElTy) != Ctx.getIntWidth(T: RElTy)) {
1669 if (IsCompAssign || LHSSigned)
1670 return castElement<CK_IntegralCast>(S&: SemaRef, E&: RHS, Ty: LHSType);
1671 return castElement<CK_IntegralCast>(S&: SemaRef, E&: LHS, Ty: RHSType);
1672 }
1673
1674 // This is a bit of an odd duck case in HLSL. It shouldn't happen, but can due
1675 // to C/C++ leaking through. The place this happens today is long vs long
1676 // long. When arguments are vector<unsigned long, N> and vector<long long, N>,
1677 // the long long has higher rank than long even though they are the same size.
1678
1679 // If this is a compound assignment cast the right hand side to the left hand
1680 // side's type.
1681 if (IsCompAssign)
1682 return castElement<CK_IntegralCast>(S&: SemaRef, E&: RHS, Ty: LHSType);
1683
1684 // If this isn't a compound assignment we convert to unsigned long long.
1685 QualType ElTy = Ctx.getCorrespondingUnsignedType(T: LHSSigned ? LElTy : RElTy);
1686 QualType NewTy = Ctx.getExtVectorType(
1687 VectorType: ElTy, NumElts: RHSType->castAs<VectorType>()->getNumElements());
1688 (void)castElement<CK_IntegralCast>(S&: SemaRef, E&: RHS, Ty: NewTy);
1689
1690 return castElement<CK_IntegralCast>(S&: SemaRef, E&: LHS, Ty: NewTy);
1691}
1692
1693static CastKind getScalarCastKind(ASTContext &Ctx, QualType DestTy,
1694 QualType SrcTy) {
1695 if (DestTy->isRealFloatingType() && SrcTy->isRealFloatingType())
1696 return CK_FloatingCast;
1697 if (DestTy->isIntegralType(Ctx) && SrcTy->isIntegralType(Ctx))
1698 return CK_IntegralCast;
1699 if (DestTy->isRealFloatingType())
1700 return CK_IntegralToFloating;
1701 assert(SrcTy->isRealFloatingType() && DestTy->isIntegralType(Ctx));
1702 return CK_FloatingToIntegral;
1703}
1704
1705QualType SemaHLSL::handleVectorBinOpConversion(ExprResult &LHS, ExprResult &RHS,
1706 QualType LHSType,
1707 QualType RHSType,
1708 bool IsCompAssign) {
1709 const auto *LVecTy = LHSType->getAs<VectorType>();
1710 const auto *RVecTy = RHSType->getAs<VectorType>();
1711 auto &Ctx = getASTContext();
1712
1713 // If the LHS is not a vector and this is a compound assignment, we truncate
1714 // the argument to a scalar then convert it to the LHS's type.
1715 if (!LVecTy && IsCompAssign) {
1716 QualType RElTy = RHSType->castAs<VectorType>()->getElementType();
1717 RHS = SemaRef.ImpCastExprToType(E: RHS.get(), Type: RElTy, CK: CK_HLSLVectorTruncation);
1718 RHSType = RHS.get()->getType();
1719 if (Ctx.hasSameUnqualifiedType(T1: LHSType, T2: RHSType))
1720 return LHSType;
1721 RHS = SemaRef.ImpCastExprToType(E: RHS.get(), Type: LHSType,
1722 CK: getScalarCastKind(Ctx, DestTy: LHSType, SrcTy: RHSType));
1723 return LHSType;
1724 }
1725
1726 unsigned EndSz = std::numeric_limits<unsigned>::max();
1727 unsigned LSz = 0;
1728 if (LVecTy)
1729 LSz = EndSz = LVecTy->getNumElements();
1730 if (RVecTy)
1731 EndSz = std::min(a: RVecTy->getNumElements(), b: EndSz);
1732 assert(EndSz != std::numeric_limits<unsigned>::max() &&
1733 "one of the above should have had a value");
1734
1735 // In a compound assignment, the left operand does not change type, the right
1736 // operand is converted to the type of the left operand.
1737 if (IsCompAssign && LSz != EndSz) {
1738 Diag(Loc: LHS.get()->getBeginLoc(),
1739 DiagID: diag::err_hlsl_vector_compound_assignment_truncation)
1740 << LHSType << RHSType;
1741 return QualType();
1742 }
1743
1744 if (RVecTy && RVecTy->getNumElements() > EndSz)
1745 castVector<CK_HLSLVectorTruncation>(S&: SemaRef, E&: RHS, Ty&: RHSType, Sz: EndSz);
1746 if (!IsCompAssign && LVecTy && LVecTy->getNumElements() > EndSz)
1747 castVector<CK_HLSLVectorTruncation>(S&: SemaRef, E&: LHS, Ty&: LHSType, Sz: EndSz);
1748
1749 if (!RVecTy)
1750 castVector<CK_VectorSplat>(S&: SemaRef, E&: RHS, Ty&: RHSType, Sz: EndSz);
1751 if (!IsCompAssign && !LVecTy)
1752 castVector<CK_VectorSplat>(S&: SemaRef, E&: LHS, Ty&: LHSType, Sz: EndSz);
1753
1754 // If we're at the same type after resizing we can stop here.
1755 if (Ctx.hasSameUnqualifiedType(T1: LHSType, T2: RHSType))
1756 return Ctx.getCommonSugaredType(X: LHSType, Y: RHSType);
1757
1758 QualType LElTy = LHSType->castAs<VectorType>()->getElementType();
1759 QualType RElTy = RHSType->castAs<VectorType>()->getElementType();
1760
1761 // Handle conversion for floating point vectors.
1762 if (LElTy->isRealFloatingType() || RElTy->isRealFloatingType())
1763 return handleFloatVectorBinOpConversion(SemaRef, LHS, RHS, LHSType, RHSType,
1764 LElTy, RElTy, IsCompAssign);
1765
1766 assert(LElTy->isIntegralType(Ctx) && RElTy->isIntegralType(Ctx) &&
1767 "HLSL Vectors can only contain integer or floating point types");
1768 return handleIntegerVectorBinOpConversion(SemaRef, LHS, RHS, LHSType, RHSType,
1769 LElTy, RElTy, IsCompAssign);
1770}
1771
1772void SemaHLSL::emitLogicalOperatorFixIt(Expr *LHS, Expr *RHS,
1773 BinaryOperatorKind Opc) {
1774 assert((Opc == BO_LOr || Opc == BO_LAnd) &&
1775 "Called with non-logical operator");
1776 llvm::SmallVector<char, 256> Buff;
1777 llvm::raw_svector_ostream OS(Buff);
1778 PrintingPolicy PP(SemaRef.getLangOpts());
1779 StringRef NewFnName = Opc == BO_LOr ? "or" : "and";
1780 OS << NewFnName << "(";
1781 LHS->printPretty(OS, Helper: nullptr, Policy: PP);
1782 OS << ", ";
1783 RHS->printPretty(OS, Helper: nullptr, Policy: PP);
1784 OS << ")";
1785 SourceRange FullRange = SourceRange(LHS->getBeginLoc(), RHS->getEndLoc());
1786 SemaRef.Diag(Loc: LHS->getBeginLoc(), DiagID: diag::note_function_suggestion)
1787 << NewFnName << FixItHint::CreateReplacement(RemoveRange: FullRange, Code: OS.str());
1788}
1789
1790std::pair<IdentifierInfo *, bool>
1791SemaHLSL::ActOnStartRootSignatureDecl(StringRef Signature) {
1792 llvm::hash_code Hash = llvm::hash_value(S: Signature);
1793 std::string IdStr = "__hlsl_rootsig_decl_" + std::to_string(val: Hash);
1794 IdentifierInfo *DeclIdent = &(getASTContext().Idents.get(Name: IdStr));
1795
1796 // Check if we have already found a decl of the same name.
1797 LookupResult R(SemaRef, DeclIdent, SourceLocation(),
1798 Sema::LookupOrdinaryName);
1799 bool Found = SemaRef.LookupQualifiedName(R, LookupCtx: SemaRef.CurContext);
1800 return {DeclIdent, Found};
1801}
1802
1803void SemaHLSL::ActOnFinishRootSignatureDecl(
1804 SourceLocation Loc, IdentifierInfo *DeclIdent,
1805 ArrayRef<hlsl::RootSignatureElement> RootElements) {
1806
1807 if (handleRootSignatureElements(Elements: RootElements))
1808 return;
1809
1810 SmallVector<llvm::hlsl::rootsig::RootElement> Elements;
1811 for (auto &RootSigElement : RootElements)
1812 Elements.push_back(Elt: RootSigElement.getElement());
1813
1814 auto *SignatureDecl = HLSLRootSignatureDecl::Create(
1815 C&: SemaRef.getASTContext(), /*DeclContext=*/DC: SemaRef.CurContext, Loc,
1816 ID: DeclIdent, Version: SemaRef.getLangOpts().HLSLRootSigVer, RootElements: Elements);
1817
1818 SignatureDecl->setImplicit();
1819 SemaRef.PushOnScopeChains(D: SignatureDecl, S: SemaRef.getCurScope());
1820}
1821
1822HLSLRootSignatureDecl *
1823SemaHLSL::lookupRootSignatureOverrideDecl(DeclContext *DC) const {
1824 if (RootSigOverrideIdent) {
1825 LookupResult R(SemaRef, RootSigOverrideIdent, SourceLocation(),
1826 Sema::LookupOrdinaryName);
1827 if (SemaRef.LookupQualifiedName(R, LookupCtx: DC))
1828 return dyn_cast<HLSLRootSignatureDecl>(Val: R.getFoundDecl());
1829 }
1830
1831 return nullptr;
1832}
1833
1834namespace {
1835
1836struct PerVisibilityBindingChecker {
1837 SemaHLSL *S;
1838 // We need one builder per `llvm::dxbc::ShaderVisibility` value.
1839 std::array<llvm::hlsl::BindingInfoBuilder, 8> Builders;
1840
1841 struct ElemInfo {
1842 const hlsl::RootSignatureElement *Elem;
1843 llvm::dxbc::ShaderVisibility Vis;
1844 bool Diagnosed;
1845 };
1846 llvm::SmallVector<ElemInfo> ElemInfoMap;
1847
1848 PerVisibilityBindingChecker(SemaHLSL *S) : S(S) {}
1849
1850 void trackBinding(llvm::dxbc::ShaderVisibility Visibility,
1851 llvm::dxil::ResourceClass RC, uint32_t Space,
1852 uint32_t LowerBound, uint32_t UpperBound,
1853 const hlsl::RootSignatureElement *Elem) {
1854 uint32_t BuilderIndex = llvm::to_underlying(E: Visibility);
1855 assert(BuilderIndex < Builders.size() &&
1856 "Not enough builders for visibility type");
1857 Builders[BuilderIndex].trackBinding(RC, Space, LowerBound, UpperBound,
1858 Cookie: static_cast<const void *>(Elem));
1859
1860 static_assert(llvm::to_underlying(E: llvm::dxbc::ShaderVisibility::All) == 0,
1861 "'All' visibility must come first");
1862 if (Visibility == llvm::dxbc::ShaderVisibility::All)
1863 for (size_t I = 1, E = Builders.size(); I < E; ++I)
1864 Builders[I].trackBinding(RC, Space, LowerBound, UpperBound,
1865 Cookie: static_cast<const void *>(Elem));
1866
1867 ElemInfoMap.push_back(Elt: {.Elem: Elem, .Vis: Visibility, .Diagnosed: false});
1868 }
1869
1870 ElemInfo &getInfo(const hlsl::RootSignatureElement *Elem) {
1871 auto It = llvm::lower_bound(
1872 Range&: ElemInfoMap, Value&: Elem,
1873 C: [](const auto &LHS, const auto &RHS) { return LHS.Elem < RHS; });
1874 assert(It->Elem == Elem && "Element not in map");
1875 return *It;
1876 }
1877
1878 bool checkOverlap() {
1879 llvm::sort(C&: ElemInfoMap, Comp: [](const auto &LHS, const auto &RHS) {
1880 return LHS.Elem < RHS.Elem;
1881 });
1882
1883 bool HadOverlap = false;
1884
1885 using llvm::hlsl::BindingInfoBuilder;
1886 auto ReportOverlap = [this,
1887 &HadOverlap](const BindingInfoBuilder &Builder,
1888 const llvm::hlsl::Binding &Reported) {
1889 HadOverlap = true;
1890
1891 const auto *Elem =
1892 static_cast<const hlsl::RootSignatureElement *>(Reported.Cookie);
1893 const llvm::hlsl::Binding &Previous = Builder.findOverlapping(ReportedBinding: Reported);
1894 const auto *PrevElem =
1895 static_cast<const hlsl::RootSignatureElement *>(Previous.Cookie);
1896
1897 ElemInfo &Info = getInfo(Elem);
1898 // We will have already diagnosed this binding if there's overlap in the
1899 // "All" visibility as well as any particular visibility.
1900 if (Info.Diagnosed)
1901 return;
1902 Info.Diagnosed = true;
1903
1904 ElemInfo &PrevInfo = getInfo(Elem: PrevElem);
1905 llvm::dxbc::ShaderVisibility CommonVis =
1906 Info.Vis == llvm::dxbc::ShaderVisibility::All ? PrevInfo.Vis
1907 : Info.Vis;
1908
1909 this->S->Diag(Loc: Elem->getLocation(), DiagID: diag::err_hlsl_resource_range_overlap)
1910 << llvm::to_underlying(E: Reported.RC) << Reported.LowerBound
1911 << Reported.isUnbounded() << Reported.UpperBound
1912 << llvm::to_underlying(E: Previous.RC) << Previous.LowerBound
1913 << Previous.isUnbounded() << Previous.UpperBound << Reported.Space
1914 << CommonVis;
1915
1916 this->S->Diag(Loc: PrevElem->getLocation(),
1917 DiagID: diag::note_hlsl_resource_range_here);
1918 };
1919
1920 for (BindingInfoBuilder &Builder : Builders)
1921 Builder.calculateBindingInfo(ReportOverlap);
1922
1923 return HadOverlap;
1924 }
1925};
1926
1927static CXXMethodDecl *lookupMethod(Sema &S, CXXRecordDecl *RecordDecl,
1928 StringRef Name, SourceLocation Loc) {
1929 DeclarationName DeclName(&S.getASTContext().Idents.get(Name));
1930 LookupResult Result(S, DeclName, Loc, Sema::LookupMemberName);
1931 if (!S.LookupQualifiedName(R&: Result, LookupCtx: static_cast<DeclContext *>(RecordDecl)))
1932 return nullptr;
1933 return cast<CXXMethodDecl>(Val: Result.getFoundDecl());
1934}
1935
1936} // end anonymous namespace
1937
1938bool SemaHLSL::handleRootSignatureElements(
1939 ArrayRef<hlsl::RootSignatureElement> Elements) {
1940 // Define some common error handling functions
1941 bool HadError = false;
1942 auto ReportError = [this, &HadError](SourceLocation Loc, uint32_t LowerBound,
1943 uint32_t UpperBound) {
1944 HadError = true;
1945 this->Diag(Loc, DiagID: diag::err_hlsl_invalid_rootsig_value)
1946 << LowerBound << UpperBound;
1947 };
1948
1949 auto ReportFloatError = [this, &HadError](SourceLocation Loc,
1950 float LowerBound,
1951 float UpperBound) {
1952 HadError = true;
1953 this->Diag(Loc, DiagID: diag::err_hlsl_invalid_rootsig_value)
1954 << llvm::formatv(Fmt: "{0:f}", Vals&: LowerBound).sstr<6>()
1955 << llvm::formatv(Fmt: "{0:f}", Vals&: UpperBound).sstr<6>();
1956 };
1957
1958 auto VerifyRegister = [ReportError](SourceLocation Loc, uint32_t Register) {
1959 if (!llvm::hlsl::rootsig::verifyRegisterValue(RegisterValue: Register))
1960 ReportError(Loc, 0, 0xfffffffe);
1961 };
1962
1963 auto VerifySpace = [ReportError](SourceLocation Loc, uint32_t Space) {
1964 if (!llvm::hlsl::rootsig::verifyRegisterSpace(RegisterSpace: Space))
1965 ReportError(Loc, 0, 0xffffffef);
1966 };
1967
1968 const uint32_t Version =
1969 llvm::to_underlying(E: SemaRef.getLangOpts().HLSLRootSigVer);
1970 const uint32_t VersionEnum = Version - 1;
1971 auto ReportFlagError = [this, &HadError, VersionEnum](SourceLocation Loc) {
1972 HadError = true;
1973 this->Diag(Loc, DiagID: diag::err_hlsl_invalid_rootsig_flag)
1974 << /*version minor*/ VersionEnum;
1975 };
1976
1977 // Iterate through the elements and do basic validations
1978 for (const hlsl::RootSignatureElement &RootSigElem : Elements) {
1979 SourceLocation Loc = RootSigElem.getLocation();
1980 const llvm::hlsl::rootsig::RootElement &Elem = RootSigElem.getElement();
1981 if (const auto *Descriptor =
1982 std::get_if<llvm::hlsl::rootsig::RootDescriptor>(ptr: &Elem)) {
1983 VerifyRegister(Loc, Descriptor->Reg.Number);
1984 VerifySpace(Loc, Descriptor->Space);
1985
1986 if (!llvm::hlsl::rootsig::verifyRootDescriptorFlag(Version,
1987 Flags: Descriptor->Flags))
1988 ReportFlagError(Loc);
1989 } else if (const auto *Constants =
1990 std::get_if<llvm::hlsl::rootsig::RootConstants>(ptr: &Elem)) {
1991 VerifyRegister(Loc, Constants->Reg.Number);
1992 VerifySpace(Loc, Constants->Space);
1993 } else if (const auto *Sampler =
1994 std::get_if<llvm::hlsl::rootsig::StaticSampler>(ptr: &Elem)) {
1995 VerifyRegister(Loc, Sampler->Reg.Number);
1996 VerifySpace(Loc, Sampler->Space);
1997
1998 assert(!std::isnan(Sampler->MaxLOD) && !std::isnan(Sampler->MinLOD) &&
1999 "By construction, parseFloatParam can't produce a NaN from a "
2000 "float_literal token");
2001
2002 if (!llvm::hlsl::rootsig::verifyMaxAnisotropy(MaxAnisotropy: Sampler->MaxAnisotropy))
2003 ReportError(Loc, 0, 16);
2004 if (!llvm::hlsl::rootsig::verifyMipLODBias(MipLODBias: Sampler->MipLODBias))
2005 ReportFloatError(Loc, -16.f, 15.99f);
2006 } else if (const auto *Clause =
2007 std::get_if<llvm::hlsl::rootsig::DescriptorTableClause>(
2008 ptr: &Elem)) {
2009 VerifyRegister(Loc, Clause->Reg.Number);
2010 VerifySpace(Loc, Clause->Space);
2011
2012 if (!llvm::hlsl::rootsig::verifyNumDescriptors(NumDescriptors: Clause->NumDescriptors)) {
2013 // NumDescriptor could techincally be ~0u but that is reserved for
2014 // unbounded, so the diagnostic will not report that as a valid int
2015 // value
2016 ReportError(Loc, 1, 0xfffffffe);
2017 }
2018
2019 if (!llvm::hlsl::rootsig::verifyDescriptorRangeFlag(Version, Type: Clause->Type,
2020 Flags: Clause->Flags))
2021 ReportFlagError(Loc);
2022 }
2023 }
2024
2025 PerVisibilityBindingChecker BindingChecker(this);
2026 SmallVector<std::pair<const llvm::hlsl::rootsig::DescriptorTableClause *,
2027 const hlsl::RootSignatureElement *>>
2028 UnboundClauses;
2029
2030 for (const hlsl::RootSignatureElement &RootSigElem : Elements) {
2031 const llvm::hlsl::rootsig::RootElement &Elem = RootSigElem.getElement();
2032 if (const auto *Descriptor =
2033 std::get_if<llvm::hlsl::rootsig::RootDescriptor>(ptr: &Elem)) {
2034 uint32_t LowerBound(Descriptor->Reg.Number);
2035 uint32_t UpperBound(LowerBound); // inclusive range
2036
2037 BindingChecker.trackBinding(
2038 Visibility: Descriptor->Visibility,
2039 RC: static_cast<llvm::dxil::ResourceClass>(Descriptor->Type),
2040 Space: Descriptor->Space, LowerBound, UpperBound, Elem: &RootSigElem);
2041 } else if (const auto *Constants =
2042 std::get_if<llvm::hlsl::rootsig::RootConstants>(ptr: &Elem)) {
2043 uint32_t LowerBound(Constants->Reg.Number);
2044 uint32_t UpperBound(LowerBound); // inclusive range
2045
2046 BindingChecker.trackBinding(
2047 Visibility: Constants->Visibility, RC: llvm::dxil::ResourceClass::CBuffer,
2048 Space: Constants->Space, LowerBound, UpperBound, Elem: &RootSigElem);
2049 } else if (const auto *Sampler =
2050 std::get_if<llvm::hlsl::rootsig::StaticSampler>(ptr: &Elem)) {
2051 uint32_t LowerBound(Sampler->Reg.Number);
2052 uint32_t UpperBound(LowerBound); // inclusive range
2053
2054 BindingChecker.trackBinding(
2055 Visibility: Sampler->Visibility, RC: llvm::dxil::ResourceClass::Sampler,
2056 Space: Sampler->Space, LowerBound, UpperBound, Elem: &RootSigElem);
2057 } else if (const auto *Clause =
2058 std::get_if<llvm::hlsl::rootsig::DescriptorTableClause>(
2059 ptr: &Elem)) {
2060 // We'll process these once we see the table element.
2061 UnboundClauses.emplace_back(Args&: Clause, Args: &RootSigElem);
2062 } else if (const auto *Table =
2063 std::get_if<llvm::hlsl::rootsig::DescriptorTable>(ptr: &Elem)) {
2064 assert(UnboundClauses.size() == Table->NumClauses &&
2065 "Number of unbound elements must match the number of clauses");
2066 bool HasAnySampler = false;
2067 bool HasAnyNonSampler = false;
2068 uint64_t Offset = 0;
2069 bool IsPrevUnbound = false;
2070 for (const auto &[Clause, ClauseElem] : UnboundClauses) {
2071 SourceLocation Loc = ClauseElem->getLocation();
2072 if (Clause->Type == llvm::dxil::ResourceClass::Sampler)
2073 HasAnySampler = true;
2074 else
2075 HasAnyNonSampler = true;
2076
2077 if (HasAnySampler && HasAnyNonSampler)
2078 Diag(Loc, DiagID: diag::err_hlsl_invalid_mixed_resources);
2079
2080 // Relevant error will have already been reported above and needs to be
2081 // fixed before we can conduct further analysis, so shortcut error
2082 // return
2083 if (Clause->NumDescriptors == 0)
2084 return true;
2085
2086 bool IsAppending =
2087 Clause->Offset == llvm::hlsl::rootsig::DescriptorTableOffsetAppend;
2088 if (!IsAppending)
2089 Offset = Clause->Offset;
2090
2091 uint64_t RangeBound = llvm::hlsl::rootsig::computeRangeBound(
2092 Offset, Size: Clause->NumDescriptors);
2093
2094 if (IsPrevUnbound && IsAppending)
2095 Diag(Loc, DiagID: diag::err_hlsl_appending_onto_unbound);
2096 else if (!llvm::hlsl::rootsig::verifyNoOverflowedOffset(Offset: RangeBound))
2097 Diag(Loc, DiagID: diag::err_hlsl_offset_overflow) << Offset << RangeBound;
2098
2099 // Update offset to be 1 past this range's bound
2100 Offset = RangeBound + 1;
2101 IsPrevUnbound = Clause->NumDescriptors ==
2102 llvm::hlsl::rootsig::NumDescriptorsUnbounded;
2103
2104 // Compute the register bounds and track resource binding
2105 uint32_t LowerBound(Clause->Reg.Number);
2106 uint32_t UpperBound = llvm::hlsl::rootsig::computeRangeBound(
2107 Offset: LowerBound, Size: Clause->NumDescriptors);
2108
2109 BindingChecker.trackBinding(
2110 Visibility: Table->Visibility,
2111 RC: static_cast<llvm::dxil::ResourceClass>(Clause->Type), Space: Clause->Space,
2112 LowerBound, UpperBound, Elem: ClauseElem);
2113 }
2114 UnboundClauses.clear();
2115 }
2116 }
2117
2118 return BindingChecker.checkOverlap();
2119}
2120
2121void SemaHLSL::handleRootSignatureAttr(Decl *D, const ParsedAttr &AL) {
2122 if (AL.getNumArgs() != 1) {
2123 Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments) << AL << 1;
2124 return;
2125 }
2126
2127 IdentifierInfo *Ident = AL.getArgAsIdent(Arg: 0)->getIdentifierInfo();
2128 if (auto *RS = D->getAttr<RootSignatureAttr>()) {
2129 if (RS->getSignatureIdent() != Ident) {
2130 Diag(Loc: AL.getLoc(), DiagID: diag::err_disallowed_duplicate_attribute) << RS;
2131 return;
2132 }
2133
2134 Diag(Loc: AL.getLoc(), DiagID: diag::warn_duplicate_attribute_exact) << RS;
2135 return;
2136 }
2137
2138 LookupResult R(SemaRef, Ident, SourceLocation(), Sema::LookupOrdinaryName);
2139 if (SemaRef.LookupQualifiedName(R, LookupCtx: D->getDeclContext()))
2140 if (auto *SignatureDecl =
2141 dyn_cast<HLSLRootSignatureDecl>(Val: R.getFoundDecl())) {
2142 D->addAttr(A: ::new (getASTContext()) RootSignatureAttr(
2143 getASTContext(), AL, Ident, SignatureDecl));
2144 }
2145}
2146
2147void SemaHLSL::handleNumThreadsAttr(Decl *D, const ParsedAttr &AL) {
2148 llvm::VersionTuple SMVersion =
2149 getASTContext().getTargetInfo().getTriple().getOSVersion();
2150 bool IsDXIL = getASTContext().getTargetInfo().getTriple().getArch() ==
2151 llvm::Triple::dxil;
2152
2153 uint32_t ZMax = 1024;
2154 uint32_t ThreadMax = 1024;
2155 if (IsDXIL && SMVersion.getMajor() <= 4) {
2156 ZMax = 1;
2157 ThreadMax = 768;
2158 } else if (IsDXIL && SMVersion.getMajor() == 5) {
2159 ZMax = 64;
2160 ThreadMax = 1024;
2161 }
2162
2163 uint32_t X;
2164 if (!SemaRef.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: X))
2165 return;
2166 if (X > 1024) {
2167 Diag(Loc: AL.getArgAsExpr(Arg: 0)->getExprLoc(),
2168 DiagID: diag::err_hlsl_numthreads_argument_oor)
2169 << 0 << 1024;
2170 return;
2171 }
2172 uint32_t Y;
2173 if (!SemaRef.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 1), Val&: Y))
2174 return;
2175 if (Y > 1024) {
2176 Diag(Loc: AL.getArgAsExpr(Arg: 1)->getExprLoc(),
2177 DiagID: diag::err_hlsl_numthreads_argument_oor)
2178 << 1 << 1024;
2179 return;
2180 }
2181 uint32_t Z;
2182 if (!SemaRef.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 2), Val&: Z))
2183 return;
2184 if (Z > ZMax) {
2185 SemaRef.Diag(Loc: AL.getArgAsExpr(Arg: 2)->getExprLoc(),
2186 DiagID: diag::err_hlsl_numthreads_argument_oor)
2187 << 2 << ZMax;
2188 return;
2189 }
2190
2191 if (X * Y * Z > ThreadMax) {
2192 Diag(Loc: AL.getLoc(), DiagID: diag::err_hlsl_numthreads_invalid) << ThreadMax;
2193 return;
2194 }
2195
2196 HLSLNumThreadsAttr *NewAttr = mergeNumThreadsAttr(D, AL, X, Y, Z);
2197 if (NewAttr)
2198 D->addAttr(A: NewAttr);
2199}
2200
2201static bool isValidWaveSizeValue(unsigned Value) {
2202 return llvm::isPowerOf2_32(Value) && Value >= 4 && Value <= 128;
2203}
2204
2205void SemaHLSL::handleWaveSizeAttr(Decl *D, const ParsedAttr &AL) {
2206 // validate that the wavesize argument is a power of 2 between 4 and 128
2207 // inclusive
2208 unsigned SpelledArgsCount = AL.getNumArgs();
2209 if (SpelledArgsCount == 0 || SpelledArgsCount > 3)
2210 return;
2211
2212 uint32_t Min;
2213 if (!SemaRef.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: Min))
2214 return;
2215
2216 uint32_t Max = 0;
2217 if (SpelledArgsCount > 1 &&
2218 !SemaRef.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 1), Val&: Max))
2219 return;
2220
2221 uint32_t Preferred = 0;
2222 if (SpelledArgsCount > 2 &&
2223 !SemaRef.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 2), Val&: Preferred))
2224 return;
2225
2226 if (SpelledArgsCount > 2) {
2227 if (!isValidWaveSizeValue(Value: Preferred)) {
2228 Diag(Loc: AL.getArgAsExpr(Arg: 2)->getExprLoc(),
2229 DiagID: diag::err_attribute_power_of_two_in_range)
2230 << AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize
2231 << Preferred;
2232 return;
2233 }
2234 // Preferred not in range.
2235 if (Preferred < Min || Preferred > Max) {
2236 Diag(Loc: AL.getArgAsExpr(Arg: 2)->getExprLoc(),
2237 DiagID: diag::err_attribute_power_of_two_in_range)
2238 << AL << Min << Max << Preferred;
2239 return;
2240 }
2241 } else if (SpelledArgsCount > 1) {
2242 if (!isValidWaveSizeValue(Value: Max)) {
2243 Diag(Loc: AL.getArgAsExpr(Arg: 1)->getExprLoc(),
2244 DiagID: diag::err_attribute_power_of_two_in_range)
2245 << AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize << Max;
2246 return;
2247 }
2248 if (Max < Min) {
2249 Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_invalid) << AL << 1;
2250 return;
2251 } else if (Max == Min) {
2252 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attr_min_eq_max) << AL;
2253 }
2254 } else {
2255 if (!isValidWaveSizeValue(Value: Min)) {
2256 Diag(Loc: AL.getArgAsExpr(Arg: 0)->getExprLoc(),
2257 DiagID: diag::err_attribute_power_of_two_in_range)
2258 << AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize << Min;
2259 return;
2260 }
2261 }
2262
2263 HLSLWaveSizeAttr *NewAttr =
2264 mergeWaveSizeAttr(D, AL, Min, Max, Preferred, SpelledArgsCount);
2265 if (NewAttr)
2266 D->addAttr(A: NewAttr);
2267}
2268
2269void SemaHLSL::handleVkExtBuiltinInputAttr(Decl *D, const ParsedAttr &AL) {
2270 uint32_t ID;
2271 if (!SemaRef.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: ID))
2272 return;
2273 D->addAttr(A: ::new (getASTContext())
2274 HLSLVkExtBuiltinInputAttr(getASTContext(), AL, ID));
2275}
2276
2277void SemaHLSL::handleVkExtBuiltinOutputAttr(Decl *D, const ParsedAttr &AL) {
2278 uint32_t ID;
2279 if (!SemaRef.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: ID))
2280 return;
2281 D->addAttr(A: ::new (getASTContext())
2282 HLSLVkExtBuiltinOutputAttr(getASTContext(), AL, ID));
2283}
2284
2285void SemaHLSL::handleVkPushConstantAttr(Decl *D, const ParsedAttr &AL) {
2286 D->addAttr(A: ::new (getASTContext())
2287 HLSLVkPushConstantAttr(getASTContext(), AL));
2288}
2289
2290void SemaHLSL::handleVkConstantIdAttr(Decl *D, const ParsedAttr &AL) {
2291 uint32_t Id;
2292 if (!SemaRef.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: Id))
2293 return;
2294 HLSLVkConstantIdAttr *NewAttr = mergeVkConstantIdAttr(D, AL, Id);
2295 if (NewAttr)
2296 D->addAttr(A: NewAttr);
2297}
2298
2299void SemaHLSL::handleVkBindingAttr(Decl *D, const ParsedAttr &AL) {
2300 uint32_t Binding = 0;
2301 if (!SemaRef.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: Binding))
2302 return;
2303 uint32_t Set = 0;
2304 if (AL.getNumArgs() > 1 &&
2305 !SemaRef.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 1), Val&: Set))
2306 return;
2307
2308 D->addAttr(A: ::new (getASTContext())
2309 HLSLVkBindingAttr(getASTContext(), AL, Binding, Set));
2310}
2311
2312void SemaHLSL::handleVkLocationAttr(Decl *D, const ParsedAttr &AL) {
2313 uint32_t Location;
2314 if (!SemaRef.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: Location))
2315 return;
2316
2317 // vk::builtin and vk::location mutually exclusive
2318 if (const auto *BuiltIn = D->getAttr<HLSLVkBuiltInAttr>()) {
2319 Diag(Loc: AL.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
2320 << AL << BuiltIn
2321 << (AL.isRegularKeywordAttribute() ||
2322 BuiltIn->isRegularKeywordAttribute());
2323 Diag(Loc: BuiltIn->getLocation(), DiagID: diag::note_conflicting_attribute);
2324 }
2325
2326 D->addAttr(A: ::new (getASTContext())
2327 HLSLVkLocationAttr(getASTContext(), AL, Location));
2328}
2329
2330void SemaHLSL::handleVkBuiltInAttr(Decl *D, const ParsedAttr &AL) {
2331 StringRef BuiltIn;
2332 SourceLocation ArgLoc;
2333 if (!SemaRef.checkStringLiteralArgumentAttr(Attr: AL, ArgNum: 0, Str&: BuiltIn, ArgLocation: &ArgLoc))
2334 return;
2335
2336 static constexpr StringRef SupportedBuiltIns[] = {
2337 "PointSize", // TODO: uncomment build-ins as they're fully implemented
2338 // "HelperInvocation", "BaseVertex", "BaseInstance",
2339 // "DrawIndex", "DeviceIndex", "ViewportMaskNV",
2340 };
2341 if (!llvm::is_contained(Range: SupportedBuiltIns, Element: BuiltIn)) {
2342 std::string Quoted;
2343 llvm::raw_string_ostream OS(Quoted);
2344 llvm::interleaveComma(c: SupportedBuiltIns, os&: OS,
2345 each_fn: [&](StringRef S) { OS << "'" << S << "'"; });
2346 Diag(Loc: ArgLoc, DiagID: diag::err_hlsl_vk_builtin_unsupported_value)
2347 << BuiltIn << Quoted;
2348 return;
2349 }
2350
2351 // vk::builtin and vk::location mutually exclusive.
2352 if (const auto *Location = D->getAttr<HLSLVkLocationAttr>()) {
2353 Diag(Loc: AL.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
2354 << AL << Location
2355 << (AL.isRegularKeywordAttribute() ||
2356 Location->isRegularKeywordAttribute());
2357 Diag(Loc: Location->getLoc(), DiagID: diag::note_conflicting_attribute);
2358 }
2359
2360 D->addAttr(A: ::new (getASTContext())
2361 HLSLVkBuiltInAttr(getASTContext(), AL, BuiltIn));
2362}
2363
2364void SemaHLSL::handleSemanticAttr(Decl *D, const ParsedAttr &AL) {
2365 uint32_t IndexValue(0), ExplicitIndex(0);
2366 if (!SemaRef.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: IndexValue) ||
2367 !SemaRef.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 1), Val&: ExplicitIndex)) {
2368 assert(0 && "HLSLUnparsedSemantic is expected to have 2 int arguments.");
2369 }
2370 assert(IndexValue > 0 ? ExplicitIndex : true);
2371
2372 SemanticKind Kind = llvm::hlsl::getSemanticKind(SemanticName: AL.getAttrName()->getName());
2373 if (Kind == SemanticKind::Invalid) {
2374 Diag(Loc: AL.getLoc(), DiagID: diag::err_hlsl_unknown_semantic) << AL;
2375 return;
2376 }
2377
2378 switch (Kind) {
2379 // FIXME: These semantics do not yet have CodeGen support.
2380 case SemanticKind::RenderTargetArrayIndex:
2381 case SemanticKind::ViewPortArrayIndex:
2382 case SemanticKind::ClipDistance:
2383 case SemanticKind::CullDistance:
2384 case SemanticKind::OutputControlPointID:
2385 case SemanticKind::DomainLocation:
2386 case SemanticKind::GSInstanceID:
2387 case SemanticKind::Coverage:
2388 case SemanticKind::InnerCoverage:
2389 case SemanticKind::Depth:
2390 case SemanticKind::DepthLessEqual:
2391 case SemanticKind::DepthGreaterEqual:
2392 case SemanticKind::StencilRef:
2393 case SemanticKind::TessFactor:
2394 case SemanticKind::InsideTessFactor:
2395 case SemanticKind::CullPrimitive:
2396 Diag(Loc: AL.getLoc(), DiagID: diag::err_hlsl_unknown_semantic) << AL;
2397 return;
2398 default:
2399 break;
2400 }
2401
2402 D->addAttr(A: HLSLParsedSemanticAttr::Create(
2403 Ctx&: getASTContext(), SemanticName: AL.getAttrName()->getName(), SemanticIndex: IndexValue, CommonInfo: AL));
2404}
2405
2406void SemaHLSL::handlePackOffsetAttr(Decl *D, const ParsedAttr &AL) {
2407 if (!isa<VarDecl>(Val: D) || !isa<HLSLBufferDecl>(Val: D->getDeclContext())) {
2408 Diag(Loc: AL.getLoc(), DiagID: diag::err_hlsl_attr_invalid_ast_node)
2409 << AL << "shader constant in a constant buffer";
2410 return;
2411 }
2412
2413 uint32_t SubComponent;
2414 if (!SemaRef.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: SubComponent))
2415 return;
2416 uint32_t Component;
2417 if (!SemaRef.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 1), Val&: Component))
2418 return;
2419
2420 QualType T = cast<VarDecl>(Val: D)->getType().getCanonicalType();
2421 // Check if T is an array or struct type.
2422 // TODO: mark matrix type as aggregate type.
2423 bool IsAggregateTy = (T->isArrayType() || T->isStructureType());
2424
2425 // Check Component is valid for T.
2426 if (Component) {
2427 unsigned Size = getASTContext().getTypeSize(T);
2428 if (IsAggregateTy) {
2429 Diag(Loc: AL.getLoc(), DiagID: diag::err_hlsl_invalid_register_or_packoffset);
2430 return;
2431 } else {
2432 // Make sure Component + sizeof(T) <= 4.
2433 if ((Component * 32 + Size) > 128) {
2434 Diag(Loc: AL.getLoc(), DiagID: diag::err_hlsl_packoffset_cross_reg_boundary);
2435 return;
2436 }
2437 QualType EltTy = T;
2438 if (const auto *VT = T->getAs<VectorType>())
2439 EltTy = VT->getElementType();
2440 unsigned Align = getASTContext().getTypeAlign(T: EltTy);
2441 if (Align > 32 && Component == 1) {
2442 // NOTE: Component 3 will hit err_hlsl_packoffset_cross_reg_boundary.
2443 // So we only need to check Component 1 here.
2444 Diag(Loc: AL.getLoc(), DiagID: diag::err_hlsl_packoffset_alignment_mismatch)
2445 << Align << EltTy;
2446 return;
2447 }
2448 }
2449 }
2450
2451 D->addAttr(A: ::new (getASTContext()) HLSLPackOffsetAttr(
2452 getASTContext(), AL, SubComponent, Component));
2453}
2454
2455void SemaHLSL::handleShaderAttr(Decl *D, const ParsedAttr &AL) {
2456 StringRef Str;
2457 SourceLocation ArgLoc;
2458 if (!SemaRef.checkStringLiteralArgumentAttr(Attr: AL, ArgNum: 0, Str, ArgLocation: &ArgLoc))
2459 return;
2460
2461 llvm::Triple::EnvironmentType ShaderType;
2462 if (!HLSLShaderAttr::ConvertStrToEnvironmentType(Val: Str, Out&: ShaderType)) {
2463 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_type_not_supported)
2464 << AL << Str << ArgLoc;
2465 return;
2466 }
2467
2468 // FIXME: check function match the shader stage.
2469
2470 HLSLShaderAttr *NewAttr = mergeShaderAttr(D, AL, ShaderType);
2471 if (NewAttr)
2472 D->addAttr(A: NewAttr);
2473}
2474
2475bool clang::CreateHLSLAttributedResourceType(
2476 Sema &S, QualType Wrapped, ArrayRef<const Attr *> AttrList,
2477 QualType &ResType, HLSLAttributedResourceLocInfo *LocInfo,
2478 Expr *SampleCountExpr) {
2479 assert(AttrList.size() && "expected list of resource attributes");
2480
2481 QualType ContainedTy = QualType();
2482 TypeSourceInfo *ContainedTyInfo = nullptr;
2483 SourceLocation LocBegin = AttrList[0]->getRange().getBegin();
2484 SourceLocation LocEnd = AttrList[0]->getRange().getEnd();
2485
2486 HLSLAttributedResourceType::Attributes ResAttrs;
2487
2488 bool HasResourceClass = false;
2489 bool HasResourceDimension = false;
2490 for (const Attr *A : AttrList) {
2491 if (!A)
2492 continue;
2493 LocEnd = A->getRange().getEnd();
2494 switch (A->getKind()) {
2495 case attr::HLSLResourceClass: {
2496 ResourceClass RC = cast<HLSLResourceClassAttr>(Val: A)->getResourceClass();
2497 if (HasResourceClass) {
2498 S.Diag(Loc: A->getLocation(), DiagID: ResAttrs.ResourceClass == RC
2499 ? diag::warn_duplicate_attribute_exact
2500 : diag::warn_duplicate_attribute)
2501 << A;
2502 return false;
2503 }
2504 ResAttrs.ResourceClass = RC;
2505 HasResourceClass = true;
2506 break;
2507 }
2508 case attr::HLSLResourceDimension: {
2509 llvm::dxil::ResourceDimension RD =
2510 cast<HLSLResourceDimensionAttr>(Val: A)->getDimension();
2511 if (HasResourceDimension) {
2512 S.Diag(Loc: A->getLocation(), DiagID: ResAttrs.ResourceDimension == RD
2513 ? diag::warn_duplicate_attribute_exact
2514 : diag::warn_duplicate_attribute)
2515 << A;
2516 return false;
2517 }
2518 ResAttrs.ResourceDimension = RD;
2519 HasResourceDimension = true;
2520 break;
2521 }
2522 case attr::HLSLIsROV:
2523 if (ResAttrs.IsROV) {
2524 S.Diag(Loc: A->getLocation(), DiagID: diag::warn_duplicate_attribute_exact) << A;
2525 return false;
2526 }
2527 ResAttrs.IsROV = true;
2528 break;
2529 case attr::HLSLRawBuffer:
2530 if (ResAttrs.RawBuffer) {
2531 S.Diag(Loc: A->getLocation(), DiagID: diag::warn_duplicate_attribute_exact) << A;
2532 return false;
2533 }
2534 ResAttrs.RawBuffer = true;
2535 break;
2536 case attr::HLSLIsArray:
2537 if (ResAttrs.IsArray) {
2538 S.Diag(Loc: A->getLocation(), DiagID: diag::warn_duplicate_attribute_exact) << A;
2539 return false;
2540 }
2541 ResAttrs.IsArray = true;
2542 break;
2543 case attr::HLSLIsMultiSampled:
2544 if (ResAttrs.SampleCountExpr) {
2545 S.Diag(Loc: A->getLocation(), DiagID: diag::warn_duplicate_attribute_exact) << A;
2546 return false;
2547 }
2548 // A bare [[hlsl::is_ms]] carries no count, so default it to 0, the same
2549 // value Texture2DMS<T> gets from its template parameter.
2550 ResAttrs.SampleCountExpr =
2551 SampleCountExpr
2552 ? SampleCountExpr
2553 : IntegerLiteral::Create(C: S.Context, V: llvm::APInt(32, 0),
2554 type: S.Context.IntTy, l: A->getLocation());
2555 break;
2556 case attr::HLSLIsCounter:
2557 if (ResAttrs.IsCounter) {
2558 S.Diag(Loc: A->getLocation(), DiagID: diag::warn_duplicate_attribute_exact) << A;
2559 return false;
2560 }
2561 ResAttrs.IsCounter = true;
2562 break;
2563 case attr::HLSLContainedType: {
2564 const HLSLContainedTypeAttr *CTAttr = cast<HLSLContainedTypeAttr>(Val: A);
2565 QualType Ty = CTAttr->getType();
2566 if (!ContainedTy.isNull()) {
2567 S.Diag(Loc: A->getLocation(), DiagID: ContainedTy == Ty
2568 ? diag::warn_duplicate_attribute_exact
2569 : diag::warn_duplicate_attribute)
2570 << A;
2571 return false;
2572 }
2573 ContainedTy = Ty;
2574 ContainedTyInfo = CTAttr->getTypeLoc();
2575 break;
2576 }
2577 default:
2578 llvm_unreachable("unhandled resource attribute type");
2579 }
2580 }
2581
2582 if (!HasResourceClass) {
2583 S.Diag(Loc: AttrList.back()->getRange().getEnd(),
2584 DiagID: diag::err_hlsl_missing_resource_class);
2585 return false;
2586 }
2587
2588 ResType = S.getASTContext().getHLSLAttributedResourceType(
2589 Wrapped, Contained: ContainedTy, Attrs: ResAttrs);
2590
2591 if (LocInfo && ContainedTyInfo) {
2592 LocInfo->Range = SourceRange(LocBegin, LocEnd);
2593 LocInfo->ContainedTyInfo = ContainedTyInfo;
2594 }
2595 return true;
2596}
2597
2598// Validates and creates an HLSL attribute that is applied as type attribute on
2599// HLSL resource. The attributes are collected in HLSLResourcesTypeAttrs and at
2600// the end of the declaration they are applied to the declaration type by
2601// wrapping it in HLSLAttributedResourceType.
2602bool SemaHLSL::handleResourceTypeAttr(QualType T, const ParsedAttr &AL) {
2603 // only allow resource type attributes on intangible types
2604 if (!T->isHLSLResourceType()) {
2605 Diag(Loc: AL.getLoc(), DiagID: diag::err_hlsl_attribute_needs_intangible_type)
2606 << AL << getASTContext().HLSLResourceTy;
2607 return false;
2608 }
2609
2610 // validate number of arguments
2611 if (!AL.checkExactlyNumArgs(S&: SemaRef, Num: AL.getMinArgs()))
2612 return false;
2613
2614 Attr *A = nullptr;
2615
2616 AttributeCommonInfo ACI(
2617 AL.getLoc(), AttributeScopeInfo(AL.getScopeName(), AL.getScopeLoc()),
2618 AttributeCommonInfo::NoSemaHandlerAttribute,
2619 {
2620 AttributeCommonInfo::AS_CXX11, 0, false /*IsAlignas*/,
2621 false /*IsRegularKeywordAttribute*/
2622 });
2623
2624 switch (AL.getKind()) {
2625 case ParsedAttr::AT_HLSLResourceClass: {
2626 StringRef Identifier;
2627 SourceLocation ArgLoc;
2628 if (!SemaRef.checkStringLiteralArgumentAttr(Attr: AL, ArgNum: 0, Str&: Identifier, ArgLocation: &ArgLoc))
2629 return false;
2630
2631 // Validate resource class value
2632 ResourceClass RC;
2633 if (!HLSLResourceClassAttr::ConvertStrToResourceClass(Val: Identifier, Out&: RC)) {
2634 Diag(Loc: ArgLoc, DiagID: diag::warn_attribute_type_not_supported)
2635 << "ResourceClass" << Identifier;
2636 return false;
2637 }
2638 A = HLSLResourceClassAttr::Create(Ctx&: getASTContext(), ResourceClass: RC, CommonInfo: ACI);
2639 break;
2640 }
2641
2642 case ParsedAttr::AT_HLSLResourceDimension: {
2643 StringRef Identifier;
2644 SourceLocation ArgLoc;
2645 if (!SemaRef.checkStringLiteralArgumentAttr(Attr: AL, ArgNum: 0, Str&: Identifier, ArgLocation: &ArgLoc))
2646 return false;
2647
2648 // Validate resource dimension value
2649 llvm::dxil::ResourceDimension RD;
2650 if (!HLSLResourceDimensionAttr::ConvertStrToResourceDimension(Val: Identifier,
2651 Out&: RD)) {
2652 Diag(Loc: ArgLoc, DiagID: diag::warn_attribute_type_not_supported)
2653 << "ResourceDimension" << Identifier;
2654 return false;
2655 }
2656 A = HLSLResourceDimensionAttr::Create(Ctx&: getASTContext(), Dimension: RD, CommonInfo: ACI);
2657 break;
2658 }
2659
2660 case ParsedAttr::AT_HLSLIsROV:
2661 A = HLSLIsROVAttr::Create(Ctx&: getASTContext(), CommonInfo: ACI);
2662 break;
2663
2664 case ParsedAttr::AT_HLSLRawBuffer:
2665 A = HLSLRawBufferAttr::Create(Ctx&: getASTContext(), CommonInfo: ACI);
2666 break;
2667
2668 case ParsedAttr::AT_HLSLIsCounter:
2669 A = HLSLIsCounterAttr::Create(Ctx&: getASTContext(), CommonInfo: ACI);
2670 break;
2671
2672 case ParsedAttr::AT_HLSLIsArray:
2673 A = HLSLIsArrayAttr::Create(Ctx&: getASTContext(), CommonInfo: ACI);
2674 break;
2675
2676 case ParsedAttr::AT_HLSLIsMultiSampled:
2677 A = HLSLIsMultiSampledAttr::Create(Ctx&: getASTContext(), CommonInfo: ACI);
2678 break;
2679
2680 case ParsedAttr::AT_HLSLContainedType: {
2681 if (AL.getNumArgs() != 1 && !AL.hasParsedType()) {
2682 Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments) << AL << 1;
2683 return false;
2684 }
2685
2686 TypeSourceInfo *TSI = nullptr;
2687 QualType QT = SemaRef.GetTypeFromParser(Ty: AL.getTypeArg(), TInfo: &TSI);
2688 assert(TSI && "no type source info for attribute argument");
2689 if (SemaRef.RequireCompleteType(Loc: TSI->getTypeLoc().getBeginLoc(), T: QT,
2690 DiagID: diag::err_incomplete_type))
2691 return false;
2692 A = HLSLContainedTypeAttr::Create(Ctx&: getASTContext(), Type: TSI, CommonInfo: ACI);
2693 break;
2694 }
2695
2696 default:
2697 llvm_unreachable("unhandled HLSL attribute");
2698 }
2699
2700 HLSLResourcesTypeAttrs.emplace_back(Args&: A);
2701 return true;
2702}
2703
2704// Combines all resource type attributes and creates HLSLAttributedResourceType.
2705QualType SemaHLSL::ProcessResourceTypeAttributes(QualType CurrentType) {
2706 if (!HLSLResourcesTypeAttrs.size())
2707 return CurrentType;
2708
2709 QualType QT = CurrentType;
2710 HLSLAttributedResourceLocInfo LocInfo;
2711 if (CreateHLSLAttributedResourceType(S&: SemaRef, Wrapped: CurrentType,
2712 AttrList: HLSLResourcesTypeAttrs, ResType&: QT, LocInfo: &LocInfo)) {
2713 const HLSLAttributedResourceType *RT =
2714 cast<HLSLAttributedResourceType>(Val: QT.getTypePtr());
2715
2716 // Temporarily store TypeLoc information for the new type.
2717 // It will be transferred to HLSLAttributesResourceTypeLoc
2718 // shortly after the type is created by TypeSpecLocFiller which
2719 // will call the TakeLocForHLSLAttribute method below.
2720 LocsForHLSLAttributedResources.insert(KV: std::pair(RT, LocInfo));
2721 }
2722 HLSLResourcesTypeAttrs.clear();
2723 return QT;
2724}
2725
2726// Returns source location for the HLSLAttributedResourceType
2727HLSLAttributedResourceLocInfo
2728SemaHLSL::TakeLocForHLSLAttribute(const HLSLAttributedResourceType *RT) {
2729 HLSLAttributedResourceLocInfo LocInfo = {};
2730 auto I = LocsForHLSLAttributedResources.find(Val: RT);
2731 if (I != LocsForHLSLAttributedResources.end()) {
2732 LocInfo = I->second;
2733 LocsForHLSLAttributedResources.erase(I);
2734 return LocInfo;
2735 }
2736 LocInfo.Range = SourceRange();
2737 return LocInfo;
2738}
2739
2740// Walks though the global variable declaration, collects all resource binding
2741// requirements and adds them to Bindings
2742void SemaHLSL::collectResourceBindingsOnUserRecordDecl(const VarDecl *VD,
2743 const RecordType *RT) {
2744 const RecordDecl *RD = RT->getDecl()->getDefinitionOrSelf();
2745 for (FieldDecl *FD : RD->fields()) {
2746 const Type *Ty = FD->getType()->getUnqualifiedDesugaredType();
2747
2748 // Unwrap arrays
2749 // FIXME: Calculate array size while unwrapping
2750 assert(!Ty->isIncompleteArrayType() &&
2751 "incomplete arrays inside user defined types are not supported");
2752 while (Ty->isConstantArrayType()) {
2753 const ConstantArrayType *CAT = cast<ConstantArrayType>(Val: Ty);
2754 Ty = CAT->getElementType()->getUnqualifiedDesugaredType();
2755 }
2756
2757 if (!Ty->isRecordType())
2758 continue;
2759
2760 if (const HLSLAttributedResourceType *AttrResType =
2761 HLSLAttributedResourceType::findHandleTypeOnResource(RT: Ty)) {
2762 // Add a new DeclBindingInfo to Bindings if it does not already exist
2763 ResourceClass RC = AttrResType->getAttrs().ResourceClass;
2764 DeclBindingInfo *DBI = Bindings.getDeclBindingInfo(VD, ResClass: RC);
2765 if (!DBI)
2766 Bindings.addDeclBindingInfo(VD, ResClass: RC);
2767 } else if (const RecordType *RT = dyn_cast<RecordType>(Val: Ty)) {
2768 // Recursively scan embedded struct or class; it would be nice to do this
2769 // without recursion, but tricky to correctly calculate the size of the
2770 // binding, which is something we are probably going to need to do later
2771 // on. Hopefully nesting of structs in structs too many levels is
2772 // unlikely.
2773 collectResourceBindingsOnUserRecordDecl(VD, RT);
2774 }
2775 }
2776}
2777
2778// Diagnose localized register binding errors for a single binding; does not
2779// diagnose resource binding on user record types, that will be done later
2780// in processResourceBindingOnDecl based on the information collected in
2781// collectResourceBindingsOnVarDecl.
2782// Returns false if the register binding is not valid.
2783static bool DiagnoseLocalRegisterBinding(Sema &S, SourceLocation &ArgLoc,
2784 Decl *D, RegisterType RegType,
2785 bool SpecifiedSpace) {
2786 int RegTypeNum = static_cast<int>(RegType);
2787
2788 // check if the decl type is groupshared
2789 if (D->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
2790 S.Diag(Loc: ArgLoc, DiagID: diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2791 return false;
2792 }
2793
2794 // Cbuffers and Tbuffers are HLSLBufferDecl types
2795 if (HLSLBufferDecl *CBufferOrTBuffer = dyn_cast<HLSLBufferDecl>(Val: D)) {
2796 ResourceClass RC = CBufferOrTBuffer->isCBuffer() ? ResourceClass::CBuffer
2797 : ResourceClass::SRV;
2798 if (RegType == getRegisterType(RC))
2799 return true;
2800
2801 S.Diag(Loc: D->getLocation(), DiagID: diag::err_hlsl_binding_type_mismatch)
2802 << RegTypeNum;
2803 return false;
2804 }
2805
2806 // Samplers, UAVs, and SRVs are VarDecl types
2807 assert(isa<VarDecl>(D) && "D is expected to be VarDecl or HLSLBufferDecl");
2808 VarDecl *VD = cast<VarDecl>(Val: D);
2809
2810 // Resource
2811 if (const HLSLAttributedResourceType *AttrResType =
2812 HLSLAttributedResourceType::findHandleTypeOnResource(
2813 RT: VD->getType().getTypePtr())) {
2814 if (RegType == getRegisterType(ResTy: AttrResType))
2815 return true;
2816
2817 S.Diag(Loc: D->getLocation(), DiagID: diag::err_hlsl_binding_type_mismatch)
2818 << RegTypeNum;
2819 return false;
2820 }
2821
2822 const clang::Type *Ty = VD->getType().getTypePtr();
2823 while (Ty->isArrayType())
2824 Ty = Ty->getArrayElementTypeNoTypeQual();
2825
2826 // Basic types
2827 if (Ty->isArithmeticType() || Ty->isVectorType()) {
2828 bool DeclaredInCOrTBuffer = isa<HLSLBufferDecl>(Val: D->getDeclContext());
2829 if (SpecifiedSpace && !DeclaredInCOrTBuffer)
2830 S.Diag(Loc: ArgLoc, DiagID: diag::err_hlsl_space_on_global_constant);
2831
2832 if (!DeclaredInCOrTBuffer && (Ty->isIntegralType(Ctx: S.getASTContext()) ||
2833 Ty->isFloatingType() || Ty->isVectorType())) {
2834 // Register annotation on default constant buffer declaration ($Globals)
2835 if (RegType == RegisterType::CBuffer)
2836 S.Diag(Loc: ArgLoc, DiagID: diag::warn_hlsl_deprecated_register_type_b);
2837 else if (RegType != RegisterType::C)
2838 S.Diag(Loc: ArgLoc, DiagID: diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2839 else
2840 return true;
2841 } else {
2842 if (RegType == RegisterType::C)
2843 S.Diag(Loc: ArgLoc, DiagID: diag::warn_hlsl_register_type_c_packoffset);
2844 else
2845 S.Diag(Loc: ArgLoc, DiagID: diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2846 }
2847 return false;
2848 }
2849 if (Ty->isRecordType())
2850 // RecordTypes will be diagnosed in processResourceBindingOnDecl
2851 // that is called from ActOnVariableDeclarator
2852 return true;
2853
2854 // Anything else is an error
2855 S.Diag(Loc: ArgLoc, DiagID: diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2856 return false;
2857}
2858
2859static bool ValidateMultipleRegisterAnnotations(Sema &S, Decl *TheDecl,
2860 RegisterType regType) {
2861 // make sure that there are no two register annotations
2862 // applied to the decl with the same register type
2863 bool RegisterTypesDetected[5] = {false};
2864 RegisterTypesDetected[static_cast<int>(regType)] = true;
2865
2866 for (auto it = TheDecl->attr_begin(); it != TheDecl->attr_end(); ++it) {
2867 if (HLSLResourceBindingAttr *attr =
2868 dyn_cast<HLSLResourceBindingAttr>(Val: *it)) {
2869
2870 RegisterType otherRegType = attr->getRegisterType();
2871 if (RegisterTypesDetected[static_cast<int>(otherRegType)]) {
2872 int otherRegTypeNum = static_cast<int>(otherRegType);
2873 S.Diag(Loc: TheDecl->getLocation(),
2874 DiagID: diag::err_hlsl_duplicate_register_annotation)
2875 << otherRegTypeNum;
2876 return false;
2877 }
2878 RegisterTypesDetected[static_cast<int>(otherRegType)] = true;
2879 }
2880 }
2881 return true;
2882}
2883
2884static bool DiagnoseHLSLRegisterAttribute(Sema &S, SourceLocation &ArgLoc,
2885 Decl *D, RegisterType RegType,
2886 bool SpecifiedSpace) {
2887
2888 // exactly one of these two types should be set
2889 assert(((isa<VarDecl>(D) && !isa<HLSLBufferDecl>(D)) ||
2890 (!isa<VarDecl>(D) && isa<HLSLBufferDecl>(D))) &&
2891 "expecting VarDecl or HLSLBufferDecl");
2892
2893 // check if the declaration contains resource matching the register type
2894 if (!DiagnoseLocalRegisterBinding(S, ArgLoc, D, RegType, SpecifiedSpace))
2895 return false;
2896
2897 // next, if multiple register annotations exist, check that none conflict.
2898 return ValidateMultipleRegisterAnnotations(S, TheDecl: D, regType: RegType);
2899}
2900
2901// return false if the slot count exceeds the limit, true otherwise
2902static bool AccumulateHLSLResourceSlots(QualType Ty, uint64_t &StartSlot,
2903 const uint64_t &Limit,
2904 const ResourceClass ResClass,
2905 ASTContext &Ctx,
2906 uint64_t ArrayCount = 1) {
2907 Ty = Ty.getCanonicalType();
2908 const Type *T = Ty.getTypePtr();
2909
2910 // Early exit if already overflowed
2911 if (StartSlot > Limit)
2912 return false;
2913
2914 // Case 1: array type
2915 if (const auto *AT = dyn_cast<ArrayType>(Val: T)) {
2916 uint64_t Count = 1;
2917
2918 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT))
2919 Count = CAT->getSize().getZExtValue();
2920
2921 QualType ElemTy = AT->getElementType();
2922 return AccumulateHLSLResourceSlots(Ty: ElemTy, StartSlot, Limit, ResClass, Ctx,
2923 ArrayCount: ArrayCount * Count);
2924 }
2925
2926 // Case 2: resource leaf
2927 if (auto ResTy = dyn_cast<HLSLAttributedResourceType>(Val: T)) {
2928 // First ensure this resource counts towards the corresponding
2929 // register type limit.
2930 if (ResTy->getAttrs().ResourceClass != ResClass)
2931 return true;
2932
2933 // Validate highest slot used
2934 uint64_t EndSlot = StartSlot + ArrayCount - 1;
2935 if (EndSlot > Limit)
2936 return false;
2937
2938 // Advance SlotCount past the consumed range
2939 StartSlot = EndSlot + 1;
2940 return true;
2941 }
2942
2943 // Case 3: struct / record
2944 if (const auto *RT = dyn_cast<RecordType>(Val: T)) {
2945 const RecordDecl *RD = RT->getDecl();
2946
2947 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
2948 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
2949 if (!AccumulateHLSLResourceSlots(Ty: Base.getType(), StartSlot, Limit,
2950 ResClass, Ctx, ArrayCount))
2951 return false;
2952 }
2953 }
2954
2955 for (const FieldDecl *Field : RD->fields()) {
2956 if (!AccumulateHLSLResourceSlots(Ty: Field->getType(), StartSlot, Limit,
2957 ResClass, Ctx, ArrayCount))
2958 return false;
2959 }
2960
2961 return true;
2962 }
2963
2964 // Case 4: everything else
2965 return true;
2966}
2967
2968// return true if there is something invalid, false otherwise
2969static bool ValidateRegisterNumber(uint64_t SlotNum, Decl *TheDecl,
2970 ASTContext &Ctx, RegisterType RegTy) {
2971 const uint64_t Limit = UINT32_MAX;
2972 if (SlotNum > Limit)
2973 return true;
2974
2975 // after verifying the number doesn't exceed uint32max, we don't need
2976 // to look further into c or i register types
2977 if (RegTy == RegisterType::C || RegTy == RegisterType::I)
2978 return false;
2979
2980 if (VarDecl *VD = dyn_cast<VarDecl>(Val: TheDecl)) {
2981 uint64_t BaseSlot = SlotNum;
2982
2983 if (!AccumulateHLSLResourceSlots(Ty: VD->getType(), StartSlot&: SlotNum, Limit,
2984 ResClass: getResourceClass(RT: RegTy), Ctx))
2985 return true;
2986
2987 // After AccumulateHLSLResourceSlots runs, SlotNum is now
2988 // the first free slot; last used was SlotNum - 1
2989 return (BaseSlot > Limit);
2990 }
2991 // handle the cbuffer/tbuffer case
2992 if (isa<HLSLBufferDecl>(Val: TheDecl))
2993 // resources cannot be put within a cbuffer, so no need
2994 // to analyze the structure since the register number
2995 // won't be pushed any higher.
2996 return (SlotNum > Limit);
2997
2998 // we don't expect any other decl type, so fail
2999 llvm_unreachable("unexpected decl type");
3000}
3001
3002void SemaHLSL::handleResourceBindingAttr(Decl *TheDecl, const ParsedAttr &AL) {
3003 if (VarDecl *VD = dyn_cast<VarDecl>(Val: TheDecl)) {
3004 QualType Ty = VD->getType();
3005 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val&: Ty))
3006 Ty = IAT->getElementType();
3007 if (SemaRef.RequireCompleteType(Loc: TheDecl->getBeginLoc(), T: Ty,
3008 DiagID: diag::err_incomplete_type))
3009 return;
3010 }
3011
3012 StringRef Slot = "";
3013 StringRef Space = "";
3014 SourceLocation SlotLoc, SpaceLoc;
3015
3016 if (!AL.isArgIdent(Arg: 0)) {
3017 Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_type)
3018 << AL << AANT_ArgumentIdentifier;
3019 return;
3020 }
3021 IdentifierLoc *Loc = AL.getArgAsIdent(Arg: 0);
3022
3023 if (AL.getNumArgs() == 2) {
3024 Slot = Loc->getIdentifierInfo()->getName();
3025 SlotLoc = Loc->getLoc();
3026 if (!AL.isArgIdent(Arg: 1)) {
3027 Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_type)
3028 << AL << AANT_ArgumentIdentifier;
3029 return;
3030 }
3031 Loc = AL.getArgAsIdent(Arg: 1);
3032 Space = Loc->getIdentifierInfo()->getName();
3033 SpaceLoc = Loc->getLoc();
3034 } else {
3035 StringRef Str = Loc->getIdentifierInfo()->getName();
3036 if (Str.starts_with(Prefix: "space")) {
3037 Space = Str;
3038 SpaceLoc = Loc->getLoc();
3039 } else {
3040 Slot = Str;
3041 SlotLoc = Loc->getLoc();
3042 Space = "space0";
3043 }
3044 }
3045
3046 RegisterType RegType = RegisterType::SRV;
3047 std::optional<unsigned> SlotNum;
3048 unsigned SpaceNum = 0;
3049
3050 // Validate slot
3051 if (!Slot.empty()) {
3052 if (!convertToRegisterType(Slot, RT: &RegType)) {
3053 Diag(Loc: SlotLoc, DiagID: diag::err_hlsl_binding_type_invalid) << Slot.substr(Start: 0, N: 1);
3054 return;
3055 }
3056 if (RegType == RegisterType::I) {
3057 Diag(Loc: SlotLoc, DiagID: diag::warn_hlsl_deprecated_register_type_i);
3058 return;
3059 }
3060 const StringRef SlotNumStr = Slot.substr(Start: 1);
3061
3062 uint64_t N;
3063
3064 // validate that the slot number is a non-empty number
3065 if (SlotNumStr.getAsInteger(Radix: 10, Result&: N)) {
3066 Diag(Loc: SlotLoc, DiagID: diag::err_hlsl_unsupported_register_number);
3067 return;
3068 }
3069
3070 // Validate register number. It should not exceed UINT32_MAX,
3071 // including if the resource type is an array that starts
3072 // before UINT32_MAX, but ends afterwards.
3073 if (ValidateRegisterNumber(SlotNum: N, TheDecl, Ctx&: getASTContext(), RegTy: RegType)) {
3074 Diag(Loc: SlotLoc, DiagID: diag::err_hlsl_register_number_too_large);
3075 return;
3076 }
3077
3078 // the slot number has been validated and does not exceed UINT32_MAX
3079 SlotNum = (unsigned)N;
3080 }
3081
3082 // Validate space
3083 if (!Space.starts_with(Prefix: "space")) {
3084 Diag(Loc: SpaceLoc, DiagID: diag::err_hlsl_expected_space) << Space;
3085 return;
3086 }
3087 StringRef SpaceNumStr = Space.substr(Start: 5);
3088 if (SpaceNumStr.getAsInteger(Radix: 10, Result&: SpaceNum)) {
3089 Diag(Loc: SpaceLoc, DiagID: diag::err_hlsl_expected_space) << Space;
3090 return;
3091 }
3092
3093 // If we have slot, diagnose it is the right register type for the decl
3094 if (SlotNum.has_value())
3095 if (!DiagnoseHLSLRegisterAttribute(S&: SemaRef, ArgLoc&: SlotLoc, D: TheDecl, RegType,
3096 SpecifiedSpace: !SpaceLoc.isInvalid()))
3097 return;
3098
3099 HLSLResourceBindingAttr *NewAttr =
3100 HLSLResourceBindingAttr::Create(Ctx&: getASTContext(), Slot, Space, CommonInfo: AL);
3101 if (NewAttr) {
3102 NewAttr->setBinding(RT: RegType, SlotNum, SpaceNum);
3103 TheDecl->addAttr(A: NewAttr);
3104 }
3105}
3106
3107void SemaHLSL::handleParamModifierAttr(Decl *D, const ParsedAttr &AL) {
3108 HLSLParamModifierAttr *NewAttr = mergeParamModifierAttr(
3109 D, AL,
3110 Spelling: static_cast<HLSLParamModifierAttr::Spelling>(AL.getSemanticSpelling()));
3111 if (NewAttr)
3112 D->addAttr(A: NewAttr);
3113}
3114
3115static bool isMatrixType(QualType QT) {
3116 const Type *Ty = QT->getUnqualifiedDesugaredType();
3117 return Ty->isDependentType() || Ty->isConstantMatrixType();
3118}
3119
3120/// Walks the existing AttributedType sugar of \p T looking for a previously
3121/// applied HLSLRowMajor/HLSLColumnMajor marker. If one is found, populates
3122/// \p ExistingKind with its attr::Kind and returns true.
3123static bool findExistingMatrixLayoutMarker(QualType T,
3124 attr::Kind &ExistingKind) {
3125 QualType Cur = T;
3126 while (const auto *AT = Cur->getAs<AttributedType>()) {
3127 attr::Kind K = AT->getAttrKind();
3128 if (K == attr::HLSLRowMajor || K == attr::HLSLColumnMajor) {
3129 ExistingKind = K;
3130 return true;
3131 }
3132 Cur = AT->getModifiedType();
3133 }
3134 return false;
3135}
3136
3137Attr *SemaHLSL::buildMatrixLayoutTypeAttr(QualType T, const ParsedAttr &AL) {
3138 if (T.isNull())
3139 return nullptr;
3140
3141 ASTContext &Ctx = getASTContext();
3142 attr::Kind AttrK = AL.getKind() == ParsedAttr::AT_HLSLRowMajor
3143 ? attr::HLSLRowMajor
3144 : attr::HLSLColumnMajor;
3145
3146 // For non-dependent types, the operand must be a matrix.
3147 if (!T->isDependentType() && !isMatrixType(QT: T)) {
3148 Diag(Loc: AL.getLoc(), DiagID: diag::err_hlsl_matrix_layout_non_matrix)
3149 << AL.getAttrName();
3150 AL.setInvalid();
3151 return nullptr;
3152 }
3153
3154 // Conflict / duplicate detection by walking existing sugar.
3155 attr::Kind ExistingKind;
3156 if (findExistingMatrixLayoutMarker(T, ExistingKind)) {
3157 if (ExistingKind == AttrK) {
3158 Diag(Loc: AL.getLoc(), DiagID: diag::warn_duplicate_attribute_exact)
3159 << AL.getAttrName();
3160 Diag(Loc: AL.getLoc(), DiagID: diag::note_previous_attribute);
3161 return nullptr;
3162 }
3163 IdentifierInfo *ExistingII = &Ctx.Idents.get(
3164 Name: ExistingKind == attr::HLSLRowMajor ? "row_major" : "column_major");
3165 Diag(Loc: AL.getLoc(), DiagID: diag::err_hlsl_matrix_layout_conflict)
3166 << AL.getAttrName() << ExistingII;
3167 Diag(Loc: AL.getLoc(), DiagID: diag::note_conflicting_attribute);
3168 AL.setInvalid();
3169 return nullptr;
3170 }
3171
3172 if (AttrK == attr::HLSLRowMajor)
3173 return ::new (Ctx) HLSLRowMajorAttr(Ctx, AL);
3174 return ::new (Ctx) HLSLColumnMajorAttr(Ctx, AL);
3175}
3176
3177// Re-validates an HLSL `row_major` / `column_major` attribute after template
3178// substitution. The parse-time check in `buildMatrixLayoutTypeAttr` is skipped
3179// for dependent types; `TransformAttributedType` calls this once the type is
3180// concrete. Returns `true` (and emits a diagnostic) if the substituted type is
3181// not a matrix or array of matrices, signaling the caller to abort the
3182// transform.
3183bool SemaHLSL::diagnoseMatrixLayoutInstantiation(attr::Kind K, QualType T,
3184 SourceLocation Loc) {
3185 if (K != attr::HLSLRowMajor && K != attr::HLSLColumnMajor)
3186 return false;
3187 if (T.isNull() || T->isDependentType())
3188 return false;
3189 if (isMatrixType(QT: T))
3190 return false;
3191 IdentifierInfo *II = &getASTContext().Idents.get(
3192 Name: K == attr::HLSLRowMajor ? "row_major" : "column_major");
3193 Diag(Loc, DiagID: diag::err_hlsl_matrix_layout_non_matrix) << II;
3194 return true;
3195}
3196
3197// Transpose and matrix mul need to read the destination layout.
3198// Elementwise builtins reuse the operand layout instead.
3199namespace {
3200
3201using llvm::dxil::BarrierMemoryTypeFlag;
3202using llvm::dxil::BarrierSemanticFlag;
3203
3204template <typename T> constexpr uint64_t barrierFlagValue(T Flag) {
3205 return llvm::to_underlying(Flag);
3206}
3207
3208/// This class implements reachable HLSL diagnostics.
3209///
3210/// It diagnoses unavailable APIs in default and relaxed availability modes.
3211/// It also validates Barrier calls in all availability modes.
3212///
3213/// This is done by traversing the AST of all shader entry point functions
3214/// and of all exported functions, and any functions that are referenced
3215/// from this AST. In other words, any functions that are reachable from
3216/// the entry points.
3217class DiagnoseHLSLAvailability : public DynamicRecursiveASTVisitor {
3218 Sema &SemaRef;
3219 bool DiagnoseAvailability;
3220
3221 // Stack of functions to be scaned
3222 llvm::SmallVector<const FunctionDecl *, 8> DeclsToScan;
3223
3224 // Tracks which environments functions have been scanned in.
3225 //
3226 // Maps FunctionDecl to an unsigned number that represents the set of shader
3227 // environments the function has been scanned for.
3228 // The llvm::Triple::EnvironmentType enum values for shader stages guaranteed
3229 // to be numbered from llvm::Triple::Pixel to llvm::Triple::Amplification
3230 // (verified by static_asserts in Triple.cpp), we can use it to index
3231 // individual bits in the set, as long as we shift the values to start with 0
3232 // by subtracting the value of llvm::Triple::Pixel first.
3233 //
3234 // The N'th bit in the set will be set if the function has been scanned
3235 // in shader environment whose llvm::Triple::EnvironmentType integer value
3236 // equals (llvm::Triple::Pixel + N).
3237 //
3238 // For example, if a function has been scanned in compute and pixel stage
3239 // environment, the value will be 0x21 (100001 binary) because:
3240 //
3241 // (int)(llvm::Triple::Pixel - llvm::Triple::Pixel) == 0
3242 // (int)(llvm::Triple::Compute - llvm::Triple::Pixel) == 5
3243 //
3244 // A FunctionDecl is mapped to 0 (or not included in the map) if it has not
3245 // been scanned in any environment.
3246 llvm::DenseMap<const FunctionDecl *, unsigned> ScannedDecls;
3247
3248 // Do not access these directly, use the get/set methods below to make
3249 // sure the values are in sync
3250 llvm::Triple::EnvironmentType CurrentShaderEnvironment;
3251 unsigned CurrentShaderStageBit;
3252
3253 // True if scanning a function that was already scanned in a different
3254 // shader stage context. Suppress stage-independent diagnostics because
3255 // they were reported during the first scan.
3256 bool ReportOnlyShaderStageIssues;
3257
3258 // Helper methods for dealing with current stage context / environment
3259 void SetShaderStageContext(llvm::Triple::EnvironmentType ShaderType) {
3260 static_assert(sizeof(unsigned) >= 4);
3261 assert(HLSLShaderAttr::isValidShaderType(ShaderType));
3262 assert((unsigned)(ShaderType - llvm::Triple::Pixel) < 31 &&
3263 "ShaderType is too big for this bitmap"); // 31 is reserved for
3264 // "unknown"
3265
3266 unsigned bitmapIndex = ShaderType - llvm::Triple::Pixel;
3267 CurrentShaderEnvironment = ShaderType;
3268 CurrentShaderStageBit = (1 << bitmapIndex);
3269 }
3270
3271 void SetUnknownShaderStageContext() {
3272 CurrentShaderEnvironment = llvm::Triple::UnknownEnvironment;
3273 CurrentShaderStageBit = (1 << 31);
3274 }
3275
3276 llvm::Triple::EnvironmentType GetCurrentShaderEnvironment() const {
3277 return CurrentShaderEnvironment;
3278 }
3279
3280 bool InUnknownShaderStageContext() const {
3281 return CurrentShaderEnvironment == llvm::Triple::UnknownEnvironment;
3282 }
3283
3284 // Helper methods for dealing with shader stage bitmap
3285 void AddToScannedFunctions(const FunctionDecl *FD) {
3286 unsigned &ScannedStages = ScannedDecls[FD];
3287 ScannedStages |= CurrentShaderStageBit;
3288 }
3289
3290 unsigned GetScannedStages(const FunctionDecl *FD) { return ScannedDecls[FD]; }
3291
3292 bool WasAlreadyScannedInCurrentStage(const FunctionDecl *FD) {
3293 return WasAlreadyScannedInCurrentStage(ScannerStages: GetScannedStages(FD));
3294 }
3295
3296 bool WasAlreadyScannedInCurrentStage(unsigned ScannerStages) {
3297 return ScannerStages & CurrentShaderStageBit;
3298 }
3299
3300 static bool NeverBeenScanned(unsigned ScannedStages) {
3301 return ScannedStages == 0;
3302 }
3303
3304 // Scanning methods
3305 void HandleFunctionOrMethodRef(FunctionDecl *FD, Expr *RefExpr);
3306 void CheckDeclAvailability(NamedDecl *D, const AvailabilityAttr *AA,
3307 SourceRange Range);
3308 const AvailabilityAttr *FindAvailabilityAttr(const Decl *D);
3309 bool HasMatchingEnvironmentOrNone(const AvailabilityAttr *AA);
3310 void DiagnoseBarrierCall(CallExpr *CE);
3311 uint64_t DiagnoseBarrierGroupMemory(Expr *MemoryArg, uint64_t MemoryFlags,
3312 bool HasVisibleGroup, bool IsAllMemory);
3313 uint64_t DiagnoseBarrierNodeMemory(Expr *MemoryArg, uint64_t MemoryFlags,
3314 bool HasKnownStage, bool IsAllMemory);
3315 void DiagnoseBarrierGroupSemantic(Expr *SemanticArg, uint64_t SemanticFlags,
3316 bool HasVisibleGroup);
3317 void DiagnoseBarrierScope(Expr *SemanticArg, uint64_t MemoryFlags,
3318 uint64_t SemanticFlags);
3319
3320public:
3321 DiagnoseHLSLAvailability(Sema &SemaRef, bool DiagnoseAvailability)
3322 : SemaRef(SemaRef), DiagnoseAvailability(DiagnoseAvailability),
3323 CurrentShaderEnvironment(llvm::Triple::UnknownEnvironment),
3324 CurrentShaderStageBit(0), ReportOnlyShaderStageIssues(false) {}
3325
3326 // AST traversal methods
3327 void RunOnTranslationUnit(const TranslationUnitDecl *TU);
3328 void RunOnFunction(const FunctionDecl *FD);
3329
3330 bool VisitDeclRefExpr(DeclRefExpr *DRE) override {
3331 FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(Val: DRE->getDecl());
3332 if (FD)
3333 HandleFunctionOrMethodRef(FD, RefExpr: DRE);
3334 return true;
3335 }
3336
3337 bool VisitMemberExpr(MemberExpr *ME) override {
3338 FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(Val: ME->getMemberDecl());
3339 if (FD)
3340 HandleFunctionOrMethodRef(FD, RefExpr: ME);
3341 return true;
3342 }
3343
3344 bool VisitCallExpr(CallExpr *CE) override {
3345 DiagnoseBarrierCall(CE);
3346 return true;
3347 }
3348};
3349
3350uint64_t DiagnoseHLSLAvailability::DiagnoseBarrierGroupMemory(
3351 Expr *MemoryArg, uint64_t MemoryFlags, bool HasVisibleGroup,
3352 bool IsAllMemory) {
3353 const uint64_t GroupSharedMemory =
3354 barrierFlagValue(Flag: BarrierMemoryTypeFlag::GroupSharedMemory);
3355 if (HasVisibleGroup || (MemoryFlags & GroupSharedMemory) == 0)
3356 return MemoryFlags;
3357
3358 if (!IsAllMemory) {
3359 SemaRef.Diag(Loc: MemoryArg->getExprLoc(),
3360 DiagID: diag::err_hlsl_barrier_flag_requires_group)
3361 << 0;
3362 return MemoryFlags;
3363 }
3364
3365 return MemoryFlags & ~GroupSharedMemory;
3366}
3367
3368uint64_t DiagnoseHLSLAvailability::DiagnoseBarrierNodeMemory(
3369 Expr *MemoryArg, uint64_t MemoryFlags, bool HasKnownStage,
3370 bool IsAllMemory) {
3371 const uint64_t NodeMemory =
3372 barrierFlagValue(Flag: BarrierMemoryTypeFlag::NodeMemory);
3373 if (!HasKnownStage || (MemoryFlags & NodeMemory) == 0)
3374 return MemoryFlags;
3375
3376 if (!IsAllMemory) {
3377 SemaRef.Diag(Loc: MemoryArg->getExprLoc(),
3378 DiagID: diag::err_hlsl_barrier_node_memory_requires_node);
3379 return MemoryFlags;
3380 }
3381
3382 return MemoryFlags & ~NodeMemory;
3383}
3384
3385void DiagnoseHLSLAvailability::DiagnoseBarrierGroupSemantic(
3386 Expr *SemanticArg, uint64_t SemanticFlags, bool HasVisibleGroup) {
3387 if (HasVisibleGroup ||
3388 (SemanticFlags & barrierFlagValue(Flag: BarrierSemanticFlag::GroupFlags)) == 0)
3389 return;
3390
3391 SemaRef.Diag(Loc: SemanticArg->getExprLoc(),
3392 DiagID: diag::err_hlsl_barrier_flag_requires_group)
3393 << ((SemanticFlags & barrierFlagValue(Flag: BarrierSemanticFlag::GroupSync)) !=
3394 0
3395 ? 1
3396 : 2);
3397}
3398
3399void DiagnoseHLSLAvailability::DiagnoseBarrierScope(Expr *SemanticArg,
3400 uint64_t MemoryFlags,
3401 uint64_t SemanticFlags) {
3402 if (ReportOnlyShaderStageIssues)
3403 return;
3404
3405 const uint64_t DeviceScopeMemory =
3406 barrierFlagValue(Flag: BarrierMemoryTypeFlag::UAVMemory) |
3407 barrierFlagValue(Flag: BarrierMemoryTypeFlag::NodeInputMemory);
3408 if ((SemanticFlags & barrierFlagValue(Flag: BarrierSemanticFlag::DeviceScope)) !=
3409 0 &&
3410 (MemoryFlags & DeviceScopeMemory) == 0)
3411 SemaRef.Diag(Loc: SemanticArg->getExprLoc(),
3412 DiagID: diag::err_hlsl_barrier_scope_requires_memory)
3413 << 1;
3414 if ((SemanticFlags & barrierFlagValue(Flag: BarrierSemanticFlag::GroupScope)) !=
3415 0 &&
3416 MemoryFlags == 0)
3417 SemaRef.Diag(Loc: SemanticArg->getExprLoc(),
3418 DiagID: diag::err_hlsl_barrier_scope_requires_memory)
3419 << 0;
3420}
3421
3422void DiagnoseHLSLAvailability::DiagnoseBarrierCall(CallExpr *CE) {
3423 const FunctionDecl *FD = CE->getDirectCallee();
3424 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_hlsl_barrier)
3425 return;
3426
3427 const llvm::Triple::EnvironmentType Stage = GetCurrentShaderEnvironment();
3428 const bool HasKnownStage = !InUnknownShaderStageContext();
3429 const bool HasVisibleGroup =
3430 !HasKnownStage || Stage == llvm::Triple::Compute ||
3431 Stage == llvm::Triple::Mesh || Stage == llvm::Triple::Amplification;
3432
3433 uint64_t MemoryFlags = barrierFlagValue(Flag: BarrierMemoryTypeFlag::ValidMask);
3434 Expr *MemoryArg = CE->getArg(Arg: 0);
3435 if (MemoryArg->getType()->isUnsignedIntegerType()) {
3436 std::optional<llvm::APSInt> Value =
3437 MemoryArg->getIntegerConstantExpr(Ctx: SemaRef.Context);
3438 if (!Value)
3439 return;
3440 MemoryFlags = Value->getZExtValue();
3441 const bool IsAllMemory =
3442 MemoryFlags == barrierFlagValue(Flag: BarrierMemoryTypeFlag::ValidMask);
3443
3444 MemoryFlags = DiagnoseBarrierGroupMemory(MemoryArg, MemoryFlags,
3445 HasVisibleGroup, IsAllMemory);
3446 MemoryFlags = DiagnoseBarrierNodeMemory(MemoryArg, MemoryFlags,
3447 HasKnownStage, IsAllMemory);
3448 } else if (!HasVisibleGroup) {
3449 SemaRef.Diag(Loc: MemoryArg->getExprLoc(),
3450 DiagID: diag::err_hlsl_barrier_resource_requires_group);
3451 return;
3452 }
3453
3454 Expr *SemanticArg = CE->getArg(Arg: 1);
3455 std::optional<llvm::APSInt> Value =
3456 SemanticArg->getIntegerConstantExpr(Ctx: SemaRef.Context);
3457 if (!Value)
3458 return;
3459 const uint64_t SemanticFlags = Value->getZExtValue();
3460
3461 DiagnoseBarrierGroupSemantic(SemanticArg, SemanticFlags, HasVisibleGroup);
3462
3463 if (MemoryArg->getType()->isUnsignedIntegerType())
3464 DiagnoseBarrierScope(SemanticArg, MemoryFlags, SemanticFlags);
3465}
3466
3467void DiagnoseHLSLAvailability::HandleFunctionOrMethodRef(FunctionDecl *FD,
3468 Expr *RefExpr) {
3469 assert((isa<DeclRefExpr>(RefExpr) || isa<MemberExpr>(RefExpr)) &&
3470 "expected DeclRefExpr or MemberExpr");
3471
3472 if (DiagnoseAvailability)
3473 if (const AvailabilityAttr *AA = FindAvailabilityAttr(D: FD))
3474 CheckDeclAvailability(
3475 D: FD, AA, Range: SourceRange(RefExpr->getBeginLoc(), RefExpr->getEndLoc()));
3476
3477 // has a definition -> add to stack to be scanned
3478 const FunctionDecl *FDWithBody = nullptr;
3479 if (FD->hasBody(Definition&: FDWithBody) && !WasAlreadyScannedInCurrentStage(FD: FDWithBody))
3480 DeclsToScan.push_back(Elt: FDWithBody);
3481}
3482
3483void DiagnoseHLSLAvailability::RunOnTranslationUnit(
3484 const TranslationUnitDecl *TU) {
3485 const TargetInfo &TargetInfo = SemaRef.getASTContext().getTargetInfo();
3486 std::string &EntryName = TargetInfo.getTargetOpts().HLSLEntry;
3487 bool IsLibraryShader = TargetInfo.getTriple().getEnvironment() ==
3488 llvm::Triple::EnvironmentType::Library;
3489 SourceLocation EntryLoc{};
3490
3491 // Iterate over all shader entry functions and library exports, and for those
3492 // that have a body (definiton), run diag scan on each, setting appropriate
3493 // shader environment context based on whether it is a shader entry function
3494 // or an exported function. Exported functions can be in namespaces and in
3495 // export declarations so we need to scan those declaration contexts as well.
3496 llvm::SmallVector<const DeclContext *, 8> DeclContextsToScan;
3497 DeclContextsToScan.push_back(Elt: TU);
3498
3499 while (!DeclContextsToScan.empty()) {
3500 const DeclContext *DC = DeclContextsToScan.pop_back_val();
3501 for (auto &D : DC->decls()) {
3502 // do not scan implicit declaration generated by the implementation
3503 if (D->isImplicit())
3504 continue;
3505
3506 // for namespace or export declaration add the context to the list to be
3507 // scanned later
3508 if (llvm::dyn_cast<NamespaceDecl>(Val: D) || llvm::dyn_cast<ExportDecl>(Val: D)) {
3509 DeclContextsToScan.push_back(Elt: llvm::dyn_cast<DeclContext>(Val: D));
3510 continue;
3511 }
3512
3513 // skip over other decls or function decls without body
3514 const FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(Val: D);
3515 if (!FD || !FD->isThisDeclarationADefinition())
3516 continue;
3517
3518 // shader entry point
3519 if (HLSLShaderAttr *ShaderAttr = FD->getAttr<HLSLShaderAttr>()) {
3520 if (!IsLibraryShader && FD->getName() == EntryName) {
3521 if (EntryLoc.isValid()) {
3522 SemaRef.Diag(Loc: FD->getLocation(),
3523 DiagID: diag::err_hlsl_ambiguous_entry_point)
3524 << EntryName;
3525 SemaRef.Diag(Loc: EntryLoc, DiagID: diag::note_previous_declaration_as)
3526 << EntryName;
3527 return;
3528 }
3529 EntryLoc = FD->getLocation();
3530 }
3531 SetShaderStageContext(ShaderAttr->getType());
3532 RunOnFunction(FD);
3533 continue;
3534 }
3535 // exported library function
3536 // FIXME: replace this loop with external linkage check once issue #92071
3537 // is resolved
3538 bool isExport = FD->isInExportDeclContext();
3539 if (!isExport) {
3540 for (const auto *Redecl : FD->redecls()) {
3541 if (Redecl->isInExportDeclContext()) {
3542 isExport = true;
3543 break;
3544 }
3545 }
3546 }
3547 if (isExport) {
3548 SetUnknownShaderStageContext();
3549 RunOnFunction(FD);
3550 continue;
3551 }
3552 }
3553 }
3554
3555 if (!IsLibraryShader && EntryLoc.isInvalid()) {
3556 SemaRef.Diag(Loc: TU->getLocation(), DiagID: diag::err_hlsl_missing_entry_point)
3557 << EntryName;
3558 return;
3559 }
3560}
3561
3562void DiagnoseHLSLAvailability::RunOnFunction(const FunctionDecl *FD) {
3563 assert(DeclsToScan.empty() && "DeclsToScan should be empty");
3564 DeclsToScan.push_back(Elt: FD);
3565
3566 while (!DeclsToScan.empty()) {
3567 // Take one decl from the stack and check it by traversing its AST.
3568 // For any CallExpr found during the traversal add it's callee to the top of
3569 // the stack to be processed next. Functions already processed are stored in
3570 // ScannedDecls.
3571 const FunctionDecl *FD = DeclsToScan.pop_back_val();
3572
3573 // Decl was already scanned
3574 const unsigned ScannedStages = GetScannedStages(FD);
3575 if (WasAlreadyScannedInCurrentStage(ScannerStages: ScannedStages))
3576 continue;
3577
3578 ReportOnlyShaderStageIssues = !NeverBeenScanned(ScannedStages);
3579
3580 AddToScannedFunctions(FD);
3581 TraverseStmt(S: FD->getBody());
3582 }
3583}
3584
3585bool DiagnoseHLSLAvailability::HasMatchingEnvironmentOrNone(
3586 const AvailabilityAttr *AA) {
3587 const IdentifierInfo *IIEnvironment = AA->getEnvironment();
3588 if (!IIEnvironment)
3589 return true;
3590
3591 llvm::Triple::EnvironmentType CurrentEnv = GetCurrentShaderEnvironment();
3592 if (CurrentEnv == llvm::Triple::UnknownEnvironment)
3593 return false;
3594
3595 llvm::Triple::EnvironmentType AttrEnv =
3596 AvailabilityAttr::getEnvironmentType(Environment: IIEnvironment->getName());
3597
3598 return CurrentEnv == AttrEnv;
3599}
3600
3601const AvailabilityAttr *
3602DiagnoseHLSLAvailability::FindAvailabilityAttr(const Decl *D) {
3603 AvailabilityAttr const *PartialMatch = nullptr;
3604 // Check each AvailabilityAttr to find the one for this platform.
3605 // For multiple attributes with the same platform try to find one for this
3606 // environment.
3607 for (const auto *A : D->attrs()) {
3608 if (const auto *Avail = dyn_cast<AvailabilityAttr>(Val: A)) {
3609 const AvailabilityAttr *EffectiveAvail = Avail->getEffectiveAttr();
3610 StringRef AttrPlatform = EffectiveAvail->getPlatform()->getName();
3611 StringRef TargetPlatform =
3612 SemaRef.getASTContext().getTargetInfo().getPlatformName();
3613
3614 // Match the platform name.
3615 if (AttrPlatform == TargetPlatform) {
3616 // Find the best matching attribute for this environment
3617 if (HasMatchingEnvironmentOrNone(AA: EffectiveAvail))
3618 return Avail;
3619 PartialMatch = Avail;
3620 }
3621 }
3622 }
3623 return PartialMatch;
3624}
3625
3626// Check availability against target shader model version and current shader
3627// stage and emit diagnostic
3628void DiagnoseHLSLAvailability::CheckDeclAvailability(NamedDecl *D,
3629 const AvailabilityAttr *AA,
3630 SourceRange Range) {
3631
3632 const IdentifierInfo *IIEnv = AA->getEnvironment();
3633
3634 if (!IIEnv) {
3635 // The availability attribute does not have environment -> it depends only
3636 // on shader model version and not on specific the shader stage.
3637
3638 // Skip emitting the diagnostics if the diagnostic mode is set to
3639 // strict (-fhlsl-strict-availability) because all relevant diagnostics
3640 // were already emitted in the DiagnoseUnguardedAvailability scan
3641 // (SemaAvailability.cpp).
3642 if (SemaRef.getLangOpts().HLSLStrictAvailability)
3643 return;
3644
3645 // Do not report shader-stage-independent issues if scanning a function
3646 // that was already scanned in a different shader stage context (they would
3647 // be duplicate)
3648 if (ReportOnlyShaderStageIssues)
3649 return;
3650
3651 } else {
3652 // The availability attribute has environment -> we need to know
3653 // the current stage context to property diagnose it.
3654 if (InUnknownShaderStageContext())
3655 return;
3656 }
3657
3658 // Check introduced version and if environment matches
3659 bool EnvironmentMatches = HasMatchingEnvironmentOrNone(AA);
3660 VersionTuple Introduced = AA->getIntroduced();
3661 VersionTuple TargetVersion =
3662 SemaRef.Context.getTargetInfo().getPlatformMinVersion();
3663
3664 if (TargetVersion >= Introduced && EnvironmentMatches)
3665 return;
3666
3667 // Emit diagnostic message
3668 const TargetInfo &TI = SemaRef.getASTContext().getTargetInfo();
3669 llvm::StringRef PlatformName(
3670 AvailabilityAttr::getPrettyPlatformName(Platform: TI.getPlatformName()));
3671
3672 llvm::StringRef CurrentEnvStr =
3673 llvm::Triple::getEnvironmentTypeName(Kind: GetCurrentShaderEnvironment());
3674
3675 llvm::StringRef AttrEnvStr =
3676 AA->getEnvironment() ? AA->getEnvironment()->getName() : "";
3677 bool UseEnvironment = !AttrEnvStr.empty();
3678
3679 if (EnvironmentMatches) {
3680 SemaRef.Diag(Loc: Range.getBegin(), DiagID: diag::warn_hlsl_availability)
3681 << Range << D << PlatformName << Introduced.getAsString()
3682 << UseEnvironment << CurrentEnvStr;
3683 } else {
3684 SemaRef.Diag(Loc: Range.getBegin(), DiagID: diag::warn_hlsl_availability_unavailable)
3685 << Range << D;
3686 }
3687
3688 SemaRef.Diag(Loc: D->getLocation(), DiagID: diag::note_partial_availability_specified_here)
3689 << D << PlatformName << Introduced.getAsString()
3690 << SemaRef.Context.getTargetInfo().getPlatformMinVersion().getAsString()
3691 << UseEnvironment << AttrEnvStr << CurrentEnvStr;
3692}
3693
3694} // namespace
3695
3696void SemaHLSL::ActOnEndOfTranslationUnit(TranslationUnitDecl *TU) {
3697 // process default CBuffer - create buffer layout struct and invoke codegenCGH
3698 if (!DefaultCBufferDecls.empty()) {
3699 HLSLBufferDecl *DefaultCBuffer = HLSLBufferDecl::CreateDefaultCBuffer(
3700 C&: SemaRef.getASTContext(), LexicalParent: SemaRef.getCurLexicalContext(),
3701 DefaultCBufferDecls);
3702 addImplicitBindingAttrToDecl(S&: SemaRef, D: DefaultCBuffer, RT: RegisterType::CBuffer,
3703 ImplicitBindingOrderID: getNextImplicitBindingOrderID());
3704 SemaRef.getCurLexicalContext()->addDecl(D: DefaultCBuffer);
3705 createHostLayoutStructForBuffer(S&: SemaRef, BufDecl: DefaultCBuffer);
3706
3707 // Set HasValidPackoffset if any of the decls has a register(c#) annotation;
3708 for (const Decl *VD : DefaultCBufferDecls) {
3709 const HLSLResourceBindingAttr *RBA =
3710 VD->getAttr<HLSLResourceBindingAttr>();
3711 if (RBA && RBA->hasRegisterSlot() &&
3712 RBA->getRegisterType() == HLSLResourceBindingAttr::RegisterType::C) {
3713 DefaultCBuffer->setHasValidPackoffset(true);
3714 break;
3715 }
3716 }
3717
3718 DeclGroupRef DG(DefaultCBuffer);
3719 SemaRef.Consumer.HandleTopLevelDecl(D: DG);
3720 }
3721 diagnoseAvailabilityViolations(TU);
3722}
3723
3724// For resource member access through a global struct array, verify that the
3725// array index selecting the struct element is a constant integer expression.
3726// Returns false if the member expression is invalid.
3727bool SemaHLSL::ActOnResourceMemberAccessExpr(MemberExpr *ME) {
3728 assert((ME->getType()->isHLSLResourceRecord() ||
3729 ME->getType()->isHLSLResourceRecordArray()) &&
3730 "expected member expr to have resource record type or array of them");
3731
3732 // Walk the AST from MemberExpr to the VarDecl of the parent struct instance
3733 // and take note of any non-constant array indexing along the way. If the
3734 // VarDecl we find is a global variable, report error if there was any
3735 // non-constant array index in the resource member access along the way.
3736 const Expr *NonConstIndexExpr = nullptr;
3737 const Expr *E = ME->getBase();
3738 while (E) {
3739 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
3740 if (!NonConstIndexExpr)
3741 return true;
3742
3743 const VarDecl *VD = cast<VarDecl>(Val: DRE->getDecl());
3744 if (!VD->hasGlobalStorage())
3745 return true;
3746
3747 SemaRef.Diag(Loc: NonConstIndexExpr->getExprLoc(),
3748 DiagID: diag::err_hlsl_resource_member_array_access_not_constant);
3749 return false;
3750 }
3751
3752 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: E)) {
3753 const Expr *IdxExpr = ASE->getIdx();
3754 if (!IdxExpr->isIntegerConstantExpr(Ctx: SemaRef.getASTContext()))
3755 NonConstIndexExpr = IdxExpr;
3756 E = ASE->getBase();
3757 } else if (const auto *SubME = dyn_cast<MemberExpr>(Val: E)) {
3758 E = SubME->getBase();
3759 } else if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
3760 E = ICE->getSubExpr();
3761 } else if (isa<CXXThisExpr>(Val: E)) {
3762 return true;
3763 } else {
3764 llvm_unreachable("unexpected expr type in resource member access");
3765 }
3766 }
3767 return true;
3768}
3769
3770NamedDecl *SemaHLSL::getConstantBufferConversionFunction(QualType Type,
3771 CXXRecordDecl *RD) {
3772 QualType AddrSpaceType =
3773 SemaRef.Context.getCanonicalType(T: SemaRef.Context.getAddrSpaceQualType(
3774 T: Type.withConst(), AddressSpace: LangAS::hlsl_constant));
3775 QualType ReturnTy = SemaRef.Context.getCanonicalType(
3776 T: SemaRef.Context.getLValueReferenceType(T: AddrSpaceType));
3777
3778 DeclarationName ConvName =
3779 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
3780 Ty: CanQualType::CreateUnsafe(Other: ReturnTy));
3781 LookupResult ConvR(SemaRef, ConvName, SourceLocation(),
3782 Sema::LookupOrdinaryName);
3783 [[maybe_unused]] bool LookupSucceeded =
3784 SemaRef.LookupQualifiedName(R&: ConvR, LookupCtx: RD);
3785 assert(LookupSucceeded);
3786
3787 for (NamedDecl *D : ConvR) {
3788 if (isa<CXXConversionDecl>(Val: D->getUnderlyingDecl()))
3789 return D;
3790 }
3791 return nullptr;
3792}
3793
3794std::optional<ExprResult>
3795SemaHLSL::tryPerformConstantBufferConversion(Expr *BaseExpr) {
3796 QualType BaseType = BaseExpr->getType();
3797 const HLSLAttributedResourceType *ResTy =
3798 HLSLAttributedResourceType::findHandleTypeOnResource(
3799 RT: BaseType.getTypePtr());
3800 if (!ResTy ||
3801 ResTy->getAttrs().ResourceClass != llvm::dxil::ResourceClass::CBuffer)
3802 return std::nullopt;
3803
3804 QualType TemplateType = ResTy->getContainedType();
3805
3806 NamedDecl *NamedConversionDecl = getConstantBufferConversionFunction(
3807 Type: TemplateType, RD: BaseType->getAsCXXRecordDecl());
3808 assert(NamedConversionDecl &&
3809 "Could not find conversion function for ConstantBuffer.");
3810 auto *ConversionDecl =
3811 cast<CXXConversionDecl>(Val: NamedConversionDecl->getUnderlyingDecl());
3812
3813 return SemaRef.BuildCXXMemberCallExpr(Exp: BaseExpr, FoundDecl: NamedConversionDecl,
3814 Method: ConversionDecl,
3815 /*HadMultipleCandidates=*/false);
3816}
3817
3818void SemaHLSL::diagnoseAvailabilityViolations(TranslationUnitDecl *TU) {
3819 // Strict mode diagnoses availability during the
3820 // DiagnoseUnguardedAvailability scan in SemaAvailability.cpp. The reachable
3821 // function scan must still run to validate Barrier calls.
3822 const TargetInfo &TI = SemaRef.getASTContext().getTargetInfo();
3823 const bool DiagnoseAvailability =
3824 !SemaRef.getLangOpts().HLSLStrictAvailability ||
3825 TI.getTriple().getEnvironment() == llvm::Triple::EnvironmentType::Library;
3826 DiagnoseHLSLAvailability(SemaRef, DiagnoseAvailability)
3827 .RunOnTranslationUnit(TU);
3828}
3829
3830static bool CheckAllArgsHaveSameType(Sema *S, CallExpr *TheCall) {
3831 assert(TheCall->getNumArgs() > 1);
3832 QualType ArgTy0 = TheCall->getArg(Arg: 0)->getType();
3833
3834 for (unsigned I = 1, N = TheCall->getNumArgs(); I < N; ++I) {
3835 if (!S->getASTContext().hasSameUnqualifiedType(
3836 T1: ArgTy0, T2: TheCall->getArg(Arg: I)->getType())) {
3837 S->Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_builtin_incompatible_vector)
3838 << TheCall->getDirectCallee() << /*useAllTerminology*/ true
3839 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
3840 TheCall->getArg(Arg: N - 1)->getEndLoc());
3841 return true;
3842 }
3843 }
3844 return false;
3845}
3846
3847static bool CheckArgTypeMatches(Sema *S, Expr *Arg, QualType ExpectedType) {
3848 QualType ArgType = Arg->getType();
3849 if (!S->getASTContext().hasSameUnqualifiedType(T1: ArgType, T2: ExpectedType)) {
3850 S->Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
3851 << ArgType << ExpectedType << 1 << 0 << 0;
3852 return true;
3853 }
3854 return false;
3855}
3856
3857static bool CheckAllArgTypesAreCorrect(
3858 Sema *S, CallExpr *TheCall,
3859 llvm::function_ref<bool(Sema *S, SourceLocation Loc, int ArgOrdinal,
3860 clang::QualType PassedType)>
3861 Check) {
3862 for (unsigned I = 0; I < TheCall->getNumArgs(); ++I) {
3863 Expr *Arg = TheCall->getArg(Arg: I);
3864 if (Check(S, Arg->getBeginLoc(), I + 1, Arg->getType()))
3865 return true;
3866 }
3867 return false;
3868}
3869
3870static bool CheckFloatRepresentation(Sema *S, SourceLocation Loc,
3871 int ArgOrdinal,
3872 clang::QualType PassedType) {
3873 clang::QualType BaseType =
3874 getElementTypeOf(T: PassedType, /*IncludeMatrix=*/false);
3875 if (!BaseType->isFloat32Type())
3876 return S->Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
3877 << ArgOrdinal << /* scalar or vector of */ 5 << /* no int */ 0
3878 << /* float */ 1 << PassedType;
3879 return false;
3880}
3881
3882static bool CheckFloatOrHalfRepresentation(Sema *S, SourceLocation Loc,
3883 int ArgOrdinal,
3884 clang::QualType PassedType) {
3885 QualType BaseType = getScalarComponentType(T: PassedType);
3886
3887 if (!BaseType->isHalfType() && !BaseType->isFloat32Type())
3888 return S->Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
3889 << ArgOrdinal << /* scalar or vector of */ 5 << /* no int */ 0
3890 << /* half or float */ 2 << PassedType;
3891 return false;
3892}
3893
3894static bool CheckAnyDoubleRepresentation(Sema *S, SourceLocation Loc,
3895 int ArgOrdinal,
3896 clang::QualType PassedType) {
3897 QualType BaseType = getScalarComponentType(T: PassedType);
3898 if (!BaseType->isDoubleType()) {
3899 // FIXME: adopt standard `err_builtin_invalid_arg_type` instead of using
3900 // this custom error.
3901 return S->Diag(Loc, DiagID: diag::err_builtin_requires_double_type)
3902 << ArgOrdinal << PassedType;
3903 }
3904
3905 return false;
3906}
3907
3908static bool CheckModifiableLValue(Sema *S, CallExpr *TheCall,
3909 unsigned ArgIndex) {
3910 auto *Arg = TheCall->getArg(Arg: ArgIndex);
3911 SourceLocation OrigLoc = Arg->getExprLoc();
3912 if (Arg->IgnoreCasts()->isModifiableLvalue(Ctx&: S->Context, Loc: &OrigLoc) ==
3913 Expr::MLV_Valid)
3914 return false;
3915 S->Diag(Loc: OrigLoc, DiagID: diag::error_hlsl_inout_lvalue) << Arg << 0;
3916 return true;
3917}
3918
3919// Verifies that the argument at `ArgIndex` of `TheCall` refers to memory in
3920// one of `AllowedSpaces`. Intended for HLSL builtins (e.g. atomics).
3921static bool CheckArgAddrSpaceOneOf(Sema *S, CallExpr *TheCall,
3922 unsigned ArgIndex,
3923 ArrayRef<LangAS> AllowedSpaces) {
3924 Expr *Arg = TheCall->getArg(Arg: ArgIndex);
3925 QualType LValueTy = Arg->IgnoreCasts()->getType();
3926 if (llvm::is_contained(Range&: AllowedSpaces, Element: LValueTy.getAddressSpace()))
3927 return false;
3928 S->Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_hlsl_atomic_arg_addr_space)
3929 << (ArgIndex + 1) << LValueTy;
3930 return true;
3931}
3932
3933static bool CheckNoDoubleVectors(Sema *S, SourceLocation Loc, int ArgOrdinal,
3934 clang::QualType PassedType) {
3935 const auto *VecTy = PassedType->getAs<VectorType>();
3936 if (!VecTy)
3937 return false;
3938
3939 if (VecTy->getElementType()->isDoubleType())
3940 return S->Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
3941 << ArgOrdinal << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
3942 << PassedType;
3943 return false;
3944}
3945
3946static bool CheckNumericRepresentation(Sema *S, SourceLocation Loc,
3947 int ArgOrdinal,
3948 clang::QualType PassedType) {
3949 if (getScalarComponentType(T: PassedType)->isBooleanType() ||
3950 (!PassedType->hasIntegerRepresentation() &&
3951 !PassedType->hasFloatingRepresentation()))
3952 return S->Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
3953 << ArgOrdinal << /* scalar or vector of */ 5 << /* integer */ 1
3954 << /* fp */ 1 << PassedType;
3955 return false;
3956}
3957
3958static bool CheckUnsignedIntVecRepresentation(Sema *S, SourceLocation Loc,
3959 int ArgOrdinal,
3960 clang::QualType PassedType) {
3961 if (auto *VecTy = PassedType->getAs<VectorType>())
3962 if (VecTy->getElementType()->isUnsignedIntegerType())
3963 return false;
3964
3965 return S->Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
3966 << ArgOrdinal << /* vector of */ 4 << /* uint */ 3 << /* no fp */ 0
3967 << PassedType;
3968}
3969
3970// checks for unsigned ints of all sizes
3971static bool CheckUnsignedIntRepresentation(Sema *S, SourceLocation Loc,
3972 int ArgOrdinal,
3973 clang::QualType PassedType) {
3974 if (!PassedType->hasUnsignedIntegerRepresentation())
3975 return S->Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
3976 << ArgOrdinal << /* scalar or vector of */ 5 << /* unsigned int */ 3
3977 << /* no fp */ 0 << PassedType;
3978 return false;
3979}
3980
3981static bool CheckExpectedBitWidth(Sema *S, CallExpr *TheCall,
3982 unsigned ArgOrdinal, unsigned Width) {
3983 QualType ArgTy = TheCall->getArg(Arg: 0)->getType();
3984 if (auto *VTy = ArgTy->getAs<VectorType>())
3985 ArgTy = VTy->getElementType();
3986 // ensure arg type has expected bit width
3987 uint64_t ElementBitCount =
3988 S->getASTContext().getTypeSizeInChars(T: ArgTy).getQuantity() * 8;
3989 if (ElementBitCount != Width) {
3990 S->Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
3991 DiagID: diag::err_integer_incorrect_bit_count)
3992 << Width << ElementBitCount;
3993 return true;
3994 }
3995 return false;
3996}
3997
3998static void SetElementTypeAsReturnType(Sema *S, CallExpr *TheCall,
3999 QualType ReturnType) {
4000 if (auto *VecTyA = TheCall->getArg(Arg: 0)->getType()->getAs<VectorType>())
4001 ReturnType =
4002 S->Context.getExtVectorType(VectorType: ReturnType, NumElts: VecTyA->getNumElements());
4003 else if (auto *MatTyA =
4004 TheCall->getArg(Arg: 0)->getType()->getAs<ConstantMatrixType>())
4005 ReturnType = S->Context.getConstantMatrixType(
4006 ElementType: ReturnType, NumRows: MatTyA->getNumRows(), NumColumns: MatTyA->getNumColumns());
4007
4008 TheCall->setType(ReturnType);
4009}
4010
4011static bool CheckScalarOrVector(Sema *S, CallExpr *TheCall, QualType Scalar,
4012 unsigned ArgIndex) {
4013 assert(TheCall->getNumArgs() >= ArgIndex);
4014 QualType ArgType = TheCall->getArg(Arg: ArgIndex)->getType();
4015 auto *VTy = ArgType->getAs<VectorType>();
4016 // not the scalar or vector<scalar>
4017 if (!(S->Context.hasSameUnqualifiedType(T1: ArgType, T2: Scalar) ||
4018 (VTy &&
4019 S->Context.hasSameUnqualifiedType(T1: VTy->getElementType(), T2: Scalar)))) {
4020 S->Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
4021 DiagID: diag::err_typecheck_expect_scalar_or_vector)
4022 << ArgType << Scalar;
4023 return true;
4024 }
4025 return false;
4026}
4027
4028static bool CheckScalarOrVectorOrMatrix(Sema *S, CallExpr *TheCall,
4029 QualType Scalar, unsigned ArgIndex) {
4030 assert(TheCall->getNumArgs() > ArgIndex);
4031
4032 Expr *Arg = TheCall->getArg(Arg: ArgIndex);
4033 QualType ArgType = Arg->getType();
4034
4035 // Scalar: T
4036 if (S->Context.hasSameUnqualifiedType(T1: ArgType, T2: Scalar))
4037 return false;
4038
4039 // Vector: vector<T>
4040 if (const auto *VTy = ArgType->getAs<VectorType>()) {
4041 if (S->Context.hasSameUnqualifiedType(T1: VTy->getElementType(), T2: Scalar))
4042 return false;
4043 }
4044
4045 // Matrix: ConstantMatrixType with element type T
4046 if (const auto *MTy = ArgType->getAs<ConstantMatrixType>()) {
4047 if (S->Context.hasSameUnqualifiedType(T1: MTy->getElementType(), T2: Scalar))
4048 return false;
4049 }
4050
4051 // Not a scalar/vector/matrix-of-scalar
4052 S->Diag(Loc: Arg->getBeginLoc(),
4053 DiagID: diag::err_typecheck_expect_scalar_or_vector_or_matrix)
4054 << ArgType << Scalar;
4055 return true;
4056}
4057
4058static bool CheckAnyScalarOrVector(Sema *S, CallExpr *TheCall,
4059 unsigned ArgIndex) {
4060 assert(TheCall->getNumArgs() >= ArgIndex);
4061 QualType ArgType = TheCall->getArg(Arg: ArgIndex)->getType();
4062 auto *VTy = ArgType->getAs<VectorType>();
4063 // not the scalar or vector<scalar>
4064 if (!(ArgType->isScalarType() ||
4065 (VTy && VTy->getElementType()->isScalarType()))) {
4066 S->Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
4067 DiagID: diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
4068 << ArgType << 1;
4069 return true;
4070 }
4071 return false;
4072}
4073
4074static bool CheckAnyScalarOrVectorOrMatrix(Sema *S, CallExpr *TheCall,
4075 unsigned ArgIndex) {
4076 assert(TheCall->getNumArgs() > ArgIndex);
4077 QualType ArgType = TheCall->getArg(Arg: ArgIndex)->getType();
4078 if (ArgType->isDependentType())
4079 return false;
4080
4081 QualType ElementType = ArgType;
4082 if (const auto *VectorTy = ArgType->getAs<VectorType>())
4083 ElementType = VectorTy->getElementType();
4084 else if (const auto *MatrixTy = ArgType->getAs<ConstantMatrixType>())
4085 ElementType = MatrixTy->getElementType();
4086
4087 if (ElementType->isBooleanType())
4088 return false;
4089
4090 if (ElementType->isIntegerType() || ElementType->isRealFloatingType()) {
4091 unsigned BitWidth = S->Context.getTypeSize(T: ElementType);
4092 if (BitWidth == 16 || BitWidth == 32 || BitWidth == 64)
4093 return false;
4094 }
4095
4096 S->Diag(Loc: TheCall->getArg(Arg: ArgIndex)->getBeginLoc(),
4097 DiagID: diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
4098 << ArgType << 2;
4099 return true;
4100}
4101
4102// Check that the argument is not a bool or vector<bool>
4103// Returns true on error
4104static bool CheckNotBoolScalarOrVector(Sema *S, CallExpr *TheCall,
4105 unsigned ArgIndex) {
4106 QualType BoolType = S->getASTContext().BoolTy;
4107 assert(ArgIndex < TheCall->getNumArgs());
4108 QualType ArgType = TheCall->getArg(Arg: ArgIndex)->getType();
4109 auto *VTy = ArgType->getAs<VectorType>();
4110 // is the bool or vector<bool>
4111 if (S->Context.hasSameUnqualifiedType(T1: ArgType, T2: BoolType) ||
4112 (VTy &&
4113 S->Context.hasSameUnqualifiedType(T1: VTy->getElementType(), T2: BoolType))) {
4114 S->Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
4115 DiagID: diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
4116 << ArgType << 0;
4117 return true;
4118 }
4119 return false;
4120}
4121
4122static bool CheckWaveActive(Sema *S, CallExpr *TheCall) {
4123 if (CheckNotBoolScalarOrVector(S, TheCall, ArgIndex: 0))
4124 return true;
4125 return false;
4126}
4127
4128static bool CheckWavePrefix(Sema *S, CallExpr *TheCall) {
4129 if (CheckNotBoolScalarOrVector(S, TheCall, ArgIndex: 0))
4130 return true;
4131 return false;
4132}
4133
4134static bool CheckWaveMultiPrefixMask(Sema *S, CallExpr *TheCall) {
4135 QualType MaskTy = TheCall->getArg(Arg: 1)->getType();
4136 QualType UInt4Ty = S->Context.getExtVectorType(VectorType: S->Context.UnsignedIntTy, NumElts: 4);
4137 if (S->Context.hasSameUnqualifiedType(T1: MaskTy, T2: UInt4Ty))
4138 return false;
4139
4140 S->Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
4141 DiagID: diag::err_typecheck_convert_incompatible)
4142 << MaskTy << UInt4Ty << 1 << 0 << 0;
4143 return true;
4144}
4145
4146static bool CheckBoolSelect(Sema *S, CallExpr *TheCall) {
4147 assert(TheCall->getNumArgs() == 3);
4148 Expr *Arg1 = TheCall->getArg(Arg: 1);
4149 Expr *Arg2 = TheCall->getArg(Arg: 2);
4150 if (!S->Context.hasSameUnqualifiedType(T1: Arg1->getType(), T2: Arg2->getType())) {
4151 S->Diag(Loc: TheCall->getBeginLoc(),
4152 DiagID: diag::err_typecheck_call_different_arg_types)
4153 << Arg1->getType() << Arg2->getType() << Arg1->getSourceRange()
4154 << Arg2->getSourceRange();
4155 return true;
4156 }
4157
4158 TheCall->setType(Arg1->getType());
4159 return false;
4160}
4161
4162static bool CheckVectorSelect(Sema *S, CallExpr *TheCall) {
4163 assert(TheCall->getNumArgs() == 3);
4164 Expr *Arg1 = TheCall->getArg(Arg: 1);
4165 QualType Arg1Ty = Arg1->getType();
4166 Expr *Arg2 = TheCall->getArg(Arg: 2);
4167 QualType Arg2Ty = Arg2->getType();
4168
4169 QualType Arg1ScalarTy = Arg1Ty;
4170 if (auto VTy = Arg1ScalarTy->getAs<VectorType>())
4171 Arg1ScalarTy = VTy->getElementType();
4172
4173 QualType Arg2ScalarTy = Arg2Ty;
4174 if (auto VTy = Arg2ScalarTy->getAs<VectorType>())
4175 Arg2ScalarTy = VTy->getElementType();
4176
4177 if (!S->Context.hasSameUnqualifiedType(T1: Arg1ScalarTy, T2: Arg2ScalarTy))
4178 S->Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_hlsl_builtin_scalar_vector_mismatch)
4179 << /* second and third */ 1 << TheCall->getCallee() << Arg1Ty << Arg2Ty;
4180
4181 QualType Arg0Ty = TheCall->getArg(Arg: 0)->getType();
4182 unsigned Arg0Length = Arg0Ty->getAs<VectorType>()->getNumElements();
4183 unsigned Arg1Length = Arg1Ty->isVectorType()
4184 ? Arg1Ty->getAs<VectorType>()->getNumElements()
4185 : 0;
4186 unsigned Arg2Length = Arg2Ty->isVectorType()
4187 ? Arg2Ty->getAs<VectorType>()->getNumElements()
4188 : 0;
4189 if (Arg1Length > 0 && Arg0Length != Arg1Length) {
4190 S->Diag(Loc: TheCall->getBeginLoc(),
4191 DiagID: diag::err_typecheck_vector_lengths_not_equal)
4192 << Arg0Ty << Arg1Ty << TheCall->getArg(Arg: 0)->getSourceRange()
4193 << Arg1->getSourceRange();
4194 return true;
4195 }
4196
4197 if (Arg2Length > 0 && Arg0Length != Arg2Length) {
4198 S->Diag(Loc: TheCall->getBeginLoc(),
4199 DiagID: diag::err_typecheck_vector_lengths_not_equal)
4200 << Arg0Ty << Arg2Ty << TheCall->getArg(Arg: 0)->getSourceRange()
4201 << Arg2->getSourceRange();
4202 return true;
4203 }
4204
4205 TheCall->setType(
4206 S->getASTContext().getExtVectorType(VectorType: Arg1ScalarTy, NumElts: Arg0Length));
4207 return false;
4208}
4209
4210static bool CheckMatrixSelect(Sema *S, CallExpr *TheCall) {
4211 assert(TheCall->getNumArgs() == 3);
4212 Expr *Arg1 = TheCall->getArg(Arg: 1);
4213 QualType Arg1Ty = Arg1->getType();
4214 Expr *Arg2 = TheCall->getArg(Arg: 2);
4215 QualType Arg2Ty = Arg2->getType();
4216
4217 QualType Arg1ScalarTy = Arg1Ty;
4218 if (auto MTy = Arg1ScalarTy->getAs<ConstantMatrixType>())
4219 Arg1ScalarTy = MTy->getElementType();
4220
4221 QualType Arg2ScalarTy = Arg2Ty;
4222 if (auto MTy = Arg2ScalarTy->getAs<ConstantMatrixType>())
4223 Arg2ScalarTy = MTy->getElementType();
4224
4225 if (!S->Context.hasSameUnqualifiedType(T1: Arg1ScalarTy, T2: Arg2ScalarTy))
4226 S->Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_hlsl_builtin_scalar_vector_mismatch)
4227 << /* second and third */ 1 << TheCall->getCallee() << Arg1Ty << Arg2Ty;
4228
4229 QualType Arg0Ty = TheCall->getArg(Arg: 0)->getType();
4230 auto *Arg0MatTy = Arg0Ty->getAs<ConstantMatrixType>();
4231 unsigned Arg0Rows = Arg0MatTy->getNumRows();
4232 unsigned Arg0Cols = Arg0MatTy->getNumColumns();
4233
4234 for (Expr *Arg : {Arg1, Arg2}) {
4235 auto *MTy = Arg->getType()->getAs<ConstantMatrixType>();
4236 if (MTy &&
4237 (MTy->getNumRows() != Arg0Rows || MTy->getNumColumns() != Arg0Cols)) {
4238 S->Diag(Loc: TheCall->getBeginLoc(),
4239 DiagID: diag::err_typecheck_vector_lengths_not_equal)
4240 << Arg0Ty << Arg->getType() << TheCall->getArg(Arg: 0)->getSourceRange()
4241 << Arg->getSourceRange();
4242 return true;
4243 }
4244 }
4245
4246 TheCall->setType(
4247 S->Context.getConstantMatrixType(ElementType: Arg1ScalarTy, NumRows: Arg0Rows, NumColumns: Arg0Cols));
4248 return false;
4249}
4250
4251static QualType getVectorOrScalarType(Sema &S, QualType BaseType,
4252 unsigned Count) {
4253 return Count > 1 ? S.Context.getExtVectorType(VectorType: BaseType, NumElts: Count) : BaseType;
4254}
4255
4256static bool CheckScalarFloatOperand(Sema &S, CallExpr *TheCall,
4257 unsigned ArgIndex) {
4258 return CheckArgTypeMatches(S: &S, Arg: TheCall->getArg(Arg: ArgIndex), ExpectedType: S.Context.FloatTy);
4259}
4260
4261static bool CheckIndexType(Sema *S, CallExpr *TheCall, unsigned IndexArgIndex) {
4262 assert(TheCall->getNumArgs() > IndexArgIndex && "Index argument missing");
4263 QualType ArgType = TheCall->getArg(Arg: IndexArgIndex)->getType();
4264 QualType IndexTy = ArgType;
4265 unsigned int ActualDim = 1;
4266 if (const auto *VTy = IndexTy->getAs<VectorType>()) {
4267 ActualDim = VTy->getNumElements();
4268 IndexTy = VTy->getElementType();
4269 }
4270 if (!IndexTy->isIntegerType()) {
4271 S->Diag(Loc: TheCall->getArg(Arg: IndexArgIndex)->getBeginLoc(),
4272 DiagID: diag::err_typecheck_expect_int)
4273 << ArgType;
4274 return true;
4275 }
4276
4277 QualType ResourceArgTy = TheCall->getArg(Arg: 0)->getType();
4278 const HLSLAttributedResourceType *ResTy =
4279 ResourceArgTy.getTypePtr()->getAs<HLSLAttributedResourceType>();
4280 assert(ResTy && "Resource argument must be a resource");
4281 HLSLAttributedResourceType::Attributes ResAttrs = ResTy->getAttrs();
4282
4283 unsigned int ExpectedDim = 1;
4284 if (ResAttrs.ResourceDimension != llvm::dxil::ResourceDimension::Unknown)
4285 ExpectedDim = getResourceDimensions(Dim: ResAttrs.ResourceDimension) +
4286 (ResAttrs.IsArray ? 1 : 0);
4287
4288 if (ActualDim != ExpectedDim) {
4289 S->Diag(Loc: TheCall->getArg(Arg: IndexArgIndex)->getBeginLoc(),
4290 DiagID: diag::err_hlsl_builtin_resource_coordinate_dimension_mismatch)
4291 << cast<NamedDecl>(Val: TheCall->getCalleeDecl()) << ExpectedDim
4292 << ActualDim;
4293 return true;
4294 }
4295
4296 return false;
4297}
4298
4299static bool CheckResourceHandle(
4300 Sema *S, CallExpr *TheCall, unsigned ArgIndex,
4301 llvm::function_ref<bool(const HLSLAttributedResourceType *ResType)> Check =
4302 nullptr) {
4303 assert(TheCall->getNumArgs() >= ArgIndex);
4304 QualType ArgType = TheCall->getArg(Arg: ArgIndex)->getType();
4305 const HLSLAttributedResourceType *ResTy =
4306 ArgType.getTypePtr()->getAs<HLSLAttributedResourceType>();
4307 if (!ResTy) {
4308 S->Diag(Loc: TheCall->getArg(Arg: ArgIndex)->getBeginLoc(),
4309 DiagID: diag::err_typecheck_expect_hlsl_resource)
4310 << ArgType;
4311 return true;
4312 }
4313 if (Check && Check(ResTy)) {
4314 S->Diag(Loc: TheCall->getArg(Arg: ArgIndex)->getExprLoc(),
4315 DiagID: diag::err_invalid_hlsl_resource_type)
4316 << ArgType;
4317 return true;
4318 }
4319 return false;
4320}
4321
4322static QualType createCounterHandleType(ASTContext &AST,
4323 QualType MainHandleTy) {
4324 assert(MainHandleTy->isHLSLAttributedResourceType() &&
4325 "expected resource handle type");
4326 auto *MainResType = MainHandleTy->getAs<HLSLAttributedResourceType>();
4327 auto MainAttrs = MainResType->getAttrs();
4328 assert(!MainAttrs.IsCounter && "cannot create a counter from a counter");
4329 MainAttrs.IsCounter = true;
4330 return AST.getHLSLAttributedResourceType(Wrapped: MainResType->getWrappedType(),
4331 Contained: MainResType->getContainedType(),
4332 Attrs: MainAttrs);
4333}
4334
4335enum class SampleKind { Sample, Bias, Grad, Level, Cmp, CmpLevelZero };
4336
4337static StringRef getSampleMethodName(SampleKind Kind) {
4338 switch (Kind) {
4339 case SampleKind::Sample:
4340 return "Sample";
4341 case SampleKind::Bias:
4342 return "SampleBias";
4343 case SampleKind::Grad:
4344 return "SampleGrad";
4345 case SampleKind::Level:
4346 return "SampleLevel";
4347 case SampleKind::Cmp:
4348 return "SampleCmp";
4349 case SampleKind::CmpLevelZero:
4350 return "SampleCmpLevelZero";
4351 }
4352 llvm_unreachable("Invalid SampleKind");
4353}
4354
4355// Returns the name of the resource method whose body the sampling or gather
4356// builtin is being emitted into, which is the name the user called. This
4357// matters for methods that share a builtin, like 'Gather' and 'GatherRed'.
4358// Falls back to DefaultName if the builtin is used outside of a resource
4359// method.
4360static StringRef getCurrentResourceMethodName(Sema &S, StringRef DefaultName) {
4361 const auto *MD = dyn_cast_if_present<CXXMethodDecl>(Val: S.getCurFunctionDecl());
4362 if (!MD || !MD->getDeclName().isIdentifier())
4363 return DefaultName;
4364
4365 QualType RecordTy = S.Context.getCanonicalTagType(TD: MD->getParent());
4366 if (!RecordTy->isHLSLResourceRecord())
4367 return DefaultName;
4368
4369 return MD->getName();
4370}
4371
4372// Sampling from and gathering on resources with a 'double' element type is not
4373// supported. Such resources are still valid declarations whose contents can be
4374// accessed by other means, like Load or the subscript operator.
4375static bool CheckNoDoubleElementType(Sema &S, CallExpr *TheCall,
4376 QualType ContainedType,
4377 StringRef DefaultName) {
4378 QualType EltTy = getElementTypeOf(T: ContainedType, /*IncludeMatrix=*/false);
4379 if (!EltTy->isSpecificBuiltinType(K: BuiltinType::Double))
4380 return false;
4381
4382 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_hlsl_sample_double_element_type)
4383 << getCurrentResourceMethodName(S, DefaultName) << ContainedType;
4384 return true;
4385}
4386
4387// Sampling textures with an integer element type was introduced in SM 6.7 as
4388// part of Advanced Texture Operations. The shader model only applies to DirectX
4389// targets; Vulkan has no such restriction.
4390static bool CheckIntegerElementTypeShaderModel(Sema &S, CallExpr *TheCall,
4391 QualType ContainedType,
4392 SampleKind Kind) {
4393 // Comparison sampling requires a floating point element type at every shader
4394 // model, which the caller diagnoses.
4395 if (Kind == SampleKind::Cmp || Kind == SampleKind::CmpLevelZero)
4396 return false;
4397
4398 // 'bool' is an integer type in HLSL, but sampling bool resources is never
4399 // allowed, so it must not be reported as requiring shader model 6.7.
4400 QualType EltTy = getElementTypeOf(T: ContainedType, /*IncludeMatrix=*/false);
4401 if (!EltTy->isIntegerType() || EltTy->isBooleanType())
4402 return false;
4403
4404 const TargetInfo &TI = S.Context.getTargetInfo();
4405 if (!TI.getTriple().isDXIL())
4406 return false;
4407
4408 VersionTuple SMVersion = TI.getPlatformMinVersion();
4409 if (SMVersion >= VersionTuple(6, 7))
4410 return false;
4411
4412 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_hlsl_sample_integer_element_type)
4413 << getCurrentResourceMethodName(S, DefaultName: getSampleMethodName(Kind))
4414 << ContainedType << SMVersion.getAsString();
4415 return true;
4416}
4417
4418static bool CheckTextureSamplerAndLocation(Sema &S, CallExpr *TheCall,
4419 bool IncludeArraySlice = true) {
4420 // Check the texture handle.
4421 if (CheckResourceHandle(S: &S, TheCall, ArgIndex: 0,
4422 Check: [](const HLSLAttributedResourceType *ResType) {
4423 return ResType->getAttrs().ResourceDimension ==
4424 llvm::dxil::ResourceDimension::Unknown;
4425 }))
4426 return true;
4427
4428 // Check the sampler handle.
4429 if (CheckResourceHandle(S: &S, TheCall, ArgIndex: 1,
4430 Check: [](const HLSLAttributedResourceType *ResType) {
4431 return ResType->getAttrs().ResourceClass !=
4432 llvm::hlsl::ResourceClass::Sampler;
4433 }))
4434 return true;
4435
4436 auto *ResourceTy =
4437 TheCall->getArg(Arg: 0)->getType()->castAs<HLSLAttributedResourceType>();
4438
4439 // Check the location.
4440 unsigned ExpectedDim =
4441 getResourceDimensions(Dim: ResourceTy->getAttrs().ResourceDimension) +
4442 (IncludeArraySlice && ResourceTy->getAttrs().IsArray ? 1 : 0);
4443 if (CheckArgTypeMatches(
4444 S: &S, Arg: TheCall->getArg(Arg: 2),
4445 ExpectedType: getVectorOrScalarType(S, BaseType: S.Context.FloatTy, Count: ExpectedDim)))
4446 return true;
4447
4448 return false;
4449}
4450
4451static bool CheckCalculateLodBuiltin(Sema &S, CallExpr *TheCall) {
4452 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
4453 return true;
4454
4455 // CalculateLevelOfDetail location uses resource dimension only (e.g. float2
4456 // for 2D), not an extra array slice component like Sample/Gather.
4457 if (CheckTextureSamplerAndLocation(S, TheCall, /*IncludeArraySlice=*/false))
4458 return true;
4459
4460 TheCall->setType(S.Context.FloatTy);
4461 return false;
4462}
4463
4464static bool CheckGatherBuiltin(Sema &S, CallExpr *TheCall, bool IsCmp) {
4465 if (S.checkArgCountRange(Call: TheCall, MinArgCount: IsCmp ? 5 : 4, MaxArgCount: IsCmp ? 6 : 5))
4466 return true;
4467
4468 if (CheckTextureSamplerAndLocation(S, TheCall))
4469 return true;
4470
4471 unsigned NextIdx = 3;
4472 if (IsCmp) {
4473 // Check the compare value.
4474 if (CheckScalarFloatOperand(S, TheCall, ArgIndex: NextIdx))
4475 return true;
4476 NextIdx++;
4477 }
4478
4479 // Check the component operand.
4480 if (CheckArgTypeMatches(S: &S, Arg: TheCall->getArg(Arg: NextIdx),
4481 ExpectedType: S.Context.UnsignedIntTy))
4482 return true;
4483 Expr *ComponentArg = TheCall->getArg(Arg: NextIdx);
4484
4485 // GatherCmp operations on Vulkan target must use component 0 (Red).
4486 if (IsCmp && S.getASTContext().getTargetInfo().getTriple().isSPIRV()) {
4487 std::optional<llvm::APSInt> ComponentOpt =
4488 ComponentArg->getIntegerConstantExpr(Ctx: S.getASTContext());
4489 if (ComponentOpt) {
4490 int64_t ComponentVal = ComponentOpt->getSExtValue();
4491 if (ComponentVal != 0) {
4492 // Issue an error if the component is not 0 (Red).
4493 // 0 -> Red, 1 -> Green, 2 -> Blue, 3 -> Alpha
4494 assert(ComponentVal >= 0 && ComponentVal <= 3 &&
4495 "The component is not in the expected range.");
4496 S.Diag(Loc: ComponentArg->getBeginLoc(),
4497 DiagID: diag::err_hlsl_gathercmp_invalid_component)
4498 << ComponentVal;
4499 return true;
4500 }
4501 }
4502 }
4503
4504 NextIdx++;
4505
4506 // Check the offset operand.
4507 const HLSLAttributedResourceType *ResourceTy =
4508 TheCall->getArg(Arg: 0)->getType()->castAs<HLSLAttributedResourceType>();
4509 if (TheCall->getNumArgs() > NextIdx) {
4510 unsigned ExpectedDim =
4511 getResourceDimensions(Dim: ResourceTy->getAttrs().ResourceDimension);
4512 if (CheckArgTypeMatches(
4513 S: &S, Arg: TheCall->getArg(Arg: NextIdx),
4514 ExpectedType: getVectorOrScalarType(S, BaseType: S.Context.IntTy, Count: ExpectedDim)))
4515 return true;
4516 NextIdx++;
4517 }
4518
4519 assert(ResourceTy->hasContainedType() &&
4520 "Expecting a contained type for resource with a dimension "
4521 "attribute.");
4522 QualType ReturnType = ResourceTy->getContainedType();
4523
4524 if (CheckNoDoubleElementType(S, TheCall, ContainedType: ReturnType,
4525 DefaultName: IsCmp ? "GatherCmp" : "Gather"))
4526 return true;
4527
4528 if (IsCmp) {
4529 if (!ReturnType->hasFloatingRepresentation()) {
4530 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_hlsl_samplecmp_requires_float);
4531 return true;
4532 }
4533 }
4534
4535 if (const auto *VecTy = ReturnType->getAs<VectorType>())
4536 ReturnType = VecTy->getElementType();
4537 ReturnType = S.Context.getExtVectorType(VectorType: ReturnType, NumElts: 4);
4538
4539 TheCall->setType(ReturnType);
4540
4541 return false;
4542}
4543static bool CheckLoadLevelBuiltin(Sema &S, CallExpr *TheCall) {
4544 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
4545 return true;
4546
4547 // Check the texture handle.
4548 if (CheckResourceHandle(S: &S, TheCall, ArgIndex: 0,
4549 Check: [](const HLSLAttributedResourceType *ResType) {
4550 return ResType->getAttrs().ResourceDimension ==
4551 llvm::dxil::ResourceDimension::Unknown;
4552 }))
4553 return true;
4554
4555 auto *ResourceTy =
4556 TheCall->getArg(Arg: 0)->getType()->castAs<HLSLAttributedResourceType>();
4557
4558 // A UAV descriptor binds a single mip slice, so a RWTexture location has no
4559 // mip component to select, and TextureLoad on a UAV takes no offset.
4560 bool IsUAV =
4561 ResourceTy->getAttrs().ResourceClass == llvm::dxil::ResourceClass::UAV;
4562 if (IsUAV && S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
4563 return true;
4564
4565 // Check the location: int3 for Texture2D and int4 for Texture2DArray, which
4566 // both carry a trailing mip level; int2 and int3 for the RWTexture forms,
4567 // which do not.
4568 unsigned ResourceDim =
4569 getResourceDimensions(Dim: ResourceTy->getAttrs().ResourceDimension);
4570 unsigned LocationDim = ResourceDim + (ResourceTy->getAttrs().IsArray ? 1 : 0);
4571 if (!IsUAV)
4572 ++LocationDim;
4573 if (CheckArgTypeMatches(
4574 S: &S, Arg: TheCall->getArg(Arg: 1),
4575 ExpectedType: getVectorOrScalarType(S, BaseType: S.Context.IntTy, Count: LocationDim)))
4576 return true;
4577
4578 // Check the offset operand (int2 for 2D textures; no array slice).
4579 if (TheCall->getNumArgs() > 2) {
4580 if (CheckArgTypeMatches(
4581 S: &S, Arg: TheCall->getArg(Arg: 2),
4582 ExpectedType: getVectorOrScalarType(S, BaseType: S.Context.IntTy, Count: ResourceDim)))
4583 return true;
4584 }
4585
4586 TheCall->setType(ResourceTy->getContainedType());
4587 return false;
4588}
4589
4590static bool CheckLoadMSBuiltin(Sema &S, CallExpr *TheCall) {
4591 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 3, MaxArgCount: 4))
4592 return true;
4593
4594 // Check the multisampled texture handle.
4595 if (CheckResourceHandle(S: &S, TheCall, ArgIndex: 0,
4596 Check: [](const HLSLAttributedResourceType *ResType) {
4597 return !ResType->isMultiSampled();
4598 }))
4599 return true;
4600
4601 auto *ResourceTy =
4602 TheCall->getArg(Arg: 0)->getType()->castAs<HLSLAttributedResourceType>();
4603
4604 // Check the location (int2 for Texture2DMS, int3 for Texture2DMSArray).
4605 // Unlike Load on regular textures, there is no mip/LOD component.
4606 unsigned ResourceDim =
4607 getResourceDimensions(Dim: ResourceTy->getAttrs().ResourceDimension);
4608 unsigned LocationDim = ResourceDim + (ResourceTy->getAttrs().IsArray ? 1 : 0);
4609 if (CheckArgTypeMatches(
4610 S: &S, Arg: TheCall->getArg(Arg: 1),
4611 ExpectedType: getVectorOrScalarType(S, BaseType: S.Context.IntTy, Count: LocationDim)))
4612 return true;
4613
4614 // Check the sample index operand (scalar int).
4615 if (CheckArgTypeMatches(S: &S, Arg: TheCall->getArg(Arg: 2), ExpectedType: S.Context.IntTy))
4616 return true;
4617
4618 // Check the offset operand (int2 for 2D textures; no array slice).
4619 if (TheCall->getNumArgs() > 3) {
4620 if (CheckArgTypeMatches(
4621 S: &S, Arg: TheCall->getArg(Arg: 3),
4622 ExpectedType: getVectorOrScalarType(S, BaseType: S.Context.IntTy, Count: ResourceDim)))
4623 return true;
4624 }
4625
4626 TheCall->setType(ResourceTy->getContainedType());
4627 return false;
4628}
4629
4630static bool CheckSamplingBuiltin(Sema &S, CallExpr *TheCall, SampleKind Kind) {
4631 unsigned MinArgs, MaxArgs;
4632 if (Kind == SampleKind::Sample) {
4633 MinArgs = 3;
4634 MaxArgs = 5;
4635 } else if (Kind == SampleKind::Bias) {
4636 MinArgs = 4;
4637 MaxArgs = 6;
4638 } else if (Kind == SampleKind::Grad) {
4639 MinArgs = 5;
4640 MaxArgs = 7;
4641 } else if (Kind == SampleKind::Level) {
4642 MinArgs = 4;
4643 MaxArgs = 5;
4644 } else if (Kind == SampleKind::Cmp) {
4645 MinArgs = 4;
4646 MaxArgs = 6;
4647 } else {
4648 assert(Kind == SampleKind::CmpLevelZero);
4649 MinArgs = 4;
4650 MaxArgs = 5;
4651 }
4652
4653 if (S.checkArgCountRange(Call: TheCall, MinArgCount: MinArgs, MaxArgCount: MaxArgs))
4654 return true;
4655
4656 if (CheckTextureSamplerAndLocation(S, TheCall))
4657 return true;
4658
4659 const HLSLAttributedResourceType *ResourceTy =
4660 TheCall->getArg(Arg: 0)->getType()->castAs<HLSLAttributedResourceType>();
4661 unsigned ExpectedDim =
4662 getResourceDimensions(Dim: ResourceTy->getAttrs().ResourceDimension);
4663
4664 unsigned NextIdx = 3;
4665 if (Kind == SampleKind::Bias || Kind == SampleKind::Level ||
4666 Kind == SampleKind::Cmp || Kind == SampleKind::CmpLevelZero) {
4667 // Check the bias, lod level, or compare value, depending on the kind.
4668 // All of them must be a scalar float value.
4669 if (CheckScalarFloatOperand(S, TheCall, ArgIndex: NextIdx))
4670 return true;
4671 NextIdx++;
4672 } else if (Kind == SampleKind::Grad) {
4673 QualType GradTy = getVectorOrScalarType(S, BaseType: S.Context.FloatTy, Count: ExpectedDim);
4674
4675 // Check the DDX operand.
4676 if (CheckArgTypeMatches(S: &S, Arg: TheCall->getArg(Arg: NextIdx), ExpectedType: GradTy))
4677 return true;
4678
4679 // Check the DDY operand.
4680 if (CheckArgTypeMatches(S: &S, Arg: TheCall->getArg(Arg: NextIdx + 1), ExpectedType: GradTy))
4681 return true;
4682 NextIdx += 2;
4683 }
4684
4685 // Check the offset operand (if applicable).
4686 if (hasResourceOffset(Dim: ResourceTy->getAttrs().ResourceDimension) &&
4687 TheCall->getNumArgs() > NextIdx) {
4688 if (CheckArgTypeMatches(
4689 S: &S, Arg: TheCall->getArg(Arg: NextIdx),
4690 ExpectedType: getVectorOrScalarType(S, BaseType: S.Context.IntTy, Count: ExpectedDim)))
4691 return true;
4692 NextIdx++;
4693 }
4694
4695 // Check the clamp operand.
4696 if (Kind != SampleKind::Level && Kind != SampleKind::CmpLevelZero &&
4697 TheCall->getNumArgs() > NextIdx) {
4698 if (CheckScalarFloatOperand(S, TheCall, ArgIndex: NextIdx))
4699 return true;
4700 }
4701
4702 assert(ResourceTy->hasContainedType() &&
4703 "Expecting a contained type for resource with a dimension "
4704 "attribute.");
4705 QualType ReturnType = ResourceTy->getContainedType();
4706
4707 if (CheckNoDoubleElementType(S, TheCall, ContainedType: ReturnType,
4708 DefaultName: getSampleMethodName(Kind)))
4709 return true;
4710
4711 if (CheckIntegerElementTypeShaderModel(S, TheCall, ContainedType: ReturnType, Kind))
4712 return true;
4713
4714 if (Kind == SampleKind::Cmp || Kind == SampleKind::CmpLevelZero) {
4715 if (!ReturnType->hasFloatingRepresentation()) {
4716 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_hlsl_samplecmp_requires_float);
4717 return true;
4718 }
4719 ReturnType = S.Context.FloatTy;
4720 }
4721 TheCall->setType(ReturnType);
4722
4723 return false;
4724}
4725
4726/// The `dest` types an interlocked operation accepts. Float is 32-bit only.
4727enum class InterlockedDest { Int, IntOrFloat, Float };
4728
4729/// Check a call to an HLSL interlocked builtin. The builtins are variadic, so
4730/// this is the only check a direct call gets. Overload resolution checks the
4731/// calls that come through the `InterlockedOp` overload sets.
4732static bool CheckInterlockedBuiltin(Sema &S, CallExpr *TheCall,
4733 unsigned MinArgs, unsigned MaxArgs,
4734 InterlockedDest Dest,
4735 bool ReportsOriginalValue) {
4736 if (MinArgs == MaxArgs) {
4737 if (S.checkArgCount(Call: TheCall, DesiredArgCount: MinArgs))
4738 return true;
4739 } else if (TheCall->getNumArgs() < MinArgs) {
4740 S.Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
4741 << /*callee_type=*/0 << /*min_arg_count=*/MinArgs
4742 << TheCall->getNumArgs() << /*is_non_object=*/0
4743 << TheCall->getSourceRange();
4744 return true;
4745 } else if (S.checkArgCountAtMost(Call: TheCall, MaxArgCount: MaxArgs)) {
4746 return true;
4747 }
4748
4749 QualType DestTy = TheCall->getArg(Arg: 0)->getType().getUnqualifiedType();
4750 const bool DestIsOK =
4751 DestTy->isSpecificBuiltinType(K: BuiltinType::Float)
4752 ? Dest != InterlockedDest::Int
4753 : Dest != InterlockedDest::Float && DestTy->isIntegerType();
4754 if (!DestIsOK) {
4755 S.Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
4756 DiagID: diag::err_builtin_invalid_arg_type)
4757 << /*ordinal=*/1 << /*scalar*/ 1
4758 << /*integer*/ (Dest == InterlockedDest::Float ? 0 : 1)
4759 << /*32 bit floating-point*/ (Dest == InterlockedDest::Int ? 0 : 3)
4760 << DestTy;
4761 return true;
4762 }
4763
4764 // 64-bit interlocked ops require SM 6.6 on DXIL. The synthesized wrapper
4765 // methods (e.g. RWByteAddressBuffer::InterlockedAdd64) are only declared on
4766 // SM 6.6+, so this defensive check only fires for direct builtin calls; skip
4767 // synthetic invocations (invalid source location).
4768 const TargetInfo &TI = S.Context.getTargetInfo();
4769 if (TheCall->getBeginLoc().isValid() &&
4770 TI.getTriple().getArch() == llvm::Triple::dxil &&
4771 S.Context.getTypeSize(T: DestTy) == 64 &&
4772 TI.getPlatformMinVersion() < VersionTuple(6, 6)) {
4773 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_hlsl_builtin_requires_sm)
4774 << TheCall->getDirectCallee() << VersionTuple(6, 6).getAsString();
4775 return true;
4776 }
4777
4778 if (CheckModifiableLValue(S: &S, TheCall, ArgIndex: 0))
4779 return true;
4780
4781 if (CheckArgAddrSpaceOneOf(S: &S, TheCall, ArgIndex: 0,
4782 AllowedSpaces: {LangAS::hlsl_groupshared, LangAS::hlsl_device}))
4783 return true;
4784
4785 // Every argument after `dest` has the destination's type.
4786 for (unsigned I = 1, E = TheCall->getNumArgs(); I != E; ++I)
4787 if (CheckArgTypeMatches(S: &S, Arg: TheCall->getArg(Arg: I), ExpectedType: DestTy))
4788 return true;
4789
4790 // Operations that report the previous value write it back through their last
4791 // argument.
4792 const unsigned NumArgs = TheCall->getNumArgs();
4793 if (ReportsOriginalValue && NumArgs == MaxArgs &&
4794 CheckModifiableLValue(S: &S, TheCall, ArgIndex: NumArgs - 1))
4795 return true;
4796
4797 TheCall->setType(S.Context.VoidTy);
4798 return false;
4799}
4800
4801// Note: returning true in this case results in CheckBuiltinFunctionCall
4802// returning an ExprError
4803bool SemaHLSL::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
4804 switch (BuiltinID) {
4805 case Builtin::BI__builtin_hlsl_barrier: {
4806 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 2))
4807 return true;
4808
4809 if (SemaRef.Context.getTargetInfo().getTriple().getArch() !=
4810 llvm::Triple::dxil) {
4811 SemaRef.Diag(Loc: TheCall->getExprLoc(), DiagID: diag::err_hlsl_dxil_only)
4812 << "Barrier";
4813 return true;
4814 }
4815
4816 Expr *MemoryArg = TheCall->getArg(Arg: 0);
4817 if (MemoryArg->getType()->isUnsignedIntegerType()) {
4818 std::optional<llvm::APSInt> MemoryFlags =
4819 MemoryArg->getIntegerConstantExpr(Ctx: SemaRef.Context);
4820 if (!MemoryFlags) {
4821 SemaRef.Diag(Loc: MemoryArg->getExprLoc(),
4822 DiagID: diag::err_constant_integer_arg_type)
4823 << "Barrier";
4824 return true;
4825 }
4826 if ((MemoryFlags->getZExtValue() &
4827 ~barrierFlagValue(Flag: BarrierMemoryTypeFlag::ValidMask)) != 0) {
4828 SemaRef.Diag(Loc: MemoryArg->getExprLoc(),
4829 DiagID: diag::err_hlsl_invalid_barrier_memory_flags);
4830 return true;
4831 }
4832 } else {
4833 const HLSLAttributedResourceType *ResTy =
4834 HLSLAttributedResourceType::findHandleTypeOnResource(
4835 RT: MemoryArg->getType().getTypePtr());
4836 if (!ResTy) {
4837 SemaRef.Diag(Loc: MemoryArg->getExprLoc(),
4838 DiagID: diag::err_typecheck_expect_hlsl_resource)
4839 << MemoryArg->getType();
4840 return true;
4841 }
4842 if (ResTy->getAttrs().ResourceClass != ResourceClass::UAV) {
4843 SemaRef.Diag(Loc: MemoryArg->getExprLoc(),
4844 DiagID: diag::err_invalid_hlsl_resource_type)
4845 << MemoryArg->getType();
4846 return true;
4847 }
4848 }
4849
4850 Expr *SemanticArg = TheCall->getArg(Arg: 1);
4851 std::optional<llvm::APSInt> SemanticFlags =
4852 SemanticArg->getIntegerConstantExpr(Ctx: SemaRef.Context);
4853 if (!SemanticFlags) {
4854 SemaRef.Diag(Loc: SemanticArg->getExprLoc(),
4855 DiagID: diag::err_constant_integer_arg_type)
4856 << "Barrier";
4857 return true;
4858 }
4859 if ((SemanticFlags->getZExtValue() &
4860 ~barrierFlagValue(Flag: BarrierSemanticFlag::ValidMask)) != 0) {
4861 SemaRef.Diag(Loc: SemanticArg->getExprLoc(),
4862 DiagID: diag::err_hlsl_invalid_barrier_semantic_flags);
4863 return true;
4864 }
4865
4866 TheCall->setType(SemaRef.Context.VoidTy);
4867 break;
4868 }
4869 case Builtin::BI__builtin_hlsl_adduint64: {
4870 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 2))
4871 return true;
4872
4873 if (CheckAllArgTypesAreCorrect(S: &SemaRef, TheCall,
4874 Check: CheckUnsignedIntVecRepresentation))
4875 return true;
4876
4877 // ensure arg integers are 32-bits
4878 if (CheckExpectedBitWidth(S: &SemaRef, TheCall, ArgOrdinal: 0, Width: 32))
4879 return true;
4880
4881 // ensure both args are vectors of total bit size of a multiple of 64
4882 auto *VTy = TheCall->getArg(Arg: 0)->getType()->getAs<VectorType>();
4883 int NumElementsArg = VTy->getNumElements();
4884 if (NumElementsArg != 2 && NumElementsArg != 4) {
4885 SemaRef.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vector_incorrect_bit_count)
4886 << 1 /*a multiple of*/ << 64 << NumElementsArg * 32;
4887 return true;
4888 }
4889
4890 // ensure first arg and second arg have the same type
4891 if (CheckAllArgsHaveSameType(S: &SemaRef, TheCall))
4892 return true;
4893
4894 ExprResult A = TheCall->getArg(Arg: 0);
4895 QualType ArgTyA = A.get()->getType();
4896 // return type is the same as the input type
4897 TheCall->setType(ArgTyA);
4898 break;
4899 }
4900 case Builtin::BI__builtin_hlsl_resource_getpointer: {
4901 if (SemaRef.checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2) ||
4902 CheckResourceHandle(S: &SemaRef, TheCall, ArgIndex: 0) ||
4903 (TheCall->getNumArgs() == 2 && CheckIndexType(S: &SemaRef, TheCall, IndexArgIndex: 1)))
4904 return true;
4905
4906 auto *ResourceTy =
4907 TheCall->getArg(Arg: 0)->getType()->castAs<HLSLAttributedResourceType>();
4908 QualType ContainedTy = ResourceTy->getContainedType();
4909 auto ReturnType = SemaRef.Context.getAddrSpaceQualType(
4910 T: ContainedTy,
4911 AddressSpace: getLangASFromResourceClass(RC: ResourceTy->getAttrs().ResourceClass));
4912 ReturnType = SemaRef.Context.getPointerType(T: ReturnType);
4913 TheCall->setType(ReturnType);
4914
4915 break;
4916 }
4917 case Builtin::BI__builtin_hlsl_resource_getpointer_typed: {
4918 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 3) ||
4919 CheckResourceHandle(S: &SemaRef, TheCall, ArgIndex: 0) ||
4920 CheckIndexType(S: &SemaRef, TheCall, IndexArgIndex: 1))
4921 return true;
4922
4923 QualType ElementTy = TheCall->getArg(Arg: 2)->getType();
4924 assert(ElementTy->isPointerType() &&
4925 "expected pointer type for second argument");
4926 ElementTy = ElementTy->getPointeeType();
4927
4928 // Reject array types
4929 if (ElementTy->isArrayType())
4930 return SemaRef.Diag(
4931 Loc: cast<FunctionDecl>(Val: SemaRef.CurContext)->getPointOfInstantiation(),
4932 DiagID: diag::err_invalid_use_of_array_type);
4933
4934 auto *ResourceTy =
4935 TheCall->getArg(Arg: 0)->getType()->castAs<HLSLAttributedResourceType>();
4936 auto ReturnType = SemaRef.Context.getAddrSpaceQualType(
4937 T: ElementTy,
4938 AddressSpace: getLangASFromResourceClass(RC: ResourceTy->getAttrs().ResourceClass));
4939 ReturnType = SemaRef.Context.getPointerType(T: ReturnType);
4940 TheCall->setType(ReturnType);
4941
4942 break;
4943 }
4944 case Builtin::BI__builtin_hlsl_transpose_if_memory_is_row_major: {
4945 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 2) ||
4946 CheckArgTypeMatches(S: &SemaRef, Arg: TheCall->getArg(Arg: 1),
4947 ExpectedType: SemaRef.getASTContext().IntTy))
4948 return true;
4949
4950 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
4951
4952 break;
4953 }
4954 case Builtin::BI__builtin_hlsl_resource_load_with_status: {
4955 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 3) ||
4956 CheckResourceHandle(S: &SemaRef, TheCall, ArgIndex: 0) ||
4957 CheckArgTypeMatches(S: &SemaRef, Arg: TheCall->getArg(Arg: 1),
4958 ExpectedType: SemaRef.getASTContext().UnsignedIntTy) ||
4959 CheckArgTypeMatches(S: &SemaRef, Arg: TheCall->getArg(Arg: 2),
4960 ExpectedType: SemaRef.getASTContext().UnsignedIntTy) ||
4961 CheckModifiableLValue(S: &SemaRef, TheCall, ArgIndex: 2))
4962 return true;
4963
4964 auto *ResourceTy =
4965 TheCall->getArg(Arg: 0)->getType()->castAs<HLSLAttributedResourceType>();
4966 QualType ReturnType = ResourceTy->getContainedType();
4967 TheCall->setType(ReturnType);
4968
4969 break;
4970 }
4971 case Builtin::BI__builtin_hlsl_resource_load_with_status_typed: {
4972 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 4) ||
4973 CheckResourceHandle(S: &SemaRef, TheCall, ArgIndex: 0) ||
4974 CheckArgTypeMatches(S: &SemaRef, Arg: TheCall->getArg(Arg: 1),
4975 ExpectedType: SemaRef.getASTContext().UnsignedIntTy) ||
4976 CheckArgTypeMatches(S: &SemaRef, Arg: TheCall->getArg(Arg: 2),
4977 ExpectedType: SemaRef.getASTContext().UnsignedIntTy) ||
4978 CheckModifiableLValue(S: &SemaRef, TheCall, ArgIndex: 2))
4979 return true;
4980
4981 QualType ReturnType = TheCall->getArg(Arg: 3)->getType();
4982 assert(ReturnType->isPointerType() &&
4983 "expected pointer type for second argument");
4984 ReturnType = ReturnType->getPointeeType();
4985
4986 // Reject array types
4987 if (ReturnType->isArrayType())
4988 return SemaRef.Diag(
4989 Loc: cast<FunctionDecl>(Val: SemaRef.CurContext)->getPointOfInstantiation(),
4990 DiagID: diag::err_invalid_use_of_array_type);
4991
4992 TheCall->setType(ReturnType);
4993
4994 break;
4995 }
4996 case Builtin::BI__builtin_hlsl_resource_load_level:
4997 return CheckLoadLevelBuiltin(S&: SemaRef, TheCall);
4998 case Builtin::BI__builtin_hlsl_resource_load_ms:
4999 return CheckLoadMSBuiltin(S&: SemaRef, TheCall);
5000 case Builtin::BI__builtin_hlsl_resource_sample:
5001 return CheckSamplingBuiltin(S&: SemaRef, TheCall, Kind: SampleKind::Sample);
5002 case Builtin::BI__builtin_hlsl_resource_sample_bias:
5003 return CheckSamplingBuiltin(S&: SemaRef, TheCall, Kind: SampleKind::Bias);
5004 case Builtin::BI__builtin_hlsl_resource_sample_grad:
5005 return CheckSamplingBuiltin(S&: SemaRef, TheCall, Kind: SampleKind::Grad);
5006 case Builtin::BI__builtin_hlsl_resource_sample_level:
5007 return CheckSamplingBuiltin(S&: SemaRef, TheCall, Kind: SampleKind::Level);
5008 case Builtin::BI__builtin_hlsl_resource_sample_cmp:
5009 return CheckSamplingBuiltin(S&: SemaRef, TheCall, Kind: SampleKind::Cmp);
5010 case Builtin::BI__builtin_hlsl_resource_sample_cmp_level_zero:
5011 return CheckSamplingBuiltin(S&: SemaRef, TheCall, Kind: SampleKind::CmpLevelZero);
5012 case Builtin::BI__builtin_hlsl_resource_calculate_lod:
5013 case Builtin::BI__builtin_hlsl_resource_calculate_lod_unclamped:
5014 return CheckCalculateLodBuiltin(S&: SemaRef, TheCall);
5015 case Builtin::BI__builtin_hlsl_resource_gather:
5016 return CheckGatherBuiltin(S&: SemaRef, TheCall, /*IsCmp=*/false);
5017 case Builtin::BI__builtin_hlsl_resource_gather_cmp:
5018 return CheckGatherBuiltin(S&: SemaRef, TheCall, /*IsCmp=*/true);
5019 case Builtin::BI__builtin_hlsl_resource_uninitializedhandle: {
5020 assert(TheCall->getNumArgs() == 1 && "expected 1 arg");
5021 // Update return type to be the attributed resource type from arg0.
5022 QualType ResourceTy = TheCall->getArg(Arg: 0)->getType();
5023 TheCall->setType(ResourceTy);
5024 break;
5025 }
5026 case Builtin::BI__builtin_hlsl_resource_handlefrombinding: {
5027 assert(TheCall->getNumArgs() == 6 && "expected 6 args");
5028 // Update return type to be the attributed resource type from arg0.
5029 QualType ResourceTy = TheCall->getArg(Arg: 0)->getType();
5030 TheCall->setType(ResourceTy);
5031 break;
5032 }
5033 case Builtin::BI__builtin_hlsl_resource_handlefromimplicitbinding: {
5034 assert(TheCall->getNumArgs() == 6 && "expected 6 args");
5035 // Update return type to be the attributed resource type from arg0.
5036 QualType ResourceTy = TheCall->getArg(Arg: 0)->getType();
5037 TheCall->setType(ResourceTy);
5038 break;
5039 }
5040 case Builtin::BI__builtin_hlsl_resource_counterhandlefromimplicitbinding: {
5041 assert(TheCall->getNumArgs() == 3 && "expected 3 args");
5042 // Update return type to be the attributed resource type from arg0
5043 // with added IsCounter flag.
5044 QualType MainHandleTy = TheCall->getArg(Arg: 0)->getType();
5045 QualType CounterHandleTy =
5046 createCounterHandleType(AST&: SemaRef.getASTContext(), MainHandleTy);
5047 TheCall->setType(CounterHandleTy);
5048 break;
5049 }
5050 case Builtin::BI__builtin_hlsl_resource_handlefromheap: {
5051 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 2) ||
5052 CheckResourceHandle(S: &SemaRef, TheCall, ArgIndex: 0) ||
5053 CheckArgTypeMatches(S: &SemaRef, Arg: TheCall->getArg(Arg: 1),
5054 ExpectedType: SemaRef.getASTContext().UnsignedIntTy))
5055 return true;
5056
5057 // Update return type to be the attributed resource type from arg0.
5058 QualType ResourceTy = TheCall->getArg(Arg: 0)->getType();
5059 TheCall->setType(ResourceTy);
5060 break;
5061 }
5062 case Builtin::BI__builtin_hlsl_resource_counterhandlefromheap: {
5063 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 1) ||
5064 CheckResourceHandle(S: &SemaRef, TheCall, ArgIndex: 0))
5065 return true;
5066 // Update return type to be the attributed resource type from arg0
5067 // with added IsCounter flag.
5068 QualType MainHandleTy = TheCall->getArg(Arg: 0)->getType();
5069 QualType CounterHandleTy =
5070 createCounterHandleType(AST&: SemaRef.getASTContext(), MainHandleTy);
5071 TheCall->setType(CounterHandleTy);
5072 break;
5073 }
5074 case Builtin::BI__builtin_hlsl_and:
5075 case Builtin::BI__builtin_hlsl_or: {
5076 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 2))
5077 return true;
5078 if (CheckScalarOrVectorOrMatrix(S: &SemaRef, TheCall, Scalar: getASTContext().BoolTy,
5079 ArgIndex: 0))
5080 return true;
5081 if (CheckAllArgsHaveSameType(S: &SemaRef, TheCall))
5082 return true;
5083
5084 ExprResult A = TheCall->getArg(Arg: 0);
5085 QualType ArgTyA = A.get()->getType();
5086 // return type is the same as the input type
5087 TheCall->setType(ArgTyA);
5088 break;
5089 }
5090 case Builtin::BI__builtin_hlsl_asdouble: {
5091 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 2))
5092 return true;
5093 if (CheckScalarOrVector(
5094 S: &SemaRef, TheCall,
5095 /*only check for uint*/ Scalar: SemaRef.Context.UnsignedIntTy,
5096 /* arg index */ ArgIndex: 0))
5097 return true;
5098 if (CheckScalarOrVector(
5099 S: &SemaRef, TheCall,
5100 /*only check for uint*/ Scalar: SemaRef.Context.UnsignedIntTy,
5101 /* arg index */ ArgIndex: 1))
5102 return true;
5103 if (CheckAllArgsHaveSameType(S: &SemaRef, TheCall))
5104 return true;
5105
5106 SetElementTypeAsReturnType(S: &SemaRef, TheCall, ReturnType: getASTContext().DoubleTy);
5107 break;
5108 }
5109 case Builtin::BI__builtin_hlsl_elementwise_clamp: {
5110 if (SemaRef.BuiltinElementwiseTernaryMath(
5111 TheCall, /*ArgTyRestr=*/
5112 Sema::EltwiseBuiltinArgTyRestriction::None))
5113 return true;
5114 break;
5115 }
5116 case Builtin::BI__builtin_hlsl_dot: {
5117 // arg count is checked by BuiltinVectorToScalarMath
5118 if (SemaRef.BuiltinVectorToScalarMath(TheCall))
5119 return true;
5120 if (CheckAllArgTypesAreCorrect(S: &SemaRef, TheCall, Check: CheckNoDoubleVectors))
5121 return true;
5122 break;
5123 }
5124 case Builtin::BI__builtin_hlsl_elementwise_firstbithigh:
5125 case Builtin::BI__builtin_hlsl_elementwise_firstbitlow: {
5126 if (SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5127 return true;
5128
5129 const Expr *Arg = TheCall->getArg(Arg: 0);
5130 QualType ArgTy = Arg->getType();
5131 QualType EltTy = ArgTy;
5132
5133 QualType ResTy = SemaRef.Context.UnsignedIntTy;
5134
5135 if (auto *VecTy = EltTy->getAs<VectorType>()) {
5136 EltTy = VecTy->getElementType();
5137 ResTy = SemaRef.Context.getExtVectorType(VectorType: ResTy, NumElts: VecTy->getNumElements());
5138 }
5139
5140 if (!EltTy->isIntegerType()) {
5141 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
5142 << 1 << /* scalar or vector of */ 5 << /* integer ty */ 1
5143 << /* no fp */ 0 << ArgTy;
5144 return true;
5145 }
5146
5147 TheCall->setType(ResTy);
5148 break;
5149 }
5150 case Builtin::BI__builtin_hlsl_select: {
5151 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 3))
5152 return true;
5153 if (CheckScalarOrVectorOrMatrix(S: &SemaRef, TheCall, Scalar: getASTContext().BoolTy,
5154 ArgIndex: 0))
5155 return true;
5156 QualType ArgTy = TheCall->getArg(Arg: 0)->getType();
5157 if (ArgTy->isBooleanType() && CheckBoolSelect(S: &SemaRef, TheCall))
5158 return true;
5159 auto *VTy = ArgTy->getAs<VectorType>();
5160 if (VTy && VTy->getElementType()->isBooleanType() &&
5161 CheckVectorSelect(S: &SemaRef, TheCall))
5162 return true;
5163 auto *MTy = ArgTy->getAs<ConstantMatrixType>();
5164 if (MTy && MTy->getElementType()->isBooleanType() &&
5165 CheckMatrixSelect(S: &SemaRef, TheCall))
5166 return true;
5167 break;
5168 }
5169 case Builtin::BI__builtin_hlsl_elementwise_saturate:
5170 case Builtin::BI__builtin_hlsl_elementwise_rcp: {
5171 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 1))
5172 return true;
5173 if (!TheCall->getArg(Arg: 0)
5174 ->getType()
5175 ->hasFloatingRepresentation()) // half or float or double
5176 return SemaRef.Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
5177 DiagID: diag::err_builtin_invalid_arg_type)
5178 << /* ordinal */ 1 << /* scalar or vector */ 5 << /* no int */ 0
5179 << /* fp */ 1 << TheCall->getArg(Arg: 0)->getType();
5180 if (SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5181 return true;
5182 break;
5183 }
5184 case Builtin::BI__builtin_hlsl_elementwise_rsqrt:
5185 case Builtin::BI__builtin_hlsl_elementwise_frac:
5186 case Builtin::BI__builtin_hlsl_elementwise_ddx_coarse:
5187 case Builtin::BI__builtin_hlsl_elementwise_ddy_coarse:
5188 case Builtin::BI__builtin_hlsl_elementwise_ddx_fine:
5189 case Builtin::BI__builtin_hlsl_elementwise_ddy_fine: {
5190 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 1))
5191 return true;
5192 if (CheckAllArgTypesAreCorrect(S: &SemaRef, TheCall,
5193 Check: CheckFloatOrHalfRepresentation))
5194 return true;
5195 if (SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5196 return true;
5197 break;
5198 }
5199 case Builtin::BI__builtin_hlsl_elementwise_isfinite:
5200 case Builtin::BI__builtin_hlsl_elementwise_isinf:
5201 case Builtin::BI__builtin_hlsl_elementwise_isnan: {
5202 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 1))
5203 return true;
5204 if (CheckAllArgTypesAreCorrect(S: &SemaRef, TheCall,
5205 Check: CheckFloatOrHalfRepresentation))
5206 return true;
5207 if (SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5208 return true;
5209 SetElementTypeAsReturnType(S: &SemaRef, TheCall, ReturnType: getASTContext().BoolTy);
5210 break;
5211 }
5212 case Builtin::BI__builtin_hlsl_mad: {
5213 if (SemaRef.BuiltinElementwiseTernaryMath(
5214 TheCall, /*ArgTyRestr=*/
5215 Sema::EltwiseBuiltinArgTyRestriction::None))
5216 return true;
5217 break;
5218 }
5219 case Builtin::BI__builtin_hlsl_mul: {
5220 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 2))
5221 return true;
5222
5223 Expr *Arg0 = TheCall->getArg(Arg: 0);
5224 Expr *Arg1 = TheCall->getArg(Arg: 1);
5225 QualType Ty0 = Arg0->getType();
5226 QualType Ty1 = Arg1->getType();
5227
5228 auto getElemType = [](QualType T) -> QualType {
5229 if (const auto *VTy = T->getAs<VectorType>())
5230 return VTy->getElementType();
5231 if (const auto *MTy = T->getAs<ConstantMatrixType>())
5232 return MTy->getElementType();
5233 return T;
5234 };
5235
5236 QualType EltTy0 = getElemType(Ty0);
5237
5238 bool IsVec0 = Ty0->isVectorType();
5239 bool IsMat0 = Ty0->isConstantMatrixType();
5240 bool IsVec1 = Ty1->isVectorType();
5241 bool IsMat1 = Ty1->isConstantMatrixType();
5242
5243 QualType RetTy;
5244
5245 if (IsVec0 && IsMat1) {
5246 auto *MatTy = Ty1->castAs<ConstantMatrixType>();
5247 RetTy = getASTContext().getExtVectorType(VectorType: EltTy0, NumElts: MatTy->getNumColumns());
5248 } else if (IsMat0 && IsVec1) {
5249 auto *MatTy = Ty0->castAs<ConstantMatrixType>();
5250 RetTy = getASTContext().getExtVectorType(VectorType: EltTy0, NumElts: MatTy->getNumRows());
5251 } else {
5252 assert(IsMat0 && IsMat1);
5253 auto *MatTy0 = Ty0->castAs<ConstantMatrixType>();
5254 auto *MatTy1 = Ty1->castAs<ConstantMatrixType>();
5255 RetTy = getASTContext().getConstantMatrixType(
5256 ElementType: EltTy0, NumRows: MatTy0->getNumRows(), NumColumns: MatTy1->getNumColumns());
5257 }
5258
5259 TheCall->setType(RetTy);
5260 break;
5261 }
5262 case Builtin::BI__builtin_elementwise_fma: {
5263 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 3) ||
5264 CheckAllArgsHaveSameType(S: &SemaRef, TheCall)) {
5265 return true;
5266 }
5267
5268 if (CheckAllArgTypesAreCorrect(S: &SemaRef, TheCall,
5269 Check: CheckAnyDoubleRepresentation))
5270 return true;
5271
5272 ExprResult A = TheCall->getArg(Arg: 0);
5273 QualType ArgTyA = A.get()->getType();
5274 // return type is the same as input type
5275 TheCall->setType(ArgTyA);
5276 break;
5277 }
5278 case Builtin::BI__builtin_hlsl_transpose: {
5279 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 1))
5280 return true;
5281
5282 Expr *Arg = TheCall->getArg(Arg: 0);
5283 QualType ArgTy = Arg->getType();
5284
5285 const auto *MatTy = ArgTy->getAs<ConstantMatrixType>();
5286 if (!MatTy) {
5287 SemaRef.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
5288 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0 << ArgTy;
5289 return true;
5290 }
5291
5292 QualType RetTy = getASTContext().getConstantMatrixType(
5293 ElementType: MatTy->getElementType(), NumRows: MatTy->getNumColumns(), NumColumns: MatTy->getNumRows());
5294 TheCall->setType(RetTy);
5295 break;
5296 }
5297 case Builtin::BI__builtin_hlsl_elementwise_sign: {
5298 if (SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5299 return true;
5300 if (CheckAllArgTypesAreCorrect(S: &SemaRef, TheCall,
5301 Check: CheckNumericRepresentation))
5302 return true;
5303 SetElementTypeAsReturnType(S: &SemaRef, TheCall, ReturnType: getASTContext().IntTy);
5304 break;
5305 }
5306 case Builtin::BI__builtin_hlsl_wave_active_all_equal: {
5307 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 1))
5308 return true;
5309
5310 // Ensure input expr type is a scalar/vector
5311 if (CheckAnyScalarOrVector(S: &SemaRef, TheCall, ArgIndex: 0))
5312 return true;
5313
5314 QualType InputTy = TheCall->getArg(Arg: 0)->getType();
5315 ASTContext &Ctx = getASTContext();
5316
5317 QualType RetTy;
5318
5319 // If vector, construct bool vector of same size
5320 if (const auto *VecTy = InputTy->getAs<ExtVectorType>()) {
5321 unsigned NumElts = VecTy->getNumElements();
5322 RetTy = Ctx.getExtVectorType(VectorType: Ctx.BoolTy, NumElts);
5323 } else {
5324 // Scalar case
5325 RetTy = Ctx.BoolTy;
5326 }
5327
5328 TheCall->setType(RetTy);
5329 break;
5330 }
5331 case Builtin::BI__builtin_hlsl_wave_active_max:
5332 case Builtin::BI__builtin_hlsl_wave_active_min:
5333 case Builtin::BI__builtin_hlsl_wave_active_sum:
5334 case Builtin::BI__builtin_hlsl_wave_active_product: {
5335 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 1))
5336 return true;
5337
5338 // Ensure input expr type is a scalar/vector and the same as the return type
5339 if (CheckAnyScalarOrVector(S: &SemaRef, TheCall, ArgIndex: 0))
5340 return true;
5341 if (CheckWaveActive(S: &SemaRef, TheCall))
5342 return true;
5343 ExprResult Expr = TheCall->getArg(Arg: 0);
5344 QualType ArgTyExpr = Expr.get()->getType();
5345 TheCall->setType(ArgTyExpr);
5346 break;
5347 }
5348 case Builtin::BI__builtin_hlsl_wave_active_bit_or:
5349 case Builtin::BI__builtin_hlsl_wave_active_bit_xor:
5350 case Builtin::BI__builtin_hlsl_wave_active_bit_and: {
5351 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 1))
5352 return true;
5353
5354 // Ensure input expr type is a scalar/vector
5355 if (CheckAnyScalarOrVector(S: &SemaRef, TheCall, ArgIndex: 0))
5356 return true;
5357
5358 if (CheckWaveActive(S: &SemaRef, TheCall))
5359 return true;
5360
5361 // Ensure the expr type is interpretable as a uint or vector<uint>
5362 ExprResult Expr = TheCall->getArg(Arg: 0);
5363 QualType ArgTyExpr = Expr.get()->getType();
5364 auto *VTy = ArgTyExpr->getAs<VectorType>();
5365 if (!(ArgTyExpr->isIntegerType() ||
5366 (VTy && VTy->getElementType()->isIntegerType()))) {
5367 SemaRef.Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
5368 DiagID: diag::err_builtin_invalid_arg_type)
5369 << ArgTyExpr << SemaRef.Context.UnsignedIntTy << 1 << 0 << 0;
5370 return true;
5371 }
5372
5373 // Ensure input expr type is the same as the return type
5374 TheCall->setType(ArgTyExpr);
5375 break;
5376 }
5377 case Builtin::BI__builtin_hlsl_interlocked_add:
5378 case Builtin::BI__builtin_hlsl_interlocked_and:
5379 case Builtin::BI__builtin_hlsl_interlocked_max:
5380 case Builtin::BI__builtin_hlsl_interlocked_min:
5381 case Builtin::BI__builtin_hlsl_interlocked_or:
5382 case Builtin::BI__builtin_hlsl_interlocked_xor:
5383 if (CheckInterlockedBuiltin(S&: SemaRef, TheCall, /*MinArgs=*/2, /*MaxArgs=*/3,
5384 Dest: InterlockedDest::Int,
5385 /*ReportsOriginalValue=*/true))
5386 return true;
5387 break;
5388 case Builtin::BI__builtin_hlsl_interlocked_exchange:
5389 if (CheckInterlockedBuiltin(S&: SemaRef, TheCall, /*MinArgs=*/3, /*MaxArgs=*/3,
5390 Dest: InterlockedDest::IntOrFloat,
5391 /*ReportsOriginalValue=*/true))
5392 return true;
5393 break;
5394 case Builtin::BI__builtin_hlsl_interlocked_compare_store:
5395 if (CheckInterlockedBuiltin(S&: SemaRef, TheCall, /*MinArgs=*/3, /*MaxArgs=*/3,
5396 Dest: InterlockedDest::Int,
5397 /*ReportsOriginalValue=*/false))
5398 return true;
5399 break;
5400 case Builtin::BI__builtin_hlsl_interlocked_compare_store_float_bitwise:
5401 if (CheckInterlockedBuiltin(S&: SemaRef, TheCall, /*MinArgs=*/3, /*MaxArgs=*/3,
5402 Dest: InterlockedDest::Float,
5403 /*ReportsOriginalValue=*/false))
5404 return true;
5405 break;
5406 case Builtin::BI__builtin_hlsl_interlocked_compare_exchange:
5407 if (CheckInterlockedBuiltin(S&: SemaRef, TheCall, /*MinArgs=*/4, /*MaxArgs=*/4,
5408 Dest: InterlockedDest::Int,
5409 /*ReportsOriginalValue=*/true))
5410 return true;
5411 break;
5412 case Builtin::BI__builtin_hlsl_interlocked_compare_exchange_float_bitwise:
5413 if (CheckInterlockedBuiltin(S&: SemaRef, TheCall, /*MinArgs=*/4, /*MaxArgs=*/4,
5414 Dest: InterlockedDest::Float,
5415 /*ReportsOriginalValue=*/true))
5416 return true;
5417 break;
5418 // Note these are llvm builtins that we want to catch invalid intrinsic
5419 // generation. Normal handling of these builtins will occur elsewhere.
5420 case Builtin::BI__builtin_elementwise_bitreverse: {
5421 // does not include a check for number of arguments
5422 // because that is done previously
5423 if (CheckAllArgTypesAreCorrect(S: &SemaRef, TheCall,
5424 Check: CheckUnsignedIntRepresentation))
5425 return true;
5426 break;
5427 }
5428 case Builtin::BI__builtin_hlsl_wave_prefix_count_bits:
5429 case Builtin::BI__builtin_hlsl_wave_multi_prefix_count_bits: {
5430 bool IsMultiPrefix =
5431 BuiltinID == Builtin::BI__builtin_hlsl_wave_multi_prefix_count_bits;
5432 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: IsMultiPrefix ? 2 : 1))
5433 return true;
5434
5435 QualType ArgType = TheCall->getArg(Arg: 0)->getType();
5436
5437 if (!(ArgType->isScalarType())) {
5438 SemaRef.Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
5439 DiagID: diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
5440 << ArgType << 0;
5441 return true;
5442 }
5443
5444 if (!(ArgType->isBooleanType())) {
5445 SemaRef.Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
5446 DiagID: diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
5447 << ArgType << 0;
5448 return true;
5449 }
5450
5451 if (IsMultiPrefix) {
5452 if (CheckWaveMultiPrefixMask(S: &SemaRef, TheCall))
5453 return true;
5454
5455 // Alias validation uses calls with an invalid source location.
5456 if (TheCall->getBeginLoc().isValid() &&
5457 !getASTContext().getTargetInfo().getTriple().isDXIL()) {
5458 SemaRef.Diag(Loc: TheCall->getBeginLoc(),
5459 DiagID: diag::err_builtin_target_unsupported)
5460 << TheCall->getSourceRange();
5461 return true;
5462 }
5463 }
5464
5465 break;
5466 }
5467 case Builtin::BI__builtin_hlsl_wave_read_lane_at: {
5468 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 2))
5469 return true;
5470
5471 // Ensure index parameter type can be interpreted as a uint
5472 ExprResult Index = TheCall->getArg(Arg: 1);
5473 QualType ArgTyIndex = Index.get()->getType();
5474 if (!ArgTyIndex->isIntegerType()) {
5475 SemaRef.Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
5476 DiagID: diag::err_typecheck_convert_incompatible)
5477 << ArgTyIndex << SemaRef.Context.UnsignedIntTy << 1 << 0 << 0;
5478 return true;
5479 }
5480
5481 // Ensure input expr type is a scalar/vector and the same as the return type
5482 if (CheckAnyScalarOrVector(S: &SemaRef, TheCall, ArgIndex: 0))
5483 return true;
5484
5485 ExprResult Expr = TheCall->getArg(Arg: 0);
5486 QualType ArgTyExpr = Expr.get()->getType();
5487 TheCall->setType(ArgTyExpr);
5488 break;
5489 }
5490 case Builtin::BI__builtin_hlsl_wave_read_lane_first: {
5491 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 1))
5492 return true;
5493
5494 if (CheckAnyScalarOrVectorOrMatrix(S: &SemaRef, TheCall, ArgIndex: 0))
5495 return true;
5496
5497 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
5498 break;
5499 }
5500 case Builtin::BI__builtin_hlsl_wave_get_lane_index: {
5501 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 0))
5502 return true;
5503 break;
5504 }
5505 case Builtin::BI__builtin_hlsl_wave_prefix_sum:
5506 case Builtin::BI__builtin_hlsl_wave_prefix_product: {
5507 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 1))
5508 return true;
5509
5510 // Ensure input expr type is a scalar/vector and the same as the return type
5511 if (CheckAnyScalarOrVector(S: &SemaRef, TheCall, ArgIndex: 0))
5512 return true;
5513 if (CheckWavePrefix(S: &SemaRef, TheCall))
5514 return true;
5515 ExprResult Expr = TheCall->getArg(Arg: 0);
5516 QualType ArgTyExpr = Expr.get()->getType();
5517 TheCall->setType(ArgTyExpr);
5518 break;
5519 }
5520 case Builtin::BI__builtin_hlsl_wave_multi_prefix_bit_and:
5521 case Builtin::BI__builtin_hlsl_wave_multi_prefix_bit_or:
5522 case Builtin::BI__builtin_hlsl_wave_multi_prefix_bit_xor:
5523 case Builtin::BI__builtin_hlsl_wave_multi_prefix_product:
5524 case Builtin::BI__builtin_hlsl_wave_multi_prefix_sum: {
5525 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 2))
5526 return true;
5527
5528 if (CheckAnyScalarOrVectorOrMatrix(S: &SemaRef, TheCall, ArgIndex: 0) ||
5529 CheckNotBoolScalarOrVector(S: &SemaRef, TheCall, ArgIndex: 0))
5530 return true;
5531
5532 QualType ValueTy = TheCall->getArg(Arg: 0)->getType();
5533 QualType ElementTy = getScalarComponentType(T: ValueTy);
5534 bool IsArithmetic =
5535 BuiltinID == Builtin::BI__builtin_hlsl_wave_multi_prefix_product ||
5536 BuiltinID == Builtin::BI__builtin_hlsl_wave_multi_prefix_sum;
5537 if ((!ElementTy->isIntegerType() &&
5538 !(IsArithmetic && ElementTy->hasFloatingRepresentation())) ||
5539 ElementTy->isBooleanType()) {
5540 SemaRef.Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
5541 DiagID: diag::err_builtin_invalid_arg_type)
5542 << 1 << (ValueTy->isMatrixType() ? 3 : 5) << 1 << IsArithmetic
5543 << ValueTy;
5544 return true;
5545 }
5546
5547 if (CheckWaveMultiPrefixMask(S: &SemaRef, TheCall))
5548 return true;
5549
5550 TheCall->setType(ValueTy);
5551 break;
5552 }
5553 case Builtin::BI__builtin_hlsl_quad_read_across_x:
5554 case Builtin::BI__builtin_hlsl_quad_read_across_y:
5555 case Builtin::BI__builtin_hlsl_quad_read_across_diagonal: {
5556 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 1))
5557 return true;
5558
5559 if (CheckAnyScalarOrVector(S: &SemaRef, TheCall, ArgIndex: 0))
5560 return true;
5561 if (CheckNotBoolScalarOrVector(S: &SemaRef, TheCall, ArgIndex: 0))
5562 return true;
5563 ExprResult Expr = TheCall->getArg(Arg: 0);
5564 QualType ArgTyExpr = Expr.get()->getType();
5565 TheCall->setType(ArgTyExpr);
5566 break;
5567 }
5568 case Builtin::BI__builtin_hlsl_elementwise_splitdouble: {
5569 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 3))
5570 return true;
5571
5572 if (CheckScalarOrVectorOrMatrix(S: &SemaRef, TheCall, Scalar: SemaRef.Context.DoubleTy,
5573 ArgIndex: 0) ||
5574 CheckScalarOrVectorOrMatrix(S: &SemaRef, TheCall,
5575 Scalar: SemaRef.Context.UnsignedIntTy, ArgIndex: 1) ||
5576 CheckScalarOrVectorOrMatrix(S: &SemaRef, TheCall,
5577 Scalar: SemaRef.Context.UnsignedIntTy, ArgIndex: 2))
5578 return true;
5579
5580 if (CheckModifiableLValue(S: &SemaRef, TheCall, ArgIndex: 1) ||
5581 CheckModifiableLValue(S: &SemaRef, TheCall, ArgIndex: 2))
5582 return true;
5583 break;
5584 }
5585 case Builtin::BI__builtin_hlsl_elementwise_clip: {
5586 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 1))
5587 return true;
5588
5589 if (CheckScalarOrVector(S: &SemaRef, TheCall, Scalar: SemaRef.Context.FloatTy, ArgIndex: 0))
5590 return true;
5591 break;
5592 }
5593 case Builtin::BI__builtin_elementwise_acos:
5594 case Builtin::BI__builtin_elementwise_asin:
5595 case Builtin::BI__builtin_elementwise_atan:
5596 case Builtin::BI__builtin_elementwise_atan2:
5597 case Builtin::BI__builtin_elementwise_ceil:
5598 case Builtin::BI__builtin_elementwise_cos:
5599 case Builtin::BI__builtin_elementwise_cosh:
5600 case Builtin::BI__builtin_elementwise_exp:
5601 case Builtin::BI__builtin_elementwise_exp2:
5602 case Builtin::BI__builtin_elementwise_exp10:
5603 case Builtin::BI__builtin_elementwise_floor:
5604 case Builtin::BI__builtin_elementwise_fmod:
5605 case Builtin::BI__builtin_elementwise_log:
5606 case Builtin::BI__builtin_elementwise_log2:
5607 case Builtin::BI__builtin_elementwise_log10:
5608 case Builtin::BI__builtin_elementwise_pow:
5609 case Builtin::BI__builtin_elementwise_roundeven:
5610 case Builtin::BI__builtin_elementwise_sin:
5611 case Builtin::BI__builtin_elementwise_sinh:
5612 case Builtin::BI__builtin_elementwise_sqrt:
5613 case Builtin::BI__builtin_elementwise_tan:
5614 case Builtin::BI__builtin_elementwise_tanh:
5615 case Builtin::BI__builtin_elementwise_trunc: {
5616 if (CheckAllArgTypesAreCorrect(S: &SemaRef, TheCall,
5617 Check: CheckFloatOrHalfRepresentation))
5618 return true;
5619 break;
5620 }
5621 case Builtin::BI__builtin_hlsl_buffer_update_counter: {
5622 assert(TheCall->getNumArgs() == 2 && "expected 2 args");
5623 auto checkResTy = [](const HLSLAttributedResourceType *ResTy) -> bool {
5624 return !(ResTy->getAttrs().ResourceClass == ResourceClass::UAV &&
5625 ResTy->getAttrs().RawBuffer && ResTy->hasContainedType());
5626 };
5627 if (CheckResourceHandle(S: &SemaRef, TheCall, ArgIndex: 0, Check: checkResTy))
5628 return true;
5629 Expr *OffsetExpr = TheCall->getArg(Arg: 1);
5630 std::optional<llvm::APSInt> Offset =
5631 OffsetExpr->getIntegerConstantExpr(Ctx: SemaRef.getASTContext());
5632 if (!Offset.has_value() || std::abs(i: Offset->getExtValue()) != 1) {
5633 SemaRef.Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
5634 DiagID: diag::err_hlsl_expect_arg_const_int_one_or_neg_one)
5635 << 1;
5636 return true;
5637 }
5638 break;
5639 }
5640 case Builtin::BI__builtin_hlsl_elementwise_f16tof32: {
5641 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 1))
5642 return true;
5643 if (CheckAllArgTypesAreCorrect(S: &SemaRef, TheCall,
5644 Check: CheckUnsignedIntRepresentation))
5645 return true;
5646 // ensure arg integers are 32 bits
5647 if (CheckExpectedBitWidth(S: &SemaRef, TheCall, ArgOrdinal: 0, Width: 32))
5648 return true;
5649 // check it wasn't a bool type
5650 QualType ArgTy = TheCall->getArg(Arg: 0)->getType();
5651 if (auto *VTy = ArgTy->getAs<VectorType>())
5652 ArgTy = VTy->getElementType();
5653 if (ArgTy->isBooleanType()) {
5654 SemaRef.Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
5655 DiagID: diag::err_builtin_invalid_arg_type)
5656 << 1 << /* scalar or vector of */ 5 << /* unsigned int */ 3
5657 << /* no fp */ 0 << TheCall->getArg(Arg: 0)->getType();
5658 return true;
5659 }
5660
5661 SetElementTypeAsReturnType(S: &SemaRef, TheCall, ReturnType: getASTContext().FloatTy);
5662 break;
5663 }
5664 case Builtin::BI__builtin_hlsl_elementwise_f32tof16: {
5665 if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 1))
5666 return true;
5667 if (CheckAllArgTypesAreCorrect(S: &SemaRef, TheCall, Check: CheckFloatRepresentation))
5668 return true;
5669 SetElementTypeAsReturnType(S: &SemaRef, TheCall,
5670 ReturnType: getASTContext().UnsignedIntTy);
5671 break;
5672 }
5673 }
5674 return false;
5675}
5676
5677static void BuildFlattenedTypeList(QualType BaseTy,
5678 llvm::SmallVectorImpl<QualType> &List) {
5679 llvm::SmallVector<QualType, 16> WorkList;
5680 WorkList.push_back(Elt: BaseTy);
5681 while (!WorkList.empty()) {
5682 QualType T = WorkList.pop_back_val();
5683 T = T.getCanonicalType().getUnqualifiedType();
5684 if (const auto *AT = dyn_cast<ConstantArrayType>(Val&: T)) {
5685 llvm::SmallVector<QualType, 16> ElementFields;
5686 // Generally I've avoided recursion in this algorithm, but arrays of
5687 // structs could be time-consuming to flatten and churn through on the
5688 // work list. Hopefully nesting arrays of structs containing arrays
5689 // of structs too many levels deep is unlikely.
5690 BuildFlattenedTypeList(BaseTy: AT->getElementType(), List&: ElementFields);
5691 // Repeat the element's field list n times.
5692 for (uint64_t Ct = 0; Ct < AT->getZExtSize(); ++Ct)
5693 llvm::append_range(C&: List, R&: ElementFields);
5694 continue;
5695 }
5696 // Vectors can only have element types that are builtin types, so this can
5697 // add directly to the list instead of to the WorkList.
5698 if (const auto *VT = dyn_cast<VectorType>(Val&: T)) {
5699 List.insert(I: List.end(), NumToInsert: VT->getNumElements(), Elt: VT->getElementType());
5700 continue;
5701 }
5702 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val&: T)) {
5703 List.insert(I: List.end(), NumToInsert: MT->getNumElementsFlattened(),
5704 Elt: MT->getElementType());
5705 continue;
5706 }
5707 if (const auto *RD = T->getAsCXXRecordDecl()) {
5708 if (RD->isStandardLayout())
5709 RD = RD->getStandardLayoutBaseWithFields();
5710
5711 // For types that we shouldn't decompose (unions and non-aggregates), just
5712 // add the type itself to the list.
5713 if (RD->isUnion() || !RD->isAggregate()) {
5714 List.push_back(Elt: T);
5715 continue;
5716 }
5717
5718 llvm::SmallVector<QualType, 16> FieldTypes;
5719 for (const auto *FD : RD->fields())
5720 if (!FD->isUnnamedBitField())
5721 FieldTypes.push_back(Elt: FD->getType());
5722 // Reverse the newly added sub-range.
5723 std::reverse(first: FieldTypes.begin(), last: FieldTypes.end());
5724 llvm::append_range(C&: WorkList, R&: FieldTypes);
5725
5726 // If this wasn't a standard layout type we may also have some base
5727 // classes to deal with.
5728 if (!RD->isStandardLayout()) {
5729 FieldTypes.clear();
5730 for (const auto &Base : RD->bases())
5731 FieldTypes.push_back(Elt: Base.getType());
5732 std::reverse(first: FieldTypes.begin(), last: FieldTypes.end());
5733 llvm::append_range(C&: WorkList, R&: FieldTypes);
5734 }
5735 continue;
5736 }
5737 List.push_back(Elt: T);
5738 }
5739}
5740
5741bool SemaHLSL::IsConstantBufferElementCompatible(clang::QualType QT) {
5742 if (QT.isNull())
5743 return false;
5744
5745 // Must be a class/struct.
5746 const auto *RD = QT->getAsCXXRecordDecl();
5747 if (!RD || RD->isUnion())
5748 return false;
5749
5750 // Cannot be a resource type or contain one.
5751 return !QT->isHLSLIntangibleType();
5752}
5753
5754bool SemaHLSL::IsTypedResourceElementCompatible(clang::QualType QT) {
5755 // null and array types are not allowed.
5756 if (QT.isNull() || QT->isArrayType())
5757 return false;
5758
5759 // UDT types are not allowed
5760 if (QT->isRecordType())
5761 return false;
5762
5763 if (QT->isBooleanType() || QT->isEnumeralType())
5764 return false;
5765
5766 // the only other valid builtin types are scalars or vectors
5767 if (QT->isArithmeticType()) {
5768 if (SemaRef.Context.getTypeSize(T: QT) / 8 > 16)
5769 return false;
5770 return true;
5771 }
5772
5773 if (const VectorType *VT = QT->getAs<VectorType>()) {
5774 int ArraySize = VT->getNumElements();
5775
5776 if (ArraySize > 4)
5777 return false;
5778
5779 QualType ElTy = VT->getElementType();
5780 if (ElTy->isBooleanType())
5781 return false;
5782
5783 if (SemaRef.Context.getTypeSize(T: QT) / 8 > 16)
5784 return false;
5785 return true;
5786 }
5787
5788 return false;
5789}
5790
5791bool SemaHLSL::IsScalarizedLayoutCompatible(QualType T1, QualType T2) const {
5792 if (T1.isNull() || T2.isNull())
5793 return false;
5794
5795 T1 = T1.getCanonicalType().getUnqualifiedType();
5796 T2 = T2.getCanonicalType().getUnqualifiedType();
5797
5798 // If both types are the same canonical type, they're obviously compatible.
5799 if (SemaRef.getASTContext().hasSameType(T1, T2))
5800 return true;
5801
5802 llvm::SmallVector<QualType, 16> T1Types;
5803 BuildFlattenedTypeList(BaseTy: T1, List&: T1Types);
5804 llvm::SmallVector<QualType, 16> T2Types;
5805 BuildFlattenedTypeList(BaseTy: T2, List&: T2Types);
5806
5807 // Check the flattened type list
5808 return llvm::equal(LRange&: T1Types, RRange&: T2Types,
5809 P: [this](QualType LHS, QualType RHS) -> bool {
5810 return SemaRef.IsLayoutCompatible(T1: LHS, T2: RHS);
5811 });
5812}
5813
5814bool SemaHLSL::CheckCompatibleParameterABI(FunctionDecl *New,
5815 FunctionDecl *Old) {
5816 if (New->getNumParams() != Old->getNumParams())
5817 return true;
5818
5819 bool HadError = false;
5820
5821 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
5822 ParmVarDecl *NewParam = New->getParamDecl(i);
5823 ParmVarDecl *OldParam = Old->getParamDecl(i);
5824
5825 // HLSL parameter declarations for inout and out must match between
5826 // declarations. In HLSL inout and out are ambiguous at the call site,
5827 // but have different calling behavior, so you cannot overload a
5828 // method based on a difference between inout and out annotations.
5829 const auto *NDAttr = NewParam->getAttr<HLSLParamModifierAttr>();
5830 unsigned NSpellingIdx = (NDAttr ? NDAttr->getSpellingListIndex() : 0);
5831 const auto *ODAttr = OldParam->getAttr<HLSLParamModifierAttr>();
5832 unsigned OSpellingIdx = (ODAttr ? ODAttr->getSpellingListIndex() : 0);
5833
5834 if (NSpellingIdx != OSpellingIdx) {
5835 SemaRef.Diag(Loc: NewParam->getLocation(),
5836 DiagID: diag::err_hlsl_param_qualifier_mismatch)
5837 << NDAttr << NewParam;
5838 SemaRef.Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_declaration_as)
5839 << ODAttr;
5840 HadError = true;
5841 }
5842 }
5843 return HadError;
5844}
5845
5846// Generally follows PerformScalarCast, with cases reordered for
5847// clarity of what types are supported
5848bool SemaHLSL::CanPerformScalarCast(QualType SrcTy, QualType DestTy) {
5849
5850 if (!SrcTy->isScalarType() || !DestTy->isScalarType())
5851 return false;
5852
5853 if (SemaRef.getASTContext().hasSameUnqualifiedType(T1: SrcTy, T2: DestTy))
5854 return true;
5855
5856 switch (SrcTy->getScalarTypeKind()) {
5857 case Type::STK_Bool: // casting from bool is like casting from an integer
5858 case Type::STK_Integral:
5859 switch (DestTy->getScalarTypeKind()) {
5860 case Type::STK_Bool:
5861 case Type::STK_Integral:
5862 case Type::STK_Floating:
5863 return true;
5864 case Type::STK_CPointer:
5865 case Type::STK_ObjCObjectPointer:
5866 case Type::STK_BlockPointer:
5867 case Type::STK_MemberPointer:
5868 llvm_unreachable("HLSL doesn't support pointers.");
5869 case Type::STK_IntegralComplex:
5870 case Type::STK_FloatingComplex:
5871 llvm_unreachable("HLSL doesn't support complex types.");
5872 case Type::STK_FixedPoint:
5873 llvm_unreachable("HLSL doesn't support fixed point types.");
5874 }
5875 llvm_unreachable("Should have returned before this");
5876
5877 case Type::STK_Floating:
5878 switch (DestTy->getScalarTypeKind()) {
5879 case Type::STK_Floating:
5880 case Type::STK_Bool:
5881 case Type::STK_Integral:
5882 return true;
5883 case Type::STK_FloatingComplex:
5884 case Type::STK_IntegralComplex:
5885 llvm_unreachable("HLSL doesn't support complex types.");
5886 case Type::STK_FixedPoint:
5887 llvm_unreachable("HLSL doesn't support fixed point types.");
5888 case Type::STK_CPointer:
5889 case Type::STK_ObjCObjectPointer:
5890 case Type::STK_BlockPointer:
5891 case Type::STK_MemberPointer:
5892 llvm_unreachable("HLSL doesn't support pointers.");
5893 }
5894 llvm_unreachable("Should have returned before this");
5895
5896 case Type::STK_MemberPointer:
5897 case Type::STK_CPointer:
5898 case Type::STK_BlockPointer:
5899 case Type::STK_ObjCObjectPointer:
5900 llvm_unreachable("HLSL doesn't support pointers.");
5901
5902 case Type::STK_FixedPoint:
5903 llvm_unreachable("HLSL doesn't support fixed point types.");
5904
5905 case Type::STK_FloatingComplex:
5906 case Type::STK_IntegralComplex:
5907 llvm_unreachable("HLSL doesn't support complex types.");
5908 }
5909
5910 llvm_unreachable("Unhandled scalar cast");
5911}
5912
5913// Can perform an HLSL Aggregate splat cast if the Dest is an aggregate and the
5914// Src is a scalar, a vector of length 1, or a 1x1 matrix
5915// Or if Dest is a vector and Src is a vector of length 1 or a 1x1 matrix
5916bool SemaHLSL::CanPerformAggregateSplatCast(Expr *Src, QualType DestTy) {
5917
5918 QualType SrcTy = Src->getType();
5919 // Not a valid HLSL Aggregate Splat cast if Dest is a scalar or if this is
5920 // going to be a vector splat from a scalar.
5921 if ((SrcTy->isScalarType() && DestTy->isVectorType()) ||
5922 DestTy->isScalarType())
5923 return false;
5924
5925 const VectorType *SrcVecTy = SrcTy->getAs<VectorType>();
5926 const ConstantMatrixType *SrcMatTy = SrcTy->getAs<ConstantMatrixType>();
5927
5928 // Src isn't a scalar, a vector of length 1, or a 1x1 matrix
5929 if (!SrcTy->isScalarType() &&
5930 !(SrcVecTy && SrcVecTy->getNumElements() == 1) &&
5931 !(SrcMatTy && SrcMatTy->getNumElementsFlattened() == 1))
5932 return false;
5933
5934 if (SrcVecTy)
5935 SrcTy = SrcVecTy->getElementType();
5936 else if (SrcMatTy)
5937 SrcTy = SrcMatTy->getElementType();
5938
5939 llvm::SmallVector<QualType> DestTypes;
5940 BuildFlattenedTypeList(BaseTy: DestTy, List&: DestTypes);
5941
5942 for (unsigned I = 0, Size = DestTypes.size(); I < Size; ++I) {
5943 if (DestTypes[I]->isUnionType())
5944 return false;
5945 if (!CanPerformScalarCast(SrcTy, DestTy: DestTypes[I]))
5946 return false;
5947 }
5948 return true;
5949}
5950
5951// Can we perform an HLSL Elementwise cast?
5952bool SemaHLSL::CanPerformElementwiseCast(Expr *Src, QualType DestTy) {
5953
5954 // Don't handle casts where LHS and RHS are any combination of scalar/vector
5955 // There must be an aggregate somewhere
5956 QualType SrcTy = Src->getType();
5957 if (SrcTy->isScalarType()) // always a splat and this cast doesn't handle that
5958 return false;
5959
5960 if (SrcTy->isVectorType() &&
5961 (DestTy->isScalarType() || DestTy->isVectorType()))
5962 return false;
5963
5964 if (SrcTy->isConstantMatrixType() &&
5965 (DestTy->isScalarType() || DestTy->isConstantMatrixType()))
5966 return false;
5967
5968 llvm::SmallVector<QualType> DestTypes;
5969 BuildFlattenedTypeList(BaseTy: DestTy, List&: DestTypes);
5970 llvm::SmallVector<QualType> SrcTypes;
5971 BuildFlattenedTypeList(BaseTy: SrcTy, List&: SrcTypes);
5972
5973 // Usually the size of SrcTypes must be greater than or equal to the size of
5974 // DestTypes.
5975 if (SrcTypes.size() < DestTypes.size())
5976 return false;
5977
5978 unsigned SrcSize = SrcTypes.size();
5979 unsigned DstSize = DestTypes.size();
5980 unsigned I;
5981 for (I = 0; I < DstSize && I < SrcSize; I++) {
5982 if (SrcTypes[I]->isUnionType() || DestTypes[I]->isUnionType())
5983 return false;
5984 if (!CanPerformScalarCast(SrcTy: SrcTypes[I], DestTy: DestTypes[I])) {
5985 return false;
5986 }
5987 }
5988
5989 // check the rest of the source type for unions.
5990 for (; I < SrcSize; I++) {
5991 if (SrcTypes[I]->isUnionType())
5992 return false;
5993 }
5994 return true;
5995}
5996
5997bool SemaHLSL::CanPerformPackedTypeCast(Expr *Src, QualType DestTy) {
5998 ASTContext &Ctx = SemaRef.getASTContext();
5999 QualType UIntTy = Ctx.UnsignedIntTy;
6000 QualType SrcTy = Src->getType();
6001
6002 return (SrcTy->isHLSLBuiltinPackedType() &&
6003 DestTy->isHLSLBuiltinPackedType()) ||
6004 (SrcTy->isHLSLBuiltinPackedType() &&
6005 Ctx.hasSameUnqualifiedType(T1: DestTy, T2: UIntTy)) ||
6006 (DestTy->isHLSLBuiltinPackedType() &&
6007 Ctx.hasSameUnqualifiedType(T1: SrcTy, T2: UIntTy));
6008}
6009
6010ExprResult SemaHLSL::CreateOutArgExpr(Expr *Arg, QualType ArgTy,
6011 QualType ParamTy,
6012 InitializedEntity Entity,
6013 SourceLocation Loc, bool IsInOut) {
6014 ASTContext &Ctx = SemaRef.getASTContext();
6015
6016 QualType Ty = ParamTy.getNonLValueExprType(Context: Ctx);
6017
6018 auto *ArgOpV =
6019 new (Ctx) OpaqueValueExpr(Loc, ArgTy, VK_LValue, OK_Ordinary, Arg);
6020
6021 // Parameters are initialized via copy initialization. This allows for
6022 // overload resolution of argument constructors.
6023 ExprResult Res = SemaRef.PerformCopyInitialization(Entity, EqualLoc: Loc, Init: ArgOpV);
6024 if (Res.isInvalid())
6025 return ExprError();
6026 Expr *Base = Res.get();
6027 // After the cast, drop the reference type when creating the exprs.
6028 Ty = Ty.getNonLValueExprType(Context: Ctx);
6029 auto *OpV = new (Ctx) OpaqueValueExpr(Loc, Ty, VK_LValue, OK_Ordinary, Base);
6030
6031 // Writebacks are performed with `=` binary operator, which allows for
6032 // overload resolution on writeback result expressions.
6033 Res = SemaRef.ActOnBinOp(S: SemaRef.getCurScope(), TokLoc: Arg->getBeginLoc(),
6034 Kind: tok::equal, LHSExpr: ArgOpV, RHSExpr: OpV);
6035
6036 if (Res.isInvalid())
6037 return ExprError();
6038 Expr *Writeback = Res.get();
6039 auto *OutExpr =
6040 HLSLOutArgExpr::Create(C: Ctx, Ty, Base: ArgOpV, OpV, WB: Writeback, IsInOut);
6041 return ExprResult(OutExpr);
6042}
6043
6044ExprResult SemaHLSL::ActOnOutParamExpr(ParmVarDecl *Param, Expr *Arg) {
6045 ASTContext &Ctx = SemaRef.getASTContext();
6046 assert(Param->hasAttr<HLSLParamModifierAttr>() &&
6047 "We should not get here without a parameter modifier expression");
6048 const auto *Attr = Param->getAttr<HLSLParamModifierAttr>();
6049 if (Attr->getABI() == ParameterABI::Ordinary)
6050 return ExprResult(Arg);
6051
6052 bool IsInOut = Attr->getABI() == ParameterABI::HLSLInOut;
6053 if (!Arg->isLValue()) {
6054 SemaRef.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::error_hlsl_inout_lvalue)
6055 << Arg << (IsInOut ? 1 : 0);
6056 return ExprError();
6057 }
6058
6059 QualType Ty = Param->getType().getNonLValueExprType(Context: Ctx);
6060
6061 // HLSL allows implicit conversions from scalars to vectors, but not the
6062 // inverse, so we need to disallow `inout` with scalar->vector or
6063 // scalar->matrix conversions.
6064 if (Arg->getType()->isScalarType() != Ty->isScalarType()) {
6065 SemaRef.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::error_hlsl_inout_scalar_extension)
6066 << Arg << (IsInOut ? 1 : 0);
6067 return ExprError();
6068 }
6069
6070 InitializedEntity Entity =
6071 InitializedEntity::InitializeParameter(Context&: Ctx, Type: Ty, Consumed: false);
6072
6073 return CreateOutArgExpr(Arg, ArgTy: Arg->getType(), ParamTy: Param->getType(), Entity,
6074 Loc: Param->getBeginLoc(), IsInOut);
6075}
6076
6077QualType SemaHLSL::getInoutParameterType(QualType Ty) {
6078 // If HLSL gains support for references, all the cites that use this will need
6079 // to be updated with semantic checking to produce errors for
6080 // pointers/references.
6081 assert(!Ty->isReferenceType() &&
6082 "Pointer and reference types cannot be inout or out parameters");
6083 Ty = SemaRef.getASTContext().getLValueReferenceType(T: Ty);
6084 Ty.addRestrict();
6085 return Ty;
6086}
6087
6088// Returns true if the type has a non-empty constant buffer layout (if it is
6089// scalar, vector or matrix, or if it contains any of these.
6090static bool hasConstantBufferLayout(QualType QT) {
6091 const Type *Ty = QT->getUnqualifiedDesugaredType();
6092 if (Ty->isScalarType() || Ty->isVectorType() || Ty->isMatrixType())
6093 return true;
6094
6095 if (Ty->isHLSLResourceRecord() || Ty->isHLSLResourceRecordArray())
6096 return false;
6097
6098 if (const auto *RD = Ty->getAsCXXRecordDecl()) {
6099 for (const auto *FD : RD->fields()) {
6100 if (hasConstantBufferLayout(QT: FD->getType()))
6101 return true;
6102 }
6103 assert(RD->getNumBases() <= 1 &&
6104 "HLSL doesn't support multiple inheritance");
6105 return RD->getNumBases()
6106 ? hasConstantBufferLayout(QT: RD->bases_begin()->getType())
6107 : false;
6108 }
6109
6110 if (const auto *AT = dyn_cast<ArrayType>(Val: Ty)) {
6111 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT))
6112 if (isZeroSizedArray(CAT))
6113 return false;
6114 return hasConstantBufferLayout(QT: AT->getElementType());
6115 }
6116
6117 return false;
6118}
6119
6120static bool IsDefaultBufferConstantDecl(const ASTContext &Ctx, VarDecl *VD) {
6121 bool IsVulkan =
6122 Ctx.getTargetInfo().getTriple().getOS() == llvm::Triple::Vulkan;
6123 bool IsVKPushConstant = IsVulkan && VD->hasAttr<HLSLVkPushConstantAttr>();
6124 QualType QT = VD->getType();
6125 return VD->getDeclContext()->isTranslationUnit() &&
6126 QT.getAddressSpace() == LangAS::Default &&
6127 VD->getStorageClass() != SC_Static &&
6128 !VD->hasAttr<HLSLVkConstantIdAttr>() && !IsVKPushConstant &&
6129 hasConstantBufferLayout(QT);
6130}
6131
6132void SemaHLSL::deduceAddressSpace(VarDecl *Decl) {
6133 // The variable already has an address space (groupshared for ex).
6134 if (Decl->getType().hasAddressSpace())
6135 return;
6136
6137 if (Decl->getType()->isDependentType())
6138 return;
6139
6140 QualType Type = Decl->getType();
6141
6142 if (Decl->hasAttr<HLSLVkExtBuiltinInputAttr>()) {
6143 LangAS ImplAS = LangAS::hlsl_input;
6144 Type = SemaRef.getASTContext().getAddrSpaceQualType(T: Type, AddressSpace: ImplAS);
6145 Decl->setType(Type);
6146 return;
6147 }
6148
6149 if (Decl->hasAttr<HLSLVkExtBuiltinOutputAttr>()) {
6150 LangAS ImplAS = LangAS::hlsl_output;
6151 Type = SemaRef.getASTContext().getAddrSpaceQualType(T: Type, AddressSpace: ImplAS);
6152 Decl->setType(Type);
6153
6154 // HLSL uses `static` differently than C++. For BuiltIn output, the static
6155 // does not imply private to the module scope.
6156 // Marking it as external to reflect the semantic this attribute brings.
6157 // See https://github.com/microsoft/hlsl-specs/issues/350
6158 Decl->setStorageClass(SC_Extern);
6159 return;
6160 }
6161
6162 bool IsVulkan = getASTContext().getTargetInfo().getTriple().getOS() ==
6163 llvm::Triple::Vulkan;
6164 if (IsVulkan && Decl->hasAttr<HLSLVkPushConstantAttr>()) {
6165 if (HasDeclaredAPushConstant)
6166 SemaRef.Diag(Loc: Decl->getLocation(), DiagID: diag::err_hlsl_push_constant_unique);
6167
6168 LangAS ImplAS = LangAS::hlsl_push_constant;
6169 Type = SemaRef.getASTContext().getAddrSpaceQualType(T: Type, AddressSpace: ImplAS);
6170 Decl->setType(Type);
6171 HasDeclaredAPushConstant = true;
6172 return;
6173 }
6174
6175 if (Type->isSamplerT() || Type->isVoidType())
6176 return;
6177
6178 // Resource handles.
6179 if (Type->isHLSLResourceRecord() || Type->isHLSLResourceRecordArray())
6180 return;
6181
6182 // Only static globals belong to the Private address space.
6183 // Non-static globals belongs to the cbuffer.
6184 if (Decl->getStorageClass() != SC_Static && !Decl->isStaticDataMember())
6185 return;
6186
6187 LangAS ImplAS = LangAS::hlsl_private;
6188 Type = SemaRef.getASTContext().getAddrSpaceQualType(T: Type, AddressSpace: ImplAS);
6189 Decl->setType(Type);
6190}
6191
6192namespace {
6193
6194// Helper class for assigning bindings to resources declared within a struct.
6195// It keeps track of all binding attributes declared on a struct instance, and
6196// the offsets for each register type that have been assigned so far.
6197// Handles both explicit and implicit bindings.
6198class StructBindingContext {
6199 // Bindings and offsets per register type. We only need to support four
6200 // register types - SRV (u), UAV (t), CBuffer (c), and Sampler (s).
6201 HLSLResourceBindingAttr *RegBindingsAttrs[4];
6202 unsigned RegBindingOffset[4];
6203
6204 // Make sure the RegisterType values are what we expect
6205 static_assert(static_cast<unsigned>(RegisterType::SRV) == 0 &&
6206 static_cast<unsigned>(RegisterType::UAV) == 1 &&
6207 static_cast<unsigned>(RegisterType::CBuffer) == 2 &&
6208 static_cast<unsigned>(RegisterType::Sampler) == 3,
6209 "unexpected register type values");
6210
6211 // Vulkan binding attribute does not vary by register type.
6212 HLSLVkBindingAttr *VkBindingAttr;
6213 unsigned VkBindingOffset;
6214
6215public:
6216 // Constructor: gather all binding attributes on a struct instance and
6217 // initialize offsets.
6218 StructBindingContext(VarDecl *VD) {
6219 for (unsigned i = 0; i < 4; ++i) {
6220 RegBindingsAttrs[i] = nullptr;
6221 RegBindingOffset[i] = 0;
6222 }
6223 VkBindingAttr = nullptr;
6224 VkBindingOffset = 0;
6225
6226 ASTContext &AST = VD->getASTContext();
6227 bool IsSpirv = AST.getTargetInfo().getTriple().isSPIRV();
6228
6229 for (Attr *A : VD->attrs()) {
6230 if (auto *RBA = dyn_cast<HLSLResourceBindingAttr>(Val: A)) {
6231 RegisterType RegType = RBA->getRegisterType();
6232 unsigned RegTypeIdx = static_cast<unsigned>(RegType);
6233 // Ignore unsupported register annotations, such as 'c' or 'i'.
6234 if (RegTypeIdx < 4)
6235 RegBindingsAttrs[RegTypeIdx] = RBA;
6236 continue;
6237 }
6238 // Gather the Vulkan binding attributes only if the target is SPIR-V.
6239 if (IsSpirv) {
6240 if (auto *VBA = dyn_cast<HLSLVkBindingAttr>(Val: A))
6241 VkBindingAttr = VBA;
6242 }
6243 }
6244 }
6245
6246 // Creates a binding attribute for a resource based on the gathered attributes
6247 // and the required register type and range.
6248 Attr *createBindingAttr(SemaHLSL &S, ASTContext &AST, RegisterType RegType,
6249 unsigned Range, bool HasCounter) {
6250 assert(static_cast<unsigned>(RegType) < 4 && "unexpected register type");
6251
6252 if (VkBindingAttr) {
6253 unsigned Offset = VkBindingOffset;
6254 VkBindingOffset += Range;
6255 return HLSLVkBindingAttr::CreateImplicit(
6256 Ctx&: AST, Binding: VkBindingAttr->getBinding() + Offset, Set: VkBindingAttr->getSet(),
6257 Range: VkBindingAttr->getRange());
6258 }
6259
6260 HLSLResourceBindingAttr *RBA =
6261 RegBindingsAttrs[static_cast<unsigned>(RegType)];
6262 HLSLResourceBindingAttr *NewAttr = nullptr;
6263
6264 if (RBA && RBA->hasRegisterSlot()) {
6265 // Explicit binding - create a new attribute with offseted slot number
6266 // based on the required register type.
6267 unsigned Offset = RegBindingOffset[static_cast<unsigned>(RegType)];
6268 RegBindingOffset[static_cast<unsigned>(RegType)] += Range;
6269
6270 unsigned NewSlotNumber = RBA->getSlotNumber() + Offset;
6271 StringRef NewSlotNumberStr =
6272 createRegisterString(AST, RegType: RBA->getRegisterType(), N: NewSlotNumber);
6273 NewAttr = HLSLResourceBindingAttr::CreateImplicit(
6274 Ctx&: AST, Slot: NewSlotNumberStr, Space: RBA->getSpace(), Range: RBA->getRange());
6275 NewAttr->setBinding(RT: RegType, SlotNum: NewSlotNumber, SpaceNum: RBA->getSpaceNumber());
6276 } else {
6277 // No binding attribute or space-only binding - create a binding
6278 // attribute for implicit binding.
6279 NewAttr = HLSLResourceBindingAttr::CreateImplicit(Ctx&: AST, Slot: "", Space: "0", Range: {});
6280 NewAttr->setBinding(RT: RegType, SlotNum: std::nullopt,
6281 SpaceNum: RBA ? RBA->getSpaceNumber() : 0);
6282 NewAttr->setImplicitBindingOrderID(S.getNextImplicitBindingOrderID());
6283 }
6284 if (HasCounter)
6285 NewAttr->setImplicitCounterBindingOrderID(
6286 S.getNextImplicitBindingOrderID());
6287 return NewAttr;
6288 }
6289};
6290
6291// Creates a global variable declaration for a resource field embedded in a
6292// struct, assigns it a binding, initializes it, and associates it with the
6293// struct declaration via an HLSLAssociatedResourceDeclAttr.
6294static void createGlobalResourceDeclForStruct(
6295 Sema &S, VarDecl *ParentVD, SourceLocation Loc, IdentifierInfo *Id,
6296 QualType ResTy, StructBindingContext &BindingCtx) {
6297 assert(isResourceRecordTypeOrArrayOf(ResTy) &&
6298 "expected resource type or array of resources");
6299
6300 DeclContext *DC = ParentVD->getNonTransparentDeclContext();
6301 assert(DC->isTranslationUnit() && "expected translation unit decl context");
6302
6303 ASTContext &AST = S.getASTContext();
6304 VarDecl *ResDecl =
6305 VarDecl::Create(C&: AST, DC, StartLoc: Loc, IdLoc: Loc, Id, T: ResTy, TInfo: nullptr, S: SC_None);
6306
6307 unsigned Range = 1;
6308 const Type *SingleResTy = ResTy.getTypePtr()->getUnqualifiedDesugaredType();
6309 while (const auto *AT = dyn_cast<ArrayType>(Val: SingleResTy)) {
6310 const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT);
6311 Range = CAT ? (Range * CAT->getSize().getZExtValue()) : 0;
6312 SingleResTy =
6313 AT->getArrayElementTypeNoTypeQual()->getUnqualifiedDesugaredType();
6314 }
6315 const HLSLAttributedResourceType *ResHandleTy =
6316 HLSLAttributedResourceType::findHandleTypeOnResource(RT: SingleResTy);
6317
6318 // Add a binding attribute to the global resource declaration.
6319 bool HasCounter = hasCounterHandle(RD: SingleResTy->getAsCXXRecordDecl());
6320 Attr *BindingAttr = BindingCtx.createBindingAttr(
6321 S&: S.HLSL(), AST, RegType: getRegisterType(ResTy: ResHandleTy), Range, HasCounter);
6322 ResDecl->addAttr(A: BindingAttr);
6323 ResDecl->addAttr(A: InternalLinkageAttr::CreateImplicit(Ctx&: AST));
6324 ResDecl->setImplicit();
6325
6326 if (Range == 1)
6327 S.HLSL().initGlobalResourceDecl(VD: ResDecl);
6328 else
6329 S.HLSL().initGlobalResourceArrayDecl(VD: ResDecl);
6330
6331 ParentVD->addAttr(
6332 A: HLSLAssociatedResourceDeclAttr::CreateImplicit(Ctx&: AST, ResDecl));
6333 DC->addDecl(D: ResDecl);
6334
6335 DeclGroupRef DG(ResDecl);
6336 S.Consumer.HandleTopLevelDecl(D: DG);
6337}
6338
6339static void handleArrayOfStructWithResources(
6340 Sema &S, VarDecl *ParentVD, const ConstantArrayType *CAT,
6341 EmbeddedResourceNameBuilder &NameBuilder, StructBindingContext &BindingCtx);
6342
6343// Scans base and all fields of a struct/class type to find all embedded
6344// resources or resource arrays. Creates a global variable for each resource
6345// found.
6346static void handleStructWithResources(Sema &S, VarDecl *ParentVD,
6347 const CXXRecordDecl *RD,
6348 EmbeddedResourceNameBuilder &NameBuilder,
6349 StructBindingContext &BindingCtx) {
6350
6351 // Scan the base classes.
6352 assert(RD->getNumBases() <= 1 && "HLSL doesn't support multiple inheritance");
6353 const auto *BasesIt = RD->bases_begin();
6354 if (BasesIt != RD->bases_end()) {
6355 QualType QT = BasesIt->getType();
6356 if (QT->isHLSLIntangibleType()) {
6357 CXXRecordDecl *BaseRD = QT->getAsCXXRecordDecl();
6358 NameBuilder.pushBaseName(N: BaseRD->getName());
6359 handleStructWithResources(S, ParentVD, RD: BaseRD, NameBuilder, BindingCtx);
6360 NameBuilder.pop();
6361 }
6362 }
6363 // Process this class fields.
6364 for (const FieldDecl *FD : RD->fields()) {
6365 QualType FDTy = FD->getType().getCanonicalType();
6366 if (!FDTy->isHLSLIntangibleType())
6367 continue;
6368
6369 NameBuilder.pushName(N: FD->getName());
6370
6371 if (isResourceRecordTypeOrArrayOf(Ty: FDTy)) {
6372 IdentifierInfo *II = NameBuilder.getNameAsIdentifier(AST&: S.getASTContext());
6373 createGlobalResourceDeclForStruct(S, ParentVD, Loc: FD->getLocation(), Id: II,
6374 ResTy: FDTy, BindingCtx);
6375 } else if (const auto *RD = FDTy->getAsCXXRecordDecl()) {
6376 handleStructWithResources(S, ParentVD, RD, NameBuilder, BindingCtx);
6377
6378 } else if (const auto *ArrayTy = dyn_cast<ConstantArrayType>(Val&: FDTy)) {
6379 assert(!FDTy->isHLSLResourceRecordArray() &&
6380 "resource arrays should have been already handled");
6381 handleArrayOfStructWithResources(S, ParentVD, CAT: ArrayTy, NameBuilder,
6382 BindingCtx);
6383 }
6384 NameBuilder.pop();
6385 }
6386}
6387
6388// Processes array of structs with resources.
6389static void
6390handleArrayOfStructWithResources(Sema &S, VarDecl *ParentVD,
6391 const ConstantArrayType *CAT,
6392 EmbeddedResourceNameBuilder &NameBuilder,
6393 StructBindingContext &BindingCtx) {
6394
6395 QualType ElementTy = CAT->getElementType().getCanonicalType();
6396 assert(ElementTy->isHLSLIntangibleType() && "Expected HLSL intangible type");
6397
6398 const ConstantArrayType *SubCAT = dyn_cast<ConstantArrayType>(Val&: ElementTy);
6399 const CXXRecordDecl *ElementRD = ElementTy->getAsCXXRecordDecl();
6400
6401 if (!SubCAT && !ElementRD)
6402 return;
6403
6404 for (unsigned I = 0, E = CAT->getSize().getZExtValue(); I < E; ++I) {
6405 NameBuilder.pushArrayIndex(Index: I);
6406 if (ElementRD)
6407 handleStructWithResources(S, ParentVD, RD: ElementRD, NameBuilder,
6408 BindingCtx);
6409 else
6410 handleArrayOfStructWithResources(S, ParentVD, CAT: SubCAT, NameBuilder,
6411 BindingCtx);
6412 NameBuilder.pop();
6413 }
6414}
6415
6416} // namespace
6417
6418// Scans all fields of a user-defined struct (or array of structs)
6419// to find all embedded resources or resource arrays. For each resource
6420// a global variable of the resource type is created and associated
6421// with the parent declaration (VD) through a HLSLAssociatedResourceDeclAttr
6422// attribute.
6423void SemaHLSL::handleGlobalStructOrArrayOfWithResources(VarDecl *VD) {
6424 EmbeddedResourceNameBuilder NameBuilder(VD->getName());
6425 StructBindingContext BindingCtx(VD);
6426
6427 const Type *VDTy = VD->getType().getTypePtr();
6428 assert(VDTy->isHLSLIntangibleType() && !isResourceRecordTypeOrArrayOf(VD) &&
6429 "Expected non-resource struct or array type");
6430
6431 if (const CXXRecordDecl *RD = VDTy->getAsCXXRecordDecl()) {
6432 handleStructWithResources(S&: SemaRef, ParentVD: VD, RD, NameBuilder, BindingCtx);
6433 return;
6434 }
6435
6436 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: VDTy)) {
6437 handleArrayOfStructWithResources(S&: SemaRef, ParentVD: VD, CAT, NameBuilder, BindingCtx);
6438 return;
6439 }
6440}
6441
6442void SemaHLSL::ActOnVariableDeclarator(VarDecl *VD) {
6443 if (VD->hasGlobalStorage()) {
6444 // make sure the declaration has a complete type
6445 if (SemaRef.RequireCompleteType(
6446 Loc: VD->getLocation(),
6447 T: SemaRef.getASTContext().getBaseElementType(QT: VD->getType()),
6448 DiagID: diag::err_typecheck_decl_incomplete_type)) {
6449 VD->setInvalidDecl();
6450 deduceAddressSpace(Decl: VD);
6451 return;
6452 }
6453
6454 // Global variables outside a cbuffer block that are not a resource, static,
6455 // groupshared, or an empty array or struct belong to the default constant
6456 // buffer $Globals (to be created at the end of the translation unit).
6457 if (IsDefaultBufferConstantDecl(Ctx: getASTContext(), VD)) {
6458 // update address space to hlsl_constant
6459 QualType NewTy = getASTContext().getAddrSpaceQualType(
6460 T: VD->getType(), AddressSpace: LangAS::hlsl_constant);
6461 VD->setType(NewTy);
6462 DefaultCBufferDecls.push_back(Elt: VD);
6463 }
6464
6465 // find all resources bindings on decl
6466 if (VD->getType()->isHLSLIntangibleType())
6467 collectResourceBindingsOnVarDecl(D: VD);
6468
6469 if (VD->hasAttr<HLSLVkConstantIdAttr>())
6470 VD->setStorageClass(StorageClass::SC_Static);
6471
6472 if (isResourceRecordTypeOrArrayOf(VD) &&
6473 VD->getStorageClass() != SC_Static) {
6474 // Add internal linkage attribute to non-static resource variables. The
6475 // global externally visible storage is accessed through the handle, which
6476 // is a member. The variable itself is not externally visible.
6477 VD->addAttr(A: InternalLinkageAttr::CreateImplicit(Ctx&: getASTContext()));
6478 }
6479
6480 // process explicit bindings
6481 processExplicitBindingsOnDecl(D: VD);
6482
6483 // Add implicit binding attribute to non-static resource arrays.
6484 if (VD->getType()->isHLSLResourceRecordArray() &&
6485 VD->getStorageClass() != SC_Static) {
6486 // If the resource array does not have an explicit binding attribute,
6487 // create an implicit one. It will be used to transfer implicit binding
6488 // order_ID to codegen.
6489 ResourceBindingAttrs Binding(VD);
6490 if (!Binding.isExplicit()) {
6491 uint32_t OrderID = getNextImplicitBindingOrderID();
6492 if (Binding.hasBinding())
6493 Binding.setImplicitOrderID(OrderID);
6494 else {
6495 addImplicitBindingAttrToDecl(
6496 S&: SemaRef, D: VD, RT: getRegisterType(ResTy: getResourceArrayHandleType(VD)),
6497 ImplicitBindingOrderID: OrderID);
6498 // Re-create the binding object to pick up the new attribute.
6499 Binding = ResourceBindingAttrs(VD);
6500 }
6501 }
6502
6503 // Get to the base type of a potentially multi-dimensional array.
6504 QualType Ty = getASTContext().getBaseElementType(QT: VD->getType());
6505
6506 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6507 if (hasCounterHandle(RD)) {
6508 if (!Binding.hasCounterImplicitOrderID()) {
6509 uint32_t OrderID = getNextImplicitBindingOrderID();
6510 Binding.setCounterImplicitOrderID(OrderID);
6511 }
6512 }
6513 }
6514
6515 // Process resources in user-defined structs, or arrays of such structs.
6516 if (VD->getStorageClass() != SC_Static &&
6517 isStructOrArrayOfWithResources(Ty: VD->getType()))
6518 handleGlobalStructOrArrayOfWithResources(VD);
6519
6520 // Mark groupshared variables as extern so they will have
6521 // external storage and won't be default initialized
6522 if (VD->hasAttr<HLSLGroupSharedAddressSpaceAttr>())
6523 VD->setStorageClass(StorageClass::SC_Extern);
6524 }
6525
6526 deduceAddressSpace(Decl: VD);
6527}
6528
6529bool SemaHLSL::initGlobalResourceDecl(VarDecl *VD) {
6530 assert(VD->getType()->isHLSLResourceRecord() &&
6531 "expected resource record type");
6532
6533 ASTContext &AST = SemaRef.getASTContext();
6534 uint64_t UIntTySize = AST.getTypeSize(T: AST.UnsignedIntTy);
6535 uint64_t IntTySize = AST.getTypeSize(T: AST.IntTy);
6536
6537 // Gather resource binding attributes.
6538 ResourceBindingAttrs Binding(VD);
6539
6540 // Find correct initialization method and create its arguments.
6541 QualType ResourceTy = VD->getType();
6542 CXXRecordDecl *ResourceDecl = ResourceTy->getAsCXXRecordDecl();
6543 CXXMethodDecl *CreateMethod = nullptr;
6544 llvm::SmallVector<Expr *> Args;
6545
6546 bool HasCounter = hasCounterHandle(RD: ResourceDecl);
6547 const char *CreateMethodName;
6548 if (Binding.isExplicit())
6549 CreateMethodName = HasCounter ? "__createFromBindingWithImplicitCounter"
6550 : "__createFromBinding";
6551 else
6552 CreateMethodName = HasCounter
6553 ? "__createFromImplicitBindingWithImplicitCounter"
6554 : "__createFromImplicitBinding";
6555
6556 CreateMethod =
6557 lookupMethod(S&: SemaRef, RecordDecl: ResourceDecl, Name: CreateMethodName, Loc: VD->getLocation());
6558
6559 if (!CreateMethod) {
6560 // This can happen if someone creates a struct that looks like an HLSL
6561 // resource record but does not have the required static create method.
6562 // No binding will be generated for it.
6563 assert(!ResourceDecl->isImplicit() &&
6564 "create method lookup should always succeed for built-in resource "
6565 "records");
6566 return false;
6567 }
6568
6569 if (Binding.isExplicit()) {
6570 IntegerLiteral *RegSlot =
6571 IntegerLiteral::Create(C: AST, V: llvm::APInt(UIntTySize, Binding.getSlot()),
6572 type: AST.UnsignedIntTy, l: SourceLocation());
6573 Args.push_back(Elt: RegSlot);
6574 } else {
6575 uint32_t OrderID = (Binding.hasImplicitOrderID())
6576 ? Binding.getImplicitOrderID()
6577 : getNextImplicitBindingOrderID();
6578 IntegerLiteral *OrderId =
6579 IntegerLiteral::Create(C: AST, V: llvm::APInt(UIntTySize, OrderID),
6580 type: AST.UnsignedIntTy, l: SourceLocation());
6581 Args.push_back(Elt: OrderId);
6582 }
6583
6584 IntegerLiteral *Space =
6585 IntegerLiteral::Create(C: AST, V: llvm::APInt(UIntTySize, Binding.getSpace()),
6586 type: AST.UnsignedIntTy, l: SourceLocation());
6587 Args.push_back(Elt: Space);
6588
6589 IntegerLiteral *RangeSize = IntegerLiteral::Create(
6590 C: AST, V: llvm::APInt(IntTySize, 1), type: AST.IntTy, l: SourceLocation());
6591 Args.push_back(Elt: RangeSize);
6592
6593 IntegerLiteral *Index = IntegerLiteral::Create(
6594 C: AST, V: llvm::APInt(UIntTySize, 0), type: AST.UnsignedIntTy, l: SourceLocation());
6595 Args.push_back(Elt: Index);
6596
6597 StringRef VarName = VD->getName();
6598 StringLiteral *Name = StringLiteral::Create(
6599 Ctx: AST, Str: VarName, Kind: StringLiteralKind::Ordinary, Pascal: false,
6600 Ty: AST.getStringLiteralArrayType(EltTy: AST.CharTy.withConst(), Length: VarName.size()),
6601 Locs: SourceLocation());
6602 ImplicitCastExpr *NameCast = ImplicitCastExpr::Create(
6603 Context: AST, T: AST.getPointerType(T: AST.CharTy.withConst()), Kind: CK_ArrayToPointerDecay,
6604 Operand: Name, BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
6605 Args.push_back(Elt: NameCast);
6606
6607 if (HasCounter) {
6608 // Will this be in the correct order?
6609 uint32_t CounterOrderID = getNextImplicitBindingOrderID();
6610 IntegerLiteral *CounterId =
6611 IntegerLiteral::Create(C: AST, V: llvm::APInt(UIntTySize, CounterOrderID),
6612 type: AST.UnsignedIntTy, l: SourceLocation());
6613 Args.push_back(Elt: CounterId);
6614 }
6615
6616 // Make sure the create method template is instantiated and emitted.
6617 if (!CreateMethod->isDefined() && CreateMethod->isTemplateInstantiation())
6618 SemaRef.InstantiateFunctionDefinition(PointOfInstantiation: VD->getLocation(), Function: CreateMethod,
6619 Recursive: true);
6620
6621 // Create CallExpr with a call to the static method and set it as the decl
6622 // initialization.
6623 DeclRefExpr *DRE = DeclRefExpr::Create(
6624 Context: AST, QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(), D: CreateMethod, RefersToEnclosingVariableOrCapture: false,
6625 NameInfo: CreateMethod->getNameInfo(), T: CreateMethod->getType(), VK: VK_PRValue);
6626
6627 auto *ImpCast = ImplicitCastExpr::Create(
6628 Context: AST, T: AST.getPointerType(T: CreateMethod->getType()),
6629 Kind: CK_FunctionToPointerDecay, Operand: DRE, BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
6630
6631 CallExpr *InitExpr =
6632 CallExpr::Create(Ctx: AST, Fn: ImpCast, Args, Ty: ResourceTy, VK: VK_PRValue,
6633 RParenLoc: SourceLocation(), FPFeatures: FPOptionsOverride());
6634 VD->setInit(InitExpr);
6635 VD->setInitStyle(VarDecl::CallInit);
6636 SemaRef.CheckCompleteVariableDeclaration(VD);
6637 return true;
6638}
6639
6640bool SemaHLSL::initGlobalResourceArrayDecl(VarDecl *VD) {
6641 assert(VD->getType()->isHLSLResourceRecordArray() &&
6642 "expected array of resource records");
6643
6644 // Individual resources in a resource array are not initialized here. They
6645 // are initialized later on during codegen when the individual resources are
6646 // accessed. Codegen will emit a call to the resource initialization method
6647 // with the specified array index. We need to make sure though that the method
6648 // for the specific resource type is instantiated, so codegen can emit a call
6649 // to it when the array element is accessed.
6650
6651 // Find correct initialization method based on the resource binding
6652 // information.
6653 ASTContext &AST = SemaRef.getASTContext();
6654 QualType ResElementTy = AST.getBaseElementType(QT: VD->getType());
6655 CXXRecordDecl *ResourceDecl = ResElementTy->getAsCXXRecordDecl();
6656 CXXMethodDecl *CreateMethod = nullptr;
6657
6658 bool HasCounter = hasCounterHandle(RD: ResourceDecl);
6659 ResourceBindingAttrs ResourceAttrs(VD);
6660 if (ResourceAttrs.isExplicit())
6661 // Resource has explicit binding.
6662 CreateMethod =
6663 lookupMethod(S&: SemaRef, RecordDecl: ResourceDecl,
6664 Name: HasCounter ? "__createFromBindingWithImplicitCounter"
6665 : "__createFromBinding",
6666 Loc: VD->getLocation());
6667 else
6668 // Resource has implicit binding.
6669 CreateMethod = lookupMethod(
6670 S&: SemaRef, RecordDecl: ResourceDecl,
6671 Name: HasCounter ? "__createFromImplicitBindingWithImplicitCounter"
6672 : "__createFromImplicitBinding",
6673 Loc: VD->getLocation());
6674
6675 if (!CreateMethod)
6676 return false;
6677
6678 // Make sure the create method template is instantiated and emitted.
6679 if (!CreateMethod->isDefined() && CreateMethod->isTemplateInstantiation())
6680 SemaRef.InstantiateFunctionDefinition(PointOfInstantiation: VD->getLocation(), Function: CreateMethod,
6681 Recursive: true);
6682 return true;
6683}
6684
6685// Returns true if the initialization has been handled.
6686// Returns false to use default initialization.
6687bool SemaHLSL::ActOnUninitializedVarDecl(VarDecl *VD) {
6688 // Objects in the hlsl_constant address space are initialized
6689 // externally, so don't synthesize an implicit initializer.
6690 if (VD->getType().getAddressSpace() == LangAS::hlsl_constant)
6691 return true;
6692
6693 if (VD->hasGlobalStorage() && VD->getStorageClass() != SC_Static) {
6694 const Type *Ty = VD->getType().getTypePtr();
6695 if (Ty->isHLSLResourceRecord() && initGlobalResourceDecl(VD))
6696 return true;
6697 if (Ty->isHLSLResourceRecordArray() && initGlobalResourceArrayDecl(VD))
6698 return true;
6699 }
6700
6701 // User-defined structs/classes do not have constructors.
6702 // When declared at a global scope, they are part of the constant buffer
6703 // and should not be initialized by the compiler.
6704 // When declared at a local scope, they are not initialized.
6705 // Also applies to arrays of user-defined structs/classes.
6706 const Type *Ty = VD->getType()->getUnqualifiedDesugaredType();
6707 while (Ty->isArrayType())
6708 Ty = Ty->getArrayElementTypeNoTypeQual()->getUnqualifiedDesugaredType();
6709 if (CXXRecordDecl *RD = Ty->getAsCXXRecordDecl())
6710 return !RD->isHLSLBuiltinRecord();
6711
6712 return false;
6713}
6714
6715std::optional<const DeclBindingInfo *> SemaHLSL::inferGlobalBinding(Expr *E) {
6716 if (auto *Ternary = dyn_cast<ConditionalOperator>(Val: E)) {
6717 auto TrueInfo = inferGlobalBinding(E: Ternary->getTrueExpr());
6718 auto FalseInfo = inferGlobalBinding(E: Ternary->getFalseExpr());
6719 if (!TrueInfo || !FalseInfo)
6720 return std::nullopt;
6721 if (*TrueInfo != *FalseInfo)
6722 return std::nullopt;
6723 return TrueInfo;
6724 }
6725
6726 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: E))
6727 E = ASE->getBase()->IgnoreParenImpCasts();
6728
6729 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens()))
6730 if (VarDecl *VD = dyn_cast<VarDecl>(Val: DRE->getDecl())) {
6731 const Type *Ty = VD->getType()->getUnqualifiedDesugaredType();
6732 if (Ty->isArrayType())
6733 Ty = Ty->getArrayElementTypeNoTypeQual();
6734
6735 if (const auto *AttrResType =
6736 HLSLAttributedResourceType::findHandleTypeOnResource(RT: Ty)) {
6737 ResourceClass RC = AttrResType->getAttrs().ResourceClass;
6738 return Bindings.getDeclBindingInfo(VD, ResClass: RC);
6739 }
6740 }
6741
6742 return nullptr;
6743}
6744
6745void SemaHLSL::trackLocalResource(VarDecl *VD, Expr *E) {
6746 std::optional<const DeclBindingInfo *> ExprBinding = inferGlobalBinding(E);
6747 if (!ExprBinding) {
6748 SemaRef.Diag(Loc: E->getBeginLoc(),
6749 DiagID: diag::warn_hlsl_assigning_local_resource_is_not_unique)
6750 << E << VD;
6751 return; // Expr use multiple resources
6752 }
6753
6754 if (*ExprBinding == nullptr)
6755 return; // No binding could be inferred to track, return without error
6756
6757 auto PrevBinding = Assigns.find(Val: VD);
6758 if (PrevBinding == Assigns.end()) {
6759 // No previous binding recorded, simply record the new assignment
6760 Assigns.insert(KV: {VD, *ExprBinding});
6761 return;
6762 }
6763
6764 // Otherwise, warn if the assignment implies different resource bindings
6765 if (*ExprBinding != PrevBinding->second) {
6766 SemaRef.Diag(Loc: E->getBeginLoc(),
6767 DiagID: diag::warn_hlsl_assigning_local_resource_is_not_unique)
6768 << E << VD;
6769 SemaRef.Diag(Loc: VD->getLocation(), DiagID: diag::note_var_declared_here) << VD;
6770 return;
6771 }
6772
6773 return;
6774}
6775
6776bool SemaHLSL::CheckResourceBinOp(BinaryOperatorKind Opc, Expr *LHSExpr,
6777 Expr *RHSExpr, SourceLocation Loc) {
6778 assert((LHSExpr->getType()->isHLSLResourceRecord() ||
6779 LHSExpr->getType()->isHLSLResourceRecordArray()) &&
6780 "expected LHS to be a resource record or array of resource records");
6781 if (Opc != BO_Assign)
6782 return true;
6783
6784 // If LHS is an array subscript, get the underlying declaration.
6785 Expr *E = LHSExpr;
6786 while (auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: E))
6787 E = ASE->getBase()->IgnoreParenImpCasts();
6788
6789 // Report error if LHS is a non-static resource declared at a global scope.
6790 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) {
6791 if (VarDecl *VD = dyn_cast<VarDecl>(Val: DRE->getDecl())) {
6792 if (VD->hasGlobalStorage() && VD->getStorageClass() != SC_Static) {
6793 // assignment to global resource is not allowed
6794 SemaRef.Diag(Loc, DiagID: diag::err_hlsl_assign_to_global_resource) << VD;
6795 SemaRef.Diag(Loc: VD->getLocation(), DiagID: diag::note_var_declared_here) << VD;
6796 return false;
6797 }
6798
6799 trackLocalResource(VD, E: RHSExpr);
6800 }
6801 }
6802 return true;
6803}
6804
6805// Returns true if the given type can have an overload of the given
6806// binary operator.
6807bool SemaHLSL::canHaveOverloadedBinOp(QualType LHSTy, BinaryOperatorKind Opc) {
6808 CXXRecordDecl *RD = LHSTy->getAsCXXRecordDecl();
6809 if (!RD)
6810 return true;
6811 return RD->isHLSLBuiltinRecord() || Opc != BO_Assign;
6812}
6813
6814// Walks though the global variable declaration, collects all resource binding
6815// requirements and adds them to Bindings
6816void SemaHLSL::collectResourceBindingsOnVarDecl(VarDecl *VD) {
6817 assert(VD->hasGlobalStorage() && VD->getType()->isHLSLIntangibleType() &&
6818 "expected global variable that contains HLSL resource");
6819
6820 // Cbuffers and Tbuffers are HLSLBufferDecl types
6821 if (const HLSLBufferDecl *CBufferOrTBuffer = dyn_cast<HLSLBufferDecl>(Val: VD)) {
6822 Bindings.addDeclBindingInfo(VD, ResClass: CBufferOrTBuffer->isCBuffer()
6823 ? ResourceClass::CBuffer
6824 : ResourceClass::SRV);
6825 return;
6826 }
6827
6828 // Unwrap arrays
6829 // FIXME: Calculate array size while unwrapping
6830 const Type *Ty = VD->getType()->getUnqualifiedDesugaredType();
6831 while (Ty->isArrayType()) {
6832 const ArrayType *AT = cast<ArrayType>(Val: Ty);
6833 Ty = AT->getElementType()->getUnqualifiedDesugaredType();
6834 }
6835
6836 // Resource (or array of resources)
6837 if (const HLSLAttributedResourceType *AttrResType =
6838 HLSLAttributedResourceType::findHandleTypeOnResource(RT: Ty)) {
6839 Bindings.addDeclBindingInfo(VD, ResClass: AttrResType->getAttrs().ResourceClass);
6840 return;
6841 }
6842
6843 // User defined record type
6844 if (const RecordType *RT = dyn_cast<RecordType>(Val: Ty))
6845 collectResourceBindingsOnUserRecordDecl(VD, RT);
6846}
6847
6848// Walks though the explicit resource binding attributes on the declaration,
6849// and makes sure there is a resource that matched the binding and updates
6850// DeclBindingInfoLists
6851void SemaHLSL::processExplicitBindingsOnDecl(VarDecl *VD) {
6852 assert(VD->hasGlobalStorage() && "expected global variable");
6853
6854 bool HasBinding = false;
6855 for (Attr *A : VD->attrs()) {
6856 if (isa<HLSLVkBindingAttr>(Val: A)) {
6857 HasBinding = true;
6858 if (auto PA = VD->getAttr<HLSLVkPushConstantAttr>())
6859 Diag(Loc: PA->getLoc(), DiagID: diag::err_hlsl_attr_incompatible) << A << PA;
6860 }
6861
6862 HLSLResourceBindingAttr *RBA = dyn_cast<HLSLResourceBindingAttr>(Val: A);
6863 if (!RBA || !RBA->hasRegisterSlot())
6864 continue;
6865 HasBinding = true;
6866
6867 RegisterType RT = RBA->getRegisterType();
6868 assert(RT != RegisterType::I && "invalid or obsolete register type should "
6869 "never have an attribute created");
6870
6871 if (RT == RegisterType::C) {
6872 if (Bindings.hasBindingInfoForDecl(VD))
6873 SemaRef.Diag(Loc: VD->getLocation(),
6874 DiagID: diag::warn_hlsl_user_defined_type_missing_member)
6875 << static_cast<int>(RT);
6876 continue;
6877 }
6878
6879 // Find DeclBindingInfo for this binding and update it, or report error
6880 // if it does not exist (user type does to contain resources with the
6881 // expected resource class).
6882 ResourceClass RC = getResourceClass(RT);
6883 if (DeclBindingInfo *BI = Bindings.getDeclBindingInfo(VD, ResClass: RC)) {
6884 // update binding info
6885 BI->setBindingAttribute(A: RBA, BT: BindingType::Explicit);
6886 } else {
6887 SemaRef.Diag(Loc: VD->getLocation(),
6888 DiagID: diag::warn_hlsl_user_defined_type_missing_member)
6889 << static_cast<int>(RT);
6890 }
6891 }
6892
6893 if (!HasBinding && isResourceRecordTypeOrArrayOf(VD))
6894 SemaRef.Diag(Loc: VD->getLocation(), DiagID: diag::warn_hlsl_implicit_binding);
6895}
6896namespace {
6897class InitListTransformer {
6898 Sema &S;
6899 ASTContext &Ctx;
6900 QualType InitTy;
6901 QualType *DstIt = nullptr;
6902 Expr **ArgIt = nullptr;
6903 // Is wrapping the destination type iterator required? This is only used for
6904 // incomplete array types where we loop over the destination type since we
6905 // don't know the full number of elements from the declaration.
6906 bool Wrap;
6907
6908 bool castInitializer(Expr *E) {
6909 assert(DstIt && "This should always be something!");
6910 if (DstIt == DestTypes.end()) {
6911 if (!Wrap) {
6912 ArgExprs.push_back(Elt: E);
6913 // This is odd, but it isn't technically a failure due to conversion, we
6914 // handle mismatched counts of arguments differently.
6915 return true;
6916 }
6917 DstIt = DestTypes.begin();
6918 }
6919 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6920 Context&: Ctx, Type: *DstIt, /* Consumed (ObjC) */ Consumed: false);
6921 ExprResult Res = S.PerformCopyInitialization(Entity, EqualLoc: E->getBeginLoc(), Init: E);
6922 if (Res.isInvalid())
6923 return false;
6924 Expr *Init = Res.get();
6925 ArgExprs.push_back(Elt: Init);
6926 DstIt++;
6927 return true;
6928 }
6929
6930 bool buildInitializerListImpl(Expr *E) {
6931 // If this is an initialization list, traverse the sub initializers.
6932 if (auto *Init = dyn_cast<InitListExpr>(Val: E)) {
6933 for (auto *SubInit : Init->inits())
6934 if (!buildInitializerListImpl(E: SubInit))
6935 return false;
6936 return true;
6937 }
6938
6939 // If this is a scalar type, just enqueue the expression.
6940 QualType Ty = E->getType().getDesugaredType(Context: Ctx);
6941
6942 if (Ty->isScalarType() || (Ty->isRecordType() && !Ty->isAggregateType()) ||
6943 Ty->isHLSLAttributedResourceType())
6944 return castInitializer(E);
6945
6946 // If this is an aggregate type and a prvalue, create an xvalue temporary
6947 // so the member accesses will be xvalues. Wrap it in OpaqueExpr to make
6948 // sure codegen will not generate duplicate copies.
6949 if (E->isPRValue() && Ty->isAggregateType()) {
6950 ExprResult TmpExpr = S.TemporaryMaterializationConversion(E);
6951 if (TmpExpr.isInvalid())
6952 return false;
6953 E = TmpExpr.get();
6954 E = new (Ctx) OpaqueValueExpr(E->getBeginLoc(), E->getType(),
6955 E->getValueKind(), E->getObjectKind(), E);
6956 }
6957
6958 if (auto *VecTy = Ty->getAs<VectorType>()) {
6959 uint64_t Size = VecTy->getNumElements();
6960
6961 QualType SizeTy = Ctx.getSizeType();
6962 uint64_t SizeTySize = Ctx.getTypeSize(T: SizeTy);
6963 for (uint64_t I = 0; I < Size; ++I) {
6964 auto *Idx = IntegerLiteral::Create(C: Ctx, V: llvm::APInt(SizeTySize, I),
6965 type: SizeTy, l: SourceLocation());
6966
6967 ExprResult ElExpr = S.CreateBuiltinArraySubscriptExpr(
6968 Base: E, LLoc: E->getBeginLoc(), Idx, RLoc: E->getEndLoc());
6969 if (ElExpr.isInvalid())
6970 return false;
6971 if (!castInitializer(E: ElExpr.get()))
6972 return false;
6973 }
6974 return true;
6975 }
6976 if (auto *MTy = Ty->getAs<ConstantMatrixType>()) {
6977 unsigned Rows = MTy->getNumRows();
6978 unsigned Cols = MTy->getNumColumns();
6979 QualType ElemTy = MTy->getElementType();
6980
6981 for (unsigned R = 0; R < Rows; ++R) {
6982 for (unsigned C = 0; C < Cols; ++C) {
6983 // row index literal
6984 Expr *RowIdx = IntegerLiteral::Create(
6985 C: Ctx, V: llvm::APInt(Ctx.getIntWidth(T: Ctx.IntTy), R), type: Ctx.IntTy,
6986 l: E->getBeginLoc());
6987 // column index literal
6988 Expr *ColIdx = IntegerLiteral::Create(
6989 C: Ctx, V: llvm::APInt(Ctx.getIntWidth(T: Ctx.IntTy), C), type: Ctx.IntTy,
6990 l: E->getBeginLoc());
6991 ExprResult ElExpr = S.CreateBuiltinMatrixSubscriptExpr(
6992 Base: E, RowIdx, ColumnIdx: ColIdx, RBLoc: E->getEndLoc());
6993 if (ElExpr.isInvalid())
6994 return false;
6995 if (!castInitializer(E: ElExpr.get()))
6996 return false;
6997 ElExpr.get()->setType(ElemTy);
6998 }
6999 }
7000 return true;
7001 }
7002
7003 if (auto *ArrTy = dyn_cast<ConstantArrayType>(Val: Ty.getTypePtr())) {
7004 uint64_t Size = ArrTy->getZExtSize();
7005 QualType SizeTy = Ctx.getSizeType();
7006 uint64_t SizeTySize = Ctx.getTypeSize(T: SizeTy);
7007 for (uint64_t I = 0; I < Size; ++I) {
7008 auto *Idx = IntegerLiteral::Create(C: Ctx, V: llvm::APInt(SizeTySize, I),
7009 type: SizeTy, l: SourceLocation());
7010 ExprResult ElExpr = S.CreateBuiltinArraySubscriptExpr(
7011 Base: E, LLoc: E->getBeginLoc(), Idx, RLoc: E->getEndLoc());
7012 if (ElExpr.isInvalid())
7013 return false;
7014 if (!buildInitializerListImpl(E: ElExpr.get()))
7015 return false;
7016 }
7017 return true;
7018 }
7019
7020 if (auto *RD = Ty->getAsCXXRecordDecl()) {
7021 llvm::SmallVector<CXXRecordDecl *> RecordDecls;
7022 RecordDecls.push_back(Elt: RD);
7023 while (RecordDecls.back()->getNumBases()) {
7024 CXXRecordDecl *D = RecordDecls.back();
7025 assert(D->getNumBases() == 1 &&
7026 "HLSL doesn't support multiple inheritance");
7027 RecordDecls.push_back(
7028 Elt: D->bases_begin()->getType()->castAsCXXRecordDecl());
7029 }
7030 while (!RecordDecls.empty()) {
7031 CXXRecordDecl *RD = RecordDecls.pop_back_val();
7032 for (auto *FD : RD->fields()) {
7033 if (FD->isUnnamedBitField())
7034 continue;
7035 DeclAccessPair Found = DeclAccessPair::make(D: FD, AS: FD->getAccess());
7036 DeclarationNameInfo NameInfo(FD->getDeclName(), E->getBeginLoc());
7037 ExprResult Res = S.BuildFieldReferenceExpr(
7038 BaseExpr: E, IsArrow: false, OpLoc: E->getBeginLoc(), SS: CXXScopeSpec(), Field: FD, FoundDecl: Found, MemberNameInfo: NameInfo);
7039 if (Res.isInvalid())
7040 return false;
7041 if (!buildInitializerListImpl(E: Res.get()))
7042 return false;
7043 }
7044 }
7045 }
7046 return true;
7047 }
7048
7049 Expr *generateInitListsImpl(QualType Ty) {
7050 Ty = Ty.getDesugaredType(Context: Ctx);
7051 assert(ArgIt != ArgExprs.end() && "Something is off in iteration!");
7052 if (Ty->isScalarType() || (Ty->isRecordType() && !Ty->isAggregateType()) ||
7053 Ty->isHLSLAttributedResourceType())
7054 return *(ArgIt++);
7055
7056 llvm::SmallVector<Expr *> Inits;
7057 if (Ty->isVectorType() || Ty->isConstantArrayType() ||
7058 Ty->isConstantMatrixType()) {
7059 QualType ElTy;
7060 uint64_t Size = 0;
7061 if (auto *ATy = Ty->getAs<VectorType>()) {
7062 ElTy = ATy->getElementType();
7063 Size = ATy->getNumElements();
7064 } else if (auto *CMTy = Ty->getAs<ConstantMatrixType>()) {
7065 ElTy = CMTy->getElementType();
7066 Size = CMTy->getNumElementsFlattened();
7067 } else {
7068 auto *VTy = cast<ConstantArrayType>(Val: Ty.getTypePtr());
7069 ElTy = VTy->getElementType();
7070 Size = VTy->getZExtSize();
7071 }
7072 for (uint64_t I = 0; I < Size; ++I)
7073 Inits.push_back(Elt: generateInitListsImpl(Ty: ElTy));
7074 }
7075 if (auto *RD = Ty->getAsCXXRecordDecl()) {
7076 llvm::SmallVector<CXXRecordDecl *> RecordDecls;
7077 RecordDecls.push_back(Elt: RD);
7078 while (RecordDecls.back()->getNumBases()) {
7079 CXXRecordDecl *D = RecordDecls.back();
7080 assert(D->getNumBases() == 1 &&
7081 "HLSL doesn't support multiple inheritance");
7082 RecordDecls.push_back(
7083 Elt: D->bases_begin()->getType()->castAsCXXRecordDecl());
7084 }
7085 while (!RecordDecls.empty()) {
7086 CXXRecordDecl *RD = RecordDecls.pop_back_val();
7087 for (auto *FD : RD->fields())
7088 if (!FD->isUnnamedBitField())
7089 Inits.push_back(Elt: generateInitListsImpl(Ty: FD->getType()));
7090 }
7091 }
7092 auto *NewInit =
7093 new (Ctx) InitListExpr(Ctx, Inits.front()->getBeginLoc(), Inits,
7094 Inits.back()->getEndLoc(), /*isExplicit=*/false);
7095 NewInit->setType(Ty);
7096 return NewInit;
7097 }
7098
7099public:
7100 llvm::SmallVector<QualType, 16> DestTypes;
7101 llvm::SmallVector<Expr *, 16> ArgExprs;
7102 InitListTransformer(Sema &SemaRef, const InitializedEntity &Entity)
7103 : S(SemaRef), Ctx(SemaRef.getASTContext()),
7104 Wrap(Entity.getType()->isIncompleteArrayType()) {
7105 InitTy = Entity.getType().getNonReferenceType();
7106 // When we're generating initializer lists for incomplete array types we
7107 // need to wrap around both when building the initializers and when
7108 // generating the final initializer lists.
7109 if (Wrap) {
7110 assert(InitTy->isIncompleteArrayType());
7111 const IncompleteArrayType *IAT = Ctx.getAsIncompleteArrayType(T: InitTy);
7112 InitTy = IAT->getElementType();
7113 }
7114 BuildFlattenedTypeList(BaseTy: InitTy, List&: DestTypes);
7115 DstIt = DestTypes.begin();
7116 }
7117
7118 bool buildInitializerList(Expr *E) { return buildInitializerListImpl(E); }
7119
7120 Expr *generateInitLists() {
7121 assert(!ArgExprs.empty() &&
7122 "Call buildInitializerList to generate argument expressions.");
7123 ArgIt = ArgExprs.begin();
7124 if (!Wrap)
7125 return generateInitListsImpl(Ty: InitTy);
7126 llvm::SmallVector<Expr *> Inits;
7127 while (ArgIt != ArgExprs.end())
7128 Inits.push_back(Elt: generateInitListsImpl(Ty: InitTy));
7129
7130 auto *NewInit =
7131 new (Ctx) InitListExpr(Ctx, Inits.front()->getBeginLoc(), Inits,
7132 Inits.back()->getEndLoc(), /*isExplicit=*/false);
7133 llvm::APInt ArySize(64, Inits.size());
7134 NewInit->setType(Ctx.getConstantArrayType(EltTy: InitTy, ArySize, SizeExpr: nullptr,
7135 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0));
7136 return NewInit;
7137 }
7138};
7139} // namespace
7140
7141// Recursively detect any incomplete array anywhere in the type graph,
7142// including arrays, struct fields, and base classes.
7143static bool containsIncompleteArrayType(QualType Ty) {
7144 Ty = Ty.getCanonicalType();
7145
7146 // Array types
7147 if (const ArrayType *AT = dyn_cast<ArrayType>(Val&: Ty)) {
7148 if (isa<IncompleteArrayType>(Val: AT))
7149 return true;
7150 return containsIncompleteArrayType(Ty: AT->getElementType());
7151 }
7152
7153 // Record (struct/class) types
7154 if (const auto *RT = Ty->getAs<RecordType>()) {
7155 const RecordDecl *RD = RT->getDecl();
7156
7157 // Walk base classes (for C++ / HLSL structs with inheritance)
7158 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
7159 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
7160 if (containsIncompleteArrayType(Ty: Base.getType()))
7161 return true;
7162 }
7163 }
7164
7165 // Walk fields
7166 for (const FieldDecl *F : RD->fields()) {
7167 if (containsIncompleteArrayType(Ty: F->getType()))
7168 return true;
7169 }
7170 }
7171
7172 return false;
7173}
7174
7175bool SemaHLSL::transformInitList(const InitializedEntity &Entity,
7176 InitListExpr *Init) {
7177 // If the initializer is a scalar, just return it.
7178 if (Init->getType()->isScalarType())
7179 return true;
7180 ASTContext &Ctx = SemaRef.getASTContext();
7181 InitListTransformer ILT(SemaRef, Entity);
7182
7183 for (unsigned I = 0; I < Init->getNumInits(); ++I) {
7184 Expr *E = Init->getInit(Init: I);
7185 if (E->HasSideEffects(Ctx)) {
7186 QualType Ty = E->getType();
7187 if (Ty->isRecordType())
7188 E = new (Ctx) MaterializeTemporaryExpr(Ty, E, E->isLValue());
7189 E = new (Ctx) OpaqueValueExpr(E->getBeginLoc(), Ty, E->getValueKind(),
7190 E->getObjectKind(), E);
7191 Init->setInit(Init: I, expr: E);
7192 }
7193 if (!ILT.buildInitializerList(E))
7194 return false;
7195 }
7196 size_t ExpectedSize = ILT.DestTypes.size();
7197 size_t ActualSize = ILT.ArgExprs.size();
7198 if (ExpectedSize == 0 && ActualSize == 0)
7199 return true;
7200
7201 // Reject empty initializer if *any* incomplete array exists structurally
7202 if (ActualSize == 0 && containsIncompleteArrayType(Ty: Entity.getType())) {
7203 QualType InitTy = Entity.getType().getNonReferenceType();
7204 if (InitTy.hasAddressSpace())
7205 InitTy = SemaRef.getASTContext().removeAddrSpaceQualType(T: InitTy);
7206
7207 SemaRef.Diag(Loc: Init->getBeginLoc(), DiagID: diag::err_hlsl_incorrect_num_initializers)
7208 << /*TooManyOrFew=*/(int)(ExpectedSize < ActualSize) << InitTy
7209 << /*ExpectedSize=*/ExpectedSize << /*ActualSize=*/ActualSize;
7210 return false;
7211 }
7212
7213 // We infer size after validating legality.
7214 // For incomplete arrays it is completely arbitrary to choose whether we think
7215 // the user intended fewer or more elements. This implementation assumes that
7216 // the user intended more, and errors that there are too few initializers to
7217 // complete the final element.
7218 if (Entity.getType()->isIncompleteArrayType()) {
7219 assert(ExpectedSize > 0 &&
7220 "The expected size of an incomplete array type must be at least 1.");
7221 ExpectedSize =
7222 ((ActualSize + ExpectedSize - 1) / ExpectedSize) * ExpectedSize;
7223 }
7224
7225 // An initializer list might be attempting to initialize a reference or
7226 // rvalue-reference. When checking the initializer we should look through
7227 // the reference.
7228 QualType InitTy = Entity.getType().getNonReferenceType();
7229 if (InitTy.hasAddressSpace())
7230 InitTy = SemaRef.getASTContext().removeAddrSpaceQualType(T: InitTy);
7231 if (ExpectedSize != ActualSize) {
7232 int TooManyOrFew = ActualSize > ExpectedSize ? 1 : 0;
7233 SemaRef.Diag(Loc: Init->getBeginLoc(), DiagID: diag::err_hlsl_incorrect_num_initializers)
7234 << TooManyOrFew << InitTy << ExpectedSize << ActualSize;
7235 return false;
7236 }
7237
7238 // generateInitListsImpl will always return an InitListExpr here, because the
7239 // scalar case is handled above.
7240 auto *NewInit = cast<InitListExpr>(Val: ILT.generateInitLists());
7241 Init->resizeInits(Context: Ctx, NumInits: NewInit->getNumInits());
7242 for (unsigned I = 0; I < NewInit->getNumInits(); ++I)
7243 Init->updateInit(C: Ctx, Init: I, expr: NewInit->getInit(Init: I));
7244 return true;
7245}
7246
7247static QualType ReportMatrixInvalidMember(Sema &S, StringRef Name,
7248 StringRef Expected,
7249 SourceLocation OpLoc,
7250 SourceLocation CompLoc) {
7251 S.Diag(Loc: OpLoc, DiagID: diag::err_builtin_matrix_invalid_member)
7252 << Name << Expected << SourceRange(CompLoc);
7253 return QualType();
7254}
7255
7256QualType SemaHLSL::checkMatrixComponent(Sema &S, QualType baseType,
7257 ExprValueKind &VK, SourceLocation OpLoc,
7258 const IdentifierInfo *CompName,
7259 SourceLocation CompLoc) {
7260 const auto *MT = baseType->castAs<ConstantMatrixType>();
7261 StringRef AccessorName = CompName->getName();
7262 assert(!AccessorName.empty() && "Matrix Accessor must have a name");
7263
7264 unsigned Rows = MT->getNumRows();
7265 unsigned Cols = MT->getNumColumns();
7266 bool IsZeroBasedAccessor = false;
7267 unsigned ChunkLen = 0;
7268 if (AccessorName.size() < 2)
7269 return ReportMatrixInvalidMember(S, Name: AccessorName,
7270 Expected: "length 4 for zero based: \'_mRC\' or "
7271 "length 3 for one-based: \'_RC\' accessor",
7272 OpLoc, CompLoc);
7273
7274 if (AccessorName[0] == '_') {
7275 if (AccessorName[1] == 'm') {
7276 IsZeroBasedAccessor = true;
7277 ChunkLen = 4; // zero-based: "_mRC"
7278 } else {
7279 ChunkLen = 3; // one-based: "_RC"
7280 }
7281 } else
7282 return ReportMatrixInvalidMember(
7283 S, Name: AccessorName, Expected: "zero based: \'_mRC\' or one-based: \'_RC\' accessor",
7284 OpLoc, CompLoc);
7285
7286 if (AccessorName.size() % ChunkLen != 0) {
7287 const llvm::StringRef Expected = IsZeroBasedAccessor
7288 ? "zero based: '_mRC' accessor"
7289 : "one-based: '_RC' accessor";
7290
7291 return ReportMatrixInvalidMember(S, Name: AccessorName, Expected, OpLoc, CompLoc);
7292 }
7293
7294 auto isDigit = [](char c) { return c >= '0' && c <= '9'; };
7295 auto isZeroBasedIndex = [](unsigned i) { return i <= 3; };
7296 auto isOneBasedIndex = [](unsigned i) { return i >= 1 && i <= 4; };
7297
7298 bool HasRepeated = false;
7299 SmallVector<bool, 16> Seen(Rows * Cols, false);
7300 unsigned NumComponents = 0;
7301 const char *Begin = AccessorName.data();
7302
7303 for (unsigned I = 0, E = AccessorName.size(); I < E; I += ChunkLen) {
7304 const char *Chunk = Begin + I;
7305 char RowChar = 0, ColChar = 0;
7306 if (IsZeroBasedAccessor) {
7307 // Zero-based: "_mRC"
7308 if (Chunk[0] != '_' || Chunk[1] != 'm') {
7309 char Bad = (Chunk[0] != '_') ? Chunk[0] : Chunk[1];
7310 return ReportMatrixInvalidMember(
7311 S, Name: StringRef(&Bad, 1), Expected: "\'_m\' prefix",
7312 OpLoc: OpLoc.getLocWithOffset(Offset: I + (Bad == Chunk[0] ? 1 : 2)), CompLoc);
7313 }
7314 RowChar = Chunk[2];
7315 ColChar = Chunk[3];
7316 } else {
7317 // One-based: "_RC"
7318 if (Chunk[0] != '_')
7319 return ReportMatrixInvalidMember(
7320 S, Name: StringRef(&Chunk[0], 1), Expected: "\'_\' prefix",
7321 OpLoc: OpLoc.getLocWithOffset(Offset: I + 1), CompLoc);
7322 RowChar = Chunk[1];
7323 ColChar = Chunk[2];
7324 }
7325
7326 // Must be digits.
7327 bool IsDigitsError = false;
7328 if (!isDigit(RowChar)) {
7329 unsigned BadPos = IsZeroBasedAccessor ? 2 : 1;
7330 ReportMatrixInvalidMember(S, Name: StringRef(&RowChar, 1), Expected: "row as integer",
7331 OpLoc: OpLoc.getLocWithOffset(Offset: I + BadPos + 1),
7332 CompLoc);
7333 IsDigitsError = true;
7334 }
7335
7336 if (!isDigit(ColChar)) {
7337 unsigned BadPos = IsZeroBasedAccessor ? 3 : 2;
7338 ReportMatrixInvalidMember(S, Name: StringRef(&ColChar, 1), Expected: "column as integer",
7339 OpLoc: OpLoc.getLocWithOffset(Offset: I + BadPos + 1),
7340 CompLoc);
7341 IsDigitsError = true;
7342 }
7343 if (IsDigitsError)
7344 return QualType();
7345
7346 unsigned Row = RowChar - '0';
7347 unsigned Col = ColChar - '0';
7348
7349 bool HasIndexingError = false;
7350 if (IsZeroBasedAccessor) {
7351 // 0-based [0..3]
7352 if (!isZeroBasedIndex(Row)) {
7353 S.Diag(Loc: OpLoc, DiagID: diag::err_hlsl_matrix_element_not_in_bounds)
7354 << /*row*/ 0 << /*zero-based*/ 0 << SourceRange(CompLoc);
7355 HasIndexingError = true;
7356 }
7357 if (!isZeroBasedIndex(Col)) {
7358 S.Diag(Loc: OpLoc, DiagID: diag::err_hlsl_matrix_element_not_in_bounds)
7359 << /*col*/ 1 << /*zero-based*/ 0 << SourceRange(CompLoc);
7360 HasIndexingError = true;
7361 }
7362 } else {
7363 // 1-based [1..4]
7364 if (!isOneBasedIndex(Row)) {
7365 S.Diag(Loc: OpLoc, DiagID: diag::err_hlsl_matrix_element_not_in_bounds)
7366 << /*row*/ 0 << /*one-based*/ 1 << SourceRange(CompLoc);
7367 HasIndexingError = true;
7368 }
7369 if (!isOneBasedIndex(Col)) {
7370 S.Diag(Loc: OpLoc, DiagID: diag::err_hlsl_matrix_element_not_in_bounds)
7371 << /*col*/ 1 << /*one-based*/ 1 << SourceRange(CompLoc);
7372 HasIndexingError = true;
7373 }
7374 // Convert to 0-based after range checking.
7375 --Row;
7376 --Col;
7377 }
7378
7379 if (HasIndexingError)
7380 return QualType();
7381
7382 // Note: matrix swizzle index is hard coded. That means Row and Col can
7383 // potentially be larger than Rows and Cols if matrix size is less than
7384 // the max index size.
7385 bool HasBoundsError = false;
7386 if (Row >= Rows) {
7387 Diag(Loc: OpLoc, DiagID: diag::err_hlsl_matrix_index_out_of_bounds)
7388 << /*Row*/ 0 << Row << Rows << SourceRange(CompLoc);
7389 HasBoundsError = true;
7390 }
7391 if (Col >= Cols) {
7392 Diag(Loc: OpLoc, DiagID: diag::err_hlsl_matrix_index_out_of_bounds)
7393 << /*Col*/ 1 << Col << Cols << SourceRange(CompLoc);
7394 HasBoundsError = true;
7395 }
7396 if (HasBoundsError)
7397 return QualType();
7398
7399 unsigned FlatIndex = Row * Cols + Col;
7400 if (Seen[FlatIndex])
7401 HasRepeated = true;
7402 Seen[FlatIndex] = true;
7403 ++NumComponents;
7404 }
7405 if (NumComponents == 0 || NumComponents > 4) {
7406 S.Diag(Loc: OpLoc, DiagID: diag::err_hlsl_matrix_swizzle_invalid_length)
7407 << NumComponents << SourceRange(CompLoc);
7408 return QualType();
7409 }
7410
7411 QualType ElemTy = MT->getElementType();
7412 if (NumComponents == 1)
7413 return ElemTy;
7414 QualType VT = S.Context.getExtVectorType(VectorType: ElemTy, NumElts: NumComponents);
7415 if (HasRepeated)
7416 VK = VK_PRValue;
7417
7418 for (Sema::ExtVectorDeclsType::iterator
7419 I = S.ExtVectorDecls.begin(source: S.getExternalSource()),
7420 E = S.ExtVectorDecls.end();
7421 I != E; ++I) {
7422 if ((*I)->getUnderlyingType() == VT)
7423 return S.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
7424 /*Qualifier=*/std::nullopt, Decl: *I);
7425 }
7426
7427 return VT;
7428}
7429
7430bool SemaHLSL::handleInitialization(VarDecl *VDecl, Expr *&Init) {
7431 // If initializing a local resource, track the resource binding it is using
7432 if (VDecl->getType()->isHLSLResourceRecord() && !VDecl->hasGlobalStorage())
7433 trackLocalResource(VD: VDecl, E: Init);
7434
7435 const HLSLVkConstantIdAttr *ConstIdAttr =
7436 VDecl->getAttr<HLSLVkConstantIdAttr>();
7437 if (!ConstIdAttr)
7438 return true;
7439
7440 ASTContext &Context = SemaRef.getASTContext();
7441
7442 APValue InitValue;
7443 if (!Init->isCXX11ConstantExpr(Ctx: Context, Result&: InitValue)) {
7444 Diag(Loc: VDecl->getLocation(), DiagID: diag::err_specialization_const);
7445 VDecl->setInvalidDecl();
7446 return false;
7447 }
7448
7449 Builtin::ID BID =
7450 getSpecConstBuiltinId(Type: VDecl->getType()->getUnqualifiedDesugaredType());
7451
7452 // Argument 1: The ID from the attribute
7453 int ConstantID = ConstIdAttr->getId();
7454 llvm::APInt IDVal(Context.getIntWidth(T: Context.IntTy), ConstantID);
7455 Expr *IdExpr = IntegerLiteral::Create(C: Context, V: IDVal, type: Context.IntTy,
7456 l: ConstIdAttr->getLocation());
7457
7458 SmallVector<Expr *, 2> Args = {IdExpr, Init};
7459 Expr *C = SemaRef.BuildBuiltinCallExpr(Loc: Init->getExprLoc(), Id: BID, CallArgs: Args);
7460 if (C->getType()->getCanonicalTypeUnqualified() !=
7461 VDecl->getType()->getCanonicalTypeUnqualified()) {
7462 C = SemaRef
7463 .BuildCStyleCastExpr(LParenLoc: SourceLocation(),
7464 Ty: Context.getTrivialTypeSourceInfo(
7465 T: Init->getType(), Loc: Init->getExprLoc()),
7466 RParenLoc: SourceLocation(), Op: C)
7467 .get();
7468 }
7469 Init = C;
7470 return true;
7471}
7472
7473QualType SemaHLSL::ActOnTemplateShorthand(TemplateDecl *Template,
7474 SourceLocation NameLoc) {
7475 if (!Template)
7476 return QualType();
7477
7478 DeclContext *DC = Template->getDeclContext();
7479 if (!DC->isNamespace() || !cast<NamespaceDecl>(Val: DC)->getIdentifier() ||
7480 cast<NamespaceDecl>(Val: DC)->getName() != "hlsl")
7481 return QualType();
7482
7483 TemplateParameterList *Params = Template->getTemplateParameters();
7484 if (!Params || Params->size() != 1)
7485 return QualType();
7486
7487 if (!Template->isImplicit())
7488 return QualType();
7489
7490 // We manually extract default arguments here instead of letting
7491 // CheckTemplateIdType handle it. This ensures that for resource types that
7492 // lack a default argument (like Buffer), we return a null QualType, which
7493 // triggers the "requires template arguments" error rather than a less
7494 // descriptive "too few template arguments" error.
7495 TemplateArgumentListInfo TemplateArgs(NameLoc, NameLoc);
7496 for (NamedDecl *P : *Params) {
7497 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: P)) {
7498 if (TTP->hasDefaultArgument()) {
7499 TemplateArgs.addArgument(Loc: TTP->getDefaultArgument());
7500 continue;
7501 }
7502 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P)) {
7503 if (NTTP->hasDefaultArgument()) {
7504 TemplateArgs.addArgument(Loc: NTTP->getDefaultArgument());
7505 continue;
7506 }
7507 } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Val: P)) {
7508 if (TTPD->hasDefaultArgument()) {
7509 TemplateArgs.addArgument(Loc: TTPD->getDefaultArgument());
7510 continue;
7511 }
7512 }
7513 return QualType();
7514 }
7515
7516 return SemaRef.CheckTemplateIdType(
7517 Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(Template), TemplateLoc: NameLoc,
7518 TemplateArgs, Scope: nullptr, /*ForNestedNameSpecifier=*/false);
7519}
7520