xref: /llvm-project/clang/lib/Frontend/CompilerInstance.cpp (revision c9ad5fb604ad56591a445c55fb955faf970f43df)
1 //===--- CompilerInstance.cpp ---------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
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"
47 
48 using namespace clang;
49 
50 CompilerInstance::CompilerInstance()
51   : Invocation(new CompilerInvocation()), ModuleManager(0) {
52 }
53 
54 CompilerInstance::~CompilerInstance() {
55   assert(OutputFiles.empty() && "Still output files in flight?");
56 }
57 
58 void CompilerInstance::setInvocation(CompilerInvocation *Value) {
59   Invocation = Value;
60 }
61 
62 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) {
63   Diagnostics = Value;
64 }
65 
66 void CompilerInstance::setTarget(TargetInfo *Value) {
67   Target = Value;
68 }
69 
70 void CompilerInstance::setFileManager(FileManager *Value) {
71   FileMgr = Value;
72 }
73 
74 void CompilerInstance::setSourceManager(SourceManager *Value) {
75   SourceMgr = Value;
76 }
77 
78 void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
79 
80 void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
81 
82 void CompilerInstance::setSema(Sema *S) {
83   TheSema.reset(S);
84 }
85 
86 void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
87   Consumer.reset(Value);
88 }
89 
90 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
91   CompletionConsumer.reset(Value);
92   getFrontendOpts().SkipFunctionBodies = Value != 0;
93 }
94 
95 // Diagnostics
96 static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
97                               unsigned argc, const char* const *argv,
98                               DiagnosticsEngine &Diags) {
99   std::string ErrorInfo;
100   OwningPtr<raw_ostream> OS(
101     new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
102   if (!ErrorInfo.empty()) {
103     Diags.Report(diag::err_fe_unable_to_open_logfile)
104                  << DiagOpts.DumpBuildInformation << ErrorInfo;
105     return;
106   }
107 
108   (*OS) << "clang -cc1 command line arguments: ";
109   for (unsigned i = 0; i != argc; ++i)
110     (*OS) << argv[i] << ' ';
111   (*OS) << '\n';
112 
113   // Chain in a diagnostic client which will log the diagnostics.
114   DiagnosticConsumer *Logger =
115     new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
116   Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
117 }
118 
119 static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
120                                const CodeGenOptions *CodeGenOpts,
121                                DiagnosticsEngine &Diags) {
122   std::string ErrorInfo;
123   bool OwnsStream = false;
124   raw_ostream *OS = &llvm::errs();
125   if (DiagOpts.DiagnosticLogFile != "-") {
126     // Create the output stream.
127     llvm::raw_fd_ostream *FileOS(
128       new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
129                                ErrorInfo, llvm::raw_fd_ostream::F_Append));
130     if (!ErrorInfo.empty()) {
131       Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
132         << DiagOpts.DumpBuildInformation << ErrorInfo;
133     } else {
134       FileOS->SetUnbuffered();
135       FileOS->SetUseAtomicWrites(true);
136       OS = FileOS;
137       OwnsStream = true;
138     }
139   }
140 
141   // Chain in the diagnostic client which will log the diagnostics.
142   LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
143                                                           OwnsStream);
144   if (CodeGenOpts)
145     Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
146   Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger));
147 }
148 
149 static void SetupSerializedDiagnostics(const DiagnosticOptions &DiagOpts,
150                                        DiagnosticsEngine &Diags,
151                                        StringRef OutputFile) {
152   std::string ErrorInfo;
153   OwningPtr<llvm::raw_fd_ostream> OS;
154   OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo,
155                                     llvm::raw_fd_ostream::F_Binary));
156 
157   if (!ErrorInfo.empty()) {
158     Diags.Report(diag::warn_fe_serialized_diag_failure)
159       << OutputFile << ErrorInfo;
160     return;
161   }
162 
163   DiagnosticConsumer *SerializedConsumer =
164     clang::serialized_diags::create(OS.take(), DiagOpts);
165 
166 
167   Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(),
168                                                 SerializedConsumer));
169 }
170 
171 void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
172                                          DiagnosticConsumer *Client,
173                                          bool ShouldOwnClient,
174                                          bool ShouldCloneClient) {
175   Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
176                                   ShouldOwnClient, ShouldCloneClient,
177                                   &getCodeGenOpts());
178 }
179 
180 IntrusiveRefCntPtr<DiagnosticsEngine>
181 CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
182                                     int Argc, const char* const *Argv,
183                                     DiagnosticConsumer *Client,
184                                     bool ShouldOwnClient,
185                                     bool ShouldCloneClient,
186                                     const CodeGenOptions *CodeGenOpts) {
187   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
188   IntrusiveRefCntPtr<DiagnosticsEngine>
189       Diags(new DiagnosticsEngine(DiagID));
190 
191   // Create the diagnostic client for reporting errors or for
192   // implementing -verify.
193   if (Client) {
194     if (ShouldCloneClient)
195       Diags->setClient(Client->clone(*Diags), ShouldOwnClient);
196     else
197       Diags->setClient(Client, ShouldOwnClient);
198   } else
199     Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
200 
201   // Chain in -verify checker, if requested.
202   if (Opts.VerifyDiagnostics)
203     Diags->setClient(new VerifyDiagnosticConsumer(*Diags));
204 
205   // Chain in -diagnostic-log-file dumper, if requested.
206   if (!Opts.DiagnosticLogFile.empty())
207     SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
208 
209   if (!Opts.DumpBuildInformation.empty())
210     SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
211 
212   if (!Opts.DiagnosticSerializationFile.empty())
213     SetupSerializedDiagnostics(Opts, *Diags,
214                                Opts.DiagnosticSerializationFile);
215 
216   // Configure our handling of diagnostics.
217   ProcessWarningOptions(*Diags, Opts);
218 
219   return Diags;
220 }
221 
222 // File Manager
223 
224 void CompilerInstance::createFileManager() {
225   FileMgr = new FileManager(getFileSystemOpts());
226 }
227 
228 // Source Manager
229 
230 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
231   SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
232 }
233 
234 // Preprocessor
235 
236 void CompilerInstance::createPreprocessor() {
237   const PreprocessorOptions &PPOpts = getPreprocessorOpts();
238 
239   // Create a PTH manager if we are using some form of a token cache.
240   PTHManager *PTHMgr = 0;
241   if (!PPOpts.TokenCache.empty())
242     PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics());
243 
244   // Create the Preprocessor.
245   HeaderSearch *HeaderInfo = new HeaderSearch(getFileManager(),
246                                               getDiagnostics(),
247                                               getLangOpts(),
248                                               &getTarget());
249   PP = new Preprocessor(getDiagnostics(), getLangOpts(), &getTarget(),
250                         getSourceManager(), *HeaderInfo, *this, PTHMgr,
251                         /*OwnsHeaderSearch=*/true);
252 
253   // Note that this is different then passing PTHMgr to Preprocessor's ctor.
254   // That argument is used as the IdentifierInfoLookup argument to
255   // IdentifierTable's ctor.
256   if (PTHMgr) {
257     PTHMgr->setPreprocessor(&*PP);
258     PP->setPTHManager(PTHMgr);
259   }
260 
261   if (PPOpts.DetailedRecord)
262     PP->createPreprocessingRecord(PPOpts.DetailedRecordConditionalDirectives);
263 
264   InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts());
265 
266   // Set up the module path, including the hash for the
267   // module-creation options.
268   SmallString<256> SpecificModuleCache(
269                            getHeaderSearchOpts().ModuleCachePath);
270   if (!getHeaderSearchOpts().DisableModuleHash)
271     llvm::sys::path::append(SpecificModuleCache,
272                             getInvocation().getModuleHash());
273   PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache);
274 
275   // Handle generating dependencies, if requested.
276   const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
277   if (!DepOpts.OutputFile.empty())
278     AttachDependencyFileGen(*PP, DepOpts);
279   if (!DepOpts.DOTOutputFile.empty())
280     AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
281                              getHeaderSearchOpts().Sysroot);
282 
283 
284   // Handle generating header include information, if requested.
285   if (DepOpts.ShowHeaderIncludes)
286     AttachHeaderIncludeGen(*PP);
287   if (!DepOpts.HeaderIncludeOutputFile.empty()) {
288     StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
289     if (OutputPath == "-")
290       OutputPath = "";
291     AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
292                            /*ShowDepth=*/false);
293   }
294 }
295 
296 // ASTContext
297 
298 void CompilerInstance::createASTContext() {
299   Preprocessor &PP = getPreprocessor();
300   Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
301                            &getTarget(), PP.getIdentifierTable(),
302                            PP.getSelectorTable(), PP.getBuiltinInfo(),
303                            /*size_reserve=*/ 0);
304 }
305 
306 // ExternalASTSource
307 
308 void CompilerInstance::createPCHExternalASTSource(StringRef Path,
309                                                   bool DisablePCHValidation,
310                                                   bool DisableStatCache,
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                                           DisableStatCache,
318                                           AllowPCHWithCompilerErrors,
319                                           getPreprocessor(), getASTContext(),
320                                           DeserializationListener,
321                                           Preamble));
322   ModuleManager = static_cast<ASTReader*>(Source.get());
323   getASTContext().setExternalSource(Source);
324 }
325 
326 ExternalASTSource *
327 CompilerInstance::createPCHExternalASTSource(StringRef Path,
328                                              const std::string &Sysroot,
329                                              bool DisablePCHValidation,
330                                              bool DisableStatCache,
331                                              bool AllowPCHWithCompilerErrors,
332                                              Preprocessor &PP,
333                                              ASTContext &Context,
334                                              void *DeserializationListener,
335                                              bool Preamble) {
336   OwningPtr<ASTReader> Reader;
337   Reader.reset(new ASTReader(PP, Context,
338                              Sysroot.empty() ? "" : Sysroot.c_str(),
339                              DisablePCHValidation, DisableStatCache,
340                              AllowPCHWithCompilerErrors));
341 
342   Reader->setDeserializationListener(
343             static_cast<ASTDeserializationListener *>(DeserializationListener));
344   switch (Reader->ReadAST(Path,
345                           Preamble ? serialization::MK_Preamble
346                                    : serialization::MK_PCH)) {
347   case ASTReader::Success:
348     // Set the predefines buffer as suggested by the PCH reader. Typically, the
349     // predefines buffer will be empty.
350     PP.setPredefines(Reader->getSuggestedPredefines());
351     return Reader.take();
352 
353   case ASTReader::Failure:
354     // Unrecoverable failure: don't even try to process the input file.
355     break;
356 
357   case ASTReader::OutOfDate:
358   case ASTReader::VersionMismatch:
359   case ASTReader::ConfigurationMismatch:
360   case ASTReader::HadErrors:
361     // No suitable PCH file could be found. Return an error.
362     break;
363   }
364 
365   return 0;
366 }
367 
368 // Code Completion
369 
370 static bool EnableCodeCompletion(Preprocessor &PP,
371                                  const std::string &Filename,
372                                  unsigned Line,
373                                  unsigned Column) {
374   // Tell the source manager to chop off the given file at a specific
375   // line and column.
376   const FileEntry *Entry = PP.getFileManager().getFile(Filename);
377   if (!Entry) {
378     PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
379       << Filename;
380     return true;
381   }
382 
383   // Truncate the named file at the given line/column.
384   PP.SetCodeCompletionPoint(Entry, Line, Column);
385   return false;
386 }
387 
388 void CompilerInstance::createCodeCompletionConsumer() {
389   const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
390   if (!CompletionConsumer) {
391     setCodeCompletionConsumer(
392       createCodeCompletionConsumer(getPreprocessor(),
393                                    Loc.FileName, Loc.Line, Loc.Column,
394                                    getFrontendOpts().CodeCompleteOpts,
395                                    llvm::outs()));
396     if (!CompletionConsumer)
397       return;
398   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
399                                   Loc.Line, Loc.Column)) {
400     setCodeCompletionConsumer(0);
401     return;
402   }
403 
404   if (CompletionConsumer->isOutputBinary() &&
405       llvm::sys::Program::ChangeStdoutToBinary()) {
406     getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
407     setCodeCompletionConsumer(0);
408   }
409 }
410 
411 void CompilerInstance::createFrontendTimer() {
412   FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
413 }
414 
415 CodeCompleteConsumer *
416 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
417                                                const std::string &Filename,
418                                                unsigned Line,
419                                                unsigned Column,
420                                                const CodeCompleteOptions &Opts,
421                                                raw_ostream &OS) {
422   if (EnableCodeCompletion(PP, Filename, Line, Column))
423     return 0;
424 
425   // Set up the creation routine for code-completion.
426   return new PrintingCodeCompleteConsumer(Opts, OS);
427 }
428 
429 void CompilerInstance::createSema(TranslationUnitKind TUKind,
430                                   CodeCompleteConsumer *CompletionConsumer) {
431   TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
432                          TUKind, CompletionConsumer));
433 }
434 
435 // Output Files
436 
437 void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
438   assert(OutFile.OS && "Attempt to add empty stream to output list!");
439   OutputFiles.push_back(OutFile);
440 }
441 
442 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
443   for (std::list<OutputFile>::iterator
444          it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
445     delete it->OS;
446     if (!it->TempFilename.empty()) {
447       if (EraseFiles) {
448         bool existed;
449         llvm::sys::fs::remove(it->TempFilename, existed);
450       } else {
451         SmallString<128> NewOutFile(it->Filename);
452 
453         // If '-working-directory' was passed, the output filename should be
454         // relative to that.
455         FileMgr->FixupRelativePath(NewOutFile);
456         if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
457                                                         NewOutFile.str())) {
458           getDiagnostics().Report(diag::err_unable_to_rename_temp)
459             << it->TempFilename << it->Filename << ec.message();
460 
461           bool existed;
462           llvm::sys::fs::remove(it->TempFilename, existed);
463         }
464       }
465     } else if (!it->Filename.empty() && EraseFiles)
466       llvm::sys::Path(it->Filename).eraseFromDisk();
467 
468   }
469   OutputFiles.clear();
470 }
471 
472 llvm::raw_fd_ostream *
473 CompilerInstance::createDefaultOutputFile(bool Binary,
474                                           StringRef InFile,
475                                           StringRef Extension) {
476   return createOutputFile(getFrontendOpts().OutputFile, Binary,
477                           /*RemoveFileOnSignal=*/true, InFile, Extension,
478                           /*UseTemporary=*/true);
479 }
480 
481 llvm::raw_fd_ostream *
482 CompilerInstance::createOutputFile(StringRef OutputPath,
483                                    bool Binary, bool RemoveFileOnSignal,
484                                    StringRef InFile,
485                                    StringRef Extension,
486                                    bool UseTemporary,
487                                    bool CreateMissingDirectories) {
488   std::string Error, OutputPathName, TempPathName;
489   llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
490                                               RemoveFileOnSignal,
491                                               InFile, Extension,
492                                               UseTemporary,
493                                               CreateMissingDirectories,
494                                               &OutputPathName,
495                                               &TempPathName);
496   if (!OS) {
497     getDiagnostics().Report(diag::err_fe_unable_to_open_output)
498       << OutputPath << Error;
499     return 0;
500   }
501 
502   // Add the output file -- but don't try to remove "-", since this means we are
503   // using stdin.
504   addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
505                 TempPathName, OS));
506 
507   return OS;
508 }
509 
510 llvm::raw_fd_ostream *
511 CompilerInstance::createOutputFile(StringRef OutputPath,
512                                    std::string &Error,
513                                    bool Binary,
514                                    bool RemoveFileOnSignal,
515                                    StringRef InFile,
516                                    StringRef Extension,
517                                    bool UseTemporary,
518                                    bool CreateMissingDirectories,
519                                    std::string *ResultPathName,
520                                    std::string *TempPathName) {
521   assert((!CreateMissingDirectories || UseTemporary) &&
522          "CreateMissingDirectories is only allowed when using temporary files");
523 
524   std::string OutFile, TempFile;
525   if (!OutputPath.empty()) {
526     OutFile = OutputPath;
527   } else if (InFile == "-") {
528     OutFile = "-";
529   } else if (!Extension.empty()) {
530     llvm::sys::Path Path(InFile);
531     Path.eraseSuffix();
532     Path.appendSuffix(Extension);
533     OutFile = Path.str();
534   } else {
535     OutFile = "-";
536   }
537 
538   OwningPtr<llvm::raw_fd_ostream> OS;
539   std::string OSFile;
540 
541   if (UseTemporary && OutFile != "-") {
542     // Only create the temporary if the parent directory exists (or create
543     // missing directories is true) and we can actually write to OutPath,
544     // otherwise we want to fail early.
545     SmallString<256> AbsPath(OutputPath);
546     llvm::sys::fs::make_absolute(AbsPath);
547     llvm::sys::Path OutPath(AbsPath);
548     bool ParentExists = false;
549     if (llvm::sys::fs::exists(llvm::sys::path::parent_path(AbsPath.str()),
550                               ParentExists))
551       ParentExists = false;
552     bool Exists;
553     if ((CreateMissingDirectories || ParentExists) &&
554         ((llvm::sys::fs::exists(AbsPath.str(), Exists) || !Exists) ||
555          (OutPath.isRegularFile() && OutPath.canWrite()))) {
556       // Create a temporary file.
557       SmallString<128> TempPath;
558       TempPath = OutFile;
559       TempPath += "-%%%%%%%%";
560       int fd;
561       if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
562                                      /*makeAbsolute=*/false, 0664)
563           == llvm::errc::success) {
564         OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
565         OSFile = TempFile = TempPath.str();
566       }
567     }
568   }
569 
570   if (!OS) {
571     OSFile = OutFile;
572     OS.reset(
573       new llvm::raw_fd_ostream(OSFile.c_str(), Error,
574                                (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
575     if (!Error.empty())
576       return 0;
577   }
578 
579   // Make sure the out stream file gets removed if we crash.
580   if (RemoveFileOnSignal)
581     llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
582 
583   if (ResultPathName)
584     *ResultPathName = OutFile;
585   if (TempPathName)
586     *TempPathName = TempFile;
587 
588   return OS.take();
589 }
590 
591 // Initialization Utilities
592 
593 bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
594                                                SrcMgr::CharacteristicKind Kind){
595   return InitializeSourceManager(InputFile, Kind, getDiagnostics(),
596                                  getFileManager(), getSourceManager(),
597                                  getFrontendOpts());
598 }
599 
600 bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
601                                                SrcMgr::CharacteristicKind Kind,
602                                                DiagnosticsEngine &Diags,
603                                                FileManager &FileMgr,
604                                                SourceManager &SourceMgr,
605                                                const FrontendOptions &Opts) {
606   // Figure out where to get and map in the main file.
607   if (InputFile != "-") {
608     const FileEntry *File = FileMgr.getFile(InputFile);
609     if (!File) {
610       Diags.Report(diag::err_fe_error_reading) << InputFile;
611       return false;
612     }
613     SourceMgr.createMainFileID(File, Kind);
614   } else {
615     OwningPtr<llvm::MemoryBuffer> SB;
616     if (llvm::MemoryBuffer::getSTDIN(SB)) {
617       // FIXME: Give ec.message() in this diag.
618       Diags.Report(diag::err_fe_error_reading_stdin);
619       return false;
620     }
621     const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
622                                                    SB->getBufferSize(), 0);
623     SourceMgr.createMainFileID(File, Kind);
624     SourceMgr.overrideFileContents(File, SB.take());
625   }
626 
627   assert(!SourceMgr.getMainFileID().isInvalid() &&
628          "Couldn't establish MainFileID!");
629   return true;
630 }
631 
632 // High-Level Operations
633 
634 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
635   assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
636   assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
637   assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
638 
639   // FIXME: Take this as an argument, once all the APIs we used have moved to
640   // taking it as an input instead of hard-coding llvm::errs.
641   raw_ostream &OS = llvm::errs();
642 
643   // Create the target instance.
644   setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
645   if (!hasTarget())
646     return false;
647 
648   // Inform the target of the language options.
649   //
650   // FIXME: We shouldn't need to do this, the target should be immutable once
651   // created. This complexity should be lifted elsewhere.
652   getTarget().setForcedLangOptions(getLangOpts());
653 
654   // rewriter project will change target built-in bool type from its default.
655   if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
656     getTarget().noSignedCharForObjCBool();
657 
658   // Validate/process some options.
659   if (getHeaderSearchOpts().Verbose)
660     OS << "clang -cc1 version " CLANG_VERSION_STRING
661        << " based upon " << PACKAGE_STRING
662        << " default target " << llvm::sys::getDefaultTargetTriple() << "\n";
663 
664   if (getFrontendOpts().ShowTimers)
665     createFrontendTimer();
666 
667   if (getFrontendOpts().ShowStats)
668     llvm::EnableStatistics();
669 
670   for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
671     // Reset the ID tables if we are reusing the SourceManager.
672     if (hasSourceManager())
673       getSourceManager().clearIDTables();
674 
675     if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) {
676       Act.Execute();
677       Act.EndSourceFile();
678     }
679   }
680 
681   // Notify the diagnostic client that all files were processed.
682   getDiagnostics().getClient()->finish();
683 
684   if (getDiagnosticOpts().ShowCarets) {
685     // We can have multiple diagnostics sharing one diagnostic client.
686     // Get the total number of warnings/errors from the client.
687     unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
688     unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
689 
690     if (NumWarnings)
691       OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
692     if (NumWarnings && NumErrors)
693       OS << " and ";
694     if (NumErrors)
695       OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
696     if (NumWarnings || NumErrors)
697       OS << " generated.\n";
698   }
699 
700   if (getFrontendOpts().ShowStats && hasFileManager()) {
701     getFileManager().PrintStats();
702     OS << "\n";
703   }
704 
705   return !getDiagnostics().getClient()->getNumErrors();
706 }
707 
708 /// \brief Determine the appropriate source input kind based on language
709 /// options.
710 static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) {
711   if (LangOpts.OpenCL)
712     return IK_OpenCL;
713   if (LangOpts.CUDA)
714     return IK_CUDA;
715   if (LangOpts.ObjC1)
716     return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC;
717   return LangOpts.CPlusPlus? IK_CXX : IK_C;
718 }
719 
720 namespace {
721   struct CompileModuleMapData {
722     CompilerInstance &Instance;
723     GenerateModuleAction &CreateModuleAction;
724   };
725 }
726 
727 /// \brief Helper function that executes the module-generating action under
728 /// a crash recovery context.
729 static void doCompileMapModule(void *UserData) {
730   CompileModuleMapData &Data
731     = *reinterpret_cast<CompileModuleMapData *>(UserData);
732   Data.Instance.ExecuteAction(Data.CreateModuleAction);
733 }
734 
735 /// \brief Compile a module file for the given module, using the options
736 /// provided by the importing compiler instance.
737 static void compileModule(CompilerInstance &ImportingInstance,
738                           Module *Module,
739                           StringRef ModuleFileName) {
740   llvm::LockFileManager Locked(ModuleFileName);
741   switch (Locked) {
742   case llvm::LockFileManager::LFS_Error:
743     return;
744 
745   case llvm::LockFileManager::LFS_Owned:
746     // We're responsible for building the module ourselves. Do so below.
747     break;
748 
749   case llvm::LockFileManager::LFS_Shared:
750     // Someone else is responsible for building the module. Wait for them to
751     // finish.
752     Locked.waitForUnlock();
753     break;
754   }
755 
756   ModuleMap &ModMap
757     = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap();
758 
759   // Construct a compiler invocation for creating this module.
760   IntrusiveRefCntPtr<CompilerInvocation> Invocation
761     (new CompilerInvocation(ImportingInstance.getInvocation()));
762 
763   PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
764 
765   // For any options that aren't intended to affect how a module is built,
766   // reset them to their default values.
767   Invocation->getLangOpts()->resetNonModularOptions();
768   PPOpts.resetNonModularOptions();
769 
770   // Note the name of the module we're building.
771   Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName();
772 
773   // Note that this module is part of the module build path, so that we
774   // can detect cycles in the module graph.
775   PPOpts.ModuleBuildPath.push_back(Module->getTopLevelModuleName());
776 
777   // If there is a module map file, build the module using the module map.
778   // Set up the inputs/outputs so that we build the module from its umbrella
779   // header.
780   FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
781   FrontendOpts.OutputFile = ModuleFileName.str();
782   FrontendOpts.DisableFree = false;
783   FrontendOpts.Inputs.clear();
784   InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts());
785 
786   // Get or create the module map that we'll use to build this module.
787   SmallString<128> TempModuleMapFileName;
788   if (const FileEntry *ModuleMapFile
789                                   = ModMap.getContainingModuleMapFile(Module)) {
790     // Use the module map where this module resides.
791     FrontendOpts.Inputs.push_back(FrontendInputFile(ModuleMapFile->getName(),
792                                                     IK));
793   } else {
794     // Create a temporary module map file.
795     TempModuleMapFileName = Module->Name;
796     TempModuleMapFileName += "-%%%%%%%%.map";
797     int FD;
798     if (llvm::sys::fs::unique_file(TempModuleMapFileName.str(), FD,
799                                    TempModuleMapFileName,
800                                    /*makeAbsolute=*/true)
801           != llvm::errc::success) {
802       ImportingInstance.getDiagnostics().Report(diag::err_module_map_temp_file)
803         << TempModuleMapFileName;
804       return;
805     }
806     // Print the module map to this file.
807     llvm::raw_fd_ostream OS(FD, /*shouldClose=*/true);
808     Module->print(OS);
809     FrontendOpts.Inputs.push_back(
810       FrontendInputFile(TempModuleMapFileName.str().str(), IK));
811   }
812 
813   // Don't free the remapped file buffers; they are owned by our caller.
814   PPOpts.RetainRemappedFileBuffers = true;
815 
816   Invocation->getDiagnosticOpts().VerifyDiagnostics = 0;
817   assert(ImportingInstance.getInvocation().getModuleHash() ==
818          Invocation->getModuleHash() && "Module hash mismatch!");
819 
820   // Construct a compiler instance that will be used to actually create the
821   // module.
822   CompilerInstance Instance;
823   Instance.setInvocation(&*Invocation);
824   Instance.createDiagnostics(/*argc=*/0, /*argv=*/0,
825                              &ImportingInstance.getDiagnosticClient(),
826                              /*ShouldOwnClient=*/true,
827                              /*ShouldCloneClient=*/true);
828 
829   // Construct a module-generating action.
830   GenerateModuleAction CreateModuleAction;
831 
832   // Execute the action to actually build the module in-place. Use a separate
833   // thread so that we get a stack large enough.
834   const unsigned ThreadStackSize = 8 << 20;
835   llvm::CrashRecoveryContext CRC;
836   CompileModuleMapData Data = { Instance, CreateModuleAction };
837   CRC.RunSafelyOnThread(&doCompileMapModule, &Data, ThreadStackSize);
838 
839   // Delete the temporary module map file.
840   // FIXME: Even though we're executing under crash protection, it would still
841   // be nice to do this with RemoveFileOnSignal when we can. However, that
842   // doesn't make sense for all clients, so clean this up manually.
843   Instance.clearOutputFiles(/*EraseFiles=*/true);
844   if (!TempModuleMapFileName.empty())
845     llvm::sys::Path(TempModuleMapFileName).eraseFromDisk();
846 }
847 
848 Module *CompilerInstance::loadModule(SourceLocation ImportLoc,
849                                      ModuleIdPath Path,
850                                      Module::NameVisibilityKind Visibility,
851                                      bool IsInclusionDirective) {
852   // If we've already handled this import, just return the cached result.
853   // This one-element cache is important to eliminate redundant diagnostics
854   // when both the preprocessor and parser see the same import declaration.
855   if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) {
856     // Make the named module visible.
857     if (LastModuleImportResult)
858       ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility);
859     return LastModuleImportResult;
860   }
861 
862   // Determine what file we're searching from.
863   StringRef ModuleName = Path[0].first->getName();
864   SourceLocation ModuleNameLoc = Path[0].second;
865 
866   clang::Module *Module = 0;
867 
868   // If we don't already have information on this module, load the module now.
869   llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known
870     = KnownModules.find(Path[0].first);
871   if (Known != KnownModules.end()) {
872     // Retrieve the cached top-level module.
873     Module = Known->second;
874   } else if (ModuleName == getLangOpts().CurrentModule) {
875     // This is the module we're building.
876     Module = PP->getHeaderSearchInfo().getModuleMap().findModule(ModuleName);
877     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
878   } else {
879     // Search for a module with the given name.
880     Module = PP->getHeaderSearchInfo().lookupModule(ModuleName);
881     std::string ModuleFileName;
882     if (Module)
883       ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(Module);
884     else
885       ModuleFileName = PP->getHeaderSearchInfo().getModuleFileName(ModuleName);
886 
887     if (ModuleFileName.empty()) {
888       getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found)
889         << ModuleName
890         << SourceRange(ImportLoc, ModuleNameLoc);
891       LastModuleImportLoc = ImportLoc;
892       LastModuleImportResult = 0;
893       return 0;
894     }
895 
896     const FileEntry *ModuleFile
897       = getFileManager().getFile(ModuleFileName, /*OpenFile=*/false,
898                                  /*CacheFailure=*/false);
899     bool BuildingModule = false;
900     if (!ModuleFile && Module) {
901       // The module is not cached, but we have a module map from which we can
902       // build the module.
903 
904       // Check whether there is a cycle in the module graph.
905       SmallVectorImpl<std::string> &ModuleBuildPath
906         = getPreprocessorOpts().ModuleBuildPath;
907       SmallVectorImpl<std::string>::iterator Pos
908         = std::find(ModuleBuildPath.begin(), ModuleBuildPath.end(), ModuleName);
909       if (Pos != ModuleBuildPath.end()) {
910         SmallString<256> CyclePath;
911         for (; Pos != ModuleBuildPath.end(); ++Pos) {
912           CyclePath += *Pos;
913           CyclePath += " -> ";
914         }
915         CyclePath += ModuleName;
916 
917         getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle)
918           << ModuleName << CyclePath;
919         return 0;
920       }
921 
922       getDiagnostics().Report(ModuleNameLoc, diag::warn_module_build)
923         << ModuleName;
924       BuildingModule = true;
925       compileModule(*this, Module, ModuleFileName);
926       ModuleFile = FileMgr->getFile(ModuleFileName);
927     }
928 
929     if (!ModuleFile) {
930       getDiagnostics().Report(ModuleNameLoc,
931                               BuildingModule? diag::err_module_not_built
932                                             : diag::err_module_not_found)
933         << ModuleName
934         << SourceRange(ImportLoc, ModuleNameLoc);
935       return 0;
936     }
937 
938     // If we don't already have an ASTReader, create one now.
939     if (!ModuleManager) {
940       if (!hasASTContext())
941         createASTContext();
942 
943       std::string Sysroot = getHeaderSearchOpts().Sysroot;
944       const PreprocessorOptions &PPOpts = getPreprocessorOpts();
945       ModuleManager = new ASTReader(getPreprocessor(), *Context,
946                                     Sysroot.empty() ? "" : Sysroot.c_str(),
947                                     PPOpts.DisablePCHValidation,
948                                     PPOpts.DisableStatCache);
949       if (hasASTConsumer()) {
950         ModuleManager->setDeserializationListener(
951           getASTConsumer().GetASTDeserializationListener());
952         getASTContext().setASTMutationListener(
953           getASTConsumer().GetASTMutationListener());
954         getPreprocessor().setPPMutationListener(
955           getASTConsumer().GetPPMutationListener());
956       }
957       OwningPtr<ExternalASTSource> Source;
958       Source.reset(ModuleManager);
959       getASTContext().setExternalSource(Source);
960       if (hasSema())
961         ModuleManager->InitializeSema(getSema());
962       if (hasASTConsumer())
963         ModuleManager->StartTranslationUnit(&getASTConsumer());
964     }
965 
966     // Try to load the module we found.
967     switch (ModuleManager->ReadAST(ModuleFile->getName(),
968                                    serialization::MK_Module)) {
969     case ASTReader::Success:
970       break;
971 
972     case ASTReader::OutOfDate:
973     case ASTReader::VersionMismatch:
974     case ASTReader::ConfigurationMismatch:
975     case ASTReader::HadErrors:
976       // FIXME: The ASTReader will already have complained, but can we showhorn
977       // that diagnostic information into a more useful form?
978       KnownModules[Path[0].first] = 0;
979       return 0;
980 
981     case ASTReader::Failure:
982       // Already complained, but note now that we failed.
983       KnownModules[Path[0].first] = 0;
984       return 0;
985     }
986 
987     if (!Module) {
988       // If we loaded the module directly, without finding a module map first,
989       // we'll have loaded the module's information from the module itself.
990       Module = PP->getHeaderSearchInfo().getModuleMap()
991                  .findModule((Path[0].first->getName()));
992     }
993 
994     if (Module)
995       Module->setASTFile(ModuleFile);
996 
997     // Cache the result of this top-level module lookup for later.
998     Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first;
999   }
1000 
1001   // If we never found the module, fail.
1002   if (!Module)
1003     return 0;
1004 
1005   // Verify that the rest of the module path actually corresponds to
1006   // a submodule.
1007   if (Path.size() > 1) {
1008     for (unsigned I = 1, N = Path.size(); I != N; ++I) {
1009       StringRef Name = Path[I].first->getName();
1010       clang::Module *Sub = Module->findSubmodule(Name);
1011 
1012       if (!Sub) {
1013         // Attempt to perform typo correction to find a module name that works.
1014         llvm::SmallVector<StringRef, 2> Best;
1015         unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
1016 
1017         for (clang::Module::submodule_iterator J = Module->submodule_begin(),
1018                                             JEnd = Module->submodule_end();
1019              J != JEnd; ++J) {
1020           unsigned ED = Name.edit_distance((*J)->Name,
1021                                            /*AllowReplacements=*/true,
1022                                            BestEditDistance);
1023           if (ED <= BestEditDistance) {
1024             if (ED < BestEditDistance) {
1025               Best.clear();
1026               BestEditDistance = ED;
1027             }
1028 
1029             Best.push_back((*J)->Name);
1030           }
1031         }
1032 
1033         // If there was a clear winner, user it.
1034         if (Best.size() == 1) {
1035           getDiagnostics().Report(Path[I].second,
1036                                   diag::err_no_submodule_suggest)
1037             << Path[I].first << Module->getFullModuleName() << Best[0]
1038             << SourceRange(Path[0].second, Path[I-1].second)
1039             << FixItHint::CreateReplacement(SourceRange(Path[I].second),
1040                                             Best[0]);
1041 
1042           Sub = Module->findSubmodule(Best[0]);
1043         }
1044       }
1045 
1046       if (!Sub) {
1047         // No submodule by this name. Complain, and don't look for further
1048         // submodules.
1049         getDiagnostics().Report(Path[I].second, diag::err_no_submodule)
1050           << Path[I].first << Module->getFullModuleName()
1051           << SourceRange(Path[0].second, Path[I-1].second);
1052         break;
1053       }
1054 
1055       Module = Sub;
1056     }
1057   }
1058 
1059   // Make the named module visible, if it's not already part of the module
1060   // we are parsing.
1061   if (ModuleName != getLangOpts().CurrentModule) {
1062     if (!Module->IsFromModuleFile) {
1063       // We have an umbrella header or directory that doesn't actually include
1064       // all of the headers within the directory it covers. Complain about
1065       // this missing submodule and recover by forgetting that we ever saw
1066       // this submodule.
1067       // FIXME: Should we detect this at module load time? It seems fairly
1068       // expensive (and rare).
1069       getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule)
1070         << Module->getFullModuleName()
1071         << SourceRange(Path.front().second, Path.back().second);
1072 
1073       return 0;
1074     }
1075 
1076     // Check whether this module is available.
1077     StringRef Feature;
1078     if (!Module->isAvailable(getLangOpts(), getTarget(), Feature)) {
1079       getDiagnostics().Report(ImportLoc, diag::err_module_unavailable)
1080         << Module->getFullModuleName()
1081         << Feature
1082         << SourceRange(Path.front().second, Path.back().second);
1083       LastModuleImportLoc = ImportLoc;
1084       LastModuleImportResult = 0;
1085       return 0;
1086     }
1087 
1088     ModuleManager->makeModuleVisible(Module, Visibility);
1089   }
1090 
1091   // If this module import was due to an inclusion directive, create an
1092   // implicit import declaration to capture it in the AST.
1093   if (IsInclusionDirective && hasASTContext()) {
1094     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
1095     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
1096                                                      ImportLoc, Module,
1097                                                      Path.back().second);
1098     TU->addDecl(ImportD);
1099     if (Consumer)
1100       Consumer->HandleImplicitImportDecl(ImportD);
1101   }
1102 
1103   LastModuleImportLoc = ImportLoc;
1104   LastModuleImportResult = Module;
1105   return Module;
1106 }
1107