1 //===--- CompilerInstance.cpp ---------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Frontend/CompilerInstance.h"
11 #include "clang/Sema/Sema.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Basic/Version.h"
19 #include "clang/Lex/HeaderSearch.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Lex/PTHManager.h"
22 #include "clang/Frontend/ChainedDiagnosticClient.h"
23 #include "clang/Frontend/FrontendAction.h"
24 #include "clang/Frontend/FrontendDiagnostic.h"
25 #include "clang/Frontend/LogDiagnosticPrinter.h"
26 #include "clang/Frontend/TextDiagnosticPrinter.h"
27 #include "clang/Frontend/VerifyDiagnosticsClient.h"
28 #include "clang/Frontend/Utils.h"
29 #include "clang/Serialization/ASTReader.h"
30 #include "clang/Sema/CodeCompleteConsumer.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;
43 CompilerInstance::CompilerInstance()
44 : Invocation(new CompilerInvocation()) {
47 CompilerInstance::~CompilerInstance() {
50 void CompilerInstance::setInvocation(CompilerInvocation *Value) {
54 void CompilerInstance::setDiagnostics(Diagnostic *Value) {
58 void CompilerInstance::setTarget(TargetInfo *Value) {
62 void CompilerInstance::setFileManager(FileManager *Value) {
66 void CompilerInstance::setSourceManager(SourceManager *Value) {
70 void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; }
72 void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; }
74 void CompilerInstance::setSema(Sema *S) {
78 void CompilerInstance::setASTConsumer(ASTConsumer *Value) {
79 Consumer.reset(Value);
82 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
83 CompletionConsumer.reset(Value);
87 static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
88 unsigned argc, const char* const *argv,
90 std::string ErrorInfo;
91 llvm::OwningPtr<llvm::raw_ostream> OS(
92 new llvm::raw_fd_ostream(DiagOpts.DumpBuildInformation.c_str(), ErrorInfo));
93 if (!ErrorInfo.empty()) {
94 Diags.Report(diag::err_fe_unable_to_open_logfile)
95 << DiagOpts.DumpBuildInformation << ErrorInfo;
99 (*OS) << "clang -cc1 command line arguments: ";
100 for (unsigned i = 0; i != argc; ++i)
101 (*OS) << argv[i] << ' ';
104 // Chain in a diagnostic client which will log the diagnostics.
105 DiagnosticClient *Logger =
106 new TextDiagnosticPrinter(*OS.take(), DiagOpts, /*OwnsOutputStream=*/true);
107 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
110 static void SetUpDiagnosticLog(const DiagnosticOptions &DiagOpts,
111 const CodeGenOptions *CodeGenOpts,
113 std::string ErrorInfo;
114 bool OwnsStream = false;
115 llvm::raw_ostream *OS = &llvm::errs();
116 if (DiagOpts.DiagnosticLogFile != "-") {
117 // Create the output stream.
118 llvm::raw_fd_ostream *FileOS(
119 new llvm::raw_fd_ostream(DiagOpts.DiagnosticLogFile.c_str(),
120 ErrorInfo, llvm::raw_fd_ostream::F_Append));
121 if (!ErrorInfo.empty()) {
122 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure)
123 << DiagOpts.DumpBuildInformation << ErrorInfo;
125 FileOS->SetUnbuffered();
126 FileOS->SetUseAtomicWrites(true);
132 // Chain in the diagnostic client which will log the diagnostics.
133 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts,
136 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
137 Diags.setClient(new ChainedDiagnosticClient(Diags.takeClient(), Logger));
140 void CompilerInstance::createDiagnostics(int Argc, const char* const *Argv,
141 DiagnosticClient *Client) {
142 Diagnostics = createDiagnostics(getDiagnosticOpts(), Argc, Argv, Client,
146 llvm::IntrusiveRefCntPtr<Diagnostic>
147 CompilerInstance::createDiagnostics(const DiagnosticOptions &Opts,
148 int Argc, const char* const *Argv,
149 DiagnosticClient *Client,
150 const CodeGenOptions *CodeGenOpts) {
151 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
152 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(new Diagnostic(DiagID));
154 // Create the diagnostic client for reporting errors or for
155 // implementing -verify.
157 Diags->setClient(Client);
159 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts));
161 // Chain in -verify checker, if requested.
162 if (Opts.VerifyDiagnostics)
163 Diags->setClient(new VerifyDiagnosticsClient(*Diags, Diags->takeClient()));
165 // Chain in -diagnostic-log-file dumper, if requested.
166 if (!Opts.DiagnosticLogFile.empty())
167 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags);
169 if (!Opts.DumpBuildInformation.empty())
170 SetUpBuildDumpLog(Opts, Argc, Argv, *Diags);
172 // Configure our handling of diagnostics.
173 ProcessWarningOptions(*Diags, Opts);
180 void CompilerInstance::createFileManager() {
181 FileMgr = new FileManager(getFileSystemOpts());
186 void CompilerInstance::createSourceManager(FileManager &FileMgr) {
187 SourceMgr = new SourceManager(getDiagnostics(), FileMgr);
192 void CompilerInstance::createPreprocessor() {
193 PP = createPreprocessor(getDiagnostics(), getLangOpts(),
194 getPreprocessorOpts(), getHeaderSearchOpts(),
195 getDependencyOutputOpts(), getTarget(),
196 getFrontendOpts(), getSourceManager(),
201 CompilerInstance::createPreprocessor(Diagnostic &Diags,
202 const LangOptions &LangInfo,
203 const PreprocessorOptions &PPOpts,
204 const HeaderSearchOptions &HSOpts,
205 const DependencyOutputOptions &DepOpts,
206 const TargetInfo &Target,
207 const FrontendOptions &FEOpts,
208 SourceManager &SourceMgr,
209 FileManager &FileMgr) {
210 // Create a PTH manager if we are using some form of a token cache.
211 PTHManager *PTHMgr = 0;
212 if (!PPOpts.TokenCache.empty())
213 PTHMgr = PTHManager::Create(PPOpts.TokenCache, Diags);
215 // Create the Preprocessor.
216 HeaderSearch *HeaderInfo = new HeaderSearch(FileMgr);
217 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
218 SourceMgr, *HeaderInfo, PTHMgr,
219 /*OwnsHeaderSearch=*/true);
221 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
222 // That argument is used as the IdentifierInfoLookup argument to
223 // IdentifierTable's ctor.
225 PTHMgr->setPreprocessor(PP);
226 PP->setPTHManager(PTHMgr);
229 if (PPOpts.DetailedRecord)
230 PP->createPreprocessingRecord(
231 PPOpts.DetailedRecordIncludesNestedMacroInstantiations);
233 InitializePreprocessor(*PP, PPOpts, HSOpts, FEOpts);
235 // Handle generating dependencies, if requested.
236 if (!DepOpts.OutputFile.empty())
237 AttachDependencyFileGen(*PP, DepOpts);
239 // Handle generating header include information, if requested.
240 if (DepOpts.ShowHeaderIncludes)
241 AttachHeaderIncludeGen(*PP);
242 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
243 llvm::StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
244 if (OutputPath == "-")
246 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath,
247 /*ShowDepth=*/false);
255 void CompilerInstance::createASTContext() {
256 Preprocessor &PP = getPreprocessor();
257 Context = new ASTContext(getLangOpts(), PP.getSourceManager(),
258 getTarget(), PP.getIdentifierTable(),
259 PP.getSelectorTable(), PP.getBuiltinInfo(),
260 /*size_reserve=*/ 0);
265 void CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
266 bool DisablePCHValidation,
267 bool DisableStatCache,
268 void *DeserializationListener){
269 llvm::OwningPtr<ExternalASTSource> Source;
270 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
271 Source.reset(createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot,
272 DisablePCHValidation,
274 getPreprocessor(), getASTContext(),
275 DeserializationListener,
277 getASTContext().setExternalSource(Source);
281 CompilerInstance::createPCHExternalASTSource(llvm::StringRef Path,
282 const std::string &Sysroot,
283 bool DisablePCHValidation,
284 bool DisableStatCache,
287 void *DeserializationListener,
289 llvm::OwningPtr<ASTReader> Reader;
290 Reader.reset(new ASTReader(PP, &Context,
291 Sysroot.empty() ? 0 : Sysroot.c_str(),
292 DisablePCHValidation, DisableStatCache));
294 Reader->setDeserializationListener(
295 static_cast<ASTDeserializationListener *>(DeserializationListener));
296 switch (Reader->ReadAST(Path,
297 Preamble ? ASTReader::Preamble : ASTReader::PCH)) {
298 case ASTReader::Success:
299 // Set the predefines buffer as suggested by the PCH reader. Typically, the
300 // predefines buffer will be empty.
301 PP.setPredefines(Reader->getSuggestedPredefines());
302 return Reader.take();
304 case ASTReader::Failure:
305 // Unrecoverable failure: don't even try to process the input file.
308 case ASTReader::IgnorePCH:
309 // No suitable PCH file could be found. Return an error.
318 static bool EnableCodeCompletion(Preprocessor &PP,
319 const std::string &Filename,
322 // Tell the source manager to chop off the given file at a specific
324 const FileEntry *Entry = PP.getFileManager().getFile(Filename);
326 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file)
331 // Truncate the named file at the given line/column.
332 PP.SetCodeCompletionPoint(Entry, Line, Column);
336 void CompilerInstance::createCodeCompletionConsumer() {
337 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
338 if (!CompletionConsumer) {
339 CompletionConsumer.reset(
340 createCodeCompletionConsumer(getPreprocessor(),
341 Loc.FileName, Loc.Line, Loc.Column,
342 getFrontendOpts().ShowMacrosInCodeCompletion,
343 getFrontendOpts().ShowCodePatternsInCodeCompletion,
344 getFrontendOpts().ShowGlobalSymbolsInCodeCompletion,
346 if (!CompletionConsumer)
348 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName,
349 Loc.Line, Loc.Column)) {
350 CompletionConsumer.reset();
354 if (CompletionConsumer->isOutputBinary() &&
355 llvm::sys::Program::ChangeStdoutToBinary()) {
356 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary);
357 CompletionConsumer.reset();
361 void CompilerInstance::createFrontendTimer() {
362 FrontendTimer.reset(new llvm::Timer("Clang front-end timer"));
365 CodeCompleteConsumer *
366 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
367 const std::string &Filename,
371 bool ShowCodePatterns,
373 llvm::raw_ostream &OS) {
374 if (EnableCodeCompletion(PP, Filename, Line, Column))
377 // Set up the creation routine for code-completion.
378 return new PrintingCodeCompleteConsumer(ShowMacros, ShowCodePatterns,
382 void CompilerInstance::createSema(bool CompleteTranslationUnit,
383 CodeCompleteConsumer *CompletionConsumer) {
384 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
385 CompleteTranslationUnit, CompletionConsumer));
390 void CompilerInstance::addOutputFile(const OutputFile &OutFile) {
391 assert(OutFile.OS && "Attempt to add empty stream to output list!");
392 OutputFiles.push_back(OutFile);
395 void CompilerInstance::clearOutputFiles(bool EraseFiles) {
396 for (std::list<OutputFile>::iterator
397 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) {
399 if (!it->TempFilename.empty()) {
402 llvm::sys::fs::remove(it->TempFilename, existed);
404 llvm::SmallString<128> NewOutFile(it->Filename);
406 // If '-working-directory' was passed, the output filename should be
408 FileMgr->FixupRelativePath(NewOutFile);
409 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename,
411 getDiagnostics().Report(diag::err_fe_unable_to_rename_temp)
412 << it->TempFilename << it->Filename << ec.message();
415 llvm::sys::fs::remove(it->TempFilename, existed);
418 } else if (!it->Filename.empty() && EraseFiles)
419 llvm::sys::Path(it->Filename).eraseFromDisk();
425 llvm::raw_fd_ostream *
426 CompilerInstance::createDefaultOutputFile(bool Binary,
427 llvm::StringRef InFile,
428 llvm::StringRef Extension) {
429 return createOutputFile(getFrontendOpts().OutputFile, Binary,
430 /*RemoveFileOnSignal=*/true, InFile, Extension);
433 llvm::raw_fd_ostream *
434 CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
435 bool Binary, bool RemoveFileOnSignal,
436 llvm::StringRef InFile,
437 llvm::StringRef Extension) {
438 std::string Error, OutputPathName, TempPathName;
439 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary,
445 getDiagnostics().Report(diag::err_fe_unable_to_open_output)
446 << OutputPath << Error;
450 // Add the output file -- but don't try to remove "-", since this means we are
452 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "",
458 llvm::raw_fd_ostream *
459 CompilerInstance::createOutputFile(llvm::StringRef OutputPath,
462 bool RemoveFileOnSignal,
463 llvm::StringRef InFile,
464 llvm::StringRef Extension,
465 std::string *ResultPathName,
466 std::string *TempPathName) {
467 std::string OutFile, TempFile;
468 if (!OutputPath.empty()) {
469 OutFile = OutputPath;
470 } else if (InFile == "-") {
472 } else if (!Extension.empty()) {
473 llvm::sys::Path Path(InFile);
475 Path.appendSuffix(Extension);
476 OutFile = Path.str();
481 if (OutFile != "-") {
482 llvm::sys::Path OutPath(OutFile);
483 // Only create the temporary if we can actually write to OutPath, otherwise
484 // we want to fail early.
486 if ((llvm::sys::fs::exists(OutPath.str(), Exists) || !Exists) ||
487 (OutPath.isRegularFile() && OutPath.canWrite())) {
488 // Create a temporary file.
489 llvm::sys::Path TempPath(OutFile);
490 if (!TempPath.createTemporaryFileOnDisk())
491 TempFile = TempPath.str();
495 std::string OSFile = OutFile;
496 if (!TempFile.empty())
499 llvm::OwningPtr<llvm::raw_fd_ostream> OS(
500 new llvm::raw_fd_ostream(OSFile.c_str(), Error,
501 (Binary ? llvm::raw_fd_ostream::F_Binary : 0)));
505 // Make sure the out stream file gets removed if we crash.
506 if (RemoveFileOnSignal)
507 llvm::sys::RemoveFileOnSignal(llvm::sys::Path(OSFile));
510 *ResultPathName = OutFile;
512 *TempPathName = TempFile;
517 // Initialization Utilities
519 bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile) {
520 return InitializeSourceManager(InputFile, getDiagnostics(), getFileManager(),
521 getSourceManager(), getFrontendOpts());
524 bool CompilerInstance::InitializeSourceManager(llvm::StringRef InputFile,
526 FileManager &FileMgr,
527 SourceManager &SourceMgr,
528 const FrontendOptions &Opts) {
529 // Figure out where to get and map in the main file, unless it's already
530 // been created (e.g., by a precompiled preamble).
531 if (!SourceMgr.getMainFileID().isInvalid()) {
532 // Do nothing: the main file has already been set.
533 } else if (InputFile != "-") {
534 const FileEntry *File = FileMgr.getFile(InputFile);
536 Diags.Report(diag::err_fe_error_reading) << InputFile;
539 SourceMgr.createMainFileID(File);
541 llvm::OwningPtr<llvm::MemoryBuffer> SB;
542 if (llvm::MemoryBuffer::getSTDIN(SB)) {
543 // FIXME: Give ec.message() in this diag.
544 Diags.Report(diag::err_fe_error_reading_stdin);
547 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
548 SB->getBufferSize(), 0);
549 SourceMgr.createMainFileID(File);
550 SourceMgr.overrideFileContents(File, SB.take());
553 assert(!SourceMgr.getMainFileID().isInvalid() &&
554 "Couldn't establish MainFileID!");
558 // High-Level Operations
560 bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
561 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
562 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
563 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
565 // FIXME: Take this as an argument, once all the APIs we used have moved to
566 // taking it as an input instead of hard-coding llvm::errs.
567 llvm::raw_ostream &OS = llvm::errs();
569 // Create the target instance.
570 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), getTargetOpts()));
574 // Inform the target of the language options.
576 // FIXME: We shouldn't need to do this, the target should be immutable once
577 // created. This complexity should be lifted elsewhere.
578 getTarget().setForcedLangOptions(getLangOpts());
580 // Validate/process some options.
581 if (getHeaderSearchOpts().Verbose)
582 OS << "clang -cc1 version " CLANG_VERSION_STRING
583 << " based upon " << PACKAGE_STRING
584 << " hosted on " << llvm::sys::getHostTriple() << "\n";
586 if (getFrontendOpts().ShowTimers)
587 createFrontendTimer();
589 if (getFrontendOpts().ShowStats)
590 llvm::EnableStatistics();
592 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) {
593 const std::string &InFile = getFrontendOpts().Inputs[i].second;
595 // Reset the ID tables if we are reusing the SourceManager.
596 if (hasSourceManager())
597 getSourceManager().clearIDTables();
599 if (Act.BeginSourceFile(*this, InFile, getFrontendOpts().Inputs[i].first)) {
605 if (getDiagnosticOpts().ShowCarets) {
606 // We can have multiple diagnostics sharing one diagnostic client.
607 // Get the total number of warnings/errors from the client.
608 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
609 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
612 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
613 if (NumWarnings && NumErrors)
616 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
617 if (NumWarnings || NumErrors)
618 OS << " generated.\n";
621 if (getFrontendOpts().ShowStats && hasFileManager()) {
622 getFileManager().PrintStats();
626 return !getDiagnostics().getClient()->getNumErrors();