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