1 //===--- CompilerInstance.cpp ---------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Frontend/CompilerInstance.h"
11 #include "clang/AST/ASTConsumer.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Basic/Version.h"
19 #include "clang/Config/config.h"
20 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
21 #include "clang/Frontend/FrontendAction.h"
22 #include "clang/Frontend/FrontendActions.h"
23 #include "clang/Frontend/FrontendDiagnostic.h"
24 #include "clang/Frontend/LogDiagnosticPrinter.h"
25 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
26 #include "clang/Frontend/TextDiagnosticPrinter.h"
27 #include "clang/Frontend/Utils.h"
28 #include "clang/Frontend/VerifyDiagnosticConsumer.h"
29 #include "clang/Lex/HeaderSearch.h"
30 #include "clang/Lex/PTHManager.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CodeCompleteConsumer.h"
33 #include "clang/Sema/Sema.h"
34 #include "clang/Serialization/ASTReader.h"
35 #include "clang/Serialization/GlobalModuleIndex.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Support/CrashRecoveryContext.h"
38 #include "llvm/Support/Errc.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/Host.h"
41 #include "llvm/Support/LockFileManager.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/Program.h"
45 #include "llvm/Support/Signals.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Support/raw_ostream.h"
49 #include <system_error>
53 using namespace clang;
55 CompilerInstance::CompilerInstance(
56 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
58 : ModuleLoader(BuildingModule), Invocation(new CompilerInvocation()),
59 ModuleManager(nullptr),
60 ThePCHContainerOperations(std::move(PCHContainerOps)),
61 BuildGlobalModuleIndex(false), HaveFullGlobalModuleIndex(false),
62 ModuleBuildFailed(false) {}
64 CompilerInstance::~CompilerInstance() {
65 assert(OutputFiles.empty() && "Still output files in flight?");
68 void CompilerInstance::setInvocation(CompilerInvocation *Value) {
72 bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
73 return (BuildGlobalModuleIndex ||
74 (ModuleManager && ModuleManager->isGlobalIndexUnavailable() &&
75 getFrontendOpts().GenerateGlobalModuleIndex)) &&
79 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
83 void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; }
84 void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; }
86 void CompilerInstance::setFileManager(FileManager *Value) {
89 VirtualFileSystem = Value->getVirtualFileSystem();
91 VirtualFileSystem.reset();
94 void CompilerInstance::setSourceManager(SourceManager *Value) {
98 void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
100 void CompilerInstance::setASTContext(ASTContext *Value) {
103 if (Context && Consumer)
104 getASTConsumer().Initialize(getASTContext());
107 void CompilerInstance::setSema(Sema *S) {
111 void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
112 Consumer = std::move(Value);
114 if (Context && Consumer)
115 getASTConsumer().Initialize(getASTContext());
118 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
119 CompletionConsumer.reset(Value);
122 std::unique_ptr<Sema> CompilerInstance::takeSema() {
123 return std::move(TheSema);
126 IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const {
127 return ModuleManager;
129 void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) {
130 ModuleManager = std::move(Reader);
133 std::shared_ptr<ModuleDependencyCollector>
134 CompilerInstance::getModuleDepCollector() const {
135 return ModuleDepCollector;
138 void CompilerInstance::setModuleDepCollector(
139 std::shared_ptr<ModuleDependencyCollector> Collector) {
140 ModuleDepCollector = std::move(Collector);
144 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
145 const CodeGenOptions *CodeGenOpts,
146 DiagnosticsEngine &Diags) {
148 std::unique_ptr<raw_ostream> StreamOwner;
149 raw_ostream *OS = &llvm::errs();
150 if (DiagOpts->DiagnosticLogFile != "-") {
151 // Create the output stream.
152 auto FileOS = llvm::make_unique<llvm::raw_fd_ostream>(
153 DiagOpts->DiagnosticLogFile, EC,
154 llvm::sys::fs::F_Append | llvm::sys::fs::F_Text);
156 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
157 << DiagOpts->DiagnosticLogFile << EC.message();
159 FileOS->SetUnbuffered();
161 StreamOwner = std::move(FileOS);
165 // Chain in the diagnostic client which will log the diagnostics.
166 auto Logger = llvm::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts,
167 std::move(StreamOwner));
169 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
170 assert(Diags.ownsClient());
172 new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
175 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
176 DiagnosticsEngine &Diags,
177 StringRef OutputFile) {
178 auto SerializedConsumer =
179 clang::serialized_diags::create(OutputFile, DiagOpts);
181 if (Diags.ownsClient()) {
182 Diags.setClient(new ChainedDiagnosticConsumer(
183 Diags.takeClient(), std::move(SerializedConsumer)));
185 Diags.setClient(new ChainedDiagnosticConsumer(
186 Diags.getClient(), std::move(SerializedConsumer)));
190 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
191 bool ShouldOwnClient) {
192 Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client,
193 ShouldOwnClient, &getCodeGenOpts());
196 IntrusiveRefCntPtr<DiagnosticsEngine>
197 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
198 DiagnosticConsumer *Client,
199 bool ShouldOwnClient,
200 const CodeGenOptions *CodeGenOpts) {
201 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
202 IntrusiveRefCntPtr<DiagnosticsEngine>
203 Diags(new DiagnosticsEngine(DiagID, Opts));
205 // Create the diagnostic client for reporting errors or for
206 // implementing -verify.
208 Diags->setClient(Client, ShouldOwnClient);
210 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
212 // Chain in -verify checker, if requested.
213 if (Opts->VerifyDiagnostics)
214 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
216 // Chain in -diagnostic-log-file dumper, if requested.
217 if (!Opts->DiagnosticLogFile.empty())
218 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
220 if (!Opts->DiagnosticSerializationFile.empty())
221 SetupSerializedDiagnostics(Opts, *Diags,
222 Opts->DiagnosticSerializationFile);
224 // Configure our handling of diagnostics.
225 ProcessWarningOptions(*Diags, *Opts);
232 void CompilerInstance::createFileManager() {
233 if (!hasVirtualFileSystem()) {
234 // TODO: choose the virtual file system based on the CompilerInvocation.
235 setVirtualFileSystem(vfs::getRealFileSystem());
237 FileMgr = new FileManager(getFileSystemOpts(), VirtualFileSystem);
242 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
243 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
246 // Initialize the remapping of files to alternative contents, e.g.,
247 // those specified through other files.
248 static void InitializeFileRemapping(DiagnosticsEngine &Diags,
249 SourceManager &SourceMgr,
250 FileManager &FileMgr,
251 const PreprocessorOptions &InitOpts) {
252 // Remap files in the source manager (with buffers).
253 for (const auto &RB : InitOpts.RemappedFileBuffers) {
254 // Create the file entry for the file that we're mapping from.
255 const FileEntry *FromFile =
256 FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0);
258 Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first;
259 if (!InitOpts.RetainRemappedFileBuffers)
264 // Override the contents of the "from" file with the contents of
266 SourceMgr.overrideFileContents(FromFile, RB.second,
267 InitOpts.RetainRemappedFileBuffers);
270 // Remap files in the source manager (with other files).
271 for (const auto &RF : InitOpts.RemappedFiles) {
272 // Find the file that we're mapping to.
273 const FileEntry *ToFile = FileMgr.getFile(RF.second);
275 Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
279 // Create the file entry for the file that we're mapping from.
280 const FileEntry *FromFile =
281 FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0);
283 Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first;
287 // Override the contents of the "from" file with the contents of
289 SourceMgr.overrideFileContents(FromFile, ToFile);
292 SourceMgr.setOverridenFilesKeepOriginalName(
293 InitOpts.RemappedFilesKeepOriginalName);
298 void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
299 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
301 // Create a PTH manager if we are using some form of a token cache.
302 PTHManager *PTHMgr = nullptr;
303 if (!PPOpts.TokenCache.empty())
304 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
306 // Create the Preprocessor.
307 HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(),
312 PP = new Preprocessor(&getPreprocessorOpts(), getDiagnostics(), getLangOpts(),
313 getSourceManager(), *HeaderInfo, *this, PTHMgr,
314 /*OwnsHeaderSearch=*/true, TUKind);
315 PP->Initialize(getTarget(), getAuxTarget());
317 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
318 // That argument is used as the IdentifierInfoLookup argument to
319 // IdentifierTable's ctor.
321 PTHMgr->setPreprocessor(&*PP);
322 PP->setPTHManager(PTHMgr);
325 if (PPOpts.DetailedRecord)
326 PP->createPreprocessingRecord();
328 // Apply remappings to the source manager.
329 InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(),
330 PP->getFileManager(), PPOpts);
332 // Predefine macros and configure the preprocessor.
333 InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(),
336 // Initialize the header search object.
337 ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(),
338 PP->getLangOpts(), PP->getTargetInfo().getTriple());
340 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
342 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules)
343 PP->getHeaderSearchInfo().setModuleCachePath(getSpecificModuleCachePath());
345 // Handle generating dependencies, if requested.
346 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
347 if (!DepOpts.OutputFile.empty())
348 TheDependencyFileGenerator.reset(
349 DependencyFileGenerator::CreateAndAttachToPreprocessor(*PP, DepOpts));
350 if (!DepOpts.DOTOutputFile.empty())
351 AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
352 getHeaderSearchOpts().Sysroot);
354 // If we don't have a collector, but we are collecting module dependencies,
355 // then we're the top level compiler instance and need to create one.
356 if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
357 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
358 DepOpts.ModuleDependencyOutputDir);
361 if (ModuleDepCollector)
362 addDependencyCollector(ModuleDepCollector);
364 for (auto &Listener : DependencyCollectors)
365 Listener->attachToPreprocessor(*PP);
367 // Handle generating header include information, if requested.
368 if (DepOpts.ShowHeaderIncludes)
369 AttachHeaderIncludeGen(*PP, DepOpts);
370 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
371 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
372 if (OutputPath == "-")
374 AttachHeaderIncludeGen(*PP, DepOpts,
375 /*ShowAllHeaders=*/true, OutputPath,
376 /*ShowDepth=*/false);
379 if (DepOpts.PrintShowIncludes) {
380 AttachHeaderIncludeGen(*PP, DepOpts,
381 /*ShowAllHeaders=*/true, /*OutputPath=*/"",
382 /*ShowDepth=*/true, /*MSStyle=*/true);
386 std::string CompilerInstance::getSpecificModuleCachePath() {
387 // Set up the module path, including the hash for the
388 // module-creation options.
389 SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath);
390 if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash)
391 llvm::sys::path::append(SpecificModuleCache,
392 getInvocation().getModuleHash());
393 return SpecificModuleCache.str();
398 void CompilerInstance::createASTContext() {
399 Preprocessor &PP = getPreprocessor();
400 auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
401 PP.getIdentifierTable(), PP.getSelectorTable(),
402 PP.getBuiltinInfo());
403 Context->InitBuiltinTypes(getTarget(), getAuxTarget());
404 setASTContext(Context);
409 void CompilerInstance::createPCHExternalASTSource(
410 StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors,
411 void *DeserializationListener, bool OwnDeserializationListener) {
412 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
413 ModuleManager = createPCHExternalASTSource(
414 Path, getHeaderSearchOpts().Sysroot, DisablePCHValidation,
415 AllowPCHWithCompilerErrors, getPreprocessor(), getASTContext(),
416 getPCHContainerReader(),
417 getFrontendOpts().ModuleFileExtensions,
418 DeserializationListener,
419 OwnDeserializationListener, Preamble,
420 getFrontendOpts().UseGlobalModuleIndex);
423 IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
424 StringRef Path, StringRef Sysroot, bool DisablePCHValidation,
425 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ASTContext &Context,
426 const PCHContainerReader &PCHContainerRdr,
427 ArrayRef<IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
428 void *DeserializationListener, bool OwnDeserializationListener,
429 bool Preamble, bool UseGlobalModuleIndex) {
430 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
432 IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader(
433 PP, Context, PCHContainerRdr, Extensions,
434 Sysroot.empty() ? "" : Sysroot.data(), DisablePCHValidation,
435 AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false,
436 HSOpts.ModulesValidateSystemHeaders, UseGlobalModuleIndex));
438 // We need the external source to be set up before we read the AST, because
439 // eagerly-deserialized declarations may use it.
440 Context.setExternalSource(Reader.get());
442 Reader->setDeserializationListener(
443 static_cast<ASTDeserializationListener *>(DeserializationListener),
444 /*TakeOwnership=*/OwnDeserializationListener);
445 switch (Reader->ReadAST(Path,
446 Preamble ? serialization::MK_Preamble
447 : serialization::MK_PCH,
449 ASTReader::ARR_None)) {
450 case ASTReader::Success:
451 // Set the predefines buffer as suggested by the PCH reader. Typically, the
452 // predefines buffer will be empty.
453 PP.setPredefines(Reader->getSuggestedPredefines());
456 case ASTReader::Failure:
457 // Unrecoverable failure: don't even try to process the input file.
460 case ASTReader::Missing:
461 case ASTReader::OutOfDate:
462 case ASTReader::VersionMismatch:
463 case ASTReader::ConfigurationMismatch:
464 case ASTReader::HadErrors:
465 // No suitable PCH file could be found. Return an error.
469 Context.setExternalSource(nullptr);
475 static bool EnableCodeCompletion(Preprocessor &PP,
479 // Tell the source manager to chop off the given file at a specific
481 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
483 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
488 // Truncate the named file at the given line/column.
489 PP.SetCodeCompletionPoint(Entry, Line, Column);
493 void CompilerInstance::createCodeCompletionConsumer() {
494 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
495 if (!CompletionConsumer) {
496 setCodeCompletionConsumer(
497 createCodeCompletionConsumer(getPreprocessor(),
498 Loc.FileName, Loc.Line, Loc.Column,
499 getFrontendOpts().CodeCompleteOpts,
501 if (!CompletionConsumer)
503 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
504 Loc.Line, Loc.Column)) {
505 setCodeCompletionConsumer(nullptr);
509 if (CompletionConsumer->isOutputBinary() &&
510 llvm::sys::ChangeStdoutToBinary()) {
511 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
512 setCodeCompletionConsumer(nullptr);
516 void CompilerInstance::createFrontendTimer() {
517 FrontendTimerGroup.reset(new llvm::TimerGroup("Clang front-end time report"));
519 new llvm::Timer("Clang front-end timer", *FrontendTimerGroup));
522 CodeCompleteConsumer *
523 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
527 const CodeCompleteOptions &Opts,
529 if (EnableCodeCompletion(PP, Filename, Line, Column))
532 // Set up the creation routine for code-completion.
533 return new PrintingCodeCompleteConsumer(Opts, OS);
536 void CompilerInstance::createSema(TranslationUnitKind TUKind,
537 CodeCompleteConsumer *CompletionConsumer) {
538 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
539 TUKind, CompletionConsumer));
544 void CompilerInstance::addOutputFile(OutputFile &&OutFile) {
545 OutputFiles.push_back(std::move(OutFile));
548 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
549 for (OutputFile &OF : OutputFiles) {
550 if (!OF.TempFilename.empty()) {
552 llvm::sys::fs::remove(OF.TempFilename);
554 SmallString<128> NewOutFile(OF.Filename);
556 // If '-working-directory' was passed, the output filename should be
558 FileMgr->FixupRelativePath(NewOutFile);
559 if (std::error_code ec =
560 llvm::sys::fs::rename(OF.TempFilename, NewOutFile)) {
561 getDiagnostics().Report(diag::err_unable_to_rename_temp)
562 << OF.TempFilename << OF.Filename << ec.message();
564 llvm::sys::fs::remove(OF.TempFilename);
567 } else if (!OF.Filename.empty() && EraseFiles)
568 llvm::sys::fs::remove(OF.Filename);
571 NonSeekStream.reset();
574 std::unique_ptr<raw_pwrite_stream>
575 CompilerInstance::createDefaultOutputFile(bool Binary, StringRef InFile,
576 StringRef Extension) {
577 return createOutputFile(getFrontendOpts().OutputFile, Binary,
578 /*RemoveFileOnSignal=*/true, InFile, Extension,
579 /*UseTemporary=*/true);
582 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
583 return llvm::make_unique<llvm::raw_null_ostream>();
586 std::unique_ptr<raw_pwrite_stream>
587 CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
588 bool RemoveFileOnSignal, StringRef InFile,
589 StringRef Extension, bool UseTemporary,
590 bool CreateMissingDirectories) {
591 std::string OutputPathName, TempPathName;
593 std::unique_ptr<raw_pwrite_stream> OS = createOutputFile(
594 OutputPath, EC, Binary, RemoveFileOnSignal, InFile, Extension,
595 UseTemporary, CreateMissingDirectories, &OutputPathName, &TempPathName);
597 getDiagnostics().Report(diag::err_fe_unable_to_open_output) << OutputPath
602 // Add the output file -- but don't try to remove "-", since this means we are
605 OutputFile((OutputPathName != "-") ? OutputPathName : "", TempPathName));
610 std::unique_ptr<llvm::raw_pwrite_stream> CompilerInstance::createOutputFile(
611 StringRef OutputPath, std::error_code &Error, bool Binary,
612 bool RemoveFileOnSignal, StringRef InFile, StringRef Extension,
613 bool UseTemporary, bool CreateMissingDirectories,
614 std::string *ResultPathName, std::string *TempPathName) {
615 assert((!CreateMissingDirectories || UseTemporary) &&
616 "CreateMissingDirectories is only allowed when using temporary files");
618 std::string OutFile, TempFile;
619 if (!OutputPath.empty()) {
620 OutFile = OutputPath;
621 } else if (InFile == "-") {
623 } else if (!Extension.empty()) {
624 SmallString<128> Path(InFile);
625 llvm::sys::path::replace_extension(Path, Extension);
626 OutFile = Path.str();
631 std::unique_ptr<llvm::raw_fd_ostream> OS;
636 UseTemporary = false;
638 llvm::sys::fs::file_status Status;
639 llvm::sys::fs::status(OutputPath, Status);
640 if (llvm::sys::fs::exists(Status)) {
641 // Fail early if we can't write to the final destination.
642 if (!llvm::sys::fs::can_write(OutputPath)) {
643 Error = make_error_code(llvm::errc::operation_not_permitted);
647 // Don't use a temporary if the output is a special file. This handles
648 // things like '-o /dev/null'
649 if (!llvm::sys::fs::is_regular_file(Status))
650 UseTemporary = false;
656 // Create a temporary file.
657 SmallString<128> TempPath;
659 TempPath += "-%%%%%%%%";
662 llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
664 if (CreateMissingDirectories &&
665 EC == llvm::errc::no_such_file_or_directory) {
666 StringRef Parent = llvm::sys::path::parent_path(OutputPath);
667 EC = llvm::sys::fs::create_directories(Parent);
669 EC = llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath);
674 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
675 OSFile = TempFile = TempPath.str();
677 // If we failed to create the temporary, fallback to writing to the file
678 // directly. This handles the corner case where we cannot write to the
679 // directory, but can write to the file.
684 OS.reset(new llvm::raw_fd_ostream(
686 (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text)));
691 // Make sure the out stream file gets removed if we crash.
692 if (RemoveFileOnSignal)
693 llvm::sys::RemoveFileOnSignal(OSFile);
696 *ResultPathName = OutFile;
698 *TempPathName = TempFile;
700 if (!Binary || OS->supportsSeeking())
701 return std::move(OS);
703 auto B = llvm::make_unique<llvm::buffer_ostream>(*OS);
704 assert(!NonSeekStream);
705 NonSeekStream = std::move(OS);
709 // Initialization Utilities
711 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
712 return InitializeSourceManager(
713 Input, getDiagnostics(), getFileManager(), getSourceManager(),
714 hasPreprocessor() ? &getPreprocessor().getHeaderSearchInfo() : nullptr,
715 getDependencyOutputOpts(), getFrontendOpts());
719 bool CompilerInstance::InitializeSourceManager(
720 const FrontendInputFile &Input, DiagnosticsEngine &Diags,
721 FileManager &FileMgr, SourceManager &SourceMgr, HeaderSearch *HS,
722 DependencyOutputOptions &DepOpts, const FrontendOptions &Opts) {
723 SrcMgr::CharacteristicKind
724 Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
726 if (Input.isBuffer()) {
727 SourceMgr.setMainFileID(SourceMgr.createFileID(
728 std::unique_ptr<llvm::MemoryBuffer>(Input.getBuffer()), Kind));
729 assert(SourceMgr.getMainFileID().isValid() &&
730 "Couldn't establish MainFileID!");
734 StringRef InputFile = Input.getFile();
736 // Figure out where to get and map in the main file.
737 if (InputFile != "-") {
738 const FileEntry *File;
739 if (Opts.FindPchSource.empty()) {
740 File = FileMgr.getFile(InputFile, /*OpenFile=*/true);
742 // When building a pch file in clang-cl mode, the .h file is built as if
743 // it was included by a cc file. Since the driver doesn't know about
744 // all include search directories, the frontend must search the input
745 // file through HeaderSearch here, as if it had been included by the
746 // cc file at Opts.FindPchSource.
747 const FileEntry *FindFile = FileMgr.getFile(Opts.FindPchSource);
749 Diags.Report(diag::err_fe_error_reading) << Opts.FindPchSource;
752 const DirectoryLookup *UnusedCurDir;
753 SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
755 Includers.push_back(std::make_pair(FindFile, FindFile->getDir()));
756 File = HS->LookupFile(InputFile, SourceLocation(), /*isAngled=*/false,
758 /*CurDir=*/UnusedCurDir, Includers,
759 /*SearchPath=*/nullptr,
760 /*RelativePath=*/nullptr,
761 /*RequestingModule=*/nullptr,
762 /*SuggestedModule=*/nullptr, /*SkipCache=*/true);
763 // Also add the header to /showIncludes output.
765 DepOpts.ShowIncludesPretendHeader = File->getName();
768 Diags.Report(diag::err_fe_error_reading) << InputFile;
772 // The natural SourceManager infrastructure can't currently handle named
773 // pipes, but we would at least like to accept them for the main
774 // file. Detect them here, read them with the volatile flag so FileMgr will
775 // pick up the correct size, and simply override their contents as we do for
777 if (File->isNamedPipe()) {
778 auto MB = FileMgr.getBufferForFile(File, /*isVolatile=*/true);
780 // Create a new virtual file that will have the correct size.
781 File = FileMgr.getVirtualFile(InputFile, (*MB)->getBufferSize(), 0);
782 SourceMgr.overrideFileContents(File, std::move(*MB));
784 Diags.Report(diag::err_cannot_open_file) << InputFile
785 << MB.getError().message();
790 SourceMgr.setMainFileID(
791 SourceMgr.createFileID(File, SourceLocation(), Kind));
793 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> SBOrErr =
794 llvm::MemoryBuffer::getSTDIN();
795 if (std::error_code EC = SBOrErr.getError()) {
796 Diags.Report(diag::err_fe_error_reading_stdin) << EC.message();
799 std::unique_ptr<llvm::MemoryBuffer> SB = std::move(SBOrErr.get());
801 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
802 SB->getBufferSize(), 0);
803 SourceMgr.setMainFileID(
804 SourceMgr.createFileID(File, SourceLocation(), Kind));
805 SourceMgr.overrideFileContents(File, std::move(SB));
808 assert(SourceMgr.getMainFileID().isValid() &&
809 "Couldn't establish MainFileID!");
813 // High-Level Operations
815 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
816 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
817 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
818 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
820 // FIXME: Take this as an argument, once all the APIs we used have moved to
821 // taking it as an input instead of hard-coding llvm::errs.
822 raw_ostream &OS = llvm::errs();
824 // Create the target instance.
825 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(),
826 getInvocation().TargetOpts));
830 // Create TargetInfo for the other side of CUDA compilation.
831 if (getLangOpts().CUDA && !getFrontendOpts().AuxTriple.empty()) {
832 auto TO = std::make_shared<TargetOptions>();
833 TO->Triple = getFrontendOpts().AuxTriple;
834 TO->HostTriple = getTarget().getTriple().str();
835 setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO));
838 // Inform the target of the language options.
840 // FIXME: We shouldn't need to do this, the target should be immutable once
841 // created. This complexity should be lifted elsewhere.
842 getTarget().adjust(getLangOpts());
844 // rewriter project will change target built-in bool type from its default.
845 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
846 getTarget().noSignedCharForObjCBool();
848 // Validate/process some options.
849 if (getHeaderSearchOpts().Verbose)
850 OS << "clang -cc1 version " CLANG_VERSION_STRING
851 << " based upon " << BACKEND_PACKAGE_STRING
852 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
854 if (getFrontendOpts().ShowTimers)
855 createFrontendTimer();
857 if (getFrontendOpts().ShowStats)
858 llvm::EnableStatistics();
860 for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
861 // Reset the ID tables if we are reusing the SourceManager and parsing
863 if (hasSourceManager() && !Act.isModelParsingAction())
864 getSourceManager().clearIDTables();
866 if (Act.BeginSourceFile(*this, FIF)) {
872 // Notify the diagnostic client that all files were processed.
873 getDiagnostics().getClient()->finish();
875 if (getDiagnosticOpts().ShowCarets) {
876 // We can have multiple diagnostics sharing one diagnostic client.
877 // Get the total number of warnings/errors from the client.
878 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
879 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
882 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
883 if (NumWarnings && NumErrors)
886 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
887 if (NumWarnings || NumErrors)
888 OS << " generated.\n";
891 if (getFrontendOpts().ShowStats && hasFileManager()) {
892 getFileManager().PrintStats();
896 return !getDiagnostics().getClient()->getNumErrors();
899 /// \brief Determine the appropriate source input kind based on language
901 static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
907 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
908 return LangOpts.CPlusPlus? IK_CXX : IK_C;
911 /// \brief Compile a module file for the given module, using the options
912 /// provided by the importing compiler instance. Returns true if the module
913 /// was built without errors.
914 static bool compileModuleImpl(CompilerInstance &ImportingInstance,
915 SourceLocation ImportLoc,
917 StringRef ModuleFileName) {
919 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
921 // Construct a compiler invocation for creating this module.
922 IntrusiveRefCntPtr<CompilerInvocation> Invocation
923 (new CompilerInvocation(ImportingInstance.getInvocation()));
925 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
927 // For any options that aren't intended to affect how a module is built,
928 // reset them to their default values.
929 Invocation->getLangOpts()->resetNonModularOptions();
930 PPOpts.resetNonModularOptions();
932 // Remove any macro definitions that are explicitly ignored by the module.
933 // They aren't supposed to affect how the module is built anyway.
934 const HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
936 std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(),
937 [&HSOpts](const std::pair<std::string, bool> &def) {
938 StringRef MacroDef = def.first;
939 return HSOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first) > 0;
941 PPOpts.Macros.end());
943 // Note the name of the module we're building.
944 Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
946 // Make sure that the failed-module structure has been allocated in
947 // the importing instance, and propagate the pointer to the newly-created
949 PreprocessorOptions &ImportingPPOpts
950 = ImportingInstance.getInvocation().getPreprocessorOpts();
951 if (!ImportingPPOpts.FailedModules)
952 ImportingPPOpts.FailedModules = new PreprocessorOptions::FailedModulesSet;
953 PPOpts.FailedModules = ImportingPPOpts.FailedModules;
955 // If there is a module map file, build the module using the module map.
956 // Set up the inputs/outputs so that we build the module from its umbrella
958 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
959 FrontendOpts.OutputFile = ModuleFileName.str();
960 FrontendOpts.DisableFree = false;
961 FrontendOpts.GenerateGlobalModuleIndex = false;
962 FrontendOpts.BuildingImplicitModule = true;
963 FrontendOpts.Inputs.clear();
964 InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
966 // Don't free the remapped file buffers; they are owned by our caller.
967 PPOpts.RetainRemappedFileBuffers = true;
969 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
970 assert(ImportingInstance.getInvocation().getModuleHash() ==
971 Invocation->getModuleHash() && "Module hash mismatch!");
973 // Construct a compiler instance that will be used to actually create the
975 CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(),
976 /*BuildingModule=*/true);
977 Instance.setInvocation(&*Invocation);
979 Instance.createDiagnostics(new ForwardingDiagnosticConsumer(
980 ImportingInstance.getDiagnosticClient()),
981 /*ShouldOwnClient=*/true);
983 Instance.setVirtualFileSystem(&ImportingInstance.getVirtualFileSystem());
985 // Note that this module is part of the module build stack, so that we
986 // can detect cycles in the module graph.
987 Instance.setFileManager(&ImportingInstance.getFileManager());
988 Instance.createSourceManager(Instance.getFileManager());
989 SourceManager &SourceMgr = Instance.getSourceManager();
990 SourceMgr.setModuleBuildStack(
991 ImportingInstance.getSourceManager().getModuleBuildStack());
992 SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(),
993 FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager()));
995 // If we're collecting module dependencies, we need to share a collector
996 // between all of the module CompilerInstances. Other than that, we don't
997 // want to produce any dependency output from the module build.
998 Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector());
999 Invocation->getDependencyOutputOpts() = DependencyOutputOptions();
1001 // Get or create the module map that we'll use to build this module.
1002 std::string InferredModuleMapContent;
1003 if (const FileEntry *ModuleMapFile =
1004 ModMap.getContainingModuleMapFile(Module)) {
1005 // Use the module map where this module resides.
1006 FrontendOpts.Inputs.emplace_back(ModuleMapFile->getName(), IK);
1008 SmallString<128> FakeModuleMapFile(Module->Directory->getName());
1009 llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map");
1010 FrontendOpts.Inputs.emplace_back(FakeModuleMapFile, IK);
1012 llvm::raw_string_ostream OS(InferredModuleMapContent);
1016 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1017 llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent);
1018 ModuleMapFile = Instance.getFileManager().getVirtualFile(
1019 FakeModuleMapFile, InferredModuleMapContent.size(), 0);
1020 SourceMgr.overrideFileContents(ModuleMapFile, std::move(ModuleMapBuffer));
1023 // Construct a module-generating action. Passing through the module map is
1024 // safe because the FileManager is shared between the compiler instances.
1025 GenerateModuleAction CreateModuleAction(
1026 ModMap.getModuleMapFileForUniquing(Module), Module->IsSystem);
1028 ImportingInstance.getDiagnostics().Report(ImportLoc,
1029 diag::remark_module_build)
1030 << Module->Name << ModuleFileName;
1032 // Execute the action to actually build the module in-place. Use a separate
1033 // thread so that we get a stack large enough.
1034 const unsigned ThreadStackSize = 8 << 20;
1035 llvm::CrashRecoveryContext CRC;
1036 CRC.RunSafelyOnThread([&]() { Instance.ExecuteAction(CreateModuleAction); },
1039 ImportingInstance.getDiagnostics().Report(ImportLoc,
1040 diag::remark_module_build_done)
1043 // Delete the temporary module map file.
1044 // FIXME: Even though we're executing under crash protection, it would still
1045 // be nice to do this with RemoveFileOnSignal when we can. However, that
1046 // doesn't make sense for all clients, so clean this up manually.
1047 Instance.clearOutputFiles(/*EraseFiles=*/true);
1049 // We've rebuilt a module. If we're allowed to generate or update the global
1050 // module index, record that fact in the importing compiler instance.
1051 if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) {
1052 ImportingInstance.setBuildGlobalModuleIndex(true);
1055 return !Instance.getDiagnostics().hasErrorOccurred();
1058 static bool compileAndLoadModule(CompilerInstance &ImportingInstance,
1059 SourceLocation ImportLoc,
1060 SourceLocation ModuleNameLoc, Module *Module,
1061 StringRef ModuleFileName) {
1062 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1064 auto diagnoseBuildFailure = [&] {
1065 Diags.Report(ModuleNameLoc, diag::err_module_not_built)
1066 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1069 // FIXME: have LockFileManager return an error_code so that we can
1070 // avoid the mkdir when the directory already exists.
1071 StringRef Dir = llvm::sys::path::parent_path(ModuleFileName);
1072 llvm::sys::fs::create_directories(Dir);
1075 unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1076 llvm::LockFileManager Locked(ModuleFileName);
1078 case llvm::LockFileManager::LFS_Error:
1079 Diags.Report(ModuleNameLoc, diag::err_module_lock_failure)
1080 << Module->Name << Locked.getErrorMessage();
1083 case llvm::LockFileManager::LFS_Owned:
1084 // We're responsible for building the module ourselves.
1085 if (!compileModuleImpl(ImportingInstance, ModuleNameLoc, Module,
1087 diagnoseBuildFailure();
1092 case llvm::LockFileManager::LFS_Shared:
1093 // Someone else is responsible for building the module. Wait for them to
1095 switch (Locked.waitForUnlock()) {
1096 case llvm::LockFileManager::Res_Success:
1097 ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1099 case llvm::LockFileManager::Res_OwnerDied:
1100 continue; // try again to get the lock.
1101 case llvm::LockFileManager::Res_Timeout:
1102 Diags.Report(ModuleNameLoc, diag::err_module_lock_timeout)
1104 // Clear the lock file so that future invokations can make progress.
1105 Locked.unsafeRemoveLockFile();
1111 // Try to read the module file, now that we've compiled it.
1112 ASTReader::ASTReadResult ReadResult =
1113 ImportingInstance.getModuleManager()->ReadAST(
1114 ModuleFileName, serialization::MK_ImplicitModule, ImportLoc,
1115 ModuleLoadCapabilities);
1117 if (ReadResult == ASTReader::OutOfDate &&
1118 Locked == llvm::LockFileManager::LFS_Shared) {
1119 // The module may be out of date in the presence of file system races,
1120 // or if one of its imports depends on header search paths that are not
1121 // consistent with this ImportingInstance. Try again...
1123 } else if (ReadResult == ASTReader::Missing) {
1124 diagnoseBuildFailure();
1125 } else if (ReadResult != ASTReader::Success &&
1126 !Diags.hasErrorOccurred()) {
1127 // The ASTReader didn't diagnose the error, so conservatively report it.
1128 diagnoseBuildFailure();
1130 return ReadResult == ASTReader::Success;
1134 /// \brief Diagnose differences between the current definition of the given
1135 /// configuration macro and the definition provided on the command line.
1136 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1137 Module *Mod, SourceLocation ImportLoc) {
1138 IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro);
1139 SourceManager &SourceMgr = PP.getSourceManager();
1141 // If this identifier has never had a macro definition, then it could
1142 // not have changed.
1143 if (!Id->hadMacroDefinition())
1145 auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id);
1147 // Find the macro definition from the command line.
1148 MacroInfo *CmdLineDefinition = nullptr;
1149 for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1150 // We only care about the predefines buffer.
1151 FileID FID = SourceMgr.getFileID(MD->getLocation());
1152 if (FID.isInvalid() || FID != PP.getPredefinesFileID())
1154 if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1155 CmdLineDefinition = DMD->getMacroInfo();
1159 auto *CurrentDefinition = PP.getMacroInfo(Id);
1160 if (CurrentDefinition == CmdLineDefinition) {
1161 // Macro matches. Nothing to do.
1162 } else if (!CurrentDefinition) {
1163 // This macro was defined on the command line, then #undef'd later.
1165 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1166 << true << ConfigMacro << Mod->getFullModuleName();
1167 auto LatestDef = LatestLocalMD->getDefinition();
1168 assert(LatestDef.isUndefined() &&
1169 "predefined macro went away with no #undef?");
1170 PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here)
1173 } else if (!CmdLineDefinition) {
1174 // There was no definition for this macro in the predefines buffer,
1175 // but there was a local definition. Complain.
1176 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1177 << false << ConfigMacro << Mod->getFullModuleName();
1178 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1179 diag::note_module_def_undef_here)
1181 } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP,
1182 /*Syntactically=*/true)) {
1183 // The macro definitions differ.
1184 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef)
1185 << false << ConfigMacro << Mod->getFullModuleName();
1186 PP.Diag(CurrentDefinition->getDefinitionLoc(),
1187 diag::note_module_def_undef_here)
1192 /// \brief Write a new timestamp file with the given path.
1193 static void writeTimestampFile(StringRef TimestampFile) {
1195 llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::F_None);
1198 /// \brief Prune the module cache of modules that haven't been accessed in
1200 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) {
1201 struct stat StatBuf;
1202 llvm::SmallString<128> TimestampFile;
1203 TimestampFile = HSOpts.ModuleCachePath;
1204 assert(!TimestampFile.empty());
1205 llvm::sys::path::append(TimestampFile, "modules.timestamp");
1207 // Try to stat() the timestamp file.
1208 if (::stat(TimestampFile.c_str(), &StatBuf)) {
1209 // If the timestamp file wasn't there, create one now.
1210 if (errno == ENOENT) {
1211 writeTimestampFile(TimestampFile);
1216 // Check whether the time stamp is older than our pruning interval.
1217 // If not, do nothing.
1218 time_t TimeStampModTime = StatBuf.st_mtime;
1219 time_t CurrentTime = time(nullptr);
1220 if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval))
1223 // Write a new timestamp file so that nobody else attempts to prune.
1224 // There is a benign race condition here, if two Clang instances happen to
1225 // notice at the same time that the timestamp is out-of-date.
1226 writeTimestampFile(TimestampFile);
1228 // Walk the entire module cache, looking for unused module files and module
1231 SmallString<128> ModuleCachePathNative;
1232 llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative);
1233 for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd;
1234 Dir != DirEnd && !EC; Dir.increment(EC)) {
1235 // If we don't have a directory, there's nothing to look into.
1236 if (!llvm::sys::fs::is_directory(Dir->path()))
1239 // Walk all of the files within this directory.
1240 for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd;
1241 File != FileEnd && !EC; File.increment(EC)) {
1242 // We only care about module and global module index files.
1243 StringRef Extension = llvm::sys::path::extension(File->path());
1244 if (Extension != ".pcm" && Extension != ".timestamp" &&
1245 llvm::sys::path::filename(File->path()) != "modules.idx")
1248 // Look at this file. If we can't stat it, there's nothing interesting
1250 if (::stat(File->path().c_str(), &StatBuf))
1253 // If the file has been used recently enough, leave it there.
1254 time_t FileAccessTime = StatBuf.st_atime;
1255 if (CurrentTime - FileAccessTime <=
1256 time_t(HSOpts.ModuleCachePruneAfter)) {
1261 llvm::sys::fs::remove(File->path());
1263 // Remove the timestamp file.
1264 std::string TimpestampFilename = File->path() + ".timestamp";
1265 llvm::sys::fs::remove(TimpestampFilename);
1268 // If we removed all of the files in the directory, remove the directory
1270 if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
1271 llvm::sys::fs::directory_iterator() && !EC)
1272 llvm::sys::fs::remove(Dir->path());
1276 void CompilerInstance::createModuleManager() {
1277 if (!ModuleManager) {
1278 if (!hasASTContext())
1281 // If we're implicitly building modules but not currently recursively
1282 // building a module, check whether we need to prune the module cache.
1283 if (getSourceManager().getModuleBuildStack().empty() &&
1284 !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() &&
1285 getHeaderSearchOpts().ModuleCachePruneInterval > 0 &&
1286 getHeaderSearchOpts().ModuleCachePruneAfter > 0) {
1287 pruneModuleCache(getHeaderSearchOpts());
1290 HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
1291 std::string Sysroot = HSOpts.Sysroot;
1292 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1293 std::unique_ptr<llvm::Timer> ReadTimer;
1294 if (FrontendTimerGroup)
1295 ReadTimer = llvm::make_unique<llvm::Timer>("Reading modules",
1296 *FrontendTimerGroup);
1297 ModuleManager = new ASTReader(
1298 getPreprocessor(), getASTContext(), getPCHContainerReader(),
1299 getFrontendOpts().ModuleFileExtensions,
1300 Sysroot.empty() ? "" : Sysroot.c_str(), PPOpts.DisablePCHValidation,
1301 /*AllowASTWithCompilerErrors=*/false,
1302 /*AllowConfigurationMismatch=*/false,
1303 HSOpts.ModulesValidateSystemHeaders,
1304 getFrontendOpts().UseGlobalModuleIndex,
1305 std::move(ReadTimer));
1306 if (hasASTConsumer()) {
1307 ModuleManager->setDeserializationListener(
1308 getASTConsumer().GetASTDeserializationListener());
1309 getASTContext().setASTMutationListener(
1310 getASTConsumer().GetASTMutationListener());
1312 getASTContext().setExternalSource(ModuleManager);
1314 ModuleManager->InitializeSema(getSema());
1315 if (hasASTConsumer())
1316 ModuleManager->StartTranslationUnit(&getASTConsumer());
1318 if (TheDependencyFileGenerator)
1319 TheDependencyFileGenerator->AttachToASTReader(*ModuleManager);
1320 for (auto &Listener : DependencyCollectors)
1321 Listener->attachToASTReader(*ModuleManager);
1325 bool CompilerInstance::loadModuleFile(StringRef FileName) {
1327 if (FrontendTimerGroup)
1328 Timer.init("Preloading " + FileName.str(), *FrontendTimerGroup);
1329 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1331 // Helper to recursively read the module names for all modules we're adding.
1332 // We mark these as known and redirect any attempt to load that module to
1333 // the files we were handed.
1334 struct ReadModuleNames : ASTReaderListener {
1335 CompilerInstance &CI;
1336 llvm::SmallVector<IdentifierInfo*, 8> LoadedModules;
1338 ReadModuleNames(CompilerInstance &CI) : CI(CI) {}
1340 void ReadModuleName(StringRef ModuleName) override {
1341 LoadedModules.push_back(
1342 CI.getPreprocessor().getIdentifierInfo(ModuleName));
1345 void registerAll() {
1346 for (auto *II : LoadedModules) {
1347 CI.KnownModules[II] = CI.getPreprocessor()
1348 .getHeaderSearchInfo()
1350 .findModule(II->getName());
1352 LoadedModules.clear();
1355 void markAllUnavailable() {
1356 for (auto *II : LoadedModules) {
1357 if (Module *M = CI.getPreprocessor()
1358 .getHeaderSearchInfo()
1360 .findModule(II->getName()))
1361 M->HasIncompatibleModuleFile = true;
1363 LoadedModules.clear();
1367 // If we don't already have an ASTReader, create one now.
1369 createModuleManager();
1371 auto Listener = llvm::make_unique<ReadModuleNames>(*this);
1372 auto &ListenerRef = *Listener;
1373 ASTReader::ListenerScope ReadModuleNamesListener(*ModuleManager,
1374 std::move(Listener));
1376 // Try to load the module file.
1377 switch (ModuleManager->ReadAST(FileName, serialization::MK_ExplicitModule,
1379 ASTReader::ARR_ConfigurationMismatch)) {
1380 case ASTReader::Success:
1381 // We successfully loaded the module file; remember the set of provided
1382 // modules so that we don't try to load implicit modules for them.
1383 ListenerRef.registerAll();
1386 case ASTReader::ConfigurationMismatch:
1387 // Ignore unusable module files.
1388 getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch)
1390 // All modules provided by any files we tried and failed to load are now
1391 // unavailable; includes of those modules should now be handled textually.
1392 ListenerRef.markAllUnavailable();
1401 CompilerInstance::loadModule(SourceLocation ImportLoc,
1403 Module::NameVisibilityKind Visibility,
1404 bool IsInclusionDirective) {
1405 // Determine what file we're searching from.
1406 StringRef ModuleName = Path[0].first->getName();
1407 SourceLocation ModuleNameLoc = Path[0].second;
1409 // If we've already handled this import, just return the cached result.
1410 // This one-element cache is important to eliminate redundant diagnostics
1411 // when both the preprocessor and parser see the same import declaration.
1412 if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
1413 // Make the named module visible.
1414 if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
1415 ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility,
1417 return LastModuleImportResult;
1420 clang::Module *Module = nullptr;
1422 // If we don't already have information on this module, load the module now.
1423 llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
1424 = KnownModules.find(Path[0].first);
1425 if (Known != KnownModules.end()) {
1426 // Retrieve the cached top-level module.
1427 Module = Known->second;
1428 } else if (ModuleName == getLangOpts().CurrentModule) {
1429 // This is the module we're building.
1430 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1431 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1433 // Search for a module with the given name.
1434 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
1436 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
1438 << SourceRange(ImportLoc, ModuleNameLoc);
1439 ModuleBuildFailed = true;
1440 return ModuleLoadResult();
1443 std::string ModuleFileName =
1444 PP->getHeaderSearchInfo().getModuleFileName(Module);
1445 if (ModuleFileName.empty()) {
1446 if (Module->HasIncompatibleModuleFile) {
1447 // We tried and failed to load a module file for this module. Fall
1448 // back to textual inclusion for its headers.
1449 return ModuleLoadResult(nullptr, /*missingExpected*/true);
1452 getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled)
1454 ModuleBuildFailed = true;
1455 return ModuleLoadResult();
1458 // If we don't already have an ASTReader, create one now.
1460 createModuleManager();
1463 if (FrontendTimerGroup)
1464 Timer.init("Loading " + ModuleFileName, *FrontendTimerGroup);
1465 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr);
1467 // Try to load the module file.
1468 unsigned ARRFlags = ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing;
1469 switch (ModuleManager->ReadAST(ModuleFileName,
1470 serialization::MK_ImplicitModule,
1471 ImportLoc, ARRFlags)) {
1472 case ASTReader::Success:
1475 case ASTReader::OutOfDate:
1476 case ASTReader::Missing: {
1477 // The module file is missing or out-of-date. Build it.
1478 assert(Module && "missing module file");
1479 // Check whether there is a cycle in the module graph.
1480 ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
1481 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1482 for (; Pos != PosEnd; ++Pos) {
1483 if (Pos->first == ModuleName)
1487 if (Pos != PosEnd) {
1488 SmallString<256> CyclePath;
1489 for (; Pos != PosEnd; ++Pos) {
1490 CyclePath += Pos->first;
1491 CyclePath += " -> ";
1493 CyclePath += ModuleName;
1495 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1496 << ModuleName << CyclePath;
1497 return ModuleLoadResult();
1500 // Check whether we have already attempted to build this module (but
1502 if (getPreprocessorOpts().FailedModules &&
1503 getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) {
1504 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built)
1506 << SourceRange(ImportLoc, ModuleNameLoc);
1507 ModuleBuildFailed = true;
1508 return ModuleLoadResult();
1511 // Try to compile and then load the module.
1512 if (!compileAndLoadModule(*this, ImportLoc, ModuleNameLoc, Module,
1514 assert(getDiagnostics().hasErrorOccurred() &&
1515 "undiagnosed error in compileAndLoadModule");
1516 if (getPreprocessorOpts().FailedModules)
1517 getPreprocessorOpts().FailedModules->addFailed(ModuleName);
1518 KnownModules[Path[0].first] = nullptr;
1519 ModuleBuildFailed = true;
1520 return ModuleLoadResult();
1523 // Okay, we've rebuilt and now loaded the module.
1527 case ASTReader::VersionMismatch:
1528 case ASTReader::ConfigurationMismatch:
1529 case ASTReader::HadErrors:
1530 ModuleLoader::HadFatalFailure = true;
1531 // FIXME: The ASTReader will already have complained, but can we shoehorn
1532 // that diagnostic information into a more useful form?
1533 KnownModules[Path[0].first] = nullptr;
1534 return ModuleLoadResult();
1536 case ASTReader::Failure:
1537 ModuleLoader::HadFatalFailure = true;
1538 // Already complained, but note now that we failed.
1539 KnownModules[Path[0].first] = nullptr;
1540 ModuleBuildFailed = true;
1541 return ModuleLoadResult();
1544 // Cache the result of this top-level module lookup for later.
1545 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1548 // If we never found the module, fail.
1550 return ModuleLoadResult();
1552 // Verify that the rest of the module path actually corresponds to
1554 if (Path.size() > 1) {
1555 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1556 StringRef Name = Path[I].first->getName();
1557 clang::Module *Sub = Module->findSubmodule(Name);
1560 // Attempt to perform typo correction to find a module name that works.
1561 SmallVector<StringRef, 2> Best;
1562 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1564 for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1565 JEnd = Module->submodule_end();
1567 unsigned ED = Name.edit_distance((*J)->Name,
1568 /*AllowReplacements=*/true,
1570 if (ED <= BestEditDistance) {
1571 if (ED < BestEditDistance) {
1573 BestEditDistance = ED;
1576 Best.push_back((*J)->Name);
1580 // If there was a clear winner, user it.
1581 if (Best.size() == 1) {
1582 getDiagnostics().Report(Path[I].second,
1583 diag::err_no_submodule_suggest)
1584 << Path[I].first << Module->getFullModuleName() << Best[0]
1585 << SourceRange(Path[0].second, Path[I-1].second)
1586 << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1589 Sub = Module->findSubmodule(Best[0]);
1594 // No submodule by this name. Complain, and don't look for further
1596 getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
1597 << Path[I].first << Module->getFullModuleName()
1598 << SourceRange(Path[0].second, Path[I-1].second);
1606 // Make the named module visible, if it's not already part of the module
1608 if (ModuleName != getLangOpts().CurrentModule) {
1609 if (!Module->IsFromModuleFile) {
1610 // We have an umbrella header or directory that doesn't actually include
1611 // all of the headers within the directory it covers. Complain about
1612 // this missing submodule and recover by forgetting that we ever saw
1614 // FIXME: Should we detect this at module load time? It seems fairly
1615 // expensive (and rare).
1616 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
1617 << Module->getFullModuleName()
1618 << SourceRange(Path.front().second, Path.back().second);
1620 return ModuleLoadResult(nullptr, true);
1623 // Check whether this module is available.
1624 clang::Module::Requirement Requirement;
1625 clang::Module::UnresolvedHeaderDirective MissingHeader;
1626 if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement,
1628 if (MissingHeader.FileNameLoc.isValid()) {
1629 getDiagnostics().Report(MissingHeader.FileNameLoc,
1630 diag::err_module_header_missing)
1631 << MissingHeader.IsUmbrella << MissingHeader.FileName;
1633 getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
1634 << Module->getFullModuleName()
1635 << Requirement.second << Requirement.first
1636 << SourceRange(Path.front().second, Path.back().second);
1638 LastModuleImportLoc = ImportLoc;
1639 LastModuleImportResult = ModuleLoadResult();
1640 return ModuleLoadResult();
1643 ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc);
1646 // Check for any configuration macros that have changed.
1647 clang::Module *TopModule = Module->getTopLevelModule();
1648 for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) {
1649 checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I],
1653 LastModuleImportLoc = ImportLoc;
1654 LastModuleImportResult = ModuleLoadResult(Module, false);
1655 return LastModuleImportResult;
1658 void CompilerInstance::makeModuleVisible(Module *Mod,
1659 Module::NameVisibilityKind Visibility,
1660 SourceLocation ImportLoc) {
1662 createModuleManager();
1666 ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc);
1669 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
1670 SourceLocation TriggerLoc) {
1671 if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty())
1674 createModuleManager();
1675 // Can't do anything if we don't have the module manager.
1678 // Get an existing global index. This loads it if not already
1680 ModuleManager->loadGlobalIndex();
1681 GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex();
1682 // If the global index doesn't exist, create it.
1683 if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
1684 hasPreprocessor()) {
1685 llvm::sys::fs::create_directories(
1686 getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1687 GlobalModuleIndex::writeIndex(
1688 getFileManager(), getPCHContainerReader(),
1689 getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1690 ModuleManager->resetForReload();
1691 ModuleManager->loadGlobalIndex();
1692 GlobalIndex = ModuleManager->getGlobalIndex();
1694 // For finding modules needing to be imported for fixit messages,
1695 // we need to make the global index cover all modules, so we do that here.
1696 if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
1697 ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
1698 bool RecreateIndex = false;
1699 for (ModuleMap::module_iterator I = MMap.module_begin(),
1700 E = MMap.module_end(); I != E; ++I) {
1701 Module *TheModule = I->second;
1702 const FileEntry *Entry = TheModule->getASTFile();
1704 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
1705 Path.push_back(std::make_pair(
1706 getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc));
1707 std::reverse(Path.begin(), Path.end());
1708 // Load a module as hidden. This also adds it to the global index.
1709 loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false);
1710 RecreateIndex = true;
1713 if (RecreateIndex) {
1714 GlobalModuleIndex::writeIndex(
1715 getFileManager(), getPCHContainerReader(),
1716 getPreprocessor().getHeaderSearchInfo().getModuleCachePath());
1717 ModuleManager->resetForReload();
1718 ModuleManager->loadGlobalIndex();
1719 GlobalIndex = ModuleManager->getGlobalIndex();
1721 HaveFullGlobalModuleIndex = true;
1726 // Check global module index for missing imports.
1728 CompilerInstance::lookupMissingImports(StringRef Name,
1729 SourceLocation TriggerLoc) {
1730 // Look for the symbol in non-imported modules, but only if an error
1731 // actually occurred.
1732 if (!buildingModule()) {
1733 // Load global module index, or retrieve a previously loaded one.
1734 GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
1737 // Only if we have a global index.
1739 GlobalModuleIndex::HitSet FoundModules;
1741 // Find the modules that reference the identifier.
1742 // Note that this only finds top-level modules.
1743 // We'll let diagnoseTypo find the actual declaration module.
1744 if (GlobalIndex->lookupIdentifier(Name, FoundModules))
1751 void CompilerInstance::resetAndLeakSema() { BuryPointer(takeSema()); }