clang 24.0.0git
Program.cpp
Go to the documentation of this file.
1//===--- Program.cpp - Bytecode 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#include "Program.h"
10#include "Context.h"
11#include "Function.h"
12#include "PrimType.h"
13#include "Reflect.h"
14#include "clang/AST/Decl.h"
15#include "clang/AST/DeclCXX.h"
17
18using namespace clang;
19using namespace clang::interp;
20
21Pointer Program::getPtrGlobal(unsigned Idx) const {
22 assert(Idx < Globals.size());
23
24 Block *B = Globals[Idx]->block();
25
26 // Force de-serialization of a redeclaration that might initialize this
27 // global.
28 if (B->getMetadataSize() != 0 &&
31 if (const VarDecl *VD = B->getDescriptor()->asVarDecl()) {
32 const VarDecl *MD = VD->getMostRecentDecl();
33 if (MD != VD && MD->hasInit() && !MD->getInit()->isValueDependent()) {
34 MD->evaluateValue();
35 // Note that we need to get Globals[Idx] here again since the code block
36 // above might've actually changed what global Idx points to.
37 return Pointer(Globals[Idx]->block());
38 }
39 }
40 }
41
42 return Pointer(B);
43}
44
46 if (auto It = GlobalIndices.find(VD); It != GlobalIndices.end())
47 return It->second;
48
49 // Find any previous declarations which were already evaluated.
50 std::optional<unsigned> Index;
51 for (const Decl *P = VD->getPreviousDecl(); P; P = P->getPreviousDecl()) {
52 if (auto It = GlobalIndices.find(P); It != GlobalIndices.end()) {
53 Index = It->second;
54 break;
55 }
56 }
57
58 // Map the decl to the existing index.
59 if (Index)
60 GlobalIndices[VD] = *Index;
61
62 return std::nullopt;
63}
64
66 if (auto It = GlobalIndices.find(E); It != GlobalIndices.end())
67 return It->second;
68 return std::nullopt;
69}
70
72 const Expr *Init) {
73 if (auto Idx = getGlobal(VD))
74 return Idx;
75
76 if (auto Idx = createGlobal(VD, Init)) {
77 GlobalIndices[VD] = *Idx;
78 return Idx;
79 }
80 return std::nullopt;
81}
82
84 bool IsConstexprUnknown) {
85 bool IsStatic, IsExtern;
86 bool IsWeak = VD->isWeak();
87 if (const auto *Var = dyn_cast<VarDecl>(VD)) {
89 IsExtern = Var->hasExternalStorage();
92 IsStatic = true;
93 IsExtern = false;
94 } else {
95 IsStatic = false;
96 IsExtern = true;
97 }
98
99 // Register all previous declarations as well. For extern blocks, just replace
100 // the index with the new variable.
101 UnsignedOrNone Idx = createGlobal(VD, VD->getType(), IsStatic, IsExtern,
102 IsWeak, IsConstexprUnknown, Init);
103 if (!Idx)
104 return std::nullopt;
105
106 Global *NewGlobal = Globals[*Idx];
107 GlobalIndices[VD] = *Idx;
108
109 for (const Decl *Redecl = VD->getPreviousDecl(); Redecl;
110 Redecl = Redecl->getPreviousDecl()) {
111 // If the redeclaration hasn't been registered yet at all, we just set its
112 // global index to Idx. If it has been registered yet, it might have
113 // pointers pointing to it and we need to transfer those pointers to the new
114 // block.
115 auto [Iter, Inserted] = GlobalIndices.try_emplace(Redecl);
116 if (Inserted) {
117 Iter->second = *Idx;
118 continue;
119 }
120
121 Block *RedeclBlock = Globals[Iter->second]->block();
122 // All pointers pointing to the previous extern decl now point to the
123 // new decl.
124 // A previous iteration might've already fixed up the pointers for this
125 // global.
126 if (RedeclBlock != NewGlobal->block())
127 RedeclBlock->movePointersTo(NewGlobal->block());
128
129 Globals[Iter->second] = NewGlobal;
130 Iter->second = *Idx;
131 }
132
133 return *Idx;
134}
135
137 if (auto Idx = getGlobal(E))
138 return Idx;
139 if (auto Idx = createGlobal(E, ExprType, /*IsStatic=*/true,
140 /*IsExtern=*/false, /*IsWeak=*/false,
141 /*IsConstexprUnknown=*/false)) {
142 GlobalIndices[E] = *Idx;
143 return *Idx;
144 }
145 return std::nullopt;
146}
147
149 bool IsExtern, bool IsWeak,
150 bool IsConstexprUnknown,
151 const Expr *Init) {
152 // Since this global variable is constexpr-unknown and a reference, register
153 // the pointee type instead. When referencing the variable, the pointer will
154 // then be of the pointee type instead of just PT_Ptr.
155 if (Ty->isReferenceType() && IsConstexprUnknown)
156 Ty = Ty->getPointeeType();
157
158 // Create a descriptor for the global.
159 Descriptor *Desc;
160 const bool IsConst = Ty.isConstQualified();
161 const bool IsTemporary = D.isExpr();
162 const bool IsVolatile = Ty.isVolatileQualified();
163 if (OptPrimType T = Ctx.classify(Ty))
164 Desc = createDescriptor(D, *T, nullptr, IsConst, IsTemporary,
165 /*IsMutable=*/false, IsVolatile);
166 else
167 Desc = createDescriptor(D, Ty.getTypePtr(), IsConst, IsTemporary,
168 /*IsMutable=*/false, IsVolatile);
169
170 if (!Desc)
171 return std::nullopt;
172 Desc->IsConstexprUnknown = IsConstexprUnknown;
173
174 // Allocate a block for storage.
175 unsigned I = Globals.size();
176
177 auto *G = new (Allocator, Desc->getAllocSize() + Block::GlobalMD)
178 Global(Ctx.getEvalID(), getCurrentDecl(), Desc, Block::GlobalMD, IsStatic,
179 IsExtern, IsWeak);
180 G->block()->invokeCtor();
181
182 // Initialize GlobalInlineDescriptor fields.
183 auto *GD = new (G->block()->rawData()) GlobalInlineDescriptor();
184 if (!Init)
185 GD->InitState = GlobalInitState::NoInitializer;
186 Globals.push_back(G);
187
188 return I;
189}
190
192 F = F->getFirstDecl();
193 assert(F);
194 auto It = Funcs.find(F);
195 return It == Funcs.end() ? nullptr : It->second;
196}
197
199 // Use the actual definition as a key.
200 RD = RD->getDefinition();
201 if (!RD)
202 return nullptr;
203
204 if (!RD->isCompleteDefinition())
205 return nullptr;
206
207 // Return an existing record if available. Otherwise, we insert nullptr now
208 // and replace that later, so recursive calls to this function with the same
209 // RecordDecl don't run into infinite recursion.
210 auto [It, Inserted] = Records.try_emplace(RD);
211 if (!Inserted)
212 return It->second;
213
214 // Number of bytes required by fields and base classes.
215 unsigned BaseSize = 0;
216 // Number of bytes required by virtual base.
217 unsigned VirtSize = 0;
218
219 // Helper to get a base descriptor.
220 auto GetBaseDesc = [this](const RecordDecl *BD,
221 const Record *BR) -> const Descriptor * {
222 if (!BR)
223 return nullptr;
224 return allocateDescriptor(BD, BR, /*IsConst=*/false, /*IsTemporary=*/false,
225 /*IsMutable=*/false, /*IsVolatile=*/false);
226 };
227
228 bool HasPtrField = false;
229 // Reserve space for base classes.
230 unsigned NumBases = 0;
231 Record::Base *Bases = nullptr;
232 unsigned NumVBases = 0;
233 Record::Base *VBases = nullptr;
234 if (const auto *CD = dyn_cast<CXXRecordDecl>(RD)) {
235 NumBases = CD->getNumBases();
236 // NB: This overallocates by all explicitly specified virtual bases.
237 if (NumBases != 0)
238 Bases = Allocate<Record::Base>(NumBases);
239
240 unsigned I = 0;
241 for (const CXXBaseSpecifier &Spec : CD->bases()) {
242 assert(I <= NumBases);
243 if (Spec.isVirtual())
244 continue;
245
246 // In error cases, the base might not be a RecordType.
247 const auto *BD = Spec.getType()->getAsCXXRecordDecl();
248 if (!BD)
249 return nullptr;
250 const Record *BR = getOrCreateRecord(BD);
251
252 const Descriptor *Desc = GetBaseDesc(BD, BR);
253 if (!Desc)
254 return nullptr;
255
256 BaseSize += align(sizeof(InlineDescriptor));
257 new (&Bases[I]) Record::Base(BD, Desc, BR, BaseSize);
258 BaseSize += align(BR->getSize());
259 HasPtrField |= BR->hasPtrField();
260 ++I;
261 }
262 // Make sure we don't include the virtual base specifiers we skipped above.
263 NumBases = I;
264
265 I = 0;
266 NumVBases = CD->getNumVBases();
267 if (NumVBases != 0)
268 VBases = Allocate<Record::Base>(NumVBases);
269 for (const CXXBaseSpecifier &Spec : CD->vbases()) {
270 assert(I <= NumVBases);
271 const auto *BD = Spec.getType()->castAsCXXRecordDecl();
272 const Record *BR = getOrCreateRecord(BD);
273
274 const Descriptor *Desc = GetBaseDesc(BD, BR);
275 if (!Desc)
276 return nullptr;
277
278 VirtSize += align(sizeof(InlineDescriptor));
279 new (&VBases[I]) Record::Base(BD, Desc, BR, VirtSize);
280 VirtSize += align(BR->getSize());
281 HasPtrField |= BR->hasPtrField();
282 ++I;
283 }
284 assert(I == NumVBases);
285 }
286
287 // Reserve space for fields.
288 unsigned NumFields = RD->getNumFields();
289 Record::Field *Fields = nullptr;
290 if (NumFields != 0)
291 Fields = Allocate<Record::Field>(NumFields);
292 unsigned I = 0;
293 for (const FieldDecl *FD : RD->fields()) {
294 FD = FD->getFirstDecl();
295 // Note that we DO create fields and descriptors
296 // for unnamed bitfields here, even though we later ignore
297 // them everywhere. That's so the FieldDecl's getFieldIndex() matches.
298
299 // Reserve space for the field's descriptor and the offset.
300 BaseSize += align(sizeof(InlineDescriptor));
301
302 // Classify the field and add its metadata.
303 QualType FT = FD->getType();
304 const bool IsConst = FT.isConstQualified();
305 const bool IsMutable = FD->isMutable();
306 const bool IsVolatile = FT.isVolatileQualified();
307 const Descriptor *Desc;
308 OptPrimType T = Ctx.classify(FT);
309 if (T) {
310 Desc = createDescriptor(FD, *T, nullptr, IsConst,
311 /*IsTemporary=*/false, IsMutable, IsVolatile);
312 HasPtrField = HasPtrField || (T == PT_Ptr);
313 } else if ((Desc = createDescriptor(FD, FT.getTypePtr(), IsConst,
314 /*IsTemporary=*/false, IsMutable,
315 IsVolatile))) {
316 HasPtrField =
317 HasPtrField ||
318 (Desc->isPrimitiveArray() && Desc->getPrimType() == PT_Ptr) ||
319 (Desc->ElemRecord && Desc->ElemRecord->hasPtrField());
320 } else {
321 Desc = allocateDescriptor(FD);
322 }
323 assert(Desc);
324 new (&Fields[I]) Record::Field(FD, Desc, BaseSize, T);
325 BaseSize += align(Desc->getAllocSize());
326 ++I;
327 }
328
329 // Adjust virtual base offsets to account for base size.
330 for (unsigned I = 0; I != NumVBases; ++I)
331 VBases[I].Offset += BaseSize;
332
333 Record *R = new (Allocator)
334 Record(RD, {Bases, NumBases}, {Fields, NumFields}, {VBases, NumVBases},
335 VirtSize, BaseSize, HasPtrField);
336 Records[RD] = R;
337 return R;
338}
339
341 bool IsConst, bool IsTemporary,
342 bool IsMutable, bool IsVolatile,
343 const Expr *Init) {
344 // Classes and structures.
345 if (const auto *RD = Ty->getAsRecordDecl()) {
346 if (const auto *Record = getOrCreateRecord(RD))
347 return allocateDescriptor(D, Record, IsConst, IsTemporary, IsMutable,
348 IsVolatile);
349 return allocateDescriptor(D);
350 }
351
352 // Arrays.
353 if (const auto *ArrayType = Ty->getAsArrayTypeUnsafe()) {
355 // Array of well-known bounds.
356 if (const auto *CAT = dyn_cast<ConstantArrayType>(ArrayType)) {
357 size_t NumElems = CAT->getZExtSize();
358 if (OptPrimType T = Ctx.classify(ElemTy)) {
359 // Arrays of primitives.
360 unsigned ElemSize = primSize(*T);
361 if ((Descriptor::MaxArrayElemBytes / ElemSize) < NumElems) {
362 return nullptr;
363 }
364 return allocateDescriptor(D, CAT, *T, NumElems, IsConst, IsTemporary,
365 IsMutable, IsVolatile);
366 }
367 // Arrays of composites. In this case, the array is a list of pointers,
368 // followed by the actual elements.
369 const Descriptor *ElemDesc =
370 createDescriptor(D, ElemTy.getTypePtr(), IsConst, IsTemporary);
371 if (!ElemDesc)
372 return nullptr;
373 unsigned ElemSize = ElemDesc->getAllocSize() + sizeof(InlineDescriptor);
374 if (std::numeric_limits<unsigned>::max() / ElemSize <= NumElems)
375 return nullptr;
376 return allocateDescriptor(D, Ty, ElemDesc, NumElems, IsConst, IsTemporary,
377 IsMutable);
378 }
379
380 // Array of unknown bounds - cannot be accessed and pointer arithmetic
381 // is forbidden on pointers to such objects.
384 if (OptPrimType T = Ctx.classify(ElemTy)) {
385 return allocateDescriptor(D, *T, IsConst, IsTemporary,
387 }
388 const Descriptor *Desc =
389 createDescriptor(D, ElemTy.getTypePtr(), IsConst, IsTemporary);
390 if (!Desc)
391 return nullptr;
392 return allocateDescriptor(D, Desc, IsTemporary,
394 }
395 }
396
397 // Atomic types.
398 if (const auto *AT = Ty->getAs<AtomicType>()) {
399 const Type *InnerTy = AT->getValueType().getTypePtr();
400 return createDescriptor(D, InnerTy, IsConst, IsTemporary, IsMutable);
401 }
402
403 // Complex types - represented as arrays of elements.
404 if (const auto *CT = Ty->getAs<ComplexType>()) {
405 OptPrimType ElemTy = Ctx.classify(CT->getElementType());
406 if (!ElemTy)
407 return nullptr;
408
409 return allocateDescriptor(D, CT, *ElemTy, 2, IsConst, IsTemporary,
410 IsMutable, IsVolatile);
411 }
412
413 // Same with vector types.
414 if (const auto *VT = Ty->getAs<VectorType>()) {
415 OptPrimType ElemTy = Ctx.classify(VT->getElementType());
416 if (!ElemTy)
417 return nullptr;
418
419 return allocateDescriptor(D, VT, *ElemTy, VT->getNumElements(), IsConst,
420 IsTemporary, IsMutable, IsVolatile);
421 }
422
423 // Same with constant matrix types.
424 if (const auto *MT = Ty->getAs<ConstantMatrixType>()) {
425 OptPrimType ElemTy = Ctx.classify(MT->getElementType());
426 if (!ElemTy)
427 return nullptr;
428
429 return allocateDescriptor(D, MT, *ElemTy, MT->getNumElementsFlattened(),
430 IsConst, IsTemporary, IsMutable, IsVolatile);
431 }
432
433 return nullptr;
434}
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
llvm::MachO::Record Record
Definition MachO.h:31
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
QualType getElementType() const
Definition TypeBase.h:3832
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3362
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4490
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1080
This represents one expression.
Definition Expr.h:113
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
Represents a member of a struct/union/class.
Definition Decl.h:3299
Represents a function declaration or definition.
Definition Decl.h:2059
A global _GUID constant.
Definition DeclCXX.h:4451
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8530
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8446
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8519
Represents a struct/union/class.
Definition Decl.h:4464
unsigned getNumFields() const
Returns the number of fields (non-static data members) in this record.
Definition Decl.h:4680
field_range fields() const
Definition Decl.h:4667
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4648
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3957
A template parameter object.
The base class of the type hierarchy.
Definition TypeBase.h:1879
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isReferenceType() const
Definition TypeBase.h:8707
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9352
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9299
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4508
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
QualType getType() const
Definition Decl.h:724
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5660
Represents a variable declaration or definition.
Definition Decl.h:933
bool hasInit() const
Definition Decl.cpp:2383
VarDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
const Expr * getInit() const
Definition Decl.h:1392
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2560
Represents a GCC generic vector type.
Definition TypeBase.h:4273
A memory block, either on the stack or in the heap.
Definition Block.h:43
const Descriptor * getDescriptor() const
Returns the block's descriptor.
Definition Block.h:73
static constexpr uint8_t GlobalMD
Definition Block.h:51
void movePointersTo(Block *B)
Move all pointers from this block to.
Definition Block.cpp:103
unsigned getMetadataSize() const
Returns the size of the metadata.
Definition Block.h:93
static bool shouldBeGloballyIndexed(const ValueDecl *VD)
Returns whether we should create a global variable for the given ValueDecl.
Definition Context.h:175
OptPrimType classify(QualType T) const
Classifies a type.
Definition Context.cpp:521
unsigned getEvalID() const
Definition Context.h:190
Bytecode function.
Definition Function.h:98
A pointer to a memory block, live or dead.
Definition Pointer.h:546
UnsignedOrNone createGlobal(const ValueDecl *VD, const Expr *Init, bool IsConstexprUnknown=false)
Creates a global and returns its index.
Definition Program.cpp:83
void * Allocate(size_t Size, unsigned Align=8) const
Definition Program.h:130
Function * getFunction(const FunctionDecl *F)
Returns a function.
Definition Program.cpp:191
Block * getGlobal(unsigned Idx)
Returns the value of a global.
Definition Program.h:68
Descriptor * createDescriptor(DeclOrExpr D, PrimType T, const Type *SourceTy=nullptr, bool IsConst=false, bool IsTemporary=false, bool IsMutable=false, bool IsVolatile=false)
Creates a descriptor for a primitive type.
Definition Program.h:115
UnsignedOrNone getOrCreateGlobal(const ValueDecl *VD, const Expr *Init=nullptr)
Returns or creates a global an creates an index to it.
Definition Program.cpp:71
Pointer getPtrGlobal(unsigned Idx) const
Returns a pointer to a global.
Definition Program.cpp:21
UnsignedOrNone getCurrentDecl() const
Returns the current declaration ID.
Definition Program.h:153
Record * getOrCreateRecord(const RecordDecl *RD)
Returns a record or creates one if it does not exist.
Definition Program.cpp:198
Structure/Class descriptor.
Definition Record.h:27
bool hasPtrField() const
If this record (or any of its bases) contains a field of type PT_Ptr.
Definition Record.h:85
unsigned getSize() const
Returns the size of the record.
Definition Record.h:75
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:218
bool Init(InterpState &S, CodePtr OpPC)
Definition Interp.h:2420
size_t primSize(PrimType Type)
Returns the size of a primitive type in bytes.
Definition PrimType.cpp:25
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
Token to denote structures of unknown size.
Definition Descriptor.h:140
Describes a memory block created by an allocation site.
Definition Descriptor.h:123
unsigned getAllocSize() const
Returns the allocated size, including metadata.
Definition Descriptor.h:238
static constexpr unsigned MaxArrayElemBytes
Maximum number of bytes to be used for array elements.
Definition Descriptor.h:143
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition Descriptor.h:252
const VarDecl * asVarDecl() const
Definition Descriptor.h:210
PrimType getPrimType() const
Definition Descriptor.h:232
const Record *const ElemRecord
Pointer to the record, if block contains records.
Definition Descriptor.h:147
Descriptor used for global variables.
Definition Descriptor.h:50
Inline descriptor embedded in structures and arrays.
Definition Descriptor.h:68