38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/SmallVector.h"
41#include "llvm/ADT/StringExtras.h"
42#include "llvm/ADT/StringRef.h"
43#include "llvm/ADT/Twine.h"
44#include "llvm/Frontend/HLSL/HLSLBinding.h"
45#include "llvm/Frontend/HLSL/RootSignatureValidations.h"
46#include "llvm/Support/Casting.h"
47#include "llvm/Support/DXILABI.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/FormatVariadic.h"
50#include "llvm/Support/raw_ostream.h"
51#include "llvm/TargetParser/Triple.h"
60using llvm::hlsl::InterpolationModifier;
61using llvm::hlsl::IOType;
62using llvm::hlsl::SemanticStageInfo;
71 return VT->getElementType();
73 return MT->getElementType();
79 case ResourceClass::SRV:
80 return RegisterType::SRV;
81 case ResourceClass::UAV:
82 return RegisterType::UAV;
83 case ResourceClass::CBuffer:
84 return RegisterType::CBuffer;
85 case ResourceClass::Sampler:
86 return RegisterType::Sampler;
88 llvm_unreachable(
"unexpected ResourceClass value");
97 case ResourceClass::SRV:
98 case ResourceClass::UAV:
100 case ResourceClass::CBuffer:
102 case ResourceClass::Sampler:
105 llvm_unreachable(
"unexpected ResourceClass value");
111 assert(RT !=
nullptr);
115 *RT = RegisterType::SRV;
119 *RT = RegisterType::UAV;
123 *RT = RegisterType::CBuffer;
127 *RT = RegisterType::Sampler;
131 *RT = RegisterType::C;
135 *RT = RegisterType::I;
144 case RegisterType::SRV:
146 case RegisterType::UAV:
148 case RegisterType::CBuffer:
150 case RegisterType::Sampler:
152 case RegisterType::C:
154 case RegisterType::I:
157 llvm_unreachable(
"unexpected RegisterType value");
162 case RegisterType::SRV:
163 return ResourceClass::SRV;
164 case RegisterType::UAV:
165 return ResourceClass::UAV;
166 case RegisterType::CBuffer:
167 return ResourceClass::CBuffer;
168 case RegisterType::Sampler:
169 return ResourceClass::Sampler;
170 case RegisterType::C:
171 case RegisterType::I:
175 llvm_unreachable(
"unexpected RegisterType value");
179 const auto *BT = dyn_cast<BuiltinType>(
Type);
183 return Builtin::BI__builtin_get_spirv_spec_constant_int;
186 switch (BT->getKind()) {
187 case BuiltinType::Bool:
188 return Builtin::BI__builtin_get_spirv_spec_constant_bool;
189 case BuiltinType::Short:
190 return Builtin::BI__builtin_get_spirv_spec_constant_short;
191 case BuiltinType::Int:
192 return Builtin::BI__builtin_get_spirv_spec_constant_int;
193 case BuiltinType::LongLong:
194 return Builtin::BI__builtin_get_spirv_spec_constant_longlong;
195 case BuiltinType::UShort:
196 return Builtin::BI__builtin_get_spirv_spec_constant_ushort;
197 case BuiltinType::UInt:
198 return Builtin::BI__builtin_get_spirv_spec_constant_uint;
199 case BuiltinType::ULongLong:
200 return Builtin::BI__builtin_get_spirv_spec_constant_ulonglong;
201 case BuiltinType::Half:
202 return Builtin::BI__builtin_get_spirv_spec_constant_half;
203 case BuiltinType::Float:
204 return Builtin::BI__builtin_get_spirv_spec_constant_float;
205 case BuiltinType::Double:
206 return Builtin::BI__builtin_get_spirv_spec_constant_double;
215 llvm::raw_svector_ostream OS(Buffer);
222 ResourceClass ResClass) {
224 "DeclBindingInfo already added");
230 DeclToBindingListIndex.try_emplace(VD, BindingsList.size());
231 return &BindingsList.emplace_back(VD, ResClass);
235 ResourceClass ResClass) {
236 auto Entry = DeclToBindingListIndex.find(VD);
237 if (Entry != DeclToBindingListIndex.end()) {
238 for (
unsigned Index = Entry->getSecond();
239 Index < BindingsList.size() && BindingsList[Index].Decl == VD;
241 if (BindingsList[Index].ResClass == ResClass)
242 return &BindingsList[Index];
249 return DeclToBindingListIndex.contains(VD);
261 getASTContext(), LexicalParent, CBuffer, KwLoc, Ident, IdentLoc, LBrace);
264 auto RC = CBuffer ? llvm::hlsl::ResourceClass::CBuffer
265 : llvm::hlsl::ResourceClass::SRV;
277 if (
T->isArrayType() ||
T->isStructureType() ||
T->isConstantMatrixType())
284 assert(Context.getTypeSize(
T) <= 64 &&
285 "Scalar bit widths larger than 64 not supported");
288 return Context.getTypeSize(
T) / 8;
295 constexpr unsigned CBufferAlign = 16;
296 if (
const auto *RD =
T->getAsRecordDecl()) {
298 for (
const FieldDecl *Field : RD->fields()) {
305 unsigned AlignSize = llvm::alignTo(Size, FieldAlign);
306 if ((AlignSize % CBufferAlign) + FieldSize > CBufferAlign) {
307 FieldAlign = CBufferAlign;
310 Size = llvm::alignTo(Size, FieldAlign);
317 unsigned ElementCount = AT->getSize().getZExtValue();
318 if (ElementCount == 0)
321 unsigned ElementSize =
323 unsigned AlignedElementSize = llvm::alignTo(ElementSize, CBufferAlign);
324 return AlignedElementSize * (ElementCount - 1) + ElementSize;
328 unsigned ElementCount = VT->getNumElements();
329 unsigned ElementSize =
331 return ElementSize * ElementCount;
334 return Context.getTypeSize(
T) / 8;
345 bool HasPackOffset =
false;
346 bool HasNonPackOffset =
false;
348 VarDecl *Var = dyn_cast<VarDecl>(Field);
351 if (Field->hasAttr<HLSLPackOffsetAttr>()) {
352 PackOffsetVec.emplace_back(Var, Field->
getAttr<HLSLPackOffsetAttr>());
353 HasPackOffset =
true;
355 HasNonPackOffset =
true;
362 if (HasNonPackOffset)
369 std::sort(PackOffsetVec.begin(), PackOffsetVec.end(),
370 [](
const std::pair<VarDecl *, HLSLPackOffsetAttr *> &LHS,
371 const std::pair<VarDecl *, HLSLPackOffsetAttr *> &RHS) {
372 return LHS.second->getOffsetInBytes() <
373 RHS.second->getOffsetInBytes();
375 for (
unsigned i = 0; i < PackOffsetVec.size() - 1; i++) {
376 VarDecl *Var = PackOffsetVec[i].first;
377 HLSLPackOffsetAttr *
Attr = PackOffsetVec[i].second;
379 unsigned Begin =
Attr->getOffsetInBytes();
380 unsigned End = Begin + Size;
381 unsigned NextBegin = PackOffsetVec[i + 1].second->getOffsetInBytes();
382 if (End > NextBegin) {
383 VarDecl *NextVar = PackOffsetVec[i + 1].first;
395 CAT = dyn_cast<ConstantArrayType>(
397 return CAT !=
nullptr;
408static const HLSLAttributedResourceType *
411 "expected array of resource records");
413 while (
const ArrayType *AT = dyn_cast<ArrayType>(Ty))
415 return HLSLAttributedResourceType::findHandleTypeOnResource(Ty);
418static const HLSLAttributedResourceType *
432 return RD->isEmpty();
461 Base.getType()->castAsCXXRecordDecl()))
472 assert(RD ==
nullptr &&
473 "there should be at most 1 record by a given name in a scope");
490 Name.append(NameBaseII->
getName());
497 size_t NameLength = Name.size();
506 Name.append(llvm::Twine(suffix).str());
507 II = &AST.
Idents.
get(Name, tok::TokenKind::identifier);
514 Name.truncate(NameLength);
529 if (
const auto *CAT = dyn_cast<ConstantArrayType>(Ty)) {
531 S, CAT->getElementType()->getUnqualifiedDesugaredType());
536 CAT->getSizeModifier(),
537 CAT->getIndexTypeCVRQualifiers())
586 "struct is already HLSL buffer compatible");
600 LS->
addAttr(PackedAttr::CreateImplicit(AST));
604 if (
unsigned NumBases = StructDecl->
getNumBases()) {
605 assert(NumBases == 1 &&
"HLSL supports only one base type");
655 LS->
addAttr(PackedAttr::CreateImplicit(AST));
660 VarDecl *VD = dyn_cast<VarDecl>(D);
676 "host layout field for $Globals decl failed to be created");
695 HLSLResourceBindingAttr::CreateImplicit(S.
getASTContext(),
"",
"0", {});
696 Attr->setBinding(RT, std::nullopt, 0);
697 Attr->setImplicitBindingOrderID(ImplicitBindingOrderID);
704 BufDecl->setRBraceLoc(RBrace);
721 BufDecl->isCBuffer() ? RegisterType::CBuffer
731 int X,
int Y,
int Z) {
732 if (HLSLNumThreadsAttr *NT = D->
getAttr<HLSLNumThreadsAttr>()) {
733 if (NT->getX() !=
X || NT->getY() != Y || NT->getZ() != Z) {
734 Diag(NT->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
735 Diag(AL.
getLoc(), diag::note_conflicting_attribute);
745 int Min,
int Max,
int Preferred,
746 int SpelledArgsCount) {
747 if (HLSLWaveSizeAttr *WS = D->
getAttr<HLSLWaveSizeAttr>()) {
748 if (WS->getMin() !=
Min || WS->getMax() !=
Max ||
749 WS->getPreferred() != Preferred ||
750 WS->getSpelledArgsCount() != SpelledArgsCount) {
751 Diag(WS->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
752 Diag(AL.
getLoc(), diag::note_conflicting_attribute);
758 Result->setSpelledArgsCount(SpelledArgsCount);
762HLSLVkConstantIdAttr *
768 Diag(AL.
getLoc(), diag::warn_attribute_ignored) << AL;
776 Diag(VD->getLocation(), diag::err_specialization_const);
780 if (!VD->getType().isConstQualified()) {
781 Diag(VD->getLocation(), diag::err_specialization_const);
785 if (HLSLVkConstantIdAttr *CI = D->
getAttr<HLSLVkConstantIdAttr>()) {
786 if (CI->getId() != Id) {
787 Diag(CI->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
788 Diag(AL.
getLoc(), diag::note_conflicting_attribute);
793 HLSLVkConstantIdAttr *
Result =
800 llvm::Triple::EnvironmentType ShaderType) {
801 if (HLSLShaderAttr *NT = D->
getAttr<HLSLShaderAttr>()) {
802 if (NT->getType() != ShaderType) {
803 Diag(NT->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
804 Diag(AL.
getLoc(), diag::note_conflicting_attribute);
808 return HLSLShaderAttr::Create(
getASTContext(), ShaderType, AL);
811HLSLParamModifierAttr *
813 HLSLParamModifierAttr::Spelling Spelling) {
816 if (HLSLParamModifierAttr *PA = D->
getAttr<HLSLParamModifierAttr>()) {
817 if ((PA->isIn() && Spelling == HLSLParamModifierAttr::Keyword_out) ||
818 (PA->isOut() && Spelling == HLSLParamModifierAttr::Keyword_in)) {
819 D->
dropAttr<HLSLParamModifierAttr>();
821 return HLSLParamModifierAttr::Create(
823 HLSLParamModifierAttr::Keyword_inout);
825 Diag(AL.
getLoc(), diag::err_hlsl_duplicate_parameter_modifier) << AL;
826 Diag(PA->getLocation(), diag::note_conflicting_attribute);
833 InterpolationModifier Modifier;
834 switch (
static_cast<HLSLInterpolationModifierAttr::Spelling
>(
836 case HLSLInterpolationModifierAttr::Keyword_nointerpolation:
837 Modifier = InterpolationModifier::NoInterpolation;
839 case HLSLInterpolationModifierAttr::Keyword_linear:
840 Modifier = InterpolationModifier::Linear;
842 case HLSLInterpolationModifierAttr::Keyword_centroid:
843 Modifier = InterpolationModifier::Centroid;
845 case HLSLInterpolationModifierAttr::Keyword_noperspective:
846 Modifier = InterpolationModifier::NoPerspective;
848 case HLSLInterpolationModifierAttr::Keyword_sample:
849 Modifier = InterpolationModifier::Sample;
851 case HLSLInterpolationModifierAttr::Keyword_center:
852 Modifier = InterpolationModifier::Center;
854 case HLSLInterpolationModifierAttr::SpellingNotCalculated:
855 llvm_unreachable(
"interpolation modifier spelling was not calculated");
858 InterpolationModifier Modifiers = Modifier;
860 auto Old =
static_cast<InterpolationModifier
>(
Previous->getModifiers());
862 if (
any(Old & Modifier)) {
863 Diag(AL.
getLoc(), diag::warn_hlsl_duplicate_interpolation) << AL;
864 }
else if (llvm::hlsl::getInterpolationMode(Modifiers) ==
865 llvm::dxbc::PSV::InterpolationMode::Invalid &&
866 llvm::hlsl::getInterpolationMode(Old) !=
867 llvm::dxbc::PSV::InterpolationMode::Invalid) {
868 Diag(AL.
getLoc(), diag::err_hlsl_interpolation_conflict);
869 Diag(
Previous->getLocation(), diag::note_conflicting_attribute);
872 InterpolationModifier OldLocation =
873 llvm::hlsl::getInterpolationSamplingLocation(Old);
874 InterpolationModifier NewLocation =
875 llvm::hlsl::getInterpolationSamplingLocation(Modifier);
876 if (
any(OldLocation) &&
any(NewLocation)) {
877 Diag(AL.
getLoc(), diag::warn_hlsl_interpolation_override)
878 << (std::max(OldLocation, NewLocation) ==
879 InterpolationModifier::Sample)
880 << (std::min(OldLocation, NewLocation) ==
881 InterpolationModifier::Centroid);
884 D->
dropAttr<HLSLInterpolationModifierAttr>();
886 D->
addAttr(HLSLInterpolationModifierAttr::Create(
890bool SemaHLSL::checkInterpolationModifiers(
891 const DeclaratorDecl *D,
const HLSLInterpolationModifierAttr *Inherited,
892 const HLSLParsedSemanticAttr *Semantic) {
895 const auto *A = D->
getAttr<HLSLInterpolationModifierAttr>();
899 Semantic = D->
getAttr<HLSLParsedSemanticAttr>();
901 const auto *FD = dyn_cast<FunctionDecl>(D);
904 if (
T->isDependentType())
906 if (
const auto *RT =
T->getAs<RecordType>()) {
912 Valid &= checkInterpolationModifiers(Field, A, Semantic);
918 auto Modifiers =
static_cast<InterpolationModifier
>(A->getModifiers());
919 if (Modifiers == InterpolationModifier::NoInterpolation) {
923 llvm::hlsl::getSemanticKind(Semantic->getSemanticName());
924 if (Kind != SemanticKind::Position && Kind != SemanticKind::Barycentrics)
926 Diag(A->getLocation(), diag::err_hlsl_interpolation_semantic)
927 << Semantic->getSemanticName();
928 Diag(Semantic->getLocation(), diag::note_conflicting_attribute);
935 Diag(A->getLocation(), diag::err_hlsl_interpolation_type) <<
T;
961 if (HLSLShaderAttr::isValidShaderType(Env) && Env != llvm::Triple::Library) {
962 if (
const auto *Shader = FD->
getAttr<HLSLShaderAttr>()) {
965 if (Shader->getType() != Env) {
966 Diag(Shader->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch)
978 case llvm::Triple::UnknownEnvironment:
979 case llvm::Triple::Library:
981 case llvm::Triple::RootSignature:
982 llvm_unreachable(
"rootsig environment has no functions");
984 llvm_unreachable(
"Unhandled environment in triple");
991 HLSLAppliedSemanticAttr *Semantic,
994 if (D->
hasAttr<HLSLVkBuiltInAttr>())
1000 const auto *ShaderAttr = FD->
getAttr<HLSLShaderAttr>();
1001 assert(ShaderAttr &&
"Entry point has no shader attribute");
1002 llvm::Triple::EnvironmentType ST = ShaderAttr->getType();
1003 SemanticKind Kind = llvm::hlsl::getSemanticKind(Semantic->getSemanticName());
1006 case SemanticKind::Position:
1010 return (ST == llvm::Triple::Vertex && !IsInput) ||
1011 (ST == llvm::Triple::Pixel && IsInput);
1012 case SemanticKind::VertexID:
1014 case SemanticKind::InstanceID:
1015 return ST == llvm::Triple::Vertex && IsInput;
1016 case SemanticKind::IsFrontFace:
1017 return ST == llvm::Triple::Pixel && IsInput;
1018 case SemanticKind::ShadingRate:
1023 return (ST == llvm::Triple::Pixel && IsInput) ||
1024 (ST == llvm::Triple::Vertex && !IsInput);
1025 case SemanticKind::Barycentrics:
1026 case SemanticKind::SampleIndex:
1027 case SemanticKind::PrimitiveID:
1028 return ST == llvm::Triple::Pixel && IsInput;
1029 case SemanticKind::StartVertexLocation:
1030 case SemanticKind::StartInstanceLocation:
1031 return ST == llvm::Triple::Vertex && IsInput;
1032 case SemanticKind::ViewID:
1041 const HLSLVkBuiltInAttr *
Attr,
1042 IOType CurrentIOType) {
1047 StringRef BuiltIn =
Attr->getBuiltIn();
1051 const auto *ShaderAttr = FD->
getAttr<HLSLShaderAttr>();
1052 assert(ShaderAttr &&
"Entry point has no shader attribute");
1053 llvm::Triple::EnvironmentType Stage = ShaderAttr->getType();
1054 bool IsIn =
any(CurrentIOType & IOType::In);
1055 bool IsOut =
any(CurrentIOType & IOType::Out);
1057 if (BuiltIn ==
"PointSize") {
1061 bool Is32BitFloat =
T->isSpecificBuiltinType(BuiltinType::Float) ||
1062 (
T->isSpecificBuiltinType(BuiltinType::Half) &&
1071 bool IsPatchConstantOrPrimitive =
1072 any(CurrentIOType & IOType::PatchConstantOrPrimitive);
1074 !IsPatchConstantOrPrimitive &&
1075 ((Stage == llvm::Triple::Vertex && IsOut) ||
1076 Stage == llvm::Triple::Hull || Stage == llvm::Triple::Domain ||
1077 Stage == llvm::Triple::Geometry ||
1078 (Stage == llvm::Triple::Mesh && IsOut));
1080 StringRef IOTypeName = (IsIn && IsOut) ?
"inputs and outputs"
1084 << BuiltIn << llvm::Triple::getEnvironmentTypeName(Stage)
1090bool SemaHLSL::determineActiveSemanticOnScalar(
FunctionDecl *FD,
1093 SemanticInfo &ActiveSemantic,
1094 SemaHLSL::SemanticContext &SC) {
1095 if (ActiveSemantic.Semantic ==
nullptr) {
1096 ActiveSemantic.Semantic = D->
getAttr<HLSLParsedSemanticAttr>();
1097 if (ActiveSemantic.Semantic)
1098 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1101 if (!ActiveSemantic.Semantic) {
1107 HLSLAppliedSemanticAttr(
getASTContext(), *ActiveSemantic.Semantic,
1108 ActiveSemantic.Semantic->getAttrName()->getName(),
1109 ActiveSemantic.Index.value_or(0));
1114 QualType
T = D == FD ? FD->getReturnType() : D->
getType();
1115 const ConstantArrayType *AT =
1118 Diag(A->getLoc(), diag::err_hlsl_semantic_zero_sized_array)
1119 << A->getAttrName();
1127 if (
const auto *MT = BaseTy->
getAs<ConstantMatrixType>())
1130 : MT->getNumColumns();
1132 checkSemanticAnnotation(FD, D, A, SC, ElementCount);
1135 unsigned Location = ActiveSemantic.Index.value_or(0);
1138 any(SC.CurrentIOType & IOType::In));
1140 if (
const auto *BuiltInAttr = D->
getAttr<HLSLVkBuiltInAttr>())
1145 bool HasVkLocation =
false;
1146 if (
auto *A = D->
getAttr<HLSLVkLocationAttr>()) {
1147 HasVkLocation =
true;
1148 Location = A->getLocation();
1151 if (SC.UsesExplicitVkLocations.value_or(HasVkLocation) != HasVkLocation) {
1152 Diag(D->
getLocation(), diag::err_hlsl_semantic_partial_explicit_indexing);
1155 SC.UsesExplicitVkLocations = HasVkLocation;
1158 ActiveSemantic.Index = Location + ElementCount;
1160 StringRef BaseName = ActiveSemantic.Semantic->getAttrName()->getName();
1161 std::string LowerName = BaseName.lower();
1162 for (
unsigned I = 0; I < ElementCount; ++I) {
1163 auto [It, Inserted] = SC.ActiveSemantics.try_emplace(
1164 (Twine(LowerName) + Twine(Location + I)).str(), D->
getLocation());
1167 << (BaseName + Twine(Location + I)).str();
1168 Diag(It->second, diag::note_previous_use);
1176bool SemaHLSL::determineActiveSemantic(
FunctionDecl *FD,
1179 SemanticInfo &ActiveSemantic,
1180 SemaHLSL::SemanticContext &SC) {
1181 if (ActiveSemantic.Semantic ==
nullptr) {
1182 ActiveSemantic.Semantic = D->
getAttr<HLSLParsedSemanticAttr>();
1183 if (ActiveSemantic.Semantic)
1184 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1190 const RecordType *RT = dyn_cast<RecordType>(
T);
1192 return determineActiveSemanticOnScalar(FD, OutputDecl, D, ActiveSemantic,
1195 const RecordDecl *RD = RT->getDecl();
1196 for (FieldDecl *Field : RD->
fields()) {
1197 SemanticInfo Info = ActiveSemantic;
1198 if (!determineActiveSemantic(FD, OutputDecl, Field, Info, SC)) {
1199 Diag(
Field->getLocation(), diag::note_hlsl_semantic_used_here) <<
Field;
1202 if (ActiveSemantic.Semantic)
1203 ActiveSemantic = Info;
1210 const auto *ShaderAttr = FD->
getAttr<HLSLShaderAttr>();
1211 assert(ShaderAttr &&
"Entry point has no shader attribute");
1212 llvm::Triple::EnvironmentType ST = ShaderAttr->getType();
1216 case llvm::Triple::Pixel:
1217 case llvm::Triple::Vertex:
1218 case llvm::Triple::Geometry:
1219 case llvm::Triple::Hull:
1220 case llvm::Triple::Domain:
1221 case llvm::Triple::RayGeneration:
1222 case llvm::Triple::Intersection:
1223 case llvm::Triple::AnyHit:
1224 case llvm::Triple::ClosestHit:
1225 case llvm::Triple::Miss:
1226 case llvm::Triple::Callable:
1227 if (
const auto *NT = FD->
getAttr<HLSLNumThreadsAttr>()) {
1228 diagnoseAttrStageMismatch(NT, ST,
1229 {llvm::Triple::Compute,
1230 llvm::Triple::Amplification,
1231 llvm::Triple::Mesh});
1234 if (
const auto *WS = FD->
getAttr<HLSLWaveSizeAttr>()) {
1235 diagnoseAttrStageMismatch(WS, ST,
1236 {llvm::Triple::Compute,
1237 llvm::Triple::Amplification,
1238 llvm::Triple::Mesh});
1243 case llvm::Triple::Compute:
1244 case llvm::Triple::Amplification:
1245 case llvm::Triple::Mesh:
1246 if (!FD->
hasAttr<HLSLNumThreadsAttr>()) {
1248 << llvm::Triple::getEnvironmentTypeName(ST);
1251 if (
const auto *WS = FD->
getAttr<HLSLWaveSizeAttr>()) {
1253 Diag(WS->getLocation(), diag::warn_hlsl_wavesize_unsupported_spirv);
1254 }
else if (Ver < VersionTuple(6, 6)) {
1255 Diag(WS->getLocation(), diag::err_hlsl_attribute_in_wrong_shader_model)
1258 }
else if (WS->getSpelledArgsCount() > 1 && Ver < VersionTuple(6, 8)) {
1261 diag::err_hlsl_attribute_number_arguments_insufficient_shader_model)
1262 << WS << WS->getSpelledArgsCount() <<
"6.8";
1267 case llvm::Triple::RootSignature:
1268 llvm_unreachable(
"rootsig environment has no function entry point");
1270 llvm_unreachable(
"Unhandled environment in triple");
1273 SemaHLSL::SemanticContext InputSC = {};
1274 InputSC.CurrentIOType = IOType::In;
1275 SemaHLSL::SemanticContext OutputSC = {};
1276 OutputSC.CurrentIOType = IOType::Out;
1279 SemanticInfo ActiveSemantic;
1280 ActiveSemantic.Semantic = Param->getAttr<HLSLParsedSemanticAttr>();
1281 if (ActiveSemantic.Semantic)
1282 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1286 const auto *MA = Param->getAttr<HLSLParamModifierAttr>();
1287 SemanticContext &SC = MA && MA->isAnyOut() ? OutputSC : InputSC;
1291 if (((ST == llvm::Triple::Pixel && (!MA || MA->isAnyIn())) ||
1292 (ST == llvm::Triple::Vertex && MA && MA->isAnyOut())) &&
1293 !checkInterpolationModifiers(Param,
nullptr,
nullptr))
1296 if (!determineActiveSemantic(FD, Param, Param, ActiveSemantic, SC)) {
1297 Diag(Param->getLocation(), diag::note_previous_decl) << Param;
1302 SemanticInfo ActiveSemantic;
1303 ActiveSemantic.Semantic = FD->
getAttr<HLSLParsedSemanticAttr>();
1304 if (ActiveSemantic.Semantic)
1305 ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex();
1307 if (ST == llvm::Triple::Vertex &&
1308 !checkInterpolationModifiers(FD,
nullptr,
nullptr))
1310 determineActiveSemantic(FD, FD, FD, ActiveSemantic, OutputSC);
1314void SemaHLSL::checkSemanticAnnotation(
1316 const HLSLAppliedSemanticAttr *SemanticAttr,
const SemanticContext &SC,
1317 unsigned ElementCount) {
1318 auto *ShaderAttr = EntryPoint->
getAttr<HLSLShaderAttr>();
1319 assert(ShaderAttr &&
"Entry point has no shader attribute");
1320 llvm::Triple::EnvironmentType ST = ShaderAttr->getType();
1323 llvm::hlsl::getSemanticKind(SemanticAttr->getSemanticName());
1324 llvm::hlsl::SemanticInterpretation Interpretation =
1325 llvm::hlsl::getInterpretationKind(Kind, ST, SC.CurrentIOType);
1326 if (Interpretation == llvm::hlsl::SemanticInterpretation::Invalid) {
1327 diagnoseSemanticStageMismatch(SemanticAttr, ST, SC.CurrentIOType, Kind);
1333 if (Interpretation == llvm::hlsl::SemanticInterpretation::Arbitrary) {
1334 diagnoseSemanticType(Param, SemanticAttr, SemanticKind::Arbitrary);
1338 diagnoseSystemSemanticIndex(SemanticAttr, Kind, ElementCount);
1339 diagnoseSemanticType(Param, SemanticAttr, Kind);
1340 diagnoseSemanticShaderModel(SemanticAttr, Kind);
1343void SemaHLSL::diagnoseSemanticShaderModel(
const HLSLAppliedSemanticAttr *A,
1346 if (!Triple.isDXIL())
1350 case SemanticKind::Barycentrics:
1351 case SemanticKind::ViewID:
1352 if (Triple.getOSVersion() < VersionTuple(6, 1))
1353 Diag(A->getLoc(), diag::err_hlsl_semantic_in_wrong_shader_model)
1354 << A->getAttrName() <<
"6.1";
1356 case SemanticKind::ShadingRate:
1357 if (Triple.getOSVersion() < VersionTuple(6, 4))
1358 Diag(A->getLoc(), diag::err_hlsl_semantic_in_wrong_shader_model)
1359 << A->getAttrName() <<
"6.4";
1361 case SemanticKind::StartVertexLocation:
1362 case SemanticKind::StartInstanceLocation:
1363 if (Triple.getOSVersion() < VersionTuple(6, 8))
1364 Diag(A->getLoc(), diag::err_hlsl_semantic_in_wrong_shader_model)
1365 << A->getAttrName() <<
"6.8";
1372void SemaHLSL::diagnoseSystemSemanticIndex(
const HLSLAppliedSemanticAttr *A,
1374 unsigned ElementCount) {
1375 assert(Kind != SemanticKind::Invalid && Kind != SemanticKind::Arbitrary &&
1376 "expected a recognized system semantic");
1377 assert(ElementCount > 0 &&
"a semantic covers at least one element");
1380 uint32_t FirstIndex = A->getSemanticIndex();
1382 constexpr uint32_t MaxSemanticIndex = std::numeric_limits<uint32_t>::max();
1383 if (LastIndex > MaxSemanticIndex) {
1384 Diag(A->getLoc(), diag::err_hlsl_semantic_index_out_of_range)
1385 << A->getAttrName() << LastIndex << MaxSemanticIndex;
1393 case SemanticKind::ClipDistance:
1394 case SemanticKind::CullDistance:
1396 case SemanticKind::Target: {
1397 constexpr unsigned MaxTargetIndex = 7;
1398 if (LastIndex > MaxTargetIndex)
1399 Diag(A->getLoc(), diag::err_hlsl_semantic_index_out_of_range)
1400 << A->getAttrName() << LastIndex << MaxTargetIndex;
1404 Diag(A->getLoc(), diag::err_hlsl_semantic_indexing_not_supported)
1405 << A->getAttrName();
1412 return VT->getElementType();
1415 return MT->getElementType();
1421 return VT->getNumElements();
1442void SemaHLSL::diagnoseSemanticType(
const Decl *D,
1443 const HLSLAppliedSemanticAttr *A,
1445 assert(Kind != SemanticKind::Invalid &&
"expected a valid semantic");
1449 if (
const auto *FD = dyn_cast<FunctionDecl>(D))
1455 T =
T.getNonReferenceType();
1458 QualType DeclaredTy =
T;
1460 T = AT->getElementType();
1468 case SemanticKind::Barycentrics:
1470 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1471 << A->getAttrName() << 2 << 3
1474 case SemanticKind::DispatchThreadID:
1475 case SemanticKind::GroupID:
1476 case SemanticKind::GroupThreadID:
1478 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1479 << A->getAttrName() << 1 << 3
1482 case SemanticKind::StartVertexLocation:
1483 case SemanticKind::StartInstanceLocation:
1484 case SemanticKind::ViewID:
1487 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1488 << A->getAttrName() << 0 << 1 << 1
1491 case SemanticKind::GroupIndex:
1493 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1494 << A->getAttrName() << 0 << 1 << 1
1497 case SemanticKind::VertexID:
1499 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1500 << A->getAttrName() << 0 << 1
1503 case SemanticKind::Position:
1504 case SemanticKind::Target:
1506 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1507 << A->getAttrName() << 1 << 4
1510 case SemanticKind::SampleIndex:
1511 case SemanticKind::PrimitiveID:
1515 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1516 << A->getAttrName() << 0 << 1
1519 case SemanticKind::InstanceID:
1520 case SemanticKind::ShadingRate:
1527 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1528 << A->getAttrName() << 0 << 1
1530 (IsSPIRV ? 4 : 3) << DeclaredTy;
1532 case SemanticKind::IsFrontFace:
1537 Diag(A->getLoc(), diag::err_hlsl_semantic_invalid_type)
1538 << A->getAttrName() << 0 << 1
1552 Diag(A->getLoc(), diag::err_hlsl_semantic_64bit_type)
1553 << A->getAttrName() << DeclaredTy;
1556void SemaHLSL::diagnoseAttrStageMismatch(
1557 const Attr *A, llvm::Triple::EnvironmentType Stage,
1558 std::initializer_list<llvm::Triple::EnvironmentType> AllowedStages) {
1559 SmallVector<StringRef, 8> StageStrings;
1560 llvm::transform(AllowedStages, std::back_inserter(StageStrings),
1561 [](llvm::Triple::EnvironmentType ST) {
1563 HLSLShaderAttr::ConvertEnvironmentTypeToStr(ST));
1565 Diag(A->
getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
1566 << A->
getAttrName() << llvm::Triple::getEnvironmentTypeName(Stage)
1567 << (AllowedStages.size() != 1) <<
join(StageStrings,
", ");
1570void SemaHLSL::diagnoseSemanticStageMismatch(
1571 const Attr *A, llvm::Triple::EnvironmentType Stage, IOType CurrentIOType,
1574 ArrayRef<SemanticStageInfo> Allowed = llvm::hlsl::getAvailableStages(Kind);
1575 auto It = llvm::find_if(Allowed, [&Stage](
const SemanticStageInfo &Info) {
1576 return Info.Stage == Stage;
1579 StringRef CurrentIOTypeName =
"patch constants or primitives";
1580 if (
any(CurrentIOType & IOType::In))
1581 CurrentIOTypeName =
"inputs";
1582 else if (
any(CurrentIOType & IOType::Out))
1583 CurrentIOTypeName =
"outputs";
1586 if (It == Allowed.end()) {
1587 Diag(A->
getLoc(), diag::err_hlsl_semantic_unsupported_iotype_for_stage)
1588 << A->
getAttrName() << llvm::Triple::getEnvironmentTypeName(Stage)
1589 << CurrentIOTypeName;
1593 IOType AllowedIOTypes = It->AllowedIOTypesMask;
1594 if (!(AllowedIOTypes & CurrentIOType)) {
1595 Diag(A->
getLoc(), diag::err_hlsl_semantic_unsupported_iotype_for_stage)
1596 << A->
getAttrName() << llvm::Triple::getEnvironmentTypeName(Stage)
1597 << CurrentIOTypeName;
1602template <CastKind Kind>
1605 Ty = VTy->getElementType();
1610template <CastKind Kind>
1622 if (LHSFloat && RHSFloat) {
1650 if (LHSSigned == RHSSigned) {
1651 if (IsCompAssign || IntOrder >= 0)
1659 if (IntOrder != (LHSSigned ? 1 : -1)) {
1660 if (IsCompAssign || RHSSigned)
1669 if (IsCompAssign || LHSSigned)
1696 return CK_FloatingCast;
1698 return CK_IntegralCast;
1700 return CK_IntegralToFloating;
1702 return CK_FloatingToIntegral;
1708 bool IsCompAssign) {
1715 if (!LVecTy && IsCompAssign) {
1717 RHS =
SemaRef.ImpCastExprToType(RHS.
get(), RElTy, CK_HLSLVectorTruncation);
1719 if (Ctx.hasSameUnqualifiedType(LHSType, RHSType))
1721 RHS =
SemaRef.ImpCastExprToType(RHS.
get(), LHSType,
1726 unsigned EndSz = std::numeric_limits<unsigned>::max();
1729 LSz = EndSz = LVecTy->getNumElements();
1732 assert(EndSz != std::numeric_limits<unsigned>::max() &&
1733 "one of the above should have had a value");
1737 if (IsCompAssign && LSz != EndSz) {
1739 diag::err_hlsl_vector_compound_assignment_truncation)
1740 << LHSType << RHSType;
1746 if (!IsCompAssign && LVecTy && LVecTy->getNumElements() > EndSz)
1751 if (!IsCompAssign && !LVecTy)
1755 if (Ctx.hasSameUnqualifiedType(LHSType, RHSType))
1756 return Ctx.getCommonSugaredType(LHSType, RHSType);
1764 LElTy, RElTy, IsCompAssign);
1767 "HLSL Vectors can only contain integer or floating point types");
1769 LElTy, RElTy, IsCompAssign);
1774 assert((Opc == BO_LOr || Opc == BO_LAnd) &&
1775 "Called with non-logical operator");
1777 llvm::raw_svector_ostream OS(Buff);
1779 StringRef NewFnName = Opc == BO_LOr ?
"or" :
"and";
1780 OS << NewFnName <<
"(";
1790std::pair<IdentifierInfo *, bool>
1793 std::string IdStr =
"__hlsl_rootsig_decl_" + std::to_string(Hash);
1800 return {DeclIdent,
Found};
1811 for (
auto &RootSigElement : RootElements)
1812 Elements.push_back(RootSigElement.getElement());
1816 DeclIdent,
SemaRef.getLangOpts().HLSLRootSigVer, Elements);
1818 SignatureDecl->setImplicit();
1824 if (RootSigOverrideIdent) {
1827 if (
SemaRef.LookupQualifiedName(R, DC))
1828 return dyn_cast<HLSLRootSignatureDecl>(R.getFoundDecl());
1836struct PerVisibilityBindingChecker {
1839 std::array<llvm::hlsl::BindingInfoBuilder, 8> Builders;
1843 llvm::dxbc::ShaderVisibility Vis;
1848 PerVisibilityBindingChecker(
SemaHLSL *S) : S(S) {}
1850 void trackBinding(llvm::dxbc::ShaderVisibility
Visibility,
1851 llvm::dxil::ResourceClass RC,
uint32_t Space,
1853 const hlsl::RootSignatureElement *Elem) {
1855 assert(BuilderIndex < Builders.size() &&
1856 "Not enough builders for visibility type");
1857 Builders[BuilderIndex].trackBinding(RC, Space, LowerBound, UpperBound,
1858 static_cast<const void *
>(Elem));
1860 static_assert(llvm::to_underlying(llvm::dxbc::ShaderVisibility::All) == 0,
1861 "'All' visibility must come first");
1862 if (
Visibility == llvm::dxbc::ShaderVisibility::All)
1863 for (
size_t I = 1, E = Builders.size(); I < E; ++I)
1864 Builders[I].trackBinding(RC, Space, LowerBound, UpperBound,
1865 static_cast<const void *
>(Elem));
1867 ElemInfoMap.push_back({Elem,
Visibility,
false});
1870 ElemInfo &
getInfo(
const hlsl::RootSignatureElement *Elem) {
1871 auto It = llvm::lower_bound(
1873 [](
const auto &LHS,
const auto &RHS) {
return LHS.Elem < RHS; });
1874 assert(It->Elem == Elem &&
"Element not in map");
1878 bool checkOverlap() {
1879 llvm::sort(ElemInfoMap, [](
const auto &LHS,
const auto &RHS) {
1880 return LHS.Elem < RHS.Elem;
1883 bool HadOverlap =
false;
1885 using llvm::hlsl::BindingInfoBuilder;
1886 auto ReportOverlap = [
this,
1887 &HadOverlap](
const BindingInfoBuilder &Builder,
1888 const llvm::hlsl::Binding &Reported) {
1892 static_cast<const hlsl::RootSignatureElement *
>(Reported.Cookie);
1893 const llvm::hlsl::Binding &
Previous = Builder.findOverlapping(Reported);
1894 const auto *PrevElem =
1895 static_cast<const hlsl::RootSignatureElement *
>(
Previous.Cookie);
1897 ElemInfo &Info =
getInfo(Elem);
1902 Info.Diagnosed =
true;
1904 ElemInfo &PrevInfo =
getInfo(PrevElem);
1905 llvm::dxbc::ShaderVisibility CommonVis =
1906 Info.Vis == llvm::dxbc::ShaderVisibility::All ? PrevInfo.Vis
1909 this->S->
Diag(Elem->
getLocation(), diag::err_hlsl_resource_range_overlap)
1910 << llvm::to_underlying(Reported.RC) << Reported.LowerBound
1911 << Reported.isUnbounded() << Reported.UpperBound
1916 this->S->
Diag(PrevElem->getLocation(),
1917 diag::note_hlsl_resource_range_here);
1920 for (BindingInfoBuilder &Builder : Builders)
1921 Builder.calculateBindingInfo(ReportOverlap);
1941 bool HadError =
false;
1942 auto ReportError = [
this, &HadError](
SourceLocation Loc, uint32_t LowerBound,
1943 uint32_t UpperBound) {
1945 this->
Diag(Loc, diag::err_hlsl_invalid_rootsig_value)
1946 << LowerBound << UpperBound;
1953 this->
Diag(Loc, diag::err_hlsl_invalid_rootsig_value)
1954 << llvm::formatv(
"{0:f}", LowerBound).sstr<6>()
1955 << llvm::formatv(
"{0:f}", UpperBound).sstr<6>();
1958 auto VerifyRegister = [ReportError](
SourceLocation Loc, uint32_t Register) {
1959 if (!llvm::hlsl::rootsig::verifyRegisterValue(Register))
1960 ReportError(Loc, 0, 0xfffffffe);
1963 auto VerifySpace = [ReportError](
SourceLocation Loc, uint32_t Space) {
1964 if (!llvm::hlsl::rootsig::verifyRegisterSpace(Space))
1965 ReportError(Loc, 0, 0xffffffef);
1968 const uint32_t Version =
1969 llvm::to_underlying(
SemaRef.getLangOpts().HLSLRootSigVer);
1970 const uint32_t VersionEnum = Version - 1;
1971 auto ReportFlagError = [
this, &HadError, VersionEnum](
SourceLocation Loc) {
1973 this->
Diag(Loc, diag::err_hlsl_invalid_rootsig_flag)
1980 const llvm::hlsl::rootsig::RootElement &Elem = RootSigElem.
getElement();
1981 if (
const auto *Descriptor =
1982 std::get_if<llvm::hlsl::rootsig::RootDescriptor>(&Elem)) {
1983 VerifyRegister(Loc, Descriptor->Reg.Number);
1984 VerifySpace(Loc, Descriptor->Space);
1986 if (!llvm::hlsl::rootsig::verifyRootDescriptorFlag(Version,
1988 ReportFlagError(Loc);
1989 }
else if (
const auto *Constants =
1990 std::get_if<llvm::hlsl::rootsig::RootConstants>(&Elem)) {
1991 VerifyRegister(Loc, Constants->Reg.Number);
1992 VerifySpace(Loc, Constants->Space);
1993 }
else if (
const auto *Sampler =
1994 std::get_if<llvm::hlsl::rootsig::StaticSampler>(&Elem)) {
1995 VerifyRegister(Loc, Sampler->Reg.Number);
1996 VerifySpace(Loc, Sampler->Space);
1999 "By construction, parseFloatParam can't produce a NaN from a "
2000 "float_literal token");
2002 if (!llvm::hlsl::rootsig::verifyMaxAnisotropy(Sampler->MaxAnisotropy))
2003 ReportError(Loc, 0, 16);
2004 if (!llvm::hlsl::rootsig::verifyMipLODBias(Sampler->MipLODBias))
2005 ReportFloatError(Loc, -16.f, 15.99f);
2006 }
else if (
const auto *Clause =
2007 std::get_if<llvm::hlsl::rootsig::DescriptorTableClause>(
2009 VerifyRegister(Loc, Clause->Reg.Number);
2010 VerifySpace(Loc, Clause->Space);
2012 if (!llvm::hlsl::rootsig::verifyNumDescriptors(Clause->NumDescriptors)) {
2016 ReportError(Loc, 1, 0xfffffffe);
2019 if (!llvm::hlsl::rootsig::verifyDescriptorRangeFlag(Version, Clause->Type,
2021 ReportFlagError(Loc);
2025 PerVisibilityBindingChecker BindingChecker(
this);
2026 SmallVector<std::pair<
const llvm::hlsl::rootsig::DescriptorTableClause *,
2031 const llvm::hlsl::rootsig::RootElement &Elem = RootSigElem.
getElement();
2032 if (
const auto *Descriptor =
2033 std::get_if<llvm::hlsl::rootsig::RootDescriptor>(&Elem)) {
2034 uint32_t LowerBound(Descriptor->Reg.Number);
2035 uint32_t UpperBound(LowerBound);
2037 BindingChecker.trackBinding(
2038 Descriptor->Visibility,
2039 static_cast<llvm::dxil::ResourceClass
>(Descriptor->Type),
2040 Descriptor->Space, LowerBound, UpperBound, &RootSigElem);
2041 }
else if (
const auto *Constants =
2042 std::get_if<llvm::hlsl::rootsig::RootConstants>(&Elem)) {
2043 uint32_t LowerBound(Constants->Reg.Number);
2044 uint32_t UpperBound(LowerBound);
2046 BindingChecker.trackBinding(
2047 Constants->Visibility, llvm::dxil::ResourceClass::CBuffer,
2048 Constants->Space, LowerBound, UpperBound, &RootSigElem);
2049 }
else if (
const auto *Sampler =
2050 std::get_if<llvm::hlsl::rootsig::StaticSampler>(&Elem)) {
2051 uint32_t LowerBound(Sampler->Reg.Number);
2052 uint32_t UpperBound(LowerBound);
2054 BindingChecker.trackBinding(
2055 Sampler->Visibility, llvm::dxil::ResourceClass::Sampler,
2056 Sampler->Space, LowerBound, UpperBound, &RootSigElem);
2057 }
else if (
const auto *Clause =
2058 std::get_if<llvm::hlsl::rootsig::DescriptorTableClause>(
2061 UnboundClauses.emplace_back(Clause, &RootSigElem);
2062 }
else if (
const auto *Table =
2063 std::get_if<llvm::hlsl::rootsig::DescriptorTable>(&Elem)) {
2064 assert(UnboundClauses.size() == Table->NumClauses &&
2065 "Number of unbound elements must match the number of clauses");
2066 bool HasAnySampler =
false;
2067 bool HasAnyNonSampler =
false;
2068 uint64_t Offset = 0;
2069 bool IsPrevUnbound =
false;
2070 for (
const auto &[Clause, ClauseElem] : UnboundClauses) {
2072 if (Clause->Type == llvm::dxil::ResourceClass::Sampler)
2073 HasAnySampler =
true;
2075 HasAnyNonSampler =
true;
2077 if (HasAnySampler && HasAnyNonSampler)
2078 Diag(Loc, diag::err_hlsl_invalid_mixed_resources);
2083 if (Clause->NumDescriptors == 0)
2087 Clause->Offset == llvm::hlsl::rootsig::DescriptorTableOffsetAppend;
2089 Offset = Clause->Offset;
2091 uint64_t RangeBound = llvm::hlsl::rootsig::computeRangeBound(
2092 Offset, Clause->NumDescriptors);
2094 if (IsPrevUnbound && IsAppending)
2095 Diag(Loc, diag::err_hlsl_appending_onto_unbound);
2096 else if (!llvm::hlsl::rootsig::verifyNoOverflowedOffset(RangeBound))
2097 Diag(Loc, diag::err_hlsl_offset_overflow) << Offset << RangeBound;
2100 Offset = RangeBound + 1;
2101 IsPrevUnbound = Clause->NumDescriptors ==
2102 llvm::hlsl::rootsig::NumDescriptorsUnbounded;
2105 uint32_t LowerBound(Clause->Reg.Number);
2106 uint32_t UpperBound = llvm::hlsl::rootsig::computeRangeBound(
2107 LowerBound, Clause->NumDescriptors);
2109 BindingChecker.trackBinding(
2111 static_cast<llvm::dxil::ResourceClass
>(Clause->Type), Clause->Space,
2112 LowerBound, UpperBound, ClauseElem);
2114 UnboundClauses.clear();
2118 return BindingChecker.checkOverlap();
2123 Diag(AL.
getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2128 if (
auto *RS = D->
getAttr<RootSignatureAttr>()) {
2129 if (RS->getSignatureIdent() != Ident) {
2130 Diag(AL.
getLoc(), diag::err_disallowed_duplicate_attribute) << RS;
2134 Diag(AL.
getLoc(), diag::warn_duplicate_attribute_exact) << RS;
2140 if (
auto *SignatureDecl =
2141 dyn_cast<HLSLRootSignatureDecl>(R.getFoundDecl())) {
2148 llvm::VersionTuple SMVersion =
2153 uint32_t ZMax = 1024;
2154 uint32_t ThreadMax = 1024;
2155 if (IsDXIL && SMVersion.getMajor() <= 4) {
2158 }
else if (IsDXIL && SMVersion.getMajor() == 5) {
2168 diag::err_hlsl_numthreads_argument_oor)
2177 diag::err_hlsl_numthreads_argument_oor)
2186 diag::err_hlsl_numthreads_argument_oor)
2191 if (
X * Y * Z > ThreadMax) {
2192 Diag(AL.
getLoc(), diag::err_hlsl_numthreads_invalid) << ThreadMax;
2209 if (SpelledArgsCount == 0 || SpelledArgsCount > 3)
2217 if (SpelledArgsCount > 1 &&
2221 uint32_t Preferred = 0;
2222 if (SpelledArgsCount > 2 &&
2226 if (SpelledArgsCount > 2) {
2229 diag::err_attribute_power_of_two_in_range)
2230 << AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize
2235 if (Preferred < Min || Preferred >
Max) {
2237 diag::err_attribute_power_of_two_in_range)
2238 << AL <<
Min <<
Max << Preferred;
2241 }
else if (SpelledArgsCount > 1) {
2244 diag::err_attribute_power_of_two_in_range)
2245 << AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize <<
Max;
2249 Diag(AL.
getLoc(), diag::err_attribute_argument_invalid) << AL << 1;
2252 Diag(AL.
getLoc(), diag::warn_attr_min_eq_max) << AL;
2257 diag::err_attribute_power_of_two_in_range)
2258 << AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize <<
Min;
2263 HLSLWaveSizeAttr *NewAttr =
2300 uint32_t Binding = 0;
2318 if (
const auto *BuiltIn = D->
getAttr<HLSLVkBuiltInAttr>()) {
2319 Diag(AL.
getLoc(), diag::err_attributes_are_not_compatible)
2322 BuiltIn->isRegularKeywordAttribute());
2323 Diag(BuiltIn->getLocation(), diag::note_conflicting_attribute);
2333 if (!
SemaRef.checkStringLiteralArgumentAttr(AL, 0, BuiltIn, &ArgLoc))
2336 static constexpr StringRef SupportedBuiltIns[] = {
2341 if (!llvm::is_contained(SupportedBuiltIns, BuiltIn)) {
2343 llvm::raw_string_ostream OS(Quoted);
2344 llvm::interleaveComma(SupportedBuiltIns, OS,
2345 [&](StringRef S) { OS <<
"'" << S <<
"'"; });
2346 Diag(ArgLoc, diag::err_hlsl_vk_builtin_unsupported_value)
2347 << BuiltIn << Quoted;
2352 if (
const auto *Location = D->
getAttr<HLSLVkLocationAttr>()) {
2353 Diag(AL.
getLoc(), diag::err_attributes_are_not_compatible)
2356 Location->isRegularKeywordAttribute());
2357 Diag(Location->getLoc(), diag::note_conflicting_attribute);
2365 uint32_t IndexValue(0), ExplicitIndex(0);
2368 assert(0 &&
"HLSLUnparsedSemantic is expected to have 2 int arguments.");
2370 assert(IndexValue > 0 ? ExplicitIndex :
true);
2373 if (Kind == SemanticKind::Invalid) {
2374 Diag(AL.
getLoc(), diag::err_hlsl_unknown_semantic) << AL;
2380 case SemanticKind::RenderTargetArrayIndex:
2381 case SemanticKind::ViewPortArrayIndex:
2382 case SemanticKind::ClipDistance:
2383 case SemanticKind::CullDistance:
2384 case SemanticKind::OutputControlPointID:
2385 case SemanticKind::DomainLocation:
2386 case SemanticKind::GSInstanceID:
2387 case SemanticKind::Coverage:
2388 case SemanticKind::InnerCoverage:
2389 case SemanticKind::Depth:
2390 case SemanticKind::DepthLessEqual:
2391 case SemanticKind::DepthGreaterEqual:
2392 case SemanticKind::StencilRef:
2393 case SemanticKind::TessFactor:
2394 case SemanticKind::InsideTessFactor:
2395 case SemanticKind::CullPrimitive:
2396 Diag(AL.
getLoc(), diag::err_hlsl_unknown_semantic) << AL;
2402 D->
addAttr(HLSLParsedSemanticAttr::Create(
2408 Diag(AL.
getLoc(), diag::err_hlsl_attr_invalid_ast_node)
2409 << AL <<
"shader constant in a constant buffer";
2413 uint32_t SubComponent;
2423 bool IsAggregateTy = (
T->isArrayType() ||
T->isStructureType());
2428 if (IsAggregateTy) {
2429 Diag(AL.
getLoc(), diag::err_hlsl_invalid_register_or_packoffset);
2433 if ((Component * 32 + Size) > 128) {
2434 Diag(AL.
getLoc(), diag::err_hlsl_packoffset_cross_reg_boundary);
2439 EltTy = VT->getElementType();
2441 if (Align > 32 && Component == 1) {
2444 Diag(AL.
getLoc(), diag::err_hlsl_packoffset_alignment_mismatch)
2458 if (!
SemaRef.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
2461 llvm::Triple::EnvironmentType ShaderType;
2462 if (!HLSLShaderAttr::ConvertStrToEnvironmentType(Str, ShaderType)) {
2463 Diag(AL.
getLoc(), diag::warn_attribute_type_not_supported)
2464 << AL << Str << ArgLoc;
2478 Expr *SampleCountExpr) {
2479 assert(AttrList.size() &&
"expected list of resource attributes");
2486 HLSLAttributedResourceType::Attributes ResAttrs;
2488 bool HasResourceClass =
false;
2489 bool HasResourceDimension =
false;
2490 for (
const Attr *A : AttrList) {
2495 case attr::HLSLResourceClass: {
2497 if (HasResourceClass) {
2499 ? diag::warn_duplicate_attribute_exact
2500 : diag::warn_duplicate_attribute)
2504 ResAttrs.ResourceClass = RC;
2505 HasResourceClass =
true;
2508 case attr::HLSLResourceDimension: {
2509 llvm::dxil::ResourceDimension RD =
2511 if (HasResourceDimension) {
2513 ? diag::warn_duplicate_attribute_exact
2514 : diag::warn_duplicate_attribute)
2518 ResAttrs.ResourceDimension = RD;
2519 HasResourceDimension =
true;
2522 case attr::HLSLIsROV:
2523 if (ResAttrs.IsROV) {
2527 ResAttrs.IsROV =
true;
2529 case attr::HLSLRawBuffer:
2530 if (ResAttrs.RawBuffer) {
2534 ResAttrs.RawBuffer =
true;
2536 case attr::HLSLIsArray:
2537 if (ResAttrs.IsArray) {
2541 ResAttrs.IsArray =
true;
2543 case attr::HLSLIsMultiSampled:
2544 if (ResAttrs.SampleCountExpr) {
2550 ResAttrs.SampleCountExpr =
2556 case attr::HLSLIsCounter:
2557 if (ResAttrs.IsCounter) {
2561 ResAttrs.IsCounter =
true;
2563 case attr::HLSLContainedType: {
2566 if (!ContainedTy.
isNull()) {
2568 ? diag::warn_duplicate_attribute_exact
2569 : diag::warn_duplicate_attribute)
2578 llvm_unreachable(
"unhandled resource attribute type");
2582 if (!HasResourceClass) {
2583 S.
Diag(AttrList.back()->getRange().getEnd(),
2584 diag::err_hlsl_missing_resource_class);
2589 Wrapped, ContainedTy, ResAttrs);
2591 if (LocInfo && ContainedTyInfo) {
2604 if (!
T->isHLSLResourceType()) {
2605 Diag(AL.
getLoc(), diag::err_hlsl_attribute_needs_intangible_type)
2620 AttributeCommonInfo::AS_CXX11, 0, false ,
2625 case ParsedAttr::AT_HLSLResourceClass: {
2626 StringRef Identifier;
2628 if (!
SemaRef.checkStringLiteralArgumentAttr(AL, 0, Identifier, &ArgLoc))
2633 if (!HLSLResourceClassAttr::ConvertStrToResourceClass(Identifier, RC)) {
2634 Diag(ArgLoc, diag::warn_attribute_type_not_supported)
2635 <<
"ResourceClass" << Identifier;
2638 A = HLSLResourceClassAttr::Create(
getASTContext(), RC, ACI);
2642 case ParsedAttr::AT_HLSLResourceDimension: {
2643 StringRef Identifier;
2645 if (!
SemaRef.checkStringLiteralArgumentAttr(AL, 0, Identifier, &ArgLoc))
2649 llvm::dxil::ResourceDimension RD;
2650 if (!HLSLResourceDimensionAttr::ConvertStrToResourceDimension(Identifier,
2652 Diag(ArgLoc, diag::warn_attribute_type_not_supported)
2653 <<
"ResourceDimension" << Identifier;
2656 A = HLSLResourceDimensionAttr::Create(
getASTContext(), RD, ACI);
2660 case ParsedAttr::AT_HLSLIsROV:
2664 case ParsedAttr::AT_HLSLRawBuffer:
2668 case ParsedAttr::AT_HLSLIsCounter:
2672 case ParsedAttr::AT_HLSLIsArray:
2676 case ParsedAttr::AT_HLSLIsMultiSampled:
2680 case ParsedAttr::AT_HLSLContainedType: {
2682 Diag(AL.
getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2688 assert(TSI &&
"no type source info for attribute argument");
2690 diag::err_incomplete_type))
2692 A = HLSLContainedTypeAttr::Create(
getASTContext(), TSI, ACI);
2697 llvm_unreachable(
"unhandled HLSL attribute");
2700 HLSLResourcesTypeAttrs.emplace_back(A);
2706 if (!HLSLResourcesTypeAttrs.size())
2712 HLSLResourcesTypeAttrs, QT, &LocInfo)) {
2713 const HLSLAttributedResourceType *RT =
2720 LocsForHLSLAttributedResources.insert(std::pair(RT, LocInfo));
2722 HLSLResourcesTypeAttrs.clear();
2730 auto I = LocsForHLSLAttributedResources.find(RT);
2731 if (I != LocsForHLSLAttributedResources.end()) {
2732 LocInfo = I->second;
2733 LocsForHLSLAttributedResources.erase(I);
2742void SemaHLSL::collectResourceBindingsOnUserRecordDecl(
const VarDecl *VD,
2743 const RecordType *RT) {
2751 "incomplete arrays inside user defined types are not supported");
2760 if (
const HLSLAttributedResourceType *AttrResType =
2761 HLSLAttributedResourceType::findHandleTypeOnResource(Ty)) {
2766 Bindings.addDeclBindingInfo(VD, RC);
2767 }
else if (
const RecordType *RT = dyn_cast<RecordType>(Ty)) {
2773 collectResourceBindingsOnUserRecordDecl(VD, RT);
2785 bool SpecifiedSpace) {
2786 int RegTypeNum =
static_cast<int>(RegType);
2789 if (D->
hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
2790 S.
Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2795 if (
HLSLBufferDecl *CBufferOrTBuffer = dyn_cast<HLSLBufferDecl>(D)) {
2796 ResourceClass RC = CBufferOrTBuffer->isCBuffer() ? ResourceClass::CBuffer
2797 : ResourceClass::SRV;
2807 assert(
isa<VarDecl>(D) &&
"D is expected to be VarDecl or HLSLBufferDecl");
2811 if (
const HLSLAttributedResourceType *AttrResType =
2812 HLSLAttributedResourceType::findHandleTypeOnResource(
2829 if (SpecifiedSpace && !DeclaredInCOrTBuffer)
2830 S.
Diag(ArgLoc, diag::err_hlsl_space_on_global_constant);
2835 if (RegType == RegisterType::CBuffer)
2836 S.
Diag(ArgLoc, diag::warn_hlsl_deprecated_register_type_b);
2837 else if (RegType != RegisterType::C)
2838 S.
Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2842 if (RegType == RegisterType::C)
2843 S.
Diag(ArgLoc, diag::warn_hlsl_register_type_c_packoffset);
2845 S.
Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2855 S.
Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum;
2863 bool RegisterTypesDetected[5] = {
false};
2864 RegisterTypesDetected[
static_cast<int>(regType)] =
true;
2867 if (HLSLResourceBindingAttr *
attr =
2868 dyn_cast<HLSLResourceBindingAttr>(*it)) {
2871 if (RegisterTypesDetected[
static_cast<int>(otherRegType)]) {
2872 int otherRegTypeNum =
static_cast<int>(otherRegType);
2874 diag::err_hlsl_duplicate_register_annotation)
2878 RegisterTypesDetected[
static_cast<int>(otherRegType)] =
true;
2886 bool SpecifiedSpace) {
2891 "expecting VarDecl or HLSLBufferDecl");
2911 if (StartSlot > Limit)
2915 if (
const auto *AT = dyn_cast<ArrayType>(
T)) {
2918 if (
const auto *CAT = dyn_cast<ConstantArrayType>(AT))
2919 Count = CAT->
getSize().getZExtValue();
2921 QualType ElemTy = AT->getElementType();
2923 ArrayCount * Count);
2927 if (
auto ResTy = dyn_cast<HLSLAttributedResourceType>(
T)) {
2930 if (ResTy->getAttrs().ResourceClass != ResClass)
2934 uint64_t EndSlot = StartSlot + ArrayCount - 1;
2935 if (EndSlot > Limit)
2939 StartSlot = EndSlot + 1;
2944 if (
const auto *RT = dyn_cast<RecordType>(
T)) {
2947 if (
const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2950 ResClass, Ctx, ArrayCount))
2957 ResClass, Ctx, ArrayCount))
2972 if (SlotNum > Limit)
2977 if (RegTy == RegisterType::C || RegTy == RegisterType::I)
2980 if (
VarDecl *VD = dyn_cast<VarDecl>(TheDecl)) {
2989 return (BaseSlot > Limit);
2996 return (SlotNum > Limit);
2999 llvm_unreachable(
"unexpected decl type");
3003 if (
VarDecl *VD = dyn_cast<VarDecl>(TheDecl)) {
3005 if (
const auto *IAT = dyn_cast<IncompleteArrayType>(Ty))
3006 Ty = IAT->getElementType();
3008 diag::err_incomplete_type))
3012 StringRef Slot =
"";
3013 StringRef Space =
"";
3017 Diag(AL.
getLoc(), diag::err_attribute_argument_type)
3027 Diag(AL.
getLoc(), diag::err_attribute_argument_type)
3033 SpaceLoc = Loc->
getLoc();
3036 if (Str.starts_with(
"space")) {
3038 SpaceLoc = Loc->
getLoc();
3047 std::optional<unsigned> SlotNum;
3048 unsigned SpaceNum = 0;
3051 if (!Slot.empty()) {
3053 Diag(SlotLoc, diag::err_hlsl_binding_type_invalid) << Slot.substr(0, 1);
3056 if (RegType == RegisterType::I) {
3057 Diag(SlotLoc, diag::warn_hlsl_deprecated_register_type_i);
3060 const StringRef SlotNumStr = Slot.substr(1);
3065 if (SlotNumStr.getAsInteger(10, N)) {
3066 Diag(SlotLoc, diag::err_hlsl_unsupported_register_number);
3074 Diag(SlotLoc, diag::err_hlsl_register_number_too_large);
3079 SlotNum = (unsigned)N;
3083 if (!Space.starts_with(
"space")) {
3084 Diag(SpaceLoc, diag::err_hlsl_expected_space) << Space;
3087 StringRef SpaceNumStr = Space.substr(5);
3088 if (SpaceNumStr.getAsInteger(10, SpaceNum)) {
3089 Diag(SpaceLoc, diag::err_hlsl_expected_space) << Space;
3094 if (SlotNum.has_value())
3099 HLSLResourceBindingAttr *NewAttr =
3100 HLSLResourceBindingAttr::Create(
getASTContext(), Slot, Space, AL);
3102 NewAttr->setBinding(RegType, SlotNum, SpaceNum);
3126 while (
const auto *AT = Cur->
getAs<AttributedType>()) {
3128 if (K == attr::HLSLRowMajor || K == attr::HLSLColumnMajor) {
3132 Cur = AT->getModifiedType();
3143 ? attr::HLSLRowMajor
3144 : attr::HLSLColumnMajor;
3148 Diag(AL.
getLoc(), diag::err_hlsl_matrix_layout_non_matrix)
3157 if (ExistingKind == AttrK) {
3158 Diag(AL.
getLoc(), diag::warn_duplicate_attribute_exact)
3160 Diag(AL.
getLoc(), diag::note_previous_attribute);
3164 ExistingKind == attr::HLSLRowMajor ?
"row_major" :
"column_major");
3165 Diag(AL.
getLoc(), diag::err_hlsl_matrix_layout_conflict)
3167 Diag(AL.
getLoc(), diag::note_conflicting_attribute);
3172 if (AttrK == attr::HLSLRowMajor)
3173 return ::new (Ctx) HLSLRowMajorAttr(Ctx, AL);
3174 return ::new (Ctx) HLSLColumnMajorAttr(Ctx, AL);
3185 if (K != attr::HLSLRowMajor && K != attr::HLSLColumnMajor)
3187 if (
T.isNull() ||
T->isDependentType())
3192 K == attr::HLSLRowMajor ?
"row_major" :
"column_major");
3193 Diag(Loc, diag::err_hlsl_matrix_layout_non_matrix) << II;
3201using llvm::dxil::BarrierMemoryTypeFlag;
3202using llvm::dxil::BarrierSemanticFlag;
3204template <
typename T>
constexpr uint64_t barrierFlagValue(
T Flag) {
3205 return llvm::to_underlying(Flag);
3219 bool DiagnoseAvailability;
3246 llvm::DenseMap<const FunctionDecl *, unsigned> ScannedDecls;
3250 llvm::Triple::EnvironmentType CurrentShaderEnvironment;
3251 unsigned CurrentShaderStageBit;
3256 bool ReportOnlyShaderStageIssues;
3259 void SetShaderStageContext(llvm::Triple::EnvironmentType ShaderType) {
3260 static_assert(
sizeof(
unsigned) >= 4);
3261 assert(HLSLShaderAttr::isValidShaderType(ShaderType));
3262 assert((
unsigned)(ShaderType - llvm::Triple::Pixel) < 31 &&
3263 "ShaderType is too big for this bitmap");
3266 unsigned bitmapIndex = ShaderType - llvm::Triple::Pixel;
3267 CurrentShaderEnvironment = ShaderType;
3268 CurrentShaderStageBit = (1 << bitmapIndex);
3271 void SetUnknownShaderStageContext() {
3272 CurrentShaderEnvironment = llvm::Triple::UnknownEnvironment;
3273 CurrentShaderStageBit = (1 << 31);
3276 llvm::Triple::EnvironmentType GetCurrentShaderEnvironment()
const {
3277 return CurrentShaderEnvironment;
3280 bool InUnknownShaderStageContext()
const {
3281 return CurrentShaderEnvironment == llvm::Triple::UnknownEnvironment;
3285 void AddToScannedFunctions(
const FunctionDecl *FD) {
3286 unsigned &ScannedStages = ScannedDecls[FD];
3287 ScannedStages |= CurrentShaderStageBit;
3290 unsigned GetScannedStages(
const FunctionDecl *FD) {
return ScannedDecls[FD]; }
3292 bool WasAlreadyScannedInCurrentStage(
const FunctionDecl *FD) {
3293 return WasAlreadyScannedInCurrentStage(GetScannedStages(FD));
3296 bool WasAlreadyScannedInCurrentStage(
unsigned ScannerStages) {
3297 return ScannerStages & CurrentShaderStageBit;
3300 static bool NeverBeenScanned(
unsigned ScannedStages) {
3301 return ScannedStages == 0;
3305 void HandleFunctionOrMethodRef(FunctionDecl *FD, Expr *RefExpr);
3306 void CheckDeclAvailability(NamedDecl *D,
const AvailabilityAttr *AA,
3308 const AvailabilityAttr *FindAvailabilityAttr(
const Decl *D);
3309 bool HasMatchingEnvironmentOrNone(
const AvailabilityAttr *AA);
3310 void DiagnoseBarrierCall(CallExpr *CE);
3312 bool HasVisibleGroup,
bool IsAllMemory);
3314 bool HasKnownStage,
bool IsAllMemory);
3315 void DiagnoseBarrierGroupSemantic(Expr *SemanticArg,
uint64_t SemanticFlags,
3316 bool HasVisibleGroup);
3317 void DiagnoseBarrierScope(Expr *SemanticArg,
uint64_t MemoryFlags,
3321 DiagnoseHLSLAvailability(Sema &SemaRef,
bool DiagnoseAvailability)
3322 : SemaRef(SemaRef), DiagnoseAvailability(DiagnoseAvailability),
3323 CurrentShaderEnvironment(llvm::Triple::UnknownEnvironment),
3324 CurrentShaderStageBit(0), ReportOnlyShaderStageIssues(
false) {}
3327 void RunOnTranslationUnit(
const TranslationUnitDecl *TU);
3328 void RunOnFunction(
const FunctionDecl *FD);
3330 bool VisitDeclRefExpr(DeclRefExpr *DRE)
override {
3331 FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(DRE->
getDecl());
3333 HandleFunctionOrMethodRef(FD, DRE);
3337 bool VisitMemberExpr(MemberExpr *ME)
override {
3338 FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(ME->
getMemberDecl());
3340 HandleFunctionOrMethodRef(FD, ME);
3344 bool VisitCallExpr(CallExpr *CE)
override {
3345 DiagnoseBarrierCall(CE);
3350uint64_t DiagnoseHLSLAvailability::DiagnoseBarrierGroupMemory(
3351 Expr *MemoryArg,
uint64_t MemoryFlags,
bool HasVisibleGroup,
3354 barrierFlagValue(BarrierMemoryTypeFlag::GroupSharedMemory);
3355 if (HasVisibleGroup || (MemoryFlags & GroupSharedMemory) == 0)
3360 diag::err_hlsl_barrier_flag_requires_group)
3365 return MemoryFlags & ~GroupSharedMemory;
3368uint64_t DiagnoseHLSLAvailability::DiagnoseBarrierNodeMemory(
3369 Expr *MemoryArg,
uint64_t MemoryFlags,
bool HasKnownStage,
3372 barrierFlagValue(BarrierMemoryTypeFlag::NodeMemory);
3373 if (!HasKnownStage || (MemoryFlags & NodeMemory) == 0)
3378 diag::err_hlsl_barrier_node_memory_requires_node);
3382 return MemoryFlags & ~NodeMemory;
3385void DiagnoseHLSLAvailability::DiagnoseBarrierGroupSemantic(
3386 Expr *SemanticArg,
uint64_t SemanticFlags,
bool HasVisibleGroup) {
3387 if (HasVisibleGroup ||
3388 (SemanticFlags & barrierFlagValue(BarrierSemanticFlag::GroupFlags)) == 0)
3392 diag::err_hlsl_barrier_flag_requires_group)
3393 << ((SemanticFlags & barrierFlagValue(BarrierSemanticFlag::GroupSync)) !=
3399void DiagnoseHLSLAvailability::DiagnoseBarrierScope(
Expr *SemanticArg,
3402 if (ReportOnlyShaderStageIssues)
3406 barrierFlagValue(BarrierMemoryTypeFlag::UAVMemory) |
3407 barrierFlagValue(BarrierMemoryTypeFlag::NodeInputMemory);
3408 if ((SemanticFlags & barrierFlagValue(BarrierSemanticFlag::DeviceScope)) !=
3410 (MemoryFlags & DeviceScopeMemory) == 0)
3412 diag::err_hlsl_barrier_scope_requires_memory)
3414 if ((SemanticFlags & barrierFlagValue(BarrierSemanticFlag::GroupScope)) !=
3418 diag::err_hlsl_barrier_scope_requires_memory)
3422void DiagnoseHLSLAvailability::DiagnoseBarrierCall(
CallExpr *CE) {
3424 if (!FD || FD->
getBuiltinID() != Builtin::BI__builtin_hlsl_barrier)
3427 const llvm::Triple::EnvironmentType Stage = GetCurrentShaderEnvironment();
3428 const bool HasKnownStage = !InUnknownShaderStageContext();
3429 const bool HasVisibleGroup =
3430 !HasKnownStage || Stage == llvm::Triple::Compute ||
3431 Stage == llvm::Triple::Mesh || Stage == llvm::Triple::Amplification;
3433 uint64_t MemoryFlags = barrierFlagValue(BarrierMemoryTypeFlag::ValidMask);
3436 std::optional<llvm::APSInt>
Value =
3440 MemoryFlags =
Value->getZExtValue();
3441 const bool IsAllMemory =
3442 MemoryFlags == barrierFlagValue(BarrierMemoryTypeFlag::ValidMask);
3444 MemoryFlags = DiagnoseBarrierGroupMemory(MemoryArg, MemoryFlags,
3445 HasVisibleGroup, IsAllMemory);
3446 MemoryFlags = DiagnoseBarrierNodeMemory(MemoryArg, MemoryFlags,
3447 HasKnownStage, IsAllMemory);
3448 }
else if (!HasVisibleGroup) {
3450 diag::err_hlsl_barrier_resource_requires_group);
3455 std::optional<llvm::APSInt>
Value =
3461 DiagnoseBarrierGroupSemantic(SemanticArg, SemanticFlags, HasVisibleGroup);
3464 DiagnoseBarrierScope(SemanticArg, MemoryFlags, SemanticFlags);
3467void DiagnoseHLSLAvailability::HandleFunctionOrMethodRef(
FunctionDecl *FD,
3470 "expected DeclRefExpr or MemberExpr");
3472 if (DiagnoseAvailability)
3473 if (
const AvailabilityAttr *AA = FindAvailabilityAttr(FD))
3474 CheckDeclAvailability(
3479 if (FD->
hasBody(FDWithBody) && !WasAlreadyScannedInCurrentStage(FDWithBody))
3480 DeclsToScan.push_back(FDWithBody);
3483void DiagnoseHLSLAvailability::RunOnTranslationUnit(
3488 llvm::Triple::EnvironmentType::Library;
3497 DeclContextsToScan.push_back(TU);
3499 while (!DeclContextsToScan.empty()) {
3500 const DeclContext *DC = DeclContextsToScan.pop_back_val();
3501 for (
auto &D : DC->
decls()) {
3508 if (llvm::dyn_cast<NamespaceDecl>(D) || llvm::dyn_cast<ExportDecl>(D)) {
3509 DeclContextsToScan.push_back(llvm::dyn_cast<DeclContext>(D));
3514 const FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(D);
3519 if (HLSLShaderAttr *ShaderAttr = FD->
getAttr<HLSLShaderAttr>()) {
3520 if (!IsLibraryShader && FD->
getName() == EntryName) {
3523 diag::err_hlsl_ambiguous_entry_point)
3525 SemaRef.
Diag(EntryLoc, diag::note_previous_declaration_as)
3531 SetShaderStageContext(ShaderAttr->getType());
3540 for (
const auto *Redecl : FD->
redecls()) {
3541 if (Redecl->isInExportDeclContext()) {
3548 SetUnknownShaderStageContext();
3555 if (!IsLibraryShader && EntryLoc.
isInvalid()) {
3562void DiagnoseHLSLAvailability::RunOnFunction(
const FunctionDecl *FD) {
3563 assert(DeclsToScan.empty() &&
"DeclsToScan should be empty");
3564 DeclsToScan.push_back(FD);
3566 while (!DeclsToScan.empty()) {
3574 const unsigned ScannedStages = GetScannedStages(FD);
3575 if (WasAlreadyScannedInCurrentStage(ScannedStages))
3578 ReportOnlyShaderStageIssues = !NeverBeenScanned(ScannedStages);
3580 AddToScannedFunctions(FD);
3585bool DiagnoseHLSLAvailability::HasMatchingEnvironmentOrNone(
3586 const AvailabilityAttr *AA) {
3591 llvm::Triple::EnvironmentType CurrentEnv = GetCurrentShaderEnvironment();
3592 if (CurrentEnv == llvm::Triple::UnknownEnvironment)
3595 llvm::Triple::EnvironmentType AttrEnv =
3596 AvailabilityAttr::getEnvironmentType(IIEnvironment->
getName());
3598 return CurrentEnv == AttrEnv;
3601const AvailabilityAttr *
3602DiagnoseHLSLAvailability::FindAvailabilityAttr(
const Decl *D) {
3603 AvailabilityAttr
const *PartialMatch =
nullptr;
3607 for (
const auto *A : D->
attrs()) {
3608 if (
const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
3609 const AvailabilityAttr *EffectiveAvail = Avail->getEffectiveAttr();
3610 StringRef AttrPlatform = EffectiveAvail->getPlatform()->getName();
3611 StringRef TargetPlatform =
3615 if (AttrPlatform == TargetPlatform) {
3617 if (HasMatchingEnvironmentOrNone(EffectiveAvail))
3619 PartialMatch = Avail;
3623 return PartialMatch;
3628void DiagnoseHLSLAvailability::CheckDeclAvailability(
NamedDecl *D,
3629 const AvailabilityAttr *AA,
3648 if (ReportOnlyShaderStageIssues)
3654 if (InUnknownShaderStageContext())
3659 bool EnvironmentMatches = HasMatchingEnvironmentOrNone(AA);
3660 VersionTuple Introduced = AA->getIntroduced();
3669 llvm::StringRef PlatformName(
3672 llvm::StringRef CurrentEnvStr =
3673 llvm::Triple::getEnvironmentTypeName(GetCurrentShaderEnvironment());
3675 llvm::StringRef AttrEnvStr =
3676 AA->getEnvironment() ? AA->getEnvironment()->getName() :
"";
3677 bool UseEnvironment = !AttrEnvStr.empty();
3679 if (EnvironmentMatches) {
3680 SemaRef.
Diag(
Range.getBegin(), diag::warn_hlsl_availability)
3681 <<
Range << D << PlatformName << Introduced.getAsString()
3682 << UseEnvironment << CurrentEnvStr;
3684 SemaRef.
Diag(
Range.getBegin(), diag::warn_hlsl_availability_unavailable)
3688 SemaRef.
Diag(D->
getLocation(), diag::note_partial_availability_specified_here)
3689 << D << PlatformName << Introduced.getAsString()
3691 << UseEnvironment << AttrEnvStr << CurrentEnvStr;
3698 if (!DefaultCBufferDecls.empty()) {
3701 DefaultCBufferDecls);
3704 SemaRef.getCurLexicalContext()->addDecl(DefaultCBuffer);
3708 for (
const Decl *VD : DefaultCBufferDecls) {
3709 const HLSLResourceBindingAttr *RBA =
3710 VD->
getAttr<HLSLResourceBindingAttr>();
3711 if (RBA && RBA->hasRegisterSlot() &&
3712 RBA->getRegisterType() == HLSLResourceBindingAttr::RegisterType::C) {
3719 SemaRef.Consumer.HandleTopLevelDecl(DG);
3721 diagnoseAvailabilityViolations(TU);
3730 "expected member expr to have resource record type or array of them");
3736 const Expr *NonConstIndexExpr =
nullptr;
3739 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3740 if (!NonConstIndexExpr)
3748 diag::err_hlsl_resource_member_array_access_not_constant);
3752 if (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
3753 const Expr *IdxExpr = ASE->getIdx();
3755 NonConstIndexExpr = IdxExpr;
3757 }
else if (
const auto *SubME = dyn_cast<MemberExpr>(E)) {
3758 E = SubME->getBase();
3759 }
else if (
const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3760 E = ICE->getSubExpr();
3764 llvm_unreachable(
"unexpected expr type in resource member access");
3773 SemaRef.Context.getCanonicalType(
SemaRef.Context.getAddrSpaceQualType(
3776 SemaRef.Context.getLValueReferenceType(AddrSpaceType));
3779 SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
3783 [[maybe_unused]]
bool LookupSucceeded =
3784 SemaRef.LookupQualifiedName(ConvR, RD);
3785 assert(LookupSucceeded);
3794std::optional<ExprResult>
3797 const HLSLAttributedResourceType *ResTy =
3798 HLSLAttributedResourceType::findHandleTypeOnResource(
3799 BaseType.getTypePtr());
3801 ResTy->getAttrs().ResourceClass != llvm::dxil::ResourceClass::CBuffer)
3802 return std::nullopt;
3804 QualType TemplateType = ResTy->getContainedType();
3808 assert(NamedConversionDecl &&
3809 "Could not find conversion function for ConstantBuffer.");
3810 auto *ConversionDecl =
3813 return SemaRef.BuildCXXMemberCallExpr(BaseExpr, NamedConversionDecl,
3823 const bool DiagnoseAvailability =
3825 TI.
getTriple().getEnvironment() == llvm::Triple::EnvironmentType::Library;
3826 DiagnoseHLSLAvailability(
SemaRef, DiagnoseAvailability)
3827 .RunOnTranslationUnit(TU);
3834 for (
unsigned I = 1, N = TheCall->
getNumArgs(); I < N; ++I) {
3837 S->
Diag(TheCall->
getBeginLoc(), diag::err_vec_builtin_incompatible_vector)
3862 for (
unsigned I = 0; I < TheCall->
getNumArgs(); ++I) {
3875 if (!BaseType->isFloat32Type())
3876 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
3877 << ArgOrdinal << 5 << 0
3887 if (!BaseType->isHalfType() && !BaseType->isFloat32Type())
3888 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
3889 << ArgOrdinal << 5 << 0
3898 if (!BaseType->isDoubleType()) {
3901 return S->
Diag(Loc, diag::err_builtin_requires_double_type)
3902 << ArgOrdinal << PassedType;
3909 unsigned ArgIndex) {
3910 auto *Arg = TheCall->
getArg(ArgIndex);
3912 if (Arg->IgnoreCasts()->isModifiableLvalue(S->
Context, &OrigLoc) ==
3915 S->
Diag(OrigLoc, diag::error_hlsl_inout_lvalue) << Arg << 0;
3929 << (ArgIndex + 1) << LValueTy;
3939 if (VecTy->getElementType()->isDoubleType())
3940 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
3941 << ArgOrdinal << 1 << 0 << 1
3952 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
3953 << ArgOrdinal << 5 << 1
3962 if (VecTy->getElementType()->isUnsignedIntegerType())
3965 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
3966 << ArgOrdinal << 4 << 3 << 0
3975 return S->
Diag(Loc, diag::err_builtin_invalid_arg_type)
3976 << ArgOrdinal << 5 << 3
3982 unsigned ArgOrdinal,
unsigned Width) {
3985 ArgTy = VTy->getElementType();
3989 if (ElementBitCount != Width) {
3991 diag::err_integer_incorrect_bit_count)
3992 << Width << ElementBitCount;
4003 else if (
auto *MatTyA =
4006 ReturnType, MatTyA->getNumRows(), MatTyA->getNumColumns());
4012 unsigned ArgIndex) {
4021 diag::err_typecheck_expect_scalar_or_vector)
4022 << ArgType << Scalar;
4029 QualType Scalar,
unsigned ArgIndex) {
4040 if (
const auto *VTy = ArgType->getAs<
VectorType>()) {
4053 diag::err_typecheck_expect_scalar_or_vector_or_matrix)
4054 << ArgType << Scalar;
4059 unsigned ArgIndex) {
4064 if (!(ArgType->isScalarType() ||
4065 (VTy && VTy->getElementType()->isScalarType()))) {
4067 diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
4075 unsigned ArgIndex) {
4078 if (ArgType->isDependentType())
4082 if (
const auto *VectorTy = ArgType->getAs<
VectorType>())
4083 ElementType = VectorTy->getElementType();
4085 ElementType = MatrixTy->getElementType();
4087 if (ElementType->isBooleanType())
4090 if (ElementType->isIntegerType() || ElementType->isRealFloatingType()) {
4092 if (BitWidth == 16 || BitWidth == 32 || BitWidth == 64)
4097 diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
4105 unsigned ArgIndex) {
4107 assert(ArgIndex < TheCall->getNumArgs());
4115 diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
4141 diag::err_typecheck_convert_incompatible)
4142 << MaskTy << UInt4Ty << 1 << 0 << 0;
4152 diag::err_typecheck_call_different_arg_types)
4171 Arg1ScalarTy = VTy->getElementType();
4175 Arg2ScalarTy = VTy->getElementType();
4178 S->
Diag(Arg1->
getBeginLoc(), diag::err_hlsl_builtin_scalar_vector_mismatch)
4179 << 1 << TheCall->
getCallee() << Arg1Ty << Arg2Ty;
4189 if (Arg1Length > 0 && Arg0Length != Arg1Length) {
4191 diag::err_typecheck_vector_lengths_not_equal)
4197 if (Arg2Length > 0 && Arg0Length != Arg2Length) {
4199 diag::err_typecheck_vector_lengths_not_equal)
4219 Arg1ScalarTy = MTy->getElementType();
4223 Arg2ScalarTy = MTy->getElementType();
4226 S->
Diag(Arg1->
getBeginLoc(), diag::err_hlsl_builtin_scalar_vector_mismatch)
4227 << 1 << TheCall->
getCallee() << Arg1Ty << Arg2Ty;
4232 unsigned Arg0Cols = Arg0MatTy->getNumColumns();
4234 for (
Expr *Arg : {Arg1, Arg2}) {
4237 (MTy->getNumRows() != Arg0Rows || MTy->getNumColumns() != Arg0Cols)) {
4239 diag::err_typecheck_vector_lengths_not_equal)
4241 << Arg->getSourceRange();
4257 unsigned ArgIndex) {
4262 assert(TheCall->
getNumArgs() > IndexArgIndex &&
"Index argument missing");
4265 unsigned int ActualDim = 1;
4267 ActualDim = VTy->getNumElements();
4268 IndexTy = VTy->getElementType();
4272 diag::err_typecheck_expect_int)
4278 const HLSLAttributedResourceType *ResTy =
4280 assert(ResTy &&
"Resource argument must be a resource");
4281 HLSLAttributedResourceType::Attributes ResAttrs = ResTy->getAttrs();
4283 unsigned int ExpectedDim = 1;
4284 if (ResAttrs.ResourceDimension != llvm::dxil::ResourceDimension::Unknown)
4286 (ResAttrs.IsArray ? 1 : 0);
4288 if (ActualDim != ExpectedDim) {
4290 diag::err_hlsl_builtin_resource_coordinate_dimension_mismatch)
4301 llvm::function_ref<
bool(
const HLSLAttributedResourceType *ResType)> Check =
4305 const HLSLAttributedResourceType *ResTy =
4309 diag::err_typecheck_expect_hlsl_resource)
4313 if (Check && Check(ResTy)) {
4315 diag::err_invalid_hlsl_resource_type)
4325 "expected resource handle type");
4326 auto *MainResType = MainHandleTy->
getAs<HLSLAttributedResourceType>();
4327 auto MainAttrs = MainResType->getAttrs();
4328 assert(!MainAttrs.IsCounter &&
"cannot create a counter from a counter");
4329 MainAttrs.IsCounter =
true;
4331 MainResType->getContainedType(),
4342 return "SampleBias";
4344 return "SampleGrad";
4346 return "SampleLevel";
4350 return "SampleCmpLevelZero";
4352 llvm_unreachable(
"Invalid SampleKind");
4362 if (!MD || !MD->getDeclName().isIdentifier())
4369 return MD->getName();
4377 StringRef DefaultName) {
4382 S.
Diag(TheCall->
getBeginLoc(), diag::err_hlsl_sample_double_element_type)
4409 if (SMVersion >= VersionTuple(6, 7))
4412 S.
Diag(TheCall->
getBeginLoc(), diag::err_hlsl_sample_integer_element_type)
4414 << ContainedType << SMVersion.getAsString();
4419 bool IncludeArraySlice =
true) {
4422 [](
const HLSLAttributedResourceType *ResType) {
4423 return ResType->getAttrs().ResourceDimension ==
4424 llvm::dxil::ResourceDimension::Unknown;
4430 [](
const HLSLAttributedResourceType *ResType) {
4431 return ResType->getAttrs().ResourceClass !=
4432 llvm::hlsl::ResourceClass::Sampler;
4440 unsigned ExpectedDim =
4442 (IncludeArraySlice && ResourceTy->getAttrs().IsArray ? 1 : 0);
4471 unsigned NextIdx = 3;
4483 Expr *ComponentArg = TheCall->
getArg(NextIdx);
4487 std::optional<llvm::APSInt> ComponentOpt =
4490 int64_t ComponentVal = ComponentOpt->getSExtValue();
4491 if (ComponentVal != 0) {
4494 assert(ComponentVal >= 0 && ComponentVal <= 3 &&
4495 "The component is not in the expected range.");
4497 diag::err_hlsl_gathercmp_invalid_component)
4507 const HLSLAttributedResourceType *ResourceTy =
4510 unsigned ExpectedDim =
4513 &S, TheCall->
getArg(NextIdx),
4519 assert(ResourceTy->hasContainedType() &&
4520 "Expecting a contained type for resource with a dimension "
4522 QualType ReturnType = ResourceTy->getContainedType();
4525 IsCmp ?
"GatherCmp" :
"Gather"))
4530 S.
Diag(TheCall->
getBeginLoc(), diag::err_hlsl_samplecmp_requires_float);
4536 ReturnType = VecTy->getElementType();
4549 [](
const HLSLAttributedResourceType *ResType) {
4550 return ResType->getAttrs().ResourceDimension ==
4551 llvm::dxil::ResourceDimension::Unknown;
4561 ResourceTy->getAttrs().ResourceClass == llvm::dxil::ResourceClass::UAV;
4568 unsigned ResourceDim =
4570 unsigned LocationDim = ResourceDim + (ResourceTy->getAttrs().IsArray ? 1 : 0);
4586 TheCall->
setType(ResourceTy->getContainedType());
4596 [](
const HLSLAttributedResourceType *ResType) {
4597 return !ResType->isMultiSampled();
4606 unsigned ResourceDim =
4608 unsigned LocationDim = ResourceDim + (ResourceTy->getAttrs().IsArray ? 1 : 0);
4626 TheCall->
setType(ResourceTy->getContainedType());
4631 unsigned MinArgs, MaxArgs;
4659 const HLSLAttributedResourceType *ResourceTy =
4661 unsigned ExpectedDim =
4664 unsigned NextIdx = 3;
4689 &S, TheCall->
getArg(NextIdx),
4702 assert(ResourceTy->hasContainedType() &&
4703 "Expecting a contained type for resource with a dimension "
4705 QualType ReturnType = ResourceTy->getContainedType();
4716 S.
Diag(TheCall->
getBeginLoc(), diag::err_hlsl_samplecmp_requires_float);
4733 unsigned MinArgs,
unsigned MaxArgs,
4735 bool ReportsOriginalValue) {
4736 if (MinArgs == MaxArgs) {
4739 }
else if (TheCall->
getNumArgs() < MinArgs) {
4740 S.
Diag(TheCall->
getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4750 const bool DestIsOK =
4756 diag::err_builtin_invalid_arg_type)
4770 TI.
getTriple().getArch() == llvm::Triple::dxil &&
4786 for (
unsigned I = 1, E = TheCall->
getNumArgs(); I != E; ++I)
4792 const unsigned NumArgs = TheCall->
getNumArgs();
4793 if (ReportsOriginalValue && NumArgs == MaxArgs &&
4804 switch (BuiltinID) {
4805 case Builtin::BI__builtin_hlsl_barrier: {
4806 if (
SemaRef.checkArgCount(TheCall, 2))
4809 if (
SemaRef.Context.getTargetInfo().getTriple().getArch() !=
4810 llvm::Triple::dxil) {
4818 std::optional<llvm::APSInt> MemoryFlags =
4822 diag::err_constant_integer_arg_type)
4826 if ((MemoryFlags->getZExtValue() &
4827 ~barrierFlagValue(BarrierMemoryTypeFlag::ValidMask)) != 0) {
4829 diag::err_hlsl_invalid_barrier_memory_flags);
4833 const HLSLAttributedResourceType *ResTy =
4834 HLSLAttributedResourceType::findHandleTypeOnResource(
4838 diag::err_typecheck_expect_hlsl_resource)
4842 if (ResTy->getAttrs().ResourceClass != ResourceClass::UAV) {
4844 diag::err_invalid_hlsl_resource_type)
4851 std::optional<llvm::APSInt> SemanticFlags =
4853 if (!SemanticFlags) {
4855 diag::err_constant_integer_arg_type)
4859 if ((SemanticFlags->getZExtValue() &
4860 ~barrierFlagValue(BarrierSemanticFlag::ValidMask)) != 0) {
4862 diag::err_hlsl_invalid_barrier_semantic_flags);
4869 case Builtin::BI__builtin_hlsl_adduint64: {
4870 if (
SemaRef.checkArgCount(TheCall, 2))
4884 if (NumElementsArg != 2 && NumElementsArg != 4) {
4886 << 1 << 64 << NumElementsArg * 32;
4900 case Builtin::BI__builtin_hlsl_resource_getpointer: {
4901 if (
SemaRef.checkArgCountRange(TheCall, 1, 2) ||
4908 QualType ContainedTy = ResourceTy->getContainedType();
4909 auto ReturnType =
SemaRef.Context.getAddrSpaceQualType(
4912 ReturnType =
SemaRef.Context.getPointerType(ReturnType);
4917 case Builtin::BI__builtin_hlsl_resource_getpointer_typed: {
4918 if (
SemaRef.checkArgCount(TheCall, 3) ||
4925 "expected pointer type for second argument");
4932 diag::err_invalid_use_of_array_type);
4936 auto ReturnType =
SemaRef.Context.getAddrSpaceQualType(
4939 ReturnType =
SemaRef.Context.getPointerType(ReturnType);
4944 case Builtin::BI__builtin_hlsl_transpose_if_memory_is_row_major: {
4945 if (
SemaRef.checkArgCount(TheCall, 2) ||
4947 SemaRef.getASTContext().IntTy))
4954 case Builtin::BI__builtin_hlsl_resource_load_with_status: {
4955 if (
SemaRef.checkArgCount(TheCall, 3) ||
4958 SemaRef.getASTContext().UnsignedIntTy) ||
4960 SemaRef.getASTContext().UnsignedIntTy) ||
4966 QualType ReturnType = ResourceTy->getContainedType();
4971 case Builtin::BI__builtin_hlsl_resource_load_with_status_typed: {
4972 if (
SemaRef.checkArgCount(TheCall, 4) ||
4975 SemaRef.getASTContext().UnsignedIntTy) ||
4977 SemaRef.getASTContext().UnsignedIntTy) ||
4983 "expected pointer type for second argument");
4990 diag::err_invalid_use_of_array_type);
4996 case Builtin::BI__builtin_hlsl_resource_load_level:
4998 case Builtin::BI__builtin_hlsl_resource_load_ms:
5000 case Builtin::BI__builtin_hlsl_resource_sample:
5002 case Builtin::BI__builtin_hlsl_resource_sample_bias:
5004 case Builtin::BI__builtin_hlsl_resource_sample_grad:
5006 case Builtin::BI__builtin_hlsl_resource_sample_level:
5008 case Builtin::BI__builtin_hlsl_resource_sample_cmp:
5010 case Builtin::BI__builtin_hlsl_resource_sample_cmp_level_zero:
5012 case Builtin::BI__builtin_hlsl_resource_calculate_lod:
5013 case Builtin::BI__builtin_hlsl_resource_calculate_lod_unclamped:
5015 case Builtin::BI__builtin_hlsl_resource_gather:
5017 case Builtin::BI__builtin_hlsl_resource_gather_cmp:
5019 case Builtin::BI__builtin_hlsl_resource_uninitializedhandle: {
5020 assert(TheCall->
getNumArgs() == 1 &&
"expected 1 arg");
5026 case Builtin::BI__builtin_hlsl_resource_handlefrombinding: {
5027 assert(TheCall->
getNumArgs() == 6 &&
"expected 6 args");
5033 case Builtin::BI__builtin_hlsl_resource_handlefromimplicitbinding: {
5034 assert(TheCall->
getNumArgs() == 6 &&
"expected 6 args");
5040 case Builtin::BI__builtin_hlsl_resource_counterhandlefromimplicitbinding: {
5041 assert(TheCall->
getNumArgs() == 3 &&
"expected 3 args");
5047 TheCall->
setType(CounterHandleTy);
5050 case Builtin::BI__builtin_hlsl_resource_handlefromheap: {
5051 if (
SemaRef.checkArgCount(TheCall, 2) ||
5054 SemaRef.getASTContext().UnsignedIntTy))
5062 case Builtin::BI__builtin_hlsl_resource_counterhandlefromheap: {
5063 if (
SemaRef.checkArgCount(TheCall, 1) ||
5071 TheCall->
setType(CounterHandleTy);
5074 case Builtin::BI__builtin_hlsl_and:
5075 case Builtin::BI__builtin_hlsl_or: {
5076 if (
SemaRef.checkArgCount(TheCall, 2))
5090 case Builtin::BI__builtin_hlsl_asdouble: {
5091 if (
SemaRef.checkArgCount(TheCall, 2))
5095 SemaRef.Context.UnsignedIntTy,
5100 SemaRef.Context.UnsignedIntTy,
5109 case Builtin::BI__builtin_hlsl_elementwise_clamp: {
5110 if (
SemaRef.BuiltinElementwiseTernaryMath(
5116 case Builtin::BI__builtin_hlsl_dot: {
5118 if (
SemaRef.BuiltinVectorToScalarMath(TheCall))
5124 case Builtin::BI__builtin_hlsl_elementwise_firstbithigh:
5125 case Builtin::BI__builtin_hlsl_elementwise_firstbitlow: {
5126 if (
SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5136 EltTy = VecTy->getElementType();
5137 ResTy =
SemaRef.Context.getExtVectorType(ResTy, VecTy->getNumElements());
5150 case Builtin::BI__builtin_hlsl_select: {
5151 if (
SemaRef.checkArgCount(TheCall, 3))
5160 if (VTy && VTy->getElementType()->isBooleanType() &&
5164 if (MTy && MTy->getElementType()->isBooleanType() &&
5169 case Builtin::BI__builtin_hlsl_elementwise_saturate:
5170 case Builtin::BI__builtin_hlsl_elementwise_rcp: {
5171 if (
SemaRef.checkArgCount(TheCall, 1))
5177 diag::err_builtin_invalid_arg_type)
5180 if (
SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5184 case Builtin::BI__builtin_hlsl_elementwise_rsqrt:
5185 case Builtin::BI__builtin_hlsl_elementwise_frac:
5186 case Builtin::BI__builtin_hlsl_elementwise_ddx_coarse:
5187 case Builtin::BI__builtin_hlsl_elementwise_ddy_coarse:
5188 case Builtin::BI__builtin_hlsl_elementwise_ddx_fine:
5189 case Builtin::BI__builtin_hlsl_elementwise_ddy_fine: {
5190 if (
SemaRef.checkArgCount(TheCall, 1))
5195 if (
SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5199 case Builtin::BI__builtin_hlsl_elementwise_isfinite:
5200 case Builtin::BI__builtin_hlsl_elementwise_isinf:
5201 case Builtin::BI__builtin_hlsl_elementwise_isnan: {
5202 if (
SemaRef.checkArgCount(TheCall, 1))
5207 if (
SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5212 case Builtin::BI__builtin_hlsl_mad: {
5213 if (
SemaRef.BuiltinElementwiseTernaryMath(
5219 case Builtin::BI__builtin_hlsl_mul: {
5220 if (
SemaRef.checkArgCount(TheCall, 2))
5230 return VTy->getElementType();
5232 return MTy->getElementType();
5236 QualType EltTy0 = getElemType(Ty0);
5245 if (IsVec0 && IsMat1) {
5248 }
else if (IsMat0 && IsVec1) {
5252 assert(IsMat0 && IsMat1);
5262 case Builtin::BI__builtin_elementwise_fma: {
5263 if (
SemaRef.checkArgCount(TheCall, 3) ||
5278 case Builtin::BI__builtin_hlsl_transpose: {
5279 if (
SemaRef.checkArgCount(TheCall, 1))
5288 << 1 << 3 << 0 << 0 << ArgTy;
5293 MatTy->getElementType(), MatTy->getNumColumns(), MatTy->getNumRows());
5297 case Builtin::BI__builtin_hlsl_elementwise_sign: {
5298 if (
SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall))
5306 case Builtin::BI__builtin_hlsl_wave_active_all_equal: {
5307 if (
SemaRef.checkArgCount(TheCall, 1))
5321 unsigned NumElts = VecTy->getNumElements();
5331 case Builtin::BI__builtin_hlsl_wave_active_max:
5332 case Builtin::BI__builtin_hlsl_wave_active_min:
5333 case Builtin::BI__builtin_hlsl_wave_active_sum:
5334 case Builtin::BI__builtin_hlsl_wave_active_product: {
5335 if (
SemaRef.checkArgCount(TheCall, 1))
5348 case Builtin::BI__builtin_hlsl_wave_active_bit_or:
5349 case Builtin::BI__builtin_hlsl_wave_active_bit_xor:
5350 case Builtin::BI__builtin_hlsl_wave_active_bit_and: {
5351 if (
SemaRef.checkArgCount(TheCall, 1))
5366 (VTy && VTy->getElementType()->isIntegerType()))) {
5368 diag::err_builtin_invalid_arg_type)
5369 << ArgTyExpr <<
SemaRef.Context.UnsignedIntTy << 1 << 0 << 0;
5377 case Builtin::BI__builtin_hlsl_interlocked_add:
5378 case Builtin::BI__builtin_hlsl_interlocked_and:
5379 case Builtin::BI__builtin_hlsl_interlocked_max:
5380 case Builtin::BI__builtin_hlsl_interlocked_min:
5381 case Builtin::BI__builtin_hlsl_interlocked_or:
5382 case Builtin::BI__builtin_hlsl_interlocked_xor:
5388 case Builtin::BI__builtin_hlsl_interlocked_exchange:
5394 case Builtin::BI__builtin_hlsl_interlocked_compare_store:
5400 case Builtin::BI__builtin_hlsl_interlocked_compare_store_float_bitwise:
5406 case Builtin::BI__builtin_hlsl_interlocked_compare_exchange:
5412 case Builtin::BI__builtin_hlsl_interlocked_compare_exchange_float_bitwise:
5420 case Builtin::BI__builtin_elementwise_bitreverse: {
5428 case Builtin::BI__builtin_hlsl_wave_prefix_count_bits:
5429 case Builtin::BI__builtin_hlsl_wave_multi_prefix_count_bits: {
5430 bool IsMultiPrefix =
5431 BuiltinID == Builtin::BI__builtin_hlsl_wave_multi_prefix_count_bits;
5432 if (
SemaRef.checkArgCount(TheCall, IsMultiPrefix ? 2 : 1))
5437 if (!(
ArgType->isScalarType())) {
5439 diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
5444 if (!(
ArgType->isBooleanType())) {
5446 diag::err_typecheck_expect_any_scalar_or_vector_or_matrix)
5451 if (IsMultiPrefix) {
5459 diag::err_builtin_target_unsupported)
5467 case Builtin::BI__builtin_hlsl_wave_read_lane_at: {
5468 if (
SemaRef.checkArgCount(TheCall, 2))
5476 diag::err_typecheck_convert_incompatible)
5477 << ArgTyIndex <<
SemaRef.Context.UnsignedIntTy << 1 << 0 << 0;
5490 case Builtin::BI__builtin_hlsl_wave_read_lane_first: {
5491 if (
SemaRef.checkArgCount(TheCall, 1))
5500 case Builtin::BI__builtin_hlsl_wave_get_lane_index: {
5501 if (
SemaRef.checkArgCount(TheCall, 0))
5505 case Builtin::BI__builtin_hlsl_wave_prefix_sum:
5506 case Builtin::BI__builtin_hlsl_wave_prefix_product: {
5507 if (
SemaRef.checkArgCount(TheCall, 1))
5520 case Builtin::BI__builtin_hlsl_wave_multi_prefix_bit_and:
5521 case Builtin::BI__builtin_hlsl_wave_multi_prefix_bit_or:
5522 case Builtin::BI__builtin_hlsl_wave_multi_prefix_bit_xor:
5523 case Builtin::BI__builtin_hlsl_wave_multi_prefix_product:
5524 case Builtin::BI__builtin_hlsl_wave_multi_prefix_sum: {
5525 if (
SemaRef.checkArgCount(TheCall, 2))
5535 BuiltinID == Builtin::BI__builtin_hlsl_wave_multi_prefix_product ||
5536 BuiltinID == Builtin::BI__builtin_hlsl_wave_multi_prefix_sum;
5541 diag::err_builtin_invalid_arg_type)
5542 << 1 << (ValueTy->
isMatrixType() ? 3 : 5) << 1 << IsArithmetic
5553 case Builtin::BI__builtin_hlsl_quad_read_across_x:
5554 case Builtin::BI__builtin_hlsl_quad_read_across_y:
5555 case Builtin::BI__builtin_hlsl_quad_read_across_diagonal: {
5556 if (
SemaRef.checkArgCount(TheCall, 1))
5568 case Builtin::BI__builtin_hlsl_elementwise_splitdouble: {
5569 if (
SemaRef.checkArgCount(TheCall, 3))
5575 SemaRef.Context.UnsignedIntTy, 1) ||
5577 SemaRef.Context.UnsignedIntTy, 2))
5585 case Builtin::BI__builtin_hlsl_elementwise_clip: {
5586 if (
SemaRef.checkArgCount(TheCall, 1))
5593 case Builtin::BI__builtin_elementwise_acos:
5594 case Builtin::BI__builtin_elementwise_asin:
5595 case Builtin::BI__builtin_elementwise_atan:
5596 case Builtin::BI__builtin_elementwise_atan2:
5597 case Builtin::BI__builtin_elementwise_ceil:
5598 case Builtin::BI__builtin_elementwise_cos:
5599 case Builtin::BI__builtin_elementwise_cosh:
5600 case Builtin::BI__builtin_elementwise_exp:
5601 case Builtin::BI__builtin_elementwise_exp2:
5602 case Builtin::BI__builtin_elementwise_exp10:
5603 case Builtin::BI__builtin_elementwise_floor:
5604 case Builtin::BI__builtin_elementwise_fmod:
5605 case Builtin::BI__builtin_elementwise_log:
5606 case Builtin::BI__builtin_elementwise_log2:
5607 case Builtin::BI__builtin_elementwise_log10:
5608 case Builtin::BI__builtin_elementwise_pow:
5609 case Builtin::BI__builtin_elementwise_roundeven:
5610 case Builtin::BI__builtin_elementwise_sin:
5611 case Builtin::BI__builtin_elementwise_sinh:
5612 case Builtin::BI__builtin_elementwise_sqrt:
5613 case Builtin::BI__builtin_elementwise_tan:
5614 case Builtin::BI__builtin_elementwise_tanh:
5615 case Builtin::BI__builtin_elementwise_trunc: {
5621 case Builtin::BI__builtin_hlsl_buffer_update_counter: {
5622 assert(TheCall->
getNumArgs() == 2 &&
"expected 2 args");
5623 auto checkResTy = [](
const HLSLAttributedResourceType *ResTy) ->
bool {
5624 return !(ResTy->getAttrs().ResourceClass == ResourceClass::UAV &&
5625 ResTy->getAttrs().RawBuffer && ResTy->hasContainedType());
5630 std::optional<llvm::APSInt> Offset =
5632 if (!Offset.has_value() ||
std::abs(Offset->getExtValue()) != 1) {
5634 diag::err_hlsl_expect_arg_const_int_one_or_neg_one)
5640 case Builtin::BI__builtin_hlsl_elementwise_f16tof32: {
5641 if (
SemaRef.checkArgCount(TheCall, 1))
5652 ArgTy = VTy->getElementType();
5655 diag::err_builtin_invalid_arg_type)
5664 case Builtin::BI__builtin_hlsl_elementwise_f32tof16: {
5665 if (
SemaRef.checkArgCount(TheCall, 1))
5680 WorkList.push_back(BaseTy);
5681 while (!WorkList.empty()) {
5683 T =
T.getCanonicalType().getUnqualifiedType();
5684 if (
const auto *AT = dyn_cast<ConstantArrayType>(
T)) {
5692 for (
uint64_t Ct = 0; Ct < AT->getZExtSize(); ++Ct)
5693 llvm::append_range(List, ElementFields);
5698 if (
const auto *VT = dyn_cast<VectorType>(
T)) {
5699 List.insert(List.end(), VT->getNumElements(), VT->getElementType());
5702 if (
const auto *MT = dyn_cast<ConstantMatrixType>(
T)) {
5703 List.insert(List.end(), MT->getNumElementsFlattened(),
5704 MT->getElementType());
5707 if (
const auto *RD =
T->getAsCXXRecordDecl()) {
5708 if (RD->isStandardLayout())
5709 RD = RD->getStandardLayoutBaseWithFields();
5713 if (RD->
isUnion() || !RD->isAggregate()) {
5719 for (
const auto *FD : RD->
fields())
5720 if (!FD->isUnnamedBitField())
5721 FieldTypes.push_back(FD->
getType());
5723 std::reverse(FieldTypes.begin(), FieldTypes.end());
5724 llvm::append_range(WorkList, FieldTypes);
5728 if (!RD->isStandardLayout()) {
5730 for (
const auto &
Base : RD->bases())
5731 FieldTypes.push_back(
Base.getType());
5732 std::reverse(FieldTypes.begin(), FieldTypes.end());
5733 llvm::append_range(WorkList, FieldTypes);
5768 if (
SemaRef.Context.getTypeSize(QT) / 8 > 16)
5774 int ArraySize = VT->getNumElements();
5779 QualType ElTy = VT->getElementType();
5783 if (
SemaRef.Context.getTypeSize(QT) / 8 > 16)
5799 if (
SemaRef.getASTContext().hasSameType(T1, T2))
5808 return llvm::equal(T1Types, T2Types,
5810 return SemaRef.IsLayoutCompatible(LHS, RHS);
5819 bool HadError =
false;
5821 for (
unsigned i = 0, e =
New->getNumParams(); i != e; ++i) {
5829 const auto *NDAttr = NewParam->
getAttr<HLSLParamModifierAttr>();
5830 unsigned NSpellingIdx = (NDAttr ? NDAttr->getSpellingListIndex() : 0);
5831 const auto *ODAttr = OldParam->
getAttr<HLSLParamModifierAttr>();
5832 unsigned OSpellingIdx = (ODAttr ? ODAttr->getSpellingListIndex() : 0);
5834 if (NSpellingIdx != OSpellingIdx) {
5836 diag::err_hlsl_param_qualifier_mismatch)
5837 << NDAttr << NewParam;
5853 if (
SemaRef.getASTContext().hasSameUnqualifiedType(SrcTy, DestTy))
5868 llvm_unreachable(
"HLSL doesn't support pointers.");
5871 llvm_unreachable(
"HLSL doesn't support complex types.");
5873 llvm_unreachable(
"HLSL doesn't support fixed point types.");
5875 llvm_unreachable(
"Should have returned before this");
5885 llvm_unreachable(
"HLSL doesn't support complex types.");
5887 llvm_unreachable(
"HLSL doesn't support fixed point types.");
5892 llvm_unreachable(
"HLSL doesn't support pointers.");
5894 llvm_unreachable(
"Should have returned before this");
5900 llvm_unreachable(
"HLSL doesn't support pointers.");
5903 llvm_unreachable(
"HLSL doesn't support fixed point types.");
5907 llvm_unreachable(
"HLSL doesn't support complex types.");
5910 llvm_unreachable(
"Unhandled scalar cast");
5931 !(SrcMatTy && SrcMatTy->getNumElementsFlattened() == 1))
5937 SrcTy = SrcMatTy->getElementType();
5942 for (
unsigned I = 0, Size = DestTypes.size(); I < Size; ++I) {
5943 if (DestTypes[I]->isUnionType())
5975 if (SrcTypes.size() < DestTypes.size())
5978 unsigned SrcSize = SrcTypes.size();
5979 unsigned DstSize = DestTypes.size();
5981 for (I = 0; I < DstSize && I < SrcSize; I++) {
5982 if (SrcTypes[I]->isUnionType() || DestTypes[I]->isUnionType())
5990 for (; I < SrcSize; I++) {
5991 if (SrcTypes[I]->isUnionType())
6034 tok::equal, ArgOpV, OpV);
6046 assert(Param->hasAttr<HLSLParamModifierAttr>() &&
6047 "We should not get here without a parameter modifier expression");
6048 const auto *
Attr = Param->getAttr<HLSLParamModifierAttr>();
6055 << Arg << (IsInOut ? 1 : 0);
6059 QualType Ty = Param->getType().getNonLValueExprType(Ctx);
6066 << Arg << (IsInOut ? 1 : 0);
6074 Param->getBeginLoc(), IsInOut);
6082 "Pointer and reference types cannot be inout or out parameters");
6083 Ty =
SemaRef.getASTContext().getLValueReferenceType(Ty);
6099 for (
const auto *FD : RD->
fields()) {
6103 assert(RD->getNumBases() <= 1 &&
6104 "HLSL doesn't support multiple inheritance");
6105 return RD->getNumBases()
6110 if (
const auto *AT = dyn_cast<ArrayType>(Ty)) {
6111 if (
const auto *CAT = dyn_cast<ConstantArrayType>(AT))
6123 bool IsVKPushConstant = IsVulkan && VD->
hasAttr<HLSLVkPushConstantAttr>();
6128 !VD->
hasAttr<HLSLVkConstantIdAttr>() && !IsVKPushConstant &&
6134 if (
Decl->getType().hasAddressSpace())
6137 if (
Decl->getType()->isDependentType())
6149 if (
Decl->
hasAttr<HLSLVkExtBuiltinOutputAttr>()) {
6163 llvm::Triple::Vulkan;
6164 if (IsVulkan &&
Decl->
hasAttr<HLSLVkPushConstantAttr>()) {
6165 if (HasDeclaredAPushConstant)
6171 HasDeclaredAPushConstant =
true;
6198class StructBindingContext {
6201 HLSLResourceBindingAttr *RegBindingsAttrs[4];
6202 unsigned RegBindingOffset[4];
6205 static_assert(
static_cast<unsigned>(RegisterType::SRV) == 0 &&
6206 static_cast<unsigned>(RegisterType::UAV) == 1 &&
6207 static_cast<unsigned>(RegisterType::CBuffer) == 2 &&
6208 static_cast<unsigned>(RegisterType::Sampler) == 3,
6209 "unexpected register type values");
6212 HLSLVkBindingAttr *VkBindingAttr;
6213 unsigned VkBindingOffset;
6218 StructBindingContext(
VarDecl *VD) {
6219 for (
unsigned i = 0; i < 4; ++i) {
6220 RegBindingsAttrs[i] =
nullptr;
6221 RegBindingOffset[i] = 0;
6223 VkBindingAttr =
nullptr;
6224 VkBindingOffset = 0;
6230 if (
auto *RBA = dyn_cast<HLSLResourceBindingAttr>(A)) {
6232 unsigned RegTypeIdx =
static_cast<unsigned>(RegType);
6235 RegBindingsAttrs[RegTypeIdx] = RBA;
6240 if (
auto *VBA = dyn_cast<HLSLVkBindingAttr>(A))
6241 VkBindingAttr = VBA;
6248 Attr *createBindingAttr(SemaHLSL &S, ASTContext &AST,
RegisterType RegType,
6249 unsigned Range,
bool HasCounter) {
6250 assert(
static_cast<unsigned>(RegType) < 4 &&
"unexpected register type");
6252 if (VkBindingAttr) {
6253 unsigned Offset = VkBindingOffset;
6254 VkBindingOffset +=
Range;
6255 return HLSLVkBindingAttr::CreateImplicit(
6256 AST, VkBindingAttr->getBinding() + Offset, VkBindingAttr->getSet(),
6257 VkBindingAttr->getRange());
6260 HLSLResourceBindingAttr *RBA =
6261 RegBindingsAttrs[
static_cast<unsigned>(RegType)];
6262 HLSLResourceBindingAttr *NewAttr =
nullptr;
6264 if (RBA && RBA->hasRegisterSlot()) {
6267 unsigned Offset = RegBindingOffset[
static_cast<unsigned>(RegType)];
6268 RegBindingOffset[
static_cast<unsigned>(RegType)] += Range;
6270 unsigned NewSlotNumber = RBA->getSlotNumber() + Offset;
6271 StringRef NewSlotNumberStr =
6273 NewAttr = HLSLResourceBindingAttr::CreateImplicit(
6274 AST, NewSlotNumberStr, RBA->getSpace(), RBA->getRange());
6275 NewAttr->setBinding(RegType, NewSlotNumber, RBA->getSpaceNumber());
6279 NewAttr = HLSLResourceBindingAttr::CreateImplicit(AST,
"",
"0", {});
6280 NewAttr->setBinding(RegType, std::nullopt,
6281 RBA ? RBA->getSpaceNumber() : 0);
6285 NewAttr->setImplicitCounterBindingOrderID(
6294static void createGlobalResourceDeclForStruct(
6296 QualType ResTy, StructBindingContext &BindingCtx) {
6298 "expected resource type or array of resources");
6309 while (
const auto *AT = dyn_cast<ArrayType>(SingleResTy)) {
6310 const auto *CAT = dyn_cast<ConstantArrayType>(AT);
6315 const HLSLAttributedResourceType *ResHandleTy =
6316 HLSLAttributedResourceType::findHandleTypeOnResource(SingleResTy);
6320 Attr *BindingAttr = BindingCtx.createBindingAttr(
6322 ResDecl->
addAttr(BindingAttr);
6323 ResDecl->
addAttr(InternalLinkageAttr::CreateImplicit(AST));
6332 HLSLAssociatedResourceDeclAttr::CreateImplicit(AST, ResDecl));
6339static void handleArrayOfStructWithResources(
6341 EmbeddedResourceNameBuilder &NameBuilder, StructBindingContext &BindingCtx);
6346static void handleStructWithResources(
Sema &S,
VarDecl *ParentVD,
6348 EmbeddedResourceNameBuilder &NameBuilder,
6349 StructBindingContext &BindingCtx) {
6352 assert(RD->
getNumBases() <= 1 &&
"HLSL doesn't support multiple inheritance");
6359 handleStructWithResources(S, ParentVD, BaseRD, NameBuilder, BindingCtx);
6373 createGlobalResourceDeclForStruct(S, ParentVD, FD->
getLocation(), II,
6376 handleStructWithResources(S, ParentVD, RD, NameBuilder, BindingCtx);
6378 }
else if (
const auto *ArrayTy = dyn_cast<ConstantArrayType>(FDTy)) {
6380 "resource arrays should have been already handled");
6381 handleArrayOfStructWithResources(S, ParentVD, ArrayTy, NameBuilder,
6390handleArrayOfStructWithResources(
Sema &S,
VarDecl *ParentVD,
6392 EmbeddedResourceNameBuilder &NameBuilder,
6393 StructBindingContext &BindingCtx) {
6401 if (!SubCAT && !ElementRD)
6404 for (
unsigned I = 0, E = CAT->
getSize().getZExtValue(); I < E; ++I) {
6407 handleStructWithResources(S, ParentVD, ElementRD, NameBuilder,
6410 handleArrayOfStructWithResources(S, ParentVD, SubCAT, NameBuilder,
6423void SemaHLSL::handleGlobalStructOrArrayOfWithResources(
VarDecl *VD) {
6424 EmbeddedResourceNameBuilder NameBuilder(VD->
getName());
6425 StructBindingContext BindingCtx(VD);
6429 "Expected non-resource struct or array type");
6432 handleStructWithResources(
SemaRef, VD, RD, NameBuilder, BindingCtx);
6436 if (
const auto *CAT = dyn_cast<ConstantArrayType>(VDTy)) {
6437 handleArrayOfStructWithResources(
SemaRef, VD, CAT, NameBuilder, BindingCtx);
6445 if (
SemaRef.RequireCompleteType(
6448 diag::err_typecheck_decl_incomplete_type)) {
6462 DefaultCBufferDecls.push_back(VD);
6467 collectResourceBindingsOnVarDecl(VD);
6469 if (VD->
hasAttr<HLSLVkConstantIdAttr>())
6481 processExplicitBindingsOnDecl(VD);
6518 handleGlobalStructOrArrayOfWithResources(VD);
6522 if (VD->
hasAttr<HLSLGroupSharedAddressSpaceAttr>())
6531 "expected resource record type");
6547 const char *CreateMethodName;
6549 CreateMethodName = HasCounter ?
"__createFromBindingWithImplicitCounter"
6550 :
"__createFromBinding";
6552 CreateMethodName = HasCounter
6553 ?
"__createFromImplicitBindingWithImplicitCounter"
6554 :
"__createFromImplicitBinding";
6559 if (!CreateMethod) {
6564 "create method lookup should always succeed for built-in resource "
6573 Args.push_back(RegSlot);
6581 Args.push_back(OrderId);
6587 Args.push_back(Space);
6591 Args.push_back(RangeSize);
6595 Args.push_back(Index);
6597 StringRef VarName = VD->
getName();
6605 Args.push_back(NameCast);
6613 Args.push_back(CounterId);
6636 SemaRef.CheckCompleteVariableDeclaration(VD);
6642 "expected array of resource records");
6663 lookupMethod(
SemaRef, ResourceDecl,
6664 HasCounter ?
"__createFromBindingWithImplicitCounter"
6665 :
"__createFromBinding",
6669 CreateMethod = lookupMethod(
6671 HasCounter ?
"__createFromImplicitBindingWithImplicitCounter"
6672 :
"__createFromImplicitBinding",
6715std::optional<const DeclBindingInfo *> SemaHLSL::inferGlobalBinding(
Expr *E) {
6716 if (
auto *Ternary = dyn_cast<ConditionalOperator>(E)) {
6717 auto TrueInfo = inferGlobalBinding(Ternary->getTrueExpr());
6718 auto FalseInfo = inferGlobalBinding(Ternary->getFalseExpr());
6719 if (!TrueInfo || !FalseInfo)
6720 return std::nullopt;
6721 if (*TrueInfo != *FalseInfo)
6722 return std::nullopt;
6726 if (
auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
6735 if (
const auto *AttrResType =
6736 HLSLAttributedResourceType::findHandleTypeOnResource(Ty)) {
6738 return Bindings.getDeclBindingInfo(VD, RC);
6745void SemaHLSL::trackLocalResource(
VarDecl *VD,
Expr *E) {
6746 std::optional<const DeclBindingInfo *> ExprBinding = inferGlobalBinding(E);
6749 diag::warn_hlsl_assigning_local_resource_is_not_unique)
6754 if (*ExprBinding ==
nullptr)
6757 auto PrevBinding = Assigns.find(VD);
6758 if (PrevBinding == Assigns.end()) {
6760 Assigns.insert({VD, *ExprBinding});
6765 if (*ExprBinding != PrevBinding->second) {
6767 diag::warn_hlsl_assigning_local_resource_is_not_unique)
6769 SemaRef.Diag(VD->getLocation(), diag::note_var_declared_here) << VD;
6780 "expected LHS to be a resource record or array of resource records");
6781 if (Opc != BO_Assign)
6786 while (
auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
6794 SemaRef.Diag(Loc, diag::err_hlsl_assign_to_global_resource) << VD;
6799 trackLocalResource(VD, RHSExpr);
6816void SemaHLSL::collectResourceBindingsOnVarDecl(
VarDecl *VD) {
6818 "expected global variable that contains HLSL resource");
6821 if (
const HLSLBufferDecl *CBufferOrTBuffer = dyn_cast<HLSLBufferDecl>(VD)) {
6822 Bindings.addDeclBindingInfo(VD, CBufferOrTBuffer->isCBuffer()
6823 ? ResourceClass::CBuffer
6824 : ResourceClass::SRV);
6837 if (
const HLSLAttributedResourceType *AttrResType =
6838 HLSLAttributedResourceType::findHandleTypeOnResource(Ty)) {
6839 Bindings.addDeclBindingInfo(VD, AttrResType->getAttrs().ResourceClass);
6844 if (
const RecordType *RT = dyn_cast<RecordType>(Ty))
6845 collectResourceBindingsOnUserRecordDecl(VD, RT);
6851void SemaHLSL::processExplicitBindingsOnDecl(
VarDecl *VD) {
6854 bool HasBinding =
false;
6855 for (Attr *A : VD->
attrs()) {
6858 if (
auto PA = VD->
getAttr<HLSLVkPushConstantAttr>())
6859 Diag(PA->getLoc(), diag::err_hlsl_attr_incompatible) << A << PA;
6862 HLSLResourceBindingAttr *RBA = dyn_cast<HLSLResourceBindingAttr>(A);
6863 if (!RBA || !RBA->hasRegisterSlot())
6868 assert(RT != RegisterType::I &&
"invalid or obsolete register type should "
6869 "never have an attribute created");
6871 if (RT == RegisterType::C) {
6872 if (Bindings.hasBindingInfoForDecl(VD))
6874 diag::warn_hlsl_user_defined_type_missing_member)
6875 <<
static_cast<int>(RT);
6883 if (DeclBindingInfo *BI = Bindings.getDeclBindingInfo(VD, RC)) {
6888 diag::warn_hlsl_user_defined_type_missing_member)
6889 <<
static_cast<int>(RT);
6897class InitListTransformer {
6901 QualType *DstIt =
nullptr;
6902 Expr **ArgIt =
nullptr;
6908 bool castInitializer(Expr *E) {
6909 assert(DstIt &&
"This should always be something!");
6910 if (DstIt == DestTypes.end()) {
6912 ArgExprs.push_back(E);
6917 DstIt = DestTypes.begin();
6920 Ctx, *DstIt,
false);
6925 ArgExprs.push_back(
Init);
6930 bool buildInitializerListImpl(Expr *E) {
6932 if (
auto *
Init = dyn_cast<InitListExpr>(E)) {
6933 for (
auto *SubInit :
Init->inits())
6934 if (!buildInitializerListImpl(SubInit))
6944 return castInitializer(E);
6958 if (
auto *VecTy = Ty->
getAs<VectorType>()) {
6965 SizeTy, SourceLocation());
6971 if (!castInitializer(ElExpr.
get()))
6976 if (
auto *MTy = Ty->
getAs<ConstantMatrixType>()) {
6977 unsigned Rows = MTy->getNumRows();
6978 unsigned Cols = MTy->getNumColumns();
6979 QualType ElemTy = MTy->getElementType();
6981 for (
unsigned R = 0;
R < Rows; ++
R) {
6982 for (
unsigned C = 0;
C < Cols; ++
C) {
6995 if (!castInitializer(ElExpr.
get()))
7003 if (
auto *ArrTy = dyn_cast<ConstantArrayType>(Ty.
getTypePtr())) {
7009 SizeTy, SourceLocation());
7014 if (!buildInitializerListImpl(ElExpr.
get()))
7021 llvm::SmallVector<CXXRecordDecl *> RecordDecls;
7022 RecordDecls.push_back(RD);
7023 while (RecordDecls.back()->getNumBases()) {
7024 CXXRecordDecl *D = RecordDecls.back();
7026 "HLSL doesn't support multiple inheritance");
7027 RecordDecls.push_back(
7030 while (!RecordDecls.empty()) {
7031 CXXRecordDecl *RD = RecordDecls.pop_back_val();
7032 for (
auto *FD : RD->
fields()) {
7033 if (FD->isUnnamedBitField())
7041 if (!buildInitializerListImpl(Res.
get()))
7049 Expr *generateInitListsImpl(QualType Ty) {
7051 assert(ArgIt != ArgExprs.end() &&
"Something is off in iteration!");
7056 llvm::SmallVector<Expr *>
Inits;
7061 if (
auto *ATy = Ty->
getAs<VectorType>()) {
7062 ElTy = ATy->getElementType();
7063 Size = ATy->getNumElements();
7064 }
else if (
auto *CMTy = Ty->
getAs<ConstantMatrixType>()) {
7065 ElTy = CMTy->getElementType();
7066 Size = CMTy->getNumElementsFlattened();
7069 ElTy = VTy->getElementType();
7070 Size = VTy->getZExtSize();
7073 Inits.push_back(generateInitListsImpl(ElTy));
7076 llvm::SmallVector<CXXRecordDecl *> RecordDecls;
7077 RecordDecls.push_back(RD);
7078 while (RecordDecls.back()->getNumBases()) {
7079 CXXRecordDecl *D = RecordDecls.back();
7081 "HLSL doesn't support multiple inheritance");
7082 RecordDecls.push_back(
7085 while (!RecordDecls.empty()) {
7086 CXXRecordDecl *RD = RecordDecls.pop_back_val();
7087 for (
auto *FD : RD->
fields())
7088 if (!FD->isUnnamedBitField())
7093 new (Ctx) InitListExpr(Ctx,
Inits.front()->getBeginLoc(),
Inits,
7094 Inits.back()->getEndLoc(),
false);
7095 NewInit->setType(Ty);
7100 llvm::SmallVector<QualType, 16> DestTypes;
7101 llvm::SmallVector<Expr *, 16> ArgExprs;
7102 InitListTransformer(Sema &SemaRef,
const InitializedEntity &Entity)
7103 : S(SemaRef), Ctx(SemaRef.getASTContext()),
7104 Wrap(Entity.
getType()->isIncompleteArrayType()) {
7105 InitTy = Entity.
getType().getNonReferenceType();
7115 DstIt = DestTypes.begin();
7118 bool buildInitializerList(Expr *E) {
return buildInitializerListImpl(E); }
7120 Expr *generateInitLists() {
7121 assert(!ArgExprs.empty() &&
7122 "Call buildInitializerList to generate argument expressions.");
7123 ArgIt = ArgExprs.begin();
7125 return generateInitListsImpl(InitTy);
7126 llvm::SmallVector<Expr *>
Inits;
7127 while (ArgIt != ArgExprs.end())
7128 Inits.push_back(generateInitListsImpl(InitTy));
7131 new (Ctx) InitListExpr(Ctx,
Inits.front()->getBeginLoc(),
Inits,
7132 Inits.back()->getEndLoc(),
false);
7133 llvm::APInt ArySize(64,
Inits.size());
7135 ArraySizeModifier::Normal, 0));
7147 if (
const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
7154 if (
const auto *RT = Ty->
getAs<RecordType>()) {
7158 if (
const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7178 if (
Init->getType()->isScalarType())
7181 InitListTransformer ILT(
SemaRef, Entity);
7183 for (
unsigned I = 0; I <
Init->getNumInits(); ++I) {
7191 Init->setInit(I, E);
7193 if (!ILT.buildInitializerList(E))
7196 size_t ExpectedSize = ILT.DestTypes.size();
7197 size_t ActualSize = ILT.ArgExprs.size();
7198 if (ExpectedSize == 0 && ActualSize == 0)
7205 InitTy =
SemaRef.getASTContext().removeAddrSpaceQualType(InitTy);
7207 SemaRef.Diag(
Init->getBeginLoc(), diag::err_hlsl_incorrect_num_initializers)
7208 << (int)(ExpectedSize < ActualSize) << InitTy
7209 << ExpectedSize << ActualSize;
7219 assert(ExpectedSize > 0 &&
7220 "The expected size of an incomplete array type must be at least 1.");
7222 ((ActualSize + ExpectedSize - 1) / ExpectedSize) * ExpectedSize;
7230 InitTy =
SemaRef.getASTContext().removeAddrSpaceQualType(InitTy);
7231 if (ExpectedSize != ActualSize) {
7232 int TooManyOrFew = ActualSize > ExpectedSize ? 1 : 0;
7233 SemaRef.Diag(
Init->getBeginLoc(), diag::err_hlsl_incorrect_num_initializers)
7234 << TooManyOrFew << InitTy << ExpectedSize << ActualSize;
7241 Init->resizeInits(Ctx, NewInit->getNumInits());
7242 for (
unsigned I = 0; I < NewInit->getNumInits(); ++I)
7243 Init->updateInit(Ctx, I, NewInit->getInit(I));
7251 S.
Diag(OpLoc, diag::err_builtin_matrix_invalid_member)
7261 StringRef AccessorName = CompName->
getName();
7262 assert(!AccessorName.empty() &&
"Matrix Accessor must have a name");
7264 unsigned Rows = MT->getNumRows();
7265 unsigned Cols = MT->getNumColumns();
7266 bool IsZeroBasedAccessor =
false;
7267 unsigned ChunkLen = 0;
7268 if (AccessorName.size() < 2)
7270 "length 4 for zero based: \'_mRC\' or "
7271 "length 3 for one-based: \'_RC\' accessor",
7274 if (AccessorName[0] ==
'_') {
7275 if (AccessorName[1] ==
'm') {
7276 IsZeroBasedAccessor =
true;
7283 S, AccessorName,
"zero based: \'_mRC\' or one-based: \'_RC\' accessor",
7286 if (AccessorName.size() % ChunkLen != 0) {
7287 const llvm::StringRef
Expected = IsZeroBasedAccessor
7288 ?
"zero based: '_mRC' accessor"
7289 :
"one-based: '_RC' accessor";
7294 auto isDigit = [](
char c) {
return c >=
'0' && c <=
'9'; };
7295 auto isZeroBasedIndex = [](
unsigned i) {
return i <= 3; };
7296 auto isOneBasedIndex = [](
unsigned i) {
return i >= 1 && i <= 4; };
7298 bool HasRepeated =
false;
7300 unsigned NumComponents = 0;
7301 const char *Begin = AccessorName.data();
7303 for (
unsigned I = 0, E = AccessorName.size(); I < E; I += ChunkLen) {
7304 const char *Chunk = Begin + I;
7305 char RowChar = 0, ColChar = 0;
7306 if (IsZeroBasedAccessor) {
7308 if (Chunk[0] !=
'_' || Chunk[1] !=
'm') {
7309 char Bad = (Chunk[0] !=
'_') ? Chunk[0] : Chunk[1];
7311 S, StringRef(&Bad, 1),
"\'_m\' prefix",
7318 if (Chunk[0] !=
'_')
7320 S, StringRef(&Chunk[0], 1),
"\'_\' prefix",
7327 bool IsDigitsError =
false;
7329 unsigned BadPos = IsZeroBasedAccessor ? 2 : 1;
7333 IsDigitsError =
true;
7337 unsigned BadPos = IsZeroBasedAccessor ? 3 : 2;
7341 IsDigitsError =
true;
7346 unsigned Row = RowChar -
'0';
7347 unsigned Col = ColChar -
'0';
7349 bool HasIndexingError =
false;
7350 if (IsZeroBasedAccessor) {
7352 if (!isZeroBasedIndex(Row)) {
7353 S.
Diag(OpLoc, diag::err_hlsl_matrix_element_not_in_bounds)
7355 HasIndexingError =
true;
7357 if (!isZeroBasedIndex(Col)) {
7358 S.
Diag(OpLoc, diag::err_hlsl_matrix_element_not_in_bounds)
7360 HasIndexingError =
true;
7364 if (!isOneBasedIndex(Row)) {
7365 S.
Diag(OpLoc, diag::err_hlsl_matrix_element_not_in_bounds)
7367 HasIndexingError =
true;
7369 if (!isOneBasedIndex(Col)) {
7370 S.
Diag(OpLoc, diag::err_hlsl_matrix_element_not_in_bounds)
7372 HasIndexingError =
true;
7379 if (HasIndexingError)
7385 bool HasBoundsError =
false;
7387 Diag(OpLoc, diag::err_hlsl_matrix_index_out_of_bounds)
7389 HasBoundsError =
true;
7392 Diag(OpLoc, diag::err_hlsl_matrix_index_out_of_bounds)
7394 HasBoundsError =
true;
7399 unsigned FlatIndex = Row * Cols + Col;
7400 if (Seen[FlatIndex])
7402 Seen[FlatIndex] =
true;
7405 if (NumComponents == 0 || NumComponents > 4) {
7406 S.
Diag(OpLoc, diag::err_hlsl_matrix_swizzle_invalid_length)
7411 QualType ElemTy = MT->getElementType();
7412 if (NumComponents == 1)
7418 for (Sema::ExtVectorDeclsType::iterator
7422 if ((*I)->getUnderlyingType() == VT)
7433 trackLocalResource(VDecl,
Init);
7435 const HLSLVkConstantIdAttr *ConstIdAttr =
7436 VDecl->
getAttr<HLSLVkConstantIdAttr>();
7443 if (!
Init->isCXX11ConstantExpr(Context, InitValue)) {
7453 int ConstantID = ConstIdAttr->getId();
7454 llvm::APInt IDVal(Context.getIntWidth(Context.IntTy), ConstantID);
7456 ConstIdAttr->getLocation());
7460 if (
C->getType()->getCanonicalTypeUnqualified() !=
7464 Context.getTrivialTypeSourceInfo(
7465 Init->getType(),
Init->getExprLoc()),
7484 if (!Params || Params->
size() != 1)
7497 if (
auto *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
7498 if (TTP->hasDefaultArgument()) {
7499 TemplateArgs.
addArgument(TTP->getDefaultArgument());
7502 }
else if (
auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
7503 if (NTTP->hasDefaultArgument()) {
7504 TemplateArgs.
addArgument(NTTP->getDefaultArgument());
7507 }
else if (
auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(P)) {
7508 if (TTPD->hasDefaultArgument()) {
7509 TemplateArgs.
addArgument(TTPD->getDefaultArgument());
7516 return SemaRef.CheckTemplateIdType(
7518 TemplateArgs,
nullptr,
false);
Defines the clang::ASTContext interface.
static bool isBooleanType(QualType Ty)
Defines enum values for all the target-independent builtin functions.
llvm::dxil::ResourceClass ResourceClass
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines AST-level helper utilities for matrix types.
static StringRef getTriple(const Command &Job)
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static bool CheckArgTypeMatches(Sema *S, Expr *Arg, QualType ExpectedType)
static void BuildFlattenedTypeList(QualType BaseTy, llvm::SmallVectorImpl< QualType > &List)
static bool CheckUnsignedIntRepresentation(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
static bool containsIncompleteArrayType(QualType Ty)
static QualType handleIntegerVectorBinOpConversion(Sema &SemaRef, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, QualType LElTy, QualType RElTy, bool IsCompAssign)
static bool convertToRegisterType(StringRef Slot, RegisterType *RT)
static StringRef createRegisterString(ASTContext &AST, RegisterType RegType, unsigned N)
static bool CheckWaveActive(Sema *S, CallExpr *TheCall)
static void createHostLayoutStructForBuffer(Sema &S, HLSLBufferDecl *BufDecl)
static void castVector(Sema &S, ExprResult &E, QualType &Ty, unsigned Sz)
static QualType ReportMatrixInvalidMember(Sema &S, StringRef Name, StringRef Expected, SourceLocation OpLoc, SourceLocation CompLoc)
static bool CheckBoolSelect(Sema *S, CallExpr *TheCall)
static bool isIntUpTo32Element(const ASTContext &Ctx, QualType Elem)
static unsigned calculateLegacyCbufferFieldAlign(const ASTContext &Context, QualType T)
static bool CheckScalarFloatOperand(Sema &S, CallExpr *TheCall, unsigned ArgIndex)
static bool isVkPipelineBuiltin(const ASTContext &AstContext, FunctionDecl *FD, const DeclaratorDecl *D, HLSLAppliedSemanticAttr *Semantic, bool IsInput)
static bool isIntElementOfWidth(const ASTContext &Ctx, QualType Elem, uint64_t Width)
static bool isZeroSizedArray(const ConstantArrayType *CAT)
static bool DiagnoseHLSLRegisterAttribute(Sema &S, SourceLocation &ArgLoc, Decl *D, RegisterType RegType, bool SpecifiedSpace)
static bool CheckAnyScalarOrVectorOrMatrix(Sema *S, CallExpr *TheCall, unsigned ArgIndex)
static bool hasConstantBufferLayout(QualType QT)
llvm::dxbc::PSV::SemanticKind SemanticKind
static FieldDecl * createFieldForHostLayoutStruct(Sema &S, const Type *Ty, IdentifierInfo *II, CXXRecordDecl *LayoutStruct)
static bool CheckIntegerElementTypeShaderModel(Sema &S, CallExpr *TheCall, QualType ContainedType, SampleKind Kind)
static bool isMatrixType(QualType QT)
static bool CheckUnsignedIntVecRepresentation(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
static bool isInvalidConstantBufferLeafElementType(const Type *Ty)
static bool CheckCalculateLodBuiltin(Sema &S, CallExpr *TheCall)
static QualType getScalarComponentType(QualType T)
static Builtin::ID getSpecConstBuiltinId(const Type *Type)
static bool CheckNumericRepresentation(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
static bool CheckNoDoubleElementType(Sema &S, CallExpr *TheCall, QualType ContainedType, StringRef DefaultName)
static const Type * createHostLayoutType(Sema &S, const Type *Ty)
static bool CheckAnyScalarOrVector(Sema *S, CallExpr *TheCall, unsigned ArgIndex)
static bool CheckInterlockedBuiltin(Sema &S, CallExpr *TheCall, unsigned MinArgs, unsigned MaxArgs, InterlockedDest Dest, bool ReportsOriginalValue)
Check a call to an HLSL interlocked builtin.
static const HLSLAttributedResourceType * getResourceArrayHandleType(QualType QT)
static IdentifierInfo * getHostLayoutStructName(Sema &S, NamedDecl *BaseDecl, bool MustBeUnique)
static QualType createCounterHandleType(ASTContext &AST, QualType MainHandleTy)
static bool CheckMatrixSelect(Sema *S, CallExpr *TheCall)
static bool CheckArgAddrSpaceOneOf(Sema *S, CallExpr *TheCall, unsigned ArgIndex, ArrayRef< LangAS > AllowedSpaces)
static void addImplicitBindingAttrToDecl(Sema &S, Decl *D, RegisterType RT, uint32_t ImplicitBindingOrderID)
static StringRef getSampleMethodName(SampleKind Kind)
static void SetElementTypeAsReturnType(Sema *S, CallExpr *TheCall, QualType ReturnType)
static unsigned calculateLegacyCbufferSize(const ASTContext &Context, QualType T)
static bool CheckLoadLevelBuiltin(Sema &S, CallExpr *TheCall)
static RegisterType getRegisterType(ResourceClass RC)
static bool ValidateRegisterNumber(uint64_t SlotNum, Decl *TheDecl, ASTContext &Ctx, RegisterType RegTy)
static bool CheckModifiableLValue(Sema *S, CallExpr *TheCall, unsigned ArgIndex)
static QualType castElement(Sema &S, ExprResult &E, QualType Ty)
static char getRegisterTypeChar(RegisterType RT)
static bool CheckNotBoolScalarOrVector(Sema *S, CallExpr *TheCall, unsigned ArgIndex)
static bool findExistingMatrixLayoutMarker(QualType T, attr::Kind &ExistingKind)
Walks the existing AttributedType sugar of T looking for a previously applied HLSLRowMajor/HLSLColumn...
static CXXRecordDecl * findRecordDeclInContext(IdentifierInfo *II, DeclContext *DC)
static bool CheckWavePrefix(Sema *S, CallExpr *TheCall)
static bool CheckExpectedBitWidth(Sema *S, CallExpr *TheCall, unsigned ArgOrdinal, unsigned Width)
static LangAS getLangASFromResourceClass(ResourceClass RC)
static bool CheckTextureSamplerAndLocation(Sema &S, CallExpr *TheCall, bool IncludeArraySlice=true)
static bool CheckVectorSelect(Sema *S, CallExpr *TheCall)
static void validateVkBuiltinUsage(Sema &S, FunctionDecl *FD, const DeclaratorDecl *D, const HLSLVkBuiltInAttr *Attr, IOType CurrentIOType)
static QualType handleFloatVectorBinOpConversion(Sema &SemaRef, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, QualType LElTy, QualType RElTy, bool IsCompAssign)
static const Type * getHostLayoutFieldType(QualType QT)
InterlockedDest
The dest types an interlocked operation accepts. Float is 32-bit only.
static unsigned getComponentCountOf(QualType T)
static ResourceClass getResourceClass(RegisterType RT)
static CXXRecordDecl * createHostLayoutStruct(Sema &S, CXXRecordDecl *StructDecl)
static bool CheckScalarOrVector(Sema *S, CallExpr *TheCall, QualType Scalar, unsigned ArgIndex)
static QualType getVectorOrScalarType(Sema &S, QualType BaseType, unsigned Count)
static bool CheckSamplingBuiltin(Sema &S, CallExpr *TheCall, SampleKind Kind)
static bool CheckScalarOrVectorOrMatrix(Sema *S, CallExpr *TheCall, QualType Scalar, unsigned ArgIndex)
static bool CheckFloatRepresentation(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
static bool CheckAnyDoubleRepresentation(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
static bool requiresImplicitBufferLayoutStructure(const CXXRecordDecl *RD)
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)
static StringRef getCurrentResourceMethodName(Sema &S, StringRef DefaultName)
static bool IsDefaultBufferConstantDecl(const ASTContext &Ctx, VarDecl *VD)
HLSLResourceBindingAttr::RegisterType RegisterType
static CastKind getScalarCastKind(ASTContext &Ctx, QualType DestTy, QualType SrcTy)
static bool CheckGatherBuiltin(Sema &S, CallExpr *TheCall, bool IsCmp)
static QualType getElementTypeOf(QualType T, bool IncludeMatrix)
static bool isValidWaveSizeValue(unsigned Value)
static bool isResourceRecordTypeOrArrayOf(QualType Ty)
static bool CheckLoadMSBuiltin(Sema &S, CallExpr *TheCall)
static bool AccumulateHLSLResourceSlots(QualType Ty, uint64_t &StartSlot, const uint64_t &Limit, const ResourceClass ResClass, ASTContext &Ctx, uint64_t ArrayCount=1)
static bool CheckNoDoubleVectors(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
static bool ValidateMultipleRegisterAnnotations(Sema &S, Decl *TheDecl, RegisterType regType)
static bool CheckWaveMultiPrefixMask(Sema *S, CallExpr *TheCall)
static bool DiagnoseLocalRegisterBinding(Sema &S, SourceLocation &ArgLoc, Decl *D, RegisterType RegType, bool SpecifiedSpace)
static bool CheckIndexType(Sema *S, CallExpr *TheCall, unsigned IndexArgIndex)
static bool isFloatOrHalfElement(QualType Elem)
This file declares semantic analysis for HLSL constructs.
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
C Language Family Type Representation.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
static const TypeInfo & getInfo(unsigned id)
return(__x > > __y)|(__x<<(32 - __y))
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
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 ...
const ConstantArrayType * getAsConstantArrayType(QualType T) const
unsigned getIntWidth(QualType T) const
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns, std::optional< MatrixType::LayoutKind > Layout=std::nullopt) const
Return the unique reference to the matrix type of the specified element type and size.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
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
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
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.
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.
static uint64_t getConstantArrayElementCount(const ConstantArrayType *CA)
Return number of (potentially nested) constant array elements.
llvm::StringRef backupStr(llvm::StringRef S) const
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
QualType getCorrespondingUnsignedType(QualType T) const
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType getCanonicalTagType(const TagDecl *TD) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
QualType getElementType() const
Attr - This represents one attribute.
attr::Kind getKind() const
SourceLocation getLocation() const
SourceLocation getScopeLoc() const
SourceRange getRange() const
const IdentifierInfo * getScopeName() const
bool isRegularKeywordAttribute() const
SourceLocation getLoc() const
const IdentifierInfo * getAttrName() const
Represents a base class of a C++ class.
QualType getType() const
Retrieves the type of the base class.
Represents a static or instance method of a struct/union/class.
Represents a C++ struct/union/class.
bool isHLSLIntangible() const
Returns true if the class contains HLSL intangible type, either as a field or in base class.
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
void setBases(CXXBaseSpecifier const *const *Bases, unsigned NumBases)
Sets the base classes of this struct or class.
base_class_iterator bases_end()
void completeDefinition() override
Indicates that the definition of this class is now complete.
unsigned getNumBases() const
Retrieves the number of base classes of this class.
bool isHLSLBuiltinRecord() const
Returns true if the class is a built-in HLSL record.
base_class_iterator bases_begin()
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
SourceLocation getBeginLoc() const
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.
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
SourceLocation getEndLoc() const
static CanQual< Type > CreateUnsafe(QualType Other)
QualType withConst() const
Retrieves a version of this type with const applied.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Represents the canonical version of C arrays with a specified constant size.
bool isZeroSize() const
Return true if the size is zero.
llvm::APInt getSize() const
Return the constant array size as an APInt.
Represents a concrete matrix type with constant number of rows and columns.
unsigned getNumColumns() const
Returns the number of columns in the matrix.
unsigned getNumRows() const
Returns the number of rows in the matrix.
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...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isTranslationUnit() const
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.
DeclContext * getNonTransparentContext()
A reference to a declared variable, function, enum, etc.
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)
Decl - This represents one declaration (or definition), e.g.
ASTContext & getASTContext() const LLVM_READONLY
attr_iterator attr_end() const
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
attr_iterator attr_begin() const
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
bool isInvalidDecl() const
SourceLocation getLocation() const
void setImplicit(bool I=true)
DeclContext * getDeclContext()
AccessSpecifier getAccess() const
SourceLocation getBeginLoc() const LLVM_READONLY
The name of a declaration.
Represents a ValueDecl that came out of a declarator.
SourceLocation getBeginLoc() const LLVM_READONLY
This represents one expression.
bool isIntegerConstantExpr(const ASTContext &Ctx) const
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Expr * IgnoreCasts() LLVM_READONLY
Skip past any casts which might surround this expression until reaching a fixed point.
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
ExtVectorType - Extended vector type.
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
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)
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Represents a function declaration or definition.
const ParmVarDecl * getParamDecl(unsigned i) const
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
QualType getReturnType() const
ArrayRef< ParmVarDecl * > parameters() const
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
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.
DeclarationNameInfo getNameInfo() const
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
static HLSLBufferDecl * Create(ASTContext &C, DeclContext *LexicalParent, bool CBuffer, SourceLocation KwLoc, IdentifierInfo *ID, SourceLocation IDLoc, SourceLocation LBrace)
void addLayoutStruct(CXXRecordDecl *LS)
void setHasValidPackoffset(bool PO)
static HLSLBufferDecl * CreateDefaultCBuffer(ASTContext &C, DeclContext *LexicalParent, ArrayRef< Decl * > DefaultCBufferDecls)
buffer_decl_range buffer_decls() const
static HLSLOutArgExpr * Create(const ASTContext &C, QualType Ty, OpaqueValueExpr *Base, OpaqueValueExpr *OpV, Expr *WB, bool IsInOut)
static HLSLRootSignatureDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, IdentifierInfo *ID, llvm::dxbc::RootSignatureVersion Version, ArrayRef< llvm::hlsl::rootsig::RootElement > RootElements)
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 ...
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Describes an C or C++ initializer list.
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'.
iterator begin(ExternalSemaSource *source, bool LocalOnly=false)
Represents the results of name lookup.
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Represents a matrix type, as defined in the Matrix Types clang extensions.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
This represents a decl that may have a name.
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
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.
Represents a parameter to a function.
ParsedAttr - Represents a syntactic attribute.
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
bool hasParsedType() const
void setInvalid(bool b=true) const
const ParsedType & getTypeArg() const
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
bool isArgIdent(unsigned Arg) const
Expr * getArgAsExpr(unsigned Arg) const
AttributeCommonInfo::Kind getKind() const
A (possibly-)qualified type.
void addRestrict()
Add the restrict qualifier to this QualType.
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
LangAS getAddressSpace() const
Return the address space of this type.
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
QualType getCanonicalType() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Represents a struct/union/class.
field_range fields() const
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
RecordDecl * getDefinitionOrSelf() const
bool hasBindingInfoForDecl(const VarDecl *VD) const
DeclBindingInfo * getDeclBindingInfo(const VarDecl *VD, ResourceClass ResClass)
DeclBindingInfo * addDeclBindingInfo(const VarDecl *VD, ResourceClass ResClass)
Scope - A scope is a transient data structure that is used while parsing the program.
ASTContext & getASTContext() const
const LangOptions & getLangOpts() const
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
ExprResult ActOnOutParamExpr(ParmVarDecl *Param, Expr *Arg)
void handleVkBuiltInAttr(Decl *D, const ParsedAttr &AL)
HLSLRootSignatureDecl * lookupRootSignatureOverrideDecl(DeclContext *DC) const
bool CanPerformElementwiseCast(Expr *Src, QualType DestType)
ExprResult CreateOutArgExpr(Expr *Arg, QualType ArgTy, QualType ParamTy, InitializedEntity Entity, SourceLocation Loc, bool IsInOut)
void handleWaveSizeAttr(Decl *D, const ParsedAttr &AL)
void handleVkLocationAttr(Decl *D, const ParsedAttr &AL)
HLSLAttributedResourceLocInfo TakeLocForHLSLAttribute(const HLSLAttributedResourceType *RT)
void handleSemanticAttr(Decl *D, const ParsedAttr &AL)
bool CanPerformScalarCast(QualType SrcTy, QualType DestTy)
QualType ProcessResourceTypeAttributes(QualType Wrapped)
void handleInterpolationModifierAttr(Decl *D, const ParsedAttr &AL)
void handleShaderAttr(Decl *D, const ParsedAttr &AL)
uint32_t getNextImplicitBindingOrderID()
void CheckEntryPoint(FunctionDecl *FD)
void handleVkExtBuiltinOutputAttr(Decl *D, const ParsedAttr &AL)
void emitLogicalOperatorFixIt(Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
bool initGlobalResourceDecl(VarDecl *VD)
void ActOnEndOfTranslationUnit(TranslationUnitDecl *TU)
bool initGlobalResourceArrayDecl(VarDecl *VD)
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
void deduceAddressSpace(VarDecl *Decl)
std::pair< IdentifierInfo *, bool > ActOnStartRootSignatureDecl(StringRef Signature)
Computes the unique Root Signature identifier from the given signature, then lookup if there is a pre...
void handlePackOffsetAttr(Decl *D, const ParsedAttr &AL)
Attr * buildMatrixLayoutTypeAttr(QualType T, const ParsedAttr &AL)
bool handleInitialization(VarDecl *VDecl, Expr *&Init)
void handleParamModifierAttr(Decl *D, const ParsedAttr &AL)
bool CheckResourceBinOp(BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc)
bool CanPerformAggregateSplatCast(Expr *Src, QualType DestType)
bool ActOnResourceMemberAccessExpr(MemberExpr *ME)
bool IsScalarizedLayoutCompatible(QualType T1, QualType T2) const
QualType ActOnTemplateShorthand(TemplateDecl *Template, SourceLocation NameLoc)
void handleRootSignatureAttr(Decl *D, const ParsedAttr &AL)
bool CheckCompatibleParameterABI(FunctionDecl *New, FunctionDecl *Old)
QualType handleVectorBinOpConversion(ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
QualType checkMatrixComponent(Sema &S, QualType baseType, ExprValueKind &VK, SourceLocation OpLoc, const IdentifierInfo *CompName, SourceLocation CompLoc)
bool IsConstantBufferElementCompatible(QualType T1)
void handleResourceBindingAttr(Decl *D, const ParsedAttr &AL)
bool IsTypedResourceElementCompatible(QualType T1)
bool transformInitList(const InitializedEntity &Entity, InitListExpr *Init)
void handleNumThreadsAttr(Decl *D, const ParsedAttr &AL)
bool ActOnUninitializedVarDecl(VarDecl *D)
void handleVkExtBuiltinInputAttr(Decl *D, const ParsedAttr &AL)
bool canHaveOverloadedBinOp(QualType Ty, BinaryOperatorKind Opc)
void ActOnTopLevelFunction(FunctionDecl *FD)
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)
NamedDecl * getConstantBufferConversionFunction(QualType Type, CXXRecordDecl *RD)
void ActOnFinishBuffer(Decl *Dcl, SourceLocation RBrace)
void handleVkBindingAttr(Decl *D, const ParsedAttr &AL)
HLSLParamModifierAttr * mergeParamModifierAttr(Decl *D, const AttributeCommonInfo &AL, HLSLParamModifierAttr::Spelling Spelling)
QualType getInoutParameterType(QualType Ty)
void handleVkConstantIdAttr(Decl *D, const ParsedAttr &AL)
std::optional< ExprResult > tryPerformConstantBufferConversion(Expr *BaseExpr)
Decl * ActOnStartBuffer(Scope *BufferScope, bool CBuffer, SourceLocation KwLoc, IdentifierInfo *Ident, SourceLocation IdentLoc, SourceLocation LBrace)
bool diagnoseMatrixLayoutInstantiation(attr::Kind K, QualType T, SourceLocation Loc)
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
bool handleRootSignatureElements(ArrayRef< hlsl::RootSignatureElement > Elements)
bool CanPerformPackedTypeCast(Expr *Src, QualType DestTy)
void ActOnFinishRootSignatureDecl(SourceLocation Loc, IdentifierInfo *DeclIdent, ArrayRef< hlsl::RootSignatureElement > Elements)
Creates the Root Signature decl of the parsed Root Signature elements onto the AST and push it onto c...
void ActOnVariableDeclarator(VarDecl *VD)
bool CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Sema - This implements semantic analysis and AST building for C.
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount)
Checks that a call expression's argument count is at most the desired number.
ExtVectorDeclsType ExtVectorDecls
ExtVectorDecls - This is a list all the extended vector types.
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
ASTContext & getASTContext() const
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.
const LangOptions & getLangOpts() const
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
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
bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount)
Checks that a call expression's argument count is the desired number.
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc)
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getEndLoc() const LLVM_READONLY
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...
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
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...
void startDefinition()
Starts the definition of this tag declaration.
Exposes information about the current target.
TargetOptions & getTargetOpts() const
Retrieve the target options.
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.
SourceLocation getBeginLoc() const
Get the begin source location.
A container of type source information.
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
The base class of the type hierarchy.
bool isBooleanType() const
bool isIncompleteArrayType() const
bool isFloat16Type() const
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
bool isConstantArrayType() const
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
CXXRecordDecl * castAsCXXRecordDecl() const
bool isArithmeticType() const
bool isConstantMatrixType() const
bool isHLSLBuiltinIntangibleType() const
bool isPointerType() const
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isHLSLIntangibleType() const
bool isEnumeralType() const
bool isScalarType() const
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
bool isFloat32Type() const
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
bool isMatrixType() const
bool isHLSLBuiltinPackedType() const
bool isHLSLResourceRecord() const
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
bool isVectorType() const
bool isRealFloatingType() const
Floating point categories.
bool isHLSLAttributedResourceType() const
bool isFloatingType() const
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
const T * getAs() const
Member-template getAs<specific type>'.
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
bool isRecordType() const
bool isHLSLResourceRecordArray() const
void setType(QualType newType)
Represents a variable declaration or definition.
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
void setInitStyle(InitializationStyle Style)
@ CallInit
Call-style initialization (C++98)
void setStorageClass(StorageClass SC)
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Represents a GCC generic vector type.
unsigned getNumElements() const
QualType getElementType() const
void pushName(llvm::StringRef N)
void pushArrayIndex(uint64_t Index)
void pushBaseName(llvm::StringRef N)
IdentifierInfo * getNameAsIdentifier(ASTContext &AST) const
Defines the clang::TargetInfo interface.
bool isStructOrArrayOfWithResources(QualType Ty)
uint32_t getResourceDimensions(llvm::dxil::ResourceDimension Dim)
bool hasResourceOffset(llvm::dxil::ResourceDimension Dim)
bool hasCounterHandle(const CXXRecordDecl *RD)
SetTy< T > join(SetTy< T > A, SetTy< T > B, typename SetTy< T >::Factory &F)
Computes the union of two ImmutableSets.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
static bool CheckFloatOrHalfRepresentation(Sema *S, SourceLocation Loc, int ArgOrdinal, clang::QualType PassedType)
@ ICIS_NoInit
No in-class initializer.
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
@ OK_Ordinary
An ordinary object is located at an address in memory.
static bool CheckAllArgTypesAreCorrect(Sema *S, CallExpr *TheCall, llvm::ArrayRef< llvm::function_ref< bool(Sema *, SourceLocation, int, QualType)> > Checks)
bool isMatrixRowMajor(const LangOptions &LangOpts, QualType T)
Returns true if matrices of T should be laid out in row-major order.
@ AANT_ArgumentIdentifier
@ Result
The result type of a method or function.
@ Ordinary
This parameter uses ordinary ABI rules for its type.
const FunctionProtoType * T
llvm::Expected< QualType > ExpectedType
@ Template
We are parsing a template declaration.
LLVM_READONLY bool isDigit(unsigned char c)
Return true if this character is an ASCII digit: [0-9].
static bool CheckAllArgsHaveSameType(Sema *S, CallExpr *TheCall)
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
bool CreateHLSLAttributedResourceType(Sema &S, QualType Wrapped, ArrayRef< const Attr * > AttrList, QualType &ResType, HLSLAttributedResourceLocInfo *LocInfo=nullptr, Expr *SampleCountExpr=nullptr)
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
U cast(CodeGen::Address addr)
@ None
No keyword precedes the qualified type name.
ActionResult< Expr * > ExprResult
Visibility
Describes the different kinds of visibility that a declaration may have.
hash_code hash_value(const clang::dependencies::ModuleID &ID)
__DEVICE__ bool isnan(float __x)
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
int __ovld __cnfn any(char)
Returns 1 if the most significant bit in any component of x is set; otherwise returns 0.
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 __builtin_riscv_nclipu_u32 int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
TypeSourceInfo * ContainedTyInfo
Describes how types, statements, expressions, and declarations should be printed.
unsigned getImplicitOrderID() const
void setCounterImplicitOrderID(unsigned Value) const
bool hasCounterImplicitOrderID() const
unsigned getSpace() const
bool hasImplicitOrderID() const
void setImplicitOrderID(unsigned Value) const
const SourceLocation & getLocation() const
const llvm::hlsl::rootsig::RootElement & getElement() const