| 1 |
//===------ Interpreter.cpp - Incremental Compilation and Execution -------===// |
| 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 |
// This file implements the component which performs incremental code |
| 10 |
// compilation and execution. |
| 11 |
// |
| 12 |
//===----------------------------------------------------------------------===// |
| 13 |
|
| 14 |
#include "DeviceOffload.h" |
| 15 |
#include "IncrementalAction.h" |
| 16 |
#include "IncrementalParser.h" |
| 17 |
#include "InterpreterUtils.h" |
| 18 |
|
| 19 |
#include "clang/AST/ASTConsumer.h" |
| 20 |
#include "clang/AST/ASTContext.h" |
| 21 |
#include "clang/AST/Mangle.h" |
| 22 |
#include "clang/AST/TypeVisitor.h" |
| 23 |
#include "clang/Basic/DiagnosticSema.h" |
| 24 |
#include "clang/Basic/TargetInfo.h" |
| 25 |
#include "clang/CodeGen/CodeGenAction.h" |
| 26 |
#include "clang/CodeGen/ObjectFilePCHContainerWriter.h" |
| 27 |
#include "clang/Driver/Compilation.h" |
| 28 |
#include "clang/Driver/Driver.h" |
| 29 |
#include "clang/Driver/Job.h" |
| 30 |
#include "clang/Driver/Tool.h" |
| 31 |
#include "clang/Frontend/CompilerInstance.h" |
| 32 |
#include "clang/Frontend/FrontendAction.h" |
| 33 |
#include "clang/Frontend/MultiplexConsumer.h" |
| 34 |
#include "clang/Frontend/TextDiagnosticBuffer.h" |
| 35 |
#include "clang/FrontendTool/Utils.h" |
| 36 |
#include "clang/Interpreter/IncrementalExecutor.h" |
| 37 |
#include "clang/Interpreter/Interpreter.h" |
| 38 |
#include "clang/Interpreter/Value.h" |
| 39 |
#include "clang/Lex/PreprocessorOptions.h" |
| 40 |
#include "clang/Options/OptionUtils.h" |
| 41 |
#include "clang/Options/Options.h" |
| 42 |
#include "clang/Sema/Lookup.h" |
| 43 |
#include "clang/Serialization/ObjectFilePCHContainerReader.h" |
| 44 |
#include "llvm/ExecutionEngine/JITSymbol.h" |
| 45 |
#include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h" |
| 46 |
#include "llvm/ExecutionEngine/Orc/LLJIT.h" |
| 47 |
#include "llvm/IR/Module.h" |
| 48 |
#include "llvm/Support/Errc.h" |
| 49 |
#include "llvm/Support/ErrorHandling.h" |
| 50 |
#include "llvm/Support/VirtualFileSystem.h" |
| 51 |
#include "llvm/Support/raw_ostream.h" |
| 52 |
#include "llvm/TargetParser/Host.h" |
| 53 |
#include "llvm/Transforms/Utils/Cloning.h" // for CloneModule |
| 54 |
|
| 55 |
#define DEBUG_TYPE "clang-repl" |
| 56 |
|
| 57 |
using namespace clang; |
| 58 |
// FIXME: Figure out how to unify with namespace init_convenience from |
| 59 |
// tools/clang-import-test/clang-import-test.cpp |
| 60 |
namespace { |
| 61 |
/// Retrieves the clang CC1 specific flags out of the compilation's jobs. |
| 62 |
/// \returns NULL on error. |
| 63 |
static llvm::Expected<const llvm::opt::ArgStringList *> |
| 64 |
GetCC1Arguments(DiagnosticsEngine *Diagnostics, |
| 65 |
driver::Compilation *Compilation) { |
| 66 |
// We expect to get back exactly one Command job, if we didn't something |
| 67 |
// failed. Extract that job from the Compilation. |
| 68 |
const driver::JobList &Jobs = Compilation->getJobs(); |
| 69 |
if (!Jobs.size() || !isa<driver::Command>(*Jobs.begin())) |
| 70 |
return llvm::createStringError(llvm::errc::not_supported, |
| 71 |
"Driver initialization failed. " |
| 72 |
"Unable to create a driver job"); |
| 73 |
|
| 74 |
// The one job we find should be to invoke clang again. |
| 75 |
const driver::Command *Cmd = cast<driver::Command>(&(*Jobs.begin())); |
| 76 |
if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") |
| 77 |
return llvm::createStringError(llvm::errc::not_supported, |
| 78 |
"Driver initialization failed"); |
| 79 |
|
| 80 |
return &Cmd->getArguments(); |
| 81 |
} |
| 82 |
|
| 83 |
static llvm::Expected<std::unique_ptr<CompilerInstance>> |
| 84 |
CreateCI(const llvm::opt::ArgStringList &Argv) { |
| 85 |
std::unique_ptr<CompilerInstance> Clang(new CompilerInstance()); |
| 86 |
|
| 87 |
// Register the support for object-file-wrapped Clang modules. |
| 88 |
// FIXME: Clang should register these container operations automatically. |
| 89 |
auto PCHOps = Clang->getPCHContainerOperations(); |
| 90 |
PCHOps->registerWriter(std::make_unique<ObjectFilePCHContainerWriter>()); |
| 91 |
PCHOps->registerReader(std::make_unique<ObjectFilePCHContainerReader>()); |
| 92 |
|
| 93 |
// Buffer diagnostics from argument parsing so that we can output them using |
| 94 |
// a well formed diagnostic object. |
| 95 |
DiagnosticOptions DiagOpts; |
| 96 |
TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer; |
| 97 |
DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, DiagsBuffer); |
| 98 |
bool Success = CompilerInvocation::CreateFromArgs( |
| 99 |
Clang->getInvocation(), llvm::ArrayRef(Argv.begin(), Argv.size()), Diags); |
| 100 |
|
| 101 |
// Infer the builtin include path if unspecified. |
| 102 |
if (Clang->getHeaderSearchOpts().UseBuiltinIncludes && |
| 103 |
Clang->getHeaderSearchOpts().ResourceDir.empty()) |
| 104 |
Clang->getHeaderSearchOpts().ResourceDir = |
| 105 |
GetResourcesPath(Argv[0], nullptr); |
| 106 |
|
| 107 |
Clang->createVirtualFileSystem(); |
| 108 |
|
| 109 |
// Create the actual diagnostics engine. |
| 110 |
Clang->createDiagnostics(); |
| 111 |
|
| 112 |
DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics()); |
| 113 |
if (!Success) |
| 114 |
return llvm::createStringError(llvm::errc::not_supported, |
| 115 |
"Initialization failed. " |
| 116 |
"Unable to flush diagnostics"); |
| 117 |
|
| 118 |
// FIXME: Merge with CompilerInstance::ExecuteAction. |
| 119 |
llvm::MemoryBuffer *MB = llvm::MemoryBuffer::getMemBuffer("").release(); |
| 120 |
Clang->getPreprocessorOpts().addRemappedFile("<<< inputs >>>", MB); |
| 121 |
|
| 122 |
Clang->setTarget(TargetInfo::CreateTargetInfo( |
| 123 |
Clang->getDiagnostics(), Clang->getInvocation().getTargetOpts())); |
| 124 |
if (!Clang->hasTarget()) |
| 125 |
return llvm::createStringError(llvm::errc::not_supported, |
| 126 |
"Initialization failed. " |
| 127 |
"Target is missing"); |
| 128 |
|
| 129 |
Clang->getTarget().adjust(Clang->getDiagnostics(), Clang->getLangOpts(), |
| 130 |
Clang->getAuxTarget()); |
| 131 |
|
| 132 |
// Don't clear the AST before backend codegen since we do codegen multiple |
| 133 |
// times, reusing the same AST. |
| 134 |
Clang->getCodeGenOpts().ClearASTBeforeBackend = false; |
| 135 |
|
| 136 |
Clang->getFrontendOpts().DisableFree = false; |
| 137 |
Clang->getCodeGenOpts().DisableFree = false; |
| 138 |
return std::move(Clang); |
| 139 |
} |
| 140 |
|
| 141 |
} // anonymous namespace |
| 142 |
|
| 143 |
namespace clang { |
| 144 |
|
| 145 |
llvm::Expected<std::unique_ptr<CompilerInstance>> |
| 146 |
IncrementalCompilerBuilder::create(std::string TT, |
| 147 |
std::vector<const char *> &ClangArgv) { |
| 148 |
|
| 149 |
// If we don't know ClangArgv0 or the address of main() at this point, try |
| 150 |
// to guess it anyway (it's possible on some platforms). |
| 151 |
std::string MainExecutableName = |
| 152 |
llvm::sys::fs::getMainExecutable(nullptr, nullptr); |
| 153 |
|
| 154 |
ClangArgv.insert(ClangArgv.begin(), MainExecutableName.c_str()); |
| 155 |
|
| 156 |
// Prepending -c to force the driver to do something if no action was |
| 157 |
// specified. By prepending we allow users to override the default |
| 158 |
// action and use other actions in incremental mode. |
| 159 |
// FIXME: Print proper driver diagnostics if the driver flags are wrong. |
| 160 |
// We do C++ by default; append right after argv[0] if no "-x" given |
| 161 |
ClangArgv.insert(ClangArgv.end(), "-Xclang"); |
| 162 |
ClangArgv.insert(ClangArgv.end(), "-fincremental-extensions"); |
| 163 |
ClangArgv.insert(ClangArgv.end(), "-c"); |
| 164 |
|
| 165 |
// Put a dummy C++ file on to ensure there's at least one compile job for the |
| 166 |
// driver to construct. |
| 167 |
ClangArgv.push_back("<<< inputs >>>"); |
| 168 |
|
| 169 |
// Buffer diagnostics from argument parsing so that we can output them using a |
| 170 |
// well formed diagnostic object. |
| 171 |
std::unique_ptr<DiagnosticOptions> DiagOpts = |
| 172 |
CreateAndPopulateDiagOpts(ClangArgv); |
| 173 |
TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer; |
| 174 |
DiagnosticsEngine Diags(DiagnosticIDs::create(), *DiagOpts, DiagsBuffer); |
| 175 |
|
| 176 |
driver::Driver Driver(/*MainBinaryName=*/ClangArgv[0], TT, Diags); |
| 177 |
Driver.setCheckInputsExist(false); // the input comes from mem buffers |
| 178 |
llvm::ArrayRef<const char *> RF = llvm::ArrayRef(ClangArgv); |
| 179 |
std::unique_ptr<driver::Compilation> Compilation(Driver.BuildCompilation(RF)); |
| 180 |
|
| 181 |
if (CompilationCB) |
| 182 |
if (auto Err = (*CompilationCB)(*Compilation.get())) |
| 183 |
return std::move(Err); |
| 184 |
|
| 185 |
if (Compilation->getArgs().hasArg(options::OPT_v)) |
| 186 |
Compilation->getJobs().Print(llvm::errs(), "\n", /*Quote=*/false); |
| 187 |
|
| 188 |
auto ErrOrCC1Args = GetCC1Arguments(&Diags, Compilation.get()); |
| 189 |
if (auto Err = ErrOrCC1Args.takeError()) |
| 190 |
return std::move(Err); |
| 191 |
|
| 192 |
return CreateCI(**ErrOrCC1Args); |
| 193 |
} |
| 194 |
|
| 195 |
llvm::Expected<std::unique_ptr<CompilerInstance>> |
| 196 |
IncrementalCompilerBuilder::CreateCpp() { |
| 197 |
std::vector<const char *> Argv; |
| 198 |
Argv.reserve(5 + 1 + UserArgs.size()); |
| 199 |
Argv.push_back("-xc++"); |
| 200 |
#ifdef __EMSCRIPTEN__ |
| 201 |
Argv.push_back("-target"); |
| 202 |
Argv.push_back("wasm32-unknown-emscripten"); |
| 203 |
Argv.push_back("-fvisibility=default"); |
| 204 |
#endif |
| 205 |
llvm::append_range(Argv, UserArgs); |
| 206 |
|
| 207 |
std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple(); |
| 208 |
return IncrementalCompilerBuilder::create(TT, Argv); |
| 209 |
} |
| 210 |
|
| 211 |
llvm::Expected<std::unique_ptr<CompilerInstance>> |
| 212 |
IncrementalCompilerBuilder::createCuda(bool device) { |
| 213 |
std::vector<const char *> Argv; |
| 214 |
Argv.reserve(5 + 4 + UserArgs.size()); |
| 215 |
|
| 216 |
Argv.push_back("-xcuda"); |
| 217 |
if (device) |
| 218 |
Argv.push_back("--cuda-device-only"); |
| 219 |
else |
| 220 |
Argv.push_back("--cuda-host-only"); |
| 221 |
|
| 222 |
std::string SDKPathArg = "--cuda-path="; |
| 223 |
if (!CudaSDKPath.empty()) { |
| 224 |
SDKPathArg += CudaSDKPath; |
| 225 |
Argv.push_back(SDKPathArg.c_str()); |
| 226 |
} |
| 227 |
|
| 228 |
std::string ArchArg = "--offload-arch="; |
| 229 |
if (!OffloadArch.empty()) { |
| 230 |
ArchArg += OffloadArch; |
| 231 |
Argv.push_back(ArchArg.c_str()); |
| 232 |
} |
| 233 |
|
| 234 |
llvm::append_range(Argv, UserArgs); |
| 235 |
|
| 236 |
std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple(); |
| 237 |
return IncrementalCompilerBuilder::create(TT, Argv); |
| 238 |
} |
| 239 |
|
| 240 |
llvm::Expected<std::unique_ptr<CompilerInstance>> |
| 241 |
IncrementalCompilerBuilder::CreateCudaDevice() { |
| 242 |
return IncrementalCompilerBuilder::createCuda(true); |
| 243 |
} |
| 244 |
|
| 245 |
llvm::Expected<std::unique_ptr<CompilerInstance>> |
| 246 |
IncrementalCompilerBuilder::CreateCudaHost() { |
| 247 |
return IncrementalCompilerBuilder::createCuda(false); |
| 248 |
} |
| 249 |
|
| 250 |
Interpreter::Interpreter(std::unique_ptr<CompilerInstance> Instance, |
| 251 |
llvm::Error &ErrOut, |
| 252 |
std::unique_ptr<IncrementalExecutorBuilder> IEB, |
| 253 |
std::unique_ptr<clang::ASTConsumer> Consumer) |
| 254 |
: IncrExecutorBuilder(std::move(IEB)) { |
| 255 |
CI = std::move(Instance); |
| 256 |
llvm::ErrorAsOutParameter EAO(&ErrOut); |
| 257 |
auto LLVMCtx = std::make_unique<llvm::LLVMContext>(); |
| 258 |
TSCtx = std::make_unique<llvm::orc::ThreadSafeContext>(std::move(LLVMCtx)); |
| 259 |
|
| 260 |
Act = TSCtx->withContextDo([&](llvm::LLVMContext *Ctx) { |
| 261 |
return std::make_unique<IncrementalAction>(*CI, *Ctx, ErrOut, *this, |
| 262 |
std::move(Consumer)); |
| 263 |
}); |
| 264 |
|
| 265 |
if (ErrOut) |
| 266 |
return; |
| 267 |
CI->ExecuteAction(*Act); |
| 268 |
|
| 269 |
IncrParser = |
| 270 |
std::make_unique<IncrementalParser>(*CI, Act.get(), ErrOut, PTUs); |
| 271 |
|
| 272 |
if (ErrOut) |
| 273 |
return; |
| 274 |
|
| 275 |
if (Act->getCodeGen()) { |
| 276 |
Act->CacheCodeGenModule(); |
| 277 |
// The initial PTU is filled by `-include`/`-include-pch` or by CUDA |
| 278 |
// includes automatically. |
| 279 |
if (!CI->getPreprocessorOpts().Includes.empty() || |
| 280 |
!CI->getPreprocessorOpts().ImplicitPCHInclude.empty()) { |
| 281 |
// We can't really directly pass the CachedInCodeGenModule to the Jit |
| 282 |
// because it will steal it, causing dangling references as explained in |
| 283 |
// Interpreter::Execute |
| 284 |
auto M = llvm::CloneModule(*Act->getCachedCodeGenModule()); |
| 285 |
ASTContext &C = CI->getASTContext(); |
| 286 |
IncrParser->RegisterPTU(C.getTranslationUnitDecl(), std::move(M)); |
| 287 |
} |
| 288 |
if (llvm::Error Err = CreateExecutor()) { |
| 289 |
ErrOut = joinErrors(std::move(ErrOut), std::move(Err)); |
| 290 |
return; |
| 291 |
} |
| 292 |
} |
| 293 |
|
| 294 |
// Not all frontends support code-generation, e.g. ast-dump actions don't |
| 295 |
if (Act->getCodeGen()) { |
| 296 |
// Process the PTUs that came from initialization. For example -include will |
| 297 |
// give us a header that's processed at initialization of the preprocessor. |
| 298 |
for (PartialTranslationUnit &PTU : PTUs) |
| 299 |
if (llvm::Error Err = Execute(PTU)) { |
| 300 |
ErrOut = joinErrors(std::move(ErrOut), std::move(Err)); |
| 301 |
return; |
| 302 |
} |
| 303 |
} |
| 304 |
} |
| 305 |
|
| 306 |
Interpreter::~Interpreter() { |
| 307 |
IncrParser.reset(); |
| 308 |
Act->FinalizeAction(); |
| 309 |
if (DeviceParser) |
| 310 |
DeviceParser.reset(); |
| 311 |
if (DeviceAct) |
| 312 |
DeviceAct->FinalizeAction(); |
| 313 |
if (IncrExecutor) { |
| 314 |
if (llvm::Error Err = IncrExecutor->cleanUp()) |
| 315 |
llvm::report_fatal_error( |
| 316 |
llvm::Twine("Failed to clean up IncrementalExecutor: ") + |
| 317 |
toString(std::move(Err))); |
| 318 |
} |
| 319 |
} |
| 320 |
|
| 321 |
// These better to put in a runtime header but we can't. This is because we |
| 322 |
// can't find the precise resource directory in unittests so we have to hard |
| 323 |
// code them. |
| 324 |
const char *const Runtimes = R"( |
| 325 |
#define __CLANG_REPL__ 1 |
| 326 |
#ifdef __cplusplus |
| 327 |
#define EXTERN_C extern "C" |
| 328 |
struct __clang_Interpreter_NewTag{} __ci_newtag; |
| 329 |
void* operator new(__SIZE_TYPE__, void* __p, __clang_Interpreter_NewTag) noexcept; |
| 330 |
template <class T, class = T (*)() /*disable for arrays*/> |
| 331 |
void __clang_Interpreter_SetValueCopyArr(const T* Src, void* Placement, unsigned long Size) { |
| 332 |
for (unsigned long Idx = 0; Idx < Size; ++Idx) |
| 333 |
new ((void*)(((T*)Placement) + Idx), __ci_newtag) T(Src[Idx]); |
| 334 |
} |
| 335 |
template <class T, unsigned long N> |
| 336 |
void __clang_Interpreter_SetValueCopyArr(const T (*Src)[N], void* Placement, unsigned long Size) { |
| 337 |
__clang_Interpreter_SetValueCopyArr(Src[0], Placement, Size); |
| 338 |
} |
| 339 |
#else |
| 340 |
#if __STDC_VERSION__ < 199901L |
| 341 |
#define CI_RESTRICT |
| 342 |
#define CI_INLINE |
| 343 |
#else |
| 344 |
#define CI_RESTRICT restrict |
| 345 |
#define CI_INLINE inline |
| 346 |
#endif |
| 347 |
#define EXTERN_C extern |
| 348 |
EXTERN_C void *memcpy(void *CI_RESTRICT dst, const void *CI_RESTRICT src, __SIZE_TYPE__ n); |
| 349 |
EXTERN_C CI_INLINE void __clang_Interpreter_SetValueCopyArr(const void* Src, void* Placement, unsigned long Size) { |
| 350 |
memcpy(Placement, Src, Size); |
| 351 |
} |
| 352 |
#endif // __cplusplus |
| 353 |
EXTERN_C void *__clang_Interpreter_SetValueWithAlloc(void*, void*, void*); |
| 354 |
EXTERN_C void __clang_Interpreter_SetValueNoAlloc(void *This, void *OutVal, void *OpaqueType, ...); |
| 355 |
)"; |
| 356 |
|
| 357 |
llvm::Expected<std::unique_ptr<Interpreter>> Interpreter::create( |
| 358 |
std::unique_ptr<CompilerInstance> CI, |
| 359 |
std::unique_ptr<IncrementalExecutorBuilder> IEB /*=nullptr*/) { |
| 360 |
llvm::Error Err = llvm::Error::success(); |
| 361 |
|
| 362 |
auto Interp = std::unique_ptr<Interpreter>(new Interpreter( |
| 363 |
std::move(CI), Err, std::move(IEB), /*Consumer=*/nullptr)); |
| 364 |
if (auto E = std::move(Err)) |
| 365 |
return std::move(E); |
| 366 |
|
| 367 |
// Add runtime code and set a marker to hide it from user code. Undo will not |
| 368 |
// go through that. |
| 369 |
if (auto E = Interp->ParseAndExecute(Runtimes)) |
| 370 |
return std::move(E); |
| 371 |
|
| 372 |
Interp->markUserCodeStart(); |
| 373 |
|
| 374 |
return std::move(Interp); |
| 375 |
} |
| 376 |
|
| 377 |
llvm::Expected<std::unique_ptr<Interpreter>> |
| 378 |
Interpreter::createWithCUDA(std::unique_ptr<CompilerInstance> CI, |
| 379 |
std::unique_ptr<CompilerInstance> DCI) { |
| 380 |
// avoid writing fat binary to disk using an in-memory virtual file system |
| 381 |
llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> IMVFS = |
| 382 |
std::make_unique<llvm::vfs::InMemoryFileSystem>(); |
| 383 |
llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayVFS = |
| 384 |
std::make_unique<llvm::vfs::OverlayFileSystem>( |
| 385 |
llvm::vfs::getRealFileSystem()); |
| 386 |
OverlayVFS->pushOverlay(IMVFS); |
| 387 |
CI->createVirtualFileSystem(OverlayVFS); |
| 388 |
CI->createFileManager(); |
| 389 |
|
| 390 |
llvm::Expected<std::unique_ptr<Interpreter>> InterpOrErr = |
| 391 |
Interpreter::create(std::move(CI)); |
| 392 |
if (!InterpOrErr) |
| 393 |
return InterpOrErr; |
| 394 |
|
| 395 |
std::unique_ptr<Interpreter> Interp = std::move(*InterpOrErr); |
| 396 |
|
| 397 |
llvm::Error Err = llvm::Error::success(); |
| 398 |
|
| 399 |
auto DeviceAct = Interp->TSCtx->withContextDo([&](llvm::LLVMContext *Ctx) { |
| 400 |
return std::make_unique<IncrementalAction>(*DCI, *Ctx, Err, *Interp); |
| 401 |
}); |
| 402 |
|
| 403 |
if (Err) |
| 404 |
return std::move(Err); |
| 405 |
|
| 406 |
Interp->DeviceAct = std::move(DeviceAct); |
| 407 |
|
| 408 |
DCI->ExecuteAction(*Interp->DeviceAct); |
| 409 |
|
| 410 |
Interp->DeviceCI = std::move(DCI); |
| 411 |
|
| 412 |
auto DeviceParser = std::make_unique<IncrementalCUDADeviceParser>( |
| 413 |
*Interp->DeviceCI, *Interp->getCompilerInstance(), |
| 414 |
Interp->DeviceAct.get(), IMVFS, Err, Interp->PTUs); |
| 415 |
|
| 416 |
if (Err) |
| 417 |
return std::move(Err); |
| 418 |
|
| 419 |
Interp->DeviceParser = std::move(DeviceParser); |
| 420 |
return std::move(Interp); |
| 421 |
} |
| 422 |
|
| 423 |
CompilerInstance *Interpreter::getCompilerInstance() { return CI.get(); } |
| 424 |
const CompilerInstance *Interpreter::getCompilerInstance() const { |
| 425 |
return const_cast<Interpreter *>(this)->getCompilerInstance(); |
| 426 |
} |
| 427 |
|
| 428 |
llvm::Expected<IncrementalExecutor &> Interpreter::getExecutionEngine() { |
| 429 |
if (!IncrExecutor) { |
| 430 |
if (auto Err = CreateExecutor()) |
| 431 |
return std::move(Err); |
| 432 |
} |
| 433 |
|
| 434 |
return *IncrExecutor.get(); |
| 435 |
} |
| 436 |
|
| 437 |
ASTContext &Interpreter::getASTContext() { |
| 438 |
return getCompilerInstance()->getASTContext(); |
| 439 |
} |
| 440 |
|
| 441 |
const ASTContext &Interpreter::getASTContext() const { |
| 442 |
return getCompilerInstance()->getASTContext(); |
| 443 |
} |
| 444 |
|
| 445 |
void Interpreter::markUserCodeStart() { |
| 446 |
assert(!InitPTUSize && "We only do this once"); |
| 447 |
InitPTUSize = PTUs.size(); |
| 448 |
} |
| 449 |
|
| 450 |
size_t Interpreter::getEffectivePTUSize() const { |
| 451 |
assert(PTUs.size() >= InitPTUSize && "empty PTU list?"); |
| 452 |
return PTUs.size() - InitPTUSize; |
| 453 |
} |
| 454 |
|
| 455 |
llvm::Expected<PartialTranslationUnit &> |
| 456 |
Interpreter::Parse(llvm::StringRef Code) { |
| 457 |
// If we have a device parser, parse it first. The generated code will be |
| 458 |
// included in the host compilation |
| 459 |
if (DeviceParser) { |
| 460 |
llvm::Expected<TranslationUnitDecl *> DeviceTU = DeviceParser->Parse(Code); |
| 461 |
if (auto E = DeviceTU.takeError()) |
| 462 |
return std::move(E); |
| 463 |
|
| 464 |
DeviceParser->RegisterPTU(*DeviceTU); |
| 465 |
|
| 466 |
llvm::Expected<llvm::StringRef> PTX = DeviceParser->GeneratePTX(); |
| 467 |
if (!PTX) |
| 468 |
return PTX.takeError(); |
| 469 |
|
| 470 |
llvm::Error Err = DeviceParser->GenerateFatbinary(); |
| 471 |
if (Err) |
| 472 |
return std::move(Err); |
| 473 |
} |
| 474 |
|
| 475 |
// Tell the interpreter sliently ignore unused expressions since value |
| 476 |
// printing could cause it. |
| 477 |
getCompilerInstance()->getDiagnostics().setSeverity( |
| 478 |
clang::diag::warn_unused_expr, diag::Severity::Ignored, SourceLocation()); |
| 479 |
|
| 480 |
llvm::Expected<TranslationUnitDecl *> TuOrErr = IncrParser->Parse(Code); |
| 481 |
if (!TuOrErr) |
| 482 |
return TuOrErr.takeError(); |
| 483 |
|
| 484 |
PartialTranslationUnit &LastPTU = IncrParser->RegisterPTU(*TuOrErr); |
| 485 |
|
| 486 |
return LastPTU; |
| 487 |
} |
| 488 |
|
| 489 |
llvm::Error Interpreter::CreateExecutor() { |
| 490 |
if (IncrExecutor) |
| 491 |
return llvm::make_error<llvm::StringError>("Operation failed. " |
| 492 |
"Execution engine exists", |
| 493 |
std::error_code()); |
| 494 |
if (!Act->getCodeGen()) |
| 495 |
return llvm::make_error<llvm::StringError>("Operation failed. " |
| 496 |
"No code generator available", |
| 497 |
std::error_code()); |
| 498 |
|
| 499 |
if (!IncrExecutorBuilder) |
| 500 |
IncrExecutorBuilder = std::make_unique<IncrementalExecutorBuilder>(); |
| 501 |
|
| 502 |
auto ExecutorOrErr = IncrExecutorBuilder->create(*TSCtx, CI->getTarget()); |
| 503 |
if (ExecutorOrErr) |
| 504 |
IncrExecutor = std::move(*ExecutorOrErr); |
| 505 |
|
| 506 |
return ExecutorOrErr.takeError(); |
| 507 |
} |
| 508 |
|
| 509 |
llvm::Error Interpreter::Execute(PartialTranslationUnit &T) { |
| 510 |
assert(T.TheModule); |
| 511 |
LLVM_DEBUG( |
| 512 |
llvm::dbgs() << "execute-ptu " |
| 513 |
<< (llvm::is_contained(PTUs, T) |
| 514 |
? std::distance(PTUs.begin(), llvm::find(PTUs, T)) |
| 515 |
: -1) |
| 516 |
<< ": [TU=" << T.TUPart << ", M=" << T.TheModule.get() |
| 517 |
<< " (" << T.TheModule->getName() << ")]\n"); |
| 518 |
if (!IncrExecutor) { |
| 519 |
auto Err = CreateExecutor(); |
| 520 |
if (Err) |
| 521 |
return Err; |
| 522 |
} |
| 523 |
// FIXME: Add a callback to retain the llvm::Module once the JIT is done. |
| 524 |
if (auto Err = IncrExecutor->addModule(T)) |
| 525 |
return Err; |
| 526 |
|
| 527 |
if (auto Err = IncrExecutor->runCtors()) |
| 528 |
return Err; |
| 529 |
|
| 530 |
return llvm::Error::success(); |
| 531 |
} |
| 532 |
|
| 533 |
llvm::Error Interpreter::ParseAndExecute(llvm::StringRef Code, Value *V) { |
| 534 |
|
| 535 |
auto PTU = Parse(Code); |
| 536 |
if (!PTU) |
| 537 |
return PTU.takeError(); |
| 538 |
if (PTU->TheModule) |
| 539 |
if (llvm::Error Err = Execute(*PTU)) |
| 540 |
return Err; |
| 541 |
|
| 542 |
if (LastValue.isValid()) { |
| 543 |
if (!V) { |
| 544 |
LastValue.dump(); |
| 545 |
LastValue.clear(); |
| 546 |
} else |
| 547 |
*V = std::move(LastValue); |
| 548 |
} |
| 549 |
return llvm::Error::success(); |
| 550 |
} |
| 551 |
|
| 552 |
llvm::Expected<llvm::orc::ExecutorAddr> |
| 553 |
Interpreter::getSymbolAddress(GlobalDecl GD) const { |
| 554 |
if (!IncrExecutor) |
| 555 |
return llvm::make_error<llvm::StringError>("Operation failed. " |
| 556 |
"No execution engine", |
| 557 |
std::error_code()); |
| 558 |
llvm::StringRef MangledName = Act->getCodeGen()->GetMangledName(GD); |
| 559 |
return getSymbolAddress(MangledName); |
| 560 |
} |
| 561 |
|
| 562 |
llvm::Expected<llvm::orc::ExecutorAddr> |
| 563 |
Interpreter::getSymbolAddress(llvm::StringRef IRName) const { |
| 564 |
if (!IncrExecutor) |
| 565 |
return llvm::make_error<llvm::StringError>("Operation failed. " |
| 566 |
"No execution engine", |
| 567 |
std::error_code()); |
| 568 |
|
| 569 |
return IncrExecutor->getSymbolAddress(IRName, IncrementalExecutor::IRName); |
| 570 |
} |
| 571 |
|
| 572 |
llvm::Expected<llvm::orc::ExecutorAddr> |
| 573 |
Interpreter::getSymbolAddressFromLinkerName(llvm::StringRef Name) const { |
| 574 |
if (!IncrExecutor) |
| 575 |
return llvm::make_error<llvm::StringError>("Operation failed. " |
| 576 |
"No execution engine", |
| 577 |
std::error_code()); |
| 578 |
|
| 579 |
return IncrExecutor->getSymbolAddress(Name, IncrementalExecutor::LinkerName); |
| 580 |
} |
| 581 |
|
| 582 |
llvm::Error Interpreter::Undo(unsigned N) { |
| 583 |
|
| 584 |
if (getEffectivePTUSize() == 0) { |
| 585 |
return llvm::make_error<llvm::StringError>("Operation failed. " |
| 586 |
"No input left to undo", |
| 587 |
std::error_code()); |
| 588 |
} else if (N > getEffectivePTUSize()) { |
| 589 |
return llvm::make_error<llvm::StringError>( |
| 590 |
llvm::formatv( |
| 591 |
"Operation failed. Wanted to undo {0} inputs, only have {1}.", N, |
| 592 |
getEffectivePTUSize()), |
| 593 |
std::error_code()); |
| 594 |
} |
| 595 |
|
| 596 |
for (unsigned I = 0; I < N; I++) { |
| 597 |
if (IncrExecutor) { |
| 598 |
if (llvm::Error Err = IncrExecutor->removeModule(PTUs.back())) |
| 599 |
return Err; |
| 600 |
} |
| 601 |
|
| 602 |
IncrParser->CleanUpPTU(PTUs.back().TUPart); |
| 603 |
PTUs.pop_back(); |
| 604 |
} |
| 605 |
return llvm::Error::success(); |
| 606 |
} |
| 607 |
|
| 608 |
llvm::Error Interpreter::LoadDynamicLibrary(const char *name) { |
| 609 |
auto EEOrErr = getExecutionEngine(); |
| 610 |
if (!EEOrErr) |
| 611 |
return EEOrErr.takeError(); |
| 612 |
|
| 613 |
return EEOrErr->LoadDynamicLibrary(name); |
| 614 |
} |
| 615 |
} // end namespace clang |