clang  16.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"
16 #include "clang/Basic/Sarif.h"
17 #include "clang/Frontend/ASTUnit.h"
24 #include "clang/Frontend/Utils.h"
25 #include "clang/Lex/HeaderSearch.h"
27 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Parse/ParseAST.h"
35 #include "llvm/ADT/ScopeExit.h"
36 #include "llvm/Support/BuryPointer.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Timer.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <memory>
43 #include <system_error>
44 using namespace clang;
45 
46 LLVM_INSTANTIATE_REGISTRY(FrontendPluginRegistry)
47 
48 namespace {
49 
50 class DelegatingDeserializationListener : public ASTDeserializationListener {
52  bool DeletePrevious;
53 
54 public:
55  explicit DelegatingDeserializationListener(
56  ASTDeserializationListener *Previous, bool DeletePrevious)
57  : Previous(Previous), DeletePrevious(DeletePrevious) {}
58  ~DelegatingDeserializationListener() override {
59  if (DeletePrevious)
60  delete Previous;
61  }
62 
63  void ReaderInitialized(ASTReader *Reader) override {
64  if (Previous)
65  Previous->ReaderInitialized(Reader);
66  }
67  void IdentifierRead(serialization::IdentID ID,
68  IdentifierInfo *II) override {
69  if (Previous)
70  Previous->IdentifierRead(ID, II);
71  }
72  void TypeRead(serialization::TypeIdx Idx, QualType T) override {
73  if (Previous)
74  Previous->TypeRead(Idx, T);
75  }
76  void DeclRead(serialization::DeclID ID, const Decl *D) override {
77  if (Previous)
78  Previous->DeclRead(ID, D);
79  }
80  void SelectorRead(serialization::SelectorID ID, Selector Sel) override {
81  if (Previous)
82  Previous->SelectorRead(ID, Sel);
83  }
84  void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
85  MacroDefinitionRecord *MD) override {
86  if (Previous)
87  Previous->MacroDefinitionRead(PPID, MD);
88  }
89 };
90 
91 /// Dumps deserialized declarations.
92 class DeserializedDeclsDumper : public DelegatingDeserializationListener {
93 public:
94  explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous,
95  bool DeletePrevious)
96  : DelegatingDeserializationListener(Previous, DeletePrevious) {}
97 
98  void DeclRead(serialization::DeclID ID, const Decl *D) override {
99  llvm::outs() << "PCH DECL: " << D->getDeclKindName();
100  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
101  llvm::outs() << " - ";
102  ND->printQualifiedName(llvm::outs());
103  }
104  llvm::outs() << "\n";
105 
106  DelegatingDeserializationListener::DeclRead(ID, D);
107  }
108 };
109 
110 /// Checks deserialized declarations and emits error if a name
111 /// matches one given in command-line using -error-on-deserialized-decl.
112 class DeserializedDeclsChecker : public DelegatingDeserializationListener {
113  ASTContext &Ctx;
114  std::set<std::string> NamesToCheck;
115 
116 public:
117  DeserializedDeclsChecker(ASTContext &Ctx,
118  const std::set<std::string> &NamesToCheck,
120  bool DeletePrevious)
121  : DelegatingDeserializationListener(Previous, DeletePrevious), Ctx(Ctx),
122  NamesToCheck(NamesToCheck) {}
123 
124  void DeclRead(serialization::DeclID ID, const Decl *D) override {
125  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
126  if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
127  unsigned DiagID
129  "%0 was deserialized");
130  Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
131  << ND;
132  }
133 
134  DelegatingDeserializationListener::DeclRead(ID, D);
135  }
136 };
137 
138 } // end anonymous namespace
139 
140 FrontendAction::FrontendAction() : Instance(nullptr) {}
141 
143 
145  std::unique_ptr<ASTUnit> AST) {
146  this->CurrentInput = CurrentInput;
147  CurrentASTUnit = std::move(AST);
148 }
149 
153  CI.getLangOpts().CurrentModule, SourceLocation(), /*AllowSearch*/false);
154 }
155 
156 std::unique_ptr<ASTConsumer>
157 FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
158  StringRef InFile) {
159  std::unique_ptr<ASTConsumer> Consumer = CreateASTConsumer(CI, InFile);
160  if (!Consumer)
161  return nullptr;
162 
163  // Validate -add-plugin args.
164  bool FoundAllPlugins = true;
165  for (const std::string &Arg : CI.getFrontendOpts().AddPluginActions) {
166  bool Found = false;
167  for (const FrontendPluginRegistry::entry &Plugin :
168  FrontendPluginRegistry::entries()) {
169  if (Plugin.getName() == Arg)
170  Found = true;
171  }
172  if (!Found) {
173  CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name) << Arg;
174  FoundAllPlugins = false;
175  }
176  }
177  if (!FoundAllPlugins)
178  return nullptr;
179 
180  // If there are no registered plugins we don't need to wrap the consumer
181  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
182  return Consumer;
183 
184  // If this is a code completion run, avoid invoking the plugin consumers
185  if (CI.hasCodeCompletionConsumer())
186  return Consumer;
187 
188  // Collect the list of plugins that go before the main action (in Consumers)
189  // or after it (in AfterConsumers)
190  std::vector<std::unique_ptr<ASTConsumer>> Consumers;
191  std::vector<std::unique_ptr<ASTConsumer>> AfterConsumers;
192  for (const FrontendPluginRegistry::entry &Plugin :
193  FrontendPluginRegistry::entries()) {
194  std::unique_ptr<PluginASTAction> P = Plugin.instantiate();
195  PluginASTAction::ActionType ActionType = P->getActionType();
196  if (ActionType == PluginASTAction::CmdlineAfterMainAction ||
198  // This is O(|plugins| * |add_plugins|), but since both numbers are
199  // way below 50 in practice, that's ok.
200  if (llvm::is_contained(CI.getFrontendOpts().AddPluginActions,
201  Plugin.getName())) {
204  else
206  }
207  }
208  if ((ActionType == PluginASTAction::AddBeforeMainAction ||
209  ActionType == PluginASTAction::AddAfterMainAction) &&
210  P->ParseArgs(
211  CI,
212  CI.getFrontendOpts().PluginArgs[std::string(Plugin.getName())])) {
213  std::unique_ptr<ASTConsumer> PluginConsumer = P->CreateASTConsumer(CI, InFile);
214  if (ActionType == PluginASTAction::AddBeforeMainAction) {
215  Consumers.push_back(std::move(PluginConsumer));
216  } else {
217  AfterConsumers.push_back(std::move(PluginConsumer));
218  }
219  }
220  }
221 
222  // Add to Consumers the main consumer, then all the plugins that go after it
223  Consumers.push_back(std::move(Consumer));
224  if (!AfterConsumers.empty()) {
225  // If we have plugins after the main consumer, which may be the codegen
226  // action, they likely will need the ASTContext, so don't clear it in the
227  // codegen action.
228  CI.getCodeGenOpts().ClearASTBeforeBackend = false;
229  for (auto &C : AfterConsumers)
230  Consumers.push_back(std::move(C));
231  }
232 
233  return std::make_unique<MultiplexConsumer>(std::move(Consumers));
234 }
235 
236 /// For preprocessed files, if the first line is the linemarker and specifies
237 /// the original source file name, use that name as the input file name.
238 /// Returns the location of the first token after the line marker directive.
239 ///
240 /// \param CI The compiler instance.
241 /// \param InputFile Populated with the filename from the line marker.
242 /// \param IsModuleMap If \c true, add a line note corresponding to this line
243 /// directive. (We need to do this because the directive will not be
244 /// visited by the preprocessor.)
246  std::string &InputFile,
247  bool IsModuleMap = false) {
248  auto &SourceMgr = CI.getSourceManager();
249  auto MainFileID = SourceMgr.getMainFileID();
250 
251  auto MainFileBuf = SourceMgr.getBufferOrNone(MainFileID);
252  if (!MainFileBuf)
253  return SourceLocation();
254 
255  std::unique_ptr<Lexer> RawLexer(
256  new Lexer(MainFileID, *MainFileBuf, SourceMgr, CI.getLangOpts()));
257 
258  // If the first line has the syntax of
259  //
260  // # NUM "FILENAME"
261  //
262  // we use FILENAME as the input file name.
263  Token T;
264  if (RawLexer->LexFromRawLexer(T) || T.getKind() != tok::hash)
265  return SourceLocation();
266  if (RawLexer->LexFromRawLexer(T) || T.isAtStartOfLine() ||
267  T.getKind() != tok::numeric_constant)
268  return SourceLocation();
269 
270  unsigned LineNo;
271  SourceLocation LineNoLoc = T.getLocation();
272  if (IsModuleMap) {
273  llvm::SmallString<16> Buffer;
274  if (Lexer::getSpelling(LineNoLoc, Buffer, SourceMgr, CI.getLangOpts())
275  .getAsInteger(10, LineNo))
276  return SourceLocation();
277  }
278 
279  RawLexer->LexFromRawLexer(T);
280  if (T.isAtStartOfLine() || T.getKind() != tok::string_literal)
281  return SourceLocation();
282 
284  if (Literal.hadError)
285  return SourceLocation();
286  RawLexer->LexFromRawLexer(T);
287  if (T.isNot(tok::eof) && !T.isAtStartOfLine())
288  return SourceLocation();
289  InputFile = Literal.GetString().str();
290 
291  if (IsModuleMap)
293  LineNoLoc, LineNo, SourceMgr.getLineTableFilenameID(InputFile), false,
294  false, SrcMgr::C_User_ModuleMap);
295 
296  return T.getLocation();
297 }
298 
299 static SmallVectorImpl<char> &
300 operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
301  Includes.append(RHS.begin(), RHS.end());
302  return Includes;
303 }
304 
305 static void addHeaderInclude(StringRef HeaderName,
306  SmallVectorImpl<char> &Includes,
307  const LangOptions &LangOpts,
308  bool IsExternC) {
309  if (IsExternC && LangOpts.CPlusPlus)
310  Includes += "extern \"C\" {\n";
311  if (LangOpts.ObjC)
312  Includes += "#import \"";
313  else
314  Includes += "#include \"";
315 
316  Includes += HeaderName;
317 
318  Includes += "\"\n";
319  if (IsExternC && LangOpts.CPlusPlus)
320  Includes += "}\n";
321 }
322 
323 /// Collect the set of header includes needed to construct the given
324 /// module and update the TopHeaders file set of the module.
325 ///
326 /// \param Module The module we're collecting includes from.
327 ///
328 /// \param Includes Will be augmented with the set of \#includes or \#imports
329 /// needed to load all of the named headers.
330 static std::error_code collectModuleHeaderIncludes(
331  const LangOptions &LangOpts, FileManager &FileMgr, DiagnosticsEngine &Diag,
332  ModuleMap &ModMap, clang::Module *Module, SmallVectorImpl<char> &Includes) {
333  // Don't collect any headers for unavailable modules.
334  if (!Module->isAvailable())
335  return std::error_code();
336 
337  // Resolve all lazy header directives to header files.
338  ModMap.resolveHeaderDirectives(Module, /*File=*/llvm::None);
339 
340  // If any headers are missing, we can't build this module. In most cases,
341  // diagnostics for this should have already been produced; we only get here
342  // if explicit stat information was provided.
343  // FIXME: If the name resolves to a file with different stat information,
344  // produce a better diagnostic.
345  if (!Module->MissingHeaders.empty()) {
346  auto &MissingHeader = Module->MissingHeaders.front();
347  Diag.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
348  << MissingHeader.IsUmbrella << MissingHeader.FileName;
349  return std::error_code();
350  }
351 
352  // Add includes for each of these headers.
353  for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
354  for (Module::Header &H : Module->Headers[HK]) {
355  Module->addTopHeader(H.Entry);
356  // Use the path as specified in the module map file. We'll look for this
357  // file relative to the module build directory (the directory containing
358  // the module map file) so this will find the same file that we found
359  // while parsing the module map.
360  addHeaderInclude(H.PathRelativeToRootModuleDirectory, Includes, LangOpts,
361  Module->IsExternC);
362  }
363  }
364  // Note that Module->PrivateHeaders will not be a TopHeader.
365 
366  if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
367  Module->addTopHeader(UmbrellaHeader.Entry);
368  if (Module->Parent)
369  // Include the umbrella header for submodules.
370  addHeaderInclude(UmbrellaHeader.PathRelativeToRootModuleDirectory,
371  Includes, LangOpts, Module->IsExternC);
372  } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
373  // Add all of the headers we find in this subdirectory.
374  std::error_code EC;
375  SmallString<128> DirNative;
376  llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
377 
378  llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
380  for (llvm::vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
381  Dir != End && !EC; Dir.increment(EC)) {
382  // Check whether this entry has an extension typically associated with
383  // headers.
384  if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
385  .Cases(".h", ".H", ".hh", ".hpp", true)
386  .Default(false))
387  continue;
388 
389  auto Header = FileMgr.getFile(Dir->path());
390  // FIXME: This shouldn't happen unless there is a file system race. Is
391  // that worth diagnosing?
392  if (!Header)
393  continue;
394 
395  // If this header is marked 'unavailable' in this module, don't include
396  // it.
397  if (ModMap.isHeaderUnavailableInModule(*Header, Module))
398  continue;
399 
400  // Compute the relative path from the directory to this file.
401  SmallVector<StringRef, 16> Components;
402  auto PathIt = llvm::sys::path::rbegin(Dir->path());
403  for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
404  Components.push_back(*PathIt);
405  SmallString<128> RelativeHeader(
406  UmbrellaDir.PathRelativeToRootModuleDirectory);
407  for (auto It = Components.rbegin(), End = Components.rend(); It != End;
408  ++It)
409  llvm::sys::path::append(RelativeHeader, *It);
410 
411  std::string RelName = RelativeHeader.c_str();
412  Headers.push_back(std::make_pair(RelName, *Header));
413  }
414 
415  if (EC)
416  return EC;
417 
418  // Sort header paths and make the header inclusion order deterministic
419  // across different OSs and filesystems.
420  llvm::sort(Headers, llvm::less_first());
421  for (auto &H : Headers) {
422  // Include this header as part of the umbrella directory.
423  Module->addTopHeader(H.second);
424  addHeaderInclude(H.first, Includes, LangOpts, Module->IsExternC);
425  }
426  }
427 
428  // Recurse into submodules.
430  SubEnd = Module->submodule_end();
431  Sub != SubEnd; ++Sub)
432  if (std::error_code Err = collectModuleHeaderIncludes(
433  LangOpts, FileMgr, Diag, ModMap, *Sub, Includes))
434  return Err;
435 
436  return std::error_code();
437 }
438 
439 static bool loadModuleMapForModuleBuild(CompilerInstance &CI, bool IsSystem,
440  bool IsPreprocessed,
441  std::string &PresumedModuleMapFile,
442  unsigned &Offset) {
443  auto &SrcMgr = CI.getSourceManager();
445 
446  // Map the current input to a file.
447  FileID ModuleMapID = SrcMgr.getMainFileID();
448  const FileEntry *ModuleMap = SrcMgr.getFileEntryForID(ModuleMapID);
449 
450  // If the module map is preprocessed, handle the initial line marker;
451  // line directives are not part of the module map syntax in general.
452  Offset = 0;
453  if (IsPreprocessed) {
454  SourceLocation EndOfLineMarker =
455  ReadOriginalFileName(CI, PresumedModuleMapFile, /*IsModuleMap*/ true);
456  if (EndOfLineMarker.isValid())
457  Offset = CI.getSourceManager().getDecomposedLoc(EndOfLineMarker).second;
458  }
459 
460  // Load the module map file.
461  if (HS.loadModuleMapFile(ModuleMap, IsSystem, ModuleMapID, &Offset,
462  PresumedModuleMapFile))
463  return true;
464 
465  if (SrcMgr.getBufferOrFake(ModuleMapID).getBufferSize() == Offset)
466  Offset = 0;
467 
468  // Infer framework module if possible.
469  if (HS.getModuleMap().canInferFrameworkModule(ModuleMap->getDir())) {
470  SmallString<128> InferredFrameworkPath = ModuleMap->getDir()->getName();
471  llvm::sys::path::append(InferredFrameworkPath,
472  CI.getLangOpts().ModuleName + ".framework");
473  if (auto Dir = CI.getFileManager().getDirectory(InferredFrameworkPath))
474  (void)HS.getModuleMap().inferFrameworkModule(*Dir, IsSystem, nullptr);
475  }
476 
477  return false;
478 }
479 
481  StringRef ModuleMapFilename) {
482  if (CI.getLangOpts().CurrentModule.empty()) {
483  CI.getDiagnostics().Report(diag::err_missing_module_name);
484 
485  // FIXME: Eventually, we could consider asking whether there was just
486  // a single module described in the module map, and use that as a
487  // default. Then it would be fairly trivial to just "compile" a module
488  // map with a single module (the common case).
489  return nullptr;
490  }
491 
492  // Dig out the module definition.
495  /*AllowSearch=*/true);
496  if (!M) {
497  CI.getDiagnostics().Report(diag::err_missing_module)
498  << CI.getLangOpts().CurrentModule << ModuleMapFilename;
499 
500  return nullptr;
501  }
502 
503  // Check whether we can build this module at all.
505  CI.getDiagnostics(), M))
506  return nullptr;
507 
508  // Inform the preprocessor that includes from within the input buffer should
509  // be resolved relative to the build directory of the module map file.
511 
512  // If the module was inferred from a different module map (via an expanded
513  // umbrella module definition), track that fact.
514  // FIXME: It would be preferable to fill this in as part of processing
515  // the module map, rather than adding it after the fact.
516  StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
517  if (!OriginalModuleMapName.empty()) {
518  auto OriginalModuleMap =
519  CI.getFileManager().getFile(OriginalModuleMapName,
520  /*openFile*/ true);
521  if (!OriginalModuleMap) {
522  CI.getDiagnostics().Report(diag::err_module_map_not_found)
523  << OriginalModuleMapName;
524  return nullptr;
525  }
526  if (*OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
528  M->IsInferred = true;
530  .setInferredModuleAllowedBy(M, *OriginalModuleMap);
531  }
532  }
533 
534  // If we're being run from the command-line, the module build stack will not
535  // have been filled in yet, so complete it now in order to allow us to detect
536  // module cycles.
537  SourceManager &SourceMgr = CI.getSourceManager();
538  if (SourceMgr.getModuleBuildStack().empty())
540  FullSourceLoc(SourceLocation(), SourceMgr));
541  return M;
542 }
543 
544 /// Compute the input buffer that should be used to build the specified module.
545 static std::unique_ptr<llvm::MemoryBuffer>
547  FileManager &FileMgr = CI.getFileManager();
548 
549  // Collect the set of #includes we need to build the module.
550  SmallString<256> HeaderContents;
551  std::error_code Err = std::error_code();
552  if (Module::Header UmbrellaHeader = M->getUmbrellaHeader())
553  addHeaderInclude(UmbrellaHeader.PathRelativeToRootModuleDirectory,
554  HeaderContents, CI.getLangOpts(), M->IsExternC);
556  CI.getLangOpts(), FileMgr, CI.getDiagnostics(),
558  HeaderContents);
559 
560  if (Err) {
561  CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
562  << M->getFullModuleName() << Err.message();
563  return nullptr;
564  }
565 
566  return llvm::MemoryBuffer::getMemBufferCopy(
567  HeaderContents, Module::getModuleInputBufferName());
568 }
569 
571  const FrontendInputFile &RealInput) {
572  FrontendInputFile Input(RealInput);
573  assert(!Instance && "Already processing a source file!");
574  assert(!Input.isEmpty() && "Unexpected empty filename!");
575  setCurrentInput(Input);
576  setCompilerInstance(&CI);
577 
578  bool HasBegunSourceFile = false;
579  bool ReplayASTFile = Input.getKind().getFormat() == InputKind::Precompiled &&
581 
582  // If we fail, reset state since the client will not end up calling the
583  // matching EndSourceFile(). All paths that return true should release this.
584  auto FailureCleanup = llvm::make_scope_exit([&]() {
585  if (HasBegunSourceFile)
587  CI.setASTConsumer(nullptr);
588  CI.clearOutputFiles(/*EraseFiles=*/true);
589  CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
591  setCompilerInstance(nullptr);
592  });
593 
594  if (!BeginInvocation(CI))
595  return false;
596 
597  // If we're replaying the build of an AST file, import it and set up
598  // the initial state from its build.
599  if (ReplayASTFile) {
601 
602  // The AST unit populates its own diagnostics engine rather than ours.
604  new DiagnosticsEngine(Diags->getDiagnosticIDs(),
605  &Diags->getDiagnosticOptions()));
606  ASTDiags->setClient(Diags->getClient(), /*OwnsClient*/false);
607 
608  // FIXME: What if the input is a memory buffer?
609  StringRef InputFile = Input.getFile();
610 
611  std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
612  std::string(InputFile), CI.getPCHContainerReader(),
614  CI.getCodeGenOpts().DebugTypeExtRefs);
615  if (!AST)
616  return false;
617 
618  // Options relating to how we treat the input (but not what we do with it)
619  // are inherited from the AST unit.
620  CI.getHeaderSearchOpts() = AST->getHeaderSearchOpts();
621  CI.getPreprocessorOpts() = AST->getPreprocessorOpts();
622  CI.getLangOpts() = AST->getLangOpts();
623 
624  // Set the shared objects, these are reset when we finish processing the
625  // file, otherwise the CompilerInstance will happily destroy them.
626  CI.setFileManager(&AST->getFileManager());
628  CI.getSourceManager().initializeForReplay(AST->getSourceManager());
629 
630  // Preload all the module files loaded transitively by the AST unit. Also
631  // load all module map files that were parsed as part of building the AST
632  // unit.
633  if (auto ASTReader = AST->getASTReader()) {
634  auto &MM = ASTReader->getModuleManager();
635  auto &PrimaryModule = MM.getPrimaryModule();
636 
637  for (serialization::ModuleFile &MF : MM)
638  if (&MF != &PrimaryModule)
639  CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName);
640 
641  ASTReader->visitTopLevelModuleMaps(PrimaryModule, [&](FileEntryRef FE) {
642  CI.getFrontendOpts().ModuleMapFiles.push_back(
643  std::string(FE.getName()));
644  });
645  }
646 
647  // Set up the input file for replay purposes.
648  auto Kind = AST->getInputKind();
649  if (Kind.getFormat() == InputKind::ModuleMap) {
650  Module *ASTModule =
651  AST->getPreprocessor().getHeaderSearchInfo().lookupModule(
652  AST->getLangOpts().CurrentModule, SourceLocation(),
653  /*AllowSearch*/ false);
654  assert(ASTModule && "module file does not define its own module");
655  Input = FrontendInputFile(ASTModule->PresumedModuleMapFile, Kind);
656  } else {
657  auto &OldSM = AST->getSourceManager();
658  FileID ID = OldSM.getMainFileID();
659  if (auto *File = OldSM.getFileEntryForID(ID))
660  Input = FrontendInputFile(File->getName(), Kind);
661  else
662  Input = FrontendInputFile(OldSM.getBufferOrFake(ID), Kind);
663  }
664  setCurrentInput(Input, std::move(AST));
665  }
666 
667  // AST files follow a very different path, since they share objects via the
668  // AST unit.
669  if (Input.getKind().getFormat() == InputKind::Precompiled) {
670  assert(!usesPreprocessorOnly() && "this case was handled above");
671  assert(hasASTFileSupport() &&
672  "This action does not have AST file support!");
673 
675 
676  // FIXME: What if the input is a memory buffer?
677  StringRef InputFile = Input.getFile();
678 
679  std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
680  std::string(InputFile), CI.getPCHContainerReader(),
682  CI.getCodeGenOpts().DebugTypeExtRefs);
683 
684  if (!AST)
685  return false;
686 
687  // Inform the diagnostic client we are processing a source file.
688  CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
689  HasBegunSourceFile = true;
690 
691  // Set the shared objects, these are reset when we finish processing the
692  // file, otherwise the CompilerInstance will happily destroy them.
693  CI.setFileManager(&AST->getFileManager());
694  CI.setSourceManager(&AST->getSourceManager());
695  CI.setPreprocessor(AST->getPreprocessorPtr());
696  Preprocessor &PP = CI.getPreprocessor();
698  PP.getLangOpts());
699  CI.setASTContext(&AST->getASTContext());
700 
701  setCurrentInput(Input, std::move(AST));
702 
703  // Initialize the action.
704  if (!BeginSourceFileAction(CI))
705  return false;
706 
707  // Create the AST consumer.
708  CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
709  if (!CI.hasASTConsumer())
710  return false;
711 
712  FailureCleanup.release();
713  return true;
714  }
715 
716  // Set up the file and source managers, if needed.
717  if (!CI.hasFileManager()) {
718  if (!CI.createFileManager()) {
719  return false;
720  }
721  }
722  if (!CI.hasSourceManager()) {
724  if (CI.getDiagnosticOpts().getFormat() == DiagnosticOptions::SARIF) {
725  static_cast<SARIFDiagnosticPrinter *>(&CI.getDiagnosticClient())
726  ->setSarifWriter(
727  std::make_unique<SarifDocumentWriter>(CI.getSourceManager()));
728  }
729  }
730 
731  // Set up embedding for any specified files. Do this before we load any
732  // source files, including the primary module map for the compilation.
733  for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
734  if (auto FE = CI.getFileManager().getFile(F, /*openFile*/true))
736  else
737  CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
738  }
741 
742  // IR files bypass the rest of initialization.
743  if (Input.getKind().getLanguage() == Language::LLVM_IR) {
744  assert(hasIRSupport() &&
745  "This action does not have IR file support!");
746 
747  // Inform the diagnostic client we are processing a source file.
748  CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
749  HasBegunSourceFile = true;
750 
751  // Initialize the action.
752  if (!BeginSourceFileAction(CI))
753  return false;
754 
755  // Initialize the main file entry.
756  if (!CI.InitializeSourceManager(CurrentInput))
757  return false;
758 
759  FailureCleanup.release();
760  return true;
761  }
762 
763  // If the implicit PCH include is actually a directory, rather than
764  // a single file, search for a suitable PCH file in that directory.
765  if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
766  FileManager &FileMgr = CI.getFileManager();
768  StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
769  std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
770  if (auto PCHDir = FileMgr.getOptionalDirectoryRef(PCHInclude)) {
771  std::error_code EC;
772  SmallString<128> DirNative;
773  llvm::sys::path::native(PCHDir->getName(), DirNative);
774  bool Found = false;
775  llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
776  for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
777  DirEnd;
778  Dir != DirEnd && !EC; Dir.increment(EC)) {
779  // Check whether this is an acceptable AST file.
781  Dir->path(), FileMgr, CI.getModuleCache(),
784  SpecificModuleCachePath, /*RequireStrictOptionMatches=*/true)) {
785  PPOpts.ImplicitPCHInclude = std::string(Dir->path());
786  Found = true;
787  break;
788  }
789  }
790 
791  if (!Found) {
792  CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
793  return false;
794  }
795  }
796  }
797 
798  // Set up the preprocessor if needed. When parsing model files the
799  // preprocessor of the original source is reused.
800  if (!isModelParsingAction())
802 
803  // Inform the diagnostic client we are processing a source file.
805  &CI.getPreprocessor());
806  HasBegunSourceFile = true;
807 
808  // Handle C++20 header units.
809  // Here, the user has the option to specify that the header name should be
810  // looked up in the pre-processor search paths (and the main filename as
811  // passed by the driver might therefore be incomplete until that look-up).
812  if (CI.getLangOpts().CPlusPlusModules && Input.getKind().isHeaderUnit() &&
813  !Input.getKind().isPreprocessed()) {
814  StringRef FileName = Input.getFile();
815  InputKind Kind = Input.getKind();
816  if (Kind.getHeaderUnitKind() != InputKind::HeaderUnit_Abs) {
817  assert(CI.hasPreprocessor() &&
818  "trying to build a header unit without a Pre-processor?");
820  // Relative searches begin from CWD.
821  const DirectoryEntry *Dir = nullptr;
822  if (auto DirOrErr = CI.getFileManager().getDirectory("."))
823  Dir = *DirOrErr;
825  CWD.push_back({nullptr, Dir});
827  HS.LookupFile(FileName, SourceLocation(),
828  /*Angled*/ Input.getKind().getHeaderUnitKind() ==
830  nullptr, nullptr, CWD, nullptr, nullptr, nullptr,
831  nullptr, nullptr, nullptr);
832  if (!FE) {
833  CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
834  << FileName;
835  return false;
836  }
837  // We now have the filename...
838  FileName = FE->getFileEntry().getName();
839  // ... still a header unit, but now use the path as written.
841  Input = FrontendInputFile(FileName, Kind, Input.isSystem());
842  }
843  // Unless the user has overridden the name, the header unit module name is
844  // the pathname for the file.
845  if (CI.getLangOpts().ModuleName.empty())
846  CI.getLangOpts().ModuleName = std::string(FileName);
848  }
849 
850  if (!CI.InitializeSourceManager(Input))
851  return false;
852 
853  if (CI.getLangOpts().CPlusPlusModules && Input.getKind().isHeaderUnit() &&
854  Input.getKind().isPreprocessed() && !usesPreprocessorOnly()) {
855  // We have an input filename like foo.iih, but we want to find the right
856  // module name (and original file, to build the map entry).
857  // Check if the first line specifies the original source file name with a
858  // linemarker.
859  std::string PresumedInputFile = std::string(getCurrentFileOrBufferName());
860  ReadOriginalFileName(CI, PresumedInputFile);
861  // Unless the user overrides this, the module name is the name by which the
862  // original file was known.
863  if (CI.getLangOpts().ModuleName.empty())
864  CI.getLangOpts().ModuleName = std::string(PresumedInputFile);
866  }
867 
868  // For module map files, we first parse the module map and synthesize a
869  // "<module-includes>" buffer before more conventional processing.
870  if (Input.getKind().getFormat() == InputKind::ModuleMap) {
871  CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
872 
873  std::string PresumedModuleMapFile;
874  unsigned OffsetToContents;
875  if (loadModuleMapForModuleBuild(CI, Input.isSystem(),
876  Input.isPreprocessed(),
877  PresumedModuleMapFile, OffsetToContents))
878  return false;
879 
880  auto *CurrentModule = prepareToBuildModule(CI, Input.getFile());
881  if (!CurrentModule)
882  return false;
883 
884  CurrentModule->PresumedModuleMapFile = PresumedModuleMapFile;
885 
886  if (OffsetToContents)
887  // If the module contents are in the same file, skip to them.
888  CI.getPreprocessor().setSkipMainFilePreamble(OffsetToContents, true);
889  else {
890  // Otherwise, convert the module description to a suitable input buffer.
891  auto Buffer = getInputBufferForModule(CI, CurrentModule);
892  if (!Buffer)
893  return false;
894 
895  // Reinitialize the main file entry to refer to the new input.
896  auto Kind = CurrentModule->IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
897  auto &SourceMgr = CI.getSourceManager();
898  auto BufferID = SourceMgr.createFileID(std::move(Buffer), Kind);
899  assert(BufferID.isValid() && "couldn't create module buffer ID");
900  SourceMgr.setMainFileID(BufferID);
901  }
902  }
903 
904  // Initialize the action.
905  if (!BeginSourceFileAction(CI))
906  return false;
907 
908  // If we were asked to load any module map files, do so now.
909  for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
910  if (auto File = CI.getFileManager().getFile(Filename))
912  *File, /*IsSystem*/false);
913  else
914  CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
915  }
916 
917  // If compiling implementation of a module, load its module map file now.
919 
920  // Add a module declaration scope so that modules from -fmodule-map-file
921  // arguments may shadow modules found implicitly in search paths.
922  CI.getPreprocessor()
924  .getModuleMap()
926 
927  // Create the AST context and consumer unless this is a preprocessor only
928  // action.
929  if (!usesPreprocessorOnly()) {
930  // Parsing a model file should reuse the existing ASTContext.
931  if (!isModelParsingAction())
932  CI.createASTContext();
933 
934  // For preprocessed files, check if the first line specifies the original
935  // source file name with a linemarker.
936  std::string PresumedInputFile = std::string(getCurrentFileOrBufferName());
937  if (Input.isPreprocessed())
938  ReadOriginalFileName(CI, PresumedInputFile);
939 
940  std::unique_ptr<ASTConsumer> Consumer =
941  CreateWrappedASTConsumer(CI, PresumedInputFile);
942  if (!Consumer)
943  return false;
944 
945  // FIXME: should not overwrite ASTMutationListener when parsing model files?
946  if (!isModelParsingAction())
947  CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
948 
949  if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
950  // Convert headers to PCH and chain them.
951  IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
952  source = createChainedIncludesSource(CI, FinalReader);
953  if (!source)
954  return false;
955  CI.setASTReader(static_cast<ASTReader *>(FinalReader.get()));
956  CI.getASTContext().setExternalSource(source);
957  } else if (CI.getLangOpts().Modules ||
958  !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
959  // Use PCM or PCH.
960  assert(hasPCHSupport() && "This action does not have PCH support!");
961  ASTDeserializationListener *DeserialListener =
962  Consumer->GetASTDeserializationListener();
963  bool DeleteDeserialListener = false;
965  DeserialListener = new DeserializedDeclsDumper(DeserialListener,
966  DeleteDeserialListener);
967  DeleteDeserialListener = true;
968  }
970  DeserialListener = new DeserializedDeclsChecker(
971  CI.getASTContext(),
973  DeserialListener, DeleteDeserialListener);
974  DeleteDeserialListener = true;
975  }
976  if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
981  DeserialListener, DeleteDeserialListener);
982  if (!CI.getASTContext().getExternalSource())
983  return false;
984  }
985  // If modules are enabled, create the AST reader before creating
986  // any builtins, so that all declarations know that they might be
987  // extended by an external source.
988  if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
990  CI.createASTReader();
991  CI.getASTReader()->setDeserializationListener(DeserialListener,
992  DeleteDeserialListener);
993  }
994  }
995 
996  CI.setASTConsumer(std::move(Consumer));
997  if (!CI.hasASTConsumer())
998  return false;
999  }
1000 
1001  // Initialize built-in info as long as we aren't using an external AST
1002  // source.
1003  if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
1004  !CI.getASTContext().getExternalSource()) {
1005  Preprocessor &PP = CI.getPreprocessor();
1007  PP.getLangOpts());
1008  } else {
1009  // FIXME: If this is a problem, recover from it by creating a multiplex
1010  // source.
1011  assert((!CI.getLangOpts().Modules || CI.getASTReader()) &&
1012  "modules enabled but created an external source that "
1013  "doesn't support modules");
1014  }
1015 
1016  // If we were asked to load any module files, do so now.
1017  for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
1018  if (!CI.loadModuleFile(ModuleFile))
1019  return false;
1020 
1021  // If there is a layout overrides file, attach an external AST source that
1022  // provides the layouts from that file.
1023  if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
1024  CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
1026  Override(new LayoutOverrideSource(
1028  CI.getASTContext().setExternalSource(Override);
1029  }
1030 
1031  // Setup HLSL External Sema Source
1032  if (CI.getLangOpts().HLSL && CI.hasASTContext()) {
1034  new HLSLExternalSemaSource());
1035  if (auto *SemaSource = dyn_cast_if_present<ExternalSemaSource>(
1036  CI.getASTContext().getExternalSource())) {
1038  new MultiplexExternalSemaSource(SemaSource, HLSLSema.get()));
1039  CI.getASTContext().setExternalSource(MultiSema);
1040  } else
1041  CI.getASTContext().setExternalSource(HLSLSema);
1042  }
1043 
1044  FailureCleanup.release();
1045  return true;
1046 }
1047 
1050 
1051  if (CI.hasFrontendTimer()) {
1052  llvm::TimeRegion Timer(CI.getFrontendTimer());
1053  ExecuteAction();
1054  }
1055  else ExecuteAction();
1056 
1057  // If we are supposed to rebuild the global module index, do so now unless
1058  // there were any module-build failures.
1059  if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
1060  CI.hasPreprocessor()) {
1061  StringRef Cache =
1063  if (!Cache.empty()) {
1064  if (llvm::Error Err = GlobalModuleIndex::writeIndex(
1066  // FIXME this drops the error on the floor, but
1067  // Index/pch-from-libclang.c seems to rely on dropping at least some of
1068  // the error conditions!
1069  consumeError(std::move(Err));
1070  }
1071  }
1072  }
1073 
1074  return llvm::Error::success();
1075 }
1076 
1079 
1080  // Inform the diagnostic client we are done with this source file.
1082 
1083  // Inform the preprocessor we are done.
1084  if (CI.hasPreprocessor())
1086 
1087  // Finalize the action.
1089 
1090  // Sema references the ast consumer, so reset sema first.
1091  //
1092  // FIXME: There is more per-file stuff we could just drop here?
1093  bool DisableFree = CI.getFrontendOpts().DisableFree;
1094  if (DisableFree) {
1095  CI.resetAndLeakSema();
1097  llvm::BuryPointer(CI.takeASTConsumer().get());
1098  } else {
1099  CI.setSema(nullptr);
1100  CI.setASTContext(nullptr);
1101  CI.setASTConsumer(nullptr);
1102  }
1103 
1104  if (CI.getFrontendOpts().ShowStats) {
1105  llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFileOrBufferName() << "':\n";
1106  CI.getPreprocessor().PrintStats();
1110  llvm::errs() << "\n";
1111  }
1112 
1113  // Cleanup the output streams, and erase the output files if instructed by the
1114  // FrontendAction.
1115  CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
1116 
1117  if (isCurrentFileAST()) {
1118  if (DisableFree) {
1122  llvm::BuryPointer(std::move(CurrentASTUnit));
1123  } else {
1124  CI.setPreprocessor(nullptr);
1125  CI.setSourceManager(nullptr);
1126  CI.setFileManager(nullptr);
1127  }
1128  }
1129 
1130  setCompilerInstance(nullptr);
1132  CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
1133 }
1134 
1137 }
1138 
1139 //===----------------------------------------------------------------------===//
1140 // Utility Actions
1141 //===----------------------------------------------------------------------===//
1142 
1145  if (!CI.hasPreprocessor())
1146  return;
1147 
1148  // FIXME: Move the truncation aspect of this into Sema, we delayed this till
1149  // here so the source manager would be initialized.
1150  if (hasCodeCompletionSupport() &&
1153 
1154  // Use a code completion consumer?
1155  CodeCompleteConsumer *CompletionConsumer = nullptr;
1156  if (CI.hasCodeCompletionConsumer())
1157  CompletionConsumer = &CI.getCodeCompletionConsumer();
1158 
1159  if (!CI.hasSema())
1160  CI.createSema(getTranslationUnitKind(), CompletionConsumer);
1161 
1164 }
1165 
1166 void PluginASTAction::anchor() { }
1167 
1168 std::unique_ptr<ASTConsumer>
1170  StringRef InFile) {
1171  llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
1172 }
1173 
1175  return WrappedAction->PrepareToExecuteAction(CI);
1176 }
1177 std::unique_ptr<ASTConsumer>
1179  StringRef InFile) {
1180  return WrappedAction->CreateASTConsumer(CI, InFile);
1181 }
1183  return WrappedAction->BeginInvocation(CI);
1184 }
1186  WrappedAction->setCurrentInput(getCurrentInput());
1187  WrappedAction->setCompilerInstance(&CI);
1188  auto Ret = WrappedAction->BeginSourceFileAction(CI);
1189  // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
1190  setCurrentInput(WrappedAction->getCurrentInput());
1191  return Ret;
1192 }
1194  WrappedAction->ExecuteAction();
1195 }
1198  WrappedAction->EndSourceFileAction();
1199 }
1201  return WrappedAction->shouldEraseOutputFiles();
1202 }
1203 
1205  return WrappedAction->usesPreprocessorOnly();
1206 }
1208  return WrappedAction->getTranslationUnitKind();
1209 }
1211  return WrappedAction->hasPCHSupport();
1212 }
1214  return WrappedAction->hasASTFileSupport();
1215 }
1217  return WrappedAction->hasIRSupport();
1218 }
1220  return WrappedAction->hasCodeCompletionSupport();
1221 }
1222 
1224  std::unique_ptr<FrontendAction> WrappedAction)
1225  : WrappedAction(std::move(WrappedAction)) {}
clang::CompilerInstance::setASTConsumer
void setASTConsumer(std::unique_ptr< ASTConsumer > Value)
setASTConsumer - Replace the current AST consumer; the compiler instance takes ownership of Value.
Definition: CompilerInstance.cpp:188
clang::WrapperFrontendAction::ExecuteAction
void ExecuteAction() override
Callback to run the program action, using the initialized compiler instance.
Definition: FrontendAction.cpp:1193
clang::ModuleMap::finishModuleDeclarationScope
void finishModuleDeclarationScope()
Creates a new declaration scope for module names, allowing previously defined modules to shadow defin...
Definition: ModuleMap.h:588
clang::CompilerInstance::hasSema
bool hasSema() const
Definition: CompilerInstance.h:501
clang::FrontendOptions::ModuleMapFiles
std::vector< std::string > ModuleMapFiles
The list of module map files to load before processing the input.
Definition: FrontendOptions.h:471
Builtins.h
clang::LangOptions::CurrentModule
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:434
clang::Preprocessor::setSkipMainFilePreamble
void setSkipMainFilePreamble(unsigned Bytes, bool StartOfLine)
Instruct the preprocessor to skip part of the main source file.
Definition: Preprocessor.h:1891
clang::FrontendOptions::AddPluginActions
std::vector< std::string > AddPluginActions
The list of plugin actions to run in addition to the normal action.
Definition: FrontendOptions.h:462
FrontendPluginRegistry.h
clang::serialization::TypeIdx
A type index; the type ID with the qualifier bits removed.
Definition: ASTBitCodes.h:88
clang::Preprocessor::PrintStats
void PrintStats()
Definition: Preprocessor.cpp:273
clang::GlobalModuleIndex::writeIndex
static llvm::Error writeIndex(FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, llvm::StringRef Path)
Write a global index into the given.
Definition: GlobalModuleIndex.cpp:852
clang::FileEntryRef
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition: FileEntry.h:62
clang::CompilerInstance::hasASTConsumer
bool hasASTConsumer() const
Definition: CompilerInstance.h:483
clang::FullSourceLoc
A SourceLocation and its associated SourceManager.
Definition: SourceLocation.h:368
loadModuleMapForModuleBuild
static bool loadModuleMapForModuleBuild(CompilerInstance &CI, bool IsSystem, bool IsPreprocessed, std::string &PresumedModuleMapFile, unsigned &Offset)
Definition: FrontendAction.cpp:439
clang::DeclaratorContext::File
@ File
clang::Module::getUmbrellaDir
DirectoryName getUmbrellaDir() const
Retrieve the directory for which this module serves as the umbrella.
Definition: Module.cpp:244
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::PreprocessorOptions
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
Definition: PreprocessorOptions.h:65
clang::InputKind::isHeaderUnit
bool isHeaderUnit() const
Definition: FrontendOptions.h:186
Ret
static bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.cpp:34
clang::FrontendInputFile::getKind
InputKind getKind() const
Definition: FrontendOptions.h:241
Diag
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.
Definition: LiteralSupport.cpp:79
clang::PluginASTAction::AddAfterMainAction
@ AddAfterMainAction
Execute the action after the main action.
Definition: FrontendAction.h:279
clang::ASTUnit::LoadFromASTFile
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, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=llvm::vfs::getRealFileSystem())
Create a ASTUnit from an AST file.
Definition: ASTUnit.cpp:757
clang::FrontendOptions::ShowStats
unsigned ShowStats
Show frontend performance metrics and statistics.
Definition: FrontendOptions.h:278
clang::Lexer::getSpelling
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:404
clang::FrontendAction::WrapperFrontendAction
friend class WrapperFrontendAction
Definition: FrontendAction.h:41
llvm::SmallVector
Definition: LLVM.h:38
clang::FrontendAction::isModelParsingAction
virtual bool isModelParsingAction() const
Is this action invoked on a model file?
Definition: FrontendAction.h:179
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::Module::getFullModuleName
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:219
clang::WrapperFrontendAction::hasCodeCompletionSupport
bool hasCodeCompletionSupport() const override
Does this action support use with code completion?
Definition: FrontendAction.cpp:1219
clang::NamedDecl
This represents a decl that may have a name.
Definition: Decl.h:247
clang::CompilerInstance::setSema
void setSema(Sema *S)
Replace the current Sema; the compiler instance takes ownership of S.
Definition: CompilerInstance.cpp:184
clang::serialization::IdentID
uint32_t IdentID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:134
clang::PreprocessorFrontendAction::CreateASTConsumer
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...
Definition: FrontendAction.cpp:1169
addHeaderInclude
static void addHeaderInclude(StringRef HeaderName, SmallVectorImpl< char > &Includes, const LangOptions &LangOpts, bool IsExternC)
Definition: FrontendAction.cpp:305
clang::FrontendOptions::PluginArgs
std::map< std::string, std::vector< std::string > > PluginArgs
Args to pass to the plugins.
Definition: FrontendOptions.h:459
clang::FrontendOptions::SkipFunctionBodies
unsigned SkipFunctionBodies
Skip over function bodies to speed up parsing in cases you do not need them (e.g.
Definition: FrontendOptions.h:306
clang::FrontendAction::hasIRSupport
virtual bool hasIRSupport() const
Does this action support use with IR files?
Definition: FrontendAction.h:197
clang::ASTContext::getFullLoc
FullSourceLoc getFullLoc(SourceLocation Loc) const
Definition: ASTContext.h:811
clang::WrapperFrontendAction::getTranslationUnitKind
TranslationUnitKind getTranslationUnitKind() override
For AST-based actions, the kind of translation unit we're handling.
Definition: FrontendAction.cpp:1207
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:737
clang::ASTReader::visitTopLevelModuleMaps
void visitTopLevelModuleMaps(serialization::ModuleFile &MF, llvm::function_ref< void(FileEntryRef)> Visitor)
Visit all the top-level module maps loaded when building the given module file.
Definition: ASTReader.cpp:9188
clang::FrontendAction::EndSourceFile
virtual void EndSourceFile()
Perform any per-file post processing, deallocate per-file objects, and run statistics and output file...
Definition: FrontendAction.cpp:1077
clang::Module::submodule_begin
submodule_iterator submodule_begin()
Definition: Module.h:708
clang::CompilerInstance::InitializeSourceManager
bool InitializeSourceManager(const FrontendInputFile &Input)
InitializeSourceManager - Initialize the source manager to set InputFile as the main file.
Definition: CompilerInstance.cpp:950
clang::CompilerInstance::getLangOpts
LangOptions & getLangOpts()
Definition: CompilerInstance.h:299
clang::WrapperFrontendAction::hasPCHSupport
bool hasPCHSupport() const override
Does this action support use with PCH?
Definition: FrontendAction.cpp:1210
Filename
StringRef Filename
Definition: Format.cpp:2715
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
clang::FrontendAction::getCurrentModule
Module * getCurrentModule() const
Definition: FrontendAction.cpp:150
clang::CompilerInstance::hasFrontendTimer
bool hasFrontendTimer() const
Definition: CompilerInstance.h:574
clang::FrontendAction::hasCodeCompletionSupport
virtual bool hasCodeCompletionSupport() const
Does this action support use with code completion?
Definition: FrontendAction.h:200
clang::HeaderSearch::LookupFile
Optional< FileEntryRef > LookupFile(StringRef Filename, SourceLocation IncludeLoc, bool isAngled, ConstSearchDirIterator FromDir, ConstSearchDirIterator *CurDir, ArrayRef< std::pair< const FileEntry *, const DirectoryEntry * >> Includers, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, Module *RequestingModule, ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool *IsFrameworkFound, bool SkipCache=false, bool BuildSystemModule=false, bool OpenFile=true, bool CacheFailures=true)
Given a "foo" or <foo> reference, look up the indicated file, return null on failure.
Definition: HeaderSearch.cpp:857
clang::FrontendInputFile
An input file for the front end.
Definition: FrontendOptions.h:218
clang::Token::isAtStartOfLine
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:269
collectModuleHeaderIncludes
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...
Definition: FrontendAction.cpp:330
clang::InputKind::withHeaderUnit
InputKind withHeaderUnit(HeaderUnitKind HU) const
Definition: FrontendOptions.h:206
clang::LangOptions::CMK_ModuleMap
@ CMK_ModuleMap
Compiling a module from a module map.
Definition: LangOptions.h:111
clang::FrontendAction::BeginInvocation
virtual bool BeginInvocation(CompilerInstance &CI)
Callback before starting processing a single input, giving the opportunity to modify the CompilerInvo...
Definition: FrontendAction.h:79
llvm::Optional< FileEntryRef >
clang::SourceManager::PrintStats
void PrintStats() const
Print statistics to stderr.
Definition: SourceManager.cpp:2152
clang::PreprocessorOptions::DumpDeserializedPCHDecls
bool DumpDeserializedPCHDecls
Dump declarations that are deserialized from PCH, for testing.
Definition: PreprocessorOptions.h:115
clang::TypePropertyCache
The type-property cache.
Definition: Type.cpp:3890
clang::CompilerInstance::getFileSystemOpts
FileSystemOptions & getFileSystemOpts()
Definition: CompilerInstance.h:275
clang::SourceManager::AddLineNote
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.
Definition: SourceManager.cpp:273
ASTDeserializationListener.h
clang::SourceManager::pushModuleBuildStack
void pushModuleBuildStack(StringRef moduleName, FullSourceLoc importLoc)
Push an entry to the module build stack.
Definition: SourceManager.h:841
FrontendAction.h
clang::DiagnosticConsumer::EndSourceFile
virtual void EndSourceFile()
Callback to inform the diagnostic client that processing of a source file has ended.
Definition: Diagnostic.h:1771
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
clang::InputKind
The kind of a file that we've been handed as an input.
Definition: FrontendOptions.h:148
clang::FileManager::getOptionalDirectoryRef
llvm::Optional< DirectoryEntryRef > getOptionalDirectoryRef(StringRef DirName, bool CacheFailure=true)
Get a DirectoryEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:170
clang::CompilerInstance::getCodeGenOpts
CodeGenOptions & getCodeGenOpts()
Definition: CompilerInstance.h:254
LiteralSupport.h
End
SourceLocation End
Definition: USRLocFinder.cpp:167
clang::SARIFDiagnosticPrinter
Definition: SARIFDiagnosticPrinter.h:30
clang::FrontendInputFile::getFile
StringRef getFile() const
Definition: FrontendOptions.h:253
clang::CompilerInstance::getPCHContainerReader
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
Definition: CompilerInstance.h:542
clang::CompilerInstance::createCodeCompletionConsumer
void createCodeCompletionConsumer()
Create a code completion consumer using the invocation; note that this will cause the source manager ...
Definition: CompilerInstance.cpp:716
clang::Preprocessor::getIdentifierTable
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:1072
clang::Module::isAvailable
bool isAvailable() const
Determine whether this module is available for use within the current translation unit.
Definition: Module.h:473
clang::FrontendAction::hasASTFileSupport
virtual bool hasASTFileSupport() const
Does this action support use with AST files?
Definition: FrontendAction.h:194
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:636
clang::ModuleMap::setInferredModuleAllowedBy
void setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap)
Definition: ModuleMap.cpp:1281
clang::ParsedSourceLocation::FileName
std::string FileName
Definition: CommandLineSourceLoc.h:25
clang::Preprocessor::getLangOpts
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:1065
Preprocessor.h
clang::HeaderSearch
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Definition: HeaderSearch.h:223
clang::CompilerInstance::resetAndLeakSourceManager
void resetAndLeakSourceManager()
Definition: CompilerInstance.h:427
clang::Lexer
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens.
Definition: Lexer.h:78
Offset
unsigned Offset
Definition: Format.cpp:2717
clang::FrontendOptions::OverrideRecordLayoutsFile
std::string OverrideRecordLayoutsFile
File name of the file that will provide record layouts (in the format produced by -fdump-record-layou...
Definition: FrontendOptions.h:489
SARIFDiagnosticPrinter.h
clang::SourceManager::setAllFilesAreTransient
void setAllFilesAreTransient(bool Transient)
Specify that all files that are read during this compilation are transient.
Definition: SourceManager.h:1012
clang::FrontendOptions::ModulesEmbedAllFiles
unsigned ModulesEmbedAllFiles
Whether we should embed all used files into the PCM file.
Definition: FrontendOptions.h:333
clang::dataflow::Literal
uint32_t Literal
Literals are represented as positive integers.
Definition: WatchedLiteralsSolver.cpp:55
clang::CompilerInstance::getFileManager
FileManager & getFileManager() const
Return the current file manager to the caller.
Definition: CompilerInstance.h:402
clang::Preprocessor::getCurrentModuleImplementation
Module * getCurrentModuleImplementation()
Retrieves the module whose implementation we're current compiling, if any.
Definition: Preprocessor.cpp:531
clang::PluginASTAction::AddBeforeMainAction
@ AddBeforeMainAction
Execute the action before the main action.
Definition: FrontendAction.h:278
clang::ASTContext::getExternalSource
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1194
clang::Module
Describes a module or submodule.
Definition: Module.h:98
clang::WrapperFrontendAction::hasIRSupport
bool hasIRSupport() const override
Does this action support use with IR files?
Definition: FrontendAction.cpp:1216
clang::FileManager::getVirtualFileSystem
llvm::vfs::FileSystem & getVirtualFileSystem() const
Definition: FileManager.h:245
clang::FrontendAction::~FrontendAction
virtual ~FrontendAction()
Definition: FrontendAction.cpp:142
clang::FrontendAction::getCurrentFileOrBufferName
StringRef getCurrentFileOrBufferName() const
Definition: FrontendAction.h:144
clang::Preprocessor::EndSourceFile
void EndSourceFile()
Inform the preprocessor callbacks that processing is complete.
Definition: Preprocessor.cpp:699
clang::LangOptions::CMK_None
@ CMK_None
Not compiling a module interface at all.
Definition: LangOptions.h:108
clang::CompilerInstance::resetAndLeakFileManager
void resetAndLeakFileManager()
Definition: CompilerInstance.h:407
clang::DirectoryEntry
Cached information about one directory (either on disk or in the virtual file system).
Definition: DirectoryEntry.h:36
clang::ASTReader::getModuleManager
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1713
clang::CompilerInstance::createASTReader
void createASTReader()
Definition: CompilerInstance.cpp:1652
MultiplexExternalSemaSource.h
clang::DiagnosticsEngine::hasErrorOccurred
bool hasErrorOccurred() const
Definition: Diagnostic.h:838
clang::FrontendAction::BeginSourceFile
bool BeginSourceFile(CompilerInstance &CI, const FrontendInputFile &Input)
Prepare the action for processing the input file Input.
Definition: FrontendAction.cpp:570
clang::Token::getKind
tok::TokenKind getKind() const
Definition: Token.h:92
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:209
clang::HeaderSearch::loadModuleMapFile
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.
Definition: HeaderSearch.cpp:1665
clang::PreprocessorOptions::ChainedIncludes
std::vector< std::string > ChainedIncludes
Headers that will be converted to chained PCHs in memory.
Definition: PreprocessorOptions.h:100
clang::SourceManager::getMainFileID
FileID getMainFileID() const
Returns the FileID of the main source file.
Definition: SourceManager.h:850
clang::CompilerInstance::getSema
Sema & getSema() const
Definition: CompilerInstance.h:503
clang::DiagnosticsEngine::Error
@ Error
Definition: Diagnostic.h:200
Utils.h
clang::LayoutOverrideSource
An external AST source that overrides the layout of a specified set of record types.
Definition: LayoutOverrideSource.h:24
clang::InputKind::HeaderUnit_Abs
@ HeaderUnit_Abs
Definition: FrontendOptions.h:171
clang::ASTContext::setExternalSource
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
Definition: ASTContext.cpp:1050
clang::FrontendAction::hasPCHSupport
virtual bool hasPCHSupport() const
Does this action support use with PCH?
Definition: FrontendAction.h:191
clang::InputKind::getLanguage
Language getLanguage() const
Definition: FrontendOptions.h:179
clang::MultiplexExternalSemaSource
An abstract interface that should be implemented by external AST sources that also provide informatio...
Definition: MultiplexExternalSemaSource.h:38
clang::HeaderSearch::lookupModule
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
Definition: HeaderSearch.cpp:272
HLSLExternalSemaSource.h
clang::InputKind::Precompiled
@ Precompiled
Definition: FrontendOptions.h:161
clang::MacroDefinitionRecord
Record the location of a macro definition.
Definition: PreprocessingRecord.h:147
clang::FrontendAction::CreateASTConsumer
virtual std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile)=0
Create the AST consumer object for this action, if supported.
clang::PreprocessorOptions::AllowPCHWithCompilerErrors
bool AllowPCHWithCompilerErrors
When true, a PCH with compiler errors will not be rejected.
Definition: PreprocessorOptions.h:108
clang::FrontendAction::getCompilerInstance
CompilerInstance & getCompilerInstance() const
Definition: FrontendAction.h:119
llvm::SmallString< 16 >
clang::PreprocessorOptions::DisablePCHOrModuleValidation
DisableValidationForModuleKind DisablePCHOrModuleValidation
Whether to disable most of the normal validation performed on precompiled headers and module files.
Definition: PreprocessorOptions.h:104
clang::CompilerInstance::resetAndLeakPreprocessor
void resetAndLeakPreprocessor()
Definition: CompilerInstance.h:449
ASTContext.h
clang::ASTReader::isAcceptableASTFile
static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, const InMemoryModuleCache &ModuleCache, const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts, const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts, StringRef ExistingModuleCachePath, bool RequireStrictOptionMatches=false)
Determine whether the given AST file is acceptable to load into a translation unit with the given lan...
Definition: ASTReader.cpp:5451
clang::FrontendAction::shouldEraseOutputFiles
virtual bool shouldEraseOutputFiles()
Callback at the end of processing a single input, to determine if the output files should be erased o...
Definition: FrontendAction.cpp:1135
clang::CompilerInstance::getPreprocessor
Preprocessor & getPreprocessor() const
Return the current preprocessor.
Definition: CompilerInstance.h:442
clang::Module::MissingHeaders
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:253
clang::FrontendAction::getTranslationUnitKind
virtual TranslationUnitKind getTranslationUnitKind()
For AST-based actions, the kind of translation unit we're handling.
Definition: FrontendAction.h:188
clang::FrontendOptions::ModulesEmbedFiles
std::vector< std::string > ModulesEmbedFiles
The list of files to embed into the compiled module file.
Definition: FrontendOptions.h:478
clang::CompilerInstance::getASTContext
ASTContext & getASTContext() const
Definition: CompilerInstance.h:462
clang::SrcMgr::C_User
@ C_User
Definition: SourceManager.h:80
clang::CompilerInstance::hasFileManager
bool hasFileManager() const
Definition: CompilerInstance.h:399
clang::FrontendAction::setCurrentInput
void setCurrentInput(const FrontendInputFile &CurrentInput, std::unique_ptr< ASTUnit > AST=nullptr)
Definition: FrontendAction.cpp:144
prepareToBuildModule
static Module * prepareToBuildModule(CompilerInstance &CI, StringRef ModuleMapFilename)
Definition: FrontendAction.cpp:480
DeclGroup.h
clang::Token::isNot
bool isNot(tok::TokenKind K) const
Definition: Token.h:98
clang::CompilerInstance
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Definition: CompilerInstance.h:72
clang::FileEntry
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:366
clang::SourceManager::getDecomposedLoc
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
Definition: SourceManager.h:1243
clang::ModuleMap
Definition: ModuleMap.h:75
clang::CompilerInstance::getPreprocessorOpts
PreprocessorOptions & getPreprocessorOpts()
Definition: CompilerInstance.h:306
clang::InputKind::getFormat
Format getFormat() const
Definition: FrontendOptions.h:180
clang::FrontendInputFile::isSystem
bool isSystem() const
Definition: FrontendOptions.h:242
clang::WrapperFrontendAction::BeginInvocation
bool BeginInvocation(CompilerInstance &CI) override
Callback before starting processing a single input, giving the opportunity to modify the CompilerInvo...
Definition: FrontendAction.cpp:1182
clang::Module::Parent
Module * Parent
The parent of this module.
Definition: Module.h:135
clang::serialization::PreprocessedEntityID
uint32_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
Definition: ASTBitCodes.h:168
clang::Module::PresumedModuleMapFile
std::string PresumedModuleMapFile
The presumed file name for the module map defining this module.
Definition: Module.h:144
clang::CompilerInstance::setPreprocessor
void setPreprocessor(std::shared_ptr< Preprocessor > Value)
Replace the current preprocessor.
Definition: CompilerInstance.cpp:173
clang::CompilerInstance::setASTReader
void setASTReader(IntrusiveRefCntPtr< ASTReader > Reader)
Definition: CompilerInstance.cpp:206
clang::CompilerInstance::getModuleCache
InMemoryModuleCache & getModuleCache() const
Definition: CompilerInstance.h:817
clang::FrontendAction::getCurrentInput
const FrontendInputFile & getCurrentInput() const
Definition: FrontendAction.h:135
clang::InputKind::ModuleMap
@ ModuleMap
Definition: FrontendOptions.h:160
clang::FrontendAction::EndSourceFileAction
virtual void EndSourceFileAction()
Callback at the end of processing a single input.
Definition: FrontendAction.h:100
clang::FileEntryRef::getName
StringRef getName() const
The name of this FileEntry.
Definition: FileEntry.h:66
clang::Module::submodule_iterator
std::vector< Module * >::iterator submodule_iterator
Definition: Module.h:705
clang::CompilerInstance::getTargetOpts
TargetOptions & getTargetOpts()
Definition: CompilerInstance.h:320
clang::Module::HK_Normal
@ HK_Normal
Definition: Module.h:204
ParseAST.h
clang::FrontendAction::FrontendAction
FrontendAction()
Definition: FrontendAction.cpp:140
clang::CompilerInstance::takeASTConsumer
std::unique_ptr< ASTConsumer > takeASTConsumer()
takeASTConsumer - Remove the current AST consumer and give ownership to the caller.
Definition: CompilerInstance.h:492
clang::CompilerInstance::loadModuleFile
bool loadModuleFile(StringRef FileName)
Definition: CompilerInstance.cpp:1703
clang::Module::HK_Private
@ HK_Private
Definition: Module.h:206
P
StringRef P
Definition: ASTMatchersInternal.cpp:563
clang::FrontendInputFile::isPreprocessed
bool isPreprocessed() const
Definition: FrontendOptions.h:247
clang::Module::Directory
const DirectoryEntry * Directory
The build directory of this module.
Definition: Module.h:140
clang::Module::Headers
SmallVector< Header, 2 > Headers[5]
The headers that are part of this module.
Definition: Module.h:233
clang::DiagnosticConsumer::BeginSourceFile
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:1763
clang::CompilerInstance::getDiagnosticClient
DiagnosticConsumer & getDiagnosticClient() const
Definition: CompilerInstance.h:342
clang::Preprocessor::getBuiltinInfo
Builtin::Context & getBuiltinInfo()
Definition: Preprocessor.h:1075
clang::ASTDeserializationListener
Definition: ASTDeserializationListener.h:30
clang::CompilerInstance::hasPreprocessor
bool hasPreprocessor() const
Definition: CompilerInstance.h:439
clang::WrapperFrontendAction::BeginSourceFileAction
bool BeginSourceFileAction(CompilerInstance &CI) override
Callback at the start of processing a single input.
Definition: FrontendAction.cpp:1185
LangStandard.h
clang::WrapperFrontendAction::usesPreprocessorOnly
bool usesPreprocessorOnly() const override
Does this action only use the preprocessor?
Definition: FrontendAction.cpp:1204
clang::HeaderSearch::getModuleCachePath
StringRef getModuleCachePath() const
Retrieve the path to the module cache.
Definition: HeaderSearch.h:418
clang::CompilerInstance::hasCodeCompletionConsumer
bool hasCodeCompletionConsumer() const
Definition: CompilerInstance.h:558
clang::Language::LLVM_IR
@ LLVM_IR
LLVM IR: we accept this so that we can run the optimizer on it, and compile it to assembly or object ...
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
clang::ASTUnit::LoadPreprocessorOnly
@ LoadPreprocessorOnly
Load options and the preprocessor state.
Definition: ASTUnit.h:672
getInputBufferForModule
static std::unique_ptr< llvm::MemoryBuffer > getInputBufferForModule(CompilerInstance &CI, Module *M)
Compute the input buffer that should be used to build the specified module.
Definition: FrontendAction.cpp:546
clang::CompilerInstance::getFrontendTimer
llvm::Timer & getFrontendTimer() const
Definition: CompilerInstance.h:576
HeaderSearch.h
clang::FrontendAction::Execute
llvm::Error Execute()
Set the source manager's main input file, and run the action.
Definition: FrontendAction.cpp:1048
ASTUnit.h
clang::CodeCompleteConsumer
Abstract interface for a consumer of code-completion information.
Definition: CodeCompleteConsumer.h:1010
clang::PreprocessorOptions::DeserializedPCHDeclsToErrorOn
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...
Definition: PreprocessorOptions.h:119
GlobalModuleIndex.h
clang::ModuleMap::resolveHeaderDirectives
void resolveHeaderDirectives(const FileEntry *File) const
Resolve all lazy header directives for the specified file.
Definition: ModuleMap.cpp:1199
clang::FrontendPluginRegistry
llvm::Registry< PluginASTAction > FrontendPluginRegistry
The frontend plugin registry.
Definition: FrontendPluginRegistry.h:22
ASTConsumer.h
clang::serialization::ModuleManager::getPrimaryModule
ModuleFile & getPrimaryModule()
Returns the primary module associated with the manager, that is, the first module loaded.
Definition: ModuleManager.h:167
clang::CompilerInstance::resetAndLeakASTContext
void resetAndLeakASTContext()
Definition: CompilerInstance.h:467
clang::DiagnosticOptions::SARIF
@ SARIF
Definition: DiagnosticOptions.h:77
clang::CompilerInstance::hasSourceManager
bool hasSourceManager() const
Definition: CompilerInstance.h:419
clang::WrapperFrontendAction::shouldEraseOutputFiles
bool shouldEraseOutputFiles() override
Callback at the end of processing a single input, to determine if the output files should be erased o...
Definition: FrontendAction.cpp:1200
clang::FrontendAction::ExecuteAction
virtual void ExecuteAction()=0
Callback to run the program action, using the initialized compiler instance.
clang::ModuleMap::isHeaderUnavailableInModule
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:711
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:85
clang::Token::getLocation
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:125
LayoutOverrideSource.h
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:81
clang::FrontendInputFile::isEmpty
bool isEmpty() const
Definition: FrontendOptions.h:244
clang::ObjCPropertyAttribute::Kind
Kind
Definition: DeclObjCCommon.h:22
clang::ASTReader
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:341
clang::HLSLExternalSemaSource
Definition: HLSLExternalSemaSource.h:23
std
Definition: Format.h:4477
clang::TranslationUnitKind
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:914
clang::FrontendOptions::ModuleFiles
std::vector< std::string > ModuleFiles
The list of additional prebuilt module files to load before processing the input.
Definition: FrontendOptions.h:475
clang::FrontendOptions::OriginalModuleMap
std::string OriginalModuleMap
When the input is a module map, the original module map file from which that map was inferred,...
Definition: FrontendOptions.h:430
clang::SourceManager::initializeForReplay
void initializeForReplay(const SourceManager &Old)
Initialize this source manager suitably to replay the compilation described by Old.
Definition: SourceManager.cpp:362
clang::CompilerInstance::getTarget
TargetInfo & getTarget() const
Definition: CompilerInstance.h:369
clang::DiagnosticsEngine::getCustomDiagID
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:868
clang::Builtin::ID
ID
Definition: Builtins.h:52
clang::CompilerInstance::getDiagnosticOpts
DiagnosticOptions & getDiagnosticOpts()
Definition: CompilerInstance.h:268
clang::createChainedIncludesSource
IntrusiveRefCntPtr< ExternalSemaSource > createChainedIncludesSource(CompilerInstance &CI, IntrusiveRefCntPtr< ExternalSemaSource > &Reader)
The ChainedIncludesSource class converts headers to chained PCHs in memory, mainly for testing.
Definition: ChainedIncludesSource.cpp:90
clang
Definition: CalledOnceCheck.h:17
clang::FileManager
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
clang::SourceManager::createFileID
FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
Definition: SourceManager.cpp:534
clang::Selector
Smart pointer class that efficiently represents Objective-C method names.
Definition: IdentifierTable.h:759
clang::Module::getModuleInputBufferName
static StringRef getModuleInputBufferName()
Definition: Module.h:726
clang::CompilerInstance::resetAndLeakSema
void resetAndLeakSema()
Definition: CompilerInstance.cpp:2297
clang::IdentifierTable::PrintStats
void PrintStats() const
Print some statistics to stderr that indicate how well the hashing is doing.
Definition: IdentifierTable.cpp:454
FrontendDiagnostic.h
clang::FrontendAction::isCurrentFileAST
bool isCurrentFileAST() const
Definition: FrontendAction.h:130
operator+=
static SmallVectorImpl< char > & operator+=(SmallVectorImpl< char > &Includes, StringRef RHS)
Definition: FrontendAction.cpp:300
ASTReader.h
clang::CompilerInstance::getCodeCompletionConsumer
CodeCompleteConsumer & getCodeCompletionConsumer() const
Definition: CompilerInstance.h:560
clang::FileID
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Definition: SourceLocation.h:38
Sarif.h
clang::Module::getUmbrellaHeader
Header getUmbrellaHeader() const
Retrieve the header that serves as the umbrella header for this module.
Definition: Module.h:624
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:110
clang::InputKind::getHeaderUnitKind
HeaderUnitKind getHeaderUnitKind() const
Definition: FrontendOptions.h:181
clang::SourceManager::getFileEntryForID
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
Definition: SourceManager.h:1043
clang::CompilerInstance::createASTContext
void createASTContext()
Create the AST context.
Definition: CompilerInstance.cpp:558
clang::WrapperFrontendAction::WrappedAction
std::unique_ptr< FrontendAction > WrappedAction
Definition: FrontendAction.h:307
clang::Module::IsExternC
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition: Module.h:298
clang::Module::submodule_end
submodule_iterator submodule_end()
Definition: Module.h:710
clang::WrapperFrontendAction::PrepareToExecuteAction
bool PrepareToExecuteAction(CompilerInstance &CI) override
Prepare to execute the action on the given CompilerInstance.
Definition: FrontendAction.cpp:1174
clang::FrontendAction::BeginSourceFileAction
virtual bool BeginSourceFileAction(CompilerInstance &CI)
Callback at the start of processing a single input.
Definition: FrontendAction.h:85
clang::FileManager::getDirectory
llvm::ErrorOr< const DirectoryEntry * > getDirectory(StringRef DirName, bool CacheFailure=true)
Lookup, cache, and verify the specified directory (real or virtual).
Definition: FileManager.cpp:189
clang::CompilerInstance::setFileManager
void setFileManager(FileManager *Value)
Replace the current file manager and virtual file system.
Definition: CompilerInstance.cpp:165
clang::ASTUnit::LoadEverything
@ LoadEverything
Load everything, including Sema.
Definition: ASTUnit.h:678
clang::SourceManager::getModuleBuildStack
ModuleBuildStack getModuleBuildStack() const
Retrieve the module build stack.
Definition: SourceManager.h:830
clang::FileManager::getFile
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
Definition: FileManager.cpp:197
clang::ASTFrontendAction::ExecuteAction
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
Definition: FrontendAction.cpp:1143
DiagnosticOptions.h
CompilerInstance.h
clang::WrapperFrontendAction::EndSourceFile
void EndSourceFile() override
Perform any per-file post processing, deallocate per-file objects, and run statistics and output file...
Definition: FrontendAction.cpp:1196
clang::CompilerInstance::getFrontendOpts
FrontendOptions & getFrontendOpts()
Definition: CompilerInstance.h:282
clang::WrapperFrontendAction::hasASTFileSupport
bool hasASTFileSupport() const override
Does this action support use with AST files?
Definition: FrontendAction.cpp:1213
clang::CompilerInstance::getASTReader
IntrusiveRefCntPtr< ASTReader > getASTReader() const
Definition: CompilerInstance.cpp:203
clang::CompilerInstance::setASTContext
void setASTContext(ASTContext *Value)
setASTContext - Replace the current AST context.
Definition: CompilerInstance.cpp:177
clang::FrontendOptions::DisableFree
unsigned DisableFree
Disable memory freeing on exit.
Definition: FrontendOptions.h:268
clang::Module::addTopHeader
void addTopHeader(const FileEntry *File)
Add a top-level header associated with this module.
Definition: Module.cpp:252
clang::comments::tok::eof
@ eof
Definition: CommentLexer.h:33
clang::Preprocessor::checkModuleIsAvailable
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.
Definition: PPDirectives.cpp:1891
clang::CompilerInstance::getDiagnostics
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
Definition: CompilerInstance.h:334
clang::CompilerInstance::getSourceManager
SourceManager & getSourceManager() const
Return the current source manager.
Definition: CompilerInstance.h:422
llvm::SmallVectorImpl< char >
clang::PluginASTAction::CmdlineAfterMainAction
@ CmdlineAfterMainAction
Execute the action after the main action if on the command line.
Definition: FrontendAction.h:275
clang::FrontendAction::setCompilerInstance
void setCompilerInstance(CompilerInstance *Value)
Definition: FrontendAction.h:124
clang::InputKind::HeaderUnit_System
@ HeaderUnit_System
Definition: FrontendOptions.h:170
clang::SrcMgr::C_System
@ C_System
Definition: SourceManager.h:81
clang::WrapperFrontendAction::CreateASTConsumer
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
Definition: FrontendAction.cpp:1178
clang::CompilerInstance::createFileManager
FileManager * createFileManager(IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS=nullptr)
Create the file manager and replace any existing one with it.
Definition: CompilerInstance.cpp:378
clang::CompilerInstance::getSpecificModuleCachePath
std::string getSpecificModuleCachePath(StringRef ModuleHash)
Definition: CompilerInstance.cpp:548
clang::CompilerInstance::createSema
void createSema(TranslationUnitKind TUKind, CodeCompleteConsumer *CompletionConsumer)
Create the Sema object to be used for parsing.
Definition: CompilerInstance.cpp:752
clang::FrontendAction::usesPreprocessorOnly
virtual bool usesPreprocessorOnly() const =0
Does this action only use the preprocessor?
Previous
StateNode * Previous
Definition: UnwrappedLineFormatter.cpp:1149
PreprocessorOptions.h
clang::Preprocessor
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:129
clang::CompilerInstance::setSourceManager
void setSourceManager(SourceManager *Value)
setSourceManager - Replace the current source manager.
Definition: CompilerInstance.cpp:169
clang::CompilerInstance::createPreprocessor
void createPreprocessor(TranslationUnitKind TUKind)
Create the preprocessor, using the invocation, file, and source managers, and replace any existing on...
Definition: CompilerInstance.cpp:453
clang::ParseAST
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
clang::Preprocessor::getHeaderSearchInfo
HeaderSearch & getHeaderSearchInfo() const
Definition: Preprocessor.h:1070
clang::serialization::DeclID
uint32_t DeclID
An ID number that refers to a declaration in an AST file.
Definition: ASTBitCodes.h:68
clang::StringLiteralParser
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
Definition: LiteralSupport.h:218
ReadOriginalFileName
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...
Definition: FrontendAction.cpp:245
clang::serialization::SelectorID
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
Definition: ASTBitCodes.h:153
clang::SrcMgr::C_User_ModuleMap
@ C_User_ModuleMap
Definition: SourceManager.h:83
clang::InputKind::isPreprocessed
bool isPreprocessed() const
Definition: FrontendOptions.h:184
clang::Decl::getLocation
SourceLocation getLocation() const
Definition: DeclBase.h:432
clang::WrapperFrontendAction::EndSourceFileAction
void EndSourceFileAction() override
Callback at the end of processing a single input.
Definition: FrontendAction.cpp:1197
clang::CompilerInstance::clearOutputFiles
void clearOutputFiles(bool EraseFiles)
clearOutputFiles - Clear the output file list.
Definition: CompilerInstance.cpp:765
clang::CompilerInstance::shouldBuildGlobalModuleIndex
bool shouldBuildGlobalModuleIndex() const
Indicates whether we should (re)build the global module index.
Definition: CompilerInstance.cpp:81
clang::CompilerInstance::createSourceManager
void createSourceManager(FileManager &FileMgr)
Create the source manager and replace any existing one with it.
Definition: CompilerInstance.cpp:391
clang::Builtin::Context::initializeBuiltins
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:102
clang::LangOptions::ModuleName
std::string ModuleName
The module currently being compiled as specified by -fmodule-name.
Definition: LangOptions.h:427
clang::serialization::ModuleFile
Information about a module that has been loaded by the ASTReader.
Definition: ModuleFile.h:111
clang::HeaderSearch::getModuleMap
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:791
clang::interp::Sub
bool Sub(InterpState &S, CodePtr OpPC)
Definition: Interp.h:163
clang::FrontendOptions::CodeCompletionAt
ParsedSourceLocation CodeCompletionAt
If given, enable code completion at the provided location.
Definition: FrontendOptions.h:442
clang::HeaderSearch::PrintStats
void PrintStats()
Definition: HeaderSearch.cpp:90
clang::CompilerInstance::getHeaderSearchOpts
HeaderSearchOptions & getHeaderSearchOpts()
Definition: CompilerInstance.h:289
clang::CompilerInstance::createPCHExternalASTSource
void createPCHExternalASTSource(StringRef Path, DisableValidationForModuleKind DisableValidation, bool AllowPCHWithCompilerErrors, void *DeserializationListener, bool OwnDeserializationListener)
Create an external AST source to read a PCH file and attach it to the AST context.
Definition: CompilerInstance.cpp:617
clang::Preprocessor::setMainFileDir
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...
Definition: Preprocessor.h:1881
clang::Module::IsInferred
unsigned IsInferred
Whether this is an inferred submodule (module * { ... }).
Definition: Module.h:301
llvm::IntrusiveRefCntPtr
Definition: LLVM.h:47
clang::PreprocessorOptions::ImplicitPCHInclude
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
Definition: PreprocessorOptions.h:97
clang::ASTContext::getDiagnostics
DiagnosticsEngine & getDiagnostics() const
Definition: ASTContext.cpp:1505
clang::ASTContext::setASTMutationListener
void setASTMutationListener(ASTMutationListener *Listener)
Attach an AST mutation listener to the AST context.
Definition: ASTContext.h:1203
clang::PluginASTAction::CmdlineBeforeMainAction
@ CmdlineBeforeMainAction
Execute the action before the main action if on the command line.
Definition: FrontendAction.h:273
clang::PluginASTAction::ActionType
ActionType
Definition: FrontendAction.h:272
clang::DiagnosticsEngine::Report
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1537
clang::Decl::getDeclKindName
const char * getDeclKindName() const
Definition: DeclBase.cpp:123
clang::CompilerInstance::hasASTContext
bool hasASTContext() const
Definition: CompilerInstance.h:460
clang::SourceManager::setFileIsTransient
void setFileIsTransient(const FileEntry *SourceFile)
Specify that a file is transient.
Definition: SourceManager.cpp:729
clang::ModuleMap::canInferFrameworkModule
bool canInferFrameworkModule(const DirectoryEntry *Dir) const
Check whether a framework module can be inferred in the given directory.
Definition: ModuleMap.h:597
MultiplexConsumer.h