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