xref: /llvm-project/clang/lib/Frontend/CompilerInstance.cpp (revision 7219a5db6ea402d19a959897bdecf6da58d2d3aa)
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/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/ChainedDiagnosticClient.h"
23 #include "clang/Frontend/FrontendAction.h"
24 #include "clang/Frontend/FrontendDiagnostic.h"
25 #include "clang/Frontend/TextDiagnosticPrinter.h"
26 #include "clang/Frontend/VerifyDiagnosticsClient.h"
27 #include "clang/Frontend/Utils.h"
28 #include "clang/Serialization/ASTReader.h"
29 #include "clang/Sema/CodeCompleteConsumer.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/Timer.h"
35 #include "llvm/System/Host.h"
36 #include "llvm/System/Path.h"
37 #include "llvm/System/Program.h"
38 #include "llvm/System/Signals.h"
39 using namespace clang;
40 
41 CompilerInstance::CompilerInstance()
42   : Invocation(new CompilerInvocation()) {
43 }
44 
45 CompilerInstance::~CompilerInstance() {
46 }
47 
48 void CompilerInstance::setLLVMContext(llvm::LLVMContext *Value) {
49   LLVMContext.reset(Value);
50 }
51 
52 void CompilerInstance::setInvocation(CompilerInvocation *Value) {
53   Invocation.reset(Value);
54 }
55 
56 void CompilerInstance::setDiagnostics(Diagnostic *Value) {
57   Diagnostics = Value;
58 }
59 
60 void CompilerInstance::setTarget(TargetInfo *Value) {
61   Target.reset(Value);
62 }
63 
64 void CompilerInstance::setFileManager(FileManager *Value) {
65   FileMgr.reset(Value);
66 }
67 
68 void CompilerInstance::setSourceManager(SourceManager *Value) {
69   SourceMgr.reset(Value);
70 }
71 
72 void CompilerInstance::setPreprocessor(Preprocessor *Value) {
73   PP.reset(Value);
74 }
75 
76 void CompilerInstance::setASTContext(ASTContext *Value) {
77   Context.reset(Value);
78 }
79 
80 void CompilerInstance::setSema(Sema *S) {
81   TheSema.reset(S);
82 }
83 
84 void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
85   Consumer.reset(Value);
86 }
87 
88 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
89   CompletionConsumer.reset(Value);
90 }
91 
92 // Diagnostics
93 static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
94                               unsigned argc, const char* const *argv,
95                               Diagnostic &Diags) {
96   std::string ErrorInfo;
97   llvm::OwningPtr<llvm::raw_ostream> OS(
98     new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
99   if (!ErrorInfo.empty()) {
100     Diags.Report(diag::err_fe_unable_to_open_logfile)
101                  << DiagOpts.DumpBuildInformation << ErrorInfo;
102     return;
103   }
104 
105   (*OS) << "clang -cc1 command line arguments: ";
106   for (unsigned i = 0; i != argc; ++i)
107     (*OS) << argv[i] << ' ';
108   (*OS) << '\n';
109 
110   // Chain in a diagnostic client which will log the diagnostics.
111   DiagnosticClient *Logger =
112     new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
113   Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
114 }
115 
116 void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
117                                          DiagnosticClient *Client) {
118   Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client);
119 }
120 
121 llvm::IntrusiveRefCntPtr<Diagnostic>
122 CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
123                                     int Argc, const char* const *Argv,
124                                     DiagnosticClient *Client) {
125   llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
126   llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
127 
128   // Create the diagnostic client for reporting errors or for
129   // implementing -verify.
130   if (Client)
131     Diags->setClient(Client);
132   else
133     Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
134 
135   // Chain in -verify checker, if requested.
136   if (Opts.VerifyDiagnostics)
137     Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
138 
139   if (!Opts.DumpBuildInformation.empty())
140     SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
141 
142   // Configure our handling of diagnostics.
143   ProcessWarningOptions(*Diags, Opts);
144 
145   return Diags;
146 }
147 
148 // File Manager
149 
150 void CompilerInstance::createFileManager() {
151   FileMgr.reset(new FileManager(getFileSystemOpts()));
152 }
153 
154 // Source Manager
155 
156 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
157   SourceMgr.reset(new SourceManager(getDiagnostics(), FileMgr));
158 }
159 
160 // Preprocessor
161 
162 void CompilerInstance::createPreprocessor() {
163   PP.reset(createPreprocessor(getDiagnostics(), getLangOpts(),
164                               getPreprocessorOpts(), getHeaderSearchOpts(),
165                               getDependencyOutputOpts(), getTarget(),
166                               getFrontendOpts(), getSourceManager(),
167                               getFileManager()));
168 }
169 
170 Preprocessor *
171 CompilerInstance::createPreprocessor(Diagnostic &Diags,
172                                      const LangOptions &LangInfo,
173                                      const PreprocessorOptions &PPOpts,
174                                      const HeaderSearchOptions &HSOpts,
175                                      const DependencyOutputOptions &DepOpts,
176                                      const TargetInfo &Target,
177                                      const FrontendOptions &FEOpts,
178                                      SourceManager &SourceMgr,
179                                      FileManager &FileMgr) {
180   // Create a PTH manager if we are using some form of a token cache.
181   PTHManager *PTHMgr = 0;
182   if (!PPOpts.TokenCache.empty())
183     PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
184 
185   // Create the Preprocessor.
186   HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
187   Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
188                                       SourceMgr, *HeaderInfo, PTHMgr,
189                                       /*OwnsHeaderSearch=*/true);
190 
191   // Note that this is different then passing PTHMgr to Preprocessor's ctor.
192   // That argument is used as the IdentifierInfoLookup argument to
193   // IdentifierTable's ctor.
194   if (PTHMgr) {
195     PTHMgr->setPreprocessor(PP);
196     PP->setPTHManager(PTHMgr);
197   }
198 
199   if (PPOpts.DetailedRecord)
200     PP->createPreprocessingRecord();
201 
202   InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
203 
204   // Handle generating dependencies, if requested.
205   if (!DepOpts.OutputFile.empty())
206     AttachDependencyFileGen(*PP, DepOpts);
207 
208   return PP;
209 }
210 
211 // ASTContext
212 
213 void CompilerInstance::createASTContext() {
214   Preprocessor &PP = getPreprocessor();
215   Context.reset(new ASTContext(getLangOpts(), PP.getSourceManager(),
216                                getTarget(), PP.getIdentifierTable(),
217                                PP.getSelectorTable(), PP.getBuiltinInfo(),
218                                /*size_reserve=*/ 0));
219 }
220 
221 // ExternalASTSource
222 
223 void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
224                                                   bool DisablePCHValidation,
225                                                  void *DeserializationListener){
226   llvm::OwningPtr<ExternalASTSource> Source;
227   bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
228   Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
229                                           DisablePCHValidation,
230                                           getPreprocessor(), getASTContext(),
231                                           DeserializationListener,
232                                           Preamble));
233   getASTContext().setExternalSource(Source);
234 }
235 
236 ExternalASTSource *
237 CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
238                                              const std::string &Sysroot,
239                                              bool DisablePCHValidation,
240                                              Preprocessor &PP,
241                                              ASTContext &Context,
242                                              void *DeserializationListener,
243                                              bool Preamble) {
244   llvm::OwningPtr<ASTReader> Reader;
245   Reader.reset(new ASTReader(PP, &Context,
246                              Sysroot.empty() ? 0 : Sysroot.c_str(),
247                              DisablePCHValidation));
248 
249   Reader->setDeserializationListener(
250             static_cast<ASTDeserializationListener *>(DeserializationListener));
251   switch (Reader->ReadAST(Path,
252                           Preamble ? ASTReader::Preamble : ASTReader::PCH)) {
253   case ASTReader::Success:
254     // Set the predefines buffer as suggested by the PCH reader. Typically, the
255     // predefines buffer will be empty.
256     PP.setPredefines(Reader->getSuggestedPredefines());
257     return Reader.take();
258 
259   case ASTReader::Failure:
260     // Unrecoverable failure: don't even try to process the input file.
261     break;
262 
263   case ASTReader::IgnorePCH:
264     // No suitable PCH file could be found. Return an error.
265     break;
266   }
267 
268   return 0;
269 }
270 
271 // Code Completion
272 
273 static bool EnableCodeCompletion(Preprocessor &PP,
274                                  const std::string &Filename,
275                                  unsigned Line,
276                                  unsigned Column) {
277   // Tell the source manager to chop off the given file at a specific
278   // line and column.
279   const FileEntry *Entry = PP.getFileManager().getFile(Filename);
280   if (!Entry) {
281     PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
282       << Filename;
283     return true;
284   }
285 
286   // Truncate the named file at the given line/column.
287   PP.SetCodeCompletionPoint(Entry, Line, Column);
288   return false;
289 }
290 
291 void CompilerInstance::createCodeCompletionConsumer() {
292   const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
293   if (!CompletionConsumer) {
294     CompletionConsumer.reset(
295       createCodeCompletionConsumer(getPreprocessor(),
296                                    Loc.FileName, Loc.Line, Loc.Column,
297                                    getFrontendOpts().ShowMacrosInCodeCompletion,
298                              getFrontendOpts().ShowCodePatternsInCodeCompletion,
299                            getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
300                                    llvm::outs()));
301     if (!CompletionConsumer)
302       return;
303   } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
304                                   Loc.Line, Loc.Column)) {
305     CompletionConsumer.reset();
306     return;
307   }
308 
309   if (CompletionConsumer->isOutputBinary() &&
310       llvm::sys::Program::ChangeStdoutToBinary()) {
311     getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
312     CompletionConsumer.reset();
313   }
314 }
315 
316 void CompilerInstance::createFrontendTimer() {
317   FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
318 }
319 
320 CodeCompleteConsumer *
321 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
322                                                const std::string &Filename,
323                                                unsigned Line,
324                                                unsigned Column,
325                                                bool ShowMacros,
326                                                bool ShowCodePatterns,
327                                                bool ShowGlobals,
328                                                llvm::raw_ostream &OS) {
329   if (EnableCodeCompletion(PP, Filename, Line, Column))
330     return 0;
331 
332   // Set up the creation routine for code-completion.
333   return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
334                                           ShowGlobals, OS);
335 }
336 
337 void CompilerInstance::createSema(bool CompleteTranslationUnit,
338                                   CodeCompleteConsumer *CompletionConsumer) {
339   TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
340                          CompleteTranslationUnit, CompletionConsumer));
341 }
342 
343 // Output Files
344 
345 void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
346   assert(OutFile.OS && "Attempt to add empty stream to output list!");
347   OutputFiles.push_back(OutFile);
348 }
349 
350 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
351   for (std::list<OutputFile>::iterator
352          it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
353     delete it->OS;
354     if (!it->TempFilename.empty()) {
355       llvm::sys::Path TempPath(it->TempFilename);
356       if (EraseFiles)
357         TempPath.eraseFromDisk();
358       else {
359         std::string Error;
360         llvm::sys::Path NewOutFile(it->Filename);
361         // If '-working-directory' was passed, the output filename should be
362         // relative to that.
363         FileManager::FixupRelativePath(NewOutFile, getFileSystemOpts());
364         if (TempPath.renamePathOnDisk(NewOutFile, &Error)) {
365           getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
366             << it->TempFilename << it->Filename << Error;
367           TempPath.eraseFromDisk();
368         }
369       }
370     } else if (!it->Filename.empty() && EraseFiles)
371       llvm::sys::Path(it->Filename).eraseFromDisk();
372 
373   }
374   OutputFiles.clear();
375 }
376 
377 llvm::raw_fd_ostream *
378 CompilerInstance::createDefaultOutputFile(bool Binary,
379                                           llvm::StringRef InFile,
380                                           llvm::StringRef Extension) {
381   return createOutputFile(getFrontendOpts().OutputFile, Binary,
382                           InFile, Extension);
383 }
384 
385 llvm::raw_fd_ostream *
386 CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
387                                    bool Binary,
388                                    llvm::StringRef InFile,
389                                    llvm::StringRef Extension) {
390   std::string Error, OutputPathName, TempPathName;
391   llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
392                                               InFile, Extension,
393                                               &OutputPathName,
394                                               &TempPathName);
395   if (!OS) {
396     getDiagnostics().Report(diag::err_fe_unable_to_open_output)
397       << OutputPath << Error;
398     return 0;
399   }
400 
401   // Add the output file -- but don't try to remove "-", since this means we are
402   // using stdin.
403   addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
404                 TempPathName, OS));
405 
406   return OS;
407 }
408 
409 llvm::raw_fd_ostream *
410 CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
411                                    std::string &Error,
412                                    bool Binary,
413                                    llvm::StringRef InFile,
414                                    llvm::StringRef Extension,
415                                    std::string *ResultPathName,
416                                    std::string *TempPathName) {
417   std::string OutFile, TempFile;
418   if (!OutputPath.empty()) {
419     OutFile = OutputPath;
420   } else if (InFile == "-") {
421     OutFile = "-";
422   } else if (!Extension.empty()) {
423     llvm::sys::Path Path(InFile);
424     Path.eraseSuffix();
425     Path.appendSuffix(Extension);
426     OutFile = Path.str();
427   } else {
428     OutFile = "-";
429   }
430 
431   if (OutFile != "-") {
432     llvm::sys::Path OutPath(OutFile);
433     // Only create the temporary if we can actually write to OutPath, otherwise
434     // we want to fail early.
435     if (!OutPath.exists() ||
436         (OutPath.isRegularFile() && OutPath.canWrite())) {
437       // Create a temporary file.
438       llvm::sys::Path TempPath(OutFile);
439       if (!TempPath.createTemporaryFileOnDisk())
440         TempFile = TempPath.str();
441     }
442   }
443 
444   std::string OSFile = OutFile;
445   if (!TempFile.empty())
446     OSFile = TempFile;
447 
448   llvm::OwningPtr<llvm::raw_fd_ostream> OS(
449     new llvm::raw_fd_ostream(OSFile.c_str(), Error,
450                              (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
451   if (!Error.empty())
452     return 0;
453 
454   // Make sure the out stream file gets removed if we crash.
455   llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
456 
457   if (ResultPathName)
458     *ResultPathName = OutFile;
459   if (TempPathName)
460     *TempPathName = TempFile;
461 
462   return OS.take();
463 }
464 
465 // Initialization Utilities
466 
467 bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
468   return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
469                                  getSourceManager(), getFrontendOpts());
470 }
471 
472 bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
473                                                Diagnostic &Diags,
474                                                FileManager &FileMgr,
475                                                SourceManager &SourceMgr,
476                                                const FrontendOptions &Opts) {
477   // Figure out where to get and map in the main file.
478   if (InputFile != "-") {
479     const FileEntry *File = FileMgr.getFile(InputFile);
480     if (!File) {
481       Diags.Report(diag::err_fe_error_reading) << InputFile;
482       return false;
483     }
484     SourceMgr.createMainFileID(File);
485   } else {
486     llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
487     if (!SB) {
488       Diags.Report(diag::err_fe_error_reading_stdin);
489       return false;
490     }
491     const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
492                                                    SB->getBufferSize(), 0);
493     SourceMgr.createMainFileID(File);
494     SourceMgr.overrideFileContents(File, SB);
495   }
496 
497   assert(!SourceMgr.getMainFileID().isInvalid() &&
498          "Couldn't establish MainFileID!");
499   return true;
500 }
501 
502 // High-Level Operations
503 
504 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
505   assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
506   assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
507   assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
508 
509   // FIXME: Take this as an argument, once all the APIs we used have moved to
510   // taking it as an input instead of hard-coding llvm::errs.
511   llvm::raw_ostream &OS = llvm::errs();
512 
513   // Create the target instance.
514   setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
515   if (!hasTarget())
516     return false;
517 
518   // Inform the target of the language options.
519   //
520   // FIXME: We shouldn't need to do this, the target should be immutable once
521   // created. This complexity should be lifted elsewhere.
522   getTarget().setForcedLangOptions(getLangOpts());
523 
524   // Validate/process some options.
525   if (getHeaderSearchOpts().Verbose)
526     OS << "clang -cc1 version " CLANG_VERSION_STRING
527        << " based upon " << PACKAGE_STRING
528        << " hosted on " << llvm::sys::getHostTriple() << "\n";
529 
530   if (getFrontendOpts().ShowTimers)
531     createFrontendTimer();
532 
533   if (getFrontendOpts().ShowStats)
534     llvm::EnableStatistics();
535 
536   for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
537     const std::string &InFile = getFrontendOpts().Inputs[i].second;
538 
539     // Reset the ID tables if we are reusing the SourceManager.
540     if (hasSourceManager())
541       getSourceManager().clearIDTables();
542 
543     if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
544       Act.Execute();
545       Act.EndSourceFile();
546     }
547   }
548 
549   if (getDiagnosticOpts().ShowCarets) {
550     // We can have multiple diagnostics sharing one diagnostic client.
551     // Get the total number of warnings/errors from the client.
552     unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
553     unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
554 
555     if (NumWarnings)
556       OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
557     if (NumWarnings && NumErrors)
558       OS << " and ";
559     if (NumErrors)
560       OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
561     if (NumWarnings || NumErrors)
562       OS << " generated.\n";
563   }
564 
565   if (getFrontendOpts().ShowStats && hasFileManager()) {
566     getFileManager().PrintStats();
567     OS << "\n";
568   }
569 
570   return !getDiagnostics().getClient()->getNumErrors();
571 }
572 
573 
574