clang 20.0.0git
InterpFrame.cpp
Go to the documentation of this file.
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"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/ExprCXX.h"
22
23using namespace clang;
24using namespace clang::interp;
25
27 InterpFrame *Caller, CodePtr RetPC, unsigned ArgSize)
28 : Caller(Caller), S(S), Depth(Caller ? Caller->Depth + 1 : 0), Func(Func),
29 RetPC(RetPC), ArgSize(ArgSize), Args(static_cast<char *>(S.Stk.top())),
30 FrameOffset(S.Stk.size()) {
31 if (!Func)
32 return;
33
34 unsigned FrameSize = Func->getFrameSize();
35 if (FrameSize == 0)
36 return;
37
38 Locals = std::make_unique<char[]>(FrameSize);
39 for (auto &Scope : Func->scopes()) {
40 for (auto &Local : Scope.locals()) {
41 new (localBlock(Local.Offset)) Block(S.Ctx.getEvalID(), Local.Desc);
42 // Note that we are NOT calling invokeCtor() here, since that is done
43 // via the InitScope op.
44 new (localInlineDesc(Local.Offset)) InlineDescriptor(Local.Desc);
45 }
46 }
47}
48
50 unsigned VarArgSize)
51 : InterpFrame(S, Func, S.Current, RetPC, Func->getArgSize() + VarArgSize) {
52 // As per our calling convention, the this pointer is
53 // part of the ArgSize.
54 // If the function has RVO, the RVO pointer is first.
55 // If the fuction has a This pointer, that one is next.
56 // Then follow the actual arguments (but those are handled
57 // in getParamPointer()).
58 if (Func->hasRVO())
59 RVOPtr = stackRef<Pointer>(0);
60
61 if (Func->hasThisPointer()) {
62 if (Func->hasRVO())
63 This = stackRef<Pointer>(sizeof(Pointer));
64 else
65 This = stackRef<Pointer>(0);
66 }
67}
68
70 for (auto &Param : Params)
71 S.deallocate(reinterpret_cast<Block *>(Param.second.get()));
72
73 // When destroying the InterpFrame, call the Dtor for all block
74 // that haven't been destroyed via a destroy() op yet.
75 // This happens when the execution is interruped midway-through.
76 if (Func) {
77 for (auto &Scope : Func->scopes()) {
78 for (auto &Local : Scope.locals()) {
79 S.deallocate(localBlock(Local.Offset));
80 }
81 }
82 }
83}
84
85void InterpFrame::initScope(unsigned Idx) {
86 if (!Func)
87 return;
88 for (auto &Local : Func->getScope(Idx).locals()) {
89 localBlock(Local.Offset)->invokeCtor();
90 }
91}
92
93void InterpFrame::destroy(unsigned Idx) {
94 for (auto &Local : Func->getScope(Idx).locals()) {
95 S.deallocate(localBlock(Local.Offset));
96 }
97}
98
99template <typename T>
100static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx,
101 QualType Ty) {
102 V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);
103}
104
105static bool shouldSkipInBacktrace(const Function *F) {
106 if (F->isBuiltin())
107 return true;
108 if (F->isLambdaStaticInvoker())
109 return true;
110
111 const FunctionDecl *FD = F->getDecl();
112 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
113 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New)
114 return true;
115 return false;
116}
117
118void InterpFrame::describe(llvm::raw_ostream &OS) const {
119 // We create frames for builtin functions as well, but we can't reliably
120 // diagnose them. The 'in call to' diagnostics for them add no value to the
121 // user _and_ it doesn't generally work since the argument types don't always
122 // match the function prototype. Just ignore them.
123 // Similarly, for lambda static invokers, we would just print __invoke().
124 if (const auto *F = getFunction(); F && shouldSkipInBacktrace(F))
125 return;
126
127 const Expr *CallExpr = Caller->getExpr(getRetPC());
128 const FunctionDecl *F = getCallee();
129 bool IsMemberCall = isa<CXXMethodDecl>(F) && !isa<CXXConstructorDecl>(F) &&
130 cast<CXXMethodDecl>(F)->isImplicitObjectMemberFunction();
131 if (Func->hasThisPointer() && IsMemberCall) {
132 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
133 const Expr *Object = MCE->getImplicitObjectArgument();
134 Object->printPretty(OS, /*Helper=*/nullptr,
136 /*Indentation=*/0);
137 if (Object->getType()->isPointerType())
138 OS << "->";
139 else
140 OS << ".";
141 } else if (const auto *OCE =
142 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
143 OCE->getArg(0)->printPretty(OS, /*Helper=*/nullptr,
145 /*Indentation=*/0);
146 OS << ".";
147 } else if (const auto *M = dyn_cast<CXXMethodDecl>(F)) {
148 print(OS, This, S.getASTContext(),
150 S.getASTContext().getRecordType(M->getParent())));
151 OS << ".";
152 }
153 }
154
156 /*Qualified=*/false);
157 OS << '(';
158 unsigned Off = 0;
159
160 Off += Func->hasRVO() ? primSize(PT_Ptr) : 0;
161 Off += Func->hasThisPointer() ? primSize(PT_Ptr) : 0;
162
163 for (unsigned I = 0, N = F->getNumParams(); I < N; ++I) {
164 QualType Ty = F->getParamDecl(I)->getType();
165
166 PrimType PrimTy = S.Ctx.classify(Ty).value_or(PT_Ptr);
167
168 TYPE_SWITCH(PrimTy, print(OS, stackRef<T>(Off), S.getASTContext(), Ty));
169 Off += align(primSize(PrimTy));
170 if (I + 1 != N)
171 OS << ", ";
172 }
173 OS << ")";
174}
175
177 if (Caller->Caller)
178 return Caller;
179 return S.getSplitFrame();
180}
181
183 if (!Caller->Func) {
184 if (SourceRange NullRange = S.getRange(nullptr, {}); NullRange.isValid())
185 return NullRange;
186 return S.EvalLocation;
187 }
188 return S.getRange(Caller->Func, RetPC - sizeof(uintptr_t));
189}
190
192 if (!Func)
193 return nullptr;
194 return Func->getDecl();
195}
196
197Pointer InterpFrame::getLocalPointer(unsigned Offset) const {
198 assert(Offset < Func->getFrameSize() && "Invalid local offset.");
199 return Pointer(localBlock(Offset));
200}
201
203 // Return the block if it was created previously.
204 if (auto Pt = Params.find(Off); Pt != Params.end())
205 return Pointer(reinterpret_cast<Block *>(Pt->second.get()));
206
207 // Allocate memory to store the parameter and the block metadata.
208 const auto &Desc = Func->getParamDescriptor(Off);
209 size_t BlockSize = sizeof(Block) + Desc.second->getAllocSize();
210 auto Memory = std::make_unique<char[]>(BlockSize);
211 auto *B = new (Memory.get()) Block(S.Ctx.getEvalID(), Desc.second);
212 B->invokeCtor();
213
214 // Copy the initial value.
215 TYPE_SWITCH(Desc.first, new (B->data()) T(stackRef<T>(Off)));
216
217 // Record the param.
218 Params.insert({Off, std::move(Memory)});
219 return Pointer(B);
220}
221
222static bool funcHasUsableBody(const Function *F) {
223 assert(F);
224
225 if (F->isConstructor() || F->isDestructor())
226 return true;
227
228 return !F->getDecl()->isImplicit();
229}
230
232 // Implicitly created functions don't have any code we could point at,
233 // so return the call site.
234 if (Func && !funcHasUsableBody(Func) && Caller)
235 return Caller->getSource(RetPC);
236
237 // Similarly, if the resulting source location is invalid anyway,
238 // point to the caller instead.
239 SourceInfo Result = S.getSource(Func, PC);
240 if (Result.getLoc().isInvalid() && Caller)
241 return Caller->getSource(RetPC);
242 return Result;
243}
244
246 if (Func && !funcHasUsableBody(Func) && Caller)
247 return Caller->getExpr(PC);
248
249 return S.getExpr(Func, PC);
250}
251
253 if (Func && !funcHasUsableBody(Func) && Caller)
254 return Caller->getLocation(RetPC);
255
256 return S.getLocation(Func, PC);
257}
258
260 if (Func && !funcHasUsableBody(Func) && Caller)
261 return Caller->getRange(RetPC);
262
263 return S.getRange(Func, PC);
264}
265
267 if (!Func)
268 return false;
269 for (const DeclContext *DC = Func->getDecl(); DC; DC = DC->getParent())
270 if (DC->isStdNamespace())
271 return true;
272
273 return false;
274}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3443
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx, QualType Ty)
static bool shouldSkipInBacktrace(const Function *F)
static bool funcHasUsableBody(const Function *F)
#define TYPE_SWITCH(Expr, B)
Definition: PrimType.h:153
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
QualType getRecordType(const RecordDecl *Decl) const
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
This represents one expression.
Definition: Expr.h:110
Represents a function declaration or definition.
Definition: Decl.h:1935
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3702
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Definition: Decl.cpp:3088
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
A (possibly-)qualified type.
Definition: Type.h:929
Encodes a location in the source.
A trivial tuple used to represent a source range.
bool isValid() const
QualType getType() const
Definition: Decl.h:682
A memory block, either on the stack or in the heap.
Definition: InterpBlock.h:49
void invokeCtor()
Invokes the constructor.
Definition: InterpBlock.h:112
Pointer into the code segment.
Definition: Source.h:30
std::optional< PrimType > classify(QualType T) const
Classifies a type.
Definition: Context.cpp:135
unsigned getEvalID() const
Definition: Context.h:113
Base class for stack frames, shared between VM and walker.
Definition: Frame.h:25
Bytecode function.
Definition: Function.h:81
Scope & getScope(unsigned Idx)
Returns a specific scope.
Definition: Function.h:134
bool isDestructor() const
Checks if the function is a destructor.
Definition: Function.h:152
bool isBuiltin() const
Definition: Function.h:198
bool isConstructor() const
Checks if the function is a constructor.
Definition: Function.h:147
const FunctionDecl * getDecl() const
Returns the original FunctionDecl.
Definition: Function.h:96
bool hasThisPointer() const
Definition: Function.h:186
bool isLambdaStaticInvoker() const
Returns whether this function is a lambda static invoker, which we generate custom byte code for.
Definition: Function.h:167
ParamDescriptor getParamDescriptor(unsigned Offset) const
Returns a parameter descriptor.
Definition: Function.cpp:30
llvm::iterator_range< llvm::SmallVector< Scope, 2 >::const_iterator > scopes() const
Range over the scope blocks.
Definition: Function.h:122
bool hasRVO() const
Checks if the first argument is a RVO pointer.
Definition: Function.h:116
Frame storing local variables.
Definition: InterpFrame.h:26
const Expr * getExpr(CodePtr PC) const
InterpFrame * Caller
The frame of the previous function.
Definition: InterpFrame.h:29
virtual SourceInfo getSource(CodePtr PC) const
Map a location to a source.
CodePtr getRetPC() const
Returns the return address of the frame.
Definition: InterpFrame.h:110
SourceLocation getLocation(CodePtr PC) const
~InterpFrame()
Destroys the frame, killing all live pointers to stack slots.
Definition: InterpFrame.cpp:69
const Function * getFunction() const
Returns the current function.
Definition: InterpFrame.h:62
SourceRange getRange(CodePtr PC) const
Pointer getLocalPointer(unsigned Offset) const
Returns a pointer to a local variables.
Frame * getCaller() const override
Returns the parent frame object.
InterpFrame(InterpState &S, const Function *Func, InterpFrame *Caller, CodePtr RetPC, unsigned ArgSize)
Creates a new frame for a method call.
Definition: InterpFrame.cpp:26
void destroy(unsigned Idx)
Invokes the destructors for a scope.
Definition: InterpFrame.cpp:93
Pointer getParamPointer(unsigned Offset)
Returns a pointer to an argument - lazily creates a block.
const FunctionDecl * getCallee() const override
Returns the caller.
void initScope(unsigned Idx)
Definition: InterpFrame.cpp:85
SourceRange getCallRange() const override
Returns the location of the call to the frame.
void describe(llvm::raw_ostream &OS) const override
Describes the frame with arguments for diagnostic purposes.
Interpreter context.
Definition: InterpState.h:36
Context & Ctx
Interpreter Context.
Definition: InterpState.h:136
ASTContext & getASTContext() const override
Definition: InterpState.h:62
SourceInfo getSource(const Function *F, CodePtr PC) const override
Delegates source mapping to the mapper.
Definition: InterpState.h:98
SourceLocation EvalLocation
Source location of the evaluating expression.
Definition: InterpState.h:140
void deallocate(Block *B)
Deallocates a pointer.
Definition: InterpState.cpp:67
A pointer to a memory block, live or dead.
Definition: Pointer.h:83
Describes a scope block.
Definition: Function.h:36
llvm::iterator_range< LocalVectorTy::const_iterator > locals() const
Definition: Function.h:50
Describes the statement/declaration an opcode was generated from.
Definition: Source.h:77
SourceLocation getLocation(const Function *F, CodePtr PC) const
Returns the location from which an opcode originates.
Definition: Source.cpp:47
SourceRange getRange(const Function *F, CodePtr PC) const
Definition: Source.cpp:51
const Expr * getExpr(const Function *F, CodePtr PC) const
Returns the expression if an opcode belongs to one, null otherwise.
Definition: Source.cpp:41
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition: PrimType.h:131
PrimType
Enumeration of the primitive types of the VM.
Definition: PrimType.h:34
size_t primSize(PrimType Type)
Returns the size of a primitive type in bytes.
Definition: PrimType.cpp:23
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
const FunctionProtoType * T
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
Inline descriptor embedded in structures and arrays.
Definition: Descriptor.h:70