20 #include "clang/Config/config.h" 38 #include "llvm/ADT/Statistic.h" 39 #include "llvm/Support/BuryPointer.h" 40 #include "llvm/Support/CrashRecoveryContext.h" 41 #include "llvm/Support/Errc.h" 42 #include "llvm/Support/FileSystem.h" 43 #include "llvm/Support/Host.h" 44 #include "llvm/Support/LockFileManager.h" 45 #include "llvm/Support/MemoryBuffer.h" 46 #include "llvm/Support/Path.h" 47 #include "llvm/Support/Program.h" 48 #include "llvm/Support/Signals.h" 49 #include "llvm/Support/TimeProfiler.h" 50 #include "llvm/Support/Timer.h" 51 #include "llvm/Support/raw_ostream.h" 53 #include <system_error> 57 using namespace clang;
59 CompilerInstance::CompilerInstance(
60 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
64 ModuleCache(SharedModuleCache ? SharedModuleCache
66 ThePCHContainerOperations(
std::move(PCHContainerOps)) {}
69 assert(OutputFiles.empty() &&
"Still output files in flight?");
73 std::shared_ptr<CompilerInvocation>
Value) {
74 Invocation = std::move(Value);
78 return (BuildGlobalModuleIndex ||
79 (ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
100 PP = std::move(Value);
106 if (Context && Consumer)
115 Consumer = std::move(Value);
117 if (Context && Consumer)
122 CompletionConsumer.reset(Value);
126 return std::move(TheSema);
130 return ModuleManager;
133 assert(ModuleCache.get() == &Reader->getModuleManager().getModuleCache() &&
134 "Expected ASTReader to use the same PCM cache");
135 ModuleManager = std::move(Reader);
138 std::shared_ptr<ModuleDependencyCollector>
140 return ModuleDepCollector;
144 std::shared_ptr<ModuleDependencyCollector> Collector) {
145 ModuleDepCollector = std::move(Collector);
149 std::shared_ptr<ModuleDependencyCollector> MDC) {
152 for (
auto &Name : HeaderMapFileNames)
157 std::shared_ptr<ModuleDependencyCollector> MDC) {
166 MDC->addFile(PCHInclude);
172 llvm::sys::path::native(PCHDir->
getName(), DirNative);
175 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
176 Dir != DirEnd && !EC; Dir.increment(EC)) {
184 MDC->addFile(Dir->path());
189 std::shared_ptr<ModuleDependencyCollector> MDC) {
196 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
197 llvm::MemoryBuffer::getFile(VFSFile);
200 llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()),
201 nullptr, VFSFile, VFSEntries);
204 for (
auto &E : VFSEntries)
205 MDC->addFile(E.VPath, E.RPath);
213 std::unique_ptr<raw_ostream> StreamOwner;
214 raw_ostream *OS = &llvm::errs();
217 auto FileOS = llvm::make_unique<llvm::raw_fd_ostream>(
219 llvm::sys::fs::F_Append | llvm::sys::fs::F_Text);
221 Diags.
Report(diag::warn_fe_cc_log_diagnostics_failure)
224 FileOS->SetUnbuffered();
226 StreamOwner = std::move(FileOS);
231 auto Logger = llvm::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
232 std::move(StreamOwner));
246 StringRef OutputFile) {
247 auto SerializedConsumer =
252 Diags.
takeClient(), std::move(SerializedConsumer)));
255 Diags.
getClient(), std::move(SerializedConsumer)));
260 bool ShouldOwnClient) {
268 bool ShouldOwnClient,
277 Diags->setClient(Client, ShouldOwnClient);
282 if (Opts->VerifyDiagnostics)
304 VFS = FileMgr ? &FileMgr->getVirtualFileSystem()
307 assert(VFS &&
"FileManager has no VFS?");
309 return FileMgr.get();
330 Diags.
Report(diag::err_fe_remap_missing_from_file) << RB.first;
347 Diags.
Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
355 Diags.
Report(diag::err_fe_remap_missing_from_file) << RF.first;
374 ModuleManager.reset();
380 PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOptsPtr(),
389 PP->createPreprocessingRecord();
393 PP->getFileManager(), PPOpts);
402 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
403 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
404 PP->getAuxTargetInfo())
405 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
408 PP->getLangOpts(), *HeaderSearchTriple);
412 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules)
426 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
432 if (ModuleDepCollector) {
439 for (
auto &Listener : DependencyCollectors)
440 Listener->attachToPreprocessor(*PP);
447 if (OutputPath ==
"-")
466 llvm::sys::path::append(SpecificModuleCache,
468 return SpecificModuleCache.str();
485 StringRef Path,
bool DisablePCHValidation,
bool AllowPCHWithCompilerErrors,
486 void *DeserializationListener,
bool OwnDeserializationListener) {
493 DeserializationListener, OwnDeserializationListener, Preamble,
498 StringRef Path, StringRef Sysroot,
bool DisablePCHValidation,
502 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
503 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
504 void *DeserializationListener,
bool OwnDeserializationListener,
505 bool Preamble,
bool UseGlobalModuleIndex) {
509 PP, ModuleCache, &Context, PCHContainerRdr, Extensions,
510 Sysroot.empty() ?
"" : Sysroot.data(), DisablePCHValidation,
511 AllowPCHWithCompilerErrors,
false,
518 Reader->setDeserializationListener(
519 static_cast<ASTDeserializationListener *>(DeserializationListener),
520 OwnDeserializationListener);
522 for (
auto &Listener : DependencyCollectors)
523 Listener->attachToASTReader(*Reader);
525 switch (Reader->ReadAST(Path,
575 if (!CompletionConsumer) {
581 if (!CompletionConsumer)
591 FrontendTimerGroup.reset(
592 new llvm::TimerGroup(
"frontend",
"Clang front-end time report"));
594 new llvm::Timer(
"frontend",
"Clang front-end timer",
595 *FrontendTimerGroup));
615 TUKind, CompletionConsumer));
617 if (ExternalSemaSrc) {
618 TheSema->addExternalSource(ExternalSemaSrc.get());
619 ExternalSemaSrc->InitializeSema(*TheSema);
626 OutputFiles.push_back(std::move(OutFile));
630 for (OutputFile &OF : OutputFiles) {
631 if (!OF.TempFilename.empty()) {
639 FileMgr->FixupRelativePath(NewOutFile);
640 if (std::error_code ec =
641 llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) {
643 << OF.TempFilename << OF.Filename << ec.message();
648 }
else if (!OF.Filename.empty() && EraseFiles)
652 if (DeleteBuiltModules) {
653 for (
auto &
Module : BuiltModules)
655 BuiltModules.clear();
657 NonSeekStream.reset();
660 std::unique_ptr<raw_pwrite_stream>
662 StringRef Extension) {
664 true, InFile, Extension,
669 return llvm::make_unique<llvm::raw_null_ostream>();
672 std::unique_ptr<raw_pwrite_stream>
674 bool RemoveFileOnSignal, StringRef InFile,
675 StringRef Extension,
bool UseTemporary,
676 bool CreateMissingDirectories) {
677 std::string OutputPathName, TempPathName;
680 OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
681 UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
691 OutputFile((OutputPathName !=
"-") ? OutputPathName :
"", TempPathName));
697 StringRef OutputPath, std::error_code &
Error,
bool Binary,
698 bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
699 bool UseTemporary,
bool CreateMissingDirectories,
700 std::string *ResultPathName, std::string *TempPathName) {
701 assert((!CreateMissingDirectories || UseTemporary) &&
702 "CreateMissingDirectories is only allowed when using temporary files");
704 std::string OutFile, TempFile;
705 if (!OutputPath.empty()) {
706 OutFile = OutputPath;
707 }
else if (InFile ==
"-") {
709 }
else if (!Extension.empty()) {
711 llvm::sys::path::replace_extension(Path, Extension);
712 OutFile = Path.str();
717 std::unique_ptr<llvm::raw_fd_ostream> OS;
722 UseTemporary =
false;
724 llvm::sys::fs::file_status Status;
725 llvm::sys::fs::status(OutputPath, Status);
726 if (llvm::sys::fs::exists(Status)) {
728 if (!llvm::sys::fs::can_write(OutputPath)) {
735 if (!llvm::sys::fs::is_regular_file(Status))
736 UseTemporary =
false;
746 StringRef OutputExtension = llvm::sys::path::extension(OutFile);
748 StringRef(OutFile).drop_back(OutputExtension.size());
749 TempPath +=
"-%%%%%%%%";
750 TempPath += OutputExtension;
754 llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
756 if (CreateMissingDirectories &&
757 EC == llvm::errc::no_such_file_or_directory) {
758 StringRef
Parent = llvm::sys::path::parent_path(OutputPath);
759 EC = llvm::sys::fs::create_directories(Parent);
761 EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
766 OS.reset(
new llvm::raw_fd_ostream(fd,
true));
767 OSFile = TempFile = TempPath.str();
776 OS.reset(
new llvm::raw_fd_ostream(
778 (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
784 if (RemoveFileOnSignal)
785 llvm::sys::RemoveFileOnSignal(OSFile);
788 *ResultPathName = OutFile;
790 *TempPathName = TempFile;
792 if (!Binary || OS->supportsSeeking())
793 return std::move(OS);
795 auto B = llvm::make_unique<llvm::buffer_ostream>(*OS);
796 assert(!NonSeekStream);
797 NonSeekStream = std::move(OS);
825 "Couldn't establish MainFileID!");
829 StringRef InputFile = Input.
getFile();
832 if (InputFile !=
"-") {
835 Diags.
Report(diag::err_fe_error_reading) << InputFile;
848 File = FileMgr.
getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
851 Diags.
Report(diag::err_cannot_open_file) << InputFile
852 << MB.getError().message();
860 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
861 llvm::MemoryBuffer::getSTDIN();
862 if (std::error_code EC = SBOrErr.getError()) {
863 Diags.
Report(diag::err_fe_error_reading_stdin) << EC.message();
866 std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
869 SB->getBufferSize(), 0);
876 "Couldn't establish MainFileID!");
883 assert(
hasDiagnostics() &&
"Diagnostics engine is not initialized!");
885 assert(!
getFrontendOpts().ShowVersion &&
"Client must handle '-version'!");
889 raw_ostream &OS = llvm::errs();
903 auto TO = std::make_shared<TargetOptions>();
927 OS <<
"clang -cc1 version " CLANG_VERSION_STRING
928 <<
" based upon " << BACKEND_PACKAGE_STRING
929 <<
" default target " << llvm::sys::getDefaultTargetTriple() <<
"\n";
935 llvm::EnableStatistics(
false);
945 consumeError(std::move(Err));
961 OS << NumWarnings <<
" warning" << (NumWarnings == 1 ?
"" :
"s");
962 if (NumWarnings && NumErrors)
965 OS << NumErrors <<
" error" << (NumErrors == 1 ?
"" :
"s");
966 if (NumWarnings || NumErrors) {
970 OS <<
" when compiling for host";
984 llvm::PrintStatistics(OS);
987 if (!StatsFile.empty()) {
989 auto StatS = llvm::make_unique<llvm::raw_fd_ostream>(StatsFile, EC,
990 llvm::sys::fs::F_Text);
993 << StatsFile << EC.message();
995 llvm::PrintStatisticsJSON(*StatS);
1005 if (LangOpts.OpenCL)
1020 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1023 llvm::function_ref<void(CompilerInstance &)> PostBuildStep =
1025 llvm::TimeTraceScope TimeScope(
"Module Compile", ModuleName);
1029 std::make_shared<CompilerInvocation>(ImportingInstance.
getInvocation());
1035 Invocation->getLangOpts()->resetNonModularOptions();
1036 PPOpts.resetNonModularOptions();
1041 PPOpts.Macros.erase(
1042 std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
1043 [&HSOpts](
const std::pair<std::string, bool> &def) {
1044 StringRef MacroDef = def.first;
1046 llvm::CachedHashString(MacroDef.split(
'=').first)) > 0;
1048 PPOpts.Macros.end());
1051 Invocation->getLangOpts()->ModuleName =
1055 Invocation->getLangOpts()->CurrentModule = ModuleName;
1064 std::make_shared<PreprocessorOptions::FailedModulesSet>();
1071 FrontendOpts.
OutputFile = ModuleFileName.str();
1078 FrontendOpts.
Inputs = {Input};
1081 PPOpts.RetainRemappedFileBuffers =
true;
1083 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
1085 Invocation->getModuleHash() &&
"Module hash mismatch!");
1093 auto &Inv = *Invocation;
1094 Instance.setInvocation(std::move(Invocation));
1103 Instance.createSourceManager(Instance.getFileManager());
1117 diag::remark_module_build)
1118 << ModuleName << ModuleFileName;
1120 PreBuildStep(Instance);
1124 llvm::CrashRecoveryContext CRC;
1125 CRC.RunSafelyOnThread(
1132 PostBuildStep(Instance);
1135 diag::remark_module_build_done)
1142 Instance.clearOutputFiles(
true);
1144 return !Instance.getDiagnostics().hasErrorOccurred();
1151 if (Filename ==
"module_private.map")
1152 llvm::sys::path::append(PublicFilename,
"module.map");
1153 else if (Filename ==
"module.private.modulemap")
1154 llvm::sys::path::append(PublicFilename,
"module.modulemap");
1157 return FileMgr.
getFile(PublicFilename);
1166 StringRef ModuleFileName) {
1181 ModuleMapFile = PublicMMFile;
1195 llvm::sys::path::append(FakeModuleMapFile,
"__inferred_module.map");
1197 std::string InferredModuleMapContent;
1198 llvm::raw_string_ostream OS(InferredModuleMapContent);
1208 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1209 llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
1210 ModuleMapFile = Instance.getFileManager().getVirtualFile(
1211 FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1212 Instance.getSourceManager().overrideFileContents(
1213 ModuleMapFile, std::move(ModuleMapBuffer));
1229 StringRef ModuleFileName) {
1232 auto diagnoseBuildFailure = [&] {
1233 Diags.
Report(ModuleNameLoc, diag::err_module_not_built)
1239 StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1240 llvm::sys::fs::create_directories(Dir);
1244 llvm::LockFileManager Locked(ModuleFileName);
1246 case llvm::LockFileManager::LFS_Error:
1250 Diags.
Report(ModuleNameLoc, diag::remark_module_lock_failure)
1251 << Module->
Name << Locked.getErrorMessage();
1253 Locked.unsafeRemoveLockFile();
1255 case llvm::LockFileManager::LFS_Owned:
1259 diagnoseBuildFailure();
1264 case llvm::LockFileManager::LFS_Shared:
1267 switch (Locked.waitForUnlock()) {
1268 case llvm::LockFileManager::Res_Success:
1271 case llvm::LockFileManager::Res_OwnerDied:
1273 case llvm::LockFileManager::Res_Timeout:
1277 Diags.
Report(ModuleNameLoc, diag::remark_module_lock_timeout)
1280 Locked.unsafeRemoveLockFile();
1290 ModuleLoadCapabilities);
1293 Locked == llvm::LockFileManager::LFS_Shared) {
1299 diagnoseBuildFailure();
1303 diagnoseBuildFailure();
1324 for (
auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1329 if (
auto *DMD = dyn_cast<DefMacroDirective>(MD))
1330 CmdLineDefinition = DMD->getMacroInfo();
1335 if (CurrentDefinition == CmdLineDefinition) {
1337 }
else if (!CurrentDefinition) {
1340 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1342 auto LatestDef = LatestLocalMD->getDefinition();
1343 assert(LatestDef.isUndefined() &&
1344 "predefined macro went away with no #undef?");
1345 PP.
Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1348 }
else if (!CmdLineDefinition) {
1351 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1353 PP.
Diag(CurrentDefinition->getDefinitionLoc(),
1354 diag::note_module_def_undef_here)
1356 }
else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1359 PP.
Diag(ImportLoc, diag::warn_module_config_macro_undef)
1361 PP.
Diag(CurrentDefinition->getDefinitionLoc(),
1362 diag::note_module_def_undef_here)
1370 llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::F_None);
1376 struct stat StatBuf;
1379 assert(!TimestampFile.empty());
1380 llvm::sys::path::append(TimestampFile,
"modules.timestamp");
1383 if (::stat(TimestampFile.c_str(), &StatBuf)) {
1385 if (errno == ENOENT) {
1393 time_t TimeStampModTime = StatBuf.st_mtime;
1394 time_t CurrentTime = time(
nullptr);
1407 llvm::sys::path::native(HSOpts.
ModuleCachePath, ModuleCachePathNative);
1408 for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
1409 Dir != DirEnd && !EC; Dir.increment(EC)) {
1411 if (!llvm::sys::fs::is_directory(Dir->path()))
1415 for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1416 File != FileEnd && !EC; File.increment(EC)) {
1418 StringRef Extension = llvm::sys::path::extension(File->path());
1419 if (Extension !=
".pcm" && Extension !=
".timestamp" &&
1420 llvm::sys::path::filename(File->path()) !=
"modules.idx")
1425 if (::stat(File->path().c_str(), &StatBuf))
1429 time_t FileAccessTime = StatBuf.st_atime;
1430 if (CurrentTime - FileAccessTime <=
1439 std::string TimpestampFilename = File->path() +
".timestamp";
1445 if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1446 llvm::sys::fs::directory_iterator() && !EC)
1452 if (!ModuleManager) {
1459 !
getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
1466 std::string Sysroot = HSOpts.
Sysroot;
1468 std::unique_ptr<llvm::Timer> ReadTimer;
1469 if (FrontendTimerGroup)
1470 ReadTimer = llvm::make_unique<llvm::Timer>(
"reading_modules",
1472 *FrontendTimerGroup);
1489 ModuleManager->InitializeSema(
getSema());
1493 for (
auto &Listener : DependencyCollectors)
1494 Listener->attachToASTReader(*ModuleManager);
1500 if (FrontendTimerGroup)
1501 Timer.init(
"preloading." + FileName.str(),
"Preloading " + FileName.str(),
1502 *FrontendTimerGroup);
1503 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer :
nullptr);
1514 void ReadModuleName(StringRef ModuleName)
override {
1515 LoadedModules.push_back(
1519 void registerAll() {
1520 for (
auto *II : LoadedModules) {
1526 LoadedModules.clear();
1529 void markAllUnavailable() {
1530 for (
auto *II : LoadedModules) {
1541 while (!Stack.empty()) {
1542 Module *Current = Stack.pop_back_val();
1545 Stack.insert(Stack.end(),
1550 LoadedModules.clear();
1560 bool ConfigMismatchIsRecoverable =
1565 auto Listener = llvm::make_unique<ReadModuleNames>(*this);
1566 auto &ListenerRef = *Listener;
1568 std::move(Listener));
1571 switch (ModuleManager->ReadAST(
1577 ListenerRef.registerAll();
1586 ListenerRef.markAllUnavailable();
1598 bool IsInclusionDirective) {
1600 StringRef ModuleName = Path[0].first->getName();
1606 if (ImportLoc.
isValid() && LastModuleImportLoc == ImportLoc) {
1609 ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
1611 return LastModuleImportResult;
1617 llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
1618 = KnownModules.find(Path[0].first);
1619 if (Known != KnownModules.end()) {
1621 Module = Known->second;
1624 Module = PP->getHeaderSearchInfo().lookupModule(
1626 !IsInclusionDirective);
1635 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1638 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName,
true,
1639 !IsInclusionDirective);
1641 PP->getHeaderSearchInfo().getHeaderSearchOpts();
1643 std::string ModuleFileName;
1645 ModuleNotFound, ModuleCache, PrebuiltModulePath, ModuleBuildPragma
1646 } Source = ModuleNotFound;
1650 auto BuiltModuleIt = BuiltModules.find(ModuleName);
1651 if (BuiltModuleIt != BuiltModules.end()) {
1652 ModuleFileName = BuiltModuleIt->second;
1653 Source = ModuleBuildPragma;
1660 PP->getHeaderSearchInfo().getPrebuiltModuleFileName(ModuleName);
1661 if (!ModuleFileName.empty())
1662 Source = PrebuiltModulePath;
1666 if (Source == ModuleNotFound && Module) {
1667 ModuleFileName = PP->getHeaderSearchInfo().getCachedModuleFileName(Module);
1668 Source = ModuleCache;
1671 if (Source == ModuleNotFound) {
1674 << ModuleName <<
SourceRange(ImportLoc, ModuleNameLoc);
1675 ModuleBuildFailed =
true;
1679 if (ModuleFileName.empty()) {
1688 ModuleBuildFailed =
true;
1697 if (FrontendTimerGroup)
1698 Timer.init(
"loading." + ModuleFileName,
"Loading " + ModuleFileName,
1699 *FrontendTimerGroup);
1700 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer :
nullptr);
1701 llvm::TimeTraceScope TimeScope(
"Module Load", ModuleName);
1705 unsigned ARRFlags = Source == ModuleCache ?
1707 Source == PrebuiltModulePath ?
1710 switch (ModuleManager->ReadAST(ModuleFileName,
1711 Source == PrebuiltModulePath
1713 : Source == ModuleBuildPragma
1716 ImportLoc, ARRFlags)) {
1718 if (Source != ModuleCache && !Module) {
1719 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName,
true,
1720 !IsInclusionDirective);
1722 FileMgr->getFile(ModuleFileName) != Module->
getASTFile()) {
1727 ModuleBuildFailed =
true;
1728 KnownModules[Path[0].first] =
nullptr;
1737 if (Source != ModuleCache) {
1741 ModuleBuildFailed =
true;
1742 KnownModules[Path[0].first] =
nullptr;
1747 assert(Module &&
"missing module file");
1750 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1751 for (; Pos != PosEnd; ++Pos) {
1752 if (Pos->first == ModuleName)
1756 if (Pos != PosEnd) {
1758 for (; Pos != PosEnd; ++Pos) {
1759 CyclePath += Pos->first;
1760 CyclePath +=
" -> ";
1762 CyclePath += ModuleName;
1765 << ModuleName << CyclePath;
1776 ModuleBuildFailed =
true;
1784 "undiagnosed error in compileAndLoadModule");
1787 KnownModules[Path[0].first] =
nullptr;
1788 ModuleBuildFailed =
true;
1797 if (Source == PrebuiltModulePath)
1801 diag::warn_module_config_mismatch)
1810 KnownModules[Path[0].first] =
nullptr;
1816 KnownModules[Path[0].first] =
nullptr;
1817 ModuleBuildFailed =
true;
1822 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1831 bool MapPrivateSubModToTopLevel =
false;
1832 if (Path.size() > 1) {
1833 for (
unsigned I = 1, N = Path.size(); I != N; ++I) {
1834 StringRef Name = Path[I].first->getName();
1841 if (!Sub && PP->getLangOpts().ImplicitModules && Name ==
"Private" &&
1844 PrivateModule.append(
"_Private");
1847 auto &II = PP->getIdentifierTable().get(
1848 PrivateModule, PP->getIdentifierInfo(Module->
Name)->getTokenID());
1849 PrivPath.push_back(std::make_pair(&II, Path[0].second));
1851 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule,
true,
1852 !IsInclusionDirective))
1854 loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective);
1856 MapPrivateSubModToTopLevel =
true;
1858 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) {
1860 diag::warn_no_priv_submodule_use_toplevel)
1866 diag::note_private_top_level_defined);
1879 unsigned ED = Name.edit_distance((*J)->Name,
1882 if (ED <= BestEditDistance) {
1883 if (ED < BestEditDistance) {
1885 BestEditDistance = ED;
1888 Best.push_back((*J)->Name);
1893 if (Best.size() == 1) {
1895 diag::err_no_submodule_suggest)
1930 <<
SourceRange(Path.front().second, Path.back().second);
1939 <<
SourceRange(Path.front().second, Path.back().second);
1940 LastModuleImportLoc = ImportLoc;
1945 ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc);
1950 for (
unsigned I = 0, N = TopModule->
ConfigMacros.size(); I != N; ++I) {
1961 LastModuleImportLoc = ImportLoc;
1963 return LastModuleImportResult;
1967 StringRef ModuleName,
1971 for (
auto &
C : CleanModuleName)
1979 if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
1980 CleanModuleName,
"pcm", ModuleFileName)) {
1982 << ModuleFileName << EC.message();
1985 std::string ModuleMapFileName = (CleanModuleName +
".map").str();
1992 std::string NullTerminatedSource(Source.str());
1997 const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile(
1998 ModuleMapFileName, NullTerminatedSource.size(), 0);
1999 Other.getSourceManager().overrideFileContents(
2001 llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource.c_str()));
2003 Other.BuiltModules = std::move(BuiltModules);
2004 Other.DeleteBuiltModules =
false;
2008 BuiltModules = std::move(Other.BuiltModules);
2013 ModuleFileName, PreBuildStep, PostBuildStep)) {
2014 BuiltModules[ModuleName] = ModuleFileName.str();
2015 llvm::sys::RemoveFileOnSignal(ModuleFileName);
2027 ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc);
2032 if (
getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
2041 ModuleManager->loadGlobalIndex();
2046 llvm::sys::fs::create_directories(
2055 consumeError(std::move(Err));
2058 ModuleManager->resetForReload();
2059 ModuleManager->loadGlobalIndex();
2060 GlobalIndex = ModuleManager->getGlobalIndex();
2064 if (!HaveFullGlobalModuleIndex && GlobalIndex && !
buildingModule()) {
2066 bool RecreateIndex =
false;
2069 Module *TheModule = I->second;
2073 Path.push_back(std::make_pair(
2075 std::reverse(Path.begin(), Path.end());
2078 RecreateIndex =
true;
2081 if (RecreateIndex) {
2086 consumeError(std::move(Err));
2089 ModuleManager->resetForReload();
2090 ModuleManager->loadGlobalIndex();
2091 GlobalIndex = ModuleManager->getGlobalIndex();
2093 HaveFullGlobalModuleIndex =
true;
2127 ExternalSemaSrc = std::move(ESS);
std::string OutputFile
The output file, if any.
unsigned IsAvailable
Whether this module is available in the current translation unit.
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
static bool compileAndLoadModule(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName)
Defines the clang::ASTContext interface.
LangOptions & getLangOpts()
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons...
std::string OriginalModuleMap
When the input is a module map, the original module map file from which that map was inferred...
std::string Name
The name of this module.
CompilerInvocation & getInvocation()
PreprocessorOptions & getPreprocessorOpts()
void createCodeCompletionConsumer()
Create a code completion consumer using the invocation; note that this will cause the source manager ...
bool hasErrorOccurred() const
std::string ModuleDependencyOutputDir
The directory to copy module dependencies to when collecting them.
DiagnosticConsumer * getClient()
std::string DwarfDebugFlags
The string to embed in the debug information for the compile unit, if non-empty.
SelectorTable & getSelectorTable()
std::string DOTOutputFile
The file to write GraphViz-formatted header dependencies to.
FileManager * createFileManager(IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr)
Create the file manager and replace any existing one with it.
std::vector< Module * >::iterator submodule_iterator
VerifyDiagnosticConsumer - Create a diagnostic client which will use markers in the input source to c...
void createFrontendTimer()
Create the frontend timer and replace any existing one with it.
bool RemappedFilesKeepOriginalName
True if the SourceManager should report the original file name for contents of files that were remapp...
Implements support for file system lookup, file system caching, and directory search management...
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
virtual void adjust(LangOptions &Opts)
Set forced language options.
void setCodeCompletionConsumer(CodeCompleteConsumer *Value)
setCodeCompletionConsumer - Replace the current code completion consumer; the compiler instance takes...
Defines the clang::FileManager interface and associated types.
void EndSourceFile()
Perform any per-file post processing, deallocate per-file objects, and run statistics and output file...
void createDiagnostics(DiagnosticConsumer *Client=nullptr, bool ShouldOwnClient=true)
Create the diagnostics engine using the invocation's diagnostic options and replace any existing one ...
submodule_iterator submodule_begin()
static void writeTimestampFile(StringRef TimestampFile)
Write a new timestamp file with the given path.
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer...
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool buildingModule() const
Returns true if this instance is building a module.
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Defines the SourceManager interface.
void createSema(TranslationUnitKind TUKind, CodeCompleteConsumer *CompletionConsumer)
Create the Sema object to be used for parsing.
FileManager & getFileManager() const
std::shared_ptr< PCHContainerOperations > getPCHContainerOperations() const
Abstract base class for actions which can be performed by the frontend.
const FileEntry * getModuleMapFileForUniquing(const Module *M) const
Get the module map file that (along with the module name) uniquely identifies this module...
DiagnosticOptions & getDiagnosticOpts()
std::string HeaderIncludeOutputFile
The file to write header include output to.
std::shared_ptr< HeaderSearchOptions > getHeaderSearchOptsPtr() const
const FileEntry * getASTFile() const
The serialized AST file for this module, if one was created.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
bool InitializeSourceManager(const FrontendInputFile &Input)
InitializeSourceManager - Initialize the source manager to set InputFile as the main file...
InMemoryModuleCache & getModuleCache() const
void setAuxTarget(TargetInfo *Value)
Replace the current AuxTarget.
ChainedDiagnosticConsumer - Chain two diagnostic clients so that diagnostics go to the first client a...
llvm::StringMap< Module * >::const_iterator module_iterator
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::shared_ptr< FailedModulesSet > FailedModules
The set of modules that failed to build.
std::unique_ptr< DiagnosticConsumer > takeClient()
Return the current diagnostic client along with ownership of that client.
ASTContext & getASTContext() const
The client can handle an AST file that cannot load because it is out-of-date relative to its input fi...
void setModuleManager(IntrusiveRefCntPtr< ASTReader > Reader)
virtual void adjustTargetOptions(const CodeGenOptions &CGOpts, TargetOptions &TargetOpts) const
Adjust target options based on codegen options.
void setSourceManager(SourceManager *Value)
setSourceManager - Replace the current source manager.
Abstract interface, implemented by clients of the front-end, which formats and prints fully processed...
DependencyOutputOptions & getDependencyOutputOpts()
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Builtin::Context & getBuiltinInfo()
void setPredefines(const char *P)
Set the predefines for this Preprocessor.
float __ovld __cnfn normalize(float p)
Returns a vector in the same direction as p but with a length of 1.
static bool compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, StringRef ModuleName, FrontendInputFile Input, StringRef OriginalModuleMapFile, StringRef ModuleFileName, llvm::function_ref< void(CompilerInstance &)> PreBuildStep=[](CompilerInstance &) {}, llvm::function_ref< void(CompilerInstance &)> PostBuildStep=[](CompilerInstance &) {})
Compile a module file for the given module, using the options provided by the importing compiler inst...
The client can handle an AST file that cannot load because it is missing.
void setExternalSemaSource(IntrusiveRefCntPtr< ExternalSemaSource > ESS)
One of these records is kept for each identifier that is lexed.
void setMainFileID(FileID FID)
Set the file ID for the main source file.
void setClient(DiagnosticConsumer *client, bool ShouldOwnClient=true)
Set the diagnostic client associated with this diagnostic object.
static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts, DiagnosticsEngine &Diags, StringRef OutputFile)
void loadModuleFromSource(SourceLocation ImportLoc, StringRef ModuleName, StringRef Source) override
Attempt to load the given module from the specified source buffer.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Input)
Prepare the action for processing the input file Input.
void createSourceManager(FileManager &FileMgr)
Create the source manager and replace any existing one with it.
static llvm::Error writeIndex(FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, llvm::StringRef Path)
Write a global index into the given.
static void collectHeaderMaps(const HeaderSearch &HS, std::shared_ptr< ModuleDependencyCollector > MDC)
ShowIncludesDestination ShowIncludesDest
Destination of cl.exe style /showIncludes info.
unsigned getNumErrors() const
A source location that has been parsed on the command line.
llvm::SmallPtrSet< ModuleFile *, 4 > HitSet
A set of module files in which we found a result.
void setASTContext(ASTContext *Value)
setASTContext - Replace the current AST context.
CodeGenOptions & getCodeGenOpts()
__DEVICE__ int max(int __a, int __b)
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
unsigned BuildingImplicitModule
Whether we are performing an implicit module build.
Describes a module or submodule.
void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility, SourceLocation ImportLoc) override
Make the given module visible.
bool SetCodeCompletionPoint(const FileEntry *File, unsigned Line, unsigned Column)
Specify the point at which code-completion will be performed.
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
std::error_code make_error_code(BuildPreambleError Error)
void setBuildGlobalModuleIndex(bool Build)
Set the flag indicating whether we should (re)build the global module index.
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
ModuleBuildStack getModuleBuildStack() const
Retrieve the module build stack.
HeaderSearch & getHeaderSearchInfo() const
FrontendOptions & getFrontendOpts()
Visibility
Describes the different kinds of visibility that a declaration may have.
PreprocessorOutputOptions & getPreprocessorOutputOpts()
Concrete class used by the front-end to report problems and issues.
ASTConsumer & getASTConsumer() const
Defines the Diagnostic-related interfaces.
bool RetainRemappedFileBuffers
Whether the compiler instance should retain (i.e., not free) the buffers associated with remapped fil...
void setASTConsumer(std::unique_ptr< ASTConsumer > Value)
setASTConsumer - Replace the current AST consumer; the compiler instance takes ownership of Value...
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
submodule_iterator submodule_end()
bool hasASTConsumer() const
void setFileManager(FileManager *Value)
Replace the current file manager and virtual file system.
HeaderSearchOptions & getHeaderSearchOpts()
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro, Module *Mod, SourceLocation ImportLoc)
Diagnose differences between the current definition of the given configuration macro and the definiti...
std::shared_ptr< ModuleDependencyCollector > getModuleDepCollector() const
The AST file itself appears corrupted.
bool DisablePCHValidation
When true, disables most of the normal validation performed on precompiled headers.
void createPCHExternalASTSource(StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors, void *DeserializationListener, bool OwnDeserializationListener)
Create an external AST source to read a PCH file and attach it to the AST context.
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...
const FileEntry * getContainingModuleMapFile(const Module *Module) const
Retrieve the module map file containing the definition of the given module.
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers)...
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
const FileEntry * getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
Sema - This implements semantic analysis and AST building for C.
static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts, const CodeGenOptions *CodeGenOpts, DiagnosticsEngine &Diags)
std::string CurrentModule
The name of the current module, of which the main source file is a part.
const DirectoryEntry * getDirectory(StringRef DirName, bool CacheFailure=true)
Lookup, cache, and verify the specified directory (real or virtual).
Module * findSubmodule(StringRef Name) const
Find the submodule with the given name.
Describes the result of attempting to load a module.
bool lookupIdentifier(llvm::StringRef Name, HitSet &Hits)
Look for all of the module files with information about the given identifier, e.g., a global function, variable, or type with that name.
IntrusiveRefCntPtr< ASTReader > getModuleManager() const
Exposes information about the current target.
void addDependencyCollector(std::shared_ptr< DependencyCollector > Listener)
A simple code-completion consumer that prints the results it receives in a simple format...
File is from a prebuilt module path.
std::string getSpecificModuleCachePath()
const AnnotatedLine * Line
RAII object to temporarily add an AST callback listener.
FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, unsigned LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
bool hasFileManager() const
Defines version macros and version-related utility functions for Clang.
void print(raw_ostream &OS, unsigned Indent=0) const
Print the module map for this module to the given stream.
Defines the clang::Preprocessor interface.
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
void createASTContext()
Create the AST context.
unsigned ShowHeaderIncludes
Show header inclusions (-H).
LLVM_READONLY bool isAlphanumeric(unsigned char c)
Return true if this character is an ASCII letter or digit: [a-zA-Z0-9].
static bool checkModuleIsAvailable(const LangOptions &LangOpts, const TargetInfo &TargetInfo, DiagnosticsEngine &Diags, Module *M)
Check that the given module is available, producing a diagnostic if not.
void setSema(Sema *S)
Replace the current Sema; the compiler instance takes ownership of S.
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
void AttachHeaderIncludeGen(Preprocessor &PP, const DependencyOutputOptions &DepOpts, bool ShowAllHeaders=false, StringRef OutputPath={}, bool ShowDepth=true, bool MSStyle=false)
AttachHeaderIncludeGen - Create a header include list generator, and attach it to the given preproces...
static InputKind::Language getLanguageFromOptions(const LangOptions &LangOpts)
Determine the appropriate source input kind based on language options.
module_iterator module_begin() const
TargetInfo * getAuxTarget() const
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, const std::shared_ptr< TargetOptions > &Opts)
Construct a target for the given options.
The result type of a method or function.
void addOutputFile(OutputFile &&OutFile)
addOutputFile - Add an output file onto the list of tracked output files.
static bool EnableCodeCompletion(Preprocessor &PP, StringRef Filename, unsigned Line, unsigned Column)
The client can't handle any AST loading failures.
std::unique_ptr< raw_pwrite_stream > createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal, StringRef BaseInput, StringRef Extension, bool UseTemporary, bool CreateMissingDirectories=false)
Create a new output file and add it to the list of tracked output files, optionally deriving the outp...
The AST file was missing.
bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override
Check global module index for missing imports.
std::unique_ptr< Sema > takeSema()
In-memory cache for modules.
std::string CPU
If given, the name of the target CPU to generate code for.
SourceManager & getSourceManager() const
const DirectoryEntry * Directory
The build directory of this module.
void overrideFileContents(const FileEntry *SourceFile, llvm::MemoryBuffer *Buffer, bool DoNotFree)
Override the contents of the given source file by providing an already-allocated buffer.
const DirectoryEntry * getDir() const
Return the directory the file lives in.
FileSystemOptions & getFileSystemOpts()
The control block was read successfully.
bool hasPreprocessor() const
void ApplyHeaderSearchOptions(HeaderSearch &HS, const HeaderSearchOptions &HSOpts, const LangOptions &Lang, const llvm::Triple &triple)
Apply the header search options to get given HeaderSearch object.
bool ExecuteAction(FrontendAction &Act)
ExecuteAction - Execute the provided action against the compiler's CompilerInvocation object...
File is a PCH file treated as the preamble.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Encodes a location in the source.
StringRef getName() const
File is a PCH file treated as such.
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
bool isNamedPipe() const
Check whether the file is a named pipe (and thus can't be opened by the native FileManager methods)...
MacroDirective * getLocalMacroDirectiveHistory(const IdentifierInfo *II) const
Given an identifier, return the latest non-imported macro directive for that identifier.
unsigned getNumWarnings() const
Options for controlling the compiler diagnostics engine.
std::vector< FrontendInputFile > Inputs
The input files and their types.
virtual void finish()
Callback to inform the diagnostic client that processing of all source files has ended.
All of the names in this module are hidden.
File is an implicitly-loaded module.
IdentifierTable & getIdentifierTable()
Cached information about one file (either on disk or in the virtual file system). ...
void AttachDependencyGraphGen(Preprocessor &PP, StringRef OutputFile, StringRef SysRoot)
AttachDependencyGraphGen - Create a dependency graph generator, and attach it to the given preprocess...
bool PrepareToExecute(CompilerInstance &CI)
Prepare the action to execute on the given compiler instance.
std::string DiagnosticSerializationFile
The file to serialize diagnostics to (non-appending).
Diagnostic consumer that forwards diagnostics along to an existing, already-initialized diagnostic co...
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
bool hasSourceManager() const
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
std::string ModuleName
The module currently being compiled as specified by -fmodule-name.
const FileEntry * getVirtualFile(StringRef Filename, off_t Size, time_t ModificationTime)
Retrieve a file entry for a "virtual" file that acts as if there were a file with the given name on d...
constexpr size_t DesiredStackSize
The amount of stack space that Clang would like to be provided with.
void pushModuleBuildStack(StringRef moduleName, FullSourceLoc importLoc)
Push an entry to the module build stack.
unsigned GenerateGlobalModuleIndex
Whether we can generate the global module index if needed.
void createPreprocessor(TranslationUnitKind TUKind)
Create the preprocessor, using the invocation, file, and source managers, and replace any existing on...
A global index for a set of module files, providing information about the identifiers within those mo...
bool shouldBuildGlobalModuleIndex() const
Indicates whether we should (re)build the global module index.
module_iterator module_end() const
The AST file was writtten with a different language/target configuration.
std::string OutputFile
The file to write dependency output to.
Abstract interface for a consumer of code-completion information.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Options controlling the behavior of code completion.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
Dataflow Directional Tag Classes.
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
bool isValid() const
Return true if this is a valid SourceLocation object.
void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership=false)
Set the AST deserialization listener.
unsigned IsMissingRequirement
Whether this module is missing a feature from Requirements.
void setPreprocessor(std::shared_ptr< Preprocessor > Value)
Replace the current preprocessor.
FileManager & getFileManager() const
Return the current file manager to the caller.
PreprocessorOptions & getPreprocessorOpts()
static void InitializeFileRemapping(DiagnosticsEngine &Diags, SourceManager &SourceMgr, FileManager &FileMgr, const PreprocessorOptions &InitOpts)
llvm::Error Execute()
Set the source manager's main input file, and run the action.
Reads an AST files chain containing the contents of a translation unit.
File is an explicitly-loaded module.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
FileID getMainFileID() const
Returns the FileID of the main source file.
bool loadModuleFile(StringRef FileName)
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const FileEntry *Entry, bool isVolatile=false, bool ShouldCloseOpenFile=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
unsigned UseGlobalModuleIndex
Whether we can use the global module index if available.
Used for handling and querying diagnostic IDs.
void setASTMutationListener(ASTMutationListener *Listener)
Attach an AST mutation listener to the AST context.
Helper class for holding the data necessary to invoke the compiler.
static const FileEntry * getPublicModuleMap(const FileEntry *File, FileManager &FileMgr)
static void pruneModuleCache(const HeaderSearchOptions &HSOpts)
Prune the module cache of modules that haven't been accessed in a long time.
SourceManager & getSourceManager() const
Return the current source manager.
static void collectIncludePCH(CompilerInstance &CI, std::shared_ptr< ModuleDependencyCollector > MDC)
FrontendOptions - Options for controlling the behavior of the frontend.
Abstract interface for a module loader.
Encapsulates the data about a macro definition (e.g.
std::string StatsFile
Filename to write statistics to.
SourceLocation DefinitionLoc
The location of the module definition.
void clearOutputFiles(bool EraseFiles)
clearOutputFiles - Clear the output file list.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
Abstract interface for callback invocations by the ASTReader.
bool hasDiagnostics() const
TargetInfo & getTarget() const
void setOverridenFilesKeepOriginalName(bool value)
Set true if the SourceManager should report the original file name for contents of files that were ov...
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="")
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
void setTarget(TargetInfo *Value)
Replace the current Target.
Cached information about one directory (either on disk or in the virtual file system).
bool hasASTContext() const
unsigned DisableFree
Disable memory freeing on exit.
virtual void Initialize(ASTContext &Context)
Initialize - This is called to initialize the consumer, providing the ASTContext. ...
void setInvocation(std::shared_ptr< CompilerInvocation > Value)
setInvocation - Replace the current invocation.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
~CompilerInstance() override
DiagnosticConsumer & getDiagnosticClient() const
FileID getPredefinesFileID() const
Returns the FileID for the preprocessor predefines.
DiagnosticsEngine & getDiagnostics() const
void InitializePreprocessor(Preprocessor &PP, const PreprocessorOptions &PPOpts, const PCHContainerReader &PCHContainerRdr, const FrontendOptions &FEOpts)
InitializePreprocessor - Initialize the preprocessor getting it and the environment ready to process ...
void setModuleBuildStack(ModuleBuildStack stack)
Set the module build stack.
TranslationUnitKind
Describes the kind of translation unit being processed.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
std::vector< std::pair< std::string, std::string > > RemappedFiles
The set of file remappings, which take existing files on the system (the first part of each pair) and...
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
void resolveLinkAsDependencies(Module *Mod)
Use PendingLinkAsModule information to mark top level link names that are going to be replaced by exp...
unsigned HasIncompatibleModuleFile
Whether we tried and failed to load a module file for this module.
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
Defines the clang::TargetInfo interface.
The AST file is out-of-date relative to its input files, and needs to be regenerated.
A SourceLocation and its associated SourceManager.
NameVisibilityKind
Describes the visibility of the various names within a particular module.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Defines the clang::FrontendAction interface and various convenience abstract classes (clang::ASTFront...
The AST file was written by a different version of Clang.
ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) override
Attempt to load the given module.
virtual void setAuxTarget(const TargetInfo *Aux)
void createModuleManager()
void setModuleDepCollector(std::shared_ptr< ModuleDependencyCollector > Collector)
static void collectVFSEntries(CompilerInstance &CI, std::shared_ptr< ModuleDependencyCollector > MDC)
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Defines utilities for dealing with stack allocation and stack space.
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions)
Read the control block for the named AST file.
GlobalModuleIndex * loadGlobalModuleIndex(SourceLocation TriggerLoc) override
Load, create, or return global module.
A trivial tuple used to represent a source range.
LangOptions * getLangOpts()
TargetOptions & getTargetOpts()
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
llvm::vfs::FileSystem & getVirtualFileSystem() const
This class handles loading and caching of source files into memory.
void setDiagnostics(DiagnosticsEngine *Value)
setDiagnostics - Replace the current diagnostics engine.
void noSignedCharForObjCBool()
std::string getModuleHash() const
Retrieve a module hash string that is suitable for uniquely identifying the conditions under which th...
std::string DiagnosticLogFile
The file to log diagnostic output to.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
bool ownsClient() const
Determine whether this DiagnosticsEngine object own its client.
StringRef getName() const
virtual bool isModelParsingAction() const
Is this action invoked on a model file?