clang 24.0.0git
SemaHLSL.h
Go to the documentation of this file.
1//===----- SemaHLSL.h ----- 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/// \file
9/// This file declares semantic analysis for HLSL constructs.
10///
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_SEMA_SEMAHLSL_H
14#define LLVM_CLANG_SEMA_SEMAHLSL_H
15
16#include "clang/AST/ASTFwd.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/Type.h"
19#include "clang/AST/TypeLoc.h"
22#include "clang/Sema/SemaBase.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringMap.h"
27#include "llvm/Frontend/HLSL/SemanticSignatures.h"
28#include "llvm/TargetParser/Triple.h"
29#include <initializer_list>
30
31namespace clang {
33class IdentifierInfo;
36class ParsedAttr;
37class Scope;
38class VarDecl;
39
40namespace hlsl {
41
42// Introduce a wrapper struct around the underlying RootElement. This structure
43// will retain extra clang diagnostic information that is not available in llvm.
46 llvm::hlsl::rootsig::RootElement Element)
47 : Loc(Loc), Element(Element) {}
48
49 const llvm::hlsl::rootsig::RootElement &getElement() const { return Element; }
50 const SourceLocation &getLocation() const { return Loc; }
51
52private:
54 llvm::hlsl::rootsig::RootElement Element;
55};
56
57} // namespace hlsl
58
59using llvm::dxil::ResourceClass;
60
61// FIXME: This can be hidden (as static function in SemaHLSL.cpp) once we no
62// longer need to create builtin buffer types in HLSLExternalSemaSource.
64 Sema &S, QualType Wrapped, ArrayRef<const Attr *> AttrList,
65 QualType &ResType, HLSLAttributedResourceLocInfo *LocInfo = nullptr,
66 Expr *SampleCountExpr = nullptr);
67
69
70// DeclBindingInfo struct stores information about required/assigned resource
71// binding onon a declaration for specific resource class.
73 const VarDecl *Decl;
75 const HLSLResourceBindingAttr *Attr;
77
82
83 void setBindingAttribute(HLSLResourceBindingAttr *A, BindingType BT) {
84 assert(Attr == nullptr && BindType == BindingType::NotAssigned &&
85 "binding attribute already assigned");
86 Attr = A;
87 BindType = BT;
88 }
89};
90
91// ResourceBindings class stores information about all resource bindings
92// in a shader. It is used for binding diagnostics and implicit binding
93// assignments.
95public:
97 ResourceClass ResClass);
99 ResourceClass ResClass);
100 bool hasBindingInfoForDecl(const VarDecl *VD) const;
101
102private:
103 // List of all resource bindings required by the shader.
104 // A global declaration can have multiple bindings for different
105 // resource classes. They are all stored sequentially in this list.
106 // The DeclToBindingListIndex hashtable maps a declaration to the
107 // index of the first binding info in the list.
109 llvm::DenseMap<const VarDecl *, unsigned> DeclToBindingListIndex;
110};
111
112class SemaHLSL : public SemaBase {
113public:
114 SemaHLSL(Sema &S);
115
116 Decl *ActOnStartBuffer(Scope *BufferScope, bool CBuffer, SourceLocation KwLoc,
117 IdentifierInfo *Ident, SourceLocation IdentLoc,
118 SourceLocation LBrace);
119 void ActOnFinishBuffer(Decl *Dcl, SourceLocation RBrace);
120 HLSLNumThreadsAttr *mergeNumThreadsAttr(Decl *D,
121 const AttributeCommonInfo &AL, int X,
122 int Y, int Z);
123 HLSLWaveSizeAttr *mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL,
124 int Min, int Max, int Preferred,
125 int SpelledArgsCount);
126 HLSLVkConstantIdAttr *
127 mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id);
128 HLSLShaderAttr *mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL,
129 llvm::Triple::EnvironmentType ShaderType);
130 HLSLParamModifierAttr *
132 HLSLParamModifierAttr::Spelling Spelling);
139
140 // Return true if everything is ok; returns false if there was an error.
141 bool CheckResourceBinOp(BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr,
142 SourceLocation Loc);
143
145
147 QualType LHSType, QualType RHSType,
148 bool IsCompAssign);
150
151 // Returns the result of converting ConstantBuffer<T> to
152 // `const hlsl_constant T&`. If `BaseExpr`'s type is not ConstantBuffer<T>
153 // then the return value is `std::nullopt`.
154 std::optional<ExprResult> tryPerformConstantBufferConversion(Expr *BaseExpr);
155
156 // Returns the conversion operator to convert `RD` to `const hlsl_constant
157 // Type&`. Returns `nullptr` if it could not be found.
159 CXXRecordDecl *RD);
160
161 /// Computes the unique Root Signature identifier from the given signature,
162 /// then lookup if there is a previousy created Root Signature decl.
163 ///
164 /// Returns the identifier and if it was found
165 std::pair<IdentifierInfo *, bool>
166 ActOnStartRootSignatureDecl(StringRef Signature);
167
168 /// Creates the Root Signature decl of the parsed Root Signature elements
169 /// onto the AST and push it onto current Scope
170 void
173
175 RootSigOverrideIdent = DeclIdent;
176 }
177
179
180 // Returns true if any RootSignatureElement is invalid and a diagnostic was
181 // produced
182 bool
184 void handleRootSignatureAttr(Decl *D, const ParsedAttr &AL);
185 void handleNumThreadsAttr(Decl *D, const ParsedAttr &AL);
186 void handleWaveSizeAttr(Decl *D, const ParsedAttr &AL);
187 void handleVkConstantIdAttr(Decl *D, const ParsedAttr &AL);
188 void handleVkBindingAttr(Decl *D, const ParsedAttr &AL);
189 void handleVkLocationAttr(Decl *D, const ParsedAttr &AL);
190 void handlePackOffsetAttr(Decl *D, const ParsedAttr &AL);
191 void handleShaderAttr(Decl *D, const ParsedAttr &AL);
192 void handleResourceBindingAttr(Decl *D, const ParsedAttr &AL);
193 void handleParamModifierAttr(Decl *D, const ParsedAttr &AL);
197 SourceLocation Loc);
198 // Re-type a layout-adapting matrix builtin call \p E with \p DestType's
199 // row_major/column_major sugar so CodeGen lowers it into that layout.
201
202 void handleSemanticAttr(Decl *D, const ParsedAttr &AL);
203
204 void handleVkExtBuiltinInputAttr(Decl *D, const ParsedAttr &AL);
205 void handleVkExtBuiltinOutputAttr(Decl *D, const ParsedAttr &AL);
206 void handleVkPushConstantAttr(Decl *D, const ParsedAttr &AL);
207
208 bool CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
211 TakeLocForHLSLAttribute(const HLSLAttributedResourceType *RT);
212
213 // HLSL Type trait implementations
217
219
221 SourceLocation NameLoc);
222
223 bool CanPerformScalarCast(QualType SrcTy, QualType DestTy);
224 bool CanPerformElementwiseCast(Expr *Src, QualType DestType);
225 bool CanPerformAggregateSplatCast(Expr *Src, QualType DestType);
226 bool CanPerformPackedTypeCast(Expr *Src, QualType DestTy);
228
230
232 bool handleInitialization(VarDecl *VDecl, Expr *&Init);
235 SourceLocation OpLoc,
236 const IdentifierInfo *CompName,
237 SourceLocation CompLoc);
238
240 return ImplicitBindingNextOrderID++;
241 }
242
245
246private:
247 // HLSL resource type attributes need to be processed all at once.
248 // This is a list to collect them.
249 llvm::SmallVector<const Attr *> HLSLResourcesTypeAttrs;
250
251 /// TypeLoc data for HLSLAttributedResourceType instances that we
252 /// have not yet populated.
253 llvm::DenseMap<const HLSLAttributedResourceType *,
255 LocsForHLSLAttributedResources;
256
257 // List of all resource bindings
259
260 // Map of local resource variables to their assigned global resources.
261 //
262 // The binding can be a nullptr, in which case, the variable has yet to be
263 // initialized or assigned to.
264 llvm::DenseMap<const VarDecl *, const DeclBindingInfo *> Assigns;
265
266 // Global declaration collected for the $Globals default constant
267 // buffer which will be created at the end of the translation unit.
268 llvm::SmallVector<Decl *> DefaultCBufferDecls;
269
270 uint32_t ImplicitBindingNextOrderID = 0;
271
272 IdentifierInfo *RootSigOverrideIdent = nullptr;
273
274 bool HasDeclaredAPushConstant = false;
275
276 // Information about the current subtree being flattened.
277 struct SemanticInfo {
278 HLSLParsedSemanticAttr *Semantic;
279 std::optional<uint32_t> Index = std::nullopt;
280 };
281
282 // The context shared by all semantics with the same IOType during
283 // flattening.
284 struct SemanticContext {
285 // Present if any semantic sharing the same IO type has an explicit or
286 // implicit SPIR-V location index assigned.
287 std::optional<bool> UsesExplicitVkLocations = std::nullopt;
288 // Lowercased semantic names with indices, mapped to their first use for
289 // overlap diagnostics.
290 llvm::StringMap<SourceLocation> ActiveSemantics = {};
291 // The IOType of this semantic set.
292 llvm::hlsl::IOType CurrentIOType;
293 };
294
295private:
296 bool
297 checkInterpolationModifiers(const DeclaratorDecl *D,
298 const HLSLInterpolationModifierAttr *Inherited,
299 const HLSLParsedSemanticAttr *Semantic);
300
301 void collectResourceBindingsOnVarDecl(VarDecl *D);
302 void collectResourceBindingsOnUserRecordDecl(const VarDecl *VD,
303 const RecordType *RT);
304
305 void checkSemanticAnnotation(FunctionDecl *EntryPoint, const Decl *Param,
306 const HLSLAppliedSemanticAttr *SemanticAttr,
307 const SemanticContext &SC,
308 unsigned ElementCount);
309
310 bool determineActiveSemanticOnScalar(FunctionDecl *FD,
311 DeclaratorDecl *OutputDecl,
312 DeclaratorDecl *D,
313 SemanticInfo &ActiveSemantic,
314 SemanticContext &SC);
315
316 bool determineActiveSemantic(FunctionDecl *FD, DeclaratorDecl *OutputDecl,
317 DeclaratorDecl *D, SemanticInfo &ActiveSemantic,
318 SemanticContext &SC);
319
320 void processExplicitBindingsOnDecl(VarDecl *D);
321
322 void diagnoseAvailabilityViolations(TranslationUnitDecl *TU);
323
324 void diagnoseAttrStageMismatch(
325 const Attr *A, llvm::Triple::EnvironmentType Stage,
326 std::initializer_list<llvm::Triple::EnvironmentType> AllowedStages);
327
328 void
329 diagnoseSemanticStageMismatch(const Attr *A,
330 llvm::Triple::EnvironmentType Stage,
331 llvm::hlsl::IOType CurrentIOType,
332 llvm::dxbc::PSV::SemanticKind SemanticKind);
333
334 // Check ElementCount consecutive indices for a system-value interpretation.
335 void diagnoseSystemSemanticIndex(const HLSLAppliedSemanticAttr *A,
336 llvm::dxbc::PSV::SemanticKind SemanticKind,
337 unsigned ElementCount);
338
339 void diagnoseSemanticType(const Decl *D, const HLSLAppliedSemanticAttr *A,
340 llvm::dxbc::PSV::SemanticKind SemanticKind);
341
342 void handleGlobalStructOrArrayOfWithResources(VarDecl *VD);
343
344 // Infer a common global binding info for an Expr
345 //
346 // Returns std::nullopt if the expr refers to non-unique global bindings.
347 // Returns nullptr if it refer to any global binding, otherwise it returns
348 // a reference to the global binding info.
349 std::optional<const DeclBindingInfo *> inferGlobalBinding(Expr *E);
350
351 void trackLocalResource(VarDecl *VDecl, Expr *E);
352};
353
354} // namespace clang
355
356#endif // LLVM_CLANG_SEMA_SEMAHLSL_H
Forward declaration of all AST node types.
llvm::dxil::ResourceClass ResourceClass
#define X(type, name)
Definition Value.h:97
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
llvm::dxbc::PSV::SemanticKind SemanticKind
Definition SemaHLSL.cpp:61
Defines the clang::SourceLocation class and associated facilities.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
Attr - This represents one attribute.
Definition Attr.h:46
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2991
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This represents one expression.
Definition Expr.h:113
Represents a function declaration or definition.
Definition Decl.h:2059
One of these records is kept for each identifier that is lexed.
Describes an C or C++ initializer list.
Definition Expr.h:5356
Describes the kind of initialization being performed, along with location information for tokens rela...
Describes an entity that is being initialized.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3412
This represents a decl that may have a name.
Definition Decl.h:275
Represents a parameter to a function.
Definition Decl.h:1820
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
A (possibly-)qualified type.
Definition TypeBase.h:938
bool hasBindingInfoForDecl(const VarDecl *VD) const
Definition SemaHLSL.cpp:246
DeclBindingInfo * getDeclBindingInfo(const VarDecl *VD, ResourceClass ResClass)
Definition SemaHLSL.cpp:232
DeclBindingInfo * addDeclBindingInfo(const VarDecl *VD, ResourceClass ResClass)
Definition SemaHLSL.cpp:219
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
SemaBase(Sema &S)
Definition SemaBase.cpp:7
ExprResult ActOnOutParamExpr(ParmVarDecl *Param, Expr *Arg)
HLSLRootSignatureDecl * lookupRootSignatureOverrideDecl(DeclContext *DC) const
bool CanPerformElementwiseCast(Expr *Src, QualType DestType)
void handleWaveSizeAttr(Decl *D, const ParsedAttr &AL)
void handleVkLocationAttr(Decl *D, const ParsedAttr &AL)
HLSLAttributedResourceLocInfo TakeLocForHLSLAttribute(const HLSLAttributedResourceType *RT)
void handleSemanticAttr(Decl *D, const ParsedAttr &AL)
bool CanPerformScalarCast(QualType SrcTy, QualType DestTy)
QualType ProcessResourceTypeAttributes(QualType Wrapped)
void handleInterpolationModifierAttr(Decl *D, const ParsedAttr &AL)
Definition SemaHLSL.cpp:830
void handleShaderAttr(Decl *D, const ParsedAttr &AL)
uint32_t getNextImplicitBindingOrderID()
Definition SemaHLSL.h:239
void CheckEntryPoint(FunctionDecl *FD)
void handleVkExtBuiltinOutputAttr(Decl *D, const ParsedAttr &AL)
void emitLogicalOperatorFixIt(Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
bool initGlobalResourceDecl(VarDecl *VD)
void ActOnEndOfTranslationUnit(TranslationUnitDecl *TU)
bool initGlobalResourceArrayDecl(VarDecl *VD)
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition SemaHLSL.cpp:761
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition SemaHLSL.cpp:727
void deduceAddressSpace(VarDecl *Decl)
std::pair< IdentifierInfo *, bool > ActOnStartRootSignatureDecl(StringRef Signature)
Computes the unique Root Signature identifier from the given signature, then lookup if there is a pre...
void handlePackOffsetAttr(Decl *D, const ParsedAttr &AL)
Attr * buildMatrixLayoutTypeAttr(QualType T, const ParsedAttr &AL)
bool handleInitialization(VarDecl *VDecl, Expr *&Init)
void handleParamModifierAttr(Decl *D, const ParsedAttr &AL)
bool CheckResourceBinOp(BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc)
bool CanPerformAggregateSplatCast(Expr *Src, QualType DestType)
bool ActOnResourceMemberAccessExpr(MemberExpr *ME)
bool IsScalarizedLayoutCompatible(QualType T1, QualType T2) const
QualType ActOnTemplateShorthand(TemplateDecl *Template, SourceLocation NameLoc)
void handleRootSignatureAttr(Decl *D, const ParsedAttr &AL)
bool CheckCompatibleParameterABI(FunctionDecl *New, FunctionDecl *Old)
QualType handleVectorBinOpConversion(ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
QualType checkMatrixComponent(Sema &S, QualType baseType, ExprValueKind &VK, SourceLocation OpLoc, const IdentifierInfo *CompName, SourceLocation CompLoc)
bool IsConstantBufferElementCompatible(QualType T1)
void handleResourceBindingAttr(Decl *D, const ParsedAttr &AL)
bool IsTypedResourceElementCompatible(QualType T1)
void SetRootSignatureOverride(IdentifierInfo *DeclIdent)
Definition SemaHLSL.h:174
bool transformInitList(const InitializedEntity &Entity, InitListExpr *Init)
void handleNumThreadsAttr(Decl *D, const ParsedAttr &AL)
bool ActOnUninitializedVarDecl(VarDecl *D)
void handleVkExtBuiltinInputAttr(Decl *D, const ParsedAttr &AL)
bool canHaveOverloadedBinOp(QualType Ty, BinaryOperatorKind Opc)
void ActOnTopLevelFunction(FunctionDecl *FD)
Definition SemaHLSL.cpp:937
bool handleResourceTypeAttr(QualType T, const ParsedAttr &AL)
void handleVkPushConstantAttr(Decl *D, const ParsedAttr &AL)
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition SemaHLSL.cpp:797
NamedDecl * getConstantBufferConversionFunction(QualType Type, CXXRecordDecl *RD)
void ActOnFinishBuffer(Decl *Dcl, SourceLocation RBrace)
Definition SemaHLSL.cpp:700
void handleVkBindingAttr(Decl *D, const ParsedAttr &AL)
HLSLParamModifierAttr * mergeParamModifierAttr(Decl *D, const AttributeCommonInfo &AL, HLSLParamModifierAttr::Spelling Spelling)
Definition SemaHLSL.cpp:810
QualType getInoutParameterType(QualType Ty)
SemaHLSL(Sema &S)
Definition SemaHLSL.cpp:250
void handleVkConstantIdAttr(Decl *D, const ParsedAttr &AL)
std::optional< ExprResult > tryPerformConstantBufferConversion(Expr *BaseExpr)
Decl * ActOnStartBuffer(Scope *BufferScope, bool CBuffer, SourceLocation KwLoc, IdentifierInfo *Ident, SourceLocation IdentLoc, SourceLocation LBrace)
Definition SemaHLSL.cpp:252
bool diagnoseMatrixLayoutInstantiation(attr::Kind K, QualType T, SourceLocation Loc)
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition SemaHLSL.cpp:741
bool handleRootSignatureElements(ArrayRef< hlsl::RootSignatureElement > Elements)
bool CanPerformPackedTypeCast(Expr *Src, QualType DestTy)
void ActOnFinishRootSignatureDecl(SourceLocation Loc, IdentifierInfo *DeclIdent, ArrayRef< hlsl::RootSignatureElement > Elements)
Creates the Root Signature decl of the parsed Root Signature elements onto the AST and push it onto c...
void ActOnVariableDeclarator(VarDecl *VD)
bool CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
Encodes a location in the source.
The base class of all kinds of template declarations (e.g., class, function, etc.).
The top declaration context.
Definition Decl.h:106
The base class of the type hierarchy.
Definition TypeBase.h:1879
Represents a variable declaration or definition.
Definition Decl.h:933
Definition SPIR.cpp:47
Top level wrappers for InstallAPI frontend operations.
BindingType
Definition SemaHLSL.h:68
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:136
bool CreateHLSLAttributedResourceType(Sema &S, QualType Wrapped, ArrayRef< const Attr * > AttrList, QualType &ResType, HLSLAttributedResourceLocInfo *LocInfo=nullptr, Expr *SampleCountExpr=nullptr)
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Implicit
An implicit conversion.
Definition Sema.h:434
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 uint8_t
const HLSLResourceBindingAttr * Attr
Definition SemaHLSL.h:75
BindingType BindType
Definition SemaHLSL.h:76
DeclBindingInfo(const VarDecl *Decl, ResourceClass ResClass, BindingType BindType=BindingType::NotAssigned, const HLSLResourceBindingAttr *Attr=nullptr)
Definition SemaHLSL.h:78
ResourceClass ResClass
Definition SemaHLSL.h:74
void setBindingAttribute(HLSLResourceBindingAttr *A, BindingType BT)
Definition SemaHLSL.h:83
const VarDecl * Decl
Definition SemaHLSL.h:73
const SourceLocation & getLocation() const
Definition SemaHLSL.h:50
RootSignatureElement(SourceLocation Loc, llvm::hlsl::rootsig::RootElement Element)
Definition SemaHLSL.h:45
const llvm::hlsl::rootsig::RootElement & getElement() const
Definition SemaHLSL.h:49