1//===--- InterpFrame.cpp - Call Frame implementation 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 "InterpFrame.h"
10#include "Boolean.h"
11#include "Function.h"
12#include "InterpStack.h"
13#include "InterpState.h"
14#include "MemberPointer.h"
15#include "Pointer.h"
16#include "PrimType.h"
17#include "Program.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/ExprCXX.h"
21
22using namespace clang;
23using namespace clang::interp;
24
25InterpFrame::InterpFrame(InterpState &S)
26 : Caller(nullptr), S(S), Depth(0), Func(nullptr), RetPC(CodePtr()),
27 ArgSize(0), Args(nullptr), FrameOffset(0) {}
28
29InterpFrame::InterpFrame(InterpState &S, const Function *Func,
30 InterpFrame *Caller, CodePtr RetPC, unsigned ArgSize)
31 : Caller(Caller), S(S), Depth(Caller ? Caller->Depth + 1 : 0), Func(Func),
32 RetPC(RetPC), ArgSize(ArgSize), Args(static_cast<char *>(S.Stk.top())),
33 FrameOffset(S.Stk.size()) {
34
35 if (!Func)
36 return;
37 // Initialize argument blocks.
38 for (unsigned I = 0, N = Func->getNumWrittenParams(); I != N; ++I)
39 new (argBlock(Index: I)) Block(S.EvalID, Func->getParamDescriptor(Index: I).Desc);
40
41 if (Func->getFrameSize() == 0)
42 return;
43
44 for (auto &Scope : Func->scopes()) {
45 for (auto &Local : Scope.locals()) {
46 new (localBlock(Offset: Local.Offset)) Block(S.EvalID, Local.Desc);
47 // Note that we are NOT calling invokeCtor() here, since that is done
48 // via the InitScope op.
49 new (localInlineDesc(Offset: Local.Offset)) InlineDescriptor(Local.Desc);
50 }
51 }
52}
53
54InterpFrame::InterpFrame(InterpState &S, const Function *Func, CodePtr RetPC,
55 unsigned VarArgSize)
56 : InterpFrame(S, Func, S.Current, RetPC, Func->getArgSize() + VarArgSize) {
57 // As per our calling convention, the this pointer is
58 // part of the ArgSize.
59 // If the function has RVO, the RVO pointer is first.
60 // If the fuction has a This pointer, that one is next.
61 // Then follow the actual arguments (but those are handled
62 // in getParamPointer()).
63 if (Func->hasRVO()) {
64 // RVO pointer offset is always 0.
65 }
66
67 if (Func->hasThisPointer())
68 ThisPointerOffset = Func->hasRVO() ? sizeof(Pointer) : 0;
69}
70
71InterpFrame::~InterpFrame() {
72 if (!Func)
73 return;
74
75 // De-initialize all argument blocks.
76 for (unsigned I = 0, N = Func->getNumWrittenParams(); I != N; ++I)
77 S.deallocate(B: argBlock(Index: I));
78
79 // When destroying the InterpFrame, call the Dtor for all block
80 // that haven't been destroyed via a destroy() op yet.
81 // This happens when the execution is interruped midway-through.
82 destroyScopes();
83}
84
85void InterpFrame::destroyScopes() {
86 if (!Func || Func->getFrameSize() == 0)
87 return;
88 for (auto &Scope : Func->scopes()) {
89 for (auto &Local : Scope.locals()) {
90 S.deallocate(B: localBlock(Offset: Local.Offset));
91 }
92 }
93}
94
95void InterpFrame::initScope(unsigned Idx) {
96 if (!Func)
97 return;
98
99 for (auto &Local : Func->getScope(Idx).locals()) {
100 assert(!localBlock(Local.Offset)->isInitialized());
101 localBlock(Offset: Local.Offset)->invokeCtor();
102 }
103}
104
105void InterpFrame::enableLocal(unsigned Idx) {
106 assert(Func);
107
108 // FIXME: This is a little dirty, but to avoid adding a flag to
109 // InlineDescriptor that's only ever useful on the toplevel of local
110 // variables, we reuse the IsActive flag for the enabled state. We should
111 // probably use a different struct than InlineDescriptor for the block-level
112 // inline descriptor of local varaibles.
113 localInlineDesc(Offset: Idx)->IsActive = true;
114}
115
116void InterpFrame::destroy(unsigned Idx) {
117 for (auto &Local : Func->getScope(Idx).locals_reverse()) {
118 S.deallocate(B: localBlock(Offset: Local.Offset));
119 }
120}
121
122template <typename T>
123static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx,
124 QualType Ty) {
125 if constexpr (std::is_same_v<Pointer, T>) {
126 if (Ty->isPointerOrReferenceType())
127 V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);
128 else {
129 if (std::optional<APValue> RValue = V.toRValue(ASTCtx, Ty))
130 RValue->printPretty(OS, Ctx: ASTCtx, Ty);
131 else
132 OS << "...";
133 }
134 } else {
135 V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);
136 }
137}
138
139static bool shouldSkipInBacktrace(const Function *F) {
140 if (F->isLambdaStaticInvoker())
141 return true;
142
143 const FunctionDecl *FD = F->getDecl();
144 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
145 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New)
146 return true;
147
148 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
149 MD && MD->getParent()->isAnonymousStructOrUnion())
150 return true;
151
152 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD);
153 Ctor && Ctor->isDefaulted() && Ctor->isTrivial() &&
154 Ctor->isCopyOrMoveConstructor() && Ctor->inits().empty())
155 return true;
156
157 return false;
158}
159
160void InterpFrame::describe(llvm::raw_ostream &OS) const {
161 assert(Func);
162 // For lambda static invokers, we would just print __invoke().
163 if (shouldSkipInBacktrace(F: Func))
164 return;
165
166 const Expr *CallExpr = Caller->getExpr(PC: getRetPC());
167 const FunctionDecl *F = getCallee();
168
169 bool IsMemberCall = false;
170 bool ExplicitInstanceParam = false;
171 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: F)) {
172 IsMemberCall = !isa<CXXConstructorDecl>(Val: MD) && !MD->isStatic();
173 ExplicitInstanceParam = MD->isExplicitObjectMemberFunction();
174 }
175
176 if (Func->hasThisPointer() && IsMemberCall) {
177 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(Val: CallExpr)) {
178 const Expr *Object = MCE->getImplicitObjectArgument();
179 Object->printPretty(OS, /*Helper=*/nullptr,
180 Policy: S.getASTContext().getPrintingPolicy(),
181 /*Indentation=*/0);
182 if (Object->getType()->isPointerType())
183 OS << "->";
184 else
185 OS << ".";
186 } else if (const auto *OCE =
187 dyn_cast_if_present<CXXOperatorCallExpr>(Val: CallExpr)) {
188 OCE->getArg(Arg: 0)->printPretty(OS, /*Helper=*/nullptr,
189 Policy: S.getASTContext().getPrintingPolicy(),
190 /*Indentation=*/0);
191 OS << ".";
192 } else if (const auto *M = dyn_cast<CXXMethodDecl>(Val: F)) {
193 print(OS, V: getThis(), ASTCtx&: S.getASTContext(),
194 Ty: S.getASTContext().getLValueReferenceType(
195 T: S.getASTContext().getCanonicalTagType(TD: M->getParent())));
196 OS << ".";
197 }
198 }
199
200 F->getNameForDiagnostic(OS, Policy: S.getASTContext().getPrintingPolicy(),
201 /*Qualified=*/false);
202 OS << '(';
203 unsigned Off = 0;
204
205 Off += Func->hasRVO() ? primSize(Type: PT_Ptr) : 0;
206 Off += Func->hasThisPointer() ? primSize(Type: PT_Ptr) : 0;
207 llvm::ListSeparator Comma;
208 for (const ParmVarDecl *Param :
209 F->parameters().slice(N: ExplicitInstanceParam)) {
210 OS << Comma;
211 QualType Ty = Param->getType();
212 PrimType PrimTy = S.Ctx.classify(T: Ty).value_or(PT: PT_Ptr);
213
214 TYPE_SWITCH(PrimTy, print(OS, stackRef<T>(Off), S.getASTContext(), Ty));
215 Off += align(Size: primSize(Type: PrimTy));
216 }
217 OS << ")";
218}
219
220SourceRange InterpFrame::getCallRange() const {
221 if (!Caller->Func) {
222 if (SourceRange NullRange = S.getRange(F: nullptr, PC: {}); NullRange.isValid())
223 return NullRange;
224 return S.EvalLocation;
225 }
226
227 // Move up to the frame that has a valid location for the caller.
228 for (const InterpFrame *C = this; C; C = C->Caller) {
229 if (!C->RetPC)
230 continue;
231 SourceRange CallRange =
232 S.getRange(F: C->Caller->Func, PC: C->RetPC - sizeof(uintptr_t));
233 if (CallRange.isValid())
234 return CallRange;
235 }
236 return S.EvalLocation;
237}
238
239const FunctionDecl *InterpFrame::getCallee() const {
240 if (!Func)
241 return nullptr;
242 return Func->getDecl();
243}
244
245Pointer InterpFrame::getLocalPointer(unsigned Offset) const {
246 assert(Offset < Func->getFrameSize() && "Invalid local offset.");
247 return Pointer(localBlock(Offset));
248}
249
250Block *InterpFrame::getLocalBlock(unsigned Offset) const {
251 return localBlock(Offset);
252}
253
254Pointer InterpFrame::getParamPointer(unsigned Index) {
255 assert(!isBottomFrame());
256
257 Block *B = argBlock(Index);
258
259 // Copy the initial value.
260 if (!B->isInitialized()) {
261 unsigned ByteOffset = Func->getParamDescriptor(Index).Offset;
262 assert(B->getDescriptor()->isPrimitive());
263 B->invokeCtor();
264 TYPE_SWITCH(B->getDescriptor()->getPrimType(),
265 new (B->data()) T(stackRef<T>(ByteOffset)));
266 assert(B->isInitialized());
267 }
268
269 return Pointer(B);
270}
271
272static bool funcHasUsableBody(const Function *F) {
273 assert(F);
274
275 if (F->isConstructor() || F->isDestructor())
276 return true;
277
278 return !F->getDecl()->isImplicit();
279}
280
281SourceInfo InterpFrame::getSource(CodePtr PC) const {
282 // Implicitly created functions don't have any code we could point at,
283 // so return the call site.
284 if (Func && !funcHasUsableBody(F: Func) && Caller)
285 return Caller->getSource(PC: RetPC);
286
287 // Similarly, if the resulting source location is invalid anyway,
288 // point to the caller instead.
289 SourceInfo Result = S.getSource(F: Func, PC);
290 if (Result.getLoc().isInvalid() && Caller)
291 return Caller->getSource(PC: RetPC);
292 return Result;
293}
294
295const Expr *InterpFrame::getExpr(CodePtr PC) const {
296 if (Func && !funcHasUsableBody(F: Func) && Caller)
297 return Caller->getExpr(PC: RetPC);
298
299 return S.getExpr(F: Func, PC);
300}
301
302SourceLocation InterpFrame::getLocation(CodePtr PC) const {
303 if (Func && !funcHasUsableBody(F: Func) && Caller)
304 return Caller->getLocation(PC: RetPC);
305
306 return S.getLocation(F: Func, PC);
307}
308
309SourceRange InterpFrame::getRange(CodePtr PC) const {
310 if (Func && !funcHasUsableBody(F: Func) && Caller)
311 return Caller->getRange(PC: RetPC);
312
313 return S.getRange(F: Func, PC);
314}
315
316bool InterpFrame::isStdFunction() const {
317 if (!Func)
318 return false;
319 for (const DeclContext *DC = Func->getDecl(); DC; DC = DC->getParent())
320 if (DC->isStdNamespace())
321 return true;
322
323 return false;
324}
325