clang 23.0.0git
Context.h
Go to the documentation of this file.
1//===--- Context.h - 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// Defines the constexpr execution context.
10//
11// The execution context manages cached bytecode and the global context.
12// It invokes the compiler and interpreter, propagating errors.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CLANG_AST_INTERP_CONTEXT_H
17#define LLVM_CLANG_AST_INTERP_CONTEXT_H
18
19#include "InterpStack.h"
21
22namespace clang {
23class LangOptions;
24class FunctionDecl;
25class VarDecl;
26class APValue;
27class BlockExpr;
28
29namespace interp {
30class Function;
31class Program;
32class State;
33enum PrimType : uint8_t;
34
36 unsigned Offset;
37 bool IsPtr;
38};
39
40class EvalIDScope;
41/// Holds all information required to evaluate constexpr code in a module.
42class Context final {
43public:
44 /// Initialises the constexpr VM.
45 Context(ASTContext &Ctx);
46
47 /// Cleans up the constexpr VM.
48 ~Context();
49
50 /// Checks if a function is a potential constant expression.
51 bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FD);
52 void isPotentialConstantExprUnevaluated(State &Parent, const Expr *E,
53 const FunctionDecl *FD);
54
55 /// Evaluates a toplevel expression as an rvalue.
56 bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result);
57
58 /// Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
59 bool evaluate(State &Parent, const Expr *E, APValue &Result,
60 ConstantExprKind Kind);
61
62 /// Evaluates a toplevel initializer.
63 bool evaluateAsInitializer(State &Parent, const VarDecl *VD, const Expr *Init,
65
66 bool evaluateCharRange(State &Parent, const Expr *SizeExpr,
67 const Expr *PtrExpr, APValue &Result);
68 bool evaluateCharRange(State &Parent, const Expr *SizeExpr,
69 const Expr *PtrExpr, std::string &Result);
70
71 /// Evaluate \param E and if it can be evaluated to a null-terminated string,
72 /// copy the result into \param Result.
73 bool evaluateString(State &Parent, const Expr *E, std::string &Result);
74
75 /// Evalute \param E and if it can be evaluated to a string literal,
76 /// run strlen() on it.
77 std::optional<uint64_t> evaluateStrlen(State &Parent, const Expr *E);
78
79 /// If \param E evaluates to a pointer the number of accessible bytes
80 /// past the pointer is estimated in \param Result as if evaluated by
81 /// the builtin function __builtin_object_size. This is a best effort
82 /// approximation, when Kind & 2 == 0 the object size is less
83 /// than or equal to the estimated size, when Kind & 2 == 1 the
84 /// true value is greater than or equal to the estimated size.
85 /// When Kind & 1 == 1 only bytes belonging to the same subobject
86 /// as the one referred to by E are considered, when Kind & 1 == 0
87 /// bytes belonging to the same storage (stack, heap allocation,
88 /// global variable) are considered.
89 std::optional<uint64_t> tryEvaluateObjectSize(State &Parent, const Expr *E,
90 unsigned Kind);
91
92 /// Returns the AST context.
93 ASTContext &getASTContext() const { return Ctx; }
94 /// Returns the language options.
95 const LangOptions &getLangOpts() const;
96 /// Returns CHAR_BIT.
97 unsigned getCharBit() const;
98 /// Return the floating-point semantics for T.
99 const llvm::fltSemantics &getFloatSemantics(QualType T) const;
100 /// Return the size of T in bits.
101 uint32_t getBitWidth(QualType T) const { return Ctx.getIntWidth(T); }
102
103 /// Classifies a type.
105
106 /// Classifies an expression.
107 OptPrimType classify(const Expr *E) const {
108 assert(E);
109 if (E->isGLValue())
110 return PT_Ptr;
111
112 return classify(E->getType());
113 }
114
115 bool canClassify(QualType T) const {
116 if (const auto *BT = dyn_cast<BuiltinType>(T)) {
117 if (BT->isInteger() || BT->isFloatingPoint())
118 return true;
119 if (BT->getKind() == BuiltinType::Bool)
120 return true;
121 }
122 if (T->isPointerOrReferenceType())
123 return true;
124
125 if (T->isArrayType() || T->isRecordType() || T->isAnyComplexType() ||
126 T->isVectorType())
127 return false;
128 return classify(T) != std::nullopt;
129 }
130 bool canClassify(const Expr *E) const {
131 if (E->isGLValue())
132 return true;
133 return canClassify(E->getType());
134 }
135
136 const CXXMethodDecl *
137 getOverridingFunction(const CXXRecordDecl *DynamicDecl,
138 const CXXRecordDecl *StaticDecl,
139 const CXXMethodDecl *InitialFunction) const;
140
141 const Function *getOrCreateFunction(const FunctionDecl *FuncDecl);
142 const Function *getOrCreateObjCBlock(const BlockExpr *E);
143
144 /// Returns whether we should create a global variable for the
145 /// given ValueDecl.
146 static bool shouldBeGloballyIndexed(const ValueDecl *VD) {
147 if (const auto *V = dyn_cast<VarDecl>(VD))
148 return V->hasGlobalStorage() || V->isConstexpr();
149
150 return false;
151 }
152
153 /// Returns the program. This is only needed for unittests.
154 Program &getProgram() const { return *P; }
155
156 unsigned collectBaseOffset(const RecordDecl *BaseDecl,
157 const RecordDecl *DerivedDecl) const;
158
159 const Record *getRecord(const RecordDecl *D) const;
160
161 unsigned getEvalID() const { return EvalID; }
162
163 /// Unevaluated builtins don't get their arguments put on the stack
164 /// automatically. They instead operate on the AST of their Call
165 /// Expression.
166 /// Similar information is available via ASTContext::BuiltinInfo,
167 /// but that is not correct for our use cases.
168 static bool isUnevaluatedBuiltin(unsigned ID);
169
170private:
171 friend class EvalIDScope;
172 /// Runs a function.
173 bool Run(State &Parent, const Function *Func);
174
175 template <typename ResultT>
176 bool evaluateStringRepr(State &Parent, const Expr *SizeExpr,
177 const Expr *PtrExpr, ResultT &Result);
178
179 /// Current compilation context.
180 ASTContext &Ctx;
181 /// Interpreter stack, shared across invocations.
182 InterpStack Stk;
183 /// Constexpr program.
184 std::unique_ptr<Program> P;
185 /// ID identifying an evaluation.
186 unsigned EvalID = 0;
187 /// Cached widths (in bits) of common types, for a faster classify().
188 unsigned ShortWidth;
189 unsigned IntWidth;
190 unsigned LongWidth;
191 unsigned LongLongWidth;
192};
193
195public:
196 EvalIDScope(Context &Ctx) : Ctx(Ctx), OldID(Ctx.EvalID) { ++Ctx.EvalID; }
197 ~EvalIDScope() { Ctx.EvalID = OldID; }
198
199private:
200 Context &Ctx;
201 const unsigned OldID;
202};
203
204} // namespace interp
205} // namespace clang
206
207#endif
Defines the clang::ASTContext interface.
#define V(N, I)
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:226
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6671
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
This represents one expression.
Definition Expr.h:112
bool isGLValue() const
Definition Expr.h:287
QualType getType() const
Definition Expr.h:144
Represents a function declaration or definition.
Definition Decl.h:2000
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
A (possibly-)qualified type.
Definition TypeBase.h:937
Represents a struct/union/class.
Definition Decl.h:4327
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
Represents a variable declaration or definition.
Definition Decl.h:926
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:42
const LangOptions & getLangOpts() const
Returns the language options.
Definition Context.cpp:370
OptPrimType classify(const Expr *E) const
Classifies an expression.
Definition Context.h:107
const Function * getOrCreateObjCBlock(const BlockExpr *E)
Definition Context.cpp:635
~Context()
Cleans up the constexpr VM.
Definition Context.cpp:37
Context(ASTContext &Ctx)
Initialises the constexpr VM.
Definition Context.cpp:28
bool evaluateCharRange(State &Parent, const Expr *SizeExpr, const Expr *PtrExpr, APValue &Result)
Definition Context.cpp:226
std::optional< uint64_t > evaluateStrlen(State &Parent, const Expr *E)
Evalute.
Definition Context.cpp:291
friend class EvalIDScope
Definition Context.h:171
bool evaluateString(State &Parent, const Expr *E, std::string &Result)
Evaluate.
Definition Context.cpp:242
static bool isUnevaluatedBuiltin(unsigned ID)
Unevaluated builtins don't get their arguments put on the stack automatically.
Definition Context.cpp:708
unsigned getCharBit() const
Returns CHAR_BIT.
Definition Context.cpp:483
bool canClassify(const Expr *E) const
Definition Context.h:130
Program & getProgram() const
Returns the program. This is only needed for unittests.
Definition Context.h:154
const llvm::fltSemantics & getFloatSemantics(QualType T) const
Return the floating-point semantics for T.
Definition Context.cpp:489
static bool shouldBeGloballyIndexed(const ValueDecl *VD)
Returns whether we should create a global variable for the given ValueDecl.
Definition Context.h:146
void isPotentialConstantExprUnevaluated(State &Parent, const Expr *E, const FunctionDecl *FD)
Definition Context.cpp:59
unsigned collectBaseOffset(const RecordDecl *BaseDecl, const RecordDecl *DerivedDecl) const
Definition Context.cpp:673
const Record * getRecord(const RecordDecl *D) const
Definition Context.cpp:704
bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FD)
Checks if a function is a potential constant expression.
Definition Context.cpp:39
const Function * getOrCreateFunction(const FunctionDecl *FuncDecl)
Definition Context.cpp:541
ASTContext & getASTContext() const
Returns the AST context.
Definition Context.h:93
uint32_t getBitWidth(QualType T) const
Return the size of T in bits.
Definition Context.h:101
OptPrimType classify(QualType T) const
Classifies a type.
Definition Context.cpp:404
bool canClassify(QualType T) const
Definition Context.h:115
bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result)
Evaluates a toplevel expression as an rvalue.
Definition Context.cpp:72
const CXXMethodDecl * getOverridingFunction(const CXXRecordDecl *DynamicDecl, const CXXRecordDecl *StaticDecl, const CXXMethodDecl *InitialFunction) const
Definition Context.cpp:505
std::optional< uint64_t > tryEvaluateObjectSize(State &Parent, const Expr *E, unsigned Kind)
If.
Definition Context.cpp:338
bool evaluate(State &Parent, const Expr *E, APValue &Result, ConstantExprKind Kind)
Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
Definition Context.cpp:102
bool evaluateAsInitializer(State &Parent, const VarDecl *VD, const Expr *Init, APValue &Result)
Evaluates a toplevel initializer.
Definition Context.cpp:131
unsigned getEvalID() const
Definition Context.h:161
EvalIDScope(Context &Ctx)
Definition Context.h:196
Bytecode function.
Definition Function.h:99
Stack frame storing temporaries and parameters.
Definition InterpStack.h:25
The program contains and links the bytecode for all functions.
Definition Program.h:36
Structure/Class descriptor.
Definition Record.h:25
Interface for the VM to interact with the AST walker's context.
Definition State.h:81
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:34
bool Init(InterpState &S, CodePtr OpPC)
Definition Interp.h:2140
The JSON file list parser is used to communicate input to InstallAPI.
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1045
@ Result
The result type of a method or function.
Definition TypeBase.h:905