clang 20.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 "Compiler.h"
12#include "EvalEmitter.h"
13#include "Interp.h"
14#include "InterpFrame.h"
15#include "InterpStack.h"
16#include "PrimType.h"
17#include "Program.h"
18#include "clang/AST/Expr.h"
20
21using namespace clang;
22using namespace clang::interp;
23
24Context::Context(ASTContext &Ctx) : Ctx(Ctx), P(new Program(*this)) {}
25
27
29 assert(Stk.empty());
30 Function *Func = P->getFunction(FD);
31 if (!Func || !Func->hasBody())
32 Func = Compiler<ByteCodeEmitter>(*this, *P).compileFunc(FD);
33
34 if (!Func)
35 return false;
36
37 APValue DummyResult;
38 if (!Run(Parent, Func, DummyResult))
39 return false;
40
41 return Func->isConstexpr();
42}
43
45 ++EvalID;
46 bool Recursing = !Stk.empty();
47 Compiler<EvalEmitter> C(*this, *P, Parent, Stk);
48
49 auto Res = C.interpretExpr(E, /*ConvertResultToRValue=*/E->isGLValue());
50
51 if (Res.isInvalid()) {
52 C.cleanup();
53 Stk.clear();
54 return false;
55 }
56
57 if (!Recursing) {
58 assert(Stk.empty());
59 C.cleanup();
60#ifndef NDEBUG
61 // Make sure we don't rely on some value being still alive in
62 // InterpStack memory.
63 Stk.clear();
64#endif
65 }
66
67 Result = Res.toAPValue();
68
69 return true;
70}
71
73 ++EvalID;
74 bool Recursing = !Stk.empty();
75 Compiler<EvalEmitter> C(*this, *P, Parent, Stk);
76
77 auto Res = C.interpretExpr(E);
78 if (Res.isInvalid()) {
79 C.cleanup();
80 Stk.clear();
81 return false;
82 }
83
84 if (!Recursing) {
85 assert(Stk.empty());
86 C.cleanup();
87#ifndef NDEBUG
88 // Make sure we don't rely on some value being still alive in
89 // InterpStack memory.
90 Stk.clear();
91#endif
92 }
93
94 Result = Res.toAPValue();
95 return true;
96}
97
99 APValue &Result) {
100 ++EvalID;
101 bool Recursing = !Stk.empty();
102 Compiler<EvalEmitter> C(*this, *P, Parent, Stk);
103
106 (VD->getType()->isRecordType() || VD->getType()->isArrayType());
107 auto Res = C.interpretDecl(VD, CheckGlobalInitialized);
108 if (Res.isInvalid()) {
109 C.cleanup();
110 Stk.clear();
111 return false;
112 }
113
114 if (!Recursing) {
115 assert(Stk.empty());
116 C.cleanup();
117#ifndef NDEBUG
118 // Make sure we don't rely on some value being still alive in
119 // InterpStack memory.
120 Stk.clear();
121#endif
122 }
123
124 Result = Res.toAPValue();
125 return true;
126}
127
128const LangOptions &Context::getLangOpts() const { return Ctx.getLangOpts(); }
129
130std::optional<PrimType> Context::classify(QualType T) const {
131 if (T->isBooleanType())
132 return PT_Bool;
133
134 // We map these to primitive arrays.
135 if (T->isAnyComplexType() || T->isVectorType())
136 return std::nullopt;
137
139 switch (Ctx.getIntWidth(T)) {
140 case 64:
141 return PT_Sint64;
142 case 32:
143 return PT_Sint32;
144 case 16:
145 return PT_Sint16;
146 case 8:
147 return PT_Sint8;
148 default:
149 return PT_IntAPS;
150 }
151 }
152
154 switch (Ctx.getIntWidth(T)) {
155 case 64:
156 return PT_Uint64;
157 case 32:
158 return PT_Uint32;
159 case 16:
160 return PT_Uint16;
161 case 8:
162 return PT_Uint8;
163 case 1:
164 // Might happen for enum types.
165 return PT_Bool;
166 default:
167 return PT_IntAP;
168 }
169 }
170
171 if (T->isNullPtrType())
172 return PT_Ptr;
173
174 if (T->isFloatingType())
175 return PT_Float;
176
177 if (T->isSpecificBuiltinType(BuiltinType::BoundMember) ||
179 return PT_MemberPtr;
180
183 return PT_FnPtr;
184
186 return PT_Ptr;
187
188 if (const auto *AT = T->getAs<AtomicType>())
189 return classify(AT->getValueType());
190
191 if (const auto *DT = dyn_cast<DecltypeType>(T))
192 return classify(DT->getUnderlyingType());
193
194 return std::nullopt;
195}
196
197unsigned Context::getCharBit() const {
198 return Ctx.getTargetInfo().getCharWidth();
199}
200
201/// Simple wrapper around getFloatTypeSemantics() to make code a
202/// little shorter.
203const llvm::fltSemantics &Context::getFloatSemantics(QualType T) const {
204 return Ctx.getFloatTypeSemantics(T);
205}
206
207bool Context::Run(State &Parent, const Function *Func, APValue &Result) {
208
209 {
210 InterpState State(Parent, *P, Stk, *this);
211 State.Current = new InterpFrame(State, Func, /*Caller=*/nullptr, CodePtr(),
212 Func->getArgSize());
213 if (Interpret(State, Result)) {
214 assert(Stk.empty());
215 return true;
216 }
217
218 // State gets destroyed here, so the Stk.clear() below doesn't accidentally
219 // remove values the State's destructor might access.
220 }
221
222 Stk.clear();
223 return false;
224}
225
226// TODO: Virtual bases?
227const CXXMethodDecl *
229 const CXXRecordDecl *StaticDecl,
230 const CXXMethodDecl *InitialFunction) const {
231 assert(DynamicDecl);
232 assert(StaticDecl);
233 assert(InitialFunction);
234
235 const CXXRecordDecl *CurRecord = DynamicDecl;
236 const CXXMethodDecl *FoundFunction = InitialFunction;
237 for (;;) {
238 const CXXMethodDecl *Overrider =
239 FoundFunction->getCorrespondingMethodDeclaredInClass(CurRecord, false);
240 if (Overrider)
241 return Overrider;
242
243 // Common case of only one base class.
244 if (CurRecord->getNumBases() == 1) {
245 CurRecord = CurRecord->bases_begin()->getType()->getAsCXXRecordDecl();
246 continue;
247 }
248
249 // Otherwise, go to the base class that will lead to the StaticDecl.
250 for (const CXXBaseSpecifier &Spec : CurRecord->bases()) {
251 const CXXRecordDecl *Base = Spec.getType()->getAsCXXRecordDecl();
252 if (Base == StaticDecl || Base->isDerivedFrom(StaticDecl)) {
253 CurRecord = Base;
254 break;
255 }
256 }
257 }
258
259 llvm_unreachable(
260 "Couldn't find an overriding function in the class hierarchy?");
261 return nullptr;
262}
263
265 assert(FD);
266 const Function *Func = P->getFunction(FD);
267 bool IsBeingCompiled = Func && Func->isDefined() && !Func->isFullyCompiled();
268 bool WasNotDefined = Func && !Func->isConstexpr() && !Func->isDefined();
269
270 if (IsBeingCompiled)
271 return Func;
272
273 if (!Func || WasNotDefined) {
274 if (auto F = Compiler<ByteCodeEmitter>(*this, *P).compileFunc(FD))
275 Func = F;
276 }
277
278 return Func;
279}
280
281unsigned Context::collectBaseOffset(const RecordDecl *BaseDecl,
282 const RecordDecl *DerivedDecl) const {
283 assert(BaseDecl);
284 assert(DerivedDecl);
285 const auto *FinalDecl = cast<CXXRecordDecl>(BaseDecl);
286 const RecordDecl *CurDecl = DerivedDecl;
287 const Record *CurRecord = P->getOrCreateRecord(CurDecl);
288 assert(CurDecl && FinalDecl);
289
290 unsigned OffsetSum = 0;
291 for (;;) {
292 assert(CurRecord->getNumBases() > 0);
293 // One level up
294 for (const Record::Base &B : CurRecord->bases()) {
295 const auto *BaseDecl = cast<CXXRecordDecl>(B.Decl);
296
297 if (BaseDecl == FinalDecl || BaseDecl->isDerivedFrom(FinalDecl)) {
298 OffsetSum += B.Offset;
299 CurRecord = B.R;
300 CurDecl = BaseDecl;
301 break;
302 }
303 }
304 if (CurDecl == FinalDecl)
305 break;
306 }
307
308 assert(OffsetSum > 0);
309 return OffsetSum;
310}
311
312const Record *Context::getRecord(const RecordDecl *D) const {
313 return P->getOrCreateRecord(D);
314}
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
const Decl * D
Expr * E
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:187
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:797
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
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:2064
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:2246
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
base_class_range bases()
Definition: DeclCXX.h:620
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
base_class_iterator bases_begin()
Definition: DeclCXX.h:627
This represents one expression.
Definition: Expr.h:110
bool isGLValue() const
Definition: Expr.h:280
Represents a function declaration or definition.
Definition: Decl.h:1932
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:476
A (possibly-)qualified type.
Definition: Type.h:941
Represents a struct/union/class.
Definition: Decl.h:4145
unsigned getCharWidth() const
Definition: TargetInfo.h:496
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isBlockPointerType() const
Definition: Type.h:8017
bool isBooleanType() const
Definition: Type.h:8447
bool isFunctionReferenceType() const
Definition: Type.h:8050
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2167
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2217
bool isArrayType() const
Definition: Type.h:8075
bool isFunctionPointerType() const
Definition: Type.h:8043
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8288
bool isAnyComplexType() const
Definition: Type.h:8111
bool isMemberPointerType() const
Definition: Type.h:8057
bool isPointerOrReferenceType() const
Definition: Type.h:8007
bool isFunctionType() const
Definition: Type.h:7999
bool isObjCObjectPointerType() const
Definition: Type.h:8145
bool isVectorType() const
Definition: Type.h:8115
bool isFloatingType() const
Definition: Type.cpp:2249
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
bool isNullPtrType() const
Definition: Type.h:8352
bool isRecordType() const
Definition: Type.h:8103
QualType getType() const
Definition: Decl.h:678
Represents a variable declaration or definition.
Definition: Decl.h:879
Pointer into the code segment.
Definition: Source.h:30
Compilation context for expressions.
Definition: Compiler.h:104
const LangOptions & getLangOpts() const
Returns the language options.
Definition: Context.cpp:128
~Context()
Cleans up the constexpr VM.
Definition: Context.cpp:26
Context(ASTContext &Ctx)
Initialises the constexpr VM.
Definition: Context.cpp:24
bool evaluate(State &Parent, const Expr *E, APValue &Result)
Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
Definition: Context.cpp:72
unsigned getCharBit() const
Returns CHAR_BIT.
Definition: Context.cpp:197
bool evaluateAsInitializer(State &Parent, const VarDecl *VD, APValue &Result)
Evaluates a toplevel initializer.
Definition: Context.cpp:98
const llvm::fltSemantics & getFloatSemantics(QualType T) const
Return the floating-point semantics for T.
Definition: Context.cpp:203
static bool shouldBeGloballyIndexed(const ValueDecl *VD)
Returns whether we should create a global variable for the given ValueDecl.
Definition: Context.h:97
unsigned collectBaseOffset(const RecordDecl *BaseDecl, const RecordDecl *DerivedDecl) const
Definition: Context.cpp:281
const Record * getRecord(const RecordDecl *D) const
Definition: Context.cpp:312
bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FnDecl)
Checks if a function is a potential constant expression.
Definition: Context.cpp:28
bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result)
Evaluates a toplevel expression as an rvalue.
Definition: Context.cpp:44
const CXXMethodDecl * getOverridingFunction(const CXXRecordDecl *DynamicDecl, const CXXRecordDecl *StaticDecl, const CXXMethodDecl *InitialFunction) const
Definition: Context.cpp:228
std::optional< PrimType > classify(QualType T) const
Classifies a type.
Definition: Context.cpp:130
const Function * getOrCreateFunction(const FunctionDecl *FD)
Definition: Context.cpp:264
Bytecode function.
Definition: Function.h:81
Frame storing local variables.
Definition: InterpFrame.h:26
void clear()
Clears the stack without calling any destructors.
Definition: InterpStack.cpp:23
bool empty() const
Returns whether the stack is empty.
Definition: InterpStack.h:91
Interpreter context.
Definition: InterpState.h:36
The program contains and links the bytecode for all functions.
Definition: Program.h:39
Structure/Class descriptor.
Definition: Record.h:25
unsigned getNumBases() const
Definition: Record.h:89
llvm::iterator_range< const_base_iter > bases() const
Definition: Record.h:85
Interface for the VM to interact with the AST walker's context.
Definition: State.h:56
Defines the clang::TargetInfo interface.
bool Interpret(InterpState &S, APValue &Result)
Interpreter entry point.
Definition: Interp.cpp:963
bool CheckGlobalInitialized(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Check if a global variable is initialized.
Definition: Interp.cpp:519
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
const FunctionProtoType * T