clang  12.0.0git
FrontendAction.cpp
Go to the documentation of this file.
1 //===--- FrontendAction.cpp -----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
10 #include "clang/AST/ASTConsumer.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/DeclGroup.h"
13 #include "clang/Basic/Builtins.h"
15 #include "clang/Frontend/ASTUnit.h"
21 #include "clang/Frontend/Utils.h"
22 #include "clang/Lex/HeaderSearch.h"
24 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Parse/ParseAST.h"
30 #include "llvm/Support/BuryPointer.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/Timer.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <system_error>
37 using namespace clang;
38 
39 LLVM_INSTANTIATE_REGISTRY(FrontendPluginRegistry)
40 
41 namespace {
42 
43 class DelegatingDeserializationListener : public ASTDeserializationListener {
45  bool DeletePrevious;
46 
47 public:
48  explicit DelegatingDeserializationListener(
49  ASTDeserializationListener *Previous, bool DeletePrevious)
50  : Previous(Previous), DeletePrevious(DeletePrevious) {}
51  ~DelegatingDeserializationListener() override {
52  if (DeletePrevious)
53  delete Previous;
54  }
55 
56  void ReaderInitialized(ASTReader *Reader) override {
57  if (Previous)
58  Previous->ReaderInitialized(Reader);
59  }
60  void IdentifierRead(serialization::IdentID ID,
61  IdentifierInfo *II) override {
62  if (Previous)
63  Previous->IdentifierRead(ID, II);
64  }
65  void TypeRead(serialization::TypeIdx Idx, QualType T) override {
66  if (Previous)
67  Previous->TypeRead(Idx, T);
68  }
69  void DeclRead(serialization::DeclID ID, const Decl *D) override {
70  if (Previous)
71  Previous->DeclRead(ID, D);
72  }
73  void SelectorRead(serialization::SelectorID ID, Selector Sel) override {
74  if (Previous)
75  Previous->SelectorRead(ID, Sel);
76  }
77  void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
78  MacroDefinitionRecord *MD) override {
79  if (Previous)
80  Previous->MacroDefinitionRead(PPID, MD);
81  }
82 };
83 
84 /// Dumps deserialized declarations.
85 class DeserializedDeclsDumper : public DelegatingDeserializationListener {
86 public:
87  explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous,
88  bool DeletePrevious)
89  : DelegatingDeserializationListener(Previous, DeletePrevious) {}
90 
91  void DeclRead(serialization::DeclID ID, const Decl *D) override {
92  llvm::outs() << "PCH DECL: " << D->getDeclKindName();
93  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
94  llvm::outs() << " - ";
95  ND->printQualifiedName(llvm::outs());
96  }
97  llvm::outs() << "\n";
98 
99  DelegatingDeserializationListener::DeclRead(ID, D);
100  }
101 };
102 
103 /// Checks deserialized declarations and emits error if a name
104 /// matches one given in command-line using -error-on-deserialized-decl.
105 class DeserializedDeclsChecker : public DelegatingDeserializationListener {
106  ASTContext &Ctx;
107  std::set<std::string> NamesToCheck;
108 
109 public:
110  DeserializedDeclsChecker(ASTContext &Ctx,
111  const std::set<std::string> &NamesToCheck,
113  bool DeletePrevious)
114  : DelegatingDeserializationListener(Previous, DeletePrevious), Ctx(Ctx),
115  NamesToCheck(NamesToCheck) {}
116 
117  void DeclRead(serialization::DeclID ID, const Decl *D) override {
118  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
119  if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
120  unsigned DiagID
122  "%0 was deserialized");
123  Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
124  << ND;
125  }
126 
127  DelegatingDeserializationListener::DeclRead(ID, D);
128  }
129 };
130 
131 } // end anonymous namespace
132 
133 FrontendAction::FrontendAction() : Instance(nullptr) {}
134 
136 
138  std::unique_ptr<ASTUnit> AST) {
139  this->CurrentInput = CurrentInput;
140  CurrentASTUnit = std::move(AST);
141 }
142 
146  CI.getLangOpts().CurrentModule, /*AllowSearch*/false);
147 }
148 
149 std::unique_ptr<ASTConsumer>
150 FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
151  StringRef InFile) {
152  std::unique_ptr<ASTConsumer> Consumer = CreateASTConsumer(CI, InFile);
153  if (!Consumer)
154  return nullptr;
155 
156  // Validate -add-plugin args.
157  bool FoundAllPlugins = true;
158  for (const std::string &Arg : CI.getFrontendOpts().AddPluginActions) {
159  bool Found = false;
160  for (const FrontendPluginRegistry::entry &Plugin :
161  FrontendPluginRegistry::entries()) {
162  if (Plugin.getName() == Arg)
163  Found = true;
164  }
165  if (!Found) {
166  CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name) << Arg;
167  FoundAllPlugins = false;
168  }
169  }
170  if (!FoundAllPlugins)
171  return nullptr;
172 
173  // If there are no registered plugins we don't need to wrap the consumer
174  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
175  return Consumer;
176 
177  // If this is a code completion run, avoid invoking the plugin consumers
178  if (CI.hasCodeCompletionConsumer())
179  return Consumer;
180 
181  // Collect the list of plugins that go before the main action (in Consumers)
182  // or after it (in AfterConsumers)
183  std::vector<std::unique_ptr<ASTConsumer>> Consumers;
184  std::vector<std::unique_ptr<ASTConsumer>> AfterConsumers;
185  for (const FrontendPluginRegistry::entry &Plugin :
186  FrontendPluginRegistry::entries()) {
187  std::unique_ptr<PluginASTAction> P = Plugin.instantiate();
188  PluginASTAction::ActionType ActionType = P->getActionType();
189  if (ActionType == PluginASTAction::Cmdline) {
190  // This is O(|plugins| * |add_plugins|), but since both numbers are
191  // way below 50 in practice, that's ok.
192  if (llvm::any_of(CI.getFrontendOpts().AddPluginActions,
193  [&](const std::string &PluginAction) {
194  return PluginAction == Plugin.getName();
195  }))
197  }
198  if ((ActionType == PluginASTAction::AddBeforeMainAction ||
199  ActionType == PluginASTAction::AddAfterMainAction) &&
200  P->ParseArgs(
201  CI,
202  CI.getFrontendOpts().PluginArgs[std::string(Plugin.getName())])) {
203  std::unique_ptr<ASTConsumer> PluginConsumer = P->CreateASTConsumer(CI, InFile);
204  if (ActionType == PluginASTAction::AddBeforeMainAction) {
205  Consumers.push_back(std::move(PluginConsumer));
206  } else {
207  AfterConsumers.push_back(std::move(PluginConsumer));
208  }
209  }
210  }
211 
212  // Add to Consumers the main consumer, then all the plugins that go after it
213  Consumers.push_back(std::move(Consumer));
214  for (auto &C : AfterConsumers) {
215  Consumers.push_back(std::move(C));
216  }
217 
218  return std::make_unique<MultiplexConsumer>(std::move(Consumers));
219 }
220 
221 /// For preprocessed files, if the first line is the linemarker and specifies
222 /// the original source file name, use that name as the input file name.
223 /// Returns the location of the first token after the line marker directive.
224 ///
225 /// \param CI The compiler instance.
226 /// \param InputFile Populated with the filename from the line marker.
227 /// \param IsModuleMap If \c true, add a line note corresponding to this line
228 /// directive. (We need to do this because the directive will not be
229 /// visited by the preprocessor.)
231  std::string &InputFile,
232  bool IsModuleMap = false) {
233  auto &SourceMgr = CI.getSourceManager();
234  auto MainFileID = SourceMgr.getMainFileID();
235 
236  auto MainFileBuf = SourceMgr.getBufferOrNone(MainFileID);
237  if (!MainFileBuf)
238  return SourceLocation();
239 
240  std::unique_ptr<Lexer> RawLexer(
241  new Lexer(MainFileID, *MainFileBuf, SourceMgr, CI.getLangOpts()));
242 
243  // If the first line has the syntax of
244  //
245  // # NUM "FILENAME"
246  //
247  // we use FILENAME as the input file name.
248  Token T;
249  if (RawLexer->LexFromRawLexer(T) || T.getKind() != tok::hash)
250  return SourceLocation();
251  if (RawLexer->LexFromRawLexer(T) || T.isAtStartOfLine() ||
252  T.getKind() != tok::numeric_constant)
253  return SourceLocation();
254 
255  unsigned LineNo;
256  SourceLocation LineNoLoc = T.getLocation();
257  if (IsModuleMap) {
258  llvm::SmallString<16> Buffer;
259  if (Lexer::getSpelling(LineNoLoc, Buffer, SourceMgr, CI.getLangOpts())
260  .getAsInteger(10, LineNo))
261  return SourceLocation();
262  }
263 
264  RawLexer->LexFromRawLexer(T);
265  if (T.isAtStartOfLine() || T.getKind() != tok::string_literal)
266  return SourceLocation();
267 
268  StringLiteralParser Literal(T, CI.getPreprocessor());
269  if (Literal.hadError)
270  return SourceLocation();
271  RawLexer->LexFromRawLexer(T);
272  if (T.isNot(tok::eof) && !T.isAtStartOfLine())
273  return SourceLocation();
274  InputFile = Literal.GetString().str();
275 
276  if (IsModuleMap)
278  LineNoLoc, LineNo, SourceMgr.getLineTableFilenameID(InputFile), false,
279  false, SrcMgr::C_User_ModuleMap);
280 
281  return T.getLocation();
282 }
283 
284 static SmallVectorImpl<char> &
285 operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
286  Includes.append(RHS.begin(), RHS.end());
287  return Includes;
288 }
289 
290 static void addHeaderInclude(StringRef HeaderName,
291  SmallVectorImpl<char> &Includes,
292  const LangOptions &LangOpts,
293  bool IsExternC) {
294  if (IsExternC && LangOpts.CPlusPlus)
295  Includes += "extern \"C\" {\n";
296  if (LangOpts.ObjC)
297  Includes += "#import \"";
298  else
299  Includes += "#include \"";
300 
301  Includes += HeaderName;
302 
303  Includes += "\"\n";
304  if (IsExternC && LangOpts.CPlusPlus)
305  Includes += "}\n";
306 }
307 
308 /// Collect the set of header includes needed to construct the given
309 /// module and update the TopHeaders file set of the module.
310 ///
311 /// \param Module The module we're collecting includes from.
312 ///
313 /// \param Includes Will be augmented with the set of \#includes or \#imports
314 /// needed to load all of the named headers.
315 static std::error_code collectModuleHeaderIncludes(
316  const LangOptions &LangOpts, FileManager &FileMgr, DiagnosticsEngine &Diag,
317  ModuleMap &ModMap, clang::Module *Module, SmallVectorImpl<char> &Includes) {
318  // Don't collect any headers for unavailable modules.
319  if (!Module->isAvailable())
320  return std::error_code();
321 
322  // Resolve all lazy header directives to header files.
324 
325  // If any headers are missing, we can't build this module. In most cases,
326  // diagnostics for this should have already been produced; we only get here
327  // if explicit stat information was provided.
328  // FIXME: If the name resolves to a file with different stat information,
329  // produce a better diagnostic.
330  if (!Module->MissingHeaders.empty()) {
331  auto &MissingHeader = Module->MissingHeaders.front();
332  Diag.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
333  << MissingHeader.IsUmbrella << MissingHeader.FileName;
334  return std::error_code();
335  }
336 
337  // Add includes for each of these headers.
338  for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
339  for (Module::Header &H : Module->Headers[HK]) {
340  Module->addTopHeader(H.Entry);
341  // Use the path as specified in the module map file. We'll look for this
342  // file relative to the module build directory (the directory containing
343  // the module map file) so this will find the same file that we found
344  // while parsing the module map.
345  addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
346  }
347  }
348  // Note that Module->PrivateHeaders will not be a TopHeader.
349 
350  if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
351  Module->addTopHeader(UmbrellaHeader.Entry);
352  if (Module->Parent)
353  // Include the umbrella header for submodules.
354  addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
355  Module->IsExternC);
356  } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
357  // Add all of the headers we find in this subdirectory.
358  std::error_code EC;
359  SmallString<128> DirNative;
360  llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
361 
362  llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
364  for (llvm::vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
365  Dir != End && !EC; Dir.increment(EC)) {
366  // Check whether this entry has an extension typically associated with
367  // headers.
368  if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
369  .Cases(".h", ".H", ".hh", ".hpp", true)
370  .Default(false))
371  continue;
372 
373  auto Header = FileMgr.getFile(Dir->path());
374  // FIXME: This shouldn't happen unless there is a file system race. Is
375  // that worth diagnosing?
376  if (!Header)
377  continue;
378 
379  // If this header is marked 'unavailable' in this module, don't include
380  // it.
381  if (ModMap.isHeaderUnavailableInModule(*Header, Module))
382  continue;
383 
384  // Compute the relative path from the directory to this file.
385  SmallVector<StringRef, 16> Components;
386  auto PathIt = llvm::sys::path::rbegin(Dir->path());
387  for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
388  Components.push_back(*PathIt);
389  SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
390  for (auto It = Components.rbegin(), End = Components.rend(); It != End;
391  ++It)
392  llvm::sys::path::append(RelativeHeader, *It);
393 
394  std::string RelName = RelativeHeader.c_str();
395  Headers.push_back(std::make_pair(RelName, *Header));
396  }
397 
398  if (EC)
399  return EC;
400 
401  // Sort header paths and make the header inclusion order deterministic
402  // across different OSs and filesystems.
403  llvm::sort(Headers.begin(), Headers.end(), [](
404  const std::pair<std::string, const FileEntry *> &LHS,
405  const std::pair<std::string, const FileEntry *> &RHS) {
406  return LHS.first < RHS.first;
407  });
408  for (auto &H : Headers) {
409  // Include this header as part of the umbrella directory.
410  Module->addTopHeader(H.second);
411  addHeaderInclude(H.first, Includes, LangOpts, Module->IsExternC);
412  }
413  }
414 
415  // Recurse into submodules.
417  SubEnd = Module->submodule_end();
418  Sub != SubEnd; ++Sub)
419  if (std::error_code Err = collectModuleHeaderIncludes(
420  LangOpts, FileMgr, Diag, ModMap, *Sub, Includes))
421  return Err;
422 
423  return std::error_code();
424 }
425 
426 static bool loadModuleMapForModuleBuild(CompilerInstance &CI, bool IsSystem,
427  bool IsPreprocessed,
428  std::string &PresumedModuleMapFile,
429  unsigned &Offset) {
430  auto &SrcMgr = CI.getSourceManager();
432 
433  // Map the current input to a file.
434  FileID ModuleMapID = SrcMgr.getMainFileID();
435  const FileEntry *ModuleMap = SrcMgr.getFileEntryForID(ModuleMapID);
436 
437  // If the module map is preprocessed, handle the initial line marker;
438  // line directives are not part of the module map syntax in general.
439  Offset = 0;
440  if (IsPreprocessed) {
441  SourceLocation EndOfLineMarker =
442  ReadOriginalFileName(CI, PresumedModuleMapFile, /*IsModuleMap*/ true);
443  if (EndOfLineMarker.isValid())
444  Offset = CI.getSourceManager().getDecomposedLoc(EndOfLineMarker).second;
445  }
446 
447  // Load the module map file.
448  if (HS.loadModuleMapFile(ModuleMap, IsSystem, ModuleMapID, &Offset,
449  PresumedModuleMapFile))
450  return true;
451 
452  if (SrcMgr.getBufferOrFake(ModuleMapID).getBufferSize() == Offset)
453  Offset = 0;
454 
455  return false;
456 }
457 
459  StringRef ModuleMapFilename) {
460  if (CI.getLangOpts().CurrentModule.empty()) {
461  CI.getDiagnostics().Report(diag::err_missing_module_name);
462 
463  // FIXME: Eventually, we could consider asking whether there was just
464  // a single module described in the module map, and use that as a
465  // default. Then it would be fairly trivial to just "compile" a module
466  // map with a single module (the common case).
467  return nullptr;
468  }
469 
470  // Dig out the module definition.
473  /*AllowSearch=*/false);
474  if (!M) {
475  CI.getDiagnostics().Report(diag::err_missing_module)
476  << CI.getLangOpts().CurrentModule << ModuleMapFilename;
477 
478  return nullptr;
479  }
480 
481  // Check whether we can build this module at all.
483  CI.getDiagnostics(), M))
484  return nullptr;
485 
486  // Inform the preprocessor that includes from within the input buffer should
487  // be resolved relative to the build directory of the module map file.
489 
490  // If the module was inferred from a different module map (via an expanded
491  // umbrella module definition), track that fact.
492  // FIXME: It would be preferable to fill this in as part of processing
493  // the module map, rather than adding it after the fact.
494  StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
495  if (!OriginalModuleMapName.empty()) {
496  auto OriginalModuleMap =
497  CI.getFileManager().getFile(OriginalModuleMapName,
498  /*openFile*/ true);
499  if (!OriginalModuleMap) {
500  CI.getDiagnostics().Report(diag::err_module_map_not_found)
501  << OriginalModuleMapName;
502  return nullptr;
503  }
504  if (*OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
506  M->IsInferred = true;
508  .setInferredModuleAllowedBy(M, *OriginalModuleMap);
509  }
510  }
511 
512  // If we're being run from the command-line, the module build stack will not
513  // have been filled in yet, so complete it now in order to allow us to detect
514  // module cycles.
515  SourceManager &SourceMgr = CI.getSourceManager();
516  if (SourceMgr.getModuleBuildStack().empty())
518  FullSourceLoc(SourceLocation(), SourceMgr));
519  return M;
520 }
521 
522 /// Compute the input buffer that should be used to build the specified module.
523 static std::unique_ptr<llvm::MemoryBuffer>
525  FileManager &FileMgr = CI.getFileManager();
526 
527  // Collect the set of #includes we need to build the module.
528  SmallString<256> HeaderContents;
529  std::error_code Err = std::error_code();
530  if (Module::Header UmbrellaHeader = M->getUmbrellaHeader())
531  addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
532  CI.getLangOpts(), M->IsExternC);
534  CI.getLangOpts(), FileMgr, CI.getDiagnostics(),
536  HeaderContents);
537 
538  if (Err) {
539  CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
540  << M->getFullModuleName() << Err.message();
541  return nullptr;
542  }
543 
544  return llvm::MemoryBuffer::getMemBufferCopy(
545  HeaderContents, Module::getModuleInputBufferName());
546 }
547 
549  const FrontendInputFile &RealInput) {
550  FrontendInputFile Input(RealInput);
551  assert(!Instance && "Already processing a source file!");
552  assert(!Input.isEmpty() && "Unexpected empty filename!");
553  setCurrentInput(Input);
554  setCompilerInstance(&CI);
555 
556  bool HasBegunSourceFile = false;
557  bool ReplayASTFile = Input.getKind().getFormat() == InputKind::Precompiled &&
559  if (!BeginInvocation(CI))
560  goto failure;
561 
562  // If we're replaying the build of an AST file, import it and set up
563  // the initial state from its build.
564  if (ReplayASTFile) {
566 
567  // The AST unit populates its own diagnostics engine rather than ours.
569  new DiagnosticsEngine(Diags->getDiagnosticIDs(),
570  &Diags->getDiagnosticOptions()));
571  ASTDiags->setClient(Diags->getClient(), /*OwnsClient*/false);
572 
573  // FIXME: What if the input is a memory buffer?
574  StringRef InputFile = Input.getFile();
575 
576  std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
577  std::string(InputFile), CI.getPCHContainerReader(),
579  CI.getCodeGenOpts().DebugTypeExtRefs);
580  if (!AST)
581  goto failure;
582 
583  // Options relating to how we treat the input (but not what we do with it)
584  // are inherited from the AST unit.
585  CI.getHeaderSearchOpts() = AST->getHeaderSearchOpts();
586  CI.getPreprocessorOpts() = AST->getPreprocessorOpts();
587  CI.getLangOpts() = AST->getLangOpts();
588 
589  // Set the shared objects, these are reset when we finish processing the
590  // file, otherwise the CompilerInstance will happily destroy them.
591  CI.setFileManager(&AST->getFileManager());
593  CI.getSourceManager().initializeForReplay(AST->getSourceManager());
594 
595  // Preload all the module files loaded transitively by the AST unit. Also
596  // load all module map files that were parsed as part of building the AST
597  // unit.
598  if (auto ASTReader = AST->getASTReader()) {
599  auto &MM = ASTReader->getModuleManager();
600  auto &PrimaryModule = MM.getPrimaryModule();
601 
602  for (serialization::ModuleFile &MF : MM)
603  if (&MF != &PrimaryModule)
604  CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName);
605 
607  PrimaryModule, [&](const FileEntry *FE) {
608  CI.getFrontendOpts().ModuleMapFiles.push_back(
609  std::string(FE->getName()));
610  });
611  }
612 
613  // Set up the input file for replay purposes.
614  auto Kind = AST->getInputKind();
615  if (Kind.getFormat() == InputKind::ModuleMap) {
616  Module *ASTModule =
617  AST->getPreprocessor().getHeaderSearchInfo().lookupModule(
618  AST->getLangOpts().CurrentModule, /*AllowSearch*/ false);
619  assert(ASTModule && "module file does not define its own module");
620  Input = FrontendInputFile(ASTModule->PresumedModuleMapFile, Kind);
621  } else {
622  auto &OldSM = AST->getSourceManager();
623  FileID ID = OldSM.getMainFileID();
624  if (auto *File = OldSM.getFileEntryForID(ID))
625  Input = FrontendInputFile(File->getName(), Kind);
626  else
627  Input = FrontendInputFile(OldSM.getBufferOrFake(ID), Kind);
628  }
629  setCurrentInput(Input, std::move(AST));
630  }
631 
632  // AST files follow a very different path, since they share objects via the
633  // AST unit.
634  if (Input.getKind().getFormat() == InputKind::Precompiled) {
635  assert(!usesPreprocessorOnly() && "this case was handled above");
636  assert(hasASTFileSupport() &&
637  "This action does not have AST file support!");
638 
640 
641  // FIXME: What if the input is a memory buffer?
642  StringRef InputFile = Input.getFile();
643 
644  std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
645  std::string(InputFile), CI.getPCHContainerReader(),
647  CI.getCodeGenOpts().DebugTypeExtRefs);
648 
649  if (!AST)
650  goto failure;
651 
652  // Inform the diagnostic client we are processing a source file.
653  CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
654  HasBegunSourceFile = true;
655 
656  // Set the shared objects, these are reset when we finish processing the
657  // file, otherwise the CompilerInstance will happily destroy them.
658  CI.setFileManager(&AST->getFileManager());
659  CI.setSourceManager(&AST->getSourceManager());
660  CI.setPreprocessor(AST->getPreprocessorPtr());
661  Preprocessor &PP = CI.getPreprocessor();
663  PP.getLangOpts());
664  CI.setASTContext(&AST->getASTContext());
665 
666  setCurrentInput(Input, std::move(AST));
667 
668  // Initialize the action.
669  if (!BeginSourceFileAction(CI))
670  goto failure;
671 
672  // Create the AST consumer.
673  CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
674  if (!CI.hasASTConsumer())
675  goto failure;
676 
677  return true;
678  }
679 
680  // Set up the file and source managers, if needed.
681  if (!CI.hasFileManager()) {
682  if (!CI.createFileManager()) {
683  goto failure;
684  }
685  }
686  if (!CI.hasSourceManager())
688 
689  // Set up embedding for any specified files. Do this before we load any
690  // source files, including the primary module map for the compilation.
691  for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
692  if (auto FE = CI.getFileManager().getFile(F, /*openFile*/true))
694  else
695  CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
696  }
699 
700  // IR files bypass the rest of initialization.
701  if (Input.getKind().getLanguage() == Language::LLVM_IR) {
702  assert(hasIRSupport() &&
703  "This action does not have IR file support!");
704 
705  // Inform the diagnostic client we are processing a source file.
706  CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
707  HasBegunSourceFile = true;
708 
709  // Initialize the action.
710  if (!BeginSourceFileAction(CI))
711  goto failure;
712 
713  // Initialize the main file entry.
714  if (!CI.InitializeSourceManager(CurrentInput))
715  goto failure;
716 
717  return true;
718  }
719 
720  // If the implicit PCH include is actually a directory, rather than
721  // a single file, search for a suitable PCH file in that directory.
722  if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
723  FileManager &FileMgr = CI.getFileManager();
725  StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
726  std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
727  if (auto PCHDir = FileMgr.getDirectory(PCHInclude)) {
728  std::error_code EC;
729  SmallString<128> DirNative;
730  llvm::sys::path::native((*PCHDir)->getName(), DirNative);
731  bool Found = false;
732  llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
733  for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
734  DirEnd;
735  Dir != DirEnd && !EC; Dir.increment(EC)) {
736  // Check whether this is an acceptable AST file.
738  Dir->path(), FileMgr, CI.getPCHContainerReader(),
740  SpecificModuleCachePath)) {
741  PPOpts.ImplicitPCHInclude = std::string(Dir->path());
742  Found = true;
743  break;
744  }
745  }
746 
747  if (!Found) {
748  CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
749  goto failure;
750  }
751  }
752  }
753 
754  // Set up the preprocessor if needed. When parsing model files the
755  // preprocessor of the original source is reused.
756  if (!isModelParsingAction())
758 
759  // Inform the diagnostic client we are processing a source file.
761  &CI.getPreprocessor());
762  HasBegunSourceFile = true;
763 
764  // Initialize the main file entry.
765  if (!CI.InitializeSourceManager(Input))
766  goto failure;
767 
768  // For module map files, we first parse the module map and synthesize a
769  // "<module-includes>" buffer before more conventional processing.
770  if (Input.getKind().getFormat() == InputKind::ModuleMap) {
771  CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
772 
773  std::string PresumedModuleMapFile;
774  unsigned OffsetToContents;
775  if (loadModuleMapForModuleBuild(CI, Input.isSystem(),
776  Input.isPreprocessed(),
777  PresumedModuleMapFile, OffsetToContents))
778  goto failure;
779 
780  auto *CurrentModule = prepareToBuildModule(CI, Input.getFile());
781  if (!CurrentModule)
782  goto failure;
783 
784  CurrentModule->PresumedModuleMapFile = PresumedModuleMapFile;
785 
786  if (OffsetToContents)
787  // If the module contents are in the same file, skip to them.
788  CI.getPreprocessor().setSkipMainFilePreamble(OffsetToContents, true);
789  else {
790  // Otherwise, convert the module description to a suitable input buffer.
791  auto Buffer = getInputBufferForModule(CI, CurrentModule);
792  if (!Buffer)
793  goto failure;
794 
795  // Reinitialize the main file entry to refer to the new input.
796  auto Kind = CurrentModule->IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
797  auto &SourceMgr = CI.getSourceManager();
798  auto BufferID = SourceMgr.createFileID(std::move(Buffer), Kind);
799  assert(BufferID.isValid() && "couldn't create module buffer ID");
800  SourceMgr.setMainFileID(BufferID);
801  }
802  }
803 
804  // Initialize the action.
805  if (!BeginSourceFileAction(CI))
806  goto failure;
807 
808  // If we were asked to load any module map files, do so now.
809  for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
810  if (auto File = CI.getFileManager().getFile(Filename))
812  *File, /*IsSystem*/false);
813  else
814  CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
815  }
816 
817  // Add a module declaration scope so that modules from -fmodule-map-file
818  // arguments may shadow modules found implicitly in search paths.
819  CI.getPreprocessor()
821  .getModuleMap()
823 
824  // Create the AST context and consumer unless this is a preprocessor only
825  // action.
826  if (!usesPreprocessorOnly()) {
827  // Parsing a model file should reuse the existing ASTContext.
828  if (!isModelParsingAction())
829  CI.createASTContext();
830 
831  // For preprocessed files, check if the first line specifies the original
832  // source file name with a linemarker.
833  std::string PresumedInputFile = std::string(getCurrentFileOrBufferName());
834  if (Input.isPreprocessed())
835  ReadOriginalFileName(CI, PresumedInputFile);
836 
837  std::unique_ptr<ASTConsumer> Consumer =
838  CreateWrappedASTConsumer(CI, PresumedInputFile);
839  if (!Consumer)
840  goto failure;
841 
842  // FIXME: should not overwrite ASTMutationListener when parsing model files?
843  if (!isModelParsingAction())
844  CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
845 
846  if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
847  // Convert headers to PCH and chain them.
848  IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
849  source = createChainedIncludesSource(CI, FinalReader);
850  if (!source)
851  goto failure;
852  CI.setASTReader(static_cast<ASTReader *>(FinalReader.get()));
853  CI.getASTContext().setExternalSource(source);
854  } else if (CI.getLangOpts().Modules ||
855  !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
856  // Use PCM or PCH.
857  assert(hasPCHSupport() && "This action does not have PCH support!");
858  ASTDeserializationListener *DeserialListener =
859  Consumer->GetASTDeserializationListener();
860  bool DeleteDeserialListener = false;
862  DeserialListener = new DeserializedDeclsDumper(DeserialListener,
863  DeleteDeserialListener);
864  DeleteDeserialListener = true;
865  }
867  DeserialListener = new DeserializedDeclsChecker(
868  CI.getASTContext(),
870  DeserialListener, DeleteDeserialListener);
871  DeleteDeserialListener = true;
872  }
873  if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
877  CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, DeserialListener,
878  DeleteDeserialListener);
879  if (!CI.getASTContext().getExternalSource())
880  goto failure;
881  }
882  // If modules are enabled, create the AST reader before creating
883  // any builtins, so that all declarations know that they might be
884  // extended by an external source.
885  if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
887  CI.createASTReader();
888  CI.getASTReader()->setDeserializationListener(DeserialListener,
889  DeleteDeserialListener);
890  }
891  }
892 
893  CI.setASTConsumer(std::move(Consumer));
894  if (!CI.hasASTConsumer())
895  goto failure;
896  }
897 
898  // Initialize built-in info as long as we aren't using an external AST
899  // source.
900  if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
902  Preprocessor &PP = CI.getPreprocessor();
904  PP.getLangOpts());
905  } else {
906  // FIXME: If this is a problem, recover from it by creating a multiplex
907  // source.
908  assert((!CI.getLangOpts().Modules || CI.getASTReader()) &&
909  "modules enabled but created an external source that "
910  "doesn't support modules");
911  }
912 
913  // If we were asked to load any module files, do so now.
914  for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
915  if (!CI.loadModuleFile(ModuleFile))
916  goto failure;
917 
918  // If there is a layout overrides file, attach an external AST source that
919  // provides the layouts from that file.
920  if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
923  Override(new LayoutOverrideSource(
925  CI.getASTContext().setExternalSource(Override);
926  }
927 
928  return true;
929 
930  // If we failed, reset state since the client will not end up calling the
931  // matching EndSourceFile().
932 failure:
933  if (HasBegunSourceFile)
935  CI.clearOutputFiles(/*EraseFiles=*/true);
936  CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
938  setCompilerInstance(nullptr);
939  return false;
940 }
941 
944 
945  if (CI.hasFrontendTimer()) {
946  llvm::TimeRegion Timer(CI.getFrontendTimer());
947  ExecuteAction();
948  }
949  else ExecuteAction();
950 
951  // If we are supposed to rebuild the global module index, do so now unless
952  // there were any module-build failures.
953  if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
954  CI.hasPreprocessor()) {
955  StringRef Cache =
957  if (!Cache.empty()) {
960  // FIXME this drops the error on the floor, but
961  // Index/pch-from-libclang.c seems to rely on dropping at least some of
962  // the error conditions!
963  consumeError(std::move(Err));
964  }
965  }
966  }
967 
968  return llvm::Error::success();
969 }
970 
973 
974  // Inform the diagnostic client we are done with this source file.
976 
977  // Inform the preprocessor we are done.
978  if (CI.hasPreprocessor())
980 
981  // Finalize the action.
983 
984  // Sema references the ast consumer, so reset sema first.
985  //
986  // FIXME: There is more per-file stuff we could just drop here?
987  bool DisableFree = CI.getFrontendOpts().DisableFree;
988  if (DisableFree) {
989  CI.resetAndLeakSema();
991  llvm::BuryPointer(CI.takeASTConsumer().get());
992  } else {
993  CI.setSema(nullptr);
994  CI.setASTContext(nullptr);
995  CI.setASTConsumer(nullptr);
996  }
997 
998  if (CI.getFrontendOpts().ShowStats) {
999  llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
1000  CI.getPreprocessor().PrintStats();
1004  llvm::errs() << "\n";
1005  }
1006 
1007  // Cleanup the output streams, and erase the output files if instructed by the
1008  // FrontendAction.
1009  CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
1010 
1011  if (isCurrentFileAST()) {
1012  if (DisableFree) {
1016  llvm::BuryPointer(std::move(CurrentASTUnit));
1017  } else {
1018  CI.setPreprocessor(nullptr);
1019  CI.setSourceManager(nullptr);
1020  CI.setFileManager(nullptr);
1021  }
1022  }
1023 
1024  setCompilerInstance(nullptr);
1026  CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
1027 }
1028 
1031 }
1032 
1033 //===----------------------------------------------------------------------===//
1034 // Utility Actions
1035 //===----------------------------------------------------------------------===//
1036 
1039  if (!CI.hasPreprocessor())
1040  return;
1041 
1042  // FIXME: Move the truncation aspect of this into Sema, we delayed this till
1043  // here so the source manager would be initialized.
1044  if (hasCodeCompletionSupport() &&
1047 
1048  // Use a code completion consumer?
1049  CodeCompleteConsumer *CompletionConsumer = nullptr;
1050  if (CI.hasCodeCompletionConsumer())
1051  CompletionConsumer = &CI.getCodeCompletionConsumer();
1052 
1053  if (!CI.hasSema())
1054  CI.createSema(getTranslationUnitKind(), CompletionConsumer);
1055 
1058 }
1059 
1060 void PluginASTAction::anchor() { }
1061 
1062 std::unique_ptr<ASTConsumer>
1064  StringRef InFile) {
1065  llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
1066 }
1067 
1069  return WrappedAction->PrepareToExecuteAction(CI);
1070 }
1071 std::unique_ptr<ASTConsumer>
1073  StringRef InFile) {
1074  return WrappedAction->CreateASTConsumer(CI, InFile);
1075 }
1077  return WrappedAction->BeginInvocation(CI);
1078 }
1080  WrappedAction->setCurrentInput(getCurrentInput());
1081  WrappedAction->setCompilerInstance(&CI);
1082  auto Ret = WrappedAction->BeginSourceFileAction(CI);
1083  // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
1084  setCurrentInput(WrappedAction->getCurrentInput());
1085  return Ret;
1086 }
1088  WrappedAction->ExecuteAction();
1089 }
1091  WrappedAction->EndSourceFileAction();
1092 }
1094  return WrappedAction->shouldEraseOutputFiles();
1095 }
1096 
1098  return WrappedAction->usesPreprocessorOnly();
1099 }
1101  return WrappedAction->getTranslationUnitKind();
1102 }
1104  return WrappedAction->hasPCHSupport();
1105 }
1107  return WrappedAction->hasASTFileSupport();
1108 }
1110  return WrappedAction->hasIRSupport();
1111 }
1113  return WrappedAction->hasCodeCompletionSupport();
1114 }
1115 
1117  std::unique_ptr<FrontendAction> WrappedAction)
1118  : WrappedAction(std::move(WrappedAction)) {}
1119 
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
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:5400
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:400
void setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap)
Definition: ModuleMap.cpp:1260
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:76
bool hasErrorOccurred() const
Definition: Diagnostic.h:795
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:228
A (possibly-)qualified type.
Definition: Type.h:661
const char * getDeclKindName() const
Definition: DeclBase.cpp:123
FileManager * createFileManager(IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr)
Create the file manager and replace any existing one with it.
std::vector< Module * >::iterator submodule_iterator
Definition: Module.h:616
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
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:619
TypePropertyCache< Private > Cache
Definition: Type.cpp:3807
virtual bool hasIRSupport() const
Does this action support use with IR files?
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...
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 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition: Module.h:273
void createSema(TranslationUnitKind TUKind, CodeCompleteConsumer *CompletionConsumer)
Create the Sema object to be used for parsing.
Load everything, including Sema.
Definition: ASTUnit.h:678
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:89
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:1469
bool InitializeSourceManager(const FrontendInputFile &Input)
InitializeSourceManager - Initialize the source manager to set InputFile as the main file.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
ASTContext & getASTContext() const
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:1700
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:699
Builtin::Context & getBuiltinInfo()
Definition: Preprocessor.h:932
virtual bool hasCodeCompletionSupport() const
Does this action support use with code completion?
IntrusiveRefCntPtr< ASTReader > getASTReader() const
std::string PresumedModuleMapFile
The presumed file name for the module map defining this module.
Definition: Module.h:133
tok::TokenKind getKind() const
Definition: Token.h:92
One of these records is kept for each identifier that is lexed.
static StringRef getModuleInputBufferName()
Definition: Module.h:637
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:186
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.
static llvm::Error writeIndex(FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, llvm::StringRef Path)
Write a global index into the given.
void resolveHeaderDirectives(const FileEntry *File) const
Resolve all lazy header directives for the specified file.
Definition: ModuleMap.cpp:1179
Definition: Format.h:3142
Module * getCurrentModule() const
bool shouldEraseOutputFiles() override
Callback at the end of processing a single input, to determine if the output files should be erased o...
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:548
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:695
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
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:576
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:57
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:922
Compiling a module from a module map.
Definition: LangOptions.h:87
std::vector< std::string > ModulesEmbedFiles
The list of files to embed into the compiled module file.
Describes a module or submodule.
Definition: Module.h:96
Execute the action before the main action.
CompilerInstance & getCompilerInstance() const
bool hasPCHSupport() const override
Does this action support use with PCH?
llvm::ErrorOr< const DirectoryEntry * > getDirectory(StringRef DirName, bool CacheFailure=true)
Lookup, cache, and verify the specified directory (real or virtual).
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:221
ModuleBuildStack getModuleBuildStack() const
Retrieve the module build stack.
HeaderSearch & getHeaderSearchInfo() const
Definition: Preprocessor.h:927
FrontendOptions & getFrontendOpts()
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1674
StringRef getCurrentFileOrBufferName() const
Load options and the preprocessor state.
Definition: ASTUnit.h:672
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:191
Module * Parent
The parent of this module.
Definition: Module.h:124
unsigned IsInferred
Whether this is an inferred submodule (module * { ... }).
Definition: Module.h:276
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:621
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)
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,...
Definition: HeaderSearch.h:158
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
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:304
StringRef Filename
Definition: Format.cpp:2079
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.
unsigned Offset
Definition: Format.cpp:2081
bool hasIRSupport() const override
Does this action support use with IR files?
SourceLocation End
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
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:126
Defines the clang::Preprocessor interface.
Not compiling a module interface at all.
Definition: LangOptions.h:84
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'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: ModuleFile.h:110
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.
bool PrepareToExecuteAction(CompilerInstance &CI) override
Prepare to execute the action on the given CompilerInstance.
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:440
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:129
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.
StringRef getName() const
Definition: FileEntry.h:364
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're handling.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
static bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.cpp:34
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:929
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:331
SmallVector< Header, 2 > Headers[5]
The headers that are part of this module.
Definition: Module.h:208
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:89
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:268
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:824
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...
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:168
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:98
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
Definition: ASTBitCodes.h:153
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
llvm::Error Execute()
Set the source manager's main input file, and run the action.
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:341
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:1052
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.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1043
uint32_t DeclID
An ID number that refers to a declaration in an AST file.
Definition: ASTBitCodes.h:68
void clearOutputFiles(bool EraseFiles)
clearOutputFiles - Clear the output file list.
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
TargetInfo & getTarget() const
uint32_t IdentID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:134
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:9115
void setCompilerInstance(CompilerInstance *Value)
std::string getSpecificModuleCachePath(StringRef ModuleHash)
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:246
void setASTReader(IntrusiveRefCntPtr< ASTReader > Reader)
std::vector< std::string > AddPluginActions
The list of plugin actions to run in addition to the normal action.
unsigned DisableFree
Disable memory freeing on exit.
The type-property cache.
Definition: Type.cpp:3761
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...
void addTopHeader(const FileEntry *File)
Add a top-level header associated with this module.
Definition: Module.cpp:256
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:640
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
LLVM IR: we accept this so that we can run the optimizer on it, and compile it to assembly or object ...
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< ASTUnit > LoadFromASTFile(const std::string &Filename, const PCHContainerReader &PCHContainerRdr, WhatToLoad ToLoad, IntrusiveRefCntPtr< DiagnosticsEngine > Diags, const FileSystemOptions &FileSystemOpts, bool UseDebugInfo=false, bool OnlyLocalDecls=false, CaptureDiagsKind CaptureDiagnostics=CaptureDiagsKind::None, bool AllowASTWithCompilerErrors=false, bool UserFilesAreVolatile=false)
Create a ASTUnit from an AST file.
Definition: ASTUnit.cpp:757
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:223
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:1692
static SmallVectorImpl< char > & operator+=(SmallVectorImpl< char > &Includes, StringRef RHS)
TargetOptions & getTargetOpts()
FullSourceLoc getFullLoc(SourceLocation Loc) const
Definition: ASTContext.h:696
llvm::vfs::FileSystem & getVirtualFileSystem() const
Definition: FileManager.h:243
This class handles loading and caching of source files into memory.
static void addHeaderInclude(StringRef HeaderName, SmallVectorImpl< char > &Includes, const LangOptions &LangOpts, bool IsExternC)
Defines enum values for all the target-independent builtin functions.
bool Sub(InterpState &S, CodePtr OpPC)
Definition: Interp.h:140
A type index; the type ID with the qualifier bits removed.
Definition: ASTBitCodes.h:88
SourceLocation getLocation() const
Definition: DeclBase.h:430
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:129
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.