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