106f32e7eSjoerg //===--- FrontendActions.cpp ----------------------------------------------===//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg 
906f32e7eSjoerg #include "clang/Frontend/FrontendActions.h"
1006f32e7eSjoerg #include "clang/AST/ASTConsumer.h"
1106f32e7eSjoerg #include "clang/Basic/FileManager.h"
12*13fbcb42Sjoerg #include "clang/Basic/TargetInfo.h"
1306f32e7eSjoerg #include "clang/Basic/LangStandard.h"
1406f32e7eSjoerg #include "clang/Frontend/ASTConsumers.h"
1506f32e7eSjoerg #include "clang/Frontend/CompilerInstance.h"
1606f32e7eSjoerg #include "clang/Frontend/FrontendDiagnostic.h"
1706f32e7eSjoerg #include "clang/Frontend/MultiplexConsumer.h"
1806f32e7eSjoerg #include "clang/Frontend/Utils.h"
1906f32e7eSjoerg #include "clang/Lex/DependencyDirectivesSourceMinimizer.h"
2006f32e7eSjoerg #include "clang/Lex/HeaderSearch.h"
2106f32e7eSjoerg #include "clang/Lex/Preprocessor.h"
2206f32e7eSjoerg #include "clang/Lex/PreprocessorOptions.h"
2306f32e7eSjoerg #include "clang/Sema/TemplateInstCallback.h"
2406f32e7eSjoerg #include "clang/Serialization/ASTReader.h"
2506f32e7eSjoerg #include "clang/Serialization/ASTWriter.h"
2606f32e7eSjoerg #include "llvm/Support/FileSystem.h"
2706f32e7eSjoerg #include "llvm/Support/MemoryBuffer.h"
2806f32e7eSjoerg #include "llvm/Support/Path.h"
2906f32e7eSjoerg #include "llvm/Support/YAMLTraits.h"
3006f32e7eSjoerg #include "llvm/Support/raw_ostream.h"
3106f32e7eSjoerg #include <memory>
3206f32e7eSjoerg #include <system_error>
3306f32e7eSjoerg 
3406f32e7eSjoerg using namespace clang;
3506f32e7eSjoerg 
3606f32e7eSjoerg namespace {
GetCodeCompletionConsumer(CompilerInstance & CI)3706f32e7eSjoerg CodeCompleteConsumer *GetCodeCompletionConsumer(CompilerInstance &CI) {
3806f32e7eSjoerg   return CI.hasCodeCompletionConsumer() ? &CI.getCodeCompletionConsumer()
3906f32e7eSjoerg                                         : nullptr;
4006f32e7eSjoerg }
4106f32e7eSjoerg 
EnsureSemaIsCreated(CompilerInstance & CI,FrontendAction & Action)4206f32e7eSjoerg void EnsureSemaIsCreated(CompilerInstance &CI, FrontendAction &Action) {
4306f32e7eSjoerg   if (Action.hasCodeCompletionSupport() &&
4406f32e7eSjoerg       !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
4506f32e7eSjoerg     CI.createCodeCompletionConsumer();
4606f32e7eSjoerg 
4706f32e7eSjoerg   if (!CI.hasSema())
4806f32e7eSjoerg     CI.createSema(Action.getTranslationUnitKind(),
4906f32e7eSjoerg                   GetCodeCompletionConsumer(CI));
5006f32e7eSjoerg }
5106f32e7eSjoerg } // namespace
5206f32e7eSjoerg 
5306f32e7eSjoerg //===----------------------------------------------------------------------===//
5406f32e7eSjoerg // Custom Actions
5506f32e7eSjoerg //===----------------------------------------------------------------------===//
5606f32e7eSjoerg 
5706f32e7eSjoerg std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)5806f32e7eSjoerg InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
5906f32e7eSjoerg   return std::make_unique<ASTConsumer>();
6006f32e7eSjoerg }
6106f32e7eSjoerg 
ExecuteAction()6206f32e7eSjoerg void InitOnlyAction::ExecuteAction() {
6306f32e7eSjoerg }
6406f32e7eSjoerg 
6506f32e7eSjoerg //===----------------------------------------------------------------------===//
6606f32e7eSjoerg // AST Consumer Actions
6706f32e7eSjoerg //===----------------------------------------------------------------------===//
6806f32e7eSjoerg 
6906f32e7eSjoerg std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)7006f32e7eSjoerg ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
7106f32e7eSjoerg   if (std::unique_ptr<raw_ostream> OS =
7206f32e7eSjoerg           CI.createDefaultOutputFile(false, InFile))
7306f32e7eSjoerg     return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter);
7406f32e7eSjoerg   return nullptr;
7506f32e7eSjoerg }
7606f32e7eSjoerg 
7706f32e7eSjoerg std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)7806f32e7eSjoerg ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
7906f32e7eSjoerg   const FrontendOptions &Opts = CI.getFrontendOpts();
8006f32e7eSjoerg   return CreateASTDumper(nullptr /*Dump to stdout.*/, Opts.ASTDumpFilter,
8106f32e7eSjoerg                          Opts.ASTDumpDecls, Opts.ASTDumpAll,
82*13fbcb42Sjoerg                          Opts.ASTDumpLookups, Opts.ASTDumpDeclTypes,
83*13fbcb42Sjoerg                          Opts.ASTDumpFormat);
8406f32e7eSjoerg }
8506f32e7eSjoerg 
8606f32e7eSjoerg std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)8706f32e7eSjoerg ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
8806f32e7eSjoerg   return CreateASTDeclNodeLister();
8906f32e7eSjoerg }
9006f32e7eSjoerg 
9106f32e7eSjoerg std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)9206f32e7eSjoerg ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
9306f32e7eSjoerg   return CreateASTViewer();
9406f32e7eSjoerg }
9506f32e7eSjoerg 
9606f32e7eSjoerg std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)9706f32e7eSjoerg GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
9806f32e7eSjoerg   std::string Sysroot;
9906f32e7eSjoerg   if (!ComputeASTConsumerArguments(CI, /*ref*/ Sysroot))
10006f32e7eSjoerg     return nullptr;
10106f32e7eSjoerg 
10206f32e7eSjoerg   std::string OutputFile;
10306f32e7eSjoerg   std::unique_ptr<raw_pwrite_stream> OS =
10406f32e7eSjoerg       CreateOutputFile(CI, InFile, /*ref*/ OutputFile);
10506f32e7eSjoerg   if (!OS)
10606f32e7eSjoerg     return nullptr;
10706f32e7eSjoerg 
10806f32e7eSjoerg   if (!CI.getFrontendOpts().RelocatablePCH)
10906f32e7eSjoerg     Sysroot.clear();
11006f32e7eSjoerg 
11106f32e7eSjoerg   const auto &FrontendOpts = CI.getFrontendOpts();
11206f32e7eSjoerg   auto Buffer = std::make_shared<PCHBuffer>();
11306f32e7eSjoerg   std::vector<std::unique_ptr<ASTConsumer>> Consumers;
11406f32e7eSjoerg   Consumers.push_back(std::make_unique<PCHGenerator>(
11506f32e7eSjoerg       CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer,
11606f32e7eSjoerg       FrontendOpts.ModuleFileExtensions,
11706f32e7eSjoerg       CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
11806f32e7eSjoerg       FrontendOpts.IncludeTimestamps, +CI.getLangOpts().CacheGeneratedPCH));
11906f32e7eSjoerg   Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
120*13fbcb42Sjoerg       CI, std::string(InFile), OutputFile, std::move(OS), Buffer));
12106f32e7eSjoerg 
12206f32e7eSjoerg   return std::make_unique<MultiplexConsumer>(std::move(Consumers));
12306f32e7eSjoerg }
12406f32e7eSjoerg 
ComputeASTConsumerArguments(CompilerInstance & CI,std::string & Sysroot)12506f32e7eSjoerg bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
12606f32e7eSjoerg                                                     std::string &Sysroot) {
12706f32e7eSjoerg   Sysroot = CI.getHeaderSearchOpts().Sysroot;
12806f32e7eSjoerg   if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
12906f32e7eSjoerg     CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
13006f32e7eSjoerg     return false;
13106f32e7eSjoerg   }
13206f32e7eSjoerg 
13306f32e7eSjoerg   return true;
13406f32e7eSjoerg }
13506f32e7eSjoerg 
13606f32e7eSjoerg std::unique_ptr<llvm::raw_pwrite_stream>
CreateOutputFile(CompilerInstance & CI,StringRef InFile,std::string & OutputFile)13706f32e7eSjoerg GeneratePCHAction::CreateOutputFile(CompilerInstance &CI, StringRef InFile,
13806f32e7eSjoerg                                     std::string &OutputFile) {
139*13fbcb42Sjoerg   // Because this is exposed via libclang we must disable RemoveFileOnSignal.
140*13fbcb42Sjoerg   std::unique_ptr<raw_pwrite_stream> OS = CI.createDefaultOutputFile(
141*13fbcb42Sjoerg       /*Binary=*/true, InFile, /*Extension=*/"", /*RemoveFileOnSignal=*/false);
14206f32e7eSjoerg   if (!OS)
14306f32e7eSjoerg     return nullptr;
14406f32e7eSjoerg 
14506f32e7eSjoerg   OutputFile = CI.getFrontendOpts().OutputFile;
14606f32e7eSjoerg   return OS;
14706f32e7eSjoerg }
14806f32e7eSjoerg 
shouldEraseOutputFiles()14906f32e7eSjoerg bool GeneratePCHAction::shouldEraseOutputFiles() {
15006f32e7eSjoerg   if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors)
15106f32e7eSjoerg     return false;
15206f32e7eSjoerg   return ASTFrontendAction::shouldEraseOutputFiles();
15306f32e7eSjoerg }
15406f32e7eSjoerg 
BeginSourceFileAction(CompilerInstance & CI)15506f32e7eSjoerg bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI) {
15606f32e7eSjoerg   CI.getLangOpts().CompilingPCH = true;
15706f32e7eSjoerg   return true;
15806f32e7eSjoerg }
15906f32e7eSjoerg 
16006f32e7eSjoerg std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)16106f32e7eSjoerg GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
16206f32e7eSjoerg                                         StringRef InFile) {
16306f32e7eSjoerg   std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
16406f32e7eSjoerg   if (!OS)
16506f32e7eSjoerg     return nullptr;
16606f32e7eSjoerg 
16706f32e7eSjoerg   std::string OutputFile = CI.getFrontendOpts().OutputFile;
16806f32e7eSjoerg   std::string Sysroot;
16906f32e7eSjoerg 
17006f32e7eSjoerg   auto Buffer = std::make_shared<PCHBuffer>();
17106f32e7eSjoerg   std::vector<std::unique_ptr<ASTConsumer>> Consumers;
17206f32e7eSjoerg 
17306f32e7eSjoerg   Consumers.push_back(std::make_unique<PCHGenerator>(
17406f32e7eSjoerg       CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer,
17506f32e7eSjoerg       CI.getFrontendOpts().ModuleFileExtensions,
176*13fbcb42Sjoerg       /*AllowASTWithErrors=*/
177*13fbcb42Sjoerg       +CI.getFrontendOpts().AllowPCMWithCompilerErrors,
17806f32e7eSjoerg       /*IncludeTimestamps=*/
17906f32e7eSjoerg       +CI.getFrontendOpts().BuildingImplicitModule,
18006f32e7eSjoerg       /*ShouldCacheASTInMemory=*/
18106f32e7eSjoerg       +CI.getFrontendOpts().BuildingImplicitModule));
18206f32e7eSjoerg   Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
183*13fbcb42Sjoerg       CI, std::string(InFile), OutputFile, std::move(OS), Buffer));
18406f32e7eSjoerg   return std::make_unique<MultiplexConsumer>(std::move(Consumers));
18506f32e7eSjoerg }
18606f32e7eSjoerg 
shouldEraseOutputFiles()187*13fbcb42Sjoerg bool GenerateModuleAction::shouldEraseOutputFiles() {
188*13fbcb42Sjoerg   return !getCompilerInstance().getFrontendOpts().AllowPCMWithCompilerErrors &&
189*13fbcb42Sjoerg          ASTFrontendAction::shouldEraseOutputFiles();
190*13fbcb42Sjoerg }
191*13fbcb42Sjoerg 
BeginSourceFileAction(CompilerInstance & CI)19206f32e7eSjoerg bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
19306f32e7eSjoerg     CompilerInstance &CI) {
19406f32e7eSjoerg   if (!CI.getLangOpts().Modules) {
19506f32e7eSjoerg     CI.getDiagnostics().Report(diag::err_module_build_requires_fmodules);
19606f32e7eSjoerg     return false;
19706f32e7eSjoerg   }
19806f32e7eSjoerg 
19906f32e7eSjoerg   return GenerateModuleAction::BeginSourceFileAction(CI);
20006f32e7eSjoerg }
20106f32e7eSjoerg 
20206f32e7eSjoerg std::unique_ptr<raw_pwrite_stream>
CreateOutputFile(CompilerInstance & CI,StringRef InFile)20306f32e7eSjoerg GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
20406f32e7eSjoerg                                                     StringRef InFile) {
20506f32e7eSjoerg   // If no output file was provided, figure out where this module would go
20606f32e7eSjoerg   // in the module cache.
20706f32e7eSjoerg   if (CI.getFrontendOpts().OutputFile.empty()) {
20806f32e7eSjoerg     StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap;
20906f32e7eSjoerg     if (ModuleMapFile.empty())
21006f32e7eSjoerg       ModuleMapFile = InFile;
21106f32e7eSjoerg 
21206f32e7eSjoerg     HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
21306f32e7eSjoerg     CI.getFrontendOpts().OutputFile =
21406f32e7eSjoerg         HS.getCachedModuleFileName(CI.getLangOpts().CurrentModule,
21506f32e7eSjoerg                                    ModuleMapFile);
21606f32e7eSjoerg   }
21706f32e7eSjoerg 
218*13fbcb42Sjoerg   // Because this is exposed via libclang we must disable RemoveFileOnSignal.
219*13fbcb42Sjoerg   return CI.createDefaultOutputFile(/*Binary=*/true, InFile, /*Extension=*/"",
220*13fbcb42Sjoerg                                     /*RemoveFileOnSignal=*/false,
22106f32e7eSjoerg                                     /*CreateMissingDirectories=*/true);
22206f32e7eSjoerg }
22306f32e7eSjoerg 
BeginSourceFileAction(CompilerInstance & CI)22406f32e7eSjoerg bool GenerateModuleInterfaceAction::BeginSourceFileAction(
22506f32e7eSjoerg     CompilerInstance &CI) {
22606f32e7eSjoerg   if (!CI.getLangOpts().ModulesTS && !CI.getLangOpts().CPlusPlusModules) {
22706f32e7eSjoerg     CI.getDiagnostics().Report(diag::err_module_interface_requires_cpp_modules);
22806f32e7eSjoerg     return false;
22906f32e7eSjoerg   }
23006f32e7eSjoerg 
23106f32e7eSjoerg   CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
23206f32e7eSjoerg 
23306f32e7eSjoerg   return GenerateModuleAction::BeginSourceFileAction(CI);
23406f32e7eSjoerg }
23506f32e7eSjoerg 
23606f32e7eSjoerg std::unique_ptr<raw_pwrite_stream>
CreateOutputFile(CompilerInstance & CI,StringRef InFile)23706f32e7eSjoerg GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
23806f32e7eSjoerg                                                 StringRef InFile) {
23906f32e7eSjoerg   return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
24006f32e7eSjoerg }
24106f32e7eSjoerg 
PrepareToExecuteAction(CompilerInstance & CI)24206f32e7eSjoerg bool GenerateHeaderModuleAction::PrepareToExecuteAction(
24306f32e7eSjoerg     CompilerInstance &CI) {
24406f32e7eSjoerg   if (!CI.getLangOpts().Modules) {
24506f32e7eSjoerg     CI.getDiagnostics().Report(diag::err_header_module_requires_modules);
24606f32e7eSjoerg     return false;
24706f32e7eSjoerg   }
24806f32e7eSjoerg 
24906f32e7eSjoerg   auto &Inputs = CI.getFrontendOpts().Inputs;
25006f32e7eSjoerg   if (Inputs.empty())
25106f32e7eSjoerg     return GenerateModuleAction::BeginInvocation(CI);
25206f32e7eSjoerg 
25306f32e7eSjoerg   auto Kind = Inputs[0].getKind();
25406f32e7eSjoerg 
25506f32e7eSjoerg   // Convert the header file inputs into a single module input buffer.
25606f32e7eSjoerg   SmallString<256> HeaderContents;
25706f32e7eSjoerg   ModuleHeaders.reserve(Inputs.size());
25806f32e7eSjoerg   for (const FrontendInputFile &FIF : Inputs) {
25906f32e7eSjoerg     // FIXME: We should support re-compiling from an AST file.
26006f32e7eSjoerg     if (FIF.getKind().getFormat() != InputKind::Source || !FIF.isFile()) {
26106f32e7eSjoerg       CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
26206f32e7eSjoerg           << (FIF.isFile() ? FIF.getFile()
263*13fbcb42Sjoerg                            : FIF.getBuffer().getBufferIdentifier());
26406f32e7eSjoerg       return true;
26506f32e7eSjoerg     }
26606f32e7eSjoerg 
26706f32e7eSjoerg     HeaderContents += "#include \"";
26806f32e7eSjoerg     HeaderContents += FIF.getFile();
26906f32e7eSjoerg     HeaderContents += "\"\n";
270*13fbcb42Sjoerg     ModuleHeaders.push_back(std::string(FIF.getFile()));
27106f32e7eSjoerg   }
27206f32e7eSjoerg   Buffer = llvm::MemoryBuffer::getMemBufferCopy(
27306f32e7eSjoerg       HeaderContents, Module::getModuleInputBufferName());
27406f32e7eSjoerg 
27506f32e7eSjoerg   // Set that buffer up as our "real" input.
27606f32e7eSjoerg   Inputs.clear();
277*13fbcb42Sjoerg   Inputs.push_back(
278*13fbcb42Sjoerg       FrontendInputFile(Buffer->getMemBufferRef(), Kind, /*IsSystem*/ false));
27906f32e7eSjoerg 
28006f32e7eSjoerg   return GenerateModuleAction::PrepareToExecuteAction(CI);
28106f32e7eSjoerg }
28206f32e7eSjoerg 
BeginSourceFileAction(CompilerInstance & CI)28306f32e7eSjoerg bool GenerateHeaderModuleAction::BeginSourceFileAction(
28406f32e7eSjoerg     CompilerInstance &CI) {
28506f32e7eSjoerg   CI.getLangOpts().setCompilingModule(LangOptions::CMK_HeaderModule);
28606f32e7eSjoerg 
28706f32e7eSjoerg   // Synthesize a Module object for the given headers.
28806f32e7eSjoerg   auto &HS = CI.getPreprocessor().getHeaderSearchInfo();
28906f32e7eSjoerg   SmallVector<Module::Header, 16> Headers;
29006f32e7eSjoerg   for (StringRef Name : ModuleHeaders) {
29106f32e7eSjoerg     const DirectoryLookup *CurDir = nullptr;
29206f32e7eSjoerg     Optional<FileEntryRef> FE = HS.LookupFile(
29306f32e7eSjoerg         Name, SourceLocation(), /*Angled*/ false, nullptr, CurDir, None,
29406f32e7eSjoerg         nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
29506f32e7eSjoerg     if (!FE) {
29606f32e7eSjoerg       CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
29706f32e7eSjoerg         << Name;
29806f32e7eSjoerg       continue;
29906f32e7eSjoerg     }
300*13fbcb42Sjoerg     Headers.push_back(
301*13fbcb42Sjoerg         {std::string(Name), std::string(Name), &FE->getFileEntry()});
30206f32e7eSjoerg   }
30306f32e7eSjoerg   HS.getModuleMap().createHeaderModule(CI.getLangOpts().CurrentModule, Headers);
30406f32e7eSjoerg 
30506f32e7eSjoerg   return GenerateModuleAction::BeginSourceFileAction(CI);
30606f32e7eSjoerg }
30706f32e7eSjoerg 
30806f32e7eSjoerg std::unique_ptr<raw_pwrite_stream>
CreateOutputFile(CompilerInstance & CI,StringRef InFile)30906f32e7eSjoerg GenerateHeaderModuleAction::CreateOutputFile(CompilerInstance &CI,
31006f32e7eSjoerg                                              StringRef InFile) {
31106f32e7eSjoerg   return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
31206f32e7eSjoerg }
31306f32e7eSjoerg 
~SyntaxOnlyAction()31406f32e7eSjoerg SyntaxOnlyAction::~SyntaxOnlyAction() {
31506f32e7eSjoerg }
31606f32e7eSjoerg 
31706f32e7eSjoerg std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)31806f32e7eSjoerg SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
31906f32e7eSjoerg   return std::make_unique<ASTConsumer>();
32006f32e7eSjoerg }
32106f32e7eSjoerg 
32206f32e7eSjoerg std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)32306f32e7eSjoerg DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
32406f32e7eSjoerg                                         StringRef InFile) {
32506f32e7eSjoerg   return std::make_unique<ASTConsumer>();
32606f32e7eSjoerg }
32706f32e7eSjoerg 
32806f32e7eSjoerg std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)32906f32e7eSjoerg VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
33006f32e7eSjoerg   return std::make_unique<ASTConsumer>();
33106f32e7eSjoerg }
33206f32e7eSjoerg 
ExecuteAction()33306f32e7eSjoerg void VerifyPCHAction::ExecuteAction() {
33406f32e7eSjoerg   CompilerInstance &CI = getCompilerInstance();
33506f32e7eSjoerg   bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
33606f32e7eSjoerg   const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
33706f32e7eSjoerg   std::unique_ptr<ASTReader> Reader(new ASTReader(
33806f32e7eSjoerg       CI.getPreprocessor(), CI.getModuleCache(), &CI.getASTContext(),
33906f32e7eSjoerg       CI.getPCHContainerReader(), CI.getFrontendOpts().ModuleFileExtensions,
34006f32e7eSjoerg       Sysroot.empty() ? "" : Sysroot.c_str(),
341*13fbcb42Sjoerg       DisableValidationForModuleKind::None,
342*13fbcb42Sjoerg       /*AllowASTWithCompilerErrors*/ false,
34306f32e7eSjoerg       /*AllowConfigurationMismatch*/ true,
34406f32e7eSjoerg       /*ValidateSystemInputs*/ true));
34506f32e7eSjoerg 
34606f32e7eSjoerg   Reader->ReadAST(getCurrentFile(),
34706f32e7eSjoerg                   Preamble ? serialization::MK_Preamble
34806f32e7eSjoerg                            : serialization::MK_PCH,
34906f32e7eSjoerg                   SourceLocation(),
35006f32e7eSjoerg                   ASTReader::ARR_ConfigurationMismatch);
35106f32e7eSjoerg }
35206f32e7eSjoerg 
35306f32e7eSjoerg namespace {
35406f32e7eSjoerg struct TemplightEntry {
35506f32e7eSjoerg   std::string Name;
35606f32e7eSjoerg   std::string Kind;
35706f32e7eSjoerg   std::string Event;
35806f32e7eSjoerg   std::string DefinitionLocation;
35906f32e7eSjoerg   std::string PointOfInstantiation;
36006f32e7eSjoerg };
36106f32e7eSjoerg } // namespace
36206f32e7eSjoerg 
36306f32e7eSjoerg namespace llvm {
36406f32e7eSjoerg namespace yaml {
36506f32e7eSjoerg template <> struct MappingTraits<TemplightEntry> {
mappingllvm::yaml::MappingTraits36606f32e7eSjoerg   static void mapping(IO &io, TemplightEntry &fields) {
36706f32e7eSjoerg     io.mapRequired("name", fields.Name);
36806f32e7eSjoerg     io.mapRequired("kind", fields.Kind);
36906f32e7eSjoerg     io.mapRequired("event", fields.Event);
37006f32e7eSjoerg     io.mapRequired("orig", fields.DefinitionLocation);
37106f32e7eSjoerg     io.mapRequired("poi", fields.PointOfInstantiation);
37206f32e7eSjoerg   }
37306f32e7eSjoerg };
37406f32e7eSjoerg } // namespace yaml
37506f32e7eSjoerg } // namespace llvm
37606f32e7eSjoerg 
37706f32e7eSjoerg namespace {
37806f32e7eSjoerg class DefaultTemplateInstCallback : public TemplateInstantiationCallback {
37906f32e7eSjoerg   using CodeSynthesisContext = Sema::CodeSynthesisContext;
38006f32e7eSjoerg 
38106f32e7eSjoerg public:
initialize(const Sema &)38206f32e7eSjoerg   void initialize(const Sema &) override {}
38306f32e7eSjoerg 
finalize(const Sema &)38406f32e7eSjoerg   void finalize(const Sema &) override {}
38506f32e7eSjoerg 
atTemplateBegin(const Sema & TheSema,const CodeSynthesisContext & Inst)38606f32e7eSjoerg   void atTemplateBegin(const Sema &TheSema,
38706f32e7eSjoerg                        const CodeSynthesisContext &Inst) override {
38806f32e7eSjoerg     displayTemplightEntry<true>(llvm::outs(), TheSema, Inst);
38906f32e7eSjoerg   }
39006f32e7eSjoerg 
atTemplateEnd(const Sema & TheSema,const CodeSynthesisContext & Inst)39106f32e7eSjoerg   void atTemplateEnd(const Sema &TheSema,
39206f32e7eSjoerg                      const CodeSynthesisContext &Inst) override {
39306f32e7eSjoerg     displayTemplightEntry<false>(llvm::outs(), TheSema, Inst);
39406f32e7eSjoerg   }
39506f32e7eSjoerg 
39606f32e7eSjoerg private:
toString(CodeSynthesisContext::SynthesisKind Kind)39706f32e7eSjoerg   static std::string toString(CodeSynthesisContext::SynthesisKind Kind) {
39806f32e7eSjoerg     switch (Kind) {
39906f32e7eSjoerg     case CodeSynthesisContext::TemplateInstantiation:
40006f32e7eSjoerg       return "TemplateInstantiation";
40106f32e7eSjoerg     case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
40206f32e7eSjoerg       return "DefaultTemplateArgumentInstantiation";
40306f32e7eSjoerg     case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
40406f32e7eSjoerg       return "DefaultFunctionArgumentInstantiation";
40506f32e7eSjoerg     case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
40606f32e7eSjoerg       return "ExplicitTemplateArgumentSubstitution";
40706f32e7eSjoerg     case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
40806f32e7eSjoerg       return "DeducedTemplateArgumentSubstitution";
40906f32e7eSjoerg     case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
41006f32e7eSjoerg       return "PriorTemplateArgumentSubstitution";
41106f32e7eSjoerg     case CodeSynthesisContext::DefaultTemplateArgumentChecking:
41206f32e7eSjoerg       return "DefaultTemplateArgumentChecking";
41306f32e7eSjoerg     case CodeSynthesisContext::ExceptionSpecEvaluation:
41406f32e7eSjoerg       return "ExceptionSpecEvaluation";
41506f32e7eSjoerg     case CodeSynthesisContext::ExceptionSpecInstantiation:
41606f32e7eSjoerg       return "ExceptionSpecInstantiation";
41706f32e7eSjoerg     case CodeSynthesisContext::DeclaringSpecialMember:
41806f32e7eSjoerg       return "DeclaringSpecialMember";
419*13fbcb42Sjoerg     case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
420*13fbcb42Sjoerg       return "DeclaringImplicitEqualityComparison";
42106f32e7eSjoerg     case CodeSynthesisContext::DefiningSynthesizedFunction:
42206f32e7eSjoerg       return "DefiningSynthesizedFunction";
42306f32e7eSjoerg     case CodeSynthesisContext::RewritingOperatorAsSpaceship:
42406f32e7eSjoerg       return "RewritingOperatorAsSpaceship";
42506f32e7eSjoerg     case CodeSynthesisContext::Memoization:
42606f32e7eSjoerg       return "Memoization";
42706f32e7eSjoerg     case CodeSynthesisContext::ConstraintsCheck:
42806f32e7eSjoerg       return "ConstraintsCheck";
42906f32e7eSjoerg     case CodeSynthesisContext::ConstraintSubstitution:
43006f32e7eSjoerg       return "ConstraintSubstitution";
431*13fbcb42Sjoerg     case CodeSynthesisContext::ConstraintNormalization:
432*13fbcb42Sjoerg       return "ConstraintNormalization";
433*13fbcb42Sjoerg     case CodeSynthesisContext::ParameterMappingSubstitution:
434*13fbcb42Sjoerg       return "ParameterMappingSubstitution";
435*13fbcb42Sjoerg     case CodeSynthesisContext::RequirementInstantiation:
436*13fbcb42Sjoerg       return "RequirementInstantiation";
437*13fbcb42Sjoerg     case CodeSynthesisContext::NestedRequirementConstraintsCheck:
438*13fbcb42Sjoerg       return "NestedRequirementConstraintsCheck";
439*13fbcb42Sjoerg     case CodeSynthesisContext::InitializingStructuredBinding:
440*13fbcb42Sjoerg       return "InitializingStructuredBinding";
441*13fbcb42Sjoerg     case CodeSynthesisContext::MarkingClassDllexported:
442*13fbcb42Sjoerg       return "MarkingClassDllexported";
44306f32e7eSjoerg     }
44406f32e7eSjoerg     return "";
44506f32e7eSjoerg   }
44606f32e7eSjoerg 
44706f32e7eSjoerg   template <bool BeginInstantiation>
displayTemplightEntry(llvm::raw_ostream & Out,const Sema & TheSema,const CodeSynthesisContext & Inst)44806f32e7eSjoerg   static void displayTemplightEntry(llvm::raw_ostream &Out, const Sema &TheSema,
44906f32e7eSjoerg                                     const CodeSynthesisContext &Inst) {
45006f32e7eSjoerg     std::string YAML;
45106f32e7eSjoerg     {
45206f32e7eSjoerg       llvm::raw_string_ostream OS(YAML);
45306f32e7eSjoerg       llvm::yaml::Output YO(OS);
45406f32e7eSjoerg       TemplightEntry Entry =
45506f32e7eSjoerg           getTemplightEntry<BeginInstantiation>(TheSema, Inst);
45606f32e7eSjoerg       llvm::yaml::EmptyContext Context;
45706f32e7eSjoerg       llvm::yaml::yamlize(YO, Entry, true, Context);
45806f32e7eSjoerg     }
45906f32e7eSjoerg     Out << "---" << YAML << "\n";
46006f32e7eSjoerg   }
46106f32e7eSjoerg 
46206f32e7eSjoerg   template <bool BeginInstantiation>
getTemplightEntry(const Sema & TheSema,const CodeSynthesisContext & Inst)46306f32e7eSjoerg   static TemplightEntry getTemplightEntry(const Sema &TheSema,
46406f32e7eSjoerg                                           const CodeSynthesisContext &Inst) {
46506f32e7eSjoerg     TemplightEntry Entry;
46606f32e7eSjoerg     Entry.Kind = toString(Inst.Kind);
46706f32e7eSjoerg     Entry.Event = BeginInstantiation ? "Begin" : "End";
46806f32e7eSjoerg     if (auto *NamedTemplate = dyn_cast_or_null<NamedDecl>(Inst.Entity)) {
46906f32e7eSjoerg       llvm::raw_string_ostream OS(Entry.Name);
470*13fbcb42Sjoerg       PrintingPolicy Policy = TheSema.Context.getPrintingPolicy();
471*13fbcb42Sjoerg       // FIXME: Also ask for FullyQualifiedNames?
472*13fbcb42Sjoerg       Policy.SuppressDefaultTemplateArgs = false;
473*13fbcb42Sjoerg       NamedTemplate->getNameForDiagnostic(OS, Policy, true);
47406f32e7eSjoerg       const PresumedLoc DefLoc =
47506f32e7eSjoerg         TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation());
47606f32e7eSjoerg       if(!DefLoc.isInvalid())
47706f32e7eSjoerg         Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" +
47806f32e7eSjoerg                                    std::to_string(DefLoc.getLine()) + ":" +
47906f32e7eSjoerg                                    std::to_string(DefLoc.getColumn());
48006f32e7eSjoerg     }
48106f32e7eSjoerg     const PresumedLoc PoiLoc =
48206f32e7eSjoerg         TheSema.getSourceManager().getPresumedLoc(Inst.PointOfInstantiation);
48306f32e7eSjoerg     if (!PoiLoc.isInvalid()) {
48406f32e7eSjoerg       Entry.PointOfInstantiation = std::string(PoiLoc.getFilename()) + ":" +
48506f32e7eSjoerg                                    std::to_string(PoiLoc.getLine()) + ":" +
48606f32e7eSjoerg                                    std::to_string(PoiLoc.getColumn());
48706f32e7eSjoerg     }
48806f32e7eSjoerg     return Entry;
48906f32e7eSjoerg   }
49006f32e7eSjoerg };
49106f32e7eSjoerg } // namespace
49206f32e7eSjoerg 
49306f32e7eSjoerg std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)49406f32e7eSjoerg TemplightDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
49506f32e7eSjoerg   return std::make_unique<ASTConsumer>();
49606f32e7eSjoerg }
49706f32e7eSjoerg 
ExecuteAction()49806f32e7eSjoerg void TemplightDumpAction::ExecuteAction() {
49906f32e7eSjoerg   CompilerInstance &CI = getCompilerInstance();
50006f32e7eSjoerg 
50106f32e7eSjoerg   // This part is normally done by ASTFrontEndAction, but needs to happen
50206f32e7eSjoerg   // before Templight observers can be created
50306f32e7eSjoerg   // FIXME: Move the truncation aspect of this into Sema, we delayed this till
50406f32e7eSjoerg   // here so the source manager would be initialized.
50506f32e7eSjoerg   EnsureSemaIsCreated(CI, *this);
50606f32e7eSjoerg 
50706f32e7eSjoerg   CI.getSema().TemplateInstCallbacks.push_back(
50806f32e7eSjoerg       std::make_unique<DefaultTemplateInstCallback>());
50906f32e7eSjoerg   ASTFrontendAction::ExecuteAction();
51006f32e7eSjoerg }
51106f32e7eSjoerg 
51206f32e7eSjoerg namespace {
51306f32e7eSjoerg   /// AST reader listener that dumps module information for a module
51406f32e7eSjoerg   /// file.
51506f32e7eSjoerg   class DumpModuleInfoListener : public ASTReaderListener {
51606f32e7eSjoerg     llvm::raw_ostream &Out;
51706f32e7eSjoerg 
51806f32e7eSjoerg   public:
DumpModuleInfoListener(llvm::raw_ostream & Out)51906f32e7eSjoerg     DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
52006f32e7eSjoerg 
52106f32e7eSjoerg #define DUMP_BOOLEAN(Value, Text)                       \
52206f32e7eSjoerg     Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
52306f32e7eSjoerg 
ReadFullVersionInformation(StringRef FullVersion)52406f32e7eSjoerg     bool ReadFullVersionInformation(StringRef FullVersion) override {
52506f32e7eSjoerg       Out.indent(2)
52606f32e7eSjoerg         << "Generated by "
52706f32e7eSjoerg         << (FullVersion == getClangFullRepositoryVersion()? "this"
52806f32e7eSjoerg                                                           : "a different")
52906f32e7eSjoerg         << " Clang: " << FullVersion << "\n";
53006f32e7eSjoerg       return ASTReaderListener::ReadFullVersionInformation(FullVersion);
53106f32e7eSjoerg     }
53206f32e7eSjoerg 
ReadModuleName(StringRef ModuleName)53306f32e7eSjoerg     void ReadModuleName(StringRef ModuleName) override {
53406f32e7eSjoerg       Out.indent(2) << "Module name: " << ModuleName << "\n";
53506f32e7eSjoerg     }
ReadModuleMapFile(StringRef ModuleMapPath)53606f32e7eSjoerg     void ReadModuleMapFile(StringRef ModuleMapPath) override {
53706f32e7eSjoerg       Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
53806f32e7eSjoerg     }
53906f32e7eSjoerg 
ReadLanguageOptions(const LangOptions & LangOpts,bool Complain,bool AllowCompatibleDifferences)54006f32e7eSjoerg     bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
54106f32e7eSjoerg                              bool AllowCompatibleDifferences) override {
54206f32e7eSjoerg       Out.indent(2) << "Language options:\n";
54306f32e7eSjoerg #define LANGOPT(Name, Bits, Default, Description) \
54406f32e7eSjoerg       DUMP_BOOLEAN(LangOpts.Name, Description);
54506f32e7eSjoerg #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
54606f32e7eSjoerg       Out.indent(4) << Description << ": "                   \
54706f32e7eSjoerg                     << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
54806f32e7eSjoerg #define VALUE_LANGOPT(Name, Bits, Default, Description) \
54906f32e7eSjoerg       Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
55006f32e7eSjoerg #define BENIGN_LANGOPT(Name, Bits, Default, Description)
55106f32e7eSjoerg #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
55206f32e7eSjoerg #include "clang/Basic/LangOptions.def"
55306f32e7eSjoerg 
55406f32e7eSjoerg       if (!LangOpts.ModuleFeatures.empty()) {
55506f32e7eSjoerg         Out.indent(4) << "Module features:\n";
55606f32e7eSjoerg         for (StringRef Feature : LangOpts.ModuleFeatures)
55706f32e7eSjoerg           Out.indent(6) << Feature << "\n";
55806f32e7eSjoerg       }
55906f32e7eSjoerg 
56006f32e7eSjoerg       return false;
56106f32e7eSjoerg     }
56206f32e7eSjoerg 
ReadTargetOptions(const TargetOptions & TargetOpts,bool Complain,bool AllowCompatibleDifferences)56306f32e7eSjoerg     bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
56406f32e7eSjoerg                            bool AllowCompatibleDifferences) override {
56506f32e7eSjoerg       Out.indent(2) << "Target options:\n";
56606f32e7eSjoerg       Out.indent(4) << "  Triple: " << TargetOpts.Triple << "\n";
56706f32e7eSjoerg       Out.indent(4) << "  CPU: " << TargetOpts.CPU << "\n";
568*13fbcb42Sjoerg       Out.indent(4) << "  TuneCPU: " << TargetOpts.TuneCPU << "\n";
56906f32e7eSjoerg       Out.indent(4) << "  ABI: " << TargetOpts.ABI << "\n";
57006f32e7eSjoerg 
57106f32e7eSjoerg       if (!TargetOpts.FeaturesAsWritten.empty()) {
57206f32e7eSjoerg         Out.indent(4) << "Target features:\n";
57306f32e7eSjoerg         for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
57406f32e7eSjoerg              I != N; ++I) {
57506f32e7eSjoerg           Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
57606f32e7eSjoerg         }
57706f32e7eSjoerg       }
57806f32e7eSjoerg 
57906f32e7eSjoerg       return false;
58006f32e7eSjoerg     }
58106f32e7eSjoerg 
ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,bool Complain)58206f32e7eSjoerg     bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
58306f32e7eSjoerg                                bool Complain) override {
58406f32e7eSjoerg       Out.indent(2) << "Diagnostic options:\n";
58506f32e7eSjoerg #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
58606f32e7eSjoerg #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
58706f32e7eSjoerg       Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
58806f32e7eSjoerg #define VALUE_DIAGOPT(Name, Bits, Default) \
58906f32e7eSjoerg       Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
59006f32e7eSjoerg #include "clang/Basic/DiagnosticOptions.def"
59106f32e7eSjoerg 
59206f32e7eSjoerg       Out.indent(4) << "Diagnostic flags:\n";
59306f32e7eSjoerg       for (const std::string &Warning : DiagOpts->Warnings)
59406f32e7eSjoerg         Out.indent(6) << "-W" << Warning << "\n";
59506f32e7eSjoerg       for (const std::string &Remark : DiagOpts->Remarks)
59606f32e7eSjoerg         Out.indent(6) << "-R" << Remark << "\n";
59706f32e7eSjoerg 
59806f32e7eSjoerg       return false;
59906f32e7eSjoerg     }
60006f32e7eSjoerg 
ReadHeaderSearchOptions(const HeaderSearchOptions & HSOpts,StringRef SpecificModuleCachePath,bool Complain)60106f32e7eSjoerg     bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
60206f32e7eSjoerg                                  StringRef SpecificModuleCachePath,
60306f32e7eSjoerg                                  bool Complain) override {
60406f32e7eSjoerg       Out.indent(2) << "Header search options:\n";
60506f32e7eSjoerg       Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
60606f32e7eSjoerg       Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
60706f32e7eSjoerg       Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
60806f32e7eSjoerg       DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
60906f32e7eSjoerg                    "Use builtin include directories [-nobuiltininc]");
61006f32e7eSjoerg       DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
61106f32e7eSjoerg                    "Use standard system include directories [-nostdinc]");
61206f32e7eSjoerg       DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
61306f32e7eSjoerg                    "Use standard C++ include directories [-nostdinc++]");
61406f32e7eSjoerg       DUMP_BOOLEAN(HSOpts.UseLibcxx,
61506f32e7eSjoerg                    "Use libc++ (rather than libstdc++) [-stdlib=]");
61606f32e7eSjoerg       return false;
61706f32e7eSjoerg     }
61806f32e7eSjoerg 
ReadPreprocessorOptions(const PreprocessorOptions & PPOpts,bool Complain,std::string & SuggestedPredefines)61906f32e7eSjoerg     bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
62006f32e7eSjoerg                                  bool Complain,
62106f32e7eSjoerg                                  std::string &SuggestedPredefines) override {
62206f32e7eSjoerg       Out.indent(2) << "Preprocessor options:\n";
62306f32e7eSjoerg       DUMP_BOOLEAN(PPOpts.UsePredefines,
62406f32e7eSjoerg                    "Uses compiler/target-specific predefines [-undef]");
62506f32e7eSjoerg       DUMP_BOOLEAN(PPOpts.DetailedRecord,
62606f32e7eSjoerg                    "Uses detailed preprocessing record (for indexing)");
62706f32e7eSjoerg 
62806f32e7eSjoerg       if (!PPOpts.Macros.empty()) {
62906f32e7eSjoerg         Out.indent(4) << "Predefined macros:\n";
63006f32e7eSjoerg       }
63106f32e7eSjoerg 
63206f32e7eSjoerg       for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
63306f32e7eSjoerg              I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
63406f32e7eSjoerg            I != IEnd; ++I) {
63506f32e7eSjoerg         Out.indent(6);
63606f32e7eSjoerg         if (I->second)
63706f32e7eSjoerg           Out << "-U";
63806f32e7eSjoerg         else
63906f32e7eSjoerg           Out << "-D";
64006f32e7eSjoerg         Out << I->first << "\n";
64106f32e7eSjoerg       }
64206f32e7eSjoerg       return false;
64306f32e7eSjoerg     }
64406f32e7eSjoerg 
64506f32e7eSjoerg     /// Indicates that a particular module file extension has been read.
readModuleFileExtension(const ModuleFileExtensionMetadata & Metadata)64606f32e7eSjoerg     void readModuleFileExtension(
64706f32e7eSjoerg            const ModuleFileExtensionMetadata &Metadata) override {
64806f32e7eSjoerg       Out.indent(2) << "Module file extension '"
64906f32e7eSjoerg                     << Metadata.BlockName << "' " << Metadata.MajorVersion
65006f32e7eSjoerg                     << "." << Metadata.MinorVersion;
65106f32e7eSjoerg       if (!Metadata.UserInfo.empty()) {
65206f32e7eSjoerg         Out << ": ";
65306f32e7eSjoerg         Out.write_escaped(Metadata.UserInfo);
65406f32e7eSjoerg       }
65506f32e7eSjoerg 
65606f32e7eSjoerg       Out << "\n";
65706f32e7eSjoerg     }
65806f32e7eSjoerg 
65906f32e7eSjoerg     /// Tells the \c ASTReaderListener that we want to receive the
66006f32e7eSjoerg     /// input files of the AST file via \c visitInputFile.
needsInputFileVisitation()66106f32e7eSjoerg     bool needsInputFileVisitation() override { return true; }
66206f32e7eSjoerg 
66306f32e7eSjoerg     /// Tells the \c ASTReaderListener that we want to receive the
66406f32e7eSjoerg     /// input files of the AST file via \c visitInputFile.
needsSystemInputFileVisitation()66506f32e7eSjoerg     bool needsSystemInputFileVisitation() override { return true; }
66606f32e7eSjoerg 
66706f32e7eSjoerg     /// Indicates that the AST file contains particular input file.
66806f32e7eSjoerg     ///
66906f32e7eSjoerg     /// \returns true to continue receiving the next input file, false to stop.
visitInputFile(StringRef Filename,bool isSystem,bool isOverridden,bool isExplicitModule)67006f32e7eSjoerg     bool visitInputFile(StringRef Filename, bool isSystem,
67106f32e7eSjoerg                         bool isOverridden, bool isExplicitModule) override {
67206f32e7eSjoerg 
67306f32e7eSjoerg       Out.indent(2) << "Input file: " << Filename;
67406f32e7eSjoerg 
67506f32e7eSjoerg       if (isSystem || isOverridden || isExplicitModule) {
67606f32e7eSjoerg         Out << " [";
67706f32e7eSjoerg         if (isSystem) {
67806f32e7eSjoerg           Out << "System";
67906f32e7eSjoerg           if (isOverridden || isExplicitModule)
68006f32e7eSjoerg             Out << ", ";
68106f32e7eSjoerg         }
68206f32e7eSjoerg         if (isOverridden) {
68306f32e7eSjoerg           Out << "Overridden";
68406f32e7eSjoerg           if (isExplicitModule)
68506f32e7eSjoerg             Out << ", ";
68606f32e7eSjoerg         }
68706f32e7eSjoerg         if (isExplicitModule)
68806f32e7eSjoerg           Out << "ExplicitModule";
68906f32e7eSjoerg 
69006f32e7eSjoerg         Out << "]";
69106f32e7eSjoerg       }
69206f32e7eSjoerg 
69306f32e7eSjoerg       Out << "\n";
69406f32e7eSjoerg 
69506f32e7eSjoerg       return true;
69606f32e7eSjoerg     }
69706f32e7eSjoerg 
69806f32e7eSjoerg     /// Returns true if this \c ASTReaderListener wants to receive the
69906f32e7eSjoerg     /// imports of the AST file via \c visitImport, false otherwise.
needsImportVisitation() const70006f32e7eSjoerg     bool needsImportVisitation() const override { return true; }
70106f32e7eSjoerg 
70206f32e7eSjoerg     /// If needsImportVisitation returns \c true, this is called for each
70306f32e7eSjoerg     /// AST file imported by this AST file.
visitImport(StringRef ModuleName,StringRef Filename)70406f32e7eSjoerg     void visitImport(StringRef ModuleName, StringRef Filename) override {
70506f32e7eSjoerg       Out.indent(2) << "Imports module '" << ModuleName
70606f32e7eSjoerg                     << "': " << Filename.str() << "\n";
70706f32e7eSjoerg     }
70806f32e7eSjoerg #undef DUMP_BOOLEAN
70906f32e7eSjoerg   };
71006f32e7eSjoerg }
71106f32e7eSjoerg 
BeginInvocation(CompilerInstance & CI)71206f32e7eSjoerg bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
71306f32e7eSjoerg   // The Object file reader also supports raw ast files and there is no point in
71406f32e7eSjoerg   // being strict about the module file format in -module-file-info mode.
71506f32e7eSjoerg   CI.getHeaderSearchOpts().ModuleFormat = "obj";
71606f32e7eSjoerg   return true;
71706f32e7eSjoerg }
71806f32e7eSjoerg 
ExecuteAction()71906f32e7eSjoerg void DumpModuleInfoAction::ExecuteAction() {
72006f32e7eSjoerg   // Set up the output file.
72106f32e7eSjoerg   std::unique_ptr<llvm::raw_fd_ostream> OutFile;
72206f32e7eSjoerg   StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
72306f32e7eSjoerg   if (!OutputFileName.empty() && OutputFileName != "-") {
72406f32e7eSjoerg     std::error_code EC;
72506f32e7eSjoerg     OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
726*13fbcb42Sjoerg                                            llvm::sys::fs::OF_TextWithCRLF));
72706f32e7eSjoerg   }
72806f32e7eSjoerg   llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
72906f32e7eSjoerg 
73006f32e7eSjoerg   Out << "Information for module file '" << getCurrentFile() << "':\n";
73106f32e7eSjoerg   auto &FileMgr = getCompilerInstance().getFileManager();
73206f32e7eSjoerg   auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
73306f32e7eSjoerg   StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
73406f32e7eSjoerg   bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
73506f32e7eSjoerg                 Magic[2] == 'C' && Magic[3] == 'H');
73606f32e7eSjoerg   Out << "  Module format: " << (IsRaw ? "raw" : "obj") << "\n";
73706f32e7eSjoerg 
73806f32e7eSjoerg   Preprocessor &PP = getCompilerInstance().getPreprocessor();
73906f32e7eSjoerg   DumpModuleInfoListener Listener(Out);
74006f32e7eSjoerg   HeaderSearchOptions &HSOpts =
74106f32e7eSjoerg       PP.getHeaderSearchInfo().getHeaderSearchOpts();
74206f32e7eSjoerg   ASTReader::readASTFileControlBlock(
74306f32e7eSjoerg       getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
74406f32e7eSjoerg       /*FindModuleFileExtensions=*/true, Listener,
74506f32e7eSjoerg       HSOpts.ModulesValidateDiagnosticOptions);
74606f32e7eSjoerg }
74706f32e7eSjoerg 
74806f32e7eSjoerg //===----------------------------------------------------------------------===//
74906f32e7eSjoerg // Preprocessor Actions
75006f32e7eSjoerg //===----------------------------------------------------------------------===//
75106f32e7eSjoerg 
ExecuteAction()75206f32e7eSjoerg void DumpRawTokensAction::ExecuteAction() {
75306f32e7eSjoerg   Preprocessor &PP = getCompilerInstance().getPreprocessor();
75406f32e7eSjoerg   SourceManager &SM = PP.getSourceManager();
75506f32e7eSjoerg 
75606f32e7eSjoerg   // Start lexing the specified input file.
757*13fbcb42Sjoerg   llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID());
75806f32e7eSjoerg   Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
75906f32e7eSjoerg   RawLex.SetKeepWhitespaceMode(true);
76006f32e7eSjoerg 
76106f32e7eSjoerg   Token RawTok;
76206f32e7eSjoerg   RawLex.LexFromRawLexer(RawTok);
76306f32e7eSjoerg   while (RawTok.isNot(tok::eof)) {
76406f32e7eSjoerg     PP.DumpToken(RawTok, true);
76506f32e7eSjoerg     llvm::errs() << "\n";
76606f32e7eSjoerg     RawLex.LexFromRawLexer(RawTok);
76706f32e7eSjoerg   }
76806f32e7eSjoerg }
76906f32e7eSjoerg 
ExecuteAction()77006f32e7eSjoerg void DumpTokensAction::ExecuteAction() {
77106f32e7eSjoerg   Preprocessor &PP = getCompilerInstance().getPreprocessor();
77206f32e7eSjoerg   // Start preprocessing the specified input file.
77306f32e7eSjoerg   Token Tok;
77406f32e7eSjoerg   PP.EnterMainSourceFile();
77506f32e7eSjoerg   do {
77606f32e7eSjoerg     PP.Lex(Tok);
77706f32e7eSjoerg     PP.DumpToken(Tok, true);
77806f32e7eSjoerg     llvm::errs() << "\n";
77906f32e7eSjoerg   } while (Tok.isNot(tok::eof));
78006f32e7eSjoerg }
78106f32e7eSjoerg 
ExecuteAction()78206f32e7eSjoerg void PreprocessOnlyAction::ExecuteAction() {
78306f32e7eSjoerg   Preprocessor &PP = getCompilerInstance().getPreprocessor();
78406f32e7eSjoerg 
78506f32e7eSjoerg   // Ignore unknown pragmas.
78606f32e7eSjoerg   PP.IgnorePragmas();
78706f32e7eSjoerg 
78806f32e7eSjoerg   Token Tok;
78906f32e7eSjoerg   // Start parsing the specified input file.
79006f32e7eSjoerg   PP.EnterMainSourceFile();
79106f32e7eSjoerg   do {
79206f32e7eSjoerg     PP.Lex(Tok);
79306f32e7eSjoerg   } while (Tok.isNot(tok::eof));
79406f32e7eSjoerg }
79506f32e7eSjoerg 
ExecuteAction()79606f32e7eSjoerg void PrintPreprocessedAction::ExecuteAction() {
79706f32e7eSjoerg   CompilerInstance &CI = getCompilerInstance();
79806f32e7eSjoerg   // Output file may need to be set to 'Binary', to avoid converting Unix style
799*13fbcb42Sjoerg   // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>) on Windows.
80006f32e7eSjoerg   //
80106f32e7eSjoerg   // Look to see what type of line endings the file uses. If there's a
80206f32e7eSjoerg   // CRLF, then we won't open the file up in binary mode. If there is
80306f32e7eSjoerg   // just an LF or CR, then we will open the file up in binary mode.
80406f32e7eSjoerg   // In this fashion, the output format should match the input format, unless
80506f32e7eSjoerg   // the input format has inconsistent line endings.
80606f32e7eSjoerg   //
80706f32e7eSjoerg   // This should be a relatively fast operation since most files won't have
80806f32e7eSjoerg   // all of their source code on a single line. However, that is still a
80906f32e7eSjoerg   // concern, so if we scan for too long, we'll just assume the file should
81006f32e7eSjoerg   // be opened in binary mode.
811*13fbcb42Sjoerg 
812*13fbcb42Sjoerg   bool BinaryMode = false;
813*13fbcb42Sjoerg   if (llvm::Triple(LLVM_HOST_TRIPLE).isOSWindows()) {
814*13fbcb42Sjoerg     BinaryMode = true;
81506f32e7eSjoerg     const SourceManager &SM = CI.getSourceManager();
816*13fbcb42Sjoerg     if (llvm::Optional<llvm::MemoryBufferRef> Buffer =
817*13fbcb42Sjoerg             SM.getBufferOrNone(SM.getMainFileID())) {
81806f32e7eSjoerg       const char *cur = Buffer->getBufferStart();
81906f32e7eSjoerg       const char *end = Buffer->getBufferEnd();
82006f32e7eSjoerg       const char *next = (cur != end) ? cur + 1 : end;
82106f32e7eSjoerg 
82206f32e7eSjoerg       // Limit ourselves to only scanning 256 characters into the source
82306f32e7eSjoerg       // file.  This is mostly a sanity check in case the file has no
82406f32e7eSjoerg       // newlines whatsoever.
825*13fbcb42Sjoerg       if (end - cur > 256)
826*13fbcb42Sjoerg         end = cur + 256;
82706f32e7eSjoerg 
82806f32e7eSjoerg       while (next < end) {
82906f32e7eSjoerg         if (*cur == 0x0D) {  // CR
83006f32e7eSjoerg           if (*next == 0x0A) // CRLF
83106f32e7eSjoerg             BinaryMode = false;
83206f32e7eSjoerg 
83306f32e7eSjoerg           break;
83406f32e7eSjoerg         } else if (*cur == 0x0A) // LF
83506f32e7eSjoerg           break;
83606f32e7eSjoerg 
83706f32e7eSjoerg         ++cur;
83806f32e7eSjoerg         ++next;
83906f32e7eSjoerg       }
84006f32e7eSjoerg     }
841*13fbcb42Sjoerg   }
84206f32e7eSjoerg 
84306f32e7eSjoerg   std::unique_ptr<raw_ostream> OS =
84406f32e7eSjoerg       CI.createDefaultOutputFile(BinaryMode, getCurrentFileOrBufferName());
84506f32e7eSjoerg   if (!OS) return;
84606f32e7eSjoerg 
84706f32e7eSjoerg   // If we're preprocessing a module map, start by dumping the contents of the
84806f32e7eSjoerg   // module itself before switching to the input buffer.
84906f32e7eSjoerg   auto &Input = getCurrentInput();
85006f32e7eSjoerg   if (Input.getKind().getFormat() == InputKind::ModuleMap) {
85106f32e7eSjoerg     if (Input.isFile()) {
85206f32e7eSjoerg       (*OS) << "# 1 \"";
85306f32e7eSjoerg       OS->write_escaped(Input.getFile());
85406f32e7eSjoerg       (*OS) << "\"\n";
85506f32e7eSjoerg     }
85606f32e7eSjoerg     getCurrentModule()->print(*OS);
85706f32e7eSjoerg     (*OS) << "#pragma clang module contents\n";
85806f32e7eSjoerg   }
85906f32e7eSjoerg 
86006f32e7eSjoerg   DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
86106f32e7eSjoerg                            CI.getPreprocessorOutputOpts());
86206f32e7eSjoerg }
86306f32e7eSjoerg 
ExecuteAction()86406f32e7eSjoerg void PrintPreambleAction::ExecuteAction() {
86506f32e7eSjoerg   switch (getCurrentFileKind().getLanguage()) {
86606f32e7eSjoerg   case Language::C:
86706f32e7eSjoerg   case Language::CXX:
86806f32e7eSjoerg   case Language::ObjC:
86906f32e7eSjoerg   case Language::ObjCXX:
87006f32e7eSjoerg   case Language::OpenCL:
871*13fbcb42Sjoerg   case Language::OpenCLCXX:
87206f32e7eSjoerg   case Language::CUDA:
87306f32e7eSjoerg   case Language::HIP:
87406f32e7eSjoerg     break;
87506f32e7eSjoerg 
87606f32e7eSjoerg   case Language::Unknown:
87706f32e7eSjoerg   case Language::Asm:
87806f32e7eSjoerg   case Language::LLVM_IR:
87906f32e7eSjoerg   case Language::RenderScript:
88006f32e7eSjoerg     // We can't do anything with these.
88106f32e7eSjoerg     return;
88206f32e7eSjoerg   }
88306f32e7eSjoerg 
88406f32e7eSjoerg   // We don't expect to find any #include directives in a preprocessed input.
88506f32e7eSjoerg   if (getCurrentFileKind().isPreprocessed())
88606f32e7eSjoerg     return;
88706f32e7eSjoerg 
88806f32e7eSjoerg   CompilerInstance &CI = getCompilerInstance();
88906f32e7eSjoerg   auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
89006f32e7eSjoerg   if (Buffer) {
89106f32e7eSjoerg     unsigned Preamble =
89206f32e7eSjoerg         Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).Size;
89306f32e7eSjoerg     llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
89406f32e7eSjoerg   }
89506f32e7eSjoerg }
89606f32e7eSjoerg 
ExecuteAction()89706f32e7eSjoerg void DumpCompilerOptionsAction::ExecuteAction() {
89806f32e7eSjoerg   CompilerInstance &CI = getCompilerInstance();
89906f32e7eSjoerg   std::unique_ptr<raw_ostream> OSP =
90006f32e7eSjoerg       CI.createDefaultOutputFile(false, getCurrentFile());
90106f32e7eSjoerg   if (!OSP)
90206f32e7eSjoerg     return;
90306f32e7eSjoerg 
90406f32e7eSjoerg   raw_ostream &OS = *OSP;
90506f32e7eSjoerg   const Preprocessor &PP = CI.getPreprocessor();
90606f32e7eSjoerg   const LangOptions &LangOpts = PP.getLangOpts();
90706f32e7eSjoerg 
90806f32e7eSjoerg   // FIXME: Rather than manually format the JSON (which is awkward due to
90906f32e7eSjoerg   // needing to remove trailing commas), this should make use of a JSON library.
91006f32e7eSjoerg   // FIXME: Instead of printing enums as an integral value and specifying the
91106f32e7eSjoerg   // type as a separate field, use introspection to print the enumerator.
91206f32e7eSjoerg 
91306f32e7eSjoerg   OS << "{\n";
91406f32e7eSjoerg   OS << "\n\"features\" : [\n";
91506f32e7eSjoerg   {
91606f32e7eSjoerg     llvm::SmallString<128> Str;
91706f32e7eSjoerg #define FEATURE(Name, Predicate)                                               \
91806f32e7eSjoerg   ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
91906f32e7eSjoerg       .toVector(Str);
92006f32e7eSjoerg #include "clang/Basic/Features.def"
92106f32e7eSjoerg #undef FEATURE
92206f32e7eSjoerg     // Remove the newline and comma from the last entry to ensure this remains
92306f32e7eSjoerg     // valid JSON.
92406f32e7eSjoerg     OS << Str.substr(0, Str.size() - 2);
92506f32e7eSjoerg   }
92606f32e7eSjoerg   OS << "\n],\n";
92706f32e7eSjoerg 
92806f32e7eSjoerg   OS << "\n\"extensions\" : [\n";
92906f32e7eSjoerg   {
93006f32e7eSjoerg     llvm::SmallString<128> Str;
93106f32e7eSjoerg #define EXTENSION(Name, Predicate)                                             \
93206f32e7eSjoerg   ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
93306f32e7eSjoerg       .toVector(Str);
93406f32e7eSjoerg #include "clang/Basic/Features.def"
93506f32e7eSjoerg #undef EXTENSION
93606f32e7eSjoerg     // Remove the newline and comma from the last entry to ensure this remains
93706f32e7eSjoerg     // valid JSON.
93806f32e7eSjoerg     OS << Str.substr(0, Str.size() - 2);
93906f32e7eSjoerg   }
94006f32e7eSjoerg   OS << "\n]\n";
94106f32e7eSjoerg 
94206f32e7eSjoerg   OS << "}";
94306f32e7eSjoerg }
94406f32e7eSjoerg 
ExecuteAction()94506f32e7eSjoerg void PrintDependencyDirectivesSourceMinimizerAction::ExecuteAction() {
94606f32e7eSjoerg   CompilerInstance &CI = getCompilerInstance();
94706f32e7eSjoerg   SourceManager &SM = CI.getPreprocessor().getSourceManager();
948*13fbcb42Sjoerg   llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID());
94906f32e7eSjoerg 
95006f32e7eSjoerg   llvm::SmallString<1024> Output;
95106f32e7eSjoerg   llvm::SmallVector<minimize_source_to_dependency_directives::Token, 32> Toks;
95206f32e7eSjoerg   if (minimizeSourceToDependencyDirectives(
953*13fbcb42Sjoerg           FromFile.getBuffer(), Output, Toks, &CI.getDiagnostics(),
95406f32e7eSjoerg           SM.getLocForStartOfFile(SM.getMainFileID()))) {
95506f32e7eSjoerg     assert(CI.getDiagnostics().hasErrorOccurred() &&
95606f32e7eSjoerg            "no errors reported for failure");
95706f32e7eSjoerg 
95806f32e7eSjoerg     // Preprocess the source when verifying the diagnostics to capture the
95906f32e7eSjoerg     // 'expected' comments.
96006f32e7eSjoerg     if (CI.getDiagnosticOpts().VerifyDiagnostics) {
96106f32e7eSjoerg       // Make sure we don't emit new diagnostics!
96206f32e7eSjoerg       CI.getDiagnostics().setSuppressAllDiagnostics(true);
96306f32e7eSjoerg       Preprocessor &PP = getCompilerInstance().getPreprocessor();
96406f32e7eSjoerg       PP.EnterMainSourceFile();
96506f32e7eSjoerg       Token Tok;
96606f32e7eSjoerg       do {
96706f32e7eSjoerg         PP.Lex(Tok);
96806f32e7eSjoerg       } while (Tok.isNot(tok::eof));
96906f32e7eSjoerg     }
97006f32e7eSjoerg     return;
97106f32e7eSjoerg   }
97206f32e7eSjoerg   llvm::outs() << Output;
97306f32e7eSjoerg }
974