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 "Floating.h"
12 #include "Function.h"
13 #include "InterpStack.h"
14 #include "InterpState.h"
15 #include "MemberPointer.h"
16 #include "Pointer.h"
17 #include "PrimType.h"
18 #include "Program.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclCXX.h"
21
22 using namespace clang;
23 using namespace clang::interp;
24
InterpFrame(InterpState & S,const Function * Func,InterpFrame * Caller,CodePtr RetPC,unsigned ArgSize)25 InterpFrame::InterpFrame(InterpState &S, const Function *Func,
26 InterpFrame *Caller, CodePtr RetPC, unsigned ArgSize)
27 : Caller(Caller), S(S), Depth(Caller ? Caller->Depth + 1 : 0), Func(Func),
28 RetPC(RetPC), ArgSize(ArgSize), Args(static_cast<char *>(S.Stk.top())),
29 FrameOffset(S.Stk.size()) {
30 if (!Func)
31 return;
32
33 unsigned FrameSize = Func->getFrameSize();
34 if (FrameSize == 0)
35 return;
36
37 Locals = std::make_unique<char[]>(FrameSize);
38 for (auto &Scope : Func->scopes()) {
39 for (auto &Local : Scope.locals()) {
40 Block *B =
41 new (localBlock(Local.Offset)) Block(S.Ctx.getEvalID(), Local.Desc);
42 B->invokeCtor();
43 new (localInlineDesc(Local.Offset)) InlineDescriptor(Local.Desc);
44 }
45 }
46 }
47
InterpFrame(InterpState & S,const Function * Func,CodePtr RetPC,unsigned VarArgSize)48 InterpFrame::InterpFrame(InterpState &S, const Function *Func, CodePtr RetPC,
49 unsigned VarArgSize)
50 : InterpFrame(S, Func, S.Current, RetPC, Func->getArgSize() + VarArgSize) {
51 // As per our calling convention, the this pointer is
52 // part of the ArgSize.
53 // If the function has RVO, the RVO pointer is first.
54 // If the fuction has a This pointer, that one is next.
55 // Then follow the actual arguments (but those are handled
56 // in getParamPointer()).
57 if (Func->hasRVO())
58 RVOPtr = stackRef<Pointer>(0);
59
60 if (Func->hasThisPointer()) {
61 if (Func->hasRVO())
62 This = stackRef<Pointer>(sizeof(Pointer));
63 else
64 This = stackRef<Pointer>(0);
65 }
66 }
67
~InterpFrame()68 InterpFrame::~InterpFrame() {
69 for (auto &Param : Params)
70 S.deallocate(reinterpret_cast<Block *>(Param.second.get()));
71
72 // When destroying the InterpFrame, call the Dtor for all block
73 // that haven't been destroyed via a destroy() op yet.
74 // This happens when the execution is interruped midway-through.
75 if (Func) {
76 for (auto &Scope : Func->scopes()) {
77 for (auto &Local : Scope.locals()) {
78 Block *B = localBlock(Local.Offset);
79 if (B->isInitialized())
80 B->invokeDtor();
81 }
82 }
83 }
84 }
85
destroy(unsigned Idx)86 void InterpFrame::destroy(unsigned Idx) {
87 for (auto &Local : Func->getScope(Idx).locals()) {
88 S.deallocate(localBlock(Local.Offset));
89 }
90 }
91
popArgs()92 void InterpFrame::popArgs() {
93 for (PrimType Ty : Func->args_reverse())
94 TYPE_SWITCH(Ty, S.Stk.discard<T>());
95 }
96
97 template <typename T>
print(llvm::raw_ostream & OS,const T & V,ASTContext &,QualType)98 static void print(llvm::raw_ostream &OS, const T &V, ASTContext &, QualType) {
99 OS << V;
100 }
101
102 template <>
print(llvm::raw_ostream & OS,const Pointer & P,ASTContext & Ctx,QualType Ty)103 void print(llvm::raw_ostream &OS, const Pointer &P, ASTContext &Ctx,
104 QualType Ty) {
105 if (P.isZero()) {
106 OS << "nullptr";
107 return;
108 }
109
110 auto printDesc = [&OS, &Ctx](const Descriptor *Desc) {
111 if (const auto *D = Desc->asDecl()) {
112 // Subfields or named values.
113 if (const auto *VD = dyn_cast<ValueDecl>(D)) {
114 OS << *VD;
115 return;
116 }
117 // Base classes.
118 if (isa<RecordDecl>(D))
119 return;
120 }
121 // Temporary expression.
122 if (const auto *E = Desc->asExpr()) {
123 E->printPretty(OS, nullptr, Ctx.getPrintingPolicy());
124 return;
125 }
126 llvm_unreachable("Invalid descriptor type");
127 };
128
129 if (!Ty->isReferenceType())
130 OS << "&";
131 llvm::SmallVector<Pointer, 2> Levels;
132 for (Pointer F = P; !F.isRoot(); ) {
133 Levels.push_back(F);
134 F = F.isArrayElement() ? F.getArray().expand() : F.getBase();
135 }
136
137 // Drop the first pointer since we print it unconditionally anyway.
138 if (!Levels.empty())
139 Levels.erase(Levels.begin());
140
141 printDesc(P.getDeclDesc());
142 for (const auto &It : Levels) {
143 if (It.inArray()) {
144 OS << "[" << It.expand().getIndex() << "]";
145 continue;
146 }
147 if (auto Index = It.getIndex()) {
148 OS << " + " << Index;
149 continue;
150 }
151 OS << ".";
152 printDesc(It.getFieldDesc());
153 }
154 }
155
describe(llvm::raw_ostream & OS) const156 void InterpFrame::describe(llvm::raw_ostream &OS) const {
157 // We create frames for builtin functions as well, but we can't reliably
158 // diagnose them. The 'in call to' diagnostics for them add no value to the
159 // user _and_ it doesn't generally work since the argument types don't always
160 // match the function prototype. Just ignore them.
161 // Similarly, for lambda static invokers, we would just print __invoke().
162 if (const auto *F = getFunction();
163 F && (F->isBuiltin() || F->isLambdaStaticInvoker()))
164 return;
165
166 const FunctionDecl *F = getCallee();
167 if (const auto *M = dyn_cast<CXXMethodDecl>(F);
168 M && M->isInstance() && !isa<CXXConstructorDecl>(F)) {
169 print(OS, This, S.getCtx(), S.getCtx().getRecordType(M->getParent()));
170 OS << "->";
171 }
172
173 F->getNameForDiagnostic(OS, S.getCtx().getPrintingPolicy(),
174 /*Qualified=*/false);
175 OS << '(';
176 unsigned Off = 0;
177
178 Off += Func->hasRVO() ? primSize(PT_Ptr) : 0;
179 Off += Func->hasThisPointer() ? primSize(PT_Ptr) : 0;
180
181 for (unsigned I = 0, N = F->getNumParams(); I < N; ++I) {
182 QualType Ty = F->getParamDecl(I)->getType();
183
184 PrimType PrimTy = S.Ctx.classify(Ty).value_or(PT_Ptr);
185
186 TYPE_SWITCH(PrimTy, print(OS, stackRef<T>(Off), S.getCtx(), Ty));
187 Off += align(primSize(PrimTy));
188 if (I + 1 != N)
189 OS << ", ";
190 }
191 OS << ")";
192 }
193
getCaller() const194 Frame *InterpFrame::getCaller() const {
195 if (Caller->Caller)
196 return Caller;
197 return S.getSplitFrame();
198 }
199
getCallRange() const200 SourceRange InterpFrame::getCallRange() const {
201 if (!Caller->Func) {
202 if (SourceRange NullRange = S.getRange(nullptr, {}); NullRange.isValid())
203 return NullRange;
204 return S.EvalLocation;
205 }
206 return S.getRange(Caller->Func, RetPC - sizeof(uintptr_t));
207 }
208
getCallee() const209 const FunctionDecl *InterpFrame::getCallee() const {
210 if (!Func)
211 return nullptr;
212 return Func->getDecl();
213 }
214
getLocalPointer(unsigned Offset) const215 Pointer InterpFrame::getLocalPointer(unsigned Offset) const {
216 assert(Offset < Func->getFrameSize() && "Invalid local offset.");
217 return Pointer(localBlock(Offset));
218 }
219
getParamPointer(unsigned Off)220 Pointer InterpFrame::getParamPointer(unsigned Off) {
221 // Return the block if it was created previously.
222 if (auto Pt = Params.find(Off); Pt != Params.end())
223 return Pointer(reinterpret_cast<Block *>(Pt->second.get()));
224
225 // Allocate memory to store the parameter and the block metadata.
226 const auto &Desc = Func->getParamDescriptor(Off);
227 size_t BlockSize = sizeof(Block) + Desc.second->getAllocSize();
228 auto Memory = std::make_unique<char[]>(BlockSize);
229 auto *B = new (Memory.get()) Block(S.Ctx.getEvalID(), Desc.second);
230 B->invokeCtor();
231
232 // Copy the initial value.
233 TYPE_SWITCH(Desc.first, new (B->data()) T(stackRef<T>(Off)));
234
235 // Record the param.
236 Params.insert({Off, std::move(Memory)});
237 return Pointer(B);
238 }
239
getSource(CodePtr PC) const240 SourceInfo InterpFrame::getSource(CodePtr PC) const {
241 // Implicitly created functions don't have any code we could point at,
242 // so return the call site.
243 if (Func && (!Func->hasBody() || Func->getDecl()->isImplicit()) && Caller)
244 return Caller->getSource(RetPC);
245
246 return S.getSource(Func, PC);
247 }
248
getExpr(CodePtr PC) const249 const Expr *InterpFrame::getExpr(CodePtr PC) const {
250 if (Func && (!Func->hasBody() || Func->getDecl()->isImplicit()) && Caller)
251 return Caller->getExpr(RetPC);
252
253 return S.getExpr(Func, PC);
254 }
255
getLocation(CodePtr PC) const256 SourceLocation InterpFrame::getLocation(CodePtr PC) const {
257 if (Func && (!Func->hasBody() || Func->getDecl()->isImplicit()) && Caller)
258 return Caller->getLocation(RetPC);
259
260 return S.getLocation(Func, PC);
261 }
262
getRange(CodePtr PC) const263 SourceRange InterpFrame::getRange(CodePtr PC) const {
264 if (Func && (!Func->hasBody() || Func->getDecl()->isImplicit()) && Caller)
265 return Caller->getRange(RetPC);
266
267 return S.getRange(Func, PC);
268 }
269