clang 19.0.0git
Context.cpp
Go to the documentation of this file.
1//===--- Context.cpp - Context for the constexpr 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 "Context.h"
10#include "ByteCodeEmitter.h"
11#include "ByteCodeExprGen.h"
12#include "ByteCodeStmtGen.h"
13#include "EvalEmitter.h"
14#include "Interp.h"
15#include "InterpFrame.h"
16#include "InterpStack.h"
17#include "PrimType.h"
18#include "Program.h"
19#include "clang/AST/Expr.h"
21
22using namespace clang;
23using namespace clang::interp;
24
25Context::Context(ASTContext &Ctx) : Ctx(Ctx), P(new Program(*this)) {}
26
28
30 assert(Stk.empty());
31 Function *Func = P->getFunction(FD);
32 if (!Func || !Func->hasBody())
33 Func = ByteCodeStmtGen<ByteCodeEmitter>(*this, *P).compileFunc(FD);
34
35 APValue DummyResult;
36 if (!Run(Parent, Func, DummyResult))
37 return false;
38
39 return Func->isConstexpr();
40}
41
43 bool Recursing = !Stk.empty();
44 ByteCodeExprGen<EvalEmitter> C(*this, *P, Parent, Stk);
45
46 auto Res = C.interpretExpr(E, /*ConvertResultToRValue=*/E->isGLValue());
47
48 if (Res.isInvalid()) {
49 Stk.clear();
50 return false;
51 }
52
53 if (!Recursing) {
54 assert(Stk.empty());
55#ifndef NDEBUG
56 // Make sure we don't rely on some value being still alive in
57 // InterpStack memory.
58 Stk.clear();
59#endif
60 }
61
62 Result = Res.toAPValue();
63
64 return true;
65}
66
68 bool Recursing = !Stk.empty();
69 ByteCodeExprGen<EvalEmitter> C(*this, *P, Parent, Stk);
70
71 auto Res = C.interpretExpr(E);
72 if (Res.isInvalid()) {
73 Stk.clear();
74 return false;
75 }
76
77 if (!Recursing) {
78 assert(Stk.empty());
79#ifndef NDEBUG
80 // Make sure we don't rely on some value being still alive in
81 // InterpStack memory.
82 Stk.clear();
83#endif
84 }
85
86 Result = Res.toAPValue();
87 return true;
88}
89
91 APValue &Result) {
92 bool Recursing = !Stk.empty();
93 ByteCodeExprGen<EvalEmitter> C(*this, *P, Parent, Stk);
94
97 (VD->getType()->isRecordType() || VD->getType()->isArrayType());
98 auto Res = C.interpretDecl(VD, CheckGlobalInitialized);
99 if (Res.isInvalid()) {
100 Stk.clear();
101 return false;
102 }
103
104 if (!Recursing) {
105 assert(Stk.empty());
106#ifndef NDEBUG
107 // Make sure we don't rely on some value being still alive in
108 // InterpStack memory.
109 Stk.clear();
110#endif
111 }
112
113 Result = Res.toAPValue();
114 return true;
115}
116
117const LangOptions &Context::getLangOpts() const { return Ctx.getLangOpts(); }
118
119std::optional<PrimType> Context::classify(QualType T) const {
120 if (T->isBooleanType())
121 return PT_Bool;
122
123 // We map these to primitive arrays.
124 if (T->isAnyComplexType() || T->isVectorType())
125 return std::nullopt;
126
128 switch (Ctx.getIntWidth(T)) {
129 case 64:
130 return PT_Sint64;
131 case 32:
132 return PT_Sint32;
133 case 16:
134 return PT_Sint16;
135 case 8:
136 return PT_Sint8;
137 default:
138 return PT_IntAPS;
139 }
140 }
141
143 switch (Ctx.getIntWidth(T)) {
144 case 64:
145 return PT_Uint64;
146 case 32:
147 return PT_Uint32;
148 case 16:
149 return PT_Uint16;
150 case 8:
151 return PT_Uint8;
152 default:
153 return PT_IntAP;
154 }
155 }
156
157 if (T->isNullPtrType())
158 return PT_Ptr;
159
160 if (T->isFloatingType())
161 return PT_Float;
162
164 T->isFunctionType() || T->isSpecificBuiltinType(BuiltinType::BoundMember))
165 return PT_FnPtr;
166
167 if (T->isReferenceType() || T->isPointerType())
168 return PT_Ptr;
169
170 if (const auto *AT = T->getAs<AtomicType>())
171 return classify(AT->getValueType());
172
173 if (const auto *DT = dyn_cast<DecltypeType>(T))
174 return classify(DT->getUnderlyingType());
175
176 if (const auto *DT = dyn_cast<MemberPointerType>(T))
177 return classify(DT->getPointeeType());
178
179 return std::nullopt;
180}
181
182unsigned Context::getCharBit() const {
183 return Ctx.getTargetInfo().getCharWidth();
184}
185
186/// Simple wrapper around getFloatTypeSemantics() to make code a
187/// little shorter.
188const llvm::fltSemantics &Context::getFloatSemantics(QualType T) const {
189 return Ctx.getFloatTypeSemantics(T);
190}
191
192bool Context::Run(State &Parent, const Function *Func, APValue &Result) {
193
194 {
195 InterpState State(Parent, *P, Stk, *this);
196 State.Current = new InterpFrame(State, Func, /*Caller=*/nullptr, CodePtr(),
197 Func->getArgSize());
198 if (Interpret(State, Result)) {
199 assert(Stk.empty());
200 return true;
201 }
202
203 // State gets destroyed here, so the Stk.clear() below doesn't accidentally
204 // remove values the State's destructor might access.
205 }
206
207 Stk.clear();
208 return false;
209}
210
211// TODO: Virtual bases?
212const CXXMethodDecl *
214 const CXXRecordDecl *StaticDecl,
215 const CXXMethodDecl *InitialFunction) const {
216 assert(DynamicDecl);
217 assert(StaticDecl);
218 assert(InitialFunction);
219
220 const CXXRecordDecl *CurRecord = DynamicDecl;
221 const CXXMethodDecl *FoundFunction = InitialFunction;
222 for (;;) {
223 const CXXMethodDecl *Overrider =
224 FoundFunction->getCorrespondingMethodDeclaredInClass(CurRecord, false);
225 if (Overrider)
226 return Overrider;
227
228 // Common case of only one base class.
229 if (CurRecord->getNumBases() == 1) {
230 CurRecord = CurRecord->bases_begin()->getType()->getAsCXXRecordDecl();
231 continue;
232 }
233
234 // Otherwise, go to the base class that will lead to the StaticDecl.
235 for (const CXXBaseSpecifier &Spec : CurRecord->bases()) {
236 const CXXRecordDecl *Base = Spec.getType()->getAsCXXRecordDecl();
237 if (Base == StaticDecl || Base->isDerivedFrom(StaticDecl)) {
238 CurRecord = Base;
239 break;
240 }
241 }
242 }
243
244 llvm_unreachable(
245 "Couldn't find an overriding function in the class hierarchy?");
246 return nullptr;
247}
248
250 assert(FD);
251 const Function *Func = P->getFunction(FD);
252 bool IsBeingCompiled = Func && Func->isDefined() && !Func->isFullyCompiled();
253 bool WasNotDefined = Func && !Func->isConstexpr() && !Func->isDefined();
254
255 if (IsBeingCompiled)
256 return Func;
257
258 if (!Func || WasNotDefined) {
259 if (auto F = ByteCodeStmtGen<ByteCodeEmitter>(*this, *P).compileFunc(FD))
260 Func = F;
261 }
262
263 return Func;
264}
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:249
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2057
CXXMethodDecl * getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD, bool MayBeBase=false)
Find if RD declares a function that overrides this function, and if so, return it.
Definition: DeclCXX.cpp:2207
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
base_class_range bases()
Definition: DeclCXX.h:618
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:612
base_class_iterator bases_begin()
Definition: DeclCXX.h:625
This represents one expression.
Definition: Expr.h:110
bool isGLValue() const
Definition: Expr.h:280
Represents a function declaration or definition.
Definition: Decl.h:1971
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:449
A (possibly-)qualified type.
Definition: Type.h:738
unsigned getCharWidth() const
Definition: TargetInfo.h:491
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1870
bool isBooleanType() const
Definition: Type.h:7823
bool isFunctionReferenceType() const
Definition: Type.h:7443
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2155
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2205
bool isArrayType() const
Definition: Type.h:7468
bool isFunctionPointerType() const
Definition: Type.h:7436
bool isPointerType() const
Definition: Type.h:7402
bool isReferenceType() const
Definition: Type.h:7414
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7664
bool isAnyComplexType() const
Definition: Type.h:7504
bool isFunctionType() const
Definition: Type.h:7398
bool isVectorType() const
Definition: Type.h:7508
bool isFloatingType() const
Definition: Type.cpp:2237
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7913
bool isNullPtrType() const
Definition: Type.h:7728
bool isRecordType() const
Definition: Type.h:7496
QualType getType() const
Definition: Decl.h:717
Represents a variable declaration or definition.
Definition: Decl.h:918
Compilation context for expressions.
Compilation context for statements.
Pointer into the code segment.
Definition: Source.h:30
const LangOptions & getLangOpts() const
Returns the language options.
Definition: Context.cpp:117
~Context()
Cleans up the constexpr VM.
Definition: Context.cpp:27
Context(ASTContext &Ctx)
Initialises the constexpr VM.
Definition: Context.cpp:25
bool evaluate(State &Parent, const Expr *E, APValue &Result)
Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
Definition: Context.cpp:67
unsigned getCharBit() const
Returns CHAR_BIT.
Definition: Context.cpp:182
bool evaluateAsInitializer(State &Parent, const VarDecl *VD, APValue &Result)
Evaluates a toplevel initializer.
Definition: Context.cpp:90
const llvm::fltSemantics & getFloatSemantics(QualType T) const
Return the floating-point semantics for T.
Definition: Context.cpp:188
static bool shouldBeGloballyIndexed(const ValueDecl *VD)
Returns whether we should create a global variable for the given ValueDecl.
Definition: Context.h:97
bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FnDecl)
Checks if a function is a potential constant expression.
Definition: Context.cpp:29
bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result)
Evaluates a toplevel expression as an rvalue.
Definition: Context.cpp:42
const CXXMethodDecl * getOverridingFunction(const CXXRecordDecl *DynamicDecl, const CXXRecordDecl *StaticDecl, const CXXMethodDecl *InitialFunction) const
Definition: Context.cpp:213
std::optional< PrimType > classify(QualType T) const
Classifies a type.
Definition: Context.cpp:119
const Function * getOrCreateFunction(const FunctionDecl *FD)
Definition: Context.cpp:249
Bytecode function.
Definition: Function.h:77
Frame storing local variables.
Definition: InterpFrame.h:28
void clear()
Clears the stack without calling any destructors.
Definition: InterpStack.cpp:24
bool empty() const
Returns whether the stack is empty.
Definition: InterpStack.h:91
Interpreter context.
Definition: InterpState.h:35
The program contains and links the bytecode for all functions.
Definition: Program.h:39
Interface for the VM to interact with the AST walker's context.
Definition: State.h:55
Defines the clang::TargetInfo interface.
bool Interpret(InterpState &S, APValue &Result)
Interpreter entry point.
Definition: Interp.cpp:694
bool CheckGlobalInitialized(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Check if a global variable is initialized.
Definition: Interp.cpp:434
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
const FunctionProtoType * T