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