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