clang 24.0.0git
InterpState.cpp
Go to the documentation of this file.
1//===--- InterpState.cpp - Interpreter 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 "InterpState.h"
10#include "InterpFrame.h"
11#include "InterpStack.h"
12#include "Program.h"
13#include "State.h"
14#include "clang/AST/DeclCXX.h"
16
17using namespace clang;
18using namespace clang::interp;
19
33
47
49 FrameAllocator &FrameAlloc, Context &Ctx,
50 SourceMapper *M)
51 : State(Ctx.getASTContext(), Status), M(M), FrameAlloc(FrameAlloc), P(P),
53 StepsLeft(Ctx.getLangOpts().ConstexprStepLimit),
54 InfiniteSteps(StepsLeft == 0), EvalID(Ctx.getEvalID()) {
55 InConstantContext = true;
59}
60
67
69 assert(Current->isBottomFrame());
70
71 while (DeadBlocks) {
72 DeadBlock *Next = DeadBlocks->Next;
73
74 // There might be a pointer in a global structure pointing to the dead
75 // block.
76 for (Pointer *P = DeadBlocks->B.Pointers; P; P = P->asBlockPointer().Next)
77 DeadBlocks->B.removePointer(P);
78
79 std::free(DeadBlocks);
80 DeadBlocks = Next;
81 }
82}
83
85 // As a last resort, make sure all pointers still pointing to a dead block
86 // don't point to it anymore.
87 if (Alloc)
88 Alloc->cleanup();
89}
90
92
94 assert(B);
95 assert(!B->isDynamic());
96 assert(!B->isStatic());
97 assert(!B->isDead());
98
99 // The block might have a pointer saved in a field in its data
100 // that points to the block itself. We call the dtor first,
101 // which will destroy all the data but leave InlineDescriptors
102 // intact. If the block THEN still has pointers, we create a
103 // DeadBlock for it.
104 if (B->IsInitialized)
105 B->invokeDtor();
106
107 assert(!B->isInitialized());
108 if (B->hasPointers()) {
109 size_t Size = B->getSize();
110 // Allocate a new block, transferring over pointers.
111 char *Memory =
112 reinterpret_cast<char *>(std::malloc(sizeof(DeadBlock) + Size));
113 auto *D = new (Memory) DeadBlock(DeadBlocks, B);
114 // Since the block doesn't hold any actual data anymore, we can just
115 // memcpy() everything over.
116 std::memcpy(D->rawData(), B->rawData(), Size);
117 D->B.IsInitialized = false;
118 }
119}
120
122 if (!Alloc)
123 return true;
124
125 bool NoAllocationsLeft = !Alloc->hasAllocations();
126
128 for (const auto &[Source, Site] : Alloc->allocation_sites()) {
129 assert(!Site.empty());
130
131 CCEDiag(Source->getExprLoc(), diag::note_constexpr_memory_leak)
132 << (Site.size() - 1) << Source->getSourceRange();
133 }
134 }
135 // Keep evaluating before C++20, since the CXXNewExpr wasn't valid there
136 // in the first place.
137 return NoAllocationsLeft || !getLangOpts().CPlusPlus20;
138}
139
141 for (const InterpFrame *F = Current; F; F = F->Caller) {
142 const Function *Func = F->getFunction();
143 if (!Func)
144 continue;
145 const auto *MD = dyn_cast_if_present<CXXMethodDecl>(Func->getDecl());
146 if (!MD)
147 continue;
148 const IdentifierInfo *FnII = MD->getIdentifier();
149 if (!FnII || !FnII->isStr(Name))
150 continue;
151
152 const auto *CTSD =
153 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
154 if (!CTSD)
155 continue;
156
157 const IdentifierInfo *ClassII = CTSD->getIdentifier();
158 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
159 if (CTSD->isInStdNamespace() && ClassII && ClassII->isStr("allocator") &&
160 TAL.size() >= 1 && TAL[0].getKind() == TemplateArgument::Type) {
161 QualType ElemType = TAL[0].getAsType();
162 const auto *NewCall = cast<CallExpr>(F->Caller->getExpr(F->getRetOpPC()));
163 return {NewCall, ElemType};
164 }
165 }
166
167 return {};
168}
169
170bool InterpState::diagnoseStepLimitExceeded(CodePtr OpPC) {
171 FFDiag(Current->getSource(OpPC), diag::note_constexpr_step_limit_exceeded, 1)
172 << getLangOpts().ConstexprStepLimit;
173 Note(Current->getSource(OpPC), diag::note_constexpr_steps);
174 return false;
175}
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
FormatToken * Next
The next token in the unwrapped line.
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
A (possibly-)qualified type.
Definition TypeBase.h:938
A template argument list.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
@ Type
The template argument is a type.
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:43
unsigned getSize() const
Returns the size of the block, including metadata.
Definition InterpBlock.h:86
void invokeDtor()
Invokes the Destructor.
bool isDead() const
Definition InterpBlock.h:84
bool isStatic() const
Checks if the block has static storage duration.
Definition InterpBlock.h:79
std::byte * rawData()
Returns a pointer to the raw data, including metadata.
bool isInitialized() const
Returns whether the data of this block has been initialized via invoking the Ctor func.
Definition InterpBlock.h:93
bool isDynamic() const
Definition InterpBlock.h:83
bool hasPointers() const
Checks if the block has any live pointers.
Definition InterpBlock.h:75
Pointer into the code segment.
Definition Source.h:31
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:48
Descriptor for a dead block.
Allocator for function frames.
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
SourceInfo getSource(CodePtr PC) const
Map a location to a source.
Stack frame storing temporaries and parameters.
Definition InterpStack.h:25
InterpFrame BottomFrame
Bottom function frame.
InterpState(const State &Parent, Program &P, InterpStack &Stk, FrameAllocator &FrameAlloc, Context &Ctx, SourceMapper *M=nullptr)
Context & Ctx
Interpreter Context.
const unsigned EvalID
ID identifying this evaluation.
InterpStack & Stk
Temporary stack.
bool maybeDiagnoseDanglingAllocations()
Diagnose any dynamic allocations that haven't been freed yet.
unsigned StepsLeft
Steps left during evaluation.
InterpFrame * Current
The current frame.
const Frame * getCurrentFrame() override
std::optional< bool > ConstantContextOverride
const bool InfiniteSteps
Whether infinite evaluation steps have been requested.
void deallocate(Block *B)
Deallocates a pointer.
StdAllocatorCaller getStdAllocatorCaller(StringRef Name) const
Program & P
Reference to the module containing all bytecode.
A pointer to a memory block, live or dead.
Definition Pointer.h:541
The program contains and links the bytecode for all functions.
Definition Program.h:37
Interface for classes which map locations to sources.
Definition Source.h:138
EvaluationMode EvalMode
Definition State.h:190
Expr::EvalStatus & getEvalStatus() const
Definition State.h:89
OptionalDiagnostic FFDiag(SourceLocation Loc, diag::kind DiagId=diag::note_invalid_subexpr_in_const_expr, unsigned ExtraNotes=0)
Diagnose that the evaluation could not be folded (FF => FoldFailure)
Definition State.cpp:37
State(ASTContext &ASTCtx, Expr::EvalStatus &EvalStatus)
Definition State.h:81
bool CheckingPotentialConstantExpression
Whether we're checking that an expression is a potential constant expression.
Definition State.h:180
bool CheckingForUndefinedBehavior
Whether we're checking for an expression that has undefined behavior.
Definition State.h:188
ASTContext & getASTContext() const
Definition State.h:90
OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId=diag::note_invalid_subexpr_in_const_expr, unsigned ExtraNotes=0)
Diagnose that the evaluation does not produce a C++11 core constant expression.
Definition State.cpp:60
const LangOptions & getLangOpts() const
Definition State.h:91
bool checkingPotentialConstantExpression() const
Are we checking whether the expression is a potential constant expression?
Definition State.h:122
bool InConstantContext
Whether or not we're in a context where the front end requires a constant value.
Definition State.h:175
Top level wrappers for InstallAPI frontend operations.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ ConstantExpression
Evaluate as a constant expression.
Definition State.h:56
U cast(CodeGen::Address addr)
Definition Address.h:327
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition Expr.h:622