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