clang 24.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 "Char.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"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/ExprCXX.h"
21
22using namespace clang;
23using namespace clang::interp;
24
26 : Caller(nullptr), S(S), Func(nullptr), RetPC(CodePtr()), Args(nullptr),
27 ArgSize(0) {}
28
30 InterpFrame *Caller, CodePtr RetPC, unsigned ArgSize)
31 : Caller(Caller), S(S), Func(Func), RetPC(RetPC),
32 Args(static_cast<char *>(S.Stk.top())), ArgSize(ArgSize) {
33 assert(Func);
34#ifndef NDEBUG
35 FrameOffset = S.Stk.size();
36#endif
37
38 FuncFlags |= Func->hasRVO() * HasRVOFlag;
39 FuncFlags |= Func->hasThisPointer() * HasThisFlag;
40
41 // Initialize argument blocks.
42 for (unsigned I = 0, N = Func->getNumWrittenParams(); I != N; ++I)
43 new (argBlock(I))
44 Block(S.EvalID, Func->getParamDescriptor(I).Desc, Block::None);
45
46 if (Func->getFrameSize() == 0)
47 return;
48
49 for (auto &Scope : Func->scopes()) {
50 for (auto &Local : Scope.locals()) {
51 Block *B = localBlock(Local.Offset);
52 new (B) Block(S.EvalID, Local.Desc, Block::Local);
53 // Note that we are NOT calling invokeCtor() here, since that is done
54 // lazily when accessing the local.
55 }
56 }
57}
58
60 unsigned VarArgSize)
61 : InterpFrame(S, Func, S.Current, RetPC, Func->getArgSize() + VarArgSize) {
62 // As per our calling convention, the this pointer is
63 // part of the ArgSize.
64 // If the function has RVO, the RVO pointer is first.
65 // If the fuction has a This pointer, that one is next.
66 // Then follow the actual arguments (but those are handled
67 // in getParamPointer()).
68}
69
71 if (!Func)
72 return;
73
74 // De-initialize all argument blocks.
75 for (unsigned I = 0, N = Func->getNumWrittenParams(); I != N; ++I)
76 S.deallocate(argBlock(I));
77
78 // When destroying the InterpFrame, call the Dtor for all blocks
79 // that haven't been destroyed via a destroy() op yet.
80 // This happens when the execution is interruped midway-through.
81 for (auto &Scope : Func->scopes()) {
82 for (auto &Local : Scope.locals()) {
83 Block *B = localBlock(Local.Offset);
84 if (B->isInitialized())
85 S.deallocate(B);
86 }
87 }
88}
89
90void InterpFrame::enableLocal(unsigned Offset) {
91 assert(Func);
92 getLocalBlock(Offset)->getBlockDesc<LocalInlineDescriptor>().IsEnabled = true;
93}
94
95void InterpFrame::destroy(unsigned Idx) {
96 for (auto &Local : Func->getScope(Idx).locals_reverse()) {
97 Block *B = localBlock(Local.Offset);
98 if (B->isInitialized())
99 S.deallocate(B);
100 }
101}
102
103template <typename T>
104static void print(llvm::raw_ostream &OS, const T &V, const Context &Ctx,
105 QualType Ty) {
106 if constexpr (std::is_same_v<Pointer, T>) {
107 if (Ty->isPointerOrReferenceType())
108 V.toAPValue(Ctx.getASTContext()).printPretty(OS, Ctx.getASTContext(), Ty);
109 else {
110 if (std::optional<APValue> RValue = V.toRValue(Ctx, Ty))
111 RValue->printPretty(OS, Ctx.getASTContext(), Ty);
112 else
113 OS << "...";
114 }
115 } else {
116 V.toAPValue(Ctx.getASTContext()).printPretty(OS, Ctx.getASTContext(), Ty);
117 }
118}
119
120static bool shouldSkipInBacktrace(const Function *F) {
121 if (F->isLambdaStaticInvoker())
122 return true;
123
124 const FunctionDecl *FD = F->getDecl();
125 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
126 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New)
127 return true;
128
129 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
130 MD && MD->getParent()->isAnonymousStructOrUnion())
131 return true;
132
133 return false;
134}
135
136void InterpFrame::describe(llvm::raw_ostream &OS) const {
137 assert(Func);
138 // For lambda static invokers, we would just print __invoke().
139 if (shouldSkipInBacktrace(Func))
140 return;
141
142 const ASTContext &ASTCtx = S.getASTContext();
143 const Expr *CallExpr = Caller->getExpr(getRetOpPC());
144 const FunctionDecl *F = Func->getDecl();
145 auto PrintingPolicy = ASTCtx.getPrintingPolicy();
147
148 bool IsMemberCall = false;
149 bool ExplicitInstanceParam = false;
150 if (const auto *MD = dyn_cast<CXXMethodDecl>(F)) {
151 IsMemberCall = !isa<CXXConstructorDecl>(MD) && !MD->isStatic();
152 ExplicitInstanceParam = MD->isExplicitObjectMemberFunction();
153 }
154
155 if (Func->hasThisPointer() && IsMemberCall) {
156 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
157 const Expr *Object = MCE->getImplicitObjectArgument();
158 Object->printPretty(OS, /*Helper=*/nullptr,
160 /*Indentation=*/0);
161 if (Object->getType()->isPointerType())
162 OS << "->";
163 else
164 OS << '.';
165 } else if (const auto *OCE =
166 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
167 OCE->getArg(0)->printPretty(OS, /*Helper=*/nullptr,
169 /*Indentation=*/0);
170 OS << '.';
171 } else if (const auto *M = dyn_cast<CXXMethodDecl>(F)) {
172 print(OS, getThis(), S.getContext(),
174 ASTCtx.getCanonicalTagType(M->getParent())));
175 OS << '.';
176 }
177 }
178
179 F->getNameForDiagnostic(OS, PrintingPolicy, /*Qualified=*/false);
180 OS << '(';
181 unsigned Off = 0;
182 unsigned ParamIndex = ExplicitInstanceParam;
183 Off += Func->hasRVO() ? primSize(PT_Ptr) : 0;
184 Off += Func->hasThisPointer() ? primSize(PT_Ptr) : 0;
185 llvm::ListSeparator Comma;
186 for (const ParmVarDecl *Param :
187 F->parameters().slice(ExplicitInstanceParam)) {
188 OS << Comma;
189 PrimType PrimT = Func->getParamDescriptor(ParamIndex).T;
190 TYPE_SWITCH(PrimT,
191 print(OS, stackRef<T>(Off), S.getContext(), Param->getType()));
192 Off += align(primSize(PrimT));
193 ++ParamIndex;
194 }
195 OS << ')';
196}
197
199 if (!Caller->Func) {
200 if (SourceRange NullRange = S.getSource({}).getRange(); NullRange.isValid())
201 return NullRange;
202
203 return S.EvalLocation;
204 }
205
206 // Move up to the frame that has a valid location for the caller.
207 for (const InterpFrame *C = this; C; C = C->Caller) {
208 if (!C->RetPC)
209 continue;
210 SourceRange CallRange =
211 C->Caller->Func->getSource(C->getRetOpPC()).getRange();
212 if (CallRange.isValid())
213 return CallRange;
214 }
215 return S.EvalLocation;
216}
217
219 if (!Func)
220 return nullptr;
221 return Func->getDecl();
222}
223
225 assert(!isBottomFrame());
226
227 Block *B = argBlock(Index);
228
229 // Copy the initial value.
230 if (!B->isInitialized()) {
231 unsigned ByteOffset = Func->getParamDescriptor(Index).Offset;
232 assert(B->getDescriptor()->isPrimitive());
233 B->invokeCtor();
235 new (B->data()) T(stackRef<T>(ByteOffset)));
236 assert(B->isInitialized());
237 }
238
239 return Pointer(B);
240}
241
242static bool funcHasUsableBody(const Function *F) {
243 assert(F);
244
245 if (F->isConstructor() || F->isDestructor())
246 return true;
247
248 return !F->getDecl()->isImplicit();
249}
250
252 if (!Func)
253 return S.getSource(PC);
254
255 // Implicitly created functions don't have any code we could point at,
256 // so return the call site.
257 if (Func && !funcHasUsableBody(Func) && Caller)
258 return Caller->getSource(getRetOpPC());
259
260 // If we have a frame for an invalid function, check the caller.
261 // This happens for the fake function frame we create in TrivialCopy.
262 if (Func && !Func->isValid())
263 return Caller->getSource(getRetOpPC());
264
265 // Similarly, if the resulting source location is invalid anyway,
266 // point to the caller instead.
267 SourceInfo Result = Func->getSource(PC);
268 if (Result.getLoc().isInvalid() && Caller)
269 return Caller->getSource(getRetOpPC());
270
271 return Result;
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)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool shouldSkipInBacktrace(const Function *F)
static void print(llvm::raw_ostream &OS, const T &V, const Context &Ctx, QualType Ty)
static bool funcHasUsableBody(const Function *F)
llvm::json::Object Object
#define TYPE_SWITCH(Expr, B)
Definition PrimType.h:240
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
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:905
CanQualType getCanonicalTagType(const TagDecl *TD) const
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2108
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:114
Represents a function declaration or definition.
Definition Decl.h:2071
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2917
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:3129
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
Represents a parameter to a function.
Definition Decl.h:1832
A (possibly-)qualified type.
Definition TypeBase.h:938
A trivial tuple used to represent a source range.
bool isPointerOrReferenceType() const
Definition TypeBase.h:8819
A memory block, either on the stack or in the heap.
Definition Block.h:68
std::byte * data()
Returns a pointer to the stored data.
Definition Block.h:140
const Descriptor * getDescriptor() const
Returns the block's descriptor.
Definition Block.h:103
void invokeCtor()
Invokes the constructor.
Definition Block.h:165
bool isInitialized() const
Returns whether the data of this block has been initialized via invoking the Ctor func.
Definition Block.h:130
Pointer into the code segment.
Definition Source.h:31
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:49
ASTContext & getASTContext() const
Returns the AST context.
Definition Context.h:116
Bytecode function.
Definition Function.h:98
CodePtr getRetOpPC() const
Returns the return address of the opcode in the caller frame.
InterpFrame(InterpState &S)
Bottom Frame.
InterpFrame * Caller
The frame of the previous function.
SourceInfo getSource(CodePtr PC) const
Map a location to a source.
~InterpFrame()
Destroys the frame, killing all live pointers to stack slots.
const Pointer & getThis() const
Returns the 'this' pointer.
unsigned getArgSize() const
Block * getLocalBlock(unsigned Offset) const
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 enableLocal(unsigned Offset)
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:47
A pointer to a memory block, live or dead.
Definition Pointer.h:547
Describes a scope block.
Definition Function.h:35
llvm::iterator_range< LocalVectorTy::const_iterator > locals() const
Definition Function.h:51
Describes the statement/declaration an opcode was generated from.
Definition Source.h:77
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:218
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:35
size_t primSize(PrimType Type)
Returns the size of a primitive type in bytes.
Definition PrimType.cpp:25
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
@ Off
Never emit colors regardless of the output stream.
Describes how types, statements, expressions, and declarations should be printed.
unsigned SuppressLambdaBody
Whether to suppress printing the body of a lambda.
bool isPrimitive() const
Checks if the descriptor is of a primitive.
Definition Descriptor.h:269
PrimType getPrimType() const
Definition Descriptor.h:240