clang  16.0.0git
Program.h
Go to the documentation of this file.
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 <map>
17 #include <vector>
18 #include "Function.h"
19 #include "Pointer.h"
20 #include "PrimType.h"
21 #include "Record.h"
22 #include "Source.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/PointerUnion.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Support/Allocator.h"
27 
28 namespace clang {
29 class RecordDecl;
30 class Expr;
31 class FunctionDecl;
32 class StringLiteral;
33 class VarDecl;
34 
35 namespace interp {
36 class Context;
37 class Record;
38 
39 /// The program contains and links the bytecode for all functions.
40 class Program final {
41 public:
42  Program(Context &Ctx) : Ctx(Ctx) {}
43 
45  // Manually destroy all the blocks. They are almost all harmless,
46  // but primitive arrays might have an InitMap* heap allocated and
47  // that needs to be freed.
48  for (Global *G : Globals)
49  G->block()->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 
69  /// Returns a pointer to a global.
70  Pointer getPtrGlobal(unsigned Idx);
71 
72  /// Returns the value of a global.
73  Block *getGlobal(unsigned Idx) {
74  assert(Idx < Globals.size());
75  return Globals[Idx]->block();
76  }
77 
78  /// Finds a global's index.
80 
81  /// Returns or creates a global an creates an index to it.
83 
84  /// Returns or creates a dummy value for parameters.
86 
87  /// Creates a global and returns its index.
89 
90  /// Creates a global from a lifetime-extended temporary.
92 
93  /// Creates a new function from a code range.
94  template <typename... Ts>
95  Function *createFunction(const FunctionDecl *Def, Ts &&... Args) {
96  Def = Def->getCanonicalDecl();
97  auto *Func = new Function(*this, Def, std::forward<Ts>(Args)...);
98  Funcs.insert({Def, std::unique_ptr<Function>(Func)});
99  return Func;
100  }
101  /// Creates an anonymous function.
102  template <typename... Ts>
103  Function *createFunction(Ts &&... Args) {
104  auto *Func = new Function(*this, std::forward<Ts>(Args)...);
105  AnonFuncs.emplace_back(Func);
106  return Func;
107  }
108 
109  /// Returns a function.
110  Function *getFunction(const FunctionDecl *F);
111 
112  /// Returns a record or creates one if it does not exist.
113  Record *getOrCreateRecord(const RecordDecl *RD);
114 
115  /// Creates a descriptor for a primitive type.
117  bool IsConst = false,
118  bool IsTemporary = false,
119  bool IsMutable = false) {
120  return allocateDescriptor(D, Type, IsConst, IsTemporary, IsMutable);
121  }
122 
123  /// Creates a descriptor for a composite type.
124  Descriptor *createDescriptor(const DeclTy &D, const Type *Ty,
125  bool IsConst = false, bool IsTemporary = false,
126  bool IsMutable = false,
127  const Expr *Init = nullptr);
128 
129  /// Context to manage declaration lifetimes.
130  class DeclScope {
131  public:
132  DeclScope(Program &P, const VarDecl *VD) : P(P) { P.startDeclaration(VD); }
133  ~DeclScope() { P.endDeclaration(); }
134 
135  private:
136  Program &P;
137  };
138 
139  /// Returns the current declaration ID.
141  if (CurrentDeclaration == NoDeclaration)
142  return llvm::Optional<unsigned>{};
143  return LastDeclaration;
144  }
145 
146 private:
147  friend class DeclScope;
148 
150  bool IsStatic, bool IsExtern,
151  const Expr *Init = nullptr);
152 
153  /// Reference to the VM context.
154  Context &Ctx;
155  /// Mapping from decls to cached bytecode functions.
156  llvm::DenseMap<const FunctionDecl *, std::unique_ptr<Function>> Funcs;
157  /// List of anonymous functions.
158  std::vector<std::unique_ptr<Function>> AnonFuncs;
159 
160  /// Function relocation locations.
161  llvm::DenseMap<const FunctionDecl *, std::vector<unsigned>> Relocs;
162 
163  /// Native pointers referenced by bytecode.
164  std::vector<const void *> NativePointers;
165  /// Cached native pointer indices.
166  llvm::DenseMap<const void *, unsigned> NativePointerIndices;
167 
168  /// Custom allocator for global storage.
169  using PoolAllocTy = llvm::BumpPtrAllocatorImpl<llvm::MallocAllocator>;
170 
171  /// Descriptor + storage for a global object.
172  ///
173  /// Global objects never go out of scope, thus they do not track pointers.
174  class Global {
175  public:
176  /// Create a global descriptor for string literals.
177  template <typename... Tys>
178  Global(Tys... Args) : B(std::forward<Tys>(Args)...) {}
179 
180  /// Allocates the global in the pool, reserving storate for data.
181  void *operator new(size_t Meta, PoolAllocTy &Alloc, size_t Data) {
182  return Alloc.Allocate(Meta + Data, alignof(void *));
183  }
184 
185  /// Return a pointer to the data.
186  char *data() { return B.data(); }
187  /// Return a pointer to the block.
188  Block *block() { return &B; }
189 
190  private:
191  /// Required metadata - does not actually track pointers.
192  Block B;
193  };
194 
195  /// Allocator for globals.
196  PoolAllocTy Allocator;
197 
198  /// Global objects.
199  std::vector<Global *> Globals;
200  /// Cached global indices.
201  llvm::DenseMap<const void *, unsigned> GlobalIndices;
202 
203  /// Mapping from decls to record metadata.
204  llvm::DenseMap<const RecordDecl *, Record *> Records;
205 
206  /// Dummy parameter to generate pointers from.
207  llvm::DenseMap<const ParmVarDecl *, unsigned> DummyParams;
208 
209  /// Creates a new descriptor.
210  template <typename... Ts>
211  Descriptor *allocateDescriptor(Ts &&... Args) {
212  return new (Allocator) Descriptor(std::forward<Ts>(Args)...);
213  }
214 
215  /// No declaration ID.
216  static constexpr unsigned NoDeclaration = (unsigned)-1;
217  /// Last declaration ID.
218  unsigned LastDeclaration = 0;
219  /// Current declaration ID.
220  unsigned CurrentDeclaration = NoDeclaration;
221 
222  /// Starts evaluating a declaration.
223  void startDeclaration(const VarDecl *Decl) {
224  LastDeclaration += 1;
225  CurrentDeclaration = LastDeclaration;
226  }
227 
228  /// Ends a global declaration.
229  void endDeclaration() {
230  CurrentDeclaration = NoDeclaration;
231  }
232 
233 public:
234  /// Dumps the disassembled bytecode to \c llvm::errs().
235  void dump() const;
236  void dump(llvm::raw_ostream &OS) const;
237 };
238 
239 } // namespace interp
240 } // namespace clang
241 
242 #endif
Pointer.h
clang::interp::Program::createFunction
Function * createFunction(Ts &&... Args)
Creates an anonymous function.
Definition: Program.h:103
clang::interp::Program::DeclScope::~DeclScope
~DeclScope()
Definition: Program.h:133
clang::FunctionDecl::getCanonicalDecl
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3391
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:737
clang::interp::Program::DeclScope
Context to manage declaration lifetimes.
Definition: Program.h:130
clang::ParmVarDecl
Represents a parameter to a function.
Definition: Decl.h:1712
llvm::Optional< unsigned >
clang::interp::Context
Holds all information required to evaluate constexpr code in a module.
Definition: Context.h:35
clang::interp::Program::getCurrentDecl
llvm::Optional< unsigned > getCurrentDecl() const
Returns the current declaration ID.
Definition: Program.h:140
clang::interp::Program::~Program
~Program()
Definition: Program.h:44
clang::interp::Program::getFunction
Function * getFunction(const FunctionDecl *F)
Returns a function.
Definition: Program.cpp:206
clang::interp::Pointer
A pointer to a memory block, live or dead.
Definition: Pointer.h:36
clang::Type
The base class of the type hierarchy.
Definition: Type.h:1565
clang::interp::Program::getGlobal
Block * getGlobal(unsigned Idx)
Returns the value of a global.
Definition: Program.h:73
Source.h
clang::interp::Program::DeclScope::DeclScope
DeclScope(Program &P, const VarDecl *VD)
Definition: Program.h:132
clang::interp::Program::createDescriptor
Descriptor * createDescriptor(const DeclTy &D, PrimType Type, bool IsConst=false, bool IsTemporary=false, bool IsMutable=false)
Creates a descriptor for a primitive type.
Definition: Program.h:116
clang::interp::Block
A memory block, either on the stack or in the heap.
Definition: InterpBlock.h:35
clang::interp::PrimType
PrimType
Enumeration of the primitive types of the VM.
Definition: PrimType.h:28
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:906
clang::StringLiteral
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1776
PrimType.h
clang::interp::Program::getOrCreateNativePointer
unsigned getOrCreateNativePointer(const void *Ptr)
Marshals a native pointer to an ID for embedding in bytecode.
Definition: Program.cpp:21
clang::interp::Program::getOrCreateGlobal
llvm::Optional< unsigned > getOrCreateGlobal(const ValueDecl *VD)
Returns or creates a global an creates an index to it.
Definition: Program.cpp:127
clang::interp::Program::getOrCreateRecord
Record * getOrCreateRecord(const RecordDecl *RD)
Returns a record or creates one if it does not exist.
Definition: Program.cpp:213
clang::interp::Program::getPtrGlobal
Pointer getPtrGlobal(unsigned Idx)
Returns a pointer to a global.
Definition: Program.cpp:98
P
StringRef P
Definition: ASTMatchersInternal.cpp:563
clang::ValueDecl
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:701
clang::interp::Program::createGlobal
llvm::Optional< unsigned > createGlobal(const ValueDecl *VD, const Expr *E)
Creates a global and returns its index.
Definition: Program.cpp:157
clang::interp::Program::dump
void dump() const
Dumps the disassembled bytecode to llvm::errs().
Definition: Disasm.cpp:72
std
Definition: Format.h:4477
clang::interp::Program::getOrCreateDummy
llvm::Optional< unsigned > getOrCreateDummy(const ParmVarDecl *PD)
Returns or creates a dummy value for parameters.
Definition: Program.cpp:138
IsStatic
bool IsStatic
Definition: Format.cpp:2727
clang::interp::Descriptor
Describes a memory block created by an allocation site.
Definition: Descriptor.h:51
clang::interp::Program::Program
Program(Context &Ctx)
Definition: Program.h:42
clang
Definition: CalledOnceCheck.h:17
clang::interp::Program::createFunction
Function * createFunction(const FunctionDecl *Def, Ts &&... Args)
Creates a new function from a code range.
Definition: Program.h:95
Function.h
clang::interp::Function
Bytecode function.
Definition: Function.h:74
clang::DeclaratorContext::Block
@ Block
unsigned
clang::interp::DeclTy
unsigned llvm::PointerUnion< const Decl *, const Expr * > DeclTy
Definition: Descriptor.h:26
clang::interp::Program::createGlobalString
unsigned createGlobalString(const StringLiteral *S)
Emits a string literal among global data.
Definition: Program.cpp:36
clang::interp::Program
The program contains and links the bytecode for all functions.
Definition: Program.h:40
clang::Expr
This represents one expression.
Definition: Expr.h:109
clang::interp::Record
Structure/Class descriptor.
Definition: Record.h:24
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1904
clang::RecordDecl
Represents a struct/union/class.
Definition: Decl.h:3983
clang::interp::Program::getNativePointer
const void * getNativePointer(unsigned Idx)
Returns the value of a marshalled native pointer.
Definition: Program.cpp:32
Record.h