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
20EvalEmitter::EvalEmitter(Context &Ctx, Program &P, State &Parent,
21 InterpStack &Stk, FrameAllocator &FA)
22 : Ctx(Ctx), P(P), S(Parent, P, Stk, FA, Ctx, this), EvalResult(&Ctx) {}
23
24/// Clean up all our resources. This needs to done in failed evaluations before
25/// we call InterpStack::clear(), because there might be a Pointer on the stack
26/// pointing into a Block in the EvalEmitter.
27void EvalEmitter::cleanup() { S.cleanup(); }
28
29EvaluationResult EvalEmitter::interpretExpr(const Expr *E,
30 bool ConvertResultToRValue,
31 bool DestroyToplevelScope) {
32 S.setEvalLocation(E->getExprLoc());
33 this->ConvertResultToRValue = ConvertResultToRValue && !isa<ConstantExpr>(Val: E);
34 this->CheckFullyInitialized = isa<ConstantExpr>(Val: E) && !E->isGLValue();
35 EvalResult.setSource(E);
36
37 if (!this->visitExpr(E, DestroyToplevelScope)) {
38 // EvalResult may already have a result set, but something failed
39 // after that (e.g. evaluating destructors).
40 EvalResult.setInvalid();
41 }
42
43 return std::move(this->EvalResult);
44}
45
46EvaluationResult EvalEmitter::interpretDecl(const VarDecl *VD, const Expr *Init,
47 bool CheckFullyInitialized) {
48 assert(VD);
49 assert(Init);
50 this->CheckFullyInitialized = CheckFullyInitialized;
51 S.EvaluatingDecl = VD;
52 S.setEvalLocation(VD->getLocation());
53 EvalResult.setSource(VD);
54
55 QualType T = VD->getType();
56 this->ConvertResultToRValue = !Init->isGLValue() && !T->isPointerType() &&
57 !T->isObjCObjectPointerType();
58
59 if (!this->visitDeclAndReturn(VD, Init, ConstantContext: S.inConstantContext()))
60 EvalResult.setInvalid();
61
62 S.EvaluatingDecl = nullptr;
63 updateGlobalTemporaries();
64 return std::move(this->EvalResult);
65}
66
67EvaluationResult EvalEmitter::interpretDestructor(const VarDecl *VD,
68 const APValue &Value) {
69 assert(VD);
70 S.setEvalLocation(VD->getLocation());
71 S.EvaluatingDecl = VD;
72 S.EvalKind = EvaluationKind::Dtor;
73 EvalResult.setSource(VD);
74
75 if (!this->visitDtorCall(VD, Value))
76 EvalResult.setInvalid();
77
78 S.EvaluatingDecl = nullptr;
79 return std::move(this->EvalResult);
80}
81
82EvaluationResult EvalEmitter::interpretAsPointer(const Expr *E,
83 PtrCallback PtrCB) {
84 S.setEvalLocation(E->getExprLoc());
85 this->ConvertResultToRValue = false;
86 this->CheckFullyInitialized = false;
87 this->PtrCB = PtrCB;
88 EvalResult.setSource(E);
89
90 if (!this->visitExpr(E, DestroyToplevelScope: true)) {
91 // EvalResult may already have a result set, but something failed
92 // after that (e.g. evaluating destructors).
93 EvalResult.setInvalid();
94 }
95
96 return std::move(this->EvalResult);
97}
98
99EvaluationResult EvalEmitter::interpretAsLValuePointer(const Expr *E,
100 PtrCallback PtrCB) {
101 S.setEvalLocation(E->getExprLoc());
102 this->ConvertResultToRValue = false;
103 this->CheckFullyInitialized = false;
104 this->PtrCB = PtrCB;
105 EvalResult.setSource(E);
106
107 if (!this->visitLValueExpr(E, DestroyToplevelScope: true))
108 EvalResult.setInvalid();
109
110 return std::move(this->EvalResult);
111}
112
113bool EvalEmitter::interpretCall(const FunctionDecl *FD, const Expr *E) {
114 // Add parameters to the parameter map. The values in the ParamOffset don't
115 // matter in this case as reading from them can't ever work.
116 for (const ParmVarDecl *PD : FD->parameters()) {
117 this->Params.insert(KV: {PD, {.Index: 0, .IsPtr: false}});
118 }
119
120 return this->visitExpr(E, /*DestroyToplevelScope=*/false);
121}
122
123std::optional<bool> EvalEmitter::interpretWithSubstitutions(
124 const FunctionDecl *Callee, ArrayRef<const Expr *> Args, const Expr *This,
125 const Expr *Condition) {
126
127 if (!this->visitWithSubstitutions(Callee, Args, This, Condition))
128 return std::nullopt;
129
130 if (EvalResult.empty() || EvalResult.isInvalid())
131 return false;
132
133 assert(!EvalResult.empty());
134 APValue Result = EvalResult.stealAPValue();
135
136 assert(Result.isInt());
137 return Result.getInt().getBoolValue();
138}
139
140void EvalEmitter::emitLabel(LabelTy Label) { CurrentLabel = Label; }
141
142EvalEmitter::LabelTy EvalEmitter::getLabel() { return NextLabel++; }
143
144Scope::Local EvalEmitter::createLocal(const Descriptor *D) {
145 // Allocate memory for a local.
146 char *Memory = reinterpret_cast<char *>(
147 S.allocate(Size: sizeof(Block) + D->getAllocSize() + Block::InlineDescMD));
148 auto *B = new (Memory) Block(Ctx.getEvalID(), D, Block::InlineDescMD,
149 /*IsStatic=*/false);
150 B->invokeCtor();
151
152 // Initialize local variable inline descriptor.
153 auto &Desc = B->getBlockDesc<InlineDescriptor>();
154 Desc.Desc = D;
155 Desc.Offset = sizeof(InlineDescriptor);
156 Desc.IsActive = false;
157 Desc.IsBase = false;
158 Desc.IsFieldMutable = false;
159 Desc.IsConst = false;
160 Desc.IsInitialized = false;
161
162 // Register the local.
163 unsigned Off = Locals.size();
164 Locals.push_back(Elt: Memory);
165 return {.Desc: D, .Offset: Off};
166}
167
168bool EvalEmitter::jumpTrue(const LabelTy &Label, SourceInfo SI) {
169 if (isActive()) {
170 CurrentSource = SI;
171 if (S.Stk.pop<bool>())
172 ActiveLabel = Label;
173 }
174 return true;
175}
176
177bool EvalEmitter::jumpFalse(const LabelTy &Label, SourceInfo SI) {
178 if (isActive()) {
179 CurrentSource = SI;
180 if (!S.Stk.pop<bool>())
181 ActiveLabel = Label;
182 }
183 return true;
184}
185
186bool EvalEmitter::jump(const LabelTy &Label, SourceInfo SI) {
187 if (isActive()) {
188 CurrentSource = SI;
189 CurrentLabel = ActiveLabel = Label;
190 }
191 return true;
192}
193
194bool EvalEmitter::fallthrough(const LabelTy &Label) {
195 if (isActive())
196 ActiveLabel = Label;
197 CurrentLabel = Label;
198 return true;
199}
200
201bool EvalEmitter::speculate(const CallExpr *E, const LabelTy &EndLabel) {
202 if (!isActive())
203 return true;
204
205 PushIgnoreDiags(S);
206 auto _ = llvm::scope_exit([&]() { PopIgnoreDiags(S); });
207
208 size_t StackSizeBefore = S.Stk.size();
209 const Expr *Arg = E->getArg(Arg: 0);
210 if (!this->visit(E: Arg)) {
211 S.Stk.clearTo(NewSize: StackSizeBefore);
212
213 if (S.inConstantContext() || Arg->HasSideEffects(Ctx: S.getASTContext()))
214 return this->emitBool(V: false, E);
215 return Invalid(S, OpPC: CodePtr());
216 }
217
218 PrimType T = Ctx.classify(T: Arg->getType()).value_or(PT: PT_Ptr);
219 if (T == PT_Ptr) {
220 const auto &Ptr = S.Stk.pop<Pointer>();
221 return this->emitBool(V: CheckBCPResult(S, Ptr), E);
222 }
223
224 // Otherwise, this is fine!
225 if (!this->emitPop(T, I: E))
226 return false;
227 return this->emitBool(V: true, E);
228}
229
230template <PrimType OpType> bool EvalEmitter::emitRet(SourceInfo Info) {
231 if (!isActive())
232 return true;
233
234 using T = typename PrimConv<OpType>::T;
235 EvalResult.takeValue(V: S.Stk.pop<T>().toAPValue(Ctx.getASTContext()));
236 return true;
237}
238
239template <> bool EvalEmitter::emitRet<PT_Ptr>(SourceInfo Info) {
240 if (!isActive())
241 return true;
242
243 const Pointer &Ptr = S.Stk.pop<Pointer>();
244 // If we're returning a raw pointer, call our callback.
245 if (this->PtrCB)
246 return (*this->PtrCB)(S, CodePtr(), Ptr);
247
248 if (!EvalResult.checkDynamicAllocations(S, Ptr, Info))
249 return false;
250 if (CheckFullyInitialized && !EvalResult.checkFullyInitialized(S, Ptr))
251 return false;
252
253 // Function pointers are always returned as lvalues.
254 if (Ptr.isFunctionPointer()) {
255 if (ConvertResultToRValue && Ptr.asFunctionPointer().Func->getDecl())
256 return false;
257 EvalResult.takeValue(V: Ptr.toAPValue(ASTCtx: Ctx.getASTContext()));
258 return true;
259 }
260
261 // Implicitly convert lvalue to rvalue, if requested.
262 if (ConvertResultToRValue) {
263 if (Ptr.isPastEnd())
264 return false;
265
266 if (!Ptr.isZero() && !CheckFinalLoad(S, OpPC: CodePtr(), Ptr))
267 return false;
268
269 // Never allow reading from a non-const pointer, unless the memory
270 // has been created in this evaluation.
271 if (!Ptr.isZero() && !Ptr.isConst() && Ptr.isBlockPointer() &&
272 Ptr.block()->getEvalID() != Ctx.getEvalID())
273 return false;
274
275 if (std::optional<APValue> V =
276 Ptr.toRValue(Ctx, ResultType: EvalResult.getSourceType())) {
277 EvalResult.takeValue(V: std::move(*V));
278 } else {
279 return false;
280 }
281 } else {
282 // If this is pointing to a local variable, just return
283 // the result, even if the pointer is dead.
284 // This will later be diagnosed by CheckLValueConstantExpression.
285 if (Ptr.isBlockPointer() && !Ptr.block()->isStatic()) {
286 EvalResult.takeValue(V: Ptr.toAPValue(ASTCtx: Ctx.getASTContext()));
287 return true;
288 }
289
290 if (!Ptr.isLive() && !Ptr.isTemporary())
291 return false;
292
293 // If the variable of this pointer is being evaluated when returning
294 // its value, mark it as constexpr-unknown.
295 APValue V = Ptr.toAPValue(ASTCtx: Ctx.getASTContext());
296 if (const Descriptor *DeclDesc = Ptr.getDeclDesc();
297 DeclDesc && S.EvaluatingDecl &&
298 DeclDesc->asVarDecl() == S.EvaluatingDecl &&
299 S.getLangOpts().CPlusPlus23 &&
300 S.EvaluatingDecl->getType()->isReferenceType()) {
301 V.setConstexprUnknown(true);
302 }
303 EvalResult.takeValue(V: std::move(V));
304 }
305
306 return true;
307}
308
309bool EvalEmitter::emitRetVoid(SourceInfo Info) {
310 EvalResult.setValid();
311 return true;
312}
313
314bool EvalEmitter::emitRetValue(SourceInfo Info) {
315 const auto &Ptr = S.Stk.pop<Pointer>();
316
317 if (!EvalResult.checkDynamicAllocations(S, Ptr, Info))
318 return false;
319 if (CheckFullyInitialized && !EvalResult.checkFullyInitialized(S, Ptr))
320 return false;
321
322 if (std::optional<APValue> APV =
323 Ptr.toRValue(Ctx, ResultType: EvalResult.getSourceType())) {
324 EvalResult.takeValue(V: std::move(*APV));
325 return true;
326 }
327
328 EvalResult.setInvalid();
329 return false;
330}
331
332bool EvalEmitter::emitGetPtrLocal(uint32_t I, SourceInfo Info) {
333 if (!isActive())
334 return true;
335
336 Block *B = getLocal(Index: I);
337 S.Stk.push<Pointer>(Args&: B, Args: sizeof(InlineDescriptor));
338 return true;
339}
340
341bool EvalEmitter::emitGetRefLocal(uint32_t I, SourceInfo Info) {
342 if (!isActive())
343 return true;
344
345 Block *B = getLocal(Index: I);
346 return handleReference(S, OpPC: CodePtr(), B);
347}
348
349template <PrimType OpType>
350bool EvalEmitter::emitGetLocal(uint32_t I, SourceInfo Info) {
351 if (!isActive())
352 return true;
353
354 using T = typename PrimConv<OpType>::T;
355
356 Block *B = getLocal(Index: I);
357
358 if (!CheckLocalLoad(S, OpPC: CodePtr(), B))
359 return false;
360
361 S.Stk.push<T>(B->deref<T>());
362 return true;
363}
364
365template <PrimType OpType>
366bool EvalEmitter::emitSetLocal(uint32_t I, SourceInfo Info) {
367 if (!isActive())
368 return true;
369
370 using T = typename PrimConv<OpType>::T;
371
372 Block *B = getLocal(Index: I);
373 B->deref<T>() = S.Stk.pop<T>();
374 auto &Desc = B->getBlockDesc<InlineDescriptor>();
375 Desc.IsInitialized = true;
376 Desc.LifeState = Lifetime::Started;
377
378 return true;
379}
380
381bool EvalEmitter::emitDestroy(uint32_t I, SourceInfo Info) {
382 if (!isActive())
383 return true;
384
385 for (auto &Local : Descriptors[I]) {
386 Block *B = getLocal(Index: Local.Offset);
387 S.deallocate(B);
388 }
389
390 return true;
391}
392
393bool EvalEmitter::emitGetLocalEnabled(uint32_t I, SourceInfo Info) {
394 if (!isActive())
395 return true;
396
397 Block *B = getLocal(Index: I);
398 const auto &Desc = B->getBlockDesc<InlineDescriptor>();
399
400 S.Stk.push<bool>(Args: Desc.IsActive);
401 return true;
402}
403
404bool EvalEmitter::emitEnableLocal(uint32_t I, SourceInfo Info) {
405 if (!isActive())
406 return true;
407
408 // FIXME: This is a little dirty, but to avoid adding a flag to
409 // InlineDescriptor that's only ever useful on the toplevel of local
410 // variables, we reuse the IsActive flag for the enabled state. We should
411 // probably use a different struct than InlineDescriptor for the block-level
412 // inline descriptor of local varaibles.
413 Block *B = getLocal(Index: I);
414 auto &Desc = B->getBlockDesc<InlineDescriptor>();
415 Desc.IsActive = true;
416 return true;
417}
418
419/// Global temporaries (LifetimeExtendedTemporary) carry their value
420/// around as an APValue, which codegen accesses.
421/// We set their value once when creating them, but we don't update it
422/// afterwards when code changes it later.
423/// This is what we do here.
424void EvalEmitter::updateGlobalTemporaries() {
425 for (const auto &[E, Temp] : S.SeenGlobalTemporaries) {
426 UnsignedOrNone GlobalIndex = P.getGlobal(E);
427 assert(GlobalIndex);
428 const Pointer &Ptr = P.getPtrGlobal(Idx: *GlobalIndex);
429 APValue *Cached = Temp->getOrCreateValue(MayCreate: true);
430
431 QualType TempType = E->getType();
432 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E))
433 TempType = MTE->getSubExpr()->skipRValueSubobjectAdjustments()->getType();
434
435 if (OptPrimType T = Ctx.classify(T: TempType)) {
436 TYPE_SWITCH(*T,
437 { *Cached = Ptr.deref<T>().toAPValue(Ctx.getASTContext()); });
438 } else {
439 if (std::optional<APValue> APV = Ptr.toRValue(Ctx, ResultType: TempType))
440 *Cached = *APV;
441 }
442 }
443 S.SeenGlobalTemporaries.clear();
444}
445
446//===----------------------------------------------------------------------===//
447// Opcode evaluators
448//===----------------------------------------------------------------------===//
449
450#define GET_EVAL_IMPL
451#include "Opcodes.inc"
452#undef GET_EVAL_IMPL
453