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