1 //===--- CompilerInstance.cpp ---------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "clang/Frontend/CompilerInstance.h" 10 #include "clang/AST/ASTConsumer.h" 11 #include "clang/AST/ASTContext.h" 12 #include "clang/AST/Decl.h" 13 #include "clang/Basic/CharInfo.h" 14 #include "clang/Basic/Diagnostic.h" 15 #include "clang/Basic/DiagnosticOptions.h" 16 #include "clang/Basic/FileManager.h" 17 #include "clang/Basic/LangStandard.h" 18 #include "clang/Basic/SourceManager.h" 19 #include "clang/Basic/Stack.h" 20 #include "clang/Basic/TargetInfo.h" 21 #include "clang/Basic/Version.h" 22 #include "clang/Config/config.h" 23 #include "clang/Frontend/ChainedDiagnosticConsumer.h" 24 #include "clang/Frontend/FrontendAction.h" 25 #include "clang/Frontend/FrontendActions.h" 26 #include "clang/Frontend/FrontendDiagnostic.h" 27 #include "clang/Frontend/FrontendPluginRegistry.h" 28 #include "clang/Frontend/LogDiagnosticPrinter.h" 29 #include "clang/Frontend/SARIFDiagnosticPrinter.h" 30 #include "clang/Frontend/SerializedDiagnosticPrinter.h" 31 #include "clang/Frontend/TextDiagnosticPrinter.h" 32 #include "clang/Frontend/Utils.h" 33 #include "clang/Frontend/VerifyDiagnosticConsumer.h" 34 #include "clang/Lex/HeaderSearch.h" 35 #include "clang/Lex/Preprocessor.h" 36 #include "clang/Lex/PreprocessorOptions.h" 37 #include "clang/Sema/CodeCompleteConsumer.h" 38 #include "clang/Sema/Sema.h" 39 #include "clang/Serialization/ASTReader.h" 40 #include "clang/Serialization/GlobalModuleIndex.h" 41 #include "clang/Serialization/InMemoryModuleCache.h" 42 #include "llvm/ADT/ScopeExit.h" 43 #include "llvm/ADT/Statistic.h" 44 #include "llvm/Support/BuryPointer.h" 45 #include "llvm/Support/CrashRecoveryContext.h" 46 #include "llvm/Support/Errc.h" 47 #include "llvm/Support/FileSystem.h" 48 #include "llvm/Support/Host.h" 49 #include "llvm/Support/LockFileManager.h" 50 #include "llvm/Support/MemoryBuffer.h" 51 #include "llvm/Support/Path.h" 52 #include "llvm/Support/Program.h" 53 #include "llvm/Support/Signals.h" 54 #include "llvm/Support/TimeProfiler.h" 55 #include "llvm/Support/Timer.h" 56 #include "llvm/Support/raw_ostream.h" 57 #include <time.h> 58 #include <utility> 59 60 using namespace clang; 61 62 CompilerInstance::CompilerInstance( 63 std::shared_ptr<PCHContainerOperations> PCHContainerOps, 64 InMemoryModuleCache *SharedModuleCache) 65 : ModuleLoader(/* BuildingModule = */ SharedModuleCache), 66 Invocation(new CompilerInvocation()), 67 ModuleCache(SharedModuleCache ? SharedModuleCache 68 : new InMemoryModuleCache), 69 ThePCHContainerOperations(std::move(PCHContainerOps)) {} 70 71 CompilerInstance::~CompilerInstance() { 72 assert(OutputFiles.empty() && "Still output files in flight?"); 73 } 74 75 void CompilerInstance::setInvocation( 76 std::shared_ptr<CompilerInvocation> Value) { 77 Invocation = std::move(Value); 78 } 79 80 bool CompilerInstance::shouldBuildGlobalModuleIndex() const { 81 return (BuildGlobalModuleIndex || 82 (TheASTReader && TheASTReader->isGlobalIndexUnavailable() && 83 getFrontendOpts().GenerateGlobalModuleIndex)) && 84 !DisableGeneratingGlobalModuleIndex; 85 } 86 87 void CompilerInstance::setDiagnostics(DiagnosticsEngine *Value) { 88 Diagnostics = Value; 89 } 90 91 void CompilerInstance::setVerboseOutputStream(raw_ostream &Value) { 92 OwnedVerboseOutputStream.reset(); 93 VerboseOutputStream = &Value; 94 } 95 96 void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) { 97 OwnedVerboseOutputStream.swap(Value); 98 VerboseOutputStream = OwnedVerboseOutputStream.get(); 99 } 100 101 void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; } 102 void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; } 103 104 bool CompilerInstance::createTarget() { 105 // Create the target instance. 106 setTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), 107 getInvocation().TargetOpts)); 108 if (!hasTarget()) 109 return false; 110 111 // Check whether AuxTarget exists, if not, then create TargetInfo for the 112 // other side of CUDA/OpenMP/SYCL compilation. 113 if (!getAuxTarget() && 114 (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 115 getLangOpts().SYCLIsDevice) && 116 !getFrontendOpts().AuxTriple.empty()) { 117 auto TO = std::make_shared<TargetOptions>(); 118 TO->Triple = llvm::Triple::normalize(getFrontendOpts().AuxTriple); 119 if (getFrontendOpts().AuxTargetCPU) 120 TO->CPU = getFrontendOpts().AuxTargetCPU.value(); 121 if (getFrontendOpts().AuxTargetFeatures) 122 TO->FeaturesAsWritten = getFrontendOpts().AuxTargetFeatures.value(); 123 TO->HostTriple = getTarget().getTriple().str(); 124 setAuxTarget(TargetInfo::CreateTargetInfo(getDiagnostics(), TO)); 125 } 126 127 if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) { 128 if (getLangOpts().RoundingMath) { 129 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_rounding); 130 getLangOpts().RoundingMath = false; 131 } 132 auto FPExc = getLangOpts().getFPExceptionMode(); 133 if (FPExc != LangOptions::FPE_Default && FPExc != LangOptions::FPE_Ignore) { 134 getDiagnostics().Report(diag::warn_fe_backend_unsupported_fp_exceptions); 135 getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore); 136 } 137 // FIXME: can we disable FEnvAccess? 138 } 139 140 // We should do it here because target knows nothing about 141 // language options when it's being created. 142 if (getLangOpts().OpenCL && 143 !getTarget().validateOpenCLTarget(getLangOpts(), getDiagnostics())) 144 return false; 145 146 // Inform the target of the language options. 147 // FIXME: We shouldn't need to do this, the target should be immutable once 148 // created. This complexity should be lifted elsewhere. 149 getTarget().adjust(getDiagnostics(), getLangOpts()); 150 151 // Adjust target options based on codegen options. 152 getTarget().adjustTargetOptions(getCodeGenOpts(), getTargetOpts()); 153 154 if (auto *Aux = getAuxTarget()) 155 getTarget().setAuxTarget(Aux); 156 157 return true; 158 } 159 160 llvm::vfs::FileSystem &CompilerInstance::getVirtualFileSystem() const { 161 return getFileManager().getVirtualFileSystem(); 162 } 163 164 void CompilerInstance::setFileManager(FileManager *Value) { 165 FileMgr = Value; 166 } 167 168 void CompilerInstance::setSourceManager(SourceManager *Value) { 169 SourceMgr = Value; 170 } 171 172 void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) { 173 PP = std::move(Value); 174 } 175 176 void CompilerInstance::setASTContext(ASTContext *Value) { 177 Context = Value; 178 179 if (Context && Consumer) 180 getASTConsumer().Initialize(getASTContext()); 181 } 182 183 void CompilerInstance::setSema(Sema *S) { 184 TheSema.reset(S); 185 } 186 187 void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) { 188 Consumer = std::move(Value); 189 190 if (Context && Consumer) 191 getASTConsumer().Initialize(getASTContext()); 192 } 193 194 void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) { 195 CompletionConsumer.reset(Value); 196 } 197 198 std::unique_ptr<Sema> CompilerInstance::takeSema() { 199 return std::move(TheSema); 200 } 201 202 IntrusiveRefCntPtr<ASTReader> CompilerInstance::getASTReader() const { 203 return TheASTReader; 204 } 205 void CompilerInstance::setASTReader(IntrusiveRefCntPtr<ASTReader> Reader) { 206 assert(ModuleCache.get() == &Reader->getModuleManager().getModuleCache() && 207 "Expected ASTReader to use the same PCM cache"); 208 TheASTReader = std::move(Reader); 209 } 210 211 std::shared_ptr<ModuleDependencyCollector> 212 CompilerInstance::getModuleDepCollector() const { 213 return ModuleDepCollector; 214 } 215 216 void CompilerInstance::setModuleDepCollector( 217 std::shared_ptr<ModuleDependencyCollector> Collector) { 218 ModuleDepCollector = std::move(Collector); 219 } 220 221 static void collectHeaderMaps(const HeaderSearch &HS, 222 std::shared_ptr<ModuleDependencyCollector> MDC) { 223 SmallVector<std::string, 4> HeaderMapFileNames; 224 HS.getHeaderMapFileNames(HeaderMapFileNames); 225 for (auto &Name : HeaderMapFileNames) 226 MDC->addFile(Name); 227 } 228 229 static void collectIncludePCH(CompilerInstance &CI, 230 std::shared_ptr<ModuleDependencyCollector> MDC) { 231 const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts(); 232 if (PPOpts.ImplicitPCHInclude.empty()) 233 return; 234 235 StringRef PCHInclude = PPOpts.ImplicitPCHInclude; 236 FileManager &FileMgr = CI.getFileManager(); 237 auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude); 238 if (!PCHDir) { 239 MDC->addFile(PCHInclude); 240 return; 241 } 242 243 std::error_code EC; 244 SmallString<128> DirNative; 245 llvm::sys::path::native(PCHDir->getName(), DirNative); 246 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem(); 247 SimpleASTReaderListener Validator(CI.getPreprocessor()); 248 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; 249 Dir != DirEnd && !EC; Dir.increment(EC)) { 250 // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not 251 // used here since we're not interested in validating the PCH at this time, 252 // but only to check whether this is a file containing an AST. 253 if (!ASTReader::readASTFileControlBlock( 254 Dir->path(), FileMgr, CI.getPCHContainerReader(), 255 /*FindModuleFileExtensions=*/false, Validator, 256 /*ValidateDiagnosticOptions=*/false)) 257 MDC->addFile(Dir->path()); 258 } 259 } 260 261 static void collectVFSEntries(CompilerInstance &CI, 262 std::shared_ptr<ModuleDependencyCollector> MDC) { 263 if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty()) 264 return; 265 266 // Collect all VFS found. 267 SmallVector<llvm::vfs::YAMLVFSEntry, 16> VFSEntries; 268 for (const std::string &VFSFile : CI.getHeaderSearchOpts().VFSOverlayFiles) { 269 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer = 270 llvm::MemoryBuffer::getFile(VFSFile); 271 if (!Buffer) 272 return; 273 llvm::vfs::collectVFSFromYAML(std::move(Buffer.get()), 274 /*DiagHandler*/ nullptr, VFSFile, VFSEntries); 275 } 276 277 for (auto &E : VFSEntries) 278 MDC->addFile(E.VPath, E.RPath); 279 } 280 281 // Diagnostics 282 static void SetUpDiagnosticLog(DiagnosticOptions *DiagOpts, 283 const CodeGenOptions *CodeGenOpts, 284 DiagnosticsEngine &Diags) { 285 std::error_code EC; 286 std::unique_ptr<raw_ostream> StreamOwner; 287 raw_ostream *OS = &llvm::errs(); 288 if (DiagOpts->DiagnosticLogFile != "-") { 289 // Create the output stream. 290 auto FileOS = std::make_unique<llvm::raw_fd_ostream>( 291 DiagOpts->DiagnosticLogFile, EC, 292 llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF); 293 if (EC) { 294 Diags.Report(diag::warn_fe_cc_log_diagnostics_failure) 295 << DiagOpts->DiagnosticLogFile << EC.message(); 296 } else { 297 FileOS->SetUnbuffered(); 298 OS = FileOS.get(); 299 StreamOwner = std::move(FileOS); 300 } 301 } 302 303 // Chain in the diagnostic client which will log the diagnostics. 304 auto Logger = std::make_unique<LogDiagnosticPrinter>(*OS, DiagOpts, 305 std::move(StreamOwner)); 306 if (CodeGenOpts) 307 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags); 308 if (Diags.ownsClient()) { 309 Diags.setClient( 310 new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger))); 311 } else { 312 Diags.setClient( 313 new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger))); 314 } 315 } 316 317 static void SetupSerializedDiagnostics(DiagnosticOptions *DiagOpts, 318 DiagnosticsEngine &Diags, 319 StringRef OutputFile) { 320 auto SerializedConsumer = 321 clang::serialized_diags::create(OutputFile, DiagOpts); 322 323 if (Diags.ownsClient()) { 324 Diags.setClient(new ChainedDiagnosticConsumer( 325 Diags.takeClient(), std::move(SerializedConsumer))); 326 } else { 327 Diags.setClient(new ChainedDiagnosticConsumer( 328 Diags.getClient(), std::move(SerializedConsumer))); 329 } 330 } 331 332 void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client, 333 bool ShouldOwnClient) { 334 Diagnostics = createDiagnostics(&getDiagnosticOpts(), Client, 335 ShouldOwnClient, &getCodeGenOpts()); 336 } 337 338 IntrusiveRefCntPtr<DiagnosticsEngine> 339 CompilerInstance::createDiagnostics(DiagnosticOptions *Opts, 340 DiagnosticConsumer *Client, 341 bool ShouldOwnClient, 342 const CodeGenOptions *CodeGenOpts) { 343 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 344 IntrusiveRefCntPtr<DiagnosticsEngine> 345 Diags(new DiagnosticsEngine(DiagID, Opts)); 346 347 // Create the diagnostic client for reporting errors or for 348 // implementing -verify. 349 if (Client) { 350 Diags->setClient(Client, ShouldOwnClient); 351 } else if (Opts->getFormat() == DiagnosticOptions::SARIF) { 352 Diags->setClient(new SARIFDiagnosticPrinter(llvm::errs(), Opts)); 353 } else 354 Diags->setClient(new TextDiagnosticPrinter(llvm::errs(), Opts)); 355 356 // Chain in -verify checker, if requested. 357 if (Opts->VerifyDiagnostics) 358 Diags->setClient(new VerifyDiagnosticConsumer(*Diags)); 359 360 // Chain in -diagnostic-log-file dumper, if requested. 361 if (!Opts->DiagnosticLogFile.empty()) 362 SetUpDiagnosticLog(Opts, CodeGenOpts, *Diags); 363 364 if (!Opts->DiagnosticSerializationFile.empty()) 365 SetupSerializedDiagnostics(Opts, *Diags, 366 Opts->DiagnosticSerializationFile); 367 368 // Configure our handling of diagnostics. 369 ProcessWarningOptions(*Diags, *Opts); 370 371 return Diags; 372 } 373 374 // File Manager 375 376 FileManager *CompilerInstance::createFileManager( 377 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { 378 if (!VFS) 379 VFS = FileMgr ? &FileMgr->getVirtualFileSystem() 380 : createVFSFromCompilerInvocation(getInvocation(), 381 getDiagnostics()); 382 assert(VFS && "FileManager has no VFS?"); 383 FileMgr = new FileManager(getFileSystemOpts(), std::move(VFS)); 384 return FileMgr.get(); 385 } 386 387 // Source Manager 388 389 void CompilerInstance::createSourceManager(FileManager &FileMgr) { 390 SourceMgr = new SourceManager(getDiagnostics(), FileMgr); 391 } 392 393 // Initialize the remapping of files to alternative contents, e.g., 394 // those specified through other files. 395 static void InitializeFileRemapping(DiagnosticsEngine &Diags, 396 SourceManager &SourceMgr, 397 FileManager &FileMgr, 398 const PreprocessorOptions &InitOpts) { 399 // Remap files in the source manager (with buffers). 400 for (const auto &RB : InitOpts.RemappedFileBuffers) { 401 // Create the file entry for the file that we're mapping from. 402 const FileEntry *FromFile = 403 FileMgr.getVirtualFile(RB.first, RB.second->getBufferSize(), 0); 404 if (!FromFile) { 405 Diags.Report(diag::err_fe_remap_missing_from_file) << RB.first; 406 if (!InitOpts.RetainRemappedFileBuffers) 407 delete RB.second; 408 continue; 409 } 410 411 // Override the contents of the "from" file with the contents of the 412 // "to" file. If the caller owns the buffers, then pass a MemoryBufferRef; 413 // otherwise, pass as a std::unique_ptr<MemoryBuffer> to transfer ownership 414 // to the SourceManager. 415 if (InitOpts.RetainRemappedFileBuffers) 416 SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef()); 417 else 418 SourceMgr.overrideFileContents( 419 FromFile, std::unique_ptr<llvm::MemoryBuffer>( 420 const_cast<llvm::MemoryBuffer *>(RB.second))); 421 } 422 423 // Remap files in the source manager (with other files). 424 for (const auto &RF : InitOpts.RemappedFiles) { 425 // Find the file that we're mapping to. 426 Optional<FileEntryRef> ToFile = FileMgr.getOptionalFileRef(RF.second); 427 if (!ToFile) { 428 Diags.Report(diag::err_fe_remap_missing_to_file) << RF.first << RF.second; 429 continue; 430 } 431 432 // Create the file entry for the file that we're mapping from. 433 const FileEntry *FromFile = 434 FileMgr.getVirtualFile(RF.first, ToFile->getSize(), 0); 435 if (!FromFile) { 436 Diags.Report(diag::err_fe_remap_missing_from_file) << RF.first; 437 continue; 438 } 439 440 // Override the contents of the "from" file with the contents of 441 // the "to" file. 442 SourceMgr.overrideFileContents(FromFile, *ToFile); 443 } 444 445 SourceMgr.setOverridenFilesKeepOriginalName( 446 InitOpts.RemappedFilesKeepOriginalName); 447 } 448 449 // Preprocessor 450 451 void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) { 452 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 453 454 // The AST reader holds a reference to the old preprocessor (if any). 455 TheASTReader.reset(); 456 457 // Create the Preprocessor. 458 HeaderSearch *HeaderInfo = 459 new HeaderSearch(getHeaderSearchOptsPtr(), getSourceManager(), 460 getDiagnostics(), getLangOpts(), &getTarget()); 461 PP = std::make_shared<Preprocessor>(Invocation->getPreprocessorOptsPtr(), 462 getDiagnostics(), getLangOpts(), 463 getSourceManager(), *HeaderInfo, *this, 464 /*IdentifierInfoLookup=*/nullptr, 465 /*OwnsHeaderSearch=*/true, TUKind); 466 getTarget().adjust(getDiagnostics(), getLangOpts()); 467 PP->Initialize(getTarget(), getAuxTarget()); 468 469 if (PPOpts.DetailedRecord) 470 PP->createPreprocessingRecord(); 471 472 // Apply remappings to the source manager. 473 InitializeFileRemapping(PP->getDiagnostics(), PP->getSourceManager(), 474 PP->getFileManager(), PPOpts); 475 476 // Predefine macros and configure the preprocessor. 477 InitializePreprocessor(*PP, PPOpts, getPCHContainerReader(), 478 getFrontendOpts()); 479 480 // Initialize the header search object. In CUDA compilations, we use the aux 481 // triple (the host triple) to initialize our header search, since we need to 482 // find the host headers in order to compile the CUDA code. 483 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple(); 484 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA && 485 PP->getAuxTargetInfo()) 486 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple(); 487 488 ApplyHeaderSearchOptions(PP->getHeaderSearchInfo(), getHeaderSearchOpts(), 489 PP->getLangOpts(), *HeaderSearchTriple); 490 491 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP); 492 493 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) { 494 std::string ModuleHash = getInvocation().getModuleHash(); 495 PP->getHeaderSearchInfo().setModuleHash(ModuleHash); 496 PP->getHeaderSearchInfo().setModuleCachePath( 497 getSpecificModuleCachePath(ModuleHash)); 498 } 499 500 // Handle generating dependencies, if requested. 501 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts(); 502 if (!DepOpts.OutputFile.empty()) 503 addDependencyCollector(std::make_shared<DependencyFileGenerator>(DepOpts)); 504 if (!DepOpts.DOTOutputFile.empty()) 505 AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile, 506 getHeaderSearchOpts().Sysroot); 507 508 // If we don't have a collector, but we are collecting module dependencies, 509 // then we're the top level compiler instance and need to create one. 510 if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) { 511 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>( 512 DepOpts.ModuleDependencyOutputDir); 513 } 514 515 // If there is a module dep collector, register with other dep collectors 516 // and also (a) collect header maps and (b) TODO: input vfs overlay files. 517 if (ModuleDepCollector) { 518 addDependencyCollector(ModuleDepCollector); 519 collectHeaderMaps(PP->getHeaderSearchInfo(), ModuleDepCollector); 520 collectIncludePCH(*this, ModuleDepCollector); 521 collectVFSEntries(*this, ModuleDepCollector); 522 } 523 524 for (auto &Listener : DependencyCollectors) 525 Listener->attachToPreprocessor(*PP); 526 527 // Handle generating header include information, if requested. 528 if (DepOpts.ShowHeaderIncludes) 529 AttachHeaderIncludeGen(*PP, DepOpts); 530 if (!DepOpts.HeaderIncludeOutputFile.empty()) { 531 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile; 532 if (OutputPath == "-") 533 OutputPath = ""; 534 AttachHeaderIncludeGen(*PP, DepOpts, 535 /*ShowAllHeaders=*/true, OutputPath, 536 /*ShowDepth=*/false); 537 } 538 539 if (DepOpts.ShowIncludesDest != ShowIncludesDestination::None) { 540 AttachHeaderIncludeGen(*PP, DepOpts, 541 /*ShowAllHeaders=*/true, /*OutputPath=*/"", 542 /*ShowDepth=*/true, /*MSStyle=*/true); 543 } 544 } 545 546 std::string CompilerInstance::getSpecificModuleCachePath(StringRef ModuleHash) { 547 // Set up the module path, including the hash for the module-creation options. 548 SmallString<256> SpecificModuleCache(getHeaderSearchOpts().ModuleCachePath); 549 if (!SpecificModuleCache.empty() && !getHeaderSearchOpts().DisableModuleHash) 550 llvm::sys::path::append(SpecificModuleCache, ModuleHash); 551 return std::string(SpecificModuleCache.str()); 552 } 553 554 // ASTContext 555 556 void CompilerInstance::createASTContext() { 557 Preprocessor &PP = getPreprocessor(); 558 auto *Context = new ASTContext(getLangOpts(), PP.getSourceManager(), 559 PP.getIdentifierTable(), PP.getSelectorTable(), 560 PP.getBuiltinInfo(), PP.TUKind); 561 Context->InitBuiltinTypes(getTarget(), getAuxTarget()); 562 setASTContext(Context); 563 } 564 565 // ExternalASTSource 566 567 namespace { 568 // Helper to recursively read the module names for all modules we're adding. 569 // We mark these as known and redirect any attempt to load that module to 570 // the files we were handed. 571 struct ReadModuleNames : ASTReaderListener { 572 Preprocessor &PP; 573 llvm::SmallVector<std::string, 8> LoadedModules; 574 575 ReadModuleNames(Preprocessor &PP) : PP(PP) {} 576 577 void ReadModuleName(StringRef ModuleName) override { 578 // Keep the module name as a string for now. It's not safe to create a new 579 // IdentifierInfo from an ASTReader callback. 580 LoadedModules.push_back(ModuleName.str()); 581 } 582 583 void registerAll() { 584 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap(); 585 for (const std::string &LoadedModule : LoadedModules) 586 MM.cacheModuleLoad(*PP.getIdentifierInfo(LoadedModule), 587 MM.findModule(LoadedModule)); 588 LoadedModules.clear(); 589 } 590 591 void markAllUnavailable() { 592 for (const std::string &LoadedModule : LoadedModules) { 593 if (Module *M = PP.getHeaderSearchInfo().getModuleMap().findModule( 594 LoadedModule)) { 595 M->HasIncompatibleModuleFile = true; 596 597 // Mark module as available if the only reason it was unavailable 598 // was missing headers. 599 SmallVector<Module *, 2> Stack; 600 Stack.push_back(M); 601 while (!Stack.empty()) { 602 Module *Current = Stack.pop_back_val(); 603 if (Current->IsUnimportable) continue; 604 Current->IsAvailable = true; 605 Stack.insert(Stack.end(), 606 Current->submodule_begin(), Current->submodule_end()); 607 } 608 } 609 } 610 LoadedModules.clear(); 611 } 612 }; 613 } // namespace 614 615 void CompilerInstance::createPCHExternalASTSource( 616 StringRef Path, DisableValidationForModuleKind DisableValidation, 617 bool AllowPCHWithCompilerErrors, void *DeserializationListener, 618 bool OwnDeserializationListener) { 619 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; 620 TheASTReader = createPCHExternalASTSource( 621 Path, getHeaderSearchOpts().Sysroot, DisableValidation, 622 AllowPCHWithCompilerErrors, getPreprocessor(), getModuleCache(), 623 getASTContext(), getPCHContainerReader(), 624 getFrontendOpts().ModuleFileExtensions, DependencyCollectors, 625 DeserializationListener, OwnDeserializationListener, Preamble, 626 getFrontendOpts().UseGlobalModuleIndex); 627 } 628 629 IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource( 630 StringRef Path, StringRef Sysroot, 631 DisableValidationForModuleKind DisableValidation, 632 bool AllowPCHWithCompilerErrors, Preprocessor &PP, 633 InMemoryModuleCache &ModuleCache, ASTContext &Context, 634 const PCHContainerReader &PCHContainerRdr, 635 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 636 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors, 637 void *DeserializationListener, bool OwnDeserializationListener, 638 bool Preamble, bool UseGlobalModuleIndex) { 639 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); 640 641 IntrusiveRefCntPtr<ASTReader> Reader(new ASTReader( 642 PP, ModuleCache, &Context, PCHContainerRdr, Extensions, 643 Sysroot.empty() ? "" : Sysroot.data(), DisableValidation, 644 AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ false, 645 HSOpts.ModulesValidateSystemHeaders, HSOpts.ValidateASTInputFilesContent, 646 UseGlobalModuleIndex)); 647 648 // We need the external source to be set up before we read the AST, because 649 // eagerly-deserialized declarations may use it. 650 Context.setExternalSource(Reader.get()); 651 652 Reader->setDeserializationListener( 653 static_cast<ASTDeserializationListener *>(DeserializationListener), 654 /*TakeOwnership=*/OwnDeserializationListener); 655 656 for (auto &Listener : DependencyCollectors) 657 Listener->attachToASTReader(*Reader); 658 659 auto Listener = std::make_unique<ReadModuleNames>(PP); 660 auto &ListenerRef = *Listener; 661 ASTReader::ListenerScope ReadModuleNamesListener(*Reader, 662 std::move(Listener)); 663 664 switch (Reader->ReadAST(Path, 665 Preamble ? serialization::MK_Preamble 666 : serialization::MK_PCH, 667 SourceLocation(), 668 ASTReader::ARR_None)) { 669 case ASTReader::Success: 670 // Set the predefines buffer as suggested by the PCH reader. Typically, the 671 // predefines buffer will be empty. 672 PP.setPredefines(Reader->getSuggestedPredefines()); 673 ListenerRef.registerAll(); 674 return Reader; 675 676 case ASTReader::Failure: 677 // Unrecoverable failure: don't even try to process the input file. 678 break; 679 680 case ASTReader::Missing: 681 case ASTReader::OutOfDate: 682 case ASTReader::VersionMismatch: 683 case ASTReader::ConfigurationMismatch: 684 case ASTReader::HadErrors: 685 // No suitable PCH file could be found. Return an error. 686 break; 687 } 688 689 ListenerRef.markAllUnavailable(); 690 Context.setExternalSource(nullptr); 691 return nullptr; 692 } 693 694 // Code Completion 695 696 static bool EnableCodeCompletion(Preprocessor &PP, 697 StringRef Filename, 698 unsigned Line, 699 unsigned Column) { 700 // Tell the source manager to chop off the given file at a specific 701 // line and column. 702 auto Entry = PP.getFileManager().getFile(Filename); 703 if (!Entry) { 704 PP.getDiagnostics().Report(diag::err_fe_invalid_code_complete_file) 705 << Filename; 706 return true; 707 } 708 709 // Truncate the named file at the given line/column. 710 PP.SetCodeCompletionPoint(*Entry, Line, Column); 711 return false; 712 } 713 714 void CompilerInstance::createCodeCompletionConsumer() { 715 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt; 716 if (!CompletionConsumer) { 717 setCodeCompletionConsumer(createCodeCompletionConsumer( 718 getPreprocessor(), Loc.FileName, Loc.Line, Loc.Column, 719 getFrontendOpts().CodeCompleteOpts, llvm::outs())); 720 return; 721 } else if (EnableCodeCompletion(getPreprocessor(), Loc.FileName, 722 Loc.Line, Loc.Column)) { 723 setCodeCompletionConsumer(nullptr); 724 return; 725 } 726 } 727 728 void CompilerInstance::createFrontendTimer() { 729 FrontendTimerGroup.reset( 730 new llvm::TimerGroup("frontend", "Clang front-end time report")); 731 FrontendTimer.reset( 732 new llvm::Timer("frontend", "Clang front-end timer", 733 *FrontendTimerGroup)); 734 } 735 736 CodeCompleteConsumer * 737 CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP, 738 StringRef Filename, 739 unsigned Line, 740 unsigned Column, 741 const CodeCompleteOptions &Opts, 742 raw_ostream &OS) { 743 if (EnableCodeCompletion(PP, Filename, Line, Column)) 744 return nullptr; 745 746 // Set up the creation routine for code-completion. 747 return new PrintingCodeCompleteConsumer(Opts, OS); 748 } 749 750 void CompilerInstance::createSema(TranslationUnitKind TUKind, 751 CodeCompleteConsumer *CompletionConsumer) { 752 TheSema.reset(new Sema(getPreprocessor(), getASTContext(), getASTConsumer(), 753 TUKind, CompletionConsumer)); 754 // Attach the external sema source if there is any. 755 if (ExternalSemaSrc) { 756 TheSema->addExternalSource(ExternalSemaSrc.get()); 757 ExternalSemaSrc->InitializeSema(*TheSema); 758 } 759 } 760 761 // Output Files 762 763 void CompilerInstance::clearOutputFiles(bool EraseFiles) { 764 // The ASTConsumer can own streams that write to the output files. 765 assert(!hasASTConsumer() && "ASTConsumer should be reset"); 766 // Ignore errors that occur when trying to discard the temp file. 767 for (OutputFile &OF : OutputFiles) { 768 if (EraseFiles) { 769 if (OF.File) 770 consumeError(OF.File->discard()); 771 if (!OF.Filename.empty()) 772 llvm::sys::fs::remove(OF.Filename); 773 continue; 774 } 775 776 if (!OF.File) 777 continue; 778 779 if (OF.File->TmpName.empty()) { 780 consumeError(OF.File->discard()); 781 continue; 782 } 783 784 llvm::Error E = OF.File->keep(OF.Filename); 785 if (!E) 786 continue; 787 788 getDiagnostics().Report(diag::err_unable_to_rename_temp) 789 << OF.File->TmpName << OF.Filename << std::move(E); 790 791 llvm::sys::fs::remove(OF.File->TmpName); 792 } 793 OutputFiles.clear(); 794 if (DeleteBuiltModules) { 795 for (auto &Module : BuiltModules) 796 llvm::sys::fs::remove(Module.second); 797 BuiltModules.clear(); 798 } 799 } 800 801 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createDefaultOutputFile( 802 bool Binary, StringRef InFile, StringRef Extension, bool RemoveFileOnSignal, 803 bool CreateMissingDirectories, bool ForceUseTemporary) { 804 StringRef OutputPath = getFrontendOpts().OutputFile; 805 Optional<SmallString<128>> PathStorage; 806 if (OutputPath.empty()) { 807 if (InFile == "-" || Extension.empty()) { 808 OutputPath = "-"; 809 } else { 810 PathStorage.emplace(InFile); 811 llvm::sys::path::replace_extension(*PathStorage, Extension); 812 OutputPath = *PathStorage; 813 } 814 } 815 816 return createOutputFile(OutputPath, Binary, RemoveFileOnSignal, 817 getFrontendOpts().UseTemporary || ForceUseTemporary, 818 CreateMissingDirectories); 819 } 820 821 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() { 822 return std::make_unique<llvm::raw_null_ostream>(); 823 } 824 825 std::unique_ptr<raw_pwrite_stream> 826 CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary, 827 bool RemoveFileOnSignal, bool UseTemporary, 828 bool CreateMissingDirectories) { 829 Expected<std::unique_ptr<raw_pwrite_stream>> OS = 830 createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary, 831 CreateMissingDirectories); 832 if (OS) 833 return std::move(*OS); 834 getDiagnostics().Report(diag::err_fe_unable_to_open_output) 835 << OutputPath << errorToErrorCode(OS.takeError()).message(); 836 return nullptr; 837 } 838 839 Expected<std::unique_ptr<llvm::raw_pwrite_stream>> 840 CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary, 841 bool RemoveFileOnSignal, 842 bool UseTemporary, 843 bool CreateMissingDirectories) { 844 assert((!CreateMissingDirectories || UseTemporary) && 845 "CreateMissingDirectories is only allowed when using temporary files"); 846 847 // If '-working-directory' was passed, the output filename should be 848 // relative to that. 849 Optional<SmallString<128>> AbsPath; 850 if (OutputPath != "-" && !llvm::sys::path::is_absolute(OutputPath)) { 851 AbsPath.emplace(OutputPath); 852 FileMgr->FixupRelativePath(*AbsPath); 853 OutputPath = *AbsPath; 854 } 855 856 std::unique_ptr<llvm::raw_fd_ostream> OS; 857 Optional<StringRef> OSFile; 858 859 if (UseTemporary) { 860 if (OutputPath == "-") 861 UseTemporary = false; 862 else { 863 llvm::sys::fs::file_status Status; 864 llvm::sys::fs::status(OutputPath, Status); 865 if (llvm::sys::fs::exists(Status)) { 866 // Fail early if we can't write to the final destination. 867 if (!llvm::sys::fs::can_write(OutputPath)) 868 return llvm::errorCodeToError( 869 make_error_code(llvm::errc::operation_not_permitted)); 870 871 // Don't use a temporary if the output is a special file. This handles 872 // things like '-o /dev/null' 873 if (!llvm::sys::fs::is_regular_file(Status)) 874 UseTemporary = false; 875 } 876 } 877 } 878 879 Optional<llvm::sys::fs::TempFile> Temp; 880 if (UseTemporary) { 881 // Create a temporary file. 882 // Insert -%%%%%%%% before the extension (if any), and because some tools 883 // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build 884 // artifacts, also append .tmp. 885 StringRef OutputExtension = llvm::sys::path::extension(OutputPath); 886 SmallString<128> TempPath = 887 StringRef(OutputPath).drop_back(OutputExtension.size()); 888 TempPath += "-%%%%%%%%"; 889 TempPath += OutputExtension; 890 TempPath += ".tmp"; 891 Expected<llvm::sys::fs::TempFile> ExpectedFile = 892 llvm::sys::fs::TempFile::create( 893 TempPath, llvm::sys::fs::all_read | llvm::sys::fs::all_write, 894 Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text); 895 896 llvm::Error E = handleErrors( 897 ExpectedFile.takeError(), [&](const llvm::ECError &E) -> llvm::Error { 898 std::error_code EC = E.convertToErrorCode(); 899 if (CreateMissingDirectories && 900 EC == llvm::errc::no_such_file_or_directory) { 901 StringRef Parent = llvm::sys::path::parent_path(OutputPath); 902 EC = llvm::sys::fs::create_directories(Parent); 903 if (!EC) { 904 ExpectedFile = llvm::sys::fs::TempFile::create(TempPath); 905 if (!ExpectedFile) 906 return llvm::errorCodeToError( 907 llvm::errc::no_such_file_or_directory); 908 } 909 } 910 return llvm::errorCodeToError(EC); 911 }); 912 913 if (E) { 914 consumeError(std::move(E)); 915 } else { 916 Temp = std::move(ExpectedFile.get()); 917 OS.reset(new llvm::raw_fd_ostream(Temp->FD, /*shouldClose=*/false)); 918 OSFile = Temp->TmpName; 919 } 920 // If we failed to create the temporary, fallback to writing to the file 921 // directly. This handles the corner case where we cannot write to the 922 // directory, but can write to the file. 923 } 924 925 if (!OS) { 926 OSFile = OutputPath; 927 std::error_code EC; 928 OS.reset(new llvm::raw_fd_ostream( 929 *OSFile, EC, 930 (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_TextWithCRLF))); 931 if (EC) 932 return llvm::errorCodeToError(EC); 933 } 934 935 // Add the output file -- but don't try to remove "-", since this means we are 936 // using stdin. 937 OutputFiles.emplace_back(((OutputPath != "-") ? OutputPath : "").str(), 938 std::move(Temp)); 939 940 if (!Binary || OS->supportsSeeking()) 941 return std::move(OS); 942 943 return std::make_unique<llvm::buffer_unique_ostream>(std::move(OS)); 944 } 945 946 // Initialization Utilities 947 948 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){ 949 return InitializeSourceManager(Input, getDiagnostics(), getFileManager(), 950 getSourceManager()); 951 } 952 953 // static 954 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input, 955 DiagnosticsEngine &Diags, 956 FileManager &FileMgr, 957 SourceManager &SourceMgr) { 958 SrcMgr::CharacteristicKind Kind = 959 Input.getKind().getFormat() == InputKind::ModuleMap 960 ? Input.isSystem() ? SrcMgr::C_System_ModuleMap 961 : SrcMgr::C_User_ModuleMap 962 : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User; 963 964 if (Input.isBuffer()) { 965 SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind)); 966 assert(SourceMgr.getMainFileID().isValid() && 967 "Couldn't establish MainFileID!"); 968 return true; 969 } 970 971 StringRef InputFile = Input.getFile(); 972 973 // Figure out where to get and map in the main file. 974 auto FileOrErr = InputFile == "-" 975 ? FileMgr.getSTDIN() 976 : FileMgr.getFileRef(InputFile, /*OpenFile=*/true); 977 if (!FileOrErr) { 978 // FIXME: include the error in the diagnostic even when it's not stdin. 979 auto EC = llvm::errorToErrorCode(FileOrErr.takeError()); 980 if (InputFile != "-") 981 Diags.Report(diag::err_fe_error_reading) << InputFile; 982 else 983 Diags.Report(diag::err_fe_error_reading_stdin) << EC.message(); 984 return false; 985 } 986 987 SourceMgr.setMainFileID( 988 SourceMgr.createFileID(*FileOrErr, SourceLocation(), Kind)); 989 990 assert(SourceMgr.getMainFileID().isValid() && 991 "Couldn't establish MainFileID!"); 992 return true; 993 } 994 995 // High-Level Operations 996 997 bool CompilerInstance::ExecuteAction(FrontendAction &Act) { 998 assert(hasDiagnostics() && "Diagnostics engine is not initialized!"); 999 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!"); 1000 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!"); 1001 1002 // Mark this point as the bottom of the stack if we don't have somewhere 1003 // better. We generally expect frontend actions to be invoked with (nearly) 1004 // DesiredStackSpace available. 1005 noteBottomOfStack(); 1006 1007 auto FinishDiagnosticClient = llvm::make_scope_exit([&]() { 1008 // Notify the diagnostic client that all files were processed. 1009 getDiagnosticClient().finish(); 1010 }); 1011 1012 raw_ostream &OS = getVerboseOutputStream(); 1013 1014 if (!Act.PrepareToExecute(*this)) 1015 return false; 1016 1017 if (!createTarget()) 1018 return false; 1019 1020 // rewriter project will change target built-in bool type from its default. 1021 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC) 1022 getTarget().noSignedCharForObjCBool(); 1023 1024 // Validate/process some options. 1025 if (getHeaderSearchOpts().Verbose) 1026 OS << "clang -cc1 version " CLANG_VERSION_STRING 1027 << " based upon " << BACKEND_PACKAGE_STRING 1028 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n"; 1029 1030 if (getCodeGenOpts().TimePasses) 1031 createFrontendTimer(); 1032 1033 if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty()) 1034 llvm::EnableStatistics(false); 1035 1036 for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) { 1037 // Reset the ID tables if we are reusing the SourceManager and parsing 1038 // regular files. 1039 if (hasSourceManager() && !Act.isModelParsingAction()) 1040 getSourceManager().clearIDTables(); 1041 1042 if (Act.BeginSourceFile(*this, FIF)) { 1043 if (llvm::Error Err = Act.Execute()) { 1044 consumeError(std::move(Err)); // FIXME this drops errors on the floor. 1045 } 1046 Act.EndSourceFile(); 1047 } 1048 } 1049 1050 if (getDiagnosticOpts().ShowCarets) { 1051 // We can have multiple diagnostics sharing one diagnostic client. 1052 // Get the total number of warnings/errors from the client. 1053 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings(); 1054 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors(); 1055 1056 if (NumWarnings) 1057 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s"); 1058 if (NumWarnings && NumErrors) 1059 OS << " and "; 1060 if (NumErrors) 1061 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s"); 1062 if (NumWarnings || NumErrors) { 1063 OS << " generated"; 1064 if (getLangOpts().CUDA) { 1065 if (!getLangOpts().CUDAIsDevice) { 1066 OS << " when compiling for host"; 1067 } else { 1068 OS << " when compiling for " << getTargetOpts().CPU; 1069 } 1070 } 1071 OS << ".\n"; 1072 } 1073 } 1074 1075 if (getFrontendOpts().ShowStats) { 1076 if (hasFileManager()) { 1077 getFileManager().PrintStats(); 1078 OS << '\n'; 1079 } 1080 llvm::PrintStatistics(OS); 1081 } 1082 StringRef StatsFile = getFrontendOpts().StatsFile; 1083 if (!StatsFile.empty()) { 1084 std::error_code EC; 1085 auto StatS = std::make_unique<llvm::raw_fd_ostream>( 1086 StatsFile, EC, llvm::sys::fs::OF_TextWithCRLF); 1087 if (EC) { 1088 getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file) 1089 << StatsFile << EC.message(); 1090 } else { 1091 llvm::PrintStatisticsJSON(*StatS); 1092 } 1093 } 1094 1095 return !getDiagnostics().getClient()->getNumErrors(); 1096 } 1097 1098 void CompilerInstance::LoadRequestedPlugins() { 1099 // Load any requested plugins. 1100 for (const std::string &Path : getFrontendOpts().Plugins) { 1101 std::string Error; 1102 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error)) 1103 getDiagnostics().Report(diag::err_fe_unable_to_load_plugin) 1104 << Path << Error; 1105 } 1106 1107 // Check if any of the loaded plugins replaces the main AST action 1108 for (const FrontendPluginRegistry::entry &Plugin : 1109 FrontendPluginRegistry::entries()) { 1110 std::unique_ptr<PluginASTAction> P(Plugin.instantiate()); 1111 if (P->getActionType() == PluginASTAction::ReplaceAction) { 1112 getFrontendOpts().ProgramAction = clang::frontend::PluginAction; 1113 getFrontendOpts().ActionName = Plugin.getName().str(); 1114 break; 1115 } 1116 } 1117 } 1118 1119 /// Determine the appropriate source input kind based on language 1120 /// options. 1121 static Language getLanguageFromOptions(const LangOptions &LangOpts) { 1122 if (LangOpts.OpenCL) 1123 return Language::OpenCL; 1124 if (LangOpts.CUDA) 1125 return Language::CUDA; 1126 if (LangOpts.ObjC) 1127 return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC; 1128 return LangOpts.CPlusPlus ? Language::CXX : Language::C; 1129 } 1130 1131 /// Compile a module file for the given module, using the options 1132 /// provided by the importing compiler instance. Returns true if the module 1133 /// was built without errors. 1134 static bool 1135 compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, 1136 StringRef ModuleName, FrontendInputFile Input, 1137 StringRef OriginalModuleMapFile, StringRef ModuleFileName, 1138 llvm::function_ref<void(CompilerInstance &)> PreBuildStep = 1139 [](CompilerInstance &) {}, 1140 llvm::function_ref<void(CompilerInstance &)> PostBuildStep = 1141 [](CompilerInstance &) {}) { 1142 llvm::TimeTraceScope TimeScope("Module Compile", ModuleName); 1143 1144 // Never compile a module that's already finalized - this would cause the 1145 // existing module to be freed, causing crashes if it is later referenced 1146 if (ImportingInstance.getModuleCache().isPCMFinal(ModuleFileName)) { 1147 ImportingInstance.getDiagnostics().Report( 1148 ImportLoc, diag::err_module_rebuild_finalized) 1149 << ModuleName; 1150 return false; 1151 } 1152 1153 // Construct a compiler invocation for creating this module. 1154 auto Invocation = 1155 std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation()); 1156 1157 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 1158 1159 // For any options that aren't intended to affect how a module is built, 1160 // reset them to their default values. 1161 Invocation->resetNonModularOptions(); 1162 1163 // Remove any macro definitions that are explicitly ignored by the module. 1164 // They aren't supposed to affect how the module is built anyway. 1165 HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts(); 1166 llvm::erase_if(PPOpts.Macros, 1167 [&HSOpts](const std::pair<std::string, bool> &def) { 1168 StringRef MacroDef = def.first; 1169 return HSOpts.ModulesIgnoreMacros.contains( 1170 llvm::CachedHashString(MacroDef.split('=').first)); 1171 }); 1172 1173 // If the original compiler invocation had -fmodule-name, pass it through. 1174 Invocation->getLangOpts()->ModuleName = 1175 ImportingInstance.getInvocation().getLangOpts()->ModuleName; 1176 1177 // Note the name of the module we're building. 1178 Invocation->getLangOpts()->CurrentModule = std::string(ModuleName); 1179 1180 // Make sure that the failed-module structure has been allocated in 1181 // the importing instance, and propagate the pointer to the newly-created 1182 // instance. 1183 PreprocessorOptions &ImportingPPOpts 1184 = ImportingInstance.getInvocation().getPreprocessorOpts(); 1185 if (!ImportingPPOpts.FailedModules) 1186 ImportingPPOpts.FailedModules = 1187 std::make_shared<PreprocessorOptions::FailedModulesSet>(); 1188 PPOpts.FailedModules = ImportingPPOpts.FailedModules; 1189 1190 // If there is a module map file, build the module using the module map. 1191 // Set up the inputs/outputs so that we build the module from its umbrella 1192 // header. 1193 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts(); 1194 FrontendOpts.OutputFile = ModuleFileName.str(); 1195 FrontendOpts.DisableFree = false; 1196 FrontendOpts.GenerateGlobalModuleIndex = false; 1197 FrontendOpts.BuildingImplicitModule = true; 1198 FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile); 1199 // Force implicitly-built modules to hash the content of the module file. 1200 HSOpts.ModulesHashContent = true; 1201 FrontendOpts.Inputs = {Input}; 1202 1203 // Don't free the remapped file buffers; they are owned by our caller. 1204 PPOpts.RetainRemappedFileBuffers = true; 1205 1206 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0; 1207 assert(ImportingInstance.getInvocation().getModuleHash() == 1208 Invocation->getModuleHash() && "Module hash mismatch!"); 1209 1210 // Construct a compiler instance that will be used to actually create the 1211 // module. Since we're sharing an in-memory module cache, 1212 // CompilerInstance::CompilerInstance is responsible for finalizing the 1213 // buffers to prevent use-after-frees. 1214 CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(), 1215 &ImportingInstance.getModuleCache()); 1216 auto &Inv = *Invocation; 1217 Instance.setInvocation(std::move(Invocation)); 1218 1219 Instance.createDiagnostics(new ForwardingDiagnosticConsumer( 1220 ImportingInstance.getDiagnosticClient()), 1221 /*ShouldOwnClient=*/true); 1222 1223 if (FrontendOpts.ModulesShareFileManager) { 1224 Instance.setFileManager(&ImportingInstance.getFileManager()); 1225 } else { 1226 Instance.createFileManager(&ImportingInstance.getVirtualFileSystem()); 1227 } 1228 Instance.createSourceManager(Instance.getFileManager()); 1229 SourceManager &SourceMgr = Instance.getSourceManager(); 1230 1231 // Note that this module is part of the module build stack, so that we 1232 // can detect cycles in the module graph. 1233 SourceMgr.setModuleBuildStack( 1234 ImportingInstance.getSourceManager().getModuleBuildStack()); 1235 SourceMgr.pushModuleBuildStack(ModuleName, 1236 FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager())); 1237 1238 // If we're collecting module dependencies, we need to share a collector 1239 // between all of the module CompilerInstances. Other than that, we don't 1240 // want to produce any dependency output from the module build. 1241 Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector()); 1242 Inv.getDependencyOutputOpts() = DependencyOutputOptions(); 1243 1244 ImportingInstance.getDiagnostics().Report(ImportLoc, 1245 diag::remark_module_build) 1246 << ModuleName << ModuleFileName; 1247 1248 PreBuildStep(Instance); 1249 1250 // Execute the action to actually build the module in-place. Use a separate 1251 // thread so that we get a stack large enough. 1252 bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnThread( 1253 [&]() { 1254 GenerateModuleFromModuleMapAction Action; 1255 Instance.ExecuteAction(Action); 1256 }, 1257 DesiredStackSize); 1258 1259 PostBuildStep(Instance); 1260 1261 ImportingInstance.getDiagnostics().Report(ImportLoc, 1262 diag::remark_module_build_done) 1263 << ModuleName; 1264 1265 if (Crashed) { 1266 // Clear the ASTConsumer if it hasn't been already, in case it owns streams 1267 // that must be closed before clearing output files. 1268 Instance.setSema(nullptr); 1269 Instance.setASTConsumer(nullptr); 1270 1271 // Delete any remaining temporary files related to Instance. 1272 Instance.clearOutputFiles(/*EraseFiles=*/true); 1273 } 1274 1275 // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors 1276 // occurred. 1277 return !Instance.getDiagnostics().hasErrorOccurred() || 1278 Instance.getFrontendOpts().AllowPCMWithCompilerErrors; 1279 } 1280 1281 static Optional<FileEntryRef> getPublicModuleMap(FileEntryRef File, 1282 FileManager &FileMgr) { 1283 StringRef Filename = llvm::sys::path::filename(File.getName()); 1284 SmallString<128> PublicFilename(File.getDir().getName()); 1285 if (Filename == "module_private.map") 1286 llvm::sys::path::append(PublicFilename, "module.map"); 1287 else if (Filename == "module.private.modulemap") 1288 llvm::sys::path::append(PublicFilename, "module.modulemap"); 1289 else 1290 return None; 1291 return FileMgr.getOptionalFileRef(PublicFilename); 1292 } 1293 1294 /// Compile a module file for the given module in a separate compiler instance, 1295 /// using the options provided by the importing compiler instance. Returns true 1296 /// if the module was built without errors. 1297 static bool compileModule(CompilerInstance &ImportingInstance, 1298 SourceLocation ImportLoc, Module *Module, 1299 StringRef ModuleFileName) { 1300 InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()), 1301 InputKind::ModuleMap); 1302 1303 // Get or create the module map that we'll use to build this module. 1304 ModuleMap &ModMap 1305 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap(); 1306 bool Result; 1307 if (Optional<FileEntryRef> ModuleMapFile = 1308 ModMap.getContainingModuleMapFile(Module)) { 1309 // Canonicalize compilation to start with the public module map. This is 1310 // vital for submodules declarations in the private module maps to be 1311 // correctly parsed when depending on a top level module in the public one. 1312 if (Optional<FileEntryRef> PublicMMFile = getPublicModuleMap( 1313 *ModuleMapFile, ImportingInstance.getFileManager())) 1314 ModuleMapFile = PublicMMFile; 1315 1316 StringRef ModuleMapFilePath = ModuleMapFile->getNameAsRequested(); 1317 1318 // Use the module map where this module resides. 1319 Result = compileModuleImpl( 1320 ImportingInstance, ImportLoc, Module->getTopLevelModuleName(), 1321 FrontendInputFile(ModuleMapFilePath, IK, +Module->IsSystem), 1322 ModMap.getModuleMapFileForUniquing(Module)->getName(), ModuleFileName); 1323 } else { 1324 // FIXME: We only need to fake up an input file here as a way of 1325 // transporting the module's directory to the module map parser. We should 1326 // be able to do that more directly, and parse from a memory buffer without 1327 // inventing this file. 1328 SmallString<128> FakeModuleMapFile(Module->Directory->getName()); 1329 llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map"); 1330 1331 std::string InferredModuleMapContent; 1332 llvm::raw_string_ostream OS(InferredModuleMapContent); 1333 Module->print(OS); 1334 OS.flush(); 1335 1336 Result = compileModuleImpl( 1337 ImportingInstance, ImportLoc, Module->getTopLevelModuleName(), 1338 FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem), 1339 ModMap.getModuleMapFileForUniquing(Module)->getName(), 1340 ModuleFileName, 1341 [&](CompilerInstance &Instance) { 1342 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer = 1343 llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent); 1344 const FileEntry *ModuleMapFile = Instance.getFileManager().getVirtualFile( 1345 FakeModuleMapFile, InferredModuleMapContent.size(), 0); 1346 Instance.getSourceManager().overrideFileContents( 1347 ModuleMapFile, std::move(ModuleMapBuffer)); 1348 }); 1349 } 1350 1351 // We've rebuilt a module. If we're allowed to generate or update the global 1352 // module index, record that fact in the importing compiler instance. 1353 if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) { 1354 ImportingInstance.setBuildGlobalModuleIndex(true); 1355 } 1356 1357 return Result; 1358 } 1359 1360 /// Read the AST right after compiling the module. 1361 static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance, 1362 SourceLocation ImportLoc, 1363 SourceLocation ModuleNameLoc, 1364 Module *Module, StringRef ModuleFileName, 1365 bool *OutOfDate) { 1366 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics(); 1367 1368 unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing; 1369 if (OutOfDate) 1370 ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate; 1371 1372 // Try to read the module file, now that we've compiled it. 1373 ASTReader::ASTReadResult ReadResult = 1374 ImportingInstance.getASTReader()->ReadAST( 1375 ModuleFileName, serialization::MK_ImplicitModule, ImportLoc, 1376 ModuleLoadCapabilities); 1377 if (ReadResult == ASTReader::Success) 1378 return true; 1379 1380 // The caller wants to handle out-of-date failures. 1381 if (OutOfDate && ReadResult == ASTReader::OutOfDate) { 1382 *OutOfDate = true; 1383 return false; 1384 } 1385 1386 // The ASTReader didn't diagnose the error, so conservatively report it. 1387 if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred()) 1388 Diags.Report(ModuleNameLoc, diag::err_module_not_built) 1389 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc); 1390 1391 return false; 1392 } 1393 1394 /// Compile a module in a separate compiler instance and read the AST, 1395 /// returning true if the module compiles without errors. 1396 static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance, 1397 SourceLocation ImportLoc, 1398 SourceLocation ModuleNameLoc, 1399 Module *Module, 1400 StringRef ModuleFileName) { 1401 if (!compileModule(ImportingInstance, ModuleNameLoc, Module, 1402 ModuleFileName)) { 1403 ImportingInstance.getDiagnostics().Report(ModuleNameLoc, 1404 diag::err_module_not_built) 1405 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc); 1406 return false; 1407 } 1408 1409 return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc, 1410 Module, ModuleFileName, 1411 /*OutOfDate=*/nullptr); 1412 } 1413 1414 /// Compile a module in a separate compiler instance and read the AST, 1415 /// returning true if the module compiles without errors, using a lock manager 1416 /// to avoid building the same module in multiple compiler instances. 1417 /// 1418 /// Uses a lock file manager and exponential backoff to reduce the chances that 1419 /// multiple instances will compete to create the same module. On timeout, 1420 /// deletes the lock file in order to avoid deadlock from crashing processes or 1421 /// bugs in the lock file manager. 1422 static bool compileModuleAndReadASTBehindLock( 1423 CompilerInstance &ImportingInstance, SourceLocation ImportLoc, 1424 SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) { 1425 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics(); 1426 1427 Diags.Report(ModuleNameLoc, diag::remark_module_lock) 1428 << ModuleFileName << Module->Name; 1429 1430 // FIXME: have LockFileManager return an error_code so that we can 1431 // avoid the mkdir when the directory already exists. 1432 StringRef Dir = llvm::sys::path::parent_path(ModuleFileName); 1433 llvm::sys::fs::create_directories(Dir); 1434 1435 while (true) { 1436 llvm::LockFileManager Locked(ModuleFileName); 1437 switch (Locked) { 1438 case llvm::LockFileManager::LFS_Error: 1439 // ModuleCache takes care of correctness and locks are only necessary for 1440 // performance. Fallback to building the module in case of any lock 1441 // related errors. 1442 Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure) 1443 << Module->Name << Locked.getErrorMessage(); 1444 // Clear out any potential leftover. 1445 Locked.unsafeRemoveLockFile(); 1446 [[fallthrough]]; 1447 case llvm::LockFileManager::LFS_Owned: 1448 // We're responsible for building the module ourselves. 1449 return compileModuleAndReadASTImpl(ImportingInstance, ImportLoc, 1450 ModuleNameLoc, Module, ModuleFileName); 1451 1452 case llvm::LockFileManager::LFS_Shared: 1453 break; // The interesting case. 1454 } 1455 1456 // Someone else is responsible for building the module. Wait for them to 1457 // finish. 1458 switch (Locked.waitForUnlock()) { 1459 case llvm::LockFileManager::Res_Success: 1460 break; // The interesting case. 1461 case llvm::LockFileManager::Res_OwnerDied: 1462 continue; // try again to get the lock. 1463 case llvm::LockFileManager::Res_Timeout: 1464 // Since ModuleCache takes care of correctness, we try waiting for 1465 // another process to complete the build so clang does not do it done 1466 // twice. If case of timeout, build it ourselves. 1467 Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout) 1468 << Module->Name; 1469 // Clear the lock file so that future invocations can make progress. 1470 Locked.unsafeRemoveLockFile(); 1471 continue; 1472 } 1473 1474 // Read the module that was just written by someone else. 1475 bool OutOfDate = false; 1476 if (readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc, 1477 Module, ModuleFileName, &OutOfDate)) 1478 return true; 1479 if (!OutOfDate) 1480 return false; 1481 1482 // The module may be out of date in the presence of file system races, 1483 // or if one of its imports depends on header search paths that are not 1484 // consistent with this ImportingInstance. Try again... 1485 } 1486 } 1487 1488 /// Compile a module in a separate compiler instance and read the AST, 1489 /// returning true if the module compiles without errors, potentially using a 1490 /// lock manager to avoid building the same module in multiple compiler 1491 /// instances. 1492 static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance, 1493 SourceLocation ImportLoc, 1494 SourceLocation ModuleNameLoc, 1495 Module *Module, StringRef ModuleFileName) { 1496 return ImportingInstance.getInvocation() 1497 .getFrontendOpts() 1498 .BuildingImplicitModuleUsesLock 1499 ? compileModuleAndReadASTBehindLock(ImportingInstance, ImportLoc, 1500 ModuleNameLoc, Module, 1501 ModuleFileName) 1502 : compileModuleAndReadASTImpl(ImportingInstance, ImportLoc, 1503 ModuleNameLoc, Module, 1504 ModuleFileName); 1505 } 1506 1507 /// Diagnose differences between the current definition of the given 1508 /// configuration macro and the definition provided on the command line. 1509 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro, 1510 Module *Mod, SourceLocation ImportLoc) { 1511 IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro); 1512 SourceManager &SourceMgr = PP.getSourceManager(); 1513 1514 // If this identifier has never had a macro definition, then it could 1515 // not have changed. 1516 if (!Id->hadMacroDefinition()) 1517 return; 1518 auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id); 1519 1520 // Find the macro definition from the command line. 1521 MacroInfo *CmdLineDefinition = nullptr; 1522 for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) { 1523 // We only care about the predefines buffer. 1524 FileID FID = SourceMgr.getFileID(MD->getLocation()); 1525 if (FID.isInvalid() || FID != PP.getPredefinesFileID()) 1526 continue; 1527 if (auto *DMD = dyn_cast<DefMacroDirective>(MD)) 1528 CmdLineDefinition = DMD->getMacroInfo(); 1529 break; 1530 } 1531 1532 auto *CurrentDefinition = PP.getMacroInfo(Id); 1533 if (CurrentDefinition == CmdLineDefinition) { 1534 // Macro matches. Nothing to do. 1535 } else if (!CurrentDefinition) { 1536 // This macro was defined on the command line, then #undef'd later. 1537 // Complain. 1538 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 1539 << true << ConfigMacro << Mod->getFullModuleName(); 1540 auto LatestDef = LatestLocalMD->getDefinition(); 1541 assert(LatestDef.isUndefined() && 1542 "predefined macro went away with no #undef?"); 1543 PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here) 1544 << true; 1545 return; 1546 } else if (!CmdLineDefinition) { 1547 // There was no definition for this macro in the predefines buffer, 1548 // but there was a local definition. Complain. 1549 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 1550 << false << ConfigMacro << Mod->getFullModuleName(); 1551 PP.Diag(CurrentDefinition->getDefinitionLoc(), 1552 diag::note_module_def_undef_here) 1553 << false; 1554 } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP, 1555 /*Syntactically=*/true)) { 1556 // The macro definitions differ. 1557 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 1558 << false << ConfigMacro << Mod->getFullModuleName(); 1559 PP.Diag(CurrentDefinition->getDefinitionLoc(), 1560 diag::note_module_def_undef_here) 1561 << false; 1562 } 1563 } 1564 1565 /// Write a new timestamp file with the given path. 1566 static void writeTimestampFile(StringRef TimestampFile) { 1567 std::error_code EC; 1568 llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None); 1569 } 1570 1571 /// Prune the module cache of modules that haven't been accessed in 1572 /// a long time. 1573 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) { 1574 llvm::sys::fs::file_status StatBuf; 1575 llvm::SmallString<128> TimestampFile; 1576 TimestampFile = HSOpts.ModuleCachePath; 1577 assert(!TimestampFile.empty()); 1578 llvm::sys::path::append(TimestampFile, "modules.timestamp"); 1579 1580 // Try to stat() the timestamp file. 1581 if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) { 1582 // If the timestamp file wasn't there, create one now. 1583 if (EC == std::errc::no_such_file_or_directory) { 1584 writeTimestampFile(TimestampFile); 1585 } 1586 return; 1587 } 1588 1589 // Check whether the time stamp is older than our pruning interval. 1590 // If not, do nothing. 1591 time_t TimeStampModTime = 1592 llvm::sys::toTimeT(StatBuf.getLastModificationTime()); 1593 time_t CurrentTime = time(nullptr); 1594 if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval)) 1595 return; 1596 1597 // Write a new timestamp file so that nobody else attempts to prune. 1598 // There is a benign race condition here, if two Clang instances happen to 1599 // notice at the same time that the timestamp is out-of-date. 1600 writeTimestampFile(TimestampFile); 1601 1602 // Walk the entire module cache, looking for unused module files and module 1603 // indices. 1604 std::error_code EC; 1605 SmallString<128> ModuleCachePathNative; 1606 llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative); 1607 for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd; 1608 Dir != DirEnd && !EC; Dir.increment(EC)) { 1609 // If we don't have a directory, there's nothing to look into. 1610 if (!llvm::sys::fs::is_directory(Dir->path())) 1611 continue; 1612 1613 // Walk all of the files within this directory. 1614 for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd; 1615 File != FileEnd && !EC; File.increment(EC)) { 1616 // We only care about module and global module index files. 1617 StringRef Extension = llvm::sys::path::extension(File->path()); 1618 if (Extension != ".pcm" && Extension != ".timestamp" && 1619 llvm::sys::path::filename(File->path()) != "modules.idx") 1620 continue; 1621 1622 // Look at this file. If we can't stat it, there's nothing interesting 1623 // there. 1624 if (llvm::sys::fs::status(File->path(), StatBuf)) 1625 continue; 1626 1627 // If the file has been used recently enough, leave it there. 1628 time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime()); 1629 if (CurrentTime - FileAccessTime <= 1630 time_t(HSOpts.ModuleCachePruneAfter)) { 1631 continue; 1632 } 1633 1634 // Remove the file. 1635 llvm::sys::fs::remove(File->path()); 1636 1637 // Remove the timestamp file. 1638 std::string TimpestampFilename = File->path() + ".timestamp"; 1639 llvm::sys::fs::remove(TimpestampFilename); 1640 } 1641 1642 // If we removed all of the files in the directory, remove the directory 1643 // itself. 1644 if (llvm::sys::fs::directory_iterator(Dir->path(), EC) == 1645 llvm::sys::fs::directory_iterator() && !EC) 1646 llvm::sys::fs::remove(Dir->path()); 1647 } 1648 } 1649 1650 void CompilerInstance::createASTReader() { 1651 if (TheASTReader) 1652 return; 1653 1654 if (!hasASTContext()) 1655 createASTContext(); 1656 1657 // If we're implicitly building modules but not currently recursively 1658 // building a module, check whether we need to prune the module cache. 1659 if (getSourceManager().getModuleBuildStack().empty() && 1660 !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() && 1661 getHeaderSearchOpts().ModuleCachePruneInterval > 0 && 1662 getHeaderSearchOpts().ModuleCachePruneAfter > 0) { 1663 pruneModuleCache(getHeaderSearchOpts()); 1664 } 1665 1666 HeaderSearchOptions &HSOpts = getHeaderSearchOpts(); 1667 std::string Sysroot = HSOpts.Sysroot; 1668 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 1669 const FrontendOptions &FEOpts = getFrontendOpts(); 1670 std::unique_ptr<llvm::Timer> ReadTimer; 1671 1672 if (FrontendTimerGroup) 1673 ReadTimer = std::make_unique<llvm::Timer>("reading_modules", 1674 "Reading modules", 1675 *FrontendTimerGroup); 1676 TheASTReader = new ASTReader( 1677 getPreprocessor(), getModuleCache(), &getASTContext(), 1678 getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions, 1679 Sysroot.empty() ? "" : Sysroot.c_str(), 1680 PPOpts.DisablePCHOrModuleValidation, 1681 /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors, 1682 /*AllowConfigurationMismatch=*/false, HSOpts.ModulesValidateSystemHeaders, 1683 HSOpts.ValidateASTInputFilesContent, 1684 getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer)); 1685 if (hasASTConsumer()) { 1686 TheASTReader->setDeserializationListener( 1687 getASTConsumer().GetASTDeserializationListener()); 1688 getASTContext().setASTMutationListener( 1689 getASTConsumer().GetASTMutationListener()); 1690 } 1691 getASTContext().setExternalSource(TheASTReader); 1692 if (hasSema()) 1693 TheASTReader->InitializeSema(getSema()); 1694 if (hasASTConsumer()) 1695 TheASTReader->StartTranslationUnit(&getASTConsumer()); 1696 1697 for (auto &Listener : DependencyCollectors) 1698 Listener->attachToASTReader(*TheASTReader); 1699 } 1700 1701 bool CompilerInstance::loadModuleFile(StringRef FileName) { 1702 llvm::Timer Timer; 1703 if (FrontendTimerGroup) 1704 Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(), 1705 *FrontendTimerGroup); 1706 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr); 1707 1708 // If we don't already have an ASTReader, create one now. 1709 if (!TheASTReader) 1710 createASTReader(); 1711 1712 // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the 1713 // ASTReader to diagnose it, since it can produce better errors that we can. 1714 bool ConfigMismatchIsRecoverable = 1715 getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch, 1716 SourceLocation()) 1717 <= DiagnosticsEngine::Warning; 1718 1719 auto Listener = std::make_unique<ReadModuleNames>(*PP); 1720 auto &ListenerRef = *Listener; 1721 ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader, 1722 std::move(Listener)); 1723 1724 // Try to load the module file. 1725 switch (TheASTReader->ReadAST( 1726 FileName, serialization::MK_ExplicitModule, SourceLocation(), 1727 ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0)) { 1728 case ASTReader::Success: 1729 // We successfully loaded the module file; remember the set of provided 1730 // modules so that we don't try to load implicit modules for them. 1731 ListenerRef.registerAll(); 1732 return true; 1733 1734 case ASTReader::ConfigurationMismatch: 1735 // Ignore unusable module files. 1736 getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch) 1737 << FileName; 1738 // All modules provided by any files we tried and failed to load are now 1739 // unavailable; includes of those modules should now be handled textually. 1740 ListenerRef.markAllUnavailable(); 1741 return true; 1742 1743 default: 1744 return false; 1745 } 1746 } 1747 1748 namespace { 1749 enum ModuleSource { 1750 MS_ModuleNotFound, 1751 MS_ModuleCache, 1752 MS_PrebuiltModulePath, 1753 MS_ModuleBuildPragma 1754 }; 1755 } // end namespace 1756 1757 /// Select a source for loading the named module and compute the filename to 1758 /// load it from. 1759 static ModuleSource selectModuleSource( 1760 Module *M, StringRef ModuleName, std::string &ModuleFilename, 1761 const std::map<std::string, std::string, std::less<>> &BuiltModules, 1762 HeaderSearch &HS) { 1763 assert(ModuleFilename.empty() && "Already has a module source?"); 1764 1765 // Check to see if the module has been built as part of this compilation 1766 // via a module build pragma. 1767 auto BuiltModuleIt = BuiltModules.find(ModuleName); 1768 if (BuiltModuleIt != BuiltModules.end()) { 1769 ModuleFilename = BuiltModuleIt->second; 1770 return MS_ModuleBuildPragma; 1771 } 1772 1773 // Try to load the module from the prebuilt module path. 1774 const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts(); 1775 if (!HSOpts.PrebuiltModuleFiles.empty() || 1776 !HSOpts.PrebuiltModulePaths.empty()) { 1777 ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName); 1778 if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty()) 1779 ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M); 1780 if (!ModuleFilename.empty()) 1781 return MS_PrebuiltModulePath; 1782 } 1783 1784 // Try to load the module from the module cache. 1785 if (M) { 1786 ModuleFilename = HS.getCachedModuleFileName(M); 1787 return MS_ModuleCache; 1788 } 1789 1790 return MS_ModuleNotFound; 1791 } 1792 1793 ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST( 1794 StringRef ModuleName, SourceLocation ImportLoc, 1795 SourceLocation ModuleNameLoc, bool IsInclusionDirective) { 1796 // Search for a module with the given name. 1797 HeaderSearch &HS = PP->getHeaderSearchInfo(); 1798 Module *M = 1799 HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective); 1800 1801 // Select the source and filename for loading the named module. 1802 std::string ModuleFilename; 1803 ModuleSource Source = 1804 selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS); 1805 if (Source == MS_ModuleNotFound) { 1806 // We can't find a module, error out here. 1807 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found) 1808 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc); 1809 return nullptr; 1810 } 1811 if (ModuleFilename.empty()) { 1812 if (M && M->HasIncompatibleModuleFile) { 1813 // We tried and failed to load a module file for this module. Fall 1814 // back to textual inclusion for its headers. 1815 return ModuleLoadResult::ConfigMismatch; 1816 } 1817 1818 getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled) 1819 << ModuleName; 1820 return nullptr; 1821 } 1822 1823 // Create an ASTReader on demand. 1824 if (!getASTReader()) 1825 createASTReader(); 1826 1827 // Time how long it takes to load the module. 1828 llvm::Timer Timer; 1829 if (FrontendTimerGroup) 1830 Timer.init("loading." + ModuleFilename, "Loading " + ModuleFilename, 1831 *FrontendTimerGroup); 1832 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr); 1833 llvm::TimeTraceScope TimeScope("Module Load", ModuleName); 1834 1835 // Try to load the module file. If we are not trying to load from the 1836 // module cache, we don't know how to rebuild modules. 1837 unsigned ARRFlags = Source == MS_ModuleCache 1838 ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing | 1839 ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate 1840 : Source == MS_PrebuiltModulePath 1841 ? 0 1842 : ASTReader::ARR_ConfigurationMismatch; 1843 switch (getASTReader()->ReadAST(ModuleFilename, 1844 Source == MS_PrebuiltModulePath 1845 ? serialization::MK_PrebuiltModule 1846 : Source == MS_ModuleBuildPragma 1847 ? serialization::MK_ExplicitModule 1848 : serialization::MK_ImplicitModule, 1849 ImportLoc, ARRFlags)) { 1850 case ASTReader::Success: { 1851 if (M) 1852 return M; 1853 assert(Source != MS_ModuleCache && 1854 "missing module, but file loaded from cache"); 1855 1856 // A prebuilt module is indexed as a ModuleFile; the Module does not exist 1857 // until the first call to ReadAST. Look it up now. 1858 M = HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective); 1859 1860 // Check whether M refers to the file in the prebuilt module path. 1861 if (M && M->getASTFile()) 1862 if (auto ModuleFile = FileMgr->getFile(ModuleFilename)) 1863 if (*ModuleFile == M->getASTFile()) 1864 return M; 1865 1866 getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt) 1867 << ModuleName; 1868 return ModuleLoadResult(); 1869 } 1870 1871 case ASTReader::OutOfDate: 1872 case ASTReader::Missing: 1873 // The most interesting case. 1874 break; 1875 1876 case ASTReader::ConfigurationMismatch: 1877 if (Source == MS_PrebuiltModulePath) 1878 // FIXME: We shouldn't be setting HadFatalFailure below if we only 1879 // produce a warning here! 1880 getDiagnostics().Report(SourceLocation(), 1881 diag::warn_module_config_mismatch) 1882 << ModuleFilename; 1883 // Fall through to error out. 1884 [[fallthrough]]; 1885 case ASTReader::VersionMismatch: 1886 case ASTReader::HadErrors: 1887 ModuleLoader::HadFatalFailure = true; 1888 // FIXME: The ASTReader will already have complained, but can we shoehorn 1889 // that diagnostic information into a more useful form? 1890 return ModuleLoadResult(); 1891 1892 case ASTReader::Failure: 1893 ModuleLoader::HadFatalFailure = true; 1894 return ModuleLoadResult(); 1895 } 1896 1897 // ReadAST returned Missing or OutOfDate. 1898 if (Source != MS_ModuleCache) { 1899 // We don't know the desired configuration for this module and don't 1900 // necessarily even have a module map. Since ReadAST already produces 1901 // diagnostics for these two cases, we simply error out here. 1902 return ModuleLoadResult(); 1903 } 1904 1905 // The module file is missing or out-of-date. Build it. 1906 assert(M && "missing module, but trying to compile for cache"); 1907 1908 // Check whether there is a cycle in the module graph. 1909 ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack(); 1910 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end(); 1911 for (; Pos != PosEnd; ++Pos) { 1912 if (Pos->first == ModuleName) 1913 break; 1914 } 1915 1916 if (Pos != PosEnd) { 1917 SmallString<256> CyclePath; 1918 for (; Pos != PosEnd; ++Pos) { 1919 CyclePath += Pos->first; 1920 CyclePath += " -> "; 1921 } 1922 CyclePath += ModuleName; 1923 1924 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle) 1925 << ModuleName << CyclePath; 1926 return nullptr; 1927 } 1928 1929 // Check whether we have already attempted to build this module (but 1930 // failed). 1931 if (getPreprocessorOpts().FailedModules && 1932 getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) { 1933 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built) 1934 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc); 1935 return nullptr; 1936 } 1937 1938 // Try to compile and then read the AST. 1939 if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M, 1940 ModuleFilename)) { 1941 assert(getDiagnostics().hasErrorOccurred() && 1942 "undiagnosed error in compileModuleAndReadAST"); 1943 if (getPreprocessorOpts().FailedModules) 1944 getPreprocessorOpts().FailedModules->addFailed(ModuleName); 1945 return nullptr; 1946 } 1947 1948 // Okay, we've rebuilt and now loaded the module. 1949 return M; 1950 } 1951 1952 ModuleLoadResult 1953 CompilerInstance::loadModule(SourceLocation ImportLoc, 1954 ModuleIdPath Path, 1955 Module::NameVisibilityKind Visibility, 1956 bool IsInclusionDirective) { 1957 // Determine what file we're searching from. 1958 StringRef ModuleName = Path[0].first->getName(); 1959 SourceLocation ModuleNameLoc = Path[0].second; 1960 1961 // If we've already handled this import, just return the cached result. 1962 // This one-element cache is important to eliminate redundant diagnostics 1963 // when both the preprocessor and parser see the same import declaration. 1964 if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) { 1965 // Make the named module visible. 1966 if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule) 1967 TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility, 1968 ImportLoc); 1969 return LastModuleImportResult; 1970 } 1971 1972 // If we don't already have information on this module, load the module now. 1973 Module *Module = nullptr; 1974 ModuleMap &MM = getPreprocessor().getHeaderSearchInfo().getModuleMap(); 1975 if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].first)) { 1976 // Use the cached result, which may be nullptr. 1977 Module = *MaybeModule; 1978 } else if (ModuleName == getLangOpts().CurrentModule) { 1979 // This is the module we're building. 1980 Module = PP->getHeaderSearchInfo().lookupModule( 1981 ModuleName, ImportLoc, /*AllowSearch*/ true, 1982 /*AllowExtraModuleMapSearch*/ !IsInclusionDirective); 1983 /// FIXME: perhaps we should (a) look for a module using the module name 1984 // to file map (PrebuiltModuleFiles) and (b) diagnose if still not found? 1985 //if (Module == nullptr) { 1986 // getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found) 1987 // << ModuleName; 1988 // DisableGeneratingGlobalModuleIndex = true; 1989 // return ModuleLoadResult(); 1990 //} 1991 MM.cacheModuleLoad(*Path[0].first, Module); 1992 } else { 1993 ModuleLoadResult Result = findOrCompileModuleAndReadAST( 1994 ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective); 1995 if (!Result.isNormal()) 1996 return Result; 1997 if (!Result) 1998 DisableGeneratingGlobalModuleIndex = true; 1999 Module = Result; 2000 MM.cacheModuleLoad(*Path[0].first, Module); 2001 } 2002 2003 // If we never found the module, fail. Otherwise, verify the module and link 2004 // it up. 2005 if (!Module) 2006 return ModuleLoadResult(); 2007 2008 // Verify that the rest of the module path actually corresponds to 2009 // a submodule. 2010 bool MapPrivateSubModToTopLevel = false; 2011 for (unsigned I = 1, N = Path.size(); I != N; ++I) { 2012 StringRef Name = Path[I].first->getName(); 2013 clang::Module *Sub = Module->findSubmodule(Name); 2014 2015 // If the user is requesting Foo.Private and it doesn't exist, try to 2016 // match Foo_Private and emit a warning asking for the user to write 2017 // @import Foo_Private instead. FIXME: remove this when existing clients 2018 // migrate off of Foo.Private syntax. 2019 if (!Sub && Name == "Private" && Module == Module->getTopLevelModule()) { 2020 SmallString<128> PrivateModule(Module->Name); 2021 PrivateModule.append("_Private"); 2022 2023 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> PrivPath; 2024 auto &II = PP->getIdentifierTable().get( 2025 PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID()); 2026 PrivPath.push_back(std::make_pair(&II, Path[0].second)); 2027 2028 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc, true, 2029 !IsInclusionDirective)) 2030 Sub = loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective); 2031 if (Sub) { 2032 MapPrivateSubModToTopLevel = true; 2033 PP->markModuleAsAffecting(Module); 2034 if (!getDiagnostics().isIgnored( 2035 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) { 2036 getDiagnostics().Report(Path[I].second, 2037 diag::warn_no_priv_submodule_use_toplevel) 2038 << Path[I].first << Module->getFullModuleName() << PrivateModule 2039 << SourceRange(Path[0].second, Path[I].second) 2040 << FixItHint::CreateReplacement(SourceRange(Path[0].second), 2041 PrivateModule); 2042 getDiagnostics().Report(Sub->DefinitionLoc, 2043 diag::note_private_top_level_defined); 2044 } 2045 } 2046 } 2047 2048 if (!Sub) { 2049 // Attempt to perform typo correction to find a module name that works. 2050 SmallVector<StringRef, 2> Best; 2051 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)(); 2052 2053 for (class Module *SubModule : Module->submodules()) { 2054 unsigned ED = 2055 Name.edit_distance(SubModule->Name, 2056 /*AllowReplacements=*/true, BestEditDistance); 2057 if (ED <= BestEditDistance) { 2058 if (ED < BestEditDistance) { 2059 Best.clear(); 2060 BestEditDistance = ED; 2061 } 2062 2063 Best.push_back(SubModule->Name); 2064 } 2065 } 2066 2067 // If there was a clear winner, user it. 2068 if (Best.size() == 1) { 2069 getDiagnostics().Report(Path[I].second, diag::err_no_submodule_suggest) 2070 << Path[I].first << Module->getFullModuleName() << Best[0] 2071 << SourceRange(Path[0].second, Path[I - 1].second) 2072 << FixItHint::CreateReplacement(SourceRange(Path[I].second), 2073 Best[0]); 2074 2075 Sub = Module->findSubmodule(Best[0]); 2076 } 2077 } 2078 2079 if (!Sub) { 2080 // No submodule by this name. Complain, and don't look for further 2081 // submodules. 2082 getDiagnostics().Report(Path[I].second, diag::err_no_submodule) 2083 << Path[I].first << Module->getFullModuleName() 2084 << SourceRange(Path[0].second, Path[I - 1].second); 2085 break; 2086 } 2087 2088 Module = Sub; 2089 } 2090 2091 // Make the named module visible, if it's not already part of the module 2092 // we are parsing. 2093 if (ModuleName != getLangOpts().CurrentModule) { 2094 if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) { 2095 // We have an umbrella header or directory that doesn't actually include 2096 // all of the headers within the directory it covers. Complain about 2097 // this missing submodule and recover by forgetting that we ever saw 2098 // this submodule. 2099 // FIXME: Should we detect this at module load time? It seems fairly 2100 // expensive (and rare). 2101 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule) 2102 << Module->getFullModuleName() 2103 << SourceRange(Path.front().second, Path.back().second); 2104 2105 return ModuleLoadResult(Module, ModuleLoadResult::MissingExpected); 2106 } 2107 2108 // Check whether this module is available. 2109 if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(), 2110 getDiagnostics(), Module)) { 2111 getDiagnostics().Report(ImportLoc, diag::note_module_import_here) 2112 << SourceRange(Path.front().second, Path.back().second); 2113 LastModuleImportLoc = ImportLoc; 2114 LastModuleImportResult = ModuleLoadResult(); 2115 return ModuleLoadResult(); 2116 } 2117 2118 TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc); 2119 } 2120 2121 // Check for any configuration macros that have changed. 2122 clang::Module *TopModule = Module->getTopLevelModule(); 2123 for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) { 2124 checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I], 2125 Module, ImportLoc); 2126 } 2127 2128 // Resolve any remaining module using export_as for this one. 2129 getPreprocessor() 2130 .getHeaderSearchInfo() 2131 .getModuleMap() 2132 .resolveLinkAsDependencies(TopModule); 2133 2134 LastModuleImportLoc = ImportLoc; 2135 LastModuleImportResult = ModuleLoadResult(Module); 2136 return LastModuleImportResult; 2137 } 2138 2139 void CompilerInstance::createModuleFromSource(SourceLocation ImportLoc, 2140 StringRef ModuleName, 2141 StringRef Source) { 2142 // Avoid creating filenames with special characters. 2143 SmallString<128> CleanModuleName(ModuleName); 2144 for (auto &C : CleanModuleName) 2145 if (!isAlphanumeric(C)) 2146 C = '_'; 2147 2148 // FIXME: Using a randomized filename here means that our intermediate .pcm 2149 // output is nondeterministic (as .pcm files refer to each other by name). 2150 // Can this affect the output in any way? 2151 SmallString<128> ModuleFileName; 2152 if (std::error_code EC = llvm::sys::fs::createTemporaryFile( 2153 CleanModuleName, "pcm", ModuleFileName)) { 2154 getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output) 2155 << ModuleFileName << EC.message(); 2156 return; 2157 } 2158 std::string ModuleMapFileName = (CleanModuleName + ".map").str(); 2159 2160 FrontendInputFile Input( 2161 ModuleMapFileName, 2162 InputKind(getLanguageFromOptions(*Invocation->getLangOpts()), 2163 InputKind::ModuleMap, /*Preprocessed*/true)); 2164 2165 std::string NullTerminatedSource(Source.str()); 2166 2167 auto PreBuildStep = [&](CompilerInstance &Other) { 2168 // Create a virtual file containing our desired source. 2169 // FIXME: We shouldn't need to do this. 2170 const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile( 2171 ModuleMapFileName, NullTerminatedSource.size(), 0); 2172 Other.getSourceManager().overrideFileContents( 2173 ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource)); 2174 2175 Other.BuiltModules = std::move(BuiltModules); 2176 Other.DeleteBuiltModules = false; 2177 }; 2178 2179 auto PostBuildStep = [this](CompilerInstance &Other) { 2180 BuiltModules = std::move(Other.BuiltModules); 2181 }; 2182 2183 // Build the module, inheriting any modules that we've built locally. 2184 if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(), 2185 ModuleFileName, PreBuildStep, PostBuildStep)) { 2186 BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName.str()); 2187 llvm::sys::RemoveFileOnSignal(ModuleFileName); 2188 } 2189 } 2190 2191 void CompilerInstance::makeModuleVisible(Module *Mod, 2192 Module::NameVisibilityKind Visibility, 2193 SourceLocation ImportLoc) { 2194 if (!TheASTReader) 2195 createASTReader(); 2196 if (!TheASTReader) 2197 return; 2198 2199 TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc); 2200 } 2201 2202 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex( 2203 SourceLocation TriggerLoc) { 2204 if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty()) 2205 return nullptr; 2206 if (!TheASTReader) 2207 createASTReader(); 2208 // Can't do anything if we don't have the module manager. 2209 if (!TheASTReader) 2210 return nullptr; 2211 // Get an existing global index. This loads it if not already 2212 // loaded. 2213 TheASTReader->loadGlobalIndex(); 2214 GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex(); 2215 // If the global index doesn't exist, create it. 2216 if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() && 2217 hasPreprocessor()) { 2218 llvm::sys::fs::create_directories( 2219 getPreprocessor().getHeaderSearchInfo().getModuleCachePath()); 2220 if (llvm::Error Err = GlobalModuleIndex::writeIndex( 2221 getFileManager(), getPCHContainerReader(), 2222 getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) { 2223 // FIXME this drops the error on the floor. This code is only used for 2224 // typo correction and drops more than just this one source of errors 2225 // (such as the directory creation failure above). It should handle the 2226 // error. 2227 consumeError(std::move(Err)); 2228 return nullptr; 2229 } 2230 TheASTReader->resetForReload(); 2231 TheASTReader->loadGlobalIndex(); 2232 GlobalIndex = TheASTReader->getGlobalIndex(); 2233 } 2234 // For finding modules needing to be imported for fixit messages, 2235 // we need to make the global index cover all modules, so we do that here. 2236 if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) { 2237 ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap(); 2238 bool RecreateIndex = false; 2239 for (ModuleMap::module_iterator I = MMap.module_begin(), 2240 E = MMap.module_end(); I != E; ++I) { 2241 Module *TheModule = I->second; 2242 const FileEntry *Entry = TheModule->getASTFile(); 2243 if (!Entry) { 2244 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 2245 Path.push_back(std::make_pair( 2246 getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc)); 2247 std::reverse(Path.begin(), Path.end()); 2248 // Load a module as hidden. This also adds it to the global index. 2249 loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false); 2250 RecreateIndex = true; 2251 } 2252 } 2253 if (RecreateIndex) { 2254 if (llvm::Error Err = GlobalModuleIndex::writeIndex( 2255 getFileManager(), getPCHContainerReader(), 2256 getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) { 2257 // FIXME As above, this drops the error on the floor. 2258 consumeError(std::move(Err)); 2259 return nullptr; 2260 } 2261 TheASTReader->resetForReload(); 2262 TheASTReader->loadGlobalIndex(); 2263 GlobalIndex = TheASTReader->getGlobalIndex(); 2264 } 2265 HaveFullGlobalModuleIndex = true; 2266 } 2267 return GlobalIndex; 2268 } 2269 2270 // Check global module index for missing imports. 2271 bool 2272 CompilerInstance::lookupMissingImports(StringRef Name, 2273 SourceLocation TriggerLoc) { 2274 // Look for the symbol in non-imported modules, but only if an error 2275 // actually occurred. 2276 if (!buildingModule()) { 2277 // Load global module index, or retrieve a previously loaded one. 2278 GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex( 2279 TriggerLoc); 2280 2281 // Only if we have a global index. 2282 if (GlobalIndex) { 2283 GlobalModuleIndex::HitSet FoundModules; 2284 2285 // Find the modules that reference the identifier. 2286 // Note that this only finds top-level modules. 2287 // We'll let diagnoseTypo find the actual declaration module. 2288 if (GlobalIndex->lookupIdentifier(Name, FoundModules)) 2289 return true; 2290 } 2291 } 2292 2293 return false; 2294 } 2295 void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); } 2296 2297 void CompilerInstance::setExternalSemaSource( 2298 IntrusiveRefCntPtr<ExternalSemaSource> ESS) { 2299 ExternalSemaSrc = std::move(ESS); 2300 } 2301