48#include "llvm/ExecutionEngine/JITSymbol.h"
49#include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h"
50#include "llvm/ExecutionEngine/Orc/LLJIT.h"
51#include "llvm/IR/Module.h"
52#include "llvm/Support/Errc.h"
53#include "llvm/Support/ErrorHandling.h"
54#include "llvm/Support/VirtualFileSystem.h"
55#include "llvm/Support/raw_ostream.h"
56#include "llvm/TargetParser/Host.h"
57#include "llvm/TargetParser/Triple.h"
58#include "llvm/Transforms/Utils/Cloning.h"
60#define DEBUG_TYPE "clang-repl"
75 return llvm::createStringError(llvm::errc::not_supported,
76 "Driver initialization failed. "
77 "Unable to create a driver job");
82 return llvm::createStringError(llvm::errc::not_supported,
83 "Driver initialization failed");
94 PICLevelReader(
unsigned &PICLevel) : PICLevel(PICLevel) {}
96 bool ReadLanguageOptions(
const LangOptions &LangOpts,
97 StringRef ModuleFilename,
bool Complain,
98 bool AllowCompatibleDifferences)
override {
99 PICLevel = LangOpts.PICLevel;
114 StringRef Filename) {
118 unsigned ASTPICLevel = 0;
119 PICLevelReader Reader(ASTPICLevel);
125 return llvm::createStringError(
126 llvm::errc::not_supported,
127 "AST file '%s' was built with PIC level %u, which is incompatible "
128 "with clang-repl's PIC level %u",
129 Filename.str().c_str(), ASTPICLevel, Clang.
getLangOpts().PICLevel);
130 return llvm::Error::success();
134CreateCI(
const llvm::opt::ArgStringList &Argv) {
139 auto PCHOps = Clang->getPCHContainerOperations();
140 PCHOps->registerWriter(std::make_unique<ObjectFilePCHContainerWriter>());
141 PCHOps->registerReader(std::make_unique<ObjectFilePCHContainerReader>());
149 Clang->getInvocation(),
llvm::ArrayRef(Argv.begin(), Argv.size()), Diags);
152 if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
153 Clang->getHeaderSearchOpts().ResourceDir.empty())
154 Clang->getHeaderSearchOpts().ResourceDir =
157 Clang->createVirtualFileSystem();
160 Clang->createDiagnostics();
164 return llvm::createStringError(llvm::errc::not_supported,
165 "Initialization failed. "
166 "Unable to flush diagnostics");
169 llvm::MemoryBuffer *MB = llvm::MemoryBuffer::getMemBuffer(
"").release();
170 Clang->getPreprocessorOpts().addRemappedFile(
"<<< inputs >>>", MB);
173 Clang->getDiagnostics(), Clang->getInvocation().getTargetOpts()));
174 if (!Clang->hasTarget())
175 return llvm::createStringError(llvm::errc::not_supported,
176 "Initialization failed. "
177 "Target is missing");
179 Clang->getTarget().adjust(Clang->getDiagnostics(), Clang->getLangOpts(),
180 Clang->getAuxTarget());
184 Clang->getCodeGenOpts().ClearASTBeforeBackend =
false;
186 Clang->getFrontendOpts().DisableFree =
false;
187 Clang->getCodeGenOpts().DisableFree =
false;
192 StringRef PCHInclude = Clang->getPreprocessorOpts().ImplicitPCHInclude;
193 if (!PCHInclude.empty())
194 if (llvm::Error Err = checkASTFilePICLevel(*Clang, PCHInclude))
195 return std::move(Err);
199 for (StringRef ModuleFile : Clang->getFrontendOpts().ModuleFiles)
200 if (llvm::Error Err = checkASTFilePICLevel(*Clang, ModuleFile))
201 return std::move(Err);
202 for (
const auto &NameAndFile :
203 Clang->getHeaderSearchOpts().PrebuiltModuleFiles)
204 if (llvm::Error Err = checkASTFilePICLevel(*Clang, NameAndFile.second))
205 return std::move(Err);
207 return std::move(Clang);
213 return llvm::createStringError(llvm::errc::not_supported,
214 "Failed to execute incremental action");
216 return llvm::Error::success();
224IncrementalCompilerBuilder::create(std::string TT,
225 std::vector<const char *> &ClangArgv) {
229 std::string MainExecutableName =
230 llvm::sys::fs::getMainExecutable(
nullptr,
nullptr);
232 ClangArgv.insert(ClangArgv.begin(), MainExecutableName.c_str());
246 llvm::Triple TargetTriple(TT);
247 if (!TargetTriple.isOSWindows() || TargetTriple.isOSCygMing())
248 ClangArgv.insert(ClangArgv.begin() + 1,
"-fPIC");
255 ClangArgv.insert(ClangArgv.end(),
"-Xclang");
256 ClangArgv.insert(ClangArgv.end(),
"-fincremental-extensions");
257 ClangArgv.insert(ClangArgv.end(),
"-c");
261 ClangArgv.push_back(
"<<< inputs >>>");
265 std::unique_ptr<DiagnosticOptions> DiagOpts =
267 TextDiagnosticBuffer *DiagsBuffer =
new TextDiagnosticBuffer;
270 driver::Driver
Driver(ClangArgv[0], TT, Diags);
271 Driver.setCheckInputsExist(
false);
272 llvm::ArrayRef<const char *> RF = llvm::ArrayRef(ClangArgv);
273 std::unique_ptr<driver::Compilation> Compilation(
Driver.BuildCompilation(RF));
276 if (
auto Err = (*CompilationCB)(*Compilation.get()))
277 return std::move(Err);
279 if (Compilation->getArgs().hasArg(options::OPT_v))
280 Compilation->getJobs().Print(llvm::errs(),
"\n",
false);
282 auto ErrOrCC1Args = GetCC1Arguments(&Diags, Compilation.get());
283 if (
auto Err = ErrOrCC1Args.takeError())
284 return std::move(Err);
286 return CreateCI(**ErrOrCC1Args);
291 std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple();
293 std::vector<const char *> Argv;
294 Argv.reserve(5 + 1 + UserArgs.size());
295 Argv.push_back(
"-xc++");
297 Argv.push_back(
"-target");
298 Argv.push_back(TT.c_str());
299 Argv.push_back(
"-fvisibility=default");
301 llvm::append_range(Argv, UserArgs);
303 return IncrementalCompilerBuilder::create(TT, Argv);
307IncrementalCompilerBuilder::createCuda(
bool device) {
308 std::vector<const char *> Argv;
309 Argv.reserve(5 + 4 + UserArgs.size());
311 Argv.push_back(
"-xcuda");
313 Argv.push_back(
"--cuda-device-only");
315 Argv.push_back(
"--cuda-host-only");
317 std::string SDKPathArg =
"--cuda-path=";
318 if (!CudaSDKPath.empty()) {
319 SDKPathArg += CudaSDKPath;
320 Argv.push_back(SDKPathArg.c_str());
323 std::string ArchArg =
"--offload-arch=";
326 Argv.push_back(ArchArg.c_str());
329 llvm::append_range(Argv, UserArgs);
331 std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple();
332 return IncrementalCompilerBuilder::create(TT, Argv);
337 return IncrementalCompilerBuilder::createCuda(
true);
342 return IncrementalCompilerBuilder::createCuda(
false);
347 std::unique_ptr<IncrementalExecutorBuilder> IEB,
348 std::unique_ptr<clang::ASTConsumer> Consumer)
349 : IncrExecutorBuilder(
std::move(IEB)) {
350 CI = std::move(Instance);
351 llvm::ErrorAsOutParameter EAO(&ErrOut);
352 auto LLVMCtx = std::make_unique<llvm::LLVMContext>();
353 TSCtx = std::make_unique<llvm::orc::ThreadSafeContext>(std::move(LLVMCtx));
358 Act = TSCtx->withContextDo([&](llvm::LLVMContext *Ctx) {
359 return std::make_unique<IncrementalAction>(*CI, *Ctx, ErrOut, *
this,
360 std::move(Consumer));
366 if (llvm::Error E = ExecuteIncrementalAction(*CI, *Act)) {
367 ErrOut = joinErrors(std::move(ErrOut), std::move(E));
372 std::make_unique<IncrementalParser>(*CI, Act.get(), ErrOut, PTUs);
377 if (Act->getCodeGen()) {
378 Act->CacheCodeGenModule();
381 if (!CI->getPreprocessorOpts().Includes.empty() ||
382 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty()) {
386 auto M = llvm::CloneModule(*Act->getCachedCodeGenModule());
388 IncrParser->RegisterPTU(
C.getTranslationUnitDecl(), std::move(M));
391 ErrOut = joinErrors(std::move(ErrOut), std::move(Err));
397 if (Act->getCodeGen()) {
401 if (llvm::Error Err =
Execute(PTU)) {
402 ErrOut = joinErrors(std::move(ErrOut), std::move(Err));
410 Act->FinalizeAction();
412 DeviceParser.reset();
414 DeviceAct->FinalizeAction();
416 if (llvm::Error Err = IncrExecutor->cleanUp())
417 llvm::report_fatal_error(
418 llvm::Twine(
"Failed to clean up IncrementalExecutor: ") +
427 #define __CLANG_REPL__ 1
429 #define EXTERN_C extern "C"
430 struct __clang_Interpreter_NewTag{} __ci_newtag;
431 void* operator new(__SIZE_TYPE__, void* __p, __clang_Interpreter_NewTag) noexcept;
432 template <class T, class = T (*)() /*disable for arrays*/>
433 void __clang_Interpreter_SetValueCopyArr(const T* Src, void* Placement, unsigned long Size) {
434 for (unsigned long Idx = 0; Idx < Size; ++Idx)
435 new ((void*)(((T*)Placement) + Idx), __ci_newtag) T(Src[Idx]);
437 template <class T, unsigned long N>
438 void __clang_Interpreter_SetValueCopyArr(const T (*Src)[N], void* Placement, unsigned long Size) {
439 __clang_Interpreter_SetValueCopyArr(Src[0], Placement, Size);
442 #if __STDC_VERSION__ < 199901L
446 #define CI_RESTRICT restrict
447 #define CI_INLINE inline
449 #define EXTERN_C extern
450 EXTERN_C void *memcpy(void *CI_RESTRICT dst, const void *CI_RESTRICT src, __SIZE_TYPE__ n);
451 EXTERN_C CI_INLINE void __clang_Interpreter_SetValueCopyArr(const void* Src, void* Placement, unsigned long Size) {
452 memcpy(Placement, Src, Size);
455 EXTERN_C void *__clang_Interpreter_SetValueWithAlloc(void*, void*, void*);
456 EXTERN_C void __clang_Interpreter_SetValueNoAlloc(void *This, void *OutVal, void *OpaqueType, ...);
460 std::unique_ptr<CompilerInstance> CI,
461 std::unique_ptr<IncrementalExecutorBuilder> IEB ) {
462 llvm::Error Err = llvm::Error::success();
464 auto Interp = std::unique_ptr<Interpreter>(
new Interpreter(
465 std::move(CI), Err, std::move(IEB),
nullptr));
466 if (
auto E = std::move(Err))
471 if (
auto E = Interp->ParseAndExecute(
Runtimes))
474 Interp->markUserCodeStart();
476 return std::move(Interp);
481 std::unique_ptr<CompilerInstance> DCI) {
487 std::unique_ptr<CompilerInstance> DCI,
490 return llvm::make_error<llvm::StringError>(
491 "Detecting the device vendor is not supported yet.",
492 llvm::inconvertibleErrorCode());
496 std::make_unique<llvm::vfs::InMemoryFileSystem>();
498 std::make_unique<llvm::vfs::OverlayFileSystem>(
499 llvm::vfs::getRealFileSystem());
500 OverlayVFS->pushOverlay(IMVFS);
501 CI->createVirtualFileSystem(OverlayVFS);
502 CI->createFileManager();
509 std::unique_ptr<Interpreter> Interp = std::move(*InterpOrErr);
511 llvm::Error Err = llvm::Error::success();
513 auto DeviceAct = Interp->TSCtx->withContextDo([&](llvm::LLVMContext *Ctx) {
514 return std::make_unique<IncrementalAction>(*DCI, *Ctx, Err, *Interp);
518 return std::move(Err);
520 Interp->DeviceAct = std::move(DeviceAct);
522 if (llvm::Error E = ExecuteIncrementalAction(*DCI, *Interp->DeviceAct))
526 Interp->DeviceAct->CacheCodeGenModule();
528 Interp->DeviceCI = std::move(DCI);
530 std::unique_ptr<IncrementalDeviceParser> DeviceParser;
532 DeviceParser = std::make_unique<IncrementalHIPDeviceParser>(
533 *Interp->DeviceCI, *Interp->getCompilerInstance(),
534 Interp->DeviceAct.get(), IMVFS, Err, Interp->PTUs);
536 DeviceParser = std::make_unique<IncrementalCUDADeviceParser>(
537 *Interp->DeviceCI, *Interp->getCompilerInstance(),
538 Interp->DeviceAct.get(), IMVFS, Err, Interp->PTUs);
541 return std::move(Err);
543 Interp->DeviceParser = std::move(DeviceParser);
544 return std::move(Interp);
555 return std::move(Err);
558 return *IncrExecutor.get();
569void Interpreter::markUserCodeStart() {
570 assert(!InitPTUSize &&
"We only do this once");
571 InitPTUSize = PTUs.size();
574size_t Interpreter::getEffectivePTUSize()
const {
575 assert(PTUs.size() >= InitPTUSize &&
"empty PTU list?");
576 return PTUs.size() - InitPTUSize;
585 if (
auto E = DeviceTU.takeError())
588 DeviceParser->RegisterPTU(*DeviceTU);
590 llvm::Error Err = DeviceParser->GenerateOffloadBinary();
592 return std::move(Err);
602 return TuOrErr.takeError();
610 LastPTU.
TheModule->print(llvm::outs(),
nullptr);
617 return llvm::make_error<llvm::StringError>(
"Operation failed. "
618 "Execution engine exists",
620 if (!Act->getCodeGen())
621 return llvm::make_error<llvm::StringError>(
"Operation failed. "
622 "No code generator available",
625 if (!IncrExecutorBuilder)
626 IncrExecutorBuilder = std::make_unique<IncrementalExecutorBuilder>();
630 IncrExecutorBuilder->LLVMArgs = CI->getFrontendOpts().LLVMArgs;
632 auto ExecutorOrErr = IncrExecutorBuilder->create(*TSCtx, CI->getTarget());
634 IncrExecutor = std::move(*ExecutorOrErr);
636 return ExecutorOrErr.takeError();
642 llvm::dbgs() <<
"execute-ptu "
643 << (llvm::is_contained(PTUs,
T)
644 ? std::distance(PTUs.begin(), llvm::find(PTUs,
T))
646 <<
": [TU=" <<
T.TUPart <<
", M=" <<
T.TheModule.get()
647 <<
" (" <<
T.TheModule->getName() <<
")]\n");
654 if (
auto Err = IncrExecutor->addModule(
T))
657 if (
auto Err = IncrExecutor->runCtors())
660 return llvm::Error::success();
665 auto PTU =
Parse(Code);
667 return PTU.takeError();
669 if (llvm::Error Err =
Execute(*PTU))
672 if (LastValue.isValid()) {
677 *
V = std::move(LastValue);
679 return llvm::Error::success();
685 return llvm::make_error<llvm::StringError>(
"Operation failed. "
686 "No execution engine",
688 llvm::StringRef MangledName = Act->getCodeGen()->GetMangledName(GD);
695 return llvm::make_error<llvm::StringError>(
"Operation failed. "
696 "No execution engine",
705 return llvm::make_error<llvm::StringError>(
"Operation failed. "
706 "No execution engine",
714 if (getEffectivePTUSize() == 0) {
715 return llvm::make_error<llvm::StringError>(
"Operation failed. "
716 "No input left to undo",
718 }
else if (N > getEffectivePTUSize()) {
719 return llvm::make_error<llvm::StringError>(
721 "Operation failed. Wanted to undo {0} inputs, only have {1}.", N,
722 getEffectivePTUSize()),
726 for (
unsigned I = 0; I < N; I++) {
728 if (llvm::Error Err = IncrExecutor->removeModule(PTUs.back()))
732 IncrParser->CleanUpPTU(PTUs.back().TUPart);
735 return llvm::Error::success();
741 return EEOrErr.takeError();
743 return EEOrErr->LoadDynamicLibrary(name);
Defines the clang::ASTContext interface.
Defines the clang::FileManager interface and associated types.
Defines the clang::FrontendAction interface and various convenience abstract classes (clang::ASTFront...
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 ...
Abstract interface for callback invocations by the ASTReader.
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.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
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
bool ExecuteAction(FrontendAction &Act)
ExecuteAction - Execute the provided action against the compiler's CompilerInvocation object.
LangOptions & getLangOpts()
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.
bool hasErrorOccurred() const
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.
GlobalDecl - represents a global declaration.
A custom action enabling the incremental processing functionality.
llvm::Expected< std::unique_ptr< CompilerInstance > > CreateCudaHost()
llvm::Expected< std::unique_ptr< CompilerInstance > > CreateCudaDevice()
llvm::Expected< std::unique_ptr< CompilerInstance > > CreateCpp()
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
llvm::Error LoadDynamicLibrary(const char *name)
Link a dynamic library.
static llvm::Expected< std::unique_ptr< Interpreter > > createWithCUDA(std::unique_ptr< CompilerInstance > CI, std::unique_ptr< CompilerInstance > DCI)
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
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.
Encodes a location in the source.
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, TargetOptions &Opts)
Construct a target for the given options.
void FlushDiagnostics(DiagnosticsEngine &Diags) const
FlushDiagnostics - Flush the buffered diagnostics to an given diagnostic engine.
The base class of the type hierarchy.
Command - An executable path/name and argument vector to execute.
const Tool & getCreator() const
getCreator - Return the Tool which caused the creation of this job.
const llvm::opt::ArgStringList & getArguments() const
Compilation - A set of tasks to perform for a single driver invocation.
JobList - A sequence of jobs to perform.
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.
@ Success
Annotation was successful.
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.
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
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.