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