clang 24.0.0git
Interpreter.cpp
Go to the documentation of this file.
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
21#include "clang/AST/Mangle.h"
30#include "clang/Driver/Driver.h"
31#include "clang/Driver/Job.h"
32#include "clang/Driver/Tool.h"
42#include "clang/Lex/Pragma.h"
47#include "clang/Sema/Lookup.h"
51#include "llvm/ADT/StringExtras.h"
52#include "llvm/ADT/StringSwitch.h"
53#include "llvm/ExecutionEngine/JITSymbol.h"
54#include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h"
55#include "llvm/ExecutionEngine/Orc/LLJIT.h"
56#include "llvm/IR/Module.h"
57#include "llvm/Support/Errc.h"
58#include "llvm/Support/ErrorHandling.h"
59#include "llvm/Support/Process.h"
60#include "llvm/Support/VirtualFileSystem.h"
61#include "llvm/Support/raw_ostream.h"
62#include "llvm/TargetParser/Host.h"
63#include "llvm/TargetParser/Triple.h"
64#include "llvm/Transforms/Utils/Cloning.h" // for CloneModule
65
66#define DEBUG_TYPE "clang-repl"
67
68using namespace clang;
69// FIXME: Figure out how to unify with namespace init_convenience from
70// tools/clang-import-test/clang-import-test.cpp
71namespace {
72/// Retrieves the clang CC1 specific flags out of the compilation's jobs.
73/// \returns NULL on error.
75GetCC1Arguments(DiagnosticsEngine *Diagnostics,
76 driver::Compilation *Compilation) {
77 // We expect to get back exactly one Command job, if we didn't something
78 // failed. Extract that job from the Compilation.
79 const driver::JobList &Jobs = Compilation->getJobs();
80 if (!Jobs.size())
81 return llvm::createStringError(llvm::errc::not_supported,
82 "Driver initialization failed. "
83 "Unable to create a driver job");
84
85 // The driver creates one device compile job per architecture (for example if
86 // --offload-arch=native finds several GPUs). Only one can be used.
87 unsigned NumDeviceJobs = llvm::count_if(Jobs, [](const driver::Command &C) {
88 return llvm::StringRef(C.getCreator().getName()) == "clang" &&
89 llvm::is_contained(C.getArguments(),
90 llvm::StringRef("-fcuda-is-device"));
91 });
92 if (NumDeviceJobs > 1)
93 return llvm::createStringError(
94 llvm::errc::not_supported,
95 "Multiple device architectures are not supported. Pass a single "
96 "--offload-arch");
97
98 // The one job we find should be to invoke clang again.
99 const driver::Command *Cmd = &*Jobs.begin();
100 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang")
101 return llvm::createStringError(llvm::errc::not_supported,
102 "Driver initialization failed");
103
104 return &Cmd->getArguments();
105}
106
107// ASTReaderListener that captures the PIC level stored in a serialized AST
108// file (PCH or PCM) so the interpreter can compare it against its own.
109class PICLevelReader : public ASTReaderListener {
110 unsigned &PICLevel;
111
112public:
113 PICLevelReader(unsigned &PICLevel) : PICLevel(PICLevel) {}
114
115 bool ReadLanguageOptions(const LangOptions &LangOpts,
116 StringRef ModuleFilename, bool Complain,
117 bool AllowCompatibleDifferences) override {
118 PICLevel = LangOpts.PICLevel;
119 return false;
120 }
121};
122
123// clang-repl always compiles position-independent code (it injects -fPIC), so a
124// PCH/PCM that was built with a different PIC level is incompatible: mixing the
125// two leads to relocations that may be out of range once the JIT maps code more
126// than 2GB away. PICLevel is a "compatible" language option, so the ASTReader
127// would otherwise accept the mismatch silently. Reject it up front.
128//
129// The file is probed with its own FileManager and ModuleCache (sharing only the
130// VFS) so this read leaves the CompilerInstance's state untouched for the real
131// load performed later by ExecuteAction().
132static llvm::Error checkASTFilePICLevel(CompilerInstance &Clang,
133 StringRef Filename) {
136 std::shared_ptr<ModuleCache> ModCache = createCrossProcessModuleCache();
137 unsigned ASTPICLevel = 0;
138 PICLevelReader Reader(ASTPICLevel);
140 Filename, *FileMgr, *ModCache, Clang.getPCHContainerReader(),
141 /*FindModuleFileExtensions=*/false, Reader,
142 /*ValidateDiagnosticOptions=*/false) &&
143 ASTPICLevel != Clang.getLangOpts().PICLevel)
144 return llvm::createStringError(
145 llvm::errc::not_supported,
146 "AST file '%s' was built with PIC level %u, which is incompatible "
147 "with clang-repl's PIC level %u",
148 Filename.str().c_str(), ASTPICLevel, Clang.getLangOpts().PICLevel);
149 return llvm::Error::success();
150}
151
153CreateCI(const llvm::opt::ArgStringList &Argv) {
154 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
155
156 // Register the support for object-file-wrapped Clang modules.
157 // FIXME: Clang should register these container operations automatically.
158 auto PCHOps = Clang->getPCHContainerOperations();
159 PCHOps->registerWriter(std::make_unique<ObjectFilePCHContainerWriter>());
160 PCHOps->registerReader(std::make_unique<ObjectFilePCHContainerReader>());
161
162 // Buffer diagnostics from argument parsing so that we can output them using
163 // a well formed diagnostic object.
164 DiagnosticOptions DiagOpts;
166 DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, DiagsBuffer);
168 Clang->getInvocation(), llvm::ArrayRef(Argv.begin(), Argv.size()), Diags);
169
170 // Infer the builtin include path if unspecified.
171 if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
172 Clang->getHeaderSearchOpts().ResourceDir.empty())
173 Clang->getHeaderSearchOpts().ResourceDir =
174 GetResourcesPath(Argv[0], nullptr);
175
176 Clang->createVirtualFileSystem();
177
178 // Create the actual diagnostics engine.
179 Clang->createDiagnostics();
180
181 DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
182 if (!Success)
183 return llvm::createStringError(llvm::errc::not_supported,
184 "Initialization failed. "
185 "Unable to flush diagnostics");
186
187 // The driver passes "<<< inputs >>>" as a placeholder main file; the real
188 // input arrives later as input_line_N buffers.
189 for (FrontendInputFile &Input : Clang->getFrontendOpts().Inputs)
190 if (Input.isFile() && Input.getFile() == "<<< inputs >>>")
191 Input = FrontendInputFile(llvm::MemoryBufferRef("", "<<< inputs >>>"),
192 Input.getKind());
193
194 if (!Clang->createTarget())
195 return llvm::createStringError(llvm::errc::not_supported,
196 "Initialization failed. "
197 "Target is missing");
198
199 // Don't clear the AST before backend codegen since we do codegen multiple
200 // times, reusing the same AST.
201 Clang->getCodeGenOpts().ClearASTBeforeBackend = false;
202
203 Clang->getFrontendOpts().DisableFree = false;
204 Clang->getCodeGenOpts().DisableFree = false;
205
206 // Reject any precompiled input (PCH or PCM) built with a PIC level that
207 // differs from clang-repl's own, before any Interpreter/FrontendAction is
208 // constructed. See checkASTFilePICLevel for the rationale.
209 StringRef PCHInclude = Clang->getPreprocessorOpts().ImplicitPCHInclude;
210 if (!PCHInclude.empty())
211 if (llvm::Error Err = checkASTFilePICLevel(*Clang, PCHInclude))
212 return std::move(Err);
213
214 // Explicitly loaded modules: -fmodule-file=<path> and
215 // -fmodule-file=<name>=<path>.
216 for (StringRef ModuleFile : Clang->getFrontendOpts().ModuleFiles)
217 if (llvm::Error Err = checkASTFilePICLevel(*Clang, ModuleFile))
218 return std::move(Err);
219 for (const auto &NameAndFile :
220 Clang->getHeaderSearchOpts().PrebuiltModuleFiles)
221 if (llvm::Error Err = checkASTFilePICLevel(*Clang, NameAndFile.second))
222 return std::move(Err);
223
224 return std::move(Clang);
225}
226
227static llvm::Error ExecuteIncrementalAction(CompilerInstance &CI,
228 IncrementalAction &Act) {
229 // Parse -mllvm before the action gives CI's library options to the
230 // LLVMContext.
231 std::string Msg;
232 llvm::raw_string_ostream OS(Msg);
233 if (!CI.parseLLVMArgs(&OS)) {
234 // Without a preprocessor, the SourceManager never adopts the buffers.
236 if (!PPOpts.RetainRemappedFileBuffers)
237 for (auto &RB : PPOpts.RemappedFileBuffers)
238 delete RB.second;
239 PPOpts.clearRemappedFiles();
240 return llvm::createStringError(llvm::StringRef(Msg).rtrim());
241 }
242 if (!CI.ExecuteAction(Act) || CI.getDiagnostics().hasErrorOccurred()) {
243 return llvm::createStringError(llvm::errc::not_supported,
244 "Failed to execute incremental action");
245 }
246 return llvm::Error::success();
247}
248
249// '#pragma clang repl optimize(<opt>)' sets the optimization level and size
250// used to emit modules for input parsed after the pragma. <opt> is an -O flag
251// spelled without the leading dash: O0, O1, O2, O3, Os or Oz.
252struct PragmaReplHandler : public PragmaHandler {
253 Interpreter &Interp;
254
255 PragmaReplHandler(Interpreter &Interp)
256 : PragmaHandler("repl"), Interp(Interp) {}
257
258 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
259 Token &FirstToken) override {
260 Token Tok;
262 if (Tok.isNot(tok::identifier) ||
263 !Tok.getIdentifierInfo()->isStr("optimize")) {
264 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
265 << "clang repl";
266 return;
267 }
268
270 if (Tok.isNot(tok::l_paren)) {
271 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen)
272 << "clang repl optimize";
273 return;
274 }
275
277 std::string Opt = PP.getSpelling(Tok);
278 // The OptimizationLevel and OptimizeSize that each -O flag sets.
279 std::optional<std::pair<unsigned, unsigned>> Level =
280 llvm::StringSwitch<std::optional<std::pair<unsigned, unsigned>>>(Opt)
281 .Case("O0", std::pair(0U, 0U))
282 .Case("O1", std::pair(1U, 0U))
283 .Case("O2", std::pair(2U, 0U))
284 .Case("O3", std::pair(3U, 0U))
285 .Case("Os", std::pair(2U, 1U))
286 .Case("Oz", std::pair(2U, 2U))
287 .Default(std::nullopt);
288 if (!Level) {
289 PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_argument)
290 << Opt << "clang repl optimize" << /*Expected=*/true
291 << "'O0', 'O1', 'O2', 'O3', 'Os' or 'Oz'";
292 return;
293 }
294
296 if (Tok.isNot(tok::r_paren)) {
297 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen)
298 << "clang repl optimize";
299 return;
300 }
301
303 if (Tok.isNot(tok::eod)) {
304 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
305 << "clang repl optimize";
306 return;
307 }
308
309 Interp.setOptLevel(Level->first, Level->second);
310 }
311};
312
313} // anonymous namespace
314
315namespace clang {
316
318IncrementalCompilerBuilder::create(std::string TT,
319 std::vector<const char *> &ClangArgv) {
320
321 // If we don't know ClangArgv0 or the address of main() at this point, try
322 // to guess it anyway (it's possible on some platforms).
323 std::string MainExecutableName =
324 llvm::sys::fs::getMainExecutable(nullptr, nullptr);
325
326 ClangArgv.insert(ClangArgv.begin(), MainExecutableName.c_str());
327
328 // Compile as position-independent code. This prevents the frontend from
329 // marking external symbols (e.g. C++ type-info such as _ZTIPKc used for
330 // exception handling) as dso_local and emitting direct PC-relative
331 // references. JITLink can place the GOT entry near the JIT'd code, keeping
332 // the relocation in range. Without -fPIC, a direct Delta32 relocation to a
333 // host symbol may be out of range when the JIT memory is mapped more than
334 // 2GB away (as on FreeBSD), breaking tests such as
335 // Interpreter/simple-exception.cpp. Insert before user arguments so it can
336 // still be overridden. On Windows (excluding Cygwin/MinGW) an explicit
337 // -fPIC is an unsupported driver option that would drop non-x86_64 targets
338 // to PIC level 0; PIC is already the forced default there where relevant,
339 // so don't inject it.
340 llvm::Triple TargetTriple(TT);
341 if (!TargetTriple.isOSWindows() || TargetTriple.isOSCygMing())
342 ClangArgv.insert(ClangArgv.begin() + 1, "-fPIC");
343
344 // Prepending -c to force the driver to do something if no action was
345 // specified. By prepending we allow users to override the default
346 // action and use other actions in incremental mode.
347 // FIXME: Print proper driver diagnostics if the driver flags are wrong.
348 // We do C++ by default; append right after argv[0] if no "-x" given
349 ClangArgv.insert(ClangArgv.end(), "-Xclang");
350 ClangArgv.insert(ClangArgv.end(), "-fincremental-extensions");
351 ClangArgv.insert(ClangArgv.end(), "-c");
352
353 // Put a dummy C++ file on to ensure there's at least one compile job for the
354 // driver to construct.
355 ClangArgv.push_back("<<< inputs >>>");
356
357 // Buffer diagnostics from argument parsing so that we can output them using a
358 // well formed diagnostic object.
359 std::unique_ptr<DiagnosticOptions> DiagOpts =
360 CreateAndPopulateDiagOpts(ClangArgv);
361 TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
362 DiagnosticsEngine Diags(DiagnosticIDs::create(), *DiagOpts, DiagsBuffer);
363
364 driver::Driver Driver(/*MainBinaryName=*/ClangArgv[0], TT, Diags);
365 Driver.setCheckInputsExist(false); // the input comes from mem buffers
366 llvm::ArrayRef<const char *> RF = llvm::ArrayRef(ClangArgv);
367 std::unique_ptr<driver::Compilation> Compilation(Driver.BuildCompilation(RF));
368
369 if (CompilationCB)
370 if (auto Err = (*CompilationCB)(*Compilation.get()))
371 return std::move(Err);
372
373 if (Compilation->getArgs().hasArg(options::OPT_v))
374 Compilation->getJobs().Print(llvm::errs(), "\n", /*Quote=*/false);
375
376 auto ErrOrCC1Args = GetCC1Arguments(&Diags, Compilation.get());
377 if (auto Err = ErrOrCC1Args.takeError())
378 return std::move(Err);
379
380 return CreateCI(**ErrOrCC1Args);
381}
382
385 std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple();
386
387 std::vector<const char *> Argv;
388 Argv.reserve(5 + 1 + UserArgs.size());
389 Argv.push_back("-xc++");
390#ifdef __EMSCRIPTEN__
391 Argv.push_back("-target");
392 Argv.push_back(TT.c_str());
393 Argv.push_back("-fvisibility=default");
394#endif
395 llvm::append_range(Argv, UserArgs);
396
397 return IncrementalCompilerBuilder::create(TT, Argv);
398}
399
401IncrementalCompilerBuilder::createOffload(bool device, OffloadType Type) {
403 return llvm::make_error<llvm::StringError>(
404 "Detecting the device vendor is not supported yet.",
405 llvm::inconvertibleErrorCode());
406
407 constexpr size_t NumDriverArgs = 6;
408
409 const bool HipEnabled = Type == OffloadType::HIP;
410 std::vector<const char *> Argv;
411 Argv.reserve(NumDriverArgs + UserArgs.size());
412 Argv.push_back(HipEnabled ? "-xhip" : "-xcuda");
413 Argv.push_back(device ? "--cuda-device-only" : "--cuda-host-only");
414
415 std::string SDKPathArg = HipEnabled ? "--rocm-path=" : "--cuda-path=";
416 if (!DeviceSDKPath.empty()) {
417 SDKPathArg += DeviceSDKPath;
418 Argv.push_back(SDKPathArg.c_str());
419 }
420
421 std::string ArchArg = "--offload-arch=";
422 if (!OffloadArch.empty()) {
423 ArchArg += OffloadArch;
424 Argv.push_back(ArchArg.c_str());
425 }
426
427 if (OffloadCUID.empty())
428 OffloadCUID = llvm::utohexstr(llvm::sys::Process::GetRandomNumber(),
429 /*LowerCase=*/true);
430 std::string CUIDArg = "-cuid=" + OffloadCUID;
431 Argv.push_back(CUIDArg.c_str());
432
433 // Unoptimized HIP kernels request hostcall support, which needs PCIe atomics
434 // and fails to dispatch without them. A -O in UserArgs comes later and wins.
435 if (device && HipEnabled)
436 Argv.push_back("-O3");
437
438 llvm::append_range(Argv, UserArgs);
439
440 std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple();
441 return IncrementalCompilerBuilder::create(TT, Argv);
442}
443
446 return IncrementalCompilerBuilder::createOffload(/*device=*/true, Type);
447}
448
451 return IncrementalCompilerBuilder::createOffload(/*device=*/false, Type);
452}
453
454Interpreter::Interpreter(std::unique_ptr<CompilerInstance> Instance,
455 llvm::Error &ErrOut,
456 std::unique_ptr<IncrementalExecutorBuilder> IEB,
457 std::unique_ptr<clang::ASTConsumer> Consumer)
458 : IncrExecutorBuilder(std::move(IEB)) {
459 CI = std::move(Instance);
460 llvm::ErrorAsOutParameter EAO(&ErrOut);
461 auto LLVMCtx = std::make_unique<llvm::LLVMContext>();
462 TSCtx = std::make_unique<llvm::orc::ThreadSafeContext>(std::move(LLVMCtx));
463
464 Act = TSCtx->withContextDo([&](llvm::LLVMContext *Ctx) {
465 return std::make_unique<IncrementalAction>(*CI, *Ctx, ErrOut, *this,
466 std::move(Consumer));
467 });
468
469 if (ErrOut)
470 return;
471
472 if (llvm::Error E = ExecuteIncrementalAction(*CI, *Act)) {
473 ErrOut = joinErrors(std::move(ErrOut), std::move(E));
474 return;
475 }
476
477 IncrParser =
478 std::make_unique<IncrementalParser>(*CI, Act.get(), ErrOut, PTUs);
479
480 if (ErrOut)
481 return;
482
483 CI->getPreprocessor().AddPragmaHandler("clang", new PragmaReplHandler(*this));
484
485 if (Act->getCodeGen()) {
486 Act->CacheCodeGenModule();
487 // The initial PTU is filled by `-include`/`-include-pch` or by CUDA
488 // includes automatically.
489 if (!CI->getPreprocessorOpts().Includes.empty() ||
490 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty()) {
491 // We can't really directly pass the CachedInCodeGenModule to the Jit
492 // because it will steal it, causing dangling references as explained in
493 // Interpreter::Execute
494 auto M = llvm::CloneModule(*Act->getCachedCodeGenModule());
495 ASTContext &C = CI->getASTContext();
496 IncrParser->RegisterPTU(C.getTranslationUnitDecl(), std::move(M));
497 }
498 if (llvm::Error Err = CreateExecutor()) {
499 ErrOut = joinErrors(std::move(ErrOut), std::move(Err));
500 return;
501 }
502 }
503
504 // Not all frontends support code-generation, e.g. ast-dump actions don't
505 if (Act->getCodeGen()) {
506 // Process the PTUs that came from initialization. For example -include will
507 // give us a header that's processed at initialization of the preprocessor.
508 for (PartialTranslationUnit &PTU : PTUs)
509 if (llvm::Error Err = Execute(PTU)) {
510 ErrOut = joinErrors(std::move(ErrOut), std::move(Err));
511 return;
512 }
513 }
514}
515
517 IncrParser.reset();
518 Act->FinalizeAction();
519 if (DeviceParser)
520 DeviceParser.reset();
521 if (DeviceAct)
522 DeviceAct->FinalizeAction();
523 if (IncrExecutor) {
524 if (llvm::Error Err = IncrExecutor->cleanUp())
525 llvm::report_fatal_error(
526 llvm::Twine("Failed to clean up IncrementalExecutor: ") +
527 toString(std::move(Err)));
528 }
529}
530
531// These better to put in a runtime header but we can't. This is because we
532// can't find the precise resource directory in unittests so we have to hard
533// code them.
534const char *const Runtimes = R"(
535 #define __CLANG_REPL__ 1
536#ifdef __cplusplus
537 #define EXTERN_C extern "C"
538 struct __clang_Interpreter_NewTag{} __ci_newtag;
539 void* operator new(__SIZE_TYPE__, void* __p, __clang_Interpreter_NewTag) noexcept;
540 template <class T, class = T (*)() /*disable for arrays*/>
541 void __clang_Interpreter_SetValueCopyArr(const T* Src, void* Placement, unsigned long Size) {
542 for (unsigned long Idx = 0; Idx < Size; ++Idx)
543 new ((void*)(((T*)Placement) + Idx), __ci_newtag) T(Src[Idx]);
544 }
545 template <class T, unsigned long N>
546 void __clang_Interpreter_SetValueCopyArr(const T (*Src)[N], void* Placement, unsigned long Size) {
547 __clang_Interpreter_SetValueCopyArr(Src[0], Placement, Size);
548 }
549#else
550 #if __STDC_VERSION__ < 199901L
551 #define CI_RESTRICT
552 #define CI_INLINE
553 #else
554 #define CI_RESTRICT restrict
555 #define CI_INLINE inline
556 #endif
557 #define EXTERN_C extern
558 EXTERN_C void *memcpy(void *CI_RESTRICT dst, const void *CI_RESTRICT src, __SIZE_TYPE__ n);
559 EXTERN_C CI_INLINE void __clang_Interpreter_SetValueCopyArr(const void* Src, void* Placement, unsigned long Size) {
560 memcpy(Placement, Src, Size);
561 }
562#endif // __cplusplus
563 EXTERN_C void *__clang_Interpreter_SetValueWithAlloc(void*, void*, void*);
564 EXTERN_C void __clang_Interpreter_SetValueNoAlloc(void *This, void *OutVal, void *OpaqueType, ...);
565)";
566
568 std::unique_ptr<CompilerInstance> CI,
569 std::unique_ptr<IncrementalExecutorBuilder> IEB /*=nullptr*/) {
570 llvm::Error Err = llvm::Error::success();
571
572 auto Interp = std::unique_ptr<Interpreter>(new Interpreter(
573 std::move(CI), Err, std::move(IEB), /*Consumer=*/nullptr));
574 if (auto E = std::move(Err))
575 return std::move(E);
576
577 // Add runtime code and set a marker to hide it from user code. Undo will not
578 // go through that.
579 if (auto E = Interp->ParseAndExecute(Runtimes))
580 return std::move(E);
581
582 Interp->markUserCodeStart();
583
584 return std::move(Interp);
585}
586
588Interpreter::createWithDevice(std::unique_ptr<CompilerInstance> CI,
589 std::unique_ptr<CompilerInstance> DCI,
592 return llvm::make_error<llvm::StringError>(
593 "Detecting the device vendor is not supported yet.",
594 llvm::inconvertibleErrorCode());
595
596 // avoid writing fat binary to disk using an in-memory virtual file system
598 std::make_unique<llvm::vfs::InMemoryFileSystem>();
600 std::make_unique<llvm::vfs::OverlayFileSystem>(
601 llvm::vfs::getRealFileSystem());
602 OverlayVFS->pushOverlay(IMVFS);
603 CI->createVirtualFileSystem(OverlayVFS);
604 CI->createFileManager();
605
607 Interpreter::create(std::move(CI));
608 if (!InterpOrErr)
609 return InterpOrErr;
610
611 std::unique_ptr<Interpreter> Interp = std::move(*InterpOrErr);
612
613 llvm::Error Err = llvm::Error::success();
614
615 auto DeviceAct = Interp->TSCtx->withContextDo([&](llvm::LLVMContext *Ctx) {
616 return std::make_unique<IncrementalAction>(*DCI, *Ctx, Err, *Interp);
617 });
618
619 if (Err)
620 return std::move(Err);
621
622 Interp->DeviceAct = std::move(DeviceAct);
623
624 if (llvm::Error E = ExecuteIncrementalAction(*DCI, *Interp->DeviceAct))
625 return std::move(E);
626
627 // Set the finalized initial device module aside, as the host path does.
628 Interp->DeviceAct->CacheCodeGenModule();
629
630 Interp->DeviceCI = std::move(DCI);
631
632 std::unique_ptr<IncrementalDeviceParser> DeviceParser;
633 if (Type == OffloadType::HIP)
634 DeviceParser = std::make_unique<IncrementalHIPDeviceParser>(
635 *Interp->DeviceCI, *Interp->getCompilerInstance(),
636 Interp->DeviceAct.get(), IMVFS, Err, Interp->PTUs);
637 else
638 DeviceParser = std::make_unique<IncrementalCUDADeviceParser>(
639 *Interp->DeviceCI, *Interp->getCompilerInstance(),
640 Interp->DeviceAct.get(), IMVFS, Err, Interp->PTUs);
641
642 if (Err)
643 return std::move(Err);
644
645 Interp->DeviceParser = std::move(DeviceParser);
646 return std::move(Interp);
647}
648
651 return const_cast<Interpreter *>(this)->getCompilerInstance();
652}
653
655 if (!IncrExecutor) {
656 if (auto Err = CreateExecutor())
657 return std::move(Err);
658 }
659
660 return *IncrExecutor.get();
661}
662
663void Interpreter::setOptLevel(unsigned OptLevel, unsigned OptSize) {
665 CGO.OptimizationLevel = OptLevel;
666 CGO.OptimizeSize = OptSize;
667 CGO.setInlining(OptLevel ? CodeGenOptions::NormalInlining
669}
670
674
678
679void Interpreter::markUserCodeStart() {
680 assert(!InitPTUSize && "We only do this once");
681 InitPTUSize = PTUs.size();
682}
683
684size_t Interpreter::getEffectivePTUSize() const {
685 assert(PTUs.size() >= InitPTUSize && "empty PTU list?");
686 return PTUs.size() - InitPTUSize;
687}
688
690Interpreter::Parse(llvm::StringRef Code) {
691 // If we have a device parser, parse it first. The generated code will be
692 // included in the host compilation
693 if (DeviceParser) {
694 llvm::Expected<TranslationUnitDecl *> DeviceTU = DeviceParser->Parse(Code);
695 if (auto E = DeviceTU.takeError())
696 return std::move(E);
697
698 PartialTranslationUnit &DevicePTU = DeviceParser->RegisterPTU(*DeviceTU);
699
700 // Under -emit-llvm, print the device module IR before it is lowered.
701 if (DevicePTU.TheModule &&
702 DeviceCI->getFrontendOpts().ProgramAction == frontend::EmitLLVM)
703 DevicePTU.TheModule->print(llvm::outs(), /*AAW=*/nullptr);
704
705 llvm::Error Err = DeviceParser->GenerateOffloadBinary();
706 if (Err)
707 return std::move(Err);
708 }
709
710 // Tell the interpreter sliently ignore unused expressions since value
711 // printing could cause it.
713 clang::diag::warn_unused_expr, diag::Severity::Ignored, SourceLocation());
714
715 llvm::Expected<TranslationUnitDecl *> TuOrErr = IncrParser->Parse(Code);
716 if (!TuOrErr)
717 return TuOrErr.takeError();
718
719 PartialTranslationUnit &LastPTU = IncrParser->RegisterPTU(*TuOrErr);
720
721 // Under -emit-llvm, print the module IR.
722 if (InitPTUSize && LastPTU.TheModule &&
723 getCompilerInstance()->getFrontendOpts().ProgramAction ==
725 LastPTU.TheModule->print(llvm::outs(), /*AAW=*/nullptr);
726
727 return LastPTU;
728}
729
731 if (IncrExecutor)
732 return llvm::make_error<llvm::StringError>("Operation failed. "
733 "Execution engine exists",
734 std::error_code());
735 if (!Act->getCodeGen())
736 return llvm::make_error<llvm::StringError>("Operation failed. "
737 "No code generator available",
738 std::error_code());
739
740 if (!IncrExecutorBuilder)
741 IncrExecutorBuilder = IncrementalExecutorBuilder::createDefault();
742
743 auto ExecutorOrErr = IncrExecutorBuilder->create(*TSCtx, CI->getTarget());
744 if (ExecutorOrErr)
745 IncrExecutor = std::move(*ExecutorOrErr);
746
747 return ExecutorOrErr.takeError();
748}
749
751 assert(T.TheModule);
752 LLVM_DEBUG(
753 llvm::dbgs() << "execute-ptu "
754 << (llvm::is_contained(PTUs, T)
755 ? std::distance(PTUs.begin(), llvm::find(PTUs, T))
756 : -1)
757 << ": [TU=" << T.TUPart << ", M=" << T.TheModule.get()
758 << " (" << T.TheModule->getName() << ")]\n");
759 if (!IncrExecutor) {
760 auto Err = CreateExecutor();
761 if (Err)
762 return Err;
763 }
764 // FIXME: Add a callback to retain the llvm::Module once the JIT is done.
765 if (auto Err = IncrExecutor->addModule(T))
766 return Err;
767
768 if (auto Err = IncrExecutor->runCtors())
769 return Err;
770
771 return llvm::Error::success();
772}
773
774llvm::Error Interpreter::ParseAndExecute(llvm::StringRef Code, Value *V) {
775
776 auto PTU = Parse(Code);
777 if (!PTU)
778 return PTU.takeError();
779 if (PTU->TheModule)
780 if (llvm::Error Err = Execute(*PTU))
781 return Err;
782
783 if (LastValue.isValid()) {
784 if (!V) {
785 LastValue.dump();
786 LastValue.clear();
787 } else
788 *V = std::move(LastValue);
789 }
790 return llvm::Error::success();
791}
792
795 if (!IncrExecutor)
796 return llvm::make_error<llvm::StringError>("Operation failed. "
797 "No execution engine",
798 std::error_code());
799 llvm::StringRef MangledName = Act->getCodeGen()->GetMangledName(GD);
800 return getSymbolAddress(MangledName);
801}
802
804Interpreter::getSymbolAddress(llvm::StringRef IRName) const {
805 if (!IncrExecutor)
806 return llvm::make_error<llvm::StringError>("Operation failed. "
807 "No execution engine",
808 std::error_code());
809
810 return IncrExecutor->getSymbolAddress(IRName, IncrementalExecutor::IRName);
811}
812
815 if (!IncrExecutor)
816 return llvm::make_error<llvm::StringError>("Operation failed. "
817 "No execution engine",
818 std::error_code());
819
820 return IncrExecutor->getSymbolAddress(Name, IncrementalExecutor::LinkerName);
821}
822
823llvm::Error Interpreter::Undo(unsigned N) {
824
825 if (getEffectivePTUSize() == 0) {
826 return llvm::make_error<llvm::StringError>("Operation failed. "
827 "No input left to undo",
828 std::error_code());
829 } else if (N > getEffectivePTUSize()) {
830 return llvm::make_error<llvm::StringError>(
831 llvm::formatv(
832 "Operation failed. Wanted to undo {0} inputs, only have {1}.", N,
833 getEffectivePTUSize()),
834 std::error_code());
835 }
836
837 for (unsigned I = 0; I < N; I++) {
838 if (IncrExecutor) {
839 if (llvm::Error Err = IncrExecutor->removeModule(PTUs.back()))
840 return Err;
841 }
842
843 IncrParser->CleanUpPTU(PTUs.back().TUPart);
844 PTUs.pop_back();
845 }
846 return llvm::Error::success();
847}
848
849llvm::Error Interpreter::LoadDynamicLibrary(const char *name) {
850 auto EEOrErr = getExecutionEngine();
851 if (!EEOrErr)
852 return EEOrErr.takeError();
853
854 return EEOrErr->LoadDynamicLibrary(name);
855}
856} // end namespace clang
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the clang::FileManager interface and associated types.
Token Tok
The Token.
Defines the clang::FrontendAction interface and various convenience abstract classes (clang::ASTFront...
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
Abstract interface for callback invocations by the ASTReader.
Definition ASTReader.h:117
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions, unsigned ClientLoadCapabilities=ARR_ConfigurationMismatch|ARR_OutOfDate)
Read the control block for the named AST file.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
bool parseLLVMArgs(llvm::raw_ostream *Errs=nullptr)
Parse the -mllvm options in FrontendOptions::LLVMArgs, setting library options in getLibraryOptions()...
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
FileSystemOptions & getFileSystemOpts()
ASTContext & getASTContext() const
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
PreprocessorOptions & getPreprocessorOpts()
bool ExecuteAction(FrontendAction &Act)
ExecuteAction - Execute the provided action against the compiler's CompilerInvocation object.
CodeGenOptions & getCodeGenOpts()
static bool CreateFromArgs(CompilerInvocation &Res, ArrayRef< const char * > CommandLineArgs, DiagnosticsEngine &Diags, const char *Argv0=nullptr)
Create a compiler invocation from a list of input options.
static llvm::IntrusiveRefCntPtr< DiagnosticIDs > create()
Options for controlling the compiler diagnostics engine.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:240
bool hasErrorOccurred() const
Definition Diagnostic.h:923
void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc)
This allows the client to specify that certain warnings are ignored.
Implements support for file system lookup, file system caching, and directory search management.
Definition FileManager.h:57
An input file for the front end.
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
A custom action enabling the incremental processing functionality.
llvm::Expected< std::unique_ptr< CompilerInstance > > CreateCpp()
llvm::Expected< std::unique_ptr< CompilerInstance > > CreateHost(OffloadType Type)
llvm::Expected< std::unique_ptr< CompilerInstance > > CreateDevice(OffloadType Type)
static std::unique_ptr< IncrementalExecutorBuilder > createDefault()
Create the default builder for the platform clangInterpreter is built for.
Provides top-level interfaces for incremental compilation and execution.
llvm::Expected< IncrementalExecutor & > getExecutionEngine()
llvm::Error ParseAndExecute(llvm::StringRef Code, Value *V=nullptr)
static llvm::Expected< std::unique_ptr< Interpreter > > create(std::unique_ptr< CompilerInstance > CI, std::unique_ptr< IncrementalExecutorBuilder > IEB=nullptr)
llvm::Error CreateExecutor()
llvm::Expected< llvm::orc::ExecutorAddr > getSymbolAddress(GlobalDecl GD) const
void setOptLevel(unsigned OptLevel, unsigned OptSize=0)
Set the optimization level and size used to emit subsequently parsed input.
llvm::Error LoadDynamicLibrary(const char *name)
Link a dynamic library.
llvm::Expected< PartialTranslationUnit & > Parse(llvm::StringRef Code)
llvm::Expected< llvm::orc::ExecutorAddr > getSymbolAddressFromLinkerName(llvm::StringRef LinkerName) const
Interpreter(std::unique_ptr< CompilerInstance > Instance, llvm::Error &Err, std::unique_ptr< IncrementalExecutorBuilder > IEB=nullptr, std::unique_ptr< clang::ASTConsumer > Consumer=nullptr)
llvm::Error Undo(unsigned N=1)
Undo N previous incremental inputs.
const CompilerInstance * getCompilerInstance() const
static llvm::Expected< std::unique_ptr< Interpreter > > createWithDevice(std::unique_ptr< CompilerInstance > CI, std::unique_ptr< CompilerInstance > DCI, OffloadType Type=OffloadType::Detect)
const ASTContext & getASTContext() const
friend class Value
llvm::Error Execute(PartialTranslationUnit &T)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
A processor an offloading action can target.
Definition OffloadArch.h:36
PragmaHandler - Instances of this interface defined to handle the various pragmas that the language f...
Definition Pragma.h:65
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
bool RetainRemappedFileBuffers
Whether the compiler instance should retain (i.e., not free) the buffers associated with remapped fil...
std::vector< std::pair< std::string, llvm::MemoryBuffer * > > RemappedFileBuffers
The set of file-to-buffer remappings, which take existing files on the system (the first part of each...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
void LexUnexpandedToken(Token &Result)
Just like Lex, but disables macro expansion of identifier tokens.
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
Encodes a location in the source.
void FlushDiagnostics(DiagnosticsEngine &Diags) const
FlushDiagnostics - Flush the buffered diagnostics to an given diagnostic engine.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
The base class of the type hierarchy.
Definition TypeBase.h:1879
Command - An executable path/name and argument vector to execute.
Definition Job.h:107
const Tool & getCreator() const
getCreator - Return the Tool which caused the creation of this job.
Definition Job.h:199
const llvm::opt::ArgStringList & getArguments() const
Definition Job.h:243
Compilation - A set of tasks to perform for a single driver invocation.
Definition Compilation.h:47
JobList - A sequence of jobs to perform.
Definition Job.h:279
size_type size() const
Definition Job.h:305
iterator begin()
Definition Job.h:306
const char * getName() const
Definition Tool.h:47
Defines the clang::TargetInfo interface.
@ Ignored
Do not present this diagnostic, ignore it.
@ EmitLLVM
Emit a .ll file.
Top level wrappers for InstallAPI frontend operations.
std::unique_ptr< DiagnosticOptions > CreateAndPopulateDiagOpts(ArrayRef< const char * > Argv)
OffloadType
The device language to offload to.
Definition Interpreter.h:51
@ Success
Annotation was successful.
Definition Parser.h:65
std::shared_ptr< ModuleCache > createCrossProcessModuleCache()
Creates new ModuleCache backed by a file system directory that may be operated on by multiple process...
@ Parse
Parse the block; this code is always used.
Definition Parser.h:137
const char *const Runtimes
const FunctionProtoType * T
std::string GetResourcesPath(StringRef BinaryPath)
Get the directory where the compiler headers reside, relative to the compiler binary path BinaryPath.
bool(*)(llvm::ArrayRef< const char * >, llvm::raw_ostream &, llvm::raw_ostream &, bool, bool) Driver
Definition Wasm.cpp:39
The class keeps track of various objects created as part of processing incremental inputs.
std::unique_ptr< llvm::Module > TheModule
The llvm IR produced for the input.
Describes how and where the pragma was introduced.
Definition Pragma.h:51