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