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