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