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