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"
20#include "clang/AST/ASTContext.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
35struct ParamOffset {
36 unsigned Offset;
37 bool IsPtr;
38};
39
40struct FuncParam {
41 unsigned Index;
42 bool IsPtr;
43};
44
45class EvalIDScope;
46/// Holds all information required to evaluate constexpr code in a module.
47class Context final {
48public:
49 /// Initialises the constexpr VM.
50 Context(ASTContext &Ctx);
51
52 /// Cleans up the constexpr VM.
53 ~Context();
54
55 /// Checks if a function is a potential constant expression.
56 bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FD);
57 void isPotentialConstantExprUnevaluated(State &Parent, const Expr *E,
58 const FunctionDecl *FD);
59
60 /// Evaluates a toplevel expression as an rvalue.
61 bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result);
62
63 /// Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
64 bool evaluate(State &Parent, const Expr *E, APValue &Result,
65 ConstantExprKind Kind);
66
67 /// Evaluates a toplevel initializer.
68 bool evaluateAsInitializer(State &Parent, const VarDecl *VD, const Expr *Init,
69 APValue &Result);
70
71 bool evaluateCharRange(State &Parent, const Expr *SizeExpr,
72 const Expr *PtrExpr, APValue &Result);
73 bool evaluateCharRange(State &Parent, const Expr *SizeExpr,
74 const Expr *PtrExpr, std::string &Result);
75
76 /// Evaluate \param E and if it can be evaluated to a null-terminated string,
77 /// copy the result into \param Result.
78 bool evaluateString(State &Parent, const Expr *E, std::string &Result);
79
80 /// Evalute \param E and if it can be evaluated to a string literal,
81 /// run strlen() on it.
82 std::optional<uint64_t> evaluateStrlen(State &Parent, const Expr *E);
83
84 /// If \param E evaluates to a pointer the number of accessible bytes
85 /// past the pointer is estimated in \param Result as if evaluated by
86 /// the builtin function __builtin_object_size. This is a best effort
87 /// approximation, when Kind & 2 == 0 the object size is less
88 /// than or equal to the estimated size, when Kind & 2 == 1 the
89 /// true value is greater than or equal to the estimated size.
90 /// When Kind & 1 == 1 only bytes belonging to the same subobject
91 /// as the one referred to by E are considered, when Kind & 1 == 0
92 /// bytes belonging to the same storage (stack, heap allocation,
93 /// global variable) are considered.
94 std::optional<uint64_t> tryEvaluateObjectSize(State &Parent, const Expr *E,
95 unsigned Kind);
96
97 /// Returns the AST context.
98 ASTContext &getASTContext() const { return Ctx; }
99 /// Returns the language options.
100 const LangOptions &getLangOpts() const;
101 /// Returns CHAR_BIT.
102 unsigned getCharBit() const;
103 /// Return the floating-point semantics for T.
104 const llvm::fltSemantics &getFloatSemantics(QualType T) const;
105 /// Return the size of T in bits.
106 uint32_t getBitWidth(QualType T) const { return Ctx.getIntWidth(T); }
107
108 /// Classifies a type.
109 OptPrimType classify(QualType T) const;
110
111 /// Classifies an expression.
112 OptPrimType classify(const Expr *E) const {
113 assert(E);
114 if (E->isGLValue())
115 return PT_Ptr;
116
117 return classify(T: E->getType());
118 }
119
120 bool canClassify(QualType T) const {
121 if (const auto *BT = dyn_cast<BuiltinType>(Val&: T)) {
122 if (BT->isInteger() || BT->isFloatingPoint())
123 return true;
124 if (BT->getKind() == BuiltinType::Bool)
125 return true;
126 }
127 if (T->isPointerOrReferenceType())
128 return true;
129
130 if (T->isArrayType() || T->isRecordType() || T->isAnyComplexType() ||
131 T->isVectorType())
132 return false;
133 return classify(T) != std::nullopt;
134 }
135 bool canClassify(const Expr *E) const {
136 if (E->isGLValue())
137 return true;
138 return canClassify(T: E->getType());
139 }
140
141 const CXXMethodDecl *
142 getOverridingFunction(const CXXRecordDecl *DynamicDecl,
143 const CXXRecordDecl *StaticDecl,
144 const CXXMethodDecl *InitialFunction) const;
145
146 const Function *getOrCreateFunction(const FunctionDecl *FuncDecl);
147 const Function *getOrCreateObjCBlock(const BlockExpr *E);
148
149 /// Returns whether we should create a global variable for the
150 /// given ValueDecl.
151 static bool shouldBeGloballyIndexed(const ValueDecl *VD) {
152 if (const auto *V = dyn_cast<VarDecl>(Val: VD))
153 return V->hasGlobalStorage() || V->isConstexpr();
154
155 return false;
156 }
157
158 /// Returns the program. This is only needed for unittests.
159 Program &getProgram() const { return *P; }
160
161 unsigned collectBaseOffset(const RecordDecl *BaseDecl,
162 const RecordDecl *DerivedDecl) const;
163
164 const Record *getRecord(const RecordDecl *D) const;
165
166 unsigned getEvalID() const { return EvalID; }
167
168 /// Unevaluated builtins don't get their arguments put on the stack
169 /// automatically. They instead operate on the AST of their Call
170 /// Expression.
171 /// Similar information is available via ASTContext::BuiltinInfo,
172 /// but that is not correct for our use cases.
173 static bool isUnevaluatedBuiltin(unsigned ID);
174
175private:
176 friend class EvalIDScope;
177 /// Runs a function.
178 bool Run(State &Parent, const Function *Func);
179
180 template <typename ResultT>
181 bool evaluateStringRepr(State &Parent, const Expr *SizeExpr,
182 const Expr *PtrExpr, ResultT &Result);
183
184 /// Current compilation context.
185 ASTContext &Ctx;
186 /// Interpreter stack, shared across invocations.
187 InterpStack Stk;
188 /// Constexpr program.
189 std::unique_ptr<Program> P;
190 /// ID identifying an evaluation.
191 unsigned EvalID = 0;
192 /// Cached widths (in bits) of common types, for a faster classify().
193 unsigned ShortWidth;
194 unsigned IntWidth;
195 unsigned LongWidth;
196 unsigned LongLongWidth;
197};
198
199class EvalIDScope {
200public:
201 EvalIDScope(Context &Ctx) : Ctx(Ctx), OldID(Ctx.EvalID) { ++Ctx.EvalID; }
202 ~EvalIDScope() { Ctx.EvalID = OldID; }
203
204private:
205 Context &Ctx;
206 const unsigned OldID;
207};
208
209} // namespace interp
210} // namespace clang
211
212#endif
213