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 handleVkBuiltInAttr(Decl *D, const ParsedAttr &AL);
190 void handleVkLocationAttr(Decl *D, const ParsedAttr &AL);
191 void handlePackOffsetAttr(Decl *D, const ParsedAttr &AL);
192 void handleShaderAttr(Decl *D, const ParsedAttr &AL);
193 void handleResourceBindingAttr(Decl *D, const ParsedAttr &AL);
194 void handleParamModifierAttr(Decl *D, const ParsedAttr &AL);
198 SourceLocation Loc);
199 // Re-type a layout-adapting matrix builtin call \p E with \p DestType's
200 // row_major/column_major sugar so CodeGen lowers it into that layout.
202
203 void handleSemanticAttr(Decl *D, const ParsedAttr &AL);
204
205 void handleVkExtBuiltinInputAttr(Decl *D, const ParsedAttr &AL);
206 void handleVkExtBuiltinOutputAttr(Decl *D, const ParsedAttr &AL);
207 void handleVkPushConstantAttr(Decl *D, const ParsedAttr &AL);
208
209 bool CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
212 TakeLocForHLSLAttribute(const HLSLAttributedResourceType *RT);
213
214 // HLSL Type trait implementations
218
220
222 SourceLocation NameLoc);
223
224 bool CanPerformScalarCast(QualType SrcTy, QualType DestTy);
225 bool CanPerformElementwiseCast(Expr *Src, QualType DestType);
226 bool CanPerformAggregateSplatCast(Expr *Src, QualType DestType);
227 bool CanPerformPackedTypeCast(Expr *Src, QualType DestTy);
228 ExprResult CreateOutArgExpr(Expr *Arg, QualType ArgTy, QualType ParamTy,
230 bool IsInOut);
232
234
236 bool handleInitialization(VarDecl *VDecl, Expr *&Init);
239 SourceLocation OpLoc,
240 const IdentifierInfo *CompName,
241 SourceLocation CompLoc);
242
244 return ImplicitBindingNextOrderID++;
245 }
246
249
250private:
251 // HLSL resource type attributes need to be processed all at once.
252 // This is a list to collect them.
253 llvm::SmallVector<const Attr *> HLSLResourcesTypeAttrs;
254
255 /// TypeLoc data for HLSLAttributedResourceType instances that we
256 /// have not yet populated.
257 llvm::DenseMap<const HLSLAttributedResourceType *,
259 LocsForHLSLAttributedResources;
260
261 // List of all resource bindings
263
264 // Map of local resource variables to their assigned global resources.
265 //
266 // The binding can be a nullptr, in which case, the variable has yet to be
267 // initialized or assigned to.
268 llvm::DenseMap<const VarDecl *, const DeclBindingInfo *> Assigns;
269
270 // Global declaration collected for the $Globals default constant
271 // buffer which will be created at the end of the translation unit.
272 llvm::SmallVector<Decl *> DefaultCBufferDecls;
273
274 uint32_t ImplicitBindingNextOrderID = 0;
275
276 IdentifierInfo *RootSigOverrideIdent = nullptr;
277
278 bool HasDeclaredAPushConstant = false;
279
280 // Information about the current subtree being flattened.
281 struct SemanticInfo {
282 HLSLParsedSemanticAttr *Semantic;
283 std::optional<uint32_t> Index = std::nullopt;
284 };
285
286 // The context shared by all semantics with the same IOType during
287 // flattening.
288 struct SemanticContext {
289 // Present if any semantic sharing the same IO type has an explicit or
290 // implicit SPIR-V location index assigned.
291 std::optional<bool> UsesExplicitVkLocations = std::nullopt;
292 // Lowercased semantic names with indices, mapped to their first use for
293 // overlap diagnostics.
294 llvm::StringMap<SourceLocation> ActiveSemantics = {};
295 // The IOType of this semantic set.
296 llvm::hlsl::IOType CurrentIOType;
297 };
298
299private:
300 bool
301 checkInterpolationModifiers(const DeclaratorDecl *D,
302 const HLSLInterpolationModifierAttr *Inherited,
303 const HLSLParsedSemanticAttr *Semantic);
304
305 void collectResourceBindingsOnVarDecl(VarDecl *D);
306 void collectResourceBindingsOnUserRecordDecl(const VarDecl *VD,
307 const RecordType *RT);
308
309 void checkSemanticAnnotation(FunctionDecl *EntryPoint, const Decl *Param,
310 const HLSLAppliedSemanticAttr *SemanticAttr,
311 const SemanticContext &SC,
312 unsigned ElementCount);
313
314 bool determineActiveSemanticOnScalar(FunctionDecl *FD,
315 DeclaratorDecl *OutputDecl,
316 DeclaratorDecl *D,
317 SemanticInfo &ActiveSemantic,
318 SemanticContext &SC);
319
320 bool determineActiveSemantic(FunctionDecl *FD, DeclaratorDecl *OutputDecl,
321 DeclaratorDecl *D, SemanticInfo &ActiveSemantic,
322 SemanticContext &SC);
323
324 void processExplicitBindingsOnDecl(VarDecl *D);
325
326 void diagnoseAvailabilityViolations(TranslationUnitDecl *TU);
327
328 void diagnoseAttrStageMismatch(
329 const Attr *A, llvm::Triple::EnvironmentType Stage,
330 std::initializer_list<llvm::Triple::EnvironmentType> AllowedStages);
331
332 void
333 diagnoseSemanticStageMismatch(const Attr *A,
334 llvm::Triple::EnvironmentType Stage,
335 llvm::hlsl::IOType CurrentIOType,
336 llvm::dxbc::PSV::SemanticKind SemanticKind);
337
338 // Check ElementCount consecutive indices for a system-value interpretation.
339 void diagnoseSystemSemanticIndex(const HLSLAppliedSemanticAttr *A,
340 llvm::dxbc::PSV::SemanticKind SemanticKind,
341 unsigned ElementCount);
342
343 void diagnoseSemanticType(const Decl *D, const HLSLAppliedSemanticAttr *A,
344 llvm::dxbc::PSV::SemanticKind SemanticKind);
345
346 void diagnoseSemanticShaderModel(const HLSLAppliedSemanticAttr *A,
347 llvm::dxbc::PSV::SemanticKind SemanticKind);
348
349 void handleGlobalStructOrArrayOfWithResources(VarDecl *VD);
350
351 // Infer a common global binding info for an Expr
352 //
353 // Returns std::nullopt if the expr refers to non-unique global bindings.
354 // Returns nullptr if it refer to any global binding, otherwise it returns
355 // a reference to the global binding info.
356 std::optional<const DeclBindingInfo *> inferGlobalBinding(Expr *E);
357
358 void trackLocalResource(VarDecl *VDecl, Expr *E);
359};
360
361} // namespace clang
362
363#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:63
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:47
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:3012
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
This represents one expression.
Definition Expr.h:114
Represents a function declaration or definition.
Definition Decl.h:2082
One of these records is kept for each identifier that is lexed.
Describes an C or C++ initializer list.
Definition Expr.h:5377
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:3433
This represents a decl that may have a name.
Definition Decl.h:276
Represents a parameter to a function.
Definition Decl.h:1832
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:248
DeclBindingInfo * getDeclBindingInfo(const VarDecl *VD, ResourceClass ResClass)
Definition SemaHLSL.cpp:234
DeclBindingInfo * addDeclBindingInfo(const VarDecl *VD, ResourceClass ResClass)
Definition SemaHLSL.cpp:221
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
SemaBase(Sema &S)
Definition SemaBase.cpp:7
ExprResult ActOnOutParamExpr(ParmVarDecl *Param, Expr *Arg)
void handleVkBuiltInAttr(Decl *D, const ParsedAttr &AL)
HLSLRootSignatureDecl * lookupRootSignatureOverrideDecl(DeclContext *DC) const
bool CanPerformElementwiseCast(Expr *Src, QualType DestType)
ExprResult CreateOutArgExpr(Expr *Arg, QualType ArgTy, QualType ParamTy, InitializedEntity Entity, SourceLocation Loc, bool IsInOut)
void handleWaveSizeAttr(Decl *D, const ParsedAttr &AL)
void handleVkLocationAttr(Decl *D, const ParsedAttr &AL)
HLSLAttributedResourceLocInfo TakeLocForHLSLAttribute(const HLSLAttributedResourceType *RT)
void handleSemanticAttr(Decl *D, const ParsedAttr &AL)
bool CanPerformScalarCast(QualType SrcTy, QualType DestTy)
QualType ProcessResourceTypeAttributes(QualType Wrapped)
void handleInterpolationModifierAttr(Decl *D, const ParsedAttr &AL)
Definition SemaHLSL.cpp:832
void handleShaderAttr(Decl *D, const ParsedAttr &AL)
uint32_t getNextImplicitBindingOrderID()
Definition SemaHLSL.h:243
void CheckEntryPoint(FunctionDecl *FD)
void handleVkExtBuiltinOutputAttr(Decl *D, const ParsedAttr &AL)
void emitLogicalOperatorFixIt(Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
bool initGlobalResourceDecl(VarDecl *VD)
void ActOnEndOfTranslationUnit(TranslationUnitDecl *TU)
bool initGlobalResourceArrayDecl(VarDecl *VD)
HLSLVkConstantIdAttr * mergeVkConstantIdAttr(Decl *D, const AttributeCommonInfo &AL, int Id)
Definition SemaHLSL.cpp:763
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition SemaHLSL.cpp:729
void deduceAddressSpace(VarDecl *Decl)
std::pair< IdentifierInfo *, bool > ActOnStartRootSignatureDecl(StringRef Signature)
Computes the unique Root Signature identifier from the given signature, then lookup if there is a pre...
void handlePackOffsetAttr(Decl *D, const ParsedAttr &AL)
Attr * buildMatrixLayoutTypeAttr(QualType T, const ParsedAttr &AL)
bool handleInitialization(VarDecl *VDecl, Expr *&Init)
void handleParamModifierAttr(Decl *D, const ParsedAttr &AL)
bool CheckResourceBinOp(BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc)
bool CanPerformAggregateSplatCast(Expr *Src, QualType DestType)
bool ActOnResourceMemberAccessExpr(MemberExpr *ME)
bool IsScalarizedLayoutCompatible(QualType T1, QualType T2) const
QualType ActOnTemplateShorthand(TemplateDecl *Template, SourceLocation NameLoc)
void handleRootSignatureAttr(Decl *D, const ParsedAttr &AL)
bool CheckCompatibleParameterABI(FunctionDecl *New, FunctionDecl *Old)
QualType handleVectorBinOpConversion(ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
QualType checkMatrixComponent(Sema &S, QualType baseType, ExprValueKind &VK, SourceLocation OpLoc, const IdentifierInfo *CompName, SourceLocation CompLoc)
bool IsConstantBufferElementCompatible(QualType T1)
void handleResourceBindingAttr(Decl *D, const ParsedAttr &AL)
bool IsTypedResourceElementCompatible(QualType T1)
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:941
bool handleResourceTypeAttr(QualType T, const ParsedAttr &AL)
void handleVkPushConstantAttr(Decl *D, const ParsedAttr &AL)
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, llvm::Triple::EnvironmentType ShaderType)
Definition SemaHLSL.cpp:799
NamedDecl * getConstantBufferConversionFunction(QualType Type, CXXRecordDecl *RD)
void ActOnFinishBuffer(Decl *Dcl, SourceLocation RBrace)
Definition SemaHLSL.cpp:702
void handleVkBindingAttr(Decl *D, const ParsedAttr &AL)
HLSLParamModifierAttr * mergeParamModifierAttr(Decl *D, const AttributeCommonInfo &AL, HLSLParamModifierAttr::Spelling Spelling)
Definition SemaHLSL.cpp:812
QualType getInoutParameterType(QualType Ty)
SemaHLSL(Sema &S)
Definition SemaHLSL.cpp:252
void handleVkConstantIdAttr(Decl *D, const ParsedAttr &AL)
std::optional< ExprResult > tryPerformConstantBufferConversion(Expr *BaseExpr)
Decl * ActOnStartBuffer(Scope *BufferScope, bool CBuffer, SourceLocation KwLoc, IdentifierInfo *Ident, SourceLocation IdentLoc, SourceLocation LBrace)
Definition SemaHLSL.cpp:254
bool diagnoseMatrixLayoutInstantiation(attr::Kind K, QualType T, SourceLocation Loc)
HLSLWaveSizeAttr * mergeWaveSizeAttr(Decl *D, const AttributeCommonInfo &AL, int Min, int Max, int Preferred, int SpelledArgsCount)
Definition SemaHLSL.cpp:743
bool handleRootSignatureElements(ArrayRef< hlsl::RootSignatureElement > Elements)
bool CanPerformPackedTypeCast(Expr *Src, QualType DestTy)
void ActOnFinishRootSignatureDecl(SourceLocation Loc, IdentifierInfo *DeclIdent, ArrayRef< hlsl::RootSignatureElement > Elements)
Creates the Root Signature decl of the parsed Root Signature elements onto the AST and push it onto c...
void ActOnVariableDeclarator(VarDecl *VD)
bool CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
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:107
The base class of the type hierarchy.
Definition TypeBase.h:1879
Represents a variable declaration or definition.
Definition Decl.h:934
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
int32_t uint32_t uint32_t __builtin_riscv_mhracc_i32 __builtin_riscv_mhraccu_u32 __builtin_riscv_mhraccsu_i32 __builtin_riscv_mulqr_i32 __builtin_riscv_mqrwacc_i64 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 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