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/ErrorHandling.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/Timer.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <system_error>
35 using namespace clang;
36 
37 LLVM_INSTANTIATE_REGISTRY(FrontendPluginRegistry)
38 
39 namespace {
40 
41 class DelegatingDeserializationListener : public ASTDeserializationListener {
43  bool DeletePrevious;
44 
45 public:
46  explicit DelegatingDeserializationListener(
47  ASTDeserializationListener *Previous, bool DeletePrevious)
48  : Previous(Previous), DeletePrevious(DeletePrevious) {}
49  ~DelegatingDeserializationListener() override {
50  if (DeletePrevious)
51  delete Previous;
52  }
53 
54  void ReaderInitialized(ASTReader *Reader) override {
55  if (Previous)
56  Previous->ReaderInitialized(Reader);
57  }
58  void IdentifierRead(serialization::IdentID ID,
59  IdentifierInfo *II) override {
60  if (Previous)
61  Previous->IdentifierRead(ID, II);
62  }
63  void TypeRead(serialization::TypeIdx Idx, QualType T) override {
64  if (Previous)
65  Previous->TypeRead(Idx, T);
66  }
67  void DeclRead(serialization::DeclID ID, const Decl *D) override {
68  if (Previous)
69  Previous->DeclRead(ID, D);
70  }
71  void SelectorRead(serialization::SelectorID ID, Selector Sel) override {
72  if (Previous)
73  Previous->SelectorRead(ID, Sel);
74  }
75  void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
76  MacroDefinitionRecord *MD) override {
77  if (Previous)
78  Previous->MacroDefinitionRead(PPID, MD);
79  }
80 };
81 
82 /// Dumps deserialized declarations.
83 class DeserializedDeclsDumper : public DelegatingDeserializationListener {
84 public:
85  explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous,
86  bool DeletePrevious)
87  : DelegatingDeserializationListener(Previous, DeletePrevious) {}
88 
89  void DeclRead(serialization::DeclID ID, const Decl *D) override {
90  llvm::outs() << "PCH DECL: " << D->getDeclKindName();
91  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
92  llvm::outs() << " - ";
93  ND->printQualifiedName(llvm::outs());
94  }
95  llvm::outs() << "\n";
96 
97  DelegatingDeserializationListener::DeclRead(ID, D);
98  }
99 };
100 
101 /// Checks deserialized declarations and emits error if a name
102 /// matches one given in command-line using -error-on-deserialized-decl.
103 class DeserializedDeclsChecker : public DelegatingDeserializationListener {
104  ASTContext &Ctx;
105  std::set<std::string> NamesToCheck;
106 
107 public:
108  DeserializedDeclsChecker(ASTContext &Ctx,
109  const std::set<std::string> &NamesToCheck,
110  ASTDeserializationListener *Previous,
111  bool DeletePrevious)
112  : DelegatingDeserializationListener(Previous, DeletePrevious), Ctx(Ctx),
113  NamesToCheck(NamesToCheck) {}
114 
115  void DeclRead(serialization::DeclID ID, const Decl *D) override {
116  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
117  if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
118  unsigned DiagID
120  "%0 was deserialized");
121  Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
122  << ND->getNameAsString();
123  }
124 
125  DelegatingDeserializationListener::DeclRead(ID, D);
126  }
127 };
128 
129 } // end anonymous namespace
130 
131 FrontendAction::FrontendAction() : Instance(nullptr) {}
132 
134 
136  std::unique_ptr<ASTUnit> AST) {
137  this->CurrentInput = CurrentInput;
138  CurrentASTUnit = std::move(AST);
139 }
140 
144  CI.getLangOpts().CurrentModule, /*AllowSearch*/false);
145 }
146 
147 std::unique_ptr<ASTConsumer>
148 FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
149  StringRef InFile) {
150  std::unique_ptr<ASTConsumer> Consumer = CreateASTConsumer(CI, InFile);
151  if (!Consumer)
152  return nullptr;
153 
154  // If there are no registered plugins we don't need to wrap the consumer
155  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
156  return Consumer;
157 
158  // If this is a code completion run, avoid invoking the plugin consumers
159  if (CI.hasCodeCompletionConsumer())
160  return Consumer;
161 
162  // Collect the list of plugins that go before the main action (in Consumers)
163  // or after it (in AfterConsumers)
164  std::vector<std::unique_ptr<ASTConsumer>> Consumers;
165  std::vector<std::unique_ptr<ASTConsumer>> AfterConsumers;
166  for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
167  ie = FrontendPluginRegistry::end();
168  it != ie; ++it) {
169  std::unique_ptr<PluginASTAction> P = it->instantiate();
170  PluginASTAction::ActionType ActionType = P->getActionType();
171  if (ActionType == PluginASTAction::Cmdline) {
172  // This is O(|plugins| * |add_plugins|), but since both numbers are
173  // way below 50 in practice, that's ok.
174  for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
175  i != e; ++i) {
176  if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
178  break;
179  }
180  }
181  }
182  if ((ActionType == PluginASTAction::AddBeforeMainAction ||
183  ActionType == PluginASTAction::AddAfterMainAction) &&
184  P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs[it->getName()])) {
185  std::unique_ptr<ASTConsumer> PluginConsumer = P->CreateASTConsumer(CI, InFile);
186  if (ActionType == PluginASTAction::AddBeforeMainAction) {
187  Consumers.push_back(std::move(PluginConsumer));
188  } else {
189  AfterConsumers.push_back(std::move(PluginConsumer));
190  }
191  }
192  }
193 
194  // Add to Consumers the main consumer, then all the plugins that go after it
195  Consumers.push_back(std::move(Consumer));
196  for (auto &C : AfterConsumers) {
197  Consumers.push_back(std::move(C));
198  }
199 
200  return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
201 }
202 
203 /// For preprocessed files, if the first line is the linemarker and specifies
204 /// the original source file name, use that name as the input file name.
205 /// Returns the location of the first token after the line marker directive.
206 ///
207 /// \param CI The compiler instance.
208 /// \param InputFile Populated with the filename from the line marker.
209 /// \param IsModuleMap If \c true, add a line note corresponding to this line
210 /// directive. (We need to do this because the directive will not be
211 /// visited by the preprocessor.)
213  std::string &InputFile,
214  bool IsModuleMap = false) {
215  auto &SourceMgr = CI.getSourceManager();
216  auto MainFileID = SourceMgr.getMainFileID();
217 
218  bool Invalid = false;
219  const auto *MainFileBuf = SourceMgr.getBuffer(MainFileID, &Invalid);
220  if (Invalid)
221  return SourceLocation();
222 
223  std::unique_ptr<Lexer> RawLexer(
224  new Lexer(MainFileID, MainFileBuf, SourceMgr, CI.getLangOpts()));
225 
226  // If the first line has the syntax of
227  //
228  // # NUM "FILENAME"
229  //
230  // we use FILENAME as the input file name.
231  Token T;
232  if (RawLexer->LexFromRawLexer(T) || T.getKind() != tok::hash)
233  return SourceLocation();
234  if (RawLexer->LexFromRawLexer(T) || T.isAtStartOfLine() ||
235  T.getKind() != tok::numeric_constant)
236  return SourceLocation();
237 
238  unsigned LineNo;
239  SourceLocation LineNoLoc = T.getLocation();
240  if (IsModuleMap) {
241  llvm::SmallString<16> Buffer;
242  if (Lexer::getSpelling(LineNoLoc, Buffer, SourceMgr, CI.getLangOpts())
243  .getAsInteger(10, LineNo))
244  return SourceLocation();
245  }
246 
247  RawLexer->LexFromRawLexer(T);
248  if (T.isAtStartOfLine() || T.getKind() != tok::string_literal)
249  return SourceLocation();
250 
251  StringLiteralParser Literal(T, CI.getPreprocessor());
252  if (Literal.hadError)
253  return SourceLocation();
254  RawLexer->LexFromRawLexer(T);
255  if (T.isNot(tok::eof) && !T.isAtStartOfLine())
256  return SourceLocation();
257  InputFile = Literal.GetString().str();
258 
259  if (IsModuleMap)
261  LineNoLoc, LineNo, SourceMgr.getLineTableFilenameID(InputFile), false,
262  false, SrcMgr::C_User_ModuleMap);
263 
264  return T.getLocation();
265 }
266 
267 static SmallVectorImpl<char> &
268 operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
269  Includes.append(RHS.begin(), RHS.end());
270  return Includes;
271 }
272 
273 static void addHeaderInclude(StringRef HeaderName,
274  SmallVectorImpl<char> &Includes,
275  const LangOptions &LangOpts,
276  bool IsExternC) {
277  if (IsExternC && LangOpts.CPlusPlus)
278  Includes += "extern \"C\" {\n";
279  if (LangOpts.ObjC1)
280  Includes += "#import \"";
281  else
282  Includes += "#include \"";
283 
284  Includes += HeaderName;
285 
286  Includes += "\"\n";
287  if (IsExternC && LangOpts.CPlusPlus)
288  Includes += "}\n";
289 }
290 
291 /// Collect the set of header includes needed to construct the given
292 /// module and update the TopHeaders file set of the module.
293 ///
294 /// \param Module The module we're collecting includes from.
295 ///
296 /// \param Includes Will be augmented with the set of \#includes or \#imports
297 /// needed to load all of the named headers.
298 static std::error_code collectModuleHeaderIncludes(
299  const LangOptions &LangOpts, FileManager &FileMgr, DiagnosticsEngine &Diag,
300  ModuleMap &ModMap, clang::Module *Module, SmallVectorImpl<char> &Includes) {
301  // Don't collect any headers for unavailable modules.
302  if (!Module->isAvailable())
303  return std::error_code();
304 
305  // Resolve all lazy header directives to header files.
306  ModMap.resolveHeaderDirectives(Module);
307 
308  // If any headers are missing, we can't build this module. In most cases,
309  // diagnostics for this should have already been produced; we only get here
310  // if explicit stat information was provided.
311  // FIXME: If the name resolves to a file with different stat information,
312  // produce a better diagnostic.
313  if (!Module->MissingHeaders.empty()) {
314  auto &MissingHeader = Module->MissingHeaders.front();
315  Diag.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
316  << MissingHeader.IsUmbrella << MissingHeader.FileName;
317  return std::error_code();
318  }
319 
320  // Add includes for each of these headers.
321  for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
322  for (Module::Header &H : Module->Headers[HK]) {
323  Module->addTopHeader(H.Entry);
324  // Use the path as specified in the module map file. We'll look for this
325  // file relative to the module build directory (the directory containing
326  // the module map file) so this will find the same file that we found
327  // while parsing the module map.
328  addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
329  }
330  }
331  // Note that Module->PrivateHeaders will not be a TopHeader.
332 
333  if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
334  Module->addTopHeader(UmbrellaHeader.Entry);
335  if (Module->Parent)
336  // Include the umbrella header for submodules.
337  addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
338  Module->IsExternC);
339  } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
340  // Add all of the headers we find in this subdirectory.
341  std::error_code EC;
342  SmallString<128> DirNative;
343  llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
344 
345  vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
346  for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
347  Dir != End && !EC; Dir.increment(EC)) {
348  // Check whether this entry has an extension typically associated with
349  // headers.
350  if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName()))
351  .Cases(".h", ".H", ".hh", ".hpp", true)
352  .Default(false))
353  continue;
354 
355  const FileEntry *Header = FileMgr.getFile(Dir->getName());
356  // FIXME: This shouldn't happen unless there is a file system race. Is
357  // that worth diagnosing?
358  if (!Header)
359  continue;
360 
361  // If this header is marked 'unavailable' in this module, don't include
362  // it.
363  if (ModMap.isHeaderUnavailableInModule(Header, Module))
364  continue;
365 
366  // Compute the relative path from the directory to this file.
367  SmallVector<StringRef, 16> Components;
368  auto PathIt = llvm::sys::path::rbegin(Dir->getName());
369  for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
370  Components.push_back(*PathIt);
371  SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
372  for (auto It = Components.rbegin(), End = Components.rend(); It != End;
373  ++It)
374  llvm::sys::path::append(RelativeHeader, *It);
375 
376  // Include this header as part of the umbrella directory.
377  Module->addTopHeader(Header);
378  addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
379  }
380 
381  if (EC)
382  return EC;
383  }
384 
385  // Recurse into submodules.
387  SubEnd = Module->submodule_end();
388  Sub != SubEnd; ++Sub)
389  if (std::error_code Err = collectModuleHeaderIncludes(
390  LangOpts, FileMgr, Diag, ModMap, *Sub, Includes))
391  return Err;
392 
393  return std::error_code();
394 }
395 
396 static bool loadModuleMapForModuleBuild(CompilerInstance &CI, bool IsSystem,
397  bool IsPreprocessed,
398  std::string &PresumedModuleMapFile,
399  unsigned &Offset) {
400  auto &SrcMgr = CI.getSourceManager();
402 
403  // Map the current input to a file.
404  FileID ModuleMapID = SrcMgr.getMainFileID();
405  const FileEntry *ModuleMap = SrcMgr.getFileEntryForID(ModuleMapID);
406 
407  // If the module map is preprocessed, handle the initial line marker;
408  // line directives are not part of the module map syntax in general.
409  Offset = 0;
410  if (IsPreprocessed) {
411  SourceLocation EndOfLineMarker =
412  ReadOriginalFileName(CI, PresumedModuleMapFile, /*IsModuleMap*/ true);
413  if (EndOfLineMarker.isValid())
414  Offset = CI.getSourceManager().getDecomposedLoc(EndOfLineMarker).second;
415  }
416 
417  // Load the module map file.
418  if (HS.loadModuleMapFile(ModuleMap, IsSystem, ModuleMapID, &Offset,
419  PresumedModuleMapFile))
420  return true;
421 
422  if (SrcMgr.getBuffer(ModuleMapID)->getBufferSize() == Offset)
423  Offset = 0;
424 
425  return false;
426 }
427 
429  StringRef ModuleMapFilename) {
430  if (CI.getLangOpts().CurrentModule.empty()) {
431  CI.getDiagnostics().Report(diag::err_missing_module_name);
432 
433  // FIXME: Eventually, we could consider asking whether there was just
434  // a single module described in the module map, and use that as a
435  // default. Then it would be fairly trivial to just "compile" a module
436  // map with a single module (the common case).
437  return nullptr;
438  }
439 
440  // Dig out the module definition.
443  /*AllowSearch=*/false);
444  if (!M) {
445  CI.getDiagnostics().Report(diag::err_missing_module)
446  << CI.getLangOpts().CurrentModule << ModuleMapFilename;
447 
448  return nullptr;
449  }
450 
451  // Check whether we can build this module at all.
453  CI.getDiagnostics(), M))
454  return nullptr;
455 
456  // Inform the preprocessor that includes from within the input buffer should
457  // be resolved relative to the build directory of the module map file.
459 
460  // If the module was inferred from a different module map (via an expanded
461  // umbrella module definition), track that fact.
462  // FIXME: It would be preferable to fill this in as part of processing
463  // the module map, rather than adding it after the fact.
464  StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
465  if (!OriginalModuleMapName.empty()) {
466  auto *OriginalModuleMap =
467  CI.getFileManager().getFile(OriginalModuleMapName,
468  /*openFile*/ true);
469  if (!OriginalModuleMap) {
470  CI.getDiagnostics().Report(diag::err_module_map_not_found)
471  << OriginalModuleMapName;
472  return nullptr;
473  }
474  if (OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
476  M->IsInferred = true;
478  .setInferredModuleAllowedBy(M, OriginalModuleMap);
479  }
480  }
481 
482  // If we're being run from the command-line, the module build stack will not
483  // have been filled in yet, so complete it now in order to allow us to detect
484  // module cycles.
485  SourceManager &SourceMgr = CI.getSourceManager();
486  if (SourceMgr.getModuleBuildStack().empty())
488  FullSourceLoc(SourceLocation(), SourceMgr));
489  return M;
490 }
491 
492 /// Compute the input buffer that should be used to build the specified module.
493 static std::unique_ptr<llvm::MemoryBuffer>
495  FileManager &FileMgr = CI.getFileManager();
496 
497  // Collect the set of #includes we need to build the module.
498  SmallString<256> HeaderContents;
499  std::error_code Err = std::error_code();
500  if (Module::Header UmbrellaHeader = M->getUmbrellaHeader())
501  addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
502  CI.getLangOpts(), M->IsExternC);
504  CI.getLangOpts(), FileMgr, CI.getDiagnostics(),
506  HeaderContents);
507 
508  if (Err) {
509  CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
510  << M->getFullModuleName() << Err.message();
511  return nullptr;
512  }
513 
514  return llvm::MemoryBuffer::getMemBufferCopy(
515  HeaderContents, Module::getModuleInputBufferName());
516 }
517 
519  const FrontendInputFile &RealInput) {
520  FrontendInputFile Input(RealInput);
521  assert(!Instance && "Already processing a source file!");
522  assert(!Input.isEmpty() && "Unexpected empty filename!");
523  setCurrentInput(Input);
524  setCompilerInstance(&CI);
525 
526  StringRef InputFile = Input.getFile();
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  std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
546  ASTDiags, CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs);
547  if (!AST)
548  goto failure;
549 
550  // Options relating to how we treat the input (but not what we do with it)
551  // are inherited from the AST unit.
552  CI.getHeaderSearchOpts() = AST->getHeaderSearchOpts();
553  CI.getPreprocessorOpts() = AST->getPreprocessorOpts();
554  CI.getLangOpts() = AST->getLangOpts();
555 
556  // Set the shared objects, these are reset when we finish processing the
557  // file, otherwise the CompilerInstance will happily destroy them.
558  CI.setFileManager(&AST->getFileManager());
560  CI.getSourceManager().initializeForReplay(AST->getSourceManager());
561 
562  // Preload all the module files loaded transitively by the AST unit. Also
563  // load all module map files that were parsed as part of building the AST
564  // unit.
565  if (auto ASTReader = AST->getASTReader()) {
566  auto &MM = ASTReader->getModuleManager();
567  auto &PrimaryModule = MM.getPrimaryModule();
568 
569  for (ModuleFile &MF : MM)
570  if (&MF != &PrimaryModule)
571  CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName);
572 
573  ASTReader->visitTopLevelModuleMaps(PrimaryModule,
574  [&](const FileEntry *FE) {
575  CI.getFrontendOpts().ModuleMapFiles.push_back(FE->getName());
576  });
577  }
578 
579  // Set up the input file for replay purposes.
580  auto Kind = AST->getInputKind();
581  if (Kind.getFormat() == InputKind::ModuleMap) {
582  Module *ASTModule =
583  AST->getPreprocessor().getHeaderSearchInfo().lookupModule(
584  AST->getLangOpts().CurrentModule, /*AllowSearch*/ false);
585  assert(ASTModule && "module file does not define its own module");
586  Input = FrontendInputFile(ASTModule->PresumedModuleMapFile, Kind);
587  } else {
588  auto &SM = CI.getSourceManager();
589  FileID ID = SM.getMainFileID();
590  if (auto *File = SM.getFileEntryForID(ID))
591  Input = FrontendInputFile(File->getName(), Kind);
592  else
593  Input = FrontendInputFile(SM.getBuffer(ID), Kind);
594  }
595  setCurrentInput(Input, std::move(AST));
596  }
597 
598  // AST files follow a very different path, since they share objects via the
599  // AST unit.
600  if (Input.getKind().getFormat() == InputKind::Precompiled) {
601  assert(!usesPreprocessorOnly() && "this case was handled above");
602  assert(hasASTFileSupport() &&
603  "This action does not have AST file support!");
604 
606 
607  std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
608  InputFile, CI.getPCHContainerReader(), ASTUnit::LoadEverything, Diags,
609  CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs);
610 
611  if (!AST)
612  goto failure;
613 
614  // Inform the diagnostic client we are processing a source file.
615  CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
616  HasBegunSourceFile = true;
617 
618  // Set the shared objects, these are reset when we finish processing the
619  // file, otherwise the CompilerInstance will happily destroy them.
620  CI.setFileManager(&AST->getFileManager());
621  CI.setSourceManager(&AST->getSourceManager());
622  CI.setPreprocessor(AST->getPreprocessorPtr());
623  Preprocessor &PP = CI.getPreprocessor();
625  PP.getLangOpts());
626  CI.setASTContext(&AST->getASTContext());
627 
628  setCurrentInput(Input, std::move(AST));
629 
630  // Initialize the action.
631  if (!BeginSourceFileAction(CI))
632  goto failure;
633 
634  // Create the AST consumer.
635  CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
636  if (!CI.hasASTConsumer())
637  goto failure;
638 
639  return true;
640  }
641 
642  // Set up the file and source managers, if needed.
643  if (!CI.hasFileManager()) {
644  if (!CI.createFileManager()) {
645  goto failure;
646  }
647  }
648  if (!CI.hasSourceManager())
650 
651  // Set up embedding for any specified files. Do this before we load any
652  // source files, including the primary module map for the compilation.
653  for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
654  if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
656  else
657  CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
658  }
661 
662  // IR files bypass the rest of initialization.
663  if (Input.getKind().getLanguage() == InputKind::LLVM_IR) {
664  assert(hasIRSupport() &&
665  "This action does not have IR file support!");
666 
667  // Inform the diagnostic client we are processing a source file.
668  CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
669  HasBegunSourceFile = true;
670 
671  // Initialize the action.
672  if (!BeginSourceFileAction(CI))
673  goto failure;
674 
675  // Initialize the main file entry.
676  if (!CI.InitializeSourceManager(CurrentInput))
677  goto failure;
678 
679  return true;
680  }
681 
682  // If the implicit PCH include is actually a directory, rather than
683  // a single file, search for a suitable PCH file in that directory.
684  if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
685  FileManager &FileMgr = CI.getFileManager();
687  StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
688  std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
689  if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
690  std::error_code EC;
691  SmallString<128> DirNative;
692  llvm::sys::path::native(PCHDir->getName(), DirNative);
693  bool Found = false;
694  vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
695  for (vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC), DirEnd;
696  Dir != DirEnd && !EC; Dir.increment(EC)) {
697  // Check whether this is an acceptable AST file.
699  Dir->getName(), FileMgr, CI.getPCHContainerReader(),
701  SpecificModuleCachePath)) {
702  PPOpts.ImplicitPCHInclude = Dir->getName();
703  Found = true;
704  break;
705  }
706  }
707 
708  if (!Found) {
709  CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
710  goto failure;
711  }
712  }
713  }
714 
715  // Set up the preprocessor if needed. When parsing model files the
716  // preprocessor of the original source is reused.
717  if (!isModelParsingAction())
719 
720  // Inform the diagnostic client we are processing a source file.
722  &CI.getPreprocessor());
723  HasBegunSourceFile = true;
724 
725  // Initialize the main file entry.
726  if (!CI.InitializeSourceManager(Input))
727  goto failure;
728 
729  // For module map files, we first parse the module map and synthesize a
730  // "<module-includes>" buffer before more conventional processing.
731  if (Input.getKind().getFormat() == InputKind::ModuleMap) {
732  CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
733 
734  std::string PresumedModuleMapFile;
735  unsigned OffsetToContents;
736  if (loadModuleMapForModuleBuild(CI, Input.isSystem(),
737  Input.isPreprocessed(),
738  PresumedModuleMapFile, OffsetToContents))
739  goto failure;
740 
741  auto *CurrentModule = prepareToBuildModule(CI, Input.getFile());
742  if (!CurrentModule)
743  goto failure;
744 
745  CurrentModule->PresumedModuleMapFile = PresumedModuleMapFile;
746 
747  if (OffsetToContents)
748  // If the module contents are in the same file, skip to them.
749  CI.getPreprocessor().setSkipMainFilePreamble(OffsetToContents, true);
750  else {
751  // Otherwise, convert the module description to a suitable input buffer.
752  auto Buffer = getInputBufferForModule(CI, CurrentModule);
753  if (!Buffer)
754  goto failure;
755 
756  // Reinitialize the main file entry to refer to the new input.
757  auto Kind = CurrentModule->IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
758  auto &SourceMgr = CI.getSourceManager();
759  auto BufferID = SourceMgr.createFileID(std::move(Buffer), Kind);
760  assert(BufferID.isValid() && "couldn't creaate module buffer ID");
761  SourceMgr.setMainFileID(BufferID);
762  }
763  }
764 
765  // Initialize the action.
766  if (!BeginSourceFileAction(CI))
767  goto failure;
768 
769  // If we were asked to load any module map files, do so now.
770  for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
771  if (auto *File = CI.getFileManager().getFile(Filename))
773  File, /*IsSystem*/false);
774  else
775  CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
776  }
777 
778  // Add a module declaration scope so that modules from -fmodule-map-file
779  // arguments may shadow modules found implicitly in search paths.
780  CI.getPreprocessor()
782  .getModuleMap()
784 
785  // Create the AST context and consumer unless this is a preprocessor only
786  // action.
787  if (!usesPreprocessorOnly()) {
788  // Parsing a model file should reuse the existing ASTContext.
789  if (!isModelParsingAction())
790  CI.createASTContext();
791 
792  // For preprocessed files, check if the first line specifies the original
793  // source file name with a linemarker.
794  std::string PresumedInputFile = InputFile;
795  if (Input.isPreprocessed())
796  ReadOriginalFileName(CI, PresumedInputFile);
797 
798  std::unique_ptr<ASTConsumer> Consumer =
799  CreateWrappedASTConsumer(CI, PresumedInputFile);
800  if (!Consumer)
801  goto failure;
802 
803  // FIXME: should not overwrite ASTMutationListener when parsing model files?
804  if (!isModelParsingAction())
805  CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
806 
807  if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
808  // Convert headers to PCH and chain them.
809  IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
810  source = createChainedIncludesSource(CI, FinalReader);
811  if (!source)
812  goto failure;
813  CI.setModuleManager(static_cast<ASTReader *>(FinalReader.get()));
814  CI.getASTContext().setExternalSource(source);
815  } else if (CI.getLangOpts().Modules ||
816  !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
817  // Use PCM or PCH.
818  assert(hasPCHSupport() && "This action does not have PCH support!");
819  ASTDeserializationListener *DeserialListener =
820  Consumer->GetASTDeserializationListener();
821  bool DeleteDeserialListener = false;
823  DeserialListener = new DeserializedDeclsDumper(DeserialListener,
824  DeleteDeserialListener);
825  DeleteDeserialListener = true;
826  }
828  DeserialListener = new DeserializedDeclsChecker(
829  CI.getASTContext(),
831  DeserialListener, DeleteDeserialListener);
832  DeleteDeserialListener = true;
833  }
834  if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
838  CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, DeserialListener,
839  DeleteDeserialListener);
840  if (!CI.getASTContext().getExternalSource())
841  goto failure;
842  }
843  // If modules are enabled, create the module manager before creating
844  // any builtins, so that all declarations know that they might be
845  // extended by an external source.
846  if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
848  CI.createModuleManager();
849  CI.getModuleManager()->setDeserializationListener(DeserialListener,
850  DeleteDeserialListener);
851  }
852  }
853 
854  CI.setASTConsumer(std::move(Consumer));
855  if (!CI.hasASTConsumer())
856  goto failure;
857  }
858 
859  // Initialize built-in info as long as we aren't using an external AST
860  // source.
861  if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
863  Preprocessor &PP = CI.getPreprocessor();
865  PP.getLangOpts());
866  } else {
867  // FIXME: If this is a problem, recover from it by creating a multiplex
868  // source.
869  assert((!CI.getLangOpts().Modules || CI.getModuleManager()) &&
870  "modules enabled but created an external source that "
871  "doesn't support modules");
872  }
873 
874  // If we were asked to load any module files, do so now.
875  for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
876  if (!CI.loadModuleFile(ModuleFile))
877  goto failure;
878 
879  // If there is a layout overrides file, attach an external AST source that
880  // provides the layouts from that file.
881  if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
884  Override(new LayoutOverrideSource(
886  CI.getASTContext().setExternalSource(Override);
887  }
888 
889  return true;
890 
891  // If we failed, reset state since the client will not end up calling the
892  // matching EndSourceFile().
893 failure:
894  if (HasBegunSourceFile)
896  CI.clearOutputFiles(/*EraseFiles=*/true);
897  CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
899  setCompilerInstance(nullptr);
900  return false;
901 }
902 
905 
906  if (CI.hasFrontendTimer()) {
907  llvm::TimeRegion Timer(CI.getFrontendTimer());
908  ExecuteAction();
909  }
910  else ExecuteAction();
911 
912  // If we are supposed to rebuild the global module index, do so now unless
913  // there were any module-build failures.
914  if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
915  CI.hasPreprocessor()) {
916  StringRef Cache =
918  if (!Cache.empty())
921  }
922 
923  return true;
924 }
925 
928 
929  // Inform the diagnostic client we are done with this source file.
931 
932  // Inform the preprocessor we are done.
933  if (CI.hasPreprocessor())
935 
936  // Finalize the action.
938 
939  // Sema references the ast consumer, so reset sema first.
940  //
941  // FIXME: There is more per-file stuff we could just drop here?
942  bool DisableFree = CI.getFrontendOpts().DisableFree;
943  if (DisableFree) {
944  CI.resetAndLeakSema();
946  BuryPointer(CI.takeASTConsumer().get());
947  } else {
948  CI.setSema(nullptr);
949  CI.setASTContext(nullptr);
950  CI.setASTConsumer(nullptr);
951  }
952 
953  if (CI.getFrontendOpts().ShowStats) {
954  llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
959  llvm::errs() << "\n";
960  }
961 
962  // Cleanup the output streams, and erase the output files if instructed by the
963  // FrontendAction.
964  CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
965 
966  if (isCurrentFileAST()) {
967  if (DisableFree) {
971  BuryPointer(CurrentASTUnit.release());
972  } else {
973  CI.setPreprocessor(nullptr);
974  CI.setSourceManager(nullptr);
975  CI.setFileManager(nullptr);
976  }
977  }
978 
979  setCompilerInstance(nullptr);
981  CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
982 }
983 
986 }
987 
988 //===----------------------------------------------------------------------===//
989 // Utility Actions
990 //===----------------------------------------------------------------------===//
991 
994  if (!CI.hasPreprocessor())
995  return;
996 
997  // FIXME: Move the truncation aspect of this into Sema, we delayed this till
998  // here so the source manager would be initialized.
999  if (hasCodeCompletionSupport() &&
1002 
1003  // Use a code completion consumer?
1004  CodeCompleteConsumer *CompletionConsumer = nullptr;
1005  if (CI.hasCodeCompletionConsumer())
1006  CompletionConsumer = &CI.getCodeCompletionConsumer();
1007 
1008  if (!CI.hasSema())
1009  CI.createSema(getTranslationUnitKind(), CompletionConsumer);
1010 
1013 }
1014 
1015 void PluginASTAction::anchor() { }
1016 
1017 std::unique_ptr<ASTConsumer>
1019  StringRef InFile) {
1020  llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
1021 }
1022 
1023 std::unique_ptr<ASTConsumer>
1025  StringRef InFile) {
1026  return WrappedAction->CreateASTConsumer(CI, InFile);
1027 }
1029  return WrappedAction->BeginInvocation(CI);
1030 }
1032  WrappedAction->setCurrentInput(getCurrentInput());
1033  WrappedAction->setCompilerInstance(&CI);
1034  auto Ret = WrappedAction->BeginSourceFileAction(CI);
1035  // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
1036  setCurrentInput(WrappedAction->getCurrentInput());
1037  return Ret;
1038 }
1040  WrappedAction->ExecuteAction();
1041 }
1043  WrappedAction->EndSourceFileAction();
1044 }
1045 
1047  return WrappedAction->usesPreprocessorOnly();
1048 }
1050  return WrappedAction->getTranslationUnitKind();
1051 }
1053  return WrappedAction->hasPCHSupport();
1054 }
1056  return WrappedAction->hasASTFileSupport();
1057 }
1059  return WrappedAction->hasIRSupport();
1060 }
1062  return WrappedAction->hasCodeCompletionSupport();
1063 }
1064 
1066  std::unique_ptr<FrontendAction> WrappedAction)
1067  : WrappedAction(std::move(WrappedAction)) {}
1068 
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
Definition: ASTContext.cpp:864
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:4940
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
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:746
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:640
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:116
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:3510
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:672
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
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:1294
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:1519
virtual directory_iterator dir_begin(const Twine &Dir, std::error_code &EC)=0
Get a directory_iterator for Dir.
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:657
Builtin::Context & getBuiltinInfo()
Definition: Preprocessor.h:835
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
The virtual file system interface.
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:153
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:1115
Definition: Format.h:2031
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()
An input iterator over the recursive contents of a virtual path, similar to llvm::sys::fs::recursive_...
void finishModuleDeclarationScope()
Creates a new declaration scope for module names, allowing previously defined modules to shadow defin...
Definition: ModuleMap.h:555
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:824
Compiling a module from a module map.
Definition: LangOptions.h:74
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.
directory_iterator & increment(std::error_code &EC)
Equivalent to operator++, with an error code.
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:182
ModuleBuildStack getModuleBuildStack() const
Retrieve the module build stack.
HeaderSearch & getHeaderSearchInfo() const
Definition: Preprocessor.h:830
FrontendOptions & getFrontendOpts()
uint32_t Offset
Definition: CacheTokens.cpp:43
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1660
Load options and the preprocessor state.
Definition: ASTUnit.h:666
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
static ErrorCode writeIndex(FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, StringRef Path)
Write a global index into the given.
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:337
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:191
const DirectoryEntry * getDirectory(StringRef DirName, bool CacheFailure=true)
Lookup, cache, and verify the specified directory (real or virtual).
StringRef Filename
Definition: Format.cpp:1605
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
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:71
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.
const SourceManager & SM
Definition: Format.cpp:1475
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
llvm::MemoryBuffer * getBuffer(FileID FID, SourceLocation Loc, bool *Invalid=nullptr) const
Return the buffer for the specified FileID.
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:84
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:832
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:59
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:775
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:354
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.
bool loadModuleFile(StringRef FileName)
void setASTMutationListener(ASTMutationListener *Listener)
Attach an AST mutation listener to the AST context.
Definition: ASTContext.h:1096
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:1087
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.
void BuryPointer(const void *Ptr)
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:9230
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:207
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:45
unsigned DisableFree
Disable memory freeing on exit.
The type-property cache.
Definition: Type.cpp:3464
Preprocessor & getPreprocessor() const
Return the current preprocessor.
bool hasCodeCompletionConsumer() const
DiagnosticConsumer & getDiagnosticClient() const
An input iterator over the entries in a virtual path, similar to llvm::sys::fs::directory_iterator.
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...
IntrusiveRefCntPtr< vfs::FileSystem > getVirtualFileSystem() const
Definition: FileManager.h:225
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:326
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.
const StringRef getCurrentFile() const
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.
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:1511
static SmallVectorImpl< char > & operator+=(SmallVectorImpl< char > &Includes, StringRef RHS)
void setInferredModuleAllowedBy(Module *M, const FileEntry *ModuleMap)
Definition: ModuleMap.cpp:1196
TargetOptions & getTargetOpts()
FullSourceLoc getFullLoc(SourceLocation Loc) const
Definition: ASTContext.h:727
This class handles loading and caching of source files into memory.
static void addHeaderInclude(StringRef HeaderName, SmallVectorImpl< char > &Includes, const LangOptions &LangOpts, bool IsExternC)
A type index; the type ID with the qualifier bits removed.
Definition: ASTBitCodes.h:89
SourceLocation getLocation() const
Definition: DeclBase.h:425
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:127
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.