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