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"
15#include "clang/AST/DeclTemplate.h"
16
17using namespace clang;
18using namespace clang::interp;
19
20InterpState::InterpState(const State &Parent, Program &P, InterpStack &Stk,
21 Context &Ctx, SourceMapper *M)
22 : State(Ctx.getASTContext(), Parent.getEvalStatus()), M(M), P(P), Stk(Stk),
23 Ctx(Ctx), BottomFrame(*this), Current(&BottomFrame),
24 StepsLeft(Ctx.getLangOpts().ConstexprStepLimit),
25 InfiniteSteps(StepsLeft == 0) {
26 InConstantContext = Parent.InConstantContext;
27 CheckingPotentialConstantExpression =
28 Parent.CheckingPotentialConstantExpression;
29 CheckingForUndefinedBehavior = Parent.CheckingForUndefinedBehavior;
30 EvalMode = Parent.EvalMode;
31}
32
33InterpState::InterpState(const State &Parent, Program &P, InterpStack &Stk,
34 Context &Ctx, const Function *Func)
35 : State(Ctx.getASTContext(), Parent.getEvalStatus()), M(nullptr), P(P),
36 Stk(Stk), Ctx(Ctx),
37 BottomFrame(*this, Func, nullptr, CodePtr(), Func->getArgSize()),
38 Current(&BottomFrame), StepsLeft(Ctx.getLangOpts().ConstexprStepLimit),
39 InfiniteSteps(StepsLeft == 0) {
40 InConstantContext = Parent.InConstantContext;
41 CheckingPotentialConstantExpression =
42 Parent.CheckingPotentialConstantExpression;
43 CheckingForUndefinedBehavior = Parent.CheckingForUndefinedBehavior;
44 EvalMode = Parent.EvalMode;
45}
46
47bool InterpState::inConstantContext() const {
48 if (ConstantContextOverride)
49 return *ConstantContextOverride;
50
51 return InConstantContext;
52}
53
54InterpState::~InterpState() {
55 while (Current && !Current->isBottomFrame()) {
56 InterpFrame *Next = Current->Caller;
57 delete Current;
58 Current = Next;
59 }
60 BottomFrame.destroyScopes();
61
62 while (DeadBlocks) {
63 DeadBlock *Next = DeadBlocks->Next;
64
65 // There might be a pointer in a global structure pointing to the dead
66 // block.
67 for (Pointer *P = DeadBlocks->B.Pointers; P; P = P->asBlockPointer().Next)
68 DeadBlocks->B.removePointer(P);
69
70 std::free(ptr: DeadBlocks);
71 DeadBlocks = Next;
72 }
73}
74
75void InterpState::cleanup() {
76 // As a last resort, make sure all pointers still pointing to a dead block
77 // don't point to it anymore.
78 if (Alloc)
79 Alloc->cleanup();
80}
81
82const Frame *InterpState::getCurrentFrame() { return Current; }
83
84void InterpState::deallocate(Block *B) {
85 assert(B);
86 assert(!B->isDynamic());
87 assert(!B->isStatic());
88 assert(!B->isDead());
89
90 // The block might have a pointer saved in a field in its data
91 // that points to the block itself. We call the dtor first,
92 // which will destroy all the data but leave InlineDescriptors
93 // intact. If the block THEN still has pointers, we create a
94 // DeadBlock for it.
95 if (B->IsInitialized)
96 B->invokeDtor();
97
98 assert(!B->isInitialized());
99 if (B->hasPointers()) {
100 size_t Size = B->getSize();
101 // Allocate a new block, transferring over pointers.
102 char *Memory =
103 reinterpret_cast<char *>(std::malloc(size: sizeof(DeadBlock) + Size));
104 auto *D = new (Memory) DeadBlock(DeadBlocks, B);
105 // Since the block doesn't hold any actual data anymore, we can just
106 // memcpy() everything over.
107 std::memcpy(dest: D->rawData(), src: B->rawData(), n: Size);
108 D->B.IsInitialized = false;
109 }
110}
111
112bool InterpState::maybeDiagnoseDanglingAllocations() {
113 if (!Alloc)
114 return true;
115
116 bool NoAllocationsLeft = !Alloc->hasAllocations();
117
118 if (!checkingPotentialConstantExpression()) {
119 for (const auto &[Source, Site] : Alloc->allocation_sites()) {
120 assert(!Site.empty());
121
122 CCEDiag(Loc: Source->getExprLoc(), DiagId: diag::note_constexpr_memory_leak)
123 << (Site.size() - 1) << Source->getSourceRange();
124 }
125 }
126 // Keep evaluating before C++20, since the CXXNewExpr wasn't valid there
127 // in the first place.
128 return NoAllocationsLeft || !getLangOpts().CPlusPlus20;
129}
130
131StdAllocatorCaller InterpState::getStdAllocatorCaller(StringRef Name) const {
132 for (const InterpFrame *F = Current; F; F = F->Caller) {
133 const Function *Func = F->getFunction();
134 if (!Func)
135 continue;
136 const auto *MD = dyn_cast_if_present<CXXMethodDecl>(Val: Func->getDecl());
137 if (!MD)
138 continue;
139 const IdentifierInfo *FnII = MD->getIdentifier();
140 if (!FnII || !FnII->isStr(Str: Name))
141 continue;
142
143 const auto *CTSD =
144 dyn_cast<ClassTemplateSpecializationDecl>(Val: MD->getParent());
145 if (!CTSD)
146 continue;
147
148 const IdentifierInfo *ClassII = CTSD->getIdentifier();
149 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
150 if (CTSD->isInStdNamespace() && ClassII && ClassII->isStr(Str: "allocator") &&
151 TAL.size() >= 1 && TAL[0].getKind() == TemplateArgument::Type) {
152 QualType ElemType = TAL[0].getAsType();
153 const auto *NewCall = cast<CallExpr>(Val: F->Caller->getExpr(PC: F->getRetPC()));
154 return {.Call: NewCall, .AllocType: ElemType};
155 }
156 }
157
158 return {};
159}
160
161bool InterpState::noteStep(CodePtr OpPC) {
162 if (InfiniteSteps)
163 return true;
164
165 --StepsLeft;
166 if (StepsLeft != 0)
167 return true;
168
169 FFDiag(SI: Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_step_limit_exceeded);
170 return false;
171}
172