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/Sema/Sema.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/Basic/Diagnostic.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Basic/Version.h"
20 #include "clang/Lex/HeaderSearch.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "clang/Lex/PTHManager.h"
23 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
24 #include "clang/Frontend/FrontendAction.h"
25 #include "clang/Frontend/FrontendActions.h"
26 #include "clang/Frontend/FrontendDiagnostic.h"
27 #include "clang/Frontend/LogDiagnosticPrinter.h"
28 #include "clang/Frontend/SerializedDiagnosticPrinter.h"
29 #include "clang/Frontend/TextDiagnosticPrinter.h"
30 #include "clang/Frontend/VerifyDiagnosticConsumer.h"
31 #include "clang/Frontend/Utils.h"
32 #include "clang/Serialization/ASTReader.h"
33 #include "clang/Sema/CodeCompleteConsumer.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/Support/Timer.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/LockFileManager.h"
41 #include "llvm/Support/Path.h"
42 #include "llvm/Support/Program.h"
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/system_error.h"
45 #include "llvm/Support/CrashRecoveryContext.h"
46 #include "llvm/Config/config.h"
48 using namespace clang;
50 CompilerInstance::CompilerInstance()
51 : Invocation(new CompilerInvocation()), ModuleManager(0) {
54 CompilerInstance::~CompilerInstance() {
55 assert(OutputFiles.empty() && "Still output files in flight?");
58 void CompilerInstance::setInvocation(CompilerInvocation *Value) {
62 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
66 void CompilerInstance::setTarget(TargetInfo *Value) {
70 void CompilerInstance::setFileManager(FileManager *Value) {
74 void CompilerInstance::setSourceManager(SourceManager *Value) {
78 void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
80 void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
82 void CompilerInstance::setSema(Sema *S) {
86 void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
87 Consumer.reset(Value);
90 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
91 CompletionConsumer.reset(Value);
95 static void SetUpBuildDumpLog(DiagnosticOptions *DiagOpts,
96 unsigned argc, const char* const *argv,
97 DiagnosticsEngine &Diags) {
98 std::string ErrorInfo;
99 OwningPtr<raw_ostream> OS(
100 new llvm::raw_fd_ostream(DiagOpts->DumpBuildInformation.c_str(),ErrorInfo));
101 if (!ErrorInfo.empty()) {
102 Diags.Report(diag::err_fe_unable_to_open_logfile)
103 << DiagOpts->DumpBuildInformation << ErrorInfo;
107 (*OS) << "clang -cc1 command line arguments: ";
108 for (unsigned i = 0; i != argc; ++i)
109 (*OS) << argv[i] << ' ';
112 // Chain in a diagnostic client which will log the diagnostics.
113 DiagnosticConsumer *Logger =
114 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
115 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
118 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts,
119 const CodeGenOptions *CodeGenOpts,
120 DiagnosticsEngine &Diags) {
121 std::string ErrorInfo;
122 bool OwnsStream = false;
123 raw_ostream *OS = &llvm::errs();
124 if (DiagOpts->DiagnosticLogFile != "-") {
125 // Create the output stream.
126 llvm::raw_fd_ostream *FileOS(
127 new llvm::raw_fd_ostream(DiagOpts->DiagnosticLogFile.c_str(),
128 ErrorInfo, llvm::raw_fd_ostream::F_Append));
129 if (!ErrorInfo.empty()) {
130 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
131 << DiagOpts->DumpBuildInformation << ErrorInfo;
133 FileOS->SetUnbuffered();
134 FileOS->SetUseAtomicWrites(true);
140 // Chain in the diagnostic client which will log the diagnostics.
141 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
144 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
145 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
148 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts,
149 DiagnosticsEngine &Diags,
150 StringRef OutputFile) {
151 std::string ErrorInfo;
152 OwningPtr<llvm::raw_fd_ostream> OS;
153 OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo,
154 llvm::raw_fd_ostream::F_Binary));
156 if (!ErrorInfo.empty()) {
157 Diags.Report(diag::warn_fe_serialized_diag_failure)
158 << OutputFile << ErrorInfo;
162 DiagnosticConsumer *SerializedConsumer =
163 clang::serialized_diags::create(OS.take(), DiagOpts);
166 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(),
167 SerializedConsumer));
170 void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
171 DiagnosticConsumer *Client,
172 bool ShouldOwnClient,
173 bool ShouldCloneClient) {
174 Diagnostics = createDiagnostics(&getDiagnosticOpts(), Argc, Argv, Client,
175 ShouldOwnClient, ShouldCloneClient,
179 IntrusiveRefCntPtr<DiagnosticsEngine>
180 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts,
181 int Argc, const char* const *Argv,
182 DiagnosticConsumer *Client,
183 bool ShouldOwnClient,
184 bool ShouldCloneClient,
185 const CodeGenOptions *CodeGenOpts) {
186 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
187 IntrusiveRefCntPtr<DiagnosticsEngine>
188 Diags(new DiagnosticsEngine(DiagID, Opts));
190 // Create the diagnostic client for reporting errors or for
191 // implementing -verify.
193 if (ShouldCloneClient)
194 Diags->setClient(Client->clone(*Diags), ShouldOwnClient);
196 Diags->setClient(Client, ShouldOwnClient);
198 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
200 // Chain in -verify checker, if requested.
201 if (Opts->VerifyDiagnostics)
202 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
204 // Chain in -diagnostic-log-file dumper, if requested.
205 if (!Opts->DiagnosticLogFile.empty())
206 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
208 if (!Opts->DumpBuildInformation.empty())
209 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
211 if (!Opts->DiagnosticSerializationFile.empty())
212 SetupSerializedDiagnostics(Opts, *Diags,
213 Opts->DiagnosticSerializationFile);
215 // Configure our handling of diagnostics.
216 ProcessWarningOptions(*Diags, *Opts);
223 void CompilerInstance::createFileManager() {
224 FileMgr = new FileManager(getFileSystemOpts());
229 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
230 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
235 void CompilerInstance::createPreprocessor() {
236 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
238 // Create a PTH manager if we are using some form of a token cache.
239 PTHManager *PTHMgr = 0;
240 if (!PPOpts.TokenCache.empty())
241 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
243 // Create the Preprocessor.
244 HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(),
249 PP = new Preprocessor(&getPreprocessorOpts(),
250 getDiagnostics(), getLangOpts(), &getTarget(),
251 getSourceManager(), *HeaderInfo, *this, PTHMgr,
252 /*OwnsHeaderSearch=*/true);
254 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
255 // That argument is used as the IdentifierInfoLookup argument to
256 // IdentifierTable's ctor.
258 PTHMgr->setPreprocessor(&*PP);
259 PP->setPTHManager(PTHMgr);
262 if (PPOpts.DetailedRecord)
263 PP->createPreprocessingRecord(PPOpts.DetailedRecordConditionalDirectives);
265 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
267 // Set up the module path, including the hash for the
268 // module-creation options.
269 SmallString<256> SpecificModuleCache(
270 getHeaderSearchOpts().ModuleCachePath);
271 if (!getHeaderSearchOpts().DisableModuleHash)
272 llvm::sys::path::append(SpecificModuleCache,
273 getInvocation().getModuleHash());
274 PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
276 // Handle generating dependencies, if requested.
277 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
278 if (!DepOpts.OutputFile.empty())
279 AttachDependencyFileGen(*PP, DepOpts);
280 if (!DepOpts.DOTOutputFile.empty())
281 AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
282 getHeaderSearchOpts().Sysroot);
285 // Handle generating header include information, if requested.
286 if (DepOpts.ShowHeaderIncludes)
287 AttachHeaderIncludeGen(*PP);
288 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
289 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
290 if (OutputPath == "-")
292 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
293 /*ShowDepth=*/false);
299 void CompilerInstance::createASTContext() {
300 Preprocessor &PP = getPreprocessor();
301 Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
302 &getTarget(), PP.getIdentifierTable(),
303 PP.getSelectorTable(), PP.getBuiltinInfo(),
304 /*size_reserve=*/ 0);
309 void CompilerInstance::createPCHExternalASTSource(StringRef Path,
310 bool DisablePCHValidation,
311 bool AllowPCHWithCompilerErrors,
312 void *DeserializationListener){
313 OwningPtr<ExternalASTSource> Source;
314 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
315 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
316 DisablePCHValidation,
317 AllowPCHWithCompilerErrors,
318 getPreprocessor(), getASTContext(),
319 DeserializationListener,
321 ModuleManager = static_cast<ASTReader*>(Source.get());
322 getASTContext().setExternalSource(Source);
326 CompilerInstance::createPCHExternalASTSource(StringRef Path,
327 const std::string &Sysroot,
328 bool DisablePCHValidation,
329 bool AllowPCHWithCompilerErrors,
332 void *DeserializationListener,
334 OwningPtr<ASTReader> Reader;
335 Reader.reset(new ASTReader(PP, Context,
336 Sysroot.empty() ? "" : Sysroot.c_str(),
337 DisablePCHValidation,
338 AllowPCHWithCompilerErrors));
340 Reader->setDeserializationListener(
341 static_cast<ASTDeserializationListener *>(DeserializationListener));
342 switch (Reader->ReadAST(Path,
343 Preamble ? serialization::MK_Preamble
344 : serialization::MK_PCH,
345 ASTReader::ARR_None)) {
346 case ASTReader::Success:
347 // Set the predefines buffer as suggested by the PCH reader. Typically, the
348 // predefines buffer will be empty.
349 PP.setPredefines(Reader->getSuggestedPredefines());
350 return Reader.take();
352 case ASTReader::Failure:
353 // Unrecoverable failure: don't even try to process the input file.
356 case ASTReader::OutOfDate:
357 case ASTReader::VersionMismatch:
358 case ASTReader::ConfigurationMismatch:
359 case ASTReader::HadErrors:
360 // No suitable PCH file could be found. Return an error.
369 static bool EnableCodeCompletion(Preprocessor &PP,
370 const std::string &Filename,
373 // Tell the source manager to chop off the given file at a specific
375 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
377 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
382 // Truncate the named file at the given line/column.
383 PP.SetCodeCompletionPoint(Entry, Line, Column);
387 void CompilerInstance::createCodeCompletionConsumer() {
388 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
389 if (!CompletionConsumer) {
390 setCodeCompletionConsumer(
391 createCodeCompletionConsumer(getPreprocessor(),
392 Loc.FileName, Loc.Line, Loc.Column,
393 getFrontendOpts().CodeCompleteOpts,
395 if (!CompletionConsumer)
397 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
398 Loc.Line, Loc.Column)) {
399 setCodeCompletionConsumer(0);
403 if (CompletionConsumer->isOutputBinary() &&
404 llvm::sys::Program::ChangeStdoutToBinary()) {
405 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
406 setCodeCompletionConsumer(0);
410 void CompilerInstance::createFrontendTimer() {
411 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
414 CodeCompleteConsumer *
415 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
416 const std::string &Filename,
419 const CodeCompleteOptions &Opts,
421 if (EnableCodeCompletion(PP, Filename, Line, Column))
424 // Set up the creation routine for code-completion.
425 return new PrintingCodeCompleteConsumer(Opts, OS);
428 void CompilerInstance::createSema(TranslationUnitKind TUKind,
429 CodeCompleteConsumer *CompletionConsumer) {
430 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
431 TUKind, CompletionConsumer));
436 void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
437 assert(OutFile.OS && "Attempt to add empty stream to output list!");
438 OutputFiles.push_back(OutFile);
441 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
442 for (std::list<OutputFile>::iterator
443 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
445 if (!it->TempFilename.empty()) {
448 llvm::sys::fs::remove(it->TempFilename, existed);
450 SmallString<128> NewOutFile(it->Filename);
452 // If '-working-directory' was passed, the output filename should be
454 FileMgr->FixupRelativePath(NewOutFile);
455 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
457 getDiagnostics().Report(diag::err_unable_to_rename_temp)
458 << it->TempFilename << it->Filename << ec.message();
461 llvm::sys::fs::remove(it->TempFilename, existed);
464 } else if (!it->Filename.empty() && EraseFiles)
465 llvm::sys::Path(it->Filename).eraseFromDisk();
471 llvm::raw_fd_ostream *
472 CompilerInstance::createDefaultOutputFile(bool Binary,
474 StringRef Extension) {
475 return createOutputFile(getFrontendOpts().OutputFile, Binary,
476 /*RemoveFileOnSignal=*/true, InFile, Extension,
477 /*UseTemporary=*/true);
480 llvm::raw_fd_ostream *
481 CompilerInstance::createOutputFile(StringRef OutputPath,
482 bool Binary, bool RemoveFileOnSignal,
486 bool CreateMissingDirectories) {
487 std::string Error, OutputPathName, TempPathName;
488 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
492 CreateMissingDirectories,
496 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
497 << OutputPath << Error;
501 // Add the output file -- but don't try to remove "-", since this means we are
503 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
509 llvm::raw_fd_ostream *
510 CompilerInstance::createOutputFile(StringRef OutputPath,
513 bool RemoveFileOnSignal,
517 bool CreateMissingDirectories,
518 std::string *ResultPathName,
519 std::string *TempPathName) {
520 assert((!CreateMissingDirectories || UseTemporary) &&
521 "CreateMissingDirectories is only allowed when using temporary files");
523 std::string OutFile, TempFile;
524 if (!OutputPath.empty()) {
525 OutFile = OutputPath;
526 } else if (InFile == "-") {
528 } else if (!Extension.empty()) {
529 llvm::sys::Path Path(InFile);
531 Path.appendSuffix(Extension);
532 OutFile = Path.str();
537 OwningPtr<llvm::raw_fd_ostream> OS;
540 if (UseTemporary && OutFile != "-") {
541 // Only create the temporary if the parent directory exists (or create
542 // missing directories is true) and we can actually write to OutPath,
543 // otherwise we want to fail early.
544 SmallString<256> AbsPath(OutputPath);
545 llvm::sys::fs::make_absolute(AbsPath);
546 llvm::sys::Path OutPath(AbsPath);
547 bool ParentExists = false;
548 if (llvm::sys::fs::exists(llvm::sys::path::parent_path(AbsPath.str()),
550 ParentExists = false;
552 if ((CreateMissingDirectories || ParentExists) &&
553 ((llvm::sys::fs::exists(AbsPath.str(), Exists) || !Exists) ||
554 (OutPath.isRegularFile() && OutPath.canWrite()))) {
555 // Create a temporary file.
556 SmallString<128> TempPath;
558 TempPath += "-%%%%%%%%";
560 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
561 /*makeAbsolute=*/false, 0664)
562 == llvm::errc::success) {
563 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
564 OSFile = TempFile = TempPath.str();
572 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
573 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
578 // Make sure the out stream file gets removed if we crash.
579 if (RemoveFileOnSignal)
580 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
583 *ResultPathName = OutFile;
585 *TempPathName = TempFile;
590 // Initialization Utilities
592 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
593 return InitializeSourceManager(Input, getDiagnostics(),
594 getFileManager(), getSourceManager(),
598 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
599 DiagnosticsEngine &Diags,
600 FileManager &FileMgr,
601 SourceManager &SourceMgr,
602 const FrontendOptions &Opts) {
603 SrcMgr::CharacteristicKind
604 Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
606 if (Input.isBuffer()) {
607 SourceMgr.createMainFileIDForMemBuffer(Input.getBuffer(), Kind);
608 assert(!SourceMgr.getMainFileID().isInvalid() &&
609 "Couldn't establish MainFileID!");
613 StringRef InputFile = Input.getFile();
615 // Figure out where to get and map in the main file.
616 if (InputFile != "-") {
617 const FileEntry *File = FileMgr.getFile(InputFile);
619 Diags.Report(diag::err_fe_error_reading) << InputFile;
622 SourceMgr.createMainFileID(File, Kind);
624 // The natural SourceManager infrastructure can't currently handle named
625 // pipes, but we would at least like to accept them for the main
626 // file. Detect them here, read them with the more generic MemoryBuffer
627 // function, and simply override their contents as we do for STDIN.
628 if (File->isNamedPipe()) {
629 OwningPtr<llvm::MemoryBuffer> MB;
630 if (llvm::error_code ec = llvm::MemoryBuffer::getFile(InputFile, MB)) {
631 Diags.Report(diag::err_cannot_open_file) << InputFile << ec.message();
634 SourceMgr.overrideFileContents(File, MB.take());
637 OwningPtr<llvm::MemoryBuffer> SB;
638 if (llvm::MemoryBuffer::getSTDIN(SB)) {
639 // FIXME: Give ec.message() in this diag.
640 Diags.Report(diag::err_fe_error_reading_stdin);
643 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
644 SB->getBufferSize(), 0);
645 SourceMgr.createMainFileID(File, Kind);
646 SourceMgr.overrideFileContents(File, SB.take());
649 assert(!SourceMgr.getMainFileID().isInvalid() &&
650 "Couldn't establish MainFileID!");
654 // High-Level Operations
656 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
657 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
658 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
659 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
661 // FIXME: Take this as an argument, once all the APIs we used have moved to
662 // taking it as an input instead of hard-coding llvm::errs.
663 raw_ostream &OS = llvm::errs();
665 // Create the target instance.
666 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
670 // Inform the target of the language options.
672 // FIXME: We shouldn't need to do this, the target should be immutable once
673 // created. This complexity should be lifted elsewhere.
674 getTarget().setForcedLangOptions(getLangOpts());
676 // rewriter project will change target built-in bool type from its default.
677 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
678 getTarget().noSignedCharForObjCBool();
680 // Validate/process some options.
681 if (getHeaderSearchOpts().Verbose)
682 OS << "clang -cc1 version " CLANG_VERSION_STRING
683 << " based upon " << PACKAGE_STRING
684 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
686 if (getFrontendOpts().ShowTimers)
687 createFrontendTimer();
689 if (getFrontendOpts().ShowStats)
690 llvm::EnableStatistics();
692 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
693 // Reset the ID tables if we are reusing the SourceManager.
694 if (hasSourceManager())
695 getSourceManager().clearIDTables();
697 if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
703 // Notify the diagnostic client that all files were processed.
704 getDiagnostics().getClient()->finish();
706 if (getDiagnosticOpts().ShowCarets) {
707 // We can have multiple diagnostics sharing one diagnostic client.
708 // Get the total number of warnings/errors from the client.
709 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
710 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
713 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
714 if (NumWarnings && NumErrors)
717 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
718 if (NumWarnings || NumErrors)
719 OS << " generated.\n";
722 if (getFrontendOpts().ShowStats && hasFileManager()) {
723 getFileManager().PrintStats();
727 return !getDiagnostics().getClient()->getNumErrors();
730 /// \brief Determine the appropriate source input kind based on language
732 static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
738 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
739 return LangOpts.CPlusPlus? IK_CXX : IK_C;
743 struct CompileModuleMapData {
744 CompilerInstance &Instance;
745 GenerateModuleAction &CreateModuleAction;
749 /// \brief Helper function that executes the module-generating action under
750 /// a crash recovery context.
751 static void doCompileMapModule(void *UserData) {
752 CompileModuleMapData &Data
753 = *reinterpret_cast<CompileModuleMapData *>(UserData);
754 Data.Instance.ExecuteAction(Data.CreateModuleAction);
757 /// \brief Compile a module file for the given module, using the options
758 /// provided by the importing compiler instance.
759 static void compileModule(CompilerInstance &ImportingInstance,
761 StringRef ModuleFileName) {
762 llvm::LockFileManager Locked(ModuleFileName);
764 case llvm::LockFileManager::LFS_Error:
767 case llvm::LockFileManager::LFS_Owned:
768 // We're responsible for building the module ourselves. Do so below.
771 case llvm::LockFileManager::LFS_Shared:
772 // Someone else is responsible for building the module. Wait for them to
774 Locked.waitForUnlock();
779 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
781 // Construct a compiler invocation for creating this module.
782 IntrusiveRefCntPtr<CompilerInvocation> Invocation
783 (new CompilerInvocation(ImportingInstance.getInvocation()));
785 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
787 // For any options that aren't intended to affect how a module is built,
788 // reset them to their default values.
789 Invocation->getLangOpts()->resetNonModularOptions();
790 PPOpts.resetNonModularOptions();
792 // Note the name of the module we're building.
793 Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
795 // Note that this module is part of the module build path, so that we
796 // can detect cycles in the module graph.
797 PPOpts.ModuleBuildPath.push_back(Module->getTopLevelModuleName());
799 // If there is a module map file, build the module using the module map.
800 // Set up the inputs/outputs so that we build the module from its umbrella
802 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
803 FrontendOpts.OutputFile = ModuleFileName.str();
804 FrontendOpts.DisableFree = false;
805 FrontendOpts.Inputs.clear();
806 InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
808 // Get or create the module map that we'll use to build this module.
809 SmallString<128> TempModuleMapFileName;
810 if (const FileEntry *ModuleMapFile
811 = ModMap.getContainingModuleMapFile(Module)) {
812 // Use the module map where this module resides.
813 FrontendOpts.Inputs.push_back(FrontendInputFile(ModuleMapFile->getName(),
816 // Create a temporary module map file.
817 TempModuleMapFileName = Module->Name;
818 TempModuleMapFileName += "-%%%%%%%%.map";
820 if (llvm::sys::fs::unique_file(TempModuleMapFileName.str(), FD,
821 TempModuleMapFileName,
822 /*makeAbsolute=*/true)
823 != llvm::errc::success) {
824 ImportingInstance.getDiagnostics().Report(diag::err_module_map_temp_file)
825 << TempModuleMapFileName;
828 // Print the module map to this file.
829 llvm::raw_fd_ostream OS(FD, /*shouldClose=*/true);
831 FrontendOpts.Inputs.push_back(
832 FrontendInputFile(TempModuleMapFileName.str().str(), IK));
835 // Don't free the remapped file buffers; they are owned by our caller.
836 PPOpts.RetainRemappedFileBuffers = true;
838 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
839 assert(ImportingInstance.getInvocation().getModuleHash() ==
840 Invocation->getModuleHash() && "Module hash mismatch!");
842 // Construct a compiler instance that will be used to actually create the
844 CompilerInstance Instance;
845 Instance.setInvocation(&*Invocation);
846 Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
847 &ImportingInstance.getDiagnosticClient(),
848 /*ShouldOwnClient=*/true,
849 /*ShouldCloneClient=*/true);
851 // Construct a module-generating action.
852 GenerateModuleAction CreateModuleAction;
854 // Execute the action to actually build the module in-place. Use a separate
855 // thread so that we get a stack large enough.
856 const unsigned ThreadStackSize = 8 << 20;
857 llvm::CrashRecoveryContext CRC;
858 CompileModuleMapData Data = { Instance, CreateModuleAction };
859 CRC.RunSafelyOnThread(&doCompileMapModule, &Data, ThreadStackSize);
861 // Delete the temporary module map file.
862 // FIXME: Even though we're executing under crash protection, it would still
863 // be nice to do this with RemoveFileOnSignal when we can. However, that
864 // doesn't make sense for all clients, so clean this up manually.
865 Instance.clearOutputFiles(/*EraseFiles=*/true);
866 if (!TempModuleMapFileName.empty())
867 llvm::sys::Path(TempModuleMapFileName).eraseFromDisk();
870 Module *CompilerInstance::loadModule(SourceLocation ImportLoc,
872 Module::NameVisibilityKind Visibility,
873 bool IsInclusionDirective) {
874 // If we've already handled this import, just return the cached result.
875 // This one-element cache is important to eliminate redundant diagnostics
876 // when both the preprocessor and parser see the same import declaration.
877 if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
878 // Make the named module visible.
879 if (LastModuleImportResult)
880 ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility);
881 return LastModuleImportResult;
884 // Determine what file we're searching from.
885 StringRef ModuleName = Path[0].first->getName();
886 SourceLocation ModuleNameLoc = Path[0].second;
888 clang::Module *Module = 0;
890 // If we don't already have information on this module, load the module now.
891 llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
892 = KnownModules.find(Path[0].first);
893 if (Known != KnownModules.end()) {
894 // Retrieve the cached top-level module.
895 Module = Known->second;
896 } else if (ModuleName == getLangOpts().CurrentModule) {
897 // This is the module we're building.
898 Module = PP->getHeaderSearchInfo().getModuleMap().findModule(ModuleName);
899 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
901 // Search for a module with the given name.
902 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
903 std::string ModuleFileName;
905 ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(Module);
907 ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(ModuleName);
909 if (ModuleFileName.empty()) {
910 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
912 << SourceRange(ImportLoc, ModuleNameLoc);
913 LastModuleImportLoc = ImportLoc;
914 LastModuleImportResult = 0;
918 const FileEntry *ModuleFile
919 = getFileManager().getFile(ModuleFileName, /*OpenFile=*/false,
920 /*CacheFailure=*/false);
921 bool BuildingModule = false;
922 if (!ModuleFile && Module) {
923 // The module is not cached, but we have a module map from which we can
926 // Check whether there is a cycle in the module graph.
927 SmallVectorImpl<std::string> &ModuleBuildPath
928 = getPreprocessorOpts().ModuleBuildPath;
929 SmallVectorImpl<std::string>::iterator Pos
930 = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(), ModuleName);
931 if (Pos != ModuleBuildPath.end()) {
932 SmallString<256> CyclePath;
933 for (; Pos != ModuleBuildPath.end(); ++Pos) {
937 CyclePath += ModuleName;
939 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
940 << ModuleName << CyclePath;
944 getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build)
946 BuildingModule = true;
947 compileModule(*this, Module, ModuleFileName);
948 ModuleFile = FileMgr->getFile(ModuleFileName);
952 getDiagnostics().Report(ModuleNameLoc,
953 BuildingModule? diag::err_module_not_built
954 : diag::err_module_not_found)
956 << SourceRange(ImportLoc, ModuleNameLoc);
960 // If we don't already have an ASTReader, create one now.
961 if (!ModuleManager) {
962 if (!hasASTContext())
965 std::string Sysroot = getHeaderSearchOpts().Sysroot;
966 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
967 ModuleManager = new ASTReader(getPreprocessor(), *Context,
968 Sysroot.empty() ? "" : Sysroot.c_str(),
969 PPOpts.DisablePCHValidation);
970 if (hasASTConsumer()) {
971 ModuleManager->setDeserializationListener(
972 getASTConsumer().GetASTDeserializationListener());
973 getASTContext().setASTMutationListener(
974 getASTConsumer().GetASTMutationListener());
975 getPreprocessor().setPPMutationListener(
976 getASTConsumer().GetPPMutationListener());
978 OwningPtr<ExternalASTSource> Source;
979 Source.reset(ModuleManager);
980 getASTContext().setExternalSource(Source);
982 ModuleManager->InitializeSema(getSema());
983 if (hasASTConsumer())
984 ModuleManager->StartTranslationUnit(&getASTConsumer());
987 // Try to load the module we found.
988 unsigned ARRFlags = ASTReader::ARR_None;
990 ARRFlags |= ASTReader::ARR_OutOfDate;
991 switch (ModuleManager->ReadAST(ModuleFile->getName(),
992 serialization::MK_Module,
994 case ASTReader::Success:
997 case ASTReader::OutOfDate: {
998 // The module file is out-of-date. Rebuild it.
999 getFileManager().invalidateCache(ModuleFile);
1001 llvm::sys::fs::remove(ModuleFileName, Existed);
1002 compileModule(*this, Module, ModuleFileName);
1004 // Try loading the module again.
1005 ModuleFile = FileMgr->getFile(ModuleFileName);
1007 ModuleManager->ReadAST(ModuleFileName,
1008 serialization::MK_Module,
1009 ASTReader::ARR_None) != ASTReader::Success) {
1010 KnownModules[Path[0].first] = 0;
1014 // Okay, we've rebuilt and now loaded the module.
1018 case ASTReader::VersionMismatch:
1019 case ASTReader::ConfigurationMismatch:
1020 case ASTReader::HadErrors:
1021 // FIXME: The ASTReader will already have complained, but can we showhorn
1022 // that diagnostic information into a more useful form?
1023 KnownModules[Path[0].first] = 0;
1026 case ASTReader::Failure:
1027 // Already complained, but note now that we failed.
1028 KnownModules[Path[0].first] = 0;
1033 // If we loaded the module directly, without finding a module map first,
1034 // we'll have loaded the module's information from the module itself.
1035 Module = PP->getHeaderSearchInfo().getModuleMap()
1036 .findModule((Path[0].first->getName()));
1040 Module->setASTFile(ModuleFile);
1042 // Cache the result of this top-level module lookup for later.
1043 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
1046 // If we never found the module, fail.
1050 // Verify that the rest of the module path actually corresponds to
1052 if (Path.size() > 1) {
1053 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1054 StringRef Name = Path[I].first->getName();
1055 clang::Module *Sub = Module->findSubmodule(Name);
1058 // Attempt to perform typo correction to find a module name that works.
1059 llvm::SmallVector<StringRef, 2> Best;
1060 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1062 for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1063 JEnd = Module->submodule_end();
1065 unsigned ED = Name.edit_distance((*J)->Name,
1066 /*AllowReplacements=*/true,
1068 if (ED <= BestEditDistance) {
1069 if (ED < BestEditDistance) {
1071 BestEditDistance = ED;
1074 Best.push_back((*J)->Name);
1078 // If there was a clear winner, user it.
1079 if (Best.size() == 1) {
1080 getDiagnostics().Report(Path[I].second,
1081 diag::err_no_submodule_suggest)
1082 << Path[I].first << Module->getFullModuleName() << Best[0]
1083 << SourceRange(Path[0].second, Path[I-1].second)
1084 << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1087 Sub = Module->findSubmodule(Best[0]);
1092 // No submodule by this name. Complain, and don't look for further
1094 getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
1095 << Path[I].first << Module->getFullModuleName()
1096 << SourceRange(Path[0].second, Path[I-1].second);
1104 // Make the named module visible, if it's not already part of the module
1106 if (ModuleName != getLangOpts().CurrentModule) {
1107 if (!Module->IsFromModuleFile) {
1108 // We have an umbrella header or directory that doesn't actually include
1109 // all of the headers within the directory it covers. Complain about
1110 // this missing submodule and recover by forgetting that we ever saw
1112 // FIXME: Should we detect this at module load time? It seems fairly
1113 // expensive (and rare).
1114 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
1115 << Module->getFullModuleName()
1116 << SourceRange(Path.front().second, Path.back().second);
1121 // Check whether this module is available.
1123 if (!Module->isAvailable(getLangOpts(), getTarget(), Feature)) {
1124 getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
1125 << Module->getFullModuleName()
1127 << SourceRange(Path.front().second, Path.back().second);
1128 LastModuleImportLoc = ImportLoc;
1129 LastModuleImportResult = 0;
1133 ModuleManager->makeModuleVisible(Module, Visibility);
1136 // If this module import was due to an inclusion directive, create an
1137 // implicit import declaration to capture it in the AST.
1138 if (IsInclusionDirective && hasASTContext()) {
1139 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
1140 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
1142 Path.back().second);
1143 TU->addDecl(ImportD);
1145 Consumer->HandleImplicitImportDecl(ImportD);
1148 LastModuleImportLoc = ImportLoc;
1149 LastModuleImportResult = Module;