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 auto ToFile = FileMgr.getFile(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 // If '-working-directory' was passed, the output filename should be 785 // relative to that. 786 SmallString<128> NewOutFile(OF.Filename); 787 FileMgr->FixupRelativePath(NewOutFile); 788 789 llvm::Error E = OF.File->keep(NewOutFile); 790 if (!E) 791 continue; 792 793 getDiagnostics().Report(diag::err_unable_to_rename_temp) 794 << OF.File->TmpName << OF.Filename << std::move(E); 795 796 llvm::sys::fs::remove(OF.File->TmpName); 797 } 798 OutputFiles.clear(); 799 if (DeleteBuiltModules) { 800 for (auto &Module : BuiltModules) 801 llvm::sys::fs::remove(Module.second); 802 BuiltModules.clear(); 803 } 804 } 805 806 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createDefaultOutputFile( 807 bool Binary, StringRef InFile, StringRef Extension, bool RemoveFileOnSignal, 808 bool CreateMissingDirectories, bool ForceUseTemporary) { 809 StringRef OutputPath = getFrontendOpts().OutputFile; 810 Optional<SmallString<128>> PathStorage; 811 if (OutputPath.empty()) { 812 if (InFile == "-" || Extension.empty()) { 813 OutputPath = "-"; 814 } else { 815 PathStorage.emplace(InFile); 816 llvm::sys::path::replace_extension(*PathStorage, Extension); 817 OutputPath = *PathStorage; 818 } 819 } 820 821 return createOutputFile(OutputPath, Binary, RemoveFileOnSignal, 822 getFrontendOpts().UseTemporary || ForceUseTemporary, 823 CreateMissingDirectories); 824 } 825 826 std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() { 827 return std::make_unique<llvm::raw_null_ostream>(); 828 } 829 830 std::unique_ptr<raw_pwrite_stream> 831 CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary, 832 bool RemoveFileOnSignal, bool UseTemporary, 833 bool CreateMissingDirectories) { 834 Expected<std::unique_ptr<raw_pwrite_stream>> OS = 835 createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary, 836 CreateMissingDirectories); 837 if (OS) 838 return std::move(*OS); 839 getDiagnostics().Report(diag::err_fe_unable_to_open_output) 840 << OutputPath << errorToErrorCode(OS.takeError()).message(); 841 return nullptr; 842 } 843 844 Expected<std::unique_ptr<llvm::raw_pwrite_stream>> 845 CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary, 846 bool RemoveFileOnSignal, 847 bool UseTemporary, 848 bool CreateMissingDirectories) { 849 assert((!CreateMissingDirectories || UseTemporary) && 850 "CreateMissingDirectories is only allowed when using temporary files"); 851 852 std::unique_ptr<llvm::raw_fd_ostream> OS; 853 Optional<StringRef> OSFile; 854 855 if (UseTemporary) { 856 if (OutputPath == "-") 857 UseTemporary = false; 858 else { 859 llvm::sys::fs::file_status Status; 860 llvm::sys::fs::status(OutputPath, Status); 861 if (llvm::sys::fs::exists(Status)) { 862 // Fail early if we can't write to the final destination. 863 if (!llvm::sys::fs::can_write(OutputPath)) 864 return llvm::errorCodeToError( 865 make_error_code(llvm::errc::operation_not_permitted)); 866 867 // Don't use a temporary if the output is a special file. This handles 868 // things like '-o /dev/null' 869 if (!llvm::sys::fs::is_regular_file(Status)) 870 UseTemporary = false; 871 } 872 } 873 } 874 875 Optional<llvm::sys::fs::TempFile> Temp; 876 if (UseTemporary) { 877 // Create a temporary file. 878 // Insert -%%%%%%%% before the extension (if any), and because some tools 879 // (noticeable, clang's own GlobalModuleIndex.cpp) glob for build 880 // artifacts, also append .tmp. 881 StringRef OutputExtension = llvm::sys::path::extension(OutputPath); 882 SmallString<128> TempPath = 883 StringRef(OutputPath).drop_back(OutputExtension.size()); 884 TempPath += "-%%%%%%%%"; 885 TempPath += OutputExtension; 886 TempPath += ".tmp"; 887 Expected<llvm::sys::fs::TempFile> ExpectedFile = 888 llvm::sys::fs::TempFile::create( 889 TempPath, llvm::sys::fs::all_read | llvm::sys::fs::all_write, 890 Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_Text); 891 892 llvm::Error E = handleErrors( 893 ExpectedFile.takeError(), [&](const llvm::ECError &E) -> llvm::Error { 894 std::error_code EC = E.convertToErrorCode(); 895 if (CreateMissingDirectories && 896 EC == llvm::errc::no_such_file_or_directory) { 897 StringRef Parent = llvm::sys::path::parent_path(OutputPath); 898 EC = llvm::sys::fs::create_directories(Parent); 899 if (!EC) { 900 ExpectedFile = llvm::sys::fs::TempFile::create(TempPath); 901 if (!ExpectedFile) 902 return llvm::errorCodeToError( 903 llvm::errc::no_such_file_or_directory); 904 } 905 } 906 return llvm::errorCodeToError(EC); 907 }); 908 909 if (E) { 910 consumeError(std::move(E)); 911 } else { 912 Temp = std::move(ExpectedFile.get()); 913 OS.reset(new llvm::raw_fd_ostream(Temp->FD, /*shouldClose=*/false)); 914 OSFile = Temp->TmpName; 915 } 916 // If we failed to create the temporary, fallback to writing to the file 917 // directly. This handles the corner case where we cannot write to the 918 // directory, but can write to the file. 919 } 920 921 if (!OS) { 922 OSFile = OutputPath; 923 std::error_code EC; 924 OS.reset(new llvm::raw_fd_ostream( 925 *OSFile, EC, 926 (Binary ? llvm::sys::fs::OF_None : llvm::sys::fs::OF_TextWithCRLF))); 927 if (EC) 928 return llvm::errorCodeToError(EC); 929 } 930 931 // Add the output file -- but don't try to remove "-", since this means we are 932 // using stdin. 933 OutputFiles.emplace_back(((OutputPath != "-") ? OutputPath : "").str(), 934 std::move(Temp)); 935 936 if (!Binary || OS->supportsSeeking()) 937 return std::move(OS); 938 939 return std::make_unique<llvm::buffer_unique_ostream>(std::move(OS)); 940 } 941 942 // Initialization Utilities 943 944 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){ 945 return InitializeSourceManager(Input, getDiagnostics(), getFileManager(), 946 getSourceManager()); 947 } 948 949 // static 950 bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input, 951 DiagnosticsEngine &Diags, 952 FileManager &FileMgr, 953 SourceManager &SourceMgr) { 954 SrcMgr::CharacteristicKind Kind = 955 Input.getKind().getFormat() == InputKind::ModuleMap 956 ? Input.isSystem() ? SrcMgr::C_System_ModuleMap 957 : SrcMgr::C_User_ModuleMap 958 : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User; 959 960 if (Input.isBuffer()) { 961 SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind)); 962 assert(SourceMgr.getMainFileID().isValid() && 963 "Couldn't establish MainFileID!"); 964 return true; 965 } 966 967 StringRef InputFile = Input.getFile(); 968 969 // Figure out where to get and map in the main file. 970 auto FileOrErr = InputFile == "-" 971 ? FileMgr.getSTDIN() 972 : FileMgr.getFileRef(InputFile, /*OpenFile=*/true); 973 if (!FileOrErr) { 974 // FIXME: include the error in the diagnostic even when it's not stdin. 975 auto EC = llvm::errorToErrorCode(FileOrErr.takeError()); 976 if (InputFile != "-") 977 Diags.Report(diag::err_fe_error_reading) << InputFile; 978 else 979 Diags.Report(diag::err_fe_error_reading_stdin) << EC.message(); 980 return false; 981 } 982 983 SourceMgr.setMainFileID( 984 SourceMgr.createFileID(*FileOrErr, SourceLocation(), Kind)); 985 986 assert(SourceMgr.getMainFileID().isValid() && 987 "Couldn't establish MainFileID!"); 988 return true; 989 } 990 991 // High-Level Operations 992 993 bool CompilerInstance::ExecuteAction(FrontendAction &Act) { 994 assert(hasDiagnostics() && "Diagnostics engine is not initialized!"); 995 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!"); 996 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!"); 997 998 // Mark this point as the bottom of the stack if we don't have somewhere 999 // better. We generally expect frontend actions to be invoked with (nearly) 1000 // DesiredStackSpace available. 1001 noteBottomOfStack(); 1002 1003 auto FinishDiagnosticClient = llvm::make_scope_exit([&]() { 1004 // Notify the diagnostic client that all files were processed. 1005 getDiagnosticClient().finish(); 1006 }); 1007 1008 raw_ostream &OS = getVerboseOutputStream(); 1009 1010 if (!Act.PrepareToExecute(*this)) 1011 return false; 1012 1013 if (!createTarget()) 1014 return false; 1015 1016 // rewriter project will change target built-in bool type from its default. 1017 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC) 1018 getTarget().noSignedCharForObjCBool(); 1019 1020 // Validate/process some options. 1021 if (getHeaderSearchOpts().Verbose) 1022 OS << "clang -cc1 version " CLANG_VERSION_STRING 1023 << " based upon " << BACKEND_PACKAGE_STRING 1024 << " default target " << llvm::sys::getDefaultTargetTriple() << "\n"; 1025 1026 if (getCodeGenOpts().TimePasses) 1027 createFrontendTimer(); 1028 1029 if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty()) 1030 llvm::EnableStatistics(false); 1031 1032 for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) { 1033 // Reset the ID tables if we are reusing the SourceManager and parsing 1034 // regular files. 1035 if (hasSourceManager() && !Act.isModelParsingAction()) 1036 getSourceManager().clearIDTables(); 1037 1038 if (Act.BeginSourceFile(*this, FIF)) { 1039 if (llvm::Error Err = Act.Execute()) { 1040 consumeError(std::move(Err)); // FIXME this drops errors on the floor. 1041 } 1042 Act.EndSourceFile(); 1043 } 1044 } 1045 1046 if (getDiagnosticOpts().ShowCarets) { 1047 // We can have multiple diagnostics sharing one diagnostic client. 1048 // Get the total number of warnings/errors from the client. 1049 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings(); 1050 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors(); 1051 1052 if (NumWarnings) 1053 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s"); 1054 if (NumWarnings && NumErrors) 1055 OS << " and "; 1056 if (NumErrors) 1057 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s"); 1058 if (NumWarnings || NumErrors) { 1059 OS << " generated"; 1060 if (getLangOpts().CUDA) { 1061 if (!getLangOpts().CUDAIsDevice) { 1062 OS << " when compiling for host"; 1063 } else { 1064 OS << " when compiling for " << getTargetOpts().CPU; 1065 } 1066 } 1067 OS << ".\n"; 1068 } 1069 } 1070 1071 if (getFrontendOpts().ShowStats) { 1072 if (hasFileManager()) { 1073 getFileManager().PrintStats(); 1074 OS << '\n'; 1075 } 1076 llvm::PrintStatistics(OS); 1077 } 1078 StringRef StatsFile = getFrontendOpts().StatsFile; 1079 if (!StatsFile.empty()) { 1080 std::error_code EC; 1081 auto StatS = std::make_unique<llvm::raw_fd_ostream>( 1082 StatsFile, EC, llvm::sys::fs::OF_TextWithCRLF); 1083 if (EC) { 1084 getDiagnostics().Report(diag::warn_fe_unable_to_open_stats_file) 1085 << StatsFile << EC.message(); 1086 } else { 1087 llvm::PrintStatisticsJSON(*StatS); 1088 } 1089 } 1090 1091 return !getDiagnostics().getClient()->getNumErrors(); 1092 } 1093 1094 void CompilerInstance::LoadRequestedPlugins() { 1095 // Load any requested plugins. 1096 for (const std::string &Path : getFrontendOpts().Plugins) { 1097 std::string Error; 1098 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error)) 1099 getDiagnostics().Report(diag::err_fe_unable_to_load_plugin) 1100 << Path << Error; 1101 } 1102 1103 // Check if any of the loaded plugins replaces the main AST action 1104 for (const FrontendPluginRegistry::entry &Plugin : 1105 FrontendPluginRegistry::entries()) { 1106 std::unique_ptr<PluginASTAction> P(Plugin.instantiate()); 1107 if (P->getActionType() == PluginASTAction::ReplaceAction) { 1108 getFrontendOpts().ProgramAction = clang::frontend::PluginAction; 1109 getFrontendOpts().ActionName = Plugin.getName().str(); 1110 break; 1111 } 1112 } 1113 } 1114 1115 /// Determine the appropriate source input kind based on language 1116 /// options. 1117 static Language getLanguageFromOptions(const LangOptions &LangOpts) { 1118 if (LangOpts.OpenCL) 1119 return Language::OpenCL; 1120 if (LangOpts.CUDA) 1121 return Language::CUDA; 1122 if (LangOpts.ObjC) 1123 return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC; 1124 return LangOpts.CPlusPlus ? Language::CXX : Language::C; 1125 } 1126 1127 /// Compile a module file for the given module, using the options 1128 /// provided by the importing compiler instance. Returns true if the module 1129 /// was built without errors. 1130 static bool 1131 compileModuleImpl(CompilerInstance &ImportingInstance, SourceLocation ImportLoc, 1132 StringRef ModuleName, FrontendInputFile Input, 1133 StringRef OriginalModuleMapFile, StringRef ModuleFileName, 1134 llvm::function_ref<void(CompilerInstance &)> PreBuildStep = 1135 [](CompilerInstance &) {}, 1136 llvm::function_ref<void(CompilerInstance &)> PostBuildStep = 1137 [](CompilerInstance &) {}) { 1138 llvm::TimeTraceScope TimeScope("Module Compile", ModuleName); 1139 1140 // Never compile a module that's already finalized - this would cause the 1141 // existing module to be freed, causing crashes if it is later referenced 1142 if (ImportingInstance.getModuleCache().isPCMFinal(ModuleFileName)) { 1143 ImportingInstance.getDiagnostics().Report( 1144 ImportLoc, diag::err_module_rebuild_finalized) 1145 << ModuleName; 1146 return false; 1147 } 1148 1149 // Construct a compiler invocation for creating this module. 1150 auto Invocation = 1151 std::make_shared<CompilerInvocation>(ImportingInstance.getInvocation()); 1152 1153 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 1154 1155 // For any options that aren't intended to affect how a module is built, 1156 // reset them to their default values. 1157 Invocation->resetNonModularOptions(); 1158 1159 // Remove any macro definitions that are explicitly ignored by the module. 1160 // They aren't supposed to affect how the module is built anyway. 1161 HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts(); 1162 llvm::erase_if(PPOpts.Macros, 1163 [&HSOpts](const std::pair<std::string, bool> &def) { 1164 StringRef MacroDef = def.first; 1165 return HSOpts.ModulesIgnoreMacros.contains( 1166 llvm::CachedHashString(MacroDef.split('=').first)); 1167 }); 1168 1169 // If the original compiler invocation had -fmodule-name, pass it through. 1170 Invocation->getLangOpts()->ModuleName = 1171 ImportingInstance.getInvocation().getLangOpts()->ModuleName; 1172 1173 // Note the name of the module we're building. 1174 Invocation->getLangOpts()->CurrentModule = std::string(ModuleName); 1175 1176 // Make sure that the failed-module structure has been allocated in 1177 // the importing instance, and propagate the pointer to the newly-created 1178 // instance. 1179 PreprocessorOptions &ImportingPPOpts 1180 = ImportingInstance.getInvocation().getPreprocessorOpts(); 1181 if (!ImportingPPOpts.FailedModules) 1182 ImportingPPOpts.FailedModules = 1183 std::make_shared<PreprocessorOptions::FailedModulesSet>(); 1184 PPOpts.FailedModules = ImportingPPOpts.FailedModules; 1185 1186 // If there is a module map file, build the module using the module map. 1187 // Set up the inputs/outputs so that we build the module from its umbrella 1188 // header. 1189 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts(); 1190 FrontendOpts.OutputFile = ModuleFileName.str(); 1191 FrontendOpts.DisableFree = false; 1192 FrontendOpts.GenerateGlobalModuleIndex = false; 1193 FrontendOpts.BuildingImplicitModule = true; 1194 FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile); 1195 // Force implicitly-built modules to hash the content of the module file. 1196 HSOpts.ModulesHashContent = true; 1197 FrontendOpts.Inputs = {Input}; 1198 1199 // Don't free the remapped file buffers; they are owned by our caller. 1200 PPOpts.RetainRemappedFileBuffers = true; 1201 1202 Invocation->getDiagnosticOpts().VerifyDiagnostics = 0; 1203 assert(ImportingInstance.getInvocation().getModuleHash() == 1204 Invocation->getModuleHash() && "Module hash mismatch!"); 1205 1206 // Construct a compiler instance that will be used to actually create the 1207 // module. Since we're sharing an in-memory module cache, 1208 // CompilerInstance::CompilerInstance is responsible for finalizing the 1209 // buffers to prevent use-after-frees. 1210 CompilerInstance Instance(ImportingInstance.getPCHContainerOperations(), 1211 &ImportingInstance.getModuleCache()); 1212 auto &Inv = *Invocation; 1213 Instance.setInvocation(std::move(Invocation)); 1214 1215 Instance.createDiagnostics(new ForwardingDiagnosticConsumer( 1216 ImportingInstance.getDiagnosticClient()), 1217 /*ShouldOwnClient=*/true); 1218 1219 if (FrontendOpts.ModulesShareFileManager) { 1220 Instance.setFileManager(&ImportingInstance.getFileManager()); 1221 } else { 1222 Instance.createFileManager(&ImportingInstance.getVirtualFileSystem()); 1223 } 1224 Instance.createSourceManager(Instance.getFileManager()); 1225 SourceManager &SourceMgr = Instance.getSourceManager(); 1226 1227 // Note that this module is part of the module build stack, so that we 1228 // can detect cycles in the module graph. 1229 SourceMgr.setModuleBuildStack( 1230 ImportingInstance.getSourceManager().getModuleBuildStack()); 1231 SourceMgr.pushModuleBuildStack(ModuleName, 1232 FullSourceLoc(ImportLoc, ImportingInstance.getSourceManager())); 1233 1234 // If we're collecting module dependencies, we need to share a collector 1235 // between all of the module CompilerInstances. Other than that, we don't 1236 // want to produce any dependency output from the module build. 1237 Instance.setModuleDepCollector(ImportingInstance.getModuleDepCollector()); 1238 Inv.getDependencyOutputOpts() = DependencyOutputOptions(); 1239 1240 ImportingInstance.getDiagnostics().Report(ImportLoc, 1241 diag::remark_module_build) 1242 << ModuleName << ModuleFileName; 1243 1244 PreBuildStep(Instance); 1245 1246 // Execute the action to actually build the module in-place. Use a separate 1247 // thread so that we get a stack large enough. 1248 bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnThread( 1249 [&]() { 1250 GenerateModuleFromModuleMapAction Action; 1251 Instance.ExecuteAction(Action); 1252 }, 1253 DesiredStackSize); 1254 1255 PostBuildStep(Instance); 1256 1257 ImportingInstance.getDiagnostics().Report(ImportLoc, 1258 diag::remark_module_build_done) 1259 << ModuleName; 1260 1261 if (Crashed) { 1262 // Clear the ASTConsumer if it hasn't been already, in case it owns streams 1263 // that must be closed before clearing output files. 1264 Instance.setSema(nullptr); 1265 Instance.setASTConsumer(nullptr); 1266 1267 // Delete any remaining temporary files related to Instance. 1268 Instance.clearOutputFiles(/*EraseFiles=*/true); 1269 } 1270 1271 // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors 1272 // occurred. 1273 return !Instance.getDiagnostics().hasErrorOccurred() || 1274 Instance.getFrontendOpts().AllowPCMWithCompilerErrors; 1275 } 1276 1277 static const FileEntry *getPublicModuleMap(const FileEntry *File, 1278 FileManager &FileMgr) { 1279 StringRef Filename = llvm::sys::path::filename(File->getName()); 1280 SmallString<128> PublicFilename(File->getDir()->getName()); 1281 if (Filename == "module_private.map") 1282 llvm::sys::path::append(PublicFilename, "module.map"); 1283 else if (Filename == "module.private.modulemap") 1284 llvm::sys::path::append(PublicFilename, "module.modulemap"); 1285 else 1286 return nullptr; 1287 if (auto FE = FileMgr.getFile(PublicFilename)) 1288 return *FE; 1289 return nullptr; 1290 } 1291 1292 /// Compile a module file for the given module in a separate compiler instance, 1293 /// using the options provided by the importing compiler instance. Returns true 1294 /// if the module was built without errors. 1295 static bool compileModule(CompilerInstance &ImportingInstance, 1296 SourceLocation ImportLoc, Module *Module, 1297 StringRef ModuleFileName) { 1298 InputKind IK(getLanguageFromOptions(ImportingInstance.getLangOpts()), 1299 InputKind::ModuleMap); 1300 1301 // Get or create the module map that we'll use to build this module. 1302 ModuleMap &ModMap 1303 = ImportingInstance.getPreprocessor().getHeaderSearchInfo().getModuleMap(); 1304 bool Result; 1305 if (const FileEntry *ModuleMapFile = 1306 ModMap.getContainingModuleMapFile(Module)) { 1307 // Canonicalize compilation to start with the public module map. This is 1308 // vital for submodules declarations in the private module maps to be 1309 // correctly parsed when depending on a top level module in the public one. 1310 if (const FileEntry *PublicMMFile = getPublicModuleMap( 1311 ModuleMapFile, ImportingInstance.getFileManager())) 1312 ModuleMapFile = PublicMMFile; 1313 1314 // FIXME: Update header search to keep FileEntryRef rather than rely on 1315 // getLastRef(). 1316 StringRef ModuleMapFilePath = 1317 ModuleMapFile->getLastRef().getNameAsRequested(); 1318 1319 // Use the module map where this module resides. 1320 Result = compileModuleImpl( 1321 ImportingInstance, ImportLoc, Module->getTopLevelModuleName(), 1322 FrontendInputFile(ModuleMapFilePath, IK, +Module->IsSystem), 1323 ModMap.getModuleMapFileForUniquing(Module)->getName(), ModuleFileName); 1324 } else { 1325 // FIXME: We only need to fake up an input file here as a way of 1326 // transporting the module's directory to the module map parser. We should 1327 // be able to do that more directly, and parse from a memory buffer without 1328 // inventing this file. 1329 SmallString<128> FakeModuleMapFile(Module->Directory->getName()); 1330 llvm::sys::path::append(FakeModuleMapFile, "__inferred_module.map"); 1331 1332 std::string InferredModuleMapContent; 1333 llvm::raw_string_ostream OS(InferredModuleMapContent); 1334 Module->print(OS); 1335 OS.flush(); 1336 1337 Result = compileModuleImpl( 1338 ImportingInstance, ImportLoc, Module->getTopLevelModuleName(), 1339 FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem), 1340 ModMap.getModuleMapFileForUniquing(Module)->getName(), 1341 ModuleFileName, 1342 [&](CompilerInstance &Instance) { 1343 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer = 1344 llvm::MemoryBuffer::getMemBuffer(InferredModuleMapContent); 1345 ModuleMapFile = Instance.getFileManager().getVirtualFile( 1346 FakeModuleMapFile, InferredModuleMapContent.size(), 0); 1347 Instance.getSourceManager().overrideFileContents( 1348 ModuleMapFile, std::move(ModuleMapBuffer)); 1349 }); 1350 } 1351 1352 // We've rebuilt a module. If we're allowed to generate or update the global 1353 // module index, record that fact in the importing compiler instance. 1354 if (ImportingInstance.getFrontendOpts().GenerateGlobalModuleIndex) { 1355 ImportingInstance.setBuildGlobalModuleIndex(true); 1356 } 1357 1358 return Result; 1359 } 1360 1361 /// Read the AST right after compiling the module. 1362 static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance, 1363 SourceLocation ImportLoc, 1364 SourceLocation ModuleNameLoc, 1365 Module *Module, StringRef ModuleFileName, 1366 bool *OutOfDate) { 1367 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics(); 1368 1369 unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing; 1370 if (OutOfDate) 1371 ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate; 1372 1373 // Try to read the module file, now that we've compiled it. 1374 ASTReader::ASTReadResult ReadResult = 1375 ImportingInstance.getASTReader()->ReadAST( 1376 ModuleFileName, serialization::MK_ImplicitModule, ImportLoc, 1377 ModuleLoadCapabilities); 1378 if (ReadResult == ASTReader::Success) 1379 return true; 1380 1381 // The caller wants to handle out-of-date failures. 1382 if (OutOfDate && ReadResult == ASTReader::OutOfDate) { 1383 *OutOfDate = true; 1384 return false; 1385 } 1386 1387 // The ASTReader didn't diagnose the error, so conservatively report it. 1388 if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred()) 1389 Diags.Report(ModuleNameLoc, diag::err_module_not_built) 1390 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc); 1391 1392 return false; 1393 } 1394 1395 /// Compile a module in a separate compiler instance and read the AST, 1396 /// returning true if the module compiles without errors. 1397 static bool compileModuleAndReadASTImpl(CompilerInstance &ImportingInstance, 1398 SourceLocation ImportLoc, 1399 SourceLocation ModuleNameLoc, 1400 Module *Module, 1401 StringRef ModuleFileName) { 1402 if (!compileModule(ImportingInstance, ModuleNameLoc, Module, 1403 ModuleFileName)) { 1404 ImportingInstance.getDiagnostics().Report(ModuleNameLoc, 1405 diag::err_module_not_built) 1406 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc); 1407 return false; 1408 } 1409 1410 return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc, 1411 Module, ModuleFileName, 1412 /*OutOfDate=*/nullptr); 1413 } 1414 1415 /// Compile a module in a separate compiler instance and read the AST, 1416 /// returning true if the module compiles without errors, using a lock manager 1417 /// to avoid building the same module in multiple compiler instances. 1418 /// 1419 /// Uses a lock file manager and exponential backoff to reduce the chances that 1420 /// multiple instances will compete to create the same module. On timeout, 1421 /// deletes the lock file in order to avoid deadlock from crashing processes or 1422 /// bugs in the lock file manager. 1423 static bool compileModuleAndReadASTBehindLock( 1424 CompilerInstance &ImportingInstance, SourceLocation ImportLoc, 1425 SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) { 1426 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics(); 1427 1428 Diags.Report(ModuleNameLoc, diag::remark_module_lock) 1429 << ModuleFileName << Module->Name; 1430 1431 // FIXME: have LockFileManager return an error_code so that we can 1432 // avoid the mkdir when the directory already exists. 1433 StringRef Dir = llvm::sys::path::parent_path(ModuleFileName); 1434 llvm::sys::fs::create_directories(Dir); 1435 1436 while (true) { 1437 llvm::LockFileManager Locked(ModuleFileName); 1438 switch (Locked) { 1439 case llvm::LockFileManager::LFS_Error: 1440 // ModuleCache takes care of correctness and locks are only necessary for 1441 // performance. Fallback to building the module in case of any lock 1442 // related errors. 1443 Diags.Report(ModuleNameLoc, diag::remark_module_lock_failure) 1444 << Module->Name << Locked.getErrorMessage(); 1445 // Clear out any potential leftover. 1446 Locked.unsafeRemoveLockFile(); 1447 [[fallthrough]]; 1448 case llvm::LockFileManager::LFS_Owned: 1449 // We're responsible for building the module ourselves. 1450 return compileModuleAndReadASTImpl(ImportingInstance, ImportLoc, 1451 ModuleNameLoc, Module, ModuleFileName); 1452 1453 case llvm::LockFileManager::LFS_Shared: 1454 break; // The interesting case. 1455 } 1456 1457 // Someone else is responsible for building the module. Wait for them to 1458 // finish. 1459 switch (Locked.waitForUnlock()) { 1460 case llvm::LockFileManager::Res_Success: 1461 break; // The interesting case. 1462 case llvm::LockFileManager::Res_OwnerDied: 1463 continue; // try again to get the lock. 1464 case llvm::LockFileManager::Res_Timeout: 1465 // Since ModuleCache takes care of correctness, we try waiting for 1466 // another process to complete the build so clang does not do it done 1467 // twice. If case of timeout, build it ourselves. 1468 Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout) 1469 << Module->Name; 1470 // Clear the lock file so that future invocations can make progress. 1471 Locked.unsafeRemoveLockFile(); 1472 continue; 1473 } 1474 1475 // Read the module that was just written by someone else. 1476 bool OutOfDate = false; 1477 if (readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc, 1478 Module, ModuleFileName, &OutOfDate)) 1479 return true; 1480 if (!OutOfDate) 1481 return false; 1482 1483 // The module may be out of date in the presence of file system races, 1484 // or if one of its imports depends on header search paths that are not 1485 // consistent with this ImportingInstance. Try again... 1486 } 1487 } 1488 1489 /// Compile a module in a separate compiler instance and read the AST, 1490 /// returning true if the module compiles without errors, potentially using a 1491 /// lock manager to avoid building the same module in multiple compiler 1492 /// instances. 1493 static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance, 1494 SourceLocation ImportLoc, 1495 SourceLocation ModuleNameLoc, 1496 Module *Module, StringRef ModuleFileName) { 1497 return ImportingInstance.getInvocation() 1498 .getFrontendOpts() 1499 .BuildingImplicitModuleUsesLock 1500 ? compileModuleAndReadASTBehindLock(ImportingInstance, ImportLoc, 1501 ModuleNameLoc, Module, 1502 ModuleFileName) 1503 : compileModuleAndReadASTImpl(ImportingInstance, ImportLoc, 1504 ModuleNameLoc, Module, 1505 ModuleFileName); 1506 } 1507 1508 /// Diagnose differences between the current definition of the given 1509 /// configuration macro and the definition provided on the command line. 1510 static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro, 1511 Module *Mod, SourceLocation ImportLoc) { 1512 IdentifierInfo *Id = PP.getIdentifierInfo(ConfigMacro); 1513 SourceManager &SourceMgr = PP.getSourceManager(); 1514 1515 // If this identifier has never had a macro definition, then it could 1516 // not have changed. 1517 if (!Id->hadMacroDefinition()) 1518 return; 1519 auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(Id); 1520 1521 // Find the macro definition from the command line. 1522 MacroInfo *CmdLineDefinition = nullptr; 1523 for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) { 1524 // We only care about the predefines buffer. 1525 FileID FID = SourceMgr.getFileID(MD->getLocation()); 1526 if (FID.isInvalid() || FID != PP.getPredefinesFileID()) 1527 continue; 1528 if (auto *DMD = dyn_cast<DefMacroDirective>(MD)) 1529 CmdLineDefinition = DMD->getMacroInfo(); 1530 break; 1531 } 1532 1533 auto *CurrentDefinition = PP.getMacroInfo(Id); 1534 if (CurrentDefinition == CmdLineDefinition) { 1535 // Macro matches. Nothing to do. 1536 } else if (!CurrentDefinition) { 1537 // This macro was defined on the command line, then #undef'd later. 1538 // Complain. 1539 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 1540 << true << ConfigMacro << Mod->getFullModuleName(); 1541 auto LatestDef = LatestLocalMD->getDefinition(); 1542 assert(LatestDef.isUndefined() && 1543 "predefined macro went away with no #undef?"); 1544 PP.Diag(LatestDef.getUndefLocation(), diag::note_module_def_undef_here) 1545 << true; 1546 return; 1547 } else if (!CmdLineDefinition) { 1548 // There was no definition for this macro in the predefines buffer, 1549 // but there was a local definition. Complain. 1550 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 1551 << false << ConfigMacro << Mod->getFullModuleName(); 1552 PP.Diag(CurrentDefinition->getDefinitionLoc(), 1553 diag::note_module_def_undef_here) 1554 << false; 1555 } else if (!CurrentDefinition->isIdenticalTo(*CmdLineDefinition, PP, 1556 /*Syntactically=*/true)) { 1557 // The macro definitions differ. 1558 PP.Diag(ImportLoc, diag::warn_module_config_macro_undef) 1559 << false << ConfigMacro << Mod->getFullModuleName(); 1560 PP.Diag(CurrentDefinition->getDefinitionLoc(), 1561 diag::note_module_def_undef_here) 1562 << false; 1563 } 1564 } 1565 1566 /// Write a new timestamp file with the given path. 1567 static void writeTimestampFile(StringRef TimestampFile) { 1568 std::error_code EC; 1569 llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None); 1570 } 1571 1572 /// Prune the module cache of modules that haven't been accessed in 1573 /// a long time. 1574 static void pruneModuleCache(const HeaderSearchOptions &HSOpts) { 1575 llvm::sys::fs::file_status StatBuf; 1576 llvm::SmallString<128> TimestampFile; 1577 TimestampFile = HSOpts.ModuleCachePath; 1578 assert(!TimestampFile.empty()); 1579 llvm::sys::path::append(TimestampFile, "modules.timestamp"); 1580 1581 // Try to stat() the timestamp file. 1582 if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) { 1583 // If the timestamp file wasn't there, create one now. 1584 if (EC == std::errc::no_such_file_or_directory) { 1585 writeTimestampFile(TimestampFile); 1586 } 1587 return; 1588 } 1589 1590 // Check whether the time stamp is older than our pruning interval. 1591 // If not, do nothing. 1592 time_t TimeStampModTime = 1593 llvm::sys::toTimeT(StatBuf.getLastModificationTime()); 1594 time_t CurrentTime = time(nullptr); 1595 if (CurrentTime - TimeStampModTime <= time_t(HSOpts.ModuleCachePruneInterval)) 1596 return; 1597 1598 // Write a new timestamp file so that nobody else attempts to prune. 1599 // There is a benign race condition here, if two Clang instances happen to 1600 // notice at the same time that the timestamp is out-of-date. 1601 writeTimestampFile(TimestampFile); 1602 1603 // Walk the entire module cache, looking for unused module files and module 1604 // indices. 1605 std::error_code EC; 1606 SmallString<128> ModuleCachePathNative; 1607 llvm::sys::path::native(HSOpts.ModuleCachePath, ModuleCachePathNative); 1608 for (llvm::sys::fs::directory_iterator Dir(ModuleCachePathNative, EC), DirEnd; 1609 Dir != DirEnd && !EC; Dir.increment(EC)) { 1610 // If we don't have a directory, there's nothing to look into. 1611 if (!llvm::sys::fs::is_directory(Dir->path())) 1612 continue; 1613 1614 // Walk all of the files within this directory. 1615 for (llvm::sys::fs::directory_iterator File(Dir->path(), EC), FileEnd; 1616 File != FileEnd && !EC; File.increment(EC)) { 1617 // We only care about module and global module index files. 1618 StringRef Extension = llvm::sys::path::extension(File->path()); 1619 if (Extension != ".pcm" && Extension != ".timestamp" && 1620 llvm::sys::path::filename(File->path()) != "modules.idx") 1621 continue; 1622 1623 // Look at this file. If we can't stat it, there's nothing interesting 1624 // there. 1625 if (llvm::sys::fs::status(File->path(), StatBuf)) 1626 continue; 1627 1628 // If the file has been used recently enough, leave it there. 1629 time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime()); 1630 if (CurrentTime - FileAccessTime <= 1631 time_t(HSOpts.ModuleCachePruneAfter)) { 1632 continue; 1633 } 1634 1635 // Remove the file. 1636 llvm::sys::fs::remove(File->path()); 1637 1638 // Remove the timestamp file. 1639 std::string TimpestampFilename = File->path() + ".timestamp"; 1640 llvm::sys::fs::remove(TimpestampFilename); 1641 } 1642 1643 // If we removed all of the files in the directory, remove the directory 1644 // itself. 1645 if (llvm::sys::fs::directory_iterator(Dir->path(), EC) == 1646 llvm::sys::fs::directory_iterator() && !EC) 1647 llvm::sys::fs::remove(Dir->path()); 1648 } 1649 } 1650 1651 void CompilerInstance::createASTReader() { 1652 if (TheASTReader) 1653 return; 1654 1655 if (!hasASTContext()) 1656 createASTContext(); 1657 1658 // If we're implicitly building modules but not currently recursively 1659 // building a module, check whether we need to prune the module cache. 1660 if (getSourceManager().getModuleBuildStack().empty() && 1661 !getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty() && 1662 getHeaderSearchOpts().ModuleCachePruneInterval > 0 && 1663 getHeaderSearchOpts().ModuleCachePruneAfter > 0) { 1664 pruneModuleCache(getHeaderSearchOpts()); 1665 } 1666 1667 HeaderSearchOptions &HSOpts = getHeaderSearchOpts(); 1668 std::string Sysroot = HSOpts.Sysroot; 1669 const PreprocessorOptions &PPOpts = getPreprocessorOpts(); 1670 const FrontendOptions &FEOpts = getFrontendOpts(); 1671 std::unique_ptr<llvm::Timer> ReadTimer; 1672 1673 if (FrontendTimerGroup) 1674 ReadTimer = std::make_unique<llvm::Timer>("reading_modules", 1675 "Reading modules", 1676 *FrontendTimerGroup); 1677 TheASTReader = new ASTReader( 1678 getPreprocessor(), getModuleCache(), &getASTContext(), 1679 getPCHContainerReader(), getFrontendOpts().ModuleFileExtensions, 1680 Sysroot.empty() ? "" : Sysroot.c_str(), 1681 PPOpts.DisablePCHOrModuleValidation, 1682 /*AllowASTWithCompilerErrors=*/FEOpts.AllowPCMWithCompilerErrors, 1683 /*AllowConfigurationMismatch=*/false, HSOpts.ModulesValidateSystemHeaders, 1684 HSOpts.ValidateASTInputFilesContent, 1685 getFrontendOpts().UseGlobalModuleIndex, std::move(ReadTimer)); 1686 if (hasASTConsumer()) { 1687 TheASTReader->setDeserializationListener( 1688 getASTConsumer().GetASTDeserializationListener()); 1689 getASTContext().setASTMutationListener( 1690 getASTConsumer().GetASTMutationListener()); 1691 } 1692 getASTContext().setExternalSource(TheASTReader); 1693 if (hasSema()) 1694 TheASTReader->InitializeSema(getSema()); 1695 if (hasASTConsumer()) 1696 TheASTReader->StartTranslationUnit(&getASTConsumer()); 1697 1698 for (auto &Listener : DependencyCollectors) 1699 Listener->attachToASTReader(*TheASTReader); 1700 } 1701 1702 bool CompilerInstance::loadModuleFile(StringRef FileName) { 1703 llvm::Timer Timer; 1704 if (FrontendTimerGroup) 1705 Timer.init("preloading." + FileName.str(), "Preloading " + FileName.str(), 1706 *FrontendTimerGroup); 1707 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr); 1708 1709 // If we don't already have an ASTReader, create one now. 1710 if (!TheASTReader) 1711 createASTReader(); 1712 1713 // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the 1714 // ASTReader to diagnose it, since it can produce better errors that we can. 1715 bool ConfigMismatchIsRecoverable = 1716 getDiagnostics().getDiagnosticLevel(diag::warn_module_config_mismatch, 1717 SourceLocation()) 1718 <= DiagnosticsEngine::Warning; 1719 1720 auto Listener = std::make_unique<ReadModuleNames>(*PP); 1721 auto &ListenerRef = *Listener; 1722 ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader, 1723 std::move(Listener)); 1724 1725 // Try to load the module file. 1726 switch (TheASTReader->ReadAST( 1727 FileName, serialization::MK_ExplicitModule, SourceLocation(), 1728 ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0)) { 1729 case ASTReader::Success: 1730 // We successfully loaded the module file; remember the set of provided 1731 // modules so that we don't try to load implicit modules for them. 1732 ListenerRef.registerAll(); 1733 return true; 1734 1735 case ASTReader::ConfigurationMismatch: 1736 // Ignore unusable module files. 1737 getDiagnostics().Report(SourceLocation(), diag::warn_module_config_mismatch) 1738 << FileName; 1739 // All modules provided by any files we tried and failed to load are now 1740 // unavailable; includes of those modules should now be handled textually. 1741 ListenerRef.markAllUnavailable(); 1742 return true; 1743 1744 default: 1745 return false; 1746 } 1747 } 1748 1749 namespace { 1750 enum ModuleSource { 1751 MS_ModuleNotFound, 1752 MS_ModuleCache, 1753 MS_PrebuiltModulePath, 1754 MS_ModuleBuildPragma 1755 }; 1756 } // end namespace 1757 1758 /// Select a source for loading the named module and compute the filename to 1759 /// load it from. 1760 static ModuleSource selectModuleSource( 1761 Module *M, StringRef ModuleName, std::string &ModuleFilename, 1762 const std::map<std::string, std::string, std::less<>> &BuiltModules, 1763 HeaderSearch &HS) { 1764 assert(ModuleFilename.empty() && "Already has a module source?"); 1765 1766 // Check to see if the module has been built as part of this compilation 1767 // via a module build pragma. 1768 auto BuiltModuleIt = BuiltModules.find(ModuleName); 1769 if (BuiltModuleIt != BuiltModules.end()) { 1770 ModuleFilename = BuiltModuleIt->second; 1771 return MS_ModuleBuildPragma; 1772 } 1773 1774 // Try to load the module from the prebuilt module path. 1775 const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts(); 1776 if (!HSOpts.PrebuiltModuleFiles.empty() || 1777 !HSOpts.PrebuiltModulePaths.empty()) { 1778 ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName); 1779 if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty()) 1780 ModuleFilename = HS.getPrebuiltImplicitModuleFileName(M); 1781 if (!ModuleFilename.empty()) 1782 return MS_PrebuiltModulePath; 1783 } 1784 1785 // Try to load the module from the module cache. 1786 if (M) { 1787 ModuleFilename = HS.getCachedModuleFileName(M); 1788 return MS_ModuleCache; 1789 } 1790 1791 return MS_ModuleNotFound; 1792 } 1793 1794 ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST( 1795 StringRef ModuleName, SourceLocation ImportLoc, 1796 SourceLocation ModuleNameLoc, bool IsInclusionDirective) { 1797 // Search for a module with the given name. 1798 HeaderSearch &HS = PP->getHeaderSearchInfo(); 1799 Module *M = 1800 HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective); 1801 1802 // Select the source and filename for loading the named module. 1803 std::string ModuleFilename; 1804 ModuleSource Source = 1805 selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS); 1806 if (Source == MS_ModuleNotFound) { 1807 // We can't find a module, error out here. 1808 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found) 1809 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc); 1810 return nullptr; 1811 } 1812 if (ModuleFilename.empty()) { 1813 if (M && M->HasIncompatibleModuleFile) { 1814 // We tried and failed to load a module file for this module. Fall 1815 // back to textual inclusion for its headers. 1816 return ModuleLoadResult::ConfigMismatch; 1817 } 1818 1819 getDiagnostics().Report(ModuleNameLoc, diag::err_module_build_disabled) 1820 << ModuleName; 1821 return nullptr; 1822 } 1823 1824 // Create an ASTReader on demand. 1825 if (!getASTReader()) 1826 createASTReader(); 1827 1828 // Time how long it takes to load the module. 1829 llvm::Timer Timer; 1830 if (FrontendTimerGroup) 1831 Timer.init("loading." + ModuleFilename, "Loading " + ModuleFilename, 1832 *FrontendTimerGroup); 1833 llvm::TimeRegion TimeLoading(FrontendTimerGroup ? &Timer : nullptr); 1834 llvm::TimeTraceScope TimeScope("Module Load", ModuleName); 1835 1836 // Try to load the module file. If we are not trying to load from the 1837 // module cache, we don't know how to rebuild modules. 1838 unsigned ARRFlags = Source == MS_ModuleCache 1839 ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing | 1840 ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate 1841 : Source == MS_PrebuiltModulePath 1842 ? 0 1843 : ASTReader::ARR_ConfigurationMismatch; 1844 switch (getASTReader()->ReadAST(ModuleFilename, 1845 Source == MS_PrebuiltModulePath 1846 ? serialization::MK_PrebuiltModule 1847 : Source == MS_ModuleBuildPragma 1848 ? serialization::MK_ExplicitModule 1849 : serialization::MK_ImplicitModule, 1850 ImportLoc, ARRFlags)) { 1851 case ASTReader::Success: { 1852 if (M) 1853 return M; 1854 assert(Source != MS_ModuleCache && 1855 "missing module, but file loaded from cache"); 1856 1857 // A prebuilt module is indexed as a ModuleFile; the Module does not exist 1858 // until the first call to ReadAST. Look it up now. 1859 M = HS.lookupModule(ModuleName, ImportLoc, true, !IsInclusionDirective); 1860 1861 // Check whether M refers to the file in the prebuilt module path. 1862 if (M && M->getASTFile()) 1863 if (auto ModuleFile = FileMgr->getFile(ModuleFilename)) 1864 if (*ModuleFile == M->getASTFile()) 1865 return M; 1866 1867 getDiagnostics().Report(ModuleNameLoc, diag::err_module_prebuilt) 1868 << ModuleName; 1869 return ModuleLoadResult(); 1870 } 1871 1872 case ASTReader::OutOfDate: 1873 case ASTReader::Missing: 1874 // The most interesting case. 1875 break; 1876 1877 case ASTReader::ConfigurationMismatch: 1878 if (Source == MS_PrebuiltModulePath) 1879 // FIXME: We shouldn't be setting HadFatalFailure below if we only 1880 // produce a warning here! 1881 getDiagnostics().Report(SourceLocation(), 1882 diag::warn_module_config_mismatch) 1883 << ModuleFilename; 1884 // Fall through to error out. 1885 [[fallthrough]]; 1886 case ASTReader::VersionMismatch: 1887 case ASTReader::HadErrors: 1888 ModuleLoader::HadFatalFailure = true; 1889 // FIXME: The ASTReader will already have complained, but can we shoehorn 1890 // that diagnostic information into a more useful form? 1891 return ModuleLoadResult(); 1892 1893 case ASTReader::Failure: 1894 ModuleLoader::HadFatalFailure = true; 1895 return ModuleLoadResult(); 1896 } 1897 1898 // ReadAST returned Missing or OutOfDate. 1899 if (Source != MS_ModuleCache) { 1900 // We don't know the desired configuration for this module and don't 1901 // necessarily even have a module map. Since ReadAST already produces 1902 // diagnostics for these two cases, we simply error out here. 1903 return ModuleLoadResult(); 1904 } 1905 1906 // The module file is missing or out-of-date. Build it. 1907 assert(M && "missing module, but trying to compile for cache"); 1908 1909 // Check whether there is a cycle in the module graph. 1910 ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack(); 1911 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end(); 1912 for (; Pos != PosEnd; ++Pos) { 1913 if (Pos->first == ModuleName) 1914 break; 1915 } 1916 1917 if (Pos != PosEnd) { 1918 SmallString<256> CyclePath; 1919 for (; Pos != PosEnd; ++Pos) { 1920 CyclePath += Pos->first; 1921 CyclePath += " -> "; 1922 } 1923 CyclePath += ModuleName; 1924 1925 getDiagnostics().Report(ModuleNameLoc, diag::err_module_cycle) 1926 << ModuleName << CyclePath; 1927 return nullptr; 1928 } 1929 1930 // Check whether we have already attempted to build this module (but 1931 // failed). 1932 if (getPreprocessorOpts().FailedModules && 1933 getPreprocessorOpts().FailedModules->hasAlreadyFailed(ModuleName)) { 1934 getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_built) 1935 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc); 1936 return nullptr; 1937 } 1938 1939 // Try to compile and then read the AST. 1940 if (!compileModuleAndReadAST(*this, ImportLoc, ModuleNameLoc, M, 1941 ModuleFilename)) { 1942 assert(getDiagnostics().hasErrorOccurred() && 1943 "undiagnosed error in compileModuleAndReadAST"); 1944 if (getPreprocessorOpts().FailedModules) 1945 getPreprocessorOpts().FailedModules->addFailed(ModuleName); 1946 return nullptr; 1947 } 1948 1949 // Okay, we've rebuilt and now loaded the module. 1950 return M; 1951 } 1952 1953 ModuleLoadResult 1954 CompilerInstance::loadModule(SourceLocation ImportLoc, 1955 ModuleIdPath Path, 1956 Module::NameVisibilityKind Visibility, 1957 bool IsInclusionDirective) { 1958 // Determine what file we're searching from. 1959 StringRef ModuleName = Path[0].first->getName(); 1960 SourceLocation ModuleNameLoc = Path[0].second; 1961 1962 // If we've already handled this import, just return the cached result. 1963 // This one-element cache is important to eliminate redundant diagnostics 1964 // when both the preprocessor and parser see the same import declaration. 1965 if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) { 1966 // Make the named module visible. 1967 if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule) 1968 TheASTReader->makeModuleVisible(LastModuleImportResult, Visibility, 1969 ImportLoc); 1970 return LastModuleImportResult; 1971 } 1972 1973 // If we don't already have information on this module, load the module now. 1974 Module *Module = nullptr; 1975 ModuleMap &MM = getPreprocessor().getHeaderSearchInfo().getModuleMap(); 1976 if (auto MaybeModule = MM.getCachedModuleLoad(*Path[0].first)) { 1977 // Use the cached result, which may be nullptr. 1978 Module = *MaybeModule; 1979 } else if (ModuleName == getLangOpts().CurrentModule) { 1980 // This is the module we're building. 1981 Module = PP->getHeaderSearchInfo().lookupModule( 1982 ModuleName, ImportLoc, /*AllowSearch*/ true, 1983 /*AllowExtraModuleMapSearch*/ !IsInclusionDirective); 1984 /// FIXME: perhaps we should (a) look for a module using the module name 1985 // to file map (PrebuiltModuleFiles) and (b) diagnose if still not found? 1986 //if (Module == nullptr) { 1987 // getDiagnostics().Report(ModuleNameLoc, diag::err_module_not_found) 1988 // << ModuleName; 1989 // DisableGeneratingGlobalModuleIndex = true; 1990 // return ModuleLoadResult(); 1991 //} 1992 MM.cacheModuleLoad(*Path[0].first, Module); 1993 } else { 1994 ModuleLoadResult Result = findOrCompileModuleAndReadAST( 1995 ModuleName, ImportLoc, ModuleNameLoc, IsInclusionDirective); 1996 if (!Result.isNormal()) 1997 return Result; 1998 if (!Result) 1999 DisableGeneratingGlobalModuleIndex = true; 2000 Module = Result; 2001 MM.cacheModuleLoad(*Path[0].first, Module); 2002 } 2003 2004 // If we never found the module, fail. Otherwise, verify the module and link 2005 // it up. 2006 if (!Module) 2007 return ModuleLoadResult(); 2008 2009 // Verify that the rest of the module path actually corresponds to 2010 // a submodule. 2011 bool MapPrivateSubModToTopLevel = false; 2012 for (unsigned I = 1, N = Path.size(); I != N; ++I) { 2013 StringRef Name = Path[I].first->getName(); 2014 clang::Module *Sub = Module->findSubmodule(Name); 2015 2016 // If the user is requesting Foo.Private and it doesn't exist, try to 2017 // match Foo_Private and emit a warning asking for the user to write 2018 // @import Foo_Private instead. FIXME: remove this when existing clients 2019 // migrate off of Foo.Private syntax. 2020 if (!Sub && Name == "Private" && Module == Module->getTopLevelModule()) { 2021 SmallString<128> PrivateModule(Module->Name); 2022 PrivateModule.append("_Private"); 2023 2024 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> PrivPath; 2025 auto &II = PP->getIdentifierTable().get( 2026 PrivateModule, PP->getIdentifierInfo(Module->Name)->getTokenID()); 2027 PrivPath.push_back(std::make_pair(&II, Path[0].second)); 2028 2029 if (PP->getHeaderSearchInfo().lookupModule(PrivateModule, ImportLoc, true, 2030 !IsInclusionDirective)) 2031 Sub = loadModule(ImportLoc, PrivPath, Visibility, IsInclusionDirective); 2032 if (Sub) { 2033 MapPrivateSubModToTopLevel = true; 2034 PP->markModuleAsAffecting(Module); 2035 if (!getDiagnostics().isIgnored( 2036 diag::warn_no_priv_submodule_use_toplevel, ImportLoc)) { 2037 getDiagnostics().Report(Path[I].second, 2038 diag::warn_no_priv_submodule_use_toplevel) 2039 << Path[I].first << Module->getFullModuleName() << PrivateModule 2040 << SourceRange(Path[0].second, Path[I].second) 2041 << FixItHint::CreateReplacement(SourceRange(Path[0].second), 2042 PrivateModule); 2043 getDiagnostics().Report(Sub->DefinitionLoc, 2044 diag::note_private_top_level_defined); 2045 } 2046 } 2047 } 2048 2049 if (!Sub) { 2050 // Attempt to perform typo correction to find a module name that works. 2051 SmallVector<StringRef, 2> Best; 2052 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)(); 2053 2054 for (class Module *SubModule : Module->submodules()) { 2055 unsigned ED = 2056 Name.edit_distance(SubModule->Name, 2057 /*AllowReplacements=*/true, BestEditDistance); 2058 if (ED <= BestEditDistance) { 2059 if (ED < BestEditDistance) { 2060 Best.clear(); 2061 BestEditDistance = ED; 2062 } 2063 2064 Best.push_back(SubModule->Name); 2065 } 2066 } 2067 2068 // If there was a clear winner, user it. 2069 if (Best.size() == 1) { 2070 getDiagnostics().Report(Path[I].second, diag::err_no_submodule_suggest) 2071 << Path[I].first << Module->getFullModuleName() << Best[0] 2072 << SourceRange(Path[0].second, Path[I - 1].second) 2073 << FixItHint::CreateReplacement(SourceRange(Path[I].second), 2074 Best[0]); 2075 2076 Sub = Module->findSubmodule(Best[0]); 2077 } 2078 } 2079 2080 if (!Sub) { 2081 // No submodule by this name. Complain, and don't look for further 2082 // submodules. 2083 getDiagnostics().Report(Path[I].second, diag::err_no_submodule) 2084 << Path[I].first << Module->getFullModuleName() 2085 << SourceRange(Path[0].second, Path[I - 1].second); 2086 break; 2087 } 2088 2089 Module = Sub; 2090 } 2091 2092 // Make the named module visible, if it's not already part of the module 2093 // we are parsing. 2094 if (ModuleName != getLangOpts().CurrentModule) { 2095 if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) { 2096 // We have an umbrella header or directory that doesn't actually include 2097 // all of the headers within the directory it covers. Complain about 2098 // this missing submodule and recover by forgetting that we ever saw 2099 // this submodule. 2100 // FIXME: Should we detect this at module load time? It seems fairly 2101 // expensive (and rare). 2102 getDiagnostics().Report(ImportLoc, diag::warn_missing_submodule) 2103 << Module->getFullModuleName() 2104 << SourceRange(Path.front().second, Path.back().second); 2105 2106 return ModuleLoadResult(Module, ModuleLoadResult::MissingExpected); 2107 } 2108 2109 // Check whether this module is available. 2110 if (Preprocessor::checkModuleIsAvailable(getLangOpts(), getTarget(), 2111 getDiagnostics(), Module)) { 2112 getDiagnostics().Report(ImportLoc, diag::note_module_import_here) 2113 << SourceRange(Path.front().second, Path.back().second); 2114 LastModuleImportLoc = ImportLoc; 2115 LastModuleImportResult = ModuleLoadResult(); 2116 return ModuleLoadResult(); 2117 } 2118 2119 TheASTReader->makeModuleVisible(Module, Visibility, ImportLoc); 2120 } 2121 2122 // Check for any configuration macros that have changed. 2123 clang::Module *TopModule = Module->getTopLevelModule(); 2124 for (unsigned I = 0, N = TopModule->ConfigMacros.size(); I != N; ++I) { 2125 checkConfigMacro(getPreprocessor(), TopModule->ConfigMacros[I], 2126 Module, ImportLoc); 2127 } 2128 2129 // Resolve any remaining module using export_as for this one. 2130 getPreprocessor() 2131 .getHeaderSearchInfo() 2132 .getModuleMap() 2133 .resolveLinkAsDependencies(TopModule); 2134 2135 LastModuleImportLoc = ImportLoc; 2136 LastModuleImportResult = ModuleLoadResult(Module); 2137 return LastModuleImportResult; 2138 } 2139 2140 void CompilerInstance::createModuleFromSource(SourceLocation ImportLoc, 2141 StringRef ModuleName, 2142 StringRef Source) { 2143 // Avoid creating filenames with special characters. 2144 SmallString<128> CleanModuleName(ModuleName); 2145 for (auto &C : CleanModuleName) 2146 if (!isAlphanumeric(C)) 2147 C = '_'; 2148 2149 // FIXME: Using a randomized filename here means that our intermediate .pcm 2150 // output is nondeterministic (as .pcm files refer to each other by name). 2151 // Can this affect the output in any way? 2152 SmallString<128> ModuleFileName; 2153 if (std::error_code EC = llvm::sys::fs::createTemporaryFile( 2154 CleanModuleName, "pcm", ModuleFileName)) { 2155 getDiagnostics().Report(ImportLoc, diag::err_fe_unable_to_open_output) 2156 << ModuleFileName << EC.message(); 2157 return; 2158 } 2159 std::string ModuleMapFileName = (CleanModuleName + ".map").str(); 2160 2161 FrontendInputFile Input( 2162 ModuleMapFileName, 2163 InputKind(getLanguageFromOptions(*Invocation->getLangOpts()), 2164 InputKind::ModuleMap, /*Preprocessed*/true)); 2165 2166 std::string NullTerminatedSource(Source.str()); 2167 2168 auto PreBuildStep = [&](CompilerInstance &Other) { 2169 // Create a virtual file containing our desired source. 2170 // FIXME: We shouldn't need to do this. 2171 const FileEntry *ModuleMapFile = Other.getFileManager().getVirtualFile( 2172 ModuleMapFileName, NullTerminatedSource.size(), 0); 2173 Other.getSourceManager().overrideFileContents( 2174 ModuleMapFile, llvm::MemoryBuffer::getMemBuffer(NullTerminatedSource)); 2175 2176 Other.BuiltModules = std::move(BuiltModules); 2177 Other.DeleteBuiltModules = false; 2178 }; 2179 2180 auto PostBuildStep = [this](CompilerInstance &Other) { 2181 BuiltModules = std::move(Other.BuiltModules); 2182 }; 2183 2184 // Build the module, inheriting any modules that we've built locally. 2185 if (compileModuleImpl(*this, ImportLoc, ModuleName, Input, StringRef(), 2186 ModuleFileName, PreBuildStep, PostBuildStep)) { 2187 BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName.str()); 2188 llvm::sys::RemoveFileOnSignal(ModuleFileName); 2189 } 2190 } 2191 2192 void CompilerInstance::makeModuleVisible(Module *Mod, 2193 Module::NameVisibilityKind Visibility, 2194 SourceLocation ImportLoc) { 2195 if (!TheASTReader) 2196 createASTReader(); 2197 if (!TheASTReader) 2198 return; 2199 2200 TheASTReader->makeModuleVisible(Mod, Visibility, ImportLoc); 2201 } 2202 2203 GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex( 2204 SourceLocation TriggerLoc) { 2205 if (getPreprocessor().getHeaderSearchInfo().getModuleCachePath().empty()) 2206 return nullptr; 2207 if (!TheASTReader) 2208 createASTReader(); 2209 // Can't do anything if we don't have the module manager. 2210 if (!TheASTReader) 2211 return nullptr; 2212 // Get an existing global index. This loads it if not already 2213 // loaded. 2214 TheASTReader->loadGlobalIndex(); 2215 GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex(); 2216 // If the global index doesn't exist, create it. 2217 if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() && 2218 hasPreprocessor()) { 2219 llvm::sys::fs::create_directories( 2220 getPreprocessor().getHeaderSearchInfo().getModuleCachePath()); 2221 if (llvm::Error Err = GlobalModuleIndex::writeIndex( 2222 getFileManager(), getPCHContainerReader(), 2223 getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) { 2224 // FIXME this drops the error on the floor. This code is only used for 2225 // typo correction and drops more than just this one source of errors 2226 // (such as the directory creation failure above). It should handle the 2227 // error. 2228 consumeError(std::move(Err)); 2229 return nullptr; 2230 } 2231 TheASTReader->resetForReload(); 2232 TheASTReader->loadGlobalIndex(); 2233 GlobalIndex = TheASTReader->getGlobalIndex(); 2234 } 2235 // For finding modules needing to be imported for fixit messages, 2236 // we need to make the global index cover all modules, so we do that here. 2237 if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) { 2238 ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap(); 2239 bool RecreateIndex = false; 2240 for (ModuleMap::module_iterator I = MMap.module_begin(), 2241 E = MMap.module_end(); I != E; ++I) { 2242 Module *TheModule = I->second; 2243 const FileEntry *Entry = TheModule->getASTFile(); 2244 if (!Entry) { 2245 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 2246 Path.push_back(std::make_pair( 2247 getPreprocessor().getIdentifierInfo(TheModule->Name), TriggerLoc)); 2248 std::reverse(Path.begin(), Path.end()); 2249 // Load a module as hidden. This also adds it to the global index. 2250 loadModule(TheModule->DefinitionLoc, Path, Module::Hidden, false); 2251 RecreateIndex = true; 2252 } 2253 } 2254 if (RecreateIndex) { 2255 if (llvm::Error Err = GlobalModuleIndex::writeIndex( 2256 getFileManager(), getPCHContainerReader(), 2257 getPreprocessor().getHeaderSearchInfo().getModuleCachePath())) { 2258 // FIXME As above, this drops the error on the floor. 2259 consumeError(std::move(Err)); 2260 return nullptr; 2261 } 2262 TheASTReader->resetForReload(); 2263 TheASTReader->loadGlobalIndex(); 2264 GlobalIndex = TheASTReader->getGlobalIndex(); 2265 } 2266 HaveFullGlobalModuleIndex = true; 2267 } 2268 return GlobalIndex; 2269 } 2270 2271 // Check global module index for missing imports. 2272 bool 2273 CompilerInstance::lookupMissingImports(StringRef Name, 2274 SourceLocation TriggerLoc) { 2275 // Look for the symbol in non-imported modules, but only if an error 2276 // actually occurred. 2277 if (!buildingModule()) { 2278 // Load global module index, or retrieve a previously loaded one. 2279 GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex( 2280 TriggerLoc); 2281 2282 // Only if we have a global index. 2283 if (GlobalIndex) { 2284 GlobalModuleIndex::HitSet FoundModules; 2285 2286 // Find the modules that reference the identifier. 2287 // Note that this only finds top-level modules. 2288 // We'll let diagnoseTypo find the actual declaration module. 2289 if (GlobalIndex->lookupIdentifier(Name, FoundModules)) 2290 return true; 2291 } 2292 } 2293 2294 return false; 2295 } 2296 void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(takeSema()); } 2297 2298 void CompilerInstance::setExternalSemaSource( 2299 IntrusiveRefCntPtr<ExternalSemaSource> ESS) { 2300 ExternalSemaSrc = std::move(ESS); 2301 } 2302