clang 19.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 "ByteCodeStmtGen.h"
11#include "Context.h"
12#include "Function.h"
13#include "Integral.h"
14#include "Opcode.h"
15#include "PrimType.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18
19using namespace clang;
20using namespace clang::interp;
21
22unsigned Program::getOrCreateNativePointer(const void *Ptr) {
23 auto It = NativePointerIndices.find(Ptr);
24 if (It != NativePointerIndices.end())
25 return It->second;
26
27 unsigned Idx = NativePointers.size();
28 NativePointers.push_back(Ptr);
29 NativePointerIndices[Ptr] = Idx;
30 return Idx;
31}
32
33const void *Program::getNativePointer(unsigned Idx) {
34 return NativePointers[Idx];
35}
36
38 const size_t CharWidth = S->getCharByteWidth();
39 const size_t BitWidth = CharWidth * Ctx.getCharBit();
40
41 PrimType CharType;
42 switch (CharWidth) {
43 case 1:
44 CharType = PT_Sint8;
45 break;
46 case 2:
47 CharType = PT_Uint16;
48 break;
49 case 4:
50 CharType = PT_Uint32;
51 break;
52 default:
53 llvm_unreachable("unsupported character width");
54 }
55
56 // Create a descriptor for the string.
57 Descriptor *Desc = allocateDescriptor(S, CharType, Descriptor::InlineDescMD,
58 S->getLength() + 1,
59 /*isConst=*/true,
60 /*isTemporary=*/false,
61 /*isMutable=*/false);
62
63 // Allocate storage for the string.
64 // The byte length does not include the null terminator.
65 unsigned I = Globals.size();
66 unsigned Sz = Desc->getAllocSize();
67 auto *G = new (Allocator, Sz) Global(Desc, /*isStatic=*/true,
68 /*isExtern=*/false);
69 G->block()->invokeCtor();
70
71 new (G->block()->rawData()) InlineDescriptor(Desc);
72 Globals.push_back(G);
73
74 // Construct the string in storage.
75 const Pointer Ptr(G->block());
76 for (unsigned I = 0, N = S->getLength(); I <= N; ++I) {
77 Pointer Field = Ptr.atIndex(I).narrow();
78 const uint32_t CodePoint = I == N ? 0 : S->getCodeUnit(I);
79 switch (CharType) {
80 case PT_Sint8: {
81 using T = PrimConv<PT_Sint8>::T;
82 Field.deref<T>() = T::from(CodePoint, BitWidth);
83 Field.initialize();
84 break;
85 }
86 case PT_Uint16: {
87 using T = PrimConv<PT_Uint16>::T;
88 Field.deref<T>() = T::from(CodePoint, BitWidth);
89 Field.initialize();
90 break;
91 }
92 case PT_Uint32: {
93 using T = PrimConv<PT_Uint32>::T;
94 Field.deref<T>() = T::from(CodePoint, BitWidth);
95 Field.initialize();
96 break;
97 }
98 default:
99 llvm_unreachable("unsupported character type");
100 }
101 }
102 return I;
103}
104
105Pointer Program::getPtrGlobal(unsigned Idx) const {
106 assert(Idx < Globals.size());
107 return Pointer(Globals[Idx]->block());
108}
109
110std::optional<unsigned> Program::getGlobal(const ValueDecl *VD) {
111 auto It = GlobalIndices.find(VD);
112 if (It != GlobalIndices.end())
113 return It->second;
114
115 // Find any previous declarations which were already evaluated.
116 std::optional<unsigned> Index;
117 for (const Decl *P = VD; P; P = P->getPreviousDecl()) {
118 auto It = GlobalIndices.find(P);
119 if (It != GlobalIndices.end()) {
120 Index = It->second;
121 break;
122 }
123 }
124
125 // Map the decl to the existing index.
126 if (Index) {
127 GlobalIndices[VD] = *Index;
128 return std::nullopt;
129 }
130
131 return Index;
132}
133
134std::optional<unsigned> Program::getOrCreateGlobal(const ValueDecl *VD,
135 const Expr *Init) {
136 if (auto Idx = getGlobal(VD))
137 return Idx;
138
139 if (auto Idx = createGlobal(VD, Init)) {
140 GlobalIndices[VD] = *Idx;
141 return Idx;
142 }
143 return std::nullopt;
144}
145
146std::optional<unsigned> Program::getOrCreateDummy(const ValueDecl *VD) {
147 // Dedup blocks since they are immutable and pointers cannot be compared.
148 if (auto It = DummyVariables.find(VD); It != DummyVariables.end())
149 return It->second;
150
151 // Create dummy descriptor.
152 // We create desriptors of 'array of unknown size' if the type is an array
153 // type _and_ the size isn't known (it's not a ConstantArrayType). If the size
154 // is known however, we create a regular dummy pointer.
155 Descriptor *Desc;
156 if (const auto *AT = VD->getType()->getAsArrayTypeUnsafe();
157 AT && !isa<ConstantArrayType>(AT))
158 Desc = allocateDescriptor(VD, Descriptor::UnknownSize{});
159 else
160 Desc = allocateDescriptor(VD);
161
162 // Allocate a block for storage.
163 unsigned I = Globals.size();
164
165 auto *G = new (Allocator, Desc->getAllocSize())
166 Global(getCurrentDecl(), Desc, /*IsStatic=*/true, /*IsExtern=*/false);
167 G->block()->invokeCtor();
168
169 Globals.push_back(G);
170 DummyVariables[VD] = I;
171 return I;
172}
173
174std::optional<unsigned> Program::createGlobal(const ValueDecl *VD,
175 const Expr *Init) {
176 assert(!getGlobal(VD));
177 bool IsStatic, IsExtern;
178 if (const auto *Var = dyn_cast<VarDecl>(VD)) {
180 IsExtern = !Var->getAnyInitializer();
181 } else if (isa<UnnamedGlobalConstantDecl, MSGuidDecl>(VD)) {
182 IsStatic = true;
183 IsExtern = false;
184 } else {
185 IsStatic = false;
186 IsExtern = true;
187 }
188 if (auto Idx = createGlobal(VD, VD->getType(), IsStatic, IsExtern, Init)) {
189 for (const Decl *P = VD; P; P = P->getPreviousDecl())
190 GlobalIndices[P] = *Idx;
191 return *Idx;
192 }
193 return std::nullopt;
194}
195
196std::optional<unsigned> Program::createGlobal(const Expr *E) {
197 return createGlobal(E, E->getType(), /*isStatic=*/true, /*isExtern=*/false);
198}
199
200std::optional<unsigned> Program::createGlobal(const DeclTy &D, QualType Ty,
201 bool IsStatic, bool IsExtern,
202 const Expr *Init) {
203 // Create a descriptor for the global.
204 Descriptor *Desc;
205 const bool IsConst = Ty.isConstQualified();
206 const bool IsTemporary = D.dyn_cast<const Expr *>();
207 if (std::optional<PrimType> T = Ctx.classify(Ty))
208 Desc =
209 createDescriptor(D, *T, Descriptor::InlineDescMD, IsConst, IsTemporary);
210 else
212 IsConst, IsTemporary);
213
214 if (!Desc)
215 return std::nullopt;
216
217 // Allocate a block for storage.
218 unsigned I = Globals.size();
219
220 auto *G = new (Allocator, Desc->getAllocSize())
221 Global(getCurrentDecl(), Desc, IsStatic, IsExtern);
222 G->block()->invokeCtor();
223
224 // Initialize InlineDescriptor fields.
225 new (G->block()->rawData()) InlineDescriptor(Desc);
226 Globals.push_back(G);
227
228 return I;
229}
230
232 F = F->getCanonicalDecl();
233 assert(F);
234 auto It = Funcs.find(F);
235 return It == Funcs.end() ? nullptr : It->second.get();
236}
237
239 // Use the actual definition as a key.
240 RD = RD->getDefinition();
241 if (!RD)
242 return nullptr;
243
244 if (!RD->isCompleteDefinition())
245 return nullptr;
246
247 // Deduplicate records.
248 if (auto It = Records.find(RD); It != Records.end())
249 return It->second;
250
251 // We insert nullptr now and replace that later, so recursive calls
252 // to this function with the same RecordDecl don't run into
253 // infinite recursion.
254 Records.insert({RD, nullptr});
255
256 // Number of bytes required by fields and base classes.
257 unsigned BaseSize = 0;
258 // Number of bytes required by virtual base.
259 unsigned VirtSize = 0;
260
261 // Helper to get a base descriptor.
262 auto GetBaseDesc = [this](const RecordDecl *BD,
263 const Record *BR) -> const Descriptor * {
264 if (!BR)
265 return nullptr;
266 return allocateDescriptor(BD, BR, std::nullopt, /*isConst=*/false,
267 /*isTemporary=*/false,
268 /*isMutable=*/false);
269 };
270
271 // Reserve space for base classes.
272 Record::BaseList Bases;
273 Record::VirtualBaseList VirtBases;
274 if (const auto *CD = dyn_cast<CXXRecordDecl>(RD)) {
275
276 for (const CXXBaseSpecifier &Spec : CD->bases()) {
277 if (Spec.isVirtual())
278 continue;
279
280 // In error cases, the base might not be a RecordType.
281 if (const auto *RT = Spec.getType()->getAs<RecordType>()) {
282 const RecordDecl *BD = RT->getDecl();
283 const Record *BR = getOrCreateRecord(BD);
284
285 if (const Descriptor *Desc = GetBaseDesc(BD, BR)) {
286 BaseSize += align(sizeof(InlineDescriptor));
287 Bases.push_back({BD, BaseSize, Desc, BR});
288 BaseSize += align(BR->getSize());
289 continue;
290 }
291 }
292 return nullptr;
293 }
294
295 for (const CXXBaseSpecifier &Spec : CD->vbases()) {
296
297 if (const auto *RT = Spec.getType()->getAs<RecordType>()) {
298 const RecordDecl *BD = RT->getDecl();
299 const Record *BR = getOrCreateRecord(BD);
300
301 if (const Descriptor *Desc = GetBaseDesc(BD, BR)) {
302 VirtSize += align(sizeof(InlineDescriptor));
303 VirtBases.push_back({BD, VirtSize, Desc, BR});
304 VirtSize += align(BR->getSize());
305 continue;
306 }
307 }
308 return nullptr;
309 }
310 }
311
312 // Reserve space for fields.
313 Record::FieldList Fields;
314 for (const FieldDecl *FD : RD->fields()) {
315 // Reserve space for the field's descriptor and the offset.
316 BaseSize += align(sizeof(InlineDescriptor));
317
318 // Classify the field and add its metadata.
319 QualType FT = FD->getType();
320 const bool IsConst = FT.isConstQualified();
321 const bool IsMutable = FD->isMutable();
322 const Descriptor *Desc;
323 if (std::optional<PrimType> T = Ctx.classify(FT)) {
324 Desc = createDescriptor(FD, *T, std::nullopt, IsConst,
325 /*isTemporary=*/false, IsMutable);
326 } else {
327 Desc = createDescriptor(FD, FT.getTypePtr(), std::nullopt, IsConst,
328 /*isTemporary=*/false, IsMutable);
329 }
330 if (!Desc)
331 return nullptr;
332 Fields.push_back({FD, BaseSize, Desc});
333 BaseSize += align(Desc->getAllocSize());
334 }
335
336 Record *R = new (Allocator) Record(RD, std::move(Bases), std::move(Fields),
337 std::move(VirtBases), VirtSize, BaseSize);
338 Records[RD] = R;
339 return R;
340}
341
344 bool IsConst, bool IsTemporary,
345 bool IsMutable, const Expr *Init) {
346 // Classes and structures.
347 if (const auto *RT = Ty->getAs<RecordType>()) {
348 if (const auto *Record = getOrCreateRecord(RT->getDecl()))
349 return allocateDescriptor(D, Record, MDSize, IsConst, IsTemporary,
350 IsMutable);
351 }
352
353 // Arrays.
354 if (const auto ArrayType = Ty->getAsArrayTypeUnsafe()) {
356 // Array of well-known bounds.
357 if (auto CAT = dyn_cast<ConstantArrayType>(ArrayType)) {
358 size_t NumElems = CAT->getZExtSize();
359 if (std::optional<PrimType> T = Ctx.classify(ElemTy)) {
360 // Arrays of primitives.
361 unsigned ElemSize = primSize(*T);
362 if (std::numeric_limits<unsigned>::max() / ElemSize <= NumElems) {
363 return {};
364 }
365 return allocateDescriptor(D, *T, MDSize, NumElems, IsConst, IsTemporary,
366 IsMutable);
367 } else {
368 // Arrays of composites. In this case, the array is a list of pointers,
369 // followed by the actual elements.
370 const Descriptor *ElemDesc = createDescriptor(
371 D, ElemTy.getTypePtr(), MDSize, IsConst, IsTemporary);
372 if (!ElemDesc)
373 return nullptr;
374 unsigned ElemSize =
375 ElemDesc->getAllocSize() + sizeof(InlineDescriptor);
376 if (std::numeric_limits<unsigned>::max() / ElemSize <= NumElems)
377 return {};
378 return allocateDescriptor(D, ElemDesc, MDSize, NumElems, IsConst,
379 IsTemporary, IsMutable);
380 }
381 }
382
383 // Array of unknown bounds - cannot be accessed and pointer arithmetic
384 // is forbidden on pointers to such objects.
385 if (isa<IncompleteArrayType>(ArrayType)) {
386 if (std::optional<PrimType> T = Ctx.classify(ElemTy)) {
387 return allocateDescriptor(D, *T, MDSize, IsTemporary,
389 } else {
390 const Descriptor *Desc = createDescriptor(D, ElemTy.getTypePtr(),
391 MDSize, IsConst, IsTemporary);
392 if (!Desc)
393 return nullptr;
394 return allocateDescriptor(D, Desc, MDSize, IsTemporary,
396 }
397 }
398 }
399
400 // Atomic types.
401 if (const auto *AT = Ty->getAs<AtomicType>()) {
402 const Type *InnerTy = AT->getValueType().getTypePtr();
403 return createDescriptor(D, InnerTy, MDSize, IsConst, IsTemporary,
404 IsMutable);
405 }
406
407 // Complex types - represented as arrays of elements.
408 if (const auto *CT = Ty->getAs<ComplexType>()) {
409 PrimType ElemTy = *Ctx.classify(CT->getElementType());
410 return allocateDescriptor(D, ElemTy, MDSize, 2, IsConst, IsTemporary,
411 IsMutable);
412 }
413
414 return nullptr;
415}
StringRef P
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
bool IsStatic
Definition: Format.cpp:2981
llvm::MachO::Records Records
Definition: MachO.h:36
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3307
QualType getElementType() const
Definition: Type.h:3319
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Complex values, per C99 6.2.5p11.
Definition: Type.h:2875
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
This represents one expression.
Definition: Expr.h:110
QualType getType() const
Definition: Expr.h:142
Represents a member of a struct/union/class.
Definition: Decl.h:3025
Represents a function declaration or definition.
Definition: Decl.h:1959
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3582
A (possibly-)qualified type.
Definition: Type.h:738
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7119
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7191
Represents a struct/union/class.
Definition: Decl.h:4133
field_range fields() const
Definition: Decl.h:4339
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4324
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5309
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3652
The base class of the type hierarchy.
Definition: Type.h:1607
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:7931
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7878
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
QualType getType() const
Definition: Decl.h:717
unsigned getCharBit() const
Returns CHAR_BIT.
Definition: Context.cpp:181
static bool shouldBeGloballyIndexed(const ValueDecl *VD)
Returns whether we should create a global variable for the given ValueDecl.
Definition: Context.h:97
std::optional< PrimType > classify(QualType T) const
Classifies a type.
Definition: Context.cpp:119
Bytecode function.
Definition: Function.h:77
A pointer to a memory block, live or dead.
Definition: Pointer.h:65
Pointer narrow() const
Restricts the scope of an array element pointer.
Definition: Pointer.h:130
Pointer atIndex(unsigned Idx) const
Offsets a pointer inside an array.
Definition: Pointer.h:104
std::optional< unsigned > getOrCreateGlobal(const ValueDecl *VD, const Expr *Init=nullptr)
Returns or creates a global an creates an index to it.
Definition: Program.cpp:134
Function * getFunction(const FunctionDecl *F)
Returns a function.
Definition: Program.cpp:231
Block * getGlobal(unsigned Idx)
Returns the value of a global.
Definition: Program.h:72
std::optional< unsigned > createGlobal(const ValueDecl *VD, const Expr *Init)
Creates a global and returns its index.
Definition: Program.cpp:174
const void * getNativePointer(unsigned Idx)
Returns the value of a marshalled native pointer.
Definition: Program.cpp:33
Descriptor * createDescriptor(const DeclTy &D, PrimType Type, Descriptor::MetadataSize MDSize=std::nullopt, bool IsConst=false, bool IsTemporary=false, bool IsMutable=false)
Creates a descriptor for a primitive type.
Definition: Program.h:116
unsigned getOrCreateNativePointer(const void *Ptr)
Marshals a native pointer to an ID for embedding in bytecode.
Definition: Program.cpp:22
unsigned createGlobalString(const StringLiteral *S)
Emits a string literal among global data.
Definition: Program.cpp:37
Pointer getPtrGlobal(unsigned Idx) const
Returns a pointer to a global.
Definition: Program.cpp:105
std::optional< unsigned > getCurrentDecl() const
Returns the current declaration ID.
Definition: Program.h:143
std::optional< unsigned > getOrCreateDummy(const ValueDecl *VD)
Returns or creates a dummy value for unknown declarations.
Definition: Program.cpp:146
Record * getOrCreateRecord(const RecordDecl *RD)
Returns a record or creates one if it does not exist.
Definition: Program.cpp:238
Structure/Class descriptor.
Definition: Record.h:25
unsigned getSize() const
Returns the size of the record.
Definition: Record.h:58
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition: PrimType.h:95
PrimType
Enumeration of the primitive types of the VM.
Definition: PrimType.h:32
size_t primSize(PrimType Type)
Returns the size of a primitive type in bytes.
Definition: PrimType.cpp:22
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
Definition: Descriptor.h:27
The JSON file list parser is used to communicate input to InstallAPI.
Token to denote structures of unknown size.
Definition: Descriptor.h:106
Describes a memory block created by an allocation site.
Definition: Descriptor.h:88
unsigned getAllocSize() const
Returns the allocated size, including metadata.
Definition: Descriptor.h:200
static constexpr MetadataSize InlineDescMD
Definition: Descriptor.h:109
std::optional< unsigned > MetadataSize
Definition: Descriptor.h:108
Inline descriptor embedded in structures and arrays.
Definition: Descriptor.h:56
Mapping from primitive types to their representation.
Definition: PrimType.h:69