clang  8.0.0svn
FrontendAction.cpp
Go to the documentation of this file.
1 //===--- FrontendAction.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"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/DeclGroup.h"
14 #include "clang/Frontend/ASTUnit.h"
20 #include "clang/Frontend/Utils.h"
21 #include "clang/Lex/HeaderSearch.h"
23 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Parse/ParseAST.h"
29 #include "llvm/Support/BuryPointer.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/Timer.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <system_error>
36 using namespace clang;
37 
38 LLVM_INSTANTIATE_REGISTRY(FrontendPluginRegistry)
39 
40 namespace {
41 
42 class DelegatingDeserializationListener : public ASTDeserializationListener {
44  bool DeletePrevious;
45 
46 public:
47  explicit DelegatingDeserializationListener(
48  ASTDeserializationListener *Previous, bool DeletePrevious)
49  : Previous(Previous), DeletePrevious(DeletePrevious) {}
50  ~DelegatingDeserializationListener() override {
51  if (DeletePrevious)
52  delete Previous;
53  }
54 
55  void ReaderInitialized(ASTReader *Reader) override {
56  if (Previous)
57  Previous->ReaderInitialized(Reader);
58  }
59  void IdentifierRead(serialization::IdentID ID,
60  IdentifierInfo *II) override {
61  if (Previous)
62  Previous->IdentifierRead(ID, II);
63  }
64  void TypeRead(serialization::TypeIdx Idx, QualType T) override {
65  if (Previous)
66  Previous->TypeRead(Idx, T);
67  }
68  void DeclRead(serialization::DeclID ID, const Decl *D) override {
69  if (Previous)
70  Previous->DeclRead(ID, D);
71  }
72  void SelectorRead(serialization::SelectorID ID, Selector Sel) override {
73  if (Previous)
74  Previous->SelectorRead(ID, Sel);
75  }
76  void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
77  MacroDefinitionRecord *MD) override {
78  if (Previous)
79  Previous->MacroDefinitionRead(PPID, MD);
80  }
81 };
82 
83 /// Dumps deserialized declarations.
84 class DeserializedDeclsDumper : public DelegatingDeserializationListener {
85 public:
86  explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous,
87  bool DeletePrevious)
88  : DelegatingDeserializationListener(Previous, DeletePrevious) {}
89 
90  void DeclRead(serialization::DeclID ID, const Decl *D) override {
91  llvm::outs() << "PCH DECL: " << D->getDeclKindName();
92  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
93  llvm::outs() << " - ";
94  ND->printQualifiedName(llvm::outs());
95  }
96  llvm::outs() << "\n";
97 
98  DelegatingDeserializationListener::DeclRead(ID, D);
99  }
100 };
101 
102 /// Checks deserialized declarations and emits error if a name
103 /// matches one given in command-line using -error-on-deserialized-decl.
104 class DeserializedDeclsChecker : public DelegatingDeserializationListener {
105  ASTContext &Ctx;
106  std::set<std::string> NamesToCheck;
107 
108 public:
109  DeserializedDeclsChecker(ASTContext &Ctx,
110  const std::set<std::string> &NamesToCheck,
111  ASTDeserializationListener *Previous,
112  bool DeletePrevious)
113  : DelegatingDeserializationListener(Previous, DeletePrevious), Ctx(Ctx),
114  NamesToCheck(NamesToCheck) {}
115 
116  void DeclRead(serialization::DeclID ID, const Decl *D) override {
117  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
118  if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
119  unsigned DiagID
121  "%0 was deserialized");
122  Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
123  << ND->getNameAsString();
124  }
125 
126  DelegatingDeserializationListener::DeclRead(ID, D);
127  }
128 };
129 
130 } // end anonymous namespace
131 
132 FrontendAction::FrontendAction() : Instance(nullptr) {}
133 
135 
137  std::unique_ptr<ASTUnit> AST) {
138  this->CurrentInput = CurrentInput;
139  CurrentASTUnit = std::move(AST);
140 }
141 
145  CI.getLangOpts().CurrentModule, /*AllowSearch*/false);
146 }
147 
148 std::unique_ptr<ASTConsumer>
149 FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
150  StringRef InFile) {
151  std::unique_ptr<ASTConsumer> Consumer = CreateASTConsumer(CI, InFile);
152  if (!Consumer)
153  return nullptr;
154 
155  // If there are no registered plugins we don't need to wrap the consumer
156  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
157  return Consumer;
158 
159  // If this is a code completion run, avoid invoking the plugin consumers
160  if (CI.hasCodeCompletionConsumer())
161  return Consumer;
162 
163  // Collect the list of plugins that go before the main action (in Consumers)
164  // or after it (in AfterConsumers)
165  std::vector<std::unique_ptr<ASTConsumer>> Consumers;
166  std::vector<std::unique_ptr<ASTConsumer>> AfterConsumers;
167  for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
168  ie = FrontendPluginRegistry::end();
169  it != ie; ++it) {
170  std::unique_ptr<PluginASTAction> P = it->instantiate();
171  PluginASTAction::ActionType ActionType = P->getActionType();
172  if (ActionType == PluginASTAction::Cmdline) {
173  // This is O(|plugins| * |add_plugins|), but since both numbers are
174  // way below 50 in practice, that's ok.
175  for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
176  i != e; ++i) {
177  if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
179  break;
180  }
181  }
182  }
183  if ((ActionType == PluginASTAction::AddBeforeMainAction ||
184  ActionType == PluginASTAction::AddAfterMainAction) &&
185  P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs[it->getName()])) {
186  std::unique_ptr<ASTConsumer> PluginConsumer = P->CreateASTConsumer(CI, InFile);
187  if (ActionType == PluginASTAction::AddBeforeMainAction) {
188  Consumers.push_back(std::move(PluginConsumer));
189  } else {
190  AfterConsumers.push_back(std::move(PluginConsumer));
191  }
192  }
193  }
194 
195  // Add to Consumers the main consumer, then all the plugins that go after it
196  Consumers.push_back(std::move(Consumer));
197  for (auto &C : AfterConsumers) {
198  Consumers.push_back(std::move(C));
199  }
200 
201  return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
202 }
203 
204 /// For preprocessed files, if the first line is the linemarker and specifies
205 /// the original source file name, use that name as the input file name.
206 /// Returns the location of the first token after the line marker directive.
207 ///
208 /// \param CI The compiler instance.
209 /// \param InputFile Populated with the filename from the line marker.
210 /// \param IsModuleMap If \c true, add a line note corresponding to this line
211 /// directive. (We need to do this because the directive will not be
212 /// visited by the preprocessor.)
214  std::string &InputFile,
215  bool IsModuleMap = false) {
216  auto &SourceMgr = CI.getSourceManager();
217  auto MainFileID = SourceMgr.getMainFileID();
218 
219  bool Invalid = false;
220  const auto *MainFileBuf = SourceMgr.getBuffer(MainFileID, &Invalid);
221  if (Invalid)
222  return SourceLocation();
223 
224  std::unique_ptr<Lexer> RawLexer(
225  new Lexer(MainFileID, MainFileBuf, SourceMgr, CI.getLangOpts()));
226 
227  // If the first line has the syntax of
228  //
229  // # NUM "FILENAME"
230  //
231  // we use FILENAME as the input file name.
232  Token T;
233  if (RawLexer->LexFromRawLexer(T) || T.getKind() != tok::hash)
234  return SourceLocation();
235  if (RawLexer->LexFromRawLexer(T) || T.isAtStartOfLine() ||
236  T.getKind() != tok::numeric_constant)
237  return SourceLocation();
238 
239  unsigned LineNo;
240  SourceLocation LineNoLoc = T.getLocation();
241  if (IsModuleMap) {
242  llvm::SmallString<16> Buffer;
243  if (Lexer::getSpelling(LineNoLoc, Buffer, SourceMgr, CI.getLangOpts())
244  .getAsInteger(10, LineNo))
245  return SourceLocation();
246  }
247 
248  RawLexer->LexFromRawLexer(T);
249  if (T.isAtStartOfLine() || T.getKind() != tok::string_literal)
250  return SourceLocation();
251 
252  StringLiteralParser Literal(T, CI.getPreprocessor());
253  if (Literal.hadError)
254  return SourceLocation();
255  RawLexer->LexFromRawLexer(T);
256  if (T.isNot(tok::eof) && !T.isAtStartOfLine())
257  return SourceLocation();
258  InputFile = Literal.GetString().str();
259 
260  if (IsModuleMap)
262  LineNoLoc, LineNo, SourceMgr.getLineTableFilenameID(InputFile), false,
263  false, SrcMgr::C_User_ModuleMap);
264 
265  return T.getLocation();
266 }
267 
268 static SmallVectorImpl<char> &
269 operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
270  Includes.append(RHS.begin(), RHS.end());
271  return Includes;
272 }
273 
274 static void addHeaderInclude(StringRef HeaderName,
275  SmallVectorImpl<char> &Includes,
276  const LangOptions &LangOpts,
277  bool IsExternC) {
278  if (IsExternC && LangOpts.CPlusPlus)
279  Includes += "extern \"C\" {\n";
280  if (LangOpts.ObjC)
281  Includes += "#import \"";
282  else
283  Includes += "#include \"";
284 
285  Includes += HeaderName;
286 
287  Includes += "\"\n";
288  if (IsExternC && LangOpts.CPlusPlus)
289  Includes += "}\n";
290 }
291 
292 /// Collect the set of header includes needed to construct the given
293 /// module and update the TopHeaders file set of the module.
294 ///
295 /// \param Module The module we're collecting includes from.
296 ///
297 /// \param Includes Will be augmented with the set of \#includes or \#imports
298 /// needed to load all of the named headers.
299 static std::error_code collectModuleHeaderIncludes(
300  const LangOptions &LangOpts, FileManager &FileMgr, DiagnosticsEngine &Diag,
301  ModuleMap &ModMap, clang::Module *Module, SmallVectorImpl<char> &Includes) {
302  // Don't collect any headers for unavailable modules.
303  if (!Module->isAvailable())
304  return std::error_code();
305 
306  // Resolve all lazy header directives to header files.
307  ModMap.resolveHeaderDirectives(Module);
308 
309  // If any headers are missing, we can't build this module. In most cases,
310  // diagnostics for this should have already been produced; we only get here
311  // if explicit stat information was provided.
312  // FIXME: If the name resolves to a file with different stat information,
313  // produce a better diagnostic.
314  if (!Module->MissingHeaders.empty()) {
315  auto &MissingHeader = Module->MissingHeaders.front();
316  Diag.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
317  << MissingHeader.IsUmbrella << MissingHeader.FileName;
318  return std::error_code();
319  }
320 
321  // Add includes for each of these headers.
322  for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
323  for (Module::Header &H : Module->Headers[HK]) {
324  Module->addTopHeader(H.Entry);
325  // Use the path as specified in the module map file. We'll look for this
326  // file relative to the module build directory (the directory containing
327  // the module map file) so this will find the same file that we found
328  // while parsing the module map.
329  addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
330  }
331  }
332  // Note that Module->PrivateHeaders will not be a TopHeader.
333 
334  if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
335  Module->addTopHeader(UmbrellaHeader.Entry);
336  if (Module->Parent)
337  // Include the umbrella header for submodules.
338  addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
339  Module->IsExternC);
340  } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
341  // Add all of the headers we find in this subdirectory.
342  std::error_code EC;
343  SmallString<128> DirNative;
344  llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
345 
346  llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
347  for (llvm::vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
348  Dir != End && !EC; Dir.increment(EC)) {
349  // Check whether this entry has an extension typically associated with
350  // headers.
351  if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
352  .Cases(".h", ".H", ".hh", ".hpp", true)
353  .Default(false))
354  continue;
355 
356  const FileEntry *Header = FileMgr.getFile(Dir->path());
357  // FIXME: This shouldn't happen unless there is a file system race. Is
358  // that worth diagnosing?
359  if (!Header)
360  continue;
361 
362  // If this header is marked 'unavailable' in this module, don't include
363  // it.
364  if (ModMap.isHeaderUnavailableInModule(Header, Module))
365  continue;
366 
367  // Compute the relative path from the directory to this file.
368  SmallVector<StringRef, 16> Components;
369  auto PathIt = llvm::sys::path::rbegin(Dir->path());
370  for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
371  Components.push_back(*PathIt);
372  SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
373  for (auto It = Components.rbegin(), End = Components.rend(); It != End;
374  ++It)
375  llvm::sys::path::append(RelativeHeader, *It);
376 
377  // Include this header as part of the umbrella directory.
378  Module->addTopHeader(Header);
379  addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
380  }
381 
382  if (EC)
383  return EC;
384  }
385 
386  // Recurse into submodules.
388  SubEnd = Module->submodule_end();
389  Sub != SubEnd; ++Sub)
390  if (std::error_code Err = collectModuleHeaderIncludes(
391  LangOpts, FileMgr, Diag, ModMap, *Sub, Includes))
392  return Err;
393 
394  return std::error_code();
395 }
396 
397 static bool loadModuleMapForModuleBuild(CompilerInstance &CI, bool IsSystem,
398  bool IsPreprocessed,
399  std::string &PresumedModuleMapFile,
400  unsigned &Offset) {
401  auto &SrcMgr = CI.getSourceManager();
403 
404  // Map the current input to a file.
405  FileID ModuleMapID = SrcMgr.getMainFileID();
406  const FileEntry *ModuleMap = SrcMgr.getFileEntryForID(ModuleMapID);
407 
408  // If the module map is preprocessed, handle the initial line marker;
409  // line directives are not part of the module map syntax in general.
410  Offset = 0;
411  if (IsPreprocessed) {
412  SourceLocation EndOfLineMarker =
413  ReadOriginalFileName(CI, PresumedModuleMapFile, /*IsModuleMap*/ true);
414  if (EndOfLineMarker.isValid())
415  Offset = CI.getSourceManager().getDecomposedLoc(EndOfLineMarker).second;
416  }
417 
418  // Load the module map file.
419  if (HS.loadModuleMapFile(ModuleMap, IsSystem, ModuleMapID, &Offset,
420  PresumedModuleMapFile))
421  return true;
422 
423  if (SrcMgr.getBuffer(ModuleMapID)->getBufferSize() == Offset)
424  Offset = 0;
425 
426  return false;
427 }
428 
430  StringRef ModuleMapFilename) {
431  if (CI.getLangOpts().CurrentModule.empty()) {
432  CI.getDiagnostics().Report(diag::err_missing_module_name);
433 
434  // FIXME: Eventually, we could consider asking whether there was just
435  // a single module described in the module map, and use that as a
436  // default. Then it would be fairly trivial to just "compile" a module
437  // map with a single module (the common case).
438  return nullptr;
439  }
440 
441  // Dig out the module definition.
444  /*AllowSearch=*/false);
445  if (!M) {
446  CI.getDiagnostics().Report(diag::err_missing_module)
447  << CI.getLangOpts().CurrentModule << ModuleMapFilename;
448 
449  return nullptr;
450  }
451 
452  // Check whether we can build this module at all.
454  CI.getDiagnostics(), M))
455  return nullptr;
456 
457  // Inform the preprocessor that includes from within the input buffer should
458  // be resolved relative to the build directory of the module map file.
460 
461  // If the module was inferred from a different module map (via an expanded
462  // umbrella module definition), track that fact.
463  // FIXME: It would be preferable to fill this in as part of processing
464  // the module map, rather than adding it after the fact.
465  StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
466  if (!OriginalModuleMapName.empty()) {
467  auto *OriginalModuleMap =
468  CI.getFileManager().getFile(OriginalModuleMapName,
469  /*openFile*/ true);
470  if (!OriginalModuleMap) {
471  CI.getDiagnostics().Report(diag::err_module_map_not_found)
472  << OriginalModuleMapName;
473  return nullptr;
474  }
475  if (OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
477  M->IsInferred = true;
479  .setInferredModuleAllowedBy(M, OriginalModuleMap);
480  }
481  }
482 
483  // If we're being run from the command-line, the module build stack will not
484  // have been filled in yet, so complete it now in order to allow us to detect
485  // module cycles.
486  SourceManager &SourceMgr = CI.getSourceManager();
487  if (SourceMgr.getModuleBuildStack().empty())
489  FullSourceLoc(SourceLocation(), SourceMgr));
490  return M;
491 }
492 
493 /// Compute the input buffer that should be used to build the specified module.
494 static std::unique_ptr<llvm::MemoryBuffer>
496  FileManager &FileMgr = CI.getFileManager();
497 
498  // Collect the set of #includes we need to build the module.
499  SmallString<256> HeaderContents;
500  std::error_code Err = std::error_code();
501  if (Module::Header UmbrellaHeader = M->getUmbrellaHeader())
502  addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
503  CI.getLangOpts(), M->IsExternC);
505  CI.getLangOpts(), FileMgr, CI.getDiagnostics(),
507  HeaderContents);
508 
509  if (Err) {
510  CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
511  << M->getFullModuleName() << Err.message();
512  return nullptr;
513  }
514 
515  return llvm::MemoryBuffer::getMemBufferCopy(
516  HeaderContents, Module::getModuleInputBufferName());
517 }
518 
520  const FrontendInputFile &RealInput) {
521  FrontendInputFile Input(RealInput);
522  assert(!Instance && "Already processing a source file!");
523  assert(!Input.isEmpty() && "Unexpected empty filename!");
524  setCurrentInput(Input);
525  setCompilerInstance(&CI);
526 
527  bool HasBegunSourceFile = false;
528  bool ReplayASTFile = Input.getKind().getFormat() == InputKind::Precompiled &&
530  if (!BeginInvocation(CI))
531  goto failure;
532 
533  // If we're replaying the build of an AST file, import it and set up
534  // the initial state from its build.
535  if (ReplayASTFile) {
537 
538  // The AST unit populates its own diagnostics engine rather than ours.
540  new DiagnosticsEngine(Diags->getDiagnosticIDs(),
541  &Diags->getDiagnosticOptions()));
542  ASTDiags->setClient(Diags->getClient(), /*OwnsClient*/false);
543 
544  // FIXME: What if the input is a memory buffer?
545  StringRef InputFile = Input.getFile();
546 
547  std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
549  ASTDiags, CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs);
550  if (!AST)
551  goto failure;
552 
553  // Options relating to how we treat the input (but not what we do with it)
554  // are inherited from the AST unit.
555  CI.getHeaderSearchOpts() = AST->getHeaderSearchOpts();
556  CI.getPreprocessorOpts() = AST->getPreprocessorOpts();
557  CI.getLangOpts() = AST->getLangOpts();
558 
559  // Set the shared objects, these are reset when we finish processing the
560  // file, otherwise the CompilerInstance will happily destroy them.
561  CI.setFileManager(&AST->getFileManager());
563  CI.getSourceManager().initializeForReplay(AST->getSourceManager());
564 
565  // Preload all the module files loaded transitively by the AST unit. Also
566  // load all module map files that were parsed as part of building the AST
567  // unit.
568  if (auto ASTReader = AST->getASTReader()) {
569  auto &MM = ASTReader->getModuleManager();
570  auto &PrimaryModule = MM.getPrimaryModule();
571 
572  for (serialization::ModuleFile &MF : MM)
573  if (&MF != &PrimaryModule)
574  CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName);
575 
576  ASTReader->visitTopLevelModuleMaps(PrimaryModule,
577  [&](const FileEntry *FE) {
578  CI.getFrontendOpts().ModuleMapFiles.push_back(FE->getName());
579  });
580  }
581 
582  // Set up the input file for replay purposes.
583  auto Kind = AST->getInputKind();
584  if (Kind.getFormat() == InputKind::ModuleMap) {
585  Module *ASTModule =
586  AST->getPreprocessor().getHeaderSearchInfo().lookupModule(
587  AST->getLangOpts().CurrentModule, /*AllowSearch*/ false);
588  assert(ASTModule && "module file does not define its own module");
589  Input = FrontendInputFile(ASTModule->PresumedModuleMapFile, Kind);
590  } else {
591  auto &OldSM = AST->getSourceManager();
592  FileID ID = OldSM.getMainFileID();
593  if (auto *File = OldSM.getFileEntryForID(ID))
594  Input = FrontendInputFile(File->getName(), Kind);
595  else
596  Input = FrontendInputFile(OldSM.getBuffer(ID), Kind);
597  }
598  setCurrentInput(Input, std::move(AST));
599  }
600 
601  // AST files follow a very different path, since they share objects via the
602  // AST unit.
603  if (Input.getKind().getFormat() == InputKind::Precompiled) {
604  assert(!usesPreprocessorOnly() && "this case was handled above");
605  assert(hasASTFileSupport() &&
606  "This action does not have AST file support!");
607 
609 
610  // FIXME: What if the input is a memory buffer?
611  StringRef InputFile = Input.getFile();
612 
613  std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
614  InputFile, CI.getPCHContainerReader(), ASTUnit::LoadEverything, Diags,
615  CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs);
616 
617  if (!AST)
618  goto failure;
619 
620  // Inform the diagnostic client we are processing a source file.
621  CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
622  HasBegunSourceFile = true;
623 
624  // Set the shared objects, these are reset when we finish processing the
625  // file, otherwise the CompilerInstance will happily destroy them.
626  CI.setFileManager(&AST->getFileManager());
627  CI.setSourceManager(&AST->getSourceManager());
628  CI.setPreprocessor(AST->getPreprocessorPtr());
629  Preprocessor &PP = CI.getPreprocessor();
631  PP.getLangOpts());
632  CI.setASTContext(&AST->getASTContext());
633 
634  setCurrentInput(Input, std::move(AST));
635 
636  // Initialize the action.
637  if (!BeginSourceFileAction(CI))
638  goto failure;
639 
640  // Create the AST consumer.
641  CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
642  if (!CI.hasASTConsumer())
643  goto failure;
644 
645  return true;
646  }
647 
648  // Set up the file and source managers, if needed.
649  if (!CI.hasFileManager()) {
650  if (!CI.createFileManager()) {
651  goto failure;
652  }
653  }
654  if (!CI.hasSourceManager())
656 
657  // Set up embedding for any specified files. Do this before we load any
658  // source files, including the primary module map for the compilation.
659  for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
660  if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
662  else
663  CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
664  }
667 
668  // IR files bypass the rest of initialization.
669  if (Input.getKind().getLanguage() == InputKind::LLVM_IR) {
670  assert(hasIRSupport() &&
671  "This action does not have IR file support!");
672 
673  // Inform the diagnostic client we are processing a source file.
674  CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
675  HasBegunSourceFile = true;
676 
677  // Initialize the action.
678  if (!BeginSourceFileAction(CI))
679  goto failure;
680 
681  // Initialize the main file entry.
682  if (!CI.InitializeSourceManager(CurrentInput))
683  goto failure;
684 
685  return true;
686  }
687 
688  // If the implicit PCH include is actually a directory, rather than
689  // a single file, search for a suitable PCH file in that directory.
690  if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
691  FileManager &FileMgr = CI.getFileManager();
693  StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
694  std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
695  if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
696  std::error_code EC;
697  SmallString<128> DirNative;
698  llvm::sys::path::native(PCHDir->getName(), DirNative);
699  bool Found = false;
700  llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
701  for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
702  DirEnd;
703  Dir != DirEnd && !EC; Dir.increment(EC)) {
704  // Check whether this is an acceptable AST file.
706  Dir->path(), FileMgr, CI.getPCHContainerReader(),
708  SpecificModuleCachePath)) {
709  PPOpts.ImplicitPCHInclude = Dir->path();
710  Found = true;
711  break;
712  }
713  }
714 
715  if (!Found) {
716  CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
717  goto failure;
718  }
719  }
720  }
721 
722  // Set up the preprocessor if needed. When parsing model files the
723  // preprocessor of the original source is reused.
724  if (!isModelParsingAction())
726 
727  // Inform the diagnostic client we are processing a source file.
729  &CI.getPreprocessor());
730  HasBegunSourceFile = true;
731 
732  // Initialize the main file entry.
733  if (!CI.InitializeSourceManager(Input))
734  goto failure;
735 
736  // For module map files, we first parse the module map and synthesize a
737  // "<module-includes>" buffer before more conventional processing.
738  if (Input.getKind().getFormat() == InputKind::ModuleMap) {
739  CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
740 
741  std::string PresumedModuleMapFile;
742  unsigned OffsetToContents;
743  if (loadModuleMapForModuleBuild(CI, Input.isSystem(),
744  Input.isPreprocessed(),
745  PresumedModuleMapFile, OffsetToContents))
746  goto failure;
747 
748  auto *CurrentModule = prepareToBuildModule(CI, Input.getFile());
749  if (!CurrentModule)
750  goto failure;
751 
752  CurrentModule->PresumedModuleMapFile = PresumedModuleMapFile;
753 
754  if (OffsetToContents)
755  // If the module contents are in the same file, skip to them.
756  CI.getPreprocessor().setSkipMainFilePreamble(OffsetToContents, true);
757  else {
758  // Otherwise, convert the module description to a suitable input buffer.
759  auto Buffer = getInputBufferForModule(CI, CurrentModule);
760  if (!Buffer)
761  goto failure;
762 
763  // Reinitialize the main file entry to refer to the new input.
764  auto Kind = CurrentModule->IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
765  auto &SourceMgr = CI.getSourceManager();
766  auto BufferID = SourceMgr.createFileID(std::move(Buffer), Kind);
767  assert(BufferID.isValid() && "couldn't creaate module buffer ID");
768  SourceMgr.setMainFileID(BufferID);
769  }
770  }
771 
772  // Initialize the action.
773  if (!BeginSourceFileAction(CI))
774  goto failure;
775 
776  // If we were asked to load any module map files, do so now.
777  for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
778  if (auto *File = CI.getFileManager().getFile(Filename))
780  File, /*IsSystem*/false);
781  else
782  CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
783  }
784 
785  // Add a module declaration scope so that modules from -fmodule-map-file
786  // arguments may shadow modules found implicitly in search paths.
787  CI.getPreprocessor()
789  .getModuleMap()
791 
792  // Create the AST context and consumer unless this is a preprocessor only
793  // action.
794  if (!usesPreprocessorOnly()) {
795  // Parsing a model file should reuse the existing ASTContext.
796  if (!isModelParsingAction())
797  CI.createASTContext();
798 
799  // For preprocessed files, check if the first line specifies the original
800  // source file name with a linemarker.
801  std::string PresumedInputFile = getCurrentFileOrBufferName();
802  if (Input.isPreprocessed())
803  ReadOriginalFileName(CI, PresumedInputFile);
804 
805  std::unique_ptr<ASTConsumer> Consumer =
806  CreateWrappedASTConsumer(CI, PresumedInputFile);
807  if (!Consumer)
808  goto failure;
809 
810  // FIXME: should not overwrite ASTMutationListener when parsing model files?
811  if (!isModelParsingAction())
812  CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
813 
814  if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
815  // Convert headers to PCH and chain them.
816  IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
817  source = createChainedIncludesSource(CI, FinalReader);
818  if (!source)
819  goto failure;
820  CI.setModuleManager(static_cast<ASTReader *>(FinalReader.get()));
821  CI.getASTContext().setExternalSource(source);
822  } else if (CI.getLangOpts().Modules ||
823  !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
824  // Use PCM or PCH.
825  assert(hasPCHSupport() && "This action does not have PCH support!");
826  ASTDeserializationListener *DeserialListener =
827  Consumer->GetASTDeserializationListener();
828  bool DeleteDeserialListener = false;
830  DeserialListener = new DeserializedDeclsDumper(DeserialListener,
831  DeleteDeserialListener);
832  DeleteDeserialListener = true;
833  }
835  DeserialListener = new DeserializedDeclsChecker(
836  CI.getASTContext(),
838  DeserialListener, DeleteDeserialListener);
839  DeleteDeserialListener = true;
840  }
841  if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
845  CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, DeserialListener,
846  DeleteDeserialListener);
847  if (!CI.getASTContext().getExternalSource())
848  goto failure;
849  }
850  // If modules are enabled, create the module manager before creating
851  // any builtins, so that all declarations know that they might be
852  // extended by an external source.
853  if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
855  CI.createModuleManager();
856  CI.getModuleManager()->setDeserializationListener(DeserialListener,
857  DeleteDeserialListener);
858  }
859  }
860 
861  CI.setASTConsumer(std::move(Consumer));
862  if (!CI.hasASTConsumer())
863  goto failure;
864  }
865 
866  // Initialize built-in info as long as we aren't using an external AST
867  // source.
868  if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
870  Preprocessor &PP = CI.getPreprocessor();
872  PP.getLangOpts());
873  } else {
874  // FIXME: If this is a problem, recover from it by creating a multiplex
875  // source.
876  assert((!CI.getLangOpts().Modules || CI.getModuleManager()) &&
877  "modules enabled but created an external source that "
878  "doesn't support modules");
879  }
880 
881  // If we were asked to load any module files, do so now.
882  for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
883  if (!CI.loadModuleFile(ModuleFile))
884  goto failure;
885 
886  // If there is a layout overrides file, attach an external AST source that
887  // provides the layouts from that file.
888  if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
891  Override(new LayoutOverrideSource(
893  CI.getASTContext().setExternalSource(Override);
894  }
895 
896  return true;
897 
898  // If we failed, reset state since the client will not end up calling the
899  // matching EndSourceFile().
900 failure:
901  if (HasBegunSourceFile)
903  CI.clearOutputFiles(/*EraseFiles=*/true);
904  CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
906  setCompilerInstance(nullptr);
907  return false;
908 }
909 
912 
913  if (CI.hasFrontendTimer()) {
914  llvm::TimeRegion Timer(CI.getFrontendTimer());
915  ExecuteAction();
916  }
917  else ExecuteAction();
918 
919  // If we are supposed to rebuild the global module index, do so now unless
920  // there were any module-build failures.
921  if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
922  CI.hasPreprocessor()) {
923  StringRef Cache =
925  if (!Cache.empty())
928  }
929 
930  return true;
931 }
932 
935 
936  // Inform the diagnostic client we are done with this source file.
938 
939  // Inform the preprocessor we are done.
940  if (CI.hasPreprocessor())
942 
943  // Finalize the action.
945 
946  // Sema references the ast consumer, so reset sema first.
947  //
948  // FIXME: There is more per-file stuff we could just drop here?
949  bool DisableFree = CI.getFrontendOpts().DisableFree;
950  if (DisableFree) {
951  CI.resetAndLeakSema();
953  llvm::BuryPointer(CI.takeASTConsumer().get());
954  } else {
955  CI.setSema(nullptr);
956  CI.setASTContext(nullptr);
957  CI.setASTConsumer(nullptr);
958  }
959 
960  if (CI.getFrontendOpts().ShowStats) {
961  llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
966  llvm::errs() << "\n";
967  }
968 
969  // Cleanup the output streams, and erase the output files if instructed by the
970  // FrontendAction.
971  CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
972 
973  if (isCurrentFileAST()) {
974  if (DisableFree) {
978  llvm::BuryPointer(std::move(CurrentASTUnit));
979  } else {
980  CI.setPreprocessor(nullptr);
981  CI.setSourceManager(nullptr);
982  CI.setFileManager(nullptr);
983  }
984  }
985 
986  setCompilerInstance(nullptr);
988  CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
989 }
990 
993 }
994 
995 //===----------------------------------------------------------------------===//
996 // Utility Actions
997 //===----------------------------------------------------------------------===//
998 
1001  if (!CI.hasPreprocessor())
1002  return;
1003 
1004  // FIXME: Move the truncation aspect of this into Sema, we delayed this till
1005  // here so the source manager would be initialized.
1006  if (hasCodeCompletionSupport() &&
1009 
1010  // Use a code completion consumer?
1011  CodeCompleteConsumer *CompletionConsumer = nullptr;
1012  if (CI.hasCodeCompletionConsumer())
1013  CompletionConsumer = &CI.getCodeCompletionConsumer();
1014 
1015  if (!CI.hasSema())
1016  CI.createSema(getTranslationUnitKind(), CompletionConsumer);
1017 
1020 }
1021 
1022 void PluginASTAction::anchor() { }
1023 
1024 std::unique_ptr<ASTConsumer>
1026  StringRef InFile) {
1027  llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
1028 }
1029 
1030 std::unique_ptr<ASTConsumer>
1032  StringRef InFile) {
1033  return WrappedAction->CreateASTConsumer(CI, InFile);
1034 }
1036  return WrappedAction->BeginInvocation(CI);
1037 }
1039  WrappedAction->setCurrentInput(getCurrentInput());
1040  WrappedAction->setCompilerInstance(&CI);
1041  auto Ret = WrappedAction->BeginSourceFileAction(CI);
1042  // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
1043  setCurrentInput(WrappedAction->getCurrentInput());
1044  return Ret;
1045 }
1047  WrappedAction->ExecuteAction();
1048 }
1050  WrappedAction->EndSourceFileAction();
1051 }
1052 
1054  return WrappedAction->usesPreprocessorOnly();
1055 }
1057  return WrappedAction->getTranslationUnitKind();
1058 }
1060  return WrappedAction->hasPCHSupport();
1061 }
1063  return WrappedAction->hasASTFileSupport();
1064 }
1066  return WrappedAction->hasIRSupport();
1067 }
1069  return WrappedAction->hasCodeCompletionSupport();
1070 }
1071 
1073  std::unique_ptr<FrontendAction> WrappedAction)
1074  : WrappedAction(std::move(WrappedAction)) {}
1075 
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
Definition: ASTContext.cpp:921
Defines the clang::ASTContext interface.
static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts, const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts, StringRef ExistingModuleCachePath)
Determine whether the given AST file is acceptable to load into a translation unit with the given lan...
Definition: ASTReader.cpp:4933
static unsigned getSpelling(const Token &Tok, const char *&Buffer, const SourceManager &SourceMgr, const LangOptions &LangOpts, bool *Invalid=nullptr)
getSpelling - This method is used to get the spelling of a token into a preallocated buffer...
Definition: Lexer.cpp:389
void setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap)
Definition: ModuleMap.cpp:1220
LangOptions & getLangOpts()
std::string OriginalModuleMap
When the input is a module map, the original module map file from which that map was inferred...
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
PreprocessorOptions & getPreprocessorOpts()
void createCodeCompletionConsumer()
Create a code completion consumer using the invocation; note that this will cause the source manager ...
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens...
Definition: Lexer.h:77
bool hasErrorOccurred() const
Definition: Diagnostic.h:744
Smart pointer class that efficiently represents Objective-C method names.
SmallVector< UnresolvedHeaderDirective, 1 > MissingHeaders
Headers that are mentioned in the module map file but could not be found on the file system...
Definition: Module.h:188
A (possibly-)qualified type.
Definition: Type.h:638
const char * getDeclKindName() const
Definition: DeclBase.cpp:123
std::vector< Module * >::iterator submodule_iterator
Definition: Module.h:553
Implements support for file system lookup, file system caching, and directory search management...
Definition: FileManager.h:122
IntrusiveRefCntPtr< ExternalSemaSource > createChainedIncludesSource(CompilerInstance &CI, IntrusiveRefCntPtr< ExternalSemaSource > &Reader)
The ChainedIncludesSource class converts headers to chained PCHs in memory, mainly for testing...
void PrintStats() const
Print some statistics to stderr that indicate how well the hashing is doing.
void EndSourceFile()
Perform any per-file post processing, deallocate per-file objects, and run statistics and output file...
submodule_iterator submodule_begin()
Definition: Module.h:556
TypePropertyCache< Private > Cache
Definition: Type.cpp:3494
virtual bool hasIRSupport() const
Does this action support use with IR files?
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer...
Format getFormat() const
unsigned IsExternC
Whether this is an &#39;extern "C"&#39; module (which implicitly puts all headers in it within an &#39;extern "C"...
Definition: Module.h:231
void createSema(TranslationUnitKind TUKind, CodeCompleteConsumer *CompletionConsumer)
Create the Sema object to be used for parsing.
Load everything, including Sema.
Definition: ASTUnit.h:671
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
void EndSourceFile()
Inform the preprocessor callbacks that processing is complete.
StringRef P
virtual bool usesPreprocessorOnly() const =0
Does this action only use the preprocessor?
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Provide a default implementation which returns aborts; this method should never be called by Frontend...
virtual bool hasASTFileSupport() const
Does this action support use with AST files?
DiagnosticsEngine & getDiagnostics() const
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1292
bool InitializeSourceManager(const FrontendInputFile &Input)
InitializeSourceManager - Initialize the source manager to set InputFile as the main file...
virtual void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II)
An identifier was deserialized from the AST file.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
static std::unique_ptr< ASTUnit > LoadFromASTFile(const std::string &Filename, const PCHContainerReader &PCHContainerRdr, WhatToLoad ToLoad, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, const FileSystemOptions &FileSystemOpts, bool UseDebugInfo=false, bool OnlyLocalDecls=false, ArrayRef< RemappedFile > RemappedFiles=None, bool CaptureDiagnostics=false, bool AllowPCHWithCompilerErrors=false, bool UserFilesAreVolatile=false)
Create a ASTUnit from an AST file.
Definition: ASTUnit.cpp:733
ASTContext & getASTContext() const
void setModuleManager(IntrusiveRefCntPtr< ASTReader > Reader)
static SourceLocation ReadOriginalFileName(CompilerInstance &CI, std::string &InputFile, bool IsModuleMap=false)
For preprocessed files, if the first line is the linemarker and specifies the original source file na...
void setSourceManager(SourceManager *Value)
setSourceManager - Replace the current source manager.
virtual void EndSourceFile()
Callback to inform the diagnostic client that processing of a source file has ended.
Definition: Diagnostic.h:1517
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:655
Builtin::Context & getBuiltinInfo()
Definition: Preprocessor.h:826
virtual bool hasCodeCompletionSupport() const
Does this action support use with code completion?
std::string PresumedModuleMapFile
The presumed file name for the module map defining this module.
Definition: Module.h:100
tok::TokenKind getKind() const
Definition: Token.h:90
One of these records is kept for each identifier that is lexed.
static StringRef getModuleInputBufferName()
Definition: Module.h:574
virtual void ReaderInitialized(ASTReader *Reader)
The ASTReader was initialized.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
Record the location of a macro definition.
bool usesPreprocessorOnly() const override
Does this action only use the preprocessor?
bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Input)
Prepare the action for processing the input file Input.
void createSourceManager(FileManager &FileMgr)
Create the source manager and replace any existing one with it.
void resolveHeaderDirectives(const FileEntry *File) const
Resolve all lazy header directives for the specified file.
Definition: ModuleMap.cpp:1139
Definition: Format.h:2072
Module * getCurrentModule() const
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
Header getUmbrellaHeader() const
Retrieve the header that serves as the umbrella header for this module.
Definition: Module.h:483
bool isHeaderUnavailableInModule(const FileEntry *Header, const Module *RequestingModule) const
Determine whether the given header is unavailable as part of the specified module.
Definition: ModuleMap.cpp:671
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
void setASTContext(ASTContext *Value)
setASTContext - Replace the current AST context.
CodeGenOptions & getCodeGenOpts()
void finishModuleDeclarationScope()
Creates a new declaration scope for module names, allowing previously defined modules to shadow defin...
Definition: ModuleMap.h:557
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:815
Compiling a module from a module map.
Definition: LangOptions.h:79
std::vector< std::string > ModulesEmbedFiles
The list of files to embed into the compiled module file.
Describes a module or submodule.
Definition: Module.h:65
Execute the action before the main action.
CompilerInstance & getCompilerInstance() const
bool hasPCHSupport() const override
Does this action support use with PCH?
Action is determined by the cc1 command-line.
unsigned ShowStats
Show frontend performance metrics and statistics.
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:214
ModuleBuildStack getModuleBuildStack() const
Retrieve the module build stack.
HeaderSearch & getHeaderSearchInfo() const
Definition: Preprocessor.h:821
FrontendOptions & getFrontendOpts()
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1661
StringRef getCurrentFileOrBufferName() const
Load options and the preprocessor state.
Definition: ASTUnit.h:665
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:149
Module * Parent
The parent of this module.
Definition: Module.h:91
unsigned IsInferred
Whether this is an inferred submodule (module * { ... }).
Definition: Module.h:234
static Module * prepareToBuildModule(CompilerInstance &CI, StringRef ModuleMapFilename)
void setASTConsumer(std::unique_ptr< ASTConsumer > Value)
setASTConsumer - Replace the current AST consumer; the compiler instance takes ownership of Value...
unsigned SkipFunctionBodies
Skip over function bodies to speed up parsing in cases you do not need them (e.g. ...
bool loadModuleMapFile(const FileEntry *File, bool IsSystem, FileID ID=FileID(), unsigned *Offset=nullptr, StringRef OriginalModuleMapFile=StringRef())
Read the contents of the given module map file.
submodule_iterator submodule_end()
Definition: Module.h:558
virtual bool BeginInvocation(CompilerInstance &CI)
Callback before starting processing a single input, giving the opportunity to modify the CompilerInvo...
InputKind getKind() const
void setFileManager(FileManager *Value)
Replace the current file manager and virtual file system.
bool BeginInvocation(CompilerInstance &CI) override
Callback before starting processing a single input, giving the opportunity to modify the CompilerInvo...
HeaderSearchOptions & getHeaderSearchOpts()
bool DisablePCHValidation
When true, disables most of the normal validation performed on precompiled headers.
CodeCompleteConsumer & getCodeCompletionConsumer() const
static bool loadModuleMapForModuleBuild(CompilerInstance &CI, bool IsSystem, bool IsPreprocessed, std::string &PresumedModuleMapFile, unsigned &Offset)
virtual void SelectorRead(serialization::SelectorID iD, Selector Sel)
A selector was read from the AST file.
void createPCHExternalASTSource(StringRef Path, bool DisablePCHValidation, bool AllowPCHWithCompilerErrors, void *DeserializationListener, bool OwnDeserializationListener)
Create an external AST source to read a PCH file and attach it to the AST context.
Encapsulates the information needed to find the file referenced by a #include or #include_next, (sub-)framework lookup, etc.
Definition: HeaderSearch.h:148
void initializeForReplay(const SourceManager &Old)
Initialize this source manager suitably to replay the compilation described by Old.
StringRef getModuleCachePath() const
Retrieve the path to the module cache.
Definition: HeaderSearch.h:335
const FileEntry * getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
virtual void DeclRead(serialization::DeclID ID, const Decl *D)
A decl was deserialized from the AST file.
llvm::Registry< PluginASTAction > FrontendPluginRegistry
The frontend plugin registry.
bool hasCodeCompletionSupport() const override
Does this action support use with code completion?
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:227
const DirectoryEntry * getDirectory(StringRef DirName, bool CacheFailure=true)
Lookup, cache, and verify the specified directory (real or virtual).
StringRef Filename
Definition: Format.cpp:1629
virtual bool shouldEraseOutputFiles()
Callback at the end of processing a single input, to determine if the output files should be erased o...
std::vector< std::string > ChainedIncludes
Headers that will be converted to chained PCHs in memory.
void setCurrentInput(const FrontendInputFile &CurrentInput, std::unique_ptr< ASTUnit > AST=nullptr)
void setFileIsTransient(const FileEntry *SourceFile)
Specify that a file is transient.
IntrusiveRefCntPtr< ASTReader > getModuleManager() const
unsigned Offset
Definition: Format.cpp:1631
bool hasIRSupport() const override
Does this action support use with IR files?
SourceLocation End
std::string getSpecificModuleCachePath()
WrapperFrontendAction(std::unique_ptr< FrontendAction > WrappedAction)
Construct a WrapperFrontendAction from an existing action, taking ownership of it.
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
StateNode * Previous
FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, unsigned LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
StringRef getFile() const
std::set< std::string > DeserializedPCHDeclsToErrorOn
This is a set of names for decls that we do not want to be deserialized, and we emit an error if they...
bool BeginSourceFileAction(CompilerInstance &CI) override
Callback at the start of processing a single input.
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:124
Defines the clang::Preprocessor interface.
Not compiling a module interface at all.
Definition: LangOptions.h:76
void createASTContext()
Create the AST context.
virtual void EndSourceFileAction()
Callback at the end of processing a single input.
TranslationUnitKind getTranslationUnitKind() override
For AST-based actions, the kind of translation unit we&#39;re handling.
static bool checkModuleIsAvailable(const LangOptions &LangOpts, const TargetInfo &TargetInfo, DiagnosticsEngine &Diags, Module *M)
Check that the given module is available, producing a diagnostic if not.
Information about a module that has been loaded by the ASTReader.
Definition: Module.h:108
unsigned ModulesEmbedAllFiles
Whether we should embed all used files into the PCM file.
void setSema(Sema *S)
Replace the current Sema; the compiler instance takes ownership of S.
FileManager * createFileManager()
Create the file manager and replace any existing one with it.
An input file for the front end.
virtual std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile)=0
Create the AST consumer object for this action, if supported.
bool isAvailable() const
Determine whether this module is available for use within the current translation unit...
Definition: Module.h:379
Information about a header directive as found in the module map file.
Definition: Module.h:151
virtual void ExecuteAction()=0
Callback to run the program action, using the initialized compiler instance.
void EndSourceFileAction() override
Callback at the end of processing a single input.
bool AllowPCHWithCompilerErrors
When true, a PCH with compiler errors will not be rejected.
const DirectoryEntry * Directory
The build directory of this module.
Definition: Module.h:96
virtual bool hasPCHSupport() const
Does this action support use with PCH?
FileSystemOptions & getFileSystemOpts()
Kind
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Encodes a location in the source.
bool Execute()
Set the source manager&#39;s main input file, and run the action.
StringRef getName() const
Definition: FileManager.h:86
std::vector< std::string > ModuleFiles
The list of additional prebuilt module files to load before processing the input. ...
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.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
virtual void MacroDefinitionRead(serialization::PreprocessedEntityID, MacroDefinitionRecord *MD)
A macro definition was read from the AST file.
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
LLVM IR: we accept this so that we can run the optimizer on it, and compile it to assembly or object ...
Information about a directory name as found in the module map file.
Definition: Module.h:160
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:823
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:60
SmallVector< Header, 2 > Headers[5]
The headers that are part of this module.
Definition: Module.h:168
void ParseAST(Preprocessor &pp, ASTConsumer *C, ASTContext &Ctx, bool PrintStats=false, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr, bool SkipFunctionBodies=false)
Parse the entire file specified, notifying the ASTConsumer as the file is parsed. ...
Definition: ParseAST.cpp:99
static std::error_code collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr, DiagnosticsEngine &Diag, ModuleMap &ModMap, clang::Module *Module, SmallVectorImpl< char > &Includes)
Collect the set of header includes needed to construct the given module and update the TopHeaders fil...
void initializeBuiltins(IdentifierTable &Table, const LangOptions &LangOpts)
Mark the identifiers for all the builtins with their appropriate builtin ID # and mark any non-portab...
Definition: Builtins.cpp:87
std::unordered_map< std::string, std::vector< std::string > > PluginArgs
Args to pass to the plugins.
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:266
Execute the action after the main action.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:773
void pushModuleBuildStack(StringRef moduleName, FullSourceLoc importLoc)
Push an entry to the module build stack.
void createPreprocessor(TranslationUnitKind TUKind)
Create the preprocessor, using the invocation, file, and source managers, and replace any existing on...
virtual void TypeRead(serialization::TypeIdx Idx, QualType T)
A type was deserialized from the AST file.
bool shouldBuildGlobalModuleIndex() const
Indicates whether we should (re)build the global module index.
uint32_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
Definition: ASTBitCodes.h:169
std::string OverrideRecordLayoutsFile
File name of the file that will provide record layouts (in the format produced by -fdump-record-layou...
Abstract interface for a consumer of code-completion information.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isNot(tok::TokenKind K) const
Definition: Token.h:96
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
Definition: ASTBitCodes.h:154
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
void setPreprocessor(std::shared_ptr< Preprocessor > Value)
Replace the current preprocessor.
FileManager & getFileManager() const
Return the current file manager to the caller.
llvm::Timer & getFrontendTimer() const
const FrontendInputFile & getCurrentInput() const
Language getLanguage() const
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:355
ModuleFile & getPrimaryModule()
Returns the primary module associated with the manager, that is, the first module loaded...
void PrintStats() const
Print statistics to stderr.
FileID getMainFileID() const
Returns the FileID of the main source file.
StringRef getCurrentFile() const
bool loadModuleFile(StringRef FileName)
void setASTMutationListener(ASTMutationListener *Listener)
Attach an AST mutation listener to the AST context.
Definition: ASTContext.h:1091
void AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID, bool IsFileEntry, bool IsFileExit, SrcMgr::CharacteristicKind FileKind)
Add a line note to the line table for the FileID and offset specified by Loc.
SourceManager & getSourceManager() const
Return the current source manager.
void addTopHeader(const FileEntry *File)
Add a top-level header associated with this module.
Definition: Module.h:496
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
Definition: ASTContext.h:1082
uint32_t DeclID
An ID number that refers to a declaration in an AST file.
Definition: ASTBitCodes.h:69
void clearOutputFiles(bool EraseFiles)
clearOutputFiles - Clear the output file list.
TargetInfo & getTarget() const
uint32_t IdentID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:135
bool hasASTFileSupport() const override
Does this action support use with AST files?
void visitTopLevelModuleMaps(serialization::ModuleFile &MF, llvm::function_ref< void(const FileEntry *)> Visitor)
Visit all the top-level module maps loaded when building the given module file.
Definition: ASTReader.cpp:9217
void setCompilerInstance(CompilerInstance *Value)
Module * lookupModule(StringRef ModuleName, bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
DirectoryName getUmbrellaDir() const
Retrieve the directory for which this module serves as the umbrella.
Definition: Module.cpp:239
std::vector< std::string > AddPluginActions
The list of plugin actions to run in addition to the normal action.
Cached information about one directory (either on disk or in the virtual file system).
Definition: FileManager.h:46
unsigned DisableFree
Disable memory freeing on exit.
The type-property cache.
Definition: Type.cpp:3448
Preprocessor & getPreprocessor() const
Return the current preprocessor.
bool hasCodeCompletionConsumer() const
DiagnosticConsumer & getDiagnosticClient() const
An external AST source that overrides the layout of a specified set of record types.
virtual bool BeginSourceFileAction(CompilerInstance &CI)
Callback at the start of processing a single input.
void setMainFileDir(const DirectoryEntry *Dir)
Set the directory in which the main file should be considered to have been found, if it is not a real...
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:362
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
A SourceLocation and its associated SourceManager.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
bool isCurrentFileAST() const
Defines the clang::FrontendAction interface and various convenience abstract classes (clang::ASTFront...
std::unique_ptr< ASTConsumer > takeASTConsumer()
takeASTConsumer - Remove the current AST consumer and give ownership to the caller.
static std::unique_ptr< llvm::MemoryBuffer > getInputBufferForModule(CompilerInstance &CI, Module *M)
Compute the input buffer that should be used to build the specified module.
static ErrorCode writeIndex(FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, llvm::StringRef Path)
Write a global index into the given.
void setAllFilesAreTransient(bool Transient)
Specify that all files that are read during this compilation are transient.
void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine)
Instruct the preprocessor to skip part of the main source file.
This represents a decl that may have a name.
Definition: Decl.h:248
bool DumpDeserializedPCHDecls
Dump declarations that are deserialized from PCH, for testing.
virtual void BeginSourceFile(const LangOptions &LangOpts, const Preprocessor *PP=nullptr)
Callback to inform the diagnostic client that processing of a source file is beginning.
Definition: Diagnostic.h:1509
static SmallVectorImpl< char > & operator+=(SmallVectorImpl< char > &Includes, StringRef RHS)
TargetOptions & getTargetOpts()
FullSourceLoc getFullLoc(SourceLocation Loc) const
Definition: ASTContext.h:718
This class handles loading and caching of source files into memory.
static void addHeaderInclude(StringRef HeaderName, SmallVectorImpl< char > &Includes, const LangOptions &LangOpts, bool IsExternC)
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystem() const
Definition: FileManager.h:234
A type index; the type ID with the qualifier bits removed.
Definition: ASTBitCodes.h:89
SourceLocation getLocation() const
Definition: DeclBase.h:418
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:125
virtual bool isModelParsingAction() const
Is this action invoked on a model file?
std::vector< std::string > ModuleMapFiles
The list of module map files to load before processing the input.