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
21EvalEmitter::EvalEmitter(Context &Ctx, Program &P, const EvalSettings &Settings,
22 InterpStack &Stk, FrameAllocator &FA)
23 : Ctx(Ctx), P(P), S(Settings, P, Stk, FA, Ctx, this), EvalResult(Ctx),
24 ConstexprKind(Settings.ConstexprKind) {}
25
26EvalEmitter::EvalEmitter(Context &Ctx, Program &P, Expr::EvalStatus &Status,
27 InterpStack &Stk, FrameAllocator &FA)
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
35EvaluationResult EvalEmitter::interpretExpr(const Expr *E,
36 bool ConvertResultToRValue,
37 bool DestroyToplevelScope) {
38 S.setEvalLocation(E->getExprLoc());
39 this->ConvertResultToRValue = ConvertResultToRValue && !isa<ConstantExpr>(Val: E);
40 this->CheckFullyInitialized = isa<ConstantExpr>(Val: 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
52EvaluationResult EvalEmitter::interpretDecl(const VarDecl *VD, const Expr *Init,
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, ConstantContext: S.inConstantContext()))
66 EvalResult.setInvalid();
67
68 S.EvaluatingDecl = nullptr;
69 updateGlobalTemporaries();
70 return std::move(this->EvalResult);
71}
72
73EvaluationResult EvalEmitter::interpretDestructor(const VarDecl *VD,
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
88EvaluationResult EvalEmitter::interpretAsPointer(const Expr *E,
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, DestroyToplevelScope: 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
105EvaluationResult EvalEmitter::interpretAsLValuePointer(const Expr *E,
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, DestroyToplevelScope: true))
114 EvalResult.setInvalid();
115
116 return std::move(this->EvalResult);
117}
118
119bool EvalEmitter::interpretCall(const FunctionDecl *FD, const Expr *E) {
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(KV: {PD, {.Index: 0, .IsPtr: false}});
124 }
125
126 return this->visitExpr(E, /*DestroyToplevelScope=*/false);
127}
128
129std::optional<bool> EvalEmitter::interpretWithSubstitutions(
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
148EvalEmitter::LabelTy EvalEmitter::getLabel() { return NextLabel++; }
149
150Scope::Local EvalEmitter::createLocal(const Descriptor *D) {
151 // Allocate memory for a local.
152 char *Memory = reinterpret_cast<char *>(
153 S.allocate(Size: 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(Elt: Memory);
171 return {.Desc: D, .Offset: Off};
172}
173
174bool EvalEmitter::jumpTrue(const LabelTy &Label, SourceInfo SI) {
175 if (isActive()) {
176 CurrentSource = SI;
177 if (S.Stk.pop<bool>())
178 ActiveLabel = Label;
179 }
180 return true;
181}
182
183bool EvalEmitter::jumpFalse(const LabelTy &Label, SourceInfo SI) {
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
200bool EvalEmitter::fallthrough(const LabelTy &Label) {
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
211 PushIgnoreDiags(S);
212 auto _ = llvm::scope_exit([&]() { PopIgnoreDiags(S); });
213
214 size_t StackSizeBefore = S.Stk.size();
215 const Expr *Arg = E->getArg(Arg: 0);
216 if (!this->visit(E: Arg)) {
217 S.Stk.clearTo(NewSize: StackSizeBefore);
218
219 if (S.inConstantContext() || Arg->HasSideEffects(Ctx: S.getASTContext()))
220 return this->emitBool(V: false, E);
221 return Invalid(S, OpPC: CodePtr());
222 }
223
224 PrimType T = Ctx.classify(T: Arg->getType()).value_or(PT: PT_Ptr);
225 if (T == PT_Ptr) {
226 const auto &Ptr = S.Stk.pop<Pointer>();
227 return this->emitBool(V: CheckBCPResult(S, Ptr), E);
228 }
229
230 // Otherwise, this is fine!
231 if (!this->emitPop(T, I: E))
232 return false;
233 return this->emitBool(V: 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(V: 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, MemberPtr: MP, Info, ConstexprKind))
251 return false;
252
253 EvalResult.takeValue(V: 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(V: Ptr.toAPValue(ASTCtx: Ctx.getASTContext()));
280 return true;
281 }
282
283 // Implicitly convert lvalue to rvalue, if requested.
284 if (ConvertResultToRValue) {
285 if (!Ptr.isZero() && !CheckFinalLoad(S, OpPC: 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, ResultType: EvalResult.getSourceType())) {
293 EvalResult.takeValue(V: 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(SI: Info, DiagId: diag::note_constexpr_var_init_non_constant, ExtraNotes: 1)
313 << DeclDesc->asVarDecl();
314 S.Note(Loc: DeclDesc->asVarDecl()->getLocation(), DiagId: diag::note_declared_at);
315
316 return false;
317 }
318
319 APValue V = Ptr.toAPValue(ASTCtx: Ctx.getASTContext());
320 EvalResult.takeValue(V: 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, ResultType: EvalResult.getSourceType())) {
341 EvalResult.takeValue(V: 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(Index: I);
354 S.Stk.push<Pointer>(Args&: B, Args: 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(Index: I);
363 return handleReference(S, OpPC: 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(Index: I);
374
375 if (!CheckLocalLoad(S, OpPC: 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(Index: 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(Index: 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(Index: I);
415 const auto &Desc = B->getBlockDesc<InlineDescriptor>();
416
417 S.Stk.push<bool>(Args: 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(Index: 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(Idx: *GlobalIndex);
446 APValue *Cached = Temp->getOrCreateValue(MayCreate: true);
447
448 QualType TempType = E->getType();
449 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E))
450 TempType = MTE->getSubExpr()->skipRValueSubobjectAdjustments()->getType();
451
452 if (OptPrimType T = Ctx.classify(T: TempType)) {
453 TYPE_SWITCH(*T,
454 { *Cached = Ptr.deref<T>().toAPValue(Ctx.getASTContext()); });
455 } else {
456 if (std::optional<APValue> APV = Ptr.toRValue(Ctx, ResultType: 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
470