1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
|
//===--- InterpreterValuePrinter.cpp - Value printing utils -----*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements routines for in-process value printing in clang-repl.
//
//===----------------------------------------------------------------------===//
#include "IncrementalParser.h"
#include "InterpreterUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/Type.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Interpreter/Interpreter.h"
#include "clang/Interpreter/Value.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Sema.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <string>
#include <cstdarg>
namespace clang {
llvm::Expected<llvm::orc::ExecutorAddr>
Interpreter::CompileDtorCall(CXXRecordDecl *CXXRD) {
assert(CXXRD && "Cannot compile a destructor for a nullptr");
if (auto Dtor = Dtors.find(CXXRD); Dtor != Dtors.end())
return Dtor->getSecond();
if (CXXRD->hasIrrelevantDestructor())
return llvm::orc::ExecutorAddr{};
CXXDestructorDecl *DtorRD =
getCompilerInstance()->getSema().LookupDestructor(CXXRD);
llvm::StringRef Name =
getCodeGen()->GetMangledName(GlobalDecl(DtorRD, Dtor_Base));
auto AddrOrErr = getSymbolAddress(Name);
if (!AddrOrErr)
return AddrOrErr.takeError();
Dtors[CXXRD] = *AddrOrErr;
return AddrOrErr;
}
enum InterfaceKind { NoAlloc, WithAlloc, CopyArray, NewTag };
class InterfaceKindVisitor
: public TypeVisitor<InterfaceKindVisitor, InterfaceKind> {
Sema &S;
Expr *E;
llvm::SmallVectorImpl<Expr *> &Args;
public:
InterfaceKindVisitor(Sema &S, Expr *E, llvm::SmallVectorImpl<Expr *> &Args)
: S(S), E(E), Args(Args) {}
InterfaceKind computeInterfaceKind(QualType Ty) {
return Visit(Ty.getTypePtr());
}
InterfaceKind VisitRecordType(const RecordType *Ty) {
return InterfaceKind::WithAlloc;
}
InterfaceKind VisitMemberPointerType(const MemberPointerType *Ty) {
return InterfaceKind::WithAlloc;
}
InterfaceKind VisitConstantArrayType(const ConstantArrayType *Ty) {
return InterfaceKind::CopyArray;
}
InterfaceKind VisitFunctionProtoType(const FunctionProtoType *Ty) {
HandlePtrType(Ty);
return InterfaceKind::NoAlloc;
}
InterfaceKind VisitPointerType(const PointerType *Ty) {
HandlePtrType(Ty);
return InterfaceKind::NoAlloc;
}
InterfaceKind VisitReferenceType(const ReferenceType *Ty) {
ExprResult AddrOfE = S.CreateBuiltinUnaryOp(SourceLocation(), UO_AddrOf, E);
assert(!AddrOfE.isInvalid() && "Can not create unary expression");
Args.push_back(AddrOfE.get());
return InterfaceKind::NoAlloc;
}
InterfaceKind VisitBuiltinType(const BuiltinType *Ty) {
if (Ty->isNullPtrType())
Args.push_back(E);
else if (Ty->isFloatingType())
Args.push_back(E);
else if (Ty->isIntegralOrEnumerationType())
HandleIntegralOrEnumType(Ty);
else if (Ty->isVoidType()) {
// Do we need to still run `E`?
}
return InterfaceKind::NoAlloc;
}
InterfaceKind VisitEnumType(const EnumType *Ty) {
HandleIntegralOrEnumType(Ty);
return InterfaceKind::NoAlloc;
}
private:
// Force cast these types to the uint that fits the register size. That way we
// reduce the number of overloads of `__clang_Interpreter_SetValueNoAlloc`.
void HandleIntegralOrEnumType(const Type *Ty) {
ASTContext &Ctx = S.getASTContext();
uint64_t PtrBits = Ctx.getTypeSize(Ctx.VoidPtrTy);
QualType UIntTy = Ctx.getBitIntType(/*Unsigned=*/true, PtrBits);
TypeSourceInfo *TSI = Ctx.getTrivialTypeSourceInfo(UIntTy);
ExprResult CastedExpr =
S.BuildCStyleCastExpr(SourceLocation(), TSI, SourceLocation(), E);
assert(!CastedExpr.isInvalid() && "Cannot create cstyle cast expr");
Args.push_back(CastedExpr.get());
}
void HandlePtrType(const Type *Ty) {
ASTContext &Ctx = S.getASTContext();
TypeSourceInfo *TSI = Ctx.getTrivialTypeSourceInfo(Ctx.VoidPtrTy);
ExprResult CastedExpr =
S.BuildCStyleCastExpr(SourceLocation(), TSI, SourceLocation(), E);
assert(!CastedExpr.isInvalid() && "Can not create cstyle cast expression");
Args.push_back(CastedExpr.get());
}
};
// This synthesizes a call expression to a speciall
// function that is responsible for generating the Value.
// In general, we transform:
// clang-repl> x
// To:
// // 1. If x is a built-in type like int, float.
// __clang_Interpreter_SetValueNoAlloc(ThisInterp, OpaqueValue, xQualType, x);
// // 2. If x is a struct, and a lvalue.
// __clang_Interpreter_SetValueNoAlloc(ThisInterp, OpaqueValue, xQualType,
// &x);
// // 3. If x is a struct, but a rvalue.
// new (__clang_Interpreter_SetValueWithAlloc(ThisInterp, OpaqueValue,
// xQualType)) (x);
llvm::Expected<Expr *> Interpreter::ExtractValueFromExpr(Expr *E) {
Sema &S = getCompilerInstance()->getSema();
ASTContext &Ctx = S.getASTContext();
// Find the value printing builtins.
if (!ValuePrintingInfo[0]) {
assert(llvm::all_of(ValuePrintingInfo, [](Expr *E) { return !E; }));
auto LookupInterface = [&](Expr *&Interface,
llvm::StringRef Name) -> llvm::Error {
LookupResult R(S, &Ctx.Idents.get(Name), SourceLocation(),
Sema::LookupOrdinaryName,
RedeclarationKind::ForVisibleRedeclaration);
S.LookupQualifiedName(R, Ctx.getTranslationUnitDecl());
if (R.empty())
return llvm::make_error<llvm::StringError>(
Name + " not found!", llvm::inconvertibleErrorCode());
CXXScopeSpec CSS;
Interface = S.BuildDeclarationNameExpr(CSS, R, /*ADL=*/false).get();
return llvm::Error::success();
};
static constexpr llvm::StringRef Builtin[] = {
"__clang_Interpreter_SetValueNoAlloc",
"__clang_Interpreter_SetValueWithAlloc",
"__clang_Interpreter_SetValueCopyArr", "__ci_newtag"};
if (llvm::Error Err =
LookupInterface(ValuePrintingInfo[NoAlloc], Builtin[NoAlloc]))
return std::move(Err);
if (Ctx.getLangOpts().CPlusPlus) {
if (llvm::Error Err =
LookupInterface(ValuePrintingInfo[WithAlloc], Builtin[WithAlloc]))
return std::move(Err);
if (llvm::Error Err =
LookupInterface(ValuePrintingInfo[CopyArray], Builtin[CopyArray]))
return std::move(Err);
if (llvm::Error Err =
LookupInterface(ValuePrintingInfo[NewTag], Builtin[NewTag]))
return std::move(Err);
}
}
llvm::SmallVector<Expr *, 4> AdjustedArgs;
// Create parameter `ThisInterp`.
AdjustedArgs.push_back(CStyleCastPtrExpr(S, Ctx.VoidPtrTy, (uintptr_t)this));
// Create parameter `OutVal`.
AdjustedArgs.push_back(
CStyleCastPtrExpr(S, Ctx.VoidPtrTy, (uintptr_t)&LastValue));
// Build `__clang_Interpreter_SetValue*` call.
// Get rid of ExprWithCleanups.
if (auto *EWC = llvm::dyn_cast_if_present<ExprWithCleanups>(E))
E = EWC->getSubExpr();
QualType Ty = E->getType();
QualType DesugaredTy = Ty.getDesugaredType(Ctx);
// For lvalue struct, we treat it as a reference.
if (DesugaredTy->isRecordType() && E->isLValue()) {
DesugaredTy = Ctx.getLValueReferenceType(DesugaredTy);
Ty = Ctx.getLValueReferenceType(Ty);
}
Expr *TypeArg =
CStyleCastPtrExpr(S, Ctx.VoidPtrTy, (uintptr_t)Ty.getAsOpaquePtr());
// The QualType parameter `OpaqueType`, represented as `void*`.
AdjustedArgs.push_back(TypeArg);
// We push the last parameter based on the type of the Expr. Note we need
// special care for rvalue struct.
InterfaceKindVisitor V(S, E, AdjustedArgs);
Scope *Scope = nullptr;
ExprResult SetValueE;
InterfaceKind Kind = V.computeInterfaceKind(DesugaredTy);
switch (Kind) {
case InterfaceKind::WithAlloc:
LLVM_FALLTHROUGH;
case InterfaceKind::CopyArray: {
// __clang_Interpreter_SetValueWithAlloc.
ExprResult AllocCall =
S.ActOnCallExpr(Scope, ValuePrintingInfo[InterfaceKind::WithAlloc],
E->getBeginLoc(), AdjustedArgs, E->getEndLoc());
assert(!AllocCall.isInvalid() && "Can't create runtime interface call!");
TypeSourceInfo *TSI = Ctx.getTrivialTypeSourceInfo(Ty, SourceLocation());
// Force CodeGen to emit destructor.
if (auto *RD = Ty->getAsCXXRecordDecl()) {
auto *Dtor = S.LookupDestructor(RD);
Dtor->addAttr(UsedAttr::CreateImplicit(Ctx));
getCompilerInstance()->getASTConsumer().HandleTopLevelDecl(
DeclGroupRef(Dtor));
}
// __clang_Interpreter_SetValueCopyArr.
if (Kind == InterfaceKind::CopyArray) {
const auto *ConstantArrTy =
cast<ConstantArrayType>(DesugaredTy.getTypePtr());
size_t ArrSize = Ctx.getConstantArrayElementCount(ConstantArrTy);
Expr *ArrSizeExpr = IntegerLiteralExpr(Ctx, ArrSize);
Expr *Args[] = {E, AllocCall.get(), ArrSizeExpr};
SetValueE =
S.ActOnCallExpr(Scope, ValuePrintingInfo[InterfaceKind::CopyArray],
SourceLocation(), Args, SourceLocation());
}
Expr *Args[] = {AllocCall.get(), ValuePrintingInfo[InterfaceKind::NewTag]};
ExprResult CXXNewCall = S.BuildCXXNew(
E->getSourceRange(),
/*UseGlobal=*/true, /*PlacementLParen=*/SourceLocation(), Args,
/*PlacementRParen=*/SourceLocation(),
/*TypeIdParens=*/SourceRange(), TSI->getType(), TSI, std::nullopt,
E->getSourceRange(), E);
assert(!CXXNewCall.isInvalid() &&
"Can't create runtime placement new call!");
SetValueE = S.ActOnFinishFullExpr(CXXNewCall.get(),
/*DiscardedValue=*/false);
break;
}
// __clang_Interpreter_SetValueNoAlloc.
case InterfaceKind::NoAlloc: {
SetValueE =
S.ActOnCallExpr(Scope, ValuePrintingInfo[InterfaceKind::NoAlloc],
E->getBeginLoc(), AdjustedArgs, E->getEndLoc());
break;
}
default:
llvm_unreachable("Unhandled InterfaceKind");
}
// It could fail, like printing an array type in C. (not supported)
if (SetValueE.isInvalid())
return E;
return SetValueE.get();
}
} // namespace clang
using namespace clang;
// Temporary rvalue struct that need special care.
REPL_EXTERNAL_VISIBILITY void *
__clang_Interpreter_SetValueWithAlloc(void *This, void *OutVal,
void *OpaqueType) {
Value &VRef = *(Value *)OutVal;
VRef = Value(static_cast<Interpreter *>(This), OpaqueType);
return VRef.getPtr();
}
extern "C" void REPL_EXTERNAL_VISIBILITY __clang_Interpreter_SetValueNoAlloc(
void *This, void *OutVal, void *OpaqueType, ...) {
Value &VRef = *(Value *)OutVal;
Interpreter *I = static_cast<Interpreter *>(This);
VRef = Value(I, OpaqueType);
if (VRef.isVoid())
return;
va_list args;
va_start(args, /*last named param*/ OpaqueType);
QualType QT = VRef.getType();
if (VRef.getKind() == Value::K_PtrOrObj) {
VRef.setPtr(va_arg(args, void *));
} else {
if (const auto *ET = QT->getAs<EnumType>())
QT = ET->getDecl()->getIntegerType();
switch (QT->castAs<BuiltinType>()->getKind()) {
default:
llvm_unreachable("unknown type kind!");
break;
// Types shorter than int are resolved as int, else va_arg has UB.
case BuiltinType::Bool:
VRef.setBool(va_arg(args, int));
break;
case BuiltinType::Char_S:
VRef.setChar_S(va_arg(args, int));
break;
case BuiltinType::SChar:
VRef.setSChar(va_arg(args, int));
break;
case BuiltinType::Char_U:
VRef.setChar_U(va_arg(args, unsigned));
break;
case BuiltinType::UChar:
VRef.setUChar(va_arg(args, unsigned));
break;
case BuiltinType::Short:
VRef.setShort(va_arg(args, int));
break;
case BuiltinType::UShort:
VRef.setUShort(va_arg(args, unsigned));
break;
case BuiltinType::Int:
VRef.setInt(va_arg(args, int));
break;
case BuiltinType::UInt:
VRef.setUInt(va_arg(args, unsigned));
break;
case BuiltinType::Long:
VRef.setLong(va_arg(args, long));
break;
case BuiltinType::ULong:
VRef.setULong(va_arg(args, unsigned long));
break;
case BuiltinType::LongLong:
VRef.setLongLong(va_arg(args, long long));
break;
case BuiltinType::ULongLong:
VRef.setULongLong(va_arg(args, unsigned long long));
break;
// Types shorter than double are resolved as double, else va_arg has UB.
case BuiltinType::Float:
VRef.setFloat(va_arg(args, double));
break;
case BuiltinType::Double:
VRef.setDouble(va_arg(args, double));
break;
case BuiltinType::LongDouble:
VRef.setLongDouble(va_arg(args, long double));
break;
// See REPL_BUILTIN_TYPES.
}
}
va_end(args);
}
// A trampoline to work around the fact that operator placement new cannot
// really be forward declared due to libc++ and libstdc++ declaration mismatch.
// FIXME: __clang_Interpreter_NewTag is ODR violation because we get the same
// definition in the interpreter runtime. We should move it in a runtime header
// which gets included by the interpreter and here.
struct __clang_Interpreter_NewTag {};
REPL_EXTERNAL_VISIBILITY void *
operator new(size_t __sz, void *__p, __clang_Interpreter_NewTag) noexcept {
// Just forward to the standard operator placement new.
return operator new(__sz, __p);
}
|