Thanks to visit codestin.com
Credit goes to clang.llvm.org

clang 22.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 "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"
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), Depth(0), Func(nullptr), RetPC(CodePtr()),
27 ArgSize(0), Args(nullptr), FrameOffset(0) {}
28
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 if (!Func)
35 return;
36
37 unsigned FrameSize = Func->getFrameSize();
38 if (FrameSize == 0)
39 return;
40
41 Locals = std::make_unique<char[]>(FrameSize);
42 for (auto &Scope : Func->scopes()) {
43 for (auto &Local : Scope.locals()) {
44 new (localBlock(Local.Offset)) Block(S.Ctx.getEvalID(), Local.Desc);
45 // Note that we are NOT calling invokeCtor() here, since that is done
46 // via the InitScope op.
47 new (localInlineDesc(Local.Offset)) InlineDescriptor(Local.Desc);
48 }
49 }
50}
51
53 unsigned VarArgSize)
54 : InterpFrame(S, Func, S.Current, RetPC, Func->getArgSize() + VarArgSize) {
55 // As per our calling convention, the this pointer is
56 // part of the ArgSize.
57 // If the function has RVO, the RVO pointer is first.
58 // If the fuction has a This pointer, that one is next.
59 // Then follow the actual arguments (but those are handled
60 // in getParamPointer()).
61 if (Func->hasRVO()) {
62 // RVO pointer offset is always 0.
63 }
64
65 if (Func->hasThisPointer())
66 ThisPointerOffset = Func->hasRVO() ? sizeof(Pointer) : 0;
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.
77}
78
80 if (!Func)
81 return;
82 for (auto &Scope : Func->scopes()) {
83 for (auto &Local : Scope.locals()) {
84 S.deallocate(localBlock(Local.Offset));
85 }
86 }
87}
88
89void InterpFrame::initScope(unsigned Idx) {
90 if (!Func)
91 return;
92 for (auto &Local : Func->getScope(Idx).locals()) {
93 localBlock(Local.Offset)->invokeCtor();
94 }
95}
96
97void InterpFrame::destroy(unsigned Idx) {
98 for (auto &Local : Func->getScope(Idx).locals_reverse()) {
99 S.deallocate(localBlock(Local.Offset));
100 }
101}
102
103template <typename T>
104static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx,
105 QualType Ty) {
106 if constexpr (std::is_same_v<Pointer, T>) {
107 if (Ty->isPointerOrReferenceType())
108 V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);
109 else {
110 if (std::optional<APValue> RValue = V.toRValue(ASTCtx, Ty))
111 RValue->printPretty(OS, ASTCtx, Ty);
112 else
113 OS << "...";
114 }
115 } else {
116 V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, 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 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
134 Ctor && Ctor->isDefaulted() && Ctor->isTrivial() &&
135 Ctor->isCopyOrMoveConstructor() && Ctor->inits().empty())
136 return true;
137
138 return false;
139}
140
141void InterpFrame::describe(llvm::raw_ostream &OS) const {
142 // For lambda static invokers, we would just print __invoke().
143 if (const auto *F = getFunction(); F && shouldSkipInBacktrace(F))
144 return;
145
146 const Expr *CallExpr = Caller->getExpr(getRetPC());
147 const FunctionDecl *F = getCallee();
148 bool IsMemberCall = isa<CXXMethodDecl>(F) && !isa<CXXConstructorDecl>(F) &&
149 cast<CXXMethodDecl>(F)->isImplicitObjectMemberFunction();
150 if (Func->hasThisPointer() && IsMemberCall) {
151 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
152 const Expr *Object = MCE->getImplicitObjectArgument();
153 Object->printPretty(OS, /*Helper=*/nullptr,
154 S.getASTContext().getPrintingPolicy(),
155 /*Indentation=*/0);
156 if (Object->getType()->isPointerType())
157 OS << "->";
158 else
159 OS << ".";
160 } else if (const auto *OCE =
161 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
162 OCE->getArg(0)->printPretty(OS, /*Helper=*/nullptr,
163 S.getASTContext().getPrintingPolicy(),
164 /*Indentation=*/0);
165 OS << ".";
166 } else if (const auto *M = dyn_cast<CXXMethodDecl>(F)) {
167 print(OS, getThis(), S.getASTContext(),
168 S.getASTContext().getLValueReferenceType(
169 S.getASTContext().getCanonicalTagType(M->getParent())));
170 OS << ".";
171 }
172 }
173
174 F->getNameForDiagnostic(OS, S.getASTContext().getPrintingPolicy(),
175 /*Qualified=*/false);
176 OS << '(';
177 unsigned Off = 0;
178
179 Off += Func->hasRVO() ? primSize(PT_Ptr) : 0;
180 Off += Func->hasThisPointer() ? primSize(PT_Ptr) : 0;
181
182 for (unsigned I = 0, N = F->getNumParams(); I < N; ++I) {
183 QualType Ty = F->getParamDecl(I)->getType();
184
185 PrimType PrimTy = S.Ctx.classify(Ty).value_or(PT_Ptr);
186
187 TYPE_SWITCH(PrimTy, print(OS, stackRef<T>(Off), S.getASTContext(), Ty));
188 Off += align(primSize(PrimTy));
189 if (I + 1 != N)
190 OS << ", ";
191 }
192 OS << ")";
193}
194
196 if (!Caller->Func) {
197 if (SourceRange NullRange = S.getRange(nullptr, {}); NullRange.isValid())
198 return NullRange;
199 return S.EvalLocation;
200 }
201
202 // Move up to the frame that has a valid location for the caller.
203 for (const InterpFrame *C = this; C; C = C->Caller) {
204 if (!C->RetPC)
205 continue;
206 SourceRange CallRange =
207 S.getRange(C->Caller->Func, C->RetPC - sizeof(uintptr_t));
208 if (CallRange.isValid())
209 return CallRange;
210 }
211 return S.EvalLocation;
212}
213
215 if (!Func)
216 return nullptr;
217 return Func->getDecl();
218}
219
220Pointer InterpFrame::getLocalPointer(unsigned Offset) const {
221 assert(Offset < Func->getFrameSize() && "Invalid local offset.");
222 return Pointer(localBlock(Offset));
223}
224
225Block *InterpFrame::getLocalBlock(unsigned Offset) const {
226 return localBlock(Offset);
227}
228
230 // Return the block if it was created previously.
231 if (auto Pt = Params.find(Off); Pt != Params.end())
232 return Pointer(reinterpret_cast<Block *>(Pt->second.get()));
233
234 // Allocate memory to store the parameter and the block metadata.
235 const auto &Desc = Func->getParamDescriptor(Off);
236 size_t BlockSize = sizeof(Block) + Desc.second->getAllocSize();
237 auto Memory = std::make_unique<char[]>(BlockSize);
238 auto *B = new (Memory.get()) Block(S.Ctx.getEvalID(), Desc.second);
239 B->invokeCtor();
240
241 // Copy the initial value.
242 TYPE_SWITCH(Desc.first, new (B->data()) T(stackRef<T>(Off)));
243
244 // Record the param.
245 Params.insert({Off, std::move(Memory)});
246 return Pointer(B);
247}
248
249static bool funcHasUsableBody(const Function *F) {
250 assert(F);
251
252 if (F->isConstructor() || F->isDestructor())
253 return true;
254
255 return !F->getDecl()->isImplicit();
256}
257
259 // Implicitly created functions don't have any code we could point at,
260 // so return the call site.
261 if (Func && !funcHasUsableBody(Func) && Caller)
262 return Caller->getSource(RetPC);
263
264 // Similarly, if the resulting source location is invalid anyway,
265 // point to the caller instead.
266 SourceInfo Result = S.getSource(Func, PC);
267 if (Result.getLoc().isInvalid() && Caller)
268 return Caller->getSource(RetPC);
269 return Result;
270}
271
273 if (Func && !funcHasUsableBody(Func) && Caller)
274 return Caller->getExpr(RetPC);
275
276 return S.getExpr(Func, PC);
277}
278
280 if (Func && !funcHasUsableBody(Func) && Caller)
281 return Caller->getLocation(RetPC);
282
283 return S.getLocation(Func, PC);
284}
285
287 if (Func && !funcHasUsableBody(Func) && Caller)
288 return Caller->getRange(RetPC);
289
290 return S.getRange(Func, PC);
291}
292
294 if (!Func)
295 return false;
296 for (const DeclContext *DC = Func->getDecl(); DC; DC = DC->getParent())
297 if (DC->isStdNamespace())
298 return true;
299
300 return false;
301}
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 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:207
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:188
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
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:112
Represents a function declaration or definition.
Definition Decl.h:1999
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2794
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3767
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:3117
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
A (possibly-)qualified type.
Definition TypeBase.h:937
Encodes a location in the source.
A trivial tuple used to represent a source range.
bool isPointerOrReferenceType() const
Definition TypeBase.h:8526
QualType getType() const
Definition Decl.h:722
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:44
Pointer into the code segment.
Definition Source.h:30
Bytecode function.
Definition Function.h:86
InterpFrame(InterpState &S)
Bottom Frame.
const Expr * getExpr(CodePtr PC) const
InterpFrame * Caller
The frame of the previous function.
Definition InterpFrame.h:29
SourceInfo getSource(CodePtr PC) const
Map a location to a source.
CodePtr getRetPC() const
Returns the return address of the frame.
Block * getLocalBlock(unsigned Offset) const
SourceLocation getLocation(CodePtr PC) const
~InterpFrame()
Destroys the frame, killing all live pointers to stack slots.
const Pointer & getThis() const
Returns the 'this' pointer.
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.
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)
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:43
A pointer to a memory block, live or dead.
Definition Pointer.h:91
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:73
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:185
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.
bool isa(CodeGen::Address addr)
Definition Address.h:330
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
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:905
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition Address.h:327
__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:67