1 //===--- FrontendAction.cpp -----------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "clang/Frontend/FrontendAction.h" 11 #include "clang/AST/ASTConsumer.h" 12 #include "clang/AST/ASTContext.h" 13 #include "clang/AST/DeclGroup.h" 14 #include "clang/Frontend/ASTUnit.h" 15 #include "clang/Frontend/CompilerInstance.h" 16 #include "clang/Frontend/FrontendDiagnostic.h" 17 #include "clang/Frontend/FrontendPluginRegistry.h" 18 #include "clang/Frontend/LayoutOverrideSource.h" 19 #include "clang/Frontend/MultiplexConsumer.h" 20 #include "clang/Frontend/Utils.h" 21 #include "clang/Lex/HeaderSearch.h" 22 #include "clang/Lex/LiteralSupport.h" 23 #include "clang/Lex/Preprocessor.h" 24 #include "clang/Lex/PreprocessorOptions.h" 25 #include "clang/Parse/ParseAST.h" 26 #include "clang/Serialization/ASTDeserializationListener.h" 27 #include "clang/Serialization/ASTReader.h" 28 #include "clang/Serialization/GlobalModuleIndex.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/FileSystem.h" 31 #include "llvm/Support/Path.h" 32 #include "llvm/Support/Timer.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include <system_error> 35 using namespace clang; 36 37 LLVM_INSTANTIATE_REGISTRY(FrontendPluginRegistry) 38 39 namespace { 40 41 class DelegatingDeserializationListener : public ASTDeserializationListener { 42 ASTDeserializationListener *Previous; 43 bool DeletePrevious; 44 45 public: 46 explicit DelegatingDeserializationListener( 47 ASTDeserializationListener *Previous, bool DeletePrevious) 48 : Previous(Previous), DeletePrevious(DeletePrevious) {} 49 ~DelegatingDeserializationListener() override { 50 if (DeletePrevious) 51 delete Previous; 52 } 53 54 void ReaderInitialized(ASTReader *Reader) override { 55 if (Previous) 56 Previous->ReaderInitialized(Reader); 57 } 58 void IdentifierRead(serialization::IdentID ID, 59 IdentifierInfo *II) override { 60 if (Previous) 61 Previous->IdentifierRead(ID, II); 62 } 63 void TypeRead(serialization::TypeIdx Idx, QualType T) override { 64 if (Previous) 65 Previous->TypeRead(Idx, T); 66 } 67 void DeclRead(serialization::DeclID ID, const Decl *D) override { 68 if (Previous) 69 Previous->DeclRead(ID, D); 70 } 71 void SelectorRead(serialization::SelectorID ID, Selector Sel) override { 72 if (Previous) 73 Previous->SelectorRead(ID, Sel); 74 } 75 void MacroDefinitionRead(serialization::PreprocessedEntityID PPID, 76 MacroDefinitionRecord *MD) override { 77 if (Previous) 78 Previous->MacroDefinitionRead(PPID, MD); 79 } 80 }; 81 82 /// Dumps deserialized declarations. 83 class DeserializedDeclsDumper : public DelegatingDeserializationListener { 84 public: 85 explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous, 86 bool DeletePrevious) 87 : DelegatingDeserializationListener(Previous, DeletePrevious) {} 88 89 void DeclRead(serialization::DeclID ID, const Decl *D) override { 90 llvm::outs() << "PCH DECL: " << D->getDeclKindName(); 91 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 92 llvm::outs() << " - " << *ND; 93 llvm::outs() << "\n"; 94 95 DelegatingDeserializationListener::DeclRead(ID, D); 96 } 97 }; 98 99 /// Checks deserialized declarations and emits error if a name 100 /// matches one given in command-line using -error-on-deserialized-decl. 101 class DeserializedDeclsChecker : public DelegatingDeserializationListener { 102 ASTContext &Ctx; 103 std::set<std::string> NamesToCheck; 104 105 public: 106 DeserializedDeclsChecker(ASTContext &Ctx, 107 const std::set<std::string> &NamesToCheck, 108 ASTDeserializationListener *Previous, 109 bool DeletePrevious) 110 : DelegatingDeserializationListener(Previous, DeletePrevious), Ctx(Ctx), 111 NamesToCheck(NamesToCheck) {} 112 113 void DeclRead(serialization::DeclID ID, const Decl *D) override { 114 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 115 if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) { 116 unsigned DiagID 117 = Ctx.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, 118 "%0 was deserialized"); 119 Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID) 120 << ND->getNameAsString(); 121 } 122 123 DelegatingDeserializationListener::DeclRead(ID, D); 124 } 125 }; 126 127 } // end anonymous namespace 128 129 FrontendAction::FrontendAction() : Instance(nullptr) {} 130 131 FrontendAction::~FrontendAction() {} 132 133 void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput, 134 std::unique_ptr<ASTUnit> AST) { 135 this->CurrentInput = CurrentInput; 136 CurrentASTUnit = std::move(AST); 137 } 138 139 Module *FrontendAction::getCurrentModule() const { 140 CompilerInstance &CI = getCompilerInstance(); 141 return CI.getPreprocessor().getHeaderSearchInfo().lookupModule( 142 CI.getLangOpts().CurrentModule, /*AllowSearch*/false); 143 } 144 145 std::unique_ptr<ASTConsumer> 146 FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI, 147 StringRef InFile) { 148 std::unique_ptr<ASTConsumer> Consumer = CreateASTConsumer(CI, InFile); 149 if (!Consumer) 150 return nullptr; 151 152 // If there are no registered plugins we don't need to wrap the consumer 153 if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end()) 154 return Consumer; 155 156 // If this is a code completion run, avoid invoking the plugin consumers 157 if (CI.hasCodeCompletionConsumer()) 158 return Consumer; 159 160 // Collect the list of plugins that go before the main action (in Consumers) 161 // or after it (in AfterConsumers) 162 std::vector<std::unique_ptr<ASTConsumer>> Consumers; 163 std::vector<std::unique_ptr<ASTConsumer>> AfterConsumers; 164 for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(), 165 ie = FrontendPluginRegistry::end(); 166 it != ie; ++it) { 167 std::unique_ptr<PluginASTAction> P = it->instantiate(); 168 PluginASTAction::ActionType ActionType = P->getActionType(); 169 if (ActionType == PluginASTAction::Cmdline) { 170 // This is O(|plugins| * |add_plugins|), but since both numbers are 171 // way below 50 in practice, that's ok. 172 for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size(); 173 i != e; ++i) { 174 if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) { 175 ActionType = PluginASTAction::AddAfterMainAction; 176 break; 177 } 178 } 179 } 180 if ((ActionType == PluginASTAction::AddBeforeMainAction || 181 ActionType == PluginASTAction::AddAfterMainAction) && 182 P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs[it->getName()])) { 183 std::unique_ptr<ASTConsumer> PluginConsumer = P->CreateASTConsumer(CI, InFile); 184 if (ActionType == PluginASTAction::AddBeforeMainAction) { 185 Consumers.push_back(std::move(PluginConsumer)); 186 } else { 187 AfterConsumers.push_back(std::move(PluginConsumer)); 188 } 189 } 190 } 191 192 // Add to Consumers the main consumer, then all the plugins that go after it 193 Consumers.push_back(std::move(Consumer)); 194 for (auto &C : AfterConsumers) { 195 Consumers.push_back(std::move(C)); 196 } 197 198 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers)); 199 } 200 201 /// For preprocessed files, if the first line is the linemarker and specifies 202 /// the original source file name, use that name as the input file name. 203 /// Returns the location of the first token after the line marker directive. 204 /// 205 /// \param CI The compiler instance. 206 /// \param InputFile Populated with the filename from the line marker. 207 /// \param IsModuleMap If \c true, add a line note corresponding to this line 208 /// directive. (We need to do this because the directive will not be 209 /// visited by the preprocessor.) 210 static SourceLocation ReadOriginalFileName(CompilerInstance &CI, 211 std::string &InputFile, 212 bool IsModuleMap = false) { 213 auto &SourceMgr = CI.getSourceManager(); 214 auto MainFileID = SourceMgr.getMainFileID(); 215 216 bool Invalid = false; 217 const auto *MainFileBuf = SourceMgr.getBuffer(MainFileID, &Invalid); 218 if (Invalid) 219 return SourceLocation(); 220 221 std::unique_ptr<Lexer> RawLexer( 222 new Lexer(MainFileID, MainFileBuf, SourceMgr, CI.getLangOpts())); 223 224 // If the first line has the syntax of 225 // 226 // # NUM "FILENAME" 227 // 228 // we use FILENAME as the input file name. 229 Token T; 230 if (RawLexer->LexFromRawLexer(T) || T.getKind() != tok::hash) 231 return SourceLocation(); 232 if (RawLexer->LexFromRawLexer(T) || T.isAtStartOfLine() || 233 T.getKind() != tok::numeric_constant) 234 return SourceLocation(); 235 236 unsigned LineNo; 237 SourceLocation LineNoLoc = T.getLocation(); 238 if (IsModuleMap) { 239 llvm::SmallString<16> Buffer; 240 if (Lexer::getSpelling(LineNoLoc, Buffer, SourceMgr, CI.getLangOpts()) 241 .getAsInteger(10, LineNo)) 242 return SourceLocation(); 243 } 244 245 RawLexer->LexFromRawLexer(T); 246 if (T.isAtStartOfLine() || T.getKind() != tok::string_literal) 247 return SourceLocation(); 248 249 StringLiteralParser Literal(T, CI.getPreprocessor()); 250 if (Literal.hadError) 251 return SourceLocation(); 252 RawLexer->LexFromRawLexer(T); 253 if (T.isNot(tok::eof) && !T.isAtStartOfLine()) 254 return SourceLocation(); 255 InputFile = Literal.GetString().str(); 256 257 if (IsModuleMap) 258 CI.getSourceManager().AddLineNote( 259 LineNoLoc, LineNo, SourceMgr.getLineTableFilenameID(InputFile), false, 260 false, SrcMgr::C_User_ModuleMap); 261 262 return T.getLocation(); 263 } 264 265 static SmallVectorImpl<char> & 266 operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) { 267 Includes.append(RHS.begin(), RHS.end()); 268 return Includes; 269 } 270 271 static void addHeaderInclude(StringRef HeaderName, 272 SmallVectorImpl<char> &Includes, 273 const LangOptions &LangOpts, 274 bool IsExternC) { 275 if (IsExternC && LangOpts.CPlusPlus) 276 Includes += "extern \"C\" {\n"; 277 if (LangOpts.ObjC1) 278 Includes += "#import \""; 279 else 280 Includes += "#include \""; 281 282 Includes += HeaderName; 283 284 Includes += "\"\n"; 285 if (IsExternC && LangOpts.CPlusPlus) 286 Includes += "}\n"; 287 } 288 289 /// Collect the set of header includes needed to construct the given 290 /// module and update the TopHeaders file set of the module. 291 /// 292 /// \param Module The module we're collecting includes from. 293 /// 294 /// \param Includes Will be augmented with the set of \#includes or \#imports 295 /// needed to load all of the named headers. 296 static std::error_code collectModuleHeaderIncludes( 297 const LangOptions &LangOpts, FileManager &FileMgr, DiagnosticsEngine &Diag, 298 ModuleMap &ModMap, clang::Module *Module, SmallVectorImpl<char> &Includes) { 299 // Don't collect any headers for unavailable modules. 300 if (!Module->isAvailable()) 301 return std::error_code(); 302 303 // Resolve all lazy header directives to header files. 304 ModMap.resolveHeaderDirectives(Module); 305 306 // If any headers are missing, we can't build this module. In most cases, 307 // diagnostics for this should have already been produced; we only get here 308 // if explicit stat information was provided. 309 // FIXME: If the name resolves to a file with different stat information, 310 // produce a better diagnostic. 311 if (!Module->MissingHeaders.empty()) { 312 auto &MissingHeader = Module->MissingHeaders.front(); 313 Diag.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing) 314 << MissingHeader.IsUmbrella << MissingHeader.FileName; 315 return std::error_code(); 316 } 317 318 // Add includes for each of these headers. 319 for (auto HK : {Module::HK_Normal, Module::HK_Private}) { 320 for (Module::Header &H : Module->Headers[HK]) { 321 Module->addTopHeader(H.Entry); 322 // Use the path as specified in the module map file. We'll look for this 323 // file relative to the module build directory (the directory containing 324 // the module map file) so this will find the same file that we found 325 // while parsing the module map. 326 addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC); 327 } 328 } 329 // Note that Module->PrivateHeaders will not be a TopHeader. 330 331 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) { 332 Module->addTopHeader(UmbrellaHeader.Entry); 333 if (Module->Parent) 334 // Include the umbrella header for submodules. 335 addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts, 336 Module->IsExternC); 337 } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) { 338 // Add all of the headers we find in this subdirectory. 339 std::error_code EC; 340 SmallString<128> DirNative; 341 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative); 342 343 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); 344 for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End; 345 Dir != End && !EC; Dir.increment(EC)) { 346 // Check whether this entry has an extension typically associated with 347 // headers. 348 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName())) 349 .Cases(".h", ".H", ".hh", ".hpp", true) 350 .Default(false)) 351 continue; 352 353 const FileEntry *Header = FileMgr.getFile(Dir->getName()); 354 // FIXME: This shouldn't happen unless there is a file system race. Is 355 // that worth diagnosing? 356 if (!Header) 357 continue; 358 359 // If this header is marked 'unavailable' in this module, don't include 360 // it. 361 if (ModMap.isHeaderUnavailableInModule(Header, Module)) 362 continue; 363 364 // Compute the relative path from the directory to this file. 365 SmallVector<StringRef, 16> Components; 366 auto PathIt = llvm::sys::path::rbegin(Dir->getName()); 367 for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt) 368 Components.push_back(*PathIt); 369 SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten); 370 for (auto It = Components.rbegin(), End = Components.rend(); It != End; 371 ++It) 372 llvm::sys::path::append(RelativeHeader, *It); 373 374 // Include this header as part of the umbrella directory. 375 Module->addTopHeader(Header); 376 addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC); 377 } 378 379 if (EC) 380 return EC; 381 } 382 383 // Recurse into submodules. 384 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(), 385 SubEnd = Module->submodule_end(); 386 Sub != SubEnd; ++Sub) 387 if (std::error_code Err = collectModuleHeaderIncludes( 388 LangOpts, FileMgr, Diag, ModMap, *Sub, Includes)) 389 return Err; 390 391 return std::error_code(); 392 } 393 394 static bool loadModuleMapForModuleBuild(CompilerInstance &CI, bool IsSystem, 395 bool IsPreprocessed, 396 std::string &PresumedModuleMapFile, 397 unsigned &Offset) { 398 auto &SrcMgr = CI.getSourceManager(); 399 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo(); 400 401 // Map the current input to a file. 402 FileID ModuleMapID = SrcMgr.getMainFileID(); 403 const FileEntry *ModuleMap = SrcMgr.getFileEntryForID(ModuleMapID); 404 405 // If the module map is preprocessed, handle the initial line marker; 406 // line directives are not part of the module map syntax in general. 407 Offset = 0; 408 if (IsPreprocessed) { 409 SourceLocation EndOfLineMarker = 410 ReadOriginalFileName(CI, PresumedModuleMapFile, /*IsModuleMap*/ true); 411 if (EndOfLineMarker.isValid()) 412 Offset = CI.getSourceManager().getDecomposedLoc(EndOfLineMarker).second; 413 } 414 415 // Load the module map file. 416 if (HS.loadModuleMapFile(ModuleMap, IsSystem, ModuleMapID, &Offset, 417 PresumedModuleMapFile)) 418 return true; 419 420 if (SrcMgr.getBuffer(ModuleMapID)->getBufferSize() == Offset) 421 Offset = 0; 422 423 return false; 424 } 425 426 static Module *prepareToBuildModule(CompilerInstance &CI, 427 StringRef ModuleMapFilename) { 428 if (CI.getLangOpts().CurrentModule.empty()) { 429 CI.getDiagnostics().Report(diag::err_missing_module_name); 430 431 // FIXME: Eventually, we could consider asking whether there was just 432 // a single module described in the module map, and use that as a 433 // default. Then it would be fairly trivial to just "compile" a module 434 // map with a single module (the common case). 435 return nullptr; 436 } 437 438 // Dig out the module definition. 439 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo(); 440 Module *M = HS.lookupModule(CI.getLangOpts().CurrentModule, 441 /*AllowSearch=*/false); 442 if (!M) { 443 CI.getDiagnostics().Report(diag::err_missing_module) 444 << CI.getLangOpts().CurrentModule << ModuleMapFilename; 445 446 return nullptr; 447 } 448 449 // Check whether we can build this module at all. 450 if (Preprocessor::checkModuleIsAvailable(CI.getLangOpts(), CI.getTarget(), 451 CI.getDiagnostics(), M)) 452 return nullptr; 453 454 // Inform the preprocessor that includes from within the input buffer should 455 // be resolved relative to the build directory of the module map file. 456 CI.getPreprocessor().setMainFileDir(M->Directory); 457 458 // If the module was inferred from a different module map (via an expanded 459 // umbrella module definition), track that fact. 460 // FIXME: It would be preferable to fill this in as part of processing 461 // the module map, rather than adding it after the fact. 462 StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap; 463 if (!OriginalModuleMapName.empty()) { 464 auto *OriginalModuleMap = 465 CI.getFileManager().getFile(OriginalModuleMapName, 466 /*openFile*/ true); 467 if (!OriginalModuleMap) { 468 CI.getDiagnostics().Report(diag::err_module_map_not_found) 469 << OriginalModuleMapName; 470 return nullptr; 471 } 472 if (OriginalModuleMap != CI.getSourceManager().getFileEntryForID( 473 CI.getSourceManager().getMainFileID())) { 474 M->IsInferred = true; 475 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap() 476 .setInferredModuleAllowedBy(M, OriginalModuleMap); 477 } 478 } 479 480 // If we're being run from the command-line, the module build stack will not 481 // have been filled in yet, so complete it now in order to allow us to detect 482 // module cycles. 483 SourceManager &SourceMgr = CI.getSourceManager(); 484 if (SourceMgr.getModuleBuildStack().empty()) 485 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule, 486 FullSourceLoc(SourceLocation(), SourceMgr)); 487 return M; 488 } 489 490 /// Compute the input buffer that should be used to build the specified module. 491 static std::unique_ptr<llvm::MemoryBuffer> 492 getInputBufferForModule(CompilerInstance &CI, Module *M) { 493 FileManager &FileMgr = CI.getFileManager(); 494 495 // Collect the set of #includes we need to build the module. 496 SmallString<256> HeaderContents; 497 std::error_code Err = std::error_code(); 498 if (Module::Header UmbrellaHeader = M->getUmbrellaHeader()) 499 addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents, 500 CI.getLangOpts(), M->IsExternC); 501 Err = collectModuleHeaderIncludes( 502 CI.getLangOpts(), FileMgr, CI.getDiagnostics(), 503 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), M, 504 HeaderContents); 505 506 if (Err) { 507 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes) 508 << M->getFullModuleName() << Err.message(); 509 return nullptr; 510 } 511 512 return llvm::MemoryBuffer::getMemBufferCopy( 513 HeaderContents, Module::getModuleInputBufferName()); 514 } 515 516 bool FrontendAction::BeginSourceFile(CompilerInstance &CI, 517 const FrontendInputFile &RealInput) { 518 FrontendInputFile Input(RealInput); 519 assert(!Instance && "Already processing a source file!"); 520 assert(!Input.isEmpty() && "Unexpected empty filename!"); 521 setCurrentInput(Input); 522 setCompilerInstance(&CI); 523 524 StringRef InputFile = Input.getFile(); 525 bool HasBegunSourceFile = false; 526 bool ReplayASTFile = Input.getKind().getFormat() == InputKind::Precompiled && 527 usesPreprocessorOnly(); 528 if (!BeginInvocation(CI)) 529 goto failure; 530 531 // If we're replaying the build of an AST file, import it and set up 532 // the initial state from its build. 533 if (ReplayASTFile) { 534 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics()); 535 536 // The AST unit populates its own diagnostics engine rather than ours. 537 IntrusiveRefCntPtr<DiagnosticsEngine> ASTDiags( 538 new DiagnosticsEngine(Diags->getDiagnosticIDs(), 539 &Diags->getDiagnosticOptions())); 540 ASTDiags->setClient(Diags->getClient(), /*OwnsClient*/false); 541 542 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile( 543 InputFile, CI.getPCHContainerReader(), ASTUnit::LoadPreprocessorOnly, 544 ASTDiags, CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs); 545 if (!AST) 546 goto failure; 547 548 // Options relating to how we treat the input (but not what we do with it) 549 // are inherited from the AST unit. 550 CI.getHeaderSearchOpts() = AST->getHeaderSearchOpts(); 551 CI.getPreprocessorOpts() = AST->getPreprocessorOpts(); 552 CI.getLangOpts() = AST->getLangOpts(); 553 554 // Set the shared objects, these are reset when we finish processing the 555 // file, otherwise the CompilerInstance will happily destroy them. 556 CI.setFileManager(&AST->getFileManager()); 557 CI.createSourceManager(CI.getFileManager()); 558 CI.getSourceManager().initializeForReplay(AST->getSourceManager()); 559 560 // Preload all the module files loaded transitively by the AST unit. Also 561 // load all module map files that were parsed as part of building the AST 562 // unit. 563 if (auto ASTReader = AST->getASTReader()) { 564 auto &MM = ASTReader->getModuleManager(); 565 auto &PrimaryModule = MM.getPrimaryModule(); 566 567 for (ModuleFile &MF : MM) 568 if (&MF != &PrimaryModule) 569 CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName); 570 571 ASTReader->visitTopLevelModuleMaps(PrimaryModule, 572 [&](const FileEntry *FE) { 573 CI.getFrontendOpts().ModuleMapFiles.push_back(FE->getName()); 574 }); 575 } 576 577 // Set up the input file for replay purposes. 578 auto Kind = AST->getInputKind(); 579 if (Kind.getFormat() == InputKind::ModuleMap) { 580 Module *ASTModule = 581 AST->getPreprocessor().getHeaderSearchInfo().lookupModule( 582 AST->getLangOpts().CurrentModule, /*AllowSearch*/ false); 583 assert(ASTModule && "module file does not define its own module"); 584 Input = FrontendInputFile(ASTModule->PresumedModuleMapFile, Kind); 585 } else { 586 auto &SM = CI.getSourceManager(); 587 FileID ID = SM.getMainFileID(); 588 if (auto *File = SM.getFileEntryForID(ID)) 589 Input = FrontendInputFile(File->getName(), Kind); 590 else 591 Input = FrontendInputFile(SM.getBuffer(ID), Kind); 592 } 593 setCurrentInput(Input, std::move(AST)); 594 } 595 596 // AST files follow a very different path, since they share objects via the 597 // AST unit. 598 if (Input.getKind().getFormat() == InputKind::Precompiled) { 599 assert(!usesPreprocessorOnly() && "this case was handled above"); 600 assert(hasASTFileSupport() && 601 "This action does not have AST file support!"); 602 603 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics()); 604 605 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile( 606 InputFile, CI.getPCHContainerReader(), ASTUnit::LoadEverything, Diags, 607 CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs); 608 609 if (!AST) 610 goto failure; 611 612 // Inform the diagnostic client we are processing a source file. 613 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr); 614 HasBegunSourceFile = true; 615 616 // Set the shared objects, these are reset when we finish processing the 617 // file, otherwise the CompilerInstance will happily destroy them. 618 CI.setFileManager(&AST->getFileManager()); 619 CI.setSourceManager(&AST->getSourceManager()); 620 CI.setPreprocessor(AST->getPreprocessorPtr()); 621 Preprocessor &PP = CI.getPreprocessor(); 622 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(), 623 PP.getLangOpts()); 624 CI.setASTContext(&AST->getASTContext()); 625 626 setCurrentInput(Input, std::move(AST)); 627 628 // Initialize the action. 629 if (!BeginSourceFileAction(CI)) 630 goto failure; 631 632 // Create the AST consumer. 633 CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile)); 634 if (!CI.hasASTConsumer()) 635 goto failure; 636 637 return true; 638 } 639 640 // Set up the file and source managers, if needed. 641 if (!CI.hasFileManager()) { 642 if (!CI.createFileManager()) { 643 goto failure; 644 } 645 } 646 if (!CI.hasSourceManager()) 647 CI.createSourceManager(CI.getFileManager()); 648 649 // Set up embedding for any specified files. Do this before we load any 650 // source files, including the primary module map for the compilation. 651 for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) { 652 if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true)) 653 CI.getSourceManager().setFileIsTransient(FE); 654 else 655 CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F; 656 } 657 if (CI.getFrontendOpts().ModulesEmbedAllFiles) 658 CI.getSourceManager().setAllFilesAreTransient(true); 659 660 // IR files bypass the rest of initialization. 661 if (Input.getKind().getLanguage() == InputKind::LLVM_IR) { 662 assert(hasIRSupport() && 663 "This action does not have IR file support!"); 664 665 // Inform the diagnostic client we are processing a source file. 666 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr); 667 HasBegunSourceFile = true; 668 669 // Initialize the action. 670 if (!BeginSourceFileAction(CI)) 671 goto failure; 672 673 // Initialize the main file entry. 674 if (!CI.InitializeSourceManager(CurrentInput)) 675 goto failure; 676 677 return true; 678 } 679 680 // If the implicit PCH include is actually a directory, rather than 681 // a single file, search for a suitable PCH file in that directory. 682 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) { 683 FileManager &FileMgr = CI.getFileManager(); 684 PreprocessorOptions &PPOpts = CI.getPreprocessorOpts(); 685 StringRef PCHInclude = PPOpts.ImplicitPCHInclude; 686 std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath(); 687 if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) { 688 std::error_code EC; 689 SmallString<128> DirNative; 690 llvm::sys::path::native(PCHDir->getName(), DirNative); 691 bool Found = false; 692 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); 693 for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd; 694 Dir != DirEnd && !EC; Dir.increment(EC)) { 695 // Check whether this is an acceptable AST file. 696 if (ASTReader::isAcceptableASTFile( 697 Dir->getName(), FileMgr, CI.getPCHContainerReader(), 698 CI.getLangOpts(), CI.getTargetOpts(), CI.getPreprocessorOpts(), 699 SpecificModuleCachePath)) { 700 PPOpts.ImplicitPCHInclude = Dir->getName(); 701 Found = true; 702 break; 703 } 704 } 705 706 if (!Found) { 707 CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude; 708 goto failure; 709 } 710 } 711 } 712 713 // Set up the preprocessor if needed. When parsing model files the 714 // preprocessor of the original source is reused. 715 if (!isModelParsingAction()) 716 CI.createPreprocessor(getTranslationUnitKind()); 717 718 // Inform the diagnostic client we are processing a source file. 719 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 720 &CI.getPreprocessor()); 721 HasBegunSourceFile = true; 722 723 // Initialize the main file entry. 724 if (!CI.InitializeSourceManager(Input)) 725 goto failure; 726 727 // For module map files, we first parse the module map and synthesize a 728 // "<module-includes>" buffer before more conventional processing. 729 if (Input.getKind().getFormat() == InputKind::ModuleMap) { 730 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap); 731 732 std::string PresumedModuleMapFile; 733 unsigned OffsetToContents; 734 if (loadModuleMapForModuleBuild(CI, Input.isSystem(), 735 Input.isPreprocessed(), 736 PresumedModuleMapFile, OffsetToContents)) 737 goto failure; 738 739 auto *CurrentModule = prepareToBuildModule(CI, Input.getFile()); 740 if (!CurrentModule) 741 goto failure; 742 743 CurrentModule->PresumedModuleMapFile = PresumedModuleMapFile; 744 745 if (OffsetToContents) 746 // If the module contents are in the same file, skip to them. 747 CI.getPreprocessor().setSkipMainFilePreamble(OffsetToContents, true); 748 else { 749 // Otherwise, convert the module description to a suitable input buffer. 750 auto Buffer = getInputBufferForModule(CI, CurrentModule); 751 if (!Buffer) 752 goto failure; 753 754 // Reinitialize the main file entry to refer to the new input. 755 auto Kind = CurrentModule->IsSystem ? SrcMgr::C_System : SrcMgr::C_User; 756 auto &SourceMgr = CI.getSourceManager(); 757 auto BufferID = SourceMgr.createFileID(std::move(Buffer), Kind); 758 assert(BufferID.isValid() && "couldn't creaate module buffer ID"); 759 SourceMgr.setMainFileID(BufferID); 760 } 761 } 762 763 // Initialize the action. 764 if (!BeginSourceFileAction(CI)) 765 goto failure; 766 767 // Create the AST context and consumer unless this is a preprocessor only 768 // action. 769 if (!usesPreprocessorOnly()) { 770 // Parsing a model file should reuse the existing ASTContext. 771 if (!isModelParsingAction()) 772 CI.createASTContext(); 773 774 // For preprocessed files, check if the first line specifies the original 775 // source file name with a linemarker. 776 std::string PresumedInputFile = InputFile; 777 if (Input.isPreprocessed()) 778 ReadOriginalFileName(CI, PresumedInputFile); 779 780 std::unique_ptr<ASTConsumer> Consumer = 781 CreateWrappedASTConsumer(CI, PresumedInputFile); 782 if (!Consumer) 783 goto failure; 784 785 // FIXME: should not overwrite ASTMutationListener when parsing model files? 786 if (!isModelParsingAction()) 787 CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener()); 788 789 if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) { 790 // Convert headers to PCH and chain them. 791 IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader; 792 source = createChainedIncludesSource(CI, FinalReader); 793 if (!source) 794 goto failure; 795 CI.setModuleManager(static_cast<ASTReader *>(FinalReader.get())); 796 CI.getASTContext().setExternalSource(source); 797 } else if (CI.getLangOpts().Modules || 798 !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) { 799 // Use PCM or PCH. 800 assert(hasPCHSupport() && "This action does not have PCH support!"); 801 ASTDeserializationListener *DeserialListener = 802 Consumer->GetASTDeserializationListener(); 803 bool DeleteDeserialListener = false; 804 if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls) { 805 DeserialListener = new DeserializedDeclsDumper(DeserialListener, 806 DeleteDeserialListener); 807 DeleteDeserialListener = true; 808 } 809 if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty()) { 810 DeserialListener = new DeserializedDeclsChecker( 811 CI.getASTContext(), 812 CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn, 813 DeserialListener, DeleteDeserialListener); 814 DeleteDeserialListener = true; 815 } 816 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) { 817 CI.createPCHExternalASTSource( 818 CI.getPreprocessorOpts().ImplicitPCHInclude, 819 CI.getPreprocessorOpts().DisablePCHValidation, 820 CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, DeserialListener, 821 DeleteDeserialListener); 822 if (!CI.getASTContext().getExternalSource()) 823 goto failure; 824 } 825 // If modules are enabled, create the module manager before creating 826 // any builtins, so that all declarations know that they might be 827 // extended by an external source. 828 if (CI.getLangOpts().Modules || !CI.hasASTContext() || 829 !CI.getASTContext().getExternalSource()) { 830 CI.createModuleManager(); 831 CI.getModuleManager()->setDeserializationListener(DeserialListener, 832 DeleteDeserialListener); 833 } 834 } 835 836 CI.setASTConsumer(std::move(Consumer)); 837 if (!CI.hasASTConsumer()) 838 goto failure; 839 } 840 841 // Initialize built-in info as long as we aren't using an external AST 842 // source. 843 if (CI.getLangOpts().Modules || !CI.hasASTContext() || 844 !CI.getASTContext().getExternalSource()) { 845 Preprocessor &PP = CI.getPreprocessor(); 846 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(), 847 PP.getLangOpts()); 848 } else { 849 // FIXME: If this is a problem, recover from it by creating a multiplex 850 // source. 851 assert((!CI.getLangOpts().Modules || CI.getModuleManager()) && 852 "modules enabled but created an external source that " 853 "doesn't support modules"); 854 } 855 856 // If we were asked to load any module map files, do so now. 857 for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) { 858 if (auto *File = CI.getFileManager().getFile(Filename)) 859 CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile( 860 File, /*IsSystem*/false); 861 else 862 CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename; 863 } 864 865 // Add a module declaration scope so that modules from -fmodule-map-file 866 // arguments may shadow modules found implicitly in search paths. 867 CI.getPreprocessor() 868 .getHeaderSearchInfo() 869 .getModuleMap() 870 .finishModuleDeclarationScope(); 871 872 // If we were asked to load any module files, do so now. 873 for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles) 874 if (!CI.loadModuleFile(ModuleFile)) 875 goto failure; 876 877 // If there is a layout overrides file, attach an external AST source that 878 // provides the layouts from that file. 879 if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() && 880 CI.hasASTContext() && !CI.getASTContext().getExternalSource()) { 881 IntrusiveRefCntPtr<ExternalASTSource> 882 Override(new LayoutOverrideSource( 883 CI.getFrontendOpts().OverrideRecordLayoutsFile)); 884 CI.getASTContext().setExternalSource(Override); 885 } 886 887 return true; 888 889 // If we failed, reset state since the client will not end up calling the 890 // matching EndSourceFile(). 891 failure: 892 if (HasBegunSourceFile) 893 CI.getDiagnosticClient().EndSourceFile(); 894 CI.clearOutputFiles(/*EraseFiles=*/true); 895 CI.getLangOpts().setCompilingModule(LangOptions::CMK_None); 896 setCurrentInput(FrontendInputFile()); 897 setCompilerInstance(nullptr); 898 return false; 899 } 900 901 bool FrontendAction::Execute() { 902 CompilerInstance &CI = getCompilerInstance(); 903 904 if (CI.hasFrontendTimer()) { 905 llvm::TimeRegion Timer(CI.getFrontendTimer()); 906 ExecuteAction(); 907 } 908 else ExecuteAction(); 909 910 // If we are supposed to rebuild the global module index, do so now unless 911 // there were any module-build failures. 912 if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() && 913 CI.hasPreprocessor()) { 914 StringRef Cache = 915 CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath(); 916 if (!Cache.empty()) 917 GlobalModuleIndex::writeIndex(CI.getFileManager(), 918 CI.getPCHContainerReader(), Cache); 919 } 920 921 return true; 922 } 923 924 void FrontendAction::EndSourceFile() { 925 CompilerInstance &CI = getCompilerInstance(); 926 927 // Inform the diagnostic client we are done with this source file. 928 CI.getDiagnosticClient().EndSourceFile(); 929 930 // Inform the preprocessor we are done. 931 if (CI.hasPreprocessor()) 932 CI.getPreprocessor().EndSourceFile(); 933 934 // Finalize the action. 935 EndSourceFileAction(); 936 937 // Sema references the ast consumer, so reset sema first. 938 // 939 // FIXME: There is more per-file stuff we could just drop here? 940 bool DisableFree = CI.getFrontendOpts().DisableFree; 941 if (DisableFree) { 942 CI.resetAndLeakSema(); 943 CI.resetAndLeakASTContext(); 944 BuryPointer(CI.takeASTConsumer().get()); 945 } else { 946 CI.setSema(nullptr); 947 CI.setASTContext(nullptr); 948 CI.setASTConsumer(nullptr); 949 } 950 951 if (CI.getFrontendOpts().ShowStats) { 952 llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n"; 953 CI.getPreprocessor().PrintStats(); 954 CI.getPreprocessor().getIdentifierTable().PrintStats(); 955 CI.getPreprocessor().getHeaderSearchInfo().PrintStats(); 956 CI.getSourceManager().PrintStats(); 957 llvm::errs() << "\n"; 958 } 959 960 // Cleanup the output streams, and erase the output files if instructed by the 961 // FrontendAction. 962 CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles()); 963 964 if (isCurrentFileAST()) { 965 if (DisableFree) { 966 CI.resetAndLeakPreprocessor(); 967 CI.resetAndLeakSourceManager(); 968 CI.resetAndLeakFileManager(); 969 BuryPointer(CurrentASTUnit.release()); 970 } else { 971 CI.setPreprocessor(nullptr); 972 CI.setSourceManager(nullptr); 973 CI.setFileManager(nullptr); 974 } 975 } 976 977 setCompilerInstance(nullptr); 978 setCurrentInput(FrontendInputFile()); 979 CI.getLangOpts().setCompilingModule(LangOptions::CMK_None); 980 } 981 982 bool FrontendAction::shouldEraseOutputFiles() { 983 return getCompilerInstance().getDiagnostics().hasErrorOccurred(); 984 } 985 986 //===----------------------------------------------------------------------===// 987 // Utility Actions 988 //===----------------------------------------------------------------------===// 989 990 void ASTFrontendAction::ExecuteAction() { 991 CompilerInstance &CI = getCompilerInstance(); 992 if (!CI.hasPreprocessor()) 993 return; 994 995 // FIXME: Move the truncation aspect of this into Sema, we delayed this till 996 // here so the source manager would be initialized. 997 if (hasCodeCompletionSupport() && 998 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty()) 999 CI.createCodeCompletionConsumer(); 1000 1001 // Use a code completion consumer? 1002 CodeCompleteConsumer *CompletionConsumer = nullptr; 1003 if (CI.hasCodeCompletionConsumer()) 1004 CompletionConsumer = &CI.getCodeCompletionConsumer(); 1005 1006 if (!CI.hasSema()) 1007 CI.createSema(getTranslationUnitKind(), CompletionConsumer); 1008 1009 ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats, 1010 CI.getFrontendOpts().SkipFunctionBodies); 1011 } 1012 1013 void PluginASTAction::anchor() { } 1014 1015 std::unique_ptr<ASTConsumer> 1016 PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI, 1017 StringRef InFile) { 1018 llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!"); 1019 } 1020 1021 std::unique_ptr<ASTConsumer> 1022 WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI, 1023 StringRef InFile) { 1024 return WrappedAction->CreateASTConsumer(CI, InFile); 1025 } 1026 bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) { 1027 return WrappedAction->BeginInvocation(CI); 1028 } 1029 bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI) { 1030 WrappedAction->setCurrentInput(getCurrentInput()); 1031 WrappedAction->setCompilerInstance(&CI); 1032 auto Ret = WrappedAction->BeginSourceFileAction(CI); 1033 // BeginSourceFileAction may change CurrentInput, e.g. during module builds. 1034 setCurrentInput(WrappedAction->getCurrentInput()); 1035 return Ret; 1036 } 1037 void WrapperFrontendAction::ExecuteAction() { 1038 WrappedAction->ExecuteAction(); 1039 } 1040 void WrapperFrontendAction::EndSourceFileAction() { 1041 WrappedAction->EndSourceFileAction(); 1042 } 1043 1044 bool WrapperFrontendAction::usesPreprocessorOnly() const { 1045 return WrappedAction->usesPreprocessorOnly(); 1046 } 1047 TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() { 1048 return WrappedAction->getTranslationUnitKind(); 1049 } 1050 bool WrapperFrontendAction::hasPCHSupport() const { 1051 return WrappedAction->hasPCHSupport(); 1052 } 1053 bool WrapperFrontendAction::hasASTFileSupport() const { 1054 return WrappedAction->hasASTFileSupport(); 1055 } 1056 bool WrapperFrontendAction::hasIRSupport() const { 1057 return WrappedAction->hasIRSupport(); 1058 } 1059 bool WrapperFrontendAction::hasCodeCompletionSupport() const { 1060 return WrappedAction->hasCodeCompletionSupport(); 1061 } 1062 1063 WrapperFrontendAction::WrapperFrontendAction( 1064 std::unique_ptr<FrontendAction> WrappedAction) 1065 : WrappedAction(std::move(WrappedAction)) {} 1066 1067