1//===--- Program.h - 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// Defines a program which organises and links multiple bytecode functions.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_INTERP_PROGRAM_H
14#define LLVM_CLANG_AST_INTERP_PROGRAM_H
15
16#include "Function.h"
17#include "Pointer.h"
18#include "PrimType.h"
19#include "Record.h"
20#include "Source.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/PointerUnion.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/Support/Allocator.h"
25#include <map>
26#include <vector>
27
28namespace clang {
29class RecordDecl;
30class Expr;
31class FunctionDecl;
32class StringLiteral;
33class VarDecl;
34
35namespace interp {
36class Context;
37
38/// The program contains and links the bytecode for all functions.
39class Program final {
40public:
41 Program(Context &Ctx) : Ctx(Ctx) {}
42
43 ~Program() {
44 // Manually destroy all the blocks. They are almost all harmless,
45 // but primitive arrays might have an InitMap* heap allocated and
46 // that needs to be freed.
47 for (Global *G : Globals)
48 if (Block *B = G->block(); B->isInitialized())
49 B->invokeDtor();
50
51 // Records might actually allocate memory themselves, but they
52 // are allocated using a BumpPtrAllocator. Call their desctructors
53 // here manually so they are properly freeing their resources.
54 for (auto RecordPair : Records) {
55 if (Record *R = RecordPair.second)
56 R->~Record();
57 }
58 }
59
60 /// Marshals a native pointer to an ID for embedding in bytecode.
61 unsigned getOrCreateNativePointer(const void *Ptr);
62
63 /// Returns the value of a marshalled native pointer.
64 const void *getNativePointer(unsigned Idx);
65
66 /// Emits a string literal among global data.
67 unsigned createGlobalString(const StringLiteral *S,
68 const Expr *Base = nullptr);
69
70 /// Returns a pointer to a global.
71 Pointer getPtrGlobal(unsigned Idx) const;
72
73 /// Returns the value of a global.
74 Block *getGlobal(unsigned Idx) {
75 assert(Idx < Globals.size());
76 return Globals[Idx]->block();
77 }
78
79 /// Finds a global's index.
80 std::optional<unsigned> getGlobal(const ValueDecl *VD);
81 std::optional<unsigned> getGlobal(const Expr *E);
82
83 /// Returns or creates a global an creates an index to it.
84 std::optional<unsigned> getOrCreateGlobal(const ValueDecl *VD,
85 const Expr *Init = nullptr);
86
87 /// Returns or creates a dummy value for unknown declarations.
88 unsigned getOrCreateDummy(const DeclTy &D);
89
90 /// Creates a global and returns its index.
91 std::optional<unsigned> createGlobal(const ValueDecl *VD, const Expr *Init);
92
93 /// Creates a global from a lifetime-extended temporary.
94 std::optional<unsigned> createGlobal(const Expr *E);
95
96 /// Creates a new function from a code range.
97 template <typename... Ts>
98 Function *createFunction(const FunctionDecl *Def, Ts &&...Args) {
99 Def = Def->getCanonicalDecl();
100 auto *Func = new Function(*this, Def, std::forward<Ts>(Args)...);
101 Funcs.insert(KV: {Def, std::unique_ptr<Function>(Func)});
102 return Func;
103 }
104 /// Creates an anonymous function.
105 template <typename... Ts> Function *createFunction(Ts &&...Args) {
106 auto *Func = new Function(*this, std::forward<Ts>(Args)...);
107 AnonFuncs.emplace_back(args&: Func);
108 return Func;
109 }
110
111 /// Returns a function.
112 Function *getFunction(const FunctionDecl *F);
113
114 /// Returns a record or creates one if it does not exist.
115 Record *getOrCreateRecord(const RecordDecl *RD);
116
117 /// Creates a descriptor for a primitive type.
118 Descriptor *createDescriptor(const DeclTy &D, PrimType T,
119 const Type *SourceTy = nullptr,
120 Descriptor::MetadataSize MDSize = std::nullopt,
121 bool IsConst = false, bool IsTemporary = false,
122 bool IsMutable = false,
123 bool IsVolatile = false) {
124 return allocateDescriptor(Args: D, Args&: SourceTy, Args&: T, Args&: MDSize, Args&: IsConst, Args&: IsTemporary,
125 Args&: IsMutable, Args&: IsVolatile);
126 }
127
128 /// Creates a descriptor for a composite type.
129 Descriptor *createDescriptor(const DeclTy &D, const Type *Ty,
130 Descriptor::MetadataSize MDSize = std::nullopt,
131 bool IsConst = false, bool IsTemporary = false,
132 bool IsMutable = false, bool IsVolatile = false,
133 const Expr *Init = nullptr);
134
135 /// Context to manage declaration lifetimes.
136 class DeclScope {
137 public:
138 DeclScope(Program &P) : P(P), PrevDecl(P.CurrentDeclaration) {
139 ++P.LastDeclaration;
140 P.CurrentDeclaration = P.LastDeclaration;
141 }
142 ~DeclScope() { P.CurrentDeclaration = PrevDecl; }
143
144 private:
145 Program &P;
146 unsigned PrevDecl;
147 };
148
149 /// Returns the current declaration ID.
150 std::optional<unsigned> getCurrentDecl() const {
151 if (CurrentDeclaration == NoDeclaration)
152 return std::nullopt;
153 return CurrentDeclaration;
154 }
155
156private:
157 friend class DeclScope;
158
159 std::optional<unsigned> createGlobal(const DeclTy &D, QualType Ty,
160 bool IsStatic, bool IsExtern,
161 bool IsWeak, const Expr *Init = nullptr);
162
163 /// Reference to the VM context.
164 Context &Ctx;
165 /// Mapping from decls to cached bytecode functions.
166 llvm::DenseMap<const FunctionDecl *, std::unique_ptr<Function>> Funcs;
167 /// List of anonymous functions.
168 std::vector<std::unique_ptr<Function>> AnonFuncs;
169
170 /// Function relocation locations.
171 llvm::DenseMap<const FunctionDecl *, std::vector<unsigned>> Relocs;
172
173 /// Native pointers referenced by bytecode.
174 std::vector<const void *> NativePointers;
175 /// Cached native pointer indices.
176 llvm::DenseMap<const void *, unsigned> NativePointerIndices;
177
178 /// Custom allocator for global storage.
179 using PoolAllocTy = llvm::BumpPtrAllocator;
180
181 /// Descriptor + storage for a global object.
182 ///
183 /// Global objects never go out of scope, thus they do not track pointers.
184 class Global {
185 public:
186 /// Create a global descriptor for string literals.
187 template <typename... Tys>
188 Global(Tys... Args) : B(std::forward<Tys>(Args)...) {}
189
190 /// Allocates the global in the pool, reserving storate for data.
191 void *operator new(size_t Meta, PoolAllocTy &Alloc, size_t Data) {
192 return Alloc.Allocate(Size: Meta + Data, Alignment: alignof(void *));
193 }
194
195 /// Return a pointer to the data.
196 std::byte *data() { return B.data(); }
197 /// Return a pointer to the block.
198 Block *block() { return &B; }
199 const Block *block() const { return &B; }
200
201 private:
202 /// Required metadata - does not actually track pointers.
203 Block B;
204 };
205
206 /// Allocator for globals.
207 PoolAllocTy Allocator;
208
209 /// Global objects.
210 std::vector<Global *> Globals;
211 /// Cached global indices.
212 llvm::DenseMap<const void *, unsigned> GlobalIndices;
213
214 /// Mapping from decls to record metadata.
215 llvm::DenseMap<const RecordDecl *, Record *> Records;
216
217 /// Dummy parameter to generate pointers from.
218 llvm::DenseMap<const void *, unsigned> DummyVariables;
219
220 /// Creates a new descriptor.
221 template <typename... Ts> Descriptor *allocateDescriptor(Ts &&...Args) {
222 return new (Allocator) Descriptor(std::forward<Ts>(Args)...);
223 }
224
225 /// No declaration ID.
226 static constexpr unsigned NoDeclaration = ~0u;
227 /// Last declaration ID.
228 unsigned LastDeclaration = 0;
229 /// Current declaration ID.
230 unsigned CurrentDeclaration = NoDeclaration;
231
232public:
233 /// Dumps the disassembled bytecode to \c llvm::errs().
234 void dump() const;
235 void dump(llvm::raw_ostream &OS) const;
236};
237
238} // namespace interp
239} // namespace clang
240
241#endif
242

source code of clang/lib/AST/ByteCode/Program.h