| 1 |
//===- unittests/Interpreter/InterpreterTest.cpp --- Interpreter tests ----===// |
| 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 |
// Unit tests for Clang's Interpreter library. |
| 10 |
// |
| 11 |
//===----------------------------------------------------------------------===// |
| 12 |
|
| 13 |
#include "clang/Interpreter/Interpreter.h" |
| 14 |
|
| 15 |
#include "clang/AST/Decl.h" |
| 16 |
#include "clang/AST/DeclGroup.h" |
| 17 |
#include "clang/AST/Mangle.h" |
| 18 |
#include "clang/Frontend/CompilerInstance.h" |
| 19 |
#include "clang/Frontend/TextDiagnosticPrinter.h" |
| 20 |
#include "clang/Sema/Lookup.h" |
| 21 |
#include "clang/Sema/Sema.h" |
| 22 |
|
| 23 |
#include "llvm/ExecutionEngine/Orc/LLJIT.h" |
| 24 |
#include "llvm/Support/ManagedStatic.h" |
| 25 |
#include "llvm/Support/TargetSelect.h" |
| 26 |
|
| 27 |
#include "gmock/gmock.h" |
| 28 |
#include "gtest/gtest.h" |
| 29 |
|
| 30 |
using namespace clang; |
| 31 |
|
| 32 |
#if defined(_AIX) |
| 33 |
#define CLANG_INTERPRETER_NO_SUPPORT_EXEC |
| 34 |
#endif |
| 35 |
|
| 36 |
namespace { |
| 37 |
using Args = std::vector<const char *>; |
| 38 |
static std::unique_ptr<Interpreter> |
| 39 |
createInterpreter(const Args &ExtraArgs = {}, |
| 40 |
DiagnosticConsumer *Client = nullptr) { |
| 41 |
Args ClangArgs = {"-Xclang", "-emit-llvm-only"}; |
| 42 |
ClangArgs.insert(ClangArgs.end(), ExtraArgs.begin(), ExtraArgs.end()); |
| 43 |
auto CI = cantFail(clang::IncrementalCompilerBuilder::create(ClangArgs)); |
| 44 |
if (Client) |
| 45 |
CI->getDiagnostics().setClient(Client, /*ShouldOwnClient=*/false); |
| 46 |
return cantFail(clang::Interpreter::create(std::move(CI))); |
| 47 |
} |
| 48 |
|
| 49 |
static size_t DeclsSize(TranslationUnitDecl *PTUDecl) { |
| 50 |
return std::distance(PTUDecl->decls().begin(), PTUDecl->decls().end()); |
| 51 |
} |
| 52 |
|
| 53 |
TEST(InterpreterTest, Sanity) { |
| 54 |
std::unique_ptr<Interpreter> Interp = createInterpreter(); |
| 55 |
|
| 56 |
using PTU = PartialTranslationUnit; |
| 57 |
|
| 58 |
PTU &R1(cantFail(Interp->Parse("void g(); void g() {}"))); |
| 59 |
EXPECT_EQ(2U, DeclsSize(R1.TUPart)); |
| 60 |
|
| 61 |
PTU &R2(cantFail(Interp->Parse("int i;"))); |
| 62 |
EXPECT_EQ(1U, DeclsSize(R2.TUPart)); |
| 63 |
} |
| 64 |
|
| 65 |
static std::string DeclToString(Decl *D) { |
| 66 |
return llvm::cast<NamedDecl>(D)->getQualifiedNameAsString(); |
| 67 |
} |
| 68 |
|
| 69 |
TEST(InterpreterTest, IncrementalInputTopLevelDecls) { |
| 70 |
std::unique_ptr<Interpreter> Interp = createInterpreter(); |
| 71 |
auto R1 = Interp->Parse("int var1 = 42; int f() { return var1; }"); |
| 72 |
// gtest doesn't expand into explicit bool conversions. |
| 73 |
EXPECT_TRUE(!!R1); |
| 74 |
auto R1DeclRange = R1->TUPart->decls(); |
| 75 |
EXPECT_EQ(2U, DeclsSize(R1->TUPart)); |
| 76 |
EXPECT_EQ("var1", DeclToString(*R1DeclRange.begin())); |
| 77 |
EXPECT_EQ("f", DeclToString(*(++R1DeclRange.begin()))); |
| 78 |
|
| 79 |
auto R2 = Interp->Parse("int var2 = f();"); |
| 80 |
EXPECT_TRUE(!!R2); |
| 81 |
auto R2DeclRange = R2->TUPart->decls(); |
| 82 |
EXPECT_EQ(1U, DeclsSize(R2->TUPart)); |
| 83 |
EXPECT_EQ("var2", DeclToString(*R2DeclRange.begin())); |
| 84 |
} |
| 85 |
|
| 86 |
TEST(InterpreterTest, Errors) { |
| 87 |
Args ExtraArgs = {"-Xclang", "-diagnostic-log-file", "-Xclang", "-"}; |
| 88 |
|
| 89 |
// Create the diagnostic engine with unowned consumer. |
| 90 |
std::string DiagnosticOutput; |
| 91 |
llvm::raw_string_ostream DiagnosticsOS(DiagnosticOutput); |
| 92 |
auto DiagPrinter = std::make_unique<TextDiagnosticPrinter>( |
| 93 |
DiagnosticsOS, new DiagnosticOptions()); |
| 94 |
|
| 95 |
auto Interp = createInterpreter(ExtraArgs, DiagPrinter.get()); |
| 96 |
auto Err = Interp->Parse("intentional_error v1 = 42; ").takeError(); |
| 97 |
using ::testing::HasSubstr; |
| 98 |
EXPECT_THAT(DiagnosticsOS.str(), |
| 99 |
HasSubstr("error: unknown type name 'intentional_error'")); |
| 100 |
EXPECT_EQ("Parsing failed.", llvm::toString(std::move(Err))); |
| 101 |
|
| 102 |
auto RecoverErr = Interp->Parse("int var1 = 42;"); |
| 103 |
EXPECT_TRUE(!!RecoverErr); |
| 104 |
} |
| 105 |
|
| 106 |
// Here we test whether the user can mix declarations and statements. The |
| 107 |
// interpreter should be smart enough to recognize the declarations from the |
| 108 |
// statements and wrap the latter into a declaration, producing valid code. |
| 109 |
TEST(InterpreterTest, DeclsAndStatements) { |
| 110 |
Args ExtraArgs = {"-Xclang", "-diagnostic-log-file", "-Xclang", "-"}; |
| 111 |
|
| 112 |
// Create the diagnostic engine with unowned consumer. |
| 113 |
std::string DiagnosticOutput; |
| 114 |
llvm::raw_string_ostream DiagnosticsOS(DiagnosticOutput); |
| 115 |
auto DiagPrinter = std::make_unique<TextDiagnosticPrinter>( |
| 116 |
DiagnosticsOS, new DiagnosticOptions()); |
| 117 |
|
| 118 |
auto Interp = createInterpreter(ExtraArgs, DiagPrinter.get()); |
| 119 |
auto R1 = Interp->Parse( |
| 120 |
"int var1 = 42; extern \"C\" int printf(const char*, ...);"); |
| 121 |
// gtest doesn't expand into explicit bool conversions. |
| 122 |
EXPECT_TRUE(!!R1); |
| 123 |
|
| 124 |
auto *PTU1 = R1->TUPart; |
| 125 |
EXPECT_EQ(2U, DeclsSize(PTU1)); |
| 126 |
|
| 127 |
auto R2 = Interp->Parse("var1++; printf(\"var1 value %d\\n\", var1);"); |
| 128 |
EXPECT_TRUE(!!R2); |
| 129 |
} |
| 130 |
|
| 131 |
TEST(InterpreterTest, UndoCommand) { |
| 132 |
Args ExtraArgs = {"-Xclang", "-diagnostic-log-file", "-Xclang", "-"}; |
| 133 |
|
| 134 |
// Create the diagnostic engine with unowned consumer. |
| 135 |
std::string DiagnosticOutput; |
| 136 |
llvm::raw_string_ostream DiagnosticsOS(DiagnosticOutput); |
| 137 |
auto DiagPrinter = std::make_unique<TextDiagnosticPrinter>( |
| 138 |
DiagnosticsOS, new DiagnosticOptions()); |
| 139 |
|
| 140 |
auto Interp = createInterpreter(ExtraArgs, DiagPrinter.get()); |
| 141 |
|
| 142 |
// Fail to undo. |
| 143 |
auto Err1 = Interp->Undo(); |
| 144 |
EXPECT_EQ("Operation failed. Too many undos", |
| 145 |
llvm::toString(std::move(Err1))); |
| 146 |
auto Err2 = Interp->Parse("int foo = 42;"); |
| 147 |
EXPECT_TRUE(!!Err2); |
| 148 |
auto Err3 = Interp->Undo(2); |
| 149 |
EXPECT_EQ("Operation failed. Too many undos", |
| 150 |
llvm::toString(std::move(Err3))); |
| 151 |
|
| 152 |
// Succeed to undo. |
| 153 |
auto Err4 = Interp->Parse("int x = 42;"); |
| 154 |
EXPECT_TRUE(!!Err4); |
| 155 |
auto Err5 = Interp->Undo(); |
| 156 |
EXPECT_FALSE(Err5); |
| 157 |
auto Err6 = Interp->Parse("int x = 24;"); |
| 158 |
EXPECT_TRUE(!!Err6); |
| 159 |
auto Err7 = Interp->Parse("#define X 42"); |
| 160 |
EXPECT_TRUE(!!Err7); |
| 161 |
auto Err8 = Interp->Undo(); |
| 162 |
EXPECT_FALSE(Err8); |
| 163 |
auto Err9 = Interp->Parse("#define X 24"); |
| 164 |
EXPECT_TRUE(!!Err9); |
| 165 |
|
| 166 |
// Undo input contains errors. |
| 167 |
auto Err10 = Interp->Parse("int y = ;"); |
| 168 |
EXPECT_FALSE(!!Err10); |
| 169 |
EXPECT_EQ("Parsing failed.", llvm::toString(Err10.takeError())); |
| 170 |
auto Err11 = Interp->Parse("int y = 42;"); |
| 171 |
EXPECT_TRUE(!!Err11); |
| 172 |
auto Err12 = Interp->Undo(); |
| 173 |
EXPECT_FALSE(Err12); |
| 174 |
} |
| 175 |
|
| 176 |
static std::string MangleName(NamedDecl *ND) { |
| 177 |
ASTContext &C = ND->getASTContext(); |
| 178 |
std::unique_ptr<MangleContext> MangleC(C.createMangleContext()); |
| 179 |
std::string mangledName; |
| 180 |
llvm::raw_string_ostream RawStr(mangledName); |
| 181 |
MangleC->mangleName(ND, RawStr); |
| 182 |
return RawStr.str(); |
| 183 |
} |
| 184 |
|
| 185 |
static bool HostSupportsJit() { |
| 186 |
auto J = llvm::orc::LLJITBuilder().create(); |
| 187 |
if (J) |
| 188 |
return true; |
| 189 |
LLVMConsumeError(llvm::wrap(J.takeError())); |
| 190 |
return false; |
| 191 |
} |
| 192 |
|
| 193 |
struct LLVMInitRAII { |
| 194 |
LLVMInitRAII() { |
| 195 |
llvm::InitializeNativeTarget(); |
| 196 |
llvm::InitializeNativeTargetAsmPrinter(); |
| 197 |
} |
| 198 |
~LLVMInitRAII() { llvm::llvm_shutdown(); } |
| 199 |
} LLVMInit; |
| 200 |
|
| 201 |
#ifdef CLANG_INTERPRETER_NO_SUPPORT_EXEC |
| 202 |
TEST(IncrementalProcessing, DISABLED_FindMangledNameSymbol) { |
| 203 |
#else |
| 204 |
TEST(IncrementalProcessing, FindMangledNameSymbol) { |
| 205 |
#endif |
| 206 |
|
| 207 |
std::unique_ptr<Interpreter> Interp = createInterpreter(); |
| 208 |
|
| 209 |
auto &PTU(cantFail(Interp->Parse("int f(const char*) {return 0;}"))); |
| 210 |
EXPECT_EQ(1U, DeclsSize(PTU.TUPart)); |
| 211 |
auto R1DeclRange = PTU.TUPart->decls(); |
| 212 |
|
| 213 |
// We cannot execute on the platform. |
| 214 |
if (!HostSupportsJit()) { |
| 215 |
return; |
| 216 |
} |
| 217 |
|
| 218 |
NamedDecl *FD = cast<FunctionDecl>(*R1DeclRange.begin()); |
| 219 |
// Lower the PTU |
| 220 |
if (llvm::Error Err = Interp->Execute(PTU)) { |
| 221 |
// We cannot execute on the platform. |
| 222 |
consumeError(std::move(Err)); |
| 223 |
return; |
| 224 |
} |
| 225 |
|
| 226 |
std::string MangledName = MangleName(FD); |
| 227 |
auto Addr = cantFail(Interp->getSymbolAddress(MangledName)); |
| 228 |
EXPECT_NE(0U, Addr); |
| 229 |
GlobalDecl GD(FD); |
| 230 |
EXPECT_EQ(Addr, cantFail(Interp->getSymbolAddress(GD))); |
| 231 |
} |
| 232 |
|
| 233 |
static void *AllocateObject(TypeDecl *TD, Interpreter &Interp) { |
| 234 |
std::string Name = TD->getQualifiedNameAsString(); |
| 235 |
const clang::Type *RDTy = TD->getTypeForDecl(); |
| 236 |
clang::ASTContext &C = Interp.getCompilerInstance()->getASTContext(); |
| 237 |
size_t Size = C.getTypeSize(RDTy); |
| 238 |
void *Addr = malloc(Size); |
| 239 |
|
| 240 |
// Tell the interpreter to call the default ctor with this memory. Synthesize: |
| 241 |
// new (loc) ClassName; |
| 242 |
static unsigned Counter = 0; |
| 243 |
std::stringstream SS; |
| 244 |
SS << "auto _v" << Counter++ << " = " |
| 245 |
<< "new ((void*)" |
| 246 |
// Windows needs us to prefix the hexadecimal value of a pointer with '0x'. |
| 247 |
<< std::hex << std::showbase << (size_t)Addr << ")" << Name << "();"; |
| 248 |
|
| 249 |
auto R = Interp.ParseAndExecute(SS.str()); |
| 250 |
if (!R) { |
| 251 |
free(Addr); |
| 252 |
return nullptr; |
| 253 |
} |
| 254 |
|
| 255 |
return Addr; |
| 256 |
} |
| 257 |
|
| 258 |
static NamedDecl *LookupSingleName(Interpreter &Interp, const char *Name) { |
| 259 |
Sema &SemaRef = Interp.getCompilerInstance()->getSema(); |
| 260 |
ASTContext &C = SemaRef.getASTContext(); |
| 261 |
DeclarationName DeclName = &C.Idents.get(Name); |
| 262 |
LookupResult R(SemaRef, DeclName, SourceLocation(), Sema::LookupOrdinaryName); |
| 263 |
SemaRef.LookupName(R, SemaRef.TUScope); |
| 264 |
assert(!R.empty()); |
| 265 |
return R.getFoundDecl(); |
| 266 |
} |
| 267 |
|
| 268 |
#ifdef CLANG_INTERPRETER_NO_SUPPORT_EXEC |
| 269 |
TEST(IncrementalProcessing, DISABLED_InstantiateTemplate) { |
| 270 |
#else |
| 271 |
TEST(IncrementalProcessing, InstantiateTemplate) { |
| 272 |
#endif |
| 273 |
// FIXME: We cannot yet handle delayed template parsing. If we run with |
| 274 |
// -fdelayed-template-parsing we try adding the newly created decl to the |
| 275 |
// active PTU which causes an assert. |
| 276 |
std::vector<const char *> Args = {"-fno-delayed-template-parsing"}; |
| 277 |
std::unique_ptr<Interpreter> Interp = createInterpreter(Args); |
| 278 |
|
| 279 |
llvm::cantFail(Interp->Parse("void* operator new(__SIZE_TYPE__, void* __p);" |
| 280 |
"extern \"C\" int printf(const char*,...);" |
| 281 |
"class A {};" |
| 282 |
"struct B {" |
| 283 |
" template<typename T>" |
| 284 |
" static int callme(T) { return 42; }" |
| 285 |
"};")); |
| 286 |
auto &PTU = llvm::cantFail(Interp->Parse("auto _t = &B::callme<A*>;")); |
| 287 |
auto PTUDeclRange = PTU.TUPart->decls(); |
| 288 |
EXPECT_EQ(1, std::distance(PTUDeclRange.begin(), PTUDeclRange.end())); |
| 289 |
|
| 290 |
// We cannot execute on the platform. |
| 291 |
if (!HostSupportsJit()) { |
| 292 |
return; |
| 293 |
} |
| 294 |
|
| 295 |
// Lower the PTU |
| 296 |
if (llvm::Error Err = Interp->Execute(PTU)) { |
| 297 |
// We cannot execute on the platform. |
| 298 |
consumeError(std::move(Err)); |
| 299 |
return; |
| 300 |
} |
| 301 |
|
| 302 |
TypeDecl *TD = cast<TypeDecl>(LookupSingleName(*Interp, "A")); |
| 303 |
void *NewA = AllocateObject(TD, *Interp); |
| 304 |
|
| 305 |
// Find back the template specialization |
| 306 |
VarDecl *VD = static_cast<VarDecl *>(*PTUDeclRange.begin()); |
| 307 |
UnaryOperator *UO = llvm::cast<UnaryOperator>(VD->getInit()); |
| 308 |
NamedDecl *TmpltSpec = llvm::cast<DeclRefExpr>(UO->getSubExpr())->getDecl(); |
| 309 |
|
| 310 |
std::string MangledName = MangleName(TmpltSpec); |
| 311 |
typedef int (*TemplateSpecFn)(void *); |
| 312 |
auto fn = (TemplateSpecFn)cantFail(Interp->getSymbolAddress(MangledName)); |
| 313 |
EXPECT_EQ(42, fn(NewA)); |
| 314 |
free(NewA); |
| 315 |
} |
| 316 |
|
| 317 |
} // end anonymous namespace |