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