clang  7.0.0svn
FrontendActions.cpp
Go to the documentation of this file.
1 //===--- FrontendActions.cpp ----------------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
11 #include "clang/AST/ASTConsumer.h"
17 #include "clang/Frontend/Utils.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/Preprocessor.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/YAMLTraits.h"
29 #include <memory>
30 #include <system_error>
31 
32 using namespace clang;
33 
34 namespace {
35 CodeCompleteConsumer *GetCodeCompletionConsumer(CompilerInstance &CI) {
37  : nullptr;
38 }
39 
40 void EnsureSemaIsCreated(CompilerInstance &CI, FrontendAction &Action) {
41  if (Action.hasCodeCompletionSupport() &&
44 
45  if (!CI.hasSema())
47  GetCodeCompletionConsumer(CI));
48 }
49 } // namespace
50 
51 //===----------------------------------------------------------------------===//
52 // Custom Actions
53 //===----------------------------------------------------------------------===//
54 
55 std::unique_ptr<ASTConsumer>
56 InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
57  return llvm::make_unique<ASTConsumer>();
58 }
59 
60 void InitOnlyAction::ExecuteAction() {
61 }
62 
63 //===----------------------------------------------------------------------===//
64 // AST Consumer Actions
65 //===----------------------------------------------------------------------===//
66 
67 std::unique_ptr<ASTConsumer>
69  if (std::unique_ptr<raw_ostream> OS =
70  CI.createDefaultOutputFile(false, InFile))
71  return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter);
72  return nullptr;
73 }
74 
75 std::unique_ptr<ASTConsumer>
77  return CreateASTDumper(nullptr /*Dump to stdout.*/,
82 }
83 
84 std::unique_ptr<ASTConsumer>
86  return CreateASTDeclNodeLister();
87 }
88 
89 std::unique_ptr<ASTConsumer>
91  return CreateASTViewer();
92 }
93 
94 std::unique_ptr<ASTConsumer>
96  StringRef InFile) {
97  return CreateDeclContextPrinter();
98 }
99 
100 std::unique_ptr<ASTConsumer>
102  std::string Sysroot;
103  if (!ComputeASTConsumerArguments(CI, /*ref*/ Sysroot))
104  return nullptr;
105 
106  std::string OutputFile;
107  std::unique_ptr<raw_pwrite_stream> OS =
108  CreateOutputFile(CI, InFile, /*ref*/ OutputFile);
109  if (!OS)
110  return nullptr;
111 
113  Sysroot.clear();
114 
115  auto Buffer = std::make_shared<PCHBuffer>();
116  std::vector<std::unique_ptr<ASTConsumer>> Consumers;
117  Consumers.push_back(llvm::make_unique<PCHGenerator>(
118  CI.getPreprocessor(), OutputFile, Sysroot,
120  /*AllowASTWithErrors*/CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
121  /*IncludeTimestamps*/
123  Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
124  CI, InFile, OutputFile, std::move(OS), Buffer));
125 
126  return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
127 }
128 
130  std::string &Sysroot) {
131  Sysroot = CI.getHeaderSearchOpts().Sysroot;
132  if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
133  CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
134  return false;
135  }
136 
137  return true;
138 }
139 
140 std::unique_ptr<llvm::raw_pwrite_stream>
142  std::string &OutputFile) {
143  // We use createOutputFile here because this is exposed via libclang, and we
144  // must disable the RemoveFileOnSignal behavior.
145  // We use a temporary to avoid race conditions.
146  std::unique_ptr<raw_pwrite_stream> OS =
147  CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
148  /*RemoveFileOnSignal=*/false, InFile,
149  /*Extension=*/"", /*useTemporary=*/true);
150  if (!OS)
151  return nullptr;
152 
153  OutputFile = CI.getFrontendOpts().OutputFile;
154  return OS;
155 }
156 
158  if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors)
159  return false;
161 }
162 
164  CI.getLangOpts().CompilingPCH = true;
165  return true;
166 }
167 
168 std::unique_ptr<ASTConsumer>
170  StringRef InFile) {
171  std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
172  if (!OS)
173  return nullptr;
174 
175  std::string OutputFile = CI.getFrontendOpts().OutputFile;
176  std::string Sysroot;
177 
178  auto Buffer = std::make_shared<PCHBuffer>();
179  std::vector<std::unique_ptr<ASTConsumer>> Consumers;
180 
181  Consumers.push_back(llvm::make_unique<PCHGenerator>(
182  CI.getPreprocessor(), OutputFile, Sysroot,
184  /*AllowASTWithErrors=*/false,
185  /*IncludeTimestamps=*/
187  Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
188  CI, InFile, OutputFile, std::move(OS), Buffer));
189  return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
190 }
191 
192 bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
193  CompilerInstance &CI) {
194  if (!CI.getLangOpts().Modules) {
195  CI.getDiagnostics().Report(diag::err_module_build_requires_fmodules);
196  return false;
197  }
198 
200 }
201 
202 std::unique_ptr<raw_pwrite_stream>
203 GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
204  StringRef InFile) {
205  // If no output file was provided, figure out where this module would go
206  // in the module cache.
207  if (CI.getFrontendOpts().OutputFile.empty()) {
208  StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap;
209  if (ModuleMapFile.empty())
210  ModuleMapFile = InFile;
211 
215  ModuleMapFile);
216  }
217 
218  // We use createOutputFile here because this is exposed via libclang, and we
219  // must disable the RemoveFileOnSignal behavior.
220  // We use a temporary to avoid race conditions.
221  return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
222  /*RemoveFileOnSignal=*/false, InFile,
223  /*Extension=*/"", /*useTemporary=*/true,
224  /*CreateMissingDirectories=*/true);
225 }
226 
227 bool GenerateModuleInterfaceAction::BeginSourceFileAction(
228  CompilerInstance &CI) {
229  if (!CI.getLangOpts().ModulesTS) {
230  CI.getDiagnostics().Report(diag::err_module_interface_requires_modules_ts);
231  return false;
232  }
233 
234  CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
235 
237 }
238 
239 std::unique_ptr<raw_pwrite_stream>
240 GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
241  StringRef InFile) {
242  return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
243 }
244 
246 }
247 
248 std::unique_ptr<ASTConsumer>
250  return llvm::make_unique<ASTConsumer>();
251 }
252 
253 std::unique_ptr<ASTConsumer>
255  StringRef InFile) {
256  return llvm::make_unique<ASTConsumer>();
257 }
258 
259 std::unique_ptr<ASTConsumer>
261  return llvm::make_unique<ASTConsumer>();
262 }
263 
267  const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
268  std::unique_ptr<ASTReader> Reader(new ASTReader(
271  Sysroot.empty() ? "" : Sysroot.c_str(),
272  /*DisableValidation*/ false,
273  /*AllowPCHWithCompilerErrors*/ false,
274  /*AllowConfigurationMismatch*/ true,
275  /*ValidateSystemInputs*/ true));
276 
277  Reader->ReadAST(getCurrentFile(),
278  Preamble ? serialization::MK_Preamble
280  SourceLocation(),
282 }
283 
284 namespace {
285 struct TemplightEntry {
286  std::string Name;
287  std::string Kind;
288  std::string Event;
289  std::string DefinitionLocation;
290  std::string PointOfInstantiation;
291 };
292 } // namespace
293 
294 namespace llvm {
295 namespace yaml {
296 template <> struct MappingTraits<TemplightEntry> {
297  static void mapping(IO &io, TemplightEntry &fields) {
298  io.mapRequired("name", fields.Name);
299  io.mapRequired("kind", fields.Kind);
300  io.mapRequired("event", fields.Event);
301  io.mapRequired("orig", fields.DefinitionLocation);
302  io.mapRequired("poi", fields.PointOfInstantiation);
303  }
304 };
305 } // namespace yaml
306 } // namespace llvm
307 
308 namespace {
309 class DefaultTemplateInstCallback : public TemplateInstantiationCallback {
310  using CodeSynthesisContext = Sema::CodeSynthesisContext;
311 
312 public:
313  void initialize(const Sema &) override {}
314 
315  void finalize(const Sema &) override {}
316 
317  void atTemplateBegin(const Sema &TheSema,
318  const CodeSynthesisContext &Inst) override {
319  displayTemplightEntry<true>(llvm::outs(), TheSema, Inst);
320  }
321 
322  void atTemplateEnd(const Sema &TheSema,
323  const CodeSynthesisContext &Inst) override {
324  displayTemplightEntry<false>(llvm::outs(), TheSema, Inst);
325  }
326 
327 private:
328  static std::string toString(CodeSynthesisContext::SynthesisKind Kind) {
329  switch (Kind) {
330  case CodeSynthesisContext::TemplateInstantiation:
331  return "TemplateInstantiation";
332  case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
333  return "DefaultTemplateArgumentInstantiation";
334  case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
335  return "DefaultFunctionArgumentInstantiation";
336  case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
337  return "ExplicitTemplateArgumentSubstitution";
338  case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
339  return "DeducedTemplateArgumentSubstitution";
340  case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
341  return "PriorTemplateArgumentSubstitution";
342  case CodeSynthesisContext::DefaultTemplateArgumentChecking:
343  return "DefaultTemplateArgumentChecking";
344  case CodeSynthesisContext::ExceptionSpecInstantiation:
345  return "ExceptionSpecInstantiation";
346  case CodeSynthesisContext::DeclaringSpecialMember:
347  return "DeclaringSpecialMember";
348  case CodeSynthesisContext::DefiningSynthesizedFunction:
349  return "DefiningSynthesizedFunction";
350  case CodeSynthesisContext::Memoization:
351  return "Memoization";
352  }
353  return "";
354  }
355 
356  template <bool BeginInstantiation>
357  static void displayTemplightEntry(llvm::raw_ostream &Out, const Sema &TheSema,
358  const CodeSynthesisContext &Inst) {
359  std::string YAML;
360  {
361  llvm::raw_string_ostream OS(YAML);
362  llvm::yaml::Output YO(OS);
363  TemplightEntry Entry =
364  getTemplightEntry<BeginInstantiation>(TheSema, Inst);
365  llvm::yaml::EmptyContext Context;
366  llvm::yaml::yamlize(YO, Entry, true, Context);
367  }
368  Out << "---" << YAML << "\n";
369  }
370 
371  template <bool BeginInstantiation>
372  static TemplightEntry getTemplightEntry(const Sema &TheSema,
373  const CodeSynthesisContext &Inst) {
374  TemplightEntry Entry;
375  Entry.Kind = toString(Inst.Kind);
376  Entry.Event = BeginInstantiation ? "Begin" : "End";
377  if (auto *NamedTemplate = dyn_cast_or_null<NamedDecl>(Inst.Entity)) {
378  llvm::raw_string_ostream OS(Entry.Name);
379  NamedTemplate->getNameForDiagnostic(OS, TheSema.getLangOpts(), true);
380  const PresumedLoc DefLoc =
381  TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation());
382  if(!DefLoc.isInvalid())
383  Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" +
384  std::to_string(DefLoc.getLine()) + ":" +
385  std::to_string(DefLoc.getColumn());
386  }
387  const PresumedLoc PoiLoc =
388  TheSema.getSourceManager().getPresumedLoc(Inst.PointOfInstantiation);
389  if (!PoiLoc.isInvalid()) {
390  Entry.PointOfInstantiation = std::string(PoiLoc.getFilename()) + ":" +
391  std::to_string(PoiLoc.getLine()) + ":" +
392  std::to_string(PoiLoc.getColumn());
393  }
394  return Entry;
395  }
396 };
397 } // namespace
398 
399 std::unique_ptr<ASTConsumer>
401  return llvm::make_unique<ASTConsumer>();
402 }
403 
406 
407  // This part is normally done by ASTFrontEndAction, but needs to happen
408  // before Templight observers can be created
409  // FIXME: Move the truncation aspect of this into Sema, we delayed this till
410  // here so the source manager would be initialized.
411  EnsureSemaIsCreated(CI, *this);
412 
413  CI.getSema().TemplateInstCallbacks.push_back(
414  llvm::make_unique<DefaultTemplateInstCallback>());
416 }
417 
418 namespace {
419  /// AST reader listener that dumps module information for a module
420  /// file.
421  class DumpModuleInfoListener : public ASTReaderListener {
422  llvm::raw_ostream &Out;
423 
424  public:
425  DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
426 
427 #define DUMP_BOOLEAN(Value, Text) \
428  Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
429 
430  bool ReadFullVersionInformation(StringRef FullVersion) override {
431  Out.indent(2)
432  << "Generated by "
433  << (FullVersion == getClangFullRepositoryVersion()? "this"
434  : "a different")
435  << " Clang: " << FullVersion << "\n";
437  }
438 
439  void ReadModuleName(StringRef ModuleName) override {
440  Out.indent(2) << "Module name: " << ModuleName << "\n";
441  }
442  void ReadModuleMapFile(StringRef ModuleMapPath) override {
443  Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
444  }
445 
446  bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
447  bool AllowCompatibleDifferences) override {
448  Out.indent(2) << "Language options:\n";
449 #define LANGOPT(Name, Bits, Default, Description) \
450  DUMP_BOOLEAN(LangOpts.Name, Description);
451 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
452  Out.indent(4) << Description << ": " \
453  << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
454 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
455  Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
456 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
457 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
458 #include "clang/Basic/LangOptions.def"
459 
460  if (!LangOpts.ModuleFeatures.empty()) {
461  Out.indent(4) << "Module features:\n";
462  for (StringRef Feature : LangOpts.ModuleFeatures)
463  Out.indent(6) << Feature << "\n";
464  }
465 
466  return false;
467  }
468 
469  bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
470  bool AllowCompatibleDifferences) override {
471  Out.indent(2) << "Target options:\n";
472  Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
473  Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
474  Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
475 
476  if (!TargetOpts.FeaturesAsWritten.empty()) {
477  Out.indent(4) << "Target features:\n";
478  for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
479  I != N; ++I) {
480  Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
481  }
482  }
483 
484  return false;
485  }
486 
487  bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
488  bool Complain) override {
489  Out.indent(2) << "Diagnostic options:\n";
490 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
491 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
492  Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
493 #define VALUE_DIAGOPT(Name, Bits, Default) \
494  Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
495 #include "clang/Basic/DiagnosticOptions.def"
496 
497  Out.indent(4) << "Diagnostic flags:\n";
498  for (const std::string &Warning : DiagOpts->Warnings)
499  Out.indent(6) << "-W" << Warning << "\n";
500  for (const std::string &Remark : DiagOpts->Remarks)
501  Out.indent(6) << "-R" << Remark << "\n";
502 
503  return false;
504  }
505 
506  bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
507  StringRef SpecificModuleCachePath,
508  bool Complain) override {
509  Out.indent(2) << "Header search options:\n";
510  Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
511  Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
512  Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
514  "Use builtin include directories [-nobuiltininc]");
516  "Use standard system include directories [-nostdinc]");
518  "Use standard C++ include directories [-nostdinc++]");
519  DUMP_BOOLEAN(HSOpts.UseLibcxx,
520  "Use libc++ (rather than libstdc++) [-stdlib=]");
521  return false;
522  }
523 
524  bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
525  bool Complain,
526  std::string &SuggestedPredefines) override {
527  Out.indent(2) << "Preprocessor options:\n";
529  "Uses compiler/target-specific predefines [-undef]");
531  "Uses detailed preprocessing record (for indexing)");
532 
533  if (!PPOpts.Macros.empty()) {
534  Out.indent(4) << "Predefined macros:\n";
535  }
536 
537  for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
538  I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
539  I != IEnd; ++I) {
540  Out.indent(6);
541  if (I->second)
542  Out << "-U";
543  else
544  Out << "-D";
545  Out << I->first << "\n";
546  }
547  return false;
548  }
549 
550  /// Indicates that a particular module file extension has been read.
551  void readModuleFileExtension(
552  const ModuleFileExtensionMetadata &Metadata) override {
553  Out.indent(2) << "Module file extension '"
554  << Metadata.BlockName << "' " << Metadata.MajorVersion
555  << "." << Metadata.MinorVersion;
556  if (!Metadata.UserInfo.empty()) {
557  Out << ": ";
558  Out.write_escaped(Metadata.UserInfo);
559  }
560 
561  Out << "\n";
562  }
563 #undef DUMP_BOOLEAN
564  };
565 }
566 
568  // The Object file reader also supports raw ast files and there is no point in
569  // being strict about the module file format in -module-file-info mode.
570  CI.getHeaderSearchOpts().ModuleFormat = "obj";
571  return true;
572 }
573 
575  // Set up the output file.
576  std::unique_ptr<llvm::raw_fd_ostream> OutFile;
577  StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
578  if (!OutputFileName.empty() && OutputFileName != "-") {
579  std::error_code EC;
580  OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
581  llvm::sys::fs::F_Text));
582  }
583  llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
584 
585  Out << "Information for module file '" << getCurrentFile() << "':\n";
586  auto &FileMgr = getCompilerInstance().getFileManager();
587  auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
588  StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
589  bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
590  Magic[2] == 'C' && Magic[3] == 'H');
591  Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n";
592 
594  DumpModuleInfoListener Listener(Out);
595  HeaderSearchOptions &HSOpts =
596  PP.getHeaderSearchInfo().getHeaderSearchOpts();
598  getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
599  /*FindModuleFileExtensions=*/true, Listener,
601 }
602 
603 //===----------------------------------------------------------------------===//
604 // Preprocessor Actions
605 //===----------------------------------------------------------------------===//
606 
610 
611  // Start lexing the specified input file.
612  const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
613  Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
614  RawLex.SetKeepWhitespaceMode(true);
615 
616  Token RawTok;
617  RawLex.LexFromRawLexer(RawTok);
618  while (RawTok.isNot(tok::eof)) {
619  PP.DumpToken(RawTok, true);
620  llvm::errs() << "\n";
621  RawLex.LexFromRawLexer(RawTok);
622  }
623 }
624 
627  // Start preprocessing the specified input file.
628  Token Tok;
629  PP.EnterMainSourceFile();
630  do {
631  PP.Lex(Tok);
632  PP.DumpToken(Tok, true);
633  llvm::errs() << "\n";
634  } while (Tok.isNot(tok::eof));
635 }
636 
639  std::unique_ptr<raw_pwrite_stream> OS =
641  if (!OS)
642  return;
643 
644  CacheTokens(CI.getPreprocessor(), OS.get());
645 }
646 
649 
650  // Ignore unknown pragmas.
651  PP.IgnorePragmas();
652 
653  Token Tok;
654  // Start parsing the specified input file.
655  PP.EnterMainSourceFile();
656  do {
657  PP.Lex(Tok);
658  } while (Tok.isNot(tok::eof));
659 }
660 
663  // Output file may need to be set to 'Binary', to avoid converting Unix style
664  // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
665  //
666  // Look to see what type of line endings the file uses. If there's a
667  // CRLF, then we won't open the file up in binary mode. If there is
668  // just an LF or CR, then we will open the file up in binary mode.
669  // In this fashion, the output format should match the input format, unless
670  // the input format has inconsistent line endings.
671  //
672  // This should be a relatively fast operation since most files won't have
673  // all of their source code on a single line. However, that is still a
674  // concern, so if we scan for too long, we'll just assume the file should
675  // be opened in binary mode.
676  bool BinaryMode = true;
677  bool InvalidFile = false;
678  const SourceManager& SM = CI.getSourceManager();
679  const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
680  &InvalidFile);
681  if (!InvalidFile) {
682  const char *cur = Buffer->getBufferStart();
683  const char *end = Buffer->getBufferEnd();
684  const char *next = (cur != end) ? cur + 1 : end;
685 
686  // Limit ourselves to only scanning 256 characters into the source
687  // file. This is mostly a sanity check in case the file has no
688  // newlines whatsoever.
689  if (end - cur > 256) end = cur + 256;
690 
691  while (next < end) {
692  if (*cur == 0x0D) { // CR
693  if (*next == 0x0A) // CRLF
694  BinaryMode = false;
695 
696  break;
697  } else if (*cur == 0x0A) // LF
698  break;
699 
700  ++cur;
701  ++next;
702  }
703  }
704 
705  std::unique_ptr<raw_ostream> OS =
706  CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
707  if (!OS) return;
708 
709  // If we're preprocessing a module map, start by dumping the contents of the
710  // module itself before switching to the input buffer.
711  auto &Input = getCurrentInput();
712  if (Input.getKind().getFormat() == InputKind::ModuleMap) {
713  if (Input.isFile()) {
714  (*OS) << "# 1 \"";
715  OS->write_escaped(Input.getFile());
716  (*OS) << "\"\n";
717  }
718  // FIXME: Include additional information here so that we don't need the
719  // original source files to exist on disk.
720  getCurrentModule()->print(*OS);
721  (*OS) << "#pragma clang module contents\n";
722  }
723 
726 }
727 
729  switch (getCurrentFileKind().getLanguage()) {
730  case InputKind::C:
731  case InputKind::CXX:
732  case InputKind::ObjC:
733  case InputKind::ObjCXX:
734  case InputKind::OpenCL:
735  case InputKind::CUDA:
736  case InputKind::HIP:
737  break;
738 
739  case InputKind::Unknown:
740  case InputKind::Asm:
741  case InputKind::LLVM_IR:
743  // We can't do anything with these.
744  return;
745  }
746 
747  // We don't expect to find any #include directives in a preprocessed input.
748  if (getCurrentFileKind().isPreprocessed())
749  return;
750 
752  auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
753  if (Buffer) {
754  unsigned Preamble =
755  Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).Size;
756  llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
757  }
758 }
759 
760 void DumpCompilerOptionsAction::ExecuteAction() {
762  std::unique_ptr<raw_ostream> OSP =
764  if (!OSP)
765  return;
766 
767  raw_ostream &OS = *OSP;
768  const Preprocessor &PP = CI.getPreprocessor();
769  const LangOptions &LangOpts = PP.getLangOpts();
770 
771  // FIXME: Rather than manually format the JSON (which is awkward due to
772  // needing to remove trailing commas), this should make use of a JSON library.
773  // FIXME: Instead of printing enums as an integral value and specifying the
774  // type as a separate field, use introspection to print the enumerator.
775 
776  OS << "{\n";
777  OS << "\n\"features\" : [\n";
778  {
780 #define FEATURE(Name, Predicate) \
781  ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
782  .toVector(Str);
783 #include "clang/Basic/Features.def"
784 #undef FEATURE
785  // Remove the newline and comma from the last entry to ensure this remains
786  // valid JSON.
787  OS << Str.substr(0, Str.size() - 2);
788  }
789  OS << "\n],\n";
790 
791  OS << "\n\"extensions\" : [\n";
792  {
794 #define EXTENSION(Name, Predicate) \
795  ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
796  .toVector(Str);
797 #include "clang/Basic/Features.def"
798 #undef EXTENSION
799  // Remove the newline and comma from the last entry to ensure this remains
800  // valid JSON.
801  OS << Str.substr(0, Str.size() - 2);
802  }
803  OS << "\n]\n";
804 
805  OS << "}";
806 }
std::string OutputFile
The output file, if any.
LangOptions & getLangOpts()
std::string OriginalModuleMap
When the input is a module map, the original module map file from which that map was inferred...
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
PreprocessorOptions & getPreprocessorOpts()
bool shouldEraseOutputFiles() override
Callback at the end of processing a single input, to determine if the output files should be erased o...
void createCodeCompletionConsumer()
Create a code completion consumer using the invocation; note that this will cause the source manager ...
std::vector< std::pair< std::string, bool > > Macros
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens...
Definition: Lexer.h:77
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained)...
Definition: Sema.h:7296
Defines the clang::FileManager interface and associated types.
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:30
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer...
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
void createSema(TranslationUnitKind TUKind, CodeCompleteConsumer *CompletionConsumer)
Create the Sema object to be used for parsing.
Abstract base class for actions which can be performed by the frontend.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1294
void finalize(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema)
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::string ASTDumpFilter
If given, filter dumped AST Decl nodes by this substring.
ASTContext & getASTContext() const
Compiling a C++ modules TS module interface unit.
Definition: LangOptions.h:77
void IgnorePragmas()
Install empty handlers for all pragmas (making them ignored).
Definition: Pragma.cpp:1814
Options for controlling the target.
Definition: TargetOptions.h:26
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:7127
virtual bool hasCodeCompletionSupport() const
Does this action support use with code completion?
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
Module * getCurrentModule() const
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
The client can handle an AST file that cannot load because it&#39;s compiled configuration doesn&#39;t match ...
Definition: ASTReader.h:1509
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:815
unsigned BuildingImplicitModule
Whether we are performing an implicit module build.
bool BeginSourceFileAction(CompilerInstance &CI) override
Callback at the start of processing a single input.
unsigned RelocatablePCH
When generating PCH files, instruct the AST writer to create relocatable PCH files.
Languages that the frontend can parse and compile.
static bool ComputeASTConsumerArguments(CompilerInstance &CI, std::string &Sysroot)
Compute the AST consumer arguments that will be used to create the PCHGenerator instance returned by ...
This is a base class for callbacks that will be notified at every template instantiation.
CompilerInstance & getCompilerInstance() const
std::string UserInfo
A string containing additional user information that will be stored with the metadata.
const PCHContainerWriter & getPCHContainerWriter() const
Return the appropriate PCHContainerWriter depending on the current CodeGenOptions.
HeaderSearch & getHeaderSearchInfo() const
Definition: Preprocessor.h:821
std::string getCachedModuleFileName(Module *Module)
Retrieve the name of the cached module file that should be used to load the given module...
FrontendOptions & getFrontendOpts()
const FormatToken & Tok
static void mapping(IO &io, TemplightEntry &fields)
PreprocessorOutputOptions & getPreprocessorOutputOpts()
std::string ResourceDir
The directory which holds the compiler resource files (builtin includes, etc.).
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
void CacheTokens(Preprocessor &PP, raw_pwrite_stream *OS)
Cache tokens for use with PCH. Note that this requires a seekable stream.
bool BeginInvocation(CompilerInstance &CI) override
Callback before starting processing a single input, giving the opportunity to modify the CompilerInvo...
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
#define DUMP_BOOLEAN(Value, Text)
const LangOptions & getLangOpts() const
Definition: Sema.h:1193
HeaderSearchOptions & getHeaderSearchOpts()
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer...
CodeCompleteConsumer & getCodeCompletionConsumer() const
std::vector< std::string > ModuleFeatures
The names of any features to enable in module &#39;requires&#39; decls in addition to the hard-coded list in ...
Definition: LangOptions.h:189
Encapsulates the information needed to find the file referenced by a #include or #include_next, (sub-)framework lookup, etc.
Definition: HeaderSearch.h:148
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:276
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:183
virtual bool shouldEraseOutputFiles()
Callback at the end of processing a single input, to determine if the output files should be erased o...
unsigned ASTDumpAll
Whether we deserialize all decls when forming AST dumps.
std::unique_ptr< ASTConsumer > CreateASTDumper(std::unique_ptr< raw_ostream > OS, StringRef FilterString, bool DumpDecls, bool Deserialize, bool DumpLookups)
void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS, const PreprocessorOutputOptions &Opts)
DoPrintPreprocessedInput - Implement -E mode.
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer...
static PreambleBounds ComputePreamble(StringRef Buffer, const LangOptions &LangOpts, unsigned MaxLines=0)
Compute the preamble of the given file.
Definition: Lexer.cpp:574
bool isInvalid() const
Return true if this object is invalid or uninitialized.
unsigned getLine() const
Return the presumed line number of this location.
void EnterMainSourceFile()
Enter the specified FileID as the main source file, which implicitly adds the builtin defines etc...
void print(raw_ostream &OS, unsigned Indent=0) const
Print the module map for this module to the given stream.
Definition: Module.cpp:373
Defines the clang::Preprocessor interface.
unsigned UseBuiltinIncludes
Include the compiler builtin includes.
Represents an unpacked "presumed" location which can be presented to the user.
InputKind getCurrentFileKind() const
const SourceManager & SM
Definition: Format.cpp:1468
unsigned MajorVersion
The major version of the extension data.
std::unique_ptr< raw_pwrite_stream > createOutputFile(StringRef OutputPath, bool Binary, bool RemoveFileOnSignal, StringRef BaseInput, StringRef Extension, bool UseTemporary, bool CreateMissingDirectories=false)
Create a new output file and add it to the list of tracked output files, optionally deriving the outp...
unsigned MinorVersion
The minor version of the extension data.
bool AllowPCHWithCompilerErrors
When true, a PCH with compiler errors will not be rejected.
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
SourceManager & getSourceManager() const
Definition: Preprocessor.h:819
const char * getFilename() const
Return the presumed filename of this location.
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
Kind
llvm::MemoryBuffer * getBuffer(FileID FID, SourceLocation Loc, bool *Invalid=nullptr) const
Return the buffer for the specified FileID.
std::string ABI
If given, the name of the target ABI to use.
Definition: TargetOptions.h:42
File is a PCH file treated as the preamble.
Definition: Module.h:54
unsigned getColumn() const
Return the presumed column number of this location.
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Encodes a location in the source.
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
Assembly: we accept this only so that we can preprocess it.
File is a PCH file treated as such.
Definition: Module.h:51
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
virtual TranslationUnitKind getTranslationUnitKind()
For AST-based actions, the kind of translation unit we&#39;re handling.
LLVM IR: we accept this so that we can run the optimizer on it, and compile it to assembly or object ...
unsigned IncludeTimestamps
Whether timestamps should be written to the produced PCH file.
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:90
void Lex(Token &Result)
Lex the next token for this preprocessor.
virtual bool ReadFullVersionInformation(StringRef FullVersion)
Receives the full Clang version information.
Definition: ASTReader.h:134
unsigned ASTDumpLookups
Whether we include lookup table dumps in AST dumps.
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line...
Definition: TargetOptions.h:51
void DumpToken(const Token &Tok, bool DumpFlags=false) const
Print the token to stderr, used for debugging.
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
Abstract interface for a consumer of code-completion information.
bool isNot(tok::TokenKind K) const
Definition: Token.h:96
Dataflow Directional Tag Classes.
FileManager & getFileManager() const
Return the current file manager to the caller.
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
const FrontendInputFile & getCurrentInput() const
bool UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:354
FileID getMainFileID() const
Returns the FileID of the main source file.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const FileEntry *Entry, bool isVolatile=false, bool ShouldCloseOpenFile=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
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...
SourceManager & getSourceManager() const
Return the current source manager.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
std::string BlockName
The name used to identify this particular extension block within the resulting module file...
std::string toString(const til::SExpr *E)
Abstract interface for callback invocations by the ASTReader.
Definition: ASTReader.h:126
std::unique_ptr< ASTConsumer > CreateDeclContextPrinter()
std::vector< std::shared_ptr< ModuleFileExtension > > ModuleFileExtensions
The list of module file extensions.
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="")
Create the default output file (from the invocation&#39;s options) and add it to the list of tracked outp...
std::unique_ptr< ASTConsumer > CreateASTViewer()
Metadata for a module file extension.
Preprocessor & getPreprocessor() const
Return the current preprocessor.
bool hasCodeCompletionConsumer() const
std::unique_ptr< ASTConsumer > CreateASTDeclNodeLister()
virtual bool BeginSourceFileAction(CompilerInstance &CI)
Callback at the start of processing a single input.
unsigned ASTDumpDecls
Whether we include declaration dumps in AST dumps.
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
SourceManager & getSourceManager() const
Definition: Sema.h:1198
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
std::pair< unsigned, bool > PrecompiledPreambleBytes
If non-zero, the implicit PCH include is actually a precompiled preamble that covers this number of b...
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
const StringRef getCurrentFile() const
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
void initialize(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema)
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:4707
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
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.
std::unique_ptr< ASTConsumer > CreateASTPrinter(std::unique_ptr< raw_ostream > OS, StringRef FilterString)
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
void SetKeepWhitespaceMode(bool Val)
SetKeepWhitespaceMode - This method lets clients enable or disable whitespace retention mode...
Definition: Lexer.h:213
std::string Triple
The name of the target triple to compile for.
Definition: TargetOptions.h:29
This class handles loading and caching of source files into memory.
std::string ModuleFormat
The module/pch container format.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:127
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer...