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