clang 24.0.0git
InterpState.h
Go to the documentation of this file.
1//===--- InterpState.h - Interpreter state 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// Definition of the interpreter state and entry point.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_INTERP_INTERPSTATE_H
14#define LLVM_CLANG_AST_INTERP_INTERPSTATE_H
15
16#include "Context.h"
17#include "DynamicAllocator.h"
18#include "Floating.h"
19#include "Function.h"
20#include "InterpFrame.h"
21#include "InterpStack.h"
22#include "State.h"
23
24namespace clang {
25namespace interp {
26class Context;
27class SourceMapper;
28
30 const Expr *Call = nullptr;
32 explicit operator bool() { return Call; }
33};
34
35// FIXME: Create one for the "checking potential constant expression"
36// evaluation.
37enum class EvaluationKind : uint8_t {
39 Dtor, /// We're checking for constant destruction of a global variable.
40};
41
42/// Interpreter context.
43class InterpState final : public State {
44public:
45 InterpState(const State &Parent, Program &P, InterpStack &Stk, Context &Ctx,
46 SourceMapper *M = nullptr);
47 InterpState(const State &Parent, Program &P, InterpStack &Stk, Context &Ctx,
48 const Function *Func);
49
51
52 void cleanup();
53
54 InterpState(const InterpState &) = delete;
55 InterpState &operator=(const InterpState &) = delete;
56
57 bool diagnosing() const { return getEvalStatus().Diag != nullptr; }
58
59 // Stack frame accessors.
60 const Frame *getCurrentFrame() override;
61 unsigned getCallStackDepth() override {
62 return Current ? (Current->getDepth() + 1) : 1;
63 }
64 bool stepsLeft() const override { return true; }
65 bool inConstantContext() const;
66
67 /// Deallocates a pointer.
68 void deallocate(Block *B);
69
70 /// Delegates source mapping to the mapper.
71 SourceInfo getSource(CodePtr PC) const { return M->getSource(PC); }
72
73 Context &getContext() const { return Ctx; }
74
76
78 if (!Alloc) {
79 Alloc = std::make_unique<DynamicAllocator>();
80 }
81
82 return *Alloc;
83 }
84
85 /// Diagnose any dynamic allocations that haven't been freed yet.
86 /// Will return \c false if there were any allocations to diagnose,
87 /// \c true otherwise.
89
90 StdAllocatorCaller getStdAllocatorCaller(StringRef Name) const;
91
92 void *allocate(size_t Size, unsigned Align = 8) const {
93 if (!Allocator)
94 Allocator.emplace();
95 return Allocator->Allocate(Size, Align);
96 }
97 template <typename T> T *allocate(size_t Num = 1) const {
98 return static_cast<T *>(allocate(Num * sizeof(T), alignof(T)));
99 }
100
101 template <typename T> T allocAP(unsigned BitWidth) {
102 unsigned NumWords = APInt::getNumWords(BitWidth);
103 if (NumWords == 1)
104 return T(BitWidth);
105 uint64_t *Mem = (uint64_t *)this->allocate(NumWords * sizeof(uint64_t));
106 // std::memset(Mem, 0, NumWords * sizeof(uint64_t)); // Debug
107 return T(Mem, BitWidth);
108 }
109
110 Floating allocFloat(const llvm::fltSemantics &Sem) {
111 if (Floating::singleWord(Sem))
112 return Floating(llvm::APFloatBase::SemanticsToEnum(Sem));
113
114 unsigned NumWords =
115 APInt::getNumWords(llvm::APFloatBase::getSizeInBits(Sem));
116 uint64_t *Mem = (uint64_t *)this->allocate(NumWords * sizeof(uint64_t));
117 // std::memset(Mem, 0, NumWords * sizeof(uint64_t)); // Debug
118 return Floating(Mem, llvm::APFloatBase::SemanticsToEnum(Sem));
119 }
120 const CXXRecordDecl **allocMemberPointerPath(unsigned Length) {
121 return reinterpret_cast<const CXXRecordDecl **>(
122 this->allocate(Length * sizeof(CXXRecordDecl *)));
123 }
125 const PointerPathEntry *OldPP) {
126 assert(Length != 0);
127 auto *PP = reinterpret_cast<PointerPathEntry *>(
128 this->allocate(Length * sizeof(PointerPathEntry)));
129 if (OldPP)
130 std::memcpy(PP, OldPP, sizeof(PointerPathEntry) * Length);
131 return PP;
132 }
133 /// Allocate a new pointer path of Length \c NewLength.
134 /// NewLength - 1 elements are copied form \c OldPP.
136 const PointerPathEntry *OldPP,
137 PointerPathEntry NewEntry) {
138 auto *PP = reinterpret_cast<PointerPathEntry *>(
139 this->allocate(NewLength * sizeof(PointerPathEntry)));
140 if (OldPP)
141 std::memcpy(PP, OldPP, sizeof(PointerPathEntry) * (NewLength - 1));
142 PP[NewLength - 1] = NewEntry;
143 return PP;
144 }
145
146 /// Note that a step has been executed. If there are no more steps remaining,
147 /// diagnoses and returns \c false.
148 bool noteStep(CodePtr OpPC) {
149 if (InfiniteSteps)
150 return true;
151
152 --StepsLeft;
153 if (LLVM_LIKELY(StepsLeft != 0))
154 return true;
155
156 return diagnoseStepLimitExceeded(OpPC);
157 }
158
159 bool initializingBlock(const Block *B) const {
161 if (V.block() == B)
162 return true;
163 return false;
164 }
165
166 bool lifetimeStartedInEvaluation(const Block *B) const {
168 return B->getEvalID() == EvalID;
169
171 assert(EvaluatingDecl);
173 return EvaluatingDecl->getType().isConstQualified();
174 }
175 return false;
176 }
177
178 /// Return if we're checking if a global variable has a constant destructor.
181 }
182 /// Return if we're checking if a global variable has a constant destructor
183 /// and the given pointer is pointing to the variable we're checking that for.
184 bool checkingConstantDestruction(const Pointer &Ptr) const {
185 return checkingConstantDestruction(Ptr.getRootVarDecl());
186 }
187 bool checkingConstantDestruction(const VarDecl *VD) const {
189 }
190
191 unsigned newStringID() { return StringID++; }
192
193private:
194 friend class EvaluationResult;
196 /// Dead block chain.
197 DeadBlock *DeadBlocks = nullptr;
198 /// Reference to the offset-source mapping.
199 SourceMapper *M;
200 /// Allocator used for dynamic allocations performed via the program.
201 std::unique_ptr<DynamicAllocator> Alloc;
202 /// Allocator for everything else, e.g. floating-point values.
203 mutable std::optional<llvm::BumpPtrAllocator> Allocator;
204 /// Diagnose that we've reached the constexpr step limit.
205 bool diagnoseStepLimitExceeded(CodePtr OpPC);
206
207public:
209 /// Reference to the module containing all bytecode.
211 /// Temporary stack.
213 /// Interpreter Context.
215 /// Bottom function frame.
217 /// The current frame.
219 /// Source location of the evaluating expression
221 /// Declaration we're initializing/evaluting, if any.
222 const VarDecl *EvaluatingDecl = nullptr;
223 /// Steps left during evaluation.
224 unsigned StepsLeft = 1;
225 /// Whether infinite evaluation steps have been requested. If this is false,
226 /// we use the StepsLeft value above.
227 const bool InfiniteSteps = false;
228 /// ID identifying this evaluation.
229 const unsigned EvalID;
230
231 unsigned StringID = 0;
232
234
235 /// Things needed to do speculative execution.
237 bool PrevDiagsEmitted = false;
238#ifndef NDEBUG
239 unsigned SpeculationDepth = 0;
240#endif
241 unsigned DiagIgnoreDepth = 0;
242 std::optional<bool> ConstantContextOverride;
243
245 std::pair<const Expr *, const LifetimeExtendedTemporaryDecl *>>
247
248 /// List of blocks we're currently running either constructors or destructors
249 /// for.
251};
252
254public:
256 : Ctx(Ctx), OldCC(Ctx.ConstantContextOverride) {
257 // We only override this if the new value is true.
258 Enabled = Value;
259 if (Enabled)
260 Ctx.ConstantContextOverride = Value;
261 }
263 if (Enabled)
264 Ctx.ConstantContextOverride = OldCC;
265 }
266
267private:
268 bool Enabled;
269 InterpState &Ctx;
270 std::optional<bool> OldCC;
271};
272
273} // namespace interp
274} // namespace clang
275
276#endif
#define V(N, I)
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
This represents one expression.
Definition Expr.h:113
A (possibly-)qualified type.
Definition TypeBase.h:938
Encodes a location in the source.
Represents a variable declaration or definition.
Definition Decl.h:933
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:43
const Descriptor * getDescriptor() const
Returns the block's descriptor.
Definition InterpBlock.h:77
unsigned getEvalID() const
The Evaluation ID this block was created in.
Pointer into the code segment.
Definition Source.h:31
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:47
Descriptor for a dead block.
Manages dynamic memory allocations done during bytecode interpretation.
If a Floating is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition Floating.h:35
bool singleWord() const
Definition Floating.h:107
Base class for stack frames, shared between VM and walker.
Definition Frame.h:28
Bytecode function.
Definition Function.h:98
Frame storing local variables.
Definition InterpFrame.h:27
Stack frame storing temporaries and parameters.
Definition InterpStack.h:25
InterpStateCCOverride(InterpState &Ctx, bool Value)
Interpreter context.
Definition InterpState.h:43
SmallVectorImpl< PartialDiagnosticAt > * PrevDiags
Things needed to do speculative execution.
bool lifetimeStartedInEvaluation(const Block *B) const
unsigned getCallStackDepth() override
Definition InterpState.h:61
InterpFrame BottomFrame
Bottom function frame.
Context & getContext() const
Definition InterpState.h:73
bool initializingBlock(const Block *B) const
DynamicAllocator & getAllocator()
Definition InterpState.h:77
Context & Ctx
Interpreter Context.
void * allocate(size_t Size, unsigned Align=8) const
Definition InterpState.h:92
Floating allocFloat(const llvm::fltSemantics &Sem)
const unsigned EvalID
ID identifying this evaluation.
bool noteStep(CodePtr OpPC)
Note that a step has been executed.
SourceInfo getSource(CodePtr PC) const
Delegates source mapping to the mapper.
Definition InterpState.h:71
InterpState(const State &Parent, Program &P, InterpStack &Stk, Context &Ctx, SourceMapper *M=nullptr)
InterpState(const InterpState &)=delete
bool stepsLeft() const override
Definition InterpState.h:64
llvm::SmallVector< std::pair< const Expr *, const LifetimeExtendedTemporaryDecl * > > SeenGlobalTemporaries
InterpStack & Stk
Temporary stack.
bool maybeDiagnoseDanglingAllocations()
Diagnose any dynamic allocations that haven't been freed yet.
SourceLocation EvalLocation
Source location of the evaluating expression.
bool checkingConstantDestruction() const
Return if we're checking if a global variable has a constant destructor.
unsigned StepsLeft
Steps left during evaluation.
const VarDecl * EvaluatingDecl
Declaration we're initializing/evaluting, if any.
bool checkingConstantDestruction(const Pointer &Ptr) const
Return if we're checking if a global variable has a constant destructor and the given pointer is poin...
InterpFrame * Current
The current frame.
PointerPathEntry * allocPointerPath(unsigned Length, const PointerPathEntry *OldPP)
const CXXRecordDecl ** allocMemberPointerPath(unsigned Length)
const Frame * getCurrentFrame() override
std::optional< bool > ConstantContextOverride
const bool InfiniteSteps
Whether infinite evaluation steps have been requested.
InterpState & operator=(const InterpState &)=delete
friend class InterpStateCCOverride
T * allocate(size_t Num=1) const
Definition InterpState.h:97
void deallocate(Block *B)
Deallocates a pointer.
PointerPathEntry * extendPointerPath(unsigned NewLength, const PointerPathEntry *OldPP, PointerPathEntry NewEntry)
Allocate a new pointer path of Length NewLength.
llvm::SmallVector< PtrView > InitializingPtrs
List of blocks we're currently running either constructors or destructors for.
T allocAP(unsigned BitWidth)
void setEvalLocation(SourceLocation SL)
Definition InterpState.h:75
StdAllocatorCaller getStdAllocatorCaller(StringRef Name) const
bool checkingConstantDestruction(const VarDecl *VD) const
Program & P
Reference to the module containing all bytecode.
A pointer to a memory block, live or dead.
Definition Pointer.h:531
The program contains and links the bytecode for all functions.
Definition Program.h:37
Describes the statement/declaration an opcode was generated from.
Definition Source.h:77
Interface for classes which map locations to sources.
Definition Source.h:138
Expr::EvalStatus & getEvalStatus() const
Definition State.h:89
State(ASTContext &ASTCtx, Expr::EvalStatus &EvalStatus)
Definition State.h:81
Top level wrappers for InstallAPI frontend operations.
const FunctionProtoType * T
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:650
const VarDecl * asVarDecl() const
Definition Descriptor.h:209