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/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/Lex/HeaderSearch.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Lex/PTHManager.h"
22 #include "clang/Frontend/ChainedDiagnosticConsumer.h"
23 #include "clang/Frontend/FrontendAction.h"
24 #include "clang/Frontend/FrontendActions.h"
25 #include "clang/Frontend/FrontendDiagnostic.h"
26 #include "clang/Frontend/LogDiagnosticPrinter.h"
27 #include "clang/Frontend/TextDiagnosticPrinter.h"
28 #include "clang/Frontend/VerifyDiagnosticConsumer.h"
29 #include "clang/Frontend/Utils.h"
30 #include "clang/Serialization/ASTReader.h"
31 #include "clang/Sema/CodeCompleteConsumer.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Support/Timer.h"
37 #include "llvm/Support/Host.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/Program.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/system_error.h"
42 #include "llvm/Support/CrashRecoveryContext.h"
43 #include "llvm/Config/config.h"
45 // Support for FileLockManager
47 #include <sys/types.h>
57 using namespace clang;
59 CompilerInstance::CompilerInstance()
60 : Invocation(new CompilerInvocation()), ModuleManager(0) {
63 CompilerInstance::~CompilerInstance() {
66 void CompilerInstance::setInvocation(CompilerInvocation *Value) {
70 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
74 void CompilerInstance::setTarget(TargetInfo *Value) {
78 void CompilerInstance::setFileManager(FileManager *Value) {
82 void CompilerInstance::setSourceManager(SourceManager *Value) {
86 void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
88 void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
90 void CompilerInstance::setSema(Sema *S) {
94 void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
95 Consumer.reset(Value);
98 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
99 CompletionConsumer.reset(Value);
103 static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
104 unsigned argc, const char* const *argv,
105 DiagnosticsEngine &Diags) {
106 std::string ErrorInfo;
107 llvm::OwningPtr<raw_ostream> OS(
108 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
109 if (!ErrorInfo.empty()) {
110 Diags.Report(diag::err_fe_unable_to_open_logfile)
111 << DiagOpts.DumpBuildInformation << ErrorInfo;
115 (*OS) << "clang -cc1 command line arguments: ";
116 for (unsigned i = 0; i != argc; ++i)
117 (*OS) << argv[i] << ' ';
120 // Chain in a diagnostic client which will log the diagnostics.
121 DiagnosticConsumer *Logger =
122 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
123 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
126 static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
127 const CodeGenOptions *CodeGenOpts,
128 DiagnosticsEngine &Diags) {
129 std::string ErrorInfo;
130 bool OwnsStream = false;
131 raw_ostream *OS = &llvm::errs();
132 if (DiagOpts.DiagnosticLogFile != "-") {
133 // Create the output stream.
134 llvm::raw_fd_ostream *FileOS(
135 new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
136 ErrorInfo, llvm::raw_fd_ostream::F_Append));
137 if (!ErrorInfo.empty()) {
138 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
139 << DiagOpts.DumpBuildInformation << ErrorInfo;
141 FileOS->SetUnbuffered();
142 FileOS->SetUseAtomicWrites(true);
148 // Chain in the diagnostic client which will log the diagnostics.
149 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
152 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
153 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
156 void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
157 DiagnosticConsumer *Client,
158 bool ShouldOwnClient,
159 bool ShouldCloneClient) {
160 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
161 ShouldOwnClient, ShouldCloneClient,
165 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
166 CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
167 int Argc, const char* const *Argv,
168 DiagnosticConsumer *Client,
169 bool ShouldOwnClient,
170 bool ShouldCloneClient,
171 const CodeGenOptions *CodeGenOpts) {
172 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
173 llvm::IntrusiveRefCntPtr<DiagnosticsEngine>
174 Diags(new DiagnosticsEngine(DiagID));
176 // Create the diagnostic client for reporting errors or for
177 // implementing -verify.
179 if (ShouldCloneClient)
180 Diags->setClient(Client->clone(*Diags), ShouldOwnClient);
182 Diags->setClient(Client, ShouldOwnClient);
184 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
186 // Chain in -verify checker, if requested.
187 if (Opts.VerifyDiagnostics)
188 Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
190 // Chain in -diagnostic-log-file dumper, if requested.
191 if (!Opts.DiagnosticLogFile.empty())
192 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
194 if (!Opts.DumpBuildInformation.empty())
195 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
197 // Configure our handling of diagnostics.
198 ProcessWarningOptions(*Diags, Opts);
205 void CompilerInstance::createFileManager() {
206 FileMgr = new FileManager(getFileSystemOpts());
211 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
212 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
217 void CompilerInstance::createPreprocessor() {
218 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
220 // Create a PTH manager if we are using some form of a token cache.
221 PTHManager *PTHMgr = 0;
222 if (!PPOpts.TokenCache.empty())
223 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
225 // Create the Preprocessor.
226 HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager());
227 PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(),
228 getSourceManager(), *HeaderInfo, *this, PTHMgr,
229 /*OwnsHeaderSearch=*/true);
231 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
232 // That argument is used as the IdentifierInfoLookup argument to
233 // IdentifierTable's ctor.
235 PTHMgr->setPreprocessor(&*PP);
236 PP->setPTHManager(PTHMgr);
239 if (PPOpts.DetailedRecord)
240 PP->createPreprocessingRecord(
241 PPOpts.DetailedRecordIncludesNestedMacroExpansions);
243 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
245 // Set up the module path, including the hash for the
246 // module-creation options.
247 llvm::SmallString<256> SpecificModuleCache(
248 getHeaderSearchOpts().ModuleCachePath);
249 if (!getHeaderSearchOpts().DisableModuleHash)
250 llvm::sys::path::append(SpecificModuleCache,
251 getInvocation().getModuleHash());
252 PP->getHeaderSearchInfo().configureModules(SpecificModuleCache,
253 getPreprocessorOpts().ModuleBuildPath.empty()
255 : getPreprocessorOpts().ModuleBuildPath.back());
257 // Handle generating dependencies, if requested.
258 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
259 if (!DepOpts.OutputFile.empty())
260 AttachDependencyFileGen(*PP, DepOpts);
262 // Handle generating header include information, if requested.
263 if (DepOpts.ShowHeaderIncludes)
264 AttachHeaderIncludeGen(*PP);
265 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
266 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
267 if (OutputPath == "-")
269 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
270 /*ShowDepth=*/false);
276 void CompilerInstance::createASTContext() {
277 Preprocessor &PP = getPreprocessor();
278 Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
279 &getTarget(), PP.getIdentifierTable(),
280 PP.getSelectorTable(), PP.getBuiltinInfo(),
281 /*size_reserve=*/ 0);
286 void CompilerInstance::createPCHExternalASTSource(StringRef Path,
287 bool DisablePCHValidation,
288 bool DisableStatCache,
289 void *DeserializationListener){
290 llvm::OwningPtr<ExternalASTSource> Source;
291 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
292 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
293 DisablePCHValidation,
295 getPreprocessor(), getASTContext(),
296 DeserializationListener,
298 ModuleManager = static_cast<ASTReader*>(Source.get());
299 getASTContext().setExternalSource(Source);
303 CompilerInstance::createPCHExternalASTSource(StringRef Path,
304 const std::string &Sysroot,
305 bool DisablePCHValidation,
306 bool DisableStatCache,
309 void *DeserializationListener,
311 llvm::OwningPtr<ASTReader> Reader;
312 Reader.reset(new ASTReader(PP, Context,
313 Sysroot.empty() ? "" : Sysroot.c_str(),
314 DisablePCHValidation, DisableStatCache));
316 Reader->setDeserializationListener(
317 static_cast<ASTDeserializationListener *>(DeserializationListener));
318 switch (Reader->ReadAST(Path,
319 Preamble ? serialization::MK_Preamble
320 : serialization::MK_PCH)) {
321 case ASTReader::Success:
322 // Set the predefines buffer as suggested by the PCH reader. Typically, the
323 // predefines buffer will be empty.
324 PP.setPredefines(Reader->getSuggestedPredefines());
325 return Reader.take();
327 case ASTReader::Failure:
328 // Unrecoverable failure: don't even try to process the input file.
331 case ASTReader::IgnorePCH:
332 // No suitable PCH file could be found. Return an error.
341 static bool EnableCodeCompletion(Preprocessor &PP,
342 const std::string &Filename,
345 // Tell the source manager to chop off the given file at a specific
347 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
349 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
354 // Truncate the named file at the given line/column.
355 PP.SetCodeCompletionPoint(Entry, Line, Column);
359 void CompilerInstance::createCodeCompletionConsumer() {
360 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
361 if (!CompletionConsumer) {
362 CompletionConsumer.reset(
363 createCodeCompletionConsumer(getPreprocessor(),
364 Loc.FileName, Loc.Line, Loc.Column,
365 getFrontendOpts().ShowMacrosInCodeCompletion,
366 getFrontendOpts().ShowCodePatternsInCodeCompletion,
367 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
369 if (!CompletionConsumer)
371 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
372 Loc.Line, Loc.Column)) {
373 CompletionConsumer.reset();
377 if (CompletionConsumer->isOutputBinary() &&
378 llvm::sys::Program::ChangeStdoutToBinary()) {
379 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
380 CompletionConsumer.reset();
384 void CompilerInstance::createFrontendTimer() {
385 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
388 CodeCompleteConsumer *
389 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
390 const std::string &Filename,
394 bool ShowCodePatterns,
397 if (EnableCodeCompletion(PP, Filename, Line, Column))
400 // Set up the creation routine for code-completion.
401 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
405 void CompilerInstance::createSema(TranslationUnitKind TUKind,
406 CodeCompleteConsumer *CompletionConsumer) {
407 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
408 TUKind, CompletionConsumer));
413 void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
414 assert(OutFile.OS && "Attempt to add empty stream to output list!");
415 OutputFiles.push_back(OutFile);
418 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
419 for (std::list<OutputFile>::iterator
420 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
422 if (!it->TempFilename.empty()) {
425 llvm::sys::fs::remove(it->TempFilename, existed);
427 llvm::SmallString<128> NewOutFile(it->Filename);
429 // If '-working-directory' was passed, the output filename should be
431 FileMgr->FixupRelativePath(NewOutFile);
432 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
434 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
435 << it->TempFilename << it->Filename << ec.message();
438 llvm::sys::fs::remove(it->TempFilename, existed);
441 } else if (!it->Filename.empty() && EraseFiles)
442 llvm::sys::Path(it->Filename).eraseFromDisk();
448 llvm::raw_fd_ostream *
449 CompilerInstance::createDefaultOutputFile(bool Binary,
451 StringRef Extension) {
452 return createOutputFile(getFrontendOpts().OutputFile, Binary,
453 /*RemoveFileOnSignal=*/true, InFile, Extension);
456 llvm::raw_fd_ostream *
457 CompilerInstance::createOutputFile(StringRef OutputPath,
458 bool Binary, bool RemoveFileOnSignal,
462 std::string Error, OutputPathName, TempPathName;
463 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
470 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
471 << OutputPath << Error;
475 // Add the output file -- but don't try to remove "-", since this means we are
477 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
483 llvm::raw_fd_ostream *
484 CompilerInstance::createOutputFile(StringRef OutputPath,
487 bool RemoveFileOnSignal,
491 std::string *ResultPathName,
492 std::string *TempPathName) {
493 std::string OutFile, TempFile;
494 if (!OutputPath.empty()) {
495 OutFile = OutputPath;
496 } else if (InFile == "-") {
498 } else if (!Extension.empty()) {
499 llvm::sys::Path Path(InFile);
501 Path.appendSuffix(Extension);
502 OutFile = Path.str();
507 llvm::OwningPtr<llvm::raw_fd_ostream> OS;
510 if (UseTemporary && OutFile != "-") {
511 llvm::sys::Path OutPath(OutFile);
512 // Only create the temporary if we can actually write to OutPath, otherwise
513 // we want to fail early.
515 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
516 (OutPath.isRegularFile() && OutPath.canWrite())) {
517 // Create a temporary file.
518 llvm::SmallString<128> TempPath;
520 TempPath += "-%%%%%%%%";
522 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
523 /*makeAbsolute=*/false) == llvm::errc::success) {
524 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
525 OSFile = TempFile = TempPath.str();
533 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
534 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
539 // Make sure the out stream file gets removed if we crash.
540 if (RemoveFileOnSignal)
541 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
544 *ResultPathName = OutFile;
546 *TempPathName = TempFile;
551 // Initialization Utilities
553 bool CompilerInstance::InitializeSourceManager(StringRef InputFile) {
554 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
555 getSourceManager(), getFrontendOpts());
558 bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
559 DiagnosticsEngine &Diags,
560 FileManager &FileMgr,
561 SourceManager &SourceMgr,
562 const FrontendOptions &Opts) {
563 // Figure out where to get and map in the main file.
564 if (InputFile != "-") {
565 const FileEntry *File = FileMgr.getFile(InputFile);
567 Diags.Report(diag::err_fe_error_reading) << InputFile;
570 SourceMgr.createMainFileID(File);
572 llvm::OwningPtr<llvm::MemoryBuffer> SB;
573 if (llvm::MemoryBuffer::getSTDIN(SB)) {
574 // FIXME: Give ec.message() in this diag.
575 Diags.Report(diag::err_fe_error_reading_stdin);
578 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
579 SB->getBufferSize(), 0);
580 SourceMgr.createMainFileID(File);
581 SourceMgr.overrideFileContents(File, SB.take());
584 assert(!SourceMgr.getMainFileID().isInvalid() &&
585 "Couldn't establish MainFileID!");
589 // High-Level Operations
591 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
592 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
593 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
594 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
596 // FIXME: Take this as an argument, once all the APIs we used have moved to
597 // taking it as an input instead of hard-coding llvm::errs.
598 raw_ostream &OS = llvm::errs();
600 // Create the target instance.
601 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
605 // Inform the target of the language options.
607 // FIXME: We shouldn't need to do this, the target should be immutable once
608 // created. This complexity should be lifted elsewhere.
609 getTarget().setForcedLangOptions(getLangOpts());
611 // Validate/process some options.
612 if (getHeaderSearchOpts().Verbose)
613 OS << "clang -cc1 version " CLANG_VERSION_STRING
614 << " based upon " << PACKAGE_STRING
615 << " hosted on " << llvm::sys::getHostTriple() << "\n";
617 if (getFrontendOpts().ShowTimers)
618 createFrontendTimer();
620 if (getFrontendOpts().ShowStats)
621 llvm::EnableStatistics();
623 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
624 const std::string &InFile = getFrontendOpts().Inputs[i].second;
626 // Reset the ID tables if we are reusing the SourceManager.
627 if (hasSourceManager())
628 getSourceManager().clearIDTables();
630 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
636 if (getDiagnosticOpts().ShowCarets) {
637 // We can have multiple diagnostics sharing one diagnostic client.
638 // Get the total number of warnings/errors from the client.
639 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
640 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
643 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
644 if (NumWarnings && NumErrors)
647 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
648 if (NumWarnings || NumErrors)
649 OS << " generated.\n";
652 if (getFrontendOpts().ShowStats && hasFileManager()) {
653 getFileManager().PrintStats();
657 return !getDiagnostics().getClient()->getNumErrors();
660 /// \brief Determine the appropriate source input kind based on language
662 static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
668 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
669 return LangOpts.CPlusPlus? IK_CXX : IK_C;
673 struct CompileModuleData {
674 CompilerInstance &Instance;
675 GeneratePCHAction &CreateModuleAction;
679 /// \brief Helper function that executes the module-generating action under
680 /// a crash recovery context.
681 static void doCompileModule(void *UserData) {
682 CompileModuleData &Data = *reinterpret_cast<CompileModuleData *>(UserData);
683 Data.Instance.ExecuteAction(Data.CreateModuleAction);
687 /// \brief Class that manages the creation of a lock file to aid
688 /// implicit coordination between different processes.
690 /// The implicit coordination works by creating a ".lock" file alongside
691 /// the file that we're coordinating for, using the atomicity of the file
692 /// system to ensure that only a single process can create that ".lock" file.
693 /// When the lock file is removed, the owning process has finished the
695 class LockFileManager {
697 /// \brief Describes the state of a lock file.
699 /// \brief The lock file has been created and is owned by this instance
702 /// \brief The lock file already exists and is owned by some other
705 /// \brief An error occurred while trying to create or find the lock
711 llvm::SmallString<128> LockFileName;
712 llvm::SmallString<128> UniqueLockFileName;
714 llvm::Optional<std::pair<std::string, int> > Owner;
715 llvm::Optional<llvm::error_code> Error;
717 LockFileManager(const LockFileManager &);
718 LockFileManager &operator=(const LockFileManager &);
720 static llvm::Optional<std::pair<std::string, int> >
721 readLockFile(StringRef LockFileName);
723 static bool processStillExecuting(StringRef Hostname, int PID);
727 LockFileManager(StringRef FileName);
730 /// \brief Determine the state of the lock file.
731 LockFileState getState() const;
733 operator LockFileState() const { return getState(); }
735 /// \brief For a shared lock, wait until the owner releases the lock.
736 void waitForUnlock();
740 /// \brief Attempt to read the lock file with the given name, if it exists.
742 /// \param LockFileName The name of the lock file to read.
744 /// \returns The process ID of the process that owns this lock file
745 llvm::Optional<std::pair<std::string, int> >
746 LockFileManager::readLockFile(StringRef LockFileName) {
747 // Check whether the lock file exists. If not, clearly there's nothing
748 // to read, so we just return.
750 if (llvm::sys::fs::exists(LockFileName, Exists) || !Exists)
751 return llvm::Optional<std::pair<std::string, int> >();
753 // Read the owning host and PID out of the lock file. If it appears that the
754 // owning process is dead, the lock file is invalid.
756 std::string Hostname;
757 std::ifstream Input(LockFileName.str().c_str());
758 if (Input >> Hostname >> PID && PID > 0 &&
759 processStillExecuting(Hostname, PID))
760 return std::make_pair(Hostname, PID);
762 // Delete the lock file. It's invalid anyway.
764 llvm::sys::fs::remove(LockFileName, Existed);
765 return llvm::Optional<std::pair<std::string, int> >();
768 bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
770 char MyHostname[256];
773 gethostname(MyHostname, 255);
774 // Check whether the process is dead. If so, we're done.
775 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
782 LockFileManager::LockFileManager(StringRef FileName)
784 LockFileName = FileName;
785 LockFileName += ".lock";
787 // If the lock file already exists, don't bother to try to create our own
788 // lock file; it won't work anyway. Just figure out who owns this lock file.
789 if ((Owner = readLockFile(LockFileName)))
792 // Create a lock file that is unique to this instance.
793 UniqueLockFileName = LockFileName;
794 UniqueLockFileName += "-%%%%%%%%";
795 int UniqueLockFileID;
796 if (llvm::error_code EC
797 = llvm::sys::fs::unique_file(UniqueLockFileName.str(),
800 /*makeAbsolute=*/false)) {
805 // Write our process ID to our unique lock file.
807 llvm::raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
810 // FIXME: move getpid() call into LLVM
814 gethostname(hostname, 255);
815 Out << hostname << ' ' << getpid();
817 Out << "localhost 1";
821 if (Out.has_error()) {
822 // We failed to write out PID, so make up an excuse, remove the
823 // unique lock file, and fail.
824 Error = llvm::make_error_code(llvm::errc::no_space_on_device);
826 llvm::sys::fs::remove(UniqueLockFileName.c_str(), Existed);
831 // Create a hard link from the lock file name. If this succeeds, we're done.
833 = llvm::sys::fs::create_hard_link(UniqueLockFileName.str(),
835 if (EC == llvm::errc::success)
838 // Creating the hard link failed.
841 // The creation of the hard link may appear to fail, but if stat'ing the
842 // unique file returns a link count of 2, then we can still declare success.
844 if (stat(UniqueLockFileName.c_str(), &StatBuf) == 0 &&
845 StatBuf.st_nlink == 2)
849 // Someone else managed to create the lock file first. Wipe out our unique
850 // lock file (it's useless now) and read the process ID from the lock file.
852 llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
853 if ((Owner = readLockFile(LockFileName)))
856 // There is a lock file that nobody owns; try to clean it up and report
858 llvm::sys::fs::remove(LockFileName.str(), Existed);
862 LockFileManager::LockFileState LockFileManager::getState() const {
872 LockFileManager::~LockFileManager() {
873 if (getState() != LFS_Owned)
876 // Since we own the lock, remove the lock file and our own unique lock file.
878 llvm::sys::fs::remove(LockFileName.str(), Existed);
879 llvm::sys::fs::remove(UniqueLockFileName.str(), Existed);
882 void LockFileManager::waitForUnlock() {
883 if (getState() != LFS_Shared)
887 unsigned long Interval = 1;
889 struct timespec Interval;
891 Interval.tv_nsec = 1000000;
893 // Don't wait more than an hour for the file to appear.
894 const unsigned MaxSeconds = 3600;
896 // Sleep for the designated interval, to allow the owning process time to
898 // FIXME: Should we hook in to system APIs to get a notification when the
899 // lock file is deleted?
903 nanosleep(&Interval, NULL);
905 // If the file no longer exists, we're done.
907 if (!llvm::sys::fs::exists(LockFileName.str(), Exists) && !Exists)
910 if (!processStillExecuting((*Owner).first, (*Owner).second))
913 // Exponentially increase the time we wait for the lock to be removed.
917 Interval.tv_sec *= 2;
918 Interval.tv_nsec *= 2;
919 if (Interval.tv_nsec >= 1000000000) {
921 Interval.tv_nsec -= 1000000000;
926 Interval < MaxSeconds * 1000
928 Interval.tv_sec < (time_t)MaxSeconds
935 /// \brief Compile a module file for the given module name with the given
936 /// umbrella header, using the options provided by the importing compiler
938 static void compileModule(CompilerInstance &ImportingInstance,
939 StringRef ModuleName,
940 StringRef ModuleFileName,
941 StringRef UmbrellaHeader) {
942 LockFileManager Locked(ModuleFileName);
944 case LockFileManager::LFS_Error:
947 case LockFileManager::LFS_Owned:
948 // We're responsible for building the module ourselves. Do so below.
951 case LockFileManager::LFS_Shared:
952 // Someone else is responsible for building the module. Wait for them to
954 Locked.waitForUnlock();
958 // Construct a compiler invocation for creating this module.
959 llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation
960 (new CompilerInvocation(ImportingInstance.getInvocation()));
962 // For any options that aren't intended to affect how a module is built,
963 // reset them to their default values.
964 Invocation->getLangOpts().resetNonModularOptions();
965 Invocation->getPreprocessorOpts().resetNonModularOptions();
967 // Note that this module is part of the module build path, so that we
968 // can detect cycles in the module graph.
969 Invocation->getPreprocessorOpts().ModuleBuildPath.push_back(ModuleName);
971 // Set up the inputs/outputs so that we build the module from its umbrella
973 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
974 FrontendOpts.OutputFile = ModuleFileName.str();
975 FrontendOpts.DisableFree = false;
976 FrontendOpts.Inputs.clear();
977 FrontendOpts.Inputs.push_back(
978 std::make_pair(getSourceInputKindFromOptions(Invocation->getLangOpts()),
981 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
984 assert(ImportingInstance.getInvocation().getModuleHash() ==
985 Invocation->getModuleHash() && "Module hash mismatch!");
987 // Construct a compiler instance that will be used to actually create the
989 CompilerInstance Instance;
990 Instance.setInvocation(&*Invocation);
991 Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
992 &ImportingInstance.getDiagnosticClient(),
993 /*ShouldOwnClient=*/true,
994 /*ShouldCloneClient=*/true);
996 // Construct a module-generating action.
997 GeneratePCHAction CreateModuleAction(true);
999 // Execute the action to actually build the module in-place. Use a separate
1000 // thread so that we get a stack large enough.
1001 const unsigned ThreadStackSize = 8 << 20;
1002 llvm::CrashRecoveryContext CRC;
1003 CompileModuleData Data = { Instance, CreateModuleAction };
1004 CRC.RunSafelyOnThread(&doCompileModule, &Data, ThreadStackSize);
1007 ModuleKey CompilerInstance::loadModule(SourceLocation ImportLoc,
1008 IdentifierInfo &ModuleName,
1009 SourceLocation ModuleNameLoc) {
1010 // Determine what file we're searching from.
1011 SourceManager &SourceMgr = getSourceManager();
1012 SourceLocation ExpandedImportLoc = SourceMgr.getExpansionLoc(ImportLoc);
1013 const FileEntry *CurFile
1014 = SourceMgr.getFileEntryForID(SourceMgr.getFileID(ExpandedImportLoc));
1016 CurFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
1018 // Search for a module with the given name.
1019 std::string UmbrellaHeader;
1020 std::string ModuleFileName;
1021 const FileEntry *ModuleFile
1022 = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName(),
1026 bool BuildingModule = false;
1027 if (!ModuleFile && !UmbrellaHeader.empty()) {
1028 // We didn't find the module, but there is an umbrella header that
1029 // can be used to create the module file. Create a separate compilation
1032 // Check whether there is a cycle in the module graph.
1033 SmallVectorImpl<std::string> &ModuleBuildPath
1034 = getPreprocessorOpts().ModuleBuildPath;
1035 SmallVectorImpl<std::string>::iterator Pos
1036 = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(),
1037 ModuleName.getName());
1038 if (Pos != ModuleBuildPath.end()) {
1039 llvm::SmallString<256> CyclePath;
1040 for (; Pos != ModuleBuildPath.end(); ++Pos) {
1042 CyclePath += " -> ";
1044 CyclePath += ModuleName.getName();
1046 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
1047 << ModuleName.getName() << CyclePath;
1051 getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build)
1052 << ModuleName.getName();
1053 BuildingModule = true;
1054 compileModule(*this, ModuleName.getName(), ModuleFileName, UmbrellaHeader);
1055 ModuleFile = PP->getHeaderSearchInfo().lookupModule(ModuleName.getName());
1059 getDiagnostics().Report(ModuleNameLoc,
1060 BuildingModule? diag::err_module_not_built
1061 : diag::err_module_not_found)
1062 << ModuleName.getName()
1063 << SourceRange(ImportLoc, ModuleNameLoc);
1067 // If we don't already have an ASTReader, create one now.
1068 if (!ModuleManager) {
1069 if (!hasASTContext())
1072 std::string Sysroot = getHeaderSearchOpts().Sysroot;
1073 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1074 ModuleManager = new ASTReader(getPreprocessor(), *Context,
1075 Sysroot.empty() ? "" : Sysroot.c_str(),
1076 PPOpts.DisablePCHValidation,
1077 PPOpts.DisableStatCache);
1078 if (hasASTConsumer()) {
1079 ModuleManager->setDeserializationListener(
1080 getASTConsumer().GetASTDeserializationListener());
1081 getASTContext().setASTMutationListener(
1082 getASTConsumer().GetASTMutationListener());
1084 llvm::OwningPtr<ExternalASTSource> Source;
1085 Source.reset(ModuleManager);
1086 getASTContext().setExternalSource(Source);
1088 ModuleManager->InitializeSema(getSema());
1089 if (hasASTConsumer())
1090 ModuleManager->StartTranslationUnit(&getASTConsumer());
1093 // Try to load the module we found.
1094 switch (ModuleManager->ReadAST(ModuleFile->getName(),
1095 serialization::MK_Module)) {
1096 case ASTReader::Success:
1099 case ASTReader::IgnorePCH:
1100 // FIXME: The ASTReader will already have complained, but can we showhorn
1101 // that diagnostic information into a more useful form?
1104 case ASTReader::Failure:
1105 // Already complained.
1109 // FIXME: The module file's FileEntry makes a poor key indeed!
1110 return (ModuleKey)ModuleFile;