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