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