1//===--- Descriptor.h - Types for the constexpr VM --------------*- C++ -*-===//
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//
9// Defines descriptors which characterise allocations.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_INTERP_DESCRIPTOR_H
14#define LLVM_CLANG_AST_INTERP_DESCRIPTOR_H
15
16#include "../ExprConstShared.h"
17#include "DeclOrExpr.h"
18#include "InitMap.h"
19#include "PrimType.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/Expr.h"
22
23namespace clang {
24namespace interp {
25class Record;
26class SourceInfo;
27struct Descriptor;
28enum PrimType : uint8_t;
29
30/// Invoked whenever a block is created. The constructor method fills in the
31/// inline descriptors of all fields and array elements. It also initializes
32/// all the fields which contain non-trivial types.
33using BlockCtorFn = void (*)(std::byte *FieldPtr, bool IsConst, bool IsMutable,
34 bool IsVolatile, bool IsActive, bool InUnion,
35 const Descriptor *FieldDesc);
36
37/// Invoked when a block is destroyed. Invokes the destructors of all
38/// non-trivial nested fields of arrays and records.
39using BlockDtorFn = void (*)(std::byte *FieldPtr, const Descriptor *FieldDesc);
40
41enum class GlobalInitState {
42 Initialized,
43 NoInitializer,
44 InitializerFailed,
45};
46
47/// Descriptor used for global variables.
48struct alignas(void *) GlobalInlineDescriptor {
49 GlobalInitState InitState = GlobalInitState::InitializerFailed;
50};
51static_assert(sizeof(GlobalInlineDescriptor) == sizeof(void *), "");
52
53enum class Lifetime : uint8_t {
54 Started,
55 NotStarted,
56 Destroyed,
57 Ended,
58};
59
60struct alignas(void *) LocalInlineDescriptor {
61 bool IsEnabled;
62 bool IsInitialized;
63 Lifetime LifeState;
64
65 LocalInlineDescriptor()
66 : IsEnabled(false), IsInitialized(false), LifeState(Lifetime::Started) {}
67 Lifetime getLifetime() const { return LifeState; }
68 void setLifetime(Lifetime L) { LifeState = L; }
69};
70static_assert(sizeof(LocalInlineDescriptor) == sizeof(void *));
71
72/// Inline descriptor embedded in structures and arrays.
73///
74/// Such descriptors precede all composite array elements and structure fields.
75/// If the base of a pointer is not zero, the base points to the end of this
76/// structure. The offset field is used to traverse the pointer chain up
77/// to the root structure which allocated the object.
78struct InlineDescriptor {
79 /// Offset inside the structure/array.
80 unsigned Offset;
81
82 /// Flag indicating if the storage is constant or not.
83 /// Relevant for primitive fields.
84 LLVM_PREFERRED_TYPE(bool)
85 unsigned IsConst : 1;
86 /// For primitive fields, it indicates if the field was initialized.
87 /// Primitive fields in static storage are always initialized.
88 /// Arrays are always initialized, even though their elements might not be.
89 /// Base classes are initialized after the constructor is invoked.
90 LLVM_PREFERRED_TYPE(bool)
91 unsigned IsInitialized : 1;
92 /// Flag indicating if the field is an embedded base class.
93 LLVM_PREFERRED_TYPE(bool)
94 unsigned IsBase : 1;
95 /// Flag inidcating if the field is a virtual base class.
96 LLVM_PREFERRED_TYPE(bool)
97 unsigned IsVirtualBase : 1;
98 /// Flag indicating if the field is the active member of a union.
99 LLVM_PREFERRED_TYPE(bool)
100 unsigned IsActive : 1;
101 /// Flag indicating if this field is in a union (even if nested).
102 LLVM_PREFERRED_TYPE(bool)
103 unsigned InUnion : 1;
104 /// Flag indicating if the field is mutable (if in a record).
105 LLVM_PREFERRED_TYPE(bool)
106 unsigned IsFieldMutable : 1;
107 /// Flag indicating if this field is a const field nested in
108 /// a mutable parent field.
109 LLVM_PREFERRED_TYPE(bool)
110 unsigned IsConstInMutable : 1;
111 /// Flag indicating if the field is an element of a composite array.
112 LLVM_PREFERRED_TYPE(bool)
113 unsigned IsArrayElement : 1;
114 LLVM_PREFERRED_TYPE(bool)
115 unsigned IsVolatile : 1;
116
117 Lifetime LifeState;
118
119 const Descriptor *Desc;
120
121 void dump() const { dump(OS&: llvm::errs()); }
122 void dump(llvm::raw_ostream &OS) const;
123};
124
125/// Describes a memory block created by an allocation site.
126struct Descriptor final {
127private:
128 /// Original declaration, used to emit the error message.
129 const DeclOrExpr Source;
130 const Type *SourceType = nullptr;
131 /// Size of an element, in host bytes.
132 const unsigned ElemSize;
133 /// Size of the storage, in host bytes.
134 const unsigned Size;
135 /// Size of the allocation (storage), in host bytes.
136 const unsigned AllocSize;
137
138 /// Value to denote arrays of unknown size.
139 static constexpr unsigned UnknownSizeMark = (unsigned)-1;
140
141public:
142 /// Token to denote structures of unknown size.
143 struct UnknownSize {};
144
145 /// Maximum number of bytes to be used for array elements.
146 static constexpr unsigned MaxArrayElemBytes =
147 std::numeric_limits<decltype(AllocSize)>::max() - sizeof(InitMapPtr);
148
149 /// Pointer to the record, if block contains records.
150 const Record *const ElemRecord = nullptr;
151 /// Descriptor of the array element.
152 const Descriptor *const ElemDesc = nullptr;
153 /// The primitive type this descriptor was created for,
154 /// or the primitive element type in case this is
155 /// a primitive array.
156 const OptPrimType PrimT = std::nullopt;
157 /// Flag indicating if the block is mutable.
158 const bool IsConst = false;
159 /// Flag indicating if a field is mutable.
160 const bool IsMutable = false;
161 /// Flag indicating if the block is a temporary.
162 const bool IsTemporary = false;
163 const bool IsVolatile = false;
164 /// Flag indicating if the block is an array.
165 const bool IsArray = false;
166
167 /// Storage management methods.
168 const BlockCtorFn CtorFn = nullptr;
169 const BlockDtorFn DtorFn = nullptr;
170
171 /// Allocates a descriptor for a primitive.
172 Descriptor(DeclOrExpr D, const Type *SourceTy, PrimType Type, bool IsConst,
173 bool IsTemporary, bool IsMutable, bool IsVolatile);
174
175 /// Allocates a descriptor for an array of primitives.
176 Descriptor(DeclOrExpr D, const Type *SourceTy, PrimType Type, size_t NumElems,
177 bool IsConst, bool IsTemporary, bool IsMutable, bool IsVolatile);
178
179 /// Allocates a descriptor for an array of primitives of unknown size.
180 Descriptor(DeclOrExpr D, PrimType Type, bool IsConst, bool IsTemporary,
181 UnknownSize);
182
183 /// Allocates a descriptor for an array of composites.
184 Descriptor(DeclOrExpr D, const Type *SourceTy, const Descriptor *Elem,
185 unsigned NumElems, bool IsConst, bool IsTemporary, bool IsMutable);
186
187 /// Allocates a descriptor for an array of composites of unknown size.
188 Descriptor(DeclOrExpr D, const Descriptor *Elem, bool IsTemporary,
189 UnknownSize);
190
191 /// Allocates a descriptor for a record.
192 Descriptor(DeclOrExpr D, const Record *R, bool IsConst, bool IsTemporary,
193 bool IsMutable, bool IsVolatile);
194
195 /// Allocates a dummy descriptor.
196 Descriptor(DeclOrExpr D);
197
198 QualType getType() const;
199 QualType getElemQualType() const;
200 QualType getDataType(const ASTContext &Ctx) const;
201 SourceLocation getLocation() const { return Source.getLocation(); }
202 SourceInfo getLoc() const;
203
204 const Decl *asDecl() const { return Source.asDecl(); }
205 const Expr *asExpr() const { return Source.asExpr(); }
206 DeclOrExpr getSource() const { return Source; }
207
208 const ValueDecl *asValueDecl() const {
209 return dyn_cast_if_present<ValueDecl>(Val: asDecl());
210 }
211
212 const VarDecl *asVarDecl() const {
213 return dyn_cast_if_present<VarDecl>(Val: asDecl());
214 }
215
216 const FieldDecl *asFieldDecl() const {
217 return dyn_cast_if_present<FieldDecl>(Val: asDecl());
218 }
219
220 const RecordDecl *asRecordDecl() const {
221 return dyn_cast_if_present<RecordDecl>(Val: asDecl());
222 }
223
224 template <typename T> const T *getAs() const {
225 return dyn_cast_if_present<T>(asDecl());
226 }
227
228 /// Returns the size of the object without metadata.
229 unsigned getSize() const {
230 assert(!isUnknownSizeArray() && "Array of unknown size");
231 return Size;
232 }
233
234 PrimType getPrimType() const {
235 assert(isPrimitiveArray() || isPrimitive());
236 return *PrimT;
237 }
238
239 /// Returns the allocated size, including metadata.
240 unsigned getAllocSize() const { return AllocSize; }
241 /// returns the size of an element when the structure is viewed as an array.
242 unsigned getElemSize() const { return ElemSize; }
243 /// Returns the element data size, i.e. not what the size of
244 /// our primitive data type is, but what the data size of that is.
245 /// E.g., for PT_SInt32, that's 4 bytes.
246 unsigned getElemDataSize() const;
247
248 /// Returns the number of elements stored in the block.
249 unsigned getNumElems() const {
250 return Size == UnknownSizeMark ? 0 : (getSize() / getElemSize());
251 }
252
253 /// Checks if the descriptor is of an array of primitives.
254 bool isPrimitiveArray() const { return IsArray && !ElemDesc; }
255 /// Checks if the descriptor is of an array of composites.
256 bool isCompositeArray() const { return IsArray && ElemDesc; }
257 /// Checks if the descriptor is of an array of zero size.
258 bool isZeroSizeArray() const { return Size == 0; }
259 /// Checks if the descriptor is of an array of unknown size.
260 bool isUnknownSizeArray() const { return Size == UnknownSizeMark; }
261
262 /// Checks if the descriptor is of a primitive.
263 bool isPrimitive() const { return !IsArray && !ElemRecord && PrimT; }
264
265 /// Checks if the descriptor is of an array.
266 bool isArray() const { return IsArray; }
267 /// Checks if the descriptor is of a record.
268 bool isRecord() const { return !IsArray && ElemRecord; }
269 /// Checks if the descriptor is of a union.
270 bool isUnion() const;
271
272 /// Whether variables of this descriptor need their destructor called or not.
273 bool hasTrivialDtor() const;
274
275 /// Returns the kind of dynamic allocation source of this block.
276 static DynAllocKind getDynAllocKindForExpr(const Expr *E);
277 /// Returns the kind of dynamic allocation source of this block.
278 DynAllocKind getDynAllocKind() const {
279 return asExpr() ? getDynAllocKindForExpr(E: asExpr()) : DynAllocKind::None;
280 }
281 /// Checks if the descriptor is of a dynamic allocation.
282 bool isDynAlloc() const { return getDynAllocKind() != DynAllocKind::None; }
283
284 /// Compute the alignment for a dynamic allocation.
285 CharUnits computeAlignForDynamicAlloc(const ASTContext &Ctx) const;
286
287 void dump() const;
288 void dump(llvm::raw_ostream &OS) const;
289 void dumpFull(unsigned Offset = 0, unsigned Indent = 0) const;
290};
291} // namespace interp
292} // namespace clang
293
294#endif
295