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 bool GenerateHeaderUnitAction::BeginSourceFileAction(CompilerInstance &CI) { 340 if (!CI.getLangOpts().CPlusPlusModules) { 341 CI.getDiagnostics().Report(diag::err_module_interface_requires_cpp_modules); 342 return false; 343 } 344 CI.getLangOpts().setCompilingModule(LangOptions::CMK_HeaderUnit); 345 return GenerateModuleAction::BeginSourceFileAction(CI); 346 } 347 348 std::unique_ptr<raw_pwrite_stream> 349 GenerateHeaderUnitAction::CreateOutputFile(CompilerInstance &CI, 350 StringRef InFile) { 351 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm"); 352 } 353 354 SyntaxOnlyAction::~SyntaxOnlyAction() { 355 } 356 357 std::unique_ptr<ASTConsumer> 358 SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 359 return std::make_unique<ASTConsumer>(); 360 } 361 362 std::unique_ptr<ASTConsumer> 363 DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI, 364 StringRef InFile) { 365 return std::make_unique<ASTConsumer>(); 366 } 367 368 std::unique_ptr<ASTConsumer> 369 VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 370 return std::make_unique<ASTConsumer>(); 371 } 372 373 void VerifyPCHAction::ExecuteAction() { 374 CompilerInstance &CI = getCompilerInstance(); 375 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; 376 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot; 377 std::unique_ptr<ASTReader> Reader(new ASTReader( 378 CI.getPreprocessor(), CI.getModuleCache(), &CI.getASTContext(), 379 CI.getPCHContainerReader(), CI.getFrontendOpts().ModuleFileExtensions, 380 Sysroot.empty() ? "" : Sysroot.c_str(), 381 DisableValidationForModuleKind::None, 382 /*AllowASTWithCompilerErrors*/ false, 383 /*AllowConfigurationMismatch*/ true, 384 /*ValidateSystemInputs*/ true)); 385 386 Reader->ReadAST(getCurrentFile(), 387 Preamble ? serialization::MK_Preamble 388 : serialization::MK_PCH, 389 SourceLocation(), 390 ASTReader::ARR_ConfigurationMismatch); 391 } 392 393 namespace { 394 struct TemplightEntry { 395 std::string Name; 396 std::string Kind; 397 std::string Event; 398 std::string DefinitionLocation; 399 std::string PointOfInstantiation; 400 }; 401 } // namespace 402 403 namespace llvm { 404 namespace yaml { 405 template <> struct MappingTraits<TemplightEntry> { 406 static void mapping(IO &io, TemplightEntry &fields) { 407 io.mapRequired("name", fields.Name); 408 io.mapRequired("kind", fields.Kind); 409 io.mapRequired("event", fields.Event); 410 io.mapRequired("orig", fields.DefinitionLocation); 411 io.mapRequired("poi", fields.PointOfInstantiation); 412 } 413 }; 414 } // namespace yaml 415 } // namespace llvm 416 417 namespace { 418 class DefaultTemplateInstCallback : public TemplateInstantiationCallback { 419 using CodeSynthesisContext = Sema::CodeSynthesisContext; 420 421 public: 422 void initialize(const Sema &) override {} 423 424 void finalize(const Sema &) override {} 425 426 void atTemplateBegin(const Sema &TheSema, 427 const CodeSynthesisContext &Inst) override { 428 displayTemplightEntry<true>(llvm::outs(), TheSema, Inst); 429 } 430 431 void atTemplateEnd(const Sema &TheSema, 432 const CodeSynthesisContext &Inst) override { 433 displayTemplightEntry<false>(llvm::outs(), TheSema, Inst); 434 } 435 436 private: 437 static std::string toString(CodeSynthesisContext::SynthesisKind Kind) { 438 switch (Kind) { 439 case CodeSynthesisContext::TemplateInstantiation: 440 return "TemplateInstantiation"; 441 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: 442 return "DefaultTemplateArgumentInstantiation"; 443 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: 444 return "DefaultFunctionArgumentInstantiation"; 445 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: 446 return "ExplicitTemplateArgumentSubstitution"; 447 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: 448 return "DeducedTemplateArgumentSubstitution"; 449 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: 450 return "PriorTemplateArgumentSubstitution"; 451 case CodeSynthesisContext::DefaultTemplateArgumentChecking: 452 return "DefaultTemplateArgumentChecking"; 453 case CodeSynthesisContext::ExceptionSpecEvaluation: 454 return "ExceptionSpecEvaluation"; 455 case CodeSynthesisContext::ExceptionSpecInstantiation: 456 return "ExceptionSpecInstantiation"; 457 case CodeSynthesisContext::DeclaringSpecialMember: 458 return "DeclaringSpecialMember"; 459 case CodeSynthesisContext::DeclaringImplicitEqualityComparison: 460 return "DeclaringImplicitEqualityComparison"; 461 case CodeSynthesisContext::DefiningSynthesizedFunction: 462 return "DefiningSynthesizedFunction"; 463 case CodeSynthesisContext::RewritingOperatorAsSpaceship: 464 return "RewritingOperatorAsSpaceship"; 465 case CodeSynthesisContext::Memoization: 466 return "Memoization"; 467 case CodeSynthesisContext::ConstraintsCheck: 468 return "ConstraintsCheck"; 469 case CodeSynthesisContext::ConstraintSubstitution: 470 return "ConstraintSubstitution"; 471 case CodeSynthesisContext::ConstraintNormalization: 472 return "ConstraintNormalization"; 473 case CodeSynthesisContext::ParameterMappingSubstitution: 474 return "ParameterMappingSubstitution"; 475 case CodeSynthesisContext::RequirementInstantiation: 476 return "RequirementInstantiation"; 477 case CodeSynthesisContext::NestedRequirementConstraintsCheck: 478 return "NestedRequirementConstraintsCheck"; 479 case CodeSynthesisContext::InitializingStructuredBinding: 480 return "InitializingStructuredBinding"; 481 case CodeSynthesisContext::MarkingClassDllexported: 482 return "MarkingClassDllexported"; 483 } 484 return ""; 485 } 486 487 template <bool BeginInstantiation> 488 static void displayTemplightEntry(llvm::raw_ostream &Out, const Sema &TheSema, 489 const CodeSynthesisContext &Inst) { 490 std::string YAML; 491 { 492 llvm::raw_string_ostream OS(YAML); 493 llvm::yaml::Output YO(OS); 494 TemplightEntry Entry = 495 getTemplightEntry<BeginInstantiation>(TheSema, Inst); 496 llvm::yaml::EmptyContext Context; 497 llvm::yaml::yamlize(YO, Entry, true, Context); 498 } 499 Out << "---" << YAML << "\n"; 500 } 501 502 static void printEntryName(const Sema &TheSema, const Decl *Entity, 503 llvm::raw_string_ostream &OS) { 504 auto *NamedTemplate = cast<NamedDecl>(Entity); 505 506 PrintingPolicy Policy = TheSema.Context.getPrintingPolicy(); 507 // FIXME: Also ask for FullyQualifiedNames? 508 Policy.SuppressDefaultTemplateArgs = false; 509 NamedTemplate->getNameForDiagnostic(OS, Policy, true); 510 511 if (!OS.str().empty()) 512 return; 513 514 Decl *Ctx = Decl::castFromDeclContext(NamedTemplate->getDeclContext()); 515 NamedDecl *NamedCtx = dyn_cast_or_null<NamedDecl>(Ctx); 516 517 if (const auto *Decl = dyn_cast<TagDecl>(NamedTemplate)) { 518 if (const auto *R = dyn_cast<RecordDecl>(Decl)) { 519 if (R->isLambda()) { 520 OS << "lambda at "; 521 Decl->getLocation().print(OS, TheSema.getSourceManager()); 522 return; 523 } 524 } 525 OS << "unnamed " << Decl->getKindName(); 526 return; 527 } 528 529 if (const auto *Decl = dyn_cast<ParmVarDecl>(NamedTemplate)) { 530 OS << "unnamed function parameter " << Decl->getFunctionScopeIndex() 531 << " "; 532 if (Decl->getFunctionScopeDepth() > 0) 533 OS << "(at depth " << Decl->getFunctionScopeDepth() << ") "; 534 OS << "of "; 535 NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true); 536 return; 537 } 538 539 if (const auto *Decl = dyn_cast<TemplateTypeParmDecl>(NamedTemplate)) { 540 if (const Type *Ty = Decl->getTypeForDecl()) { 541 if (const auto *TTPT = dyn_cast_or_null<TemplateTypeParmType>(Ty)) { 542 OS << "unnamed template type parameter " << TTPT->getIndex() << " "; 543 if (TTPT->getDepth() > 0) 544 OS << "(at depth " << TTPT->getDepth() << ") "; 545 OS << "of "; 546 NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true); 547 return; 548 } 549 } 550 } 551 552 if (const auto *Decl = dyn_cast<NonTypeTemplateParmDecl>(NamedTemplate)) { 553 OS << "unnamed template non-type parameter " << Decl->getIndex() << " "; 554 if (Decl->getDepth() > 0) 555 OS << "(at depth " << Decl->getDepth() << ") "; 556 OS << "of "; 557 NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true); 558 return; 559 } 560 561 if (const auto *Decl = dyn_cast<TemplateTemplateParmDecl>(NamedTemplate)) { 562 OS << "unnamed template template parameter " << Decl->getIndex() << " "; 563 if (Decl->getDepth() > 0) 564 OS << "(at depth " << Decl->getDepth() << ") "; 565 OS << "of "; 566 NamedCtx->getNameForDiagnostic(OS, TheSema.getLangOpts(), true); 567 return; 568 } 569 570 llvm_unreachable("Failed to retrieve a name for this entry!"); 571 OS << "unnamed identifier"; 572 } 573 574 template <bool BeginInstantiation> 575 static TemplightEntry getTemplightEntry(const Sema &TheSema, 576 const CodeSynthesisContext &Inst) { 577 TemplightEntry Entry; 578 Entry.Kind = toString(Inst.Kind); 579 Entry.Event = BeginInstantiation ? "Begin" : "End"; 580 llvm::raw_string_ostream OS(Entry.Name); 581 printEntryName(TheSema, Inst.Entity, OS); 582 const PresumedLoc DefLoc = 583 TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation()); 584 if (!DefLoc.isInvalid()) 585 Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" + 586 std::to_string(DefLoc.getLine()) + ":" + 587 std::to_string(DefLoc.getColumn()); 588 const PresumedLoc PoiLoc = 589 TheSema.getSourceManager().getPresumedLoc(Inst.PointOfInstantiation); 590 if (!PoiLoc.isInvalid()) { 591 Entry.PointOfInstantiation = std::string(PoiLoc.getFilename()) + ":" + 592 std::to_string(PoiLoc.getLine()) + ":" + 593 std::to_string(PoiLoc.getColumn()); 594 } 595 return Entry; 596 } 597 }; 598 } // namespace 599 600 std::unique_ptr<ASTConsumer> 601 TemplightDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 602 return std::make_unique<ASTConsumer>(); 603 } 604 605 void TemplightDumpAction::ExecuteAction() { 606 CompilerInstance &CI = getCompilerInstance(); 607 608 // This part is normally done by ASTFrontEndAction, but needs to happen 609 // before Templight observers can be created 610 // FIXME: Move the truncation aspect of this into Sema, we delayed this till 611 // here so the source manager would be initialized. 612 EnsureSemaIsCreated(CI, *this); 613 614 CI.getSema().TemplateInstCallbacks.push_back( 615 std::make_unique<DefaultTemplateInstCallback>()); 616 ASTFrontendAction::ExecuteAction(); 617 } 618 619 namespace { 620 /// AST reader listener that dumps module information for a module 621 /// file. 622 class DumpModuleInfoListener : public ASTReaderListener { 623 llvm::raw_ostream &Out; 624 625 public: 626 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { } 627 628 #define DUMP_BOOLEAN(Value, Text) \ 629 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n" 630 631 bool ReadFullVersionInformation(StringRef FullVersion) override { 632 Out.indent(2) 633 << "Generated by " 634 << (FullVersion == getClangFullRepositoryVersion()? "this" 635 : "a different") 636 << " Clang: " << FullVersion << "\n"; 637 return ASTReaderListener::ReadFullVersionInformation(FullVersion); 638 } 639 640 void ReadModuleName(StringRef ModuleName) override { 641 Out.indent(2) << "Module name: " << ModuleName << "\n"; 642 } 643 void ReadModuleMapFile(StringRef ModuleMapPath) override { 644 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n"; 645 } 646 647 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, 648 bool AllowCompatibleDifferences) override { 649 Out.indent(2) << "Language options:\n"; 650 #define LANGOPT(Name, Bits, Default, Description) \ 651 DUMP_BOOLEAN(LangOpts.Name, Description); 652 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 653 Out.indent(4) << Description << ": " \ 654 << static_cast<unsigned>(LangOpts.get##Name()) << "\n"; 655 #define VALUE_LANGOPT(Name, Bits, Default, Description) \ 656 Out.indent(4) << Description << ": " << LangOpts.Name << "\n"; 657 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 658 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 659 #include "clang/Basic/LangOptions.def" 660 661 if (!LangOpts.ModuleFeatures.empty()) { 662 Out.indent(4) << "Module features:\n"; 663 for (StringRef Feature : LangOpts.ModuleFeatures) 664 Out.indent(6) << Feature << "\n"; 665 } 666 667 return false; 668 } 669 670 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, 671 bool AllowCompatibleDifferences) override { 672 Out.indent(2) << "Target options:\n"; 673 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n"; 674 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n"; 675 Out.indent(4) << " TuneCPU: " << TargetOpts.TuneCPU << "\n"; 676 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n"; 677 678 if (!TargetOpts.FeaturesAsWritten.empty()) { 679 Out.indent(4) << "Target features:\n"; 680 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); 681 I != N; ++I) { 682 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n"; 683 } 684 } 685 686 return false; 687 } 688 689 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, 690 bool Complain) override { 691 Out.indent(2) << "Diagnostic options:\n"; 692 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name); 693 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 694 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n"; 695 #define VALUE_DIAGOPT(Name, Bits, Default) \ 696 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n"; 697 #include "clang/Basic/DiagnosticOptions.def" 698 699 Out.indent(4) << "Diagnostic flags:\n"; 700 for (const std::string &Warning : DiagOpts->Warnings) 701 Out.indent(6) << "-W" << Warning << "\n"; 702 for (const std::string &Remark : DiagOpts->Remarks) 703 Out.indent(6) << "-R" << Remark << "\n"; 704 705 return false; 706 } 707 708 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 709 StringRef SpecificModuleCachePath, 710 bool Complain) override { 711 Out.indent(2) << "Header search options:\n"; 712 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n"; 713 Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n"; 714 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n"; 715 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes, 716 "Use builtin include directories [-nobuiltininc]"); 717 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes, 718 "Use standard system include directories [-nostdinc]"); 719 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes, 720 "Use standard C++ include directories [-nostdinc++]"); 721 DUMP_BOOLEAN(HSOpts.UseLibcxx, 722 "Use libc++ (rather than libstdc++) [-stdlib=]"); 723 return false; 724 } 725 726 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, 727 bool Complain, 728 std::string &SuggestedPredefines) override { 729 Out.indent(2) << "Preprocessor options:\n"; 730 DUMP_BOOLEAN(PPOpts.UsePredefines, 731 "Uses compiler/target-specific predefines [-undef]"); 732 DUMP_BOOLEAN(PPOpts.DetailedRecord, 733 "Uses detailed preprocessing record (for indexing)"); 734 735 if (!PPOpts.Macros.empty()) { 736 Out.indent(4) << "Predefined macros:\n"; 737 } 738 739 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator 740 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end(); 741 I != IEnd; ++I) { 742 Out.indent(6); 743 if (I->second) 744 Out << "-U"; 745 else 746 Out << "-D"; 747 Out << I->first << "\n"; 748 } 749 return false; 750 } 751 752 /// Indicates that a particular module file extension has been read. 753 void readModuleFileExtension( 754 const ModuleFileExtensionMetadata &Metadata) override { 755 Out.indent(2) << "Module file extension '" 756 << Metadata.BlockName << "' " << Metadata.MajorVersion 757 << "." << Metadata.MinorVersion; 758 if (!Metadata.UserInfo.empty()) { 759 Out << ": "; 760 Out.write_escaped(Metadata.UserInfo); 761 } 762 763 Out << "\n"; 764 } 765 766 /// Tells the \c ASTReaderListener that we want to receive the 767 /// input files of the AST file via \c visitInputFile. 768 bool needsInputFileVisitation() override { return true; } 769 770 /// Tells the \c ASTReaderListener that we want to receive the 771 /// input files of the AST file via \c visitInputFile. 772 bool needsSystemInputFileVisitation() override { return true; } 773 774 /// Indicates that the AST file contains particular input file. 775 /// 776 /// \returns true to continue receiving the next input file, false to stop. 777 bool visitInputFile(StringRef Filename, bool isSystem, 778 bool isOverridden, bool isExplicitModule) override { 779 780 Out.indent(2) << "Input file: " << Filename; 781 782 if (isSystem || isOverridden || isExplicitModule) { 783 Out << " ["; 784 if (isSystem) { 785 Out << "System"; 786 if (isOverridden || isExplicitModule) 787 Out << ", "; 788 } 789 if (isOverridden) { 790 Out << "Overridden"; 791 if (isExplicitModule) 792 Out << ", "; 793 } 794 if (isExplicitModule) 795 Out << "ExplicitModule"; 796 797 Out << "]"; 798 } 799 800 Out << "\n"; 801 802 return true; 803 } 804 805 /// Returns true if this \c ASTReaderListener wants to receive the 806 /// imports of the AST file via \c visitImport, false otherwise. 807 bool needsImportVisitation() const override { return true; } 808 809 /// If needsImportVisitation returns \c true, this is called for each 810 /// AST file imported by this AST file. 811 void visitImport(StringRef ModuleName, StringRef Filename) override { 812 Out.indent(2) << "Imports module '" << ModuleName 813 << "': " << Filename.str() << "\n"; 814 } 815 #undef DUMP_BOOLEAN 816 }; 817 } 818 819 bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) { 820 // The Object file reader also supports raw ast files and there is no point in 821 // being strict about the module file format in -module-file-info mode. 822 CI.getHeaderSearchOpts().ModuleFormat = "obj"; 823 return true; 824 } 825 826 static StringRef ModuleKindName(Module::ModuleKind MK) { 827 switch (MK) { 828 case Module::ModuleMapModule: 829 return "Module Map Module"; 830 case Module::ModuleInterfaceUnit: 831 return "Interface Unit"; 832 case Module::ModulePartitionInterface: 833 return "Partition Interface"; 834 case Module::ModulePartitionImplementation: 835 return "Partition Implementation"; 836 case Module::ModuleHeaderUnit: 837 return "Header Unit"; 838 case Module::GlobalModuleFragment: 839 return "Global Module Fragment"; 840 case Module::PrivateModuleFragment: 841 return "Private Module Fragment"; 842 } 843 llvm_unreachable("unknown module kind!"); 844 } 845 846 void DumpModuleInfoAction::ExecuteAction() { 847 assert(isCurrentFileAST() && "dumping non-AST?"); 848 // Set up the output file. 849 std::unique_ptr<llvm::raw_fd_ostream> OutFile; 850 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile; 851 if (!OutputFileName.empty() && OutputFileName != "-") { 852 std::error_code EC; 853 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC, 854 llvm::sys::fs::OF_TextWithCRLF)); 855 } 856 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs(); 857 858 Out << "Information for module file '" << getCurrentFile() << "':\n"; 859 auto &FileMgr = getCompilerInstance().getFileManager(); 860 auto Buffer = FileMgr.getBufferForFile(getCurrentFile()); 861 StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer(); 862 bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' && 863 Magic[2] == 'C' && Magic[3] == 'H'); 864 Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n"; 865 866 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 867 DumpModuleInfoListener Listener(Out); 868 HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); 869 870 // The FrontendAction::BeginSourceFile () method loads the AST so that much 871 // of the information is already available and modules should have been 872 // loaded. 873 874 const LangOptions &LO = getCurrentASTUnit().getLangOpts(); 875 if (LO.CPlusPlusModules && !LO.CurrentModule.empty()) { 876 877 ASTReader *R = getCurrentASTUnit().getASTReader().get(); 878 unsigned SubModuleCount = R->getTotalNumSubmodules(); 879 serialization::ModuleFile &MF = R->getModuleManager().getPrimaryModule(); 880 Out << " ====== C++20 Module structure ======\n"; 881 882 if (MF.ModuleName != LO.CurrentModule) 883 Out << " Mismatched module names : " << MF.ModuleName << " and " 884 << LO.CurrentModule << "\n"; 885 886 struct SubModInfo { 887 unsigned Idx; 888 Module *Mod; 889 Module::ModuleKind Kind; 890 std::string &Name; 891 bool Seen; 892 }; 893 std::map<std::string, SubModInfo> SubModMap; 894 auto PrintSubMapEntry = [&](std::string Name, Module::ModuleKind Kind) { 895 Out << " " << ModuleKindName(Kind) << " '" << Name << "'"; 896 auto I = SubModMap.find(Name); 897 if (I == SubModMap.end()) 898 Out << " was not found in the sub modules!\n"; 899 else { 900 I->second.Seen = true; 901 Out << " is at index #" << I->second.Idx << "\n"; 902 } 903 }; 904 Module *Primary = nullptr; 905 for (unsigned Idx = 0; Idx <= SubModuleCount; ++Idx) { 906 Module *M = R->getModule(Idx); 907 if (!M) 908 continue; 909 if (M->Name == LO.CurrentModule) { 910 Primary = M; 911 Out << " " << ModuleKindName(M->Kind) << " '" << LO.CurrentModule 912 << "' is the Primary Module at index #" << Idx << "\n"; 913 SubModMap.insert({M->Name, {Idx, M, M->Kind, M->Name, true}}); 914 } else 915 SubModMap.insert({M->Name, {Idx, M, M->Kind, M->Name, false}}); 916 } 917 if (Primary) { 918 if (!Primary->submodules().empty()) 919 Out << " Sub Modules:\n"; 920 for (auto MI : Primary->submodules()) { 921 PrintSubMapEntry(MI->Name, MI->Kind); 922 } 923 if (!Primary->Imports.empty()) 924 Out << " Imports:\n"; 925 for (auto IMP : Primary->Imports) { 926 PrintSubMapEntry(IMP->Name, IMP->Kind); 927 } 928 if (!Primary->Exports.empty()) 929 Out << " Exports:\n"; 930 for (unsigned MN = 0, N = Primary->Exports.size(); MN != N; ++MN) { 931 if (Module *M = Primary->Exports[MN].getPointer()) { 932 PrintSubMapEntry(M->Name, M->Kind); 933 } 934 } 935 } 936 // Now let's print out any modules we did not see as part of the Primary. 937 for (auto SM : SubModMap) { 938 if (!SM.second.Seen && SM.second.Mod) { 939 Out << " " << ModuleKindName(SM.second.Kind) << " '" << SM.first 940 << "' at index #" << SM.second.Idx 941 << " has no direct reference in the Primary\n"; 942 } 943 } 944 Out << " ====== ======\n"; 945 } 946 947 // The reminder of the output is produced from the listener as the AST 948 // FileCcontrolBlock is (re-)parsed. 949 ASTReader::readASTFileControlBlock( 950 getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(), 951 /*FindModuleFileExtensions=*/true, Listener, 952 HSOpts.ModulesValidateDiagnosticOptions); 953 } 954 955 //===----------------------------------------------------------------------===// 956 // Preprocessor Actions 957 //===----------------------------------------------------------------------===// 958 959 void DumpRawTokensAction::ExecuteAction() { 960 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 961 SourceManager &SM = PP.getSourceManager(); 962 963 // Start lexing the specified input file. 964 llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID()); 965 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts()); 966 RawLex.SetKeepWhitespaceMode(true); 967 968 Token RawTok; 969 RawLex.LexFromRawLexer(RawTok); 970 while (RawTok.isNot(tok::eof)) { 971 PP.DumpToken(RawTok, true); 972 llvm::errs() << "\n"; 973 RawLex.LexFromRawLexer(RawTok); 974 } 975 } 976 977 void DumpTokensAction::ExecuteAction() { 978 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 979 // Start preprocessing the specified input file. 980 Token Tok; 981 PP.EnterMainSourceFile(); 982 do { 983 PP.Lex(Tok); 984 PP.DumpToken(Tok, true); 985 llvm::errs() << "\n"; 986 } while (Tok.isNot(tok::eof)); 987 } 988 989 void PreprocessOnlyAction::ExecuteAction() { 990 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 991 992 // Ignore unknown pragmas. 993 PP.IgnorePragmas(); 994 995 Token Tok; 996 // Start parsing the specified input file. 997 PP.EnterMainSourceFile(); 998 do { 999 PP.Lex(Tok); 1000 } while (Tok.isNot(tok::eof)); 1001 } 1002 1003 void PrintPreprocessedAction::ExecuteAction() { 1004 CompilerInstance &CI = getCompilerInstance(); 1005 // Output file may need to be set to 'Binary', to avoid converting Unix style 1006 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>) on Windows. 1007 // 1008 // Look to see what type of line endings the file uses. If there's a 1009 // CRLF, then we won't open the file up in binary mode. If there is 1010 // just an LF or CR, then we will open the file up in binary mode. 1011 // In this fashion, the output format should match the input format, unless 1012 // the input format has inconsistent line endings. 1013 // 1014 // This should be a relatively fast operation since most files won't have 1015 // all of their source code on a single line. However, that is still a 1016 // concern, so if we scan for too long, we'll just assume the file should 1017 // be opened in binary mode. 1018 1019 bool BinaryMode = false; 1020 if (llvm::Triple(LLVM_HOST_TRIPLE).isOSWindows()) { 1021 BinaryMode = true; 1022 const SourceManager &SM = CI.getSourceManager(); 1023 if (llvm::Optional<llvm::MemoryBufferRef> Buffer = 1024 SM.getBufferOrNone(SM.getMainFileID())) { 1025 const char *cur = Buffer->getBufferStart(); 1026 const char *end = Buffer->getBufferEnd(); 1027 const char *next = (cur != end) ? cur + 1 : end; 1028 1029 // Limit ourselves to only scanning 256 characters into the source 1030 // file. This is mostly a check in case the file has no 1031 // newlines whatsoever. 1032 if (end - cur > 256) 1033 end = cur + 256; 1034 1035 while (next < end) { 1036 if (*cur == 0x0D) { // CR 1037 if (*next == 0x0A) // CRLF 1038 BinaryMode = false; 1039 1040 break; 1041 } else if (*cur == 0x0A) // LF 1042 break; 1043 1044 ++cur; 1045 ++next; 1046 } 1047 } 1048 } 1049 1050 std::unique_ptr<raw_ostream> OS = 1051 CI.createDefaultOutputFile(BinaryMode, getCurrentFileOrBufferName()); 1052 if (!OS) return; 1053 1054 // If we're preprocessing a module map, start by dumping the contents of the 1055 // module itself before switching to the input buffer. 1056 auto &Input = getCurrentInput(); 1057 if (Input.getKind().getFormat() == InputKind::ModuleMap) { 1058 if (Input.isFile()) { 1059 (*OS) << "# 1 \""; 1060 OS->write_escaped(Input.getFile()); 1061 (*OS) << "\"\n"; 1062 } 1063 getCurrentModule()->print(*OS); 1064 (*OS) << "#pragma clang module contents\n"; 1065 } 1066 1067 DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(), 1068 CI.getPreprocessorOutputOpts()); 1069 } 1070 1071 void PrintPreambleAction::ExecuteAction() { 1072 switch (getCurrentFileKind().getLanguage()) { 1073 case Language::C: 1074 case Language::CXX: 1075 case Language::ObjC: 1076 case Language::ObjCXX: 1077 case Language::OpenCL: 1078 case Language::OpenCLCXX: 1079 case Language::CUDA: 1080 case Language::HIP: 1081 case Language::HLSL: 1082 break; 1083 1084 case Language::Unknown: 1085 case Language::Asm: 1086 case Language::LLVM_IR: 1087 case Language::RenderScript: 1088 // We can't do anything with these. 1089 return; 1090 } 1091 1092 // We don't expect to find any #include directives in a preprocessed input. 1093 if (getCurrentFileKind().isPreprocessed()) 1094 return; 1095 1096 CompilerInstance &CI = getCompilerInstance(); 1097 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile()); 1098 if (Buffer) { 1099 unsigned Preamble = 1100 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).Size; 1101 llvm::outs().write((*Buffer)->getBufferStart(), Preamble); 1102 } 1103 } 1104 1105 void DumpCompilerOptionsAction::ExecuteAction() { 1106 CompilerInstance &CI = getCompilerInstance(); 1107 std::unique_ptr<raw_ostream> OSP = 1108 CI.createDefaultOutputFile(false, getCurrentFile()); 1109 if (!OSP) 1110 return; 1111 1112 raw_ostream &OS = *OSP; 1113 const Preprocessor &PP = CI.getPreprocessor(); 1114 const LangOptions &LangOpts = PP.getLangOpts(); 1115 1116 // FIXME: Rather than manually format the JSON (which is awkward due to 1117 // needing to remove trailing commas), this should make use of a JSON library. 1118 // FIXME: Instead of printing enums as an integral value and specifying the 1119 // type as a separate field, use introspection to print the enumerator. 1120 1121 OS << "{\n"; 1122 OS << "\n\"features\" : [\n"; 1123 { 1124 llvm::SmallString<128> Str; 1125 #define FEATURE(Name, Predicate) \ 1126 ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \ 1127 .toVector(Str); 1128 #include "clang/Basic/Features.def" 1129 #undef FEATURE 1130 // Remove the newline and comma from the last entry to ensure this remains 1131 // valid JSON. 1132 OS << Str.substr(0, Str.size() - 2); 1133 } 1134 OS << "\n],\n"; 1135 1136 OS << "\n\"extensions\" : [\n"; 1137 { 1138 llvm::SmallString<128> Str; 1139 #define EXTENSION(Name, Predicate) \ 1140 ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \ 1141 .toVector(Str); 1142 #include "clang/Basic/Features.def" 1143 #undef EXTENSION 1144 // Remove the newline and comma from the last entry to ensure this remains 1145 // valid JSON. 1146 OS << Str.substr(0, Str.size() - 2); 1147 } 1148 OS << "\n]\n"; 1149 1150 OS << "}"; 1151 } 1152 1153 void PrintDependencyDirectivesSourceMinimizerAction::ExecuteAction() { 1154 CompilerInstance &CI = getCompilerInstance(); 1155 SourceManager &SM = CI.getPreprocessor().getSourceManager(); 1156 llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID()); 1157 1158 llvm::SmallString<1024> Output; 1159 llvm::SmallVector<minimize_source_to_dependency_directives::Token, 32> Toks; 1160 if (minimizeSourceToDependencyDirectives( 1161 FromFile.getBuffer(), Output, Toks, &CI.getDiagnostics(), 1162 SM.getLocForStartOfFile(SM.getMainFileID()))) { 1163 assert(CI.getDiagnostics().hasErrorOccurred() && 1164 "no errors reported for failure"); 1165 1166 // Preprocess the source when verifying the diagnostics to capture the 1167 // 'expected' comments. 1168 if (CI.getDiagnosticOpts().VerifyDiagnostics) { 1169 // Make sure we don't emit new diagnostics! 1170 CI.getDiagnostics().setSuppressAllDiagnostics(true); 1171 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 1172 PP.EnterMainSourceFile(); 1173 Token Tok; 1174 do { 1175 PP.Lex(Tok); 1176 } while (Tok.isNot(tok::eof)); 1177 } 1178 return; 1179 } 1180 llvm::outs() << Output; 1181 } 1182 1183 void GetDependenciesByModuleNameAction::ExecuteAction() { 1184 CompilerInstance &CI = getCompilerInstance(); 1185 Preprocessor &PP = CI.getPreprocessor(); 1186 SourceManager &SM = PP.getSourceManager(); 1187 FileID MainFileID = SM.getMainFileID(); 1188 SourceLocation FileStart = SM.getLocForStartOfFile(MainFileID); 1189 SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; 1190 IdentifierInfo *ModuleID = PP.getIdentifierInfo(ModuleName); 1191 Path.push_back(std::make_pair(ModuleID, FileStart)); 1192 auto ModResult = CI.loadModule(FileStart, Path, Module::Hidden, false); 1193 PPCallbacks *CB = PP.getPPCallbacks(); 1194 CB->moduleImport(SourceLocation(), Path, ModResult); 1195 } 1196