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