clang 18.0.0git
EvalEmitter.cpp
Go to the documentation of this file.
1//===--- EvalEmitter.cpp - Instruction emitter for the 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 "EvalEmitter.h"
10#include "ByteCodeGenError.h"
11#include "Context.h"
12#include "IntegralAP.h"
13#include "Interp.h"
14#include "Opcode.h"
15#include "clang/AST/DeclCXX.h"
16
17using namespace clang;
18using namespace clang::interp;
19
21 InterpStack &Stk, APValue &Result)
22 : Ctx(Ctx), P(P), S(Parent, P, Stk, Ctx, this), Result(Result) {
23 // Create a dummy frame for the interpreter which does not have locals.
24 S.Current =
25 new InterpFrame(S, /*Func=*/nullptr, /*Caller=*/nullptr, CodePtr());
26}
27
29 for (auto &[K, V] : Locals) {
30 Block *B = reinterpret_cast<Block *>(V.get());
31 if (B->isInitialized())
32 B->invokeDtor();
33 }
34}
35
37 if (this->visitExpr(E))
38 return true;
39 if (BailLocation)
40 return llvm::make_error<ByteCodeGenError>(*BailLocation);
41 return false;
42}
43
45 if (this->visitDecl(VD))
46 return true;
47 if (BailLocation)
48 return llvm::make_error<ByteCodeGenError>(*BailLocation);
49 return false;
50}
51
53 CurrentLabel = Label;
54}
55
57
59 // Allocate memory for a local.
60 auto Memory = std::make_unique<char[]>(sizeof(Block) + D->getAllocSize());
61 auto *B = new (Memory.get()) Block(D, /*isStatic=*/false);
62 B->invokeCtor();
63
64 // Initialize local variable inline descriptor.
65 InlineDescriptor &Desc = *reinterpret_cast<InlineDescriptor *>(B->rawData());
66 Desc.Desc = D;
67 Desc.Offset = sizeof(InlineDescriptor);
68 Desc.IsActive = true;
69 Desc.IsBase = false;
70 Desc.IsFieldMutable = false;
71 Desc.IsConst = false;
72 Desc.IsInitialized = false;
73
74 // Register the local.
75 unsigned Off = Locals.size();
76 Locals.insert({Off, std::move(Memory)});
77 return {Off, D};
78}
79
81 if (!BailLocation)
82 BailLocation = Loc;
83 return false;
84}
85
87 if (isActive()) {
88 if (S.Stk.pop<bool>())
89 ActiveLabel = Label;
90 }
91 return true;
92}
93
95 if (isActive()) {
96 if (!S.Stk.pop<bool>())
97 ActiveLabel = Label;
98 }
99 return true;
100}
101
103 if (isActive())
104 CurrentLabel = ActiveLabel = Label;
105 return true;
106}
107
109 if (isActive())
110 ActiveLabel = Label;
111 CurrentLabel = Label;
112 return true;
113}
114
115template <PrimType OpType> bool EvalEmitter::emitRet(const SourceInfo &Info) {
116 if (!isActive())
117 return true;
118 using T = typename PrimConv<OpType>::T;
119 return ReturnValue<T>(S.Stk.pop<T>(), Result);
120}
121
122bool EvalEmitter::emitRetVoid(const SourceInfo &Info) { return true; }
123
124bool EvalEmitter::emitRetValue(const SourceInfo &Info) {
125 // Method to recursively traverse composites.
126 std::function<bool(QualType, const Pointer &, APValue &)> Composite;
127 Composite = [this, &Composite](QualType Ty, const Pointer &Ptr, APValue &R) {
128 if (const auto *AT = Ty->getAs<AtomicType>())
129 Ty = AT->getValueType();
130
131 if (const auto *RT = Ty->getAs<RecordType>()) {
132 const auto *Record = Ptr.getRecord();
133 assert(Record && "Missing record descriptor");
134
135 bool Ok = true;
136 if (RT->getDecl()->isUnion()) {
137 const FieldDecl *ActiveField = nullptr;
139 for (const auto &F : Record->fields()) {
140 const Pointer &FP = Ptr.atField(F.Offset);
141 QualType FieldTy = F.Decl->getType();
142 if (FP.isActive()) {
143 if (std::optional<PrimType> T = Ctx.classify(FieldTy)) {
144 TYPE_SWITCH(*T, Ok &= ReturnValue<T>(FP.deref<T>(), Value));
145 } else {
146 Ok &= Composite(FieldTy, FP, Value);
147 }
148 break;
149 }
150 }
151 R = APValue(ActiveField, Value);
152 } else {
153 unsigned NF = Record->getNumFields();
154 unsigned NB = Record->getNumBases();
155 unsigned NV = Ptr.isBaseClass() ? 0 : Record->getNumVirtualBases();
156
157 R = APValue(APValue::UninitStruct(), NB, NF);
158
159 for (unsigned I = 0; I < NF; ++I) {
160 const Record::Field *FD = Record->getField(I);
161 QualType FieldTy = FD->Decl->getType();
162 const Pointer &FP = Ptr.atField(FD->Offset);
163 APValue &Value = R.getStructField(I);
164
165 if (std::optional<PrimType> T = Ctx.classify(FieldTy)) {
166 TYPE_SWITCH(*T, Ok &= ReturnValue<T>(FP.deref<T>(), Value));
167 } else {
168 Ok &= Composite(FieldTy, FP, Value);
169 }
170 }
171
172 for (unsigned I = 0; I < NB; ++I) {
173 const Record::Base *BD = Record->getBase(I);
174 QualType BaseTy = Ctx.getASTContext().getRecordType(BD->Decl);
175 const Pointer &BP = Ptr.atField(BD->Offset);
176 Ok &= Composite(BaseTy, BP, R.getStructBase(I));
177 }
178
179 for (unsigned I = 0; I < NV; ++I) {
180 const Record::Base *VD = Record->getVirtualBase(I);
181 QualType VirtBaseTy = Ctx.getASTContext().getRecordType(VD->Decl);
182 const Pointer &VP = Ptr.atField(VD->Offset);
183 Ok &= Composite(VirtBaseTy, VP, R.getStructBase(NB + I));
184 }
185 }
186 return Ok;
187 }
188
189 if (Ty->isIncompleteArrayType()) {
190 R = APValue(APValue::UninitArray(), 0, 0);
191 return true;
192 }
193
194 if (const auto *AT = Ty->getAsArrayTypeUnsafe()) {
195 const size_t NumElems = Ptr.getNumElems();
196 QualType ElemTy = AT->getElementType();
197 R = APValue(APValue::UninitArray{}, NumElems, NumElems);
198
199 bool Ok = true;
200 for (unsigned I = 0; I < NumElems; ++I) {
201 APValue &Slot = R.getArrayInitializedElt(I);
202 const Pointer &EP = Ptr.atIndex(I);
203 if (std::optional<PrimType> T = Ctx.classify(ElemTy)) {
204 TYPE_SWITCH(*T, Ok &= ReturnValue<T>(EP.deref<T>(), Slot));
205 } else {
206 Ok &= Composite(ElemTy, EP.narrow(), Slot);
207 }
208 }
209 return Ok;
210 }
211 llvm_unreachable("invalid value to return");
212 };
213
214 // Return the composite type.
215 const auto &Ptr = S.Stk.pop<Pointer>();
216 return Composite(Ptr.getType(), Ptr, Result);
217}
218
219bool EvalEmitter::emitGetPtrLocal(uint32_t I, const SourceInfo &Info) {
220 if (!isActive())
221 return true;
222
223 Block *B = getLocal(I);
224 S.Stk.push<Pointer>(B, sizeof(InlineDescriptor));
225 return true;
226}
227
228template <PrimType OpType>
229bool EvalEmitter::emitGetLocal(uint32_t I, const SourceInfo &Info) {
230 if (!isActive())
231 return true;
232
233 using T = typename PrimConv<OpType>::T;
234
235 Block *B = getLocal(I);
236 S.Stk.push<T>(*reinterpret_cast<T *>(B->data()));
237 return true;
238}
239
240template <PrimType OpType>
241bool EvalEmitter::emitSetLocal(uint32_t I, const SourceInfo &Info) {
242 if (!isActive())
243 return true;
244
245 using T = typename PrimConv<OpType>::T;
246
247 Block *B = getLocal(I);
248 *reinterpret_cast<T *>(B->data()) = S.Stk.pop<T>();
249 InlineDescriptor &Desc = *reinterpret_cast<InlineDescriptor *>(B->rawData());
250 Desc.IsInitialized = true;
251
252 return true;
253}
254
255bool EvalEmitter::emitDestroy(uint32_t I, const SourceInfo &Info) {
256 if (!isActive())
257 return true;
258
259 for (auto &Local : Descriptors[I]) {
260 Block *B = getLocal(Local.Offset);
261 S.deallocate(B);
262 }
263
264 return true;
265}
266
267//===----------------------------------------------------------------------===//
268// Opcode evaluators
269//===----------------------------------------------------------------------===//
270
271#define GET_EVAL_IMPL
272#include "Opcodes.inc"
273#undef GET_EVAL_IMPL
#define V(N, I)
Definition: ASTContext.h:3241
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
#define TYPE_SWITCH(Expr, B)
Definition: PrimType.h:109
std::string Label
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APValue & getArrayInitializedElt(unsigned I)
Definition: APValue.h:510
QualType getRecordType(const RecordDecl *Decl) const
This represents one expression.
Definition: Expr.h:110
Represents a member of a struct/union/class.
Definition: Decl.h:3015
A (possibly-)qualified type.
Definition: Type.h:736
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4969
Encodes a location in the source.
bool isIncompleteArrayType() const
Definition: Type.h:7105
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:7601
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7548
QualType getType() const
Definition: Decl.h:715
Represents a variable declaration or definition.
Definition: Decl.h:916
A memory block, either on the stack or in the heap.
Definition: InterpBlock.h:49
void invokeDtor()
Invokes the Destructor.
Definition: InterpBlock.h:115
std::byte * data()
Returns a pointer to the stored data.
Definition: InterpBlock.h:78
void invokeCtor()
Invokes the constructor.
Definition: InterpBlock.h:106
std::byte * rawData()
Returns a pointer to the raw data, including metadata.
Definition: InterpBlock.h:91
bool isInitialized() const
Definition: InterpBlock.h:74
Pointer into the code segment.
Definition: Source.h:30
Holds all information required to evaluate constexpr code in a module.
Definition: Context.h:40
ASTContext & getASTContext() const
Returns the AST context.
Definition: Context.h:58
std::optional< PrimType > classify(QualType T) const
Classifies an expression.
Definition: Context.cpp:91
bool jump(const LabelTy &Label)
virtual bool visitExpr(const Expr *E)=0
Methods implemented by the compiler.
EvalEmitter(Context &Ctx, Program &P, State &Parent, InterpStack &Stk, APValue &Result)
Definition: EvalEmitter.cpp:20
bool jumpFalse(const LabelTy &Label)
Definition: EvalEmitter.cpp:94
Local createLocal(Descriptor *D)
Callback for registering a local.
Definition: EvalEmitter.cpp:58
bool bail(const Stmt *S)
Definition: EvalEmitter.h:54
void emitLabel(LabelTy Label)
Define a label.
Definition: EvalEmitter.cpp:52
bool fallthrough(const LabelTy &Label)
LabelTy getLabel()
Create a label.
Definition: EvalEmitter.cpp:56
llvm::Expected< bool > interpretDecl(const VarDecl *VD)
Definition: EvalEmitter.cpp:44
llvm::Expected< bool > interpretExpr(const Expr *E)
Definition: EvalEmitter.cpp:36
llvm::SmallVector< SmallVector< Local, 8 >, 2 > Descriptors
Local descriptors.
Definition: EvalEmitter.h:79
virtual bool visitDecl(const VarDecl *VD)=0
bool jumpTrue(const LabelTy &Label)
Emits jumps.
Definition: EvalEmitter.cpp:86
Frame storing local variables.
Definition: InterpFrame.h:28
Stack frame storing temporaries and parameters.
Definition: InterpStack.h:26
T pop()
Returns the value from the top of the stack and removes it.
Definition: InterpStack.h:42
void push(Tys &&... Args)
Constructs a value in place on the top of the stack.
Definition: InterpStack.h:34
InterpStack & Stk
Temporary stack.
Definition: InterpState.h:109
InterpFrame * Current
The current frame.
Definition: InterpState.h:113
void deallocate(Block *B)
Deallocates a pointer.
Definition: InterpState.cpp:48
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
bool isActive() const
Checks if the object is active.
Definition: Pointer.h:323
Pointer atField(unsigned Off) const
Creates a pointer to a field.
Definition: Pointer.h:116
T & deref() const
Dereferences the pointer, if it's live.
Definition: Pointer.h:375
The program contains and links the bytecode for all functions.
Definition: Program.h:40
Structure/Class descriptor.
Definition: Record.h:25
unsigned getNumBases() const
Definition: Record.h:90
const Field * getField(const FieldDecl *FD) const
Returns a field.
Definition: Record.cpp:30
const Base * getVirtualBase(const RecordDecl *RD) const
Returns a virtual base descriptor.
Definition: Record.cpp:50
unsigned getNumFields() const
Definition: Record.h:81
unsigned getNumVirtualBases() const
Definition: Record.h:101
llvm::iterator_range< const_field_iter > fields() const
Definition: Record.h:77
const Base * getBase(const RecordDecl *FD) const
Returns a base descriptor.
Definition: Record.cpp:36
Describes the statement/declaration an opcode was generated from.
Definition: Source.h:72
Interface for the VM to interact with the AST walker's context.
Definition: State.h:55
#define bool
Definition: stdbool.h:20
Describes a memory block created by an allocation site.
Definition: Descriptor.h:79
unsigned getAllocSize() const
Returns the allocated size, including metadata.
Definition: Descriptor.h:172
Inline descriptor embedded in structures and arrays.
Definition: Descriptor.h:56
unsigned IsActive
Flag indicating if the field is the active member of a union.
Definition: Descriptor.h:71
unsigned IsBase
Flag indicating if the field is an embedded base class.
Definition: Descriptor.h:69
const Descriptor * Desc
Definition: Descriptor.h:75
unsigned Offset
Offset inside the structure/array.
Definition: Descriptor.h:58
unsigned IsInitialized
For primitive fields, it indicates if the field was initialized.
Definition: Descriptor.h:67
unsigned IsConst
Flag indicating if the storage is constant or not.
Definition: Descriptor.h:62
unsigned IsFieldMutable
Flag indicating if the field is mutable (if in a record).
Definition: Descriptor.h:73
Mapping from primitive types to their representation.
Definition: PrimType.h:65
Describes a base class.
Definition: Record.h:36
const RecordDecl * Decl
Definition: Record.h:37
Describes a record field.
Definition: Record.h:28
const FieldDecl * Decl
Definition: Record.h:29
Information about a local's storage.
Definition: Function.h:37
unsigned Offset
Offset of the local in frame.
Definition: Function.h:39