clang  14.0.0git
FrontendActions.cpp
Go to the documentation of this file.
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 
10 #include "clang/AST/ASTConsumer.h"
12 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Frontend/Utils.h"
20 #include "clang/Lex/HeaderSearch.h"
21 #include "clang/Lex/Preprocessor.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/YAMLTraits.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <memory>
32 #include <system_error>
33 
34 using namespace clang;
35 
36 namespace {
37 CodeCompleteConsumer *GetCodeCompletionConsumer(CompilerInstance &CI) {
39  : nullptr;
40 }
41 
42 void EnsureSemaIsCreated(CompilerInstance &CI, FrontendAction &Action) {
43  if (Action.hasCodeCompletionSupport() &&
46 
47  if (!CI.hasSema())
49  GetCodeCompletionConsumer(CI));
50 }
51 } // namespace
52 
53 //===----------------------------------------------------------------------===//
54 // Custom Actions
55 //===----------------------------------------------------------------------===//
56 
57 std::unique_ptr<ASTConsumer>
58 InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
59  return std::make_unique<ASTConsumer>();
60 }
61 
62 void InitOnlyAction::ExecuteAction() {
63 }
64 
65 // Basically PreprocessOnlyAction::ExecuteAction.
66 void ReadPCHAndPreprocessAction::ExecuteAction() {
68 
69  // Ignore unknown pragmas.
70  PP.IgnorePragmas();
71 
72  Token Tok;
73  // Start parsing the specified input file.
75  do {
76  PP.Lex(Tok);
77  } while (Tok.isNot(tok::eof));
78 }
79 
80 std::unique_ptr<ASTConsumer>
81 ReadPCHAndPreprocessAction::CreateASTConsumer(CompilerInstance &CI,
82  StringRef InFile) {
83  return std::make_unique<ASTConsumer>();
84 }
85 
86 //===----------------------------------------------------------------------===//
87 // AST Consumer Actions
88 //===----------------------------------------------------------------------===//
89 
90 std::unique_ptr<ASTConsumer>
92  if (std::unique_ptr<raw_ostream> OS =
93  CI.createDefaultOutputFile(false, InFile))
94  return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter);
95  return nullptr;
96 }
97 
98 std::unique_ptr<ASTConsumer>
100  const FrontendOptions &Opts = CI.getFrontendOpts();
101  return CreateASTDumper(nullptr /*Dump to stdout.*/, Opts.ASTDumpFilter,
102  Opts.ASTDumpDecls, Opts.ASTDumpAll,
103  Opts.ASTDumpLookups, Opts.ASTDumpDeclTypes,
104  Opts.ASTDumpFormat);
105 }
106 
107 std::unique_ptr<ASTConsumer>
109  return CreateASTDeclNodeLister();
110 }
111 
112 std::unique_ptr<ASTConsumer>
114  return CreateASTViewer();
115 }
116 
117 std::unique_ptr<ASTConsumer>
119  std::string Sysroot;
120  if (!ComputeASTConsumerArguments(CI, /*ref*/ Sysroot))
121  return nullptr;
122 
123  std::string OutputFile;
124  std::unique_ptr<raw_pwrite_stream> OS =
125  CreateOutputFile(CI, InFile, /*ref*/ OutputFile);
126  if (!OS)
127  return nullptr;
128 
130  Sysroot.clear();
131 
132  const auto &FrontendOpts = CI.getFrontendOpts();
133  auto Buffer = std::make_shared<PCHBuffer>();
134  std::vector<std::unique_ptr<ASTConsumer>> Consumers;
135  Consumers.push_back(std::make_unique<PCHGenerator>(
136  CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer,
137  FrontendOpts.ModuleFileExtensions,
139  FrontendOpts.IncludeTimestamps, +CI.getLangOpts().CacheGeneratedPCH));
140  Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
141  CI, std::string(InFile), OutputFile, std::move(OS), Buffer));
142 
143  return std::make_unique<MultiplexConsumer>(std::move(Consumers));
144 }
145 
147  std::string &Sysroot) {
148  Sysroot = CI.getHeaderSearchOpts().Sysroot;
149  if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
150  CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
151  return false;
152  }
153 
154  return true;
155 }
156 
157 std::unique_ptr<llvm::raw_pwrite_stream>
159  std::string &OutputFile) {
160  // Because this is exposed via libclang we must disable RemoveFileOnSignal.
161  std::unique_ptr<raw_pwrite_stream> OS = CI.createDefaultOutputFile(
162  /*Binary=*/true, InFile, /*Extension=*/"", /*RemoveFileOnSignal=*/false);
163  if (!OS)
164  return nullptr;
165 
166  OutputFile = CI.getFrontendOpts().OutputFile;
167  return OS;
168 }
169 
171  if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors)
172  return false;
174 }
175 
177  CI.getLangOpts().CompilingPCH = true;
178  return true;
179 }
180 
181 std::unique_ptr<ASTConsumer>
183  StringRef InFile) {
184  std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
185  if (!OS)
186  return nullptr;
187 
188  std::string OutputFile = CI.getFrontendOpts().OutputFile;
189  std::string Sysroot;
190 
191  auto Buffer = std::make_shared<PCHBuffer>();
192  std::vector<std::unique_ptr<ASTConsumer>> Consumers;
193 
194  Consumers.push_back(std::make_unique<PCHGenerator>(
195  CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer,
197  /*AllowASTWithErrors=*/
199  /*IncludeTimestamps=*/
201  /*ShouldCacheASTInMemory=*/
203  Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
204  CI, std::string(InFile), OutputFile, std::move(OS), Buffer));
205  return std::make_unique<MultiplexConsumer>(std::move(Consumers));
206 }
207 
211 }
212 
213 bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
214  CompilerInstance &CI) {
215  if (!CI.getLangOpts().Modules) {
216  CI.getDiagnostics().Report(diag::err_module_build_requires_fmodules);
217  return false;
218  }
219 
221 }
222 
223 std::unique_ptr<raw_pwrite_stream>
224 GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
225  StringRef InFile) {
226  // If no output file was provided, figure out where this module would go
227  // in the module cache.
228  if (CI.getFrontendOpts().OutputFile.empty()) {
229  StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap;
230  if (ModuleMapFile.empty())
231  ModuleMapFile = InFile;
232 
236  ModuleMapFile);
237  }
238 
239  // Because this is exposed via libclang we must disable RemoveFileOnSignal.
240  return CI.createDefaultOutputFile(/*Binary=*/true, InFile, /*Extension=*/"",
241  /*RemoveFileOnSignal=*/false,
242  /*CreateMissingDirectories=*/true,
243  /*ForceUseTemporary=*/true);
244 }
245 
246 bool GenerateModuleInterfaceAction::BeginSourceFileAction(
247  CompilerInstance &CI) {
248  if (!CI.getLangOpts().ModulesTS && !CI.getLangOpts().CPlusPlusModules) {
249  CI.getDiagnostics().Report(diag::err_module_interface_requires_cpp_modules);
250  return false;
251  }
252 
253  CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
254 
256 }
257 
258 std::unique_ptr<raw_pwrite_stream>
259 GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
260  StringRef InFile) {
261  return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
262 }
263 
264 bool GenerateHeaderModuleAction::PrepareToExecuteAction(
265  CompilerInstance &CI) {
266  if (!CI.getLangOpts().Modules) {
267  CI.getDiagnostics().Report(diag::err_header_module_requires_modules);
268  return false;
269  }
270 
271  auto &Inputs = CI.getFrontendOpts().Inputs;
272  if (Inputs.empty())
274 
275  auto Kind = Inputs[0].getKind();
276 
277  // Convert the header file inputs into a single module input buffer.
278  SmallString<256> HeaderContents;
279  ModuleHeaders.reserve(Inputs.size());
280  for (const FrontendInputFile &FIF : Inputs) {
281  // FIXME: We should support re-compiling from an AST file.
282  if (FIF.getKind().getFormat() != InputKind::Source || !FIF.isFile()) {
283  CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
284  << (FIF.isFile() ? FIF.getFile()
285  : FIF.getBuffer().getBufferIdentifier());
286  return true;
287  }
288 
289  HeaderContents += "#include \"";
290  HeaderContents += FIF.getFile();
291  HeaderContents += "\"\n";
292  ModuleHeaders.push_back(std::string(FIF.getFile()));
293  }
294  Buffer = llvm::MemoryBuffer::getMemBufferCopy(
295  HeaderContents, Module::getModuleInputBufferName());
296 
297  // Set that buffer up as our "real" input.
298  Inputs.clear();
299  Inputs.push_back(
300  FrontendInputFile(Buffer->getMemBufferRef(), Kind, /*IsSystem*/ false));
301 
303 }
304 
305 bool GenerateHeaderModuleAction::BeginSourceFileAction(
306  CompilerInstance &CI) {
307  CI.getLangOpts().setCompilingModule(LangOptions::CMK_HeaderModule);
308 
309  // Synthesize a Module object for the given headers.
310  auto &HS = CI.getPreprocessor().getHeaderSearchInfo();
312  for (StringRef Name : ModuleHeaders) {
313  const DirectoryLookup *CurDir = nullptr;
315  Name, SourceLocation(), /*Angled*/ false, nullptr, CurDir, None,
316  nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
317  if (!FE) {
318  CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
319  << Name;
320  continue;
321  }
322  Headers.push_back(
323  {std::string(Name), std::string(Name), &FE->getFileEntry()});
324  }
326 
328 }
329 
330 std::unique_ptr<raw_pwrite_stream>
331 GenerateHeaderModuleAction::CreateOutputFile(CompilerInstance &CI,
332  StringRef InFile) {
333  return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
334 }
335 
337 }
338 
339 std::unique_ptr<ASTConsumer>
341  return std::make_unique<ASTConsumer>();
342 }
343 
344 std::unique_ptr<ASTConsumer>
346  StringRef InFile) {
347  return std::make_unique<ASTConsumer>();
348 }
349 
350 std::unique_ptr<ASTConsumer>
352  return std::make_unique<ASTConsumer>();
353 }
354 
358  const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
359  std::unique_ptr<ASTReader> Reader(new ASTReader(
360  CI.getPreprocessor(), CI.getModuleCache(), &CI.getASTContext(),
362  Sysroot.empty() ? "" : Sysroot.c_str(),
364  /*AllowASTWithCompilerErrors*/ false,
365  /*AllowConfigurationMismatch*/ true,
366  /*ValidateSystemInputs*/ true));
367 
368  Reader->ReadAST(getCurrentFile(),
371  SourceLocation(),
373 }
374 
375 namespace {
376 struct TemplightEntry {
377  std::string Name;
379  std::string Event;
380  std::string DefinitionLocation;
381  std::string PointOfInstantiation;
382 };
383 } // namespace
384 
385 namespace llvm {
386 namespace yaml {
387 template <> struct MappingTraits<TemplightEntry> {
388  static void mapping(IO &io, TemplightEntry &fields) {
389  io.mapRequired("name", fields.Name);
390  io.mapRequired("kind", fields.Kind);
391  io.mapRequired("event", fields.Event);
392  io.mapRequired("orig", fields.DefinitionLocation);
393  io.mapRequired("poi", fields.PointOfInstantiation);
394  }
395 };
396 } // namespace yaml
397 } // namespace llvm
398 
399 namespace {
400 class DefaultTemplateInstCallback : public TemplateInstantiationCallback {
401  using CodeSynthesisContext = Sema::CodeSynthesisContext;
402 
403 public:
404  void initialize(const Sema &) override {}
405 
406  void finalize(const Sema &) override {}
407 
408  void atTemplateBegin(const Sema &TheSema,
409  const CodeSynthesisContext &Inst) override {
410  displayTemplightEntry<true>(llvm::outs(), TheSema, Inst);
411  }
412 
413  void atTemplateEnd(const Sema &TheSema,
414  const CodeSynthesisContext &Inst) override {
415  displayTemplightEntry<false>(llvm::outs(), TheSema, Inst);
416  }
417 
418 private:
419  static std::string toString(CodeSynthesisContext::SynthesisKind Kind) {
420  switch (Kind) {
421  case CodeSynthesisContext::TemplateInstantiation:
422  return "TemplateInstantiation";
423  case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
424  return "DefaultTemplateArgumentInstantiation";
425  case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
426  return "DefaultFunctionArgumentInstantiation";
427  case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
428  return "ExplicitTemplateArgumentSubstitution";
429  case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
430  return "DeducedTemplateArgumentSubstitution";
431  case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
432  return "PriorTemplateArgumentSubstitution";
433  case CodeSynthesisContext::DefaultTemplateArgumentChecking:
434  return "DefaultTemplateArgumentChecking";
435  case CodeSynthesisContext::ExceptionSpecEvaluation:
436  return "ExceptionSpecEvaluation";
437  case CodeSynthesisContext::ExceptionSpecInstantiation:
438  return "ExceptionSpecInstantiation";
439  case CodeSynthesisContext::DeclaringSpecialMember:
440  return "DeclaringSpecialMember";
441  case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
442  return "DeclaringImplicitEqualityComparison";
443  case CodeSynthesisContext::DefiningSynthesizedFunction:
444  return "DefiningSynthesizedFunction";
445  case CodeSynthesisContext::RewritingOperatorAsSpaceship:
446  return "RewritingOperatorAsSpaceship";
447  case CodeSynthesisContext::Memoization:
448  return "Memoization";
449  case CodeSynthesisContext::ConstraintsCheck:
450  return "ConstraintsCheck";
451  case CodeSynthesisContext::ConstraintSubstitution:
452  return "ConstraintSubstitution";
453  case CodeSynthesisContext::ConstraintNormalization:
454  return "ConstraintNormalization";
455  case CodeSynthesisContext::ParameterMappingSubstitution:
456  return "ParameterMappingSubstitution";
457  case CodeSynthesisContext::RequirementInstantiation:
458  return "RequirementInstantiation";
459  case CodeSynthesisContext::NestedRequirementConstraintsCheck:
460  return "NestedRequirementConstraintsCheck";
461  case CodeSynthesisContext::InitializingStructuredBinding:
462  return "InitializingStructuredBinding";
463  case CodeSynthesisContext::MarkingClassDllexported:
464  return "MarkingClassDllexported";
465  }
466  return "";
467  }
468 
469  template <bool BeginInstantiation>
470  static void displayTemplightEntry(llvm::raw_ostream &Out, const Sema &TheSema,
471  const CodeSynthesisContext &Inst) {
472  std::string YAML;
473  {
474  llvm::raw_string_ostream OS(YAML);
475  llvm::yaml::Output YO(OS);
476  TemplightEntry Entry =
477  getTemplightEntry<BeginInstantiation>(TheSema, Inst);
478  llvm::yaml::EmptyContext Context;
479  llvm::yaml::yamlize(YO, Entry, true, Context);
480  }
481  Out << "---" << YAML << "\n";
482  }
483 
484  template <bool BeginInstantiation>
485  static TemplightEntry getTemplightEntry(const Sema &TheSema,
486  const CodeSynthesisContext &Inst) {
487  TemplightEntry Entry;
488  Entry.Kind = toString(Inst.Kind);
489  Entry.Event = BeginInstantiation ? "Begin" : "End";
490  if (auto *NamedTemplate = dyn_cast_or_null<NamedDecl>(Inst.Entity)) {
491  llvm::raw_string_ostream OS(Entry.Name);
492  PrintingPolicy Policy = TheSema.Context.getPrintingPolicy();
493  // FIXME: Also ask for FullyQualifiedNames?
494  Policy.SuppressDefaultTemplateArgs = false;
495  NamedTemplate->getNameForDiagnostic(OS, Policy, true);
496  const PresumedLoc DefLoc =
497  TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation());
498  if(!DefLoc.isInvalid())
499  Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" +
500  std::to_string(DefLoc.getLine()) + ":" +
501  std::to_string(DefLoc.getColumn());
502  }
503  const PresumedLoc PoiLoc =
504  TheSema.getSourceManager().getPresumedLoc(Inst.PointOfInstantiation);
505  if (!PoiLoc.isInvalid()) {
506  Entry.PointOfInstantiation = std::string(PoiLoc.getFilename()) + ":" +
507  std::to_string(PoiLoc.getLine()) + ":" +
508  std::to_string(PoiLoc.getColumn());
509  }
510  return Entry;
511  }
512 };
513 } // namespace
514 
515 std::unique_ptr<ASTConsumer>
517  return std::make_unique<ASTConsumer>();
518 }
519 
522 
523  // This part is normally done by ASTFrontEndAction, but needs to happen
524  // before Templight observers can be created
525  // FIXME: Move the truncation aspect of this into Sema, we delayed this till
526  // here so the source manager would be initialized.
527  EnsureSemaIsCreated(CI, *this);
528 
529  CI.getSema().TemplateInstCallbacks.push_back(
530  std::make_unique<DefaultTemplateInstCallback>());
532 }
533 
534 namespace {
535  /// AST reader listener that dumps module information for a module
536  /// file.
537  class DumpModuleInfoListener : public ASTReaderListener {
538  llvm::raw_ostream &Out;
539 
540  public:
541  DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
542 
543 #define DUMP_BOOLEAN(Value, Text) \
544  Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
545 
546  bool ReadFullVersionInformation(StringRef FullVersion) override {
547  Out.indent(2)
548  << "Generated by "
549  << (FullVersion == getClangFullRepositoryVersion()? "this"
550  : "a different")
551  << " Clang: " << FullVersion << "\n";
553  }
554 
555  void ReadModuleName(StringRef ModuleName) override {
556  Out.indent(2) << "Module name: " << ModuleName << "\n";
557  }
558  void ReadModuleMapFile(StringRef ModuleMapPath) override {
559  Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
560  }
561 
562  bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
563  bool AllowCompatibleDifferences) override {
564  Out.indent(2) << "Language options:\n";
565 #define LANGOPT(Name, Bits, Default, Description) \
566  DUMP_BOOLEAN(LangOpts.Name, Description);
567 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
568  Out.indent(4) << Description << ": " \
569  << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
570 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
571  Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
572 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
573 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
574 #include "clang/Basic/LangOptions.def"
575 
576  if (!LangOpts.ModuleFeatures.empty()) {
577  Out.indent(4) << "Module features:\n";
578  for (StringRef Feature : LangOpts.ModuleFeatures)
579  Out.indent(6) << Feature << "\n";
580  }
581 
582  return false;
583  }
584 
585  bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
586  bool AllowCompatibleDifferences) override {
587  Out.indent(2) << "Target options:\n";
588  Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
589  Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
590  Out.indent(4) << " TuneCPU: " << TargetOpts.TuneCPU << "\n";
591  Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
592 
593  if (!TargetOpts.FeaturesAsWritten.empty()) {
594  Out.indent(4) << "Target features:\n";
595  for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
596  I != N; ++I) {
597  Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
598  }
599  }
600 
601  return false;
602  }
603 
604  bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
605  bool Complain) override {
606  Out.indent(2) << "Diagnostic options:\n";
607 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
608 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
609  Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
610 #define VALUE_DIAGOPT(Name, Bits, Default) \
611  Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
612 #include "clang/Basic/DiagnosticOptions.def"
613 
614  Out.indent(4) << "Diagnostic flags:\n";
615  for (const std::string &Warning : DiagOpts->Warnings)
616  Out.indent(6) << "-W" << Warning << "\n";
617  for (const std::string &Remark : DiagOpts->Remarks)
618  Out.indent(6) << "-R" << Remark << "\n";
619 
620  return false;
621  }
622 
623  bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
624  StringRef SpecificModuleCachePath,
625  bool Complain) override {
626  Out.indent(2) << "Header search options:\n";
627  Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
628  Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
629  Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
631  "Use builtin include directories [-nobuiltininc]");
633  "Use standard system include directories [-nostdinc]");
635  "Use standard C++ include directories [-nostdinc++]");
636  DUMP_BOOLEAN(HSOpts.UseLibcxx,
637  "Use libc++ (rather than libstdc++) [-stdlib=]");
638  return false;
639  }
640 
641  bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
642  bool Complain,
643  std::string &SuggestedPredefines) override {
644  Out.indent(2) << "Preprocessor options:\n";
646  "Uses compiler/target-specific predefines [-undef]");
648  "Uses detailed preprocessing record (for indexing)");
649 
650  if (!PPOpts.Macros.empty()) {
651  Out.indent(4) << "Predefined macros:\n";
652  }
653 
654  for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
655  I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
656  I != IEnd; ++I) {
657  Out.indent(6);
658  if (I->second)
659  Out << "-U";
660  else
661  Out << "-D";
662  Out << I->first << "\n";
663  }
664  return false;
665  }
666 
667  /// Indicates that a particular module file extension has been read.
668  void readModuleFileExtension(
669  const ModuleFileExtensionMetadata &Metadata) override {
670  Out.indent(2) << "Module file extension '"
671  << Metadata.BlockName << "' " << Metadata.MajorVersion
672  << "." << Metadata.MinorVersion;
673  if (!Metadata.UserInfo.empty()) {
674  Out << ": ";
675  Out.write_escaped(Metadata.UserInfo);
676  }
677 
678  Out << "\n";
679  }
680 
681  /// Tells the \c ASTReaderListener that we want to receive the
682  /// input files of the AST file via \c visitInputFile.
683  bool needsInputFileVisitation() override { return true; }
684 
685  /// Tells the \c ASTReaderListener that we want to receive the
686  /// input files of the AST file via \c visitInputFile.
687  bool needsSystemInputFileVisitation() override { return true; }
688 
689  /// Indicates that the AST file contains particular input file.
690  ///
691  /// \returns true to continue receiving the next input file, false to stop.
692  bool visitInputFile(StringRef Filename, bool isSystem,
693  bool isOverridden, bool isExplicitModule) override {
694 
695  Out.indent(2) << "Input file: " << Filename;
696 
697  if (isSystem || isOverridden || isExplicitModule) {
698  Out << " [";
699  if (isSystem) {
700  Out << "System";
701  if (isOverridden || isExplicitModule)
702  Out << ", ";
703  }
704  if (isOverridden) {
705  Out << "Overridden";
706  if (isExplicitModule)
707  Out << ", ";
708  }
709  if (isExplicitModule)
710  Out << "ExplicitModule";
711 
712  Out << "]";
713  }
714 
715  Out << "\n";
716 
717  return true;
718  }
719 
720  /// Returns true if this \c ASTReaderListener wants to receive the
721  /// imports of the AST file via \c visitImport, false otherwise.
722  bool needsImportVisitation() const override { return true; }
723 
724  /// If needsImportVisitation returns \c true, this is called for each
725  /// AST file imported by this AST file.
726  void visitImport(StringRef ModuleName, StringRef Filename) override {
727  Out.indent(2) << "Imports module '" << ModuleName
728  << "': " << Filename.str() << "\n";
729  }
730 #undef DUMP_BOOLEAN
731  };
732 }
733 
735  // The Object file reader also supports raw ast files and there is no point in
736  // being strict about the module file format in -module-file-info mode.
737  CI.getHeaderSearchOpts().ModuleFormat = "obj";
738  return true;
739 }
740 
742  // Set up the output file.
743  std::unique_ptr<llvm::raw_fd_ostream> OutFile;
744  StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
745  if (!OutputFileName.empty() && OutputFileName != "-") {
746  std::error_code EC;
747  OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
748  llvm::sys::fs::OF_TextWithCRLF));
749  }
750  llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
751 
752  Out << "Information for module file '" << getCurrentFile() << "':\n";
753  auto &FileMgr = getCompilerInstance().getFileManager();
754  auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
755  StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
756  bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
757  Magic[2] == 'C' && Magic[3] == 'H');
758  Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n";
759 
761  DumpModuleInfoListener Listener(Out);
762  HeaderSearchOptions &HSOpts =
763  PP.getHeaderSearchInfo().getHeaderSearchOpts();
765  getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
766  /*FindModuleFileExtensions=*/true, Listener,
768 }
769 
770 //===----------------------------------------------------------------------===//
771 // Preprocessor Actions
772 //===----------------------------------------------------------------------===//
773 
777 
778  // Start lexing the specified input file.
779  llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID());
780  Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
781  RawLex.SetKeepWhitespaceMode(true);
782 
783  Token RawTok;
784  RawLex.LexFromRawLexer(RawTok);
785  while (RawTok.isNot(tok::eof)) {
786  PP.DumpToken(RawTok, true);
787  llvm::errs() << "\n";
788  RawLex.LexFromRawLexer(RawTok);
789  }
790 }
791 
794  // Start preprocessing the specified input file.
795  Token Tok;
796  PP.EnterMainSourceFile();
797  do {
798  PP.Lex(Tok);
799  PP.DumpToken(Tok, true);
800  llvm::errs() << "\n";
801  } while (Tok.isNot(tok::eof));
802 }
803 
806 
807  // Ignore unknown pragmas.
808  PP.IgnorePragmas();
809 
810  Token Tok;
811  // Start parsing the specified input file.
812  PP.EnterMainSourceFile();
813  do {
814  PP.Lex(Tok);
815  } while (Tok.isNot(tok::eof));
816 }
817 
820  // Output file may need to be set to 'Binary', to avoid converting Unix style
821  // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>) on Windows.
822  //
823  // Look to see what type of line endings the file uses. If there's a
824  // CRLF, then we won't open the file up in binary mode. If there is
825  // just an LF or CR, then we will open the file up in binary mode.
826  // In this fashion, the output format should match the input format, unless
827  // the input format has inconsistent line endings.
828  //
829  // This should be a relatively fast operation since most files won't have
830  // all of their source code on a single line. However, that is still a
831  // concern, so if we scan for too long, we'll just assume the file should
832  // be opened in binary mode.
833 
834  bool BinaryMode = false;
835  if (llvm::Triple(LLVM_HOST_TRIPLE).isOSWindows()) {
836  BinaryMode = true;
837  const SourceManager &SM = CI.getSourceManager();
839  SM.getBufferOrNone(SM.getMainFileID())) {
840  const char *cur = Buffer->getBufferStart();
841  const char *end = Buffer->getBufferEnd();
842  const char *next = (cur != end) ? cur + 1 : end;
843 
844  // Limit ourselves to only scanning 256 characters into the source
845  // file. This is mostly a check in case the file has no
846  // newlines whatsoever.
847  if (end - cur > 256)
848  end = cur + 256;
849 
850  while (next < end) {
851  if (*cur == 0x0D) { // CR
852  if (*next == 0x0A) // CRLF
853  BinaryMode = false;
854 
855  break;
856  } else if (*cur == 0x0A) // LF
857  break;
858 
859  ++cur;
860  ++next;
861  }
862  }
863  }
864 
865  std::unique_ptr<raw_ostream> OS =
867  if (!OS) return;
868 
869  // If we're preprocessing a module map, start by dumping the contents of the
870  // module itself before switching to the input buffer.
871  auto &Input = getCurrentInput();
872  if (Input.getKind().getFormat() == InputKind::ModuleMap) {
873  if (Input.isFile()) {
874  (*OS) << "# 1 \"";
875  OS->write_escaped(Input.getFile());
876  (*OS) << "\"\n";
877  }
878  getCurrentModule()->print(*OS);
879  (*OS) << "#pragma clang module contents\n";
880  }
881 
884 }
885 
887  switch (getCurrentFileKind().getLanguage()) {
888  case Language::C:
889  case Language::CXX:
890  case Language::ObjC:
891  case Language::ObjCXX:
892  case Language::OpenCL:
893  case Language::OpenCLCXX:
894  case Language::CUDA:
895  case Language::HIP:
896  break;
897 
898  case Language::Unknown:
899  case Language::Asm:
900  case Language::LLVM_IR:
902  // We can't do anything with these.
903  return;
904  }
905 
906  // We don't expect to find any #include directives in a preprocessed input.
907  if (getCurrentFileKind().isPreprocessed())
908  return;
909 
911  auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
912  if (Buffer) {
913  unsigned Preamble =
914  Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).Size;
915  llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
916  }
917 }
918 
919 void DumpCompilerOptionsAction::ExecuteAction() {
921  std::unique_ptr<raw_ostream> OSP =
923  if (!OSP)
924  return;
925 
926  raw_ostream &OS = *OSP;
927  const Preprocessor &PP = CI.getPreprocessor();
928  const LangOptions &LangOpts = PP.getLangOpts();
929 
930  // FIXME: Rather than manually format the JSON (which is awkward due to
931  // needing to remove trailing commas), this should make use of a JSON library.
932  // FIXME: Instead of printing enums as an integral value and specifying the
933  // type as a separate field, use introspection to print the enumerator.
934 
935  OS << "{\n";
936  OS << "\n\"features\" : [\n";
937  {
939 #define FEATURE(Name, Predicate) \
940  ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
941  .toVector(Str);
942 #include "clang/Basic/Features.def"
943 #undef FEATURE
944  // Remove the newline and comma from the last entry to ensure this remains
945  // valid JSON.
946  OS << Str.substr(0, Str.size() - 2);
947  }
948  OS << "\n],\n";
949 
950  OS << "\n\"extensions\" : [\n";
951  {
953 #define EXTENSION(Name, Predicate) \
954  ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
955  .toVector(Str);
956 #include "clang/Basic/Features.def"
957 #undef EXTENSION
958  // Remove the newline and comma from the last entry to ensure this remains
959  // valid JSON.
960  OS << Str.substr(0, Str.size() - 2);
961  }
962  OS << "\n]\n";
963 
964  OS << "}";
965 }
966 
970  llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID());
971 
975  FromFile.getBuffer(), Output, Toks, &CI.getDiagnostics(),
976  SM.getLocForStartOfFile(SM.getMainFileID()))) {
977  assert(CI.getDiagnostics().hasErrorOccurred() &&
978  "no errors reported for failure");
979 
980  // Preprocess the source when verifying the diagnostics to capture the
981  // 'expected' comments.
982  if (CI.getDiagnosticOpts().VerifyDiagnostics) {
983  // Make sure we don't emit new diagnostics!
986  PP.EnterMainSourceFile();
987  Token Tok;
988  do {
989  PP.Lex(Tok);
990  } while (Tok.isNot(tok::eof));
991  }
992  return;
993  }
994  llvm::outs() << Output;
995 }
996 
997 void GetDependenciesByModuleNameAction::ExecuteAction() {
999  Preprocessor &PP = CI.getPreprocessor();
1001  FileID MainFileID = SM.getMainFileID();
1002  SourceLocation FileStart = SM.getLocForStartOfFile(MainFileID);
1004  IdentifierInfo *ModuleID = PP.getIdentifierInfo(ModuleName);
1005  Path.push_back(std::make_pair(ModuleID, FileStart));
1006  auto ModResult = CI.loadModule(FileStart, Path, Module::Hidden, false);
1007  PPCallbacks *CB = PP.getPPCallbacks();
1008  CB->moduleImport(SourceLocation(), Path, ModResult);
1009 }
clang::Language::CUDA
@ CUDA
clang::CompilerInstance::hasSema
bool hasSema() const
Definition: CompilerInstance.h:503
clang::LangOptions::CurrentModule
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:343
clang::LangOptions::CMK_ModuleInterface
@ CMK_ModuleInterface
Compiling a C++ modules TS module interface unit.
Definition: LangOptions.h:94
llvm
Definition: Dominators.h:30
clang::CreateASTViewer
std::unique_ptr< ASTConsumer > CreateASTViewer()
Definition: ASTConsumers.cpp:215
clang::TemplightDumpAction::CreateASTConsumer
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
Definition: FrontendActions.cpp:516
clang::CompilerInstance::getPreprocessorOutputOpts
PreprocessorOutputOptions & getPreprocessorOutputOpts()
Definition: CompilerInstance.h:315
clang::initialize
void initialize(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema)
Definition: TemplateInstCallback.h:43
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::PreprocessorOptions
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
Definition: PreprocessorOptions.h:64
clang::PresumedLoc::getLine
unsigned getLine() const
Return the presumed line number of this location.
Definition: SourceLocation.h:337
clang::Preprocessor::getPPCallbacks
PPCallbacks * getPPCallbacks() const
Definition: Preprocessor.h:1057
clang::Preprocessor::Lex
void Lex(Token &Result)
Lex the next token for this preprocessor.
Definition: Preprocessor.cpp:888
clang::GeneratePCHAction::shouldEraseOutputFiles
bool shouldEraseOutputFiles() override
Callback at the end of processing a single input, to determine if the output files should be erased o...
Definition: FrontendActions.cpp:170
clang::PrintPreprocessedAction::ExecuteAction
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
Definition: FrontendActions.cpp:818
llvm::SmallVector
Definition: LLVM.h:38
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::minimizeSourceToDependencyDirectives
bool minimizeSourceToDependencyDirectives(llvm::StringRef Input, llvm::SmallVectorImpl< char > &Output, llvm::SmallVectorImpl< minimize_source_to_dependency_directives::Token > &Tokens, DiagnosticsEngine *Diags=nullptr, SourceLocation InputSourceLoc=SourceLocation())
Minimize the input down to the preprocessor directives that might have an effect on the dependencies ...
clang::PPCallbacks
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition: PPCallbacks.h:35
clang::Preprocessor::IgnorePragmas
void IgnorePragmas()
Install empty handlers for all pragmas (making them ignored).
Definition: Pragma.cpp:2187
TargetInfo.h
clang::ASTPrintAction::CreateASTConsumer
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
Definition: FrontendActions.cpp:91
clang::DumpModuleInfoAction::CreateASTConsumer
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
Definition: FrontendActions.cpp:345
clang::HeaderSearchOptions::UseStandardSystemIncludes
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
Definition: HeaderSearchOptions.h:185
clang::CompilerInstance::getLangOpts
LangOptions & getLangOpts()
Definition: CompilerInstance.h:301
Filename
StringRef Filename
Definition: Format.cpp:2379
clang::FrontendAction::getCurrentModule
Module * getCurrentModule() const
Definition: FrontendAction.cpp:144
clang::Language::OpenCLCXX
@ OpenCLCXX
clang::FrontendAction::hasCodeCompletionSupport
virtual bool hasCodeCompletionSupport() const
Does this action support use with code completion?
Definition: FrontendAction.h:200
clang::ASTReader::ARR_ConfigurationMismatch
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition: ASTReader.h:1552
clang::FrontendInputFile
An input file for the front end.
Definition: FrontendOptions.h:185
clang::Sema::getSourceManager
SourceManager & getSourceManager() const
Definition: Sema.h:1577
clang::PrintDependencyDirectivesSourceMinimizerAction::ExecuteAction
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
Definition: FrontendActions.cpp:967
clang::FrontendAction::BeginInvocation
virtual bool BeginInvocation(CompilerInstance &CI)
Callback before starting processing a single input, giving the opportunity to modify the CompilerInvo...
Definition: FrontendAction.h:79
llvm::Optional< FileEntryRef >
clang::SourceManager::getPresumedLoc
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
Definition: SourceManager.cpp:1515
clang::Sema::TemplateInstCallbacks
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained).
Definition: Sema.h:8895
clang::DiagnosticsEngine::setSuppressAllDiagnostics
void setSuppressAllDiagnostics(bool Val)
Suppress all diagnostics, to silence the front end when we know that we don't want any more diagnosti...
Definition: Diagnostic.h:690
clang::PrintingPolicy
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:59
clang::PreprocessorOptions::DetailedRecord
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
Definition: PreprocessorOptions.h:76
clang::Language::Asm
@ Asm
Assembly: we accept this only so that we can preprocess it.
ASTWriter.h
clang::Lexer::LexFromRawLexer
bool LexFromRawLexer(Token &Result)
LexFromRawLexer - Lex a token from a designated raw lexer (one with no associated preprocessor object...
Definition: Lexer.h:204
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
clang::HeaderSearchOptions::ModulesValidateDiagnosticOptions
unsigned ModulesValidateDiagnosticOptions
Definition: HeaderSearchOptions.h:211
clang::InputKind::Source
@ Source
Definition: FrontendOptions.h:154
clang::CompilerInstance::getPCHContainerReader
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
Definition: CompilerInstance.h:544
clang::CompilerInstance::createCodeCompletionConsumer
void createCodeCompletionConsumer()
Create a code completion consumer using the invocation; note that this will cause the source manager ...
Definition: CompilerInstance.cpp:709
clang::DumpModuleInfoAction::BeginInvocation
bool BeginInvocation(CompilerInstance &CI) override
Callback before starting processing a single input, giving the opportunity to modify the CompilerInvo...
Definition: FrontendActions.cpp:734
llvm::yaml::MappingTraits< TemplightEntry >::mapping
static void mapping(IO &io, TemplightEntry &fields)
Definition: FrontendActions.cpp:388
clang::DisableValidationForModuleKind::None
@ None
Perform validation, don't disable it.
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:626
clang::FrontendOptions::Inputs
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
Definition: FrontendOptions.h:386
clang::ParsedSourceLocation::FileName
std::string FileName
Definition: CommandLineSourceLoc.h:25
clang::Preprocessor::getLangOpts
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:960
clang::Sema::Context
ASTContext & Context
Definition: Sema.h:410
Preprocessor.h
clang::HeaderSearch
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Definition: HeaderSearch.h:162
clang::Lexer
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens.
Definition: Lexer.h:76
clang::DumpTokensAction::ExecuteAction
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
Definition: FrontendActions.cpp:792
clang::DumpModuleInfoAction::ExecuteAction
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
Definition: FrontendActions.cpp:741
clang::GeneratePCHAction::CreateOutputFile
static std::unique_ptr< llvm::raw_pwrite_stream > CreateOutputFile(CompilerInstance &CI, StringRef InFile, std::string &OutputFile)
Creates file to write the PCH into and returns a stream to write it into.
Definition: FrontendActions.cpp:158
clang::PrintingPolicy::SuppressDefaultTemplateArgs
unsigned SuppressDefaultTemplateArgs
When true, attempt to suppress template arguments that match the default argument for the parameter.
Definition: PrettyPrinter.h:189
clang::ModuleMap::createHeaderModule
Module * createHeaderModule(StringRef Name, ArrayRef< Module::Header > Headers)
Create a header module from the specified list of headers.
Definition: ModuleMap.cpp:881
clang::DumpRawTokensAction::ExecuteAction
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
Definition: FrontendActions.cpp:774
clang::CompilerInstance::getFileManager
FileManager & getFileManager() const
Return the current file manager to the caller.
Definition: CompilerInstance.h:404
clang::VerifyPCHAction::ExecuteAction
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
Definition: FrontendActions.cpp:355
clang::FrontendOptions::ASTDumpFormat
ASTDumpOutputFormat ASTDumpFormat
Specifies the output format of the AST.
Definition: FrontendOptions.h:313
clang::serialized_diags::Remark
@ Remark
Definition: SerializedDiagnostics.h:49
clang::Language::RenderScript
@ RenderScript
clang::FrontendOptions::ASTDumpDecls
unsigned ASTDumpDecls
Whether we include declaration dumps in AST dumps.
Definition: FrontendOptions.h:278
clang::GenerateModuleAction::shouldEraseOutputFiles
bool shouldEraseOutputFiles() override
Callback at the end of processing a single input, to determine if the output files should be erased o...
Definition: FrontendActions.cpp:208
clang::ASTReaderListener::ReadFullVersionInformation
virtual bool ReadFullVersionInformation(StringRef FullVersion)
Receives the full Clang version information.
Definition: ASTReader.h:122
clang::Module::Hidden
@ Hidden
All of the names in this module are hidden.
Definition: Module.h:314
clang::serialization::MK_Preamble
@ MK_Preamble
File is a PCH file treated as the preamble.
Definition: ModuleFile.h:53
clang::FrontendAction::getCurrentFileOrBufferName
StringRef getCurrentFileOrBufferName() const
Definition: FrontendAction.h:144
clang::FrontendOptions::OutputFile
std::string OutputFile
The output file, if any.
Definition: FrontendOptions.h:393
clang::FrontendOptions::ASTDumpFilter
std::string ASTDumpFilter
If given, filter dumped AST Decl nodes by this substring.
Definition: FrontendOptions.h:399
clang::PresumedLoc::getFilename
const char * getFilename() const
Return the presumed filename of this location.
Definition: SourceLocation.h:324
clang::HeaderSearchOptions::Sysroot
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
Definition: HeaderSearchOptions.h:100
clang::threadSafety::sx::toString
std::string toString(const til::SExpr *E)
Definition: ThreadSafetyCommon.h:89
clang::DiagnosticsEngine::hasErrorOccurred
bool hasErrorOccurred() const
Definition: Diagnostic.h:836
clang::LangOptions::CMK_HeaderModule
@ CMK_HeaderModule
Compiling a module from a list of header files.
Definition: LangOptions.h:91
clang::DirectoryLookup
DirectoryLookup - This class represents one entry in the search list that specifies the search order ...
Definition: DirectoryLookup.h:30
clang::CompilerInstance::getSema
Sema & getSema() const
Definition: CompilerInstance.h:505
clang::FrontendOptions
FrontendOptions - Options for controlling the behavior of the frontend.
Definition: FrontendOptions.h:228
clang::SyntaxOnlyAction::~SyntaxOnlyAction
~SyntaxOnlyAction() override
Definition: FrontendActions.cpp:336
Utils.h
clang::atTemplateEnd
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
Definition: TemplateInstCallback.h:71
TemplateInstCallback.h
clang::serialized_diags::Warning
@ Warning
Definition: SerializedDiagnostics.h:46
clang::LangOptions::ModuleFeatures
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
Definition: LangOptions.h:349
clang::TargetOptions::ABI
std::string ABI
If given, the name of the target ABI to use.
Definition: TargetOptions.h:45
clang::FrontendOptions::ASTDumpDeclTypes
unsigned ASTDumpDeclTypes
Whether we include declaration type dumps in AST dumps.
Definition: FrontendOptions.h:287
clang::HeaderSearchOptions::ModuleFormat
std::string ModuleFormat
The module/pch container format.
Definition: HeaderSearchOptions.h:125
clang::PreprocessorOptions::AllowPCHWithCompilerErrors
bool AllowPCHWithCompilerErrors
When true, a PCH with compiler errors will not be rejected.
Definition: PreprocessorOptions.h:107
clang::FrontendOptions::ASTDumpAll
unsigned ASTDumpAll
Whether we deserialize all decls when forming AST dumps.
Definition: FrontendOptions.h:281
clang::Sema::CodeSynthesisContext
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:8684
clang::FrontendAction::getCompilerInstance
CompilerInstance & getCompilerInstance() const
Definition: FrontendAction.h:119
llvm::SmallString
Definition: LLVM.h:37
clang::Language::C
@ C
Languages that the frontend can parse and compile.
clang::HeaderSearch::LookupFile
Optional< FileEntryRef > LookupFile(StringRef Filename, SourceLocation IncludeLoc, bool isAngled, const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir, ArrayRef< std::pair< const FileEntry *, const DirectoryEntry * >> Includers, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool *IsFrameworkFound, bool SkipCache=false, bool BuildSystemModule=false)
Given a "foo" or <foo> reference, look up the indicated file, return null on failure.
Definition: HeaderSearch.cpp:795
clang::atTemplateBegin
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
Definition: TemplateInstCallback.h:61
clang::PreambleBounds::Size
unsigned Size
Size of the preamble in bytes.
Definition: Lexer.h:60
clang::ModuleFileExtensionMetadata::MajorVersion
unsigned MajorVersion
The major version of the extension data.
Definition: ModuleFileExtension.h:44
clang::getClangFullRepositoryVersion
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:60
clang::PreprocessorOptions::UsePredefines
bool UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
Definition: PreprocessorOptions.h:72
clang::CreateASTPrinter
std::unique_ptr< ASTConsumer > CreateASTPrinter(std::unique_ptr< raw_ostream > OS, StringRef FilterString)
Definition: ASTConsumers.cpp:160
clang::PresumedLoc::getColumn
unsigned getColumn() const
Return the presumed column number of this location.
Definition: SourceLocation.h:345
clang::FrontendAction::shouldEraseOutputFiles
virtual bool shouldEraseOutputFiles()
Callback at the end of processing a single input, to determine if the output files should be erased o...
Definition: FrontendAction.cpp:1047
clang::CompilerInstance::getPreprocessor
Preprocessor & getPreprocessor() const
Return the current preprocessor.
Definition: CompilerInstance.h:444
clang::ASTReader::readASTFileControlBlock
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions)
Read the control block for the named AST file.
Definition: ASTReader.cpp:5149
clang::HeaderSearchOptions::UseLibcxx
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
Definition: HeaderSearchOptions.h:191
clang::FrontendAction::getTranslationUnitKind
virtual TranslationUnitKind getTranslationUnitKind()
For AST-based actions, the kind of translation unit we're handling.
Definition: FrontendAction.h:188
clang::CompilerInstance::getASTContext
ASTContext & getASTContext() const
Definition: CompilerInstance.h:464
clang::Preprocessor::EnterMainSourceFile
void EnterMainSourceFile()
Enter the specified FileID as the main source file, which implicitly adds the builtin defines etc.
Definition: Preprocessor.cpp:530
clang::GenerateModuleAction::CreateASTConsumer
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
Definition: FrontendActions.cpp:182
clang::FrontendOptions::AllowPCMWithCompilerErrors
unsigned AllowPCMWithCompilerErrors
Output (and read) PCM files regardless of compiler errors.
Definition: FrontendOptions.h:308
clang::FrontendOptions::ASTDumpLookups
unsigned ASTDumpLookups
Whether we include lookup table dumps in AST dumps.
Definition: FrontendOptions.h:284
clang::HeaderSearchOptions::UseStandardCXXIncludes
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
Definition: HeaderSearchOptions.h:188
clang::Token::isNot
bool isNot(tok::TokenKind K) const
Definition: Token.h:98
clang::CompilerInstance
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Definition: CompilerInstance.h:74
clang::CompilerInstance::getPreprocessorOpts
PreprocessorOptions & getPreprocessorOpts()
Definition: CompilerInstance.h:308
clang::FrontendAction::getCurrentFileKind
InputKind getCurrentFileKind() const
Definition: FrontendAction.h:151
clang::ASTDumpAction::CreateASTConsumer
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
Definition: FrontendActions.cpp:99
clang::ModuleFileExtensionMetadata::UserInfo
std::string UserInfo
A string containing additional user information that will be stored with the metadata.
Definition: ModuleFileExtension.h:51
clang::FrontendOptions::ModuleFileExtensions
std::vector< std::shared_ptr< ModuleFileExtension > > ModuleFileExtensions
The list of module file extensions.
Definition: FrontendOptions.h:420
clang::CompilerInstance::getModuleCache
InMemoryModuleCache & getModuleCache() const
Definition: CompilerInstance.h:819
clang::Preprocessor::getSourceManager
SourceManager & getSourceManager() const
Definition: Preprocessor.h:964
clang::FrontendAction::getCurrentInput
const FrontendInputFile & getCurrentInput() const
Definition: FrontendAction.h:135
clang::InputKind::ModuleMap
@ ModuleMap
Definition: FrontendOptions.h:155
clang::PresumedLoc::isInvalid
bool isInvalid() const
Return true if this object is invalid or uninitialized.
Definition: SourceLocation.h:318
clang::HeaderSearch::getCachedModuleFileName
std::string getCachedModuleFileName(Module *Module)
Retrieve the name of the cached module file that should be used to load the given module.
Definition: HeaderSearch.cpp:153
clang::GeneratePCHAction::ComputeASTConsumerArguments
static bool ComputeASTConsumerArguments(CompilerInstance &CI, std::string &Sysroot)
Compute the AST consumer arguments that will be used to create the PCHGenerator instance returned by ...
Definition: FrontendActions.cpp:146
LangStandard.h
clang::ASTViewAction::CreateASTConsumer
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
Definition: FrontendActions.cpp:113
clang::ASTContext::getPrintingPolicy
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:687
clang::Language::CXX
@ CXX
clang::Language::ObjCXX
@ ObjCXX
clang::CompilerInstance::hasCodeCompletionConsumer
bool hasCodeCompletionConsumer() const
Definition: CompilerInstance.h:560
clang::Language::LLVM_IR
@ LLVM_IR
LLVM IR: we accept this so that we can run the optimizer on it, and compile it to assembly or object ...
clang::FrontendAction::getCurrentFile
StringRef getCurrentFile() const
Definition: FrontendAction.h:139
HeaderSearch.h
clang::FileManager::getBufferForFile
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const FileEntry *Entry, bool isVolatile=false, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Definition: FileManager.cpp:521
clang::CompilerInstance::getPCHContainerWriter
const PCHContainerWriter & getPCHContainerWriter() const
Return the appropriate PCHContainerWriter depending on the current CodeGenOptions.
Definition: CompilerInstance.h:530
clang::ASTDeclListAction::CreateASTConsumer
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
Definition: FrontendActions.cpp:108
clang::PreprocessorOptions::PrecompiledPreambleBytes
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
Definition: PreprocessorOptions.h:125
clang::Sema
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:354
FrontendActions.h
clang::FrontendAction::PrepareToExecuteAction
virtual bool PrepareToExecuteAction(CompilerInstance &CI)
Prepare to execute the action on the given CompilerInstance.
Definition: FrontendAction.h:55
clang::PreprocessOnlyAction::ExecuteAction
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
Definition: FrontendActions.cpp:804
clang::Preprocessor::DumpToken
void DumpToken(const Token &Tok, bool DumpFlags=false) const
Print the token to stderr, used for debugging.
Definition: Preprocessor.cpp:231
clang::CodeCompleteConsumer
Abstract interface for a consumer of code-completion information.
Definition: CodeCompleteConsumer.h:1000
clang::Language::ObjC
@ ObjC
clang::PrintPreambleAction::ExecuteAction
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
Definition: FrontendActions.cpp:886
ASTConsumer.h
clang::ModuleFileExtensionMetadata::MinorVersion
unsigned MinorVersion
The minor version of the extension data.
Definition: ModuleFileExtension.h:47
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:84
clang::CreateASTDumper
std::unique_ptr< ASTConsumer > CreateASTDumper(std::unique_ptr< raw_ostream > OS, StringRef FilterString, bool DumpDecls, bool Deserialize, bool DumpLookups, bool DumpDeclTypes, ASTDumpOutputFormat Format)
Definition: ASTConsumers.cpp:167
clang::FrontendOptions::BuildingImplicitModule
unsigned BuildingImplicitModule
Whether we are performing an implicit module build.
Definition: FrontendOptions.h:290
clang::TargetOptions::TuneCPU
std::string TuneCPU
If given, the name of the target CPU to tune code for.
Definition: TargetOptions.h:39
clang::TargetOptions::CPU
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:58
clang::DoPrintPreprocessedInput
void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS, const PreprocessorOutputOptions &Opts)
DoPrintPreprocessedInput - Implement -E mode.
Definition: PrintPreprocessedOutput.cpp:945
clang::Lexer::SetKeepWhitespaceMode
void SetKeepWhitespaceMode(bool Val)
SetKeepWhitespaceMode - This method lets clients enable or disable whitespace retention mode.
Definition: Lexer.h:222
clang::ObjCPropertyAttribute::Kind
Kind
Definition: DeclObjCCommon.h:22
clang::TemplateInstantiationCallback
This is a base class for callbacks that will be notified at every template instantiation.
Definition: TemplateInstCallback.h:23
clang::ASTReader
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:342
clang::TargetOptions::FeaturesAsWritten
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line.
Definition: TargetOptions.h:54
clang::FrontendOptions::OriginalModuleMap
std::string OriginalModuleMap
When the input is a module map, the original module map file from which that map was inferred,...
Definition: FrontendOptions.h:390
clang::FrontendAction
Abstract base class for actions which can be performed by the frontend.
Definition: FrontendAction.h:36
clang::CompilerInstance::getDiagnosticOpts
DiagnosticOptions & getDiagnosticOpts()
Definition: CompilerInstance.h:270
clang
Definition: CalledOnceCheck.h:17
clang::PCHContainerWriter::CreatePCHContainerGenerator
virtual std::unique_ptr< ASTConsumer > CreatePCHContainerGenerator(CompilerInstance &CI, const std::string &MainFileName, const std::string &OutputFileName, std::unique_ptr< llvm::raw_pwrite_stream > OS, std::shared_ptr< PCHBuffer > Buffer) const =0
Return an ASTConsumer that can be chained with a PCHGenerator that produces a wrapper file format con...
clang::Module::getModuleInputBufferName
static StringRef getModuleInputBufferName()
Definition: Module.h:641
clang::ModuleFileExtensionMetadata::BlockName
std::string BlockName
The name used to identify this particular extension block within the resulting module file.
Definition: ModuleFileExtension.h:41
clang::CompilerInstance::createDefaultOutputFile
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
Definition: CompilerInstance.cpp:802
FrontendDiagnostic.h
clang::Module::print
void print(raw_ostream &OS, unsigned Indent=0, bool Dump=false) const
Print the module map for this module to the given stream.
Definition: Module.cpp:431
ASTReader.h
clang::TemplightDumpAction::ExecuteAction
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
Definition: FrontendActions.cpp:520
clang::ASTReaderListener
Abstract interface for callback invocations by the ASTReader.
Definition: ASTReader.h:114
clang::TargetOptions::Triple
std::string Triple
The name of the target triple to compile for.
Definition: TargetOptions.h:29
clang::CompilerInstance::getCodeCompletionConsumer
CodeCompleteConsumer & getCodeCompletionConsumer() const
Definition: CompilerInstance.h:562
clang::ModuleFileExtensionMetadata
Metadata for a module file extension.
Definition: ModuleFileExtension.h:36
clang::FileID
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Definition: SourceLocation.h:38
clang::SrcMgr::isSystem
bool isSystem(CharacteristicKind CK)
Determine whether a file / directory characteristic is for system code.
Definition: SourceManager.h:87
clang::FrontendAction::BeginSourceFileAction
virtual bool BeginSourceFileAction(CompilerInstance &CI)
Callback at the start of processing a single input.
Definition: FrontendAction.h:85
clang::ASTFrontendAction::ExecuteAction
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
Definition: FrontendAction.cpp:1055
clang::VerifyPCHAction::CreateASTConsumer
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
Definition: FrontendActions.cpp:351
CompilerInstance.h
clang::CompilerInstance::getFrontendOpts
FrontendOptions & getFrontendOpts()
Definition: CompilerInstance.h:284
clang::Language::Unknown
@ Unknown
clang::FrontendOptions::RelocatablePCH
unsigned RelocatablePCH
When generating PCH files, instruct the AST writer to create relocatable PCH files.
Definition: FrontendOptions.h:235
clang::CreateASTDeclNodeLister
std::unique_ptr< ASTConsumer > CreateASTDeclNodeLister()
Definition: ASTConsumers.cpp:178
clang::CompilerInstance::loadModule
ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective) override
Attempt to load the given module.
Definition: CompilerInstance.cpp:1935
clang::serialization::MK_PCH
@ MK_PCH
File is a PCH file treated as such.
Definition: ModuleFile.h:50
clang::HeaderSearchOptions::ResourceDir
std::string ResourceDir
The directory which holds the compiler resource files (builtin includes, etc.).
Definition: HeaderSearchOptions.h:110
clang::TargetOptions
Options for controlling the target.
Definition: TargetOptions.h:26
clang::comments::tok::eof
@ eof
Definition: CommentLexer.h:33
clang::Lexer::ComputePreamble
static PreambleBounds ComputePreamble(StringRef Buffer, const LangOptions &LangOpts, unsigned MaxLines=0)
Compute the preamble of the given file.
Definition: Lexer.cpp:589
clang::PresumedLoc
Represents an unpacked "presumed" location which can be presented to the user.
Definition: SourceLocation.h:302
clang::Language::HIP
@ HIP
clang::CompilerInstance::getDiagnostics
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
Definition: CompilerInstance.h:336
clang::CompilerInstance::getSourceManager
SourceManager & getSourceManager() const
Return the current source manager.
Definition: CompilerInstance.h:424
FileManager.h
clang::CompilerInstance::createSema
void createSema(TranslationUnitKind TUKind, CodeCompleteConsumer *CompletionConsumer)
Create the Sema object to be used for parsing.
Definition: CompilerInstance.cpp:748
PreprocessorOptions.h
clang::Preprocessor
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:130
SM
#define SM(sm)
Definition: Cuda.cpp:81
clang::Preprocessor::getHeaderSearchInfo
HeaderSearch & getHeaderSearchInfo() const
Definition: Preprocessor.h:965
DUMP_BOOLEAN
#define DUMP_BOOLEAN(Value, Text)
Definition: FrontendActions.cpp:543
clang::HeaderSearchOptions::UseBuiltinIncludes
unsigned UseBuiltinIncludes
Include the compiler builtin includes.
Definition: HeaderSearchOptions.h:182
clang::PreprocessorOptions::Macros
std::vector< std::pair< std::string, bool > > Macros
Definition: PreprocessorOptions.h:66
clang::finalize
void finalize(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema)
Definition: TemplateInstCallback.h:52
clang::HeaderSearch::getModuleMap
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:728
clang::FrontendOptions::CodeCompletionAt
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
Definition: FrontendOptions.h:402
clang::CompilerInstance::getHeaderSearchOpts
HeaderSearchOptions & getHeaderSearchOpts()
Definition: CompilerInstance.h:291
clang::PPCallbacks::moduleImport
virtual void moduleImport(SourceLocation ImportLoc, ModuleIdPath Path, const Module *Imported)
Callback invoked whenever there was an explicit module-import syntax.
Definition: PPCallbacks.h:166
clang::Preprocessor::getIdentifierInfo
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
Definition: Preprocessor.h:1243
llvm::IntrusiveRefCntPtr
Definition: LLVM.h:47
DependencyDirectivesSourceMinimizer.h
clang::ento::ObjKind::OS
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
clang::OpenCL
@ OpenCL
clang::HeaderSearchOptions
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
Definition: HeaderSearchOptions.h:68
clang::SkipFunctionBodiesScope::Preamble
@ Preamble
clang::DiagnosticsEngine::Report
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1523
clang::GeneratePCHAction::BeginSourceFileAction
bool BeginSourceFileAction(CompilerInstance &CI) override
Callback at the start of processing a single input.
Definition: FrontendActions.cpp:176
clang::SyntaxOnlyAction::CreateASTConsumer
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
Definition: FrontendActions.cpp:340
ASTConsumers.h
clang::GeneratePCHAction::CreateASTConsumer
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
Definition: FrontendActions.cpp:118
MultiplexConsumer.h