| 1 |
//===- SemaHLSL.cpp - Semantic Analysis for HLSL constructs ---------------===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
// This implements Semantic Analysis for HLSL constructs. |
| 9 |
//===----------------------------------------------------------------------===// |
| 10 |
|
| 11 |
#include "clang/Sema/SemaHLSL.h" |
| 12 |
#include "clang/AST/ASTConsumer.h" |
| 13 |
#include "clang/AST/ASTContext.h" |
| 14 |
#include "clang/AST/Attr.h" |
| 15 |
#include "clang/AST/Attrs.inc" |
| 16 |
#include "clang/AST/Decl.h" |
| 17 |
#include "clang/AST/DeclBase.h" |
| 18 |
#include "clang/AST/DeclCXX.h" |
| 19 |
#include "clang/AST/DeclarationName.h" |
| 20 |
#include "clang/AST/DynamicRecursiveASTVisitor.h" |
| 21 |
#include "clang/AST/Expr.h" |
| 22 |
#include "clang/AST/HLSLResource.h" |
| 23 |
#include "clang/AST/Type.h" |
| 24 |
#include "clang/AST/TypeBase.h" |
| 25 |
#include "clang/AST/TypeLoc.h" |
| 26 |
#include "clang/Basic/Builtins.h" |
| 27 |
#include "clang/Basic/DiagnosticSema.h" |
| 28 |
#include "clang/Basic/IdentifierTable.h" |
| 29 |
#include "clang/Basic/LLVM.h" |
| 30 |
#include "clang/Basic/SourceLocation.h" |
| 31 |
#include "clang/Basic/Specifiers.h" |
| 32 |
#include "clang/Basic/TargetInfo.h" |
| 33 |
#include "clang/Sema/Initialization.h" |
| 34 |
#include "clang/Sema/Lookup.h" |
| 35 |
#include "clang/Sema/ParsedAttr.h" |
| 36 |
#include "clang/Sema/Sema.h" |
| 37 |
#include "clang/Sema/Template.h" |
| 38 |
#include "llvm/ADT/ArrayRef.h" |
| 39 |
#include "llvm/ADT/STLExtras.h" |
| 40 |
#include "llvm/ADT/SmallVector.h" |
| 41 |
#include "llvm/ADT/StringExtras.h" |
| 42 |
#include "llvm/ADT/StringRef.h" |
| 43 |
#include "llvm/ADT/Twine.h" |
| 44 |
#include "llvm/Frontend/HLSL/HLSLBinding.h" |
| 45 |
#include "llvm/Frontend/HLSL/RootSignatureValidations.h" |
| 46 |
#include "llvm/Support/Casting.h" |
| 47 |
#include "llvm/Support/DXILABI.h" |
| 48 |
#include "llvm/Support/ErrorHandling.h" |
| 49 |
#include "llvm/Support/FormatVariadic.h" |
| 50 |
#include "llvm/TargetParser/Triple.h" |
| 51 |
#include <cmath> |
| 52 |
#include <cstddef> |
| 53 |
#include <iterator> |
| 54 |
#include <utility> |
| 55 |
|
| 56 |
using namespace clang; |
| 57 |
using namespace clang::hlsl; |
| 58 |
using RegisterType = HLSLResourceBindingAttr::RegisterType; |
| 59 |
|
| 60 |
static CXXRecordDecl *createHostLayoutStruct(Sema &S, |
| 61 |
CXXRecordDecl *StructDecl); |
| 62 |
|
| 63 |
static RegisterType getRegisterType(ResourceClass RC) { |
| 64 |
switch (RC) { |
| 65 |
case ResourceClass::SRV: |
| 66 |
return RegisterType::SRV; |
| 67 |
case ResourceClass::UAV: |
| 68 |
return RegisterType::UAV; |
| 69 |
case ResourceClass::CBuffer: |
| 70 |
return RegisterType::CBuffer; |
| 71 |
case ResourceClass::Sampler: |
| 72 |
return RegisterType::Sampler; |
| 73 |
} |
| 74 |
llvm_unreachable("unexpected ResourceClass value"); |
| 75 |
} |
| 76 |
|
| 77 |
static RegisterType getRegisterType(const HLSLAttributedResourceType *ResTy) { |
| 78 |
return getRegisterType(ResTy->getAttrs().ResourceClass); |
| 79 |
} |
| 80 |
|
| 81 |
// Converts the first letter of string Slot to RegisterType. |
| 82 |
// Returns false if the letter does not correspond to a valid register type. |
| 83 |
static bool convertToRegisterType(StringRef Slot, RegisterType *RT) { |
| 84 |
assert(RT != nullptr); |
| 85 |
switch (Slot[0]) { |
| 86 |
case 't': |
| 87 |
case 'T': |
| 88 |
*RT = RegisterType::SRV; |
| 89 |
return true; |
| 90 |
case 'u': |
| 91 |
case 'U': |
| 92 |
*RT = RegisterType::UAV; |
| 93 |
return true; |
| 94 |
case 'b': |
| 95 |
case 'B': |
| 96 |
*RT = RegisterType::CBuffer; |
| 97 |
return true; |
| 98 |
case 's': |
| 99 |
case 'S': |
| 100 |
*RT = RegisterType::Sampler; |
| 101 |
return true; |
| 102 |
case 'c': |
| 103 |
case 'C': |
| 104 |
*RT = RegisterType::C; |
| 105 |
return true; |
| 106 |
case 'i': |
| 107 |
case 'I': |
| 108 |
*RT = RegisterType::I; |
| 109 |
return true; |
| 110 |
default: |
| 111 |
return false; |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
static ResourceClass getResourceClass(RegisterType RT) { |
| 116 |
switch (RT) { |
| 117 |
case RegisterType::SRV: |
| 118 |
return ResourceClass::SRV; |
| 119 |
case RegisterType::UAV: |
| 120 |
return ResourceClass::UAV; |
| 121 |
case RegisterType::CBuffer: |
| 122 |
return ResourceClass::CBuffer; |
| 123 |
case RegisterType::Sampler: |
| 124 |
return ResourceClass::Sampler; |
| 125 |
case RegisterType::C: |
| 126 |
case RegisterType::I: |
| 127 |
// Deliberately falling through to the unreachable below. |
| 128 |
break; |
| 129 |
} |
| 130 |
llvm_unreachable("unexpected RegisterType value"); |
| 131 |
} |
| 132 |
|
| 133 |
static Builtin::ID getSpecConstBuiltinId(const Type *Type) { |
| 134 |
const auto *BT = dyn_cast<BuiltinType>(Type); |
| 135 |
if (!BT) { |
| 136 |
if (!Type->isEnumeralType()) |
| 137 |
return Builtin::NotBuiltin; |
| 138 |
return Builtin::BI__builtin_get_spirv_spec_constant_int; |
| 139 |
} |
| 140 |
|
| 141 |
switch (BT->getKind()) { |
| 142 |
case BuiltinType::Bool: |
| 143 |
return Builtin::BI__builtin_get_spirv_spec_constant_bool; |
| 144 |
case BuiltinType::Short: |
| 145 |
return Builtin::BI__builtin_get_spirv_spec_constant_short; |
| 146 |
case BuiltinType::Int: |
| 147 |
return Builtin::BI__builtin_get_spirv_spec_constant_int; |
| 148 |
case BuiltinType::LongLong: |
| 149 |
return Builtin::BI__builtin_get_spirv_spec_constant_longlong; |
| 150 |
case BuiltinType::UShort: |
| 151 |
return Builtin::BI__builtin_get_spirv_spec_constant_ushort; |
| 152 |
case BuiltinType::UInt: |
| 153 |
return Builtin::BI__builtin_get_spirv_spec_constant_uint; |
| 154 |
case BuiltinType::ULongLong: |
| 155 |
return Builtin::BI__builtin_get_spirv_spec_constant_ulonglong; |
| 156 |
case BuiltinType::Half: |
| 157 |
return Builtin::BI__builtin_get_spirv_spec_constant_half; |
| 158 |
case BuiltinType::Float: |
| 159 |
return Builtin::BI__builtin_get_spirv_spec_constant_float; |
| 160 |
case BuiltinType::Double: |
| 161 |
return Builtin::BI__builtin_get_spirv_spec_constant_double; |
| 162 |
default: |
| 163 |
return Builtin::NotBuiltin; |
| 164 |
} |
| 165 |
} |
| 166 |
|
| 167 |
DeclBindingInfo *ResourceBindings::addDeclBindingInfo(const VarDecl *VD, |
| 168 |
ResourceClass ResClass) { |
| 169 |
assert(getDeclBindingInfo(VD, ResClass) == nullptr && |
| 170 |
"DeclBindingInfo already added"); |
| 171 |
assert(!hasBindingInfoForDecl(VD) || BindingsList.back().Decl == VD); |
| 172 |
// VarDecl may have multiple entries for different resource classes. |
| 173 |
// DeclToBindingListIndex stores the index of the first binding we saw |
| 174 |
// for this decl. If there are any additional ones then that index |
| 175 |
// shouldn't be updated. |
| 176 |
DeclToBindingListIndex.try_emplace(VD, BindingsList.size()); |
| 177 |
return &BindingsList.emplace_back(VD, ResClass); |
| 178 |
} |
| 179 |
|
| 180 |
DeclBindingInfo *ResourceBindings::getDeclBindingInfo(const VarDecl *VD, |
| 181 |
ResourceClass ResClass) { |
| 182 |
auto Entry = DeclToBindingListIndex.find(VD); |
| 183 |
if (Entry != DeclToBindingListIndex.end()) { |
| 184 |
for (unsigned Index = Entry->getSecond(); |
| 185 |
Index < BindingsList.size() && BindingsList[Index].Decl == VD; |
| 186 |
++Index) { |
| 187 |
if (BindingsList[Index].ResClass == ResClass) |
| 188 |
return &BindingsList[Index]; |
| 189 |
} |
| 190 |
} |
| 191 |
return nullptr; |
| 192 |
} |
| 193 |
|
| 194 |
bool ResourceBindings::hasBindingInfoForDecl(const VarDecl *VD) const { |
| 195 |
return DeclToBindingListIndex.contains(VD); |
| 196 |
} |
| 197 |
|
| 198 |
SemaHLSL::SemaHLSL(Sema &S) : SemaBase(S) {} |
| 199 |
|
| 200 |
Decl *SemaHLSL::ActOnStartBuffer(Scope *BufferScope, bool CBuffer, |
| 201 |
SourceLocation KwLoc, IdentifierInfo *Ident, |
| 202 |
SourceLocation IdentLoc, |
| 203 |
SourceLocation LBrace) { |
| 204 |
// For anonymous namespace, take the location of the left brace. |
| 205 |
DeclContext *LexicalParent = SemaRef.getCurLexicalContext(); |
| 206 |
HLSLBufferDecl *Result = HLSLBufferDecl::Create( |
| 207 |
getASTContext(), LexicalParent, CBuffer, KwLoc, Ident, IdentLoc, LBrace); |
| 208 |
|
| 209 |
// if CBuffer is false, then it's a TBuffer |
| 210 |
auto RC = CBuffer ? llvm::hlsl::ResourceClass::CBuffer |
| 211 |
: llvm::hlsl::ResourceClass::SRV; |
| 212 |
Result->addAttr(HLSLResourceClassAttr::CreateImplicit(getASTContext(), RC)); |
| 213 |
|
| 214 |
SemaRef.PushOnScopeChains(Result, BufferScope); |
| 215 |
SemaRef.PushDeclContext(BufferScope, Result); |
| 216 |
|
| 217 |
return Result; |
| 218 |
} |
| 219 |
|
| 220 |
static unsigned calculateLegacyCbufferFieldAlign(const ASTContext &Context, |
| 221 |
QualType T) { |
| 222 |
// Arrays and Structs are always aligned to new buffer rows |
| 223 |
if (T->isArrayType() || T->isStructureType()) |
| 224 |
return 16; |
| 225 |
|
| 226 |
// Vectors are aligned to the type they contain |
| 227 |
if (const VectorType *VT = T->getAs<VectorType>()) |
| 228 |
return calculateLegacyCbufferFieldAlign(Context, VT->getElementType()); |
| 229 |
|
| 230 |
assert(Context.getTypeSize(T) <= 64 && |
| 231 |
"Scalar bit widths larger than 64 not supported"); |
| 232 |
|
| 233 |
// Scalar types are aligned to their byte width |
| 234 |
return Context.getTypeSize(T) / 8; |
| 235 |
} |
| 236 |
|
| 237 |
// Calculate the size of a legacy cbuffer type in bytes based on |
| 238 |
// https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-packing-rules |
| 239 |
static unsigned calculateLegacyCbufferSize(const ASTContext &Context, |
| 240 |
QualType T) { |
| 241 |
constexpr unsigned CBufferAlign = 16; |
| 242 |
if (const auto *RD = T->getAsRecordDecl()) { |
| 243 |
unsigned Size = 0; |
| 244 |
for (const FieldDecl *Field : RD->fields()) { |
| 245 |
QualType Ty = Field->getType(); |
| 246 |
unsigned FieldSize = calculateLegacyCbufferSize(Context, Ty); |
| 247 |
unsigned FieldAlign = calculateLegacyCbufferFieldAlign(Context, Ty); |
| 248 |
|
| 249 |
// If the field crosses the row boundary after alignment it drops to the |
| 250 |
// next row |
| 251 |
unsigned AlignSize = llvm::alignTo(Size, FieldAlign); |
| 252 |
if ((AlignSize % CBufferAlign) + FieldSize > CBufferAlign) { |
| 253 |
FieldAlign = CBufferAlign; |
| 254 |
} |
| 255 |
|
| 256 |
Size = llvm::alignTo(Size, FieldAlign); |
| 257 |
Size += FieldSize; |
| 258 |
} |
| 259 |
return Size; |
| 260 |
} |
| 261 |
|
| 262 |
if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) { |
| 263 |
unsigned ElementCount = AT->getSize().getZExtValue(); |
| 264 |
if (ElementCount == 0) |
| 265 |
return 0; |
| 266 |
|
| 267 |
unsigned ElementSize = |
| 268 |
calculateLegacyCbufferSize(Context, AT->getElementType()); |
| 269 |
unsigned AlignedElementSize = llvm::alignTo(ElementSize, CBufferAlign); |
| 270 |
return AlignedElementSize * (ElementCount - 1) + ElementSize; |
| 271 |
} |
| 272 |
|
| 273 |
if (const VectorType *VT = T->getAs<VectorType>()) { |
| 274 |
unsigned ElementCount = VT->getNumElements(); |
| 275 |
unsigned ElementSize = |
| 276 |
calculateLegacyCbufferSize(Context, VT->getElementType()); |
| 277 |
return ElementSize * ElementCount; |
| 278 |
} |
| 279 |
|
| 280 |
return Context.getTypeSize(T) / 8; |
| 281 |
} |
| 282 |
|
| 283 |
// Validate packoffset: |
| 284 |
// - if packoffset it used it must be set on all declarations inside the buffer |
| 285 |
// - packoffset ranges must not overlap |
| 286 |
static void validatePackoffset(Sema &S, HLSLBufferDecl *BufDecl) { |
| 287 |
llvm::SmallVector<std::pair<VarDecl *, HLSLPackOffsetAttr *>> PackOffsetVec; |
| 288 |
|
| 289 |
// Make sure the packoffset annotations are either on all declarations |
| 290 |
// or on none. |
| 291 |
bool HasPackOffset = false; |
| 292 |
bool HasNonPackOffset = false; |
| 293 |
for (auto *Field : BufDecl->buffer_decls()) { |
| 294 |
VarDecl *Var = dyn_cast<VarDecl>(Field); |
| 295 |
if (!Var) |
| 296 |
continue; |
| 297 |
if (Field->hasAttr<HLSLPackOffsetAttr>()) { |
| 298 |
PackOffsetVec.emplace_back(Var, Field->getAttr<HLSLPackOffsetAttr>()); |
| 299 |
HasPackOffset = true; |
| 300 |
} else { |
| 301 |
HasNonPackOffset = true; |
| 302 |
} |
| 303 |
} |
| 304 |
|
| 305 |
if (!HasPackOffset) |
| 306 |
return; |
| 307 |
|
| 308 |
if (HasNonPackOffset) |
| 309 |
S.Diag(BufDecl->getLocation(), diag::warn_hlsl_packoffset_mix); |
| 310 |
|
| 311 |
// Make sure there is no overlap in packoffset - sort PackOffsetVec by offset |
| 312 |
// and compare adjacent values. |
| 313 |
bool IsValid = true; |
| 314 |
ASTContext &Context = S.getASTContext(); |
| 315 |
std::sort(PackOffsetVec.begin(), PackOffsetVec.end(), |
| 316 |
[](const std::pair<VarDecl *, HLSLPackOffsetAttr *> &LHS, |
| 317 |
const std::pair<VarDecl *, HLSLPackOffsetAttr *> &RHS) { |
| 318 |
return LHS.second->getOffsetInBytes() < |
| 319 |
RHS.second->getOffsetInBytes(); |
| 320 |
}); |
| 321 |
for (unsigned i = 0; i < PackOffsetVec.size() - 1; i++) { |
| 322 |
VarDecl *Var = PackOffsetVec[i].first; |
| 323 |
HLSLPackOffsetAttr *Attr = PackOffsetVec[i].second; |
| 324 |
unsigned Size = calculateLegacyCbufferSize(Context, Var->getType()); |
| 325 |
unsigned Begin = Attr->getOffsetInBytes(); |
| 326 |
unsigned End = Begin + Size; |
| 327 |
unsigned NextBegin = PackOffsetVec[i + 1].second->getOffsetInBytes(); |
| 328 |
if (End > NextBegin) { |
| 329 |
VarDecl *NextVar = PackOffsetVec[i + 1].first; |
| 330 |
S.Diag(NextVar->getLocation(), diag::err_hlsl_packoffset_overlap) |
| 331 |
<< NextVar << Var; |
| 332 |
IsValid = false; |
| 333 |
} |
| 334 |
} |
| 335 |
BufDecl->setHasValidPackoffset(IsValid); |
| 336 |
} |
| 337 |
|
| 338 |
// Returns true if the array has a zero size = if any of the dimensions is 0 |
| 339 |
static bool isZeroSizedArray(const ConstantArrayType *CAT) { |
| 340 |
while (CAT && !CAT->isZeroSize()) |
| 341 |
CAT = dyn_cast<ConstantArrayType>( |
| 342 |
CAT->getElementType()->getUnqualifiedDesugaredType()); |
| 343 |
return CAT != nullptr; |
| 344 |
} |
| 345 |
|
| 346 |
static bool isResourceRecordTypeOrArrayOf(VarDecl *VD) { |
| 347 |
const Type *Ty = VD->getType().getTypePtr(); |
| 348 |
return Ty->isHLSLResourceRecord() || Ty->isHLSLResourceRecordArray(); |
| 349 |
} |
| 350 |
|
| 351 |
static const HLSLAttributedResourceType * |
| 352 |
getResourceArrayHandleType(VarDecl *VD) { |
| 353 |
assert(VD->getType()->isHLSLResourceRecordArray() && |
| 354 |
"expected array of resource records"); |
| 355 |
const Type *Ty = VD->getType()->getUnqualifiedDesugaredType(); |
| 356 |
while (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) |
| 357 |
Ty = AT->getArrayElementTypeNoTypeQual()->getUnqualifiedDesugaredType(); |
| 358 |
return HLSLAttributedResourceType::findHandleTypeOnResource(Ty); |
| 359 |
} |
| 360 |
|
| 361 |
// Returns true if the type is a leaf element type that is not valid to be |
| 362 |
// included in HLSL Buffer, such as a resource class, empty struct, zero-sized |
| 363 |
// array, or a builtin intangible type. Returns false it is a valid leaf element |
| 364 |
// type or if it is a record type that needs to be inspected further. |
| 365 |
static bool isInvalidConstantBufferLeafElementType(const Type *Ty) { |
| 366 |
Ty = Ty->getUnqualifiedDesugaredType(); |
| 367 |
if (Ty->isHLSLResourceRecord() || Ty->isHLSLResourceRecordArray()) |
| 368 |
return true; |
| 369 |
if (const auto *RD = Ty->getAsCXXRecordDecl()) |
| 370 |
return RD->isEmpty(); |
| 371 |
if (Ty->isConstantArrayType() && |
| 372 |
isZeroSizedArray(cast<ConstantArrayType>(Ty))) |
| 373 |
return true; |
| 374 |
if (Ty->isHLSLBuiltinIntangibleType() || Ty->isHLSLAttributedResourceType()) |
| 375 |
return true; |
| 376 |
return false; |
| 377 |
} |
| 378 |
|
| 379 |
// Returns true if the struct contains at least one element that prevents it |
| 380 |
// from being included inside HLSL Buffer as is, such as an intangible type, |
| 381 |
// empty struct, or zero-sized array. If it does, a new implicit layout struct |
| 382 |
// needs to be created for HLSL Buffer use that will exclude these unwanted |
| 383 |
// declarations (see createHostLayoutStruct function). |
| 384 |
static bool requiresImplicitBufferLayoutStructure(const CXXRecordDecl *RD) { |
| 385 |
if (RD->isHLSLIntangible() || RD->isEmpty()) |
| 386 |
return true; |
| 387 |
// check fields |
| 388 |
for (const FieldDecl *Field : RD->fields()) { |
| 389 |
QualType Ty = Field->getType(); |
| 390 |
if (isInvalidConstantBufferLeafElementType(Ty.getTypePtr())) |
| 391 |
return true; |
| 392 |
if (const auto *RD = Ty->getAsCXXRecordDecl(); |
| 393 |
RD && requiresImplicitBufferLayoutStructure(RD)) |
| 394 |
return true; |
| 395 |
} |
| 396 |
// check bases |
| 397 |
for (const CXXBaseSpecifier &Base : RD->bases()) |
| 398 |
if (requiresImplicitBufferLayoutStructure( |
| 399 |
Base.getType()->castAsCXXRecordDecl())) |
| 400 |
return true; |
| 401 |
return false; |
| 402 |
} |
| 403 |
|
| 404 |
static CXXRecordDecl *findRecordDeclInContext(IdentifierInfo *II, |
| 405 |
DeclContext *DC) { |
| 406 |
CXXRecordDecl *RD = nullptr; |
| 407 |
for (NamedDecl *Decl : |
| 408 |
DC->getNonTransparentContext()->lookup(DeclarationName(II))) { |
| 409 |
if (CXXRecordDecl *FoundRD = dyn_cast<CXXRecordDecl>(Decl)) { |
| 410 |
assert(RD == nullptr && |
| 411 |
"there should be at most 1 record by a given name in a scope"); |
| 412 |
RD = FoundRD; |
| 413 |
} |
| 414 |
} |
| 415 |
return RD; |
| 416 |
} |
| 417 |
|
| 418 |
// Creates a name for buffer layout struct using the provide name base. |
| 419 |
// If the name must be unique (not previously defined), a suffix is added |
| 420 |
// until a unique name is found. |
| 421 |
static IdentifierInfo *getHostLayoutStructName(Sema &S, NamedDecl *BaseDecl, |
| 422 |
bool MustBeUnique) { |
| 423 |
ASTContext &AST = S.getASTContext(); |
| 424 |
|
| 425 |
IdentifierInfo *NameBaseII = BaseDecl->getIdentifier(); |
| 426 |
llvm::SmallString<64> Name("__cblayout_"); |
| 427 |
if (NameBaseII) { |
| 428 |
Name.append(NameBaseII->getName()); |
| 429 |
} else { |
| 430 |
// anonymous struct |
| 431 |
Name.append("anon"); |
| 432 |
MustBeUnique = true; |
| 433 |
} |
| 434 |
|
| 435 |
size_t NameLength = Name.size(); |
| 436 |
IdentifierInfo *II = &AST.Idents.get(Name, tok::TokenKind::identifier); |
| 437 |
if (!MustBeUnique) |
| 438 |
return II; |
| 439 |
|
| 440 |
unsigned suffix = 0; |
| 441 |
while (true) { |
| 442 |
if (suffix != 0) { |
| 443 |
Name.append("_"); |
| 444 |
Name.append(llvm::Twine(suffix).str()); |
| 445 |
II = &AST.Idents.get(Name, tok::TokenKind::identifier); |
| 446 |
} |
| 447 |
if (!findRecordDeclInContext(II, BaseDecl->getDeclContext())) |
| 448 |
return II; |
| 449 |
// declaration with that name already exists - increment suffix and try |
| 450 |
// again until unique name is found |
| 451 |
suffix++; |
| 452 |
Name.truncate(NameLength); |
| 453 |
}; |
| 454 |
} |
| 455 |
|
| 456 |
// Creates a field declaration of given name and type for HLSL buffer layout |
| 457 |
// struct. Returns nullptr if the type cannot be use in HLSL Buffer layout. |
| 458 |
static FieldDecl *createFieldForHostLayoutStruct(Sema &S, const Type *Ty, |
| 459 |
IdentifierInfo *II, |
| 460 |
CXXRecordDecl *LayoutStruct) { |
| 461 |
if (isInvalidConstantBufferLeafElementType(Ty)) |
| 462 |
return nullptr; |
| 463 |
|
| 464 |
if (auto *RD = Ty->getAsCXXRecordDecl()) { |
| 465 |
if (requiresImplicitBufferLayoutStructure(RD)) { |
| 466 |
RD = createHostLayoutStruct(S, RD); |
| 467 |
if (!RD) |
| 468 |
return nullptr; |
| 469 |
Ty = S.Context.getCanonicalTagType(RD)->getTypePtr(); |
| 470 |
} |
| 471 |
} |
| 472 |
|
| 473 |
QualType QT = QualType(Ty, 0); |
| 474 |
ASTContext &AST = S.getASTContext(); |
| 475 |
TypeSourceInfo *TSI = AST.getTrivialTypeSourceInfo(QT, SourceLocation()); |
| 476 |
auto *Field = FieldDecl::Create(AST, LayoutStruct, SourceLocation(), |
| 477 |
SourceLocation(), II, QT, TSI, nullptr, false, |
| 478 |
InClassInitStyle::ICIS_NoInit); |
| 479 |
Field->setAccess(AccessSpecifier::AS_public); |
| 480 |
return Field; |
| 481 |
} |
| 482 |
|
| 483 |
// Creates host layout struct for a struct included in HLSL Buffer. |
| 484 |
// The layout struct will include only fields that are allowed in HLSL buffer. |
| 485 |
// These fields will be filtered out: |
| 486 |
// - resource classes |
| 487 |
// - empty structs |
| 488 |
// - zero-sized arrays |
| 489 |
// Returns nullptr if the resulting layout struct would be empty. |
| 490 |
static CXXRecordDecl *createHostLayoutStruct(Sema &S, |
| 491 |
CXXRecordDecl *StructDecl) { |
| 492 |
assert(requiresImplicitBufferLayoutStructure(StructDecl) && |
| 493 |
"struct is already HLSL buffer compatible"); |
| 494 |
|
| 495 |
ASTContext &AST = S.getASTContext(); |
| 496 |
DeclContext *DC = StructDecl->getDeclContext(); |
| 497 |
IdentifierInfo *II = getHostLayoutStructName(S, StructDecl, false); |
| 498 |
|
| 499 |
// reuse existing if the layout struct if it already exists |
| 500 |
if (CXXRecordDecl *RD = findRecordDeclInContext(II, DC)) |
| 501 |
return RD; |
| 502 |
|
| 503 |
CXXRecordDecl *LS = |
| 504 |
CXXRecordDecl::Create(AST, TagDecl::TagKind::Struct, DC, SourceLocation(), |
| 505 |
SourceLocation(), II); |
| 506 |
LS->setImplicit(true); |
| 507 |
LS->addAttr(PackedAttr::CreateImplicit(AST)); |
| 508 |
LS->startDefinition(); |
| 509 |
|
| 510 |
// copy base struct, create HLSL Buffer compatible version if needed |
| 511 |
if (unsigned NumBases = StructDecl->getNumBases()) { |
| 512 |
assert(NumBases == 1 && "HLSL supports only one base type"); |
| 513 |
(void)NumBases; |
| 514 |
CXXBaseSpecifier Base = *StructDecl->bases_begin(); |
| 515 |
CXXRecordDecl *BaseDecl = Base.getType()->castAsCXXRecordDecl(); |
| 516 |
if (requiresImplicitBufferLayoutStructure(BaseDecl)) { |
| 517 |
BaseDecl = createHostLayoutStruct(S, BaseDecl); |
| 518 |
if (BaseDecl) { |
| 519 |
TypeSourceInfo *TSI = |
| 520 |
AST.getTrivialTypeSourceInfo(AST.getCanonicalTagType(BaseDecl)); |
| 521 |
Base = CXXBaseSpecifier(SourceRange(), false, StructDecl->isClass(), |
| 522 |
AS_none, TSI, SourceLocation()); |
| 523 |
} |
| 524 |
} |
| 525 |
if (BaseDecl) { |
| 526 |
const CXXBaseSpecifier *BasesArray[1] = {&Base}; |
| 527 |
LS->setBases(BasesArray, 1); |
| 528 |
} |
| 529 |
} |
| 530 |
|
| 531 |
// filter struct fields |
| 532 |
for (const FieldDecl *FD : StructDecl->fields()) { |
| 533 |
const Type *Ty = FD->getType()->getUnqualifiedDesugaredType(); |
| 534 |
if (FieldDecl *NewFD = |
| 535 |
createFieldForHostLayoutStruct(S, Ty, FD->getIdentifier(), LS)) |
| 536 |
LS->addDecl(NewFD); |
| 537 |
} |
| 538 |
LS->completeDefinition(); |
| 539 |
|
| 540 |
if (LS->field_empty() && LS->getNumBases() == 0) |
| 541 |
return nullptr; |
| 542 |
|
| 543 |
DC->addDecl(LS); |
| 544 |
return LS; |
| 545 |
} |
| 546 |
|
| 547 |
// Creates host layout struct for HLSL Buffer. The struct will include only |
| 548 |
// fields of types that are allowed in HLSL buffer and it will filter out: |
| 549 |
// - static or groupshared variable declarations |
| 550 |
// - resource classes |
| 551 |
// - empty structs |
| 552 |
// - zero-sized arrays |
| 553 |
// - non-variable declarations |
| 554 |
// The layout struct will be added to the HLSLBufferDecl declarations. |
| 555 |
void createHostLayoutStructForBuffer(Sema &S, HLSLBufferDecl *BufDecl) { |
| 556 |
ASTContext &AST = S.getASTContext(); |
| 557 |
IdentifierInfo *II = getHostLayoutStructName(S, BufDecl, true); |
| 558 |
|
| 559 |
CXXRecordDecl *LS = |
| 560 |
CXXRecordDecl::Create(AST, TagDecl::TagKind::Struct, BufDecl, |
| 561 |
SourceLocation(), SourceLocation(), II); |
| 562 |
LS->addAttr(PackedAttr::CreateImplicit(AST)); |
| 563 |
LS->setImplicit(true); |
| 564 |
LS->startDefinition(); |
| 565 |
|
| 566 |
for (Decl *D : BufDecl->buffer_decls()) { |
| 567 |
VarDecl *VD = dyn_cast<VarDecl>(D); |
| 568 |
if (!VD || VD->getStorageClass() == SC_Static || |
| 569 |
VD->getType().getAddressSpace() == LangAS::hlsl_groupshared) |
| 570 |
continue; |
| 571 |
const Type *Ty = VD->getType()->getUnqualifiedDesugaredType(); |
| 572 |
if (FieldDecl *FD = |
| 573 |
createFieldForHostLayoutStruct(S, Ty, VD->getIdentifier(), LS)) { |
| 574 |
// add the field decl to the layout struct |
| 575 |
LS->addDecl(FD); |
| 576 |
// update address space of the original decl to hlsl_constant |
| 577 |
QualType NewTy = |
| 578 |
AST.getAddrSpaceQualType(VD->getType(), LangAS::hlsl_constant); |
| 579 |
VD->setType(NewTy); |
| 580 |
} |
| 581 |
} |
| 582 |
LS->completeDefinition(); |
| 583 |
BufDecl->addLayoutStruct(LS); |
| 584 |
} |
| 585 |
|
| 586 |
static void addImplicitBindingAttrToDecl(Sema &S, Decl *D, RegisterType RT, |
| 587 |
uint32_t ImplicitBindingOrderID) { |
| 588 |
auto *Attr = |
| 589 |
HLSLResourceBindingAttr::CreateImplicit(S.getASTContext(), "", "0", {}); |
| 590 |
Attr->setBinding(RT, std::nullopt, 0); |
| 591 |
Attr->setImplicitBindingOrderID(ImplicitBindingOrderID); |
| 592 |
D->addAttr(Attr); |
| 593 |
} |
| 594 |
|
| 595 |
// Handle end of cbuffer/tbuffer declaration |
| 596 |
void SemaHLSL::ActOnFinishBuffer(Decl *Dcl, SourceLocation RBrace) { |
| 597 |
auto *BufDecl = cast<HLSLBufferDecl>(Dcl); |
| 598 |
BufDecl->setRBraceLoc(RBrace); |
| 599 |
|
| 600 |
validatePackoffset(SemaRef, BufDecl); |
| 601 |
|
| 602 |
createHostLayoutStructForBuffer(SemaRef, BufDecl); |
| 603 |
|
| 604 |
// Handle implicit binding if needed. |
| 605 |
ResourceBindingAttrs ResourceAttrs(Dcl); |
| 606 |
if (!ResourceAttrs.isExplicit()) { |
| 607 |
SemaRef.Diag(Dcl->getLocation(), diag::warn_hlsl_implicit_binding); |
| 608 |
// Use HLSLResourceBindingAttr to transfer implicit binding order_ID |
| 609 |
// to codegen. If it does not exist, create an implicit attribute. |
| 610 |
uint32_t OrderID = getNextImplicitBindingOrderID(); |
| 611 |
if (ResourceAttrs.hasBinding()) |
| 612 |
ResourceAttrs.setImplicitOrderID(OrderID); |
| 613 |
else |
| 614 |
addImplicitBindingAttrToDecl(SemaRef, BufDecl, |
| 615 |
BufDecl->isCBuffer() ? RegisterType::CBuffer |
| 616 |
: RegisterType::SRV, |
| 617 |
OrderID); |
| 618 |
} |
| 619 |
|
| 620 |
SemaRef.PopDeclContext(); |
| 621 |
} |
| 622 |
|
| 623 |
HLSLNumThreadsAttr *SemaHLSL::mergeNumThreadsAttr(Decl *D, |
| 624 |
const AttributeCommonInfo &AL, |
| 625 |
int X, int Y, int Z) { |
| 626 |
if (HLSLNumThreadsAttr *NT = D->getAttr<HLSLNumThreadsAttr>()) { |
| 627 |
if (NT->getX() != X || NT->getY() != Y || NT->getZ() != Z) { |
| 628 |
Diag(NT->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL; |
| 629 |
Diag(AL.getLoc(), diag::note_conflicting_attribute); |
| 630 |
} |
| 631 |
return nullptr; |
| 632 |
} |
| 633 |
return ::new (getASTContext()) |
| 634 |
HLSLNumThreadsAttr(getASTContext(), AL, X, Y, Z); |
| 635 |
} |
| 636 |
|
| 637 |
HLSLWaveSizeAttr *SemaHLSL::mergeWaveSizeAttr(Decl *D, |
| 638 |
const AttributeCommonInfo &AL, |
| 639 |
int Min, int Max, int Preferred, |
| 640 |
int SpelledArgsCount) { |
| 641 |
if (HLSLWaveSizeAttr *WS = D->getAttr<HLSLWaveSizeAttr>()) { |
| 642 |
if (WS->getMin() != Min || WS->getMax() != Max || |
| 643 |
WS->getPreferred() != Preferred || |
| 644 |
WS->getSpelledArgsCount() != SpelledArgsCount) { |
| 645 |
Diag(WS->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL; |
| 646 |
Diag(AL.getLoc(), diag::note_conflicting_attribute); |
| 647 |
} |
| 648 |
return nullptr; |
| 649 |
} |
| 650 |
HLSLWaveSizeAttr *Result = ::new (getASTContext()) |
| 651 |
HLSLWaveSizeAttr(getASTContext(), AL, Min, Max, Preferred); |
| 652 |
Result->setSpelledArgsCount(SpelledArgsCount); |
| 653 |
return Result; |
| 654 |
} |
| 655 |
|
| 656 |
HLSLVkConstantIdAttr * |
| 657 |
SemaHLSL::mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, |
| 658 |
int Id) { |
| 659 |
|
| 660 |
auto &TargetInfo = getASTContext().getTargetInfo(); |
| 661 |
if (TargetInfo.getTriple().getArch() != llvm::Triple::spirv) { |
| 662 |
Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL; |
| 663 |
return nullptr; |
| 664 |
} |
| 665 |
|
| 666 |
auto *VD = cast<VarDecl>(D); |
| 667 |
|
| 668 |
if (getSpecConstBuiltinId(VD->getType()->getUnqualifiedDesugaredType()) == |
| 669 |
Builtin::NotBuiltin) { |
| 670 |
Diag(VD->getLocation(), diag::err_specialization_const); |
| 671 |
return nullptr; |
| 672 |
} |
| 673 |
|
| 674 |
if (!VD->getType().isConstQualified()) { |
| 675 |
Diag(VD->getLocation(), diag::err_specialization_const); |
| 676 |
return nullptr; |
| 677 |
} |
| 678 |
|
| 679 |
if (HLSLVkConstantIdAttr *CI = D->getAttr<HLSLVkConstantIdAttr>()) { |
| 680 |
if (CI->getId() != Id) { |
| 681 |
Diag(CI->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL; |
| 682 |
Diag(AL.getLoc(), diag::note_conflicting_attribute); |
| 683 |
} |
| 684 |
return nullptr; |
| 685 |
} |
| 686 |
|
| 687 |
HLSLVkConstantIdAttr *Result = |
| 688 |
::new (getASTContext()) HLSLVkConstantIdAttr(getASTContext(), AL, Id); |
| 689 |
return Result; |
| 690 |
} |
| 691 |
|
| 692 |
HLSLShaderAttr * |
| 693 |
SemaHLSL::mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, |
| 694 |
llvm::Triple::EnvironmentType ShaderType) { |
| 695 |
if (HLSLShaderAttr *NT = D->getAttr<HLSLShaderAttr>()) { |
| 696 |
if (NT->getType() != ShaderType) { |
| 697 |
Diag(NT->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL; |
| 698 |
Diag(AL.getLoc(), diag::note_conflicting_attribute); |
| 699 |
} |
| 700 |
return nullptr; |
| 701 |
} |
| 702 |
return HLSLShaderAttr::Create(getASTContext(), ShaderType, AL); |
| 703 |
} |
| 704 |
|
| 705 |
HLSLParamModifierAttr * |
| 706 |
SemaHLSL::mergeParamModifierAttr(Decl *D, const AttributeCommonInfo &AL, |
| 707 |
HLSLParamModifierAttr::Spelling Spelling) { |
| 708 |
// We can only merge an `in` attribute with an `out` attribute. All other |
| 709 |
// combinations of duplicated attributes are ill-formed. |
| 710 |
if (HLSLParamModifierAttr *PA = D->getAttr<HLSLParamModifierAttr>()) { |
| 711 |
if ((PA->isIn() && Spelling == HLSLParamModifierAttr::Keyword_out) || |
| 712 |
(PA->isOut() && Spelling == HLSLParamModifierAttr::Keyword_in)) { |
| 713 |
D->dropAttr<HLSLParamModifierAttr>(); |
| 714 |
SourceRange AdjustedRange = {PA->getLocation(), AL.getRange().getEnd()}; |
| 715 |
return HLSLParamModifierAttr::Create( |
| 716 |
getASTContext(), /*MergedSpelling=*/true, AdjustedRange, |
| 717 |
HLSLParamModifierAttr::Keyword_inout); |
| 718 |
} |
| 719 |
Diag(AL.getLoc(), diag::err_hlsl_duplicate_parameter_modifier) << AL; |
| 720 |
Diag(PA->getLocation(), diag::note_conflicting_attribute); |
| 721 |
return nullptr; |
| 722 |
} |
| 723 |
return HLSLParamModifierAttr::Create(getASTContext(), AL); |
| 724 |
} |
| 725 |
|
| 726 |
void SemaHLSL::ActOnTopLevelFunction(FunctionDecl *FD) { |
| 727 |
auto &TargetInfo = getASTContext().getTargetInfo(); |
| 728 |
|
| 729 |
if (FD->getName() != TargetInfo.getTargetOpts().HLSLEntry) |
| 730 |
return; |
| 731 |
|
| 732 |
// If we have specified a root signature to override the entry function then |
| 733 |
// attach it now |
| 734 |
HLSLRootSignatureDecl *SignatureDecl = |
| 735 |
lookupRootSignatureOverrideDecl(FD->getDeclContext()); |
| 736 |
if (SignatureDecl) { |
| 737 |
FD->dropAttr<RootSignatureAttr>(); |
| 738 |
// We could look up the SourceRange of the macro here as well |
| 739 |
AttributeCommonInfo AL(RootSigOverrideIdent, AttributeScopeInfo(), |
| 740 |
SourceRange(), ParsedAttr::Form::Microsoft()); |
| 741 |
FD->addAttr(::new (getASTContext()) RootSignatureAttr( |
| 742 |
getASTContext(), AL, RootSigOverrideIdent, SignatureDecl)); |
| 743 |
} |
| 744 |
|
| 745 |
llvm::Triple::EnvironmentType Env = TargetInfo.getTriple().getEnvironment(); |
| 746 |
if (HLSLShaderAttr::isValidShaderType(Env) && Env != llvm::Triple::Library) { |
| 747 |
if (const auto *Shader = FD->getAttr<HLSLShaderAttr>()) { |
| 748 |
// The entry point is already annotated - check that it matches the |
| 749 |
// triple. |
| 750 |
if (Shader->getType() != Env) { |
| 751 |
Diag(Shader->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch) |
| 752 |
<< Shader; |
| 753 |
FD->setInvalidDecl(); |
| 754 |
} |
| 755 |
} else { |
| 756 |
// Implicitly add the shader attribute if the entry function isn't |
| 757 |
// explicitly annotated. |
| 758 |
FD->addAttr(HLSLShaderAttr::CreateImplicit(getASTContext(), Env, |
| 759 |
FD->getBeginLoc())); |
| 760 |
} |
| 761 |
} else { |
| 762 |
switch (Env) { |
| 763 |
case llvm::Triple::UnknownEnvironment: |
| 764 |
case llvm::Triple::Library: |
| 765 |
break; |
| 766 |
case llvm::Triple::RootSignature: |
| 767 |
llvm_unreachable("rootsig environment has no functions"); |
| 768 |
default: |
| 769 |
llvm_unreachable("Unhandled environment in triple"); |
| 770 |
} |
| 771 |
} |
| 772 |
} |
| 773 |
|
| 774 |
static bool isVkPipelineBuiltin(const ASTContext &AstContext, FunctionDecl *FD, |
| 775 |
HLSLAppliedSemanticAttr *Semantic, |
| 776 |
bool IsInput) { |
| 777 |
if (AstContext.getTargetInfo().getTriple().getOS() != llvm::Triple::Vulkan) |
| 778 |
return false; |
| 779 |
|
| 780 |
const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>(); |
| 781 |
assert(ShaderAttr && "Entry point has no shader attribute"); |
| 782 |
llvm::Triple::EnvironmentType ST = ShaderAttr->getType(); |
| 783 |
auto SemanticName = Semantic->getSemanticName().upper(); |
| 784 |
|
| 785 |
// The SV_Position semantic is lowered to: |
| 786 |
// - Position built-in for vertex output. |
| 787 |
// - FragCoord built-in for fragment input. |
| 788 |
if (SemanticName == "SV_POSITION") { |
| 789 |
return (ST == llvm::Triple::Vertex && !IsInput) || |
| 790 |
(ST == llvm::Triple::Pixel && IsInput); |
| 791 |
} |
| 792 |
|
| 793 |
return false; |
| 794 |
} |
| 795 |
|
| 796 |
bool SemaHLSL::determineActiveSemanticOnScalar(FunctionDecl *FD, |
| 797 |
DeclaratorDecl *OutputDecl, |
| 798 |
DeclaratorDecl *D, |
| 799 |
SemanticInfo &ActiveSemantic, |
| 800 |
SemaHLSL::SemanticContext &SC) { |
| 801 |
if (ActiveSemantic.Semantic == nullptr) { |
| 802 |
ActiveSemantic.Semantic = D->getAttr<HLSLParsedSemanticAttr>(); |
| 803 |
if (ActiveSemantic.Semantic) |
| 804 |
ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex(); |
| 805 |
} |
| 806 |
|
| 807 |
if (!ActiveSemantic.Semantic) { |
| 808 |
Diag(D->getLocation(), diag::err_hlsl_missing_semantic_annotation); |
| 809 |
return false; |
| 810 |
} |
| 811 |
|
| 812 |
auto *A = ::new (getASTContext()) |
| 813 |
HLSLAppliedSemanticAttr(getASTContext(), *ActiveSemantic.Semantic, |
| 814 |
ActiveSemantic.Semantic->getAttrName()->getName(), |
| 815 |
ActiveSemantic.Index.value_or(0)); |
| 816 |
if (!A) |
| 817 |
return false; |
| 818 |
|
| 819 |
checkSemanticAnnotation(FD, D, A, SC); |
| 820 |
OutputDecl->addAttr(A); |
| 821 |
|
| 822 |
unsigned Location = ActiveSemantic.Index.value_or(0); |
| 823 |
|
| 824 |
if (!isVkPipelineBuiltin(getASTContext(), FD, A, |
| 825 |
SC.CurrentIOType & IOType::In)) { |
| 826 |
bool HasVkLocation = false; |
| 827 |
if (auto *A = D->getAttr<HLSLVkLocationAttr>()) { |
| 828 |
HasVkLocation = true; |
| 829 |
Location = A->getLocation(); |
| 830 |
} |
| 831 |
|
| 832 |
if (SC.UsesExplicitVkLocations.value_or(HasVkLocation) != HasVkLocation) { |
| 833 |
Diag(D->getLocation(), diag::err_hlsl_semantic_partial_explicit_indexing); |
| 834 |
return false; |
| 835 |
} |
| 836 |
SC.UsesExplicitVkLocations = HasVkLocation; |
| 837 |
} |
| 838 |
|
| 839 |
const ConstantArrayType *AT = dyn_cast<ConstantArrayType>(D->getType()); |
| 840 |
unsigned ElementCount = AT ? AT->getZExtSize() : 1; |
| 841 |
ActiveSemantic.Index = Location + ElementCount; |
| 842 |
|
| 843 |
Twine BaseName = Twine(ActiveSemantic.Semantic->getAttrName()->getName()); |
| 844 |
for (unsigned I = 0; I < ElementCount; ++I) { |
| 845 |
Twine VariableName = BaseName.concat(Twine(Location + I)); |
| 846 |
|
| 847 |
auto [_, Inserted] = SC.ActiveSemantics.insert(VariableName.str()); |
| 848 |
if (!Inserted) { |
| 849 |
Diag(D->getLocation(), diag::err_hlsl_semantic_index_overlap) |
| 850 |
<< VariableName.str(); |
| 851 |
return false; |
| 852 |
} |
| 853 |
} |
| 854 |
|
| 855 |
return true; |
| 856 |
} |
| 857 |
|
| 858 |
bool SemaHLSL::determineActiveSemantic(FunctionDecl *FD, |
| 859 |
DeclaratorDecl *OutputDecl, |
| 860 |
DeclaratorDecl *D, |
| 861 |
SemanticInfo &ActiveSemantic, |
| 862 |
SemaHLSL::SemanticContext &SC) { |
| 863 |
if (ActiveSemantic.Semantic == nullptr) { |
| 864 |
ActiveSemantic.Semantic = D->getAttr<HLSLParsedSemanticAttr>(); |
| 865 |
if (ActiveSemantic.Semantic) |
| 866 |
ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex(); |
| 867 |
} |
| 868 |
|
| 869 |
const Type *T = D == FD ? &*FD->getReturnType() : &*D->getType(); |
| 870 |
T = T->getUnqualifiedDesugaredType(); |
| 871 |
|
| 872 |
const RecordType *RT = dyn_cast<RecordType>(T); |
| 873 |
if (!RT) |
| 874 |
return determineActiveSemanticOnScalar(FD, OutputDecl, D, ActiveSemantic, |
| 875 |
SC); |
| 876 |
|
| 877 |
const RecordDecl *RD = RT->getDecl(); |
| 878 |
for (FieldDecl *Field : RD->fields()) { |
| 879 |
SemanticInfo Info = ActiveSemantic; |
| 880 |
if (!determineActiveSemantic(FD, OutputDecl, Field, Info, SC)) { |
| 881 |
Diag(Field->getLocation(), diag::note_hlsl_semantic_used_here) << Field; |
| 882 |
return false; |
| 883 |
} |
| 884 |
if (ActiveSemantic.Semantic) |
| 885 |
ActiveSemantic = Info; |
| 886 |
} |
| 887 |
|
| 888 |
return true; |
| 889 |
} |
| 890 |
|
| 891 |
void SemaHLSL::CheckEntryPoint(FunctionDecl *FD) { |
| 892 |
const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>(); |
| 893 |
assert(ShaderAttr && "Entry point has no shader attribute"); |
| 894 |
llvm::Triple::EnvironmentType ST = ShaderAttr->getType(); |
| 895 |
auto &TargetInfo = getASTContext().getTargetInfo(); |
| 896 |
VersionTuple Ver = TargetInfo.getTriple().getOSVersion(); |
| 897 |
switch (ST) { |
| 898 |
case llvm::Triple::Pixel: |
| 899 |
case llvm::Triple::Vertex: |
| 900 |
case llvm::Triple::Geometry: |
| 901 |
case llvm::Triple::Hull: |
| 902 |
case llvm::Triple::Domain: |
| 903 |
case llvm::Triple::RayGeneration: |
| 904 |
case llvm::Triple::Intersection: |
| 905 |
case llvm::Triple::AnyHit: |
| 906 |
case llvm::Triple::ClosestHit: |
| 907 |
case llvm::Triple::Miss: |
| 908 |
case llvm::Triple::Callable: |
| 909 |
if (const auto *NT = FD->getAttr<HLSLNumThreadsAttr>()) { |
| 910 |
diagnoseAttrStageMismatch(NT, ST, |
| 911 |
{llvm::Triple::Compute, |
| 912 |
llvm::Triple::Amplification, |
| 913 |
llvm::Triple::Mesh}); |
| 914 |
FD->setInvalidDecl(); |
| 915 |
} |
| 916 |
if (const auto *WS = FD->getAttr<HLSLWaveSizeAttr>()) { |
| 917 |
diagnoseAttrStageMismatch(WS, ST, |
| 918 |
{llvm::Triple::Compute, |
| 919 |
llvm::Triple::Amplification, |
| 920 |
llvm::Triple::Mesh}); |
| 921 |
FD->setInvalidDecl(); |
| 922 |
} |
| 923 |
break; |
| 924 |
|
| 925 |
case llvm::Triple::Compute: |
| 926 |
case llvm::Triple::Amplification: |
| 927 |
case llvm::Triple::Mesh: |
| 928 |
if (!FD->hasAttr<HLSLNumThreadsAttr>()) { |
| 929 |
Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads) |
| 930 |
<< llvm::Triple::getEnvironmentTypeName(ST); |
| 931 |
FD->setInvalidDecl(); |
| 932 |
} |
| 933 |
if (const auto *WS = FD->getAttr<HLSLWaveSizeAttr>()) { |
| 934 |
if (Ver < VersionTuple(6, 6)) { |
| 935 |
Diag(WS->getLocation(), diag::err_hlsl_attribute_in_wrong_shader_model) |
| 936 |
<< WS << "6.6"; |
| 937 |
FD->setInvalidDecl(); |
| 938 |
} else if (WS->getSpelledArgsCount() > 1 && Ver < VersionTuple(6, 8)) { |
| 939 |
Diag( |
| 940 |
WS->getLocation(), |
| 941 |
diag::err_hlsl_attribute_number_arguments_insufficient_shader_model) |
| 942 |
<< WS << WS->getSpelledArgsCount() << "6.8"; |
| 943 |
FD->setInvalidDecl(); |
| 944 |
} |
| 945 |
} |
| 946 |
break; |
| 947 |
case llvm::Triple::RootSignature: |
| 948 |
llvm_unreachable("rootsig environment has no function entry point"); |
| 949 |
default: |
| 950 |
llvm_unreachable("Unhandled environment in triple"); |
| 951 |
} |
| 952 |
|
| 953 |
SemaHLSL::SemanticContext InputSC = {}; |
| 954 |
InputSC.CurrentIOType = IOType::In; |
| 955 |
|
| 956 |
for (ParmVarDecl *Param : FD->parameters()) { |
| 957 |
SemanticInfo ActiveSemantic; |
| 958 |
ActiveSemantic.Semantic = Param->getAttr<HLSLParsedSemanticAttr>(); |
| 959 |
if (ActiveSemantic.Semantic) |
| 960 |
ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex(); |
| 961 |
|
| 962 |
// FIXME: Verify output semantics in parameters. |
| 963 |
if (!determineActiveSemantic(FD, Param, Param, ActiveSemantic, InputSC)) { |
| 964 |
Diag(Param->getLocation(), diag::note_previous_decl) << Param; |
| 965 |
FD->setInvalidDecl(); |
| 966 |
} |
| 967 |
} |
| 968 |
|
| 969 |
SemanticInfo ActiveSemantic; |
| 970 |
SemaHLSL::SemanticContext OutputSC = {}; |
| 971 |
OutputSC.CurrentIOType = IOType::Out; |
| 972 |
ActiveSemantic.Semantic = FD->getAttr<HLSLParsedSemanticAttr>(); |
| 973 |
if (ActiveSemantic.Semantic) |
| 974 |
ActiveSemantic.Index = ActiveSemantic.Semantic->getSemanticIndex(); |
| 975 |
if (!FD->getReturnType()->isVoidType()) |
| 976 |
determineActiveSemantic(FD, FD, FD, ActiveSemantic, OutputSC); |
| 977 |
} |
| 978 |
|
| 979 |
void SemaHLSL::checkSemanticAnnotation( |
| 980 |
FunctionDecl *EntryPoint, const Decl *Param, |
| 981 |
const HLSLAppliedSemanticAttr *SemanticAttr, const SemanticContext &SC) { |
| 982 |
auto *ShaderAttr = EntryPoint->getAttr<HLSLShaderAttr>(); |
| 983 |
assert(ShaderAttr && "Entry point has no shader attribute"); |
| 984 |
llvm::Triple::EnvironmentType ST = ShaderAttr->getType(); |
| 985 |
|
| 986 |
auto SemanticName = SemanticAttr->getSemanticName().upper(); |
| 987 |
if (SemanticName == "SV_DISPATCHTHREADID" || |
| 988 |
SemanticName == "SV_GROUPINDEX" || SemanticName == "SV_GROUPTHREADID" || |
| 989 |
SemanticName == "SV_GROUPID") { |
| 990 |
|
| 991 |
if (ST != llvm::Triple::Compute) |
| 992 |
diagnoseSemanticStageMismatch(SemanticAttr, ST, SC.CurrentIOType, |
| 993 |
{{llvm::Triple::Compute, IOType::In}}); |
| 994 |
|
| 995 |
if (SemanticAttr->getSemanticIndex() != 0) { |
| 996 |
std::string PrettyName = |
| 997 |
"'" + SemanticAttr->getSemanticName().str() + "'"; |
| 998 |
Diag(SemanticAttr->getLoc(), |
| 999 |
diag::err_hlsl_semantic_indexing_not_supported) |
| 1000 |
<< PrettyName; |
| 1001 |
} |
| 1002 |
return; |
| 1003 |
} |
| 1004 |
|
| 1005 |
if (SemanticName == "SV_POSITION") { |
| 1006 |
// SV_Position can be an input or output in vertex shaders, |
| 1007 |
// but only an input in pixel shaders. |
| 1008 |
diagnoseSemanticStageMismatch(SemanticAttr, ST, SC.CurrentIOType, |
| 1009 |
{{llvm::Triple::Vertex, IOType::InOut}, |
| 1010 |
{llvm::Triple::Pixel, IOType::In}}); |
| 1011 |
return; |
| 1012 |
} |
| 1013 |
|
| 1014 |
if (SemanticName == "SV_TARGET") { |
| 1015 |
diagnoseSemanticStageMismatch(SemanticAttr, ST, SC.CurrentIOType, |
| 1016 |
{{llvm::Triple::Pixel, IOType::Out}}); |
| 1017 |
return; |
| 1018 |
} |
| 1019 |
|
| 1020 |
// FIXME: catch-all for non-implemented system semantics reaching this |
| 1021 |
// location. |
| 1022 |
if (SemanticAttr->getAttrName()->getName().starts_with_insensitive("SV_")) |
| 1023 |
llvm_unreachable("Unknown SemanticAttr"); |
| 1024 |
} |
| 1025 |
|
| 1026 |
void SemaHLSL::diagnoseAttrStageMismatch( |
| 1027 |
const Attr *A, llvm::Triple::EnvironmentType Stage, |
| 1028 |
std::initializer_list<llvm::Triple::EnvironmentType> AllowedStages) { |
| 1029 |
SmallVector<StringRef, 8> StageStrings; |
| 1030 |
llvm::transform(AllowedStages, std::back_inserter(StageStrings), |
| 1031 |
[](llvm::Triple::EnvironmentType ST) { |
| 1032 |
return StringRef( |
| 1033 |
HLSLShaderAttr::ConvertEnvironmentTypeToStr(ST)); |
| 1034 |
}); |
| 1035 |
Diag(A->getLoc(), diag::err_hlsl_attr_unsupported_in_stage) |
| 1036 |
<< A->getAttrName() << llvm::Triple::getEnvironmentTypeName(Stage) |
| 1037 |
<< (AllowedStages.size() != 1) << join(StageStrings, ", "); |
| 1038 |
} |
| 1039 |
|
| 1040 |
void SemaHLSL::diagnoseSemanticStageMismatch( |
| 1041 |
const Attr *A, llvm::Triple::EnvironmentType Stage, IOType CurrentIOType, |
| 1042 |
std::initializer_list<SemanticStageInfo> Allowed) { |
| 1043 |
|
| 1044 |
for (auto &Case : Allowed) { |
| 1045 |
if (Case.Stage != Stage) |
| 1046 |
continue; |
| 1047 |
|
| 1048 |
if (CurrentIOType & Case.AllowedIOTypesMask) |
| 1049 |
return; |
| 1050 |
|
| 1051 |
SmallVector<std::string, 8> ValidCases; |
| 1052 |
llvm::transform( |
| 1053 |
Allowed, std::back_inserter(ValidCases), [](SemanticStageInfo Case) { |
| 1054 |
SmallVector<std::string, 2> ValidType; |
| 1055 |
if (Case.AllowedIOTypesMask & IOType::In) |
| 1056 |
ValidType.push_back("input"); |
| 1057 |
if (Case.AllowedIOTypesMask & IOType::Out) |
| 1058 |
ValidType.push_back("output"); |
| 1059 |
return std::string( |
| 1060 |
HLSLShaderAttr::ConvertEnvironmentTypeToStr(Case.Stage)) + |
| 1061 |
" " + join(ValidType, "/"); |
| 1062 |
}); |
| 1063 |
Diag(A->getLoc(), diag::err_hlsl_semantic_unsupported_iotype_for_stage) |
| 1064 |
<< A->getAttrName() << (CurrentIOType & IOType::In ? "input" : "output") |
| 1065 |
<< llvm::Triple::getEnvironmentTypeName(Case.Stage) |
| 1066 |
<< join(ValidCases, ", "); |
| 1067 |
return; |
| 1068 |
} |
| 1069 |
|
| 1070 |
SmallVector<StringRef, 8> StageStrings; |
| 1071 |
llvm::transform( |
| 1072 |
Allowed, std::back_inserter(StageStrings), [](SemanticStageInfo Case) { |
| 1073 |
return StringRef( |
| 1074 |
HLSLShaderAttr::ConvertEnvironmentTypeToStr(Case.Stage)); |
| 1075 |
}); |
| 1076 |
|
| 1077 |
Diag(A->getLoc(), diag::err_hlsl_attr_unsupported_in_stage) |
| 1078 |
<< A->getAttrName() << llvm::Triple::getEnvironmentTypeName(Stage) |
| 1079 |
<< (Allowed.size() != 1) << join(StageStrings, ", "); |
| 1080 |
} |
| 1081 |
|
| 1082 |
template <CastKind Kind> |
| 1083 |
static void castVector(Sema &S, ExprResult &E, QualType &Ty, unsigned Sz) { |
| 1084 |
if (const auto *VTy = Ty->getAs<VectorType>()) |
| 1085 |
Ty = VTy->getElementType(); |
| 1086 |
Ty = S.getASTContext().getExtVectorType(Ty, Sz); |
| 1087 |
E = S.ImpCastExprToType(E.get(), Ty, Kind); |
| 1088 |
} |
| 1089 |
|
| 1090 |
template <CastKind Kind> |
| 1091 |
static QualType castElement(Sema &S, ExprResult &E, QualType Ty) { |
| 1092 |
E = S.ImpCastExprToType(E.get(), Ty, Kind); |
| 1093 |
return Ty; |
| 1094 |
} |
| 1095 |
|
| 1096 |
static QualType handleFloatVectorBinOpConversion( |
| 1097 |
Sema &SemaRef, ExprResult &LHS, ExprResult &RHS, QualType LHSType, |
| 1098 |
QualType RHSType, QualType LElTy, QualType RElTy, bool IsCompAssign) { |
| 1099 |
bool LHSFloat = LElTy->isRealFloatingType(); |
| 1100 |
bool RHSFloat = RElTy->isRealFloatingType(); |
| 1101 |
|
| 1102 |
if (LHSFloat && RHSFloat) { |
| 1103 |
if (IsCompAssign || |
| 1104 |
SemaRef.getASTContext().getFloatingTypeOrder(LElTy, RElTy) > 0) |
| 1105 |
return castElement<CK_FloatingCast>(SemaRef, RHS, LHSType); |
| 1106 |
|
| 1107 |
return castElement<CK_FloatingCast>(SemaRef, LHS, RHSType); |
| 1108 |
} |
| 1109 |
|
| 1110 |
if (LHSFloat) |
| 1111 |
return castElement<CK_IntegralToFloating>(SemaRef, RHS, LHSType); |
| 1112 |
|
| 1113 |
assert(RHSFloat); |
| 1114 |
if (IsCompAssign) |
| 1115 |
return castElement<clang::CK_FloatingToIntegral>(SemaRef, RHS, LHSType); |
| 1116 |
|
| 1117 |
return castElement<CK_IntegralToFloating>(SemaRef, LHS, RHSType); |
| 1118 |
} |
| 1119 |
|
| 1120 |
static QualType handleIntegerVectorBinOpConversion( |
| 1121 |
Sema &SemaRef, ExprResult &LHS, ExprResult &RHS, QualType LHSType, |
| 1122 |
QualType RHSType, QualType LElTy, QualType RElTy, bool IsCompAssign) { |
| 1123 |
|
| 1124 |
int IntOrder = SemaRef.Context.getIntegerTypeOrder(LElTy, RElTy); |
| 1125 |
bool LHSSigned = LElTy->hasSignedIntegerRepresentation(); |
| 1126 |
bool RHSSigned = RElTy->hasSignedIntegerRepresentation(); |
| 1127 |
auto &Ctx = SemaRef.getASTContext(); |
| 1128 |
|
| 1129 |
// If both types have the same signedness, use the higher ranked type. |
| 1130 |
if (LHSSigned == RHSSigned) { |
| 1131 |
if (IsCompAssign || IntOrder >= 0) |
| 1132 |
return castElement<CK_IntegralCast>(SemaRef, RHS, LHSType); |
| 1133 |
|
| 1134 |
return castElement<CK_IntegralCast>(SemaRef, LHS, RHSType); |
| 1135 |
} |
| 1136 |
|
| 1137 |
// If the unsigned type has greater than or equal rank of the signed type, use |
| 1138 |
// the unsigned type. |
| 1139 |
if (IntOrder != (LHSSigned ? 1 : -1)) { |
| 1140 |
if (IsCompAssign || RHSSigned) |
| 1141 |
return castElement<CK_IntegralCast>(SemaRef, RHS, LHSType); |
| 1142 |
return castElement<CK_IntegralCast>(SemaRef, LHS, RHSType); |
| 1143 |
} |
| 1144 |
|
| 1145 |
// At this point the signed type has higher rank than the unsigned type, which |
| 1146 |
// means it will be the same size or bigger. If the signed type is bigger, it |
| 1147 |
// can represent all the values of the unsigned type, so select it. |
| 1148 |
if (Ctx.getIntWidth(LElTy) != Ctx.getIntWidth(RElTy)) { |
| 1149 |
if (IsCompAssign || LHSSigned) |
| 1150 |
return castElement<CK_IntegralCast>(SemaRef, RHS, LHSType); |
| 1151 |
return castElement<CK_IntegralCast>(SemaRef, LHS, RHSType); |
| 1152 |
} |
| 1153 |
|
| 1154 |
// This is a bit of an odd duck case in HLSL. It shouldn't happen, but can due |
| 1155 |
// to C/C++ leaking through. The place this happens today is long vs long |
| 1156 |
// long. When arguments are vector<unsigned long, N> and vector<long long, N>, |
| 1157 |
// the long long has higher rank than long even though they are the same size. |
| 1158 |
|
| 1159 |
// If this is a compound assignment cast the right hand side to the left hand |
| 1160 |
// side's type. |
| 1161 |
if (IsCompAssign) |
| 1162 |
return castElement<CK_IntegralCast>(SemaRef, RHS, LHSType); |
| 1163 |
|
| 1164 |
// If this isn't a compound assignment we convert to unsigned long long. |
| 1165 |
QualType ElTy = Ctx.getCorrespondingUnsignedType(LHSSigned ? LElTy : RElTy); |
| 1166 |
QualType NewTy = Ctx.getExtVectorType( |
| 1167 |
ElTy, RHSType->castAs<VectorType>()->getNumElements()); |
| 1168 |
(void)castElement<CK_IntegralCast>(SemaRef, RHS, NewTy); |
| 1169 |
|
| 1170 |
return castElement<CK_IntegralCast>(SemaRef, LHS, NewTy); |
| 1171 |
} |
| 1172 |
|
| 1173 |
static CastKind getScalarCastKind(ASTContext &Ctx, QualType DestTy, |
| 1174 |
QualType SrcTy) { |
| 1175 |
if (DestTy->isRealFloatingType() && SrcTy->isRealFloatingType()) |
| 1176 |
return CK_FloatingCast; |
| 1177 |
if (DestTy->isIntegralType(Ctx) && SrcTy->isIntegralType(Ctx)) |
| 1178 |
return CK_IntegralCast; |
| 1179 |
if (DestTy->isRealFloatingType()) |
| 1180 |
return CK_IntegralToFloating; |
| 1181 |
assert(SrcTy->isRealFloatingType() && DestTy->isIntegralType(Ctx)); |
| 1182 |
return CK_FloatingToIntegral; |
| 1183 |
} |
| 1184 |
|
| 1185 |
QualType SemaHLSL::handleVectorBinOpConversion(ExprResult &LHS, ExprResult &RHS, |
| 1186 |
QualType LHSType, |
| 1187 |
QualType RHSType, |
| 1188 |
bool IsCompAssign) { |
| 1189 |
const auto *LVecTy = LHSType->getAs<VectorType>(); |
| 1190 |
const auto *RVecTy = RHSType->getAs<VectorType>(); |
| 1191 |
auto &Ctx = getASTContext(); |
| 1192 |
|
| 1193 |
// If the LHS is not a vector and this is a compound assignment, we truncate |
| 1194 |
// the argument to a scalar then convert it to the LHS's type. |
| 1195 |
if (!LVecTy && IsCompAssign) { |
| 1196 |
QualType RElTy = RHSType->castAs<VectorType>()->getElementType(); |
| 1197 |
RHS = SemaRef.ImpCastExprToType(RHS.get(), RElTy, CK_HLSLVectorTruncation); |
| 1198 |
RHSType = RHS.get()->getType(); |
| 1199 |
if (Ctx.hasSameUnqualifiedType(LHSType, RHSType)) |
| 1200 |
return LHSType; |
| 1201 |
RHS = SemaRef.ImpCastExprToType(RHS.get(), LHSType, |
| 1202 |
getScalarCastKind(Ctx, LHSType, RHSType)); |
| 1203 |
return LHSType; |
| 1204 |
} |
| 1205 |
|
| 1206 |
unsigned EndSz = std::numeric_limits<unsigned>::max(); |
| 1207 |
unsigned LSz = 0; |
| 1208 |
if (LVecTy) |
| 1209 |
LSz = EndSz = LVecTy->getNumElements(); |
| 1210 |
if (RVecTy) |
| 1211 |
EndSz = std::min(RVecTy->getNumElements(), EndSz); |
| 1212 |
assert(EndSz != std::numeric_limits<unsigned>::max() && |
| 1213 |
"one of the above should have had a value"); |
| 1214 |
|
| 1215 |
// In a compound assignment, the left operand does not change type, the right |
| 1216 |
// operand is converted to the type of the left operand. |
| 1217 |
if (IsCompAssign && LSz != EndSz) { |
| 1218 |
Diag(LHS.get()->getBeginLoc(), |
| 1219 |
diag::err_hlsl_vector_compound_assignment_truncation) |
| 1220 |
<< LHSType << RHSType; |
| 1221 |
return QualType(); |
| 1222 |
} |
| 1223 |
|
| 1224 |
if (RVecTy && RVecTy->getNumElements() > EndSz) |
| 1225 |
castVector<CK_HLSLVectorTruncation>(SemaRef, RHS, RHSType, EndSz); |
| 1226 |
if (!IsCompAssign && LVecTy && LVecTy->getNumElements() > EndSz) |
| 1227 |
castVector<CK_HLSLVectorTruncation>(SemaRef, LHS, LHSType, EndSz); |
| 1228 |
|
| 1229 |
if (!RVecTy) |
| 1230 |
castVector<CK_VectorSplat>(SemaRef, RHS, RHSType, EndSz); |
| 1231 |
if (!IsCompAssign && !LVecTy) |
| 1232 |
castVector<CK_VectorSplat>(SemaRef, LHS, LHSType, EndSz); |
| 1233 |
|
| 1234 |
// If we're at the same type after resizing we can stop here. |
| 1235 |
if (Ctx.hasSameUnqualifiedType(LHSType, RHSType)) |
| 1236 |
return Ctx.getCommonSugaredType(LHSType, RHSType); |
| 1237 |
|
| 1238 |
QualType LElTy = LHSType->castAs<VectorType>()->getElementType(); |
| 1239 |
QualType RElTy = RHSType->castAs<VectorType>()->getElementType(); |
| 1240 |
|
| 1241 |
// Handle conversion for floating point vectors. |
| 1242 |
if (LElTy->isRealFloatingType() || RElTy->isRealFloatingType()) |
| 1243 |
return handleFloatVectorBinOpConversion(SemaRef, LHS, RHS, LHSType, RHSType, |
| 1244 |
LElTy, RElTy, IsCompAssign); |
| 1245 |
|
| 1246 |
assert(LElTy->isIntegralType(Ctx) && RElTy->isIntegralType(Ctx) && |
| 1247 |
"HLSL Vectors can only contain integer or floating point types"); |
| 1248 |
return handleIntegerVectorBinOpConversion(SemaRef, LHS, RHS, LHSType, RHSType, |
| 1249 |
LElTy, RElTy, IsCompAssign); |
| 1250 |
} |
| 1251 |
|
| 1252 |
void SemaHLSL::emitLogicalOperatorFixIt(Expr *LHS, Expr *RHS, |
| 1253 |
BinaryOperatorKind Opc) { |
| 1254 |
assert((Opc == BO_LOr || Opc == BO_LAnd) && |
| 1255 |
"Called with non-logical operator"); |
| 1256 |
llvm::SmallVector<char, 256> Buff; |
| 1257 |
llvm::raw_svector_ostream OS(Buff); |
| 1258 |
PrintingPolicy PP(SemaRef.getLangOpts()); |
| 1259 |
StringRef NewFnName = Opc == BO_LOr ? "or" : "and"; |
| 1260 |
OS << NewFnName << "("; |
| 1261 |
LHS->printPretty(OS, nullptr, PP); |
| 1262 |
OS << ", "; |
| 1263 |
RHS->printPretty(OS, nullptr, PP); |
| 1264 |
OS << ")"; |
| 1265 |
SourceRange FullRange = SourceRange(LHS->getBeginLoc(), RHS->getEndLoc()); |
| 1266 |
SemaRef.Diag(LHS->getBeginLoc(), diag::note_function_suggestion) |
| 1267 |
<< NewFnName << FixItHint::CreateReplacement(FullRange, OS.str()); |
| 1268 |
} |
| 1269 |
|
| 1270 |
std::pair<IdentifierInfo *, bool> |
| 1271 |
SemaHLSL::ActOnStartRootSignatureDecl(StringRef Signature) { |
| 1272 |
llvm::hash_code Hash = llvm::hash_value(Signature); |
| 1273 |
std::string IdStr = "__hlsl_rootsig_decl_" + std::to_string(Hash); |
| 1274 |
IdentifierInfo *DeclIdent = &(getASTContext().Idents.get(IdStr)); |
| 1275 |
|
| 1276 |
// Check if we have already found a decl of the same name. |
| 1277 |
LookupResult R(SemaRef, DeclIdent, SourceLocation(), |
| 1278 |
Sema::LookupOrdinaryName); |
| 1279 |
bool Found = SemaRef.LookupQualifiedName(R, SemaRef.CurContext); |
| 1280 |
return {DeclIdent, Found}; |
| 1281 |
} |
| 1282 |
|
| 1283 |
void SemaHLSL::ActOnFinishRootSignatureDecl( |
| 1284 |
SourceLocation Loc, IdentifierInfo *DeclIdent, |
| 1285 |
ArrayRef<hlsl::RootSignatureElement> RootElements) { |
| 1286 |
|
| 1287 |
if (handleRootSignatureElements(RootElements)) |
| 1288 |
return; |
| 1289 |
|
| 1290 |
SmallVector<llvm::hlsl::rootsig::RootElement> Elements; |
| 1291 |
for (auto &RootSigElement : RootElements) |
| 1292 |
Elements.push_back(RootSigElement.getElement()); |
| 1293 |
|
| 1294 |
auto *SignatureDecl = HLSLRootSignatureDecl::Create( |
| 1295 |
SemaRef.getASTContext(), /*DeclContext=*/SemaRef.CurContext, Loc, |
| 1296 |
DeclIdent, SemaRef.getLangOpts().HLSLRootSigVer, Elements); |
| 1297 |
|
| 1298 |
SignatureDecl->setImplicit(); |
| 1299 |
SemaRef.PushOnScopeChains(SignatureDecl, SemaRef.getCurScope()); |
| 1300 |
} |
| 1301 |
|
| 1302 |
HLSLRootSignatureDecl * |
| 1303 |
SemaHLSL::lookupRootSignatureOverrideDecl(DeclContext *DC) const { |
| 1304 |
if (RootSigOverrideIdent) { |
| 1305 |
LookupResult R(SemaRef, RootSigOverrideIdent, SourceLocation(), |
| 1306 |
Sema::LookupOrdinaryName); |
| 1307 |
if (SemaRef.LookupQualifiedName(R, DC)) |
| 1308 |
return dyn_cast<HLSLRootSignatureDecl>(R.getFoundDecl()); |
| 1309 |
} |
| 1310 |
|
| 1311 |
return nullptr; |
| 1312 |
} |
| 1313 |
|
| 1314 |
namespace { |
| 1315 |
|
| 1316 |
struct PerVisibilityBindingChecker { |
| 1317 |
SemaHLSL *S; |
| 1318 |
// We need one builder per `llvm::dxbc::ShaderVisibility` value. |
| 1319 |
std::array<llvm::hlsl::BindingInfoBuilder, 8> Builders; |
| 1320 |
|
| 1321 |
struct ElemInfo { |
| 1322 |
const hlsl::RootSignatureElement *Elem; |
| 1323 |
llvm::dxbc::ShaderVisibility Vis; |
| 1324 |
bool Diagnosed; |
| 1325 |
}; |
| 1326 |
llvm::SmallVector<ElemInfo> ElemInfoMap; |
| 1327 |
|
| 1328 |
PerVisibilityBindingChecker(SemaHLSL *S) : S(S) {} |
| 1329 |
|
| 1330 |
void trackBinding(llvm::dxbc::ShaderVisibility Visibility, |
| 1331 |
llvm::dxil::ResourceClass RC, uint32_t Space, |
| 1332 |
uint32_t LowerBound, uint32_t UpperBound, |
| 1333 |
const hlsl::RootSignatureElement *Elem) { |
| 1334 |
uint32_t BuilderIndex = llvm::to_underlying(Visibility); |
| 1335 |
assert(BuilderIndex < Builders.size() && |
| 1336 |
"Not enough builders for visibility type"); |
| 1337 |
Builders[BuilderIndex].trackBinding(RC, Space, LowerBound, UpperBound, |
| 1338 |
static_cast<const void *>(Elem)); |
| 1339 |
|
| 1340 |
static_assert(llvm::to_underlying(llvm::dxbc::ShaderVisibility::All) == 0, |
| 1341 |
"'All' visibility must come first"); |
| 1342 |
if (Visibility == llvm::dxbc::ShaderVisibility::All) |
| 1343 |
for (size_t I = 1, E = Builders.size(); I < E; ++I) |
| 1344 |
Builders[I].trackBinding(RC, Space, LowerBound, UpperBound, |
| 1345 |
static_cast<const void *>(Elem)); |
| 1346 |
|
| 1347 |
ElemInfoMap.push_back({Elem, Visibility, false}); |
| 1348 |
} |
| 1349 |
|
| 1350 |
ElemInfo &getInfo(const hlsl::RootSignatureElement *Elem) { |
| 1351 |
auto It = llvm::lower_bound( |
| 1352 |
ElemInfoMap, Elem, |
| 1353 |
[](const auto &LHS, const auto &RHS) { return LHS.Elem < RHS; }); |
| 1354 |
assert(It->Elem == Elem && "Element not in map"); |
| 1355 |
return *It; |
| 1356 |
} |
| 1357 |
|
| 1358 |
bool checkOverlap() { |
| 1359 |
llvm::sort(ElemInfoMap, [](const auto &LHS, const auto &RHS) { |
| 1360 |
return LHS.Elem < RHS.Elem; |
| 1361 |
}); |
| 1362 |
|
| 1363 |
bool HadOverlap = false; |
| 1364 |
|
| 1365 |
using llvm::hlsl::BindingInfoBuilder; |
| 1366 |
auto ReportOverlap = [this, |
| 1367 |
&HadOverlap](const BindingInfoBuilder &Builder, |
| 1368 |
const llvm::hlsl::Binding &Reported) { |
| 1369 |
HadOverlap = true; |
| 1370 |
|
| 1371 |
const auto *Elem = |
| 1372 |
static_cast<const hlsl::RootSignatureElement *>(Reported.Cookie); |
| 1373 |
const llvm::hlsl::Binding &Previous = Builder.findOverlapping(Reported); |
| 1374 |
const auto *PrevElem = |
| 1375 |
static_cast<const hlsl::RootSignatureElement *>(Previous.Cookie); |
| 1376 |
|
| 1377 |
ElemInfo &Info = getInfo(Elem); |
| 1378 |
// We will have already diagnosed this binding if there's overlap in the |
| 1379 |
// "All" visibility as well as any particular visibility. |
| 1380 |
if (Info.Diagnosed) |
| 1381 |
return; |
| 1382 |
Info.Diagnosed = true; |
| 1383 |
|
| 1384 |
ElemInfo &PrevInfo = getInfo(PrevElem); |
| 1385 |
llvm::dxbc::ShaderVisibility CommonVis = |
| 1386 |
Info.Vis == llvm::dxbc::ShaderVisibility::All ? PrevInfo.Vis |
| 1387 |
: Info.Vis; |
| 1388 |
|
| 1389 |
this->S->Diag(Elem->getLocation(), diag::err_hlsl_resource_range_overlap) |
| 1390 |
<< llvm::to_underlying(Reported.RC) << Reported.LowerBound |
| 1391 |
<< Reported.isUnbounded() << Reported.UpperBound |
| 1392 |
<< llvm::to_underlying(Previous.RC) << Previous.LowerBound |
| 1393 |
<< Previous.isUnbounded() << Previous.UpperBound << Reported.Space |
| 1394 |
<< CommonVis; |
| 1395 |
|
| 1396 |
this->S->Diag(PrevElem->getLocation(), |
| 1397 |
diag::note_hlsl_resource_range_here); |
| 1398 |
}; |
| 1399 |
|
| 1400 |
for (BindingInfoBuilder &Builder : Builders) |
| 1401 |
Builder.calculateBindingInfo(ReportOverlap); |
| 1402 |
|
| 1403 |
return HadOverlap; |
| 1404 |
} |
| 1405 |
}; |
| 1406 |
|
| 1407 |
static CXXMethodDecl *lookupMethod(Sema &S, CXXRecordDecl *RecordDecl, |
| 1408 |
StringRef Name, SourceLocation Loc) { |
| 1409 |
DeclarationName DeclName(&S.getASTContext().Idents.get(Name)); |
| 1410 |
LookupResult Result(S, DeclName, Loc, Sema::LookupMemberName); |
| 1411 |
if (!S.LookupQualifiedName(Result, static_cast<DeclContext *>(RecordDecl))) |
| 1412 |
return nullptr; |
| 1413 |
return cast<CXXMethodDecl>(Result.getFoundDecl()); |
| 1414 |
} |
| 1415 |
|
| 1416 |
} // end anonymous namespace |
| 1417 |
|
| 1418 |
static bool hasCounterHandle(const CXXRecordDecl *RD) { |
| 1419 |
if (RD->field_empty()) |
| 1420 |
return false; |
| 1421 |
auto It = std::next(RD->field_begin()); |
| 1422 |
if (It == RD->field_end()) |
| 1423 |
return false; |
| 1424 |
const FieldDecl *SecondField = *It; |
| 1425 |
if (const auto *ResTy = |
| 1426 |
SecondField->getType()->getAs<HLSLAttributedResourceType>()) { |
| 1427 |
return ResTy->getAttrs().IsCounter; |
| 1428 |
} |
| 1429 |
return false; |
| 1430 |
} |
| 1431 |
|
| 1432 |
bool SemaHLSL::handleRootSignatureElements( |
| 1433 |
ArrayRef<hlsl::RootSignatureElement> Elements) { |
| 1434 |
// Define some common error handling functions |
| 1435 |
bool HadError = false; |
| 1436 |
auto ReportError = [this, &HadError](SourceLocation Loc, uint32_t LowerBound, |
| 1437 |
uint32_t UpperBound) { |
| 1438 |
HadError = true; |
| 1439 |
this->Diag(Loc, diag::err_hlsl_invalid_rootsig_value) |
| 1440 |
<< LowerBound << UpperBound; |
| 1441 |
}; |
| 1442 |
|
| 1443 |
auto ReportFloatError = [this, &HadError](SourceLocation Loc, |
| 1444 |
float LowerBound, |
| 1445 |
float UpperBound) { |
| 1446 |
HadError = true; |
| 1447 |
this->Diag(Loc, diag::err_hlsl_invalid_rootsig_value) |
| 1448 |
<< llvm::formatv("{0:f}", LowerBound).sstr<6>() |
| 1449 |
<< llvm::formatv("{0:f}", UpperBound).sstr<6>(); |
| 1450 |
}; |
| 1451 |
|
| 1452 |
auto VerifyRegister = [ReportError](SourceLocation Loc, uint32_t Register) { |
| 1453 |
if (!llvm::hlsl::rootsig::verifyRegisterValue(Register)) |
| 1454 |
ReportError(Loc, 0, 0xfffffffe); |
| 1455 |
}; |
| 1456 |
|
| 1457 |
auto VerifySpace = [ReportError](SourceLocation Loc, uint32_t Space) { |
| 1458 |
if (!llvm::hlsl::rootsig::verifyRegisterSpace(Space)) |
| 1459 |
ReportError(Loc, 0, 0xffffffef); |
| 1460 |
}; |
| 1461 |
|
| 1462 |
const uint32_t Version = |
| 1463 |
llvm::to_underlying(SemaRef.getLangOpts().HLSLRootSigVer); |
| 1464 |
const uint32_t VersionEnum = Version - 1; |
| 1465 |
auto ReportFlagError = [this, &HadError, VersionEnum](SourceLocation Loc) { |
| 1466 |
HadError = true; |
| 1467 |
this->Diag(Loc, diag::err_hlsl_invalid_rootsig_flag) |
| 1468 |
<< /*version minor*/ VersionEnum; |
| 1469 |
}; |
| 1470 |
|
| 1471 |
// Iterate through the elements and do basic validations |
| 1472 |
for (const hlsl::RootSignatureElement &RootSigElem : Elements) { |
| 1473 |
SourceLocation Loc = RootSigElem.getLocation(); |
| 1474 |
const llvm::hlsl::rootsig::RootElement &Elem = RootSigElem.getElement(); |
| 1475 |
if (const auto *Descriptor = |
| 1476 |
std::get_if<llvm::hlsl::rootsig::RootDescriptor>(&Elem)) { |
| 1477 |
VerifyRegister(Loc, Descriptor->Reg.Number); |
| 1478 |
VerifySpace(Loc, Descriptor->Space); |
| 1479 |
|
| 1480 |
if (!llvm::hlsl::rootsig::verifyRootDescriptorFlag(Version, |
| 1481 |
Descriptor->Flags)) |
| 1482 |
ReportFlagError(Loc); |
| 1483 |
} else if (const auto *Constants = |
| 1484 |
std::get_if<llvm::hlsl::rootsig::RootConstants>(&Elem)) { |
| 1485 |
VerifyRegister(Loc, Constants->Reg.Number); |
| 1486 |
VerifySpace(Loc, Constants->Space); |
| 1487 |
} else if (const auto *Sampler = |
| 1488 |
std::get_if<llvm::hlsl::rootsig::StaticSampler>(&Elem)) { |
| 1489 |
VerifyRegister(Loc, Sampler->Reg.Number); |
| 1490 |
VerifySpace(Loc, Sampler->Space); |
| 1491 |
|
| 1492 |
assert(!std::isnan(Sampler->MaxLOD) && !std::isnan(Sampler->MinLOD) && |
| 1493 |
"By construction, parseFloatParam can't produce a NaN from a " |
| 1494 |
"float_literal token"); |
| 1495 |
|
| 1496 |
if (!llvm::hlsl::rootsig::verifyMaxAnisotropy(Sampler->MaxAnisotropy)) |
| 1497 |
ReportError(Loc, 0, 16); |
| 1498 |
if (!llvm::hlsl::rootsig::verifyMipLODBias(Sampler->MipLODBias)) |
| 1499 |
ReportFloatError(Loc, -16.f, 15.99f); |
| 1500 |
} else if (const auto *Clause = |
| 1501 |
std::get_if<llvm::hlsl::rootsig::DescriptorTableClause>( |
| 1502 |
&Elem)) { |
| 1503 |
VerifyRegister(Loc, Clause->Reg.Number); |
| 1504 |
VerifySpace(Loc, Clause->Space); |
| 1505 |
|
| 1506 |
if (!llvm::hlsl::rootsig::verifyNumDescriptors(Clause->NumDescriptors)) { |
| 1507 |
// NumDescriptor could techincally be ~0u but that is reserved for |
| 1508 |
// unbounded, so the diagnostic will not report that as a valid int |
| 1509 |
// value |
| 1510 |
ReportError(Loc, 1, 0xfffffffe); |
| 1511 |
} |
| 1512 |
|
| 1513 |
if (!llvm::hlsl::rootsig::verifyDescriptorRangeFlag(Version, Clause->Type, |
| 1514 |
Clause->Flags)) |
| 1515 |
ReportFlagError(Loc); |
| 1516 |
} |
| 1517 |
} |
| 1518 |
|
| 1519 |
PerVisibilityBindingChecker BindingChecker(this); |
| 1520 |
SmallVector<std::pair<const llvm::hlsl::rootsig::DescriptorTableClause *, |
| 1521 |
const hlsl::RootSignatureElement *>> |
| 1522 |
UnboundClauses; |
| 1523 |
|
| 1524 |
for (const hlsl::RootSignatureElement &RootSigElem : Elements) { |
| 1525 |
const llvm::hlsl::rootsig::RootElement &Elem = RootSigElem.getElement(); |
| 1526 |
if (const auto *Descriptor = |
| 1527 |
std::get_if<llvm::hlsl::rootsig::RootDescriptor>(&Elem)) { |
| 1528 |
uint32_t LowerBound(Descriptor->Reg.Number); |
| 1529 |
uint32_t UpperBound(LowerBound); // inclusive range |
| 1530 |
|
| 1531 |
BindingChecker.trackBinding( |
| 1532 |
Descriptor->Visibility, |
| 1533 |
static_cast<llvm::dxil::ResourceClass>(Descriptor->Type), |
| 1534 |
Descriptor->Space, LowerBound, UpperBound, &RootSigElem); |
| 1535 |
} else if (const auto *Constants = |
| 1536 |
std::get_if<llvm::hlsl::rootsig::RootConstants>(&Elem)) { |
| 1537 |
uint32_t LowerBound(Constants->Reg.Number); |
| 1538 |
uint32_t UpperBound(LowerBound); // inclusive range |
| 1539 |
|
| 1540 |
BindingChecker.trackBinding( |
| 1541 |
Constants->Visibility, llvm::dxil::ResourceClass::CBuffer, |
| 1542 |
Constants->Space, LowerBound, UpperBound, &RootSigElem); |
| 1543 |
} else if (const auto *Sampler = |
| 1544 |
std::get_if<llvm::hlsl::rootsig::StaticSampler>(&Elem)) { |
| 1545 |
uint32_t LowerBound(Sampler->Reg.Number); |
| 1546 |
uint32_t UpperBound(LowerBound); // inclusive range |
| 1547 |
|
| 1548 |
BindingChecker.trackBinding( |
| 1549 |
Sampler->Visibility, llvm::dxil::ResourceClass::Sampler, |
| 1550 |
Sampler->Space, LowerBound, UpperBound, &RootSigElem); |
| 1551 |
} else if (const auto *Clause = |
| 1552 |
std::get_if<llvm::hlsl::rootsig::DescriptorTableClause>( |
| 1553 |
&Elem)) { |
| 1554 |
// We'll process these once we see the table element. |
| 1555 |
UnboundClauses.emplace_back(Clause, &RootSigElem); |
| 1556 |
} else if (const auto *Table = |
| 1557 |
std::get_if<llvm::hlsl::rootsig::DescriptorTable>(&Elem)) { |
| 1558 |
assert(UnboundClauses.size() == Table->NumClauses && |
| 1559 |
"Number of unbound elements must match the number of clauses"); |
| 1560 |
bool HasAnySampler = false; |
| 1561 |
bool HasAnyNonSampler = false; |
| 1562 |
uint64_t Offset = 0; |
| 1563 |
bool IsPrevUnbound = false; |
| 1564 |
for (const auto &[Clause, ClauseElem] : UnboundClauses) { |
| 1565 |
SourceLocation Loc = ClauseElem->getLocation(); |
| 1566 |
if (Clause->Type == llvm::dxil::ResourceClass::Sampler) |
| 1567 |
HasAnySampler = true; |
| 1568 |
else |
| 1569 |
HasAnyNonSampler = true; |
| 1570 |
|
| 1571 |
if (HasAnySampler && HasAnyNonSampler) |
| 1572 |
Diag(Loc, diag::err_hlsl_invalid_mixed_resources); |
| 1573 |
|
| 1574 |
// Relevant error will have already been reported above and needs to be |
| 1575 |
// fixed before we can conduct further analysis, so shortcut error |
| 1576 |
// return |
| 1577 |
if (Clause->NumDescriptors == 0) |
| 1578 |
return true; |
| 1579 |
|
| 1580 |
bool IsAppending = |
| 1581 |
Clause->Offset == llvm::hlsl::rootsig::DescriptorTableOffsetAppend; |
| 1582 |
if (!IsAppending) |
| 1583 |
Offset = Clause->Offset; |
| 1584 |
|
| 1585 |
uint64_t RangeBound = llvm::hlsl::rootsig::computeRangeBound( |
| 1586 |
Offset, Clause->NumDescriptors); |
| 1587 |
|
| 1588 |
if (IsPrevUnbound && IsAppending) |
| 1589 |
Diag(Loc, diag::err_hlsl_appending_onto_unbound); |
| 1590 |
else if (!llvm::hlsl::rootsig::verifyNoOverflowedOffset(RangeBound)) |
| 1591 |
Diag(Loc, diag::err_hlsl_offset_overflow) << Offset << RangeBound; |
| 1592 |
|
| 1593 |
// Update offset to be 1 past this range's bound |
| 1594 |
Offset = RangeBound + 1; |
| 1595 |
IsPrevUnbound = Clause->NumDescriptors == |
| 1596 |
llvm::hlsl::rootsig::NumDescriptorsUnbounded; |
| 1597 |
|
| 1598 |
// Compute the register bounds and track resource binding |
| 1599 |
uint32_t LowerBound(Clause->Reg.Number); |
| 1600 |
uint32_t UpperBound = llvm::hlsl::rootsig::computeRangeBound( |
| 1601 |
LowerBound, Clause->NumDescriptors); |
| 1602 |
|
| 1603 |
BindingChecker.trackBinding( |
| 1604 |
Table->Visibility, |
| 1605 |
static_cast<llvm::dxil::ResourceClass>(Clause->Type), Clause->Space, |
| 1606 |
LowerBound, UpperBound, ClauseElem); |
| 1607 |
} |
| 1608 |
UnboundClauses.clear(); |
| 1609 |
} |
| 1610 |
} |
| 1611 |
|
| 1612 |
return BindingChecker.checkOverlap(); |
| 1613 |
} |
| 1614 |
|
| 1615 |
void SemaHLSL::handleRootSignatureAttr(Decl *D, const ParsedAttr &AL) { |
| 1616 |
if (AL.getNumArgs() != 1) { |
| 1617 |
Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1; |
| 1618 |
return; |
| 1619 |
} |
| 1620 |
|
| 1621 |
IdentifierInfo *Ident = AL.getArgAsIdent(0)->getIdentifierInfo(); |
| 1622 |
if (auto *RS = D->getAttr<RootSignatureAttr>()) { |
| 1623 |
if (RS->getSignatureIdent() != Ident) { |
| 1624 |
Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << RS; |
| 1625 |
return; |
| 1626 |
} |
| 1627 |
|
| 1628 |
Diag(AL.getLoc(), diag::warn_duplicate_attribute_exact) << RS; |
| 1629 |
return; |
| 1630 |
} |
| 1631 |
|
| 1632 |
LookupResult R(SemaRef, Ident, SourceLocation(), Sema::LookupOrdinaryName); |
| 1633 |
if (SemaRef.LookupQualifiedName(R, D->getDeclContext())) |
| 1634 |
if (auto *SignatureDecl = |
| 1635 |
dyn_cast<HLSLRootSignatureDecl>(R.getFoundDecl())) { |
| 1636 |
D->addAttr(::new (getASTContext()) RootSignatureAttr( |
| 1637 |
getASTContext(), AL, Ident, SignatureDecl)); |
| 1638 |
} |
| 1639 |
} |
| 1640 |
|
| 1641 |
void SemaHLSL::handleNumThreadsAttr(Decl *D, const ParsedAttr &AL) { |
| 1642 |
llvm::VersionTuple SMVersion = |
| 1643 |
getASTContext().getTargetInfo().getTriple().getOSVersion(); |
| 1644 |
bool IsDXIL = getASTContext().getTargetInfo().getTriple().getArch() == |
| 1645 |
llvm::Triple::dxil; |
| 1646 |
|
| 1647 |
uint32_t ZMax = 1024; |
| 1648 |
uint32_t ThreadMax = 1024; |
| 1649 |
if (IsDXIL && SMVersion.getMajor() <= 4) { |
| 1650 |
ZMax = 1; |
| 1651 |
ThreadMax = 768; |
| 1652 |
} else if (IsDXIL && SMVersion.getMajor() == 5) { |
| 1653 |
ZMax = 64; |
| 1654 |
ThreadMax = 1024; |
| 1655 |
} |
| 1656 |
|
| 1657 |
uint32_t X; |
| 1658 |
if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), X)) |
| 1659 |
return; |
| 1660 |
if (X > 1024) { |
| 1661 |
Diag(AL.getArgAsExpr(0)->getExprLoc(), |
| 1662 |
diag::err_hlsl_numthreads_argument_oor) |
| 1663 |
<< 0 << 1024; |
| 1664 |
return; |
| 1665 |
} |
| 1666 |
uint32_t Y; |
| 1667 |
if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(1), Y)) |
| 1668 |
return; |
| 1669 |
if (Y > 1024) { |
| 1670 |
Diag(AL.getArgAsExpr(1)->getExprLoc(), |
| 1671 |
diag::err_hlsl_numthreads_argument_oor) |
| 1672 |
<< 1 << 1024; |
| 1673 |
return; |
| 1674 |
} |
| 1675 |
uint32_t Z; |
| 1676 |
if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(2), Z)) |
| 1677 |
return; |
| 1678 |
if (Z > ZMax) { |
| 1679 |
SemaRef.Diag(AL.getArgAsExpr(2)->getExprLoc(), |
| 1680 |
diag::err_hlsl_numthreads_argument_oor) |
| 1681 |
<< 2 << ZMax; |
| 1682 |
return; |
| 1683 |
} |
| 1684 |
|
| 1685 |
if (X * Y * Z > ThreadMax) { |
| 1686 |
Diag(AL.getLoc(), diag::err_hlsl_numthreads_invalid) << ThreadMax; |
| 1687 |
return; |
| 1688 |
} |
| 1689 |
|
| 1690 |
HLSLNumThreadsAttr *NewAttr = mergeNumThreadsAttr(D, AL, X, Y, Z); |
| 1691 |
if (NewAttr) |
| 1692 |
D->addAttr(NewAttr); |
| 1693 |
} |
| 1694 |
|
| 1695 |
static bool isValidWaveSizeValue(unsigned Value) { |
| 1696 |
return llvm::isPowerOf2_32(Value) && Value >= 4 && Value <= 128; |
| 1697 |
} |
| 1698 |
|
| 1699 |
void SemaHLSL::handleWaveSizeAttr(Decl *D, const ParsedAttr &AL) { |
| 1700 |
// validate that the wavesize argument is a power of 2 between 4 and 128 |
| 1701 |
// inclusive |
| 1702 |
unsigned SpelledArgsCount = AL.getNumArgs(); |
| 1703 |
if (SpelledArgsCount == 0 || SpelledArgsCount > 3) |
| 1704 |
return; |
| 1705 |
|
| 1706 |
uint32_t Min; |
| 1707 |
if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), Min)) |
| 1708 |
return; |
| 1709 |
|
| 1710 |
uint32_t Max = 0; |
| 1711 |
if (SpelledArgsCount > 1 && |
| 1712 |
!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(1), Max)) |
| 1713 |
return; |
| 1714 |
|
| 1715 |
uint32_t Preferred = 0; |
| 1716 |
if (SpelledArgsCount > 2 && |
| 1717 |
!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(2), Preferred)) |
| 1718 |
return; |
| 1719 |
|
| 1720 |
if (SpelledArgsCount > 2) { |
| 1721 |
if (!isValidWaveSizeValue(Preferred)) { |
| 1722 |
Diag(AL.getArgAsExpr(2)->getExprLoc(), |
| 1723 |
diag::err_attribute_power_of_two_in_range) |
| 1724 |
<< AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize |
| 1725 |
<< Preferred; |
| 1726 |
return; |
| 1727 |
} |
| 1728 |
// Preferred not in range. |
| 1729 |
if (Preferred < Min || Preferred > Max) { |
| 1730 |
Diag(AL.getArgAsExpr(2)->getExprLoc(), |
| 1731 |
diag::err_attribute_power_of_two_in_range) |
| 1732 |
<< AL << Min << Max << Preferred; |
| 1733 |
return; |
| 1734 |
} |
| 1735 |
} else if (SpelledArgsCount > 1) { |
| 1736 |
if (!isValidWaveSizeValue(Max)) { |
| 1737 |
Diag(AL.getArgAsExpr(1)->getExprLoc(), |
| 1738 |
diag::err_attribute_power_of_two_in_range) |
| 1739 |
<< AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize << Max; |
| 1740 |
return; |
| 1741 |
} |
| 1742 |
if (Max < Min) { |
| 1743 |
Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 1; |
| 1744 |
return; |
| 1745 |
} else if (Max == Min) { |
| 1746 |
Diag(AL.getLoc(), diag::warn_attr_min_eq_max) << AL; |
| 1747 |
} |
| 1748 |
} else { |
| 1749 |
if (!isValidWaveSizeValue(Min)) { |
| 1750 |
Diag(AL.getArgAsExpr(0)->getExprLoc(), |
| 1751 |
diag::err_attribute_power_of_two_in_range) |
| 1752 |
<< AL << llvm::dxil::MinWaveSize << llvm::dxil::MaxWaveSize << Min; |
| 1753 |
return; |
| 1754 |
} |
| 1755 |
} |
| 1756 |
|
| 1757 |
HLSLWaveSizeAttr *NewAttr = |
| 1758 |
mergeWaveSizeAttr(D, AL, Min, Max, Preferred, SpelledArgsCount); |
| 1759 |
if (NewAttr) |
| 1760 |
D->addAttr(NewAttr); |
| 1761 |
} |
| 1762 |
|
| 1763 |
void SemaHLSL::handleVkExtBuiltinInputAttr(Decl *D, const ParsedAttr &AL) { |
| 1764 |
uint32_t ID; |
| 1765 |
if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), ID)) |
| 1766 |
return; |
| 1767 |
D->addAttr(::new (getASTContext()) |
| 1768 |
HLSLVkExtBuiltinInputAttr(getASTContext(), AL, ID)); |
| 1769 |
} |
| 1770 |
|
| 1771 |
void SemaHLSL::handleVkPushConstantAttr(Decl *D, const ParsedAttr &AL) { |
| 1772 |
D->addAttr(::new (getASTContext()) |
| 1773 |
HLSLVkPushConstantAttr(getASTContext(), AL)); |
| 1774 |
} |
| 1775 |
|
| 1776 |
void SemaHLSL::handleVkConstantIdAttr(Decl *D, const ParsedAttr &AL) { |
| 1777 |
uint32_t Id; |
| 1778 |
if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), Id)) |
| 1779 |
return; |
| 1780 |
HLSLVkConstantIdAttr *NewAttr = mergeVkConstantIdAttr(D, AL, Id); |
| 1781 |
if (NewAttr) |
| 1782 |
D->addAttr(NewAttr); |
| 1783 |
} |
| 1784 |
|
| 1785 |
void SemaHLSL::handleVkBindingAttr(Decl *D, const ParsedAttr &AL) { |
| 1786 |
uint32_t Binding = 0; |
| 1787 |
if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), Binding)) |
| 1788 |
return; |
| 1789 |
uint32_t Set = 0; |
| 1790 |
if (AL.getNumArgs() > 1 && |
| 1791 |
!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(1), Set)) |
| 1792 |
return; |
| 1793 |
|
| 1794 |
D->addAttr(::new (getASTContext()) |
| 1795 |
HLSLVkBindingAttr(getASTContext(), AL, Binding, Set)); |
| 1796 |
} |
| 1797 |
|
| 1798 |
void SemaHLSL::handleVkLocationAttr(Decl *D, const ParsedAttr &AL) { |
| 1799 |
uint32_t Location; |
| 1800 |
if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), Location)) |
| 1801 |
return; |
| 1802 |
|
| 1803 |
D->addAttr(::new (getASTContext()) |
| 1804 |
HLSLVkLocationAttr(getASTContext(), AL, Location)); |
| 1805 |
} |
| 1806 |
|
| 1807 |
bool SemaHLSL::diagnoseInputIDType(QualType T, const ParsedAttr &AL) { |
| 1808 |
const auto *VT = T->getAs<VectorType>(); |
| 1809 |
|
| 1810 |
if (!T->hasUnsignedIntegerRepresentation() || |
| 1811 |
(VT && VT->getNumElements() > 3)) { |
| 1812 |
Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_type) |
| 1813 |
<< AL << "uint/uint2/uint3"; |
| 1814 |
return false; |
| 1815 |
} |
| 1816 |
|
| 1817 |
return true; |
| 1818 |
} |
| 1819 |
|
| 1820 |
bool SemaHLSL::diagnosePositionType(QualType T, const ParsedAttr &AL) { |
| 1821 |
const auto *VT = T->getAs<VectorType>(); |
| 1822 |
if (!T->hasFloatingRepresentation() || (VT && VT->getNumElements() > 4)) { |
| 1823 |
Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_type) |
| 1824 |
<< AL << "float/float1/float2/float3/float4"; |
| 1825 |
return false; |
| 1826 |
} |
| 1827 |
|
| 1828 |
return true; |
| 1829 |
} |
| 1830 |
|
| 1831 |
void SemaHLSL::diagnoseSystemSemanticAttr(Decl *D, const ParsedAttr &AL, |
| 1832 |
std::optional<unsigned> Index) { |
| 1833 |
std::string SemanticName = AL.getAttrName()->getName().upper(); |
| 1834 |
|
| 1835 |
auto *VD = cast<ValueDecl>(D); |
| 1836 |
QualType ValueType = VD->getType(); |
| 1837 |
if (auto *FD = dyn_cast<FunctionDecl>(D)) |
| 1838 |
ValueType = FD->getReturnType(); |
| 1839 |
|
| 1840 |
bool IsOutput = false; |
| 1841 |
if (HLSLParamModifierAttr *MA = D->getAttr<HLSLParamModifierAttr>()) { |
| 1842 |
if (MA->isOut()) { |
| 1843 |
IsOutput = true; |
| 1844 |
ValueType = cast<ReferenceType>(ValueType)->getPointeeType(); |
| 1845 |
} |
| 1846 |
} |
| 1847 |
|
| 1848 |
if (SemanticName == "SV_DISPATCHTHREADID") { |
| 1849 |
diagnoseInputIDType(ValueType, AL); |
| 1850 |
if (IsOutput) |
| 1851 |
Diag(AL.getLoc(), diag::err_hlsl_semantic_output_not_supported) << AL; |
| 1852 |
if (Index.has_value()) |
| 1853 |
Diag(AL.getLoc(), diag::err_hlsl_semantic_indexing_not_supported) << AL; |
| 1854 |
D->addAttr(createSemanticAttr<HLSLParsedSemanticAttr>(AL, Index)); |
| 1855 |
return; |
| 1856 |
} |
| 1857 |
|
| 1858 |
if (SemanticName == "SV_GROUPINDEX") { |
| 1859 |
if (IsOutput) |
| 1860 |
Diag(AL.getLoc(), diag::err_hlsl_semantic_output_not_supported) << AL; |
| 1861 |
if (Index.has_value()) |
| 1862 |
Diag(AL.getLoc(), diag::err_hlsl_semantic_indexing_not_supported) << AL; |
| 1863 |
D->addAttr(createSemanticAttr<HLSLParsedSemanticAttr>(AL, Index)); |
| 1864 |
return; |
| 1865 |
} |
| 1866 |
|
| 1867 |
if (SemanticName == "SV_GROUPTHREADID") { |
| 1868 |
diagnoseInputIDType(ValueType, AL); |
| 1869 |
if (IsOutput) |
| 1870 |
Diag(AL.getLoc(), diag::err_hlsl_semantic_output_not_supported) << AL; |
| 1871 |
if (Index.has_value()) |
| 1872 |
Diag(AL.getLoc(), diag::err_hlsl_semantic_indexing_not_supported) << AL; |
| 1873 |
D->addAttr(createSemanticAttr<HLSLParsedSemanticAttr>(AL, Index)); |
| 1874 |
return; |
| 1875 |
} |
| 1876 |
|
| 1877 |
if (SemanticName == "SV_GROUPID") { |
| 1878 |
diagnoseInputIDType(ValueType, AL); |
| 1879 |
if (IsOutput) |
| 1880 |
Diag(AL.getLoc(), diag::err_hlsl_semantic_output_not_supported) << AL; |
| 1881 |
if (Index.has_value()) |
| 1882 |
Diag(AL.getLoc(), diag::err_hlsl_semantic_indexing_not_supported) << AL; |
| 1883 |
D->addAttr(createSemanticAttr<HLSLParsedSemanticAttr>(AL, Index)); |
| 1884 |
return; |
| 1885 |
} |
| 1886 |
|
| 1887 |
if (SemanticName == "SV_POSITION") { |
| 1888 |
const auto *VT = ValueType->getAs<VectorType>(); |
| 1889 |
if (!ValueType->hasFloatingRepresentation() || |
| 1890 |
(VT && VT->getNumElements() > 4)) |
| 1891 |
Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_type) |
| 1892 |
<< AL << "float/float1/float2/float3/float4"; |
| 1893 |
D->addAttr(createSemanticAttr<HLSLParsedSemanticAttr>(AL, Index)); |
| 1894 |
return; |
| 1895 |
} |
| 1896 |
|
| 1897 |
if (SemanticName == "SV_TARGET") { |
| 1898 |
const auto *VT = ValueType->getAs<VectorType>(); |
| 1899 |
if (!ValueType->hasFloatingRepresentation() || |
| 1900 |
(VT && VT->getNumElements() > 4)) |
| 1901 |
Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_type) |
| 1902 |
<< AL << "float/float1/float2/float3/float4"; |
| 1903 |
D->addAttr(createSemanticAttr<HLSLParsedSemanticAttr>(AL, Index)); |
| 1904 |
return; |
| 1905 |
} |
| 1906 |
|
| 1907 |
Diag(AL.getLoc(), diag::err_hlsl_unknown_semantic) << AL; |
| 1908 |
} |
| 1909 |
|
| 1910 |
void SemaHLSL::handleSemanticAttr(Decl *D, const ParsedAttr &AL) { |
| 1911 |
uint32_t IndexValue(0), ExplicitIndex(0); |
| 1912 |
if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), IndexValue) || |
| 1913 |
!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(1), ExplicitIndex)) { |
| 1914 |
assert(0 && "HLSLUnparsedSemantic is expected to have 2 int arguments."); |
| 1915 |
} |
| 1916 |
assert(IndexValue > 0 ? ExplicitIndex : true); |
| 1917 |
std::optional<unsigned> Index = |
| 1918 |
ExplicitIndex ? std::optional<unsigned>(IndexValue) : std::nullopt; |
| 1919 |
|
| 1920 |
if (AL.getAttrName()->getName().starts_with_insensitive("SV_")) |
| 1921 |
diagnoseSystemSemanticAttr(D, AL, Index); |
| 1922 |
else |
| 1923 |
D->addAttr(createSemanticAttr<HLSLParsedSemanticAttr>(AL, Index)); |
| 1924 |
} |
| 1925 |
|
| 1926 |
void SemaHLSL::handlePackOffsetAttr(Decl *D, const ParsedAttr &AL) { |
| 1927 |
if (!isa<VarDecl>(D) || !isa<HLSLBufferDecl>(D->getDeclContext())) { |
| 1928 |
Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_ast_node) |
| 1929 |
<< AL << "shader constant in a constant buffer"; |
| 1930 |
return; |
| 1931 |
} |
| 1932 |
|
| 1933 |
uint32_t SubComponent; |
| 1934 |
if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(0), SubComponent)) |
| 1935 |
return; |
| 1936 |
uint32_t Component; |
| 1937 |
if (!SemaRef.checkUInt32Argument(AL, AL.getArgAsExpr(1), Component)) |
| 1938 |
return; |
| 1939 |
|
| 1940 |
QualType T = cast<VarDecl>(D)->getType().getCanonicalType(); |
| 1941 |
// Check if T is an array or struct type. |
| 1942 |
// TODO: mark matrix type as aggregate type. |
| 1943 |
bool IsAggregateTy = (T->isArrayType() || T->isStructureType()); |
| 1944 |
|
| 1945 |
// Check Component is valid for T. |
| 1946 |
if (Component) { |
| 1947 |
unsigned Size = getASTContext().getTypeSize(T); |
| 1948 |
if (IsAggregateTy) { |
| 1949 |
Diag(AL.getLoc(), diag::err_hlsl_invalid_register_or_packoffset); |
| 1950 |
return; |
| 1951 |
} else { |
| 1952 |
// Make sure Component + sizeof(T) <= 4. |
| 1953 |
if ((Component * 32 + Size) > 128) { |
| 1954 |
Diag(AL.getLoc(), diag::err_hlsl_packoffset_cross_reg_boundary); |
| 1955 |
return; |
| 1956 |
} |
| 1957 |
QualType EltTy = T; |
| 1958 |
if (const auto *VT = T->getAs<VectorType>()) |
| 1959 |
EltTy = VT->getElementType(); |
| 1960 |
unsigned Align = getASTContext().getTypeAlign(EltTy); |
| 1961 |
if (Align > 32 && Component == 1) { |
| 1962 |
// NOTE: Component 3 will hit err_hlsl_packoffset_cross_reg_boundary. |
| 1963 |
// So we only need to check Component 1 here. |
| 1964 |
Diag(AL.getLoc(), diag::err_hlsl_packoffset_alignment_mismatch) |
| 1965 |
<< Align << EltTy; |
| 1966 |
return; |
| 1967 |
} |
| 1968 |
} |
| 1969 |
} |
| 1970 |
|
| 1971 |
D->addAttr(::new (getASTContext()) HLSLPackOffsetAttr( |
| 1972 |
getASTContext(), AL, SubComponent, Component)); |
| 1973 |
} |
| 1974 |
|
| 1975 |
void SemaHLSL::handleShaderAttr(Decl *D, const ParsedAttr &AL) { |
| 1976 |
StringRef Str; |
| 1977 |
SourceLocation ArgLoc; |
| 1978 |
if (!SemaRef.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) |
| 1979 |
return; |
| 1980 |
|
| 1981 |
llvm::Triple::EnvironmentType ShaderType; |
| 1982 |
if (!HLSLShaderAttr::ConvertStrToEnvironmentType(Str, ShaderType)) { |
| 1983 |
Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) |
| 1984 |
<< AL << Str << ArgLoc; |
| 1985 |
return; |
| 1986 |
} |
| 1987 |
|
| 1988 |
// FIXME: check function match the shader stage. |
| 1989 |
|
| 1990 |
HLSLShaderAttr *NewAttr = mergeShaderAttr(D, AL, ShaderType); |
| 1991 |
if (NewAttr) |
| 1992 |
D->addAttr(NewAttr); |
| 1993 |
} |
| 1994 |
|
| 1995 |
bool clang::CreateHLSLAttributedResourceType( |
| 1996 |
Sema &S, QualType Wrapped, ArrayRef<const Attr *> AttrList, |
| 1997 |
QualType &ResType, HLSLAttributedResourceLocInfo *LocInfo) { |
| 1998 |
assert(AttrList.size() && "expected list of resource attributes"); |
| 1999 |
|
| 2000 |
QualType ContainedTy = QualType(); |
| 2001 |
TypeSourceInfo *ContainedTyInfo = nullptr; |
| 2002 |
SourceLocation LocBegin = AttrList[0]->getRange().getBegin(); |
| 2003 |
SourceLocation LocEnd = AttrList[0]->getRange().getEnd(); |
| 2004 |
|
| 2005 |
HLSLAttributedResourceType::Attributes ResAttrs; |
| 2006 |
|
| 2007 |
bool HasResourceClass = false; |
| 2008 |
for (const Attr *A : AttrList) { |
| 2009 |
if (!A) |
| 2010 |
continue; |
| 2011 |
LocEnd = A->getRange().getEnd(); |
| 2012 |
switch (A->getKind()) { |
| 2013 |
case attr::HLSLResourceClass: { |
| 2014 |
ResourceClass RC = cast<HLSLResourceClassAttr>(A)->getResourceClass(); |
| 2015 |
if (HasResourceClass) { |
| 2016 |
S.Diag(A->getLocation(), ResAttrs.ResourceClass == RC |
| 2017 |
? diag::warn_duplicate_attribute_exact |
| 2018 |
: diag::warn_duplicate_attribute) |
| 2019 |
<< A; |
| 2020 |
return false; |
| 2021 |
} |
| 2022 |
ResAttrs.ResourceClass = RC; |
| 2023 |
HasResourceClass = true; |
| 2024 |
break; |
| 2025 |
} |
| 2026 |
case attr::HLSLROV: |
| 2027 |
if (ResAttrs.IsROV) { |
| 2028 |
S.Diag(A->getLocation(), diag::warn_duplicate_attribute_exact) << A; |
| 2029 |
return false; |
| 2030 |
} |
| 2031 |
ResAttrs.IsROV = true; |
| 2032 |
break; |
| 2033 |
case attr::HLSLRawBuffer: |
| 2034 |
if (ResAttrs.RawBuffer) { |
| 2035 |
S.Diag(A->getLocation(), diag::warn_duplicate_attribute_exact) << A; |
| 2036 |
return false; |
| 2037 |
} |
| 2038 |
ResAttrs.RawBuffer = true; |
| 2039 |
break; |
| 2040 |
case attr::HLSLIsCounter: |
| 2041 |
if (ResAttrs.IsCounter) { |
| 2042 |
S.Diag(A->getLocation(), diag::warn_duplicate_attribute_exact) << A; |
| 2043 |
return false; |
| 2044 |
} |
| 2045 |
ResAttrs.IsCounter = true; |
| 2046 |
break; |
| 2047 |
case attr::HLSLContainedType: { |
| 2048 |
const HLSLContainedTypeAttr *CTAttr = cast<HLSLContainedTypeAttr>(A); |
| 2049 |
QualType Ty = CTAttr->getType(); |
| 2050 |
if (!ContainedTy.isNull()) { |
| 2051 |
S.Diag(A->getLocation(), ContainedTy == Ty |
| 2052 |
? diag::warn_duplicate_attribute_exact |
| 2053 |
: diag::warn_duplicate_attribute) |
| 2054 |
<< A; |
| 2055 |
return false; |
| 2056 |
} |
| 2057 |
ContainedTy = Ty; |
| 2058 |
ContainedTyInfo = CTAttr->getTypeLoc(); |
| 2059 |
break; |
| 2060 |
} |
| 2061 |
default: |
| 2062 |
llvm_unreachable("unhandled resource attribute type"); |
| 2063 |
} |
| 2064 |
} |
| 2065 |
|
| 2066 |
if (!HasResourceClass) { |
| 2067 |
S.Diag(AttrList.back()->getRange().getEnd(), |
| 2068 |
diag::err_hlsl_missing_resource_class); |
| 2069 |
return false; |
| 2070 |
} |
| 2071 |
|
| 2072 |
ResType = S.getASTContext().getHLSLAttributedResourceType( |
| 2073 |
Wrapped, ContainedTy, ResAttrs); |
| 2074 |
|
| 2075 |
if (LocInfo && ContainedTyInfo) { |
| 2076 |
LocInfo->Range = SourceRange(LocBegin, LocEnd); |
| 2077 |
LocInfo->ContainedTyInfo = ContainedTyInfo; |
| 2078 |
} |
| 2079 |
return true; |
| 2080 |
} |
| 2081 |
|
| 2082 |
// Validates and creates an HLSL attribute that is applied as type attribute on |
| 2083 |
// HLSL resource. The attributes are collected in HLSLResourcesTypeAttrs and at |
| 2084 |
// the end of the declaration they are applied to the declaration type by |
| 2085 |
// wrapping it in HLSLAttributedResourceType. |
| 2086 |
bool SemaHLSL::handleResourceTypeAttr(QualType T, const ParsedAttr &AL) { |
| 2087 |
// only allow resource type attributes on intangible types |
| 2088 |
if (!T->isHLSLResourceType()) { |
| 2089 |
Diag(AL.getLoc(), diag::err_hlsl_attribute_needs_intangible_type) |
| 2090 |
<< AL << getASTContext().HLSLResourceTy; |
| 2091 |
return false; |
| 2092 |
} |
| 2093 |
|
| 2094 |
// validate number of arguments |
| 2095 |
if (!AL.checkExactlyNumArgs(SemaRef, AL.getMinArgs())) |
| 2096 |
return false; |
| 2097 |
|
| 2098 |
Attr *A = nullptr; |
| 2099 |
|
| 2100 |
AttributeCommonInfo ACI( |
| 2101 |
AL.getLoc(), AttributeScopeInfo(AL.getScopeName(), AL.getScopeLoc()), |
| 2102 |
AttributeCommonInfo::NoSemaHandlerAttribute, |
| 2103 |
{ |
| 2104 |
AttributeCommonInfo::AS_CXX11, 0, false /*IsAlignas*/, |
| 2105 |
false /*IsRegularKeywordAttribute*/ |
| 2106 |
}); |
| 2107 |
|
| 2108 |
switch (AL.getKind()) { |
| 2109 |
case ParsedAttr::AT_HLSLResourceClass: { |
| 2110 |
if (!AL.isArgIdent(0)) { |
| 2111 |
Diag(AL.getLoc(), diag::err_attribute_argument_type) |
| 2112 |
<< AL << AANT_ArgumentIdentifier; |
| 2113 |
return false; |
| 2114 |
} |
| 2115 |
|
| 2116 |
IdentifierLoc *Loc = AL.getArgAsIdent(0); |
| 2117 |
StringRef Identifier = Loc->getIdentifierInfo()->getName(); |
| 2118 |
SourceLocation ArgLoc = Loc->getLoc(); |
| 2119 |
|
| 2120 |
// Validate resource class value |
| 2121 |
ResourceClass RC; |
| 2122 |
if (!HLSLResourceClassAttr::ConvertStrToResourceClass(Identifier, RC)) { |
| 2123 |
Diag(ArgLoc, diag::warn_attribute_type_not_supported) |
| 2124 |
<< "ResourceClass" << Identifier; |
| 2125 |
return false; |
| 2126 |
} |
| 2127 |
A = HLSLResourceClassAttr::Create(getASTContext(), RC, ACI); |
| 2128 |
break; |
| 2129 |
} |
| 2130 |
|
| 2131 |
case ParsedAttr::AT_HLSLROV: |
| 2132 |
A = HLSLROVAttr::Create(getASTContext(), ACI); |
| 2133 |
break; |
| 2134 |
|
| 2135 |
case ParsedAttr::AT_HLSLRawBuffer: |
| 2136 |
A = HLSLRawBufferAttr::Create(getASTContext(), ACI); |
| 2137 |
break; |
| 2138 |
|
| 2139 |
case ParsedAttr::AT_HLSLIsCounter: |
| 2140 |
A = HLSLIsCounterAttr::Create(getASTContext(), ACI); |
| 2141 |
break; |
| 2142 |
|
| 2143 |
case ParsedAttr::AT_HLSLContainedType: { |
| 2144 |
if (AL.getNumArgs() != 1 && !AL.hasParsedType()) { |
| 2145 |
Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1; |
| 2146 |
return false; |
| 2147 |
} |
| 2148 |
|
| 2149 |
TypeSourceInfo *TSI = nullptr; |
| 2150 |
QualType QT = SemaRef.GetTypeFromParser(AL.getTypeArg(), &TSI); |
| 2151 |
assert(TSI && "no type source info for attribute argument"); |
| 2152 |
if (SemaRef.RequireCompleteType(TSI->getTypeLoc().getBeginLoc(), QT, |
| 2153 |
diag::err_incomplete_type)) |
| 2154 |
return false; |
| 2155 |
A = HLSLContainedTypeAttr::Create(getASTContext(), TSI, ACI); |
| 2156 |
break; |
| 2157 |
} |
| 2158 |
|
| 2159 |
default: |
| 2160 |
llvm_unreachable("unhandled HLSL attribute"); |
| 2161 |
} |
| 2162 |
|
| 2163 |
HLSLResourcesTypeAttrs.emplace_back(A); |
| 2164 |
return true; |
| 2165 |
} |
| 2166 |
|
| 2167 |
// Combines all resource type attributes and creates HLSLAttributedResourceType. |
| 2168 |
QualType SemaHLSL::ProcessResourceTypeAttributes(QualType CurrentType) { |
| 2169 |
if (!HLSLResourcesTypeAttrs.size()) |
| 2170 |
return CurrentType; |
| 2171 |
|
| 2172 |
QualType QT = CurrentType; |
| 2173 |
HLSLAttributedResourceLocInfo LocInfo; |
| 2174 |
if (CreateHLSLAttributedResourceType(SemaRef, CurrentType, |
| 2175 |
HLSLResourcesTypeAttrs, QT, &LocInfo)) { |
| 2176 |
const HLSLAttributedResourceType *RT = |
| 2177 |
cast<HLSLAttributedResourceType>(QT.getTypePtr()); |
| 2178 |
|
| 2179 |
// Temporarily store TypeLoc information for the new type. |
| 2180 |
// It will be transferred to HLSLAttributesResourceTypeLoc |
| 2181 |
// shortly after the type is created by TypeSpecLocFiller which |
| 2182 |
// will call the TakeLocForHLSLAttribute method below. |
| 2183 |
LocsForHLSLAttributedResources.insert(std::pair(RT, LocInfo)); |
| 2184 |
} |
| 2185 |
HLSLResourcesTypeAttrs.clear(); |
| 2186 |
return QT; |
| 2187 |
} |
| 2188 |
|
| 2189 |
// Returns source location for the HLSLAttributedResourceType |
| 2190 |
HLSLAttributedResourceLocInfo |
| 2191 |
SemaHLSL::TakeLocForHLSLAttribute(const HLSLAttributedResourceType *RT) { |
| 2192 |
HLSLAttributedResourceLocInfo LocInfo = {}; |
| 2193 |
auto I = LocsForHLSLAttributedResources.find(RT); |
| 2194 |
if (I != LocsForHLSLAttributedResources.end()) { |
| 2195 |
LocInfo = I->second; |
| 2196 |
LocsForHLSLAttributedResources.erase(I); |
| 2197 |
return LocInfo; |
| 2198 |
} |
| 2199 |
LocInfo.Range = SourceRange(); |
| 2200 |
return LocInfo; |
| 2201 |
} |
| 2202 |
|
| 2203 |
// Walks though the global variable declaration, collects all resource binding |
| 2204 |
// requirements and adds them to Bindings |
| 2205 |
void SemaHLSL::collectResourceBindingsOnUserRecordDecl(const VarDecl *VD, |
| 2206 |
const RecordType *RT) { |
| 2207 |
const RecordDecl *RD = RT->getDecl()->getDefinitionOrSelf(); |
| 2208 |
for (FieldDecl *FD : RD->fields()) { |
| 2209 |
const Type *Ty = FD->getType()->getUnqualifiedDesugaredType(); |
| 2210 |
|
| 2211 |
// Unwrap arrays |
| 2212 |
// FIXME: Calculate array size while unwrapping |
| 2213 |
assert(!Ty->isIncompleteArrayType() && |
| 2214 |
"incomplete arrays inside user defined types are not supported"); |
| 2215 |
while (Ty->isConstantArrayType()) { |
| 2216 |
const ConstantArrayType *CAT = cast<ConstantArrayType>(Ty); |
| 2217 |
Ty = CAT->getElementType()->getUnqualifiedDesugaredType(); |
| 2218 |
} |
| 2219 |
|
| 2220 |
if (!Ty->isRecordType()) |
| 2221 |
continue; |
| 2222 |
|
| 2223 |
if (const HLSLAttributedResourceType *AttrResType = |
| 2224 |
HLSLAttributedResourceType::findHandleTypeOnResource(Ty)) { |
| 2225 |
// Add a new DeclBindingInfo to Bindings if it does not already exist |
| 2226 |
ResourceClass RC = AttrResType->getAttrs().ResourceClass; |
| 2227 |
DeclBindingInfo *DBI = Bindings.getDeclBindingInfo(VD, RC); |
| 2228 |
if (!DBI) |
| 2229 |
Bindings.addDeclBindingInfo(VD, RC); |
| 2230 |
} else if (const RecordType *RT = dyn_cast<RecordType>(Ty)) { |
| 2231 |
// Recursively scan embedded struct or class; it would be nice to do this |
| 2232 |
// without recursion, but tricky to correctly calculate the size of the |
| 2233 |
// binding, which is something we are probably going to need to do later |
| 2234 |
// on. Hopefully nesting of structs in structs too many levels is |
| 2235 |
// unlikely. |
| 2236 |
collectResourceBindingsOnUserRecordDecl(VD, RT); |
| 2237 |
} |
| 2238 |
} |
| 2239 |
} |
| 2240 |
|
| 2241 |
// Diagnose localized register binding errors for a single binding; does not |
| 2242 |
// diagnose resource binding on user record types, that will be done later |
| 2243 |
// in processResourceBindingOnDecl based on the information collected in |
| 2244 |
// collectResourceBindingsOnVarDecl. |
| 2245 |
// Returns false if the register binding is not valid. |
| 2246 |
static bool DiagnoseLocalRegisterBinding(Sema &S, SourceLocation &ArgLoc, |
| 2247 |
Decl *D, RegisterType RegType, |
| 2248 |
bool SpecifiedSpace) { |
| 2249 |
int RegTypeNum = static_cast<int>(RegType); |
| 2250 |
|
| 2251 |
// check if the decl type is groupshared |
| 2252 |
if (D->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) { |
| 2253 |
S.Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum; |
| 2254 |
return false; |
| 2255 |
} |
| 2256 |
|
| 2257 |
// Cbuffers and Tbuffers are HLSLBufferDecl types |
| 2258 |
if (HLSLBufferDecl *CBufferOrTBuffer = dyn_cast<HLSLBufferDecl>(D)) { |
| 2259 |
ResourceClass RC = CBufferOrTBuffer->isCBuffer() ? ResourceClass::CBuffer |
| 2260 |
: ResourceClass::SRV; |
| 2261 |
if (RegType == getRegisterType(RC)) |
| 2262 |
return true; |
| 2263 |
|
| 2264 |
S.Diag(D->getLocation(), diag::err_hlsl_binding_type_mismatch) |
| 2265 |
<< RegTypeNum; |
| 2266 |
return false; |
| 2267 |
} |
| 2268 |
|
| 2269 |
// Samplers, UAVs, and SRVs are VarDecl types |
| 2270 |
assert(isa<VarDecl>(D) && "D is expected to be VarDecl or HLSLBufferDecl"); |
| 2271 |
VarDecl *VD = cast<VarDecl>(D); |
| 2272 |
|
| 2273 |
// Resource |
| 2274 |
if (const HLSLAttributedResourceType *AttrResType = |
| 2275 |
HLSLAttributedResourceType::findHandleTypeOnResource( |
| 2276 |
VD->getType().getTypePtr())) { |
| 2277 |
if (RegType == getRegisterType(AttrResType)) |
| 2278 |
return true; |
| 2279 |
|
| 2280 |
S.Diag(D->getLocation(), diag::err_hlsl_binding_type_mismatch) |
| 2281 |
<< RegTypeNum; |
| 2282 |
return false; |
| 2283 |
} |
| 2284 |
|
| 2285 |
const clang::Type *Ty = VD->getType().getTypePtr(); |
| 2286 |
while (Ty->isArrayType()) |
| 2287 |
Ty = Ty->getArrayElementTypeNoTypeQual(); |
| 2288 |
|
| 2289 |
// Basic types |
| 2290 |
if (Ty->isArithmeticType() || Ty->isVectorType()) { |
| 2291 |
bool DeclaredInCOrTBuffer = isa<HLSLBufferDecl>(D->getDeclContext()); |
| 2292 |
if (SpecifiedSpace && !DeclaredInCOrTBuffer) |
| 2293 |
S.Diag(ArgLoc, diag::err_hlsl_space_on_global_constant); |
| 2294 |
|
| 2295 |
if (!DeclaredInCOrTBuffer && (Ty->isIntegralType(S.getASTContext()) || |
| 2296 |
Ty->isFloatingType() || Ty->isVectorType())) { |
| 2297 |
// Register annotation on default constant buffer declaration ($Globals) |
| 2298 |
if (RegType == RegisterType::CBuffer) |
| 2299 |
S.Diag(ArgLoc, diag::warn_hlsl_deprecated_register_type_b); |
| 2300 |
else if (RegType != RegisterType::C) |
| 2301 |
S.Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum; |
| 2302 |
else |
| 2303 |
return true; |
| 2304 |
} else { |
| 2305 |
if (RegType == RegisterType::C) |
| 2306 |
S.Diag(ArgLoc, diag::warn_hlsl_register_type_c_packoffset); |
| 2307 |
else |
| 2308 |
S.Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum; |
| 2309 |
} |
| 2310 |
return false; |
| 2311 |
} |
| 2312 |
if (Ty->isRecordType()) |
| 2313 |
// RecordTypes will be diagnosed in processResourceBindingOnDecl |
| 2314 |
// that is called from ActOnVariableDeclarator |
| 2315 |
return true; |
| 2316 |
|
| 2317 |
// Anything else is an error |
| 2318 |
S.Diag(ArgLoc, diag::err_hlsl_binding_type_mismatch) << RegTypeNum; |
| 2319 |
return false; |
| 2320 |
} |
| 2321 |
|
| 2322 |
static bool ValidateMultipleRegisterAnnotations(Sema &S, Decl *TheDecl, |
| 2323 |
RegisterType regType) { |
| 2324 |
// make sure that there are no two register annotations |
| 2325 |
// applied to the decl with the same register type |
| 2326 |
bool RegisterTypesDetected[5] = {false}; |
| 2327 |
RegisterTypesDetected[static_cast<int>(regType)] = true; |
| 2328 |
|
| 2329 |
for (auto it = TheDecl->attr_begin(); it != TheDecl->attr_end(); ++it) { |
| 2330 |
if (HLSLResourceBindingAttr *attr = |
| 2331 |
dyn_cast<HLSLResourceBindingAttr>(*it)) { |
| 2332 |
|
| 2333 |
RegisterType otherRegType = attr->getRegisterType(); |
| 2334 |
if (RegisterTypesDetected[static_cast<int>(otherRegType)]) { |
| 2335 |
int otherRegTypeNum = static_cast<int>(otherRegType); |
| 2336 |
S.Diag(TheDecl->getLocation(), |
| 2337 |
diag::err_hlsl_duplicate_register_annotation) |
| 2338 |
<< otherRegTypeNum; |
| 2339 |
return false; |
| 2340 |
} |
| 2341 |
RegisterTypesDetected[static_cast<int>(otherRegType)] = true; |
| 2342 |
} |
| 2343 |
} |
| 2344 |
return true; |
| 2345 |
} |
| 2346 |
|
| 2347 |
static bool DiagnoseHLSLRegisterAttribute(Sema &S, SourceLocation &ArgLoc, |
| 2348 |
Decl *D, RegisterType RegType, |
| 2349 |
bool SpecifiedSpace) { |
| 2350 |
|
| 2351 |
// exactly one of these two types should be set |
| 2352 |
assert(((isa<VarDecl>(D) && !isa<HLSLBufferDecl>(D)) || |
| 2353 |
(!isa<VarDecl>(D) && isa<HLSLBufferDecl>(D))) && |
| 2354 |
"expecting VarDecl or HLSLBufferDecl"); |
| 2355 |
|
| 2356 |
// check if the declaration contains resource matching the register type |
| 2357 |
if (!DiagnoseLocalRegisterBinding(S, ArgLoc, D, RegType, SpecifiedSpace)) |
| 2358 |
return false; |
| 2359 |
|
| 2360 |
// next, if multiple register annotations exist, check that none conflict. |
| 2361 |
return ValidateMultipleRegisterAnnotations(S, D, RegType); |
| 2362 |
} |
| 2363 |
|
| 2364 |
// return false if the slot count exceeds the limit, true otherwise |
| 2365 |
static bool AccumulateHLSLResourceSlots(QualType Ty, uint64_t &StartSlot, |
| 2366 |
const uint64_t &Limit, |
| 2367 |
const ResourceClass ResClass, |
| 2368 |
ASTContext &Ctx, |
| 2369 |
uint64_t ArrayCount = 1) { |
| 2370 |
Ty = Ty.getCanonicalType(); |
| 2371 |
const Type *T = Ty.getTypePtr(); |
| 2372 |
|
| 2373 |
// Early exit if already overflowed |
| 2374 |
if (StartSlot > Limit) |
| 2375 |
return false; |
| 2376 |
|
| 2377 |
// Case 1: array type |
| 2378 |
if (const auto *AT = dyn_cast<ArrayType>(T)) { |
| 2379 |
uint64_t Count = 1; |
| 2380 |
|
| 2381 |
if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) |
| 2382 |
Count = CAT->getSize().getZExtValue(); |
| 2383 |
|
| 2384 |
QualType ElemTy = AT->getElementType(); |
| 2385 |
return AccumulateHLSLResourceSlots(ElemTy, StartSlot, Limit, ResClass, Ctx, |
| 2386 |
ArrayCount * Count); |
| 2387 |
} |
| 2388 |
|
| 2389 |
// Case 2: resource leaf |
| 2390 |
if (auto ResTy = dyn_cast<HLSLAttributedResourceType>(T)) { |
| 2391 |
// First ensure this resource counts towards the corresponding |
| 2392 |
// register type limit. |
| 2393 |
if (ResTy->getAttrs().ResourceClass != ResClass) |
| 2394 |
return true; |
| 2395 |
|
| 2396 |
// Validate highest slot used |
| 2397 |
uint64_t EndSlot = StartSlot + ArrayCount - 1; |
| 2398 |
if (EndSlot > Limit) |
| 2399 |
return false; |
| 2400 |
|
| 2401 |
// Advance SlotCount past the consumed range |
| 2402 |
StartSlot = EndSlot + 1; |
| 2403 |
return true; |
| 2404 |
} |
| 2405 |
|
| 2406 |
// Case 3: struct / record |
| 2407 |
if (const auto *RT = dyn_cast<RecordType>(T)) { |
| 2408 |
const RecordDecl *RD = RT->getDecl(); |
| 2409 |
|
| 2410 |
if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { |
| 2411 |
for (const CXXBaseSpecifier &Base : CXXRD->bases()) { |
| 2412 |
if (!AccumulateHLSLResourceSlots(Base.getType(), StartSlot, Limit, |
| 2413 |
ResClass, Ctx, ArrayCount)) |
| 2414 |
return false; |
| 2415 |
} |
| 2416 |
} |
| 2417 |
|
| 2418 |
for (const FieldDecl *Field : RD->fields()) { |
| 2419 |
if (!AccumulateHLSLResourceSlots(Field->getType(), StartSlot, Limit, |
| 2420 |
ResClass, Ctx, ArrayCount)) |
| 2421 |
return false; |
| 2422 |
} |
| 2423 |
|
| 2424 |
return true; |
| 2425 |
} |
| 2426 |
|
| 2427 |
// Case 4: everything else |
| 2428 |
return true; |
| 2429 |
} |
| 2430 |
|
| 2431 |
// return true if there is something invalid, false otherwise |
| 2432 |
static bool ValidateRegisterNumber(const StringRef SlotNumStr, Decl *TheDecl, |
| 2433 |
ASTContext &Ctx, RegisterType RegTy, |
| 2434 |
unsigned &Result) { |
| 2435 |
uint64_t SlotNum; |
| 2436 |
if (SlotNumStr.getAsInteger(10, SlotNum)) |
| 2437 |
return true; |
| 2438 |
|
| 2439 |
const uint64_t Limit = UINT32_MAX; |
| 2440 |
if (SlotNum > Limit) |
| 2441 |
return true; |
| 2442 |
|
| 2443 |
// after verifying the number doesn't exceed uint32max, we don't need |
| 2444 |
// to look further into c or i register types |
| 2445 |
if (RegTy == RegisterType::C || RegTy == RegisterType::I) { |
| 2446 |
SlotNumStr.getAsInteger(10, Result); |
| 2447 |
return false; |
| 2448 |
} |
| 2449 |
|
| 2450 |
if (VarDecl *VD = dyn_cast<VarDecl>(TheDecl)) { |
| 2451 |
uint64_t BaseSlot = SlotNum; |
| 2452 |
|
| 2453 |
if (!AccumulateHLSLResourceSlots(VD->getType(), SlotNum, Limit, |
| 2454 |
getResourceClass(RegTy), Ctx)) |
| 2455 |
return true; |
| 2456 |
|
| 2457 |
// After AccumulateHLSLResourceSlots runs, SlotNum is now |
| 2458 |
// the first free slot; last used was SlotNum - 1 |
| 2459 |
if (BaseSlot > Limit) |
| 2460 |
return true; |
| 2461 |
|
| 2462 |
SlotNumStr.getAsInteger(10, Result); |
| 2463 |
return false; |
| 2464 |
} |
| 2465 |
// handle the cbuffer/tbuffer case |
| 2466 |
if (dyn_cast<HLSLBufferDecl>(TheDecl)) { |
| 2467 |
// resources cannot be put within a cbuffer, so no need |
| 2468 |
// to analyze the structure since the register number |
| 2469 |
// won't be pushed any higher. |
| 2470 |
if (SlotNum > Limit) |
| 2471 |
return true; |
| 2472 |
|
| 2473 |
SlotNumStr.getAsInteger(10, Result); |
| 2474 |
return false; |
| 2475 |
} |
| 2476 |
|
| 2477 |
// we don't expect any other decl type, so fail |
| 2478 |
return true; |
| 2479 |
} |
| 2480 |
|
| 2481 |
void SemaHLSL::handleResourceBindingAttr(Decl *TheDecl, const ParsedAttr &AL) { |
| 2482 |
if (VarDecl *VD = dyn_cast<VarDecl>(TheDecl)) { |
| 2483 |
QualType Ty = VD->getType(); |
| 2484 |
if (const auto *IAT = dyn_cast<IncompleteArrayType>(Ty)) |
| 2485 |
Ty = IAT->getElementType(); |
| 2486 |
if (SemaRef.RequireCompleteType(TheDecl->getBeginLoc(), Ty, |
| 2487 |
diag::err_incomplete_type)) |
| 2488 |
return; |
| 2489 |
} |
| 2490 |
|
| 2491 |
StringRef Slot = ""; |
| 2492 |
StringRef Space = ""; |
| 2493 |
SourceLocation SlotLoc, SpaceLoc; |
| 2494 |
|
| 2495 |
if (!AL.isArgIdent(0)) { |
| 2496 |
Diag(AL.getLoc(), diag::err_attribute_argument_type) |
| 2497 |
<< AL << AANT_ArgumentIdentifier; |
| 2498 |
return; |
| 2499 |
} |
| 2500 |
IdentifierLoc *Loc = AL.getArgAsIdent(0); |
| 2501 |
|
| 2502 |
if (AL.getNumArgs() == 2) { |
| 2503 |
Slot = Loc->getIdentifierInfo()->getName(); |
| 2504 |
SlotLoc = Loc->getLoc(); |
| 2505 |
if (!AL.isArgIdent(1)) { |
| 2506 |
Diag(AL.getLoc(), diag::err_attribute_argument_type) |
| 2507 |
<< AL << AANT_ArgumentIdentifier; |
| 2508 |
return; |
| 2509 |
} |
| 2510 |
Loc = AL.getArgAsIdent(1); |
| 2511 |
Space = Loc->getIdentifierInfo()->getName(); |
| 2512 |
SpaceLoc = Loc->getLoc(); |
| 2513 |
} else { |
| 2514 |
StringRef Str = Loc->getIdentifierInfo()->getName(); |
| 2515 |
if (Str.starts_with("space")) { |
| 2516 |
Space = Str; |
| 2517 |
SpaceLoc = Loc->getLoc(); |
| 2518 |
} else { |
| 2519 |
Slot = Str; |
| 2520 |
SlotLoc = Loc->getLoc(); |
| 2521 |
Space = "space0"; |
| 2522 |
} |
| 2523 |
} |
| 2524 |
|
| 2525 |
RegisterType RegType = RegisterType::SRV; |
| 2526 |
std::optional<unsigned> SlotNum; |
| 2527 |
unsigned SpaceNum = 0; |
| 2528 |
|
| 2529 |
// Validate slot |
| 2530 |
if (!Slot.empty()) { |
| 2531 |
if (!convertToRegisterType(Slot, &RegType)) { |
| 2532 |
Diag(SlotLoc, diag::err_hlsl_binding_type_invalid) << Slot.substr(0, 1); |
| 2533 |
return; |
| 2534 |
} |
| 2535 |
if (RegType == RegisterType::I) { |
| 2536 |
Diag(SlotLoc, diag::warn_hlsl_deprecated_register_type_i); |
| 2537 |
return; |
| 2538 |
} |
| 2539 |
const StringRef SlotNumStr = Slot.substr(1); |
| 2540 |
|
| 2541 |
unsigned N; |
| 2542 |
|
| 2543 |
// validate that the slot number is a non-empty number |
| 2544 |
if (SlotNumStr.empty() || !llvm::all_of(SlotNumStr, llvm::isDigit)) { |
| 2545 |
Diag(SlotLoc, diag::err_hlsl_unsupported_register_number); |
| 2546 |
return; |
| 2547 |
} |
| 2548 |
|
| 2549 |
// Validate register number. It should not exceed UINT32_MAX, |
| 2550 |
// including if the resource type is an array that starts |
| 2551 |
// before UINT32_MAX, but ends afterwards. |
| 2552 |
if (ValidateRegisterNumber(SlotNumStr, TheDecl, getASTContext(), RegType, |
| 2553 |
N)) { |
| 2554 |
Diag(SlotLoc, diag::err_hlsl_register_number_too_large); |
| 2555 |
return; |
| 2556 |
} |
| 2557 |
|
| 2558 |
SlotNum = N; |
| 2559 |
} |
| 2560 |
|
| 2561 |
// Validate space |
| 2562 |
if (!Space.starts_with("space")) { |
| 2563 |
Diag(SpaceLoc, diag::err_hlsl_expected_space) << Space; |
| 2564 |
return; |
| 2565 |
} |
| 2566 |
StringRef SpaceNumStr = Space.substr(5); |
| 2567 |
if (SpaceNumStr.getAsInteger(10, SpaceNum)) { |
| 2568 |
Diag(SpaceLoc, diag::err_hlsl_expected_space) << Space; |
| 2569 |
return; |
| 2570 |
} |
| 2571 |
|
| 2572 |
// If we have slot, diagnose it is the right register type for the decl |
| 2573 |
if (SlotNum.has_value()) |
| 2574 |
if (!DiagnoseHLSLRegisterAttribute(SemaRef, SlotLoc, TheDecl, RegType, |
| 2575 |
!SpaceLoc.isInvalid())) |
| 2576 |
return; |
| 2577 |
|
| 2578 |
HLSLResourceBindingAttr *NewAttr = |
| 2579 |
HLSLResourceBindingAttr::Create(getASTContext(), Slot, Space, AL); |
| 2580 |
if (NewAttr) { |
| 2581 |
NewAttr->setBinding(RegType, SlotNum, SpaceNum); |
| 2582 |
TheDecl->addAttr(NewAttr); |
| 2583 |
} |
| 2584 |
} |
| 2585 |
|
| 2586 |
void SemaHLSL::handleParamModifierAttr(Decl *D, const ParsedAttr &AL) { |
| 2587 |
HLSLParamModifierAttr *NewAttr = mergeParamModifierAttr( |
| 2588 |
D, AL, |
| 2589 |
static_cast<HLSLParamModifierAttr::Spelling>(AL.getSemanticSpelling())); |
| 2590 |
if (NewAttr) |
| 2591 |
D->addAttr(NewAttr); |
| 2592 |
} |
| 2593 |
|
| 2594 |
namespace { |
| 2595 |
|
| 2596 |
/// This class implements HLSL availability diagnostics for default |
| 2597 |
/// and relaxed mode |
| 2598 |
/// |
| 2599 |
/// The goal of this diagnostic is to emit an error or warning when an |
| 2600 |
/// unavailable API is found in code that is reachable from the shader |
| 2601 |
/// entry function or from an exported function (when compiling a shader |
| 2602 |
/// library). |
| 2603 |
/// |
| 2604 |
/// This is done by traversing the AST of all shader entry point functions |
| 2605 |
/// and of all exported functions, and any functions that are referenced |
| 2606 |
/// from this AST. In other words, any functions that are reachable from |
| 2607 |
/// the entry points. |
| 2608 |
class DiagnoseHLSLAvailability : public DynamicRecursiveASTVisitor { |
| 2609 |
Sema &SemaRef; |
| 2610 |
|
| 2611 |
// Stack of functions to be scaned |
| 2612 |
llvm::SmallVector<const FunctionDecl *, 8> DeclsToScan; |
| 2613 |
|
| 2614 |
// Tracks which environments functions have been scanned in. |
| 2615 |
// |
| 2616 |
// Maps FunctionDecl to an unsigned number that represents the set of shader |
| 2617 |
// environments the function has been scanned for. |
| 2618 |
// The llvm::Triple::EnvironmentType enum values for shader stages guaranteed |
| 2619 |
// to be numbered from llvm::Triple::Pixel to llvm::Triple::Amplification |
| 2620 |
// (verified by static_asserts in Triple.cpp), we can use it to index |
| 2621 |
// individual bits in the set, as long as we shift the values to start with 0 |
| 2622 |
// by subtracting the value of llvm::Triple::Pixel first. |
| 2623 |
// |
| 2624 |
// The N'th bit in the set will be set if the function has been scanned |
| 2625 |
// in shader environment whose llvm::Triple::EnvironmentType integer value |
| 2626 |
// equals (llvm::Triple::Pixel + N). |
| 2627 |
// |
| 2628 |
// For example, if a function has been scanned in compute and pixel stage |
| 2629 |
// environment, the value will be 0x21 (100001 binary) because: |
| 2630 |
// |
| 2631 |
// (int)(llvm::Triple::Pixel - llvm::Triple::Pixel) == 0 |
| 2632 |
// (int)(llvm::Triple::Compute - llvm::Triple::Pixel) == 5 |
| 2633 |
// |
| 2634 |
// A FunctionDecl is mapped to 0 (or not included in the map) if it has not |
| 2635 |
// been scanned in any environment. |
| 2636 |
llvm::DenseMap<const FunctionDecl *, unsigned> ScannedDecls; |
| 2637 |
|
| 2638 |
// Do not access these directly, use the get/set methods below to make |
| 2639 |
// sure the values are in sync |
| 2640 |
llvm::Triple::EnvironmentType CurrentShaderEnvironment; |
| 2641 |
unsigned CurrentShaderStageBit; |
| 2642 |
|
| 2643 |
// True if scanning a function that was already scanned in a different |
| 2644 |
// shader stage context, and therefore we should not report issues that |
| 2645 |
// depend only on shader model version because they would be duplicate. |
| 2646 |
bool ReportOnlyShaderStageIssues; |
| 2647 |
|
| 2648 |
// Helper methods for dealing with current stage context / environment |
| 2649 |
void SetShaderStageContext(llvm::Triple::EnvironmentType ShaderType) { |
| 2650 |
static_assert(sizeof(unsigned) >= 4); |
| 2651 |
assert(HLSLShaderAttr::isValidShaderType(ShaderType)); |
| 2652 |
assert((unsigned)(ShaderType - llvm::Triple::Pixel) < 31 && |
| 2653 |
"ShaderType is too big for this bitmap"); // 31 is reserved for |
| 2654 |
// "unknown" |
| 2655 |
|
| 2656 |
unsigned bitmapIndex = ShaderType - llvm::Triple::Pixel; |
| 2657 |
CurrentShaderEnvironment = ShaderType; |
| 2658 |
CurrentShaderStageBit = (1 << bitmapIndex); |
| 2659 |
} |
| 2660 |
|
| 2661 |
void SetUnknownShaderStageContext() { |
| 2662 |
CurrentShaderEnvironment = llvm::Triple::UnknownEnvironment; |
| 2663 |
CurrentShaderStageBit = (1 << 31); |
| 2664 |
} |
| 2665 |
|
| 2666 |
llvm::Triple::EnvironmentType GetCurrentShaderEnvironment() const { |
| 2667 |
return CurrentShaderEnvironment; |
| 2668 |
} |
| 2669 |
|
| 2670 |
bool InUnknownShaderStageContext() const { |
| 2671 |
return CurrentShaderEnvironment == llvm::Triple::UnknownEnvironment; |
| 2672 |
} |
| 2673 |
|
| 2674 |
// Helper methods for dealing with shader stage bitmap |
| 2675 |
void AddToScannedFunctions(const FunctionDecl *FD) { |
| 2676 |
unsigned &ScannedStages = ScannedDecls[FD]; |
| 2677 |
ScannedStages |= CurrentShaderStageBit; |
| 2678 |
} |
| 2679 |
|
| 2680 |
unsigned GetScannedStages(const FunctionDecl *FD) { return ScannedDecls[FD]; } |
| 2681 |
|
| 2682 |
bool WasAlreadyScannedInCurrentStage(const FunctionDecl *FD) { |
| 2683 |
return WasAlreadyScannedInCurrentStage(GetScannedStages(FD)); |
| 2684 |
} |
| 2685 |
|
| 2686 |
bool WasAlreadyScannedInCurrentStage(unsigned ScannerStages) { |
| 2687 |
return ScannerStages & CurrentShaderStageBit; |
| 2688 |
} |
| 2689 |
|
| 2690 |
static bool NeverBeenScanned(unsigned ScannedStages) { |
| 2691 |
return ScannedStages == 0; |
| 2692 |
} |
| 2693 |
|
| 2694 |
// Scanning methods |
| 2695 |
void HandleFunctionOrMethodRef(FunctionDecl *FD, Expr *RefExpr); |
| 2696 |
void CheckDeclAvailability(NamedDecl *D, const AvailabilityAttr *AA, |
| 2697 |
SourceRange Range); |
| 2698 |
const AvailabilityAttr *FindAvailabilityAttr(const Decl *D); |
| 2699 |
bool HasMatchingEnvironmentOrNone(const AvailabilityAttr *AA); |
| 2700 |
|
| 2701 |
public: |
| 2702 |
DiagnoseHLSLAvailability(Sema &SemaRef) |
| 2703 |
: SemaRef(SemaRef), |
| 2704 |
CurrentShaderEnvironment(llvm::Triple::UnknownEnvironment), |
| 2705 |
CurrentShaderStageBit(0), ReportOnlyShaderStageIssues(false) {} |
| 2706 |
|
| 2707 |
// AST traversal methods |
| 2708 |
void RunOnTranslationUnit(const TranslationUnitDecl *TU); |
| 2709 |
void RunOnFunction(const FunctionDecl *FD); |
| 2710 |
|
| 2711 |
bool VisitDeclRefExpr(DeclRefExpr *DRE) override { |
| 2712 |
FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(DRE->getDecl()); |
| 2713 |
if (FD) |
| 2714 |
HandleFunctionOrMethodRef(FD, DRE); |
| 2715 |
return true; |
| 2716 |
} |
| 2717 |
|
| 2718 |
bool VisitMemberExpr(MemberExpr *ME) override { |
| 2719 |
FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(ME->getMemberDecl()); |
| 2720 |
if (FD) |
| 2721 |
HandleFunctionOrMethodRef(FD, ME); |
| 2722 |
return true; |
| 2723 |
} |
| 2724 |
}; |
| 2725 |
|
| 2726 |
void DiagnoseHLSLAvailability::HandleFunctionOrMethodRef(FunctionDecl *FD, |
| 2727 |
Expr *RefExpr) { |
| 2728 |
assert((isa<DeclRefExpr>(RefExpr) || isa<MemberExpr>(RefExpr)) && |
| 2729 |
"expected DeclRefExpr or MemberExpr"); |
| 2730 |
|
| 2731 |
// has a definition -> add to stack to be scanned |
| 2732 |
const FunctionDecl *FDWithBody = nullptr; |
| 2733 |
if (FD->hasBody(FDWithBody)) { |
| 2734 |
if (!WasAlreadyScannedInCurrentStage(FDWithBody)) |
| 2735 |
DeclsToScan.push_back(FDWithBody); |
| 2736 |
return; |
| 2737 |
} |
| 2738 |
|
| 2739 |
// no body -> diagnose availability |
| 2740 |
const AvailabilityAttr *AA = FindAvailabilityAttr(FD); |
| 2741 |
if (AA) |
| 2742 |
CheckDeclAvailability( |
| 2743 |
FD, AA, SourceRange(RefExpr->getBeginLoc(), RefExpr->getEndLoc())); |
| 2744 |
} |
| 2745 |
|
| 2746 |
void DiagnoseHLSLAvailability::RunOnTranslationUnit( |
| 2747 |
const TranslationUnitDecl *TU) { |
| 2748 |
|
| 2749 |
// Iterate over all shader entry functions and library exports, and for those |
| 2750 |
// that have a body (definiton), run diag scan on each, setting appropriate |
| 2751 |
// shader environment context based on whether it is a shader entry function |
| 2752 |
// or an exported function. Exported functions can be in namespaces and in |
| 2753 |
// export declarations so we need to scan those declaration contexts as well. |
| 2754 |
llvm::SmallVector<const DeclContext *, 8> DeclContextsToScan; |
| 2755 |
DeclContextsToScan.push_back(TU); |
| 2756 |
|
| 2757 |
while (!DeclContextsToScan.empty()) { |
| 2758 |
const DeclContext *DC = DeclContextsToScan.pop_back_val(); |
| 2759 |
for (auto &D : DC->decls()) { |
| 2760 |
// do not scan implicit declaration generated by the implementation |
| 2761 |
if (D->isImplicit()) |
| 2762 |
continue; |
| 2763 |
|
| 2764 |
// for namespace or export declaration add the context to the list to be |
| 2765 |
// scanned later |
| 2766 |
if (llvm::dyn_cast<NamespaceDecl>(D) || llvm::dyn_cast<ExportDecl>(D)) { |
| 2767 |
DeclContextsToScan.push_back(llvm::dyn_cast<DeclContext>(D)); |
| 2768 |
continue; |
| 2769 |
} |
| 2770 |
|
| 2771 |
// skip over other decls or function decls without body |
| 2772 |
const FunctionDecl *FD = llvm::dyn_cast<FunctionDecl>(D); |
| 2773 |
if (!FD || !FD->isThisDeclarationADefinition()) |
| 2774 |
continue; |
| 2775 |
|
| 2776 |
// shader entry point |
| 2777 |
if (HLSLShaderAttr *ShaderAttr = FD->getAttr<HLSLShaderAttr>()) { |
| 2778 |
SetShaderStageContext(ShaderAttr->getType()); |
| 2779 |
RunOnFunction(FD); |
| 2780 |
continue; |
| 2781 |
} |
| 2782 |
// exported library function |
| 2783 |
// FIXME: replace this loop with external linkage check once issue #92071 |
| 2784 |
// is resolved |
| 2785 |
bool isExport = FD->isInExportDeclContext(); |
| 2786 |
if (!isExport) { |
| 2787 |
for (const auto *Redecl : FD->redecls()) { |
| 2788 |
if (Redecl->isInExportDeclContext()) { |
| 2789 |
isExport = true; |
| 2790 |
break; |
| 2791 |
} |
| 2792 |
} |
| 2793 |
} |
| 2794 |
if (isExport) { |
| 2795 |
SetUnknownShaderStageContext(); |
| 2796 |
RunOnFunction(FD); |
| 2797 |
continue; |
| 2798 |
} |
| 2799 |
} |
| 2800 |
} |
| 2801 |
} |
| 2802 |
|
| 2803 |
void DiagnoseHLSLAvailability::RunOnFunction(const FunctionDecl *FD) { |
| 2804 |
assert(DeclsToScan.empty() && "DeclsToScan should be empty"); |
| 2805 |
DeclsToScan.push_back(FD); |
| 2806 |
|
| 2807 |
while (!DeclsToScan.empty()) { |
| 2808 |
// Take one decl from the stack and check it by traversing its AST. |
| 2809 |
// For any CallExpr found during the traversal add it's callee to the top of |
| 2810 |
// the stack to be processed next. Functions already processed are stored in |
| 2811 |
// ScannedDecls. |
| 2812 |
const FunctionDecl *FD = DeclsToScan.pop_back_val(); |
| 2813 |
|
| 2814 |
// Decl was already scanned |
| 2815 |
const unsigned ScannedStages = GetScannedStages(FD); |
| 2816 |
if (WasAlreadyScannedInCurrentStage(ScannedStages)) |
| 2817 |
continue; |
| 2818 |
|
| 2819 |
ReportOnlyShaderStageIssues = !NeverBeenScanned(ScannedStages); |
| 2820 |
|
| 2821 |
AddToScannedFunctions(FD); |
| 2822 |
TraverseStmt(FD->getBody()); |
| 2823 |
} |
| 2824 |
} |
| 2825 |
|
| 2826 |
bool DiagnoseHLSLAvailability::HasMatchingEnvironmentOrNone( |
| 2827 |
const AvailabilityAttr *AA) { |
| 2828 |
const IdentifierInfo *IIEnvironment = AA->getEnvironment(); |
| 2829 |
if (!IIEnvironment) |
| 2830 |
return true; |
| 2831 |
|
| 2832 |
llvm::Triple::EnvironmentType CurrentEnv = GetCurrentShaderEnvironment(); |
| 2833 |
if (CurrentEnv == llvm::Triple::UnknownEnvironment) |
| 2834 |
return false; |
| 2835 |
|
| 2836 |
llvm::Triple::EnvironmentType AttrEnv = |
| 2837 |
AvailabilityAttr::getEnvironmentType(IIEnvironment->getName()); |
| 2838 |
|
| 2839 |
return CurrentEnv == AttrEnv; |
| 2840 |
} |
| 2841 |
|
| 2842 |
const AvailabilityAttr * |
| 2843 |
DiagnoseHLSLAvailability::FindAvailabilityAttr(const Decl *D) { |
| 2844 |
AvailabilityAttr const *PartialMatch = nullptr; |
| 2845 |
// Check each AvailabilityAttr to find the one for this platform. |
| 2846 |
// For multiple attributes with the same platform try to find one for this |
| 2847 |
// environment. |
| 2848 |
for (const auto *A : D->attrs()) { |
| 2849 |
if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) { |
| 2850 |
StringRef AttrPlatform = Avail->getPlatform()->getName(); |
| 2851 |
StringRef TargetPlatform = |
| 2852 |
SemaRef.getASTContext().getTargetInfo().getPlatformName(); |
| 2853 |
|
| 2854 |
// Match the platform name. |
| 2855 |
if (AttrPlatform == TargetPlatform) { |
| 2856 |
// Find the best matching attribute for this environment |
| 2857 |
if (HasMatchingEnvironmentOrNone(Avail)) |
| 2858 |
return Avail; |
| 2859 |
PartialMatch = Avail; |
| 2860 |
} |
| 2861 |
} |
| 2862 |
} |
| 2863 |
return PartialMatch; |
| 2864 |
} |
| 2865 |
|
| 2866 |
// Check availability against target shader model version and current shader |
| 2867 |
// stage and emit diagnostic |
| 2868 |
void DiagnoseHLSLAvailability::CheckDeclAvailability(NamedDecl *D, |
| 2869 |
const AvailabilityAttr *AA, |
| 2870 |
SourceRange Range) { |
| 2871 |
|
| 2872 |
const IdentifierInfo *IIEnv = AA->getEnvironment(); |
| 2873 |
|
| 2874 |
if (!IIEnv) { |
| 2875 |
// The availability attribute does not have environment -> it depends only |
| 2876 |
// on shader model version and not on specific the shader stage. |
| 2877 |
|
| 2878 |
// Skip emitting the diagnostics if the diagnostic mode is set to |
| 2879 |
// strict (-fhlsl-strict-availability) because all relevant diagnostics |
| 2880 |
// were already emitted in the DiagnoseUnguardedAvailability scan |
| 2881 |
// (SemaAvailability.cpp). |
| 2882 |
if (SemaRef.getLangOpts().HLSLStrictAvailability) |
| 2883 |
return; |
| 2884 |
|
| 2885 |
// Do not report shader-stage-independent issues if scanning a function |
| 2886 |
// that was already scanned in a different shader stage context (they would |
| 2887 |
// be duplicate) |
| 2888 |
if (ReportOnlyShaderStageIssues) |
| 2889 |
return; |
| 2890 |
|
| 2891 |
} else { |
| 2892 |
// The availability attribute has environment -> we need to know |
| 2893 |
// the current stage context to property diagnose it. |
| 2894 |
if (InUnknownShaderStageContext()) |
| 2895 |
return; |
| 2896 |
} |
| 2897 |
|
| 2898 |
// Check introduced version and if environment matches |
| 2899 |
bool EnvironmentMatches = HasMatchingEnvironmentOrNone(AA); |
| 2900 |
VersionTuple Introduced = AA->getIntroduced(); |
| 2901 |
VersionTuple TargetVersion = |
| 2902 |
SemaRef.Context.getTargetInfo().getPlatformMinVersion(); |
| 2903 |
|
| 2904 |
if (TargetVersion >= Introduced && EnvironmentMatches) |
| 2905 |
return; |
| 2906 |
|
| 2907 |
// Emit diagnostic message |
| 2908 |
const TargetInfo &TI = SemaRef.getASTContext().getTargetInfo(); |
| 2909 |
llvm::StringRef PlatformName( |
| 2910 |
AvailabilityAttr::getPrettyPlatformName(TI.getPlatformName())); |
| 2911 |
|
| 2912 |
llvm::StringRef CurrentEnvStr = |
| 2913 |
llvm::Triple::getEnvironmentTypeName(GetCurrentShaderEnvironment()); |
| 2914 |
|
| 2915 |
llvm::StringRef AttrEnvStr = |
| 2916 |
AA->getEnvironment() ? AA->getEnvironment()->getName() : ""; |
| 2917 |
bool UseEnvironment = !AttrEnvStr.empty(); |
| 2918 |
|
| 2919 |
if (EnvironmentMatches) { |
| 2920 |
SemaRef.Diag(Range.getBegin(), diag::warn_hlsl_availability) |
| 2921 |
<< Range << D << PlatformName << Introduced.getAsString() |
| 2922 |
<< UseEnvironment << CurrentEnvStr; |
| 2923 |
} else { |
| 2924 |
SemaRef.Diag(Range.getBegin(), diag::warn_hlsl_availability_unavailable) |
| 2925 |
<< Range << D; |
| 2926 |
} |
| 2927 |
|
| 2928 |
SemaRef.Diag(D->getLocation(), diag::note_partial_availability_specified_here) |
| 2929 |
<< D << PlatformName << Introduced.getAsString() |
| 2930 |
<< SemaRef.Context.getTargetInfo().getPlatformMinVersion().getAsString() |
| 2931 |
<< UseEnvironment << AttrEnvStr << CurrentEnvStr; |
| 2932 |
} |
| 2933 |
|
| 2934 |
} // namespace |
| 2935 |
|
| 2936 |
void SemaHLSL::ActOnEndOfTranslationUnit(TranslationUnitDecl *TU) { |
| 2937 |
// process default CBuffer - create buffer layout struct and invoke codegenCGH |
| 2938 |
if (!DefaultCBufferDecls.empty()) { |
| 2939 |
HLSLBufferDecl *DefaultCBuffer = HLSLBufferDecl::CreateDefaultCBuffer( |
| 2940 |
SemaRef.getASTContext(), SemaRef.getCurLexicalContext(), |
| 2941 |
DefaultCBufferDecls); |
| 2942 |
addImplicitBindingAttrToDecl(SemaRef, DefaultCBuffer, RegisterType::CBuffer, |
| 2943 |
getNextImplicitBindingOrderID()); |
| 2944 |
SemaRef.getCurLexicalContext()->addDecl(DefaultCBuffer); |
| 2945 |
createHostLayoutStructForBuffer(SemaRef, DefaultCBuffer); |
| 2946 |
|
| 2947 |
// Set HasValidPackoffset if any of the decls has a register(c#) annotation; |
| 2948 |
for (const Decl *VD : DefaultCBufferDecls) { |
| 2949 |
const HLSLResourceBindingAttr *RBA = |
| 2950 |
VD->getAttr<HLSLResourceBindingAttr>(); |
| 2951 |
if (RBA && RBA->hasRegisterSlot() && |
| 2952 |
RBA->getRegisterType() == HLSLResourceBindingAttr::RegisterType::C) { |
| 2953 |
DefaultCBuffer->setHasValidPackoffset(true); |
| 2954 |
break; |
| 2955 |
} |
| 2956 |
} |
| 2957 |
|
| 2958 |
DeclGroupRef DG(DefaultCBuffer); |
| 2959 |
SemaRef.Consumer.HandleTopLevelDecl(DG); |
| 2960 |
} |
| 2961 |
diagnoseAvailabilityViolations(TU); |
| 2962 |
} |
| 2963 |
|
| 2964 |
void SemaHLSL::diagnoseAvailabilityViolations(TranslationUnitDecl *TU) { |
| 2965 |
// Skip running the diagnostics scan if the diagnostic mode is |
| 2966 |
// strict (-fhlsl-strict-availability) and the target shader stage is known |
| 2967 |
// because all relevant diagnostics were already emitted in the |
| 2968 |
// DiagnoseUnguardedAvailability scan (SemaAvailability.cpp). |
| 2969 |
const TargetInfo &TI = SemaRef.getASTContext().getTargetInfo(); |
| 2970 |
if (SemaRef.getLangOpts().HLSLStrictAvailability && |
| 2971 |
TI.getTriple().getEnvironment() != llvm::Triple::EnvironmentType::Library) |
| 2972 |
return; |
| 2973 |
|
| 2974 |
DiagnoseHLSLAvailability(SemaRef).RunOnTranslationUnit(TU); |
| 2975 |
} |
| 2976 |
|
| 2977 |
static bool CheckAllArgsHaveSameType(Sema *S, CallExpr *TheCall) { |
| 2978 |
assert(TheCall->getNumArgs() > 1); |
| 2979 |
QualType ArgTy0 = TheCall->getArg(0)->getType(); |
| 2980 |
|
| 2981 |
for (unsigned I = 1, N = TheCall->getNumArgs(); I < N; ++I) { |
| 2982 |
if (!S->getASTContext().hasSameUnqualifiedType( |
| 2983 |
ArgTy0, TheCall->getArg(I)->getType())) { |
| 2984 |
S->Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_incompatible_vector) |
| 2985 |
<< TheCall->getDirectCallee() << /*useAllTerminology*/ true |
| 2986 |
<< SourceRange(TheCall->getArg(0)->getBeginLoc(), |
| 2987 |
TheCall->getArg(N - 1)->getEndLoc()); |
| 2988 |
return true; |
| 2989 |
} |
| 2990 |
} |
| 2991 |
return false; |
| 2992 |
} |
| 2993 |
|
| 2994 |
static bool CheckArgTypeMatches(Sema *S, Expr *Arg, QualType ExpectedType) { |
| 2995 |
QualType ArgType = Arg->getType(); |
| 2996 |
if (!S->getASTContext().hasSameUnqualifiedType(ArgType, ExpectedType)) { |
| 2997 |
S->Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) |
| 2998 |
<< ArgType << ExpectedType << 1 << 0 << 0; |
| 2999 |
return true; |
| 3000 |
} |
| 3001 |
return false; |
| 3002 |
} |
| 3003 |
|
| 3004 |
static bool CheckAllArgTypesAreCorrect( |
| 3005 |
Sema *S, CallExpr *TheCall, |
| 3006 |
llvm::function_ref<bool(Sema *S, SourceLocation Loc, int ArgOrdinal, |
| 3007 |
clang::QualType PassedType)> |
| 3008 |
Check) { |
| 3009 |
for (unsigned I = 0; I < TheCall->getNumArgs(); ++I) { |
| 3010 |
Expr *Arg = TheCall->getArg(I); |
| 3011 |
if (Check(S, Arg->getBeginLoc(), I + 1, Arg->getType())) |
| 3012 |
return true; |
| 3013 |
} |
| 3014 |
return false; |
| 3015 |
} |
| 3016 |
|
| 3017 |
static bool CheckFloatOrHalfRepresentation(Sema *S, SourceLocation Loc, |
| 3018 |
int ArgOrdinal, |
| 3019 |
clang::QualType PassedType) { |
| 3020 |
clang::QualType BaseType = |
| 3021 |
PassedType->isVectorType() |
| 3022 |
? PassedType->castAs<clang::VectorType>()->getElementType() |
| 3023 |
: PassedType; |
| 3024 |
if (!BaseType->isHalfType() && !BaseType->isFloat32Type()) |
| 3025 |
return S->Diag(Loc, diag::err_builtin_invalid_arg_type) |
| 3026 |
<< ArgOrdinal << /* scalar or vector of */ 5 << /* no int */ 0 |
| 3027 |
<< /* half or float */ 2 << PassedType; |
| 3028 |
return false; |
| 3029 |
} |
| 3030 |
|
| 3031 |
static bool CheckModifiableLValue(Sema *S, CallExpr *TheCall, |
| 3032 |
unsigned ArgIndex) { |
| 3033 |
auto *Arg = TheCall->getArg(ArgIndex); |
| 3034 |
SourceLocation OrigLoc = Arg->getExprLoc(); |
| 3035 |
if (Arg->IgnoreCasts()->isModifiableLvalue(S->Context, &OrigLoc) == |
| 3036 |
Expr::MLV_Valid) |
| 3037 |
return false; |
| 3038 |
S->Diag(OrigLoc, diag::error_hlsl_inout_lvalue) << Arg << 0; |
| 3039 |
return true; |
| 3040 |
} |
| 3041 |
|
| 3042 |
static bool CheckNoDoubleVectors(Sema *S, SourceLocation Loc, int ArgOrdinal, |
| 3043 |
clang::QualType PassedType) { |
| 3044 |
const auto *VecTy = PassedType->getAs<VectorType>(); |
| 3045 |
if (!VecTy) |
| 3046 |
return false; |
| 3047 |
|
| 3048 |
if (VecTy->getElementType()->isDoubleType()) |
| 3049 |
return S->Diag(Loc, diag::err_builtin_invalid_arg_type) |
| 3050 |
<< ArgOrdinal << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1 |
| 3051 |
<< PassedType; |
| 3052 |
return false; |
| 3053 |
} |
| 3054 |
|
| 3055 |
static bool CheckFloatingOrIntRepresentation(Sema *S, SourceLocation Loc, |
| 3056 |
int ArgOrdinal, |
| 3057 |
clang::QualType PassedType) { |
| 3058 |
if (!PassedType->hasIntegerRepresentation() && |
| 3059 |
!PassedType->hasFloatingRepresentation()) |
| 3060 |
return S->Diag(Loc, diag::err_builtin_invalid_arg_type) |
| 3061 |
<< ArgOrdinal << /* scalar or vector of */ 5 << /* integer */ 1 |
| 3062 |
<< /* fp */ 1 << PassedType; |
| 3063 |
return false; |
| 3064 |
} |
| 3065 |
|
| 3066 |
static bool CheckUnsignedIntVecRepresentation(Sema *S, SourceLocation Loc, |
| 3067 |
int ArgOrdinal, |
| 3068 |
clang::QualType PassedType) { |
| 3069 |
if (auto *VecTy = PassedType->getAs<VectorType>()) |
| 3070 |
if (VecTy->getElementType()->isUnsignedIntegerType()) |
| 3071 |
return false; |
| 3072 |
|
| 3073 |
return S->Diag(Loc, diag::err_builtin_invalid_arg_type) |
| 3074 |
<< ArgOrdinal << /* vector of */ 4 << /* uint */ 3 << /* no fp */ 0 |
| 3075 |
<< PassedType; |
| 3076 |
} |
| 3077 |
|
| 3078 |
// checks for unsigned ints of all sizes |
| 3079 |
static bool CheckUnsignedIntRepresentation(Sema *S, SourceLocation Loc, |
| 3080 |
int ArgOrdinal, |
| 3081 |
clang::QualType PassedType) { |
| 3082 |
if (!PassedType->hasUnsignedIntegerRepresentation()) |
| 3083 |
return S->Diag(Loc, diag::err_builtin_invalid_arg_type) |
| 3084 |
<< ArgOrdinal << /* scalar or vector of */ 5 << /* unsigned int */ 3 |
| 3085 |
<< /* no fp */ 0 << PassedType; |
| 3086 |
return false; |
| 3087 |
} |
| 3088 |
|
| 3089 |
static bool CheckExpectedBitWidth(Sema *S, CallExpr *TheCall, |
| 3090 |
unsigned ArgOrdinal, unsigned Width) { |
| 3091 |
QualType ArgTy = TheCall->getArg(0)->getType(); |
| 3092 |
if (auto *VTy = ArgTy->getAs<VectorType>()) |
| 3093 |
ArgTy = VTy->getElementType(); |
| 3094 |
// ensure arg type has expected bit width |
| 3095 |
uint64_t ElementBitCount = |
| 3096 |
S->getASTContext().getTypeSizeInChars(ArgTy).getQuantity() * 8; |
| 3097 |
if (ElementBitCount != Width) { |
| 3098 |
S->Diag(TheCall->getArg(0)->getBeginLoc(), |
| 3099 |
diag::err_integer_incorrect_bit_count) |
| 3100 |
<< Width << ElementBitCount; |
| 3101 |
return true; |
| 3102 |
} |
| 3103 |
return false; |
| 3104 |
} |
| 3105 |
|
| 3106 |
static void SetElementTypeAsReturnType(Sema *S, CallExpr *TheCall, |
| 3107 |
QualType ReturnType) { |
| 3108 |
auto *VecTyA = TheCall->getArg(0)->getType()->getAs<VectorType>(); |
| 3109 |
if (VecTyA) |
| 3110 |
ReturnType = |
| 3111 |
S->Context.getExtVectorType(ReturnType, VecTyA->getNumElements()); |
| 3112 |
|
| 3113 |
TheCall->setType(ReturnType); |
| 3114 |
} |
| 3115 |
|
| 3116 |
static bool CheckScalarOrVector(Sema *S, CallExpr *TheCall, QualType Scalar, |
| 3117 |
unsigned ArgIndex) { |
| 3118 |
assert(TheCall->getNumArgs() >= ArgIndex); |
| 3119 |
QualType ArgType = TheCall->getArg(ArgIndex)->getType(); |
| 3120 |
auto *VTy = ArgType->getAs<VectorType>(); |
| 3121 |
// not the scalar or vector<scalar> |
| 3122 |
if (!(S->Context.hasSameUnqualifiedType(ArgType, Scalar) || |
| 3123 |
(VTy && |
| 3124 |
S->Context.hasSameUnqualifiedType(VTy->getElementType(), Scalar)))) { |
| 3125 |
S->Diag(TheCall->getArg(0)->getBeginLoc(), |
| 3126 |
diag::err_typecheck_expect_scalar_or_vector) |
| 3127 |
<< ArgType << Scalar; |
| 3128 |
return true; |
| 3129 |
} |
| 3130 |
return false; |
| 3131 |
} |
| 3132 |
|
| 3133 |
static bool CheckScalarOrVectorOrMatrix(Sema *S, CallExpr *TheCall, |
| 3134 |
QualType Scalar, unsigned ArgIndex) { |
| 3135 |
assert(TheCall->getNumArgs() > ArgIndex); |
| 3136 |
|
| 3137 |
Expr *Arg = TheCall->getArg(ArgIndex); |
| 3138 |
QualType ArgType = Arg->getType(); |
| 3139 |
|
| 3140 |
// Scalar: T |
| 3141 |
if (S->Context.hasSameUnqualifiedType(ArgType, Scalar)) |
| 3142 |
return false; |
| 3143 |
|
| 3144 |
// Vector: vector<T> |
| 3145 |
if (const auto *VTy = ArgType->getAs<VectorType>()) { |
| 3146 |
if (S->Context.hasSameUnqualifiedType(VTy->getElementType(), Scalar)) |
| 3147 |
return false; |
| 3148 |
} |
| 3149 |
|
| 3150 |
// Matrix: ConstantMatrixType with element type T |
| 3151 |
if (const auto *MTy = ArgType->getAs<ConstantMatrixType>()) { |
| 3152 |
if (S->Context.hasSameUnqualifiedType(MTy->getElementType(), Scalar)) |
| 3153 |
return false; |
| 3154 |
} |
| 3155 |
|
| 3156 |
// Not a scalar/vector/matrix-of-scalar |
| 3157 |
S->Diag(Arg->getBeginLoc(), |
| 3158 |
diag::err_typecheck_expect_scalar_or_vector_or_matrix) |
| 3159 |
<< ArgType << Scalar; |
| 3160 |
return true; |
| 3161 |
} |
| 3162 |
|
| 3163 |
static bool CheckAnyScalarOrVector(Sema *S, CallExpr *TheCall, |
| 3164 |
unsigned ArgIndex) { |
| 3165 |
assert(TheCall->getNumArgs() >= ArgIndex); |
| 3166 |
QualType ArgType = TheCall->getArg(ArgIndex)->getType(); |
| 3167 |
auto *VTy = ArgType->getAs<VectorType>(); |
| 3168 |
// not the scalar or vector<scalar> |
| 3169 |
if (!(ArgType->isScalarType() || |
| 3170 |
(VTy && VTy->getElementType()->isScalarType()))) { |
| 3171 |
S->Diag(TheCall->getArg(0)->getBeginLoc(), |
| 3172 |
diag::err_typecheck_expect_any_scalar_or_vector) |
| 3173 |
<< ArgType << 1; |
| 3174 |
return true; |
| 3175 |
} |
| 3176 |
return false; |
| 3177 |
} |
| 3178 |
|
| 3179 |
static bool CheckWaveActive(Sema *S, CallExpr *TheCall) { |
| 3180 |
QualType BoolType = S->getASTContext().BoolTy; |
| 3181 |
assert(TheCall->getNumArgs() >= 1); |
| 3182 |
QualType ArgType = TheCall->getArg(0)->getType(); |
| 3183 |
auto *VTy = ArgType->getAs<VectorType>(); |
| 3184 |
// is the bool or vector<bool> |
| 3185 |
if (S->Context.hasSameUnqualifiedType(ArgType, BoolType) || |
| 3186 |
(VTy && |
| 3187 |
S->Context.hasSameUnqualifiedType(VTy->getElementType(), BoolType))) { |
| 3188 |
S->Diag(TheCall->getArg(0)->getBeginLoc(), |
| 3189 |
diag::err_typecheck_expect_any_scalar_or_vector) |
| 3190 |
<< ArgType << 0; |
| 3191 |
return true; |
| 3192 |
} |
| 3193 |
return false; |
| 3194 |
} |
| 3195 |
|
| 3196 |
static bool CheckBoolSelect(Sema *S, CallExpr *TheCall) { |
| 3197 |
assert(TheCall->getNumArgs() == 3); |
| 3198 |
Expr *Arg1 = TheCall->getArg(1); |
| 3199 |
Expr *Arg2 = TheCall->getArg(2); |
| 3200 |
if (!S->Context.hasSameUnqualifiedType(Arg1->getType(), Arg2->getType())) { |
| 3201 |
S->Diag(TheCall->getBeginLoc(), |
| 3202 |
diag::err_typecheck_call_different_arg_types) |
| 3203 |
<< Arg1->getType() << Arg2->getType() << Arg1->getSourceRange() |
| 3204 |
<< Arg2->getSourceRange(); |
| 3205 |
return true; |
| 3206 |
} |
| 3207 |
|
| 3208 |
TheCall->setType(Arg1->getType()); |
| 3209 |
return false; |
| 3210 |
} |
| 3211 |
|
| 3212 |
static bool CheckVectorSelect(Sema *S, CallExpr *TheCall) { |
| 3213 |
assert(TheCall->getNumArgs() == 3); |
| 3214 |
Expr *Arg1 = TheCall->getArg(1); |
| 3215 |
QualType Arg1Ty = Arg1->getType(); |
| 3216 |
Expr *Arg2 = TheCall->getArg(2); |
| 3217 |
QualType Arg2Ty = Arg2->getType(); |
| 3218 |
|
| 3219 |
QualType Arg1ScalarTy = Arg1Ty; |
| 3220 |
if (auto VTy = Arg1ScalarTy->getAs<VectorType>()) |
| 3221 |
Arg1ScalarTy = VTy->getElementType(); |
| 3222 |
|
| 3223 |
QualType Arg2ScalarTy = Arg2Ty; |
| 3224 |
if (auto VTy = Arg2ScalarTy->getAs<VectorType>()) |
| 3225 |
Arg2ScalarTy = VTy->getElementType(); |
| 3226 |
|
| 3227 |
if (!S->Context.hasSameUnqualifiedType(Arg1ScalarTy, Arg2ScalarTy)) |
| 3228 |
S->Diag(Arg1->getBeginLoc(), diag::err_hlsl_builtin_scalar_vector_mismatch) |
| 3229 |
<< /* second and third */ 1 << TheCall->getCallee() << Arg1Ty << Arg2Ty; |
| 3230 |
|
| 3231 |
QualType Arg0Ty = TheCall->getArg(0)->getType(); |
| 3232 |
unsigned Arg0Length = Arg0Ty->getAs<VectorType>()->getNumElements(); |
| 3233 |
unsigned Arg1Length = Arg1Ty->isVectorType() |
| 3234 |
? Arg1Ty->getAs<VectorType>()->getNumElements() |
| 3235 |
: 0; |
| 3236 |
unsigned Arg2Length = Arg2Ty->isVectorType() |
| 3237 |
? Arg2Ty->getAs<VectorType>()->getNumElements() |
| 3238 |
: 0; |
| 3239 |
if (Arg1Length > 0 && Arg0Length != Arg1Length) { |
| 3240 |
S->Diag(TheCall->getBeginLoc(), |
| 3241 |
diag::err_typecheck_vector_lengths_not_equal) |
| 3242 |
<< Arg0Ty << Arg1Ty << TheCall->getArg(0)->getSourceRange() |
| 3243 |
<< Arg1->getSourceRange(); |
| 3244 |
return true; |
| 3245 |
} |
| 3246 |
|
| 3247 |
if (Arg2Length > 0 && Arg0Length != Arg2Length) { |
| 3248 |
S->Diag(TheCall->getBeginLoc(), |
| 3249 |
diag::err_typecheck_vector_lengths_not_equal) |
| 3250 |
<< Arg0Ty << Arg2Ty << TheCall->getArg(0)->getSourceRange() |
| 3251 |
<< Arg2->getSourceRange(); |
| 3252 |
return true; |
| 3253 |
} |
| 3254 |
|
| 3255 |
TheCall->setType( |
| 3256 |
S->getASTContext().getExtVectorType(Arg1ScalarTy, Arg0Length)); |
| 3257 |
return false; |
| 3258 |
} |
| 3259 |
|
| 3260 |
static bool CheckResourceHandle( |
| 3261 |
Sema *S, CallExpr *TheCall, unsigned ArgIndex, |
| 3262 |
llvm::function_ref<bool(const HLSLAttributedResourceType *ResType)> Check = |
| 3263 |
nullptr) { |
| 3264 |
assert(TheCall->getNumArgs() >= ArgIndex); |
| 3265 |
QualType ArgType = TheCall->getArg(ArgIndex)->getType(); |
| 3266 |
const HLSLAttributedResourceType *ResTy = |
| 3267 |
ArgType.getTypePtr()->getAs<HLSLAttributedResourceType>(); |
| 3268 |
if (!ResTy) { |
| 3269 |
S->Diag(TheCall->getArg(ArgIndex)->getBeginLoc(), |
| 3270 |
diag::err_typecheck_expect_hlsl_resource) |
| 3271 |
<< ArgType; |
| 3272 |
return true; |
| 3273 |
} |
| 3274 |
if (Check && Check(ResTy)) { |
| 3275 |
S->Diag(TheCall->getArg(ArgIndex)->getExprLoc(), |
| 3276 |
diag::err_invalid_hlsl_resource_type) |
| 3277 |
<< ArgType; |
| 3278 |
return true; |
| 3279 |
} |
| 3280 |
return false; |
| 3281 |
} |
| 3282 |
|
| 3283 |
// Note: returning true in this case results in CheckBuiltinFunctionCall |
| 3284 |
// returning an ExprError |
| 3285 |
bool SemaHLSL::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { |
| 3286 |
switch (BuiltinID) { |
| 3287 |
case Builtin::BI__builtin_hlsl_adduint64: { |
| 3288 |
if (SemaRef.checkArgCount(TheCall, 2)) |
| 3289 |
return true; |
| 3290 |
|
| 3291 |
if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall, |
| 3292 |
CheckUnsignedIntVecRepresentation)) |
| 3293 |
return true; |
| 3294 |
|
| 3295 |
// ensure arg integers are 32-bits |
| 3296 |
if (CheckExpectedBitWidth(&SemaRef, TheCall, 0, 32)) |
| 3297 |
return true; |
| 3298 |
|
| 3299 |
// ensure both args are vectors of total bit size of a multiple of 64 |
| 3300 |
auto *VTy = TheCall->getArg(0)->getType()->getAs<VectorType>(); |
| 3301 |
int NumElementsArg = VTy->getNumElements(); |
| 3302 |
if (NumElementsArg != 2 && NumElementsArg != 4) { |
| 3303 |
SemaRef.Diag(TheCall->getBeginLoc(), diag::err_vector_incorrect_bit_count) |
| 3304 |
<< 1 /*a multiple of*/ << 64 << NumElementsArg * 32; |
| 3305 |
return true; |
| 3306 |
} |
| 3307 |
|
| 3308 |
// ensure first arg and second arg have the same type |
| 3309 |
if (CheckAllArgsHaveSameType(&SemaRef, TheCall)) |
| 3310 |
return true; |
| 3311 |
|
| 3312 |
ExprResult A = TheCall->getArg(0); |
| 3313 |
QualType ArgTyA = A.get()->getType(); |
| 3314 |
// return type is the same as the input type |
| 3315 |
TheCall->setType(ArgTyA); |
| 3316 |
break; |
| 3317 |
} |
| 3318 |
case Builtin::BI__builtin_hlsl_resource_getpointer: { |
| 3319 |
if (SemaRef.checkArgCount(TheCall, 2) || |
| 3320 |
CheckResourceHandle(&SemaRef, TheCall, 0) || |
| 3321 |
CheckArgTypeMatches(&SemaRef, TheCall->getArg(1), |
| 3322 |
SemaRef.getASTContext().UnsignedIntTy)) |
| 3323 |
return true; |
| 3324 |
|
| 3325 |
auto *ResourceTy = |
| 3326 |
TheCall->getArg(0)->getType()->castAs<HLSLAttributedResourceType>(); |
| 3327 |
QualType ContainedTy = ResourceTy->getContainedType(); |
| 3328 |
auto ReturnType = |
| 3329 |
SemaRef.Context.getAddrSpaceQualType(ContainedTy, LangAS::hlsl_device); |
| 3330 |
ReturnType = SemaRef.Context.getPointerType(ReturnType); |
| 3331 |
TheCall->setType(ReturnType); |
| 3332 |
TheCall->setValueKind(VK_LValue); |
| 3333 |
|
| 3334 |
break; |
| 3335 |
} |
| 3336 |
case Builtin::BI__builtin_hlsl_resource_load_with_status: { |
| 3337 |
if (SemaRef.checkArgCount(TheCall, 3) || |
| 3338 |
CheckResourceHandle(&SemaRef, TheCall, 0) || |
| 3339 |
CheckArgTypeMatches(&SemaRef, TheCall->getArg(1), |
| 3340 |
SemaRef.getASTContext().UnsignedIntTy) || |
| 3341 |
CheckArgTypeMatches(&SemaRef, TheCall->getArg(2), |
| 3342 |
SemaRef.getASTContext().UnsignedIntTy) || |
| 3343 |
CheckModifiableLValue(&SemaRef, TheCall, 2)) |
| 3344 |
return true; |
| 3345 |
|
| 3346 |
auto *ResourceTy = |
| 3347 |
TheCall->getArg(0)->getType()->castAs<HLSLAttributedResourceType>(); |
| 3348 |
QualType ReturnType = ResourceTy->getContainedType(); |
| 3349 |
TheCall->setType(ReturnType); |
| 3350 |
|
| 3351 |
break; |
| 3352 |
} |
| 3353 |
|
| 3354 |
case Builtin::BI__builtin_hlsl_resource_uninitializedhandle: { |
| 3355 |
assert(TheCall->getNumArgs() == 1 && "expected 1 arg"); |
| 3356 |
// Update return type to be the attributed resource type from arg0. |
| 3357 |
QualType ResourceTy = TheCall->getArg(0)->getType(); |
| 3358 |
TheCall->setType(ResourceTy); |
| 3359 |
break; |
| 3360 |
} |
| 3361 |
case Builtin::BI__builtin_hlsl_resource_handlefrombinding: { |
| 3362 |
assert(TheCall->getNumArgs() == 6 && "expected 6 args"); |
| 3363 |
// Update return type to be the attributed resource type from arg0. |
| 3364 |
QualType ResourceTy = TheCall->getArg(0)->getType(); |
| 3365 |
TheCall->setType(ResourceTy); |
| 3366 |
break; |
| 3367 |
} |
| 3368 |
case Builtin::BI__builtin_hlsl_resource_handlefromimplicitbinding: { |
| 3369 |
assert(TheCall->getNumArgs() == 6 && "expected 6 args"); |
| 3370 |
// Update return type to be the attributed resource type from arg0. |
| 3371 |
QualType ResourceTy = TheCall->getArg(0)->getType(); |
| 3372 |
TheCall->setType(ResourceTy); |
| 3373 |
break; |
| 3374 |
} |
| 3375 |
case Builtin::BI__builtin_hlsl_resource_counterhandlefromimplicitbinding: { |
| 3376 |
assert(TheCall->getNumArgs() == 3 && "expected 3 args"); |
| 3377 |
ASTContext &AST = SemaRef.getASTContext(); |
| 3378 |
QualType MainHandleTy = TheCall->getArg(0)->getType(); |
| 3379 |
auto *MainResType = MainHandleTy->getAs<HLSLAttributedResourceType>(); |
| 3380 |
auto MainAttrs = MainResType->getAttrs(); |
| 3381 |
assert(!MainAttrs.IsCounter && "cannot create a counter from a counter"); |
| 3382 |
MainAttrs.IsCounter = true; |
| 3383 |
QualType CounterHandleTy = AST.getHLSLAttributedResourceType( |
| 3384 |
MainResType->getWrappedType(), MainResType->getContainedType(), |
| 3385 |
MainAttrs); |
| 3386 |
// Update return type to be the attributed resource type from arg0 |
| 3387 |
// with added IsCounter flag. |
| 3388 |
TheCall->setType(CounterHandleTy); |
| 3389 |
break; |
| 3390 |
} |
| 3391 |
case Builtin::BI__builtin_hlsl_and: |
| 3392 |
case Builtin::BI__builtin_hlsl_or: { |
| 3393 |
if (SemaRef.checkArgCount(TheCall, 2)) |
| 3394 |
return true; |
| 3395 |
if (CheckScalarOrVectorOrMatrix(&SemaRef, TheCall, getASTContext().BoolTy, |
| 3396 |
0)) |
| 3397 |
return true; |
| 3398 |
if (CheckAllArgsHaveSameType(&SemaRef, TheCall)) |
| 3399 |
return true; |
| 3400 |
|
| 3401 |
ExprResult A = TheCall->getArg(0); |
| 3402 |
QualType ArgTyA = A.get()->getType(); |
| 3403 |
// return type is the same as the input type |
| 3404 |
TheCall->setType(ArgTyA); |
| 3405 |
break; |
| 3406 |
} |
| 3407 |
case Builtin::BI__builtin_hlsl_all: |
| 3408 |
case Builtin::BI__builtin_hlsl_any: { |
| 3409 |
if (SemaRef.checkArgCount(TheCall, 1)) |
| 3410 |
return true; |
| 3411 |
if (CheckAnyScalarOrVector(&SemaRef, TheCall, 0)) |
| 3412 |
return true; |
| 3413 |
break; |
| 3414 |
} |
| 3415 |
case Builtin::BI__builtin_hlsl_asdouble: { |
| 3416 |
if (SemaRef.checkArgCount(TheCall, 2)) |
| 3417 |
return true; |
| 3418 |
if (CheckScalarOrVector( |
| 3419 |
&SemaRef, TheCall, |
| 3420 |
/*only check for uint*/ SemaRef.Context.UnsignedIntTy, |
| 3421 |
/* arg index */ 0)) |
| 3422 |
return true; |
| 3423 |
if (CheckScalarOrVector( |
| 3424 |
&SemaRef, TheCall, |
| 3425 |
/*only check for uint*/ SemaRef.Context.UnsignedIntTy, |
| 3426 |
/* arg index */ 1)) |
| 3427 |
return true; |
| 3428 |
if (CheckAllArgsHaveSameType(&SemaRef, TheCall)) |
| 3429 |
return true; |
| 3430 |
|
| 3431 |
SetElementTypeAsReturnType(&SemaRef, TheCall, getASTContext().DoubleTy); |
| 3432 |
break; |
| 3433 |
} |
| 3434 |
case Builtin::BI__builtin_hlsl_elementwise_clamp: { |
| 3435 |
if (SemaRef.BuiltinElementwiseTernaryMath( |
| 3436 |
TheCall, /*ArgTyRestr=*/ |
| 3437 |
Sema::EltwiseBuiltinArgTyRestriction::None)) |
| 3438 |
return true; |
| 3439 |
break; |
| 3440 |
} |
| 3441 |
case Builtin::BI__builtin_hlsl_dot: { |
| 3442 |
// arg count is checked by BuiltinVectorToScalarMath |
| 3443 |
if (SemaRef.BuiltinVectorToScalarMath(TheCall)) |
| 3444 |
return true; |
| 3445 |
if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall, CheckNoDoubleVectors)) |
| 3446 |
return true; |
| 3447 |
break; |
| 3448 |
} |
| 3449 |
case Builtin::BI__builtin_hlsl_elementwise_firstbithigh: |
| 3450 |
case Builtin::BI__builtin_hlsl_elementwise_firstbitlow: { |
| 3451 |
if (SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall)) |
| 3452 |
return true; |
| 3453 |
|
| 3454 |
const Expr *Arg = TheCall->getArg(0); |
| 3455 |
QualType ArgTy = Arg->getType(); |
| 3456 |
QualType EltTy = ArgTy; |
| 3457 |
|
| 3458 |
QualType ResTy = SemaRef.Context.UnsignedIntTy; |
| 3459 |
|
| 3460 |
if (auto *VecTy = EltTy->getAs<VectorType>()) { |
| 3461 |
EltTy = VecTy->getElementType(); |
| 3462 |
ResTy = SemaRef.Context.getExtVectorType(ResTy, VecTy->getNumElements()); |
| 3463 |
} |
| 3464 |
|
| 3465 |
if (!EltTy->isIntegerType()) { |
| 3466 |
Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) |
| 3467 |
<< 1 << /* scalar or vector of */ 5 << /* integer ty */ 1 |
| 3468 |
<< /* no fp */ 0 << ArgTy; |
| 3469 |
return true; |
| 3470 |
} |
| 3471 |
|
| 3472 |
TheCall->setType(ResTy); |
| 3473 |
break; |
| 3474 |
} |
| 3475 |
case Builtin::BI__builtin_hlsl_select: { |
| 3476 |
if (SemaRef.checkArgCount(TheCall, 3)) |
| 3477 |
return true; |
| 3478 |
if (CheckScalarOrVector(&SemaRef, TheCall, getASTContext().BoolTy, 0)) |
| 3479 |
return true; |
| 3480 |
QualType ArgTy = TheCall->getArg(0)->getType(); |
| 3481 |
if (ArgTy->isBooleanType() && CheckBoolSelect(&SemaRef, TheCall)) |
| 3482 |
return true; |
| 3483 |
auto *VTy = ArgTy->getAs<VectorType>(); |
| 3484 |
if (VTy && VTy->getElementType()->isBooleanType() && |
| 3485 |
CheckVectorSelect(&SemaRef, TheCall)) |
| 3486 |
return true; |
| 3487 |
break; |
| 3488 |
} |
| 3489 |
case Builtin::BI__builtin_hlsl_elementwise_saturate: |
| 3490 |
case Builtin::BI__builtin_hlsl_elementwise_rcp: { |
| 3491 |
if (SemaRef.checkArgCount(TheCall, 1)) |
| 3492 |
return true; |
| 3493 |
if (!TheCall->getArg(0) |
| 3494 |
->getType() |
| 3495 |
->hasFloatingRepresentation()) // half or float or double |
| 3496 |
return SemaRef.Diag(TheCall->getArg(0)->getBeginLoc(), |
| 3497 |
diag::err_builtin_invalid_arg_type) |
| 3498 |
<< /* ordinal */ 1 << /* scalar or vector */ 5 << /* no int */ 0 |
| 3499 |
<< /* fp */ 1 << TheCall->getArg(0)->getType(); |
| 3500 |
if (SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall)) |
| 3501 |
return true; |
| 3502 |
break; |
| 3503 |
} |
| 3504 |
case Builtin::BI__builtin_hlsl_elementwise_degrees: |
| 3505 |
case Builtin::BI__builtin_hlsl_elementwise_radians: |
| 3506 |
case Builtin::BI__builtin_hlsl_elementwise_rsqrt: |
| 3507 |
case Builtin::BI__builtin_hlsl_elementwise_frac: |
| 3508 |
case Builtin::BI__builtin_hlsl_elementwise_ddx_coarse: |
| 3509 |
case Builtin::BI__builtin_hlsl_elementwise_ddy_coarse: |
| 3510 |
case Builtin::BI__builtin_hlsl_elementwise_ddx_fine: |
| 3511 |
case Builtin::BI__builtin_hlsl_elementwise_ddy_fine: { |
| 3512 |
if (SemaRef.checkArgCount(TheCall, 1)) |
| 3513 |
return true; |
| 3514 |
if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall, |
| 3515 |
CheckFloatOrHalfRepresentation)) |
| 3516 |
return true; |
| 3517 |
if (SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall)) |
| 3518 |
return true; |
| 3519 |
break; |
| 3520 |
} |
| 3521 |
case Builtin::BI__builtin_hlsl_elementwise_isinf: |
| 3522 |
case Builtin::BI__builtin_hlsl_elementwise_isnan: { |
| 3523 |
if (SemaRef.checkArgCount(TheCall, 1)) |
| 3524 |
return true; |
| 3525 |
if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall, |
| 3526 |
CheckFloatOrHalfRepresentation)) |
| 3527 |
return true; |
| 3528 |
if (SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall)) |
| 3529 |
return true; |
| 3530 |
SetElementTypeAsReturnType(&SemaRef, TheCall, getASTContext().BoolTy); |
| 3531 |
break; |
| 3532 |
} |
| 3533 |
case Builtin::BI__builtin_hlsl_lerp: { |
| 3534 |
if (SemaRef.checkArgCount(TheCall, 3)) |
| 3535 |
return true; |
| 3536 |
if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall, |
| 3537 |
CheckFloatOrHalfRepresentation)) |
| 3538 |
return true; |
| 3539 |
if (CheckAllArgsHaveSameType(&SemaRef, TheCall)) |
| 3540 |
return true; |
| 3541 |
if (SemaRef.BuiltinElementwiseTernaryMath(TheCall)) |
| 3542 |
return true; |
| 3543 |
break; |
| 3544 |
} |
| 3545 |
case Builtin::BI__builtin_hlsl_mad: { |
| 3546 |
if (SemaRef.BuiltinElementwiseTernaryMath( |
| 3547 |
TheCall, /*ArgTyRestr=*/ |
| 3548 |
Sema::EltwiseBuiltinArgTyRestriction::None)) |
| 3549 |
return true; |
| 3550 |
break; |
| 3551 |
} |
| 3552 |
case Builtin::BI__builtin_hlsl_normalize: { |
| 3553 |
if (SemaRef.checkArgCount(TheCall, 1)) |
| 3554 |
return true; |
| 3555 |
if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall, |
| 3556 |
CheckFloatOrHalfRepresentation)) |
| 3557 |
return true; |
| 3558 |
ExprResult A = TheCall->getArg(0); |
| 3559 |
QualType ArgTyA = A.get()->getType(); |
| 3560 |
// return type is the same as the input type |
| 3561 |
TheCall->setType(ArgTyA); |
| 3562 |
break; |
| 3563 |
} |
| 3564 |
case Builtin::BI__builtin_hlsl_elementwise_sign: { |
| 3565 |
if (SemaRef.PrepareBuiltinElementwiseMathOneArgCall(TheCall)) |
| 3566 |
return true; |
| 3567 |
if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall, |
| 3568 |
CheckFloatingOrIntRepresentation)) |
| 3569 |
return true; |
| 3570 |
SetElementTypeAsReturnType(&SemaRef, TheCall, getASTContext().IntTy); |
| 3571 |
break; |
| 3572 |
} |
| 3573 |
case Builtin::BI__builtin_hlsl_step: { |
| 3574 |
if (SemaRef.checkArgCount(TheCall, 2)) |
| 3575 |
return true; |
| 3576 |
if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall, |
| 3577 |
CheckFloatOrHalfRepresentation)) |
| 3578 |
return true; |
| 3579 |
|
| 3580 |
ExprResult A = TheCall->getArg(0); |
| 3581 |
QualType ArgTyA = A.get()->getType(); |
| 3582 |
// return type is the same as the input type |
| 3583 |
TheCall->setType(ArgTyA); |
| 3584 |
break; |
| 3585 |
} |
| 3586 |
case Builtin::BI__builtin_hlsl_wave_active_max: |
| 3587 |
case Builtin::BI__builtin_hlsl_wave_active_min: |
| 3588 |
case Builtin::BI__builtin_hlsl_wave_active_sum: { |
| 3589 |
if (SemaRef.checkArgCount(TheCall, 1)) |
| 3590 |
return true; |
| 3591 |
|
| 3592 |
// Ensure input expr type is a scalar/vector and the same as the return type |
| 3593 |
if (CheckAnyScalarOrVector(&SemaRef, TheCall, 0)) |
| 3594 |
return true; |
| 3595 |
if (CheckWaveActive(&SemaRef, TheCall)) |
| 3596 |
return true; |
| 3597 |
ExprResult Expr = TheCall->getArg(0); |
| 3598 |
QualType ArgTyExpr = Expr.get()->getType(); |
| 3599 |
TheCall->setType(ArgTyExpr); |
| 3600 |
break; |
| 3601 |
} |
| 3602 |
// Note these are llvm builtins that we want to catch invalid intrinsic |
| 3603 |
// generation. Normal handling of these builtins will occur elsewhere. |
| 3604 |
case Builtin::BI__builtin_elementwise_bitreverse: { |
| 3605 |
// does not include a check for number of arguments |
| 3606 |
// because that is done previously |
| 3607 |
if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall, |
| 3608 |
CheckUnsignedIntRepresentation)) |
| 3609 |
return true; |
| 3610 |
break; |
| 3611 |
} |
| 3612 |
case Builtin::BI__builtin_hlsl_wave_read_lane_at: { |
| 3613 |
if (SemaRef.checkArgCount(TheCall, 2)) |
| 3614 |
return true; |
| 3615 |
|
| 3616 |
// Ensure index parameter type can be interpreted as a uint |
| 3617 |
ExprResult Index = TheCall->getArg(1); |
| 3618 |
QualType ArgTyIndex = Index.get()->getType(); |
| 3619 |
if (!ArgTyIndex->isIntegerType()) { |
| 3620 |
SemaRef.Diag(TheCall->getArg(1)->getBeginLoc(), |
| 3621 |
diag::err_typecheck_convert_incompatible) |
| 3622 |
<< ArgTyIndex << SemaRef.Context.UnsignedIntTy << 1 << 0 << 0; |
| 3623 |
return true; |
| 3624 |
} |
| 3625 |
|
| 3626 |
// Ensure input expr type is a scalar/vector and the same as the return type |
| 3627 |
if (CheckAnyScalarOrVector(&SemaRef, TheCall, 0)) |
| 3628 |
return true; |
| 3629 |
|
| 3630 |
ExprResult Expr = TheCall->getArg(0); |
| 3631 |
QualType ArgTyExpr = Expr.get()->getType(); |
| 3632 |
TheCall->setType(ArgTyExpr); |
| 3633 |
break; |
| 3634 |
} |
| 3635 |
case Builtin::BI__builtin_hlsl_wave_get_lane_index: { |
| 3636 |
if (SemaRef.checkArgCount(TheCall, 0)) |
| 3637 |
return true; |
| 3638 |
break; |
| 3639 |
} |
| 3640 |
case Builtin::BI__builtin_hlsl_elementwise_splitdouble: { |
| 3641 |
if (SemaRef.checkArgCount(TheCall, 3)) |
| 3642 |
return true; |
| 3643 |
|
| 3644 |
if (CheckScalarOrVector(&SemaRef, TheCall, SemaRef.Context.DoubleTy, 0) || |
| 3645 |
CheckScalarOrVector(&SemaRef, TheCall, SemaRef.Context.UnsignedIntTy, |
| 3646 |
1) || |
| 3647 |
CheckScalarOrVector(&SemaRef, TheCall, SemaRef.Context.UnsignedIntTy, |
| 3648 |
2)) |
| 3649 |
return true; |
| 3650 |
|
| 3651 |
if (CheckModifiableLValue(&SemaRef, TheCall, 1) || |
| 3652 |
CheckModifiableLValue(&SemaRef, TheCall, 2)) |
| 3653 |
return true; |
| 3654 |
break; |
| 3655 |
} |
| 3656 |
case Builtin::BI__builtin_hlsl_elementwise_clip: { |
| 3657 |
if (SemaRef.checkArgCount(TheCall, 1)) |
| 3658 |
return true; |
| 3659 |
|
| 3660 |
if (CheckScalarOrVector(&SemaRef, TheCall, SemaRef.Context.FloatTy, 0)) |
| 3661 |
return true; |
| 3662 |
break; |
| 3663 |
} |
| 3664 |
case Builtin::BI__builtin_elementwise_acos: |
| 3665 |
case Builtin::BI__builtin_elementwise_asin: |
| 3666 |
case Builtin::BI__builtin_elementwise_atan: |
| 3667 |
case Builtin::BI__builtin_elementwise_atan2: |
| 3668 |
case Builtin::BI__builtin_elementwise_ceil: |
| 3669 |
case Builtin::BI__builtin_elementwise_cos: |
| 3670 |
case Builtin::BI__builtin_elementwise_cosh: |
| 3671 |
case Builtin::BI__builtin_elementwise_exp: |
| 3672 |
case Builtin::BI__builtin_elementwise_exp2: |
| 3673 |
case Builtin::BI__builtin_elementwise_exp10: |
| 3674 |
case Builtin::BI__builtin_elementwise_floor: |
| 3675 |
case Builtin::BI__builtin_elementwise_fmod: |
| 3676 |
case Builtin::BI__builtin_elementwise_log: |
| 3677 |
case Builtin::BI__builtin_elementwise_log2: |
| 3678 |
case Builtin::BI__builtin_elementwise_log10: |
| 3679 |
case Builtin::BI__builtin_elementwise_pow: |
| 3680 |
case Builtin::BI__builtin_elementwise_roundeven: |
| 3681 |
case Builtin::BI__builtin_elementwise_sin: |
| 3682 |
case Builtin::BI__builtin_elementwise_sinh: |
| 3683 |
case Builtin::BI__builtin_elementwise_sqrt: |
| 3684 |
case Builtin::BI__builtin_elementwise_tan: |
| 3685 |
case Builtin::BI__builtin_elementwise_tanh: |
| 3686 |
case Builtin::BI__builtin_elementwise_trunc: { |
| 3687 |
if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall, |
| 3688 |
CheckFloatOrHalfRepresentation)) |
| 3689 |
return true; |
| 3690 |
break; |
| 3691 |
} |
| 3692 |
case Builtin::BI__builtin_hlsl_buffer_update_counter: { |
| 3693 |
assert(TheCall->getNumArgs() == 2 && "expected 2 args"); |
| 3694 |
auto checkResTy = [](const HLSLAttributedResourceType *ResTy) -> bool { |
| 3695 |
return !(ResTy->getAttrs().ResourceClass == ResourceClass::UAV && |
| 3696 |
ResTy->getAttrs().RawBuffer && ResTy->hasContainedType()); |
| 3697 |
}; |
| 3698 |
if (CheckResourceHandle(&SemaRef, TheCall, 0, checkResTy)) |
| 3699 |
return true; |
| 3700 |
Expr *OffsetExpr = TheCall->getArg(1); |
| 3701 |
std::optional<llvm::APSInt> Offset = |
| 3702 |
OffsetExpr->getIntegerConstantExpr(SemaRef.getASTContext()); |
| 3703 |
if (!Offset.has_value() || std::abs(Offset->getExtValue()) != 1) { |
| 3704 |
SemaRef.Diag(TheCall->getArg(1)->getBeginLoc(), |
| 3705 |
diag::err_hlsl_expect_arg_const_int_one_or_neg_one) |
| 3706 |
<< 1; |
| 3707 |
return true; |
| 3708 |
} |
| 3709 |
break; |
| 3710 |
} |
| 3711 |
case Builtin::BI__builtin_hlsl_elementwise_f16tof32: { |
| 3712 |
if (SemaRef.checkArgCount(TheCall, 1)) |
| 3713 |
return true; |
| 3714 |
if (CheckAllArgTypesAreCorrect(&SemaRef, TheCall, |
| 3715 |
CheckUnsignedIntRepresentation)) |
| 3716 |
return true; |
| 3717 |
// ensure arg integers are 32 bits |
| 3718 |
if (CheckExpectedBitWidth(&SemaRef, TheCall, 0, 32)) |
| 3719 |
return true; |
| 3720 |
// check it wasn't a bool type |
| 3721 |
QualType ArgTy = TheCall->getArg(0)->getType(); |
| 3722 |
if (auto *VTy = ArgTy->getAs<VectorType>()) |
| 3723 |
ArgTy = VTy->getElementType(); |
| 3724 |
if (ArgTy->isBooleanType()) { |
| 3725 |
SemaRef.Diag(TheCall->getArg(0)->getBeginLoc(), |
| 3726 |
diag::err_builtin_invalid_arg_type) |
| 3727 |
<< 1 << /* scalar or vector of */ 5 << /* unsigned int */ 3 |
| 3728 |
<< /* no fp */ 0 << TheCall->getArg(0)->getType(); |
| 3729 |
return true; |
| 3730 |
} |
| 3731 |
|
| 3732 |
SetElementTypeAsReturnType(&SemaRef, TheCall, getASTContext().FloatTy); |
| 3733 |
break; |
| 3734 |
} |
| 3735 |
} |
| 3736 |
return false; |
| 3737 |
} |
| 3738 |
|
| 3739 |
static void BuildFlattenedTypeList(QualType BaseTy, |
| 3740 |
llvm::SmallVectorImpl<QualType> &List) { |
| 3741 |
llvm::SmallVector<QualType, 16> WorkList; |
| 3742 |
WorkList.push_back(BaseTy); |
| 3743 |
while (!WorkList.empty()) { |
| 3744 |
QualType T = WorkList.pop_back_val(); |
| 3745 |
T = T.getCanonicalType().getUnqualifiedType(); |
| 3746 |
if (const auto *AT = dyn_cast<ConstantArrayType>(T)) { |
| 3747 |
llvm::SmallVector<QualType, 16> ElementFields; |
| 3748 |
// Generally I've avoided recursion in this algorithm, but arrays of |
| 3749 |
// structs could be time-consuming to flatten and churn through on the |
| 3750 |
// work list. Hopefully nesting arrays of structs containing arrays |
| 3751 |
// of structs too many levels deep is unlikely. |
| 3752 |
BuildFlattenedTypeList(AT->getElementType(), ElementFields); |
| 3753 |
// Repeat the element's field list n times. |
| 3754 |
for (uint64_t Ct = 0; Ct < AT->getZExtSize(); ++Ct) |
| 3755 |
llvm::append_range(List, ElementFields); |
| 3756 |
continue; |
| 3757 |
} |
| 3758 |
// Vectors can only have element types that are builtin types, so this can |
| 3759 |
// add directly to the list instead of to the WorkList. |
| 3760 |
if (const auto *VT = dyn_cast<VectorType>(T)) { |
| 3761 |
List.insert(List.end(), VT->getNumElements(), VT->getElementType()); |
| 3762 |
continue; |
| 3763 |
} |
| 3764 |
if (const auto *MT = dyn_cast<ConstantMatrixType>(T)) { |
| 3765 |
List.insert(List.end(), MT->getNumElementsFlattened(), |
| 3766 |
MT->getElementType()); |
| 3767 |
continue; |
| 3768 |
} |
| 3769 |
if (const auto *RD = T->getAsCXXRecordDecl()) { |
| 3770 |
if (RD->isStandardLayout()) |
| 3771 |
RD = RD->getStandardLayoutBaseWithFields(); |
| 3772 |
|
| 3773 |
// For types that we shouldn't decompose (unions and non-aggregates), just |
| 3774 |
// add the type itself to the list. |
| 3775 |
if (RD->isUnion() || !RD->isAggregate()) { |
| 3776 |
List.push_back(T); |
| 3777 |
continue; |
| 3778 |
} |
| 3779 |
|
| 3780 |
llvm::SmallVector<QualType, 16> FieldTypes; |
| 3781 |
for (const auto *FD : RD->fields()) |
| 3782 |
if (!FD->isUnnamedBitField()) |
| 3783 |
FieldTypes.push_back(FD->getType()); |
| 3784 |
// Reverse the newly added sub-range. |
| 3785 |
std::reverse(FieldTypes.begin(), FieldTypes.end()); |
| 3786 |
llvm::append_range(WorkList, FieldTypes); |
| 3787 |
|
| 3788 |
// If this wasn't a standard layout type we may also have some base |
| 3789 |
// classes to deal with. |
| 3790 |
if (!RD->isStandardLayout()) { |
| 3791 |
FieldTypes.clear(); |
| 3792 |
for (const auto &Base : RD->bases()) |
| 3793 |
FieldTypes.push_back(Base.getType()); |
| 3794 |
std::reverse(FieldTypes.begin(), FieldTypes.end()); |
| 3795 |
llvm::append_range(WorkList, FieldTypes); |
| 3796 |
} |
| 3797 |
continue; |
| 3798 |
} |
| 3799 |
List.push_back(T); |
| 3800 |
} |
| 3801 |
} |
| 3802 |
|
| 3803 |
bool SemaHLSL::IsTypedResourceElementCompatible(clang::QualType QT) { |
| 3804 |
// null and array types are not allowed. |
| 3805 |
if (QT.isNull() || QT->isArrayType()) |
| 3806 |
return false; |
| 3807 |
|
| 3808 |
// UDT types are not allowed |
| 3809 |
if (QT->isRecordType()) |
| 3810 |
return false; |
| 3811 |
|
| 3812 |
if (QT->isBooleanType() || QT->isEnumeralType()) |
| 3813 |
return false; |
| 3814 |
|
| 3815 |
// the only other valid builtin types are scalars or vectors |
| 3816 |
if (QT->isArithmeticType()) { |
| 3817 |
if (SemaRef.Context.getTypeSize(QT) / 8 > 16) |
| 3818 |
return false; |
| 3819 |
return true; |
| 3820 |
} |
| 3821 |
|
| 3822 |
if (const VectorType *VT = QT->getAs<VectorType>()) { |
| 3823 |
int ArraySize = VT->getNumElements(); |
| 3824 |
|
| 3825 |
if (ArraySize > 4) |
| 3826 |
return false; |
| 3827 |
|
| 3828 |
QualType ElTy = VT->getElementType(); |
| 3829 |
if (ElTy->isBooleanType()) |
| 3830 |
return false; |
| 3831 |
|
| 3832 |
if (SemaRef.Context.getTypeSize(QT) / 8 > 16) |
| 3833 |
return false; |
| 3834 |
return true; |
| 3835 |
} |
| 3836 |
|
| 3837 |
return false; |
| 3838 |
} |
| 3839 |
|
| 3840 |
bool SemaHLSL::IsScalarizedLayoutCompatible(QualType T1, QualType T2) const { |
| 3841 |
if (T1.isNull() || T2.isNull()) |
| 3842 |
return false; |
| 3843 |
|
| 3844 |
T1 = T1.getCanonicalType().getUnqualifiedType(); |
| 3845 |
T2 = T2.getCanonicalType().getUnqualifiedType(); |
| 3846 |
|
| 3847 |
// If both types are the same canonical type, they're obviously compatible. |
| 3848 |
if (SemaRef.getASTContext().hasSameType(T1, T2)) |
| 3849 |
return true; |
| 3850 |
|
| 3851 |
llvm::SmallVector<QualType, 16> T1Types; |
| 3852 |
BuildFlattenedTypeList(T1, T1Types); |
| 3853 |
llvm::SmallVector<QualType, 16> T2Types; |
| 3854 |
BuildFlattenedTypeList(T2, T2Types); |
| 3855 |
|
| 3856 |
// Check the flattened type list |
| 3857 |
return llvm::equal(T1Types, T2Types, |
| 3858 |
[this](QualType LHS, QualType RHS) -> bool { |
| 3859 |
return SemaRef.IsLayoutCompatible(LHS, RHS); |
| 3860 |
}); |
| 3861 |
} |
| 3862 |
|
| 3863 |
bool SemaHLSL::CheckCompatibleParameterABI(FunctionDecl *New, |
| 3864 |
FunctionDecl *Old) { |
| 3865 |
if (New->getNumParams() != Old->getNumParams()) |
| 3866 |
return true; |
| 3867 |
|
| 3868 |
bool HadError = false; |
| 3869 |
|
| 3870 |
for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { |
| 3871 |
ParmVarDecl *NewParam = New->getParamDecl(i); |
| 3872 |
ParmVarDecl *OldParam = Old->getParamDecl(i); |
| 3873 |
|
| 3874 |
// HLSL parameter declarations for inout and out must match between |
| 3875 |
// declarations. In HLSL inout and out are ambiguous at the call site, |
| 3876 |
// but have different calling behavior, so you cannot overload a |
| 3877 |
// method based on a difference between inout and out annotations. |
| 3878 |
const auto *NDAttr = NewParam->getAttr<HLSLParamModifierAttr>(); |
| 3879 |
unsigned NSpellingIdx = (NDAttr ? NDAttr->getSpellingListIndex() : 0); |
| 3880 |
const auto *ODAttr = OldParam->getAttr<HLSLParamModifierAttr>(); |
| 3881 |
unsigned OSpellingIdx = (ODAttr ? ODAttr->getSpellingListIndex() : 0); |
| 3882 |
|
| 3883 |
if (NSpellingIdx != OSpellingIdx) { |
| 3884 |
SemaRef.Diag(NewParam->getLocation(), |
| 3885 |
diag::err_hlsl_param_qualifier_mismatch) |
| 3886 |
<< NDAttr << NewParam; |
| 3887 |
SemaRef.Diag(OldParam->getLocation(), diag::note_previous_declaration_as) |
| 3888 |
<< ODAttr; |
| 3889 |
HadError = true; |
| 3890 |
} |
| 3891 |
} |
| 3892 |
return HadError; |
| 3893 |
} |
| 3894 |
|
| 3895 |
// Generally follows PerformScalarCast, with cases reordered for |
| 3896 |
// clarity of what types are supported |
| 3897 |
bool SemaHLSL::CanPerformScalarCast(QualType SrcTy, QualType DestTy) { |
| 3898 |
|
| 3899 |
if (!SrcTy->isScalarType() || !DestTy->isScalarType()) |
| 3900 |
return false; |
| 3901 |
|
| 3902 |
if (SemaRef.getASTContext().hasSameUnqualifiedType(SrcTy, DestTy)) |
| 3903 |
return true; |
| 3904 |
|
| 3905 |
switch (SrcTy->getScalarTypeKind()) { |
| 3906 |
case Type::STK_Bool: // casting from bool is like casting from an integer |
| 3907 |
case Type::STK_Integral: |
| 3908 |
switch (DestTy->getScalarTypeKind()) { |
| 3909 |
case Type::STK_Bool: |
| 3910 |
case Type::STK_Integral: |
| 3911 |
case Type::STK_Floating: |
| 3912 |
return true; |
| 3913 |
case Type::STK_CPointer: |
| 3914 |
case Type::STK_ObjCObjectPointer: |
| 3915 |
case Type::STK_BlockPointer: |
| 3916 |
case Type::STK_MemberPointer: |
| 3917 |
llvm_unreachable("HLSL doesn't support pointers."); |
| 3918 |
case Type::STK_IntegralComplex: |
| 3919 |
case Type::STK_FloatingComplex: |
| 3920 |
llvm_unreachable("HLSL doesn't support complex types."); |
| 3921 |
case Type::STK_FixedPoint: |
| 3922 |
llvm_unreachable("HLSL doesn't support fixed point types."); |
| 3923 |
} |
| 3924 |
llvm_unreachable("Should have returned before this"); |
| 3925 |
|
| 3926 |
case Type::STK_Floating: |
| 3927 |
switch (DestTy->getScalarTypeKind()) { |
| 3928 |
case Type::STK_Floating: |
| 3929 |
case Type::STK_Bool: |
| 3930 |
case Type::STK_Integral: |
| 3931 |
return true; |
| 3932 |
case Type::STK_FloatingComplex: |
| 3933 |
case Type::STK_IntegralComplex: |
| 3934 |
llvm_unreachable("HLSL doesn't support complex types."); |
| 3935 |
case Type::STK_FixedPoint: |
| 3936 |
llvm_unreachable("HLSL doesn't support fixed point types."); |
| 3937 |
case Type::STK_CPointer: |
| 3938 |
case Type::STK_ObjCObjectPointer: |
| 3939 |
case Type::STK_BlockPointer: |
| 3940 |
case Type::STK_MemberPointer: |
| 3941 |
llvm_unreachable("HLSL doesn't support pointers."); |
| 3942 |
} |
| 3943 |
llvm_unreachable("Should have returned before this"); |
| 3944 |
|
| 3945 |
case Type::STK_MemberPointer: |
| 3946 |
case Type::STK_CPointer: |
| 3947 |
case Type::STK_BlockPointer: |
| 3948 |
case Type::STK_ObjCObjectPointer: |
| 3949 |
llvm_unreachable("HLSL doesn't support pointers."); |
| 3950 |
|
| 3951 |
case Type::STK_FixedPoint: |
| 3952 |
llvm_unreachable("HLSL doesn't support fixed point types."); |
| 3953 |
|
| 3954 |
case Type::STK_FloatingComplex: |
| 3955 |
case Type::STK_IntegralComplex: |
| 3956 |
llvm_unreachable("HLSL doesn't support complex types."); |
| 3957 |
} |
| 3958 |
|
| 3959 |
llvm_unreachable("Unhandled scalar cast"); |
| 3960 |
} |
| 3961 |
|
| 3962 |
// Can perform an HLSL Aggregate splat cast if the Dest is an aggregate and the |
| 3963 |
// Src is a scalar or a vector of length 1 |
| 3964 |
// Or if Dest is a vector and Src is a vector of length 1 |
| 3965 |
bool SemaHLSL::CanPerformAggregateSplatCast(Expr *Src, QualType DestTy) { |
| 3966 |
|
| 3967 |
QualType SrcTy = Src->getType(); |
| 3968 |
// Not a valid HLSL Aggregate Splat cast if Dest is a scalar or if this is |
| 3969 |
// going to be a vector splat from a scalar. |
| 3970 |
if ((SrcTy->isScalarType() && DestTy->isVectorType()) || |
| 3971 |
DestTy->isScalarType()) |
| 3972 |
return false; |
| 3973 |
|
| 3974 |
const VectorType *SrcVecTy = SrcTy->getAs<VectorType>(); |
| 3975 |
|
| 3976 |
// Src isn't a scalar or a vector of length 1 |
| 3977 |
if (!SrcTy->isScalarType() && !(SrcVecTy && SrcVecTy->getNumElements() == 1)) |
| 3978 |
return false; |
| 3979 |
|
| 3980 |
if (SrcVecTy) |
| 3981 |
SrcTy = SrcVecTy->getElementType(); |
| 3982 |
|
| 3983 |
llvm::SmallVector<QualType> DestTypes; |
| 3984 |
BuildFlattenedTypeList(DestTy, DestTypes); |
| 3985 |
|
| 3986 |
for (unsigned I = 0, Size = DestTypes.size(); I < Size; ++I) { |
| 3987 |
if (DestTypes[I]->isUnionType()) |
| 3988 |
return false; |
| 3989 |
if (!CanPerformScalarCast(SrcTy, DestTypes[I])) |
| 3990 |
return false; |
| 3991 |
} |
| 3992 |
return true; |
| 3993 |
} |
| 3994 |
|
| 3995 |
// Can we perform an HLSL Elementwise cast? |
| 3996 |
bool SemaHLSL::CanPerformElementwiseCast(Expr *Src, QualType DestTy) { |
| 3997 |
|
| 3998 |
// Don't handle casts where LHS and RHS are any combination of scalar/vector |
| 3999 |
// There must be an aggregate somewhere |
| 4000 |
QualType SrcTy = Src->getType(); |
| 4001 |
if (SrcTy->isScalarType()) // always a splat and this cast doesn't handle that |
| 4002 |
return false; |
| 4003 |
|
| 4004 |
if (SrcTy->isVectorType() && |
| 4005 |
(DestTy->isScalarType() || DestTy->isVectorType())) |
| 4006 |
return false; |
| 4007 |
|
| 4008 |
if (SrcTy->isConstantMatrixType() && |
| 4009 |
(DestTy->isScalarType() || DestTy->isConstantMatrixType())) |
| 4010 |
return false; |
| 4011 |
|
| 4012 |
llvm::SmallVector<QualType> DestTypes; |
| 4013 |
BuildFlattenedTypeList(DestTy, DestTypes); |
| 4014 |
llvm::SmallVector<QualType> SrcTypes; |
| 4015 |
BuildFlattenedTypeList(SrcTy, SrcTypes); |
| 4016 |
|
| 4017 |
// Usually the size of SrcTypes must be greater than or equal to the size of |
| 4018 |
// DestTypes. |
| 4019 |
if (SrcTypes.size() < DestTypes.size()) |
| 4020 |
return false; |
| 4021 |
|
| 4022 |
unsigned SrcSize = SrcTypes.size(); |
| 4023 |
unsigned DstSize = DestTypes.size(); |
| 4024 |
unsigned I; |
| 4025 |
for (I = 0; I < DstSize && I < SrcSize; I++) { |
| 4026 |
if (SrcTypes[I]->isUnionType() || DestTypes[I]->isUnionType()) |
| 4027 |
return false; |
| 4028 |
if (!CanPerformScalarCast(SrcTypes[I], DestTypes[I])) { |
| 4029 |
return false; |
| 4030 |
} |
| 4031 |
} |
| 4032 |
|
| 4033 |
// check the rest of the source type for unions. |
| 4034 |
for (; I < SrcSize; I++) { |
| 4035 |
if (SrcTypes[I]->isUnionType()) |
| 4036 |
return false; |
| 4037 |
} |
| 4038 |
return true; |
| 4039 |
} |
| 4040 |
|
| 4041 |
ExprResult SemaHLSL::ActOnOutParamExpr(ParmVarDecl *Param, Expr *Arg) { |
| 4042 |
assert(Param->hasAttr<HLSLParamModifierAttr>() && |
| 4043 |
"We should not get here without a parameter modifier expression"); |
| 4044 |
const auto *Attr = Param->getAttr<HLSLParamModifierAttr>(); |
| 4045 |
if (Attr->getABI() == ParameterABI::Ordinary) |
| 4046 |
return ExprResult(Arg); |
| 4047 |
|
| 4048 |
bool IsInOut = Attr->getABI() == ParameterABI::HLSLInOut; |
| 4049 |
if (!Arg->isLValue()) { |
| 4050 |
SemaRef.Diag(Arg->getBeginLoc(), diag::error_hlsl_inout_lvalue) |
| 4051 |
<< Arg << (IsInOut ? 1 : 0); |
| 4052 |
return ExprError(); |
| 4053 |
} |
| 4054 |
|
| 4055 |
ASTContext &Ctx = SemaRef.getASTContext(); |
| 4056 |
|
| 4057 |
QualType Ty = Param->getType().getNonLValueExprType(Ctx); |
| 4058 |
|
| 4059 |
// HLSL allows implicit conversions from scalars to vectors, but not the |
| 4060 |
// inverse, so we need to disallow `inout` with scalar->vector or |
| 4061 |
// scalar->matrix conversions. |
| 4062 |
if (Arg->getType()->isScalarType() != Ty->isScalarType()) { |
| 4063 |
SemaRef.Diag(Arg->getBeginLoc(), diag::error_hlsl_inout_scalar_extension) |
| 4064 |
<< Arg << (IsInOut ? 1 : 0); |
| 4065 |
return ExprError(); |
| 4066 |
} |
| 4067 |
|
| 4068 |
auto *ArgOpV = new (Ctx) OpaqueValueExpr(Param->getBeginLoc(), Arg->getType(), |
| 4069 |
VK_LValue, OK_Ordinary, Arg); |
| 4070 |
|
| 4071 |
// Parameters are initialized via copy initialization. This allows for |
| 4072 |
// overload resolution of argument constructors. |
| 4073 |
InitializedEntity Entity = |
| 4074 |
InitializedEntity::InitializeParameter(Ctx, Ty, false); |
| 4075 |
ExprResult Res = |
| 4076 |
SemaRef.PerformCopyInitialization(Entity, Param->getBeginLoc(), ArgOpV); |
| 4077 |
if (Res.isInvalid()) |
| 4078 |
return ExprError(); |
| 4079 |
Expr *Base = Res.get(); |
| 4080 |
// After the cast, drop the reference type when creating the exprs. |
| 4081 |
Ty = Ty.getNonLValueExprType(Ctx); |
| 4082 |
auto *OpV = new (Ctx) |
| 4083 |
OpaqueValueExpr(Param->getBeginLoc(), Ty, VK_LValue, OK_Ordinary, Base); |
| 4084 |
|
| 4085 |
// Writebacks are performed with `=` binary operator, which allows for |
| 4086 |
// overload resolution on writeback result expressions. |
| 4087 |
Res = SemaRef.ActOnBinOp(SemaRef.getCurScope(), Param->getBeginLoc(), |
| 4088 |
tok::equal, ArgOpV, OpV); |
| 4089 |
|
| 4090 |
if (Res.isInvalid()) |
| 4091 |
return ExprError(); |
| 4092 |
Expr *Writeback = Res.get(); |
| 4093 |
auto *OutExpr = |
| 4094 |
HLSLOutArgExpr::Create(Ctx, Ty, ArgOpV, OpV, Writeback, IsInOut); |
| 4095 |
|
| 4096 |
return ExprResult(OutExpr); |
| 4097 |
} |
| 4098 |
|
| 4099 |
QualType SemaHLSL::getInoutParameterType(QualType Ty) { |
| 4100 |
// If HLSL gains support for references, all the cites that use this will need |
| 4101 |
// to be updated with semantic checking to produce errors for |
| 4102 |
// pointers/references. |
| 4103 |
assert(!Ty->isReferenceType() && |
| 4104 |
"Pointer and reference types cannot be inout or out parameters"); |
| 4105 |
Ty = SemaRef.getASTContext().getLValueReferenceType(Ty); |
| 4106 |
Ty.addRestrict(); |
| 4107 |
return Ty; |
| 4108 |
} |
| 4109 |
|
| 4110 |
static bool IsDefaultBufferConstantDecl(const ASTContext &Ctx, VarDecl *VD) { |
| 4111 |
bool IsVulkan = |
| 4112 |
Ctx.getTargetInfo().getTriple().getOS() == llvm::Triple::Vulkan; |
| 4113 |
bool IsVKPushConstant = IsVulkan && VD->hasAttr<HLSLVkPushConstantAttr>(); |
| 4114 |
QualType QT = VD->getType(); |
| 4115 |
return VD->getDeclContext()->isTranslationUnit() && |
| 4116 |
QT.getAddressSpace() == LangAS::Default && |
| 4117 |
VD->getStorageClass() != SC_Static && |
| 4118 |
!VD->hasAttr<HLSLVkConstantIdAttr>() && !IsVKPushConstant && |
| 4119 |
!isInvalidConstantBufferLeafElementType(QT.getTypePtr()); |
| 4120 |
} |
| 4121 |
|
| 4122 |
void SemaHLSL::deduceAddressSpace(VarDecl *Decl) { |
| 4123 |
// The variable already has an address space (groupshared for ex). |
| 4124 |
if (Decl->getType().hasAddressSpace()) |
| 4125 |
return; |
| 4126 |
|
| 4127 |
if (Decl->getType()->isDependentType()) |
| 4128 |
return; |
| 4129 |
|
| 4130 |
QualType Type = Decl->getType(); |
| 4131 |
|
| 4132 |
if (Decl->hasAttr<HLSLVkExtBuiltinInputAttr>()) { |
| 4133 |
LangAS ImplAS = LangAS::hlsl_input; |
| 4134 |
Type = SemaRef.getASTContext().getAddrSpaceQualType(Type, ImplAS); |
| 4135 |
Decl->setType(Type); |
| 4136 |
return; |
| 4137 |
} |
| 4138 |
|
| 4139 |
bool IsVulkan = getASTContext().getTargetInfo().getTriple().getOS() == |
| 4140 |
llvm::Triple::Vulkan; |
| 4141 |
if (IsVulkan && Decl->hasAttr<HLSLVkPushConstantAttr>()) { |
| 4142 |
if (HasDeclaredAPushConstant) |
| 4143 |
SemaRef.Diag(Decl->getLocation(), diag::err_hlsl_push_constant_unique); |
| 4144 |
|
| 4145 |
LangAS ImplAS = LangAS::hlsl_push_constant; |
| 4146 |
Type = SemaRef.getASTContext().getAddrSpaceQualType(Type, ImplAS); |
| 4147 |
Decl->setType(Type); |
| 4148 |
HasDeclaredAPushConstant = true; |
| 4149 |
return; |
| 4150 |
} |
| 4151 |
|
| 4152 |
if (Type->isSamplerT() || Type->isVoidType()) |
| 4153 |
return; |
| 4154 |
|
| 4155 |
// Resource handles. |
| 4156 |
if (Type->isHLSLResourceRecord() || Type->isHLSLResourceRecordArray()) |
| 4157 |
return; |
| 4158 |
|
| 4159 |
// Only static globals belong to the Private address space. |
| 4160 |
// Non-static globals belongs to the cbuffer. |
| 4161 |
if (Decl->getStorageClass() != SC_Static && !Decl->isStaticDataMember()) |
| 4162 |
return; |
| 4163 |
|
| 4164 |
LangAS ImplAS = LangAS::hlsl_private; |
| 4165 |
Type = SemaRef.getASTContext().getAddrSpaceQualType(Type, ImplAS); |
| 4166 |
Decl->setType(Type); |
| 4167 |
} |
| 4168 |
|
| 4169 |
void SemaHLSL::ActOnVariableDeclarator(VarDecl *VD) { |
| 4170 |
if (VD->hasGlobalStorage()) { |
| 4171 |
// make sure the declaration has a complete type |
| 4172 |
if (SemaRef.RequireCompleteType( |
| 4173 |
VD->getLocation(), |
| 4174 |
SemaRef.getASTContext().getBaseElementType(VD->getType()), |
| 4175 |
diag::err_typecheck_decl_incomplete_type)) { |
| 4176 |
VD->setInvalidDecl(); |
| 4177 |
deduceAddressSpace(VD); |
| 4178 |
return; |
| 4179 |
} |
| 4180 |
|
| 4181 |
// Global variables outside a cbuffer block that are not a resource, static, |
| 4182 |
// groupshared, or an empty array or struct belong to the default constant |
| 4183 |
// buffer $Globals (to be created at the end of the translation unit). |
| 4184 |
if (IsDefaultBufferConstantDecl(getASTContext(), VD)) { |
| 4185 |
// update address space to hlsl_constant |
| 4186 |
QualType NewTy = getASTContext().getAddrSpaceQualType( |
| 4187 |
VD->getType(), LangAS::hlsl_constant); |
| 4188 |
VD->setType(NewTy); |
| 4189 |
DefaultCBufferDecls.push_back(VD); |
| 4190 |
} |
| 4191 |
|
| 4192 |
// find all resources bindings on decl |
| 4193 |
if (VD->getType()->isHLSLIntangibleType()) |
| 4194 |
collectResourceBindingsOnVarDecl(VD); |
| 4195 |
|
| 4196 |
if (VD->hasAttr<HLSLVkConstantIdAttr>()) |
| 4197 |
VD->setStorageClass(StorageClass::SC_Static); |
| 4198 |
|
| 4199 |
if (isResourceRecordTypeOrArrayOf(VD) && |
| 4200 |
VD->getStorageClass() != SC_Static) { |
| 4201 |
// Add internal linkage attribute to non-static resource variables. The |
| 4202 |
// global externally visible storage is accessed through the handle, which |
| 4203 |
// is a member. The variable itself is not externally visible. |
| 4204 |
VD->addAttr(InternalLinkageAttr::CreateImplicit(getASTContext())); |
| 4205 |
} |
| 4206 |
|
| 4207 |
// process explicit bindings |
| 4208 |
processExplicitBindingsOnDecl(VD); |
| 4209 |
|
| 4210 |
// Add implicit binding attribute to non-static resource arrays. |
| 4211 |
if (VD->getType()->isHLSLResourceRecordArray() && |
| 4212 |
VD->getStorageClass() != SC_Static) { |
| 4213 |
// If the resource array does not have an explicit binding attribute, |
| 4214 |
// create an implicit one. It will be used to transfer implicit binding |
| 4215 |
// order_ID to codegen. |
| 4216 |
ResourceBindingAttrs Binding(VD); |
| 4217 |
if (!Binding.isExplicit()) { |
| 4218 |
uint32_t OrderID = getNextImplicitBindingOrderID(); |
| 4219 |
if (Binding.hasBinding()) |
| 4220 |
Binding.setImplicitOrderID(OrderID); |
| 4221 |
else { |
| 4222 |
addImplicitBindingAttrToDecl( |
| 4223 |
SemaRef, VD, getRegisterType(getResourceArrayHandleType(VD)), |
| 4224 |
OrderID); |
| 4225 |
// Re-create the binding object to pick up the new attribute. |
| 4226 |
Binding = ResourceBindingAttrs(VD); |
| 4227 |
} |
| 4228 |
} |
| 4229 |
|
| 4230 |
// Get to the base type of a potentially multi-dimensional array. |
| 4231 |
QualType Ty = getASTContext().getBaseElementType(VD->getType()); |
| 4232 |
|
| 4233 |
const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); |
| 4234 |
if (hasCounterHandle(RD)) { |
| 4235 |
if (!Binding.hasCounterImplicitOrderID()) { |
| 4236 |
uint32_t OrderID = getNextImplicitBindingOrderID(); |
| 4237 |
Binding.setCounterImplicitOrderID(OrderID); |
| 4238 |
} |
| 4239 |
} |
| 4240 |
} |
| 4241 |
} |
| 4242 |
|
| 4243 |
deduceAddressSpace(VD); |
| 4244 |
} |
| 4245 |
|
| 4246 |
bool SemaHLSL::initGlobalResourceDecl(VarDecl *VD) { |
| 4247 |
assert(VD->getType()->isHLSLResourceRecord() && |
| 4248 |
"expected resource record type"); |
| 4249 |
|
| 4250 |
ASTContext &AST = SemaRef.getASTContext(); |
| 4251 |
uint64_t UIntTySize = AST.getTypeSize(AST.UnsignedIntTy); |
| 4252 |
uint64_t IntTySize = AST.getTypeSize(AST.IntTy); |
| 4253 |
|
| 4254 |
// Gather resource binding attributes. |
| 4255 |
ResourceBindingAttrs Binding(VD); |
| 4256 |
|
| 4257 |
// Find correct initialization method and create its arguments. |
| 4258 |
QualType ResourceTy = VD->getType(); |
| 4259 |
CXXRecordDecl *ResourceDecl = ResourceTy->getAsCXXRecordDecl(); |
| 4260 |
CXXMethodDecl *CreateMethod = nullptr; |
| 4261 |
llvm::SmallVector<Expr *> Args; |
| 4262 |
|
| 4263 |
bool HasCounter = hasCounterHandle(ResourceDecl); |
| 4264 |
const char *CreateMethodName; |
| 4265 |
if (Binding.isExplicit()) |
| 4266 |
CreateMethodName = HasCounter ? "__createFromBindingWithImplicitCounter" |
| 4267 |
: "__createFromBinding"; |
| 4268 |
else |
| 4269 |
CreateMethodName = HasCounter |
| 4270 |
? "__createFromImplicitBindingWithImplicitCounter" |
| 4271 |
: "__createFromImplicitBinding"; |
| 4272 |
|
| 4273 |
CreateMethod = |
| 4274 |
lookupMethod(SemaRef, ResourceDecl, CreateMethodName, VD->getLocation()); |
| 4275 |
|
| 4276 |
if (!CreateMethod) |
| 4277 |
// This can happen if someone creates a struct that looks like an HLSL |
| 4278 |
// resource record but does not have the required static create method. |
| 4279 |
// No binding will be generated for it. |
| 4280 |
return false; |
| 4281 |
|
| 4282 |
if (Binding.isExplicit()) { |
| 4283 |
IntegerLiteral *RegSlot = |
| 4284 |
IntegerLiteral::Create(AST, llvm::APInt(UIntTySize, Binding.getSlot()), |
| 4285 |
AST.UnsignedIntTy, SourceLocation()); |
| 4286 |
Args.push_back(RegSlot); |
| 4287 |
} else { |
| 4288 |
uint32_t OrderID = (Binding.hasImplicitOrderID()) |
| 4289 |
? Binding.getImplicitOrderID() |
| 4290 |
: getNextImplicitBindingOrderID(); |
| 4291 |
IntegerLiteral *OrderId = |
| 4292 |
IntegerLiteral::Create(AST, llvm::APInt(UIntTySize, OrderID), |
| 4293 |
AST.UnsignedIntTy, SourceLocation()); |
| 4294 |
Args.push_back(OrderId); |
| 4295 |
} |
| 4296 |
|
| 4297 |
IntegerLiteral *Space = |
| 4298 |
IntegerLiteral::Create(AST, llvm::APInt(UIntTySize, Binding.getSpace()), |
| 4299 |
AST.UnsignedIntTy, SourceLocation()); |
| 4300 |
Args.push_back(Space); |
| 4301 |
|
| 4302 |
IntegerLiteral *RangeSize = IntegerLiteral::Create( |
| 4303 |
AST, llvm::APInt(IntTySize, 1), AST.IntTy, SourceLocation()); |
| 4304 |
Args.push_back(RangeSize); |
| 4305 |
|
| 4306 |
IntegerLiteral *Index = IntegerLiteral::Create( |
| 4307 |
AST, llvm::APInt(UIntTySize, 0), AST.UnsignedIntTy, SourceLocation()); |
| 4308 |
Args.push_back(Index); |
| 4309 |
|
| 4310 |
StringRef VarName = VD->getName(); |
| 4311 |
StringLiteral *Name = StringLiteral::Create( |
| 4312 |
AST, VarName, StringLiteralKind::Ordinary, false, |
| 4313 |
AST.getStringLiteralArrayType(AST.CharTy.withConst(), VarName.size()), |
| 4314 |
SourceLocation()); |
| 4315 |
ImplicitCastExpr *NameCast = ImplicitCastExpr::Create( |
| 4316 |
AST, AST.getPointerType(AST.CharTy.withConst()), CK_ArrayToPointerDecay, |
| 4317 |
Name, nullptr, VK_PRValue, FPOptionsOverride()); |
| 4318 |
Args.push_back(NameCast); |
| 4319 |
|
| 4320 |
if (HasCounter) { |
| 4321 |
// Will this be in the correct order? |
| 4322 |
uint32_t CounterOrderID = getNextImplicitBindingOrderID(); |
| 4323 |
IntegerLiteral *CounterId = |
| 4324 |
IntegerLiteral::Create(AST, llvm::APInt(UIntTySize, CounterOrderID), |
| 4325 |
AST.UnsignedIntTy, SourceLocation()); |
| 4326 |
Args.push_back(CounterId); |
| 4327 |
} |
| 4328 |
|
| 4329 |
// Make sure the create method template is instantiated and emitted. |
| 4330 |
if (!CreateMethod->isDefined() && CreateMethod->isTemplateInstantiation()) |
| 4331 |
SemaRef.InstantiateFunctionDefinition(VD->getLocation(), CreateMethod, |
| 4332 |
true); |
| 4333 |
|
| 4334 |
// Create CallExpr with a call to the static method and set it as the decl |
| 4335 |
// initialization. |
| 4336 |
DeclRefExpr *DRE = DeclRefExpr::Create( |
| 4337 |
AST, NestedNameSpecifierLoc(), SourceLocation(), CreateMethod, false, |
| 4338 |
CreateMethod->getNameInfo(), CreateMethod->getType(), VK_PRValue); |
| 4339 |
|
| 4340 |
auto *ImpCast = ImplicitCastExpr::Create( |
| 4341 |
AST, AST.getPointerType(CreateMethod->getType()), |
| 4342 |
CK_FunctionToPointerDecay, DRE, nullptr, VK_PRValue, FPOptionsOverride()); |
| 4343 |
|
| 4344 |
CallExpr *InitExpr = |
| 4345 |
CallExpr::Create(AST, ImpCast, Args, ResourceTy, VK_PRValue, |
| 4346 |
SourceLocation(), FPOptionsOverride()); |
| 4347 |
VD->setInit(InitExpr); |
| 4348 |
VD->setInitStyle(VarDecl::CallInit); |
| 4349 |
SemaRef.CheckCompleteVariableDeclaration(VD); |
| 4350 |
return true; |
| 4351 |
} |
| 4352 |
|
| 4353 |
bool SemaHLSL::initGlobalResourceArrayDecl(VarDecl *VD) { |
| 4354 |
assert(VD->getType()->isHLSLResourceRecordArray() && |
| 4355 |
"expected array of resource records"); |
| 4356 |
|
| 4357 |
// Individual resources in a resource array are not initialized here. They |
| 4358 |
// are initialized later on during codegen when the individual resources are |
| 4359 |
// accessed. Codegen will emit a call to the resource initialization method |
| 4360 |
// with the specified array index. We need to make sure though that the method |
| 4361 |
// for the specific resource type is instantiated, so codegen can emit a call |
| 4362 |
// to it when the array element is accessed. |
| 4363 |
|
| 4364 |
// Find correct initialization method based on the resource binding |
| 4365 |
// information. |
| 4366 |
ASTContext &AST = SemaRef.getASTContext(); |
| 4367 |
QualType ResElementTy = AST.getBaseElementType(VD->getType()); |
| 4368 |
CXXRecordDecl *ResourceDecl = ResElementTy->getAsCXXRecordDecl(); |
| 4369 |
CXXMethodDecl *CreateMethod = nullptr; |
| 4370 |
|
| 4371 |
bool HasCounter = hasCounterHandle(ResourceDecl); |
| 4372 |
ResourceBindingAttrs ResourceAttrs(VD); |
| 4373 |
if (ResourceAttrs.isExplicit()) |
| 4374 |
// Resource has explicit binding. |
| 4375 |
CreateMethod = |
| 4376 |
lookupMethod(SemaRef, ResourceDecl, |
| 4377 |
HasCounter ? "__createFromBindingWithImplicitCounter" |
| 4378 |
: "__createFromBinding", |
| 4379 |
VD->getLocation()); |
| 4380 |
else |
| 4381 |
// Resource has implicit binding. |
| 4382 |
CreateMethod = lookupMethod( |
| 4383 |
SemaRef, ResourceDecl, |
| 4384 |
HasCounter ? "__createFromImplicitBindingWithImplicitCounter" |
| 4385 |
: "__createFromImplicitBinding", |
| 4386 |
VD->getLocation()); |
| 4387 |
|
| 4388 |
if (!CreateMethod) |
| 4389 |
return false; |
| 4390 |
|
| 4391 |
// Make sure the create method template is instantiated and emitted. |
| 4392 |
if (!CreateMethod->isDefined() && CreateMethod->isTemplateInstantiation()) |
| 4393 |
SemaRef.InstantiateFunctionDefinition(VD->getLocation(), CreateMethod, |
| 4394 |
true); |
| 4395 |
return true; |
| 4396 |
} |
| 4397 |
|
| 4398 |
// Returns true if the initialization has been handled. |
| 4399 |
// Returns false to use default initialization. |
| 4400 |
bool SemaHLSL::ActOnUninitializedVarDecl(VarDecl *VD) { |
| 4401 |
// Objects in the hlsl_constant address space are initialized |
| 4402 |
// externally, so don't synthesize an implicit initializer. |
| 4403 |
if (VD->getType().getAddressSpace() == LangAS::hlsl_constant) |
| 4404 |
return true; |
| 4405 |
|
| 4406 |
// Initialize non-static resources at the global scope. |
| 4407 |
if (VD->hasGlobalStorage() && VD->getStorageClass() != SC_Static) { |
| 4408 |
const Type *Ty = VD->getType().getTypePtr(); |
| 4409 |
if (Ty->isHLSLResourceRecord()) |
| 4410 |
return initGlobalResourceDecl(VD); |
| 4411 |
if (Ty->isHLSLResourceRecordArray()) |
| 4412 |
return initGlobalResourceArrayDecl(VD); |
| 4413 |
} |
| 4414 |
return false; |
| 4415 |
} |
| 4416 |
|
| 4417 |
// Return true if everything is ok; returns false if there was an error. |
| 4418 |
bool SemaHLSL::CheckResourceBinOp(BinaryOperatorKind Opc, Expr *LHSExpr, |
| 4419 |
Expr *RHSExpr, SourceLocation Loc) { |
| 4420 |
assert((LHSExpr->getType()->isHLSLResourceRecord() || |
| 4421 |
LHSExpr->getType()->isHLSLResourceRecordArray()) && |
| 4422 |
"expected LHS to be a resource record or array of resource records"); |
| 4423 |
if (Opc != BO_Assign) |
| 4424 |
return true; |
| 4425 |
|
| 4426 |
// If LHS is an array subscript, get the underlying declaration. |
| 4427 |
Expr *E = LHSExpr; |
| 4428 |
while (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) |
| 4429 |
E = ASE->getBase()->IgnoreParenImpCasts(); |
| 4430 |
|
| 4431 |
// Report error if LHS is a non-static resource declared at a global scope. |
| 4432 |
if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { |
| 4433 |
if (VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { |
| 4434 |
if (VD->hasGlobalStorage() && VD->getStorageClass() != SC_Static) { |
| 4435 |
// assignment to global resource is not allowed |
| 4436 |
SemaRef.Diag(Loc, diag::err_hlsl_assign_to_global_resource) << VD; |
| 4437 |
SemaRef.Diag(VD->getLocation(), diag::note_var_declared_here) << VD; |
| 4438 |
return false; |
| 4439 |
} |
| 4440 |
} |
| 4441 |
} |
| 4442 |
return true; |
| 4443 |
} |
| 4444 |
|
| 4445 |
// Walks though the global variable declaration, collects all resource binding |
| 4446 |
// requirements and adds them to Bindings |
| 4447 |
void SemaHLSL::collectResourceBindingsOnVarDecl(VarDecl *VD) { |
| 4448 |
assert(VD->hasGlobalStorage() && VD->getType()->isHLSLIntangibleType() && |
| 4449 |
"expected global variable that contains HLSL resource"); |
| 4450 |
|
| 4451 |
// Cbuffers and Tbuffers are HLSLBufferDecl types |
| 4452 |
if (const HLSLBufferDecl *CBufferOrTBuffer = dyn_cast<HLSLBufferDecl>(VD)) { |
| 4453 |
Bindings.addDeclBindingInfo(VD, CBufferOrTBuffer->isCBuffer() |
| 4454 |
? ResourceClass::CBuffer |
| 4455 |
: ResourceClass::SRV); |
| 4456 |
return; |
| 4457 |
} |
| 4458 |
|
| 4459 |
// Unwrap arrays |
| 4460 |
// FIXME: Calculate array size while unwrapping |
| 4461 |
const Type *Ty = VD->getType()->getUnqualifiedDesugaredType(); |
| 4462 |
while (Ty->isArrayType()) { |
| 4463 |
const ArrayType *AT = cast<ArrayType>(Ty); |
| 4464 |
Ty = AT->getElementType()->getUnqualifiedDesugaredType(); |
| 4465 |
} |
| 4466 |
|
| 4467 |
// Resource (or array of resources) |
| 4468 |
if (const HLSLAttributedResourceType *AttrResType = |
| 4469 |
HLSLAttributedResourceType::findHandleTypeOnResource(Ty)) { |
| 4470 |
Bindings.addDeclBindingInfo(VD, AttrResType->getAttrs().ResourceClass); |
| 4471 |
return; |
| 4472 |
} |
| 4473 |
|
| 4474 |
// User defined record type |
| 4475 |
if (const RecordType *RT = dyn_cast<RecordType>(Ty)) |
| 4476 |
collectResourceBindingsOnUserRecordDecl(VD, RT); |
| 4477 |
} |
| 4478 |
|
| 4479 |
// Walks though the explicit resource binding attributes on the declaration, |
| 4480 |
// and makes sure there is a resource that matched the binding and updates |
| 4481 |
// DeclBindingInfoLists |
| 4482 |
void SemaHLSL::processExplicitBindingsOnDecl(VarDecl *VD) { |
| 4483 |
assert(VD->hasGlobalStorage() && "expected global variable"); |
| 4484 |
|
| 4485 |
bool HasBinding = false; |
| 4486 |
for (Attr *A : VD->attrs()) { |
| 4487 |
if (isa<HLSLVkBindingAttr>(A)) { |
| 4488 |
HasBinding = true; |
| 4489 |
if (auto PA = VD->getAttr<HLSLVkPushConstantAttr>()) |
| 4490 |
Diag(PA->getLoc(), diag::err_hlsl_attr_incompatible) << A << PA; |
| 4491 |
} |
| 4492 |
|
| 4493 |
HLSLResourceBindingAttr *RBA = dyn_cast<HLSLResourceBindingAttr>(A); |
| 4494 |
if (!RBA || !RBA->hasRegisterSlot()) |
| 4495 |
continue; |
| 4496 |
HasBinding = true; |
| 4497 |
|
| 4498 |
RegisterType RT = RBA->getRegisterType(); |
| 4499 |
assert(RT != RegisterType::I && "invalid or obsolete register type should " |
| 4500 |
"never have an attribute created"); |
| 4501 |
|
| 4502 |
if (RT == RegisterType::C) { |
| 4503 |
if (Bindings.hasBindingInfoForDecl(VD)) |
| 4504 |
SemaRef.Diag(VD->getLocation(), |
| 4505 |
diag::warn_hlsl_user_defined_type_missing_member) |
| 4506 |
<< static_cast<int>(RT); |
| 4507 |
continue; |
| 4508 |
} |
| 4509 |
|
| 4510 |
// Find DeclBindingInfo for this binding and update it, or report error |
| 4511 |
// if it does not exist (user type does to contain resources with the |
| 4512 |
// expected resource class). |
| 4513 |
ResourceClass RC = getResourceClass(RT); |
| 4514 |
if (DeclBindingInfo *BI = Bindings.getDeclBindingInfo(VD, RC)) { |
| 4515 |
// update binding info |
| 4516 |
BI->setBindingAttribute(RBA, BindingType::Explicit); |
| 4517 |
} else { |
| 4518 |
SemaRef.Diag(VD->getLocation(), |
| 4519 |
diag::warn_hlsl_user_defined_type_missing_member) |
| 4520 |
<< static_cast<int>(RT); |
| 4521 |
} |
| 4522 |
} |
| 4523 |
|
| 4524 |
if (!HasBinding && isResourceRecordTypeOrArrayOf(VD)) |
| 4525 |
SemaRef.Diag(VD->getLocation(), diag::warn_hlsl_implicit_binding); |
| 4526 |
} |
| 4527 |
namespace { |
| 4528 |
class InitListTransformer { |
| 4529 |
Sema &S; |
| 4530 |
ASTContext &Ctx; |
| 4531 |
QualType InitTy; |
| 4532 |
QualType *DstIt = nullptr; |
| 4533 |
Expr **ArgIt = nullptr; |
| 4534 |
// Is wrapping the destination type iterator required? This is only used for |
| 4535 |
// incomplete array types where we loop over the destination type since we |
| 4536 |
// don't know the full number of elements from the declaration. |
| 4537 |
bool Wrap; |
| 4538 |
|
| 4539 |
bool castInitializer(Expr *E) { |
| 4540 |
assert(DstIt && "This should always be something!"); |
| 4541 |
if (DstIt == DestTypes.end()) { |
| 4542 |
if (!Wrap) { |
| 4543 |
ArgExprs.push_back(E); |
| 4544 |
// This is odd, but it isn't technically a failure due to conversion, we |
| 4545 |
// handle mismatched counts of arguments differently. |
| 4546 |
return true; |
| 4547 |
} |
| 4548 |
DstIt = DestTypes.begin(); |
| 4549 |
} |
| 4550 |
InitializedEntity Entity = InitializedEntity::InitializeParameter( |
| 4551 |
Ctx, *DstIt, /* Consumed (ObjC) */ false); |
| 4552 |
ExprResult Res = S.PerformCopyInitialization(Entity, E->getBeginLoc(), E); |
| 4553 |
if (Res.isInvalid()) |
| 4554 |
return false; |
| 4555 |
Expr *Init = Res.get(); |
| 4556 |
ArgExprs.push_back(Init); |
| 4557 |
DstIt++; |
| 4558 |
return true; |
| 4559 |
} |
| 4560 |
|
| 4561 |
bool buildInitializerListImpl(Expr *E) { |
| 4562 |
// If this is an initialization list, traverse the sub initializers. |
| 4563 |
if (auto *Init = dyn_cast<InitListExpr>(E)) { |
| 4564 |
for (auto *SubInit : Init->inits()) |
| 4565 |
if (!buildInitializerListImpl(SubInit)) |
| 4566 |
return false; |
| 4567 |
return true; |
| 4568 |
} |
| 4569 |
|
| 4570 |
// If this is a scalar type, just enqueue the expression. |
| 4571 |
QualType Ty = E->getType(); |
| 4572 |
|
| 4573 |
if (Ty->isScalarType() || (Ty->isRecordType() && !Ty->isAggregateType())) |
| 4574 |
return castInitializer(E); |
| 4575 |
|
| 4576 |
if (auto *VecTy = Ty->getAs<VectorType>()) { |
| 4577 |
uint64_t Size = VecTy->getNumElements(); |
| 4578 |
|
| 4579 |
QualType SizeTy = Ctx.getSizeType(); |
| 4580 |
uint64_t SizeTySize = Ctx.getTypeSize(SizeTy); |
| 4581 |
for (uint64_t I = 0; I < Size; ++I) { |
| 4582 |
auto *Idx = IntegerLiteral::Create(Ctx, llvm::APInt(SizeTySize, I), |
| 4583 |
SizeTy, SourceLocation()); |
| 4584 |
|
| 4585 |
ExprResult ElExpr = S.CreateBuiltinArraySubscriptExpr( |
| 4586 |
E, E->getBeginLoc(), Idx, E->getEndLoc()); |
| 4587 |
if (ElExpr.isInvalid()) |
| 4588 |
return false; |
| 4589 |
if (!castInitializer(ElExpr.get())) |
| 4590 |
return false; |
| 4591 |
} |
| 4592 |
return true; |
| 4593 |
} |
| 4594 |
if (auto *MTy = Ty->getAs<ConstantMatrixType>()) { |
| 4595 |
unsigned Rows = MTy->getNumRows(); |
| 4596 |
unsigned Cols = MTy->getNumColumns(); |
| 4597 |
QualType ElemTy = MTy->getElementType(); |
| 4598 |
|
| 4599 |
for (unsigned C = 0; C < Cols; ++C) { |
| 4600 |
for (unsigned R = 0; R < Rows; ++R) { |
| 4601 |
// row index literal |
| 4602 |
Expr *RowIdx = IntegerLiteral::Create( |
| 4603 |
Ctx, llvm::APInt(Ctx.getIntWidth(Ctx.IntTy), R), Ctx.IntTy, |
| 4604 |
E->getBeginLoc()); |
| 4605 |
// column index literal |
| 4606 |
Expr *ColIdx = IntegerLiteral::Create( |
| 4607 |
Ctx, llvm::APInt(Ctx.getIntWidth(Ctx.IntTy), C), Ctx.IntTy, |
| 4608 |
E->getBeginLoc()); |
| 4609 |
ExprResult ElExpr = S.CreateBuiltinMatrixSubscriptExpr( |
| 4610 |
E, RowIdx, ColIdx, E->getEndLoc()); |
| 4611 |
if (ElExpr.isInvalid()) |
| 4612 |
return false; |
| 4613 |
if (!castInitializer(ElExpr.get())) |
| 4614 |
return false; |
| 4615 |
ElExpr.get()->setType(ElemTy); |
| 4616 |
} |
| 4617 |
} |
| 4618 |
return true; |
| 4619 |
} |
| 4620 |
|
| 4621 |
if (auto *ArrTy = dyn_cast<ConstantArrayType>(Ty.getTypePtr())) { |
| 4622 |
uint64_t Size = ArrTy->getZExtSize(); |
| 4623 |
QualType SizeTy = Ctx.getSizeType(); |
| 4624 |
uint64_t SizeTySize = Ctx.getTypeSize(SizeTy); |
| 4625 |
for (uint64_t I = 0; I < Size; ++I) { |
| 4626 |
auto *Idx = IntegerLiteral::Create(Ctx, llvm::APInt(SizeTySize, I), |
| 4627 |
SizeTy, SourceLocation()); |
| 4628 |
ExprResult ElExpr = S.CreateBuiltinArraySubscriptExpr( |
| 4629 |
E, E->getBeginLoc(), Idx, E->getEndLoc()); |
| 4630 |
if (ElExpr.isInvalid()) |
| 4631 |
return false; |
| 4632 |
if (!buildInitializerListImpl(ElExpr.get())) |
| 4633 |
return false; |
| 4634 |
} |
| 4635 |
return true; |
| 4636 |
} |
| 4637 |
|
| 4638 |
if (auto *RD = Ty->getAsCXXRecordDecl()) { |
| 4639 |
llvm::SmallVector<CXXRecordDecl *> RecordDecls; |
| 4640 |
RecordDecls.push_back(RD); |
| 4641 |
while (RecordDecls.back()->getNumBases()) { |
| 4642 |
CXXRecordDecl *D = RecordDecls.back(); |
| 4643 |
assert(D->getNumBases() == 1 && |
| 4644 |
"HLSL doesn't support multiple inheritance"); |
| 4645 |
RecordDecls.push_back( |
| 4646 |
D->bases_begin()->getType()->castAsCXXRecordDecl()); |
| 4647 |
} |
| 4648 |
while (!RecordDecls.empty()) { |
| 4649 |
CXXRecordDecl *RD = RecordDecls.pop_back_val(); |
| 4650 |
for (auto *FD : RD->fields()) { |
| 4651 |
if (FD->isUnnamedBitField()) |
| 4652 |
continue; |
| 4653 |
DeclAccessPair Found = DeclAccessPair::make(FD, FD->getAccess()); |
| 4654 |
DeclarationNameInfo NameInfo(FD->getDeclName(), E->getBeginLoc()); |
| 4655 |
ExprResult Res = S.BuildFieldReferenceExpr( |
| 4656 |
E, false, E->getBeginLoc(), CXXScopeSpec(), FD, Found, NameInfo); |
| 4657 |
if (Res.isInvalid()) |
| 4658 |
return false; |
| 4659 |
if (!buildInitializerListImpl(Res.get())) |
| 4660 |
return false; |
| 4661 |
} |
| 4662 |
} |
| 4663 |
} |
| 4664 |
return true; |
| 4665 |
} |
| 4666 |
|
| 4667 |
Expr *generateInitListsImpl(QualType Ty) { |
| 4668 |
assert(ArgIt != ArgExprs.end() && "Something is off in iteration!"); |
| 4669 |
if (Ty->isScalarType() || (Ty->isRecordType() && !Ty->isAggregateType())) |
| 4670 |
return *(ArgIt++); |
| 4671 |
|
| 4672 |
llvm::SmallVector<Expr *> Inits; |
| 4673 |
Ty = Ty.getDesugaredType(Ctx); |
| 4674 |
if (Ty->isVectorType() || Ty->isConstantArrayType() || |
| 4675 |
Ty->isConstantMatrixType()) { |
| 4676 |
QualType ElTy; |
| 4677 |
uint64_t Size = 0; |
| 4678 |
if (auto *ATy = Ty->getAs<VectorType>()) { |
| 4679 |
ElTy = ATy->getElementType(); |
| 4680 |
Size = ATy->getNumElements(); |
| 4681 |
} else if (auto *CMTy = Ty->getAs<ConstantMatrixType>()) { |
| 4682 |
ElTy = CMTy->getElementType(); |
| 4683 |
Size = CMTy->getNumElementsFlattened(); |
| 4684 |
} else { |
| 4685 |
auto *VTy = cast<ConstantArrayType>(Ty.getTypePtr()); |
| 4686 |
ElTy = VTy->getElementType(); |
| 4687 |
Size = VTy->getZExtSize(); |
| 4688 |
} |
| 4689 |
for (uint64_t I = 0; I < Size; ++I) |
| 4690 |
Inits.push_back(generateInitListsImpl(ElTy)); |
| 4691 |
} |
| 4692 |
if (auto *RD = Ty->getAsCXXRecordDecl()) { |
| 4693 |
llvm::SmallVector<CXXRecordDecl *> RecordDecls; |
| 4694 |
RecordDecls.push_back(RD); |
| 4695 |
while (RecordDecls.back()->getNumBases()) { |
| 4696 |
CXXRecordDecl *D = RecordDecls.back(); |
| 4697 |
assert(D->getNumBases() == 1 && |
| 4698 |
"HLSL doesn't support multiple inheritance"); |
| 4699 |
RecordDecls.push_back( |
| 4700 |
D->bases_begin()->getType()->castAsCXXRecordDecl()); |
| 4701 |
} |
| 4702 |
while (!RecordDecls.empty()) { |
| 4703 |
CXXRecordDecl *RD = RecordDecls.pop_back_val(); |
| 4704 |
for (auto *FD : RD->fields()) |
| 4705 |
if (!FD->isUnnamedBitField()) |
| 4706 |
Inits.push_back(generateInitListsImpl(FD->getType())); |
| 4707 |
} |
| 4708 |
} |
| 4709 |
auto *NewInit = new (Ctx) InitListExpr(Ctx, Inits.front()->getBeginLoc(), |
| 4710 |
Inits, Inits.back()->getEndLoc()); |
| 4711 |
NewInit->setType(Ty); |
| 4712 |
return NewInit; |
| 4713 |
} |
| 4714 |
|
| 4715 |
public: |
| 4716 |
llvm::SmallVector<QualType, 16> DestTypes; |
| 4717 |
llvm::SmallVector<Expr *, 16> ArgExprs; |
| 4718 |
InitListTransformer(Sema &SemaRef, const InitializedEntity &Entity) |
| 4719 |
: S(SemaRef), Ctx(SemaRef.getASTContext()), |
| 4720 |
Wrap(Entity.getType()->isIncompleteArrayType()) { |
| 4721 |
InitTy = Entity.getType().getNonReferenceType(); |
| 4722 |
// When we're generating initializer lists for incomplete array types we |
| 4723 |
// need to wrap around both when building the initializers and when |
| 4724 |
// generating the final initializer lists. |
| 4725 |
if (Wrap) { |
| 4726 |
assert(InitTy->isIncompleteArrayType()); |
| 4727 |
const IncompleteArrayType *IAT = Ctx.getAsIncompleteArrayType(InitTy); |
| 4728 |
InitTy = IAT->getElementType(); |
| 4729 |
} |
| 4730 |
BuildFlattenedTypeList(InitTy, DestTypes); |
| 4731 |
DstIt = DestTypes.begin(); |
| 4732 |
} |
| 4733 |
|
| 4734 |
bool buildInitializerList(Expr *E) { return buildInitializerListImpl(E); } |
| 4735 |
|
| 4736 |
Expr *generateInitLists() { |
| 4737 |
assert(!ArgExprs.empty() && |
| 4738 |
"Call buildInitializerList to generate argument expressions."); |
| 4739 |
ArgIt = ArgExprs.begin(); |
| 4740 |
if (!Wrap) |
| 4741 |
return generateInitListsImpl(InitTy); |
| 4742 |
llvm::SmallVector<Expr *> Inits; |
| 4743 |
while (ArgIt != ArgExprs.end()) |
| 4744 |
Inits.push_back(generateInitListsImpl(InitTy)); |
| 4745 |
|
| 4746 |
auto *NewInit = new (Ctx) InitListExpr(Ctx, Inits.front()->getBeginLoc(), |
| 4747 |
Inits, Inits.back()->getEndLoc()); |
| 4748 |
llvm::APInt ArySize(64, Inits.size()); |
| 4749 |
NewInit->setType(Ctx.getConstantArrayType(InitTy, ArySize, nullptr, |
| 4750 |
ArraySizeModifier::Normal, 0)); |
| 4751 |
return NewInit; |
| 4752 |
} |
| 4753 |
}; |
| 4754 |
} // namespace |
| 4755 |
|
| 4756 |
bool SemaHLSL::transformInitList(const InitializedEntity &Entity, |
| 4757 |
InitListExpr *Init) { |
| 4758 |
// If the initializer is a scalar, just return it. |
| 4759 |
if (Init->getType()->isScalarType()) |
| 4760 |
return true; |
| 4761 |
ASTContext &Ctx = SemaRef.getASTContext(); |
| 4762 |
InitListTransformer ILT(SemaRef, Entity); |
| 4763 |
|
| 4764 |
for (unsigned I = 0; I < Init->getNumInits(); ++I) { |
| 4765 |
Expr *E = Init->getInit(I); |
| 4766 |
if (E->HasSideEffects(Ctx)) { |
| 4767 |
QualType Ty = E->getType(); |
| 4768 |
if (Ty->isRecordType()) |
| 4769 |
E = new (Ctx) MaterializeTemporaryExpr(Ty, E, E->isLValue()); |
| 4770 |
E = new (Ctx) OpaqueValueExpr(E->getBeginLoc(), Ty, E->getValueKind(), |
| 4771 |
E->getObjectKind(), E); |
| 4772 |
Init->setInit(I, E); |
| 4773 |
} |
| 4774 |
if (!ILT.buildInitializerList(E)) |
| 4775 |
return false; |
| 4776 |
} |
| 4777 |
size_t ExpectedSize = ILT.DestTypes.size(); |
| 4778 |
size_t ActualSize = ILT.ArgExprs.size(); |
| 4779 |
if (ExpectedSize == 0 && ActualSize == 0) |
| 4780 |
return true; |
| 4781 |
|
| 4782 |
// For incomplete arrays it is completely arbitrary to choose whether we think |
| 4783 |
// the user intended fewer or more elements. This implementation assumes that |
| 4784 |
// the user intended more, and errors that there are too few initializers to |
| 4785 |
// complete the final element. |
| 4786 |
if (Entity.getType()->isIncompleteArrayType()) { |
| 4787 |
assert(ExpectedSize > 0 && |
| 4788 |
"The expected size of an incomplete array type must be at least 1."); |
| 4789 |
ExpectedSize = |
| 4790 |
((ActualSize + ExpectedSize - 1) / ExpectedSize) * ExpectedSize; |
| 4791 |
} |
| 4792 |
|
| 4793 |
// An initializer list might be attempting to initialize a reference or |
| 4794 |
// rvalue-reference. When checking the initializer we should look through |
| 4795 |
// the reference. |
| 4796 |
QualType InitTy = Entity.getType().getNonReferenceType(); |
| 4797 |
if (InitTy.hasAddressSpace()) |
| 4798 |
InitTy = SemaRef.getASTContext().removeAddrSpaceQualType(InitTy); |
| 4799 |
if (ExpectedSize != ActualSize) { |
| 4800 |
int TooManyOrFew = ActualSize > ExpectedSize ? 1 : 0; |
| 4801 |
SemaRef.Diag(Init->getBeginLoc(), diag::err_hlsl_incorrect_num_initializers) |
| 4802 |
<< TooManyOrFew << InitTy << ExpectedSize << ActualSize; |
| 4803 |
return false; |
| 4804 |
} |
| 4805 |
|
| 4806 |
// generateInitListsImpl will always return an InitListExpr here, because the |
| 4807 |
// scalar case is handled above. |
| 4808 |
auto *NewInit = cast<InitListExpr>(ILT.generateInitLists()); |
| 4809 |
Init->resizeInits(Ctx, NewInit->getNumInits()); |
| 4810 |
for (unsigned I = 0; I < NewInit->getNumInits(); ++I) |
| 4811 |
Init->updateInit(Ctx, I, NewInit->getInit(I)); |
| 4812 |
return true; |
| 4813 |
} |
| 4814 |
|
| 4815 |
bool SemaHLSL::handleInitialization(VarDecl *VDecl, Expr *&Init) { |
| 4816 |
const HLSLVkConstantIdAttr *ConstIdAttr = |
| 4817 |
VDecl->getAttr<HLSLVkConstantIdAttr>(); |
| 4818 |
if (!ConstIdAttr) |
| 4819 |
return true; |
| 4820 |
|
| 4821 |
ASTContext &Context = SemaRef.getASTContext(); |
| 4822 |
|
| 4823 |
APValue InitValue; |
| 4824 |
if (!Init->isCXX11ConstantExpr(Context, &InitValue)) { |
| 4825 |
Diag(VDecl->getLocation(), diag::err_specialization_const); |
| 4826 |
VDecl->setInvalidDecl(); |
| 4827 |
return false; |
| 4828 |
} |
| 4829 |
|
| 4830 |
Builtin::ID BID = |
| 4831 |
getSpecConstBuiltinId(VDecl->getType()->getUnqualifiedDesugaredType()); |
| 4832 |
|
| 4833 |
// Argument 1: The ID from the attribute |
| 4834 |
int ConstantID = ConstIdAttr->getId(); |
| 4835 |
llvm::APInt IDVal(Context.getIntWidth(Context.IntTy), ConstantID); |
| 4836 |
Expr *IdExpr = IntegerLiteral::Create(Context, IDVal, Context.IntTy, |
| 4837 |
ConstIdAttr->getLocation()); |
| 4838 |
|
| 4839 |
SmallVector<Expr *, 2> Args = {IdExpr, Init}; |
| 4840 |
Expr *C = SemaRef.BuildBuiltinCallExpr(Init->getExprLoc(), BID, Args); |
| 4841 |
if (C->getType()->getCanonicalTypeUnqualified() != |
| 4842 |
VDecl->getType()->getCanonicalTypeUnqualified()) { |
| 4843 |
C = SemaRef |
| 4844 |
.BuildCStyleCastExpr(SourceLocation(), |
| 4845 |
Context.getTrivialTypeSourceInfo( |
| 4846 |
Init->getType(), Init->getExprLoc()), |
| 4847 |
SourceLocation(), C) |
| 4848 |
.get(); |
| 4849 |
} |
| 4850 |
Init = C; |
| 4851 |
return true; |
| 4852 |
} |