clang 24.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 "Context.h"
11#include "EvalSettings.h"
12#include "IntegralAP.h"
13#include "Interp.h"
14#include "clang/AST/DeclCXX.h"
15#include "clang/AST/ExprCXX.h"
16#include "llvm/ADT/ScopeExit.h"
17
18using namespace clang;
19using namespace clang::interp;
20
23 : Ctx(Ctx), P(P), S(Settings, P, Stk, FA, Ctx, this), EvalResult(Ctx),
24 ConstexprKind(Settings.ConstexprKind) {}
25
28 : Ctx(Ctx), P(P), S(Status, P, Stk, FA, Ctx, this), EvalResult(Ctx) {}
29
30/// Clean up all our resources. This needs to done in failed evaluations before
31/// we call InterpStack::clear(), because there might be a Pointer on the stack
32/// pointing into a Block in the EvalEmitter.
33void EvalEmitter::cleanup() { S.cleanup(); }
34
36 bool ConvertResultToRValue,
37 bool DestroyToplevelScope) {
38 S.setEvalLocation(E->getExprLoc());
39 this->ConvertResultToRValue = ConvertResultToRValue && !isa<ConstantExpr>(E);
40 this->CheckFullyInitialized = isa<ConstantExpr>(E) && !E->isGLValue();
41 EvalResult.setSource(E);
42
43 if (!this->visitExpr(E, DestroyToplevelScope)) {
44 // EvalResult may already have a result set, but something failed
45 // after that (e.g. evaluating destructors).
46 EvalResult.setInvalid();
47 }
48
49 return std::move(this->EvalResult);
50}
51
53 bool CheckFullyInitialized) {
54 assert(VD);
55 assert(Init);
56 this->CheckFullyInitialized = CheckFullyInitialized;
57 S.EvaluatingDecl = VD;
58 S.setEvalLocation(VD->getLocation());
59 EvalResult.setSource(VD);
60
61 QualType T = VD->getType();
62 this->ConvertResultToRValue = !Init->isGLValue() && !T->isPointerType() &&
63 !T->isObjCObjectPointerType();
64
65 if (!this->visitDeclAndReturn(VD, Init, S.inConstantContext()))
66 EvalResult.setInvalid();
67
68 S.EvaluatingDecl = nullptr;
69 updateGlobalTemporaries();
70 return std::move(this->EvalResult);
71}
72
74 const APValue &Value) {
75 assert(VD);
76 S.setEvalLocation(VD->getLocation());
77 S.EvaluatingDecl = VD;
78 S.EvalKind = EvaluationKind::Dtor;
79 EvalResult.setSource(VD);
80
81 if (!this->visitDtorCall(VD, Value))
82 EvalResult.setInvalid();
83
84 S.EvaluatingDecl = nullptr;
85 return std::move(this->EvalResult);
86}
87
89 PtrCallback PtrCB) {
90 S.setEvalLocation(E->getExprLoc());
91 this->ConvertResultToRValue = false;
92 this->CheckFullyInitialized = false;
93 this->PtrCB = PtrCB;
94 EvalResult.setSource(E);
95
96 if (!this->visitExpr(E, true)) {
97 // EvalResult may already have a result set, but something failed
98 // after that (e.g. evaluating destructors).
99 EvalResult.setInvalid();
100 }
101
102 return std::move(this->EvalResult);
103}
104
106 PtrCallback PtrCB) {
107 S.setEvalLocation(E->getExprLoc());
108 this->ConvertResultToRValue = false;
109 this->CheckFullyInitialized = false;
110 this->PtrCB = PtrCB;
111 EvalResult.setSource(E);
112
113 if (!this->visitLValueExpr(E, true))
114 EvalResult.setInvalid();
115
116 return std::move(this->EvalResult);
117}
118
120 // Add parameters to the parameter map. The values in the ParamOffset don't
121 // matter in this case as reading from them can't ever work.
122 for (const ParmVarDecl *PD : FD->parameters()) {
123 this->Params.insert({PD, {0, false}});
124 }
125
126 return this->visitExpr(E, /*DestroyToplevelScope=*/false);
127}
128
130 const FunctionDecl *Callee, ArrayRef<const Expr *> Args, const Expr *This,
131 const Expr *Condition) {
132
133 if (!this->visitWithSubstitutions(Callee, Args, This, Condition))
134 return std::nullopt;
135
136 if (EvalResult.empty() || EvalResult.isInvalid())
137 return false;
138
139 assert(!EvalResult.empty());
140 APValue Result = EvalResult.stealAPValue();
141
142 assert(Result.isInt());
143 return Result.getInt().getBoolValue();
144}
145
146void EvalEmitter::emitLabel(LabelTy Label) { CurrentLabel = Label; }
147
149
151 // Allocate memory for a local.
152 char *Memory = reinterpret_cast<char *>(
153 S.allocate(sizeof(Block) + D->getAllocSize() + Block::InlineDescMD));
154 auto *B = new (Memory) Block(Ctx.getEvalID(), D, Block::InlineDescMD,
155 /*IsStatic=*/false);
156 B->invokeCtor();
157
158 // Initialize local variable inline descriptor.
159 auto &Desc = B->getBlockDesc<InlineDescriptor>();
160 Desc.Desc = D;
161 Desc.Offset = sizeof(InlineDescriptor);
162 Desc.IsActive = false;
163 Desc.IsBase = false;
164 Desc.IsFieldMutable = false;
165 Desc.IsConst = false;
166 Desc.IsInitialized = false;
167
168 // Register the local.
169 unsigned Off = Locals.size();
170 Locals.push_back(Memory);
171 return {D, Off};
172}
173
175 if (isActive()) {
176 CurrentSource = SI;
177 if (S.Stk.pop<bool>())
178 ActiveLabel = Label;
179 }
180 return true;
181}
182
184 if (isActive()) {
185 CurrentSource = SI;
186 if (!S.Stk.pop<bool>())
187 ActiveLabel = Label;
188 }
189 return true;
190}
191
192bool EvalEmitter::jump(const LabelTy &Label, SourceInfo SI) {
193 if (isActive()) {
194 CurrentSource = SI;
195 CurrentLabel = ActiveLabel = Label;
196 }
197 return true;
198}
199
201 if (isActive())
202 ActiveLabel = Label;
203 CurrentLabel = Label;
204 return true;
205}
206
207bool EvalEmitter::speculate(const CallExpr *E, const LabelTy &EndLabel) {
208 if (!isActive())
209 return true;
210
212 auto _ = llvm::scope_exit([&]() { PopIgnoreDiags(S); });
213
214 size_t StackSizeBefore = S.Stk.size();
215 const Expr *Arg = E->getArg(0);
216 if (!this->visit(Arg)) {
217 S.Stk.clearTo(StackSizeBefore);
218
219 if (S.inConstantContext() || Arg->HasSideEffects(S.getASTContext()))
220 return this->emitBool(false, E);
221 return Invalid(S, CodePtr());
222 }
223
224 PrimType T = Ctx.classify(Arg->getType()).value_or(PT_Ptr);
225 if (T == PT_Ptr) {
226 const auto &Ptr = S.Stk.pop<Pointer>();
227 return this->emitBool(CheckBCPResult(S, Ptr), E);
228 }
229
230 // Otherwise, this is fine!
231 if (!this->emitPop(T, E))
232 return false;
233 return this->emitBool(true, E);
234}
235
236template <PrimType OpType> bool EvalEmitter::emitRet(SourceInfo Info) {
237 if (!isActive())
238 return true;
239
240 using T = typename PrimConv<OpType>::T;
241 EvalResult.takeValue(S.Stk.pop<T>().toAPValue(Ctx.getASTContext()));
242 return true;
243}
244
245template <> bool EvalEmitter::emitRet<PT_MemberPtr>(SourceInfo Info) {
246 if (!isActive())
247 return true;
248
249 const MemberPointer &MP = S.Stk.pop<MemberPointer>();
250 if (!EvalResult.checkMemberPointer(S, MP, Info, ConstexprKind))
251 return false;
252
253 EvalResult.takeValue(MP.toAPValue(Ctx.getASTContext()));
254 return true;
255}
256
257template <> bool EvalEmitter::emitRet<PT_Ptr>(SourceInfo Info) {
258 if (!isActive())
259 return true;
260
261 const Pointer &Ptr = S.Stk.pop<Pointer>();
262 // If we're returning a raw pointer, call our callback.
263 if (this->PtrCB)
264 return (*this->PtrCB)(S, CodePtr(), Ptr);
265
266 if (!EvalResult.checkDynamicAllocations(S, Ptr, Info))
267 return false;
268
269 if (CheckFullyInitialized && !EvalResult.checkFullyInitialized(S, Ptr))
270 return false;
271
272 // Function pointers are always returned as lvalues.
273 if (Ptr.isFunctionPointer()) {
274 if (ConvertResultToRValue && Ptr.asFunctionPointer().Func->getDecl())
275 return false;
276 if (!EvalResult.checkFunctionPointer(S, Ptr, Info, ConstexprKind))
277 return false;
278
279 EvalResult.takeValue(Ptr.toAPValue(Ctx.getASTContext()));
280 return true;
281 }
282
283 // Implicitly convert lvalue to rvalue, if requested.
284 if (ConvertResultToRValue) {
285 if (!Ptr.isZero() && !CheckFinalLoad(S, CodePtr(), Ptr))
286 return false;
287
288 if (!EvalResult.checkLValueFields(S, Ptr, Info, ConstexprKind))
289 return false;
290
291 if (std::optional<APValue> V =
292 Ptr.toRValue(Ctx, EvalResult.getSourceType())) {
293 EvalResult.takeValue(std::move(*V));
294 return true;
295 }
296 return false;
297 }
298
299 // Return as lvalue.
300 if (!EvalResult.checkLValue(S, Ptr, Info, ConstexprKind))
301 return false;
302
303 if (!Ptr.isLive() && !Ptr.isTemporary())
304 return false;
305
306 if (const Descriptor *DeclDesc = Ptr.getDeclDesc();
307 DeclDesc && S.EvaluatingDecl &&
308 ((DeclDesc->asVarDecl() == S.EvaluatingDecl &&
309 S.getLangOpts().CPlusPlus23 &&
310 S.EvaluatingDecl->getType()->isReferenceType()) ||
311 DeclDesc->IsConstexprUnknown)) {
312 S.FFDiag(Info, diag::note_constexpr_var_init_non_constant, 1)
313 << DeclDesc->asVarDecl();
314 S.Note(DeclDesc->asVarDecl()->getLocation(), diag::note_declared_at);
315
316 return false;
317 }
318
319 APValue V = Ptr.toAPValue(Ctx.getASTContext());
320 EvalResult.takeValue(std::move(V));
321 return true;
322}
323
324bool EvalEmitter::emitRetVoid(SourceInfo Info) {
325 EvalResult.setValid();
326 return true;
327}
328
329bool EvalEmitter::emitRetValue(SourceInfo Info) {
330 const auto &Ptr = S.Stk.pop<Pointer>();
331
332 if (!EvalResult.checkDynamicAllocations(S, Ptr, Info))
333 return false;
334 if (CheckFullyInitialized && !EvalResult.checkFullyInitialized(S, Ptr))
335 return false;
336 if (!EvalResult.checkLValueFields(S, Ptr, Info, ConstexprKind))
337 return false;
338
339 if (std::optional<APValue> APV =
340 Ptr.toRValue(Ctx, EvalResult.getSourceType())) {
341 EvalResult.takeValue(std::move(*APV));
342 return true;
343 }
344
345 EvalResult.setInvalid();
346 return false;
347}
348
349bool EvalEmitter::emitGetPtrLocal(uint32_t I, SourceInfo Info) {
350 if (!isActive())
351 return true;
352
353 Block *B = getLocal(I);
354 S.Stk.push<Pointer>(B, sizeof(InlineDescriptor));
355 return true;
356}
357
358bool EvalEmitter::emitGetRefLocal(uint32_t I, SourceInfo Info) {
359 if (!isActive())
360 return true;
361
362 Block *B = getLocal(I);
363 return handleReference(S, CodePtr(), B);
364}
365
366template <PrimType OpType>
367bool EvalEmitter::emitGetLocal(uint32_t I, SourceInfo Info) {
368 if (!isActive())
369 return true;
370
371 using T = typename PrimConv<OpType>::T;
372
373 Block *B = getLocal(I);
374
375 if (!CheckLocalLoad(S, CodePtr(), B))
376 return false;
377
378 S.Stk.push<T>(B->deref<T>());
379 return true;
380}
381
382template <PrimType OpType>
383bool EvalEmitter::emitSetLocal(uint32_t I, SourceInfo Info) {
384 if (!isActive())
385 return true;
386
387 using T = typename PrimConv<OpType>::T;
388
389 Block *B = getLocal(I);
390 B->deref<T>() = S.Stk.pop<T>();
391 auto &Desc = B->getBlockDesc<InlineDescriptor>();
392 Desc.IsInitialized = true;
393 Desc.LifeState = Lifetime::Started;
394
395 return true;
396}
397
398bool EvalEmitter::emitDestroy(uint32_t I, SourceInfo Info) {
399 if (!isActive())
400 return true;
401
402 for (auto &Local : Descriptors[I]) {
403 Block *B = getLocal(Local.Offset);
404 S.deallocate(B);
405 }
406
407 return true;
408}
409
410bool EvalEmitter::emitGetLocalEnabled(uint32_t I, SourceInfo Info) {
411 if (!isActive())
412 return true;
413
414 Block *B = getLocal(I);
415 const auto &Desc = B->getBlockDesc<InlineDescriptor>();
416
417 S.Stk.push<bool>(Desc.IsActive);
418 return true;
419}
420
421bool EvalEmitter::emitEnableLocal(uint32_t I, SourceInfo Info) {
422 if (!isActive())
423 return true;
424
425 // FIXME: This is a little dirty, but to avoid adding a flag to
426 // InlineDescriptor that's only ever useful on the toplevel of local
427 // variables, we reuse the IsActive flag for the enabled state. We should
428 // probably use a different struct than InlineDescriptor for the block-level
429 // inline descriptor of local varaibles.
430 Block *B = getLocal(I);
431 auto &Desc = B->getBlockDesc<InlineDescriptor>();
432 Desc.IsActive = true;
433 return true;
434}
435
436/// Global temporaries (LifetimeExtendedTemporary) carry their value
437/// around as an APValue, which codegen accesses.
438/// We set their value once when creating them, but we don't update it
439/// afterwards when code changes it later.
440/// This is what we do here.
441void EvalEmitter::updateGlobalTemporaries() {
442 for (const auto &[E, Temp] : S.SeenGlobalTemporaries) {
443 UnsignedOrNone GlobalIndex = P.getGlobal(E);
444 assert(GlobalIndex);
445 const Pointer &Ptr = P.getPtrGlobal(*GlobalIndex);
446 APValue *Cached = Temp->getOrCreateValue(true);
447
448 QualType TempType = E->getType();
449 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
450 TempType = MTE->getSubExpr()->skipRValueSubobjectAdjustments()->getType();
451
452 if (OptPrimType T = Ctx.classify(TempType)) {
453 TYPE_SWITCH(*T,
454 { *Cached = Ptr.deref<T>().toAPValue(Ctx.getASTContext()); });
455 } else {
456 if (std::optional<APValue> APV = Ptr.toRValue(Ctx, TempType))
457 *Cached = *APV;
458 }
459 }
460 S.SeenGlobalTemporaries.clear();
461}
462
463//===----------------------------------------------------------------------===//
464// Opcode evaluators
465//===----------------------------------------------------------------------===//
466
467#define GET_EVAL_IMPL
468#include "Opcodes.inc"
469#undef GET_EVAL_IMPL
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value)
Check that this evaluated value is fully-initialized and can be loaded by an lvalue-to-rvalue convers...
#define TYPE_SWITCH(Expr, B)
Definition PrimType.h:240
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2991
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3195
SourceLocation getLocation() const
Definition DeclBase.h:447
This represents one expression.
Definition Expr.h:113
bool isGLValue() const
Definition Expr.h:288
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3728
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:145
Represents a function declaration or definition.
Definition Decl.h:2059
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
Represents a parameter to a function.
Definition Decl.h:1820
A (possibly-)qualified type.
Definition TypeBase.h:938
QualType getType() const
Definition Decl.h:724
Represents a variable declaration or definition.
Definition Decl.h:933
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:43
const T & deref() const
static constexpr uint8_t InlineDescMD
Definition InterpBlock.h:50
Pointer into the code segment.
Definition Source.h:31
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:49
ASTContext & getASTContext() const
Returns the AST context.
Definition Context.h:116
llvm::DenseMap< const ParmVarDecl *, FuncParam > Params
Parameter indices.
EvaluationResult interpretDecl(const VarDecl *VD, const Expr *Init, bool CheckFullyInitialized)
EvaluationResult interpretDestructor(const VarDecl *VD, const APValue &Value)
bool jump(const LabelTy &Label, SourceInfo SI)
virtual bool visit(const Expr *E)=0
bool speculate(const CallExpr *E, const LabelTy &EndLabel)
Speculative execution.
Local createLocal(const Descriptor *D)
Callback for registering a local.
std::optional< bool > interpretWithSubstitutions(const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This, const Expr *Condition)
virtual bool visitDtorCall(const VarDecl *VD, const APValue &Value)=0
bool jumpFalse(const LabelTy &Label, SourceInfo SI)
EvalEmitter(Context &Ctx, Program &P, const EvalSettings &Settings, InterpStack &Stk, FrameAllocator &FrameAlloc)
bool interpretCall(const FunctionDecl *FD, const Expr *E)
Interpret the given expression as if it was in the body of the given function, i.e.
void emitLabel(LabelTy Label)
Define a label.
EvaluationResult interpretExpr(const Expr *E)
Definition EvalEmitter.h:40
bool isActive() const
Since expressions can only jump forward, predicated execution is used to deal with if-else statements...
virtual bool visitWithSubstitutions(const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This, const Expr *Condition)=0
EvaluationResult interpretAsLValuePointer(const Expr *E, PtrCallback PtrCB)
virtual bool visitExpr(const Expr *E, bool DestroyToplevelScope)=0
Methods implemented by the compiler.
bool fallthrough(const LabelTy &Label)
virtual bool visitDeclAndReturn(const VarDecl *VD, const Expr *Init, bool ConstantContext)=0
void cleanup()
Clean up all resources.
LabelTy getLabel()
Create a label.
EvaluationResult interpretAsPointer(const Expr *E, PtrCallback PtrCB)
Interpret the given Expr to a Pointer.
llvm::SmallVector< SmallVector< Local, 2 >, 1 > Descriptors
Local descriptors.
virtual bool emitBool(bool V, const Expr *E)=0
bool jumpTrue(const LabelTy &Label, SourceInfo SI)
Emits jumps.
virtual bool visitLValueExpr(const Expr *E, bool DestroyToplevelScope)=0
llvm::function_ref< bool(InterpState &S, CodePtr OpPC, const Pointer &)> PtrCallback
Definition EvalEmitter.h:37
Defines the result of an evaluation.
static bool checkMemberPointer(InterpState &S, const MemberPointer &MemberPtr, SourceInfo Info, ConstantExprKind ConstexprKind)
Check if the given member pointer can be returned from an evaluation.
bool checkFunctionPointer(InterpState &S, const Pointer &Ptr, SourceInfo Info, ConstantExprKind ConstexprKind) const
Check if the given function pointer can be returned from an evaluation.
bool checkDynamicAllocations(InterpState &S, const Pointer &Ptr, SourceInfo Info) const
Check that none of the blocks the given pointer (transitively) points to are dynamically allocated.
bool checkFullyInitialized(InterpState &S, const Pointer &Ptr) const
Check that all subobjects of the given pointer have been initialized.
Allocator for function frames.
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:40
InterpStack & Stk
Temporary stack.
APValue toAPValue(const ASTContext &) const
A pointer to a memory block, live or dead.
Definition Pointer.h:546
The program contains and links the bytecode for all functions.
Definition Program.h:38
Describes the statement/declaration an opcode was generated from.
Definition Source.h:77
bool PushIgnoreDiags(InterpState &S)
Definition Interp.h:3718
bool PopIgnoreDiags(InterpState &S)
Definition Interp.h:3730
bool handleReference(InterpState &S, CodePtr OpPC, Block *B)
Definition Interp.cpp:3051
bool CheckBCPResult(InterpState &S, const Pointer &Ptr)
Definition Interp.cpp:351
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3223
bool CheckFinalLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
This is not used by any of the opcodes directly.
Definition Interp.cpp:1043
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:35
bool Init(InterpState &S, CodePtr OpPC)
Definition Interp.h:2420
bool CheckLocalLoad(InterpState &S, CodePtr OpPC, const Block *B)
Definition Interp.cpp:900
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ Result
The result type of a method or function.
Definition TypeBase.h:906
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
@ Off
Never emit colors regardless of the output stream.
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition Expr.h:622
Describes a memory block created by an allocation site.
Definition Descriptor.h:123
const bool IsConst
Flag indicating if the block is mutable.
Definition Descriptor.h:155
unsigned getAllocSize() const
Returns the allocated size, including metadata.
Definition Descriptor.h:238
Inline descriptor embedded in structures and arrays.
Definition Descriptor.h:68
Mapping from primitive types to their representation.
Definition PrimType.h:164
Information about a local's storage.
Definition Function.h:38