1 //===--- FrontendActions.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/FrontendActions.h" 10 #include "clang/AST/ASTConsumer.h" 11 #include "clang/AST/Decl.h" 12 #include "clang/Basic/FileManager.h" 13 #include "clang/Basic/LangStandard.h" 14 #include "clang/Basic/Module.h" 15 #include "clang/Basic/TargetInfo.h" 16 #include "clang/Frontend/ASTConsumers.h" 17 #include "clang/Frontend/CompilerInstance.h" 18 #include "clang/Frontend/FrontendDiagnostic.h" 19 #include "clang/Frontend/MultiplexConsumer.h" 20 #include "clang/Frontend/Utils.h" 21 #include "clang/Lex/DependencyDirectivesSourceMinimizer.h" 22 #include "clang/Lex/HeaderSearch.h" 23 #include "clang/Lex/Preprocessor.h" 24 #include "clang/Lex/PreprocessorOptions.h" 25 #include "clang/Sema/TemplateInstCallback.h" 26 #include "clang/Serialization/ASTReader.h" 27 #include "clang/Serialization/ASTWriter.h" 28 #include "clang/Serialization/ModuleFile.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/FileSystem.h" 31 #include "llvm/Support/MemoryBuffer.h" 32 #include "llvm/Support/Path.h" 33 #include "llvm/Support/YAMLTraits.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include <memory> 36 #include <system_error> 37 38 using namespace clang; 39 40 namespace { 41 CodeCompleteConsumer *GetCodeCompletionConsumer(CompilerInstance &CI) { 42 return CI.hasCodeCompletionConsumer() ? &CI.getCodeCompletionConsumer() 43 : nullptr; 44 } 45 46 void EnsureSemaIsCreated(CompilerInstance &CI, FrontendAction &Action) { 47 if (Action.hasCodeCompletionSupport() && 48 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty()) 49 CI.createCodeCompletionConsumer(); 50 51 if (!CI.hasSema()) 52 CI.createSema(Action.getTranslationUnitKind(), 53 GetCodeCompletionConsumer(CI)); 54 } 55 } // namespace 56 57 //===----------------------------------------------------------------------===// 58 // Custom Actions 59 //===----------------------------------------------------------------------===// 60 61 std::unique_ptr<ASTConsumer> 62 InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 63 return std::make_unique<ASTConsumer>(); 64 } 65 66 void InitOnlyAction::ExecuteAction() { 67 } 68 69 // Basically PreprocessOnlyAction::ExecuteAction. 70 void ReadPCHAndPreprocessAction::ExecuteAction() { 71 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 72 73 // Ignore unknown pragmas. 74 PP.IgnorePragmas(); 75 76 Token Tok; 77 // Start parsing the specified input file. 78 PP.EnterMainSourceFile(); 79 do { 80 PP.Lex(Tok); 81 } while (Tok.isNot(tok::eof)); 82 } 83 84 std::unique_ptr<ASTConsumer> 85 ReadPCHAndPreprocessAction::CreateASTConsumer(CompilerInstance &CI, 86 StringRef InFile) { 87 return std::make_unique<ASTConsumer>(); 88 } 89 90 //===----------------------------------------------------------------------===// 91 // AST Consumer Actions 92 //===----------------------------------------------------------------------===// 93 94 std::unique_ptr<ASTConsumer> 95 ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 96 if (std::unique_ptr<raw_ostream> OS = 97 CI.createDefaultOutputFile(false, InFile)) 98 return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter); 99 return nullptr; 100 } 101 102 std::unique_ptr<ASTConsumer> 103 ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 104 const FrontendOptions &Opts = CI.getFrontendOpts(); 105 return CreateASTDumper(nullptr /*Dump to stdout.*/, Opts.ASTDumpFilter, 106 Opts.ASTDumpDecls, Opts.ASTDumpAll, 107 Opts.ASTDumpLookups, Opts.ASTDumpDeclTypes, 108 Opts.ASTDumpFormat); 109 } 110 111 std::unique_ptr<ASTConsumer> 112 ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 113 return CreateASTDeclNodeLister(); 114 } 115 116 std::unique_ptr<ASTConsumer> 117 ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 118 return CreateASTViewer(); 119 } 120 121 std::unique_ptr<ASTConsumer> 122 GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 123 std::string Sysroot; 124 if (!ComputeASTConsumerArguments(CI, /*ref*/ Sysroot)) 125 return nullptr; 126 127 std::string OutputFile; 128 std::unique_ptr<raw_pwrite_stream> OS = 129 CreateOutputFile(CI, InFile, /*ref*/ OutputFile); 130 if (!OS) 131 return nullptr; 132 133 if (!CI.getFrontendOpts().RelocatablePCH) 134 Sysroot.clear(); 135 136 const auto &FrontendOpts = CI.getFrontendOpts(); 137 auto Buffer = std::make_shared<PCHBuffer>(); 138 std::vector<std::unique_ptr<ASTConsumer>> Consumers; 139 Consumers.push_back(std::make_unique<PCHGenerator>( 140 CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer, 141 FrontendOpts.ModuleFileExtensions, 142 CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, 143 FrontendOpts.IncludeTimestamps, +CI.getLangOpts().CacheGeneratedPCH)); 144 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator( 145 CI, std::string(InFile), OutputFile, std::move(OS), Buffer)); 146 147 return std::make_unique<MultiplexConsumer>(std::move(Consumers)); 148 } 149 150 bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI, 151 std::string &Sysroot) { 152 Sysroot = CI.getHeaderSearchOpts().Sysroot; 153 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) { 154 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot); 155 return false; 156 } 157 158 return true; 159 } 160 161 std::unique_ptr<llvm::raw_pwrite_stream> 162 GeneratePCHAction::CreateOutputFile(CompilerInstance &CI, StringRef InFile, 163 std::string &OutputFile) { 164 // Because this is exposed via libclang we must disable RemoveFileOnSignal. 165 std::unique_ptr<raw_pwrite_stream> OS = CI.createDefaultOutputFile( 166 /*Binary=*/true, InFile, /*Extension=*/"", /*RemoveFileOnSignal=*/false); 167 if (!OS) 168 return nullptr; 169 170 OutputFile = CI.getFrontendOpts().OutputFile; 171 return OS; 172 } 173 174 bool GeneratePCHAction::shouldEraseOutputFiles() { 175 if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors) 176 return false; 177 return ASTFrontendAction::shouldEraseOutputFiles(); 178 } 179 180 bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI) { 181 CI.getLangOpts().CompilingPCH = true; 182 return true; 183 } 184 185 std::unique_ptr<ASTConsumer> 186 GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI, 187 StringRef InFile) { 188 std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile); 189 if (!OS) 190 return nullptr; 191 192 std::string OutputFile = CI.getFrontendOpts().OutputFile; 193 std::string Sysroot; 194 195 auto Buffer = std::make_shared<PCHBuffer>(); 196 std::vector<std::unique_ptr<ASTConsumer>> Consumers; 197 198 Consumers.push_back(std::make_unique<PCHGenerator>( 199 CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer, 200 CI.getFrontendOpts().ModuleFileExtensions, 201 /*AllowASTWithErrors=*/ 202 +CI.getFrontendOpts().AllowPCMWithCompilerErrors, 203 /*IncludeTimestamps=*/ 204 +CI.getFrontendOpts().BuildingImplicitModule, 205 /*ShouldCacheASTInMemory=*/ 206 +CI.getFrontendOpts().BuildingImplicitModule)); 207 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator( 208 CI, std::string(InFile), OutputFile, std::move(OS), Buffer)); 209 return std::make_unique<MultiplexConsumer>(std::move(Consumers)); 210 } 211 212 bool GenerateModuleAction::shouldEraseOutputFiles() { 213 return !getCompilerInstance().getFrontendOpts().AllowPCMWithCompilerErrors && 214 ASTFrontendAction::shouldEraseOutputFiles(); 215 } 216 217 bool GenerateModuleFromModuleMapAction::BeginSourceFileAction( 218 CompilerInstance &CI) { 219 if (!CI.getLangOpts().Modules) { 220 CI.getDiagnostics().Report(diag::err_module_build_requires_fmodules); 221 return false; 222 } 223 224 return GenerateModuleAction::BeginSourceFileAction(CI); 225 } 226 227 std::unique_ptr<raw_pwrite_stream> 228 GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI, 229 StringRef InFile) { 230 // If no output file was provided, figure out where this module would go 231 // in the module cache. 232 if (CI.getFrontendOpts().OutputFile.empty()) { 233 StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap; 234 if (ModuleMapFile.empty()) 235 ModuleMapFile = InFile; 236 237 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo(); 238 CI.getFrontendOpts().OutputFile = 239 HS.getCachedModuleFileName(CI.getLangOpts().CurrentModule, 240 ModuleMapFile); 241 } 242 243 // Because this is exposed via libclang we must disable RemoveFileOnSignal. 244 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, /*Extension=*/"", 245 /*RemoveFileOnSignal=*/false, 246 /*CreateMissingDirectories=*/true, 247 /*ForceUseTemporary=*/true); 248 } 249 250 bool GenerateModuleInterfaceAction::BeginSourceFileAction( 251 CompilerInstance &CI) { 252 if (!CI.getLangOpts().ModulesTS && !CI.getLangOpts().CPlusPlusModules) { 253 CI.getDiagnostics().Report(diag::err_module_interface_requires_cpp_modules); 254 return false; 255 } 256 257 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface); 258 259 return GenerateModuleAction::BeginSourceFileAction(CI); 260 } 261 262 std::unique_ptr<raw_pwrite_stream> 263 GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI, 264 StringRef InFile) { 265 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm"); 266 } 267 268 bool GenerateHeaderModuleAction::PrepareToExecuteAction( 269 CompilerInstance &CI) { 270 if (!CI.getLangOpts().Modules) { 271 CI.getDiagnostics().Report(diag::err_header_module_requires_modules); 272 return false; 273 } 274 275 auto &Inputs = CI.getFrontendOpts().Inputs; 276 if (Inputs.empty()) 277 return GenerateModuleAction::BeginInvocation(CI); 278 279 auto Kind = Inputs[0].getKind(); 280 281 // Convert the header file inputs into a single module input buffer. 282 SmallString<256> HeaderContents; 283 ModuleHeaders.reserve(Inputs.size()); 284 for (const FrontendInputFile &FIF : Inputs) { 285 // FIXME: We should support re-compiling from an AST file. 286 if (FIF.getKind().getFormat() != InputKind::Source || !FIF.isFile()) { 287 CI.getDiagnostics().Report(diag::err_module_header_file_not_found) 288 << (FIF.isFile() ? FIF.getFile() 289 : FIF.getBuffer().getBufferIdentifier()); 290 return true; 291 } 292 293 HeaderContents += "#include \""; 294 HeaderContents += FIF.getFile(); 295 HeaderContents += "\"\n"; 296 ModuleHeaders.push_back(std::string(FIF.getFile())); 297 } 298 Buffer = llvm::MemoryBuffer::getMemBufferCopy( 299 HeaderContents, Module::getModuleInputBufferName()); 300 301 // Set that buffer up as our "real" input. 302 Inputs.clear(); 303 Inputs.push_back( 304 FrontendInputFile(Buffer->getMemBufferRef(), Kind, /*IsSystem*/ false)); 305 306 return GenerateModuleAction::PrepareToExecuteAction(CI); 307 } 308 309 bool GenerateHeaderModuleAction::BeginSourceFileAction( 310 CompilerInstance &CI) { 311 CI.getLangOpts().setCompilingModule(LangOptions::CMK_HeaderModule); 312 313 // Synthesize a Module object for the given headers. 314 auto &HS = CI.getPreprocessor().getHeaderSearchInfo(); 315 SmallVector<Module::Header, 16> Headers; 316 for (StringRef Name : ModuleHeaders) { 317 Optional<FileEntryRef> FE = HS.LookupFile( 318 Name, SourceLocation(), /*Angled*/ false, nullptr, nullptr, None, 319 nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); 320 if (!FE) { 321 CI.getDiagnostics().Report(diag::err_module_header_file_not_found) 322 << Name; 323 continue; 324 } 325 Headers.push_back( 326 {std::string(Name), std::string(Name), &FE->getFileEntry()}); 327 } 328 HS.getModuleMap().createHeaderModule(CI.getLangOpts().CurrentModule, Headers); 329 330 return GenerateModuleAction::BeginSourceFileAction(CI); 331 } 332 333 std::unique_ptr<raw_pwrite_stream> 334 GenerateHeaderModuleAction::CreateOutputFile(CompilerInstance &CI, 335 StringRef InFile) { 336 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm"); 337 } 338 339 SyntaxOnlyAction::~SyntaxOnlyAction() { 340 } 341 342 std::unique_ptr<ASTConsumer> 343 SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 344 return std::make_unique<ASTConsumer>(); 345 } 346 347 std::unique_ptr<ASTConsumer> 348 DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI, 349 StringRef InFile) { 350 return std::make_unique<ASTConsumer>(); 351 } 352 353 std::unique_ptr<ASTConsumer> 354 VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 355 return std::make_unique<ASTConsumer>(); 356 } 357 358 void VerifyPCHAction::ExecuteAction() { 359 CompilerInstance &CI = getCompilerInstance(); 360 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; 361 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot; 362 std::unique_ptr<ASTReader> Reader(new ASTReader( 363 CI.getPreprocessor(), CI.getModuleCache(), &CI.getASTContext(), 364 CI.getPCHContainerReader(), CI.getFrontendOpts().ModuleFileExtensions, 365 Sysroot.empty() ? "" : Sysroot.c_str(), 366 DisableValidationForModuleKind::None, 367 /*AllowASTWithCompilerErrors*/ false, 368 /*AllowConfigurationMismatch*/ true, 369 /*ValidateSystemInputs*/ true)); 370 371 Reader->ReadAST(getCurrentFile(), 372 Preamble ? serialization::MK_Preamble 373 : serialization::MK_PCH, 374 SourceLocation(), 375 ASTReader::ARR_ConfigurationMismatch); 376 } 377 378 namespace { 379 struct TemplightEntry { 380 std::string Name; 381 std::string Kind; 382 std::string Event; 383 std::string DefinitionLocation; 384 std::string PointOfInstantiation; 385 }; 386 } // namespace 387 388 namespace llvm { 389 namespace yaml { 390 template <> struct MappingTraits<TemplightEntry> { 391 static void mapping(IO &io, TemplightEntry &fields) { 392 io.mapRequired("name", fields.Name); 393 io.mapRequired("kind", fields.Kind); 394 io.mapRequired("event", fields.Event); 395 io.mapRequired("orig", fields.DefinitionLocation); 396 io.mapRequired("poi", fields.PointOfInstantiation); 397 } 398 }; 399 } // namespace yaml 400 } // namespace llvm 401 402 namespace { 403 class DefaultTemplateInstCallback : public TemplateInstantiationCallback { 404 using CodeSynthesisContext = Sema::CodeSynthesisContext; 405 406 public: 407 void initialize(const Sema &) override {} 408 409 void finalize(const Sema &) override {} 410 411 void atTemplateBegin(const Sema &TheSema, 412 const CodeSynthesisContext &Inst) override { 413 displayTemplightEntry<true>(llvm::outs(), TheSema, Inst); 414 } 415 416 void atTemplateEnd(const Sema &TheSema, 417 const CodeSynthesisContext &Inst) override { 418 displayTemplightEntry<false>(llvm::outs(), TheSema, Inst); 419 } 420 421 private: 422 static std::string toString(CodeSynthesisContext::SynthesisKind Kind) { 423 switch (Kind) { 424 case CodeSynthesisContext::TemplateInstantiation: 425 return "TemplateInstantiation"; 426 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: 427 return "DefaultTemplateArgumentInstantiation"; 428 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: 429 return "DefaultFunctionArgumentInstantiation"; 430 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: 431 return "ExplicitTemplateArgumentSubstitution"; 432 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: 433 return "DeducedTemplateArgumentSubstitution"; 434 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: 435 return "PriorTemplateArgumentSubstitution"; 436 case CodeSynthesisContext::DefaultTemplateArgumentChecking: 437 return "DefaultTemplateArgumentChecking"; 438 case CodeSynthesisContext::ExceptionSpecEvaluation: 439 return "ExceptionSpecEvaluation"; 440 case CodeSynthesisContext::ExceptionSpecInstantiation: 441 return "ExceptionSpecInstantiation"; 442 case CodeSynthesisContext::DeclaringSpecialMember: 443 return "DeclaringSpecialMember"; 444 case CodeSynthesisContext::DeclaringImplicitEqualityComparison: 445 return "DeclaringImplicitEqualityComparison"; 446 case CodeSynthesisContext::DefiningSynthesizedFunction: 447 return "DefiningSynthesizedFunction"; 448 case CodeSynthesisContext::RewritingOperatorAsSpaceship: 449 return "RewritingOperatorAsSpaceship"; 450 case CodeSynthesisContext::Memoization: 451 return "Memoization"; 452 case CodeSynthesisContext::ConstraintsCheck: 453 return "ConstraintsCheck"; 454 case CodeSynthesisContext::ConstraintSubstitution: 455 return "ConstraintSubstitution"; 456 case CodeSynthesisContext::ConstraintNormalization: 457 return "ConstraintNormalization"; 458 case CodeSynthesisContext::ParameterMappingSubstitution: 459 return "ParameterMappingSubstitution"; 460 case CodeSynthesisContext::RequirementInstantiation: 461 return "RequirementInstantiation"; 462 case CodeSynthesisContext::NestedRequirementConstraintsCheck: 463 return "NestedRequirementConstraintsCheck"; 464 case CodeSynthesisContext::InitializingStructuredBinding: 465 return "InitializingStructuredBinding"; 466 case CodeSynthesisContext::MarkingClassDllexported: 467 return "MarkingClassDllexported"; 468 } 469 return ""; 470 } 471 472 template <bool BeginInstantiation> 473 static void displayTemplightEntry(llvm::raw_ostream &Out, const Sema &TheSema, 474 const CodeSynthesisContext &Inst) { 475 std::string YAML; 476 { 477 llvm::raw_string_ostream OS(YAML); 478 llvm::yaml::Output YO(OS); 479 TemplightEntry Entry = 480 getTemplightEntry<BeginInstantiation>(TheSema, Inst); 481 llvm::yaml::EmptyContext Context; 482 llvm::yaml::yamlize(YO, Entry, true, Context); 483 } 484 Out << "---" << YAML << "\n"; 485 } 486 487 static void printEntryName(const Sema &TheSema, const Decl *Entity, 488 llvm::raw_string_ostream &OS) { 489 auto *NamedTemplate = cast<NamedDecl>(Entity); 490 491 PrintingPolicy Policy = TheSema.Context.getPrintingPolicy(); 492 // FIXME: Also ask for FullyQualifiedNames? 493 Policy.SuppressDefaultTemplateArgs = false; 494 NamedTemplate->getNameForDiagnostic(OS, Policy, true); 495 496 if (!OS.str().empty()) 497 return; 498 499 Decl *Ctx = Decl::castFromDeclContext(NamedTemplate->getDeclContext()); 500 NamedDecl *NamedCtx = dyn_cast_or_null<NamedDecl>(Ctx); 501 502 if (const auto *Decl = dyn_cast<TagDecl>(NamedTemplate)) { 503 if (const auto *R = dyn_cast<RecordDecl>(Decl)) { 504 if (R->isLambda()) { 505 OS << "lambda at "; 506 Decl->getLocation().print(OS, TheSema.getSourceManager()); 507 return; 508 } 509 } 510 OS << "unnamed " << Decl->getKindName(); 511 return; 512 } 513 514 if (const auto *Decl = dyn_cast<ParmVarDecl>(NamedTemplate)) { 515 OS << "unnamed function parameter " << Decl->getFunctionScopeIndex() 516 << " "; 517 if (Decl->getFunctionScopeDepth() > 0) 518 OS << "(at depth " << Decl->getFunctionScopeDepth() << ") "; 519 OS << "of "; 520 NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true); 521 return; 522 } 523 524 if (const auto *Decl = dyn_cast<TemplateTypeParmDecl>(NamedTemplate)) { 525 if (const Type *Ty = Decl->getTypeForDecl()) { 526 if (const auto *TTPT = dyn_cast_or_null<TemplateTypeParmType>(Ty)) { 527 OS << "unnamed template type parameter " << TTPT->getIndex() << " "; 528 if (TTPT->getDepth() > 0) 529 OS << "(at depth " << TTPT->getDepth() << ") "; 530 OS << "of "; 531 NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true); 532 return; 533 } 534 } 535 } 536 537 if (const auto *Decl = dyn_cast<NonTypeTemplateParmDecl>(NamedTemplate)) { 538 OS << "unnamed template non-type parameter " << Decl->getIndex() << " "; 539 if (Decl->getDepth() > 0) 540 OS << "(at depth " << Decl->getDepth() << ") "; 541 OS << "of "; 542 NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true); 543 return; 544 } 545 546 if (const auto *Decl = dyn_cast<TemplateTemplateParmDecl>(NamedTemplate)) { 547 OS << "unnamed template template parameter " << Decl->getIndex() << " "; 548 if (Decl->getDepth() > 0) 549 OS << "(at depth " << Decl->getDepth() << ") "; 550 OS << "of "; 551 NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true); 552 return; 553 } 554 555 llvm_unreachable("Failed to retrieve a name for this entry!"); 556 OS << "unnamed identifier"; 557 } 558 559 template <bool BeginInstantiation> 560 static TemplightEntry getTemplightEntry(const Sema &TheSema, 561 const CodeSynthesisContext &Inst) { 562 TemplightEntry Entry; 563 Entry.Kind = toString(Inst.Kind); 564 Entry.Event = BeginInstantiation ? "Begin" : "End"; 565 llvm::raw_string_ostream OS(Entry.Name); 566 printEntryName(TheSema, Inst.Entity, OS); 567 const PresumedLoc DefLoc = 568 TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation()); 569 if (!DefLoc.isInvalid()) 570 Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" + 571 std::to_string(DefLoc.getLine()) + ":" + 572 std::to_string(DefLoc.getColumn()); 573 const PresumedLoc PoiLoc = 574 TheSema.getSourceManager().getPresumedLoc(Inst.PointOfInstantiation); 575 if (!PoiLoc.isInvalid()) { 576 Entry.PointOfInstantiation = std::string(PoiLoc.getFilename()) + ":" + 577 std::to_string(PoiLoc.getLine()) + ":" + 578 std::to_string(PoiLoc.getColumn()); 579 } 580 return Entry; 581 } 582 }; 583 } // namespace 584 585 std::unique_ptr<ASTConsumer> 586 TemplightDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 587 return std::make_unique<ASTConsumer>(); 588 } 589 590 void TemplightDumpAction::ExecuteAction() { 591 CompilerInstance &CI = getCompilerInstance(); 592 593 // This part is normally done by ASTFrontEndAction, but needs to happen 594 // before Templight observers can be created 595 // FIXME: Move the truncation aspect of this into Sema, we delayed this till 596 // here so the source manager would be initialized. 597 EnsureSemaIsCreated(CI, *this); 598 599 CI.getSema().TemplateInstCallbacks.push_back( 600 std::make_unique<DefaultTemplateInstCallback>()); 601 ASTFrontendAction::ExecuteAction(); 602 } 603 604 namespace { 605 /// AST reader listener that dumps module information for a module 606 /// file. 607 class DumpModuleInfoListener : public ASTReaderListener { 608 llvm::raw_ostream &Out; 609 610 public: 611 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { } 612 613 #define DUMP_BOOLEAN(Value, Text) \ 614 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n" 615 616 bool ReadFullVersionInformation(StringRef FullVersion) override { 617 Out.indent(2) 618 << "Generated by " 619 << (FullVersion == getClangFullRepositoryVersion()? "this" 620 : "a different") 621 << " Clang: " << FullVersion << "\n"; 622 return ASTReaderListener::ReadFullVersionInformation(FullVersion); 623 } 624 625 void ReadModuleName(StringRef ModuleName) override { 626 Out.indent(2) << "Module name: " << ModuleName << "\n"; 627 } 628 void ReadModuleMapFile(StringRef ModuleMapPath) override { 629 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n"; 630 } 631 632 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, 633 bool AllowCompatibleDifferences) override { 634 Out.indent(2) << "Language options:\n"; 635 #define LANGOPT(Name, Bits, Default, Description) \ 636 DUMP_BOOLEAN(LangOpts.Name, Description); 637 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 638 Out.indent(4) << Description << ": " \ 639 << static_cast<unsigned>(LangOpts.get##Name()) << "\n"; 640 #define VALUE_LANGOPT(Name, Bits, Default, Description) \ 641 Out.indent(4) << Description << ": " << LangOpts.Name << "\n"; 642 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 643 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 644 #include "clang/Basic/LangOptions.def" 645 646 if (!LangOpts.ModuleFeatures.empty()) { 647 Out.indent(4) << "Module features:\n"; 648 for (StringRef Feature : LangOpts.ModuleFeatures) 649 Out.indent(6) << Feature << "\n"; 650 } 651 652 return false; 653 } 654 655 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, 656 bool AllowCompatibleDifferences) override { 657 Out.indent(2) << "Target options:\n"; 658 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n"; 659 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n"; 660 Out.indent(4) << " TuneCPU: " << TargetOpts.TuneCPU << "\n"; 661 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n"; 662 663 if (!TargetOpts.FeaturesAsWritten.empty()) { 664 Out.indent(4) << "Target features:\n"; 665 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); 666 I != N; ++I) { 667 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n"; 668 } 669 } 670 671 return false; 672 } 673 674 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, 675 bool Complain) override { 676 Out.indent(2) << "Diagnostic options:\n"; 677 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name); 678 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 679 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n"; 680 #define VALUE_DIAGOPT(Name, Bits, Default) \ 681 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n"; 682 #include "clang/Basic/DiagnosticOptions.def" 683 684 Out.indent(4) << "Diagnostic flags:\n"; 685 for (const std::string &Warning : DiagOpts->Warnings) 686 Out.indent(6) << "-W" << Warning << "\n"; 687 for (const std::string &Remark : DiagOpts->Remarks) 688 Out.indent(6) << "-R" << Remark << "\n"; 689 690 return false; 691 } 692 693 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 694 StringRef SpecificModuleCachePath, 695 bool Complain) override { 696 Out.indent(2) << "Header search options:\n"; 697 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n"; 698 Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n"; 699 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n"; 700 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes, 701 "Use builtin include directories [-nobuiltininc]"); 702 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes, 703 "Use standard system include directories [-nostdinc]"); 704 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes, 705 "Use standard C++ include directories [-nostdinc++]"); 706 DUMP_BOOLEAN(HSOpts.UseLibcxx, 707 "Use libc++ (rather than libstdc++) [-stdlib=]"); 708 return false; 709 } 710 711 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, 712 bool Complain, 713 std::string &SuggestedPredefines) override { 714 Out.indent(2) << "Preprocessor options:\n"; 715 DUMP_BOOLEAN(PPOpts.UsePredefines, 716 "Uses compiler/target-specific predefines [-undef]"); 717 DUMP_BOOLEAN(PPOpts.DetailedRecord, 718 "Uses detailed preprocessing record (for indexing)"); 719 720 if (!PPOpts.Macros.empty()) { 721 Out.indent(4) << "Predefined macros:\n"; 722 } 723 724 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator 725 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end(); 726 I != IEnd; ++I) { 727 Out.indent(6); 728 if (I->second) 729 Out << "-U"; 730 else 731 Out << "-D"; 732 Out << I->first << "\n"; 733 } 734 return false; 735 } 736 737 /// Indicates that a particular module file extension has been read. 738 void readModuleFileExtension( 739 const ModuleFileExtensionMetadata &Metadata) override { 740 Out.indent(2) << "Module file extension '" 741 << Metadata.BlockName << "' " << Metadata.MajorVersion 742 << "." << Metadata.MinorVersion; 743 if (!Metadata.UserInfo.empty()) { 744 Out << ": "; 745 Out.write_escaped(Metadata.UserInfo); 746 } 747 748 Out << "\n"; 749 } 750 751 /// Tells the \c ASTReaderListener that we want to receive the 752 /// input files of the AST file via \c visitInputFile. 753 bool needsInputFileVisitation() override { return true; } 754 755 /// Tells the \c ASTReaderListener that we want to receive the 756 /// input files of the AST file via \c visitInputFile. 757 bool needsSystemInputFileVisitation() override { return true; } 758 759 /// Indicates that the AST file contains particular input file. 760 /// 761 /// \returns true to continue receiving the next input file, false to stop. 762 bool visitInputFile(StringRef Filename, bool isSystem, 763 bool isOverridden, bool isExplicitModule) override { 764 765 Out.indent(2) << "Input file: " << Filename; 766 767 if (isSystem || isOverridden || isExplicitModule) { 768 Out << " ["; 769 if (isSystem) { 770 Out << "System"; 771 if (isOverridden || isExplicitModule) 772 Out << ", "; 773 } 774 if (isOverridden) { 775 Out << "Overridden"; 776 if (isExplicitModule) 777 Out << ", "; 778 } 779 if (isExplicitModule) 780 Out << "ExplicitModule"; 781 782 Out << "]"; 783 } 784 785 Out << "\n"; 786 787 return true; 788 } 789 790 /// Returns true if this \c ASTReaderListener wants to receive the 791 /// imports of the AST file via \c visitImport, false otherwise. 792 bool needsImportVisitation() const override { return true; } 793 794 /// If needsImportVisitation returns \c true, this is called for each 795 /// AST file imported by this AST file. 796 void visitImport(StringRef ModuleName, StringRef Filename) override { 797 Out.indent(2) << "Imports module '" << ModuleName 798 << "': " << Filename.str() << "\n"; 799 } 800 #undef DUMP_BOOLEAN 801 }; 802 } 803 804 bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) { 805 // The Object file reader also supports raw ast files and there is no point in 806 // being strict about the module file format in -module-file-info mode. 807 CI.getHeaderSearchOpts().ModuleFormat = "obj"; 808 return true; 809 } 810 811 static StringRef ModuleKindName(Module::ModuleKind MK) { 812 switch (MK) { 813 case Module::ModuleMapModule: 814 return "Module Map Module"; 815 case Module::ModuleInterfaceUnit: 816 return "Interface Unit"; 817 case Module::ModulePartitionInterface: 818 return "Partition Interface"; 819 case Module::ModulePartitionImplementation: 820 return "Partition Implementation"; 821 case Module::GlobalModuleFragment: 822 return "Global Module Fragment"; 823 case Module::PrivateModuleFragment: 824 return "Private Module Fragment"; 825 } 826 llvm_unreachable("unknown module kind!"); 827 } 828 829 void DumpModuleInfoAction::ExecuteAction() { 830 assert(isCurrentFileAST() && "dumping non-AST?"); 831 // Set up the output file. 832 std::unique_ptr<llvm::raw_fd_ostream> OutFile; 833 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile; 834 if (!OutputFileName.empty() && OutputFileName != "-") { 835 std::error_code EC; 836 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC, 837 llvm::sys::fs::OF_TextWithCRLF)); 838 } 839 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs(); 840 841 Out << "Information for module file '" << getCurrentFile() << "':\n"; 842 auto &FileMgr = getCompilerInstance().getFileManager(); 843 auto Buffer = FileMgr.getBufferForFile(getCurrentFile()); 844 StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer(); 845 bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' && 846 Magic[2] == 'C' && Magic[3] == 'H'); 847 Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n"; 848 849 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 850 DumpModuleInfoListener Listener(Out); 851 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); 852 853 // The FrontendAction::BeginSourceFile () method loads the AST so that much 854 // of the information is already available and modules should have been 855 // loaded. 856 857 const LangOptions &LO = getCurrentASTUnit().getLangOpts(); 858 if (LO.CPlusPlusModules && !LO.CurrentModule.empty()) { 859 860 ASTReader *R = getCurrentASTUnit().getASTReader().get(); 861 unsigned SubModuleCount = R->getTotalNumSubmodules(); 862 serialization::ModuleFile &MF = R->getModuleManager().getPrimaryModule(); 863 Out << " ====== C++20 Module structure ======\n"; 864 865 if (MF.ModuleName != LO.CurrentModule) 866 Out << " Mismatched module names : " << MF.ModuleName << " and " 867 << LO.CurrentModule << "\n"; 868 869 struct SubModInfo { 870 unsigned Idx; 871 Module *Mod; 872 Module::ModuleKind Kind; 873 std::string &Name; 874 bool Seen; 875 }; 876 std::map<std::string, SubModInfo> SubModMap; 877 auto PrintSubMapEntry = [&](std::string Name, Module::ModuleKind Kind) { 878 Out << " " << ModuleKindName(Kind) << " '" << Name << "'"; 879 auto I = SubModMap.find(Name); 880 if (I == SubModMap.end()) 881 Out << " was not found in the sub modules!\n"; 882 else { 883 I->second.Seen = true; 884 Out << " is at index #" << I->second.Idx << "\n"; 885 } 886 }; 887 Module *Primary = nullptr; 888 for (unsigned Idx = 0; Idx <= SubModuleCount; ++Idx) { 889 Module *M = R->getModule(Idx); 890 if (!M) 891 continue; 892 if (M->Name == LO.CurrentModule) { 893 Primary = M; 894 Out << " " << ModuleKindName(M->Kind) << " '" << LO.CurrentModule 895 << "' is the Primary Module at index #" << Idx << "\n"; 896 SubModMap.insert({M->Name, {Idx, M, M->Kind, M->Name, true}}); 897 } else 898 SubModMap.insert({M->Name, {Idx, M, M->Kind, M->Name, false}}); 899 } 900 if (Primary) { 901 if (!Primary->submodules().empty()) 902 Out << " Sub Modules:\n"; 903 for (auto MI : Primary->submodules()) { 904 PrintSubMapEntry(MI->Name, MI->Kind); 905 } 906 if (!Primary->Imports.empty()) 907 Out << " Imports:\n"; 908 for (auto IMP : Primary->Imports) { 909 PrintSubMapEntry(IMP->Name, IMP->Kind); 910 } 911 if (!Primary->Exports.empty()) 912 Out << " Exports:\n"; 913 for (unsigned MN = 0, N = Primary->Exports.size(); MN != N; ++MN) { 914 if (Module *M = Primary->Exports[MN].getPointer()) { 915 PrintSubMapEntry(M->Name, M->Kind); 916 } 917 } 918 } 919 // Now let's print out any modules we did not see as part of the Primary. 920 for (auto SM : SubModMap) { 921 if (!SM.second.Seen && SM.second.Mod) { 922 Out << " " << ModuleKindName(SM.second.Kind) << " '" << SM.first 923 << "' at index #" << SM.second.Idx 924 << " has no direct reference in the Primary\n"; 925 } 926 } 927 Out << " ====== ======\n"; 928 } 929 930 // The reminder of the output is produced from the listener as the AST 931 // FileCcontrolBlock is (re-)parsed. 932 ASTReader::readASTFileControlBlock( 933 getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(), 934 /*FindModuleFileExtensions=*/true, Listener, 935 HSOpts.ModulesValidateDiagnosticOptions); 936 } 937 938 //===----------------------------------------------------------------------===// 939 // Preprocessor Actions 940 //===----------------------------------------------------------------------===// 941 942 void DumpRawTokensAction::ExecuteAction() { 943 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 944 SourceManager &SM = PP.getSourceManager(); 945 946 // Start lexing the specified input file. 947 llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID()); 948 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts()); 949 RawLex.SetKeepWhitespaceMode(true); 950 951 Token RawTok; 952 RawLex.LexFromRawLexer(RawTok); 953 while (RawTok.isNot(tok::eof)) { 954 PP.DumpToken(RawTok, true); 955 llvm::errs() << "\n"; 956 RawLex.LexFromRawLexer(RawTok); 957 } 958 } 959 960 void DumpTokensAction::ExecuteAction() { 961 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 962 // Start preprocessing the specified input file. 963 Token Tok; 964 PP.EnterMainSourceFile(); 965 do { 966 PP.Lex(Tok); 967 PP.DumpToken(Tok, true); 968 llvm::errs() << "\n"; 969 } while (Tok.isNot(tok::eof)); 970 } 971 972 void PreprocessOnlyAction::ExecuteAction() { 973 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 974 975 // Ignore unknown pragmas. 976 PP.IgnorePragmas(); 977 978 Token Tok; 979 // Start parsing the specified input file. 980 PP.EnterMainSourceFile(); 981 do { 982 PP.Lex(Tok); 983 } while (Tok.isNot(tok::eof)); 984 } 985 986 void PrintPreprocessedAction::ExecuteAction() { 987 CompilerInstance &CI = getCompilerInstance(); 988 // Output file may need to be set to 'Binary', to avoid converting Unix style 989 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>) on Windows. 990 // 991 // Look to see what type of line endings the file uses. If there's a 992 // CRLF, then we won't open the file up in binary mode. If there is 993 // just an LF or CR, then we will open the file up in binary mode. 994 // In this fashion, the output format should match the input format, unless 995 // the input format has inconsistent line endings. 996 // 997 // This should be a relatively fast operation since most files won't have 998 // all of their source code on a single line. However, that is still a 999 // concern, so if we scan for too long, we'll just assume the file should 1000 // be opened in binary mode. 1001 1002 bool BinaryMode = false; 1003 if (llvm::Triple(LLVM_HOST_TRIPLE).isOSWindows()) { 1004 BinaryMode = true; 1005 const SourceManager &SM = CI.getSourceManager(); 1006 if (llvm::Optional<llvm::MemoryBufferRef> Buffer = 1007 SM.getBufferOrNone(SM.getMainFileID())) { 1008 const char *cur = Buffer->getBufferStart(); 1009 const char *end = Buffer->getBufferEnd(); 1010 const char *next = (cur != end) ? cur + 1 : end; 1011 1012 // Limit ourselves to only scanning 256 characters into the source 1013 // file. This is mostly a check in case the file has no 1014 // newlines whatsoever. 1015 if (end - cur > 256) 1016 end = cur + 256; 1017 1018 while (next < end) { 1019 if (*cur == 0x0D) { // CR 1020 if (*next == 0x0A) // CRLF 1021 BinaryMode = false; 1022 1023 break; 1024 } else if (*cur == 0x0A) // LF 1025 break; 1026 1027 ++cur; 1028 ++next; 1029 } 1030 } 1031 } 1032 1033 std::unique_ptr<raw_ostream> OS = 1034 CI.createDefaultOutputFile(BinaryMode, getCurrentFileOrBufferName()); 1035 if (!OS) return; 1036 1037 // If we're preprocessing a module map, start by dumping the contents of the 1038 // module itself before switching to the input buffer. 1039 auto &Input = getCurrentInput(); 1040 if (Input.getKind().getFormat() == InputKind::ModuleMap) { 1041 if (Input.isFile()) { 1042 (*OS) << "# 1 \""; 1043 OS->write_escaped(Input.getFile()); 1044 (*OS) << "\"\n"; 1045 } 1046 getCurrentModule()->print(*OS); 1047 (*OS) << "#pragma clang module contents\n"; 1048 } 1049 1050 DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(), 1051 CI.getPreprocessorOutputOpts()); 1052 } 1053 1054 void PrintPreambleAction::ExecuteAction() { 1055 switch (getCurrentFileKind().getLanguage()) { 1056 case Language::C: 1057 case Language::CXX: 1058 case Language::ObjC: 1059 case Language::ObjCXX: 1060 case Language::OpenCL: 1061 case Language::OpenCLCXX: 1062 case Language::CUDA: 1063 case Language::HIP: 1064 break; 1065 1066 case Language::Unknown: 1067 case Language::Asm: 1068 case Language::LLVM_IR: 1069 case Language::RenderScript: 1070 // We can't do anything with these. 1071 return; 1072 } 1073 1074 // We don't expect to find any #include directives in a preprocessed input. 1075 if (getCurrentFileKind().isPreprocessed()) 1076 return; 1077 1078 CompilerInstance &CI = getCompilerInstance(); 1079 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile()); 1080 if (Buffer) { 1081 unsigned Preamble = 1082 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).Size; 1083 llvm::outs().write((*Buffer)->getBufferStart(), Preamble); 1084 } 1085 } 1086 1087 void DumpCompilerOptionsAction::ExecuteAction() { 1088 CompilerInstance &CI = getCompilerInstance(); 1089 std::unique_ptr<raw_ostream> OSP = 1090 CI.createDefaultOutputFile(false, getCurrentFile()); 1091 if (!OSP) 1092 return; 1093 1094 raw_ostream &OS = *OSP; 1095 const Preprocessor &PP = CI.getPreprocessor(); 1096 const LangOptions &LangOpts = PP.getLangOpts(); 1097 1098 // FIXME: Rather than manually format the JSON (which is awkward due to 1099 // needing to remove trailing commas), this should make use of a JSON library. 1100 // FIXME: Instead of printing enums as an integral value and specifying the 1101 // type as a separate field, use introspection to print the enumerator. 1102 1103 OS << "{\n"; 1104 OS << "\n\"features\" : [\n"; 1105 { 1106 llvm::SmallString<128> Str; 1107 #define FEATURE(Name, Predicate) \ 1108 ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \ 1109 .toVector(Str); 1110 #include "clang/Basic/Features.def" 1111 #undef FEATURE 1112 // Remove the newline and comma from the last entry to ensure this remains 1113 // valid JSON. 1114 OS << Str.substr(0, Str.size() - 2); 1115 } 1116 OS << "\n],\n"; 1117 1118 OS << "\n\"extensions\" : [\n"; 1119 { 1120 llvm::SmallString<128> Str; 1121 #define EXTENSION(Name, Predicate) \ 1122 ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \ 1123 .toVector(Str); 1124 #include "clang/Basic/Features.def" 1125 #undef EXTENSION 1126 // Remove the newline and comma from the last entry to ensure this remains 1127 // valid JSON. 1128 OS << Str.substr(0, Str.size() - 2); 1129 } 1130 OS << "\n]\n"; 1131 1132 OS << "}"; 1133 } 1134 1135 void PrintDependencyDirectivesSourceMinimizerAction::ExecuteAction() { 1136 CompilerInstance &CI = getCompilerInstance(); 1137 SourceManager &SM = CI.getPreprocessor().getSourceManager(); 1138 llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID()); 1139 1140 llvm::SmallString<1024> Output; 1141 llvm::SmallVector<minimize_source_to_dependency_directives::Token, 32> Toks; 1142 if (minimizeSourceToDependencyDirectives( 1143 FromFile.getBuffer(), Output, Toks, &CI.getDiagnostics(), 1144 SM.getLocForStartOfFile(SM.getMainFileID()))) { 1145 assert(CI.getDiagnostics().hasErrorOccurred() && 1146 "no errors reported for failure"); 1147 1148 // Preprocess the source when verifying the diagnostics to capture the 1149 // 'expected' comments. 1150 if (CI.getDiagnosticOpts().VerifyDiagnostics) { 1151 // Make sure we don't emit new diagnostics! 1152 CI.getDiagnostics().setSuppressAllDiagnostics(true); 1153 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 1154 PP.EnterMainSourceFile(); 1155 Token Tok; 1156 do { 1157 PP.Lex(Tok); 1158 } while (Tok.isNot(tok::eof)); 1159 } 1160 return; 1161 } 1162 llvm::outs() << Output; 1163 } 1164 1165 void GetDependenciesByModuleNameAction::ExecuteAction() { 1166 CompilerInstance &CI = getCompilerInstance(); 1167 Preprocessor &PP = CI.getPreprocessor(); 1168 SourceManager &SM = PP.getSourceManager(); 1169 FileID MainFileID = SM.getMainFileID(); 1170 SourceLocation FileStart = SM.getLocForStartOfFile(MainFileID); 1171 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 1172 IdentifierInfo *ModuleID = PP.getIdentifierInfo(ModuleName); 1173 Path.push_back(std::make_pair(ModuleID, FileStart)); 1174 auto ModResult = CI.loadModule(FileStart, Path, Module::Hidden, false); 1175 PPCallbacks *CB = PP.getPPCallbacks(); 1176 CB->moduleImport(SourceLocation(), Path, ModResult); 1177 } 1178