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/AST/Decl.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/Frontend/ChainedDiagnosticConsumer.h" 20 #include "clang/Frontend/FrontendAction.h" 21 #include "clang/Frontend/FrontendActions.h" 22 #include "clang/Frontend/FrontendDiagnostic.h" 23 #include "clang/Frontend/LogDiagnosticPrinter.h" 24 #include "clang/Frontend/SerializedDiagnosticPrinter.h" 25 #include "clang/Frontend/TextDiagnosticPrinter.h" 26 #include "clang/Frontend/Utils.h" 27 #include "clang/Frontend/VerifyDiagnosticConsumer.h" 28 #include "clang/Lex/HeaderSearch.h" 29 #include "clang/Lex/PTHManager.h" 30 #include "clang/Lex/Preprocessor.h" 31 #include "clang/Sema/CodeCompleteConsumer.h" 32 #include "clang/Sema/Sema.h" 33 #include "clang/Serialization/ASTReader.h" 34 #include "clang/Serialization/GlobalModuleIndex.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/Config/config.h" 37 #include "llvm/Support/CrashRecoveryContext.h" 38 #include "llvm/Support/FileSystem.h" 39 #include "llvm/Support/Host.h" 40 #include "llvm/Support/LockFileManager.h" 41 #include "llvm/Support/MemoryBuffer.h" 42 #include "llvm/Support/Path.h" 43 #include "llvm/Support/Program.h" 44 #include "llvm/Support/Signals.h" 45 #include "llvm/Support/Timer.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include "llvm/Support/system_error.h" 48 #include <sys/stat.h> 49 #include <time.h> 50 51 using namespace clang; 52 53 CompilerInstance::CompilerInstance(bool BuildingModule) 54 : ModuleLoader(BuildingModule), 55 Invocation(new CompilerInvocation()), ModuleManager(0), 56 BuildGlobalModuleIndex(false), HaveFullGlobalModuleIndex(false), 57 ModuleBuildFailed(false) { 58 } 59 60 CompilerInstance::~CompilerInstance() { 61 assert(OutputFiles.empty() && "Still output files in flight?"); 62 } 63 64 void CompilerInstance::setInvocation(CompilerInvocation *Value) { 65 Invocation = Value; 66 } 67 68 bool CompilerInstance::shouldBuildGlobalModuleIndex() const { 69 return (BuildGlobalModuleIndex || 70 (ModuleManager && ModuleManager->isGlobalIndexUnavailable() && 71 getFrontendOpts().GenerateGlobalModuleIndex)) && 72 !ModuleBuildFailed; 73 } 74 75 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) { 76 Diagnostics = Value; 77 } 78 79 void CompilerInstance::setTarget(TargetInfo *Value) { 80 Target = Value; 81 } 82 83 void CompilerInstance::setFileManager(FileManager *Value) { 84 FileMgr = Value; 85 if (Value) 86 VirtualFileSystem = Value->getVirtualFileSystem(); 87 else 88 VirtualFileSystem.reset(); 89 } 90 91 void CompilerInstance::setSourceManager(SourceManager *Value) { 92 SourceMgr = Value; 93 } 94 95 void CompilerInstance::setPreprocessor(Preprocessor *Value) { PP = Value; } 96 97 void CompilerInstance::setASTContext(ASTContext *Value) { Context = Value; } 98 99 void CompilerInstance::setSema(Sema *S) { 100 TheSema.reset(S); 101 } 102 103 void CompilerInstance::setASTConsumer(ASTConsumer *Value) { 104 Consumer.reset(Value); 105 } 106 107 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) { 108 CompletionConsumer.reset(Value); 109 } 110 111 IntrusiveRefCntPtr<ASTReader> CompilerInstance::getModuleManager() const { 112 return ModuleManager; 113 } 114 void CompilerInstance::setModuleManager(IntrusiveRefCntPtr<ASTReader> Reader) { 115 ModuleManager = Reader; 116 } 117 118 // Diagnostics 119 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts, 120 const CodeGenOptions *CodeGenOpts, 121 DiagnosticsEngine &Diags) { 122 std::string ErrorInfo; 123 bool OwnsStream = false; 124 raw_ostream *OS = &llvm::errs(); 125 if (DiagOpts->DiagnosticLogFile != "-") { 126 // Create the output stream. 127 llvm::raw_fd_ostream *FileOS(new llvm::raw_fd_ostream( 128 DiagOpts->DiagnosticLogFile.c_str(), ErrorInfo, 129 llvm::sys::fs::F_Append | llvm::sys::fs::F_Text)); 130 if (!ErrorInfo.empty()) { 131 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure) 132 << DiagOpts->DiagnosticLogFile << ErrorInfo; 133 } else { 134 FileOS->SetUnbuffered(); 135 FileOS->SetUseAtomicWrites(true); 136 OS = FileOS; 137 OwnsStream = true; 138 } 139 } 140 141 // Chain in the diagnostic client which will log the diagnostics. 142 LogDiagnosticPrinter *Logger = new LogDiagnosticPrinter(*OS, DiagOpts, 143 OwnsStream); 144 if (CodeGenOpts) 145 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags); 146 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), Logger)); 147 } 148 149 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts, 150 DiagnosticsEngine &Diags, 151 StringRef OutputFile) { 152 std::string ErrorInfo; 153 std::unique_ptr<llvm::raw_fd_ostream> OS; 154 OS.reset(new llvm::raw_fd_ostream(OutputFile.str().c_str(), ErrorInfo, 155 llvm::sys::fs::F_None)); 156 157 if (!ErrorInfo.empty()) { 158 Diags.Report(diag::warn_fe_serialized_diag_failure) 159 << OutputFile << ErrorInfo; 160 return; 161 } 162 163 DiagnosticConsumer *SerializedConsumer = 164 clang::serialized_diags::create(OS.release(), DiagOpts); 165 166 Diags.setClient(new ChainedDiagnosticConsumer(Diags.takeClient(), 167 SerializedConsumer)); 168 } 169 170 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client, 171 bool ShouldOwnClient) { 172 Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client, 173 ShouldOwnClient, &getCodeGenOpts()); 174 } 175 176 IntrusiveRefCntPtr<DiagnosticsEngine> 177 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts, 178 DiagnosticConsumer *Client, 179 bool ShouldOwnClient, 180 const CodeGenOptions *CodeGenOpts) { 181 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 182 IntrusiveRefCntPtr<DiagnosticsEngine> 183 Diags(new DiagnosticsEngine(DiagID, Opts)); 184 185 // Create the diagnostic client for reporting errors or for 186 // implementing -verify. 187 if (Client) { 188 Diags->setClient(Client, ShouldOwnClient); 189 } else 190 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts)); 191 192 // Chain in -verify checker, if requested. 193 if (Opts->VerifyDiagnostics) 194 Diags->setClient(new VerifyDiagnosticConsumer(*Diags)); 195 196 // Chain in -diagnostic-log-file dumper, if requested. 197 if (!Opts->DiagnosticLogFile.empty()) 198 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags); 199 200 if (!Opts->DiagnosticSerializationFile.empty()) 201 SetupSerializedDiagnostics(Opts, *Diags, 202 Opts->DiagnosticSerializationFile); 203 204 // Configure our handling of diagnostics. 205 ProcessWarningOptions(*Diags, *Opts); 206 207 return Diags; 208 } 209 210 // File Manager 211 212 void CompilerInstance::createFileManager() { 213 if (!hasVirtualFileSystem()) { 214 // TODO: choose the virtual file system based on the CompilerInvocation. 215 setVirtualFileSystem(vfs::getRealFileSystem()); 216 } 217 FileMgr = new FileManager(getFileSystemOpts(), VirtualFileSystem); 218 } 219 220 // Source Manager 221 222 void CompilerInstance::createSourceManager(FileManager &FileMgr) { 223 SourceMgr = new SourceManager(getDiagnostics(), FileMgr); 224 } 225 226 // Preprocessor 227 228 void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) { 229 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 230 231 // Create a PTH manager if we are using some form of a token cache. 232 PTHManager *PTHMgr = 0; 233 if (!PPOpts.TokenCache.empty()) 234 PTHMgr = PTHManager::Create(PPOpts.TokenCache, getDiagnostics()); 235 236 // Create the Preprocessor. 237 HeaderSearch *HeaderInfo = new HeaderSearch(&getHeaderSearchOpts(), 238 getSourceManager(), 239 getDiagnostics(), 240 getLangOpts(), 241 &getTarget()); 242 PP = new Preprocessor(&getPreprocessorOpts(), 243 getDiagnostics(), getLangOpts(), &getTarget(), 244 getSourceManager(), *HeaderInfo, *this, PTHMgr, 245 /*OwnsHeaderSearch=*/true, 246 /*DelayInitialization=*/false, 247 TUKind); 248 249 // Note that this is different then passing PTHMgr to Preprocessor's ctor. 250 // That argument is used as the IdentifierInfoLookup argument to 251 // IdentifierTable's ctor. 252 if (PTHMgr) { 253 PTHMgr->setPreprocessor(&*PP); 254 PP->setPTHManager(PTHMgr); 255 } 256 257 if (PPOpts.DetailedRecord) 258 PP->createPreprocessingRecord(); 259 260 InitializePreprocessor(*PP, PPOpts, getHeaderSearchOpts(), getFrontendOpts()); 261 262 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP); 263 264 // Set up the module path, including the hash for the 265 // module-creation options. 266 SmallString<256> SpecificModuleCache( 267 getHeaderSearchOpts().ModuleCachePath); 268 if (!getHeaderSearchOpts().DisableModuleHash) 269 llvm::sys::path::append(SpecificModuleCache, 270 getInvocation().getModuleHash()); 271 PP->getHeaderSearchInfo().setModuleCachePath(SpecificModuleCache); 272 273 // Handle generating dependencies, if requested. 274 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts(); 275 if (!DepOpts.OutputFile.empty()) 276 TheDependencyFileGenerator.reset( 277 DependencyFileGenerator::CreateAndAttachToPreprocessor(*PP, DepOpts)); 278 if (!DepOpts.DOTOutputFile.empty()) 279 AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile, 280 getHeaderSearchOpts().Sysroot); 281 282 283 // Handle generating header include information, if requested. 284 if (DepOpts.ShowHeaderIncludes) 285 AttachHeaderIncludeGen(*PP); 286 if (!DepOpts.HeaderIncludeOutputFile.empty()) { 287 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile; 288 if (OutputPath == "-") 289 OutputPath = ""; 290 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/true, OutputPath, 291 /*ShowDepth=*/false); 292 } 293 294 if (DepOpts.PrintShowIncludes) { 295 AttachHeaderIncludeGen(*PP, /*ShowAllHeaders=*/false, /*OutputPath=*/"", 296 /*ShowDepth=*/true, /*MSStyle=*/true); 297 } 298 } 299 300 // ASTContext 301 302 void CompilerInstance::createASTContext() { 303 Preprocessor &PP = getPreprocessor(); 304 Context = new ASTContext(getLangOpts(), PP.getSourceManager(), 305 &getTarget(), PP.getIdentifierTable(), 306 PP.getSelectorTable(), PP.getBuiltinInfo(), 307 /*size_reserve=*/ 0); 308 } 309 310 // ExternalASTSource 311 312 void CompilerInstance::createPCHExternalASTSource(StringRef Path, 313 bool DisablePCHValidation, 314 bool AllowPCHWithCompilerErrors, 315 void *DeserializationListener){ 316 IntrusiveRefCntPtr<ExternalASTSource> Source; 317 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; 318 Source = createPCHExternalASTSource(Path, getHeaderSearchOpts().Sysroot, 319 DisablePCHValidation, 320 AllowPCHWithCompilerErrors, 321 getPreprocessor(), getASTContext(), 322 DeserializationListener, 323 Preamble, 324 getFrontendOpts().UseGlobalModuleIndex); 325 ModuleManager = static_cast<ASTReader*>(Source.getPtr()); 326 getASTContext().setExternalSource(Source); 327 } 328 329 ExternalASTSource * 330 CompilerInstance::createPCHExternalASTSource(StringRef Path, 331 const std::string &Sysroot, 332 bool DisablePCHValidation, 333 bool AllowPCHWithCompilerErrors, 334 Preprocessor &PP, 335 ASTContext &Context, 336 void *DeserializationListener, 337 bool Preamble, 338 bool UseGlobalModuleIndex) { 339 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); 340 341 std::unique_ptr<ASTReader> Reader; 342 Reader.reset(new ASTReader(PP, Context, 343 Sysroot.empty() ? "" : Sysroot.c_str(), 344 DisablePCHValidation, 345 AllowPCHWithCompilerErrors, 346 /*AllowConfigurationMismatch*/false, 347 HSOpts.ModulesValidateSystemHeaders, 348 UseGlobalModuleIndex)); 349 350 Reader->setDeserializationListener( 351 static_cast<ASTDeserializationListener *>(DeserializationListener)); 352 switch (Reader->ReadAST(Path, 353 Preamble ? serialization::MK_Preamble 354 : serialization::MK_PCH, 355 SourceLocation(), 356 ASTReader::ARR_None)) { 357 case ASTReader::Success: 358 // Set the predefines buffer as suggested by the PCH reader. Typically, the 359 // predefines buffer will be empty. 360 PP.setPredefines(Reader->getSuggestedPredefines()); 361 return Reader.release(); 362 363 case ASTReader::Failure: 364 // Unrecoverable failure: don't even try to process the input file. 365 break; 366 367 case ASTReader::Missing: 368 case ASTReader::OutOfDate: 369 case ASTReader::VersionMismatch: 370 case ASTReader::ConfigurationMismatch: 371 case ASTReader::HadErrors: 372 // No suitable PCH file could be found. Return an error. 373 break; 374 } 375 376 return 0; 377 } 378 379 // Code Completion 380 381 static bool EnableCodeCompletion(Preprocessor &PP, 382 const std::string &Filename, 383 unsigned Line, 384 unsigned Column) { 385 // Tell the source manager to chop off the given file at a specific 386 // line and column. 387 const FileEntry *Entry = PP.getFileManager().getFile(Filename); 388 if (!Entry) { 389 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file) 390 << Filename; 391 return true; 392 } 393 394 // Truncate the named file at the given line/column. 395 PP.SetCodeCompletionPoint(Entry, Line, Column); 396 return false; 397 } 398 399 void CompilerInstance::createCodeCompletionConsumer() { 400 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt; 401 if (!CompletionConsumer) { 402 setCodeCompletionConsumer( 403 createCodeCompletionConsumer(getPreprocessor(), 404 Loc.FileName, Loc.Line, Loc.Column, 405 getFrontendOpts().CodeCompleteOpts, 406 llvm::outs())); 407 if (!CompletionConsumer) 408 return; 409 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName, 410 Loc.Line, Loc.Column)) { 411 setCodeCompletionConsumer(0); 412 return; 413 } 414 415 if (CompletionConsumer->isOutputBinary() && 416 llvm::sys::ChangeStdoutToBinary()) { 417 getPreprocessor().getDiagnostics().Report(diag::err_fe_stdout_binary); 418 setCodeCompletionConsumer(0); 419 } 420 } 421 422 void CompilerInstance::createFrontendTimer() { 423 FrontendTimer.reset(new llvm::Timer("Clang front-end timer")); 424 } 425 426 CodeCompleteConsumer * 427 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP, 428 const std::string &Filename, 429 unsigned Line, 430 unsigned Column, 431 const CodeCompleteOptions &Opts, 432 raw_ostream &OS) { 433 if (EnableCodeCompletion(PP, Filename, Line, Column)) 434 return 0; 435 436 // Set up the creation routine for code-completion. 437 return new PrintingCodeCompleteConsumer(Opts, OS); 438 } 439 440 void CompilerInstance::createSema(TranslationUnitKind TUKind, 441 CodeCompleteConsumer *CompletionConsumer) { 442 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(), 443 TUKind, CompletionConsumer)); 444 } 445 446 // Output Files 447 448 void CompilerInstance::addOutputFile(const OutputFile &OutFile) { 449 assert(OutFile.OS && "Attempt to add empty stream to output list!"); 450 OutputFiles.push_back(OutFile); 451 } 452 453 void CompilerInstance::clearOutputFiles(bool EraseFiles) { 454 for (std::list<OutputFile>::iterator 455 it = OutputFiles.begin(), ie = OutputFiles.end(); it != ie; ++it) { 456 delete it->OS; 457 if (!it->TempFilename.empty()) { 458 if (EraseFiles) { 459 llvm::sys::fs::remove(it->TempFilename); 460 } else { 461 SmallString<128> NewOutFile(it->Filename); 462 463 // If '-working-directory' was passed, the output filename should be 464 // relative to that. 465 FileMgr->FixupRelativePath(NewOutFile); 466 if (llvm::error_code ec = llvm::sys::fs::rename(it->TempFilename, 467 NewOutFile.str())) { 468 getDiagnostics().Report(diag::err_unable_to_rename_temp) 469 << it->TempFilename << it->Filename << ec.message(); 470 471 llvm::sys::fs::remove(it->TempFilename); 472 } 473 } 474 } else if (!it->Filename.empty() && EraseFiles) 475 llvm::sys::fs::remove(it->Filename); 476 477 } 478 OutputFiles.clear(); 479 } 480 481 llvm::raw_fd_ostream * 482 CompilerInstance::createDefaultOutputFile(bool Binary, 483 StringRef InFile, 484 StringRef Extension) { 485 return createOutputFile(getFrontendOpts().OutputFile, Binary, 486 /*RemoveFileOnSignal=*/true, InFile, Extension, 487 /*UseTemporary=*/true); 488 } 489 490 llvm::raw_fd_ostream * 491 CompilerInstance::createOutputFile(StringRef OutputPath, 492 bool Binary, bool RemoveFileOnSignal, 493 StringRef InFile, 494 StringRef Extension, 495 bool UseTemporary, 496 bool CreateMissingDirectories) { 497 std::string Error, OutputPathName, TempPathName; 498 llvm::raw_fd_ostream *OS = createOutputFile(OutputPath, Error, Binary, 499 RemoveFileOnSignal, 500 InFile, Extension, 501 UseTemporary, 502 CreateMissingDirectories, 503 &OutputPathName, 504 &TempPathName); 505 if (!OS) { 506 getDiagnostics().Report(diag::err_fe_unable_to_open_output) 507 << OutputPath << Error; 508 return 0; 509 } 510 511 // Add the output file -- but don't try to remove "-", since this means we are 512 // using stdin. 513 addOutputFile(OutputFile((OutputPathName != "-") ? OutputPathName : "", 514 TempPathName, OS)); 515 516 return OS; 517 } 518 519 llvm::raw_fd_ostream * 520 CompilerInstance::createOutputFile(StringRef OutputPath, 521 std::string &Error, 522 bool Binary, 523 bool RemoveFileOnSignal, 524 StringRef InFile, 525 StringRef Extension, 526 bool UseTemporary, 527 bool CreateMissingDirectories, 528 std::string *ResultPathName, 529 std::string *TempPathName) { 530 assert((!CreateMissingDirectories || UseTemporary) && 531 "CreateMissingDirectories is only allowed when using temporary files"); 532 533 std::string OutFile, TempFile; 534 if (!OutputPath.empty()) { 535 OutFile = OutputPath; 536 } else if (InFile == "-") { 537 OutFile = "-"; 538 } else if (!Extension.empty()) { 539 SmallString<128> Path(InFile); 540 llvm::sys::path::replace_extension(Path, Extension); 541 OutFile = Path.str(); 542 } else { 543 OutFile = "-"; 544 } 545 546 std::unique_ptr<llvm::raw_fd_ostream> OS; 547 std::string OSFile; 548 549 if (UseTemporary) { 550 if (OutFile == "-") 551 UseTemporary = false; 552 else { 553 llvm::sys::fs::file_status Status; 554 llvm::sys::fs::status(OutputPath, Status); 555 if (llvm::sys::fs::exists(Status)) { 556 // Fail early if we can't write to the final destination. 557 if (!llvm::sys::fs::can_write(OutputPath)) 558 return 0; 559 560 // Don't use a temporary if the output is a special file. This handles 561 // things like '-o /dev/null' 562 if (!llvm::sys::fs::is_regular_file(Status)) 563 UseTemporary = false; 564 } 565 } 566 } 567 568 if (UseTemporary) { 569 // Create a temporary file. 570 SmallString<128> TempPath; 571 TempPath = OutFile; 572 TempPath += "-%%%%%%%%"; 573 int fd; 574 llvm::error_code EC = 575 llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath); 576 577 if (CreateMissingDirectories && 578 EC == llvm::errc::no_such_file_or_directory) { 579 StringRef Parent = llvm::sys::path::parent_path(OutputPath); 580 EC = llvm::sys::fs::create_directories(Parent); 581 if (!EC) { 582 EC = llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath); 583 } 584 } 585 586 if (!EC) { 587 OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true)); 588 OSFile = TempFile = TempPath.str(); 589 } 590 // If we failed to create the temporary, fallback to writing to the file 591 // directly. This handles the corner case where we cannot write to the 592 // directory, but can write to the file. 593 } 594 595 if (!OS) { 596 OSFile = OutFile; 597 OS.reset(new llvm::raw_fd_ostream( 598 OSFile.c_str(), Error, 599 (Binary ? llvm::sys::fs::F_None : llvm::sys::fs::F_Text))); 600 if (!Error.empty()) 601 return 0; 602 } 603 604 // Make sure the out stream file gets removed if we crash. 605 if (RemoveFileOnSignal) 606 llvm::sys::RemoveFileOnSignal(OSFile); 607 608 if (ResultPathName) 609 *ResultPathName = OutFile; 610 if (TempPathName) 611 *TempPathName = TempFile; 612 613 return OS.release(); 614 } 615 616 // Initialization Utilities 617 618 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){ 619 return InitializeSourceManager(Input, getDiagnostics(), 620 getFileManager(), getSourceManager(), 621 getFrontendOpts()); 622 } 623 624 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input, 625 DiagnosticsEngine &Diags, 626 FileManager &FileMgr, 627 SourceManager &SourceMgr, 628 const FrontendOptions &Opts) { 629 SrcMgr::CharacteristicKind 630 Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User; 631 632 if (Input.isBuffer()) { 633 SourceMgr.createMainFileIDForMemBuffer(Input.getBuffer(), Kind); 634 assert(!SourceMgr.getMainFileID().isInvalid() && 635 "Couldn't establish MainFileID!"); 636 return true; 637 } 638 639 StringRef InputFile = Input.getFile(); 640 641 // Figure out where to get and map in the main file. 642 if (InputFile != "-") { 643 const FileEntry *File = FileMgr.getFile(InputFile, /*OpenFile=*/true); 644 if (!File) { 645 Diags.Report(diag::err_fe_error_reading) << InputFile; 646 return false; 647 } 648 649 // The natural SourceManager infrastructure can't currently handle named 650 // pipes, but we would at least like to accept them for the main 651 // file. Detect them here, read them with the volatile flag so FileMgr will 652 // pick up the correct size, and simply override their contents as we do for 653 // STDIN. 654 if (File->isNamedPipe()) { 655 std::string ErrorStr; 656 if (llvm::MemoryBuffer *MB = 657 FileMgr.getBufferForFile(File, &ErrorStr, /*isVolatile=*/true)) { 658 // Create a new virtual file that will have the correct size. 659 File = FileMgr.getVirtualFile(InputFile, MB->getBufferSize(), 0); 660 SourceMgr.overrideFileContents(File, MB); 661 } else { 662 Diags.Report(diag::err_cannot_open_file) << InputFile << ErrorStr; 663 return false; 664 } 665 } 666 667 SourceMgr.createMainFileID(File, Kind); 668 } else { 669 std::unique_ptr<llvm::MemoryBuffer> SB; 670 if (llvm::error_code ec = llvm::MemoryBuffer::getSTDIN(SB)) { 671 Diags.Report(diag::err_fe_error_reading_stdin) << ec.message(); 672 return false; 673 } 674 const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(), 675 SB->getBufferSize(), 0); 676 SourceMgr.createMainFileID(File, Kind); 677 SourceMgr.overrideFileContents(File, SB.release()); 678 } 679 680 assert(!SourceMgr.getMainFileID().isInvalid() && 681 "Couldn't establish MainFileID!"); 682 return true; 683 } 684 685 // High-Level Operations 686 687 bool CompilerInstance::ExecuteAction(FrontendAction &Act) { 688 assert(hasDiagnostics() && "Diagnostics engine is not initialized!"); 689 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!"); 690 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!"); 691 692 // FIXME: Take this as an argument, once all the APIs we used have moved to 693 // taking it as an input instead of hard-coding llvm::errs. 694 raw_ostream &OS = llvm::errs(); 695 696 // Create the target instance. 697 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), &getTargetOpts())); 698 if (!hasTarget()) 699 return false; 700 701 // Inform the target of the language options. 702 // 703 // FIXME: We shouldn't need to do this, the target should be immutable once 704 // created. This complexity should be lifted elsewhere. 705 getTarget().setForcedLangOptions(getLangOpts()); 706 707 // rewriter project will change target built-in bool type from its default. 708 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC) 709 getTarget().noSignedCharForObjCBool(); 710 711 // Validate/process some options. 712 if (getHeaderSearchOpts().Verbose) 713 OS << "clang -cc1 version " CLANG_VERSION_STRING 714 << " based upon " << PACKAGE_STRING 715 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n"; 716 717 if (getFrontendOpts().ShowTimers) 718 createFrontendTimer(); 719 720 if (getFrontendOpts().ShowStats) 721 llvm::EnableStatistics(); 722 723 for (unsigned i = 0, e = getFrontendOpts().Inputs.size(); i != e; ++i) { 724 // Reset the ID tables if we are reusing the SourceManager. 725 if (hasSourceManager()) 726 getSourceManager().clearIDTables(); 727 728 if (Act.BeginSourceFile(*this, getFrontendOpts().Inputs[i])) { 729 Act.Execute(); 730 Act.EndSourceFile(); 731 } 732 } 733 734 // Notify the diagnostic client that all files were processed. 735 getDiagnostics().getClient()->finish(); 736 737 if (getDiagnosticOpts().ShowCarets) { 738 // We can have multiple diagnostics sharing one diagnostic client. 739 // Get the total number of warnings/errors from the client. 740 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings(); 741 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors(); 742 743 if (NumWarnings) 744 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s"); 745 if (NumWarnings && NumErrors) 746 OS << " and "; 747 if (NumErrors) 748 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s"); 749 if (NumWarnings || NumErrors) 750 OS << " generated.\n"; 751 } 752 753 if (getFrontendOpts().ShowStats && hasFileManager()) { 754 getFileManager().PrintStats(); 755 OS << "\n"; 756 } 757 758 return !getDiagnostics().getClient()->getNumErrors(); 759 } 760 761 /// \brief Determine the appropriate source input kind based on language 762 /// options. 763 static InputKind getSourceInputKindFromOptions(const LangOptions &LangOpts) { 764 if (LangOpts.OpenCL) 765 return IK_OpenCL; 766 if (LangOpts.CUDA) 767 return IK_CUDA; 768 if (LangOpts.ObjC1) 769 return LangOpts.CPlusPlus? IK_ObjCXX : IK_ObjC; 770 return LangOpts.CPlusPlus? IK_CXX : IK_C; 771 } 772 773 /// \brief Compile a module file for the given module, using the options 774 /// provided by the importing compiler instance. 775 static void compileModuleImpl(CompilerInstance &ImportingInstance, 776 SourceLocation ImportLoc, 777 Module *Module, 778 StringRef ModuleFileName) { 779 ModuleMap &ModMap 780 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap(); 781 782 // Construct a compiler invocation for creating this module. 783 IntrusiveRefCntPtr<CompilerInvocation> Invocation 784 (new CompilerInvocation(ImportingInstance.getInvocation())); 785 786 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 787 788 // For any options that aren't intended to affect how a module is built, 789 // reset them to their default values. 790 Invocation->getLangOpts()->resetNonModularOptions(); 791 PPOpts.resetNonModularOptions(); 792 793 // Remove any macro definitions that are explicitly ignored by the module. 794 // They aren't supposed to affect how the module is built anyway. 795 const HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts(); 796 PPOpts.Macros.erase( 797 std::remove_if(PPOpts.Macros.begin(), PPOpts.Macros.end(), 798 [&HSOpts](const std::pair<std::string, bool> &def) { 799 StringRef MacroDef = def.first; 800 return HSOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first) > 0; 801 }), 802 PPOpts.Macros.end()); 803 804 // Note the name of the module we're building. 805 Invocation->getLangOpts()->CurrentModule = Module->getTopLevelModuleName(); 806 807 // Make sure that the failed-module structure has been allocated in 808 // the importing instance, and propagate the pointer to the newly-created 809 // instance. 810 PreprocessorOptions &ImportingPPOpts 811 = ImportingInstance.getInvocation().getPreprocessorOpts(); 812 if (!ImportingPPOpts.FailedModules) 813 ImportingPPOpts.FailedModules = new PreprocessorOptions::FailedModulesSet; 814 PPOpts.FailedModules = ImportingPPOpts.FailedModules; 815 816 // If there is a module map file, build the module using the module map. 817 // Set up the inputs/outputs so that we build the module from its umbrella 818 // header. 819 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts(); 820 FrontendOpts.OutputFile = ModuleFileName.str(); 821 FrontendOpts.DisableFree = false; 822 FrontendOpts.GenerateGlobalModuleIndex = false; 823 FrontendOpts.Inputs.clear(); 824 InputKind IK = getSourceInputKindFromOptions(*Invocation->getLangOpts()); 825 826 // Don't free the remapped file buffers; they are owned by our caller. 827 PPOpts.RetainRemappedFileBuffers = true; 828 829 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0; 830 assert(ImportingInstance.getInvocation().getModuleHash() == 831 Invocation->getModuleHash() && "Module hash mismatch!"); 832 833 // Construct a compiler instance that will be used to actually create the 834 // module. 835 CompilerInstance Instance(/*BuildingModule=*/true); 836 Instance.setInvocation(&*Invocation); 837 838 Instance.createDiagnostics(new ForwardingDiagnosticConsumer( 839 ImportingInstance.getDiagnosticClient()), 840 /*ShouldOwnClient=*/true); 841 842 Instance.setVirtualFileSystem(&ImportingInstance.getVirtualFileSystem()); 843 844 // Note that this module is part of the module build stack, so that we 845 // can detect cycles in the module graph. 846 Instance.setFileManager(&ImportingInstance.getFileManager()); 847 Instance.createSourceManager(Instance.getFileManager()); 848 SourceManager &SourceMgr = Instance.getSourceManager(); 849 SourceMgr.setModuleBuildStack( 850 ImportingInstance.getSourceManager().getModuleBuildStack()); 851 SourceMgr.pushModuleBuildStack(Module->getTopLevelModuleName(), 852 FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager())); 853 854 // Get or create the module map that we'll use to build this module. 855 std::string InferredModuleMapContent; 856 if (const FileEntry *ModuleMapFile = 857 ModMap.getContainingModuleMapFile(Module)) { 858 // Use the module map where this module resides. 859 FrontendOpts.Inputs.push_back( 860 FrontendInputFile(ModuleMapFile->getName(), IK)); 861 } else { 862 llvm::raw_string_ostream OS(InferredModuleMapContent); 863 Module->print(OS); 864 OS.flush(); 865 FrontendOpts.Inputs.push_back( 866 FrontendInputFile("__inferred_module.map", IK)); 867 868 const llvm::MemoryBuffer *ModuleMapBuffer = 869 llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent); 870 ModuleMapFile = Instance.getFileManager().getVirtualFile( 871 "__inferred_module.map", InferredModuleMapContent.size(), 0); 872 SourceMgr.overrideFileContents(ModuleMapFile, ModuleMapBuffer); 873 } 874 875 // Construct a module-generating action. Passing through Module->ModuleMap is 876 // safe because the FileManager is shared between the compiler instances. 877 GenerateModuleAction CreateModuleAction(Module->ModuleMap, Module->IsSystem); 878 879 // Execute the action to actually build the module in-place. Use a separate 880 // thread so that we get a stack large enough. 881 const unsigned ThreadStackSize = 8 << 20; 882 llvm::CrashRecoveryContext CRC; 883 CRC.RunSafelyOnThread([&]() { Instance.ExecuteAction(CreateModuleAction); }, 884 ThreadStackSize); 885 886 // Delete the temporary module map file. 887 // FIXME: Even though we're executing under crash protection, it would still 888 // be nice to do this with RemoveFileOnSignal when we can. However, that 889 // doesn't make sense for all clients, so clean this up manually. 890 Instance.clearOutputFiles(/*EraseFiles=*/true); 891 892 // We've rebuilt a module. If we're allowed to generate or update the global 893 // module index, record that fact in the importing compiler instance. 894 if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) { 895 ImportingInstance.setBuildGlobalModuleIndex(true); 896 } 897 } 898 899 static void compileModule(CompilerInstance &ImportingInstance, 900 SourceLocation ImportLoc, 901 Module *Module, 902 StringRef ModuleFileName) { 903 // FIXME: have LockFileManager return an error_code so that we can 904 // avoid the mkdir when the directory already exists. 905 StringRef Dir = llvm::sys::path::parent_path(ModuleFileName); 906 llvm::sys::fs::create_directories(Dir); 907 908 while (1) { 909 llvm::LockFileManager Locked(ModuleFileName); 910 switch (Locked) { 911 case llvm::LockFileManager::LFS_Error: 912 return; 913 914 case llvm::LockFileManager::LFS_Owned: 915 // We're responsible for building the module ourselves. Do so below. 916 break; 917 918 case llvm::LockFileManager::LFS_Shared: 919 // Someone else is responsible for building the module. Wait for them to 920 // finish. 921 if (Locked.waitForUnlock() == llvm::LockFileManager::Res_OwnerDied) 922 continue; // try again to get the lock. 923 return; 924 } 925 926 return compileModuleImpl(ImportingInstance, ImportLoc, Module, 927 ModuleFileName); 928 } 929 } 930 931 /// \brief Diagnose differences between the current definition of the given 932 /// configuration macro and the definition provided on the command line. 933 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro, 934 Module *Mod, SourceLocation ImportLoc) { 935 IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro); 936 SourceManager &SourceMgr = PP.getSourceManager(); 937 938 // If this identifier has never had a macro definition, then it could 939 // not have changed. 940 if (!Id->hadMacroDefinition()) 941 return; 942 943 // If this identifier does not currently have a macro definition, 944 // check whether it had one on the command line. 945 if (!Id->hasMacroDefinition()) { 946 MacroDirective::DefInfo LatestDef = 947 PP.getMacroDirectiveHistory(Id)->getDefinition(); 948 for (MacroDirective::DefInfo Def = LatestDef; Def; 949 Def = Def.getPreviousDefinition()) { 950 FileID FID = SourceMgr.getFileID(Def.getLocation()); 951 if (FID.isInvalid()) 952 continue; 953 954 // We only care about the predefines buffer. 955 if (FID != PP.getPredefinesFileID()) 956 continue; 957 958 // This macro was defined on the command line, then #undef'd later. 959 // Complain. 960 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 961 << true << ConfigMacro << Mod->getFullModuleName(); 962 if (LatestDef.isUndefined()) 963 PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here) 964 << true; 965 return; 966 } 967 968 // Okay: no definition in the predefines buffer. 969 return; 970 } 971 972 // This identifier has a macro definition. Check whether we had a definition 973 // on the command line. 974 MacroDirective::DefInfo LatestDef = 975 PP.getMacroDirectiveHistory(Id)->getDefinition(); 976 MacroDirective::DefInfo PredefinedDef; 977 for (MacroDirective::DefInfo Def = LatestDef; Def; 978 Def = Def.getPreviousDefinition()) { 979 FileID FID = SourceMgr.getFileID(Def.getLocation()); 980 if (FID.isInvalid()) 981 continue; 982 983 // We only care about the predefines buffer. 984 if (FID != PP.getPredefinesFileID()) 985 continue; 986 987 PredefinedDef = Def; 988 break; 989 } 990 991 // If there was no definition for this macro in the predefines buffer, 992 // complain. 993 if (!PredefinedDef || 994 (!PredefinedDef.getLocation().isValid() && 995 PredefinedDef.getUndefLocation().isValid())) { 996 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 997 << false << ConfigMacro << Mod->getFullModuleName(); 998 PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here) 999 << false; 1000 return; 1001 } 1002 1003 // If the current macro definition is the same as the predefined macro 1004 // definition, it's okay. 1005 if (LatestDef.getMacroInfo() == PredefinedDef.getMacroInfo() || 1006 LatestDef.getMacroInfo()->isIdenticalTo(*PredefinedDef.getMacroInfo(),PP, 1007 /*Syntactically=*/true)) 1008 return; 1009 1010 // The macro definitions differ. 1011 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 1012 << false << ConfigMacro << Mod->getFullModuleName(); 1013 PP.Diag(LatestDef.getLocation(), diag::note_module_def_undef_here) 1014 << false; 1015 } 1016 1017 /// \brief Write a new timestamp file with the given path. 1018 static void writeTimestampFile(StringRef TimestampFile) { 1019 std::string ErrorInfo; 1020 llvm::raw_fd_ostream Out(TimestampFile.str().c_str(), ErrorInfo, 1021 llvm::sys::fs::F_None); 1022 } 1023 1024 /// \brief Prune the module cache of modules that haven't been accessed in 1025 /// a long time. 1026 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) { 1027 struct stat StatBuf; 1028 llvm::SmallString<128> TimestampFile; 1029 TimestampFile = HSOpts.ModuleCachePath; 1030 llvm::sys::path::append(TimestampFile, "modules.timestamp"); 1031 1032 // Try to stat() the timestamp file. 1033 if (::stat(TimestampFile.c_str(), &StatBuf)) { 1034 // If the timestamp file wasn't there, create one now. 1035 if (errno == ENOENT) { 1036 writeTimestampFile(TimestampFile); 1037 } 1038 return; 1039 } 1040 1041 // Check whether the time stamp is older than our pruning interval. 1042 // If not, do nothing. 1043 time_t TimeStampModTime = StatBuf.st_mtime; 1044 time_t CurrentTime = time(0); 1045 if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval)) 1046 return; 1047 1048 // Write a new timestamp file so that nobody else attempts to prune. 1049 // There is a benign race condition here, if two Clang instances happen to 1050 // notice at the same time that the timestamp is out-of-date. 1051 writeTimestampFile(TimestampFile); 1052 1053 // Walk the entire module cache, looking for unused module files and module 1054 // indices. 1055 llvm::error_code EC; 1056 SmallString<128> ModuleCachePathNative; 1057 llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative); 1058 for (llvm::sys::fs::directory_iterator 1059 Dir(ModuleCachePathNative.str(), EC), DirEnd; 1060 Dir != DirEnd && !EC; Dir.increment(EC)) { 1061 // If we don't have a directory, there's nothing to look into. 1062 if (!llvm::sys::fs::is_directory(Dir->path())) 1063 continue; 1064 1065 // Walk all of the files within this directory. 1066 for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd; 1067 File != FileEnd && !EC; File.increment(EC)) { 1068 // We only care about module and global module index files. 1069 StringRef Extension = llvm::sys::path::extension(File->path()); 1070 if (Extension != ".pcm" && Extension != ".timestamp" && 1071 llvm::sys::path::filename(File->path()) != "modules.idx") 1072 continue; 1073 1074 // Look at this file. If we can't stat it, there's nothing interesting 1075 // there. 1076 if (::stat(File->path().c_str(), &StatBuf)) 1077 continue; 1078 1079 // If the file has been used recently enough, leave it there. 1080 time_t FileAccessTime = StatBuf.st_atime; 1081 if (CurrentTime - FileAccessTime <= 1082 time_t(HSOpts.ModuleCachePruneAfter)) { 1083 continue; 1084 } 1085 1086 // Remove the file. 1087 llvm::sys::fs::remove(File->path()); 1088 1089 // Remove the timestamp file. 1090 std::string TimpestampFilename = File->path() + ".timestamp"; 1091 llvm::sys::fs::remove(TimpestampFilename); 1092 } 1093 1094 // If we removed all of the files in the directory, remove the directory 1095 // itself. 1096 if (llvm::sys::fs::directory_iterator(Dir->path(), EC) == 1097 llvm::sys::fs::directory_iterator() && !EC) 1098 llvm::sys::fs::remove(Dir->path()); 1099 } 1100 } 1101 1102 void CompilerInstance::createModuleManager() { 1103 if (!ModuleManager) { 1104 if (!hasASTContext()) 1105 createASTContext(); 1106 1107 // If we're not recursively building a module, check whether we 1108 // need to prune the module cache. 1109 if (getSourceManager().getModuleBuildStack().empty() && 1110 getHeaderSearchOpts().ModuleCachePruneInterval > 0 && 1111 getHeaderSearchOpts().ModuleCachePruneAfter > 0) { 1112 pruneModuleCache(getHeaderSearchOpts()); 1113 } 1114 1115 HeaderSearchOptions &HSOpts = getHeaderSearchOpts(); 1116 std::string Sysroot = HSOpts.Sysroot; 1117 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 1118 ModuleManager = new ASTReader(getPreprocessor(), *Context, 1119 Sysroot.empty() ? "" : Sysroot.c_str(), 1120 PPOpts.DisablePCHValidation, 1121 /*AllowASTWithCompilerErrors=*/false, 1122 /*AllowConfigurationMismatch=*/false, 1123 HSOpts.ModulesValidateSystemHeaders, 1124 getFrontendOpts().UseGlobalModuleIndex); 1125 if (hasASTConsumer()) { 1126 ModuleManager->setDeserializationListener( 1127 getASTConsumer().GetASTDeserializationListener()); 1128 getASTContext().setASTMutationListener( 1129 getASTConsumer().GetASTMutationListener()); 1130 } 1131 getASTContext().setExternalSource(ModuleManager); 1132 if (hasSema()) 1133 ModuleManager->InitializeSema(getSema()); 1134 if (hasASTConsumer()) 1135 ModuleManager->StartTranslationUnit(&getASTConsumer()); 1136 } 1137 } 1138 1139 ModuleLoadResult 1140 CompilerInstance::loadModule(SourceLocation ImportLoc, 1141 ModuleIdPath Path, 1142 Module::NameVisibilityKind Visibility, 1143 bool IsInclusionDirective) { 1144 // Determine what file we're searching from. 1145 StringRef ModuleName = Path[0].first->getName(); 1146 SourceLocation ModuleNameLoc = Path[0].second; 1147 1148 // If we've already handled this import, just return the cached result. 1149 // This one-element cache is important to eliminate redundant diagnostics 1150 // when both the preprocessor and parser see the same import declaration. 1151 if (!ImportLoc.isInvalid() && LastModuleImportLoc == ImportLoc) { 1152 // Make the named module visible. 1153 if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule) 1154 ModuleManager->makeModuleVisible(LastModuleImportResult, Visibility, 1155 ImportLoc, /*Complain=*/false); 1156 return LastModuleImportResult; 1157 } 1158 1159 clang::Module *Module = 0; 1160 1161 // If we don't already have information on this module, load the module now. 1162 llvm::DenseMap<const IdentifierInfo *, clang::Module *>::iterator Known 1163 = KnownModules.find(Path[0].first); 1164 if (Known != KnownModules.end()) { 1165 // Retrieve the cached top-level module. 1166 Module = Known->second; 1167 } else if (ModuleName == getLangOpts().CurrentModule) { 1168 // This is the module we're building. 1169 Module = PP->getHeaderSearchInfo().getModuleMap().findModule(ModuleName); 1170 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first; 1171 } else { 1172 // Search for a module with the given name. 1173 Module = PP->getHeaderSearchInfo().lookupModule(ModuleName); 1174 if (!Module) { 1175 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found) 1176 << ModuleName 1177 << SourceRange(ImportLoc, ModuleNameLoc); 1178 ModuleBuildFailed = true; 1179 return ModuleLoadResult(); 1180 } 1181 1182 std::string ModuleFileName = 1183 PP->getHeaderSearchInfo().getModuleFileName(Module); 1184 1185 // If we don't already have an ASTReader, create one now. 1186 if (!ModuleManager) 1187 createModuleManager(); 1188 1189 if (TheDependencyFileGenerator) 1190 TheDependencyFileGenerator->AttachToASTReader(*ModuleManager); 1191 1192 // Try to load the module file. 1193 unsigned ARRFlags = ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing; 1194 switch (ModuleManager->ReadAST(ModuleFileName, serialization::MK_Module, 1195 ImportLoc, ARRFlags)) { 1196 case ASTReader::Success: 1197 break; 1198 1199 case ASTReader::OutOfDate: 1200 case ASTReader::Missing: { 1201 // The module file is missing or out-of-date. Build it. 1202 assert(Module && "missing module file"); 1203 // Check whether there is a cycle in the module graph. 1204 ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack(); 1205 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end(); 1206 for (; Pos != PosEnd; ++Pos) { 1207 if (Pos->first == ModuleName) 1208 break; 1209 } 1210 1211 if (Pos != PosEnd) { 1212 SmallString<256> CyclePath; 1213 for (; Pos != PosEnd; ++Pos) { 1214 CyclePath += Pos->first; 1215 CyclePath += " -> "; 1216 } 1217 CyclePath += ModuleName; 1218 1219 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle) 1220 << ModuleName << CyclePath; 1221 return ModuleLoadResult(); 1222 } 1223 1224 // Check whether we have already attempted to build this module (but 1225 // failed). 1226 if (getPreprocessorOpts().FailedModules && 1227 getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) { 1228 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built) 1229 << ModuleName 1230 << SourceRange(ImportLoc, ModuleNameLoc); 1231 ModuleBuildFailed = true; 1232 return ModuleLoadResult(); 1233 } 1234 1235 // Try to compile the module. 1236 compileModule(*this, ModuleNameLoc, Module, ModuleFileName); 1237 1238 // Try to read the module file, now that we've compiled it. 1239 ASTReader::ASTReadResult ReadResult 1240 = ModuleManager->ReadAST(ModuleFileName, 1241 serialization::MK_Module, ImportLoc, 1242 ASTReader::ARR_Missing); 1243 if (ReadResult != ASTReader::Success) { 1244 if (ReadResult == ASTReader::Missing) { 1245 getDiagnostics().Report(ModuleNameLoc, 1246 Module? diag::err_module_not_built 1247 : diag::err_module_not_found) 1248 << ModuleName 1249 << SourceRange(ImportLoc, ModuleNameLoc); 1250 } 1251 1252 if (getPreprocessorOpts().FailedModules) 1253 getPreprocessorOpts().FailedModules->addFailed(ModuleName); 1254 KnownModules[Path[0].first] = 0; 1255 ModuleBuildFailed = true; 1256 return ModuleLoadResult(); 1257 } 1258 1259 // Okay, we've rebuilt and now loaded the module. 1260 break; 1261 } 1262 1263 case ASTReader::VersionMismatch: 1264 case ASTReader::ConfigurationMismatch: 1265 case ASTReader::HadErrors: 1266 ModuleLoader::HadFatalFailure = true; 1267 // FIXME: The ASTReader will already have complained, but can we showhorn 1268 // that diagnostic information into a more useful form? 1269 KnownModules[Path[0].first] = 0; 1270 return ModuleLoadResult(); 1271 1272 case ASTReader::Failure: 1273 ModuleLoader::HadFatalFailure = true; 1274 // Already complained, but note now that we failed. 1275 KnownModules[Path[0].first] = 0; 1276 ModuleBuildFailed = true; 1277 return ModuleLoadResult(); 1278 } 1279 1280 // Cache the result of this top-level module lookup for later. 1281 Known = KnownModules.insert(std::make_pair(Path[0].first, Module)).first; 1282 } 1283 1284 // If we never found the module, fail. 1285 if (!Module) 1286 return ModuleLoadResult(); 1287 1288 // Verify that the rest of the module path actually corresponds to 1289 // a submodule. 1290 if (Path.size() > 1) { 1291 for (unsigned I = 1, N = Path.size(); I != N; ++I) { 1292 StringRef Name = Path[I].first->getName(); 1293 clang::Module *Sub = Module->findSubmodule(Name); 1294 1295 if (!Sub) { 1296 // Attempt to perform typo correction to find a module name that works. 1297 SmallVector<StringRef, 2> Best; 1298 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)(); 1299 1300 for (clang::Module::submodule_iterator J = Module->submodule_begin(), 1301 JEnd = Module->submodule_end(); 1302 J != JEnd; ++J) { 1303 unsigned ED = Name.edit_distance((*J)->Name, 1304 /*AllowReplacements=*/true, 1305 BestEditDistance); 1306 if (ED <= BestEditDistance) { 1307 if (ED < BestEditDistance) { 1308 Best.clear(); 1309 BestEditDistance = ED; 1310 } 1311 1312 Best.push_back((*J)->Name); 1313 } 1314 } 1315 1316 // If there was a clear winner, user it. 1317 if (Best.size() == 1) { 1318 getDiagnostics().Report(Path[I].second, 1319 diag::err_no_submodule_suggest) 1320 << Path[I].first << Module->getFullModuleName() << Best[0] 1321 << SourceRange(Path[0].second, Path[I-1].second) 1322 << FixItHint::CreateReplacement(SourceRange(Path[I].second), 1323 Best[0]); 1324 1325 Sub = Module->findSubmodule(Best[0]); 1326 } 1327 } 1328 1329 if (!Sub) { 1330 // No submodule by this name. Complain, and don't look for further 1331 // submodules. 1332 getDiagnostics().Report(Path[I].second, diag::err_no_submodule) 1333 << Path[I].first << Module->getFullModuleName() 1334 << SourceRange(Path[0].second, Path[I-1].second); 1335 break; 1336 } 1337 1338 Module = Sub; 1339 } 1340 } 1341 1342 // Make the named module visible, if it's not already part of the module 1343 // we are parsing. 1344 if (ModuleName != getLangOpts().CurrentModule) { 1345 if (!Module->IsFromModuleFile) { 1346 // We have an umbrella header or directory that doesn't actually include 1347 // all of the headers within the directory it covers. Complain about 1348 // this missing submodule and recover by forgetting that we ever saw 1349 // this submodule. 1350 // FIXME: Should we detect this at module load time? It seems fairly 1351 // expensive (and rare). 1352 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule) 1353 << Module->getFullModuleName() 1354 << SourceRange(Path.front().second, Path.back().second); 1355 1356 return ModuleLoadResult(0, true); 1357 } 1358 1359 // Check whether this module is available. 1360 clang::Module::Requirement Requirement; 1361 clang::Module::HeaderDirective MissingHeader; 1362 if (!Module->isAvailable(getLangOpts(), getTarget(), Requirement, 1363 MissingHeader)) { 1364 if (MissingHeader.FileNameLoc.isValid()) { 1365 getDiagnostics().Report(MissingHeader.FileNameLoc, 1366 diag::err_module_header_missing) 1367 << MissingHeader.IsUmbrella << MissingHeader.FileName; 1368 } else { 1369 getDiagnostics().Report(ImportLoc, diag::err_module_unavailable) 1370 << Module->getFullModuleName() 1371 << Requirement.second << Requirement.first 1372 << SourceRange(Path.front().second, Path.back().second); 1373 } 1374 LastModuleImportLoc = ImportLoc; 1375 LastModuleImportResult = ModuleLoadResult(); 1376 return ModuleLoadResult(); 1377 } 1378 1379 ModuleManager->makeModuleVisible(Module, Visibility, ImportLoc, 1380 /*Complain=*/true); 1381 } 1382 1383 // Check for any configuration macros that have changed. 1384 clang::Module *TopModule = Module->getTopLevelModule(); 1385 for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) { 1386 checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I], 1387 Module, ImportLoc); 1388 } 1389 1390 // If this module import was due to an inclusion directive, create an 1391 // implicit import declaration to capture it in the AST. 1392 if (IsInclusionDirective && hasASTContext()) { 1393 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 1394 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 1395 ImportLoc, Module, 1396 Path.back().second); 1397 TU->addDecl(ImportD); 1398 if (Consumer) 1399 Consumer->HandleImplicitImportDecl(ImportD); 1400 } 1401 1402 LastModuleImportLoc = ImportLoc; 1403 LastModuleImportResult = ModuleLoadResult(Module, false); 1404 return LastModuleImportResult; 1405 } 1406 1407 void CompilerInstance::makeModuleVisible(Module *Mod, 1408 Module::NameVisibilityKind Visibility, 1409 SourceLocation ImportLoc, 1410 bool Complain){ 1411 ModuleManager->makeModuleVisible(Mod, Visibility, ImportLoc, Complain); 1412 } 1413 1414 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex( 1415 SourceLocation TriggerLoc) { 1416 if (!ModuleManager) 1417 createModuleManager(); 1418 // Can't do anything if we don't have the module manager. 1419 if (!ModuleManager) 1420 return 0; 1421 // Get an existing global index. This loads it if not already 1422 // loaded. 1423 ModuleManager->loadGlobalIndex(); 1424 GlobalModuleIndex *GlobalIndex = ModuleManager->getGlobalIndex(); 1425 // If the global index doesn't exist, create it. 1426 if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() && 1427 hasPreprocessor()) { 1428 llvm::sys::fs::create_directories( 1429 getPreprocessor().getHeaderSearchInfo().getModuleCachePath()); 1430 GlobalModuleIndex::writeIndex( 1431 getFileManager(), 1432 getPreprocessor().getHeaderSearchInfo().getModuleCachePath()); 1433 ModuleManager->resetForReload(); 1434 ModuleManager->loadGlobalIndex(); 1435 GlobalIndex = ModuleManager->getGlobalIndex(); 1436 } 1437 // For finding modules needing to be imported for fixit messages, 1438 // we need to make the global index cover all modules, so we do that here. 1439 if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) { 1440 ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap(); 1441 bool RecreateIndex = false; 1442 for (ModuleMap::module_iterator I = MMap.module_begin(), 1443 E = MMap.module_end(); I != E; ++I) { 1444 Module *TheModule = I->second; 1445 const FileEntry *Entry = TheModule->getASTFile(); 1446 if (!Entry) { 1447 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 1448 Path.push_back(std::make_pair( 1449 getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc)); 1450 std::reverse(Path.begin(), Path.end()); 1451 // Load a module as hidden. This also adds it to the global index. 1452 loadModule(TheModule->DefinitionLoc, Path, 1453 Module::Hidden, false); 1454 RecreateIndex = true; 1455 } 1456 } 1457 if (RecreateIndex) { 1458 GlobalModuleIndex::writeIndex( 1459 getFileManager(), 1460 getPreprocessor().getHeaderSearchInfo().getModuleCachePath()); 1461 ModuleManager->resetForReload(); 1462 ModuleManager->loadGlobalIndex(); 1463 GlobalIndex = ModuleManager->getGlobalIndex(); 1464 } 1465 HaveFullGlobalModuleIndex = true; 1466 } 1467 return GlobalIndex; 1468 } 1469 1470 // Check global module index for missing imports. 1471 bool 1472 CompilerInstance::lookupMissingImports(StringRef Name, 1473 SourceLocation TriggerLoc) { 1474 // Look for the symbol in non-imported modules, but only if an error 1475 // actually occurred. 1476 if (!buildingModule()) { 1477 // Load global module index, or retrieve a previously loaded one. 1478 GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex( 1479 TriggerLoc); 1480 1481 // Only if we have a global index. 1482 if (GlobalIndex) { 1483 GlobalModuleIndex::HitSet FoundModules; 1484 1485 // Find the modules that reference the identifier. 1486 // Note that this only finds top-level modules. 1487 // We'll let diagnoseTypo find the actual declaration module. 1488 if (GlobalIndex->lookupIdentifier(Name, FoundModules)) 1489 return true; 1490 } 1491 } 1492 1493 return false; 1494 } 1495