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 "IntegralAP.h"
12#include "Interp.h"
13#include "clang/AST/DeclCXX.h"
14#include "clang/AST/ExprCXX.h"
15#include "llvm/ADT/ScopeExit.h"
16
17using namespace clang;
18using namespace clang::interp;
19
22 ConstantExprKind ConstexprKind)
23 : Ctx(Ctx), P(P), S(Parent, P, Stk, FA, Ctx, this), EvalResult(Ctx),
24 ConstexprKind(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.isPastEnd())
286 return false;
287
288 if (!Ptr.isZero() && !CheckFinalLoad(S, CodePtr(), Ptr))
289 return false;
290
291 // Never allow reading from a non-const pointer, unless the memory
292 // has been created in this evaluation.
293 if (!Ptr.isZero() && !Ptr.isConst() && Ptr.isBlockPointer() &&
294 Ptr.block()->getEvalID() != Ctx.getEvalID())
295 return false;
296
297 if (!EvalResult.checkLValueFields(S, Ptr, Info, ConstexprKind))
298 return false;
299
300 if (std::optional<APValue> V =
301 Ptr.toRValue(Ctx, EvalResult.getSourceType())) {
302 EvalResult.takeValue(std::move(*V));
303 return true;
304 }
305 return false;
306 }
307
308 // Return as lvalue.
309 if (!EvalResult.checkLValue(S, Ptr, Info, ConstexprKind))
310 return false;
311
312 if (!Ptr.isLive() && !Ptr.isTemporary())
313 return false;
314
315 if (const Descriptor *DeclDesc = Ptr.getDeclDesc();
316 DeclDesc && S.EvaluatingDecl &&
317 ((DeclDesc->asVarDecl() == S.EvaluatingDecl &&
318 S.getLangOpts().CPlusPlus23 &&
319 S.EvaluatingDecl->getType()->isReferenceType()) ||
320 DeclDesc->IsConstexprUnknown)) {
321 S.FFDiag(Info, diag::note_constexpr_var_init_non_constant, 1)
322 << DeclDesc->asVarDecl();
323 S.Note(DeclDesc->asVarDecl()->getLocation(), diag::note_declared_at);
324
325 return false;
326 }
327
328 APValue V = Ptr.toAPValue(Ctx.getASTContext());
329 EvalResult.takeValue(std::move(V));
330 return true;
331}
332
333bool EvalEmitter::emitRetVoid(SourceInfo Info) {
334 EvalResult.setValid();
335 return true;
336}
337
338bool EvalEmitter::emitRetValue(SourceInfo Info) {
339 const auto &Ptr = S.Stk.pop<Pointer>();
340
341 if (!EvalResult.checkDynamicAllocations(S, Ptr, Info))
342 return false;
343 if (CheckFullyInitialized && !EvalResult.checkFullyInitialized(S, Ptr))
344 return false;
345 if (!EvalResult.checkLValueFields(S, Ptr, Info, ConstexprKind))
346 return false;
347
348 if (std::optional<APValue> APV =
349 Ptr.toRValue(Ctx, EvalResult.getSourceType())) {
350 EvalResult.takeValue(std::move(*APV));
351 return true;
352 }
353
354 EvalResult.setInvalid();
355 return false;
356}
357
358bool EvalEmitter::emitGetPtrLocal(uint32_t I, SourceInfo Info) {
359 if (!isActive())
360 return true;
361
362 Block *B = getLocal(I);
363 S.Stk.push<Pointer>(B, sizeof(InlineDescriptor));
364 return true;
365}
366
367bool EvalEmitter::emitGetRefLocal(uint32_t I, SourceInfo Info) {
368 if (!isActive())
369 return true;
370
371 Block *B = getLocal(I);
372 return handleReference(S, CodePtr(), B);
373}
374
375template <PrimType OpType>
376bool EvalEmitter::emitGetLocal(uint32_t I, SourceInfo Info) {
377 if (!isActive())
378 return true;
379
380 using T = typename PrimConv<OpType>::T;
381
382 Block *B = getLocal(I);
383
384 if (!CheckLocalLoad(S, CodePtr(), B))
385 return false;
386
387 S.Stk.push<T>(B->deref<T>());
388 return true;
389}
390
391template <PrimType OpType>
392bool EvalEmitter::emitSetLocal(uint32_t I, SourceInfo Info) {
393 if (!isActive())
394 return true;
395
396 using T = typename PrimConv<OpType>::T;
397
398 Block *B = getLocal(I);
399 B->deref<T>() = S.Stk.pop<T>();
400 auto &Desc = B->getBlockDesc<InlineDescriptor>();
401 Desc.IsInitialized = true;
402 Desc.LifeState = Lifetime::Started;
403
404 return true;
405}
406
407bool EvalEmitter::emitDestroy(uint32_t I, SourceInfo Info) {
408 if (!isActive())
409 return true;
410
411 for (auto &Local : Descriptors[I]) {
412 Block *B = getLocal(Local.Offset);
413 S.deallocate(B);
414 }
415
416 return true;
417}
418
419bool EvalEmitter::emitGetLocalEnabled(uint32_t I, SourceInfo Info) {
420 if (!isActive())
421 return true;
422
423 Block *B = getLocal(I);
424 const auto &Desc = B->getBlockDesc<InlineDescriptor>();
425
426 S.Stk.push<bool>(Desc.IsActive);
427 return true;
428}
429
430bool EvalEmitter::emitEnableLocal(uint32_t I, SourceInfo Info) {
431 if (!isActive())
432 return true;
433
434 // FIXME: This is a little dirty, but to avoid adding a flag to
435 // InlineDescriptor that's only ever useful on the toplevel of local
436 // variables, we reuse the IsActive flag for the enabled state. We should
437 // probably use a different struct than InlineDescriptor for the block-level
438 // inline descriptor of local varaibles.
439 Block *B = getLocal(I);
440 auto &Desc = B->getBlockDesc<InlineDescriptor>();
441 Desc.IsActive = true;
442 return true;
443}
444
445/// Global temporaries (LifetimeExtendedTemporary) carry their value
446/// around as an APValue, which codegen accesses.
447/// We set their value once when creating them, but we don't update it
448/// afterwards when code changes it later.
449/// This is what we do here.
450void EvalEmitter::updateGlobalTemporaries() {
451 for (const auto &[E, Temp] : S.SeenGlobalTemporaries) {
452 UnsignedOrNone GlobalIndex = P.getGlobal(E);
453 assert(GlobalIndex);
454 const Pointer &Ptr = P.getPtrGlobal(*GlobalIndex);
455 APValue *Cached = Temp->getOrCreateValue(true);
456
457 QualType TempType = E->getType();
458 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
459 TempType = MTE->getSubExpr()->skipRValueSubobjectAdjustments()->getType();
460
461 if (OptPrimType T = Ctx.classify(TempType)) {
462 TYPE_SWITCH(*T,
463 { *Cached = Ptr.deref<T>().toAPValue(Ctx.getASTContext()); });
464 } else {
465 if (std::optional<APValue> APV = Ptr.toRValue(Ctx, TempType))
466 *Cached = *APV;
467 }
468 }
469 S.SeenGlobalTemporaries.clear();
470}
471
472//===----------------------------------------------------------------------===//
473// Opcode evaluators
474//===----------------------------------------------------------------------===//
475
476#define GET_EVAL_IMPL
477#include "Opcodes.inc"
478#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:235
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:123
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
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:3722
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:48
ASTContext & getASTContext() const
Returns the AST context.
Definition Context.h:109
EvalEmitter(Context &Ctx, Program &P, State &Parent, InterpStack &Stk, FrameAllocator &FrameAlloc, ConstantExprKind ConstexprKind=ConstantExprKind::Normal)
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)
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:25
T pop()
Returns the value from the top of the stack and removes it.
Definition InterpStack.h:39
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:37
Describes the statement/declaration an opcode was generated from.
Definition Source.h:77
Interface for the VM to interact with the AST walker's context.
Definition State.h:79
bool PushIgnoreDiags(InterpState &S)
Definition Interp.h:3723
bool PopIgnoreDiags(InterpState &S)
Definition Interp.h:3735
bool handleReference(InterpState &S, CodePtr OpPC, Block *B)
Definition Interp.cpp:3070
bool CheckBCPResult(InterpState &S, const Pointer &Ptr)
Definition Interp.cpp:353
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3228
bool CheckFinalLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
This is not used by any of the opcodes directly.
Definition Interp.cpp:1072
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:34
bool Init(InterpState &S, CodePtr OpPC)
Definition Interp.h:2425
bool CheckLocalLoad(InterpState &S, CodePtr OpPC, const Block *B)
Definition Interp.cpp:929
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1062
@ 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.
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
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:122
const bool IsConst
Flag indicating if the block is mutable.
Definition Descriptor.h:154
unsigned getAllocSize() const
Returns the allocated size, including metadata.
Definition Descriptor.h:237
Inline descriptor embedded in structures and arrays.
Definition Descriptor.h:67
Mapping from primitive types to their representation.
Definition PrimType.h:162
Information about a local's storage.
Definition Function.h:38