1 //===--- Context.cpp - Context for the constexpr VM -------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
10 #include "ByteCodeEmitter.h"
11 #include "ByteCodeExprGen.h"
12 #include "ByteCodeStmtGen.h"
13 #include "EvalEmitter.h"
15 #include "InterpFrame.h"
16 #include "InterpStack.h"
19 #include "clang/AST/Expr.h"
21 using namespace clang;
22 using namespace clang::interp;
24 Context::Context(ASTContext &Ctx) : Ctx(Ctx), P(new Program(*this)) {}
26 Context::~Context() {}
28 bool Context::isPotentialConstantExpr(State &Parent, const FunctionDecl *FD) {
29 Function *Func = P->getFunction(FD);
31 if (auto R = ByteCodeStmtGen<ByteCodeEmitter>(*this, *P).compileFunc(FD)) {
34 handleAllErrors(R.takeError(), [&Parent](ByteCodeGenError &Err) {
35 Parent.FFDiag(Err.getLoc(), diag::err_experimental_clang_interp_failed);
41 if (!Func->isConstexpr())
45 return Run(Parent, Func, Dummy);
48 bool Context::evaluateAsRValue(State &Parent, const Expr *E, APValue &Result) {
49 ByteCodeExprGen<EvalEmitter> C(*this, *P, Parent, Stk, Result);
50 return Check(Parent, C.interpretExpr(E));
53 bool Context::evaluateAsInitializer(State &Parent, const VarDecl *VD,
55 ByteCodeExprGen<EvalEmitter> C(*this, *P, Parent, Stk, Result);
56 return Check(Parent, C.interpretDecl(VD));
59 const LangOptions &Context::getLangOpts() const { return Ctx.getLangOpts(); }
61 llvm::Optional<PrimType> Context::classify(QualType T) {
62 if (T->isReferenceType() || T->isPointerType()) {
66 if (T->isBooleanType())
69 if (T->isSignedIntegerOrEnumerationType()) {
70 switch (Ctx.getIntWidth(T)) {
84 if (T->isUnsignedIntegerOrEnumerationType()) {
85 switch (Ctx.getIntWidth(T)) {
99 if (T->isNullPtrType())
102 if (auto *AT = dyn_cast<AtomicType>(T))
103 return classify(AT->getValueType());
108 unsigned Context::getCharBit() const {
109 return Ctx.getTargetInfo().getCharWidth();
112 bool Context::Run(State &Parent, Function *Func, APValue &Result) {
113 InterpState State(Parent, *P, Stk, *this);
114 State.Current = new InterpFrame(State, Func, nullptr, {}, {});
115 if (Interpret(State, Result))
121 bool Context::Check(State &Parent, llvm::Expected<bool> &&Flag) {
124 handleAllErrors(Flag.takeError(), [&Parent](ByteCodeGenError &Err) {
125 Parent.FFDiag(Err.getLoc(), diag::err_experimental_clang_interp_failed);