clang 21.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 : Caller(nullptr), S(S), Depth(0), Func(nullptr), RetPC(CodePtr()),
28 ArgSize(0), Args(nullptr), FrameOffset(0), IsBottom(true) {}
29
31 InterpFrame *Caller, CodePtr RetPC, unsigned ArgSize)
32 : Caller(Caller), S(S), Depth(Caller ? Caller->Depth + 1 : 0), Func(Func),
33 RetPC(RetPC), ArgSize(ArgSize), Args(static_cast<char *>(S.Stk.top())),
34 FrameOffset(S.Stk.size()), IsBottom(!Caller) {
35 if (!Func)
36 return;
37
38 unsigned FrameSize = Func->getFrameSize();
39 if (FrameSize == 0)
40 return;
41
42 Locals = std::make_unique<char[]>(FrameSize);
43 for (auto &Scope : Func->scopes()) {
44 for (auto &Local : Scope.locals()) {
45 new (localBlock(Local.Offset)) Block(S.Ctx.getEvalID(), Local.Desc);
46 // Note that we are NOT calling invokeCtor() here, since that is done
47 // via the InitScope op.
48 new (localInlineDesc(Local.Offset)) InlineDescriptor(Local.Desc);
49 }
50 }
51}
52
54 unsigned VarArgSize)
55 : InterpFrame(S, Func, S.Current, RetPC, Func->getArgSize() + VarArgSize) {
56 // As per our calling convention, the this pointer is
57 // part of the ArgSize.
58 // If the function has RVO, the RVO pointer is first.
59 // If the fuction has a This pointer, that one is next.
60 // Then follow the actual arguments (but those are handled
61 // in getParamPointer()).
62 if (Func->hasRVO())
63 RVOPtr = stackRef<Pointer>(0);
64
65 if (Func->hasThisPointer()) {
66 if (Func->hasRVO())
67 This = stackRef<Pointer>(sizeof(Pointer));
68 else
69 This = stackRef<Pointer>(0);
70 }
71}
72
74 for (auto &Param : Params)
75 S.deallocate(reinterpret_cast<Block *>(Param.second.get()));
76
77 // When destroying the InterpFrame, call the Dtor for all block
78 // that haven't been destroyed via a destroy() op yet.
79 // This happens when the execution is interruped midway-through.
81}
82
84 if (!Func)
85 return;
86 for (auto &Scope : Func->scopes()) {
87 for (auto &Local : Scope.locals()) {
88 S.deallocate(localBlock(Local.Offset));
89 }
90 }
91}
92
93void InterpFrame::initScope(unsigned Idx) {
94 if (!Func)
95 return;
96 for (auto &Local : Func->getScope(Idx).locals()) {
97 localBlock(Local.Offset)->invokeCtor();
98 }
99}
100
101void InterpFrame::destroy(unsigned Idx) {
102 for (auto &Local : Func->getScope(Idx).locals()) {
103 S.deallocate(localBlock(Local.Offset));
104 }
105}
106
107template <typename T>
108static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx,
109 QualType Ty) {
110 V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);
111}
112
113static bool shouldSkipInBacktrace(const Function *F) {
114 if (F->isBuiltin())
115 return true;
116 if (F->isLambdaStaticInvoker())
117 return true;
118
119 const FunctionDecl *FD = F->getDecl();
120 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
121 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New)
122 return true;
123 return false;
124}
125
126void InterpFrame::describe(llvm::raw_ostream &OS) const {
127 // We create frames for builtin functions as well, but we can't reliably
128 // diagnose them. The 'in call to' diagnostics for them add no value to the
129 // user _and_ it doesn't generally work since the argument types don't always
130 // match the function prototype. Just ignore them.
131 // Similarly, for lambda static invokers, we would just print __invoke().
132 if (const auto *F = getFunction(); F && shouldSkipInBacktrace(F))
133 return;
134
135 const Expr *CallExpr = Caller->getExpr(getRetPC());
136 const FunctionDecl *F = getCallee();
137 bool IsMemberCall = isa<CXXMethodDecl>(F) && !isa<CXXConstructorDecl>(F) &&
138 cast<CXXMethodDecl>(F)->isImplicitObjectMemberFunction();
139 if (Func->hasThisPointer() && IsMemberCall) {
140 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
141 const Expr *Object = MCE->getImplicitObjectArgument();
142 Object->printPretty(OS, /*Helper=*/nullptr,
144 /*Indentation=*/0);
145 if (Object->getType()->isPointerType())
146 OS << "->";
147 else
148 OS << ".";
149 } else if (const auto *OCE =
150 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
151 OCE->getArg(0)->printPretty(OS, /*Helper=*/nullptr,
153 /*Indentation=*/0);
154 OS << ".";
155 } else if (const auto *M = dyn_cast<CXXMethodDecl>(F)) {
156 print(OS, This, S.getASTContext(),
158 S.getASTContext().getRecordType(M->getParent())));
159 OS << ".";
160 }
161 }
162
164 /*Qualified=*/false);
165 OS << '(';
166 unsigned Off = 0;
167
168 Off += Func->hasRVO() ? primSize(PT_Ptr) : 0;
169 Off += Func->hasThisPointer() ? primSize(PT_Ptr) : 0;
170
171 for (unsigned I = 0, N = F->getNumParams(); I < N; ++I) {
172 QualType Ty = F->getParamDecl(I)->getType();
173
174 PrimType PrimTy = S.Ctx.classify(Ty).value_or(PT_Ptr);
175
176 TYPE_SWITCH(PrimTy, print(OS, stackRef<T>(Off), S.getASTContext(), Ty));
177 Off += align(primSize(PrimTy));
178 if (I + 1 != N)
179 OS << ", ";
180 }
181 OS << ")";
182}
183
185 if (Caller->Caller)
186 return Caller;
187 return S.getSplitFrame();
188}
189
191 if (!Caller->Func) {
192 if (SourceRange NullRange = S.getRange(nullptr, {}); NullRange.isValid())
193 return NullRange;
194 return S.EvalLocation;
195 }
196 return S.getRange(Caller->Func, RetPC - sizeof(uintptr_t));
197}
198
200 if (!Func)
201 return nullptr;
202 return Func->getDecl();
203}
204
205Pointer InterpFrame::getLocalPointer(unsigned Offset) const {
206 assert(Offset < Func->getFrameSize() && "Invalid local offset.");
207 return Pointer(localBlock(Offset));
208}
209
211 // Return the block if it was created previously.
212 if (auto Pt = Params.find(Off); Pt != Params.end())
213 return Pointer(reinterpret_cast<Block *>(Pt->second.get()));
214
215 // Allocate memory to store the parameter and the block metadata.
216 const auto &Desc = Func->getParamDescriptor(Off);
217 size_t BlockSize = sizeof(Block) + Desc.second->getAllocSize();
218 auto Memory = std::make_unique<char[]>(BlockSize);
219 auto *B = new (Memory.get()) Block(S.Ctx.getEvalID(), Desc.second);
220 B->invokeCtor();
221
222 // Copy the initial value.
223 TYPE_SWITCH(Desc.first, new (B->data()) T(stackRef<T>(Off)));
224
225 // Record the param.
226 Params.insert({Off, std::move(Memory)});
227 return Pointer(B);
228}
229
230static bool funcHasUsableBody(const Function *F) {
231 assert(F);
232
233 if (F->isConstructor() || F->isDestructor())
234 return true;
235
236 return !F->getDecl()->isImplicit();
237}
238
240 // Implicitly created functions don't have any code we could point at,
241 // so return the call site.
242 if (Func && !funcHasUsableBody(Func) && Caller)
243 return Caller->getSource(RetPC);
244
245 // Similarly, if the resulting source location is invalid anyway,
246 // point to the caller instead.
247 SourceInfo Result = S.getSource(Func, PC);
248 if (Result.getLoc().isInvalid() && Caller)
249 return Caller->getSource(RetPC);
250 return Result;
251}
252
254 if (Func && !funcHasUsableBody(Func) && Caller)
255 return Caller->getExpr(RetPC);
256
257 return S.getExpr(Func, PC);
258}
259
261 if (Func && !funcHasUsableBody(Func) && Caller)
262 return Caller->getLocation(RetPC);
263
264 return S.getLocation(Func, PC);
265}
266
268 if (Func && !funcHasUsableBody(Func) && Caller)
269 return Caller->getRange(RetPC);
270
271 return S.getRange(Func, PC);
272}
273
275 if (!Func)
276 return false;
277 for (const DeclContext *DC = Func->getDecl(); DC; DC = DC->getParent())
278 if (DC->isStdNamespace())
279 return true;
280
281 return false;
282}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3460
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:1442
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2107
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:3713
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:3084
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:132
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:141
bool isDestructor() const
Checks if the function is a destructor.
Definition: Function.h:156
bool isBuiltin() const
Definition: Function.h:193
bool isConstructor() const
Checks if the function is a constructor.
Definition: Function.h:154
const FunctionDecl * getDecl() const
Returns the original FunctionDecl.
Definition: Function.h:103
bool hasThisPointer() const
Definition: Function.h:181
bool isLambdaStaticInvoker() const
Returns whether this function is a lambda static invoker, which we generate custom byte code for.
Definition: Function.h:160
ParamDescriptor getParamDescriptor(unsigned Offset) const
Returns a parameter descriptor.
Definition: Function.cpp:46
llvm::iterator_range< llvm::SmallVector< Scope, 2 >::const_iterator > scopes() const
Range over the scope blocks.
Definition: Function.h:129
bool hasRVO() const
Checks if the first argument is a RVO pointer.
Definition: Function.h:123
Frame storing local variables.
Definition: InterpFrame.h:26
InterpFrame(InterpState &S)
Bottom Frame.
Definition: InterpFrame.cpp: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:119
SourceLocation getLocation(CodePtr PC) const
~InterpFrame()
Destroys the frame, killing all live pointers to stack slots.
Definition: InterpFrame.cpp:73
const Function * getFunction() const
Returns the current function.
Definition: InterpFrame.h:71
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.
void destroy(unsigned Idx)
Invokes the destructors for a scope.
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:93
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:138
ASTContext & getASTContext() const override
Definition: InterpState.h:64
SourceInfo getSource(const Function *F, CodePtr PC) const override
Delegates source mapping to the mapper.
Definition: InterpState.h:100
SourceLocation EvalLocation
Source location of the evaluating expression.
Definition: InterpState.h:144
void deallocate(Block *B)
Deallocates a pointer.
Definition: InterpState.cpp:75
A pointer to a memory block, live or dead.
Definition: Pointer.h:88
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...
#define true
Definition: stdbool.h:25
Inline descriptor embedded in structures and arrays.
Definition: Descriptor.h:70