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

source code of clang/lib/Frontend/FrontendActions.cpp