clang 24.0.0git
HLSLBufferLayoutBuilder.cpp
Go to the documentation of this file.
1//===- HLSLBufferLayoutBuilder.cpp ----------------------------------------===//
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
10#include "CGHLSLRuntime.h"
11#include "CodeGenModule.h"
12#include "TargetInfo.h"
13#include "clang/AST/Type.h"
14
15//===----------------------------------------------------------------------===//
16// Implementation of constant buffer layout common between DirectX and
17// SPIR/SPIR-V.
18//===----------------------------------------------------------------------===//
19
20using namespace clang;
21using namespace clang::CodeGen;
22
24 CharUnits::fromQuantity(llvm::hlsl::CBufferRowSizeInBytes);
25
26namespace clang {
27namespace CodeGen {
28
29llvm::StructType *
31 const CGHLSLOffsetInfo &OffsetInfo) {
32
33 // check if we already have the layout type for this struct
34 // TODO: Do we need to check for matching OffsetInfo?
35 if (llvm::StructType *Ty = CGM.getHLSLRuntime().getHLSLBufferLayoutType(RT))
36 return Ty;
37
38 // iterate over all fields of the record, including fields on base classes
40 RecordDecls.push_back(RT->castAsCXXRecordDecl());
41 while (RecordDecls.back()->getNumBases()) {
42 CXXRecordDecl *D = RecordDecls.back();
43 assert(D->getNumBases() == 1 &&
44 "HLSL doesn't support multiple inheritance");
45 RecordDecls.push_back(D->bases_begin()->getType()->castAsCXXRecordDecl());
46 }
47
49 unsigned OffsetIdx = 0;
50 for (const CXXRecordDecl *RD : llvm::reverse(RecordDecls))
51 for (const auto *FD : RD->fields())
52 FieldsWithOffset.emplace_back(FD, OffsetInfo[OffsetIdx++]);
53
54 if (!OffsetInfo.empty())
55 llvm::stable_sort(FieldsWithOffset, [](const auto &LHS, const auto &RHS) {
56 return CGHLSLOffsetInfo::compareOffsets(LHS.second, RHS.second);
57 });
58
60 CharUnits CurrentOffset = CharUnits::Zero();
61 for (auto &[FD, Offset] : FieldsWithOffset) {
62 llvm::Type *LayoutType = layOutType(FD->getType());
63 if (!LayoutType)
64 continue;
65
66 const llvm::DataLayout &DL = CGM.getDataLayout();
67 CharUnits Size =
68 CharUnits::fromQuantity(DL.getTypeSizeInBits(LayoutType) / 8);
69 CharUnits Align = CharUnits::fromQuantity(DL.getABITypeAlign(LayoutType));
70
71 if (LayoutType->isAggregateType() ||
72 (CurrentOffset % CBufferRowSize) + Size > CBufferRowSize)
73 Align = Align.alignTo(CBufferRowSize);
74
75 CharUnits NextOffset = CurrentOffset.alignTo(Align);
76
77 if (Offset != CGHLSLOffsetInfo::Unspecified) {
78 CharUnits PackOffset = CharUnits::fromQuantity(Offset);
79 assert(PackOffset >= NextOffset &&
80 "Offset is invalid - would overlap with previous object");
81 NextOffset = PackOffset;
82 }
83
84 if (NextOffset > CurrentOffset) {
85 llvm::Type *Padding = CGM.getTargetCodeGenInfo().getHLSLPadding(
86 CGM, NextOffset - CurrentOffset);
87 assert(Padding && "No padding type for target?");
88 Layout.emplace_back(Padding);
89 CurrentOffset = NextOffset;
90 }
91 Layout.emplace_back(LayoutType);
92 CurrentOffset += Size;
93 }
94
95 // Create the layout struct type; anonymous structs have empty name but
96 // non-empty qualified name
97 const auto *Decl = RT->castAsCXXRecordDecl();
98 std::string Name =
99 Decl->getName().empty() ? "anon" : Decl->getQualifiedNameAsString();
100
101 llvm::StructType *NewTy = llvm::StructType::create(Layout, Name,
102 /*isPacked=*/true);
103 CGM.getHLSLRuntime().addHLSLBufferLayoutType(RT, NewTy);
104 return NewTy;
105}
106
107llvm::Type *HLSLBufferLayoutBuilder::padArrayElements(llvm::Type *EltTy,
108 uint64_t Count) {
109 CharUnits EltSize =
110 CharUnits::fromQuantity(CGM.getDataLayout().getTypeSizeInBits(EltTy) / 8);
111 CharUnits Padding = EltSize.alignTo(CBufferRowSize) - EltSize;
112
113 // If we don't have any padding between elements then we just need the array
114 // itself.
115 if (Count < 2 || Padding.isZero())
116 return llvm::ArrayType::get(EltTy, Count);
117
118 llvm::LLVMContext &Context = CGM.getLLVMContext();
119 llvm::Type *PaddingTy =
120 CGM.getTargetCodeGenInfo().getHLSLPadding(CGM, Padding);
121 assert(PaddingTy && "No padding type for target?");
122 auto *PaddedEltTy =
123 llvm::StructType::get(Context, {EltTy, PaddingTy}, /*isPacked=*/true);
124 return llvm::StructType::get(
125 Context, {llvm::ArrayType::get(PaddedEltTy, Count - 1), EltTy},
126 /*IsPacked=*/true);
127}
128
130 llvm::Type *EltTy = layOutType(AT->getElementType());
131 uint64_t Count = AT->getZExtSize();
132 return padArrayElements(EltTy, Count);
133}
134
136 // ConvertTypeForMem already handles row/column-major layout and bool
137 // promotion, producing [Count x <VecLen x EltTy>]. We just need to add
138 // cbuffer padding between the array elements. Pass the sugared QualType so
139 // that the `row_major`/`column_major` orientation attribute is preserved.
140 llvm::ArrayType *MemTy =
141 cast<llvm::ArrayType>(CGM.getTypes().ConvertTypeForMem(Ty));
142 return padArrayElements(MemTy->getElementType(), MemTy->getNumElements());
143}
144
146 // HLSL resource types are not included in the buffer layout.
148 return nullptr;
149
150 if (const auto *AT = CGM.getContext().getAsConstantArrayType(Ty))
151 return layOutArray(AT);
152
153 if (Ty->isStructureOrClassType()) {
154 CGHLSLOffsetInfo EmptyOffsets;
155 return layOutStruct(Ty->getAsCanonical<RecordType>(), EmptyOffsets);
156 }
157
158 if (Ty->isConstantMatrixType())
159 return layOutMatrix(Ty);
160
161 return CGM.getTypes().ConvertTypeForMem(Ty);
162}
163
164} // namespace CodeGen
165} // namespace clang
constexpr CharUnits CBufferRowSize
C Language Family Type Representation.
QualType getElementType() const
Definition TypeBase.h:3833
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:603
base_class_iterator bases_begin()
Definition DeclCXX.h:616
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
CharUnits alignTo(CharUnits Align) const
Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is a multiple...
Definition CharUnits.h:171
static constexpr CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
static const uint32_t Unspecified
static bool compareOffsets(uint32_t LHS, uint32_t RHS)
Comparison function for offsets received from operator[] suitable for use in a stable_sort.
const llvm::DataLayout & getDataLayout() const
const TargetCodeGenInfo & getTargetCodeGenInfo()
llvm::LLVMContext & getLLVMContext()
llvm::StructType * layOutStruct(const RecordType *StructType, const CGHLSLOffsetInfo &OffsetInfo)
Lays out a struct type following HLSL buffer rules and considering any explicit offset information.
llvm::Type * layOutArray(const ConstantArrayType *AT)
Lays out an array type following HLSL buffer rules.
llvm::Type * layOutMatrix(QualType Ty)
Lays out a matrix type following HLSL buffer rules.
llvm::Type * layOutType(QualType Type)
Lays out a type following HLSL buffer rules.
virtual llvm::Type * getHLSLPadding(CodeGenModule &CGM, CharUnits NumBytes) const
Return an LLVM type that corresponds to padding in HLSL types.
Definition TargetInfo.h:467
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3859
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3935
A (possibly-)qualified type.
Definition TypeBase.h:938
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isConstantMatrixType() const
Definition TypeBase.h:9084
bool isHLSLResourceRecord() const
Definition Type.cpp:5742
bool isStructureOrClassType() const
Definition Type.cpp:839
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3003
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5746
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
Top level wrappers for InstallAPI frontend operations.
U cast(CodeGen::Address addr)
Definition Address.h:327