clang  19.0.0git
ASTReader.cpp
Go to the documentation of this file.
1 //===- ASTReader.cpp - AST File Reader ------------------------------------===//
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 //
9 // This file defines the ASTReader class, which reads AST files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "ASTCommon.h"
14 #include "ASTReaderInternals.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclBase.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclFriend.h"
25 #include "clang/AST/DeclGroup.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclTemplate.h"
29 #include "clang/AST/Expr.h"
30 #include "clang/AST/ExprCXX.h"
35 #include "clang/AST/OpenMPClause.h"
37 #include "clang/AST/TemplateBase.h"
38 #include "clang/AST/TemplateName.h"
39 #include "clang/AST/Type.h"
40 #include "clang/AST/TypeLoc.h"
44 #include "clang/Basic/Diagnostic.h"
52 #include "clang/Basic/LLVM.h"
54 #include "clang/Basic/Module.h"
60 #include "clang/Basic/Sanitizers.h"
64 #include "clang/Basic/Specifiers.h"
65 #include "clang/Basic/TargetInfo.h"
67 #include "clang/Basic/TokenKinds.h"
68 #include "clang/Basic/Version.h"
69 #include "clang/Lex/HeaderSearch.h"
71 #include "clang/Lex/MacroInfo.h"
72 #include "clang/Lex/ModuleMap.h"
74 #include "clang/Lex/Preprocessor.h"
76 #include "clang/Lex/Token.h"
78 #include "clang/Sema/Scope.h"
79 #include "clang/Sema/Sema.h"
80 #include "clang/Sema/SemaCUDA.h"
81 #include "clang/Sema/SemaObjC.h"
82 #include "clang/Sema/Weak.h"
94 #include "llvm/ADT/APFloat.h"
95 #include "llvm/ADT/APInt.h"
96 #include "llvm/ADT/APSInt.h"
97 #include "llvm/ADT/ArrayRef.h"
98 #include "llvm/ADT/DenseMap.h"
99 #include "llvm/ADT/FloatingPointMode.h"
100 #include "llvm/ADT/FoldingSet.h"
101 #include "llvm/ADT/Hashing.h"
102 #include "llvm/ADT/IntrusiveRefCntPtr.h"
103 #include "llvm/ADT/STLExtras.h"
104 #include "llvm/ADT/ScopeExit.h"
105 #include "llvm/ADT/SmallPtrSet.h"
106 #include "llvm/ADT/SmallString.h"
107 #include "llvm/ADT/SmallVector.h"
108 #include "llvm/ADT/StringExtras.h"
109 #include "llvm/ADT/StringMap.h"
110 #include "llvm/ADT/StringRef.h"
111 #include "llvm/ADT/iterator_range.h"
112 #include "llvm/Bitstream/BitstreamReader.h"
113 #include "llvm/Support/Casting.h"
114 #include "llvm/Support/Compiler.h"
115 #include "llvm/Support/Compression.h"
116 #include "llvm/Support/DJB.h"
117 #include "llvm/Support/Endian.h"
118 #include "llvm/Support/Error.h"
119 #include "llvm/Support/ErrorHandling.h"
120 #include "llvm/Support/FileSystem.h"
121 #include "llvm/Support/LEB128.h"
122 #include "llvm/Support/MemoryBuffer.h"
123 #include "llvm/Support/Path.h"
124 #include "llvm/Support/SaveAndRestore.h"
125 #include "llvm/Support/TimeProfiler.h"
126 #include "llvm/Support/Timer.h"
127 #include "llvm/Support/VersionTuple.h"
128 #include "llvm/Support/raw_ostream.h"
129 #include "llvm/TargetParser/Triple.h"
130 #include <algorithm>
131 #include <cassert>
132 #include <cstddef>
133 #include <cstdint>
134 #include <cstdio>
135 #include <ctime>
136 #include <iterator>
137 #include <limits>
138 #include <map>
139 #include <memory>
140 #include <optional>
141 #include <string>
142 #include <system_error>
143 #include <tuple>
144 #include <utility>
145 #include <vector>
146 
147 using namespace clang;
148 using namespace clang::serialization;
149 using namespace clang::serialization::reader;
150 using llvm::BitstreamCursor;
151 
152 //===----------------------------------------------------------------------===//
153 // ChainedASTReaderListener implementation
154 //===----------------------------------------------------------------------===//
155 
156 bool
158  return First->ReadFullVersionInformation(FullVersion) ||
159  Second->ReadFullVersionInformation(FullVersion);
160 }
161 
162 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
163  First->ReadModuleName(ModuleName);
164  Second->ReadModuleName(ModuleName);
165 }
166 
167 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
168  First->ReadModuleMapFile(ModuleMapPath);
169  Second->ReadModuleMapFile(ModuleMapPath);
170 }
171 
172 bool
174  bool Complain,
175  bool AllowCompatibleDifferences) {
176  return First->ReadLanguageOptions(LangOpts, Complain,
177  AllowCompatibleDifferences) ||
178  Second->ReadLanguageOptions(LangOpts, Complain,
179  AllowCompatibleDifferences);
180 }
181 
183  const TargetOptions &TargetOpts, bool Complain,
184  bool AllowCompatibleDifferences) {
185  return First->ReadTargetOptions(TargetOpts, Complain,
186  AllowCompatibleDifferences) ||
187  Second->ReadTargetOptions(TargetOpts, Complain,
188  AllowCompatibleDifferences);
189 }
190 
192  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
193  return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
194  Second->ReadDiagnosticOptions(DiagOpts, Complain);
195 }
196 
197 bool
199  bool Complain) {
200  return First->ReadFileSystemOptions(FSOpts, Complain) ||
201  Second->ReadFileSystemOptions(FSOpts, Complain);
202 }
203 
205  const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
206  bool Complain) {
207  return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
208  Complain) ||
209  Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
210  Complain);
211 }
212 
214  const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain,
215  std::string &SuggestedPredefines) {
216  return First->ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,
217  SuggestedPredefines) ||
218  Second->ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,
219  SuggestedPredefines);
220 }
221 
223  unsigned Value) {
224  First->ReadCounter(M, Value);
225  Second->ReadCounter(M, Value);
226 }
227 
229  return First->needsInputFileVisitation() ||
230  Second->needsInputFileVisitation();
231 }
232 
234  return First->needsSystemInputFileVisitation() ||
235  Second->needsSystemInputFileVisitation();
236 }
237 
239  ModuleKind Kind) {
240  First->visitModuleFile(Filename, Kind);
241  Second->visitModuleFile(Filename, Kind);
242 }
243 
245  bool isSystem,
246  bool isOverridden,
247  bool isExplicitModule) {
248  bool Continue = false;
249  if (First->needsInputFileVisitation() &&
250  (!isSystem || First->needsSystemInputFileVisitation()))
251  Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
252  isExplicitModule);
253  if (Second->needsInputFileVisitation() &&
254  (!isSystem || Second->needsSystemInputFileVisitation()))
255  Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
256  isExplicitModule);
257  return Continue;
258 }
259 
261  const ModuleFileExtensionMetadata &Metadata) {
262  First->readModuleFileExtension(Metadata);
263  Second->readModuleFileExtension(Metadata);
264 }
265 
266 //===----------------------------------------------------------------------===//
267 // PCH validator implementation
268 //===----------------------------------------------------------------------===//
269 
271 
272 /// Compare the given set of language options against an existing set of
273 /// language options.
274 ///
275 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
276 /// \param AllowCompatibleDifferences If true, differences between compatible
277 /// language options will be permitted.
278 ///
279 /// \returns true if the languagae options mis-match, false otherwise.
280 static bool checkLanguageOptions(const LangOptions &LangOpts,
281  const LangOptions &ExistingLangOpts,
282  DiagnosticsEngine *Diags,
283  bool AllowCompatibleDifferences = true) {
284 #define LANGOPT(Name, Bits, Default, Description) \
285  if (ExistingLangOpts.Name != LangOpts.Name) { \
286  if (Diags) { \
287  if (Bits == 1) \
288  Diags->Report(diag::err_pch_langopt_mismatch) \
289  << Description << LangOpts.Name << ExistingLangOpts.Name; \
290  else \
291  Diags->Report(diag::err_pch_langopt_value_mismatch) \
292  << Description; \
293  } \
294  return true; \
295  }
296 
297 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
298  if (ExistingLangOpts.Name != LangOpts.Name) { \
299  if (Diags) \
300  Diags->Report(diag::err_pch_langopt_value_mismatch) \
301  << Description; \
302  return true; \
303  }
304 
305 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
306  if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
307  if (Diags) \
308  Diags->Report(diag::err_pch_langopt_value_mismatch) \
309  << Description; \
310  return true; \
311  }
312 
313 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
314  if (!AllowCompatibleDifferences) \
315  LANGOPT(Name, Bits, Default, Description)
316 
317 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
318  if (!AllowCompatibleDifferences) \
319  ENUM_LANGOPT(Name, Bits, Default, Description)
320 
321 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
322  if (!AllowCompatibleDifferences) \
323  VALUE_LANGOPT(Name, Bits, Default, Description)
324 
325 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
326 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
327 #define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description)
328 #include "clang/Basic/LangOptions.def"
329 
330  if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
331  if (Diags)
332  Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
333  return true;
334  }
335 
336  if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
337  if (Diags)
338  Diags->Report(diag::err_pch_langopt_value_mismatch)
339  << "target Objective-C runtime";
340  return true;
341  }
342 
343  if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
344  LangOpts.CommentOpts.BlockCommandNames) {
345  if (Diags)
346  Diags->Report(diag::err_pch_langopt_value_mismatch)
347  << "block command names";
348  return true;
349  }
350 
351  // Sanitizer feature mismatches are treated as compatible differences. If
352  // compatible differences aren't allowed, we still only want to check for
353  // mismatches of non-modular sanitizers (the only ones which can affect AST
354  // generation).
355  if (!AllowCompatibleDifferences) {
356  SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
357  SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
358  SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
359  ExistingSanitizers.clear(ModularSanitizers);
360  ImportedSanitizers.clear(ModularSanitizers);
361  if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
362  const std::string Flag = "-fsanitize=";
363  if (Diags) {
364 #define SANITIZER(NAME, ID) \
365  { \
366  bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
367  bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
368  if (InExistingModule != InImportedModule) \
369  Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
370  << InExistingModule << (Flag + NAME); \
371  }
372 #include "clang/Basic/Sanitizers.def"
373  }
374  return true;
375  }
376  }
377 
378  return false;
379 }
380 
381 /// Compare the given set of target options against an existing set of
382 /// target options.
383 ///
384 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
385 ///
386 /// \returns true if the target options mis-match, false otherwise.
387 static bool checkTargetOptions(const TargetOptions &TargetOpts,
388  const TargetOptions &ExistingTargetOpts,
389  DiagnosticsEngine *Diags,
390  bool AllowCompatibleDifferences = true) {
391 #define CHECK_TARGET_OPT(Field, Name) \
392  if (TargetOpts.Field != ExistingTargetOpts.Field) { \
393  if (Diags) \
394  Diags->Report(diag::err_pch_targetopt_mismatch) \
395  << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
396  return true; \
397  }
398 
399  // The triple and ABI must match exactly.
400  CHECK_TARGET_OPT(Triple, "target");
401  CHECK_TARGET_OPT(ABI, "target ABI");
402 
403  // We can tolerate different CPUs in many cases, notably when one CPU
404  // supports a strict superset of another. When allowing compatible
405  // differences skip this check.
406  if (!AllowCompatibleDifferences) {
407  CHECK_TARGET_OPT(CPU, "target CPU");
408  CHECK_TARGET_OPT(TuneCPU, "tune CPU");
409  }
410 
411 #undef CHECK_TARGET_OPT
412 
413  // Compare feature sets.
414  SmallVector<StringRef, 4> ExistingFeatures(
415  ExistingTargetOpts.FeaturesAsWritten.begin(),
416  ExistingTargetOpts.FeaturesAsWritten.end());
417  SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
418  TargetOpts.FeaturesAsWritten.end());
419  llvm::sort(ExistingFeatures);
420  llvm::sort(ReadFeatures);
421 
422  // We compute the set difference in both directions explicitly so that we can
423  // diagnose the differences differently.
424  SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
425  std::set_difference(
426  ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
427  ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
428  std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
429  ExistingFeatures.begin(), ExistingFeatures.end(),
430  std::back_inserter(UnmatchedReadFeatures));
431 
432  // If we are allowing compatible differences and the read feature set is
433  // a strict subset of the existing feature set, there is nothing to diagnose.
434  if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
435  return false;
436 
437  if (Diags) {
438  for (StringRef Feature : UnmatchedReadFeatures)
439  Diags->Report(diag::err_pch_targetopt_feature_mismatch)
440  << /* is-existing-feature */ false << Feature;
441  for (StringRef Feature : UnmatchedExistingFeatures)
442  Diags->Report(diag::err_pch_targetopt_feature_mismatch)
443  << /* is-existing-feature */ true << Feature;
444  }
445 
446  return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
447 }
448 
449 bool
451  bool Complain,
452  bool AllowCompatibleDifferences) {
453  const LangOptions &ExistingLangOpts = PP.getLangOpts();
454  return checkLanguageOptions(LangOpts, ExistingLangOpts,
455  Complain ? &Reader.Diags : nullptr,
456  AllowCompatibleDifferences);
457 }
458 
460  bool Complain,
461  bool AllowCompatibleDifferences) {
462  const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
463  return checkTargetOptions(TargetOpts, ExistingTargetOpts,
464  Complain ? &Reader.Diags : nullptr,
465  AllowCompatibleDifferences);
466 }
467 
468 namespace {
469 
470 using MacroDefinitionsMap =
471  llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
472 using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
473 
474 } // namespace
475 
477  DiagnosticsEngine &Diags,
478  bool Complain) {
480 
481  // Check current mappings for new -Werror mappings, and the stored mappings
482  // for cases that were explicitly mapped to *not* be errors that are now
483  // errors because of options like -Werror.
484  DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
485 
486  for (DiagnosticsEngine *MappingSource : MappingSources) {
487  for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
488  diag::kind DiagID = DiagIDMappingPair.first;
489  Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
490  if (CurLevel < DiagnosticsEngine::Error)
491  continue; // not significant
492  Level StoredLevel =
493  StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
494  if (StoredLevel < DiagnosticsEngine::Error) {
495  if (Complain)
496  Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
497  Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
498  return true;
499  }
500  }
501  }
502 
503  return false;
504 }
505 
508  if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
509  return true;
510  return Ext >= diag::Severity::Error;
511 }
512 
514  DiagnosticsEngine &Diags, bool IsSystem,
515  bool SystemHeaderWarningsInModule,
516  bool Complain) {
517  // Top-level options
518  if (IsSystem) {
519  if (Diags.getSuppressSystemWarnings())
520  return false;
521  // If -Wsystem-headers was not enabled before, and it was not explicit,
522  // be conservative
523  if (StoredDiags.getSuppressSystemWarnings() &&
524  !SystemHeaderWarningsInModule) {
525  if (Complain)
526  Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
527  return true;
528  }
529  }
530 
531  if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
532  if (Complain)
533  Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
534  return true;
535  }
536 
537  if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
538  !StoredDiags.getEnableAllWarnings()) {
539  if (Complain)
540  Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
541  return true;
542  }
543 
544  if (isExtHandlingFromDiagsError(Diags) &&
545  !isExtHandlingFromDiagsError(StoredDiags)) {
546  if (Complain)
547  Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
548  return true;
549  }
550 
551  return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
552 }
553 
554 /// Return the top import module if it is implicit, nullptr otherwise.
556  Preprocessor &PP) {
557  // If the original import came from a file explicitly generated by the user,
558  // don't check the diagnostic mappings.
559  // FIXME: currently this is approximated by checking whether this is not a
560  // module import of an implicitly-loaded module file.
561  // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
562  // the transitive closure of its imports, since unrelated modules cannot be
563  // imported until after this module finishes validation.
564  ModuleFile *TopImport = &*ModuleMgr.rbegin();
565  while (!TopImport->ImportedBy.empty())
566  TopImport = TopImport->ImportedBy[0];
567  if (TopImport->Kind != MK_ImplicitModule)
568  return nullptr;
569 
570  StringRef ModuleName = TopImport->ModuleName;
571  assert(!ModuleName.empty() && "diagnostic options read before module name");
572 
573  Module *M =
574  PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
575  assert(M && "missing module");
576  return M;
577 }
578 
580  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
581  DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
582  IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
584  new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
585  // This should never fail, because we would have processed these options
586  // before writing them to an ASTFile.
587  ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
588 
589  ModuleManager &ModuleMgr = Reader.getModuleManager();
590  assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
591 
592  Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
593  if (!TopM)
594  return false;
595 
596  Module *Importer = PP.getCurrentModule();
597 
598  DiagnosticOptions &ExistingOpts = ExistingDiags.getDiagnosticOptions();
599  bool SystemHeaderWarningsInModule =
600  Importer && llvm::is_contained(ExistingOpts.SystemHeaderWarningsModules,
601  Importer->Name);
602 
603  // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
604  // contains the union of their flags.
605  return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
606  SystemHeaderWarningsInModule, Complain);
607 }
608 
609 /// Collect the macro definitions provided by the given preprocessor
610 /// options.
611 static void
613  MacroDefinitionsMap &Macros,
614  SmallVectorImpl<StringRef> *MacroNames = nullptr) {
615  for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
616  StringRef Macro = PPOpts.Macros[I].first;
617  bool IsUndef = PPOpts.Macros[I].second;
618 
619  std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
620  StringRef MacroName = MacroPair.first;
621  StringRef MacroBody = MacroPair.second;
622 
623  // For an #undef'd macro, we only care about the name.
624  if (IsUndef) {
625  if (MacroNames && !Macros.count(MacroName))
626  MacroNames->push_back(MacroName);
627 
628  Macros[MacroName] = std::make_pair("", true);
629  continue;
630  }
631 
632  // For a #define'd macro, figure out the actual definition.
633  if (MacroName.size() == Macro.size())
634  MacroBody = "1";
635  else {
636  // Note: GCC drops anything following an end-of-line character.
637  StringRef::size_type End = MacroBody.find_first_of("\n\r");
638  MacroBody = MacroBody.substr(0, End);
639  }
640 
641  if (MacroNames && !Macros.count(MacroName))
642  MacroNames->push_back(MacroName);
643  Macros[MacroName] = std::make_pair(MacroBody, false);
644  }
645 }
646 
651 };
652 
653 /// Check the preprocessor options deserialized from the control block
654 /// against the preprocessor options in an existing preprocessor.
655 ///
656 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
657 /// \param Validation If set to OptionValidateNone, ignore differences in
658 /// preprocessor options. If set to OptionValidateContradictions,
659 /// require that options passed both in the AST file and on the command
660 /// line (-D or -U) match, but tolerate options missing in one or the
661 /// other. If set to OptionValidateContradictions, require that there
662 /// are no differences in the options between the two.
664  const PreprocessorOptions &PPOpts,
665  const PreprocessorOptions &ExistingPPOpts, bool ReadMacros,
666  DiagnosticsEngine *Diags, FileManager &FileMgr,
667  std::string &SuggestedPredefines, const LangOptions &LangOpts,
669  if (ReadMacros) {
670  // Check macro definitions.
671  MacroDefinitionsMap ASTFileMacros;
672  collectMacroDefinitions(PPOpts, ASTFileMacros);
673  MacroDefinitionsMap ExistingMacros;
674  SmallVector<StringRef, 4> ExistingMacroNames;
675  collectMacroDefinitions(ExistingPPOpts, ExistingMacros,
676  &ExistingMacroNames);
677 
678  // Use a line marker to enter the <command line> file, as the defines and
679  // undefines here will have come from the command line.
680  SuggestedPredefines += "# 1 \"<command line>\" 1\n";
681 
682  for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
683  // Dig out the macro definition in the existing preprocessor options.
684  StringRef MacroName = ExistingMacroNames[I];
685  std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
686 
687  // Check whether we know anything about this macro name or not.
688  llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
689  ASTFileMacros.find(MacroName);
690  if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
691  if (Validation == OptionValidateStrictMatches) {
692  // If strict matches are requested, don't tolerate any extra defines
693  // on the command line that are missing in the AST file.
694  if (Diags) {
695  Diags->Report(diag::err_pch_macro_def_undef) << MacroName << true;
696  }
697  return true;
698  }
699  // FIXME: Check whether this identifier was referenced anywhere in the
700  // AST file. If so, we should reject the AST file. Unfortunately, this
701  // information isn't in the control block. What shall we do about it?
702 
703  if (Existing.second) {
704  SuggestedPredefines += "#undef ";
705  SuggestedPredefines += MacroName.str();
706  SuggestedPredefines += '\n';
707  } else {
708  SuggestedPredefines += "#define ";
709  SuggestedPredefines += MacroName.str();
710  SuggestedPredefines += ' ';
711  SuggestedPredefines += Existing.first.str();
712  SuggestedPredefines += '\n';
713  }
714  continue;
715  }
716 
717  // If the macro was defined in one but undef'd in the other, we have a
718  // conflict.
719  if (Existing.second != Known->second.second) {
720  if (Diags) {
721  Diags->Report(diag::err_pch_macro_def_undef)
722  << MacroName << Known->second.second;
723  }
724  return true;
725  }
726 
727  // If the macro was #undef'd in both, or if the macro bodies are
728  // identical, it's fine.
729  if (Existing.second || Existing.first == Known->second.first) {
730  ASTFileMacros.erase(Known);
731  continue;
732  }
733 
734  // The macro bodies differ; complain.
735  if (Diags) {
736  Diags->Report(diag::err_pch_macro_def_conflict)
737  << MacroName << Known->second.first << Existing.first;
738  }
739  return true;
740  }
741 
742  // Leave the <command line> file and return to <built-in>.
743  SuggestedPredefines += "# 1 \"<built-in>\" 2\n";
744 
745  if (Validation == OptionValidateStrictMatches) {
746  // If strict matches are requested, don't tolerate any extra defines in
747  // the AST file that are missing on the command line.
748  for (const auto &MacroName : ASTFileMacros.keys()) {
749  if (Diags) {
750  Diags->Report(diag::err_pch_macro_def_undef) << MacroName << false;
751  }
752  return true;
753  }
754  }
755  }
756 
757  // Check whether we're using predefines.
758  if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
759  Validation != OptionValidateNone) {
760  if (Diags) {
761  Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
762  }
763  return true;
764  }
765 
766  // Detailed record is important since it is used for the module cache hash.
767  if (LangOpts.Modules &&
768  PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
769  Validation != OptionValidateNone) {
770  if (Diags) {
771  Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
772  }
773  return true;
774  }
775 
776  // Compute the #include and #include_macros lines we need.
777  for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
778  StringRef File = ExistingPPOpts.Includes[I];
779 
780  if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
781  !ExistingPPOpts.PCHThroughHeader.empty()) {
782  // In case the through header is an include, we must add all the includes
783  // to the predefines so the start point can be determined.
784  SuggestedPredefines += "#include \"";
785  SuggestedPredefines += File;
786  SuggestedPredefines += "\"\n";
787  continue;
788  }
789 
790  if (File == ExistingPPOpts.ImplicitPCHInclude)
791  continue;
792 
793  if (llvm::is_contained(PPOpts.Includes, File))
794  continue;
795 
796  SuggestedPredefines += "#include \"";
797  SuggestedPredefines += File;
798  SuggestedPredefines += "\"\n";
799  }
800 
801  for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
802  StringRef File = ExistingPPOpts.MacroIncludes[I];
803  if (llvm::is_contained(PPOpts.MacroIncludes, File))
804  continue;
805 
806  SuggestedPredefines += "#__include_macros \"";
807  SuggestedPredefines += File;
808  SuggestedPredefines += "\"\n##\n";
809  }
810 
811  return false;
812 }
813 
815  bool ReadMacros, bool Complain,
816  std::string &SuggestedPredefines) {
817  const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
818 
820  PPOpts, ExistingPPOpts, ReadMacros, Complain ? &Reader.Diags : nullptr,
821  PP.getFileManager(), SuggestedPredefines, PP.getLangOpts());
822 }
823 
825  const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain,
826  std::string &SuggestedPredefines) {
827  return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(), ReadMacros,
828  nullptr, PP.getFileManager(),
829  SuggestedPredefines, PP.getLangOpts(),
831 }
832 
833 /// Check that the specified and the existing module cache paths are equivalent.
834 ///
835 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
836 /// \returns true when the module cache paths differ.
837 static bool checkModuleCachePath(llvm::vfs::FileSystem &VFS,
838  StringRef SpecificModuleCachePath,
839  StringRef ExistingModuleCachePath,
840  DiagnosticsEngine *Diags,
841  const LangOptions &LangOpts,
842  const PreprocessorOptions &PPOpts) {
843  if (!LangOpts.Modules || PPOpts.AllowPCHWithDifferentModulesCachePath ||
844  SpecificModuleCachePath == ExistingModuleCachePath)
845  return false;
846  auto EqualOrErr =
847  VFS.equivalent(SpecificModuleCachePath, ExistingModuleCachePath);
848  if (EqualOrErr && *EqualOrErr)
849  return false;
850  if (Diags)
851  Diags->Report(diag::err_pch_modulecache_mismatch)
852  << SpecificModuleCachePath << ExistingModuleCachePath;
853  return true;
854 }
855 
857  StringRef SpecificModuleCachePath,
858  bool Complain) {
859  return checkModuleCachePath(Reader.getFileManager().getVirtualFileSystem(),
860  SpecificModuleCachePath,
861  PP.getHeaderSearchInfo().getModuleCachePath(),
862  Complain ? &Reader.Diags : nullptr,
863  PP.getLangOpts(), PP.getPreprocessorOpts());
864 }
865 
866 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
867  PP.setCounterValue(Value);
868 }
869 
870 //===----------------------------------------------------------------------===//
871 // AST reader implementation
872 //===----------------------------------------------------------------------===//
873 
874 static uint64_t readULEB(const unsigned char *&P) {
875  unsigned Length = 0;
876  const char *Error = nullptr;
877 
878  uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
879  if (Error)
880  llvm::report_fatal_error(Error);
881  P += Length;
882  return Val;
883 }
884 
885 /// Read ULEB-encoded key length and data length.
886 static std::pair<unsigned, unsigned>
887 readULEBKeyDataLength(const unsigned char *&P) {
888  unsigned KeyLen = readULEB(P);
889  if ((unsigned)KeyLen != KeyLen)
890  llvm::report_fatal_error("key too large");
891 
892  unsigned DataLen = readULEB(P);
893  if ((unsigned)DataLen != DataLen)
894  llvm::report_fatal_error("data too large");
895 
896  return std::make_pair(KeyLen, DataLen);
897 }
898 
900  bool TakeOwnership) {
901  DeserializationListener = Listener;
902  OwnsDeserializationListener = TakeOwnership;
903 }
904 
906  return serialization::ComputeHash(Sel);
907 }
908 
909 std::pair<unsigned, unsigned>
911  return readULEBKeyDataLength(d);
912 }
913 
915 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
916  using namespace llvm::support;
917 
918  SelectorTable &SelTable = Reader.getContext().Selectors;
919  unsigned N = endian::readNext<uint16_t, llvm::endianness::little>(d);
920  const IdentifierInfo *FirstII = Reader.getLocalIdentifier(
921  F, endian::readNext<uint32_t, llvm::endianness::little>(d));
922  if (N == 0)
923  return SelTable.getNullarySelector(FirstII);
924  else if (N == 1)
925  return SelTable.getUnarySelector(FirstII);
926 
928  Args.push_back(FirstII);
929  for (unsigned I = 1; I != N; ++I)
930  Args.push_back(Reader.getLocalIdentifier(
931  F, endian::readNext<uint32_t, llvm::endianness::little>(d)));
932 
933  return SelTable.getSelector(N, Args.data());
934 }
935 
938  unsigned DataLen) {
939  using namespace llvm::support;
940 
941  data_type Result;
942 
943  Result.ID = Reader.getGlobalSelectorID(
944  F, endian::readNext<uint32_t, llvm::endianness::little>(d));
945  unsigned FullInstanceBits =
946  endian::readNext<uint16_t, llvm::endianness::little>(d);
947  unsigned FullFactoryBits =
948  endian::readNext<uint16_t, llvm::endianness::little>(d);
949  Result.InstanceBits = FullInstanceBits & 0x3;
950  Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
951  Result.FactoryBits = FullFactoryBits & 0x3;
952  Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
953  unsigned NumInstanceMethods = FullInstanceBits >> 3;
954  unsigned NumFactoryMethods = FullFactoryBits >> 3;
955 
956  // Load instance methods
957  for (unsigned I = 0; I != NumInstanceMethods; ++I) {
958  if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
959  F,
960  LocalDeclID(endian::readNext<DeclID, llvm::endianness::little>(d))))
961  Result.Instance.push_back(Method);
962  }
963 
964  // Load factory methods
965  for (unsigned I = 0; I != NumFactoryMethods; ++I) {
966  if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
967  F,
968  LocalDeclID(endian::readNext<DeclID, llvm::endianness::little>(d))))
969  Result.Factory.push_back(Method);
970  }
971 
972  return Result;
973 }
974 
976  return llvm::djbHash(a);
977 }
978 
979 std::pair<unsigned, unsigned>
981  return readULEBKeyDataLength(d);
982 }
983 
985 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
986  assert(n >= 2 && d[n-1] == '\0');
987  return StringRef((const char*) d, n-1);
988 }
989 
990 /// Whether the given identifier is "interesting".
991 static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II,
992  bool IsModule) {
993  bool IsInteresting =
994  II.getNotableIdentifierID() != tok::NotableIdentifierKind::not_notable ||
996  II.getObjCKeywordID() != tok::ObjCKeywordKind::objc_not_keyword;
997  return II.hadMacroDefinition() || II.isPoisoned() ||
998  (!IsModule && IsInteresting) || II.hasRevertedTokenIDToIdentifier() ||
999  (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
1000  II.getFETokenInfo());
1001 }
1002 
1003 static bool readBit(unsigned &Bits) {
1004  bool Value = Bits & 0x1;
1005  Bits >>= 1;
1006  return Value;
1007 }
1008 
1010  using namespace llvm::support;
1011 
1012  unsigned RawID = endian::readNext<uint32_t, llvm::endianness::little>(d);
1013  return Reader.getGlobalIdentifierID(F, RawID >> 1);
1014 }
1015 
1017  if (!II.isFromAST()) {
1018  II.setIsFromAST();
1019  bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
1020  if (isInterestingIdentifier(Reader, II, IsModule))
1022  }
1023 }
1024 
1026  const unsigned char* d,
1027  unsigned DataLen) {
1028  using namespace llvm::support;
1029 
1030  unsigned RawID = endian::readNext<uint32_t, llvm::endianness::little>(d);
1031  bool IsInteresting = RawID & 0x01;
1032 
1033  // Wipe out the "is interesting" bit.
1034  RawID = RawID >> 1;
1035 
1036  // Build the IdentifierInfo and link the identifier ID with it.
1037  IdentifierInfo *II = KnownII;
1038  if (!II) {
1039  II = &Reader.getIdentifierTable().getOwn(k);
1040  KnownII = II;
1041  }
1042  markIdentifierFromAST(Reader, *II);
1043  Reader.markIdentifierUpToDate(II);
1044 
1045  IdentifierID ID = Reader.getGlobalIdentifierID(F, RawID);
1046  if (!IsInteresting) {
1047  // For uninteresting identifiers, there's nothing else to do. Just notify
1048  // the reader that we've finished loading this identifier.
1049  Reader.SetIdentifierInfo(ID, II);
1050  return II;
1051  }
1052 
1053  unsigned ObjCOrBuiltinID =
1054  endian::readNext<uint16_t, llvm::endianness::little>(d);
1055  unsigned Bits = endian::readNext<uint16_t, llvm::endianness::little>(d);
1056  bool CPlusPlusOperatorKeyword = readBit(Bits);
1057  bool HasRevertedTokenIDToIdentifier = readBit(Bits);
1058  bool Poisoned = readBit(Bits);
1059  bool ExtensionToken = readBit(Bits);
1060  bool HadMacroDefinition = readBit(Bits);
1061 
1062  assert(Bits == 0 && "Extra bits in the identifier?");
1063  DataLen -= 8;
1064 
1065  // Set or check the various bits in the IdentifierInfo structure.
1066  // Token IDs are read-only.
1067  if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
1069  if (!F.isModule())
1070  II->setObjCOrBuiltinID(ObjCOrBuiltinID);
1071  assert(II->isExtensionToken() == ExtensionToken &&
1072  "Incorrect extension token flag");
1073  (void)ExtensionToken;
1074  if (Poisoned)
1075  II->setIsPoisoned(true);
1076  assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
1077  "Incorrect C++ operator keyword flag");
1078  (void)CPlusPlusOperatorKeyword;
1079 
1080  // If this identifier is a macro, deserialize the macro
1081  // definition.
1082  if (HadMacroDefinition) {
1083  uint32_t MacroDirectivesOffset =
1084  endian::readNext<uint32_t, llvm::endianness::little>(d);
1085  DataLen -= 4;
1086 
1087  Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1088  }
1089 
1090  Reader.SetIdentifierInfo(ID, II);
1091 
1092  // Read all of the declarations visible at global scope with this
1093  // name.
1094  if (DataLen > 0) {
1096  for (; DataLen > 0; DataLen -= sizeof(DeclID))
1097  DeclIDs.push_back(Reader.getGlobalDeclID(
1098  F,
1099  LocalDeclID(endian::readNext<DeclID, llvm::endianness::little>(d))));
1100  Reader.SetGloballyVisibleDecls(II, DeclIDs);
1101  }
1102 
1103  return II;
1104 }
1105 
1107  : Kind(Name.getNameKind()) {
1108  switch (Kind) {
1110  Data = (uint64_t)Name.getAsIdentifierInfo();
1111  break;
1115  Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1116  break;
1118  Data = Name.getCXXOverloadedOperator();
1119  break;
1121  Data = (uint64_t)Name.getCXXLiteralIdentifier();
1122  break;
1124  Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1125  ->getDeclName().getAsIdentifierInfo();
1126  break;
1131  Data = 0;
1132  break;
1133  }
1134 }
1135 
1137  llvm::FoldingSetNodeID ID;
1138  ID.AddInteger(Kind);
1139 
1140  switch (Kind) {
1144  ID.AddString(((IdentifierInfo*)Data)->getName());
1145  break;
1150  break;
1152  ID.AddInteger((OverloadedOperatorKind)Data);
1153  break;
1158  break;
1159  }
1160 
1161  return ID.ComputeHash();
1162 }
1163 
1164 ModuleFile *
1165 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1166  using namespace llvm::support;
1167 
1168  uint32_t ModuleFileID =
1169  endian::readNext<uint32_t, llvm::endianness::little>(d);
1170  return Reader.getLocalModuleFile(F, ModuleFileID);
1171 }
1172 
1173 std::pair<unsigned, unsigned>
1174 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1175  return readULEBKeyDataLength(d);
1176 }
1177 
1179 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1180  using namespace llvm::support;
1181 
1182  auto Kind = (DeclarationName::NameKind)*d++;
1183  uint64_t Data;
1184  switch (Kind) {
1188  Data = (uint64_t)Reader.getLocalIdentifier(
1189  F, endian::readNext<uint32_t, llvm::endianness::little>(d));
1190  break;
1194  Data = (uint64_t)Reader
1195  .getLocalSelector(
1196  F, endian::readNext<uint32_t, llvm::endianness::little>(d))
1197  .getAsOpaquePtr();
1198  break;
1200  Data = *d++; // OverloadedOperatorKind
1201  break;
1206  Data = 0;
1207  break;
1208  }
1209 
1210  return DeclarationNameKey(Kind, Data);
1211 }
1212 
1213 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1214  const unsigned char *d,
1215  unsigned DataLen,
1216  data_type_builder &Val) {
1217  using namespace llvm::support;
1218 
1219  for (unsigned NumDecls = DataLen / sizeof(DeclID); NumDecls; --NumDecls) {
1220  LocalDeclID LocalID(endian::readNext<DeclID, llvm::endianness::little>(d));
1221  Val.insert(Reader.getGlobalDeclID(F, LocalID));
1222  }
1223 }
1224 
1225 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1226  BitstreamCursor &Cursor,
1227  uint64_t Offset,
1228  DeclContext *DC) {
1229  assert(Offset != 0);
1230 
1231  SavedStreamPosition SavedPosition(Cursor);
1232  if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1233  Error(std::move(Err));
1234  return true;
1235  }
1236 
1237  RecordData Record;
1238  StringRef Blob;
1239  Expected<unsigned> MaybeCode = Cursor.ReadCode();
1240  if (!MaybeCode) {
1241  Error(MaybeCode.takeError());
1242  return true;
1243  }
1244  unsigned Code = MaybeCode.get();
1245 
1246  Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1247  if (!MaybeRecCode) {
1248  Error(MaybeRecCode.takeError());
1249  return true;
1250  }
1251  unsigned RecCode = MaybeRecCode.get();
1252  if (RecCode != DECL_CONTEXT_LEXICAL) {
1253  Error("Expected lexical block");
1254  return true;
1255  }
1256 
1257  assert(!isa<TranslationUnitDecl>(DC) &&
1258  "expected a TU_UPDATE_LEXICAL record for TU");
1259  // If we are handling a C++ class template instantiation, we can see multiple
1260  // lexical updates for the same record. It's important that we select only one
1261  // of them, so that field numbering works properly. Just pick the first one we
1262  // see.
1263  auto &Lex = LexicalDecls[DC];
1264  if (!Lex.first) {
1265  Lex = std::make_pair(
1266  &M, llvm::ArrayRef(
1267  reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
1268  Blob.size() / sizeof(DeclID)));
1269  }
1270  DC->setHasExternalLexicalStorage(true);
1271  return false;
1272 }
1273 
1274 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1275  BitstreamCursor &Cursor,
1276  uint64_t Offset,
1277  GlobalDeclID ID) {
1278  assert(Offset != 0);
1279 
1280  SavedStreamPosition SavedPosition(Cursor);
1281  if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1282  Error(std::move(Err));
1283  return true;
1284  }
1285 
1286  RecordData Record;
1287  StringRef Blob;
1288  Expected<unsigned> MaybeCode = Cursor.ReadCode();
1289  if (!MaybeCode) {
1290  Error(MaybeCode.takeError());
1291  return true;
1292  }
1293  unsigned Code = MaybeCode.get();
1294 
1295  Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1296  if (!MaybeRecCode) {
1297  Error(MaybeRecCode.takeError());
1298  return true;
1299  }
1300  unsigned RecCode = MaybeRecCode.get();
1301  if (RecCode != DECL_CONTEXT_VISIBLE) {
1302  Error("Expected visible lookup table block");
1303  return true;
1304  }
1305 
1306  // We can't safely determine the primary context yet, so delay attaching the
1307  // lookup table until we're done with recursive deserialization.
1308  auto *Data = (const unsigned char*)Blob.data();
1309  PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1310  return false;
1311 }
1312 
1313 void ASTReader::Error(StringRef Msg) const {
1314  Error(diag::err_fe_pch_malformed, Msg);
1315  if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1316  !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1317  Diag(diag::note_module_cache_path)
1318  << PP.getHeaderSearchInfo().getModuleCachePath();
1319  }
1320 }
1321 
1322 void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1323  StringRef Arg3) const {
1324  if (Diags.isDiagnosticInFlight())
1325  Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
1326  else
1327  Diag(DiagID) << Arg1 << Arg2 << Arg3;
1328 }
1329 
1330 void ASTReader::Error(llvm::Error &&Err) const {
1331  llvm::Error RemainingErr =
1332  handleErrors(std::move(Err), [this](const DiagnosticError &E) {
1333  auto Diag = E.getDiagnostic().second;
1334 
1335  // Ideally we'd just emit it, but have to handle a possible in-flight
1336  // diagnostic. Note that the location is currently ignored as well.
1337  auto NumArgs = Diag.getStorage()->NumDiagArgs;
1338  assert(NumArgs <= 3 && "Can only have up to 3 arguments");
1339  StringRef Arg1, Arg2, Arg3;
1340  switch (NumArgs) {
1341  case 3:
1342  Arg3 = Diag.getStringArg(2);
1343  [[fallthrough]];
1344  case 2:
1345  Arg2 = Diag.getStringArg(1);
1346  [[fallthrough]];
1347  case 1:
1348  Arg1 = Diag.getStringArg(0);
1349  }
1350  Error(Diag.getDiagID(), Arg1, Arg2, Arg3);
1351  });
1352  if (RemainingErr)
1353  Error(toString(std::move(RemainingErr)));
1354 }
1355 
1356 //===----------------------------------------------------------------------===//
1357 // Source Manager Deserialization
1358 //===----------------------------------------------------------------------===//
1359 
1360 /// Read the line table in the source manager block.
1361 void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
1362  unsigned Idx = 0;
1363  LineTableInfo &LineTable = SourceMgr.getLineTable();
1364 
1365  // Parse the file names
1366  std::map<int, int> FileIDs;
1367  FileIDs[-1] = -1; // For unspecified filenames.
1368  for (unsigned I = 0; Record[Idx]; ++I) {
1369  // Extract the file name
1370  auto Filename = ReadPath(F, Record, Idx);
1371  FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1372  }
1373  ++Idx;
1374 
1375  // Parse the line entries
1376  std::vector<LineEntry> Entries;
1377  while (Idx < Record.size()) {
1378  FileID FID = ReadFileID(F, Record, Idx);
1379 
1380  // Extract the line entries
1381  unsigned NumEntries = Record[Idx++];
1382  assert(NumEntries && "no line entries for file ID");
1383  Entries.clear();
1384  Entries.reserve(NumEntries);
1385  for (unsigned I = 0; I != NumEntries; ++I) {
1386  unsigned FileOffset = Record[Idx++];
1387  unsigned LineNo = Record[Idx++];
1388  int FilenameID = FileIDs[Record[Idx++]];
1391  unsigned IncludeOffset = Record[Idx++];
1392  Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1393  FileKind, IncludeOffset));
1394  }
1395  LineTable.AddEntry(FID, Entries);
1396  }
1397 }
1398 
1399 /// Read a source manager block
1400 llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1401  using namespace SrcMgr;
1402 
1403  BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1404 
1405  // Set the source-location entry cursor to the current position in
1406  // the stream. This cursor will be used to read the contents of the
1407  // source manager block initially, and then lazily read
1408  // source-location entries as needed.
1409  SLocEntryCursor = F.Stream;
1410 
1411  // The stream itself is going to skip over the source manager block.
1412  if (llvm::Error Err = F.Stream.SkipBlock())
1413  return Err;
1414 
1415  // Enter the source manager block.
1416  if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1417  return Err;
1418  F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
1419 
1420  RecordData Record;
1421  while (true) {
1423  SLocEntryCursor.advanceSkippingSubblocks();
1424  if (!MaybeE)
1425  return MaybeE.takeError();
1426  llvm::BitstreamEntry E = MaybeE.get();
1427 
1428  switch (E.Kind) {
1429  case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1431  return llvm::createStringError(std::errc::illegal_byte_sequence,
1432  "malformed block record in AST file");
1433  case llvm::BitstreamEntry::EndBlock:
1434  return llvm::Error::success();
1436  // The interesting case.
1437  break;
1438  }
1439 
1440  // Read a record.
1441  Record.clear();
1442  StringRef Blob;
1443  Expected<unsigned> MaybeRecord =
1444  SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1445  if (!MaybeRecord)
1446  return MaybeRecord.takeError();
1447  switch (MaybeRecord.get()) {
1448  default: // Default behavior: ignore.
1449  break;
1450 
1451  case SM_SLOC_FILE_ENTRY:
1452  case SM_SLOC_BUFFER_ENTRY:
1454  // Once we hit one of the source location entries, we're done.
1455  return llvm::Error::success();
1456  }
1457  }
1458 }
1459 
1462  BitstreamCursor &Cursor = F->SLocEntryCursor;
1463  SavedStreamPosition SavedPosition(Cursor);
1464  if (llvm::Error Err = Cursor.JumpToBit(F->SLocEntryOffsetsBase +
1465  F->SLocEntryOffsets[Index]))
1466  return std::move(Err);
1467 
1468  Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
1469  if (!MaybeEntry)
1470  return MaybeEntry.takeError();
1471 
1472  llvm::BitstreamEntry Entry = MaybeEntry.get();
1473  if (Entry.Kind != llvm::BitstreamEntry::Record)
1474  return llvm::createStringError(
1475  std::errc::illegal_byte_sequence,
1476  "incorrectly-formatted source location entry in AST file");
1477 
1479  StringRef Blob;
1480  Expected<unsigned> MaybeSLOC = Cursor.readRecord(Entry.ID, Record, &Blob);
1481  if (!MaybeSLOC)
1482  return MaybeSLOC.takeError();
1483 
1484  switch (MaybeSLOC.get()) {
1485  default:
1486  return llvm::createStringError(
1487  std::errc::illegal_byte_sequence,
1488  "incorrectly-formatted source location entry in AST file");
1489  case SM_SLOC_FILE_ENTRY:
1490  case SM_SLOC_BUFFER_ENTRY:
1492  return F->SLocEntryBaseOffset + Record[0];
1493  }
1494 }
1495 
1497  auto SLocMapI =
1498  GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset - SLocOffset - 1);
1499  assert(SLocMapI != GlobalSLocOffsetMap.end() &&
1500  "Corrupted global sloc offset map");
1501  ModuleFile *F = SLocMapI->second;
1502 
1503  bool Invalid = false;
1504 
1505  auto It = llvm::upper_bound(
1506  llvm::index_range(0, F->LocalNumSLocEntries), SLocOffset,
1507  [&](SourceLocation::UIntTy Offset, std::size_t LocalIndex) {
1508  int ID = F->SLocEntryBaseID + LocalIndex;
1509  std::size_t Index = -ID - 2;
1510  if (!SourceMgr.SLocEntryOffsetLoaded[Index]) {
1511  assert(!SourceMgr.SLocEntryLoaded[Index]);
1512  auto MaybeEntryOffset = readSLocOffset(F, LocalIndex);
1513  if (!MaybeEntryOffset) {
1514  Error(MaybeEntryOffset.takeError());
1515  Invalid = true;
1516  return true;
1517  }
1518  SourceMgr.LoadedSLocEntryTable[Index] =
1519  SrcMgr::SLocEntry::getOffsetOnly(*MaybeEntryOffset);
1520  SourceMgr.SLocEntryOffsetLoaded[Index] = true;
1521  }
1522  return Offset < SourceMgr.LoadedSLocEntryTable[Index].getOffset();
1523  });
1524 
1525  if (Invalid)
1526  return 0;
1527 
1528  // The iterator points to the first entry with start offset greater than the
1529  // offset of interest. The previous entry must contain the offset of interest.
1530  return F->SLocEntryBaseID + *std::prev(It);
1531 }
1532 
1534  if (ID == 0)
1535  return false;
1536 
1537  if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1538  Error("source location entry ID out-of-range for AST file");
1539  return true;
1540  }
1541 
1542  // Local helper to read the (possibly-compressed) buffer data following the
1543  // entry record.
1544  auto ReadBuffer = [this](
1545  BitstreamCursor &SLocEntryCursor,
1546  StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1548  StringRef Blob;
1549  Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1550  if (!MaybeCode) {
1551  Error(MaybeCode.takeError());
1552  return nullptr;
1553  }
1554  unsigned Code = MaybeCode.get();
1555 
1556  Expected<unsigned> MaybeRecCode =
1557  SLocEntryCursor.readRecord(Code, Record, &Blob);
1558  if (!MaybeRecCode) {
1559  Error(MaybeRecCode.takeError());
1560  return nullptr;
1561  }
1562  unsigned RecCode = MaybeRecCode.get();
1563 
1564  if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1565  // Inspect the first byte to differentiate zlib (\x78) and zstd
1566  // (little-endian 0xFD2FB528).
1567  const llvm::compression::Format F =
1568  Blob.size() > 0 && Blob.data()[0] == 0x78
1569  ? llvm::compression::Format::Zlib
1570  : llvm::compression::Format::Zstd;
1571  if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1572  Error(Reason);
1573  return nullptr;
1574  }
1575  SmallVector<uint8_t, 0> Decompressed;
1576  if (llvm::Error E = llvm::compression::decompress(
1577  F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
1578  Error("could not decompress embedded file contents: " +
1579  llvm::toString(std::move(E)));
1580  return nullptr;
1581  }
1582  return llvm::MemoryBuffer::getMemBufferCopy(
1583  llvm::toStringRef(Decompressed), Name);
1584  } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1585  return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1586  } else {
1587  Error("AST record has invalid code");
1588  return nullptr;
1589  }
1590  };
1591 
1592  ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1593  if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1595  F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1596  Error(std::move(Err));
1597  return true;
1598  }
1599 
1600  BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1602 
1603  ++NumSLocEntriesRead;
1604  Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1605  if (!MaybeEntry) {
1606  Error(MaybeEntry.takeError());
1607  return true;
1608  }
1609  llvm::BitstreamEntry Entry = MaybeEntry.get();
1610 
1611  if (Entry.Kind != llvm::BitstreamEntry::Record) {
1612  Error("incorrectly-formatted source location entry in AST file");
1613  return true;
1614  }
1615 
1617  StringRef Blob;
1618  Expected<unsigned> MaybeSLOC =
1619  SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1620  if (!MaybeSLOC) {
1621  Error(MaybeSLOC.takeError());
1622  return true;
1623  }
1624  switch (MaybeSLOC.get()) {
1625  default:
1626  Error("incorrectly-formatted source location entry in AST file");
1627  return true;
1628 
1629  case SM_SLOC_FILE_ENTRY: {
1630  // We will detect whether a file changed and return 'Failure' for it, but
1631  // we will also try to fail gracefully by setting up the SLocEntry.
1632  unsigned InputID = Record[4];
1633  InputFile IF = getInputFile(*F, InputID);
1635  bool OverriddenBuffer = IF.isOverridden();
1636 
1637  // Note that we only check if a File was returned. If it was out-of-date
1638  // we have complained but we will continue creating a FileID to recover
1639  // gracefully.
1640  if (!File)
1641  return true;
1642 
1643  SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1644  if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1645  // This is the module's main file.
1646  IncludeLoc = getImportLocation(F);
1647  }
1649  FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1650  FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1651  BaseOffset + Record[0]);
1652  SrcMgr::FileInfo &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
1653  FileInfo.NumCreatedFIDs = Record[5];
1654  if (Record[3])
1655  FileInfo.setHasLineDirectives();
1656 
1657  unsigned NumFileDecls = Record[7];
1658  if (NumFileDecls && ContextObj) {
1659  const LocalDeclID *FirstDecl = F->FileSortedDecls + Record[6];
1660  assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1661  FileDeclIDs[FID] =
1662  FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
1663  }
1664 
1665  const SrcMgr::ContentCache &ContentCache =
1666  SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
1667  if (OverriddenBuffer && !ContentCache.BufferOverridden &&
1668  ContentCache.ContentsEntry == ContentCache.OrigEntry &&
1669  !ContentCache.getBufferIfLoaded()) {
1670  auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1671  if (!Buffer)
1672  return true;
1673  SourceMgr.overrideFileContents(*File, std::move(Buffer));
1674  }
1675 
1676  break;
1677  }
1678 
1679  case SM_SLOC_BUFFER_ENTRY: {
1680  const char *Name = Blob.data();
1681  unsigned Offset = Record[0];
1683  FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1684  SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1685  if (IncludeLoc.isInvalid() && F->isModule()) {
1686  IncludeLoc = getImportLocation(F);
1687  }
1688 
1689  auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1690  if (!Buffer)
1691  return true;
1692  FileID FID = SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1693  BaseOffset + Offset, IncludeLoc);
1694  if (Record[3]) {
1695  auto &FileInfo = SourceMgr.getSLocEntry(FID).getFile();
1696  FileInfo.setHasLineDirectives();
1697  }
1698  break;
1699  }
1700 
1701  case SM_SLOC_EXPANSION_ENTRY: {
1703  SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1], Seq);
1704  SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2], Seq);
1705  SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3], Seq);
1706  SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
1707  Record[5], Record[4], ID,
1708  BaseOffset + Record[0]);
1709  break;
1710  }
1711  }
1712 
1713  return false;
1714 }
1715 
1716 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1717  if (ID == 0)
1718  return std::make_pair(SourceLocation(), "");
1719 
1720  if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1721  Error("source location entry ID out-of-range for AST file");
1722  return std::make_pair(SourceLocation(), "");
1723  }
1724 
1725  // Find which module file this entry lands in.
1726  ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1727  if (!M->isModule())
1728  return std::make_pair(SourceLocation(), "");
1729 
1730  // FIXME: Can we map this down to a particular submodule? That would be
1731  // ideal.
1732  return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1733 }
1734 
1735 /// Find the location where the module F is imported.
1736 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1737  if (F->ImportLoc.isValid())
1738  return F->ImportLoc;
1739 
1740  // Otherwise we have a PCH. It's considered to be "imported" at the first
1741  // location of its includer.
1742  if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1743  // Main file is the importer.
1744  assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1745  return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1746  }
1747  return F->ImportedBy[0]->FirstLoc;
1748 }
1749 
1750 /// Enter a subblock of the specified BlockID with the specified cursor. Read
1751 /// the abbreviations that are at the top of the block and then leave the cursor
1752 /// pointing into the block.
1753 llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
1754  unsigned BlockID,
1755  uint64_t *StartOfBlockOffset) {
1756  if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
1757  return Err;
1758 
1759  if (StartOfBlockOffset)
1760  *StartOfBlockOffset = Cursor.GetCurrentBitNo();
1761 
1762  while (true) {
1763  uint64_t Offset = Cursor.GetCurrentBitNo();
1764  Expected<unsigned> MaybeCode = Cursor.ReadCode();
1765  if (!MaybeCode)
1766  return MaybeCode.takeError();
1767  unsigned Code = MaybeCode.get();
1768 
1769  // We expect all abbrevs to be at the start of the block.
1770  if (Code != llvm::bitc::DEFINE_ABBREV) {
1771  if (llvm::Error Err = Cursor.JumpToBit(Offset))
1772  return Err;
1773  return llvm::Error::success();
1774  }
1775  if (llvm::Error Err = Cursor.ReadAbbrevRecord())
1776  return Err;
1777  }
1778 }
1779 
1781  unsigned &Idx) {
1782  Token Tok;
1783  Tok.startToken();
1784  Tok.setLocation(ReadSourceLocation(M, Record, Idx));
1785  Tok.setKind((tok::TokenKind)Record[Idx++]);
1786  Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1787 
1788  if (Tok.isAnnotation()) {
1789  Tok.setAnnotationEndLoc(ReadSourceLocation(M, Record, Idx));
1790  switch (Tok.getKind()) {
1791  case tok::annot_pragma_loop_hint: {
1792  auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
1793  Info->PragmaName = ReadToken(M, Record, Idx);
1794  Info->Option = ReadToken(M, Record, Idx);
1795  unsigned NumTokens = Record[Idx++];
1796  SmallVector<Token, 4> Toks;
1797  Toks.reserve(NumTokens);
1798  for (unsigned I = 0; I < NumTokens; ++I)
1799  Toks.push_back(ReadToken(M, Record, Idx));
1800  Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
1801  Tok.setAnnotationValue(static_cast<void *>(Info));
1802  break;
1803  }
1804  case tok::annot_pragma_pack: {
1805  auto *Info = new (PP.getPreprocessorAllocator()) Sema::PragmaPackInfo;
1806  Info->Action = static_cast<Sema::PragmaMsStackAction>(Record[Idx++]);
1807  auto SlotLabel = ReadString(Record, Idx);
1808  Info->SlotLabel =
1809  llvm::StringRef(SlotLabel).copy(PP.getPreprocessorAllocator());
1810  Info->Alignment = ReadToken(M, Record, Idx);
1811  Tok.setAnnotationValue(static_cast<void *>(Info));
1812  break;
1813  }
1814  // Some annotation tokens do not use the PtrData field.
1815  case tok::annot_pragma_openmp:
1816  case tok::annot_pragma_openmp_end:
1817  case tok::annot_pragma_unused:
1818  case tok::annot_pragma_openacc:
1819  case tok::annot_pragma_openacc_end:
1820  break;
1821  default:
1822  llvm_unreachable("missing deserialization code for annotation token");
1823  }
1824  } else {
1825  Tok.setLength(Record[Idx++]);
1826  if (IdentifierInfo *II = getLocalIdentifier(M, Record[Idx++]))
1827  Tok.setIdentifierInfo(II);
1828  }
1829  return Tok;
1830 }
1831 
1833  BitstreamCursor &Stream = F.MacroCursor;
1834 
1835  // Keep track of where we are in the stream, then jump back there
1836  // after reading this macro.
1837  SavedStreamPosition SavedPosition(Stream);
1838 
1839  if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1840  // FIXME this drops errors on the floor.
1841  consumeError(std::move(Err));
1842  return nullptr;
1843  }
1846  MacroInfo *Macro = nullptr;
1847  llvm::MutableArrayRef<Token> MacroTokens;
1848 
1849  while (true) {
1850  // Advance to the next record, but if we get to the end of the block, don't
1851  // pop it (removing all the abbreviations from the cursor) since we want to
1852  // be able to reseek within the block and read entries.
1853  unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1854  Expected<llvm::BitstreamEntry> MaybeEntry =
1855  Stream.advanceSkippingSubblocks(Flags);
1856  if (!MaybeEntry) {
1857  Error(MaybeEntry.takeError());
1858  return Macro;
1859  }
1860  llvm::BitstreamEntry Entry = MaybeEntry.get();
1861 
1862  switch (Entry.Kind) {
1863  case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1865  Error("malformed block record in AST file");
1866  return Macro;
1867  case llvm::BitstreamEntry::EndBlock:
1868  return Macro;
1870  // The interesting case.
1871  break;
1872  }
1873 
1874  // Read a record.
1875  Record.clear();
1876  PreprocessorRecordTypes RecType;
1877  if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1878  RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1879  else {
1880  Error(MaybeRecType.takeError());
1881  return Macro;
1882  }
1883  switch (RecType) {
1884  case PP_MODULE_MACRO:
1886  return Macro;
1887 
1888  case PP_MACRO_OBJECT_LIKE:
1889  case PP_MACRO_FUNCTION_LIKE: {
1890  // If we already have a macro, that means that we've hit the end
1891  // of the definition of the macro we were looking for. We're
1892  // done.
1893  if (Macro)
1894  return Macro;
1895 
1896  unsigned NextIndex = 1; // Skip identifier ID.
1897  SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1898  MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1899  MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1900  MI->setIsUsed(Record[NextIndex++]);
1901  MI->setUsedForHeaderGuard(Record[NextIndex++]);
1902  MacroTokens = MI->allocateTokens(Record[NextIndex++],
1903  PP.getPreprocessorAllocator());
1904  if (RecType == PP_MACRO_FUNCTION_LIKE) {
1905  // Decode function-like macro info.
1906  bool isC99VarArgs = Record[NextIndex++];
1907  bool isGNUVarArgs = Record[NextIndex++];
1908  bool hasCommaPasting = Record[NextIndex++];
1909  MacroParams.clear();
1910  unsigned NumArgs = Record[NextIndex++];
1911  for (unsigned i = 0; i != NumArgs; ++i)
1912  MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1913 
1914  // Install function-like macro info.
1915  MI->setIsFunctionLike();
1916  if (isC99VarArgs) MI->setIsC99Varargs();
1917  if (isGNUVarArgs) MI->setIsGNUVarargs();
1918  if (hasCommaPasting) MI->setHasCommaPasting();
1919  MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
1920  }
1921 
1922  // Remember that we saw this macro last so that we add the tokens that
1923  // form its body to it.
1924  Macro = MI;
1925 
1926  if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1927  Record[NextIndex]) {
1928  // We have a macro definition. Register the association
1930  GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1931  PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1932  PreprocessingRecord::PPEntityID PPID =
1933  PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1934  MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1935  PPRec.getPreprocessedEntity(PPID));
1936  if (PPDef)
1937  PPRec.RegisterMacroDefinition(Macro, PPDef);
1938  }
1939 
1940  ++NumMacrosRead;
1941  break;
1942  }
1943 
1944  case PP_TOKEN: {
1945  // If we see a TOKEN before a PP_MACRO_*, then the file is
1946  // erroneous, just pretend we didn't see this.
1947  if (!Macro) break;
1948  if (MacroTokens.empty()) {
1949  Error("unexpected number of macro tokens for a macro in AST file");
1950  return Macro;
1951  }
1952 
1953  unsigned Idx = 0;
1954  MacroTokens[0] = ReadToken(F, Record, Idx);
1955  MacroTokens = MacroTokens.drop_front();
1956  break;
1957  }
1958  }
1959  }
1960 }
1961 
1964  unsigned LocalID) const {
1965  if (!M.ModuleOffsetMap.empty())
1966  ReadModuleOffsetMap(M);
1967 
1970  assert(I != M.PreprocessedEntityRemap.end()
1971  && "Invalid index into preprocessed entity index remap");
1972 
1973  return LocalID + I->second;
1974 }
1975 
1976 const FileEntry *HeaderFileInfoTrait::getFile(const internal_key_type &Key) {
1977  FileManager &FileMgr = Reader.getFileManager();
1978  if (!Key.Imported) {
1979  if (auto File = FileMgr.getFile(Key.Filename))
1980  return *File;
1981  return nullptr;
1982  }
1983 
1984  std::string Resolved = std::string(Key.Filename);
1985  Reader.ResolveImportedPath(M, Resolved);
1986  if (auto File = FileMgr.getFile(Resolved))
1987  return *File;
1988  return nullptr;
1989 }
1990 
1992  return llvm::hash_combine(ikey.Size, ikey.ModTime);
1993 }
1994 
1996 HeaderFileInfoTrait::GetInternalKey(external_key_type ekey) {
1997  internal_key_type ikey = {ekey.getSize(),
1998  M.HasTimestamps ? ekey.getModificationTime() : 0,
1999  ekey.getName(), /*Imported*/ false};
2000  return ikey;
2001 }
2002 
2003 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
2004  if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
2005  return false;
2006 
2007  if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
2008  return true;
2009 
2010  // Determine whether the actual files are equivalent.
2011  const FileEntry *FEA = getFile(a);
2012  const FileEntry *FEB = getFile(b);
2013  return FEA && FEA == FEB;
2014 }
2015 
2016 std::pair<unsigned, unsigned>
2017 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
2018  return readULEBKeyDataLength(d);
2019 }
2020 
2022 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
2023  using namespace llvm::support;
2024 
2025  internal_key_type ikey;
2026  ikey.Size = off_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2027  ikey.ModTime =
2028  time_t(endian::readNext<uint64_t, llvm::endianness::little>(d));
2029  ikey.Filename = (const char *)d;
2030  ikey.Imported = true;
2031  return ikey;
2032 }
2033 
2035 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
2036  unsigned DataLen) {
2037  using namespace llvm::support;
2038 
2039  const unsigned char *End = d + DataLen;
2040  HeaderFileInfo HFI;
2041  unsigned Flags = *d++;
2042 
2043  bool Included = (Flags >> 6) & 0x01;
2044  if (Included)
2045  if (const FileEntry *FE = getFile(key))
2046  // Not using \c Preprocessor::markIncluded(), since that would attempt to
2047  // deserialize this header file info again.
2048  Reader.getPreprocessor().getIncludedFiles().insert(FE);
2049 
2050  // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
2051  HFI.isImport |= (Flags >> 5) & 0x01;
2052  HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
2053  HFI.DirInfo = (Flags >> 1) & 0x07;
2054  HFI.IndexHeaderMapHeader = Flags & 0x01;
2055  HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
2056  M, endian::readNext<uint32_t, llvm::endianness::little>(d));
2057  if (unsigned FrameworkOffset =
2058  endian::readNext<uint32_t, llvm::endianness::little>(d)) {
2059  // The framework offset is 1 greater than the actual offset,
2060  // since 0 is used as an indicator for "no framework name".
2061  StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
2062  HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
2063  }
2064 
2065  assert((End - d) % 4 == 0 &&
2066  "Wrong data length in HeaderFileInfo deserialization");
2067  while (d != End) {
2068  uint32_t LocalSMID =
2069  endian::readNext<uint32_t, llvm::endianness::little>(d);
2070  auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
2071  LocalSMID >>= 3;
2072 
2073  // This header is part of a module. Associate it with the module to enable
2074  // implicit module import.
2075  SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
2076  Module *Mod = Reader.getSubmodule(GlobalSMID);
2077  FileManager &FileMgr = Reader.getFileManager();
2078  ModuleMap &ModMap =
2079  Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
2080 
2081  std::string Filename = std::string(key.Filename);
2082  if (key.Imported)
2083  Reader.ResolveImportedPath(M, Filename);
2084  if (auto FE = FileMgr.getOptionalFileRef(Filename)) {
2085  // FIXME: NameAsWritten
2086  Module::Header H = {std::string(key.Filename), "", *FE};
2087  ModMap.addHeader(Mod, H, HeaderRole, /*Imported=*/true);
2088  }
2089  HFI.mergeModuleMembership(HeaderRole);
2090  }
2091 
2092  // This HeaderFileInfo was externally loaded.
2093  HFI.External = true;
2094  HFI.IsValid = true;
2095  return HFI;
2096 }
2097 
2099  uint32_t MacroDirectivesOffset) {
2100  assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
2101  PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
2102 }
2103 
2105  // Note that we are loading defined macros.
2106  Deserializing Macros(this);
2107 
2108  for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
2109  BitstreamCursor &MacroCursor = I.MacroCursor;
2110 
2111  // If there was no preprocessor block, skip this file.
2112  if (MacroCursor.getBitcodeBytes().empty())
2113  continue;
2114 
2115  BitstreamCursor Cursor = MacroCursor;
2116  if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
2117  Error(std::move(Err));
2118  return;
2119  }
2120 
2122  while (true) {
2123  Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
2124  if (!MaybeE) {
2125  Error(MaybeE.takeError());
2126  return;
2127  }
2128  llvm::BitstreamEntry E = MaybeE.get();
2129 
2130  switch (E.Kind) {
2131  case llvm::BitstreamEntry::SubBlock: // Handled for us already.
2133  Error("malformed block record in AST file");
2134  return;
2135  case llvm::BitstreamEntry::EndBlock:
2136  goto NextCursor;
2137 
2139  Record.clear();
2140  Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
2141  if (!MaybeRecord) {
2142  Error(MaybeRecord.takeError());
2143  return;
2144  }
2145  switch (MaybeRecord.get()) {
2146  default: // Default behavior: ignore.
2147  break;
2148 
2149  case PP_MACRO_OBJECT_LIKE:
2150  case PP_MACRO_FUNCTION_LIKE: {
2151  IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
2152  if (II->isOutOfDate())
2153  updateOutOfDateIdentifier(*II);
2154  break;
2155  }
2156 
2157  case PP_TOKEN:
2158  // Ignore tokens.
2159  break;
2160  }
2161  break;
2162  }
2163  }
2164  }
2165  NextCursor: ;
2166  }
2167 }
2168 
2169 namespace {
2170 
2171  /// Visitor class used to look up identifirs in an AST file.
2172  class IdentifierLookupVisitor {
2173  StringRef Name;
2174  unsigned NameHash;
2175  unsigned PriorGeneration;
2176  unsigned &NumIdentifierLookups;
2177  unsigned &NumIdentifierLookupHits;
2178  IdentifierInfo *Found = nullptr;
2179 
2180  public:
2181  IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2182  unsigned &NumIdentifierLookups,
2183  unsigned &NumIdentifierLookupHits)
2184  : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2185  PriorGeneration(PriorGeneration),
2186  NumIdentifierLookups(NumIdentifierLookups),
2187  NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2188 
2189  bool operator()(ModuleFile &M) {
2190  // If we've already searched this module file, skip it now.
2191  if (M.Generation <= PriorGeneration)
2192  return true;
2193 
2194  ASTIdentifierLookupTable *IdTable
2196  if (!IdTable)
2197  return false;
2198 
2199  ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2200  Found);
2201  ++NumIdentifierLookups;
2202  ASTIdentifierLookupTable::iterator Pos =
2203  IdTable->find_hashed(Name, NameHash, &Trait);
2204  if (Pos == IdTable->end())
2205  return false;
2206 
2207  // Dereferencing the iterator has the effect of building the
2208  // IdentifierInfo node and populating it with the various
2209  // declarations it needs.
2210  ++NumIdentifierLookupHits;
2211  Found = *Pos;
2212  return true;
2213  }
2214 
2215  // Retrieve the identifier info found within the module
2216  // files.
2217  IdentifierInfo *getIdentifierInfo() const { return Found; }
2218  };
2219 
2220 } // namespace
2221 
2223  // Note that we are loading an identifier.
2224  Deserializing AnIdentifier(this);
2225 
2226  unsigned PriorGeneration = 0;
2227  if (getContext().getLangOpts().Modules)
2228  PriorGeneration = IdentifierGeneration[&II];
2229 
2230  // If there is a global index, look there first to determine which modules
2231  // provably do not have any results for this identifier.
2233  GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2234  if (!loadGlobalIndex()) {
2235  if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2236  HitsPtr = &Hits;
2237  }
2238  }
2239 
2240  IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2241  NumIdentifierLookups,
2242  NumIdentifierLookupHits);
2243  ModuleMgr.visit(Visitor, HitsPtr);
2244  markIdentifierUpToDate(&II);
2245 }
2246 
2248  if (!II)
2249  return;
2250 
2251  const_cast<IdentifierInfo *>(II)->setOutOfDate(false);
2252 
2253  // Update the generation for this identifier.
2254  if (getContext().getLangOpts().Modules)
2255  IdentifierGeneration[II] = getGeneration();
2256 }
2257 
2259  const PendingMacroInfo &PMInfo) {
2260  ModuleFile &M = *PMInfo.M;
2261 
2262  BitstreamCursor &Cursor = M.MacroCursor;
2263  SavedStreamPosition SavedPosition(Cursor);
2264  if (llvm::Error Err =
2265  Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
2266  Error(std::move(Err));
2267  return;
2268  }
2269 
2270  struct ModuleMacroRecord {
2271  SubmoduleID SubModID;
2272  MacroInfo *MI;
2273  SmallVector<SubmoduleID, 8> Overrides;
2274  };
2276 
2277  // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2278  // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2279  // macro histroy.
2281  while (true) {
2282  Expected<llvm::BitstreamEntry> MaybeEntry =
2283  Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2284  if (!MaybeEntry) {
2285  Error(MaybeEntry.takeError());
2286  return;
2287  }
2288  llvm::BitstreamEntry Entry = MaybeEntry.get();
2289 
2290  if (Entry.Kind != llvm::BitstreamEntry::Record) {
2291  Error("malformed block record in AST file");
2292  return;
2293  }
2294 
2295  Record.clear();
2296  Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2297  if (!MaybePP) {
2298  Error(MaybePP.takeError());
2299  return;
2300  }
2301  switch ((PreprocessorRecordTypes)MaybePP.get()) {
2303  break;
2304 
2305  case PP_MODULE_MACRO: {
2306  ModuleMacros.push_back(ModuleMacroRecord());
2307  auto &Info = ModuleMacros.back();
2308  Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2309  Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
2310  for (int I = 2, N = Record.size(); I != N; ++I)
2311  Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2312  continue;
2313  }
2314 
2315  default:
2316  Error("malformed block record in AST file");
2317  return;
2318  }
2319 
2320  // We found the macro directive history; that's the last record
2321  // for this macro.
2322  break;
2323  }
2324 
2325  // Module macros are listed in reverse dependency order.
2326  {
2327  std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2329  for (auto &MMR : ModuleMacros) {
2330  Overrides.clear();
2331  for (unsigned ModID : MMR.Overrides) {
2332  Module *Mod = getSubmodule(ModID);
2333  auto *Macro = PP.getModuleMacro(Mod, II);
2334  assert(Macro && "missing definition for overridden macro");
2335  Overrides.push_back(Macro);
2336  }
2337 
2338  bool Inserted = false;
2339  Module *Owner = getSubmodule(MMR.SubModID);
2340  PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2341  }
2342  }
2343 
2344  // Don't read the directive history for a module; we don't have anywhere
2345  // to put it.
2346  if (M.isModule())
2347  return;
2348 
2349  // Deserialize the macro directives history in reverse source-order.
2350  MacroDirective *Latest = nullptr, *Earliest = nullptr;
2351  unsigned Idx = 0, N = Record.size();
2352  while (Idx < N) {
2353  MacroDirective *MD = nullptr;
2354  SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
2356  switch (K) {
2358  MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2359  MD = PP.AllocateDefMacroDirective(MI, Loc);
2360  break;
2361  }
2363  MD = PP.AllocateUndefMacroDirective(Loc);
2364  break;
2366  bool isPublic = Record[Idx++];
2367  MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2368  break;
2369  }
2370 
2371  if (!Latest)
2372  Latest = MD;
2373  if (Earliest)
2374  Earliest->setPrevious(MD);
2375  Earliest = MD;
2376  }
2377 
2378  if (Latest)
2379  PP.setLoadedMacroDirective(II, Earliest, Latest);
2380 }
2381 
2382 bool ASTReader::shouldDisableValidationForFile(
2383  const serialization::ModuleFile &M) const {
2384  if (DisableValidationKind == DisableValidationForModuleKind::None)
2385  return false;
2386 
2387  // If a PCH is loaded and validation is disabled for PCH then disable
2388  // validation for the PCH and the modules it loads.
2389  ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2390 
2391  switch (K) {
2392  case MK_MainFile:
2393  case MK_Preamble:
2394  case MK_PCH:
2395  return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2396  case MK_ImplicitModule:
2397  case MK_ExplicitModule:
2398  case MK_PrebuiltModule:
2399  return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2400  }
2401 
2402  return false;
2403 }
2404 
2405 InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2406  // If this ID is bogus, just return an empty input file.
2407  if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2408  return InputFileInfo();
2409 
2410  // If we've already loaded this input file, return it.
2411  if (!F.InputFileInfosLoaded[ID - 1].Filename.empty())
2412  return F.InputFileInfosLoaded[ID - 1];
2413 
2414  // Go find this input file.
2415  BitstreamCursor &Cursor = F.InputFilesCursor;
2416  SavedStreamPosition SavedPosition(Cursor);
2417  if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2418  F.InputFileOffsets[ID - 1])) {
2419  // FIXME this drops errors on the floor.
2420  consumeError(std::move(Err));
2421  }
2422 
2423  Expected<unsigned> MaybeCode = Cursor.ReadCode();
2424  if (!MaybeCode) {
2425  // FIXME this drops errors on the floor.
2426  consumeError(MaybeCode.takeError());
2427  }
2428  unsigned Code = MaybeCode.get();
2429  RecordData Record;
2430  StringRef Blob;
2431 
2432  if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2433  assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2434  "invalid record type for input file");
2435  else {
2436  // FIXME this drops errors on the floor.
2437  consumeError(Maybe.takeError());
2438  }
2439 
2440  assert(Record[0] == ID && "Bogus stored ID or offset");
2441  InputFileInfo R;
2442  R.StoredSize = static_cast<off_t>(Record[1]);
2443  R.StoredTime = static_cast<time_t>(Record[2]);
2444  R.Overridden = static_cast<bool>(Record[3]);
2445  R.Transient = static_cast<bool>(Record[4]);
2446  R.TopLevel = static_cast<bool>(Record[5]);
2447  R.ModuleMap = static_cast<bool>(Record[6]);
2448  std::tie(R.FilenameAsRequested, R.Filename) = [&]() {
2449  uint16_t AsRequestedLength = Record[7];
2450 
2451  std::string NameAsRequested = Blob.substr(0, AsRequestedLength).str();
2452  std::string Name = Blob.substr(AsRequestedLength).str();
2453 
2454  ResolveImportedPath(F, NameAsRequested);
2455  ResolveImportedPath(F, Name);
2456 
2457  if (Name.empty())
2458  Name = NameAsRequested;
2459 
2460  return std::make_pair(std::move(NameAsRequested), std::move(Name));
2461  }();
2462 
2463  Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2464  if (!MaybeEntry) // FIXME this drops errors on the floor.
2465  consumeError(MaybeEntry.takeError());
2466  llvm::BitstreamEntry Entry = MaybeEntry.get();
2467  assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2468  "expected record type for input file hash");
2469 
2470  Record.clear();
2471  if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2472  assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2473  "invalid record type for input file hash");
2474  else {
2475  // FIXME this drops errors on the floor.
2476  consumeError(Maybe.takeError());
2477  }
2478  R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2479  static_cast<uint64_t>(Record[0]);
2480 
2481  // Note that we've loaded this input file info.
2482  F.InputFileInfosLoaded[ID - 1] = R;
2483  return R;
2484 }
2485 
2486 static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2487 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2488  // If this ID is bogus, just return an empty input file.
2489  if (ID == 0 || ID > F.InputFilesLoaded.size())
2490  return InputFile();
2491 
2492  // If we've already loaded this input file, return it.
2493  if (F.InputFilesLoaded[ID-1].getFile())
2494  return F.InputFilesLoaded[ID-1];
2495 
2496  if (F.InputFilesLoaded[ID-1].isNotFound())
2497  return InputFile();
2498 
2499  // Go find this input file.
2500  BitstreamCursor &Cursor = F.InputFilesCursor;
2501  SavedStreamPosition SavedPosition(Cursor);
2502  if (llvm::Error Err = Cursor.JumpToBit(F.InputFilesOffsetBase +
2503  F.InputFileOffsets[ID - 1])) {
2504  // FIXME this drops errors on the floor.
2505  consumeError(std::move(Err));
2506  }
2507 
2508  InputFileInfo FI = getInputFileInfo(F, ID);
2509  off_t StoredSize = FI.StoredSize;
2510  time_t StoredTime = FI.StoredTime;
2511  bool Overridden = FI.Overridden;
2512  bool Transient = FI.Transient;
2513  StringRef Filename = FI.FilenameAsRequested;
2514  uint64_t StoredContentHash = FI.ContentHash;
2515 
2516  // For standard C++ modules, we don't need to check the inputs.
2517  bool SkipChecks = F.StandardCXXModule;
2518 
2519  const HeaderSearchOptions &HSOpts =
2520  PP.getHeaderSearchInfo().getHeaderSearchOpts();
2521 
2522  // The option ForceCheckCXX20ModulesInputFiles is only meaningful for C++20
2523  // modules.
2525  SkipChecks = false;
2526  Overridden = false;
2527  }
2528 
2529  auto File = FileMgr.getOptionalFileRef(Filename, /*OpenFile=*/false);
2530 
2531  // For an overridden file, create a virtual file with the stored
2532  // size/timestamp.
2533  if ((Overridden || Transient || SkipChecks) && !File)
2534  File = FileMgr.getVirtualFileRef(Filename, StoredSize, StoredTime);
2535 
2536  if (!File) {
2537  if (Complain) {
2538  std::string ErrorStr = "could not find file '";
2539  ErrorStr += Filename;
2540  ErrorStr += "' referenced by AST file '";
2541  ErrorStr += F.FileName;
2542  ErrorStr += "'";
2543  Error(ErrorStr);
2544  }
2545  // Record that we didn't find the file.
2547  return InputFile();
2548  }
2549 
2550  // Check if there was a request to override the contents of the file
2551  // that was part of the precompiled header. Overriding such a file
2552  // can lead to problems when lexing using the source locations from the
2553  // PCH.
2554  SourceManager &SM = getSourceManager();
2555  // FIXME: Reject if the overrides are different.
2556  if ((!Overridden && !Transient) && !SkipChecks &&
2557  SM.isFileOverridden(*File)) {
2558  if (Complain)
2559  Error(diag::err_fe_pch_file_overridden, Filename);
2560 
2561  // After emitting the diagnostic, bypass the overriding file to recover
2562  // (this creates a separate FileEntry).
2563  File = SM.bypassFileContentsOverride(*File);
2564  if (!File) {
2566  return InputFile();
2567  }
2568  }
2569 
2570  struct Change {
2571  enum ModificationKind {
2572  Size,
2573  ModTime,
2574  Content,
2575  None,
2576  } Kind;
2577  std::optional<int64_t> Old = std::nullopt;
2578  std::optional<int64_t> New = std::nullopt;
2579  };
2580  auto HasInputContentChanged = [&](Change OriginalChange) {
2581  assert(ValidateASTInputFilesContent &&
2582  "We should only check the content of the inputs with "
2583  "ValidateASTInputFilesContent enabled.");
2584 
2585  if (StoredContentHash == static_cast<uint64_t>(llvm::hash_code(-1)))
2586  return OriginalChange;
2587 
2588  auto MemBuffOrError = FileMgr.getBufferForFile(*File);
2589  if (!MemBuffOrError) {
2590  if (!Complain)
2591  return OriginalChange;
2592  std::string ErrorStr = "could not get buffer for file '";
2593  ErrorStr += File->getName();
2594  ErrorStr += "'";
2595  Error(ErrorStr);
2596  return OriginalChange;
2597  }
2598 
2599  // FIXME: hash_value is not guaranteed to be stable!
2600  auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2601  if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2602  return Change{Change::None};
2603 
2604  return Change{Change::Content};
2605  };
2606  auto HasInputFileChanged = [&]() {
2607  if (StoredSize != File->getSize())
2608  return Change{Change::Size, StoredSize, File->getSize()};
2609  if (!shouldDisableValidationForFile(F) && StoredTime &&
2610  StoredTime != File->getModificationTime()) {
2611  Change MTimeChange = {Change::ModTime, StoredTime,
2612  File->getModificationTime()};
2613 
2614  // In case the modification time changes but not the content,
2615  // accept the cached file as legit.
2616  if (ValidateASTInputFilesContent)
2617  return HasInputContentChanged(MTimeChange);
2618 
2619  return MTimeChange;
2620  }
2621  return Change{Change::None};
2622  };
2623 
2624  bool IsOutOfDate = false;
2625  auto FileChange = SkipChecks ? Change{Change::None} : HasInputFileChanged();
2626  // When ForceCheckCXX20ModulesInputFiles and ValidateASTInputFilesContent
2627  // enabled, it is better to check the contents of the inputs. Since we can't
2628  // get correct modified time information for inputs from overriden inputs.
2629  if (HSOpts.ForceCheckCXX20ModulesInputFiles && ValidateASTInputFilesContent &&
2630  F.StandardCXXModule && FileChange.Kind == Change::None)
2631  FileChange = HasInputContentChanged(FileChange);
2632 
2633  // When we have StoredTime equal to zero and ValidateASTInputFilesContent,
2634  // it is better to check the content of the input files because we cannot rely
2635  // on the file modification time, which will be the same (zero) for these
2636  // files.
2637  if (!StoredTime && ValidateASTInputFilesContent &&
2638  FileChange.Kind == Change::None)
2639  FileChange = HasInputContentChanged(FileChange);
2640 
2641  // For an overridden file, there is nothing to validate.
2642  if (!Overridden && FileChange.Kind != Change::None) {
2643  if (Complain && !Diags.isDiagnosticInFlight()) {
2644  // Build a list of the PCH imports that got us here (in reverse).
2645  SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2646  while (!ImportStack.back()->ImportedBy.empty())
2647  ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2648 
2649  // The top-level PCH is stale.
2650  StringRef TopLevelPCHName(ImportStack.back()->FileName);
2651  Diag(diag::err_fe_ast_file_modified)
2652  << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2653  << TopLevelPCHName << FileChange.Kind
2654  << (FileChange.Old && FileChange.New)
2655  << llvm::itostr(FileChange.Old.value_or(0))
2656  << llvm::itostr(FileChange.New.value_or(0));
2657 
2658  // Print the import stack.
2659  if (ImportStack.size() > 1) {
2660  Diag(diag::note_pch_required_by)
2661  << Filename << ImportStack[0]->FileName;
2662  for (unsigned I = 1; I < ImportStack.size(); ++I)
2663  Diag(diag::note_pch_required_by)
2664  << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2665  }
2666 
2667  Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2668  }
2669 
2670  IsOutOfDate = true;
2671  }
2672  // FIXME: If the file is overridden and we've already opened it,
2673  // issue an error (or split it into a separate FileEntry).
2674 
2675  InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
2676 
2677  // Note that we've loaded this input file.
2678  F.InputFilesLoaded[ID-1] = IF;
2679  return IF;
2680 }
2681 
2682 /// If we are loading a relocatable PCH or module file, and the filename
2683 /// is not an absolute path, add the system or module root to the beginning of
2684 /// the file name.
2686  // Resolve relative to the base directory, if we have one.
2687  if (!M.BaseDirectory.empty())
2688  return ResolveImportedPath(Filename, M.BaseDirectory);
2689 }
2690 
2691 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2692  if (Filename.empty() || llvm::sys::path::is_absolute(Filename) ||
2693  Filename == "<built-in>" || Filename == "<command line>")
2694  return;
2695 
2696  SmallString<128> Buffer;
2697  llvm::sys::path::append(Buffer, Prefix, Filename);
2698  Filename.assign(Buffer.begin(), Buffer.end());
2699 }
2700 
2701 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2702  switch (ARR) {
2703  case ASTReader::Failure: return true;
2704  case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2705  case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2708  return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2709  case ASTReader::HadErrors: return true;
2710  case ASTReader::Success: return false;
2711  }
2712 
2713  llvm_unreachable("unknown ASTReadResult");
2714 }
2715 
2716 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2717  BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2718  bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2719  std::string &SuggestedPredefines) {
2720  if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2721  // FIXME this drops errors on the floor.
2722  consumeError(std::move(Err));
2723  return Failure;
2724  }
2725 
2726  // Read all of the records in the options block.
2727  RecordData Record;
2728  ASTReadResult Result = Success;
2729  while (true) {
2730  Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2731  if (!MaybeEntry) {
2732  // FIXME this drops errors on the floor.
2733  consumeError(MaybeEntry.takeError());
2734  return Failure;
2735  }
2736  llvm::BitstreamEntry Entry = MaybeEntry.get();
2737 
2738  switch (Entry.Kind) {
2740  case llvm::BitstreamEntry::SubBlock:
2741  return Failure;
2742 
2743  case llvm::BitstreamEntry::EndBlock:
2744  return Result;
2745 
2747  // The interesting case.
2748  break;
2749  }
2750 
2751  // Read and process a record.
2752  Record.clear();
2753  Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2754  if (!MaybeRecordType) {
2755  // FIXME this drops errors on the floor.
2756  consumeError(MaybeRecordType.takeError());
2757  return Failure;
2758  }
2759  switch ((OptionsRecordTypes)MaybeRecordType.get()) {
2760  case LANGUAGE_OPTIONS: {
2761  bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2762  if (ParseLanguageOptions(Record, Complain, Listener,
2763  AllowCompatibleConfigurationMismatch))
2764  Result = ConfigurationMismatch;
2765  break;
2766  }
2767 
2768  case TARGET_OPTIONS: {
2769  bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2770  if (ParseTargetOptions(Record, Complain, Listener,
2771  AllowCompatibleConfigurationMismatch))
2772  Result = ConfigurationMismatch;
2773  break;
2774  }
2775 
2776  case FILE_SYSTEM_OPTIONS: {
2777  bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2778  if (!AllowCompatibleConfigurationMismatch &&
2779  ParseFileSystemOptions(Record, Complain, Listener))
2780  Result = ConfigurationMismatch;
2781  break;
2782  }
2783 
2784  case HEADER_SEARCH_OPTIONS: {
2785  bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2786  if (!AllowCompatibleConfigurationMismatch &&
2787  ParseHeaderSearchOptions(Record, Complain, Listener))
2788  Result = ConfigurationMismatch;
2789  break;
2790  }
2791 
2792  case PREPROCESSOR_OPTIONS:
2793  bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2794  if (!AllowCompatibleConfigurationMismatch &&
2795  ParsePreprocessorOptions(Record, Complain, Listener,
2796  SuggestedPredefines))
2797  Result = ConfigurationMismatch;
2798  break;
2799  }
2800  }
2801 }
2802 
2804 ASTReader::ReadControlBlock(ModuleFile &F,
2806  const ModuleFile *ImportedBy,
2807  unsigned ClientLoadCapabilities) {
2808  BitstreamCursor &Stream = F.Stream;
2809 
2810  if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2811  Error(std::move(Err));
2812  return Failure;
2813  }
2814 
2815  // Lambda to read the unhashed control block the first time it's called.
2816  //
2817  // For PCM files, the unhashed control block cannot be read until after the
2818  // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2819  // need to look ahead before reading the IMPORTS record. For consistency,
2820  // this block is always read somehow (see BitstreamEntry::EndBlock).
2821  bool HasReadUnhashedControlBlock = false;
2822  auto readUnhashedControlBlockOnce = [&]() {
2823  if (!HasReadUnhashedControlBlock) {
2824  HasReadUnhashedControlBlock = true;
2825  if (ASTReadResult Result =
2826  readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2827  return Result;
2828  }
2829  return Success;
2830  };
2831 
2832  bool DisableValidation = shouldDisableValidationForFile(F);
2833 
2834  // Read all of the records and blocks in the control block.
2835  RecordData Record;
2836  unsigned NumInputs = 0;
2837  unsigned NumUserInputs = 0;
2838  StringRef BaseDirectoryAsWritten;
2839  while (true) {
2840  Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2841  if (!MaybeEntry) {
2842  Error(MaybeEntry.takeError());
2843  return Failure;
2844  }
2845  llvm::BitstreamEntry Entry = MaybeEntry.get();
2846 
2847  switch (Entry.Kind) {
2849  Error("malformed block record in AST file");
2850  return Failure;
2851  case llvm::BitstreamEntry::EndBlock: {
2852  // Validate the module before returning. This call catches an AST with
2853  // no module name and no imports.
2854  if (ASTReadResult Result = readUnhashedControlBlockOnce())
2855  return Result;
2856 
2857  // Validate input files.
2858  const HeaderSearchOptions &HSOpts =
2859  PP.getHeaderSearchInfo().getHeaderSearchOpts();
2860 
2861  // All user input files reside at the index range [0, NumUserInputs), and
2862  // system input files reside at [NumUserInputs, NumInputs). For explicitly
2863  // loaded module files, ignore missing inputs.
2864  if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2865  F.Kind != MK_PrebuiltModule) {
2866  bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2867 
2868  // If we are reading a module, we will create a verification timestamp,
2869  // so we verify all input files. Otherwise, verify only user input
2870  // files.
2871 
2872  unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
2875  F.Kind == MK_ImplicitModule)
2876  N = NumUserInputs;
2877 
2878  for (unsigned I = 0; I < N; ++I) {
2879  InputFile IF = getInputFile(F, I+1, Complain);
2880  if (!IF.getFile() || IF.isOutOfDate())
2881  return OutOfDate;
2882  }
2883  }
2884 
2885  if (Listener)
2886  Listener->visitModuleFile(F.FileName, F.Kind);
2887 
2888  if (Listener && Listener->needsInputFileVisitation()) {
2889  unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2890  : NumUserInputs;
2891  for (unsigned I = 0; I < N; ++I) {
2892  bool IsSystem = I >= NumUserInputs;
2893  InputFileInfo FI = getInputFileInfo(F, I + 1);
2894  Listener->visitInputFile(
2895  FI.FilenameAsRequested, IsSystem, FI.Overridden,
2897  }
2898  }
2899 
2900  return Success;
2901  }
2902 
2903  case llvm::BitstreamEntry::SubBlock:
2904  switch (Entry.ID) {
2905  case INPUT_FILES_BLOCK_ID:
2906  F.InputFilesCursor = Stream;
2907  if (llvm::Error Err = Stream.SkipBlock()) {
2908  Error(std::move(Err));
2909  return Failure;
2910  }
2911  if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2912  Error("malformed block record in AST file");
2913  return Failure;
2914  }
2915  F.InputFilesOffsetBase = F.InputFilesCursor.GetCurrentBitNo();
2916  continue;
2917 
2918  case OPTIONS_BLOCK_ID:
2919  // If we're reading the first module for this group, check its options
2920  // are compatible with ours. For modules it imports, no further checking
2921  // is required, because we checked them when we built it.
2922  if (Listener && !ImportedBy) {
2923  // Should we allow the configuration of the module file to differ from
2924  // the configuration of the current translation unit in a compatible
2925  // way?
2926  //
2927  // FIXME: Allow this for files explicitly specified with -include-pch.
2928  bool AllowCompatibleConfigurationMismatch =
2930 
2931  ASTReadResult Result =
2932  ReadOptionsBlock(Stream, ClientLoadCapabilities,
2933  AllowCompatibleConfigurationMismatch, *Listener,
2934  SuggestedPredefines);
2935  if (Result == Failure) {
2936  Error("malformed block record in AST file");
2937  return Result;
2938  }
2939 
2940  if (DisableValidation ||
2941  (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2942  Result = Success;
2943 
2944  // If we can't load the module, exit early since we likely
2945  // will rebuild the module anyway. The stream may be in the
2946  // middle of a block.
2947  if (Result != Success)
2948  return Result;
2949  } else if (llvm::Error Err = Stream.SkipBlock()) {
2950  Error(std::move(Err));
2951  return Failure;
2952  }
2953  continue;
2954 
2955  default:
2956  if (llvm::Error Err = Stream.SkipBlock()) {
2957  Error(std::move(Err));
2958  return Failure;
2959  }
2960  continue;
2961  }
2962 
2964  // The interesting case.
2965  break;
2966  }
2967 
2968  // Read and process a record.
2969  Record.clear();
2970  StringRef Blob;
2971  Expected<unsigned> MaybeRecordType =
2972  Stream.readRecord(Entry.ID, Record, &Blob);
2973  if (!MaybeRecordType) {
2974  Error(MaybeRecordType.takeError());
2975  return Failure;
2976  }
2977  switch ((ControlRecordTypes)MaybeRecordType.get()) {
2978  case METADATA: {
2979  if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2980  if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2981  Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2982  : diag::err_pch_version_too_new);
2983  return VersionMismatch;
2984  }
2985 
2986  bool hasErrors = Record[7];
2987  if (hasErrors && !DisableValidation) {
2988  // If requested by the caller and the module hasn't already been read
2989  // or compiled, mark modules on error as out-of-date.
2990  if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
2991  canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
2992  return OutOfDate;
2993 
2994  if (!AllowASTWithCompilerErrors) {
2995  Diag(diag::err_pch_with_compiler_errors);
2996  return HadErrors;
2997  }
2998  }
2999  if (hasErrors) {
3000  Diags.ErrorOccurred = true;
3001  Diags.UncompilableErrorOccurred = true;
3002  Diags.UnrecoverableErrorOccurred = true;
3003  }
3004 
3005  F.RelocatablePCH = Record[4];
3006  // Relative paths in a relocatable PCH are relative to our sysroot.
3007  if (F.RelocatablePCH)
3008  F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
3009 
3010  F.StandardCXXModule = Record[5];
3011 
3012  F.HasTimestamps = Record[6];
3013 
3014  const std::string &CurBranch = getClangFullRepositoryVersion();
3015  StringRef ASTBranch = Blob;
3016  if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
3017  if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3018  Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
3019  return VersionMismatch;
3020  }
3021  break;
3022  }
3023 
3024  case IMPORTS: {
3025  // Validate the AST before processing any imports (otherwise, untangling
3026  // them can be error-prone and expensive). A module will have a name and
3027  // will already have been validated, but this catches the PCH case.
3028  if (ASTReadResult Result = readUnhashedControlBlockOnce())
3029  return Result;
3030 
3031  // Load each of the imported PCH files.
3032  unsigned Idx = 0, N = Record.size();
3033  while (Idx < N) {
3034  // Read information about the AST file.
3035  ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
3036  // Whether we're importing a standard c++ module.
3037  bool IsImportingStdCXXModule = Record[Idx++];
3038  // The import location will be the local one for now; we will adjust
3039  // all import locations of module imports after the global source
3040  // location info are setup, in ReadAST.
3041  auto [ImportLoc, ImportModuleFileIndex] =
3042  ReadUntranslatedSourceLocation(Record[Idx++]);
3043  // The import location must belong to the current module file itself.
3044  assert(ImportModuleFileIndex == 0);
3045  off_t StoredSize = !IsImportingStdCXXModule ? (off_t)Record[Idx++] : 0;
3046  time_t StoredModTime =
3047  !IsImportingStdCXXModule ? (time_t)Record[Idx++] : 0;
3048 
3049  ASTFileSignature StoredSignature;
3050  if (!IsImportingStdCXXModule) {
3051  auto FirstSignatureByte = Record.begin() + Idx;
3052  StoredSignature = ASTFileSignature::create(
3053  FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);
3054  Idx += ASTFileSignature::size;
3055  }
3056 
3057  std::string ImportedName = ReadString(Record, Idx);
3058  std::string ImportedFile;
3059 
3060  // For prebuilt and explicit modules first consult the file map for
3061  // an override. Note that here we don't search prebuilt module
3062  // directories if we're not importing standard c++ module, only the
3063  // explicit name to file mappings. Also, we will still verify the
3064  // size/signature making sure it is essentially the same file but
3065  // perhaps in a different location.
3066  if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
3067  ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
3068  ImportedName, /*FileMapOnly*/ !IsImportingStdCXXModule);
3069 
3070  // For C++20 Modules, we won't record the path to the imported modules
3071  // in the BMI
3072  if (!IsImportingStdCXXModule) {
3073  if (ImportedFile.empty()) {
3074  // Use BaseDirectoryAsWritten to ensure we use the same path in the
3075  // ModuleCache as when writing.
3076  ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
3077  } else
3078  SkipPath(Record, Idx);
3079  } else if (ImportedFile.empty()) {
3080  Diag(clang::diag::err_failed_to_find_module_file) << ImportedName;
3081  return Missing;
3082  }
3083 
3084  // If our client can't cope with us being out of date, we can't cope with
3085  // our dependency being missing.
3086  unsigned Capabilities = ClientLoadCapabilities;
3087  if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3088  Capabilities &= ~ARR_Missing;
3089 
3090  // Load the AST file.
3091  auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
3092  Loaded, StoredSize, StoredModTime,
3093  StoredSignature, Capabilities);
3094 
3095  // If we diagnosed a problem, produce a backtrace.
3096  bool recompilingFinalized =
3097  Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&
3098  getModuleManager().getModuleCache().isPCMFinal(F.FileName);
3099  if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized)
3100  Diag(diag::note_module_file_imported_by)
3101  << F.FileName << !F.ModuleName.empty() << F.ModuleName;
3102  if (recompilingFinalized)
3103  Diag(diag::note_module_file_conflict);
3104 
3105  switch (Result) {
3106  case Failure: return Failure;
3107  // If we have to ignore the dependency, we'll have to ignore this too.
3108  case Missing:
3109  case OutOfDate: return OutOfDate;
3110  case VersionMismatch: return VersionMismatch;
3111  case ConfigurationMismatch: return ConfigurationMismatch;
3112  case HadErrors: return HadErrors;
3113  case Success: break;
3114  }
3115  }
3116  break;
3117  }
3118 
3119  case ORIGINAL_FILE:
3120  F.OriginalSourceFileID = FileID::get(Record[0]);
3121  F.ActualOriginalSourceFileName = std::string(Blob);
3123  ResolveImportedPath(F, F.OriginalSourceFileName);
3124  break;
3125 
3126  case ORIGINAL_FILE_ID:
3127  F.OriginalSourceFileID = FileID::get(Record[0]);
3128  break;
3129 
3130  case MODULE_NAME:
3131  F.ModuleName = std::string(Blob);
3132  Diag(diag::remark_module_import)
3133  << F.ModuleName << F.FileName << (ImportedBy ? true : false)
3134  << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
3135  if (Listener)
3136  Listener->ReadModuleName(F.ModuleName);
3137 
3138  // Validate the AST as soon as we have a name so we can exit early on
3139  // failure.
3140  if (ASTReadResult Result = readUnhashedControlBlockOnce())
3141  return Result;
3142 
3143  break;
3144 
3145  case MODULE_DIRECTORY: {
3146  // Save the BaseDirectory as written in the PCM for computing the module
3147  // filename for the ModuleCache.
3148  BaseDirectoryAsWritten = Blob;
3149  assert(!F.ModuleName.empty() &&
3150  "MODULE_DIRECTORY found before MODULE_NAME");
3151  F.BaseDirectory = std::string(Blob);
3152  if (!PP.getPreprocessorOpts().ModulesCheckRelocated)
3153  break;
3154  // If we've already loaded a module map file covering this module, we may
3155  // have a better path for it (relative to the current build).
3156  Module *M = PP.getHeaderSearchInfo().lookupModule(
3157  F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
3158  /*AllowExtraModuleMapSearch*/ true);
3159  if (M && M->Directory) {
3160  // If we're implicitly loading a module, the base directory can't
3161  // change between the build and use.
3162  // Don't emit module relocation error if we have -fno-validate-pch
3163  if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3166  auto BuildDir = PP.getFileManager().getOptionalDirectoryRef(Blob);
3167  if (!BuildDir || *BuildDir != M->Directory) {
3168  if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
3169  Diag(diag::err_imported_module_relocated)
3170  << F.ModuleName << Blob << M->Directory->getName();
3171  return OutOfDate;
3172  }
3173  }
3174  F.BaseDirectory = std::string(M->Directory->getName());
3175  }
3176  break;
3177  }
3178 
3179  case MODULE_MAP_FILE:
3180  if (ASTReadResult Result =
3181  ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
3182  return Result;
3183  break;
3184 
3185  case INPUT_FILE_OFFSETS:
3186  NumInputs = Record[0];
3187  NumUserInputs = Record[1];
3188  F.InputFileOffsets =
3189  (const llvm::support::unaligned_uint64_t *)Blob.data();
3190  F.InputFilesLoaded.resize(NumInputs);
3191  F.InputFileInfosLoaded.resize(NumInputs);
3192  F.NumUserInputFiles = NumUserInputs;
3193  break;
3194  }
3195  }
3196 }
3197 
3198 llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3199  unsigned ClientLoadCapabilities) {
3200  BitstreamCursor &Stream = F.Stream;
3201 
3202  if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3203  return Err;
3204  F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
3205 
3206  // Read all of the records and blocks for the AST file.
3207  RecordData Record;
3208  while (true) {
3209  Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3210  if (!MaybeEntry)
3211  return MaybeEntry.takeError();
3212  llvm::BitstreamEntry Entry = MaybeEntry.get();
3213 
3214  switch (Entry.Kind) {
3216  return llvm::createStringError(
3217  std::errc::illegal_byte_sequence,
3218  "error at end of module block in AST file");
3219  case llvm::BitstreamEntry::EndBlock:
3220  // Outside of C++, we do not store a lookup map for the translation unit.
3221  // Instead, mark it as needing a lookup map to be built if this module
3222  // contains any declarations lexically within it (which it always does!).
3223  // This usually has no cost, since we very rarely need the lookup map for
3224  // the translation unit outside C++.
3225  if (ASTContext *Ctx = ContextObj) {
3226  DeclContext *DC = Ctx->getTranslationUnitDecl();
3227  if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
3229  }
3230 
3231  return llvm::Error::success();
3232  case llvm::BitstreamEntry::SubBlock:
3233  switch (Entry.ID) {
3234  case DECLTYPES_BLOCK_ID:
3235  // We lazily load the decls block, but we want to set up the
3236  // DeclsCursor cursor to point into it. Clone our current bitcode
3237  // cursor to it, enter the block and read the abbrevs in that block.
3238  // With the main cursor, we just skip over it.
3239  F.DeclsCursor = Stream;
3240  if (llvm::Error Err = Stream.SkipBlock())
3241  return Err;
3242  if (llvm::Error Err = ReadBlockAbbrevs(
3244  return Err;
3245  break;
3246 
3247  case PREPROCESSOR_BLOCK_ID:
3248  F.MacroCursor = Stream;
3249  if (!PP.getExternalSource())
3250  PP.setExternalSource(this);
3251 
3252  if (llvm::Error Err = Stream.SkipBlock())
3253  return Err;
3254  if (llvm::Error Err =
3255  ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3256  return Err;
3257  F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
3258  break;
3259 
3261  F.PreprocessorDetailCursor = Stream;
3262 
3263  if (llvm::Error Err = Stream.SkipBlock()) {
3264  return Err;
3265  }
3266  if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3268  return Err;
3270  = F.PreprocessorDetailCursor.GetCurrentBitNo();
3271 
3272  if (!PP.getPreprocessingRecord())
3273  PP.createPreprocessingRecord();
3274  if (!PP.getPreprocessingRecord()->getExternalSource())
3275  PP.getPreprocessingRecord()->SetExternalSource(*this);
3276  break;
3277 
3279  if (llvm::Error Err = ReadSourceManagerBlock(F))
3280  return Err;
3281  break;
3282 
3283  case SUBMODULE_BLOCK_ID:
3284  if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3285  return Err;
3286  break;
3287 
3288  case COMMENTS_BLOCK_ID: {
3289  BitstreamCursor C = Stream;
3290 
3291  if (llvm::Error Err = Stream.SkipBlock())
3292  return Err;
3293  if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3294  return Err;
3295  CommentsCursors.push_back(std::make_pair(C, &F));
3296  break;
3297  }
3298 
3299  default:
3300  if (llvm::Error Err = Stream.SkipBlock())
3301  return Err;
3302  break;
3303  }
3304  continue;
3305 
3307  // The interesting case.
3308  break;
3309  }
3310 
3311  // Read and process a record.
3312  Record.clear();
3313  StringRef Blob;
3314  Expected<unsigned> MaybeRecordType =
3315  Stream.readRecord(Entry.ID, Record, &Blob);
3316  if (!MaybeRecordType)
3317  return MaybeRecordType.takeError();
3318  ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3319 
3320  // If we're not loading an AST context, we don't care about most records.
3321  if (!ContextObj) {
3322  switch (RecordType) {
3323  case IDENTIFIER_TABLE:
3324  case IDENTIFIER_OFFSET:
3326  case STATISTICS:
3327  case PP_ASSUME_NONNULL_LOC:
3328  case PP_CONDITIONAL_STACK:
3329  case PP_COUNTER_VALUE:
3331  case MODULE_OFFSET_MAP:
3333  case PPD_ENTITIES_OFFSETS:
3334  case HEADER_SEARCH_TABLE:
3335  case IMPORTED_MODULES:
3336  case MACRO_OFFSET:
3337  break;
3338  default:
3339  continue;
3340  }
3341  }
3342 
3343  switch (RecordType) {
3344  default: // Default behavior: ignore.
3345  break;
3346 
3347  case TYPE_OFFSET: {
3348  if (F.LocalNumTypes != 0)
3349  return llvm::createStringError(
3350  std::errc::illegal_byte_sequence,
3351  "duplicate TYPE_OFFSET record in AST file");
3352  F.TypeOffsets = reinterpret_cast<const UnalignedUInt64 *>(Blob.data());
3353  F.LocalNumTypes = Record[0];
3354  unsigned LocalBaseTypeIndex = Record[1];
3355  F.BaseTypeIndex = getTotalNumTypes();
3356 
3357  if (F.LocalNumTypes > 0) {
3358  // Introduce the global -> local mapping for types within this module.
3359  GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
3360 
3361  // Introduce the local -> global mapping for types within this module.
3363  std::make_pair(LocalBaseTypeIndex,
3364  F.BaseTypeIndex - LocalBaseTypeIndex));
3365 
3366  TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3367  }
3368  break;
3369  }
3370 
3371  case DECL_OFFSET: {
3372  if (F.LocalNumDecls != 0)
3373  return llvm::createStringError(
3374  std::errc::illegal_byte_sequence,
3375  "duplicate DECL_OFFSET record in AST file");
3376  F.DeclOffsets = (const DeclOffset *)Blob.data();
3377  F.LocalNumDecls = Record[0];
3378  unsigned LocalBaseDeclID = Record[1];
3379  F.BaseDeclID = getTotalNumDecls();
3380 
3381  if (F.LocalNumDecls > 0) {
3382  // Introduce the global -> local mapping for declarations within this
3383  // module.
3384  GlobalDeclMap.insert(std::make_pair(
3385  GlobalDeclID(getTotalNumDecls() + NUM_PREDEF_DECL_IDS), &F));
3386 
3387  // Introduce the local -> global mapping for declarations within this
3388  // module.
3390  std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
3391 
3392  // Introduce the global -> local mapping for declarations within this
3393  // module.
3394  F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
3395 
3396  DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3397  }
3398  break;
3399  }
3400 
3401  case TU_UPDATE_LEXICAL: {
3402  DeclContext *TU = ContextObj->getTranslationUnitDecl();
3403  LexicalContents Contents(
3404  reinterpret_cast<const unaligned_decl_id_t *>(Blob.data()),
3405  static_cast<unsigned int>(Blob.size() / sizeof(DeclID)));
3406  TULexicalDecls.push_back(std::make_pair(&F, Contents));
3407  TU->setHasExternalLexicalStorage(true);
3408  break;
3409  }
3410 
3411  case UPDATE_VISIBLE: {
3412  unsigned Idx = 0;
3413  GlobalDeclID ID = ReadDeclID(F, Record, Idx);
3414  auto *Data = (const unsigned char*)Blob.data();
3415  PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
3416  // If we've already loaded the decl, perform the updates when we finish
3417  // loading this block.
3418  if (Decl *D = GetExistingDecl(ID))
3419  PendingUpdateRecords.push_back(
3420  PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3421  break;
3422  }
3423 
3424  case IDENTIFIER_TABLE:
3426  reinterpret_cast<const unsigned char *>(Blob.data());
3427  if (Record[0]) {
3428  F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3429  F.IdentifierTableData + Record[0],
3430  F.IdentifierTableData + sizeof(uint32_t),
3432  ASTIdentifierLookupTrait(*this, F));
3433 
3434  PP.getIdentifierTable().setExternalIdentifierLookup(this);
3435  }
3436  break;
3437 
3438  case IDENTIFIER_OFFSET: {
3439  if (F.LocalNumIdentifiers != 0)
3440  return llvm::createStringError(
3441  std::errc::illegal_byte_sequence,
3442  "duplicate IDENTIFIER_OFFSET record in AST file");
3443  F.IdentifierOffsets = (const uint32_t *)Blob.data();
3444  F.LocalNumIdentifiers = Record[0];
3445  unsigned LocalBaseIdentifierID = Record[1];
3446  F.BaseIdentifierID = getTotalNumIdentifiers();
3447 
3448  if (F.LocalNumIdentifiers > 0) {
3449  // Introduce the global -> local mapping for identifiers within this
3450  // module.
3451  GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
3452  &F));
3453 
3454  // Introduce the local -> global mapping for identifiers within this
3455  // module.
3457  std::make_pair(LocalBaseIdentifierID,
3458  F.BaseIdentifierID - LocalBaseIdentifierID));
3459 
3460  IdentifiersLoaded.resize(IdentifiersLoaded.size()
3461  + F.LocalNumIdentifiers);
3462  }
3463  break;
3464  }
3465 
3467  F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3468  break;
3469 
3471  // FIXME: Skip reading this record if our ASTConsumer doesn't care
3472  // about "interesting" decls (for instance, if we're building a module).
3473  for (unsigned I = 0, N = Record.size(); I != N; ++I)
3474  EagerlyDeserializedDecls.push_back(
3475  getGlobalDeclID(F, LocalDeclID(Record[I])));
3476  break;
3477 
3478  case MODULAR_CODEGEN_DECLS:
3479  // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3480  // them (ie: if we're not codegenerating this module).
3481  if (F.Kind == MK_MainFile ||
3482  getContext().getLangOpts().BuildingPCHWithObjectFile)
3483  for (unsigned I = 0, N = Record.size(); I != N; ++I)
3484  EagerlyDeserializedDecls.push_back(
3485  getGlobalDeclID(F, LocalDeclID(Record[I])));
3486  break;
3487 
3488  case SPECIAL_TYPES:
3489  if (SpecialTypes.empty()) {
3490  for (unsigned I = 0, N = Record.size(); I != N; ++I)
3491  SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3492  break;
3493  }
3494 
3495  if (SpecialTypes.size() != Record.size())
3496  return llvm::createStringError(std::errc::illegal_byte_sequence,
3497  "invalid special-types record");
3498 
3499  for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3500  serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3501  if (!SpecialTypes[I])
3502  SpecialTypes[I] = ID;
3503  // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3504  // merge step?
3505  }
3506  break;
3507 
3508  case STATISTICS:
3509  TotalNumStatements += Record[0];
3510  TotalNumMacros += Record[1];
3511  TotalLexicalDeclContexts += Record[2];
3512  TotalVisibleDeclContexts += Record[3];
3513  break;
3514 
3516  for (unsigned I = 0, N = Record.size(); I != N; ++I)
3517  UnusedFileScopedDecls.push_back(
3518  getGlobalDeclID(F, LocalDeclID(Record[I])));
3519  break;
3520 
3521  case DELEGATING_CTORS:
3522  for (unsigned I = 0, N = Record.size(); I != N; ++I)
3523  DelegatingCtorDecls.push_back(
3524  getGlobalDeclID(F, LocalDeclID(Record[I])));
3525  break;
3526 
3528  if (Record.size() % 3 != 0)
3529  return llvm::createStringError(std::errc::illegal_byte_sequence,
3530  "invalid weak identifiers record");
3531 
3532  // FIXME: Ignore weak undeclared identifiers from non-original PCH
3533  // files. This isn't the way to do it :)
3534  WeakUndeclaredIdentifiers.clear();
3535 
3536  // Translate the weak, undeclared identifiers into global IDs.
3537  for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3538  WeakUndeclaredIdentifiers.push_back(
3539  getGlobalIdentifierID(F, Record[I++]));
3540  WeakUndeclaredIdentifiers.push_back(
3541  getGlobalIdentifierID(F, Record[I++]));
3542  WeakUndeclaredIdentifiers.push_back(
3543  ReadSourceLocation(F, Record, I).getRawEncoding());
3544  }
3545  break;
3546 
3547  case SELECTOR_OFFSETS: {
3548  F.SelectorOffsets = (const uint32_t *)Blob.data();
3549  F.LocalNumSelectors = Record[0];
3550  unsigned LocalBaseSelectorID = Record[1];
3551  F.BaseSelectorID = getTotalNumSelectors();
3552 
3553  if (F.LocalNumSelectors > 0) {
3554  // Introduce the global -> local mapping for selectors within this
3555  // module.
3556  GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3557 
3558  // Introduce the local -> global mapping for selectors within this
3559  // module.
3561  std::make_pair(LocalBaseSelectorID,
3562  F.BaseSelectorID - LocalBaseSelectorID));
3563 
3564  SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3565  }
3566  break;
3567  }
3568 
3569  case METHOD_POOL:
3570  F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3571  if (Record[0])
3573  = ASTSelectorLookupTable::Create(
3576  ASTSelectorLookupTrait(*this, F));
3577  TotalNumMethodPoolEntries += Record[1];
3578  break;
3579 
3581  if (!Record.empty()) {
3582  for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3583  ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3584  Record[Idx++]));
3585  ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3586  getRawEncoding());
3587  }
3588  }
3589  break;
3590 
3591  case PP_ASSUME_NONNULL_LOC: {
3592  unsigned Idx = 0;
3593  if (!Record.empty())
3594  PP.setPreambleRecordedPragmaAssumeNonNullLoc(
3595  ReadSourceLocation(F, Record, Idx));
3596  break;
3597  }
3598 
3599  case PP_CONDITIONAL_STACK:
3600  if (!Record.empty()) {
3601  unsigned Idx = 0, End = Record.size() - 1;
3602  bool ReachedEOFWhileSkipping = Record[Idx++];
3603  std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3604  if (ReachedEOFWhileSkipping) {
3605  SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3606  SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3607  bool FoundNonSkipPortion = Record[Idx++];
3608  bool FoundElse = Record[Idx++];
3609  SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3610  SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3611  FoundElse, ElseLoc);
3612  }
3613  SmallVector<PPConditionalInfo, 4> ConditionalStack;
3614  while (Idx < End) {
3615  auto Loc = ReadSourceLocation(F, Record, Idx);
3616  bool WasSkipping = Record[Idx++];
3617  bool FoundNonSkip = Record[Idx++];
3618  bool FoundElse = Record[Idx++];
3619  ConditionalStack.push_back(
3620  {Loc, WasSkipping, FoundNonSkip, FoundElse});
3621  }
3622  PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
3623  }
3624  break;
3625 
3626  case PP_COUNTER_VALUE:
3627  if (!Record.empty() && Listener)
3628  Listener->ReadCounter(F, Record[0]);
3629  break;
3630 
3631  case FILE_SORTED_DECLS:
3632  F.FileSortedDecls = (const LocalDeclID *)Blob.data();
3633  F.NumFileSortedDecls = Record[0];
3634  break;
3635 
3636  case SOURCE_LOCATION_OFFSETS: {
3637  F.SLocEntryOffsets = (const uint32_t *)Blob.data();
3638  F.LocalNumSLocEntries = Record[0];
3639  SourceLocation::UIntTy SLocSpaceSize = Record[1];
3641  std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
3642  SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
3643  SLocSpaceSize);
3644  if (!F.SLocEntryBaseID) {
3645  if (!Diags.isDiagnosticInFlight()) {
3646  Diags.Report(SourceLocation(), diag::remark_sloc_usage);
3647  SourceMgr.noteSLocAddressSpaceUsage(Diags);
3648  }
3649  return llvm::createStringError(std::errc::invalid_argument,
3650  "ran out of source locations");
3651  }
3652  // Make our entry in the range map. BaseID is negative and growing, so
3653  // we invert it. Because we invert it, though, we need the other end of
3654  // the range.
3655  unsigned RangeStart =
3657  GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3659 
3660  // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3661  assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
3662  GlobalSLocOffsetMap.insert(
3663  std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3664  - SLocSpaceSize,&F));
3665 
3666  TotalNumSLocEntries += F.LocalNumSLocEntries;
3667  break;
3668  }
3669 
3670  case MODULE_OFFSET_MAP:
3671  F.ModuleOffsetMap = Blob;
3672  break;
3673 
3675  ParseLineTable(F, Record);
3676  break;
3677 
3678  case EXT_VECTOR_DECLS:
3679  for (unsigned I = 0, N = Record.size(); I != N; ++I)
3680  ExtVectorDecls.push_back(getGlobalDeclID(F, LocalDeclID(Record[I])));
3681  break;
3682 
3683  case VTABLE_USES:
3684  if (Record.size() % 3 != 0)
3685  return llvm::createStringError(std::errc::illegal_byte_sequence,
3686  "Invalid VTABLE_USES record");
3687 
3688  // Later tables overwrite earlier ones.
3689  // FIXME: Modules will have some trouble with this. This is clearly not
3690  // the right way to do this.
3691  VTableUses.clear();
3692 
3693  for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3694  VTableUses.push_back(
3695  {getGlobalDeclID(F, LocalDeclID(Record[Idx++])),
3696  ReadSourceLocation(F, Record, Idx).getRawEncoding(),
3697  (bool)Record[Idx++]});
3698  }
3699  break;
3700 
3702 
3703  if (Record.size() % 2 != 0)
3704  return llvm::createStringError(
3705  std::errc::illegal_byte_sequence,
3706  "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3707 
3708  for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3709  PendingInstantiations.push_back(
3710  {getGlobalDeclID(F, LocalDeclID(Record[I++])),
3711  ReadSourceLocation(F, Record, I).getRawEncoding()});
3712  }
3713  break;
3714 
3715  case SEMA_DECL_REFS:
3716  if (Record.size() != 3)
3717  return llvm::createStringError(std::errc::illegal_byte_sequence,
3718  "Invalid SEMA_DECL_REFS block");
3719  for (unsigned I = 0, N = Record.size(); I != N; ++I)
3720  SemaDeclRefs.push_back(getGlobalDeclID(F, LocalDeclID(Record[I])));
3721  break;
3722 
3723  case PPD_ENTITIES_OFFSETS: {
3724  F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3725  assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3726  F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3727 
3728  unsigned LocalBasePreprocessedEntityID = Record[0];
3729 
3730  unsigned StartingID;
3731  if (!PP.getPreprocessingRecord())
3732  PP.createPreprocessingRecord();
3733  if (!PP.getPreprocessingRecord()->getExternalSource())
3734  PP.getPreprocessingRecord()->SetExternalSource(*this);
3735  StartingID
3736  = PP.getPreprocessingRecord()
3737  ->allocateLoadedEntities(F.NumPreprocessedEntities);
3738  F.BasePreprocessedEntityID = StartingID;
3739 
3740  if (F.NumPreprocessedEntities > 0) {
3741  // Introduce the global -> local mapping for preprocessed entities in
3742  // this module.
3743  GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3744 
3745  // Introduce the local -> global mapping for preprocessed entities in
3746  // this module.
3748  std::make_pair(LocalBasePreprocessedEntityID,
3749  F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3750  }
3751 
3752  break;
3753  }
3754 
3755  case PPD_SKIPPED_RANGES: {
3756  F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3757  assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3758  F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3759 
3760  if (!PP.getPreprocessingRecord())
3761  PP.createPreprocessingRecord();
3762  if (!PP.getPreprocessingRecord()->getExternalSource())
3763  PP.getPreprocessingRecord()->SetExternalSource(*this);
3764  F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3765  ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
3766 
3767  if (F.NumPreprocessedSkippedRanges > 0)
3768  GlobalSkippedRangeMap.insert(
3769  std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3770  break;
3771  }
3772 
3773  case DECL_UPDATE_OFFSETS:
3774  if (Record.size() % 2 != 0)
3775  return llvm::createStringError(
3776  std::errc::illegal_byte_sequence,
3777  "invalid DECL_UPDATE_OFFSETS block in AST file");
3778  for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3779  GlobalDeclID ID = getGlobalDeclID(F, LocalDeclID(Record[I]));
3780  DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3781 
3782  // If we've already loaded the decl, perform the updates when we finish
3783  // loading this block.
3784  if (Decl *D = GetExistingDecl(ID))
3785  PendingUpdateRecords.push_back(
3786  PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3787  }
3788  break;
3789 
3791  if (Record.size() % 3 != 0)
3792  return llvm::createStringError(
3793  std::errc::illegal_byte_sequence,
3794  "invalid DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD block in AST "
3795  "file");
3796  for (unsigned I = 0, N = Record.size(); I != N; I += 3) {
3797  GlobalDeclID ID = getGlobalDeclID(F, LocalDeclID(Record[I]));
3798 
3799  uint64_t BaseOffset = F.DeclsBlockStartOffset;
3800  assert(BaseOffset && "Invalid DeclsBlockStartOffset for module file!");
3801  uint64_t LexicalOffset = Record[I + 1] ? BaseOffset + Record[I + 1] : 0;
3802  uint64_t VisibleOffset = Record[I + 2] ? BaseOffset + Record[I + 2] : 0;
3803 
3804  DelayedNamespaceOffsetMap[ID] = {LexicalOffset, VisibleOffset};
3805 
3806  assert(!GetExistingDecl(ID) &&
3807  "We shouldn't load the namespace in the front of delayed "
3808  "namespace lexical and visible block");
3809  }
3810  break;
3811  }
3812 
3813  case OBJC_CATEGORIES_MAP:
3814  if (F.LocalNumObjCCategoriesInMap != 0)
3815  return llvm::createStringError(
3816  std::errc::illegal_byte_sequence,
3817  "duplicate OBJC_CATEGORIES_MAP record in AST file");
3818 
3820  F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3821  break;
3822 
3823  case OBJC_CATEGORIES:
3824  F.ObjCCategories.swap(Record);
3825  break;
3826 
3828  // Later tables overwrite earlier ones.
3829  // FIXME: Modules will have trouble with this.
3830  CUDASpecialDeclRefs.clear();
3831  for (unsigned I = 0, N = Record.size(); I != N; ++I)
3832  CUDASpecialDeclRefs.push_back(
3833  getGlobalDeclID(F, LocalDeclID(Record[I])));
3834  break;
3835 
3836  case HEADER_SEARCH_TABLE:
3837  F.HeaderFileInfoTableData = Blob.data();
3839  if (Record[0]) {
3841  = HeaderFileInfoLookupTable::Create(
3842  (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3843  (const unsigned char *)F.HeaderFileInfoTableData,
3844  HeaderFileInfoTrait(*this, F,
3845  &PP.getHeaderSearchInfo(),
3846  Blob.data() + Record[2]));
3847 
3848  PP.getHeaderSearchInfo().SetExternalSource(this);
3849  if (!PP.getHeaderSearchInfo().getExternalLookup())
3850  PP.getHeaderSearchInfo().SetExternalLookup(this);
3851  }
3852  break;
3853 
3854  case FP_PRAGMA_OPTIONS:
3855  // Later tables overwrite earlier ones.
3856  FPPragmaOptions.swap(Record);
3857  break;
3858 
3859  case OPENCL_EXTENSIONS:
3860  for (unsigned I = 0, E = Record.size(); I != E; ) {
3861  auto Name = ReadString(Record, I);
3862  auto &OptInfo = OpenCLExtensions.OptMap[Name];
3863  OptInfo.Supported = Record[I++] != 0;
3864  OptInfo.Enabled = Record[I++] != 0;
3865  OptInfo.WithPragma = Record[I++] != 0;
3866  OptInfo.Avail = Record[I++];
3867  OptInfo.Core = Record[I++];
3868  OptInfo.Opt = Record[I++];
3869  }
3870  break;
3871 
3872  case TENTATIVE_DEFINITIONS:
3873  for (unsigned I = 0, N = Record.size(); I != N; ++I)
3874  TentativeDefinitions.push_back(
3875  getGlobalDeclID(F, LocalDeclID(Record[I])));
3876  break;
3877 
3878  case KNOWN_NAMESPACES:
3879  for (unsigned I = 0, N = Record.size(); I != N; ++I)
3880  KnownNamespaces.push_back(getGlobalDeclID(F, LocalDeclID(Record[I])));
3881  break;
3882 
3883  case UNDEFINED_BUT_USED:
3884  if (Record.size() % 2 != 0)
3885  return llvm::createStringError(std::errc::illegal_byte_sequence,
3886  "invalid undefined-but-used record");
3887  for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3888  UndefinedButUsed.push_back(
3889  {getGlobalDeclID(F, LocalDeclID(Record[I++])),
3890  ReadSourceLocation(F, Record, I).getRawEncoding()});
3891  }
3892  break;
3893 
3895  for (unsigned I = 0, N = Record.size(); I != N;) {
3896  DelayedDeleteExprs.push_back(
3897  getGlobalDeclID(F, LocalDeclID(Record[I++])).get());
3898  const uint64_t Count = Record[I++];
3899  DelayedDeleteExprs.push_back(Count);
3900  for (uint64_t C = 0; C < Count; ++C) {
3901  DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3902  bool IsArrayForm = Record[I++] == 1;
3903  DelayedDeleteExprs.push_back(IsArrayForm);
3904  }
3905  }
3906  break;
3907 
3908  case IMPORTED_MODULES:
3909  if (!F.isModule()) {
3910  // If we aren't loading a module (which has its own exports), make
3911  // all of the imported modules visible.
3912  // FIXME: Deal with macros-only imports.
3913  for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3914  unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3915  SourceLocation Loc = ReadSourceLocation(F, Record, I);
3916  if (GlobalID) {
3917  PendingImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3918  if (DeserializationListener)
3919  DeserializationListener->ModuleImportRead(GlobalID, Loc);
3920  }
3921  }
3922  }
3923  break;
3924 
3925  case MACRO_OFFSET: {
3926  if (F.LocalNumMacros != 0)
3927  return llvm::createStringError(
3928  std::errc::illegal_byte_sequence,
3929  "duplicate MACRO_OFFSET record in AST file");
3930  F.MacroOffsets = (const uint32_t *)Blob.data();
3931  F.LocalNumMacros = Record[0];
3932  unsigned LocalBaseMacroID = Record[1];
3934  F.BaseMacroID = getTotalNumMacros();
3935 
3936  if (F.LocalNumMacros > 0) {
3937  // Introduce the global -> local mapping for macros within this module.
3938  GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3939 
3940  // Introduce the local -> global mapping for macros within this module.
3942  std::make_pair(LocalBaseMacroID,
3943  F.BaseMacroID - LocalBaseMacroID));
3944 
3945  MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3946  }
3947  break;
3948  }
3949 
3950  case LATE_PARSED_TEMPLATE:
3951  LateParsedTemplates.emplace_back(
3952  std::piecewise_construct, std::forward_as_tuple(&F),
3953  std::forward_as_tuple(Record.begin(), Record.end()));
3954  break;
3955 
3957  if (Record.size() != 1)
3958  return llvm::createStringError(std::errc::illegal_byte_sequence,
3959  "invalid pragma optimize record");
3960  OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3961  break;
3962 
3964  if (Record.size() != 1)
3965  return llvm::createStringError(std::errc::illegal_byte_sequence,
3966  "invalid pragma ms_struct record");
3967  PragmaMSStructState = Record[0];
3968  break;
3969 
3971  if (Record.size() != 2)
3972  return llvm::createStringError(
3973  std::errc::illegal_byte_sequence,
3974  "invalid pragma pointers to members record");
3975  PragmaMSPointersToMembersState = Record[0];
3976  PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3977  break;
3978 
3980  for (unsigned I = 0, N = Record.size(); I != N; ++I)
3981  UnusedLocalTypedefNameCandidates.push_back(
3982  getGlobalDeclID(F, LocalDeclID(Record[I])));
3983  break;
3984 
3986  if (Record.size() != 1)
3987  return llvm::createStringError(std::errc::illegal_byte_sequence,
3988  "invalid cuda pragma options record");
3989  ForceHostDeviceDepth = Record[0];
3990  break;
3991 
3993  if (Record.size() < 3)
3994  return llvm::createStringError(std::errc::illegal_byte_sequence,
3995  "invalid pragma pack record");
3996  PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
3997  PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3998  unsigned NumStackEntries = Record[2];
3999  unsigned Idx = 3;
4000  // Reset the stack when importing a new module.
4001  PragmaAlignPackStack.clear();
4002  for (unsigned I = 0; I < NumStackEntries; ++I) {
4003  PragmaAlignPackStackEntry Entry;
4004  Entry.Value = ReadAlignPackInfo(Record[Idx++]);
4005  Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4006  Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4007  PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
4008  Entry.SlotLabel = PragmaAlignPackStrings.back();
4009  PragmaAlignPackStack.push_back(Entry);
4010  }
4011  break;
4012  }
4013 
4015  if (Record.size() < 3)
4016  return llvm::createStringError(std::errc::illegal_byte_sequence,
4017  "invalid pragma float control record");
4018  FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
4019  FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
4020  unsigned NumStackEntries = Record[2];
4021  unsigned Idx = 3;
4022  // Reset the stack when importing a new module.
4023  FpPragmaStack.clear();
4024  for (unsigned I = 0; I < NumStackEntries; ++I) {
4025  FpPragmaStackEntry Entry;
4026  Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
4027  Entry.Location = ReadSourceLocation(F, Record[Idx++]);
4028  Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
4029  FpPragmaStrings.push_back(ReadString(Record, Idx));
4030  Entry.SlotLabel = FpPragmaStrings.back();
4031  FpPragmaStack.push_back(Entry);
4032  }
4033  break;
4034  }
4035 
4037  for (unsigned I = 0, N = Record.size(); I != N; ++I)
4038  DeclsToCheckForDeferredDiags.insert(
4039  getGlobalDeclID(F, LocalDeclID(Record[I])));
4040  break;
4041  }
4042  }
4043 }
4044 
4045 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
4046  assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
4047 
4048  // Additional remapping information.
4049  const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
4050  const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
4051  F.ModuleOffsetMap = StringRef();
4052 
4053  using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
4054  RemapBuilder IdentifierRemap(F.IdentifierRemap);
4055  RemapBuilder MacroRemap(F.MacroRemap);
4056  RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
4057  RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
4058  RemapBuilder SelectorRemap(F.SelectorRemap);
4059  RemapBuilder DeclRemap(F.DeclRemap);
4060  RemapBuilder TypeRemap(F.TypeRemap);
4061 
4062  auto &ImportedModuleVector = F.TransitiveImports;
4063  assert(ImportedModuleVector.empty());
4064 
4065  while (Data < DataEnd) {
4066  // FIXME: Looking up dependency modules by filename is horrible. Let's
4067  // start fixing this with prebuilt, explicit and implicit modules and see
4068  // how it goes...
4069  using namespace llvm::support;
4070  ModuleKind Kind = static_cast<ModuleKind>(
4071  endian::readNext<uint8_t, llvm::endianness::little>(Data));
4072  uint16_t Len = endian::readNext<uint16_t, llvm::endianness::little>(Data);
4073  StringRef Name = StringRef((const char*)Data, Len);
4074  Data += Len;
4077  ? ModuleMgr.lookupByModuleName(Name)
4078  : ModuleMgr.lookupByFileName(Name));
4079  if (!OM) {
4080  std::string Msg = "refers to unknown module, cannot find ";
4081  Msg.append(std::string(Name));
4082  Error(Msg);
4083  return;
4084  }
4085 
4086  ImportedModuleVector.push_back(OM);
4087 
4088  uint32_t IdentifierIDOffset =
4089  endian::readNext<uint32_t, llvm::endianness::little>(Data);
4090  uint32_t MacroIDOffset =
4091  endian::readNext<uint32_t, llvm::endianness::little>(Data);
4092  uint32_t PreprocessedEntityIDOffset =
4093  endian::readNext<uint32_t, llvm::endianness::little>(Data);
4094  uint32_t SubmoduleIDOffset =
4095  endian::readNext<uint32_t, llvm::endianness::little>(Data);
4096  uint32_t SelectorIDOffset =
4097  endian::readNext<uint32_t, llvm::endianness::little>(Data);
4098  uint32_t DeclIDOffset =
4099  endian::readNext<uint32_t, llvm::endianness::little>(Data);
4100  uint32_t TypeIndexOffset =
4101  endian::readNext<uint32_t, llvm::endianness::little>(Data);
4102 
4103  auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
4104  RemapBuilder &Remap) {
4105  constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
4106  if (Offset != None)
4107  Remap.insert(std::make_pair(Offset,
4108  static_cast<int>(BaseOffset - Offset)));
4109  };
4110 
4111  mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
4112  mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
4113  mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
4114  PreprocessedEntityRemap);
4115  mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
4116  mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
4117  mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
4118  mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
4119 
4120  // Global -> local mappings.
4121  F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
4122  }
4123 }
4124 
4126 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
4127  const ModuleFile *ImportedBy,
4128  unsigned ClientLoadCapabilities) {
4129  unsigned Idx = 0;
4130  F.ModuleMapPath = ReadPath(F, Record, Idx);
4131 
4132  // Try to resolve ModuleName in the current header search context and
4133  // verify that it is found in the same module map file as we saved. If the
4134  // top-level AST file is a main file, skip this check because there is no
4135  // usable header search context.
4136  assert(!F.ModuleName.empty() &&
4137  "MODULE_NAME should come before MODULE_MAP_FILE");
4138  if (PP.getPreprocessorOpts().ModulesCheckRelocated &&
4139  F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
4140  // An implicitly-loaded module file should have its module listed in some
4141  // module map file that we've already loaded.
4142  Module *M =
4143  PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
4144  auto &Map = PP.getHeaderSearchInfo().getModuleMap();
4145  OptionalFileEntryRef ModMap =
4146  M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
4147  // Don't emit module relocation error if we have -fno-validate-pch
4148  if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
4150  !ModMap) {
4151  if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
4152  if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {
4153  // This module was defined by an imported (explicit) module.
4154  Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
4155  << ASTFE->getName();
4156  } else {
4157  // This module was built with a different module map.
4158  Diag(diag::err_imported_module_not_found)
4159  << F.ModuleName << F.FileName
4160  << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
4161  << !ImportedBy;
4162  // In case it was imported by a PCH, there's a chance the user is
4163  // just missing to include the search path to the directory containing
4164  // the modulemap.
4165  if (ImportedBy && ImportedBy->Kind == MK_PCH)
4166  Diag(diag::note_imported_by_pch_module_not_found)
4167  << llvm::sys::path::parent_path(F.ModuleMapPath);
4168  }
4169  }
4170  return OutOfDate;
4171  }
4172 
4173  assert(M && M->Name == F.ModuleName && "found module with different name");
4174 
4175  // Check the primary module map file.
4176  auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
4177  if (!StoredModMap || *StoredModMap != ModMap) {
4178  assert(ModMap && "found module is missing module map file");
4179  assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4180  "top-level import should be verified");
4181  bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4182  if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4183  Diag(diag::err_imported_module_modmap_changed)
4184  << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4185  << ModMap->getName() << F.ModuleMapPath << NotImported;
4186  return OutOfDate;
4187  }
4188 
4189  ModuleMap::AdditionalModMapsSet AdditionalStoredMaps;
4190  for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
4191  // FIXME: we should use input files rather than storing names.
4192  std::string Filename = ReadPath(F, Record, Idx);
4193  auto SF = FileMgr.getOptionalFileRef(Filename, false, false);
4194  if (!SF) {
4195  if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4196  Error("could not find file '" + Filename +"' referenced by AST file");
4197  return OutOfDate;
4198  }
4199  AdditionalStoredMaps.insert(*SF);
4200  }
4201 
4202  // Check any additional module map files (e.g. module.private.modulemap)
4203  // that are not in the pcm.
4204  if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
4205  for (FileEntryRef ModMap : *AdditionalModuleMaps) {
4206  // Remove files that match
4207  // Note: SmallPtrSet::erase is really remove
4208  if (!AdditionalStoredMaps.erase(ModMap)) {
4209  if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4210  Diag(diag::err_module_different_modmap)
4211  << F.ModuleName << /*new*/0 << ModMap.getName();
4212  return OutOfDate;
4213  }
4214  }
4215  }
4216 
4217  // Check any additional module map files that are in the pcm, but not
4218  // found in header search. Cases that match are already removed.
4219  for (FileEntryRef ModMap : AdditionalStoredMaps) {
4220  if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
4221  Diag(diag::err_module_different_modmap)
4222  << F.ModuleName << /*not new*/1 << ModMap.getName();
4223  return OutOfDate;
4224  }
4225  }
4226 
4227  if (Listener)
4228  Listener->ReadModuleMapFile(F.ModuleMapPath);
4229  return Success;
4230 }
4231 
4232 /// Move the given method to the back of the global list of methods.
4234  // Find the entry for this selector in the method pool.
4236  S.ObjC().MethodPool.find(Method->getSelector());
4237  if (Known == S.ObjC().MethodPool.end())
4238  return;
4239 
4240  // Retrieve the appropriate method list.
4241  ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4242  : Known->second.second;
4243  bool Found = false;
4244  for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
4245  if (!Found) {
4246  if (List->getMethod() == Method) {
4247  Found = true;
4248  } else {
4249  // Keep searching.
4250  continue;
4251  }
4252  }
4253 
4254  if (List->getNext())
4255  List->setMethod(List->getNext()->getMethod());
4256  else
4257  List->setMethod(Method);
4258  }
4259 }
4260 
4261 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
4262  assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4263  for (Decl *D : Names) {
4264  bool wasHidden = !D->isUnconditionallyVisible();
4265  D->setVisibleDespiteOwningModule();
4266 
4267  if (wasHidden && SemaObj) {
4268  if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4269  moveMethodToBackOfGlobalList(*SemaObj, Method);
4270  }
4271  }
4272  }
4273 }
4274 
4276  Module::NameVisibilityKind NameVisibility,
4277  SourceLocation ImportLoc) {
4280  Stack.push_back(Mod);
4281  while (!Stack.empty()) {
4282  Mod = Stack.pop_back_val();
4283 
4284  if (NameVisibility <= Mod->NameVisibility) {
4285  // This module already has this level of visibility (or greater), so
4286  // there is nothing more to do.
4287  continue;
4288  }
4289 
4290  if (Mod->isUnimportable()) {
4291  // Modules that aren't importable cannot be made visible.
4292  continue;
4293  }
4294 
4295  // Update the module's name visibility.
4296  Mod->NameVisibility = NameVisibility;
4297 
4298  // If we've already deserialized any names from this module,
4299  // mark them as visible.
4300  HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4301  if (Hidden != HiddenNamesMap.end()) {
4302  auto HiddenNames = std::move(*Hidden);
4303  HiddenNamesMap.erase(Hidden);
4304  makeNamesVisible(HiddenNames.second, HiddenNames.first);
4305  assert(!HiddenNamesMap.contains(Mod) &&
4306  "making names visible added hidden names");
4307  }
4308 
4309  // Push any exported modules onto the stack to be marked as visible.
4310  SmallVector<Module *, 16> Exports;
4311  Mod->getExportedModules(Exports);
4313  I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4314  Module *Exported = *I;
4315  if (Visited.insert(Exported).second)
4316  Stack.push_back(Exported);
4317  }
4318  }
4319 }
4320 
4321 /// We've merged the definition \p MergedDef into the existing definition
4322 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4323 /// visible.
4325  NamedDecl *MergedDef) {
4326  if (!Def->isUnconditionallyVisible()) {
4327  // If MergedDef is visible or becomes visible, make the definition visible.
4328  if (MergedDef->isUnconditionallyVisible())
4330  else {
4331  getContext().mergeDefinitionIntoModule(
4332  Def, MergedDef->getImportedOwningModule(),
4333  /*NotifyListeners*/ false);
4334  PendingMergedDefinitionsToDeduplicate.insert(Def);
4335  }
4336  }
4337 }
4338 
4340  if (GlobalIndex)
4341  return false;
4342 
4343  if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4344  !PP.getLangOpts().Modules)
4345  return true;
4346 
4347  // Try to load the global index.
4348  TriedLoadingGlobalIndex = true;
4349  StringRef ModuleCachePath
4350  = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4351  std::pair<GlobalModuleIndex *, llvm::Error> Result =
4352  GlobalModuleIndex::readIndex(ModuleCachePath);
4353  if (llvm::Error Err = std::move(Result.second)) {
4354  assert(!Result.first);
4355  consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4356  return true;
4357  }
4358 
4359  GlobalIndex.reset(Result.first);
4360  ModuleMgr.setGlobalIndex(GlobalIndex.get());
4361  return false;
4362 }
4363 
4365  return PP.getLangOpts().Modules && UseGlobalIndex &&
4366  !hasGlobalIndex() && TriedLoadingGlobalIndex;
4367 }
4368 
4370  // Overwrite the timestamp file contents so that file's mtime changes.
4371  std::string TimestampFilename = MF.getTimestampFilename();
4372  std::error_code EC;
4373  llvm::raw_fd_ostream OS(TimestampFilename, EC,
4374  llvm::sys::fs::OF_TextWithCRLF);
4375  if (EC)
4376  return;
4377  OS << "Timestamp file\n";
4378  OS.close();
4379  OS.clear_error(); // Avoid triggering a fatal error.
4380 }
4381 
4382 /// Given a cursor at the start of an AST file, scan ahead and drop the
4383 /// cursor into the start of the given block ID, returning false on success and
4384 /// true on failure.
4385 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4386  while (true) {
4387  Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4388  if (!MaybeEntry) {
4389  // FIXME this drops errors on the floor.
4390  consumeError(MaybeEntry.takeError());
4391  return true;
4392  }
4393  llvm::BitstreamEntry Entry = MaybeEntry.get();
4394 
4395  switch (Entry.Kind) {
4397  case llvm::BitstreamEntry::EndBlock:
4398  return true;
4399 
4401  // Ignore top-level records.
4402  if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4403  break;
4404  else {
4405  // FIXME this drops errors on the floor.
4406  consumeError(Skipped.takeError());
4407  return true;
4408  }
4409 
4410  case llvm::BitstreamEntry::SubBlock:
4411  if (Entry.ID == BlockID) {
4412  if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4413  // FIXME this drops the error on the floor.
4414  consumeError(std::move(Err));
4415  return true;
4416  }
4417  // Found it!
4418  return false;
4419  }
4420 
4421  if (llvm::Error Err = Cursor.SkipBlock()) {
4422  // FIXME this drops the error on the floor.
4423  consumeError(std::move(Err));
4424  return true;
4425  }
4426  }
4427  }
4428 }
4429 
4431  SourceLocation ImportLoc,
4432  unsigned ClientLoadCapabilities,
4433  ModuleFile **NewLoadedModuleFile) {
4434  llvm::TimeTraceScope scope("ReadAST", FileName);
4435 
4436  llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4437  llvm::SaveAndRestore<std::optional<ModuleKind>> SetCurModuleKindRAII(
4438  CurrentDeserializingModuleKind, Type);
4439 
4440  // Defer any pending actions until we get to the end of reading the AST file.
4441  Deserializing AnASTFile(this);
4442 
4443  // Bump the generation number.
4444  unsigned PreviousGeneration = 0;
4445  if (ContextObj)
4446  PreviousGeneration = incrementGeneration(*ContextObj);
4447 
4448  unsigned NumModules = ModuleMgr.size();
4450  if (ASTReadResult ReadResult =
4451  ReadASTCore(FileName, Type, ImportLoc,
4452  /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4453  ClientLoadCapabilities)) {
4454  ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4455 
4456  // If we find that any modules are unusable, the global index is going
4457  // to be out-of-date. Just remove it.
4458  GlobalIndex.reset();
4459  ModuleMgr.setGlobalIndex(nullptr);
4460  return ReadResult;
4461  }
4462 
4463  if (NewLoadedModuleFile && !Loaded.empty())
4464  *NewLoadedModuleFile = Loaded.back().Mod;
4465 
4466  // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4467  // remove modules from this point. Various fields are updated during reading
4468  // the AST block and removing the modules would result in dangling pointers.
4469  // They are generally only incidentally dereferenced, ie. a binary search
4470  // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4471  // be dereferenced but it wouldn't actually be used.
4472 
4473  // Load the AST blocks of all of the modules that we loaded. We can still
4474  // hit errors parsing the ASTs at this point.
4475  for (ImportedModule &M : Loaded) {
4476  ModuleFile &F = *M.Mod;
4477  llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
4478 
4479  // Read the AST block.
4480  if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4481  Error(std::move(Err));
4482  return Failure;
4483  }
4484 
4485  // The AST block should always have a definition for the main module.
4486  if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4487  Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4488  return Failure;
4489  }
4490 
4491  // Read the extension blocks.
4493  if (llvm::Error Err = ReadExtensionBlock(F)) {
4494  Error(std::move(Err));
4495  return Failure;
4496  }
4497  }
4498 
4499  // Once read, set the ModuleFile bit base offset and update the size in
4500  // bits of all files we've seen.
4501  F.GlobalBitOffset = TotalModulesSizeInBits;
4502  TotalModulesSizeInBits += F.SizeInBits;
4503  GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4504  }
4505 
4506  // Preload source locations and interesting indentifiers.
4507  for (ImportedModule &M : Loaded) {
4508  ModuleFile &F = *M.Mod;
4509 
4510  // Map the original source file ID into the ID space of the current
4511  // compilation.
4512  if (F.OriginalSourceFileID.isValid())
4513  F.OriginalSourceFileID = TranslateFileID(F, F.OriginalSourceFileID);
4514 
4515  for (auto Offset : F.PreloadIdentifierOffsets) {
4516  const unsigned char *Data = F.IdentifierTableData + Offset;
4517 
4518  ASTIdentifierLookupTrait Trait(*this, F);
4519  auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4520  auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4521 
4522  IdentifierInfo *II;
4523  if (!PP.getLangOpts().CPlusPlus) {
4524  // Identifiers present in both the module file and the importing
4525  // instance are marked out-of-date so that they can be deserialized
4526  // on next use via ASTReader::updateOutOfDateIdentifier().
4527  // Identifiers present in the module file but not in the importing
4528  // instance are ignored for now, preventing growth of the identifier
4529  // table. They will be deserialized on first use via ASTReader::get().
4530  auto It = PP.getIdentifierTable().find(Key);
4531  if (It == PP.getIdentifierTable().end())
4532  continue;
4533  II = It->second;
4534  } else {
4535  // With C++ modules, not many identifiers are considered interesting.
4536  // All identifiers in the module file can be placed into the identifier
4537  // table of the importing instance and marked as out-of-date. This makes
4538  // ASTReader::get() a no-op, and deserialization will take place on
4539  // first/next use via ASTReader::updateOutOfDateIdentifier().
4540  II = &PP.getIdentifierTable().getOwn(Key);
4541  }
4542 
4543  II->setOutOfDate(true);
4544 
4545  // Mark this identifier as being from an AST file so that we can track
4546  // whether we need to serialize it.
4547  markIdentifierFromAST(*this, *II);
4548 
4549  // Associate the ID with the identifier so that the writer can reuse it.
4550  auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4551  SetIdentifierInfo(ID, II);
4552  }
4553  }
4554 
4555  // Builtins and library builtins have already been initialized. Mark all
4556  // identifiers as out-of-date, so that they are deserialized on first use.
4557  if (Type == MK_PCH || Type == MK_Preamble || Type == MK_MainFile)
4558  for (auto &Id : PP.getIdentifierTable())
4559  Id.second->setOutOfDate(true);
4560 
4561  // Mark selectors as out of date.
4562  for (const auto &Sel : SelectorGeneration)
4563  SelectorOutOfDate[Sel.first] = true;
4564 
4565  // Setup the import locations and notify the module manager that we've
4566  // committed to these module files.
4567  for (ImportedModule &M : Loaded) {
4568  ModuleFile &F = *M.Mod;
4569 
4570  ModuleMgr.moduleFileAccepted(&F);
4571 
4572  // Set the import location.
4573  F.DirectImportLoc = ImportLoc;
4574  // FIXME: We assume that locations from PCH / preamble do not need
4575  // any translation.
4576  if (!M.ImportedBy)
4577  F.ImportLoc = M.ImportLoc;
4578  else
4579  F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4580  }
4581 
4582  // Resolve any unresolved module exports.
4583  for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4584  UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4585  SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4586  Module *ResolvedMod = getSubmodule(GlobalID);
4587 
4588  switch (Unresolved.Kind) {
4589  case UnresolvedModuleRef::Conflict:
4590  if (ResolvedMod) {
4591  Module::Conflict Conflict;
4592  Conflict.Other = ResolvedMod;
4593  Conflict.Message = Unresolved.String.str();
4594  Unresolved.Mod->Conflicts.push_back(Conflict);
4595  }
4596  continue;
4597 
4598  case UnresolvedModuleRef::Import:
4599  if (ResolvedMod)
4600  Unresolved.Mod->Imports.insert(ResolvedMod);
4601  continue;
4602 
4603  case UnresolvedModuleRef::Affecting:
4604  if (ResolvedMod)
4605  Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
4606  continue;
4607 
4608  case UnresolvedModuleRef::Export:
4609  if (ResolvedMod || Unresolved.IsWildcard)
4610  Unresolved.Mod->Exports.push_back(
4611  Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4612  continue;
4613  }
4614  }
4615  UnresolvedModuleRefs.clear();
4616 
4617  // FIXME: How do we load the 'use'd modules? They may not be submodules.
4618  // Might be unnecessary as use declarations are only used to build the
4619  // module itself.
4620 
4621  if (ContextObj)
4622  InitializeContext();
4623 
4624  if (SemaObj)
4625  UpdateSema();
4626 
4627  if (DeserializationListener)
4628  DeserializationListener->ReaderInitialized(this);
4629 
4630  ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
4631  if (PrimaryModule.OriginalSourceFileID.isValid()) {
4632  // If this AST file is a precompiled preamble, then set the
4633  // preamble file ID of the source manager to the file source file
4634  // from which the preamble was built.
4635  if (Type == MK_Preamble) {
4636  SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4637  } else if (Type == MK_MainFile) {
4638  SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4639  }
4640  }
4641 
4642  // For any Objective-C class definitions we have already loaded, make sure
4643  // that we load any additional categories.
4644  if (ContextObj) {
4645  for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4646  loadObjCCategories(GlobalDeclID(ObjCClassesLoaded[I]->getGlobalID()),
4647  ObjCClassesLoaded[I], PreviousGeneration);
4648  }
4649  }
4650 
4651  HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
4653  // Now we are certain that the module and all modules it depends on are
4654  // up-to-date. For implicitly-built module files, ensure the corresponding
4655  // timestamp files are up-to-date in this build session.
4656  for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4657  ImportedModule &M = Loaded[I];
4658  if (M.Mod->Kind == MK_ImplicitModule &&
4659  M.Mod->InputFilesValidationTimestamp < HSOpts.BuildSessionTimestamp)
4660  updateModuleTimestamp(*M.Mod);
4661  }
4662  }
4663 
4664  return Success;
4665 }
4666 
4667 static ASTFileSignature readASTFileSignature(StringRef PCH);
4668 
4669 /// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4670 static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4671  // FIXME checking magic headers is done in other places such as
4672  // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4673  // always done the same. Unify it all with a helper.
4674  if (!Stream.canSkipToPos(4))
4675  return llvm::createStringError(std::errc::illegal_byte_sequence,
4676  "file too small to contain AST file magic");
4677  for (unsigned C : {'C', 'P', 'C', 'H'})
4678  if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4679  if (Res.get() != C)
4680  return llvm::createStringError(
4681  std::errc::illegal_byte_sequence,
4682  "file doesn't start with AST file magic");
4683  } else
4684  return Res.takeError();
4685  return llvm::Error::success();
4686 }
4687 
4689  switch (Kind) {
4690  case MK_PCH:
4691  return 0; // PCH
4692  case MK_ImplicitModule:
4693  case MK_ExplicitModule:
4694  case MK_PrebuiltModule:
4695  return 1; // module
4696  case MK_MainFile:
4697  case MK_Preamble:
4698  return 2; // main source file
4699  }
4700  llvm_unreachable("unknown module kind");
4701 }
4702 
4704 ASTReader::ReadASTCore(StringRef FileName,
4705  ModuleKind Type,
4706  SourceLocation ImportLoc,
4707  ModuleFile *ImportedBy,
4709  off_t ExpectedSize, time_t ExpectedModTime,
4710  ASTFileSignature ExpectedSignature,
4711  unsigned ClientLoadCapabilities) {
4712  ModuleFile *M;
4713  std::string ErrorStr;
4715  = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
4716  getGeneration(), ExpectedSize, ExpectedModTime,
4717  ExpectedSignature, readASTFileSignature,
4718  M, ErrorStr);
4719 
4720  switch (AddResult) {
4722  Diag(diag::remark_module_import)
4723  << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4724  << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
4725  return Success;
4726 
4728  // Load module file below.
4729  break;
4730 
4732  // The module file was missing; if the client can handle that, return
4733  // it.
4734  if (ClientLoadCapabilities & ARR_Missing)
4735  return Missing;
4736 
4737  // Otherwise, return an error.
4738  Diag(diag::err_ast_file_not_found)
4739  << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4740  << ErrorStr;
4741  return Failure;
4742 
4744  // We couldn't load the module file because it is out-of-date. If the
4745  // client can handle out-of-date, return it.
4746  if (ClientLoadCapabilities & ARR_OutOfDate)
4747  return OutOfDate;
4748 
4749  // Otherwise, return an error.
4750  Diag(diag::err_ast_file_out_of_date)
4751  << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
4752  << ErrorStr;
4753  return Failure;
4754  }
4755 
4756  assert(M && "Missing module file");
4757 
4758  bool ShouldFinalizePCM = false;
4759  auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4760  auto &MC = getModuleManager().getModuleCache();
4761  if (ShouldFinalizePCM)
4762  MC.finalizePCM(FileName);
4763  else
4764  MC.tryToDropPCM(FileName);
4765  });
4766  ModuleFile &F = *M;
4767  BitstreamCursor &Stream = F.Stream;
4768  Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4769  F.SizeInBits = F.Buffer->getBufferSize() * 8;
4770 
4771  // Sniff for the signature.
4772  if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4773  Diag(diag::err_ast_file_invalid)
4774  << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
4775  return Failure;
4776  }
4777 
4778  // This is used for compatibility with older PCH formats.
4779  bool HaveReadControlBlock = false;
4780  while (true) {
4781  Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4782  if (!MaybeEntry) {
4783  Error(MaybeEntry.takeError());
4784  return Failure;
4785  }
4786  llvm::BitstreamEntry Entry = MaybeEntry.get();
4787 
4788  switch (Entry.Kind) {
4791  case llvm::BitstreamEntry::EndBlock:
4792  Error("invalid record at top-level of AST file");
4793  return Failure;
4794 
4795  case llvm::BitstreamEntry::SubBlock:
4796  break;
4797  }
4798 
4799  switch (Entry.ID) {
4800  case CONTROL_BLOCK_ID:
4801  HaveReadControlBlock = true;
4802  switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4803  case Success:
4804  // Check that we didn't try to load a non-module AST file as a module.
4805  //
4806  // FIXME: Should we also perform the converse check? Loading a module as
4807  // a PCH file sort of works, but it's a bit wonky.
4808  if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4809  Type == MK_PrebuiltModule) &&
4810  F.ModuleName.empty()) {
4811  auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4812  if (Result != OutOfDate ||
4813  (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4814  Diag(diag::err_module_file_not_module) << FileName;
4815  return Result;
4816  }
4817  break;
4818 
4819  case Failure: return Failure;
4820  case Missing: return Missing;
4821  case OutOfDate: return OutOfDate;
4822  case VersionMismatch: return VersionMismatch;
4823  case ConfigurationMismatch: return ConfigurationMismatch;
4824  case HadErrors: return HadErrors;
4825  }
4826  break;
4827 
4828  case AST_BLOCK_ID:
4829  if (!HaveReadControlBlock) {
4830  if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4831  Diag(diag::err_pch_version_too_old);
4832  return VersionMismatch;
4833  }
4834 
4835  // Record that we've loaded this module.
4836  Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4837  ShouldFinalizePCM = true;
4838  return Success;
4839 
4840  default:
4841  if (llvm::Error Err = Stream.SkipBlock()) {
4842  Error(std::move(Err));
4843  return Failure;
4844  }
4845  break;
4846  }
4847  }
4848 
4849  llvm_unreachable("unexpected break; expected return");
4850 }
4851 
4853 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4854  unsigned ClientLoadCapabilities) {
4855  const HeaderSearchOptions &HSOpts =
4856  PP.getHeaderSearchInfo().getHeaderSearchOpts();
4857  bool AllowCompatibleConfigurationMismatch =
4859  bool DisableValidation = shouldDisableValidationForFile(F);
4860 
4861  ASTReadResult Result = readUnhashedControlBlockImpl(
4862  &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4863  Listener.get(),
4864  WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4865 
4866  // If F was directly imported by another module, it's implicitly validated by
4867  // the importing module.
4868  if (DisableValidation || WasImportedBy ||
4869  (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4870  return Success;
4871 
4872  if (Result == Failure) {
4873  Error("malformed block record in AST file");
4874  return Failure;
4875  }
4876 
4877  if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4878  // If this module has already been finalized in the ModuleCache, we're stuck
4879  // with it; we can only load a single version of each module.
4880  //
4881  // This can happen when a module is imported in two contexts: in one, as a
4882  // user module; in another, as a system module (due to an import from
4883  // another module marked with the [system] flag). It usually indicates a
4884  // bug in the module map: this module should also be marked with [system].
4885  //
4886  // If -Wno-system-headers (the default), and the first import is as a
4887  // system module, then validation will fail during the as-user import,
4888  // since -Werror flags won't have been validated. However, it's reasonable
4889  // to treat this consistently as a system module.
4890  //
4891  // If -Wsystem-headers, the PCM on disk was built with
4892  // -Wno-system-headers, and the first import is as a user module, then
4893  // validation will fail during the as-system import since the PCM on disk
4894  // doesn't guarantee that -Werror was respected. However, the -Werror
4895  // flags were checked during the initial as-user import.
4896  if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
4897  Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4898  return Success;
4899  }
4900  }
4901 
4902  return Result;
4903 }
4904 
4905 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4906  ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4907  bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4908  bool ValidateDiagnosticOptions) {
4909  // Initialize a stream.
4910  BitstreamCursor Stream(StreamData);
4911 
4912  // Sniff for the signature.
4913  if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4914  // FIXME this drops the error on the floor.
4915  consumeError(std::move(Err));
4916  return Failure;
4917  }
4918 
4919  // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4921  return Failure;
4922 
4923  // Read all of the records in the options block.
4924  RecordData Record;
4925  ASTReadResult Result = Success;
4926  while (true) {
4927  Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4928  if (!MaybeEntry) {
4929  // FIXME this drops the error on the floor.
4930  consumeError(MaybeEntry.takeError());
4931  return Failure;
4932  }
4933  llvm::BitstreamEntry Entry = MaybeEntry.get();
4934 
4935  switch (Entry.Kind) {
4937  case llvm::BitstreamEntry::SubBlock:
4938  return Failure;
4939 
4940  case llvm::BitstreamEntry::EndBlock:
4941  return Result;
4942 
4944  // The interesting case.
4945  break;
4946  }
4947 
4948  // Read and process a record.
4949  Record.clear();
4950  StringRef Blob;
4951  Expected<unsigned> MaybeRecordType =
4952  Stream.readRecord(Entry.ID, Record, &Blob);
4953  if (!MaybeRecordType) {
4954  // FIXME this drops the error.
4955  return Failure;
4956  }
4957  switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
4958  case SIGNATURE:
4959  if (F) {
4960  F->Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
4961  assert(F->Signature != ASTFileSignature::createDummy() &&
4962  "Dummy AST file signature not backpatched in ASTWriter.");
4963  }
4964  break;
4965  case AST_BLOCK_HASH:
4966  if (F) {
4967  F->ASTBlockHash = ASTFileSignature::create(Blob.begin(), Blob.end());
4969  "Dummy AST block hash not backpatched in ASTWriter.");
4970  }
4971  break;
4972  case DIAGNOSTIC_OPTIONS: {
4973  bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4974  if (Listener && ValidateDiagnosticOptions &&
4975  !AllowCompatibleConfigurationMismatch &&
4976  ParseDiagnosticOptions(Record, Complain, *Listener))
4977  Result = OutOfDate; // Don't return early. Read the signature.
4978  break;
4979  }
4980  case HEADER_SEARCH_PATHS: {
4981  bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
4982  if (Listener && !AllowCompatibleConfigurationMismatch &&
4983  ParseHeaderSearchPaths(Record, Complain, *Listener))
4984  Result = ConfigurationMismatch;
4985  break;
4986  }
4987  case DIAG_PRAGMA_MAPPINGS:
4988  if (!F)
4989  break;
4990  if (F->PragmaDiagMappings.empty())
4991  F->PragmaDiagMappings.swap(Record);
4992  else
4993  F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4994  Record.begin(), Record.end());
4995  break;
4997  if (F)
4998  F->SearchPathUsage = ReadBitVector(Record, Blob);
4999  break;
5000  case VFS_USAGE:
5001  if (F)
5002  F->VFSUsage = ReadBitVector(Record, Blob);
5003  break;
5004  }
5005  }
5006 }
5007 
5008 /// Parse a record and blob containing module file extension metadata.
5011  StringRef Blob,
5012  ModuleFileExtensionMetadata &Metadata) {
5013  if (Record.size() < 4) return true;
5014 
5015  Metadata.MajorVersion = Record[0];
5016  Metadata.MinorVersion = Record[1];
5017 
5018  unsigned BlockNameLen = Record[2];
5019  unsigned UserInfoLen = Record[3];
5020 
5021  if (BlockNameLen + UserInfoLen > Blob.size()) return true;
5022 
5023  Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
5024  Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
5025  Blob.data() + BlockNameLen + UserInfoLen);
5026  return false;
5027 }
5028 
5029 llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
5030  BitstreamCursor &Stream = F.Stream;
5031 
5032  RecordData Record;
5033  while (true) {
5034  Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5035  if (!MaybeEntry)
5036  return MaybeEntry.takeError();
5037  llvm::BitstreamEntry Entry = MaybeEntry.get();
5038 
5039  switch (Entry.Kind) {
5040  case llvm::BitstreamEntry::SubBlock:
5041  if (llvm::Error Err = Stream.SkipBlock())
5042  return Err;
5043  continue;
5044  case llvm::BitstreamEntry::EndBlock:
5045  return llvm::Error::success();
5047  return llvm::createStringError(std::errc::illegal_byte_sequence,
5048  "malformed block record in AST file");
5050  break;
5051  }
5052 
5053  Record.clear();
5054  StringRef Blob;
5055  Expected<unsigned> MaybeRecCode =
5056  Stream.readRecord(Entry.ID, Record, &Blob);
5057  if (!MaybeRecCode)
5058  return MaybeRecCode.takeError();
5059  switch (MaybeRecCode.get()) {
5060  case EXTENSION_METADATA: {
5061  ModuleFileExtensionMetadata Metadata;
5062  if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5063  return llvm::createStringError(
5064  std::errc::illegal_byte_sequence,
5065  "malformed EXTENSION_METADATA in AST file");
5066 
5067  // Find a module file extension with this block name.
5068  auto Known = ModuleFileExtensions.find(Metadata.BlockName);
5069  if (Known == ModuleFileExtensions.end()) break;
5070 
5071  // Form a reader.
5072  if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
5073  F, Stream)) {
5074  F.ExtensionReaders.push_back(std::move(Reader));
5075  }
5076 
5077  break;
5078  }
5079  }
5080  }
5081 
5082  return llvm::Error::success();
5083 }
5084 
5086  assert(ContextObj && "no context to initialize");
5087  ASTContext &Context = *ContextObj;
5088 
5089  // If there's a listener, notify them that we "read" the translation unit.
5090  if (DeserializationListener)
5091  DeserializationListener->DeclRead(
5093  Context.getTranslationUnitDecl());
5094 
5095  // FIXME: Find a better way to deal with collisions between these
5096  // built-in types. Right now, we just ignore the problem.
5097 
5098  // Load the special types.
5099  if (SpecialTypes.size() >= NumSpecialTypeIDs) {
5100  if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
5101  if (!Context.CFConstantStringTypeDecl)
5102  Context.setCFConstantStringType(GetType(String));
5103  }
5104 
5105  if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
5106  QualType FileType = GetType(File);
5107  if (FileType.isNull()) {
5108  Error("FILE type is NULL");
5109  return;
5110  }
5111 
5112  if (!Context.FILEDecl) {
5113  if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
5114  Context.setFILEDecl(Typedef->getDecl());
5115  else {
5116  const TagType *Tag = FileType->getAs<TagType>();
5117  if (!Tag) {
5118  Error("Invalid FILE type in AST file");
5119  return;
5120  }
5121  Context.setFILEDecl(Tag->getDecl());
5122  }
5123  }
5124  }
5125 
5126  if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
5127  QualType Jmp_bufType = GetType(Jmp_buf);
5128  if (Jmp_bufType.isNull()) {
5129  Error("jmp_buf type is NULL");
5130  return;
5131  }
5132 
5133  if (!Context.jmp_bufDecl) {
5134  if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
5135  Context.setjmp_bufDecl(Typedef->getDecl());
5136  else {
5137  const TagType *Tag = Jmp_bufType->getAs<TagType>();
5138  if (!Tag) {
5139  Error("Invalid jmp_buf type in AST file");
5140  return;
5141  }
5142  Context.setjmp_bufDecl(Tag->getDecl());
5143  }
5144  }
5145  }
5146 
5147  if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
5148  QualType Sigjmp_bufType = GetType(Sigjmp_buf);
5149  if (Sigjmp_bufType.isNull()) {
5150  Error("sigjmp_buf type is NULL");
5151  return;
5152  }
5153 
5154  if (!Context.sigjmp_bufDecl) {
5155  if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
5156  Context.setsigjmp_bufDecl(Typedef->getDecl());
5157  else {
5158  const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
5159  assert(Tag && "Invalid sigjmp_buf type in AST file");
5160  Context.setsigjmp_bufDecl(Tag->getDecl());
5161  }
5162  }
5163  }
5164 
5165  if (unsigned ObjCIdRedef
5166  = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
5167  if (Context.ObjCIdRedefinitionType.isNull())
5168  Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
5169  }
5170 
5171  if (unsigned ObjCClassRedef
5172  = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
5173  if (Context.ObjCClassRedefinitionType.isNull())
5174  Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
5175  }
5176 
5177  if (unsigned ObjCSelRedef
5178  = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
5179  if (Context.ObjCSelRedefinitionType.isNull())
5180  Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
5181  }
5182 
5183  if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
5184  QualType Ucontext_tType = GetType(Ucontext_t);
5185  if (Ucontext_tType.isNull()) {
5186  Error("ucontext_t type is NULL");
5187  return;
5188  }
5189 
5190  if (!Context.ucontext_tDecl) {
5191  if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
5192  Context.setucontext_tDecl(Typedef->getDecl());
5193  else {
5194  const TagType *Tag = Ucontext_tType->getAs<TagType>();
5195  assert(Tag && "Invalid ucontext_t type in AST file");
5196  Context.setucontext_tDecl(Tag->getDecl());
5197  }
5198  }
5199  }
5200  }
5201 
5202  ReadPragmaDiagnosticMappings(Context.getDiagnostics());
5203 
5204  // If there were any CUDA special declarations, deserialize them.
5205  if (!CUDASpecialDeclRefs.empty()) {
5206  assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
5207  Context.setcudaConfigureCallDecl(
5208  cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
5209  }
5210 
5211  // Re-export any modules that were imported by a non-module AST file.
5212  // FIXME: This does not make macro-only imports visible again.
5213  for (auto &Import : PendingImportedModules) {
5214  if (Module *Imported = getSubmodule(Import.ID)) {
5215  makeModuleVisible(Imported, Module::AllVisible,
5216  /*ImportLoc=*/Import.ImportLoc);
5217  if (Import.ImportLoc.isValid())
5218  PP.makeModuleVisible(Imported, Import.ImportLoc);
5219  // This updates visibility for Preprocessor only. For Sema, which can be
5220  // nullptr here, we do the same later, in UpdateSema().
5221  }
5222  }
5223 
5224  // Hand off these modules to Sema.
5225  PendingImportedModulesSema.append(PendingImportedModules);
5226  PendingImportedModules.clear();
5227 }
5228 
5230  // Nothing to do for now.
5231 }
5232 
5233 /// Reads and return the signature record from \p PCH's control block, or
5234 /// else returns 0.
5236  BitstreamCursor Stream(PCH);
5237  if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5238  // FIXME this drops the error on the floor.
5239  consumeError(std::move(Err));
5240  return ASTFileSignature();
5241  }
5242 
5243  // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5245  return ASTFileSignature();
5246 
5247  // Scan for SIGNATURE inside the diagnostic options block.
5249  while (true) {
5250  Expected<llvm::BitstreamEntry> MaybeEntry =
5251  Stream.advanceSkippingSubblocks();
5252  if (!MaybeEntry) {
5253  // FIXME this drops the error on the floor.
5254  consumeError(MaybeEntry.takeError());
5255  return ASTFileSignature();
5256  }
5257  llvm::BitstreamEntry Entry = MaybeEntry.get();
5258 
5259  if (Entry.Kind != llvm::BitstreamEntry::Record)
5260  return ASTFileSignature();
5261 
5262  Record.clear();
5263  StringRef Blob;
5264  Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5265  if (!MaybeRecord) {
5266  // FIXME this drops the error on the floor.
5267  consumeError(MaybeRecord.takeError());
5268  return ASTFileSignature();
5269  }
5270  if (SIGNATURE == MaybeRecord.get()) {
5271  auto Signature = ASTFileSignature::create(Blob.begin(), Blob.end());
5272  assert(Signature != ASTFileSignature::createDummy() &&
5273  "Dummy AST file signature not backpatched in ASTWriter.");
5274  return Signature;
5275  }
5276  }
5277 }
5278 
5279 /// Retrieve the name of the original source file name
5280 /// directly from the AST file, without actually loading the AST
5281 /// file.
5283  const std::string &ASTFileName, FileManager &FileMgr,
5284  const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5285  // Open the AST file.
5286  auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
5287  /*RequiresNullTerminator=*/false);
5288  if (!Buffer) {
5289  Diags.Report(diag::err_fe_unable_to_read_pch_file)
5290  << ASTFileName << Buffer.getError().message();
5291  return std::string();
5292  }
5293 
5294  // Initialize the stream
5295  BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5296 
5297  // Sniff for the signature.
5298  if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5299  Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5300  return std::string();
5301  }
5302 
5303  // Scan for the CONTROL_BLOCK_ID block.
5304  if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5305  Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5306  return std::string();
5307  }
5308 
5309  // Scan for ORIGINAL_FILE inside the control block.
5311  while (true) {
5312  Expected<llvm::BitstreamEntry> MaybeEntry =
5313  Stream.advanceSkippingSubblocks();
5314  if (!MaybeEntry) {
5315  // FIXME this drops errors on the floor.
5316  consumeError(MaybeEntry.takeError());
5317  return std::string();
5318  }
5319  llvm::BitstreamEntry Entry = MaybeEntry.get();
5320 
5321  if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5322  return std::string();
5323 
5324  if (Entry.Kind != llvm::BitstreamEntry::Record) {
5325  Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5326  return std::string();
5327  }
5328 
5329  Record.clear();
5330  StringRef Blob;
5331  Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5332  if (!MaybeRecord) {
5333  // FIXME this drops the errors on the floor.
5334  consumeError(MaybeRecord.takeError());
5335  return std::string();
5336  }
5337  if (ORIGINAL_FILE == MaybeRecord.get())
5338  return Blob.str();
5339  }
5340 }
5341 
5342 namespace {
5343 
5344  class SimplePCHValidator : public ASTReaderListener {
5345  const LangOptions &ExistingLangOpts;
5346  const TargetOptions &ExistingTargetOpts;
5347  const PreprocessorOptions &ExistingPPOpts;
5348  std::string ExistingModuleCachePath;
5349  FileManager &FileMgr;
5350  bool StrictOptionMatches;
5351 
5352  public:
5353  SimplePCHValidator(const LangOptions &ExistingLangOpts,
5354  const TargetOptions &ExistingTargetOpts,
5355  const PreprocessorOptions &ExistingPPOpts,
5356  StringRef ExistingModuleCachePath, FileManager &FileMgr,
5357  bool StrictOptionMatches)
5358  : ExistingLangOpts(ExistingLangOpts),
5359  ExistingTargetOpts(ExistingTargetOpts),
5360  ExistingPPOpts(ExistingPPOpts),
5361  ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),
5362  StrictOptionMatches(StrictOptionMatches) {}
5363 
5364  bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5365  bool AllowCompatibleDifferences) override {
5366  return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5367  AllowCompatibleDifferences);
5368  }
5369 
5370  bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5371  bool AllowCompatibleDifferences) override {
5372  return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5373  AllowCompatibleDifferences);
5374  }
5375 
5376  bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5377  StringRef SpecificModuleCachePath,
5378  bool Complain) override {
5379  return checkModuleCachePath(
5380  FileMgr.getVirtualFileSystem(), SpecificModuleCachePath,
5381  ExistingModuleCachePath, nullptr, ExistingLangOpts, ExistingPPOpts);
5382  }
5383 
5384  bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5385  bool ReadMacros, bool Complain,
5386  std::string &SuggestedPredefines) override {
5387  return checkPreprocessorOptions(
5388  PPOpts, ExistingPPOpts, ReadMacros, /*Diags=*/nullptr, FileMgr,
5389  SuggestedPredefines, ExistingLangOpts,
5390  StrictOptionMatches ? OptionValidateStrictMatches
5392  }
5393  };
5394 
5395 } // namespace
5396 
5398  StringRef Filename, FileManager &FileMgr,
5399  const InMemoryModuleCache &ModuleCache,
5400  const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
5401  ASTReaderListener &Listener, bool ValidateDiagnosticOptions,
5402  unsigned ClientLoadCapabilities) {
5403  // Open the AST file.
5404  std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5405  llvm::MemoryBuffer *Buffer = ModuleCache.lookupPCM(Filename);
5406  if (!Buffer) {
5407  // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5408  // read again later, but we do not have the context here to determine if it
5409  // is safe to change the result of InMemoryModuleCache::getPCMState().
5410 
5411  // FIXME: This allows use of the VFS; we do not allow use of the
5412  // VFS when actually loading a module.
5413  auto BufferOrErr = FileMgr.getBufferForFile(Filename);
5414  if (!BufferOrErr)
5415  return true;
5416  OwnedBuffer = std::move(*BufferOrErr);
5417  Buffer = OwnedBuffer.get();
5418  }
5419 
5420  // Initialize the stream
5421  StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
5422  BitstreamCursor Stream(Bytes);
5423 
5424  // Sniff for the signature.
5425  if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5426  consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5427  return true;
5428  }
5429 
5430  // Scan for the CONTROL_BLOCK_ID block.
5431  if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
5432  return true;
5433 
5434  bool NeedsInputFiles = Listener.needsInputFileVisitation();
5435  bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5436  bool NeedsImports = Listener.needsImportVisitation();
5437  BitstreamCursor InputFilesCursor;
5438  uint64_t InputFilesOffsetBase = 0;
5439 
5441  std::string ModuleDir;
5442  bool DoneWithControlBlock = false;
5443  while (!DoneWithControlBlock) {
5444  Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5445  if (!MaybeEntry) {
5446  // FIXME this drops the error on the floor.
5447  consumeError(MaybeEntry.takeError());
5448  return true;
5449  }
5450  llvm::BitstreamEntry Entry = MaybeEntry.get();
5451 
5452  switch (Entry.Kind) {
5453  case llvm::BitstreamEntry::SubBlock: {
5454  switch (Entry.ID) {
5455  case OPTIONS_BLOCK_ID: {
5456  std::string IgnoredSuggestedPredefines;
5457  if (ReadOptionsBlock(Stream, ClientLoadCapabilities,
5458  /*AllowCompatibleConfigurationMismatch*/ false,
5459  Listener, IgnoredSuggestedPredefines) != Success)
5460  return true;
5461  break;
5462  }
5463 
5464  case INPUT_FILES_BLOCK_ID:
5465  InputFilesCursor = Stream;
5466  if (llvm::Error Err = Stream.SkipBlock()) {
5467  // FIXME this drops the error on the floor.
5468  consumeError(std::move(Err));
5469  return true;
5470  }
5471  if (NeedsInputFiles &&
5472  ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5473  return true;
5474  InputFilesOffsetBase = InputFilesCursor.GetCurrentBitNo();
5475  break;
5476 
5477  default:
5478  if (llvm::Error Err = Stream.SkipBlock()) {
5479  // FIXME this drops the error on the floor.
5480  consumeError(std::move(Err));
5481  return true;
5482  }
5483  break;
5484  }
5485 
5486  continue;
5487  }
5488 
5489  case llvm::BitstreamEntry::EndBlock:
5490  DoneWithControlBlock = true;
5491  break;
5492 
5494  return true;
5495 
5497  break;
5498  }
5499 
5500  if (DoneWithControlBlock) break;
5501 
5502  Record.clear();
5503  StringRef Blob;
5504  Expected<unsigned> MaybeRecCode =
5505  Stream.readRecord(Entry.ID, Record, &Blob);
5506  if (!MaybeRecCode) {
5507  // FIXME this drops the error.
5508  return Failure;
5509  }
5510  switch ((ControlRecordTypes)MaybeRecCode.get()) {
5511  case METADATA:
5512  if (Record[0] != VERSION_MAJOR)
5513  return true;
5514  if (Listener.ReadFullVersionInformation(Blob))
5515  return true;
5516  break;
5517  case MODULE_NAME:
5518  Listener.ReadModuleName(Blob);
5519  break;
5520  case MODULE_DIRECTORY:
5521  ModuleDir = std::string(Blob);
5522  break;
5523  case MODULE_MAP_FILE: {
5524  unsigned Idx = 0;
5525  auto Path = ReadString(Record, Idx);
5526  ResolveImportedPath(Path, ModuleDir);
5527  Listener.ReadModuleMapFile(Path);
5528  break;
5529  }
5530  case INPUT_FILE_OFFSETS: {
5531  if (!NeedsInputFiles)
5532  break;
5533 
5534  unsigned NumInputFiles = Record[0];
5535  unsigned NumUserFiles = Record[1];
5536  const llvm::support::unaligned_uint64_t *InputFileOffs =
5537  (const llvm::support::unaligned_uint64_t *)Blob.data();
5538  for (unsigned I = 0; I != NumInputFiles; ++I) {
5539  // Go find this input file.
5540  bool isSystemFile = I >= NumUserFiles;
5541 
5542  if (isSystemFile && !NeedsSystemInputFiles)
5543  break; // the rest are system input files
5544 
5545  BitstreamCursor &Cursor = InputFilesCursor;
5546  SavedStreamPosition SavedPosition(Cursor);
5547  if (llvm::Error Err =
5548  Cursor.JumpToBit(InputFilesOffsetBase + InputFileOffs[I])) {
5549  // FIXME this drops errors on the floor.
5550  consumeError(std::move(Err));
5551  }
5552 
5553  Expected<unsigned> MaybeCode = Cursor.ReadCode();
5554  if (!MaybeCode) {
5555  // FIXME this drops errors on the floor.
5556  consumeError(MaybeCode.takeError());
5557  }
5558  unsigned Code = MaybeCode.get();
5559 
5561  StringRef Blob;
5562  bool shouldContinue = false;
5563  Expected<unsigned> MaybeRecordType =
5564  Cursor.readRecord(Code, Record, &Blob);
5565  if (!MaybeRecordType) {
5566  // FIXME this drops errors on the floor.
5567  consumeError(MaybeRecordType.takeError());
5568  }
5569  switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5570  case INPUT_FILE_HASH:
5571  break;
5572  case INPUT_FILE:
5573  bool Overridden = static_cast<bool>(Record[3]);
5574  std::string Filename = std::string(Blob);
5575  ResolveImportedPath(Filename, ModuleDir);
5576  shouldContinue = Listener.visitInputFile(
5577  Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
5578  break;
5579  }
5580  if (!shouldContinue)
5581  break;
5582  }
5583  break;
5584  }
5585 
5586  case IMPORTS: {
5587  if (!NeedsImports)
5588  break;
5589 
5590  unsigned Idx = 0, N = Record.size();
5591  while (Idx < N) {
5592  // Read information about the AST file.
5593 
5594  // Skip Kind
5595  Idx++;
5596  bool IsStandardCXXModule = Record[Idx++];
5597 
5598  // Skip ImportLoc
5599  Idx++;
5600 
5601  // In C++20 Modules, we don't record the path to imported
5602  // modules in the BMI files.
5603  if (IsStandardCXXModule) {
5604  std::string ModuleName = ReadString(Record, Idx);
5605  Listener.visitImport(ModuleName, /*Filename=*/"");
5606  continue;
5607  }
5608 
5609  // Skip Size, ModTime and Signature
5610  Idx += 1 + 1 + ASTFileSignature::size;
5611  std::string ModuleName = ReadString(Record, Idx);
5612  std::string Filename = ReadString(Record, Idx);
5613  ResolveImportedPath(Filename, ModuleDir);
5614  Listener.visitImport(ModuleName, Filename);
5615  }
5616  break;
5617  }
5618 
5619  default:
5620  // No other validation to perform.
5621  break;
5622  }
5623  }
5624 
5625  // Look for module file extension blocks, if requested.
5626  if (FindModuleFileExtensions) {
5627  BitstreamCursor SavedStream = Stream;
5628  while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5629  bool DoneWithExtensionBlock = false;
5630  while (!DoneWithExtensionBlock) {
5631  Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5632  if (!MaybeEntry) {
5633  // FIXME this drops the error.
5634  return true;
5635  }
5636  llvm::BitstreamEntry Entry = MaybeEntry.get();
5637 
5638  switch (Entry.Kind) {
5639  case llvm::BitstreamEntry::SubBlock:
5640  if (llvm::Error Err = Stream.SkipBlock()) {
5641  // FIXME this drops the error on the floor.
5642  consumeError(std::move(Err));
5643  return true;
5644  }
5645  continue;
5646 
5647  case llvm::BitstreamEntry::EndBlock:
5648  DoneWithExtensionBlock = true;
5649  continue;
5650 
5652  return true;
5653 
5655  break;
5656  }
5657 
5658  Record.clear();
5659  StringRef Blob;
5660  Expected<unsigned> MaybeRecCode =
5661  Stream.readRecord(Entry.ID, Record, &Blob);
5662  if (!MaybeRecCode) {
5663  // FIXME this drops the error.
5664  return true;
5665  }
5666  switch (MaybeRecCode.get()) {
5667  case EXTENSION_METADATA: {
5668  ModuleFileExtensionMetadata Metadata;
5669  if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5670  return true;
5671 
5672  Listener.readModuleFileExtension(Metadata);
5673  break;
5674  }
5675  }
5676  }
5677  }
5678  Stream = SavedStream;
5679  }
5680 
5681  // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5682  if (readUnhashedControlBlockImpl(
5683  nullptr, Bytes, ClientLoadCapabilities,
5684  /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5685  ValidateDiagnosticOptions) != Success)
5686  return true;
5687 
5688  return false;
5689 }
5690 
5692  const InMemoryModuleCache &ModuleCache,
5693  const PCHContainerReader &PCHContainerRdr,
5694  const LangOptions &LangOpts,
5695  const TargetOptions &TargetOpts,
5696  const PreprocessorOptions &PPOpts,
5697  StringRef ExistingModuleCachePath,
5698  bool RequireStrictOptionMatches) {
5699  SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5700  ExistingModuleCachePath, FileMgr,
5701  RequireStrictOptionMatches);
5702  return !readASTFileControlBlock(Filename, FileMgr, ModuleCache,
5703  PCHContainerRdr,
5704  /*FindModuleFileExtensions=*/false, validator,
5705  /*ValidateDiagnosticOptions=*/true);
5706 }
5707 
5708 llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
5709  unsigned ClientLoadCapabilities) {
5710  // Enter the submodule block.
5711  if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
5712  return Err;
5713 
5714  ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5715  bool First = true;
5716  Module *CurrentModule = nullptr;
5717  RecordData Record;
5718  while (true) {
5719  Expected<llvm::BitstreamEntry> MaybeEntry =
5720  F.Stream.advanceSkippingSubblocks();
5721  if (!MaybeEntry)
5722  return MaybeEntry.takeError();
5723  llvm::BitstreamEntry Entry = MaybeEntry.get();
5724 
5725  switch (Entry.Kind) {
5726  case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5728  return llvm::createStringError(std::errc::illegal_byte_sequence,
5729  "malformed block record in AST file");
5730  case llvm::BitstreamEntry::EndBlock:
5731  return llvm::Error::success();
5733  // The interesting case.
5734  break;
5735  }
5736 
5737  // Read a record.
5738  StringRef Blob;
5739  Record.clear();
5740  Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5741  if (!MaybeKind)
5742  return MaybeKind.takeError();
5743  unsigned Kind = MaybeKind.get();
5744 
5745  if ((Kind == SUBMODULE_METADATA) != First)
5746  return llvm::createStringError(
5747  std::errc::illegal_byte_sequence,
5748  "submodule metadata record should be at beginning of block");
5749  First = false;
5750 
5751  // Submodule information is only valid if we have a current module.
5752  // FIXME: Should we error on these cases?
5753  if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5755  continue;
5756 
5757  switch (Kind) {
5758  default: // Default behavior: ignore.
5759  break;
5760 
5761  case SUBMODULE_DEFINITION: {
5762  if (Record.size() < 13)
5763  return llvm::createStringError(std::errc::illegal_byte_sequence,
5764  "malformed module definition");
5765 
5766  StringRef Name = Blob;
5767  unsigned Idx = 0;
5768  SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5769  SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
5771  SourceLocation DefinitionLoc = ReadSourceLocation(F, Record[Idx++]);
5772  bool IsFramework = Record[Idx++];
5773  bool IsExplicit = Record[Idx++];
5774  bool IsSystem = Record[Idx++];
5775  bool IsExternC = Record[Idx++];
5776  bool InferSubmodules = Record[Idx++];
5777  bool InferExplicitSubmodules = Record[Idx++];
5778  bool InferExportWildcard = Record[Idx++];
5779  bool ConfigMacrosExhaustive = Record[Idx++];
5780  bool ModuleMapIsPrivate = Record[Idx++];
5781  bool NamedModuleHasInit = Record[Idx++];
5782 
5783  Module *ParentModule = nullptr;
5784  if (Parent)
5785  ParentModule = getSubmodule(Parent);
5786 
5787  // Retrieve this (sub)module from the module map, creating it if
5788  // necessary.
5789  CurrentModule =
5790  ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5791  .first;
5792 
5793  // FIXME: Call ModMap.setInferredModuleAllowedBy()
5794 
5795  SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5796  if (GlobalIndex >= SubmodulesLoaded.size() ||
5797  SubmodulesLoaded[GlobalIndex])
5798  return llvm::createStringError(std::errc::invalid_argument,
5799  "too many submodules");
5800 
5801  if (!ParentModule) {
5802  if (OptionalFileEntryRef CurFile = CurrentModule->getASTFile()) {
5803  // Don't emit module relocation error if we have -fno-validate-pch
5804  if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
5806  CurFile != F.File) {
5807  auto ConflictError =
5808  PartialDiagnostic(diag::err_module_file_conflict,
5809  ContextObj->DiagAllocator)
5810  << CurrentModule->getTopLevelModuleName() << CurFile->getName()
5811  << F.File.getName();
5812  return DiagnosticError::create(CurrentImportLoc, ConflictError);
5813  }
5814  }
5815 
5816  F.DidReadTopLevelSubmodule = true;
5817  CurrentModule->setASTFile(F.File);
5818  CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
5819  }
5820 
5821  CurrentModule->Kind = Kind;
5822  CurrentModule->DefinitionLoc = DefinitionLoc;
5823  CurrentModule->Signature = F.Signature;
5824  CurrentModule->IsFromModuleFile = true;
5825  CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
5826  CurrentModule->IsExternC = IsExternC;
5827  CurrentModule->InferSubmodules = InferSubmodules;
5828  CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5829  CurrentModule->InferExportWildcard = InferExportWildcard;
5830  CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
5831  CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
5832  CurrentModule->NamedModuleHasInit = NamedModuleHasInit;
5833  if (DeserializationListener)
5834  DeserializationListener->ModuleRead(GlobalID, CurrentModule);
5835 
5836  SubmodulesLoaded[GlobalIndex] = CurrentModule;
5837 
5838  // Clear out data that will be replaced by what is in the module file.
5839  CurrentModule->LinkLibraries.clear();
5840  CurrentModule->ConfigMacros.clear();
5841  CurrentModule->UnresolvedConflicts.clear();
5842  CurrentModule->Conflicts.clear();
5843 
5844  // The module is available unless it's missing a requirement; relevant
5845  // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5846  // Missing headers that were present when the module was built do not
5847  // make it unavailable -- if we got this far, this must be an explicitly
5848  // imported module file.
5849  CurrentModule->Requirements.clear();
5850  CurrentModule->MissingHeaders.clear();
5851  CurrentModule->IsUnimportable =
5852  ParentModule && ParentModule->IsUnimportable;
5853  CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
5854  break;
5855  }
5856 
5858  // FIXME: This doesn't work for framework modules as `Filename` is the
5859  // name as written in the module file and does not include
5860  // `Headers/`, so this path will never exist.
5861  std::string Filename = std::string(Blob);
5862  ResolveImportedPath(F, Filename);
5863  if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) {
5864  if (!CurrentModule->getUmbrellaHeaderAsWritten()) {
5865  // FIXME: NameAsWritten
5866  ModMap.setUmbrellaHeaderAsWritten(CurrentModule, *Umbrella, Blob, "");
5867  }
5868  // Note that it's too late at this point to return out of date if the
5869  // name from the PCM doesn't match up with the one in the module map,
5870  // but also quite unlikely since we will have already checked the
5871  // modification time and size of the module map file itself.
5872  }
5873  break;
5874  }
5875 
5876  case SUBMODULE_HEADER:
5879  // We lazily associate headers with their modules via the HeaderInfo table.
5880  // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5881  // of complete filenames or remove it entirely.
5882  break;
5883 
5886  // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5887  // them here.
5888  break;
5889 
5890  case SUBMODULE_TOPHEADER: {
5891  std::string HeaderName(Blob);
5892  ResolveImportedPath(F, HeaderName);
5893  CurrentModule->addTopHeaderFilename(HeaderName);
5894  break;
5895  }
5896 
5897  case SUBMODULE_UMBRELLA_DIR: {
5898  // See comments in SUBMODULE_UMBRELLA_HEADER
5899  std::string Dirname = std::string(Blob);
5900  ResolveImportedPath(F, Dirname);
5901  if (auto Umbrella =
5902  PP.getFileManager().getOptionalDirectoryRef(Dirname)) {
5903  if (!CurrentModule->getUmbrellaDirAsWritten()) {
5904  // FIXME: NameAsWritten
5905  ModMap.setUmbrellaDirAsWritten(CurrentModule, *Umbrella, Blob, "");
5906  }
5907  }
5908  break;
5909  }
5910 
5911  case SUBMODULE_METADATA: {
5912  F.BaseSubmoduleID = getTotalNumSubmodules();
5913  F.LocalNumSubmodules = Record[0];
5914  unsigned LocalBaseSubmoduleID = Record[1];
5915  if (F.LocalNumSubmodules > 0) {
5916  // Introduce the global -> local mapping for submodules within this
5917  // module.
5918  GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
5919 
5920  // Introduce the local -> global mapping for submodules within this
5921  // module.
5923  std::make_pair(LocalBaseSubmoduleID,
5924  F.BaseSubmoduleID - LocalBaseSubmoduleID));
5925 
5926  SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5927  }
5928  break;
5929  }
5930 
5931  case SUBMODULE_IMPORTS:
5932  for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5933  UnresolvedModuleRef Unresolved;
5934  Unresolved.File = &F;
5935  Unresolved.Mod = CurrentModule;
5936  Unresolved.ID = Record[Idx];
5937  Unresolved.Kind = UnresolvedModuleRef::Import;
5938  Unresolved.IsWildcard = false;
5939  UnresolvedModuleRefs.push_back(Unresolved);
5940  }
5941  break;
5942 
5944  for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5945  UnresolvedModuleRef Unresolved;
5946  Unresolved.File = &F;
5947  Unresolved.Mod = CurrentModule;
5948  Unresolved.ID = Record[Idx];
5949  Unresolved.Kind = UnresolvedModuleRef::Affecting;
5950  Unresolved.IsWildcard = false;
5951  UnresolvedModuleRefs.push_back(Unresolved);
5952  }
5953  break;
5954 
5955  case SUBMODULE_EXPORTS:
5956  for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
5957  UnresolvedModuleRef Unresolved;
5958  Unresolved.File = &F;
5959  Unresolved.Mod = CurrentModule;
5960  Unresolved.ID = Record[Idx];
5961  Unresolved.Kind = UnresolvedModuleRef::Export;
5962  Unresolved.IsWildcard = Record[Idx + 1];
5963  UnresolvedModuleRefs.push_back(Unresolved);
5964  }
5965 
5966  // Once we've loaded the set of exports, there's no reason to keep
5967  // the parsed, unresolved exports around.
5968  CurrentModule->UnresolvedExports.clear();
5969  break;
5970 
5971  case SUBMODULE_REQUIRES:
5972  CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5973  PP.getTargetInfo());
5974  break;
5975 
5977  ModMap.resolveLinkAsDependencies(CurrentModule);
5978  CurrentModule->LinkLibraries.push_back(
5979  Module::LinkLibrary(std::string(Blob), Record[0]));
5980  break;
5981 
5983  CurrentModule->ConfigMacros.push_back(Blob.str());
5984  break;
5985 
5986  case SUBMODULE_CONFLICT: {
5987  UnresolvedModuleRef Unresolved;
5988  Unresolved.File = &F;
5989  Unresolved.Mod = CurrentModule;
5990  Unresolved.ID = Record[0];
5991  Unresolved.Kind = UnresolvedModuleRef::Conflict;
5992  Unresolved.IsWildcard = false;
5993  Unresolved.String = Blob;
5994  UnresolvedModuleRefs.push_back(Unresolved);
5995  break;
5996  }
5997 
5998  case SUBMODULE_INITIALIZERS: {
5999  if (!ContextObj)
6000  break;
6002  for (auto &ID : Record)
6003  Inits.push_back(getGlobalDeclID(F, LocalDeclID(ID)));
6004  ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
6005  break;
6006  }
6007 
6008  case SUBMODULE_EXPORT_AS:
6009  CurrentModule->ExportAsModule = Blob.str();
6010  ModMap.addLinkAsDependency(CurrentModule);
6011  break;
6012  }
6013  }
6014 }
6015 
6016 /// Parse the record that corresponds to a LangOptions data
6017 /// structure.
6018 ///
6019 /// This routine parses the language options from the AST file and then gives
6020 /// them to the AST listener if one is set.
6021 ///
6022 /// \returns true if the listener deems the file unacceptable, false otherwise.
6023 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
6024  bool Complain,
6025  ASTReaderListener &Listener,
6026  bool AllowCompatibleDifferences) {
6027  LangOptions LangOpts;
6028  unsigned Idx = 0;
6029 #define LANGOPT(Name, Bits, Default, Description) \
6030  LangOpts.Name = Record[Idx++];
6031 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
6032  LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
6033 #include "clang/Basic/LangOptions.def"
6034 #define SANITIZER(NAME, ID) \
6035  LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
6036 #include "clang/Basic/Sanitizers.def"
6037 
6038  for (unsigned N = Record[Idx++]; N; --N)
6039  LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
6040 
6041  ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
6042  VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
6043  LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
6044 
6045  LangOpts.CurrentModule = ReadString(Record, Idx);
6046 
6047  // Comment options.
6048  for (unsigned N = Record[Idx++]; N; --N) {
6049  LangOpts.CommentOpts.BlockCommandNames.push_back(
6050  ReadString(Record, Idx));
6051  }
6052  LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
6053 
6054  // OpenMP offloading options.
6055  for (unsigned N = Record[Idx++]; N; --N) {
6056  LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
6057  }
6058 
6059  LangOpts.OMPHostIRFile = ReadString(Record, Idx);
6060 
6061  return Listener.ReadLanguageOptions(LangOpts, Complain,
6062  AllowCompatibleDifferences);
6063 }
6064 
6065 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
6066  ASTReaderListener &Listener,
6067  bool AllowCompatibleDifferences) {
6068  unsigned Idx = 0;
6069  TargetOptions TargetOpts;
6070  TargetOpts.Triple = ReadString(Record, Idx);
6071  TargetOpts.CPU = ReadString(Record, Idx);
6072  TargetOpts.TuneCPU = ReadString(Record, Idx);
6073  TargetOpts.ABI = ReadString(Record, Idx);
6074  for (unsigned N = Record[Idx++]; N; --N) {
6075  TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
6076  }
6077  for (unsigned N = Record[Idx++]; N; --N) {
6078  TargetOpts.Features.push_back(ReadString(Record, Idx));
6079  }
6080 
6081  return Listener.ReadTargetOptions(TargetOpts, Complain,
6082  AllowCompatibleDifferences);
6083 }
6084 
6085 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
6086  ASTReaderListener &Listener) {
6088  unsigned Idx = 0;
6089 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
6090 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
6091  DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
6092 #include "clang/Basic/DiagnosticOptions.def"
6093 
6094  for (unsigned N = Record[Idx++]; N; --N)
6095  DiagOpts->Warnings.push_back(ReadString(Record, Idx));
6096  for (unsigned N = Record[Idx++]; N; --N)
6097  DiagOpts->Remarks.push_back(ReadString(Record, Idx));
6098 
6099  return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
6100 }
6101 
6102 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
6103  ASTReaderListener &Listener) {
6104  FileSystemOptions FSOpts;
6105  unsigned Idx = 0;
6106  FSOpts.WorkingDir = ReadString(Record, Idx);
6107  return Listener.ReadFileSystemOptions(FSOpts, Complain);
6108 }
6109 
6110 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
6111  bool Complain,
6112  ASTReaderListener &Listener) {
6113  HeaderSearchOptions HSOpts;
6114  unsigned Idx = 0;
6115  HSOpts.Sysroot = ReadString(Record, Idx);
6116 
6117  HSOpts.ResourceDir = ReadString(Record, Idx);
6118  HSOpts.ModuleCachePath = ReadString(Record, Idx);
6119  HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
6120  HSOpts.DisableModuleHash = Record[Idx++];
6121  HSOpts.ImplicitModuleMaps = Record[Idx++];
6122  HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
6123  HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
6124  HSOpts.UseBuiltinIncludes = Record[Idx++];
6125  HSOpts.UseStandardSystemIncludes = Record[Idx++];
6126  HSOpts.UseStandardCXXIncludes = Record[Idx++];
6127  HSOpts.UseLibcxx = Record[Idx++];
6128  std::string SpecificModuleCachePath = ReadString(Record, Idx);
6129 
6130  return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
6131  Complain);
6132 }
6133 
6134 bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
6135  ASTReaderListener &Listener) {
6136  HeaderSearchOptions HSOpts;
6137  unsigned Idx = 0;
6138 
6139  // Include entries.
6140  for (unsigned N = Record[Idx++]; N; --N) {
6141  std::string Path = ReadString(Record, Idx);
6143  = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
6144  bool IsFramework = Record[Idx++];
6145  bool IgnoreSysRoot = Record[Idx++];
6146  HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
6147  IgnoreSysRoot);
6148  }
6149 
6150  // System header prefixes.
6151  for (unsigned N = Record[Idx++]; N; --N) {
6152  std::string Prefix = ReadString(Record, Idx);
6153  bool IsSystemHeader = Record[Idx++];
6154  HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
6155  }
6156 
6157  // VFS overlay files.
6158  for (unsigned N = Record[Idx++]; N; --N) {
6159  std::string VFSOverlayFile = ReadString(Record, Idx);
6160  HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
6161  }
6162 
6163  return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
6164 }
6165 
6166 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
6167  bool Complain,
6168  ASTReaderListener &Listener,
6169  std::string &SuggestedPredefines) {
6170  PreprocessorOptions PPOpts;
6171  unsigned Idx = 0;
6172 
6173  // Macro definitions/undefs
6174  bool ReadMacros = Record[Idx++];
6175  if (ReadMacros) {
6176  for (unsigned N = Record[Idx++]; N; --N) {
6177  std::string Macro = ReadString(Record, Idx);
6178  bool IsUndef = Record[Idx++];
6179  PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
6180  }
6181  }
6182 
6183  // Includes
6184  for (unsigned N = Record[Idx++]; N; --N) {
6185  PPOpts.Includes.push_back(ReadString(Record, Idx));
6186  }
6187 
6188  // Macro Includes
6189  for (unsigned N = Record[Idx++]; N; --N) {
6190  PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
6191  }
6192 
6193  PPOpts.UsePredefines = Record[Idx++];
6194  PPOpts.DetailedRecord = Record[Idx++];
6195  PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
6196  PPOpts.ObjCXXARCStandardLibrary =
6197  static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
6198  SuggestedPredefines.clear();
6199  return Listener.ReadPreprocessorOptions(PPOpts, ReadMacros, Complain,
6200  SuggestedPredefines);
6201 }
6202 
6203 std::pair<ModuleFile *, unsigned>
6204 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
6205  GlobalPreprocessedEntityMapType::iterator
6206  I = GlobalPreprocessedEntityMap.find(GlobalIndex);
6207  assert(I != GlobalPreprocessedEntityMap.end() &&
6208  "Corrupted global preprocessed entity map");
6209  ModuleFile *M = I->second;
6210  unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
6211  return std::make_pair(M, LocalIndex);
6212 }
6213 
6214 llvm::iterator_range<PreprocessingRecord::iterator>
6215 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
6216  if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
6217  return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
6219 
6220  return llvm::make_range(PreprocessingRecord::iterator(),
6222 }
6223 
6224 bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6225  unsigned int ClientLoadCapabilities) {
6226  return ClientLoadCapabilities & ARR_OutOfDate &&
6227  !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);
6228 }
6229 
6230 llvm::iterator_range<ASTReader::ModuleDeclIterator>
6232  return llvm::make_range(
6233  ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
6234  ModuleDeclIterator(this, &Mod,
6235  Mod.FileSortedDecls + Mod.NumFileSortedDecls));
6236 }
6237 
6239  auto I = GlobalSkippedRangeMap.find(GlobalIndex);
6240  assert(I != GlobalSkippedRangeMap.end() &&
6241  "Corrupted global skipped range map");
6242  ModuleFile *M = I->second;
6243  unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
6244  assert(LocalIndex < M->NumPreprocessedSkippedRanges);
6245  PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
6246  SourceRange Range(ReadSourceLocation(*M, RawRange.getBegin()),
6247  ReadSourceLocation(*M, RawRange.getEnd()));
6248  assert(Range.isValid());
6249  return Range;
6250 }
6251 
6253  PreprocessedEntityID PPID = Index+1;
6254  std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6255  ModuleFile &M = *PPInfo.first;
6256  unsigned LocalIndex = PPInfo.second;
6257  const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6258 
6259  if (!PP.getPreprocessingRecord()) {
6260  Error("no preprocessing record");
6261  return nullptr;
6262  }
6263 
6265  if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
6266  M.MacroOffsetsBase + PPOffs.getOffset())) {
6267  Error(std::move(Err));
6268  return nullptr;
6269  }
6270 
6271  Expected<llvm::BitstreamEntry> MaybeEntry =
6272  M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
6273  if (!MaybeEntry) {
6274  Error(MaybeEntry.takeError());
6275  return nullptr;
6276  }
6277  llvm::BitstreamEntry Entry = MaybeEntry.get();
6278 
6279  if (Entry.Kind != llvm::BitstreamEntry::Record)
6280  return nullptr;
6281 
6282  // Read the record.
6283  SourceRange Range(ReadSourceLocation(M, PPOffs.getBegin()),
6284  ReadSourceLocation(M, PPOffs.getEnd()));
6285  PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
6286  StringRef Blob;
6288  Expected<unsigned> MaybeRecType =
6289  M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
6290  if (!MaybeRecType) {
6291  Error(MaybeRecType.takeError());
6292  return nullptr;
6293  }
6294  switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
6295  case PPD_MACRO_EXPANSION: {
6296  bool isBuiltin = Record[0];
6297  IdentifierInfo *Name = nullptr;
6298  MacroDefinitionRecord *Def = nullptr;
6299  if (isBuiltin)
6300  Name = getLocalIdentifier(M, Record[1]);
6301  else {
6302  PreprocessedEntityID GlobalID =
6303  getGlobalPreprocessedEntityID(M, Record[1]);
6304  Def = cast<MacroDefinitionRecord>(
6305  PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
6306  }
6307 
6308  MacroExpansion *ME;
6309  if (isBuiltin)
6310  ME = new (PPRec) MacroExpansion(Name, Range);
6311  else
6312  ME = new (PPRec) MacroExpansion(Def, Range);
6313 
6314  return ME;
6315  }
6316 
6317  case PPD_MACRO_DEFINITION: {
6318  // Decode the identifier info and then check again; if the macro is
6319  // still defined and associated with the identifier,
6320  IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
6321  MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
6322 
6323  if (DeserializationListener)
6324  DeserializationListener->MacroDefinitionRead(PPID, MD);
6325 
6326  return MD;
6327  }
6328 
6329  case PPD_INCLUSION_DIRECTIVE: {
6330  const char *FullFileNameStart = Blob.data() + Record[0];
6331  StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6333  if (!FullFileName.empty())
6334  File = PP.getFileManager().getOptionalFileRef(FullFileName);
6335 
6336  // FIXME: Stable encoding
6338  = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6340  = new (PPRec) InclusionDirective(PPRec, Kind,
6341  StringRef(Blob.data(), Record[0]),
6342  Record[1], Record[3],
6343  File,
6344  Range);
6345  return ID;
6346  }
6347  }
6348 
6349  llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6350 }
6351 
6352 /// Find the next module that contains entities and return the ID
6353 /// of the first entry.
6354 ///
6355 /// \param SLocMapI points at a chunk of a module that contains no
6356 /// preprocessed entities or the entities it contains are not the ones we are
6357 /// looking for.
6358 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6359  GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6360  ++SLocMapI;
6361  for (GlobalSLocOffsetMapType::const_iterator
6362  EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6363  ModuleFile &M = *SLocMapI->second;
6365  return M.BasePreprocessedEntityID;
6366  }
6367 
6368  return getTotalNumPreprocessedEntities();
6369 }
6370 
6371 namespace {
6372 
6373 struct PPEntityComp {
6374  const ASTReader &Reader;
6375  ModuleFile &M;
6376 
6377  PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6378 
6379  bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6380  SourceLocation LHS = getLoc(L);
6381  SourceLocation RHS = getLoc(R);
6382  return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6383  }
6384 
6385  bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6386  SourceLocation LHS = getLoc(L);
6387  return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6388  }
6389 
6390  bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6391  SourceLocation RHS = getLoc(R);
6392  return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6393  }
6394 
6395  SourceLocation getLoc(const PPEntityOffset &PPE) const {
6396  return Reader.ReadSourceLocation(M, PPE.getBegin());
6397  }
6398 };
6399 
6400 } // namespace
6401 
6402 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6403  bool EndsAfter) const {
6404  if (SourceMgr.isLocalSourceLocation(Loc))
6405  return getTotalNumPreprocessedEntities();
6406 
6407  GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6408  SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6409  assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6410  "Corrupted global sloc offset map");
6411 
6412  if (SLocMapI->second->NumPreprocessedEntities == 0)
6413  return findNextPreprocessedEntity(SLocMapI);
6414 
6415  ModuleFile &M = *SLocMapI->second;
6416 
6417  using pp_iterator = const PPEntityOffset *;
6418 
6419  pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6420  pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6421 
6422  size_t Count = M.NumPreprocessedEntities;
6423  size_t Half;
6424  pp_iterator First = pp_begin;
6425  pp_iterator PPI;
6426 
6427  if (EndsAfter) {
6428  PPI = std::upper_bound(pp_begin, pp_end, Loc,
6429  PPEntityComp(*this, M));
6430  } else {
6431  // Do a binary search manually instead of using std::lower_bound because
6432  // The end locations of entities may be unordered (when a macro expansion
6433  // is inside another macro argument), but for this case it is not important
6434  // whether we get the first macro expansion or its containing macro.
6435  while (Count > 0) {
6436  Half = Count / 2;
6437  PPI = First;
6438  std::advance(PPI, Half);
6439  if (SourceMgr.isBeforeInTranslationUnit(
6440  ReadSourceLocation(M, PPI->getEnd()), Loc)) {
6441  First = PPI;
6442  ++First;
6443  Count = Count - Half - 1;
6444  } else
6445  Count = Half;
6446  }
6447  }
6448 
6449  if (PPI == pp_end)
6450  return findNextPreprocessedEntity(SLocMapI);
6451 
6452  return M.BasePreprocessedEntityID + (PPI - pp_begin);
6453 }
6454 
6455 /// Returns a pair of [Begin, End) indices of preallocated
6456 /// preprocessed entities that \arg Range encompasses.
6457 std::pair<unsigned, unsigned>
6459  if (Range.isInvalid())
6460  return std::make_pair(0,0);
6461  assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6462 
6463  PreprocessedEntityID BeginID =
6464  findPreprocessedEntity(Range.getBegin(), false);
6465  PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
6466  return std::make_pair(BeginID, EndID);
6467 }
6468 
6469 /// Optionally returns true or false if the preallocated preprocessed
6470 /// entity with index \arg Index came from file \arg FID.
6471 std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6472  FileID FID) {
6473  if (FID.isInvalid())
6474  return false;
6475 
6476  std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6477  ModuleFile &M = *PPInfo.first;
6478  unsigned LocalIndex = PPInfo.second;
6479  const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6480 
6481  SourceLocation Loc = ReadSourceLocation(M, PPOffs.getBegin());
6482  if (Loc.isInvalid())
6483  return false;
6484 
6485  if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6486  return true;
6487  else
6488  return false;
6489 }
6490 
6491 namespace {
6492 
6493  /// Visitor used to search for information about a header file.
6494  class HeaderFileInfoVisitor {
6495  FileEntryRef FE;
6496  std::optional<HeaderFileInfo> HFI;
6497 
6498  public:
6499  explicit HeaderFileInfoVisitor(FileEntryRef FE) : FE(FE) {}
6500 
6501  bool operator()(ModuleFile &M) {
6503  = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
6504  if (!Table)
6505  return false;
6506 
6507  // Look in the on-disk hash table for an entry for this file name.
6508  HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
6509  if (Pos == Table->end())
6510  return false;
6511 
6512  HFI = *Pos;
6513  return true;
6514  }
6515 
6516  std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
6517  };
6518 
6519 } // namespace
6520 
6522  HeaderFileInfoVisitor Visitor(FE);
6523  ModuleMgr.visit(Visitor);
6524  if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
6525  return *HFI;
6526 
6527  return HeaderFileInfo();
6528 }
6529 
6531  using DiagState = DiagnosticsEngine::DiagState;
6532  SmallVector<DiagState *, 32> DiagStates;
6533 
6534  for (ModuleFile &F : ModuleMgr) {
6535  unsigned Idx = 0;
6536  auto &Record = F.PragmaDiagMappings;
6537  if (Record.empty())
6538  continue;
6539 
6540  DiagStates.clear();
6541 
6542  auto ReadDiagState = [&](const DiagState &BasedOn,
6543  bool IncludeNonPragmaStates) {
6544  unsigned BackrefID = Record[Idx++];
6545  if (BackrefID != 0)
6546  return DiagStates[BackrefID - 1];
6547 
6548  // A new DiagState was created here.
6549  Diag.DiagStates.push_back(BasedOn);
6550  DiagState *NewState = &Diag.DiagStates.back();
6551  DiagStates.push_back(NewState);
6552  unsigned Size = Record[Idx++];
6553  assert(Idx + Size * 2 <= Record.size() &&
6554  "Invalid data, not enough diag/map pairs");
6555  while (Size--) {
6556  unsigned DiagID = Record[Idx++];
6557  DiagnosticMapping NewMapping =
6559  if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6560  continue;
6561 
6562  DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6563 
6564  // If this mapping was specified as a warning but the severity was
6565  // upgraded due to diagnostic settings, simulate the current diagnostic
6566  // settings (and use a warning).
6567  if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6569  NewMapping.setUpgradedFromWarning(false);
6570  }
6571 
6572  Mapping = NewMapping;
6573  }
6574  return NewState;
6575  };
6576 
6577  // Read the first state.
6578  DiagState *FirstState;
6579  if (F.Kind == MK_ImplicitModule) {
6580  // Implicitly-built modules are reused with different diagnostic
6581  // settings. Use the initial diagnostic state from Diag to simulate this
6582  // compilation's diagnostic settings.
6583  FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6584  DiagStates.push_back(FirstState);
6585 
6586  // Skip the initial diagnostic state from the serialized module.
6587  assert(Record[1] == 0 &&
6588  "Invalid data, unexpected backref in initial state");
6589  Idx = 3 + Record[2] * 2;
6590  assert(Idx < Record.size() &&
6591  "Invalid data, not enough state change pairs in initial state");
6592  } else if (F.isModule()) {
6593  // For an explicit module, preserve the flags from the module build
6594  // command line (-w, -Weverything, -Werror, ...) along with any explicit
6595  // -Wblah flags.
6596  unsigned Flags = Record[Idx++];
6597  DiagState Initial;
6598  Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6599  Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6600  Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6601  Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6602  Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6603  Initial.ExtBehavior = (diag::Severity)Flags;
6604  FirstState = ReadDiagState(Initial, true);
6605 
6606  assert(F.OriginalSourceFileID.isValid());
6607 
6608  // Set up the root buffer of the module to start with the initial
6609  // diagnostic state of the module itself, to cover files that contain no
6610  // explicit transitions (for which we did not serialize anything).
6611  Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6612  .StateTransitions.push_back({FirstState, 0});
6613  } else {
6614  // For prefix ASTs, start with whatever the user configured on the
6615  // command line.
6616  Idx++; // Skip flags.
6617  FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
6618  }
6619 
6620  // Read the state transitions.
6621  unsigned NumLocations = Record[Idx++];
6622  while (NumLocations--) {
6623  assert(Idx < Record.size() &&
6624  "Invalid data, missing pragma diagnostic states");
6625  FileID FID = ReadFileID(F, Record, Idx);
6626  assert(FID.isValid() && "invalid FileID for transition");
6627  unsigned Transitions = Record[Idx++];
6628 
6629  // Note that we don't need to set up Parent/ParentOffset here, because
6630  // we won't be changing the diagnostic state within imported FileIDs
6631  // (other than perhaps appending to the main source file, which has no
6632  // parent).
6633  auto &F = Diag.DiagStatesByLoc.Files[FID];
6634  F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6635  for (unsigned I = 0; I != Transitions; ++I) {
6636  unsigned Offset = Record[Idx++];
6637  auto *State = ReadDiagState(*FirstState, false);
6638  F.StateTransitions.push_back({State, Offset});
6639  }
6640  }
6641 
6642  // Read the final state.
6643  assert(Idx < Record.size() &&
6644  "Invalid data, missing final pragma diagnostic state");
6645  SourceLocation CurStateLoc = ReadSourceLocation(F, Record[Idx++]);
6646  auto *CurState = ReadDiagState(*FirstState, false);
6647 
6648  if (!F.isModule()) {
6649  Diag.DiagStatesByLoc.CurDiagState = CurState;
6650  Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6651 
6652  // Preserve the property that the imaginary root file describes the
6653  // current state.
6654  FileID NullFile;
6655  auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
6656  if (T.empty())
6657  T.push_back({CurState, 0});
6658  else
6659  T[0].State = CurState;
6660  }
6661 
6662  // Don't try to read these mappings again.
6663  Record.clear();
6664  }
6665 }
6666 
6667 /// Get the correct cursor and offset for loading a type.
6668 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6669  GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6670  assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6671  ModuleFile *M = I->second;
6672  return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex].get() +
6674 }
6675 
6676 static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6677  switch (code) {
6678 #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6679  case TYPE_##CODE_ID: return Type::CLASS_ID;
6680 #include "clang/Serialization/TypeBitCodes.def"
6681  default:
6682  return std::nullopt;
6683  }
6684 }
6685 
6686 /// Read and return the type with the given index..
6687 ///
6688 /// The index is the type ID, shifted and minus the number of predefs. This
6689 /// routine actually reads the record corresponding to the type at the given
6690 /// location. It is a helper routine for GetType, which deals with reading type
6691 /// IDs.
6692 QualType ASTReader::readTypeRecord(unsigned Index) {
6693  assert(ContextObj && "reading type with no AST context");
6694  ASTContext &Context = *ContextObj;
6695  RecordLocation Loc = TypeCursorForIndex(Index);
6696  BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
6697 
6698  // Keep track of where we are in the stream, then jump back there
6699  // after reading this type.
6700  SavedStreamPosition SavedPosition(DeclsCursor);
6701 
6702  ReadingKindTracker ReadingKind(Read_Type, *this);
6703 
6704  // Note that we are loading a type record.
6705  Deserializing AType(this);
6706 
6707  if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6708  Error(std::move(Err));
6709  return QualType();
6710  }
6711  Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6712  if (!RawCode) {
6713  Error(RawCode.takeError());
6714  return QualType();
6715  }
6716 
6717  ASTRecordReader Record(*this, *Loc.F);
6718  Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6719  if (!Code) {
6720  Error(Code.takeError());
6721  return QualType();
6722  }
6723  if (Code.get() == TYPE_EXT_QUAL) {
6724  QualType baseType = Record.readQualType();
6725  Qualifiers quals = Record.readQualifiers();
6726  return Context.getQualifiedType(baseType, quals);
6727  }
6728 
6729  auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6730  if (!maybeClass) {
6731  Error("Unexpected code for type");
6732  return QualType();
6733  }
6734 
6736  return TypeReader.read(*maybeClass);
6737 }
6738 
6739 namespace clang {
6740 
6741 class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6743 
6744  ASTRecordReader &Reader;
6745  LocSeq *Seq;
6746 
6747  SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); }
6748  SourceRange readSourceRange() { return Reader.readSourceRange(Seq); }
6749 
6750  TypeSourceInfo *GetTypeSourceInfo() {
6751  return Reader.readTypeSourceInfo();
6752  }
6753 
6754  NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6755  return Reader.readNestedNameSpecifierLoc();
6756  }
6757 
6758  Attr *ReadAttr() {
6759  return Reader.readAttr();
6760  }
6761 
6762 public:
6764  : Reader(Reader), Seq(Seq) {}
6765 
6766  // We want compile-time assurance that we've enumerated all of
6767  // these, so unfortunately we have to declare them first, then
6768  // define them out-of-line.
6769 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6770 #define TYPELOC(CLASS, PARENT) \
6771  void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6772 #include "clang/AST/TypeLocNodes.def"
6773 
6774  void VisitFunctionTypeLoc(FunctionTypeLoc);
6775  void VisitArrayTypeLoc(ArrayTypeLoc);
6776 };
6777 
6778 } // namespace clang
6779 
6780 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6781  // nothing to do
6782 }
6783 
6784 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6785  TL.setBuiltinLoc(readSourceLocation());
6786  if (TL.needsExtraLocalData()) {
6787  TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6788  TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
6789  TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
6790  TL.setModeAttr(Reader.readInt());
6791  }
6792 }
6793 
6794 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6795  TL.setNameLoc(readSourceLocation());
6796 }
6797 
6798 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6799  TL.setStarLoc(readSourceLocation());
6800 }
6801 
6802 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6803  // nothing to do
6804 }
6805 
6806 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6807  // nothing to do
6808 }
6809 
6810 void TypeLocReader::VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6811  // nothing to do
6812 }
6813 
6814 void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6815  TL.setExpansionLoc(readSourceLocation());
6816 }
6817 
6818 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6819  TL.setCaretLoc(readSourceLocation());
6820 }
6821 
6822 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6823  TL.setAmpLoc(readSourceLocation());
6824 }
6825 
6826 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6827  TL.setAmpAmpLoc(readSourceLocation());
6828 }
6829 
6830 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6831  TL.setStarLoc(readSourceLocation());
6832  TL.setClassTInfo(GetTypeSourceInfo());
6833 }
6834 
6836  TL.setLBracketLoc(readSourceLocation());
6837  TL.setRBracketLoc(readSourceLocation());
6838  if (Reader.readBool())
6839  TL.setSizeExpr(Reader.readExpr());
6840  else
6841  TL.setSizeExpr(nullptr);
6842 }
6843 
6844 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6845  VisitArrayTypeLoc(TL);
6846 }
6847 
6848 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6849  VisitArrayTypeLoc(TL);
6850 }
6851 
6852 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6853  VisitArrayTypeLoc(TL);
6854 }
6855 
6856 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6858  VisitArrayTypeLoc(TL);
6859 }
6860 
6861 void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6863 
6864  TL.setAttrNameLoc(readSourceLocation());
6865  TL.setAttrOperandParensRange(readSourceRange());
6866  TL.setAttrExprOperand(Reader.readExpr());
6867 }
6868 
6869 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6871  TL.setNameLoc(readSourceLocation());
6872 }
6873 
6874 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6875  TL.setNameLoc(readSourceLocation());
6876 }
6877 
6878 void TypeLocReader::VisitDependentVectorTypeLoc(
6880  TL.setNameLoc(readSourceLocation());
6881 }
6882 
6883 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6884  TL.setNameLoc(readSourceLocation());
6885 }
6886 
6887 void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
6888  TL.setAttrNameLoc(readSourceLocation());
6889  TL.setAttrOperandParensRange(readSourceRange());
6890  TL.setAttrRowOperand(Reader.readExpr());
6891  TL.setAttrColumnOperand(Reader.readExpr());
6892 }
6893 
6894 void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
6896  TL.setAttrNameLoc(readSourceLocation());
6897  TL.setAttrOperandParensRange(readSourceRange());
6898  TL.setAttrRowOperand(Reader.readExpr());
6899  TL.setAttrColumnOperand(Reader.readExpr());
6900 }
6901 
6903  TL.setLocalRangeBegin(readSourceLocation());
6904  TL.setLParenLoc(readSourceLocation());
6905  TL.setRParenLoc(readSourceLocation());
6906  TL.setExceptionSpecRange(readSourceRange());
6907  TL.setLocalRangeEnd(readSourceLocation());
6908  for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6909  TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
6910  }
6911 }
6912 
6913 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6914  VisitFunctionTypeLoc(TL);
6915 }
6916 
6917 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6918  VisitFunctionTypeLoc(TL);
6919 }
6920 
6921 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6922  TL.setNameLoc(readSourceLocation());
6923 }
6924 
6925 void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
6926  TL.setNameLoc(readSourceLocation());
6927 }
6928 
6929 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6930  TL.setNameLoc(readSourceLocation());
6931 }
6932 
6933 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6934  TL.setTypeofLoc(readSourceLocation());
6935  TL.setLParenLoc(readSourceLocation());
6936  TL.setRParenLoc(readSourceLocation());
6937 }
6938 
6939 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6940  TL.setTypeofLoc(readSourceLocation());
6941  TL.setLParenLoc(readSourceLocation());
6942  TL.setRParenLoc(readSourceLocation());
6943  TL.setUnmodifiedTInfo(GetTypeSourceInfo());
6944 }
6945 
6946 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6947  TL.setDecltypeLoc(readSourceLocation());
6948  TL.setRParenLoc(readSourceLocation());
6949 }
6950 
6951 void TypeLocReader::VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
6952  TL.setEllipsisLoc(readSourceLocation());
6953 }
6954 
6955 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6956  TL.setKWLoc(readSourceLocation());
6957  TL.setLParenLoc(readSourceLocation());
6958  TL.setRParenLoc(readSourceLocation());
6959  TL.setUnderlyingTInfo(GetTypeSourceInfo());
6960 }
6961 
6963  auto NNS = readNestedNameSpecifierLoc();
6964  auto TemplateKWLoc = readSourceLocation();
6965  auto ConceptNameLoc = readDeclarationNameInfo();
6966  auto FoundDecl = readDeclAs<NamedDecl>();
6967  auto NamedConcept = readDeclAs<ConceptDecl>();
6968  auto *CR = ConceptReference::Create(
6969  getContext(), NNS, TemplateKWLoc, ConceptNameLoc, FoundDecl, NamedConcept,
6970  (readBool() ? readASTTemplateArgumentListInfo() : nullptr));
6971  return CR;
6972 }
6973 
6974 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6975  TL.setNameLoc(readSourceLocation());
6976  if (Reader.readBool())
6977  TL.setConceptReference(Reader.readConceptReference());
6978  if (Reader.readBool())
6979  TL.setRParenLoc(readSourceLocation());
6980 }
6981 
6982 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6984  TL.setTemplateNameLoc(readSourceLocation());
6985 }
6986 
6987 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6988  TL.setNameLoc(readSourceLocation());
6989 }
6990 
6991 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6992  TL.setNameLoc(readSourceLocation());
6993 }
6994 
6995 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6996  TL.setAttr(ReadAttr());
6997 }
6998 
6999 void TypeLocReader::VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
7000  // Nothing to do
7001 }
7002 
7003 void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
7004  // Nothing to do.
7005 }
7006 
7007 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
7008  TL.setNameLoc(readSourceLocation());
7009 }
7010 
7011 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7013  TL.setNameLoc(readSourceLocation());
7014 }
7015 
7016 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7018  TL.setNameLoc(readSourceLocation());
7019 }
7020 
7021 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7023  TL.setTemplateKeywordLoc(readSourceLocation());
7024  TL.setTemplateNameLoc(readSourceLocation());
7025  TL.setLAngleLoc(readSourceLocation());
7026  TL.setRAngleLoc(readSourceLocation());
7027  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
7028  TL.setArgLocInfo(i,
7029  Reader.readTemplateArgumentLocInfo(
7030  TL.getTypePtr()->template_arguments()[i].getKind()));
7031 }
7032 
7033 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
7034  TL.setLParenLoc(readSourceLocation());
7035  TL.setRParenLoc(readSourceLocation());
7036 }
7037 
7038 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
7039  TL.setElaboratedKeywordLoc(readSourceLocation());
7040  TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7041 }
7042 
7043 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
7044  TL.setNameLoc(readSourceLocation());
7045 }
7046 
7047 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
7048  TL.setElaboratedKeywordLoc(readSourceLocation());
7049  TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7050  TL.setNameLoc(readSourceLocation());
7051 }
7052 
7053 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
7055  TL.setElaboratedKeywordLoc(readSourceLocation());
7056  TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
7057  TL.setTemplateKeywordLoc(readSourceLocation());
7058  TL.setTemplateNameLoc(readSourceLocation());
7059  TL.setLAngleLoc(readSourceLocation());
7060  TL.setRAngleLoc(readSourceLocation());
7061  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
7062  TL.setArgLocInfo(I,
7063  Reader.readTemplateArgumentLocInfo(
7064  TL.getTypePtr()->template_arguments()[I].getKind()));
7065 }
7066 
7067 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
7068  TL.setEllipsisLoc(readSourceLocation());
7069 }
7070 
7071 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
7072  TL.setNameLoc(readSourceLocation());
7073  TL.setNameEndLoc(readSourceLocation());
7074 }
7075 
7076 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7077  if (TL.getNumProtocols()) {
7078  TL.setProtocolLAngleLoc(readSourceLocation());
7079  TL.setProtocolRAngleLoc(readSourceLocation());
7080  }
7081  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7082  TL.setProtocolLoc(i, readSourceLocation());
7083 }
7084 
7085 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
7086  TL.setHasBaseTypeAsWritten(Reader.readBool());
7087  TL.setTypeArgsLAngleLoc(readSourceLocation());
7088  TL.setTypeArgsRAngleLoc(readSourceLocation());
7089  for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
7090  TL.setTypeArgTInfo(i, GetTypeSourceInfo());
7091  TL.setProtocolLAngleLoc(readSourceLocation());
7092  TL.setProtocolRAngleLoc(readSourceLocation());
7093  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
7094  TL.setProtocolLoc(i, readSourceLocation());
7095 }
7096 
7097 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
7098  TL.setStarLoc(readSourceLocation());
7099 }
7100 
7101 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
7102  TL.setKWLoc(readSourceLocation());
7103  TL.setLParenLoc(readSourceLocation());
7104  TL.setRParenLoc(readSourceLocation());
7105 }
7106 
7107 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
7108  TL.setKWLoc(readSourceLocation());
7109 }
7110 
7111 void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
7112  TL.setNameLoc(readSourceLocation());
7113 }
7114 void TypeLocReader::VisitDependentBitIntTypeLoc(
7116  TL.setNameLoc(readSourceLocation());
7117 }
7118 
7120  LocSeq::State Seq(ParentSeq);
7121  TypeLocReader TLR(*this, Seq);
7122  for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7123  TLR.Visit(TL);
7124 }
7125 
7127  QualType InfoTy = readType();
7128  if (InfoTy.isNull())
7129  return nullptr;
7130 
7131  TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
7132  readTypeLoc(TInfo->getTypeLoc());
7133  return TInfo;
7134 }
7135 
7137  assert(ContextObj && "reading type with no AST context");
7138  ASTContext &Context = *ContextObj;
7139 
7140  unsigned FastQuals = ID & Qualifiers::FastMask;
7141  unsigned Index = ID >> Qualifiers::FastWidth;
7142 
7143  if (Index < NUM_PREDEF_TYPE_IDS) {
7144  QualType T;
7145  switch ((PredefinedTypeIDs)Index) {
7146  case PREDEF_TYPE_LAST_ID:
7147  // We should never use this one.
7148  llvm_unreachable("Invalid predefined type");
7149  break;
7150  case PREDEF_TYPE_NULL_ID:
7151  return QualType();
7152  case PREDEF_TYPE_VOID_ID:
7153  T = Context.VoidTy;
7154  break;
7155  case PREDEF_TYPE_BOOL_ID:
7156  T = Context.BoolTy;
7157  break;
7158  case PREDEF_TYPE_CHAR_U_ID:
7159  case PREDEF_TYPE_CHAR_S_ID:
7160  // FIXME: Check that the signedness of CharTy is correct!
7161  T = Context.CharTy;
7162  break;
7163  case PREDEF_TYPE_UCHAR_ID:
7164  T = Context.UnsignedCharTy;
7165  break;
7166  case PREDEF_TYPE_USHORT_ID:
7167  T = Context.UnsignedShortTy;
7168  break;
7169  case PREDEF_TYPE_UINT_ID:
7170  T = Context.UnsignedIntTy;
7171  break;
7172  case PREDEF_TYPE_ULONG_ID:
7173  T = Context.UnsignedLongTy;
7174  break;
7176  T = Context.UnsignedLongLongTy;
7177  break;
7179  T = Context.UnsignedInt128Ty;
7180  break;
7181  case PREDEF_TYPE_SCHAR_ID:
7182  T = Context.SignedCharTy;
7183  break;
7184  case PREDEF_TYPE_WCHAR_ID:
7185  T = Context.WCharTy;
7186  break;
7187  case PREDEF_TYPE_SHORT_ID:
7188  T = Context.ShortTy;
7189  break;
7190  case PREDEF_TYPE_INT_ID:
7191  T = Context.IntTy;
7192  break;
7193  case PREDEF_TYPE_LONG_ID:
7194  T = Context.LongTy;
7195  break;
7197  T = Context.LongLongTy;
7198  break;
7199  case PREDEF_TYPE_INT128_ID:
7200  T = Context.Int128Ty;
7201  break;
7203  T = Context.BFloat16Ty;
7204  break;
7205  case PREDEF_TYPE_HALF_ID:
7206  T = Context.HalfTy;
7207  break;
7208  case PREDEF_TYPE_FLOAT_ID:
7209  T = Context.FloatTy;
7210  break;
7211  case PREDEF_TYPE_DOUBLE_ID:
7212  T = Context.DoubleTy;
7213  break;
7215  T = Context.LongDoubleTy;
7216  break;
7218  T = Context.ShortAccumTy;
7219  break;
7220  case PREDEF_TYPE_ACCUM_ID:
7221  T = Context.AccumTy;
7222  break;
7224  T = Context.LongAccumTy;
7225  break;
7227  T = Context.UnsignedShortAccumTy;
7228  break;
7229  case PREDEF_TYPE_UACCUM_ID:
7230  T = Context.UnsignedAccumTy;
7231  break;
7233  T = Context.UnsignedLongAccumTy;
7234  break;
7236  T = Context.ShortFractTy;
7237  break;
7238  case PREDEF_TYPE_FRACT_ID:
7239  T = Context.FractTy;
7240  break;
7242  T = Context.LongFractTy;
7243  break;
7245  T = Context.UnsignedShortFractTy;
7246  break;
7247  case PREDEF_TYPE_UFRACT_ID:
7248  T = Context.UnsignedFractTy;
7249  break;
7251  T = Context.UnsignedLongFractTy;
7252  break;
7254  T = Context.SatShortAccumTy;
7255  break;
7257  T = Context.SatAccumTy;
7258  break;
7260  T = Context.SatLongAccumTy;
7261  break;
7263  T = Context.SatUnsignedShortAccumTy;
7264  break;
7266  T = Context.SatUnsignedAccumTy;
7267  break;
7269  T = Context.SatUnsignedLongAccumTy;
7270  break;
7272  T = Context.SatShortFractTy;
7273  break;
7275  T = Context.SatFractTy;
7276  break;
7278  T = Context.SatLongFractTy;
7279  break;
7281  T = Context.SatUnsignedShortFractTy;
7282  break;
7284  T = Context.SatUnsignedFractTy;
7285  break;
7287  T = Context.SatUnsignedLongFractTy;
7288  break;
7290  T = Context.Float16Ty;
7291  break;
7293  T = Context.Float128Ty;
7294  break;
7295  case PREDEF_TYPE_IBM128_ID:
7296  T = Context.Ibm128Ty;
7297  break;
7299  T = Context.OverloadTy;
7300  break;
7302  T = Context.UnresolvedTemplateTy;
7303  break;
7305  T = Context.BoundMemberTy;
7306  break;
7308  T = Context.PseudoObjectTy;
7309  break;
7311  T = Context.DependentTy;
7312  break;
7314  T = Context.UnknownAnyTy;
7315  break;
7317  T = Context.NullPtrTy;
7318  break;
7319  case PREDEF_TYPE_CHAR8_ID:
7320  T = Context.Char8Ty;
7321  break;
7322  case PREDEF_TYPE_CHAR16_ID:
7323  T = Context.Char16Ty;
7324  break;
7325  case PREDEF_TYPE_CHAR32_ID:
7326  T = Context.Char32Ty;
7327  break;
7328  case PREDEF_TYPE_OBJC_ID:
7329  T = Context.ObjCBuiltinIdTy;
7330  break;
7332  T = Context.ObjCBuiltinClassTy;
7333  break;
7334  case PREDEF_TYPE_OBJC_SEL:
7335  T = Context.ObjCBuiltinSelTy;
7336  break;
7337 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7338  case PREDEF_TYPE_##Id##_ID: \
7339  T = Context.SingletonId; \
7340  break;
7341 #include "clang/Basic/OpenCLImageTypes.def"
7342 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7343  case PREDEF_TYPE_SAMPLED_##Id##_ID: \
7344  T = Context.Sampled##SingletonId; \
7345  break;
7346 #define IMAGE_WRITE_TYPE(Type, Id, Ext)
7347 #define IMAGE_READ_WRITE_TYPE(Type, Id, Ext)
7348 #include "clang/Basic/OpenCLImageTypes.def"
7349 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7350  case PREDEF_TYPE_##Id##_ID: \
7351  T = Context.Id##Ty; \
7352  break;
7353 #include "clang/Basic/OpenCLExtensionTypes.def"
7355  T = Context.OCLSamplerTy;
7356  break;
7357  case PREDEF_TYPE_EVENT_ID:
7358  T = Context.OCLEventTy;
7359  break;
7361  T = Context.OCLClkEventTy;
7362  break;
7363  case PREDEF_TYPE_QUEUE_ID:
7364  T = Context.OCLQueueTy;
7365  break;
7367  T = Context.OCLReserveIDTy;
7368  break;
7370  T = Context.getAutoDeductType();
7371  break;
7373  T = Context.getAutoRRefDeductType();
7374  break;
7376  T = Context.ARCUnbridgedCastTy;
7377  break;
7379  T = Context.BuiltinFnTy;
7380  break;
7382  T = Context.IncompleteMatrixIdxTy;
7383  break;
7385  T = Context.ArraySectionTy;
7386  break;
7388  T = Context.OMPArrayShapingTy;
7389  break;
7391  T = Context.OMPIteratorTy;
7392  break;
7393 #define SVE_TYPE(Name, Id, SingletonId) \
7394  case PREDEF_TYPE_##Id##_ID: \
7395  T = Context.SingletonId; \
7396  break;
7397 #include "clang/Basic/AArch64SVEACLETypes.def"
7398 #define PPC_VECTOR_TYPE(Name, Id, Size) \
7399  case PREDEF_TYPE_##Id##_ID: \
7400  T = Context.Id##Ty; \
7401  break;
7402 #include "clang/Basic/PPCTypes.def"
7403 #define RVV_TYPE(Name, Id, SingletonId) \
7404  case PREDEF_TYPE_##Id##_ID: \
7405  T = Context.SingletonId; \
7406  break;
7407 #include "clang/Basic/RISCVVTypes.def"
7408 #define WASM_TYPE(Name, Id, SingletonId) \
7409  case PREDEF_TYPE_##Id##_ID: \
7410  T = Context.SingletonId; \
7411  break;
7412 #include "clang/Basic/WebAssemblyReferenceTypes.def"
7413  }
7414 
7415  assert(!T.isNull() && "Unknown predefined type");
7416  return T.withFastQualifiers(FastQuals);
7417  }
7418 
7419  Index -= NUM_PREDEF_TYPE_IDS;
7420  assert(Index < TypesLoaded.size() && "Type index out-of-range");
7421  if (TypesLoaded[Index].isNull()) {
7422  TypesLoaded[Index] = readTypeRecord(Index);
7423  if (TypesLoaded[Index].isNull())
7424  return QualType();
7425 
7426  TypesLoaded[Index]->setFromAST();
7427  if (DeserializationListener)
7428  DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7429  TypesLoaded[Index]);
7430  }
7431 
7432  return TypesLoaded[Index].withFastQualifiers(FastQuals);
7433 }
7434 
7436  return GetType(getGlobalTypeID(F, LocalID));
7437 }
7438 
7440 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7441  unsigned FastQuals = LocalID & Qualifiers::FastMask;
7442  unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
7443 
7444  if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7445  return LocalID;
7446 
7447  if (!F.ModuleOffsetMap.empty())
7448  ReadModuleOffsetMap(F);
7449 
7451  = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7452  assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
7453 
7454  unsigned GlobalIndex = LocalIndex + I->second;
7455  return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7456 }
7457 
7460  switch (Kind) {
7462  return readExpr();
7464  return readTypeSourceInfo();
7466  NestedNameSpecifierLoc QualifierLoc =
7467  readNestedNameSpecifierLoc();
7468  SourceLocation TemplateNameLoc = readSourceLocation();
7469  return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7470  TemplateNameLoc, SourceLocation());
7471  }
7473  NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7474  SourceLocation TemplateNameLoc = readSourceLocation();
7475  SourceLocation EllipsisLoc = readSourceLocation();
7476  return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7477  TemplateNameLoc, EllipsisLoc);
7478  }
7485  // FIXME: Is this right?
7486  return TemplateArgumentLocInfo();
7487  }
7488  llvm_unreachable("unexpected template argument loc");
7489 }
7490 
7492  TemplateArgument Arg = readTemplateArgument();
7493 
7494  if (Arg.getKind() == TemplateArgument::Expression) {
7495  if (readBool()) // bool InfoHasSameExpr.
7497  }
7498  return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
7499 }
7500 
7502  TemplateArgumentListInfo &Result) {
7503  Result.setLAngleLoc(readSourceLocation());
7504  Result.setRAngleLoc(readSourceLocation());
7505  unsigned NumArgsAsWritten = readInt();
7506  for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7507  Result.addArgument(readTemplateArgumentLoc());
7508 }
7509 
7512  TemplateArgumentListInfo Result;
7513  readTemplateArgumentListInfo(Result);
7514  return ASTTemplateArgumentListInfo::Create(getContext(), Result);
7515 }
7516 
7518 
7520  if (NumCurrentElementsDeserializing) {
7521  // We arrange to not care about the complete redeclaration chain while we're
7522  // deserializing. Just remember that the AST has marked this one as complete
7523  // but that it's not actually complete yet, so we know we still need to
7524  // complete it later.
7525  PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7526  return;
7527  }
7528 
7529  if (!D->getDeclContext()) {
7530  assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
7531  return;
7532  }
7533 
7534  const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7535 
7536  // If this is a named declaration, complete it by looking it up
7537  // within its context.
7538  //
7539  // FIXME: Merging a function definition should merge
7540  // all mergeable entities within it.
7541  if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) {
7542  if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
7543  if (!getContext().getLangOpts().CPlusPlus &&
7544  isa<TranslationUnitDecl>(DC)) {
7545  // Outside of C++, we don't have a lookup table for the TU, so update
7546  // the identifier instead. (For C++ modules, we don't store decls
7547  // in the serialized identifier table, so we do the lookup in the TU.)
7548  auto *II = Name.getAsIdentifierInfo();
7549  assert(II && "non-identifier name in C?");
7550  if (II->isOutOfDate())
7551  updateOutOfDateIdentifier(*II);
7552  } else
7553  DC->lookup(Name);
7554  } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
7555  // Find all declarations of this kind from the relevant context.
7556  for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7557  auto *DC = cast<DeclContext>(DCDecl);
7558  SmallVector<Decl*, 8> Decls;
7559  FindExternalLexicalDecls(
7560  DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7561  }
7562  }
7563  }
7564 
7565  if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7566  CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7567  if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7568  VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7569  if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7570  if (auto *Template = FD->getPrimaryTemplate())
7571  Template->LoadLazySpecializations();
7572  }
7573 }
7574 
7577  RecordLocation Loc = getLocalBitOffset(Offset);
7578  BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7579  SavedStreamPosition SavedPosition(Cursor);
7580  if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7581  Error(std::move(Err));
7582  return nullptr;
7583  }
7584  ReadingKindTracker ReadingKind(Read_Decl, *this);
7585  Deserializing D(this);
7586 
7587  Expected<unsigned> MaybeCode = Cursor.ReadCode();
7588  if (!MaybeCode) {
7589  Error(MaybeCode.takeError());
7590  return nullptr;
7591  }
7592  unsigned Code = MaybeCode.get();
7593 
7594  ASTRecordReader Record(*this, *Loc.F);
7595  Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7596  if (!MaybeRecCode) {
7597  Error(MaybeRecCode.takeError());
7598  return nullptr;
7599  }
7600  if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
7601  Error("malformed AST file: missing C++ ctor initializers");
7602  return nullptr;
7603  }
7604 
7605  return Record.readCXXCtorInitializers();
7606 }
7607 
7609  assert(ContextObj && "reading base specifiers with no AST context");
7610  ASTContext &Context = *ContextObj;
7611 
7612  RecordLocation Loc = getLocalBitOffset(Offset);
7613  BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7614  SavedStreamPosition SavedPosition(Cursor);
7615  if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7616  Error(std::move(Err));
7617  return nullptr;
7618  }
7619  ReadingKindTracker ReadingKind(Read_Decl, *this);
7620  Deserializing D(this);
7621 
7622  Expected<unsigned> MaybeCode = Cursor.ReadCode();
7623  if (!MaybeCode) {
7624  Error(MaybeCode.takeError());
7625  return nullptr;
7626  }
7627  unsigned Code = MaybeCode.get();
7628 
7629  ASTRecordReader Record(*this, *Loc.F);
7630  Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7631  if (!MaybeRecCode) {
7632  Error(MaybeCode.takeError());
7633  return nullptr;
7634  }
7635  unsigned RecCode = MaybeRecCode.get();
7636 
7637  if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
7638  Error("malformed AST file: missing C++ base specifiers");
7639  return nullptr;
7640  }
7641 
7642  unsigned NumBases = Record.readInt();
7643  void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
7644  CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
7645  for (unsigned I = 0; I != NumBases; ++I)
7646  Bases[I] = Record.readCXXBaseSpecifier();
7647  return Bases;
7648 }
7649 
7651  LocalDeclID LocalID) const {
7652  DeclID ID = LocalID.get();
7653  if (ID < NUM_PREDEF_DECL_IDS)
7654  return GlobalDeclID(ID);
7655 
7656  if (!F.ModuleOffsetMap.empty())
7657  ReadModuleOffsetMap(F);
7658 
7661  assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
7662 
7663  return GlobalDeclID(ID + I->second);
7664 }
7665 
7667  // Predefined decls aren't from any module.
7668  if (ID.get() < NUM_PREDEF_DECL_IDS)
7669  return false;
7670 
7671  return ID.get() - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
7673 }
7674 
7676  if (!D->isFromASTFile())
7677  return nullptr;
7679  GlobalDeclMap.find(GlobalDeclID(D->getGlobalID()));
7680  assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7681  return I->second;
7682 }
7683 
7685  if (ID.get() < NUM_PREDEF_DECL_IDS)
7686  return SourceLocation();
7687 
7688  unsigned Index = ID.get() - NUM_PREDEF_DECL_IDS;
7689 
7690  if (Index > DeclsLoaded.size()) {
7691  Error("declaration ID out-of-range for AST file");
7692  return SourceLocation();
7693  }
7694 
7695  if (Decl *D = DeclsLoaded[Index])
7696  return D->getLocation();
7697 
7699  DeclCursorForID(ID, Loc);
7700  return Loc;
7701 }
7702 
7704  switch (ID) {
7705  case PREDEF_DECL_NULL_ID:
7706  return nullptr;
7707 
7709  return Context.getTranslationUnitDecl();
7710 
7712  return Context.getObjCIdDecl();
7713 
7715  return Context.getObjCSelDecl();
7716 
7718  return Context.getObjCClassDecl();
7719 
7721  return Context.getObjCProtocolDecl();
7722 
7724  return Context.getInt128Decl();
7725 
7727  return Context.getUInt128Decl();
7728 
7730  return Context.getObjCInstanceTypeDecl();
7731 
7733  return Context.getBuiltinVaListDecl();
7734 
7736  return Context.getVaListTagDecl();
7737 
7739  return Context.getBuiltinMSVaListDecl();
7740 
7742  return Context.getMSGuidTagDecl();
7743 
7745  return Context.getExternCContextDecl();
7746 
7748  return Context.getMakeIntegerSeqDecl();
7749 
7751  return Context.getCFConstantStringDecl();
7752 
7754  return Context.getCFConstantStringTagDecl();
7755 
7757  return Context.getTypePackElementDecl();
7758  }
7759  llvm_unreachable("PredefinedDeclIDs unknown enum value");
7760 }
7761 
7763  assert(ContextObj && "reading decl with no AST context");
7764  if (ID.get() < NUM_PREDEF_DECL_IDS) {
7765  Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
7766  if (D) {
7767  // Track that we have merged the declaration with ID \p ID into the
7768  // pre-existing predefined declaration \p D.
7769  auto &Merged = KeyDecls[D->getCanonicalDecl()];
7770  if (Merged.empty())
7771  Merged.push_back(ID);
7772  }
7773  return D;
7774  }
7775 
7776  unsigned Index = ID.get() - NUM_PREDEF_DECL_IDS;
7777 
7778  if (Index >= DeclsLoaded.size()) {
7779  assert(0 && "declaration ID out-of-range for AST file");
7780  Error("declaration ID out-of-range for AST file");
7781  return nullptr;
7782  }
7783 
7784  return DeclsLoaded[Index];
7785 }
7786 
7788  if (ID.get() < NUM_PREDEF_DECL_IDS)
7789  return GetExistingDecl(ID);
7790 
7791  unsigned Index = ID.get() - NUM_PREDEF_DECL_IDS;
7792 
7793  if (Index >= DeclsLoaded.size()) {
7794  assert(0 && "declaration ID out-of-range for AST file");
7795  Error("declaration ID out-of-range for AST file");
7796  return nullptr;
7797  }
7798 
7799  if (!DeclsLoaded[Index]) {
7800  ReadDeclRecord(ID);
7801  if (DeserializationListener)
7802  DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7803  }
7804 
7805  return DeclsLoaded[Index];
7806 }
7807 
7809  GlobalDeclID GlobalID) {
7810  DeclID ID = GlobalID.get();
7811  if (ID < NUM_PREDEF_DECL_IDS)
7812  return LocalDeclID(ID);
7813 
7814  GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7815  assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7816  ModuleFile *Owner = I->second;
7817 
7818  llvm::DenseMap<ModuleFile *, DeclID>::iterator Pos =
7819  M.GlobalToLocalDeclIDs.find(Owner);
7820  if (Pos == M.GlobalToLocalDeclIDs.end())
7821  return LocalDeclID();
7822 
7823  return LocalDeclID(ID - Owner->BaseDeclID + Pos->second);
7824 }
7825 
7827  unsigned &Idx) {
7828  if (Idx >= Record.size()) {
7829  Error("Corrupted AST file");
7830  return GlobalDeclID(0);
7831  }
7832 
7833  return getGlobalDeclID(F, LocalDeclID(Record[Idx++]));
7834 }
7835 
7836 /// Resolve the offset of a statement into a statement.
7837 ///
7838 /// This operation will read a new statement from the external
7839 /// source each time it is called, and is meant to be used via a
7840 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7842  // Switch case IDs are per Decl.
7843  ClearSwitchCaseIDs();
7844 
7845  // Offset here is a global offset across the entire chain.
7846  RecordLocation Loc = getLocalBitOffset(Offset);
7847  if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7848  Error(std::move(Err));
7849  return nullptr;
7850  }
7851  assert(NumCurrentElementsDeserializing == 0 &&
7852  "should not be called while already deserializing");
7853  Deserializing D(this);
7854  return ReadStmtFromStream(*Loc.F);
7855 }
7856 
7858  const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7859  SmallVectorImpl<Decl *> &Decls) {
7860  bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7861 
7862  auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
7863  assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7864  for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7865  auto K = (Decl::Kind)+LexicalDecls[I];
7866  if (!IsKindWeWant(K))
7867  continue;
7868 
7869  auto ID = (DeclID) + LexicalDecls[I + 1];
7870 
7871  // Don't add predefined declarations to the lexical context more
7872  // than once.
7873  if (ID < NUM_PREDEF_DECL_IDS) {
7874  if (PredefsVisited[ID])
7875  continue;
7876 
7877  PredefsVisited[ID] = true;
7878  }
7879 
7880  if (Decl *D = GetLocalDecl(*M, LocalDeclID(ID))) {
7881  assert(D->getKind() == K && "wrong kind for lexical decl");
7882  if (!DC->isDeclInLexicalTraversal(D))
7883  Decls.push_back(D);
7884  }
7885  }
7886  };
7887 
7888  if (isa<TranslationUnitDecl>(DC)) {
7889  for (const auto &Lexical : TULexicalDecls)
7890  Visit(Lexical.first, Lexical.second);
7891  } else {
7892  auto I = LexicalDecls.find(DC);
7893  if (I != LexicalDecls.end())
7894  Visit(I->second.first, I->second.second);
7895  }
7896 
7897  ++NumLexicalDeclContextsRead;
7898 }
7899 
7900 namespace {
7901 
7902 class DeclIDComp {
7903  ASTReader &Reader;
7904  ModuleFile &Mod;
7905 
7906 public:
7907  DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7908 
7909  bool operator()(LocalDeclID L, LocalDeclID R) const {
7910  SourceLocation LHS = getLocation(L);
7911  SourceLocation RHS = getLocation(R);
7912  return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7913  }
7914 
7915  bool operator()(SourceLocation LHS, LocalDeclID R) const {
7916  SourceLocation RHS = getLocation(R);
7917  return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7918  }
7919 
7920  bool operator()(LocalDeclID L, SourceLocation RHS) const {
7921  SourceLocation LHS = getLocation(L);
7922  return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7923  }
7924 
7925  SourceLocation getLocation(LocalDeclID ID) const {
7926  return Reader.getSourceManager().getFileLoc(
7927  Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7928  }
7929 };
7930 
7931 } // namespace
7932 
7934  unsigned Offset, unsigned Length,
7935  SmallVectorImpl<Decl *> &Decls) {
7936  SourceManager &SM = getSourceManager();
7937 
7938  llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7939  if (I == FileDeclIDs.end())
7940  return;
7941 
7942  FileDeclsInfo &DInfo = I->second;
7943  if (DInfo.Decls.empty())
7944  return;
7945 
7947  BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7948  SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7949 
7950  DeclIDComp DIDComp(*this, *DInfo.Mod);
7952  llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
7953  if (BeginIt != DInfo.Decls.begin())
7954  --BeginIt;
7955 
7956  // If we are pointing at a top-level decl inside an objc container, we need
7957  // to backtrack until we find it otherwise we will fail to report that the
7958  // region overlaps with an objc container.
7959  while (BeginIt != DInfo.Decls.begin() &&
7960  GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7961  ->isTopLevelDeclInObjCContainer())
7962  --BeginIt;
7963 
7965  llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
7966  if (EndIt != DInfo.Decls.end())
7967  ++EndIt;
7968 
7969  for (ArrayRef<LocalDeclID>::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
7970  Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7971 }
7972 
7973 bool
7975  DeclarationName Name) {
7976  assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
7977  "DeclContext has no visible decls in storage");
7978  if (!Name)
7979  return false;
7980 
7981  auto It = Lookups.find(DC);
7982  if (It == Lookups.end())
7983  return false;
7984 
7985  Deserializing LookupResults(this);
7986 
7987  // Load the list of declarations.
7990 
7991  for (GlobalDeclID ID : It->second.Table.find(Name)) {
7992  NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7993  if (ND->getDeclName() == Name && Found.insert(ND).second)
7994  Decls.push_back(ND);
7995  }
7996 
7997  ++NumVisibleDeclContextsRead;
7998  SetExternalVisibleDeclsForName(DC, Name, Decls);
7999  return !Decls.empty();
8000 }
8001 
8003  if (!DC->hasExternalVisibleStorage())
8004  return;
8005 
8006  auto It = Lookups.find(DC);
8007  assert(It != Lookups.end() &&
8008  "have external visible storage but no lookup tables");
8009 
8010  DeclsMap Decls;
8011 
8012  for (GlobalDeclID ID : It->second.Table.findAll()) {
8013  NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
8014  Decls[ND->getDeclName()].push_back(ND);
8015  }
8016 
8017  ++NumVisibleDeclContextsRead;
8018 
8019  for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
8020  SetExternalVisibleDeclsForName(DC, I->first, I->second);
8021  }
8022  const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8023 }
8024 
8027  auto I = Lookups.find(Primary);
8028  return I == Lookups.end() ? nullptr : &I->second;
8029 }
8030 
8031 /// Under non-PCH compilation the consumer receives the objc methods
8032 /// before receiving the implementation, and codegen depends on this.
8033 /// We simulate this by deserializing and passing to consumer the methods of the
8034 /// implementation before passing the deserialized implementation decl.
8036  ASTConsumer *Consumer) {
8037  assert(ImplD && Consumer);
8038 
8039  for (auto *I : ImplD->methods())
8040  Consumer->HandleInterestingDecl(DeclGroupRef(I));
8041 
8042  Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8043 }
8044 
8045 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
8046  if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
8047  PassObjCImplDeclToConsumer(ImplD, Consumer);
8048  else
8049  Consumer->HandleInterestingDecl(DeclGroupRef(D));
8050 }
8051 
8053  this->Consumer = Consumer;
8054 
8055  if (Consumer)
8056  PassInterestingDeclsToConsumer();
8057 
8058  if (DeserializationListener)
8059  DeserializationListener->ReaderInitialized(this);
8060 }
8061 
8063  std::fprintf(stderr, "*** AST File Statistics:\n");
8064 
8065  unsigned NumTypesLoaded =
8066  TypesLoaded.size() - llvm::count(TypesLoaded.materialized(), QualType());
8067  unsigned NumDeclsLoaded =
8068  DeclsLoaded.size() -
8069  llvm::count(DeclsLoaded.materialized(), (Decl *)nullptr);
8070  unsigned NumIdentifiersLoaded =
8071  IdentifiersLoaded.size() -
8072  llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
8073  unsigned NumMacrosLoaded =
8074  MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
8075  unsigned NumSelectorsLoaded =
8076  SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
8077 
8078  if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8079  std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
8080  NumSLocEntriesRead, TotalNumSLocEntries,
8081  ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8082  if (!TypesLoaded.empty())
8083  std::fprintf(stderr, " %u/%u types read (%f%%)\n",
8084  NumTypesLoaded, (unsigned)TypesLoaded.size(),
8085  ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8086  if (!DeclsLoaded.empty())
8087  std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
8088  NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8089  ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8090  if (!IdentifiersLoaded.empty())
8091  std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
8092  NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8093  ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8094  if (!MacrosLoaded.empty())
8095  std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8096  NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8097  ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8098  if (!SelectorsLoaded.empty())
8099  std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
8100  NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8101  ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8102  if (TotalNumStatements)
8103  std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
8104  NumStatementsRead, TotalNumStatements,
8105  ((float)NumStatementsRead/TotalNumStatements * 100));
8106  if (TotalNumMacros)
8107  std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8108  NumMacrosRead, TotalNumMacros,
8109  ((float)NumMacrosRead/TotalNumMacros * 100));
8110  if (TotalLexicalDeclContexts)
8111  std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
8112  NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8113  ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8114  * 100));
8115  if (TotalVisibleDeclContexts)
8116  std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
8117  NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8118  ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8119  * 100));
8120  if (TotalNumMethodPoolEntries)
8121  std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
8122  NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8123  ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8124  * 100));
8125  if (NumMethodPoolLookups)
8126  std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
8127  NumMethodPoolHits, NumMethodPoolLookups,
8128  ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
8129  if (NumMethodPoolTableLookups)
8130  std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
8131  NumMethodPoolTableHits, NumMethodPoolTableLookups,
8132  ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8133  * 100.0));
8134  if (NumIdentifierLookupHits)
8135  std::fprintf(stderr,
8136  " %u / %u identifier table lookups succeeded (%f%%)\n",
8137  NumIdentifierLookupHits, NumIdentifierLookups,
8138  (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
8139 
8140  if (GlobalIndex) {
8141  std::fprintf(stderr, "\n");
8142  GlobalIndex->printStats();
8143  }
8144 
8145  std::fprintf(stderr, "\n");
8146  dump();
8147  std::fprintf(stderr, "\n");
8148 }
8149 
8150 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
8151 LLVM_DUMP_METHOD static void
8152 dumpModuleIDMap(StringRef Name,
8153  const ContinuousRangeMap<Key, ModuleFile *,
8154  InitialCapacity> &Map) {
8155  if (Map.begin() == Map.end())
8156  return;
8157 
8159 
8160  llvm::errs() << Name << ":\n";
8161  for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
8162  I != IEnd; ++I) {
8163  uint64_t ID = 0;
8164  if constexpr (std::is_integral_v<Key>)
8165  ID = I->first;
8166  else /*GlobalDeclID*/
8167  ID = I->first.get();
8168  llvm::errs() << " " << ID << " -> " << I->second->FileName << "\n";
8169  }
8170 }
8171 
8172 LLVM_DUMP_METHOD void ASTReader::dump() {
8173  llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
8174  dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
8175  dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
8176  dumpModuleIDMap("Global type map", GlobalTypeMap);
8177  dumpModuleIDMap("Global declaration map", GlobalDeclMap);
8178  dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
8179  dumpModuleIDMap("Global macro map", GlobalMacroMap);
8180  dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
8181  dumpModuleIDMap("Global selector map", GlobalSelectorMap);
8182  dumpModuleIDMap("Global preprocessed entity map",
8183  GlobalPreprocessedEntityMap);
8184 
8185  llvm::errs() << "\n*** PCH/Modules Loaded:";
8186  for (ModuleFile &M : ModuleMgr)
8187  M.dump();
8188 }
8189 
8190 /// Return the amount of memory used by memory buffers, breaking down
8191 /// by heap-backed versus mmap'ed memory.
8193  for (ModuleFile &I : ModuleMgr) {
8194  if (llvm::MemoryBuffer *buf = I.Buffer) {
8195  size_t bytes = buf->getBufferSize();
8196  switch (buf->getBufferKind()) {
8197  case llvm::MemoryBuffer::MemoryBuffer_Malloc:
8198  sizes.malloc_bytes += bytes;
8199  break;
8200  case llvm::MemoryBuffer::MemoryBuffer_MMap:
8201  sizes.mmap_bytes += bytes;
8202  break;
8203  }
8204  }
8205  }
8206 }
8207 
8209  SemaObj = &S;
8210  S.addExternalSource(this);
8211 
8212  // Makes sure any declarations that were deserialized "too early"
8213  // still get added to the identifier's declaration chains.
8214  for (GlobalDeclID ID : PreloadedDeclIDs) {
8215  NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
8216  pushExternalDeclIntoScope(D, D->getDeclName());
8217  }
8218  PreloadedDeclIDs.clear();
8219 
8220  // FIXME: What happens if these are changed by a module import?
8221  if (!FPPragmaOptions.empty()) {
8222  assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
8223  FPOptionsOverride NewOverrides =
8224  FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
8225  SemaObj->CurFPFeatures =
8226  NewOverrides.applyOverrides(SemaObj->getLangOpts());
8227  }
8228 
8229  SemaObj->OpenCLFeatures = OpenCLExtensions;
8230 
8231  UpdateSema();
8232 }
8233 
8235  assert(SemaObj && "no Sema to update");
8236 
8237  // Load the offsets of the declarations that Sema references.
8238  // They will be lazily deserialized when needed.
8239  if (!SemaDeclRefs.empty()) {
8240  assert(SemaDeclRefs.size() % 3 == 0);
8241  for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
8242  if (!SemaObj->StdNamespace)
8243  SemaObj->StdNamespace = SemaDeclRefs[I].get();
8244  if (!SemaObj->StdBadAlloc)
8245  SemaObj->StdBadAlloc = SemaDeclRefs[I + 1].get();
8246  if (!SemaObj->StdAlignValT)
8247  SemaObj->StdAlignValT = SemaDeclRefs[I + 2].get();
8248  }
8249  SemaDeclRefs.clear();
8250  }
8251 
8252  // Update the state of pragmas. Use the same API as if we had encountered the
8253  // pragma in the source.
8254  if(OptimizeOffPragmaLocation.isValid())
8255  SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
8256  if (PragmaMSStructState != -1)
8257  SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
8258  if (PointersToMembersPragmaLocation.isValid()) {
8259  SemaObj->ActOnPragmaMSPointersToMembers(
8261  PragmaMSPointersToMembersState,
8262  PointersToMembersPragmaLocation);
8263  }
8264  SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
8265 
8266  if (PragmaAlignPackCurrentValue) {
8267  // The bottom of the stack might have a default value. It must be adjusted
8268  // to the current value to ensure that the packing state is preserved after
8269  // popping entries that were included/imported from a PCH/module.
8270  bool DropFirst = false;
8271  if (!PragmaAlignPackStack.empty() &&
8272  PragmaAlignPackStack.front().Location.isInvalid()) {
8273  assert(PragmaAlignPackStack.front().Value ==
8274  SemaObj->AlignPackStack.DefaultValue &&
8275  "Expected a default alignment value");
8276  SemaObj->AlignPackStack.Stack.emplace_back(
8277  PragmaAlignPackStack.front().SlotLabel,
8278  SemaObj->AlignPackStack.CurrentValue,
8279  SemaObj->AlignPackStack.CurrentPragmaLocation,
8280  PragmaAlignPackStack.front().PushLocation);
8281  DropFirst = true;
8282  }
8283  for (const auto &Entry :
8284  llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
8285  SemaObj->AlignPackStack.Stack.emplace_back(
8286  Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8287  }
8288  if (PragmaAlignPackCurrentLocation.isInvalid()) {
8289  assert(*PragmaAlignPackCurrentValue ==
8290  SemaObj->AlignPackStack.DefaultValue &&
8291  "Expected a default align and pack value");
8292  // Keep the current values.
8293  } else {
8294  SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
8295  SemaObj->AlignPackStack.CurrentPragmaLocation =
8296  PragmaAlignPackCurrentLocation;
8297  }
8298  }
8299  if (FpPragmaCurrentValue) {
8300  // The bottom of the stack might have a default value. It must be adjusted
8301  // to the current value to ensure that fp-pragma state is preserved after
8302  // popping entries that were included/imported from a PCH/module.
8303  bool DropFirst = false;
8304  if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
8305  assert(FpPragmaStack.front().Value ==
8306  SemaObj->FpPragmaStack.DefaultValue &&
8307  "Expected a default pragma float_control value");
8308  SemaObj->FpPragmaStack.Stack.emplace_back(
8309  FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
8310  SemaObj->FpPragmaStack.CurrentPragmaLocation,
8311  FpPragmaStack.front().PushLocation);
8312  DropFirst = true;
8313  }
8314  for (const auto &Entry :
8315  llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
8316  SemaObj->FpPragmaStack.Stack.emplace_back(
8317  Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8318  if (FpPragmaCurrentLocation.isInvalid()) {
8319  assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
8320  "Expected a default pragma float_control value");
8321  // Keep the current values.
8322  } else {
8323  SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
8324  SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
8325  }
8326  }
8327 
8328  // For non-modular AST files, restore visiblity of modules.
8329  for (auto &Import : PendingImportedModulesSema) {
8330  if (Import.ImportLoc.isInvalid())
8331  continue;
8332  if (Module *Imported = getSubmodule(Import.ID)) {
8333  SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
8334  }
8335  }
8336  PendingImportedModulesSema.clear();
8337 }
8338 
8339 IdentifierInfo *ASTReader::get(StringRef Name) {
8340  // Note that we are loading an identifier.
8341  Deserializing AnIdentifier(this);
8342 
8343  IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
8344  NumIdentifierLookups,
8345  NumIdentifierLookupHits);
8346 
8347  // We don't need to do identifier table lookups in C++ modules (we preload
8348  // all interesting declarations, and don't need to use the scope for name
8349  // lookups). Perform the lookup in PCH files, though, since we don't build
8350  // a complete initial identifier table if we're carrying on from a PCH.
8351  if (PP.getLangOpts().CPlusPlus) {
8352  for (auto *F : ModuleMgr.pch_modules())
8353  if (Visitor(*F))
8354  break;
8355  } else {
8356  // If there is a global index, look there first to determine which modules
8357  // provably do not have any results for this identifier.
8359  GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8360  if (!loadGlobalIndex()) {
8361  if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8362  HitsPtr = &Hits;
8363  }
8364  }
8365 
8366  ModuleMgr.visit(Visitor, HitsPtr);
8367  }
8368 
8369  IdentifierInfo *II = Visitor.getIdentifierInfo();
8370  markIdentifierUpToDate(II);
8371  return II;
8372 }
8373 
8374 namespace clang {
8375 
8376  /// An identifier-lookup iterator that enumerates all of the
8377  /// identifiers stored within a set of AST files.
8379  /// The AST reader whose identifiers are being enumerated.
8380  const ASTReader &Reader;
8381 
8382  /// The current index into the chain of AST files stored in
8383  /// the AST reader.
8384  unsigned Index;
8385 
8386  /// The current position within the identifier lookup table
8387  /// of the current AST file.
8388  ASTIdentifierLookupTable::key_iterator Current;
8389 
8390  /// The end position within the identifier lookup table of
8391  /// the current AST file.
8392  ASTIdentifierLookupTable::key_iterator End;
8393 
8394  /// Whether to skip any modules in the ASTReader.
8395  bool SkipModules;
8396 
8397  public:
8398  explicit ASTIdentifierIterator(const ASTReader &Reader,
8399  bool SkipModules = false);
8400 
8401  StringRef Next() override;
8402  };
8403 
8404 } // namespace clang
8405 
8407  bool SkipModules)
8408  : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
8409 }
8410 
8412  while (Current == End) {
8413  // If we have exhausted all of our AST files, we're done.
8414  if (Index == 0)
8415  return StringRef();
8416 
8417  --Index;
8418  ModuleFile &F = Reader.ModuleMgr[Index];
8419  if (SkipModules && F.isModule())
8420  continue;
8421 
8422  ASTIdentifierLookupTable *IdTable =
8424  Current = IdTable->key_begin();
8425  End = IdTable->key_end();
8426  }
8427 
8428  // We have any identifiers remaining in the current AST file; return
8429  // the next one.
8430  StringRef Result = *Current;
8431  ++Current;
8432  return Result;
8433 }
8434 
8435 namespace {
8436 
8437 /// A utility for appending two IdentifierIterators.
8438 class ChainedIdentifierIterator : public IdentifierIterator {
8439  std::unique_ptr<IdentifierIterator> Current;
8440  std::unique_ptr<IdentifierIterator> Queued;
8441 
8442 public:
8443  ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8444  std::unique_ptr<IdentifierIterator> Second)
8445  : Current(std::move(First)), Queued(std::move(Second)) {}
8446 
8447  StringRef Next() override {
8448  if (!Current)
8449  return StringRef();
8450 
8451  StringRef result = Current->Next();
8452  if (!result.empty())
8453  return result;
8454 
8455  // Try the queued iterator, which may itself be empty.
8456  Current.reset();
8457  std::swap(Current, Queued);
8458  return Next();
8459  }
8460 };
8461 
8462 } // namespace
8463 
8465  if (!loadGlobalIndex()) {
8466  std::unique_ptr<IdentifierIterator> ReaderIter(
8467  new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8468  std::unique_ptr<IdentifierIterator> ModulesIter(
8469  GlobalIndex->createIdentifierIterator());
8470  return new ChainedIdentifierIterator(std::move(ReaderIter),
8471  std::move(ModulesIter));
8472  }
8473 
8474  return new ASTIdentifierIterator(*this);
8475 }
8476 
8477 namespace clang {
8478 namespace serialization {
8479 
8481  ASTReader &Reader;
8482  Selector Sel;
8483  unsigned PriorGeneration;
8484  unsigned InstanceBits = 0;
8485  unsigned FactoryBits = 0;
8486  bool InstanceHasMoreThanOneDecl = false;
8487  bool FactoryHasMoreThanOneDecl = false;
8488  SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8489  SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
8490 
8491  public:
8493  unsigned PriorGeneration)
8494  : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
8495 
8497  if (!M.SelectorLookupTable)
8498  return false;
8499 
8500  // If we've already searched this module file, skip it now.
8501  if (M.Generation <= PriorGeneration)
8502  return true;
8503 
8504  ++Reader.NumMethodPoolTableLookups;
8505  ASTSelectorLookupTable *PoolTable
8507  ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
8508  if (Pos == PoolTable->end())
8509  return false;
8510 
8511  ++Reader.NumMethodPoolTableHits;
8512  ++Reader.NumSelectorsRead;
8513  // FIXME: Not quite happy with the statistics here. We probably should
8514  // disable this tracking when called via LoadSelector.
8515  // Also, should entries without methods count as misses?
8516  ++Reader.NumMethodPoolEntriesRead;
8518  if (Reader.DeserializationListener)
8519  Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
8520 
8521  // Append methods in the reverse order, so that later we can process them
8522  // in the order they appear in the source code by iterating through
8523  // the vector in the reverse order.
8524  InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
8525  FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
8526  InstanceBits = Data.InstanceBits;
8527  FactoryBits = Data.FactoryBits;
8528  InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8529  FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
8530  return false;
8531  }
8532 
8533  /// Retrieve the instance methods found by this visitor.
8535  return InstanceMethods;
8536  }
8537 
8538  /// Retrieve the instance methods found by this visitor.
8540  return FactoryMethods;
8541  }
8542 
8543  unsigned getInstanceBits() const { return InstanceBits; }
8544  unsigned getFactoryBits() const { return FactoryBits; }
8545 
8547  return InstanceHasMoreThanOneDecl;
8548  }
8549 
8550  bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
8551  };
8552 
8553 } // namespace serialization
8554 } // namespace clang
8555 
8556 /// Add the given set of methods to the method list.
8558  ObjCMethodList &List) {
8559  for (ObjCMethodDecl *M : llvm::reverse(Methods))
8560  S.ObjC().addMethodToGlobalList(&List, M);
8561 }
8562 
8564  // Get the selector generation and update it to the current generation.
8565  unsigned &Generation = SelectorGeneration[Sel];
8566  unsigned PriorGeneration = Generation;
8567  Generation = getGeneration();
8568  SelectorOutOfDate[Sel] = false;
8569 
8570  // Search for methods defined with this selector.
8571  ++NumMethodPoolLookups;
8572  ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
8573  ModuleMgr.visit(Visitor);
8574 
8575  if (Visitor.getInstanceMethods().empty() &&
8576  Visitor.getFactoryMethods().empty())
8577  return;
8578 
8579  ++NumMethodPoolHits;
8580 
8581  if (!getSema())
8582  return;
8583 
8584  Sema &S = *getSema();
8586  S.ObjC()
8587  .MethodPool
8588  .insert(std::make_pair(Sel, SemaObjC::GlobalMethodPool::Lists()))
8589  .first;
8590 
8591  Pos->second.first.setBits(Visitor.getInstanceBits());
8592  Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
8593  Pos->second.second.setBits(Visitor.getFactoryBits());
8594  Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
8595 
8596  // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8597  // when building a module we keep every method individually and may need to
8598  // update hasMoreThanOneDecl as we add the methods.
8599  addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8600  addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
8601 }
8602 
8604  if (SelectorOutOfDate[Sel])
8605  ReadMethodPool(Sel);
8606 }
8607 
8609  SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8610  Namespaces.clear();
8611 
8612  for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8613  if (NamespaceDecl *Namespace
8614  = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
8615  Namespaces.push_back(Namespace);
8616  }
8617 }
8618 
8620  llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
8621  for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
8622  UndefinedButUsedDecl &U = UndefinedButUsed[Idx++];
8623  NamedDecl *D = cast<NamedDecl>(GetDecl(U.ID));
8625  Undefined.insert(std::make_pair(D, Loc));
8626  }
8627  UndefinedButUsed.clear();
8628 }
8629 
8631  FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8632  Exprs) {
8633  for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
8634  FieldDecl *FD =
8635  cast<FieldDecl>(GetDecl(GlobalDeclID(DelayedDeleteExprs[Idx++])));
8636  uint64_t Count = DelayedDeleteExprs[Idx++];
8637  for (uint64_t C = 0; C < Count; ++C) {
8638  SourceLocation DeleteLoc =
8639  SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8640  const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8641  Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8642  }
8643  }
8644 }
8645 
8647  SmallVectorImpl<VarDecl *> &TentativeDefs) {
8648  for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8649  VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
8650  if (Var)
8651  TentativeDefs.push_back(Var);
8652  }
8653  TentativeDefinitions.clear();
8654 }
8655 
8658  for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8659  DeclaratorDecl *D
8660  = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
8661  if (D)
8662  Decls.push_back(D);
8663  }
8664  UnusedFileScopedDecls.clear();
8665 }
8666 
8669  for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8671  = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
8672  if (D)
8673  Decls.push_back(D);
8674  }
8675  DelegatingCtorDecls.clear();
8676 }
8677 
8679  for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8680  TypedefNameDecl *D
8681  = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
8682  if (D)
8683  Decls.push_back(D);
8684  }
8685  ExtVectorDecls.clear();
8686 }
8687 
8690  for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8691  ++I) {
8692  TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8693  GetDecl(UnusedLocalTypedefNameCandidates[I]));
8694  if (D)
8695  Decls.insert(D);
8696  }
8697  UnusedLocalTypedefNameCandidates.clear();
8698 }
8699 
8702  for (auto I : DeclsToCheckForDeferredDiags) {
8703  auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
8704  if (D)
8705  Decls.insert(D);
8706  }
8707  DeclsToCheckForDeferredDiags.clear();
8708 }
8709 
8711  SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
8712  if (ReferencedSelectorsData.empty())
8713  return;
8714 
8715  // If there are @selector references added them to its pool. This is for
8716  // implementation of -Wselector.
8717  unsigned int DataSize = ReferencedSelectorsData.size()-1;
8718  unsigned I = 0;
8719  while (I < DataSize) {
8720  Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8721  SourceLocation SelLoc
8722  = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8723  Sels.push_back(std::make_pair(Sel, SelLoc));
8724  }
8725  ReferencedSelectorsData.clear();
8726 }
8727 
8729  SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
8730  if (WeakUndeclaredIdentifiers.empty())
8731  return;
8732 
8733  for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
8734  IdentifierInfo *WeakId
8735  = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8736  IdentifierInfo *AliasId
8737  = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8739  SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8740  WeakInfo WI(AliasId, Loc);
8741  WeakIDs.push_back(std::make_pair(WeakId, WI));
8742  }
8743  WeakUndeclaredIdentifiers.clear();
8744 }
8745 
8747  for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8748  ExternalVTableUse VT;
8749  VTableUse &TableInfo = VTableUses[Idx++];
8750  VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(TableInfo.ID));
8751  VT.Location = SourceLocation::getFromRawEncoding(TableInfo.RawLoc);
8752  VT.DefinitionRequired = TableInfo.Used;
8753  VTables.push_back(VT);
8754  }
8755 
8756  VTableUses.clear();
8757 }
8758 
8760  SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
8761  for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8762  PendingInstantiation &Inst = PendingInstantiations[Idx++];
8763  ValueDecl *D = cast<ValueDecl>(GetDecl(Inst.ID));
8765 
8766  Pending.push_back(std::make_pair(D, Loc));
8767  }
8768  PendingInstantiations.clear();
8769 }
8770 
8772  llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8773  &LPTMap) {
8774  for (auto &LPT : LateParsedTemplates) {
8775  ModuleFile *FMod = LPT.first;
8776  RecordDataImpl &LateParsed = LPT.second;
8777  for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
8778  /* In loop */) {
8779  FunctionDecl *FD = cast<FunctionDecl>(
8780  GetLocalDecl(*FMod, LocalDeclID(LateParsed[Idx++])));
8781 
8782  auto LT = std::make_unique<LateParsedTemplate>();
8783  LT->D = GetLocalDecl(*FMod, LocalDeclID(LateParsed[Idx++]));
8784  LT->FPO = FPOptions::getFromOpaqueInt(LateParsed[Idx++]);
8785 
8787  assert(F && "No module");
8788 
8789  unsigned TokN = LateParsed[Idx++];
8790  LT->Toks.reserve(TokN);
8791  for (unsigned T = 0; T < TokN; ++T)
8792  LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
8793 
8794  LPTMap.insert(std::make_pair(FD, std::move(LT)));
8795  }
8796  }
8797 
8798  LateParsedTemplates.clear();
8799 }
8800 
8802  if (Lambda->getLambdaContextDecl()) {
8803  // Keep track of this lambda so it can be merged with another lambda that
8804  // is loaded later.
8805  LambdaDeclarationsForMerging.insert(
8806  {{Lambda->getLambdaContextDecl()->getCanonicalDecl(),
8807  Lambda->getLambdaIndexInContext()},
8808  const_cast<CXXRecordDecl *>(Lambda)});
8809  }
8810 }
8811 
8813  // It would be complicated to avoid reading the methods anyway. So don't.
8814  ReadMethodPool(Sel);
8815 }
8816 
8818  assert(ID && "Non-zero identifier ID required");
8819  assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8820  IdentifiersLoaded[ID - 1] = II;
8821  if (DeserializationListener)
8822  DeserializationListener->IdentifierRead(ID, II);
8823 }
8824 
8825 /// Set the globally-visible declarations associated with the given
8826 /// identifier.
8827 ///
8828 /// If the AST reader is currently in a state where the given declaration IDs
8829 /// cannot safely be resolved, they are queued until it is safe to resolve
8830 /// them.
8831 ///
8832 /// \param II an IdentifierInfo that refers to one or more globally-visible
8833 /// declarations.
8834 ///
8835 /// \param DeclIDs the set of declaration IDs with the name @p II that are
8836 /// visible at global scope.
8837 ///
8838 /// \param Decls if non-null, this vector will be populated with the set of
8839 /// deserialized declarations. These declarations will not be pushed into
8840 /// scope.
8842  IdentifierInfo *II, const SmallVectorImpl<GlobalDeclID> &DeclIDs,
8843  SmallVectorImpl<Decl *> *Decls) {
8844  if (NumCurrentElementsDeserializing && !Decls) {
8845  PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
8846  return;
8847  }
8848 
8849  for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
8850  if (!SemaObj) {
8851  // Queue this declaration so that it will be added to the
8852  // translation unit scope and identifier's declaration chain
8853  // once a Sema object is known.
8854  PreloadedDeclIDs.push_back(DeclIDs[I]);
8855  continue;
8856  }
8857 
8858  NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8859 
8860  // If we're simply supposed to record the declarations, do so now.
8861  if (Decls) {
8862  Decls->push_back(D);
8863  continue;
8864  }
8865 
8866  // Introduce this declaration into the translation-unit scope
8867  // and add it to the declaration chain for this identifier, so
8868  // that (unqualified) name lookup will find it.
8869  pushExternalDeclIntoScope(D, II);
8870  }
8871 }
8872 
8874  if (ID == 0)
8875  return nullptr;
8876 
8877  if (IdentifiersLoaded.empty()) {
8878  Error("no identifier table in AST file");
8879  return nullptr;
8880  }
8881 
8882  ID -= 1;
8883  if (!IdentifiersLoaded[ID]) {
8884  GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8885  assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8886  ModuleFile *M = I->second;
8887  unsigned Index = ID - M->BaseIdentifierID;
8888  const unsigned char *Data =
8889  M->IdentifierTableData + M->IdentifierOffsets[Index];
8890 
8891  ASTIdentifierLookupTrait Trait(*this, *M);
8892  auto KeyDataLen = Trait.ReadKeyDataLength(Data);
8893  auto Key = Trait.ReadKey(Data, KeyDataLen.first);
8894  auto &II = PP.getIdentifierTable().get(Key);
8895  IdentifiersLoaded[ID] = &II;
8896  markIdentifierFromAST(*this, II);
8897  if (DeserializationListener)
8898  DeserializationListener->IdentifierRead(ID + 1, &II);
8899  }
8900 
8901  return IdentifiersLoaded[ID];
8902 }
8903 
8905  return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
8906 }
8907 
8909  if (LocalID < NUM_PREDEF_IDENT_IDS)
8910  return LocalID;
8911 
8912  if (!M.ModuleOffsetMap.empty())
8913  ReadModuleOffsetMap(M);
8914 
8916  = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
8917  assert(I != M.IdentifierRemap.end()
8918  && "Invalid index into identifier index remap");
8919 
8920  return LocalID + I->second;
8921 }
8922 
8924  if (ID == 0)
8925  return nullptr;
8926 
8927  if (MacrosLoaded.empty()) {
8928  Error("no macro table in AST file");
8929  return nullptr;
8930  }
8931 
8932  ID -= NUM_PREDEF_MACRO_IDS;
8933  if (!MacrosLoaded[ID]) {
8935  = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8936  assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8937  ModuleFile *M = I->second;
8938  unsigned Index = ID - M->BaseMacroID;
8939  MacrosLoaded[ID] =
8940  ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
8941 
8942  if (DeserializationListener)
8943  DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8944  MacrosLoaded[ID]);
8945  }
8946 
8947  return MacrosLoaded[ID];
8948 }
8949 
8951  if (LocalID < NUM_PREDEF_MACRO_IDS)
8952  return LocalID;
8953 
8954  if (!M.ModuleOffsetMap.empty())
8955  ReadModuleOffsetMap(M);
8956 
8958  = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8959  assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8960 
8961  return LocalID + I->second;
8962 }
8963 
8965 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const {
8966  if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8967  return LocalID;
8968 
8969  if (!M.ModuleOffsetMap.empty())
8970  ReadModuleOffsetMap(M);
8971 
8974  assert(I != M.SubmoduleRemap.end()
8975  && "Invalid index into submodule index remap");
8976 
8977  return LocalID + I->second;
8978 }
8979 
8981  if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8982  assert(GlobalID == 0 && "Unhandled global submodule ID");
8983  return nullptr;
8984  }
8985 
8986  if (GlobalID > SubmodulesLoaded.size()) {
8987  Error("submodule ID out of range in AST file");
8988  return nullptr;
8989  }
8990 
8991  return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8992 }
8993 
8995  return getSubmodule(ID);
8996 }
8997 
8999  if (ID & 1) {
9000  // It's a module, look it up by submodule ID.
9001  auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(M, ID >> 1));
9002  return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
9003  } else {
9004  // It's a prefix (preamble, PCH, ...). Look it up by index.
9005  unsigned IndexFromEnd = ID >> 1;
9006  assert(IndexFromEnd && "got reference to unknown module file");
9007  return getModuleManager().pch_modules().end()[-IndexFromEnd];
9008  }
9009 }
9010 
9012  if (!M)
9013  return 1;
9014 
9015  // For a file representing a module, use the submodule ID of the top-level
9016  // module as the file ID. For any other kind of file, the number of such
9017  // files loaded beforehand will be the same on reload.
9018  // FIXME: Is this true even if we have an explicit module file and a PCH?
9019  if (M->isModule())
9020  return ((M->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
9021 
9022  auto PCHModules = getModuleManager().pch_modules();
9023  auto I = llvm::find(PCHModules, M);
9024  assert(I != PCHModules.end() && "emitting reference to unknown file");
9025  return (I - PCHModules.end()) << 1;
9026 }
9027 
9028 std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
9029  if (Module *M = getSubmodule(ID))
9030  return ASTSourceDescriptor(*M);
9031 
9032  // If there is only a single PCH, return it instead.
9033  // Chained PCH are not supported.
9034  const auto &PCHChain = ModuleMgr.pch_modules();
9035  if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
9036  ModuleFile &MF = ModuleMgr.getPrimaryModule();
9037  StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
9038  StringRef FileName = llvm::sys::path::filename(MF.FileName);
9039  return ASTSourceDescriptor(ModuleName,
9040  llvm::sys::path::parent_path(MF.FileName),
9041  FileName, MF.Signature);
9042  }
9043  return std::nullopt;
9044 }
9045 
9047  auto I = DefinitionSource.find(FD);
9048  if (I == DefinitionSource.end())
9049  return EK_ReplyHazy;
9050  return I->second ? EK_Never : EK_Always;
9051 }
9052 
9054  return DecodeSelector(getGlobalSelectorID(M, LocalID));
9055 }
9056 
9058  if (ID == 0)
9059  return Selector();
9060 
9061  if (ID > SelectorsLoaded.size()) {
9062  Error("selector ID out of range in AST file");
9063  return Selector();
9064  }
9065 
9066  if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
9067  // Load this selector from the selector table.
9068  GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9069  assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9070  ModuleFile &M = *I->second;
9071  ASTSelectorLookupTrait Trait(*this, M);
9072  unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9073  SelectorsLoaded[ID - 1] =
9074  Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9075  if (DeserializationListener)
9076  DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9077  }
9078 
9079  return SelectorsLoaded[ID - 1];
9080 }
9081 
9083  return DecodeSelector(ID);
9084 }
9085 
9087  // ID 0 (the null selector) is considered an external selector.
9088  return getTotalNumSelectors() + 1;
9089 }
9090 
9092 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
9093  if (LocalID < NUM_PREDEF_SELECTOR_IDS)
9094  return LocalID;
9095 
9096  if (!M.ModuleOffsetMap.empty())
9097  ReadModuleOffsetMap(M);
9098 
9101  assert(I != M.SelectorRemap.end()
9102  && "Invalid index into selector index remap");
9103 
9104  return LocalID + I->second;
9105 }
9106 
9109  switch (Name.getNameKind()) {
9114 
9117 
9120  readSourceLocation());
9121 
9128  break;
9129  }
9130  return DeclarationNameLoc();
9131 }
9132 
9134  DeclarationNameInfo NameInfo;
9135  NameInfo.setName(readDeclarationName());
9136  NameInfo.setLoc(readSourceLocation());
9137  NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
9138  return NameInfo;
9139 }
9140 
9142  return TypeCoupledDeclRefInfo(readDeclAs<ValueDecl>(), readBool());
9143 }
9144 
9147  unsigned NumTPLists = readInt();
9148  Info.NumTemplParamLists = NumTPLists;
9149  if (NumTPLists) {
9150  Info.TemplParamLists =
9151  new (getContext()) TemplateParameterList *[NumTPLists];
9152  for (unsigned i = 0; i != NumTPLists; ++i)
9154  }
9155 }
9156 
9159  SourceLocation TemplateLoc = readSourceLocation();
9160  SourceLocation LAngleLoc = readSourceLocation();
9161  SourceLocation RAngleLoc = readSourceLocation();
9162 
9163  unsigned NumParams = readInt();
9165  Params.reserve(NumParams);
9166  while (NumParams--)
9167  Params.push_back(readDeclAs<NamedDecl>());
9168 
9169  bool HasRequiresClause = readBool();
9170  Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
9171 
9173  getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
9174  return TemplateParams;
9175 }
9176 
9179  bool Canonicalize) {
9180  unsigned NumTemplateArgs = readInt();
9181  TemplArgs.reserve(NumTemplateArgs);
9182  while (NumTemplateArgs--)
9183  TemplArgs.push_back(readTemplateArgument(Canonicalize));
9184 }
9185 
9186 /// Read a UnresolvedSet structure.
9188  unsigned NumDecls = readInt();
9189  Set.reserve(getContext(), NumDecls);
9190  while (NumDecls--) {
9193  Set.addLazyDecl(getContext(), ID.get(), AS);
9194  }
9195 }
9196 
9199  bool isVirtual = readBool();
9200  bool isBaseOfClass = readBool();
9201  AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
9202  bool inheritConstructors = readBool();
9205  SourceLocation EllipsisLoc = readSourceLocation();
9206  CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
9207  EllipsisLoc);
9208  Result.setInheritConstructors(inheritConstructors);
9209  return Result;
9210 }
9211 
9214  ASTContext &Context = getContext();
9215  unsigned NumInitializers = readInt();
9216  assert(NumInitializers && "wrote ctor initializers but have no inits");
9217  auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
9218  for (unsigned i = 0; i != NumInitializers; ++i) {
9219  TypeSourceInfo *TInfo = nullptr;
9220  bool IsBaseVirtual = false;
9221  FieldDecl *Member = nullptr;
9222  IndirectFieldDecl *IndirectMember = nullptr;
9223 
9225  switch (Type) {
9226  case CTOR_INITIALIZER_BASE:
9227  TInfo = readTypeSourceInfo();
9228  IsBaseVirtual = readBool();
9229  break;
9230 
9232  TInfo = readTypeSourceInfo();
9233  break;
9234 
9236  Member = readDeclAs<FieldDecl>();
9237  break;
9238 
9240  IndirectMember = readDeclAs<IndirectFieldDecl>();
9241  break;
9242  }
9243 
9244  SourceLocation MemberOrEllipsisLoc = readSourceLocation();
9245  Expr *Init = readExpr();
9246  SourceLocation LParenLoc = readSourceLocation();
9247  SourceLocation RParenLoc = readSourceLocation();
9248 
9249  CXXCtorInitializer *BOMInit;
9250  if (Type == CTOR_INITIALIZER_BASE)
9251  BOMInit = new (Context)
9252  CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
9253  RParenLoc, MemberOrEllipsisLoc);
9254  else if (Type == CTOR_INITIALIZER_DELEGATING)
9255  BOMInit = new (Context)
9256  CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
9257  else if (Member)
9258  BOMInit = new (Context)
9259  CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
9260  Init, RParenLoc);
9261  else
9262  BOMInit = new (Context)
9263  CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
9264  LParenLoc, Init, RParenLoc);
9265 
9266  if (/*IsWritten*/readBool()) {
9267  unsigned SourceOrder = readInt();
9268  BOMInit->setSourceOrder(SourceOrder);
9269  }
9270 
9271  CtorInitializers[i] = BOMInit;
9272  }
9273 
9274  return CtorInitializers;
9275 }
9276 
9279  ASTContext &Context = getContext();
9280  unsigned N = readInt();
9282  for (unsigned I = 0; I != N; ++I) {
9283  auto Kind = readNestedNameSpecifierKind();
9284  switch (Kind) {
9288  Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9289  break;
9290  }
9291 
9293  NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
9295  Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9296  break;
9297  }
9298 
9300  NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
9302  Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9303  break;
9304  }
9305 
9308  bool Template = readBool();
9310  if (!T)
9311  return NestedNameSpecifierLoc();
9312  SourceLocation ColonColonLoc = readSourceLocation();
9313 
9314  // FIXME: 'template' keyword location not saved anywhere, so we fake it.
9315  Builder.Extend(Context,
9316  Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9317  T->getTypeLoc(), ColonColonLoc);
9318  break;
9319  }
9320 
9322  SourceLocation ColonColonLoc = readSourceLocation();
9323  Builder.MakeGlobal(Context, ColonColonLoc);
9324  break;
9325  }
9326 
9328  CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
9330  Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9331  break;
9332  }
9333  }
9334  }
9335 
9336  return Builder.getWithLocInContext(Context);
9337 }
9338 
9340  unsigned &Idx, LocSeq *Seq) {
9341  SourceLocation beg = ReadSourceLocation(F, Record, Idx, Seq);
9342  SourceLocation end = ReadSourceLocation(F, Record, Idx, Seq);
9343  return SourceRange(beg, end);
9344 }
9345 
9347  const StringRef Blob) {
9348  unsigned Count = Record[0];
9349  const char *Byte = Blob.data();
9350  llvm::BitVector Ret = llvm::BitVector(Count, false);
9351  for (unsigned I = 0; I < Count; ++Byte)
9352  for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
9353  if (*Byte & (1 << Bit))
9354  Ret[I] = true;
9355  return Ret;
9356 }
9357 
9358 /// Read a floating-point value
9359 llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
9360  return llvm::APFloat(Sem, readAPInt());
9361 }
9362 
9363 // Read a string
9364 std::string ASTReader::ReadString(const RecordDataImpl &Record, unsigned &Idx) {
9365  unsigned Len = Record[Idx++];
9366  std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9367  Idx += Len;
9368  return Result;
9369 }
9370 
9372  unsigned &Idx) {
9373  std::string Filename = ReadString(Record, Idx);
9375  return Filename;
9376 }
9377 
9378 std::string ASTReader::ReadPath(StringRef BaseDirectory,
9379  const RecordData &Record, unsigned &Idx) {
9380  std::string Filename = ReadString(Record, Idx);
9381  if (!BaseDirectory.empty())
9382  ResolveImportedPath(Filename, BaseDirectory);
9383  return Filename;
9384 }
9385 
9387  unsigned &Idx) {
9388  unsigned Major = Record[Idx++];
9389  unsigned Minor = Record[Idx++];
9390  unsigned Subminor = Record[Idx++];
9391  if (Minor == 0)
9392  return VersionTuple(Major);
9393  if (Subminor == 0)
9394  return VersionTuple(Major, Minor - 1);
9395  return VersionTuple(Major, Minor - 1, Subminor - 1);
9396 }
9397 
9399  const RecordData &Record,
9400  unsigned &Idx) {
9401  CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
9403 }
9404 
9405 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
9406  return Diag(CurrentImportLoc, DiagID);
9407 }
9408 
9410  return Diags.Report(Loc, DiagID);
9411 }
9412 
9413 /// Retrieve the identifier table associated with the
9414 /// preprocessor.
9416  return PP.getIdentifierTable();
9417 }
9418 
9419 /// Record that the given ID maps to the given switch-case
9420 /// statement.
9422  assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
9423  "Already have a SwitchCase with this ID");
9424  (*CurrSwitchCaseStmts)[ID] = SC;
9425 }
9426 
9427 /// Retrieve the switch-case statement with the given ID.
9429  assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
9430  return (*CurrSwitchCaseStmts)[ID];
9431 }
9432 
9434  CurrSwitchCaseStmts->clear();
9435 }
9436 
9438  ASTContext &Context = getContext();
9439  std::vector<RawComment *> Comments;
9440  for (SmallVectorImpl<std::pair<BitstreamCursor,
9441  serialization::ModuleFile *>>::iterator
9442  I = CommentsCursors.begin(),
9443  E = CommentsCursors.end();
9444  I != E; ++I) {
9445  Comments.clear();
9446  BitstreamCursor &Cursor = I->first;
9447  serialization::ModuleFile &F = *I->second;
9448  SavedStreamPosition SavedPosition(Cursor);
9449 
9451  while (true) {
9452  Expected<llvm::BitstreamEntry> MaybeEntry =
9453  Cursor.advanceSkippingSubblocks(
9454  BitstreamCursor::AF_DontPopBlockAtEnd);
9455  if (!MaybeEntry) {
9456  Error(MaybeEntry.takeError());
9457  return;
9458  }
9459  llvm::BitstreamEntry Entry = MaybeEntry.get();
9460 
9461  switch (Entry.Kind) {
9462  case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9464  Error("malformed block record in AST file");
9465  return;
9466  case llvm::BitstreamEntry::EndBlock:
9467  goto NextCursor;
9469  // The interesting case.
9470  break;
9471  }
9472 
9473  // Read a record.
9474  Record.clear();
9475  Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9476  if (!MaybeComment) {
9477  Error(MaybeComment.takeError());
9478  return;
9479  }
9480  switch ((CommentRecordTypes)MaybeComment.get()) {
9481  case COMMENTS_RAW_COMMENT: {
9482  unsigned Idx = 0;
9483  SourceRange SR = ReadSourceRange(F, Record, Idx);
9486  bool IsTrailingComment = Record[Idx++];
9487  bool IsAlmostTrailingComment = Record[Idx++];
9488  Comments.push_back(new (Context) RawComment(
9489  SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
9490  break;
9491  }
9492  }
9493  }
9494  NextCursor:
9495  llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9496  FileToOffsetToComment;
9497  for (RawComment *C : Comments) {
9498  SourceLocation CommentLoc = C->getBeginLoc();
9499  if (CommentLoc.isValid()) {
9500  std::pair<FileID, unsigned> Loc =
9501  SourceMgr.getDecomposedLoc(CommentLoc);
9502  if (Loc.first.isValid())
9503  Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9504  }
9505  }
9506  }
9507 }
9508 
9510  serialization::ModuleFile &MF, bool IncludeSystem,
9511  llvm::function_ref<void(const serialization::InputFileInfo &IFI,
9512  bool IsSystem)>
9513  Visitor) {
9514  unsigned NumUserInputs = MF.NumUserInputFiles;
9515  unsigned NumInputs = MF.InputFilesLoaded.size();
9516  assert(NumUserInputs <= NumInputs);
9517  unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9518  for (unsigned I = 0; I < N; ++I) {
9519  bool IsSystem = I >= NumUserInputs;
9520  InputFileInfo IFI = getInputFileInfo(MF, I+1);
9521  Visitor(IFI, IsSystem);
9522  }
9523 }
9524 
9526  bool IncludeSystem, bool Complain,
9527  llvm::function_ref<void(const serialization::InputFile &IF,
9528  bool isSystem)> Visitor) {
9529  unsigned NumUserInputs = MF.NumUserInputFiles;
9530  unsigned NumInputs = MF.InputFilesLoaded.size();
9531  assert(NumUserInputs <= NumInputs);
9532  unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9533  for (unsigned I = 0; I < N; ++I) {
9534  bool IsSystem = I >= NumUserInputs;
9535  InputFile IF = getInputFile(MF, I+1, Complain);
9536  Visitor(IF, IsSystem);
9537  }
9538 }
9539 
9542  llvm::function_ref<void(FileEntryRef FE)> Visitor) {
9543  unsigned NumInputs = MF.InputFilesLoaded.size();
9544  for (unsigned I = 0; I < NumInputs; ++I) {
9545  InputFileInfo IFI = getInputFileInfo(MF, I + 1);
9546  if (IFI.TopLevel && IFI.ModuleMap)
9547  if (auto FE = getInputFile(MF, I + 1).getFile())
9548  Visitor(*FE);
9549  }
9550 }
9551 
9552 void ASTReader::finishPendingActions() {
9553  while (
9554  !PendingIdentifierInfos.empty() || !PendingDeducedFunctionTypes.empty() ||
9555  !PendingDeducedVarTypes.empty() || !PendingIncompleteDeclChains.empty() ||
9556  !PendingDeclChains.empty() || !PendingMacroIDs.empty() ||
9557  !PendingDeclContextInfos.empty() || !PendingUpdateRecords.empty() ||
9558  !PendingObjCExtensionIvarRedeclarations.empty()) {
9559  // If any identifiers with corresponding top-level declarations have
9560  // been loaded, load those declarations now.
9561  using TopLevelDeclsMap =
9562  llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
9563  TopLevelDeclsMap TopLevelDecls;
9564 
9565  while (!PendingIdentifierInfos.empty()) {
9566  IdentifierInfo *II = PendingIdentifierInfos.back().first;
9568  std::move(PendingIdentifierInfos.back().second);
9569  PendingIdentifierInfos.pop_back();
9570 
9571  SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
9572  }
9573 
9574  // Load each function type that we deferred loading because it was a
9575  // deduced type that might refer to a local type declared within itself.
9576  for (unsigned I = 0; I != PendingDeducedFunctionTypes.size(); ++I) {
9577  auto *FD = PendingDeducedFunctionTypes[I].first;
9578  FD->setType(GetType(PendingDeducedFunctionTypes[I].second));
9579 
9580  if (auto *DT = FD->getReturnType()->getContainedDeducedType()) {
9581  // If we gave a function a deduced return type, remember that we need to
9582  // propagate that along the redeclaration chain.
9583  if (DT->isDeduced()) {
9584  PendingDeducedTypeUpdates.insert(
9585  {FD->getCanonicalDecl(), FD->getReturnType()});
9586  continue;
9587  }
9588 
9589  // The function has undeduced DeduceType return type. We hope we can
9590  // find the deduced type by iterating the redecls in other modules
9591  // later.
9592  PendingUndeducedFunctionDecls.push_back(FD);
9593  continue;
9594  }
9595  }
9596  PendingDeducedFunctionTypes.clear();
9597 
9598  // Load each variable type that we deferred loading because it was a
9599  // deduced type that might refer to a local type declared within itself.
9600  for (unsigned I = 0; I != PendingDeducedVarTypes.size(); ++I) {
9601  auto *VD = PendingDeducedVarTypes[I].first;
9602  VD->setType(GetType(PendingDeducedVarTypes[I].second));
9603  }
9604  PendingDeducedVarTypes.clear();
9605 
9606  // For each decl chain that we wanted to complete while deserializing, mark
9607  // it as "still needs to be completed".
9608  for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9609  markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9610  }
9611  PendingIncompleteDeclChains.clear();
9612 
9613  // Load pending declaration chains.
9614  for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
9615  loadPendingDeclChain(PendingDeclChains[I].first,
9616  PendingDeclChains[I].second);
9617  PendingDeclChains.clear();
9618 
9619  // Make the most recent of the top-level declarations visible.
9620  for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9621  TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9622  IdentifierInfo *II = TLD->first;
9623  for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9624  pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
9625  }
9626  }
9627 
9628  // Load any pending macro definitions.
9629  for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
9630  IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9632  GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9633  // Initialize the macro history from chained-PCHs ahead of module imports.
9634  for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9635  ++IDIdx) {
9636  const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9637  if (!Info.M->isModule())
9638  resolvePendingMacro(II, Info);
9639  }
9640  // Handle module imports.
9641  for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9642  ++IDIdx) {
9643  const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9644  if (Info.M->isModule())
9645  resolvePendingMacro(II, Info);
9646  }
9647  }
9648  PendingMacroIDs.clear();
9649 
9650  // Wire up the DeclContexts for Decls that we delayed setting until
9651  // recursive loading is completed.
9652  while (!PendingDeclContextInfos.empty()) {
9653  PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9654  PendingDeclContextInfos.pop_front();
9655  DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9656  DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9657  Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9658  }
9659 
9660  // Perform any pending declaration updates.
9661  while (!PendingUpdateRecords.empty()) {
9662  auto Update = PendingUpdateRecords.pop_back_val();
9663  ReadingKindTracker ReadingKind(Read_Decl, *this);
9664  loadDeclUpdateRecords(Update);
9665  }
9666 
9667  while (!PendingObjCExtensionIvarRedeclarations.empty()) {
9668  auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
9669  auto DuplicateIvars =
9670  PendingObjCExtensionIvarRedeclarations.back().second;
9671  llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
9673  ExtensionsPair.first->getASTContext(),
9674  ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
9675  StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
9676  /*Complain =*/false,
9677  /*ErrorOnTagTypeMismatch =*/true);
9678  if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
9679  // Merge redeclared ivars with their predecessors.
9680  for (auto IvarPair : DuplicateIvars) {
9681  ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
9682  // Change semantic DeclContext but keep the lexical one.
9683  Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
9684  Ivar->getLexicalDeclContext(),
9685  getContext());
9686  getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
9687  }
9688  // Invalidate duplicate extension and the cached ivar list.
9689  ExtensionsPair.first->setInvalidDecl();
9690  ExtensionsPair.second->getClassInterface()
9691  ->getDefinition()
9692  ->setIvarList(nullptr);
9693  } else {
9694  for (auto IvarPair : DuplicateIvars) {
9695  Diag(IvarPair.first->getLocation(),
9696  diag::err_duplicate_ivar_declaration)
9697  << IvarPair.first->getIdentifier();
9698  Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
9699  }
9700  }
9701  PendingObjCExtensionIvarRedeclarations.pop_back();
9702  }
9703  }
9704 
9705  // At this point, all update records for loaded decls are in place, so any
9706  // fake class definitions should have become real.
9707  assert(PendingFakeDefinitionData.empty() &&
9708  "faked up a class definition but never saw the real one");
9709 
9710  // If we deserialized any C++ or Objective-C class definitions, any
9711  // Objective-C protocol definitions, or any redeclarable templates, make sure
9712  // that all redeclarations point to the definitions. Note that this can only
9713  // happen now, after the redeclaration chains have been fully wired.
9714  for (Decl *D : PendingDefinitions) {
9715  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9716  if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
9717  // Make sure that the TagType points at the definition.
9718  const_cast<TagType*>(TagT)->decl = TD;
9719  }
9720 
9721  if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
9722  for (auto *R = getMostRecentExistingDecl(RD); R;
9723  R = R->getPreviousDecl()) {
9724  assert((R == D) ==
9725  cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
9726  "declaration thinks it's the definition but it isn't");
9727  cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
9728  }
9729  }
9730 
9731  continue;
9732  }
9733 
9734  if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
9735  // Make sure that the ObjCInterfaceType points at the definition.
9736  const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9737  ->Decl = ID;
9738 
9739  for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9740  cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9741 
9742  continue;
9743  }
9744 
9745  if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
9746  for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9747  cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9748 
9749  continue;
9750  }
9751 
9752  auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9753  for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9754  cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9755  }
9756  PendingDefinitions.clear();
9757 
9758  // Load the bodies of any functions or methods we've encountered. We do
9759  // this now (delayed) so that we can be sure that the declaration chains
9760  // have been fully wired up (hasBody relies on this).
9761  // FIXME: We shouldn't require complete redeclaration chains here.
9762  for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9763  PBEnd = PendingBodies.end();
9764  PB != PBEnd; ++PB) {
9765  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9766  // For a function defined inline within a class template, force the
9767  // canonical definition to be the one inside the canonical definition of
9768  // the template. This ensures that we instantiate from a correct view
9769  // of the template.
9770  //
9771  // Sadly we can't do this more generally: we can't be sure that all
9772  // copies of an arbitrary class definition will have the same members
9773  // defined (eg, some member functions may not be instantiated, and some
9774  // special members may or may not have been implicitly defined).
9775  if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9776  if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9777  continue;
9778 
9779  // FIXME: Check for =delete/=default?
9780  const FunctionDecl *Defn = nullptr;
9781  if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9782  FD->setLazyBody(PB->second);
9783  } else {
9784  auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
9785  mergeDefinitionVisibility(NonConstDefn, FD);
9786 
9787  if (!FD->isLateTemplateParsed() &&
9788  !NonConstDefn->isLateTemplateParsed() &&
9789  // We only perform ODR checks for decls not in the explicit
9790  // global module fragment.
9791  !shouldSkipCheckingODR(FD) &&
9792  FD->getODRHash() != NonConstDefn->getODRHash()) {
9793  if (!isa<CXXMethodDecl>(FD)) {
9794  PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9795  } else if (FD->getLexicalParent()->isFileContext() &&
9796  NonConstDefn->getLexicalParent()->isFileContext()) {
9797  // Only diagnose out-of-line method definitions. If they are
9798  // in class definitions, then an error will be generated when
9799  // processing the class bodies.
9800  PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9801  }
9802  }
9803  }
9804  continue;
9805  }
9806 
9807  ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9808  if (!getContext().getLangOpts().Modules || !MD->hasBody())
9809  MD->setLazyBody(PB->second);
9810  }
9811  PendingBodies.clear();
9812 
9813  // Inform any classes that had members added that they now have more members.
9814  for (auto [RD, MD] : PendingAddedClassMembers) {
9815  RD->addedMember(MD);
9816  }
9817  PendingAddedClassMembers.clear();
9818 
9819  // Do some cleanup.
9820  for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9822  PendingMergedDefinitionsToDeduplicate.clear();
9823 }
9824 
9825 void ASTReader::diagnoseOdrViolations() {
9826  if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9827  PendingRecordOdrMergeFailures.empty() &&
9828  PendingFunctionOdrMergeFailures.empty() &&
9829  PendingEnumOdrMergeFailures.empty() &&
9830  PendingObjCInterfaceOdrMergeFailures.empty() &&
9831  PendingObjCProtocolOdrMergeFailures.empty())
9832  return;
9833 
9834  // Trigger the import of the full definition of each class that had any
9835  // odr-merging problems, so we can produce better diagnostics for them.
9836  // These updates may in turn find and diagnose some ODR failures, so take
9837  // ownership of the set first.
9838  auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9839  PendingOdrMergeFailures.clear();
9840  for (auto &Merge : OdrMergeFailures) {
9841  Merge.first->buildLookup();
9842  Merge.first->decls_begin();
9843  Merge.first->bases_begin();
9844  Merge.first->vbases_begin();
9845  for (auto &RecordPair : Merge.second) {
9846  auto *RD = RecordPair.first;
9847  RD->decls_begin();
9848  RD->bases_begin();
9849  RD->vbases_begin();
9850  }
9851  }
9852 
9853  // Trigger the import of the full definition of each record in C/ObjC.
9854  auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
9855  PendingRecordOdrMergeFailures.clear();
9856  for (auto &Merge : RecordOdrMergeFailures) {
9857  Merge.first->decls_begin();
9858  for (auto &D : Merge.second)
9859  D->decls_begin();
9860  }
9861 
9862  // Trigger the import of the full interface definition.
9863  auto ObjCInterfaceOdrMergeFailures =
9864  std::move(PendingObjCInterfaceOdrMergeFailures);
9865  PendingObjCInterfaceOdrMergeFailures.clear();
9866  for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
9867  Merge.first->decls_begin();
9868  for (auto &InterfacePair : Merge.second)
9869  InterfacePair.first->decls_begin();
9870  }
9871 
9872  // Trigger the import of functions.
9873  auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9874  PendingFunctionOdrMergeFailures.clear();
9875  for (auto &Merge : FunctionOdrMergeFailures) {
9876  Merge.first->buildLookup();
9877  Merge.first->decls_begin();
9878  Merge.first->getBody();
9879  for (auto &FD : Merge.second) {
9880  FD->buildLookup();
9881  FD->decls_begin();
9882  FD->getBody();
9883  }
9884  }
9885 
9886  // Trigger the import of enums.
9887  auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9888  PendingEnumOdrMergeFailures.clear();
9889  for (auto &Merge : EnumOdrMergeFailures) {
9890  Merge.first->decls_begin();
9891  for (auto &Enum : Merge.second) {
9892  Enum->decls_begin();
9893  }
9894  }
9895 
9896  // Trigger the import of the full protocol definition.
9897  auto ObjCProtocolOdrMergeFailures =
9898  std::move(PendingObjCProtocolOdrMergeFailures);
9899  PendingObjCProtocolOdrMergeFailures.clear();
9900  for (auto &Merge : ObjCProtocolOdrMergeFailures) {
9901  Merge.first->decls_begin();
9902  for (auto &ProtocolPair : Merge.second)
9903  ProtocolPair.first->decls_begin();
9904  }
9905 
9906  // For each declaration from a merged context, check that the canonical
9907  // definition of that context also contains a declaration of the same
9908  // entity.
9909  //
9910  // Caution: this loop does things that might invalidate iterators into
9911  // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9912  while (!PendingOdrMergeChecks.empty()) {
9913  NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9914 
9915  // FIXME: Skip over implicit declarations for now. This matters for things
9916  // like implicitly-declared special member functions. This isn't entirely
9917  // correct; we can end up with multiple unmerged declarations of the same
9918  // implicit entity.
9919  if (D->isImplicit())
9920  continue;
9921 
9922  DeclContext *CanonDef = D->getDeclContext();
9923 
9924  bool Found = false;
9925  const Decl *DCanon = D->getCanonicalDecl();
9926 
9927  for (auto *RI : D->redecls()) {
9928  if (RI->getLexicalDeclContext() == CanonDef) {
9929  Found = true;
9930  break;
9931  }
9932  }
9933  if (Found)
9934  continue;
9935 
9936  // Quick check failed, time to do the slow thing. Note, we can't just
9937  // look up the name of D in CanonDef here, because the member that is
9938  // in CanonDef might not be found by name lookup (it might have been
9939  // replaced by a more recent declaration in the lookup table), and we
9940  // can't necessarily find it in the redeclaration chain because it might
9941  // be merely mergeable, not redeclarable.
9943  for (auto *CanonMember : CanonDef->decls()) {
9944  if (CanonMember->getCanonicalDecl() == DCanon) {
9945  // This can happen if the declaration is merely mergeable and not
9946  // actually redeclarable (we looked for redeclarations earlier).
9947  //
9948  // FIXME: We should be able to detect this more efficiently, without
9949  // pulling in all of the members of CanonDef.
9950  Found = true;
9951  break;
9952  }
9953  if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9954  if (ND->getDeclName() == D->getDeclName())
9955  Candidates.push_back(ND);
9956  }
9957 
9958  if (!Found) {
9959  // The AST doesn't like TagDecls becoming invalid after they've been
9960  // completed. We only really need to mark FieldDecls as invalid here.
9961  if (!isa<TagDecl>(D))
9962  D->setInvalidDecl();
9963 
9964  // Ensure we don't accidentally recursively enter deserialization while
9965  // we're producing our diagnostic.
9966  Deserializing RecursionGuard(this);
9967 
9968  std::string CanonDefModule =
9970  cast<Decl>(CanonDef));
9971  Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9973  << CanonDef << CanonDefModule.empty() << CanonDefModule;
9974 
9975  if (Candidates.empty())
9976  Diag(cast<Decl>(CanonDef)->getLocation(),
9977  diag::note_module_odr_violation_no_possible_decls) << D;
9978  else {
9979  for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9980  Diag(Candidates[I]->getLocation(),
9981  diag::note_module_odr_violation_possible_decl)
9982  << Candidates[I];
9983  }
9984 
9985  DiagnosedOdrMergeFailures.insert(CanonDef);
9986  }
9987  }
9988 
9989  if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
9990  FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
9991  ObjCInterfaceOdrMergeFailures.empty() &&
9992  ObjCProtocolOdrMergeFailures.empty())
9993  return;
9994 
9995  ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
9996  getPreprocessor().getLangOpts());
9997 
9998  // Issue any pending ODR-failure diagnostics.
9999  for (auto &Merge : OdrMergeFailures) {
10000  // If we've already pointed out a specific problem with this class, don't
10001  // bother issuing a general "something's different" diagnostic.
10002  if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10003  continue;
10004 
10005  bool Diagnosed = false;
10006  CXXRecordDecl *FirstRecord = Merge.first;
10007  for (auto &RecordPair : Merge.second) {
10008  if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
10009  RecordPair.second)) {
10010  Diagnosed = true;
10011  break;
10012  }
10013  }
10014 
10015  if (!Diagnosed) {
10016  // All definitions are updates to the same declaration. This happens if a
10017  // module instantiates the declaration of a class template specialization
10018  // and two or more other modules instantiate its definition.
10019  //
10020  // FIXME: Indicate which modules had instantiations of this definition.
10021  // FIXME: How can this even happen?
10022  Diag(Merge.first->getLocation(),
10023  diag::err_module_odr_violation_different_instantiations)
10024  << Merge.first;
10025  }
10026  }
10027 
10028  // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
10029  // that in C++ this is done as a part of CXXRecordDecl ODR checking.
10030  for (auto &Merge : RecordOdrMergeFailures) {
10031  // If we've already pointed out a specific problem with this class, don't
10032  // bother issuing a general "something's different" diagnostic.
10033  if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10034  continue;
10035 
10036  RecordDecl *FirstRecord = Merge.first;
10037  bool Diagnosed = false;
10038  for (auto *SecondRecord : Merge.second) {
10039  if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
10040  Diagnosed = true;
10041  break;
10042  }
10043  }
10044  (void)Diagnosed;
10045  assert(Diagnosed && "Unable to emit ODR diagnostic.");
10046  }
10047 
10048  // Issue ODR failures diagnostics for functions.
10049  for (auto &Merge : FunctionOdrMergeFailures) {
10050  FunctionDecl *FirstFunction = Merge.first;
10051  bool Diagnosed = false;
10052  for (auto &SecondFunction : Merge.second) {
10053  if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
10054  Diagnosed = true;
10055  break;
10056  }
10057  }
10058  (void)Diagnosed;
10059  assert(Diagnosed && "Unable to emit ODR diagnostic.");
10060  }
10061 
10062  // Issue ODR failures diagnostics for enums.
10063  for (auto &Merge : EnumOdrMergeFailures) {
10064  // If we've already pointed out a specific problem with this enum, don't
10065  // bother issuing a general "something's different" diagnostic.
10066  if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10067  continue;
10068 
10069  EnumDecl *FirstEnum = Merge.first;
10070  bool Diagnosed = false;
10071  for (auto &SecondEnum : Merge.second) {
10072  if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
10073  Diagnosed = true;
10074  break;
10075  }
10076  }
10077  (void)Diagnosed;
10078  assert(Diagnosed && "Unable to emit ODR diagnostic.");
10079  }
10080 
10081  for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
10082  // If we've already pointed out a specific problem with this interface,
10083  // don't bother issuing a general "something's different" diagnostic.
10084  if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10085  continue;
10086 
10087  bool Diagnosed = false;
10088  ObjCInterfaceDecl *FirstID = Merge.first;
10089  for (auto &InterfacePair : Merge.second) {
10090  if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
10091  InterfacePair.second)) {
10092  Diagnosed = true;
10093  break;
10094  }
10095  }
10096  (void)Diagnosed;
10097  assert(Diagnosed && "Unable to emit ODR diagnostic.");
10098  }
10099 
10100  for (auto &Merge : ObjCProtocolOdrMergeFailures) {
10101  // If we've already pointed out a specific problem with this protocol,
10102  // don't bother issuing a general "something's different" diagnostic.
10103  if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
10104  continue;
10105 
10106  ObjCProtocolDecl *FirstProtocol = Merge.first;
10107  bool Diagnosed = false;
10108  for (auto &ProtocolPair : Merge.second) {
10109  if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
10110  ProtocolPair.second)) {
10111  Diagnosed = true;
10112  break;
10113  }
10114  }
10115  (void)Diagnosed;
10116  assert(Diagnosed && "Unable to emit ODR diagnostic.");
10117  }
10118 }
10119 
10121  if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
10122  ReadTimer->startTimer();
10123 }
10124 
10126  assert(NumCurrentElementsDeserializing &&
10127  "FinishedDeserializing not paired with StartedDeserializing");
10128  if (NumCurrentElementsDeserializing == 1) {
10129  // We decrease NumCurrentElementsDeserializing only after pending actions
10130  // are finished, to avoid recursively re-calling finishPendingActions().
10131  finishPendingActions();
10132  }
10133  --NumCurrentElementsDeserializing;
10134 
10135  if (NumCurrentElementsDeserializing == 0) {
10136  // Propagate exception specification and deduced type updates along
10137  // redeclaration chains.
10138  //
10139  // We do this now rather than in finishPendingActions because we want to
10140  // be able to walk the complete redeclaration chains of the updated decls.
10141  while (!PendingExceptionSpecUpdates.empty() ||
10142  !PendingDeducedTypeUpdates.empty()) {
10143  auto ESUpdates = std::move(PendingExceptionSpecUpdates);
10144  PendingExceptionSpecUpdates.clear();
10145  for (auto Update : ESUpdates) {
10146  ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10147  auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
10148  auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
10149  if (auto *Listener = getContext().getASTMutationListener())
10150  Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
10151  for (auto *Redecl : Update.second->redecls())
10152  getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
10153  }
10154 
10155  auto DTUpdates = std::move(PendingDeducedTypeUpdates);
10156  PendingDeducedTypeUpdates.clear();
10157  for (auto Update : DTUpdates) {
10158  ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
10159  // FIXME: If the return type is already deduced, check that it matches.
10161  Update.second);
10162  }
10163 
10164  auto UDTUpdates = std::move(PendingUndeducedFunctionDecls);
10165  PendingUndeducedFunctionDecls.clear();
10166  // We hope we can find the deduced type for the functions by iterating
10167  // redeclarations in other modules.
10168  for (FunctionDecl *UndeducedFD : UDTUpdates)
10169  (void)UndeducedFD->getMostRecentDecl();
10170  }
10171 
10172  if (ReadTimer)
10173  ReadTimer->stopTimer();
10174 
10175  diagnoseOdrViolations();
10176 
10177  // We are not in recursive loading, so it's safe to pass the "interesting"
10178  // decls to the consumer.
10179  if (Consumer)
10180  PassInterestingDeclsToConsumer();
10181  }
10182 }
10183 
10184 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
10185  if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
10186  // Remove any fake results before adding any real ones.
10187  auto It = PendingFakeLookupResults.find(II);
10188  if (It != PendingFakeLookupResults.end()) {
10189  for (auto *ND : It->second)
10190  SemaObj->IdResolver.RemoveDecl(ND);
10191  // FIXME: this works around module+PCH performance issue.
10192  // Rather than erase the result from the map, which is O(n), just clear
10193  // the vector of NamedDecls.
10194  It->second.clear();
10195  }
10196  }
10197 
10198  if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
10199  SemaObj->TUScope->AddDecl(D);
10200  } else if (SemaObj->TUScope) {
10201  // Adding the decl to IdResolver may have failed because it was already in
10202  // (even though it was not added in scope). If it is already in, make sure
10203  // it gets in the scope as well.
10204  if (llvm::is_contained(SemaObj->IdResolver.decls(Name), D))
10205  SemaObj->TUScope->AddDecl(D);
10206  }
10207 }
10208 
10210  ASTContext *Context,
10211  const PCHContainerReader &PCHContainerRdr,
10212  ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
10213  StringRef isysroot,
10214  DisableValidationForModuleKind DisableValidationKind,
10215  bool AllowASTWithCompilerErrors,
10216  bool AllowConfigurationMismatch, bool ValidateSystemInputs,
10217  bool ValidateASTInputFilesContent, bool UseGlobalIndex,
10218  std::unique_ptr<llvm::Timer> ReadTimer)
10219  : Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH)
10221  : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
10222  SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
10223  PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
10224  ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
10225  PCHContainerRdr, PP.getHeaderSearchInfo()),
10226  DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
10227  DisableValidationKind(DisableValidationKind),
10228  AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
10229  AllowConfigurationMismatch(AllowConfigurationMismatch),
10230  ValidateSystemInputs(ValidateSystemInputs),
10231  ValidateASTInputFilesContent(ValidateASTInputFilesContent),
10232  UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
10233  SourceMgr.setExternalSLocEntrySource(this);
10234 
10235  for (const auto &Ext : Extensions) {
10236  auto BlockName = Ext->getExtensionMetadata().BlockName;
10237  auto Known = ModuleFileExtensions.find(BlockName);
10238  if (Known != ModuleFileExtensions.end()) {
10239  Diags.Report(diag::warn_duplicate_module_file_extension)
10240  << BlockName;
10241  continue;
10242  }
10243 
10244  ModuleFileExtensions.insert({BlockName, Ext});
10245  }
10246 }
10247 
10249  if (OwnsDeserializationListener)
10250  delete DeserializationListener;
10251 }
10252 
10254  return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
10255 }
10256 
10258  unsigned AbbrevID) {
10259  Idx = 0;
10260  Record.clear();
10261  return Cursor.readRecord(AbbrevID, Record);
10262 }
10263 //===----------------------------------------------------------------------===//
10264 //// OMPClauseReader implementation
10265 ////===----------------------------------------------------------------------===//
10266 
10267 // This has to be in namespace clang because it's friended by all
10268 // of the OMP clauses.
10269 namespace clang {
10270 
10271 class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
10273  ASTContext &Context;
10274 
10275 public:
10277  : Record(Record), Context(Record.getContext()) {}
10278 #define GEN_CLANG_CLAUSE_CLASS
10279 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
10280 #include "llvm/Frontend/OpenMP/OMP.inc"
10281  OMPClause *readClause();
10284 };
10285 
10286 } // end namespace clang
10287 
10289  return OMPClauseReader(*this).readClause();
10290 }
10291 
10293  OMPClause *C = nullptr;
10294  switch (llvm::omp::Clause(Record.readInt())) {
10295  case llvm::omp::OMPC_if:
10296  C = new (Context) OMPIfClause();
10297  break;
10298  case llvm::omp::OMPC_final:
10299  C = new (Context) OMPFinalClause();
10300  break;
10301  case llvm::omp::OMPC_num_threads:
10302  C = new (Context) OMPNumThreadsClause();
10303  break;
10304  case llvm::omp::OMPC_safelen:
10305  C = new (Context) OMPSafelenClause();
10306  break;
10307  case llvm::omp::OMPC_simdlen:
10308  C = new (Context) OMPSimdlenClause();
10309  break;
10310  case llvm::omp::OMPC_sizes: {
10311  unsigned NumSizes = Record.readInt();
10312  C = OMPSizesClause::CreateEmpty(Context, NumSizes);
10313  break;
10314  }
10315  case llvm::omp::OMPC_full:
10316  C = OMPFullClause::CreateEmpty(Context);
10317  break;
10318  case llvm::omp::OMPC_partial:
10319  C = OMPPartialClause::CreateEmpty(Context);
10320  break;
10321  case llvm::omp::OMPC_allocator:
10322  C = new (Context) OMPAllocatorClause();
10323  break;
10324  case llvm::omp::OMPC_collapse:
10325  C = new (Context) OMPCollapseClause();
10326  break;
10327  case llvm::omp::OMPC_default:
10328  C = new (Context) OMPDefaultClause();
10329  break;
10330  case llvm::omp::OMPC_proc_bind:
10331  C = new (Context) OMPProcBindClause();
10332  break;
10333  case llvm::omp::OMPC_schedule:
10334  C = new (Context) OMPScheduleClause();
10335  break;
10336  case llvm::omp::OMPC_ordered:
10337  C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
10338  break;
10339  case llvm::omp::OMPC_nowait:
10340  C = new (Context) OMPNowaitClause();
10341  break;
10342  case llvm::omp::OMPC_untied:
10343  C = new (Context) OMPUntiedClause();
10344  break;
10345  case llvm::omp::OMPC_mergeable:
10346  C = new (Context) OMPMergeableClause();
10347  break;
10348  case llvm::omp::OMPC_read:
10349  C = new (Context) OMPReadClause();
10350  break;
10351  case llvm::omp::OMPC_write:
10352  C = new (Context) OMPWriteClause();
10353  break;
10354  case llvm::omp::OMPC_update:
10355  C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
10356  break;
10357  case llvm::omp::OMPC_capture:
10358  C = new (Context) OMPCaptureClause();
10359  break;
10360  case llvm::omp::OMPC_compare:
10361  C = new (Context) OMPCompareClause();
10362  break;
10363  case llvm::omp::OMPC_fail:
10364  C = new (Context) OMPFailClause();
10365  break;
10366  case llvm::omp::OMPC_seq_cst:
10367  C = new (Context) OMPSeqCstClause();
10368  break;
10369  case llvm::omp::OMPC_acq_rel:
10370  C = new (Context) OMPAcqRelClause();
10371  break;
10372  case llvm::omp::OMPC_acquire:
10373  C = new (Context) OMPAcquireClause();
10374  break;
10375  case llvm::omp::OMPC_release:
10376  C = new (Context) OMPReleaseClause();
10377  break;
10378  case llvm::omp::OMPC_relaxed:
10379  C = new (Context) OMPRelaxedClause();
10380  break;
10381  case llvm::omp::OMPC_weak:
10382  C = new (Context) OMPWeakClause();
10383  break;
10384  case llvm::omp::OMPC_threads:
10385  C = new (Context) OMPThreadsClause();
10386  break;
10387  case llvm::omp::OMPC_simd:
10388  C = new (Context) OMPSIMDClause();
10389  break;
10390  case llvm::omp::OMPC_nogroup:
10391  C = new (Context) OMPNogroupClause();
10392  break;
10393  case llvm::omp::OMPC_unified_address:
10394  C = new (Context) OMPUnifiedAddressClause();
10395  break;
10396  case llvm::omp::OMPC_unified_shared_memory:
10397  C = new (Context) OMPUnifiedSharedMemoryClause();
10398  break;
10399  case llvm::omp::OMPC_reverse_offload:
10400  C = new (Context) OMPReverseOffloadClause();
10401  break;
10402  case llvm::omp::OMPC_dynamic_allocators:
10403  C = new (Context) OMPDynamicAllocatorsClause();
10404  break;
10405  case llvm::omp::OMPC_atomic_default_mem_order:
10406  C = new (Context) OMPAtomicDefaultMemOrderClause();
10407  break;
10408  case llvm::omp::OMPC_at:
10409  C = new (Context) OMPAtClause();
10410  break;
10411  case llvm::omp::OMPC_severity:
10412  C = new (Context) OMPSeverityClause();
10413  break;
10414  case llvm::omp::OMPC_message:
10415  C = new (Context) OMPMessageClause();
10416  break;
10417  case llvm::omp::OMPC_private:
10418  C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
10419  break;
10420  case llvm::omp::OMPC_firstprivate:
10421  C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
10422  break;
10423  case llvm::omp::OMPC_lastprivate:
10424  C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
10425  break;
10426  case llvm::omp::OMPC_shared:
10427  C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
10428  break;
10429  case llvm::omp::OMPC_reduction: {
10430  unsigned N = Record.readInt();
10431  auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
10432  C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
10433  break;
10434  }
10435  case llvm::omp::OMPC_task_reduction:
10436  C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
10437  break;
10438  case llvm::omp::OMPC_in_reduction:
10439  C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
10440  break;
10441  case llvm::omp::OMPC_linear:
10442  C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
10443  break;
10444  case llvm::omp::OMPC_aligned:
10445  C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
10446  break;
10447  case llvm::omp::OMPC_copyin:
10448  C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
10449  break;
10450  case llvm::omp::OMPC_copyprivate:
10451  C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
10452  break;
10453  case llvm::omp::OMPC_flush:
10454  C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
10455  break;
10456  case llvm::omp::OMPC_depobj:
10457  C = OMPDepobjClause::CreateEmpty(Context);
10458  break;
10459  case llvm::omp::OMPC_depend: {
10460  unsigned NumVars = Record.readInt();
10461  unsigned NumLoops = Record.readInt();
10462  C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
10463  break;
10464  }
10465  case llvm::omp::OMPC_device:
10466  C = new (Context) OMPDeviceClause();
10467  break;
10468  case llvm::omp::OMPC_map: {
10470  Sizes.NumVars = Record.readInt();
10471  Sizes.NumUniqueDeclarations = Record.readInt();
10472  Sizes.NumComponentLists = Record.readInt();
10473  Sizes.NumComponents = Record.readInt();
10474  C = OMPMapClause::CreateEmpty(Context, Sizes);
10475  break;
10476  }
10477  case llvm::omp::OMPC_num_teams:
10478  C = new (Context) OMPNumTeamsClause();
10479  break;
10480  case llvm::omp::OMPC_thread_limit:
10481  C = new (Context) OMPThreadLimitClause();
10482  break;
10483  case llvm::omp::OMPC_priority:
10484  C = new (Context) OMPPriorityClause();
10485  break;
10486  case llvm::omp::OMPC_grainsize:
10487  C = new (Context) OMPGrainsizeClause();
10488  break;
10489  case llvm::omp::OMPC_num_tasks:
10490  C = new (Context) OMPNumTasksClause();
10491  break;
10492  case llvm::omp::OMPC_hint:
10493  C = new (Context) OMPHintClause();
10494  break;
10495  case llvm::omp::OMPC_dist_schedule:
10496  C = new (Context) OMPDistScheduleClause();
10497  break;
10498  case llvm::omp::OMPC_defaultmap:
10499  C = new (Context) OMPDefaultmapClause();
10500  break;
10501  case llvm::omp::OMPC_to: {
10503  Sizes.NumVars = Record.readInt();
10504  Sizes.NumUniqueDeclarations = Record.readInt();
10505  Sizes.NumComponentLists = Record.readInt();
10506  Sizes.NumComponents = Record.readInt();
10507  C = OMPToClause::CreateEmpty(Context, Sizes);
10508  break;
10509  }
10510  case llvm::omp::OMPC_from: {
10512  Sizes.NumVars = Record.readInt();
10513  Sizes.NumUniqueDeclarations = Record.readInt();
10514  Sizes.NumComponentLists = Record.readInt();
10515  Sizes.NumComponents = Record.readInt();
10516  C = OMPFromClause::CreateEmpty(Context, Sizes);
10517  break;
10518  }
10519  case llvm::omp::OMPC_use_device_ptr: {
10521  Sizes.NumVars = Record.readInt();
10522  Sizes.NumUniqueDeclarations = Record.readInt();
10523  Sizes.NumComponentLists = Record.readInt();
10524  Sizes.NumComponents = Record.readInt();
10525  C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
10526  break;
10527  }
10528  case llvm::omp::OMPC_use_device_addr: {
10530  Sizes.NumVars = Record.readInt();
10531  Sizes.NumUniqueDeclarations = Record.readInt();
10532  Sizes.NumComponentLists = Record.readInt();
10533  Sizes.NumComponents = Record.readInt();
10534  C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
10535  break;
10536  }
10537  case llvm::omp::OMPC_is_device_ptr: {
10539  Sizes.NumVars = Record.readInt();
10540  Sizes.NumUniqueDeclarations = Record.readInt();
10541  Sizes.NumComponentLists = Record.readInt();
10542  Sizes.NumComponents = Record.readInt();
10543  C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
10544  break;
10545  }
10546  case llvm::omp::OMPC_has_device_addr: {
10548  Sizes.NumVars = Record.readInt();
10549  Sizes.NumUniqueDeclarations = Record.readInt();
10550  Sizes.NumComponentLists = Record.readInt();
10551  Sizes.NumComponents = Record.readInt();
10552  C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
10553  break;
10554  }
10555  case llvm::omp::OMPC_allocate:
10556  C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
10557  break;
10558  case llvm::omp::OMPC_nontemporal:
10559  C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
10560  break;
10561  case llvm::omp::OMPC_inclusive:
10562  C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
10563  break;
10564  case llvm::omp::OMPC_exclusive:
10565  C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
10566  break;
10567  case llvm::omp::OMPC_order:
10568  C = new (Context) OMPOrderClause();
10569  break;
10570  case llvm::omp::OMPC_init:
10571  C = OMPInitClause::CreateEmpty(Context, Record.readInt());
10572  break;
10573  case llvm::omp::OMPC_use:
10574  C = new (Context) OMPUseClause();
10575  break;
10576  case llvm::omp::OMPC_destroy:
10577  C = new (Context) OMPDestroyClause();
10578  break;
10579  case llvm::omp::OMPC_novariants:
10580  C = new (Context) OMPNovariantsClause();
10581  break;
10582  case llvm::omp::OMPC_nocontext:
10583  C = new (Context) OMPNocontextClause();
10584  break;
10585  case llvm::omp::OMPC_detach:
10586  C = new (Context) OMPDetachClause();
10587  break;
10588  case llvm::omp::OMPC_uses_allocators:
10589  C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
10590  break;
10591  case llvm::omp::OMPC_affinity:
10592  C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
10593  break;
10594  case llvm::omp::OMPC_filter:
10595  C = new (Context) OMPFilterClause();
10596  break;
10597  case llvm::omp::OMPC_bind:
10598  C = OMPBindClause::CreateEmpty(Context);
10599  break;
10600  case llvm::omp::OMPC_align:
10601  C = new (Context) OMPAlignClause();
10602  break;
10603  case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
10604  C = new (Context) OMPXDynCGroupMemClause();
10605  break;
10606  case llvm::omp::OMPC_doacross: {
10607  unsigned NumVars = Record.readInt();
10608  unsigned NumLoops = Record.readInt();
10609  C = OMPDoacrossClause::CreateEmpty(Context, NumVars, NumLoops);
10610  break;
10611  }
10612  case llvm::omp::OMPC_ompx_attribute:
10613  C = new (Context) OMPXAttributeClause();
10614  break;
10615  case llvm::omp::OMPC_ompx_bare:
10616  C = new (Context) OMPXBareClause();
10617  break;
10618 #define OMP_CLAUSE_NO_CLASS(Enum, Str) \
10619  case llvm::omp::Enum: \
10620  break;
10621 #include "llvm/Frontend/OpenMP/OMPKinds.def"
10622  default:
10623  break;
10624  }
10625  assert(C && "Unknown OMPClause type");
10626 
10627  Visit(C);
10628  C->setLocStart(Record.readSourceLocation());
10629  C->setLocEnd(Record.readSourceLocation());
10630 
10631  return C;
10632 }
10633 
10635  C->setPreInitStmt(Record.readSubStmt(),
10636  static_cast<OpenMPDirectiveKind>(Record.readInt()));
10637 }
10638 
10641  C->setPostUpdateExpr(Record.readSubExpr());
10642 }
10643 
10644 void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
10646  C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
10647  C->setNameModifierLoc(Record.readSourceLocation());
10648  C->setColonLoc(Record.readSourceLocation());
10649  C->setCondition(Record.readSubExpr());
10650  C->setLParenLoc(Record.readSourceLocation());
10651 }
10652 
10653 void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
10655  C->setCondition(Record.readSubExpr());
10656  C->setLParenLoc(Record.readSourceLocation());
10657 }
10658 
10659 void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
10661  C->setNumThreads(Record.readSubExpr());
10662  C->setLParenLoc(Record.readSourceLocation());
10663 }
10664 
10665 void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
10666  C->setSafelen(Record.readSubExpr());
10667  C->setLParenLoc(Record.readSourceLocation());
10668 }
10669 
10670 void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
10671  C->setSimdlen(Record.readSubExpr());
10672  C->setLParenLoc(Record.readSourceLocation());
10673 }
10674 
10675 void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
10676  for (Expr *&E : C->getSizesRefs())
10677  E = Record.readSubExpr();
10678  C->setLParenLoc(Record.readSourceLocation());
10679 }
10680 
10681 void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
10682 
10683 void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
10684  C->setFactor(Record.readSubExpr());
10685  C->setLParenLoc(Record.readSourceLocation());
10686 }
10687 
10688 void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
10689  C->setAllocator(Record.readExpr());
10690  C->setLParenLoc(Record.readSourceLocation());
10691 }
10692 
10693 void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
10694  C->setNumForLoops(Record.readSubExpr());
10695  C->setLParenLoc(Record.readSourceLocation());
10696 }
10697 
10698 void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
10699  C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
10700  C->setLParenLoc(Record.readSourceLocation());
10701  C->setDefaultKindKwLoc(Record.readSourceLocation());
10702 }
10703 
10704 void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
10705  C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
10706  C->setLParenLoc(Record.readSourceLocation());
10707  C->setProcBindKindKwLoc(Record.readSourceLocation());
10708 }
10709 
10710 void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
10712  C->setScheduleKind(
10713  static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
10714  C->setFirstScheduleModifier(
10715  static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10716  C->setSecondScheduleModifier(
10717  static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
10718  C->setChunkSize(Record.readSubExpr());
10719  C->setLParenLoc(Record.readSourceLocation());
10720  C->setFirstScheduleModifierLoc(Record.readSourceLocation());
10721  C->setSecondScheduleModifierLoc(Record.readSourceLocation());
10722  C->setScheduleKindLoc(Record.readSourceLocation());
10723  C->setCommaLoc(Record.readSourceLocation());
10724 }
10725 
10726 void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
10727  C->setNumForLoops(Record.readSubExpr());
10728  for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10729  C->setLoopNumIterations(I, Record.readSubExpr());
10730  for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
10731  C->setLoopCounter(I, Record.readSubExpr());
10732  C->setLParenLoc(Record.readSourceLocation());
10733 }
10734 
10735 void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
10736  C->setEventHandler(Record.readSubExpr());
10737  C->setLParenLoc(Record.readSourceLocation());
10738 }
10739 
10740 void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
10741 
10742 void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
10743 
10744 void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
10745 
10746 void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
10747 
10748 void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
10749 
10750 void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
10751  if (C->isExtended()) {
10752  C->setLParenLoc(Record.readSourceLocation());
10753  C->setArgumentLoc(Record.readSourceLocation());
10754  C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
10755  }
10756 }
10757 
10758 void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
10759 
10760 void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
10761 
10762 // Read the parameter of fail clause. This will have been saved when
10763 // OMPClauseWriter is called.
10764 void OMPClauseReader::VisitOMPFailClause(OMPFailClause *C) {
10765  C->setLParenLoc(Record.readSourceLocation());
10766  SourceLocation FailParameterLoc = Record.readSourceLocation();
10767  C->setFailParameterLoc(FailParameterLoc);
10768  OpenMPClauseKind CKind = Record.readEnum<OpenMPClauseKind>();
10769  C->setFailParameter(CKind);
10770 }
10771 
10772 void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
10773 
10774 void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
10775 
10776 void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
10777 
10778 void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
10779 
10780 void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
10781 
10782 void OMPClauseReader::VisitOMPWeakClause(OMPWeakClause *) {}
10783 
10784 void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
10785 
10786 void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
10787 
10788 void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
10789 
10790 void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
10791  unsigned NumVars = C->varlist_size();
10793  Vars.reserve(NumVars);
10794  for (unsigned I = 0; I != NumVars; ++I)
10795  Vars.push_back(Record.readSubExpr());
10796  C->setVarRefs(Vars);
10797  C->setIsTarget(Record.readBool());
10798  C->setIsTargetSync(Record.readBool());
10799  C->setLParenLoc(Record.readSourceLocation());
10800  C->setVarLoc(Record.readSourceLocation());
10801 }
10802 
10803 void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
10804  C->setInteropVar(Record.readSubExpr());
10805  C->setLParenLoc(Record.readSourceLocation());
10806  C->setVarLoc(Record.readSourceLocation());
10807 }
10808 
10809 void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
10810  C->setInteropVar(Record.readSubExpr());
10811  C->setLParenLoc(Record.readSourceLocation());
10812  C->setVarLoc(Record.readSourceLocation());
10813 }
10814 
10815 void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
10817  C->setCondition(Record.readSubExpr());
10818  C->setLParenLoc(Record.readSourceLocation());
10819 }
10820 
10821 void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
10823  C->setCondition(Record.readSubExpr());
10824  C->setLParenLoc(Record.readSourceLocation());
10825 }
10826 
10827 void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
10828 
10829 void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
10831 
10832 void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
10833 
10834 void
10835 OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
10836 }
10837 
10838 void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
10840  C->setAtomicDefaultMemOrderKind(
10841  static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
10842  C->setLParenLoc(Record.readSourceLocation());
10843  C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
10844 }
10845 
10846 void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
10847  C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
10848  C->setLParenLoc(Record.readSourceLocation());
10849  C->setAtKindKwLoc(Record.readSourceLocation());
10850 }
10851 
10852 void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
10853  C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
10854  C->setLParenLoc(Record.readSourceLocation());
10855  C->setSeverityKindKwLoc(Record.readSourceLocation());
10856 }
10857 
10858 void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
10859  C->setMessageString(Record.readSubExpr());
10860  C->setLParenLoc(Record.readSourceLocation());
10861 }
10862 
10863 void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
10864  C->setLParenLoc(Record.readSourceLocation());
10865  unsigned NumVars = C->varlist_size();
10867  Vars.reserve(NumVars);
10868  for (unsigned i = 0; i != NumVars; ++i)
10869  Vars.push_back(Record.readSubExpr());
10870  C->setVarRefs(Vars);
10871  Vars.clear();
10872  for (unsigned i = 0; i != NumVars; ++i)
10873  Vars.push_back(Record.readSubExpr());
10874  C->setPrivateCopies(Vars);
10875 }
10876 
10877 void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
10879  C->setLParenLoc(Record.readSourceLocation());
10880  unsigned NumVars = C->varlist_size();
10882  Vars.reserve(NumVars);
10883  for (unsigned i = 0; i != NumVars; ++i)
10884  Vars.push_back(Record.readSubExpr());
10885  C->setVarRefs(Vars);
10886  Vars.clear();
10887  for (unsigned i = 0; i != NumVars; ++i)
10888  Vars.push_back(Record.readSubExpr());
10889  C->setPrivateCopies(Vars);
10890  Vars.clear();
10891  for (unsigned i = 0; i != NumVars; ++i)
10892  Vars.push_back(Record.readSubExpr());
10893  C->setInits(Vars);
10894 }
10895 
10896 void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
10898  C->setLParenLoc(Record.readSourceLocation());
10899  C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
10900  C->setKindLoc(Record.readSourceLocation());
10901  C->setColonLoc(Record.readSourceLocation());
10902  unsigned NumVars = C->varlist_size();
10904  Vars.reserve(NumVars);
10905  for (unsigned i = 0; i != NumVars; ++i)
10906  Vars.push_back(Record.readSubExpr());
10907  C->setVarRefs(Vars);
10908  Vars.clear();
10909  for (unsigned i = 0; i != NumVars; ++i)
10910  Vars.push_back(Record.readSubExpr());
10911  C->setPrivateCopies(Vars);
10912  Vars.clear();
10913  for (unsigned i = 0; i != NumVars; ++i)
10914  Vars.push_back(Record.readSubExpr());
10915  C->setSourceExprs(Vars);
10916  Vars.clear();
10917  for (unsigned i = 0; i != NumVars; ++i)
10918  Vars.push_back(Record.readSubExpr());
10919  C->setDestinationExprs(Vars);
10920  Vars.clear();
10921  for (unsigned i = 0; i != NumVars; ++i)
10922  Vars.push_back(Record.readSubExpr());
10923  C->setAssignmentOps(Vars);
10924 }
10925 
10926 void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
10927  C->setLParenLoc(Record.readSourceLocation());
10928  unsigned NumVars = C->varlist_size();
10930  Vars.reserve(NumVars);
10931  for (unsigned i = 0; i != NumVars; ++i)
10932  Vars.push_back(Record.readSubExpr());
10933  C->setVarRefs(Vars);
10934 }
10935 
10936 void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
10938  C->setLParenLoc(Record.readSourceLocation());
10939  C->setModifierLoc(Record.readSourceLocation());
10940  C->setColonLoc(Record.readSourceLocation());
10941  NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10942  DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10943  C->setQualifierLoc(NNSL);
10944  C->setNameInfo(DNI);
10945 
10946  unsigned NumVars = C->varlist_size();
10948  Vars.reserve(NumVars);
10949  for (unsigned i = 0; i != NumVars; ++i)
10950  Vars.push_back(Record.readSubExpr());
10951  C->setVarRefs(Vars);
10952  Vars.clear();
10953  for (unsigned i = 0; i != NumVars; ++i)
10954  Vars.push_back(Record.readSubExpr());
10955  C->setPrivates(Vars);
10956  Vars.clear();
10957  for (unsigned i = 0; i != NumVars; ++i)
10958  Vars.push_back(Record.readSubExpr());
10959  C->setLHSExprs(Vars);
10960  Vars.clear();
10961  for (unsigned i = 0; i != NumVars; ++i)
10962  Vars.push_back(Record.readSubExpr());
10963  C->setRHSExprs(Vars);
10964  Vars.clear();
10965  for (unsigned i = 0; i != NumVars; ++i)
10966  Vars.push_back(Record.readSubExpr());
10967  C->setReductionOps(Vars);
10968  if (C->getModifier() == OMPC_REDUCTION_inscan) {
10969  Vars.clear();
10970  for (unsigned i = 0; i != NumVars; ++i)
10971  Vars.push_back(Record.readSubExpr());
10972  C->setInscanCopyOps(Vars);
10973  Vars.clear();
10974  for (unsigned i = 0; i != NumVars; ++i)
10975  Vars.push_back(Record.readSubExpr());
10976  C->setInscanCopyArrayTemps(Vars);
10977  Vars.clear();
10978  for (unsigned i = 0; i != NumVars; ++i)
10979  Vars.push_back(Record.readSubExpr());
10980  C->setInscanCopyArrayElems(Vars);
10981  }
10982 }
10983 
10984 void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
10986  C->setLParenLoc(Record.readSourceLocation());
10987  C->setColonLoc(Record.readSourceLocation());
10988  NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10989  DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
10990  C->setQualifierLoc(NNSL);
10991  C->setNameInfo(DNI);
10992 
10993  unsigned NumVars = C->varlist_size();
10995  Vars.reserve(NumVars);
10996  for (unsigned I = 0; I != NumVars; ++I)
10997  Vars.push_back(Record.readSubExpr());
10998  C->setVarRefs(Vars);
10999  Vars.clear();
11000  for (unsigned I = 0; I != NumVars; ++I)
11001  Vars.push_back(Record.readSubExpr());
11002  C->setPrivates(Vars);
11003  Vars.clear();
11004  for (unsigned I = 0; I != NumVars; ++I)
11005  Vars.push_back(Record.readSubExpr());
11006  C->setLHSExprs(Vars);
11007  Vars.clear();
11008  for (unsigned I = 0; I != NumVars; ++I)
11009  Vars.push_back(Record.readSubExpr());
11010  C->setRHSExprs(Vars);
11011  Vars.clear();
11012  for (unsigned I = 0; I != NumVars; ++I)
11013  Vars.push_back(Record.readSubExpr());
11014  C->setReductionOps(Vars);
11015 }
11016 
11017 void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
11019  C->setLParenLoc(Record.readSourceLocation());
11020  C->setColonLoc(Record.readSourceLocation());
11021  NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11022  DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11023  C->setQualifierLoc(NNSL);
11024  C->setNameInfo(DNI);
11025 
11026  unsigned NumVars = C->varlist_size();
11028  Vars.reserve(NumVars);
11029  for (unsigned I = 0; I != NumVars; ++I)
11030  Vars.push_back(Record.readSubExpr());
11031  C->setVarRefs(Vars);
11032  Vars.clear();
11033  for (unsigned I = 0; I != NumVars; ++I)
11034  Vars.push_back(Record.readSubExpr());
11035  C->setPrivates(Vars);
11036  Vars.clear();
11037  for (unsigned I = 0; I != NumVars; ++I)
11038  Vars.push_back(Record.readSubExpr());
11039  C->setLHSExprs(Vars);
11040  Vars.clear();
11041  for (unsigned I = 0; I != NumVars; ++I)
11042  Vars.push_back(Record.readSubExpr());
11043  C->setRHSExprs(Vars);
11044  Vars.clear();
11045  for (unsigned I = 0; I != NumVars; ++I)
11046  Vars.push_back(Record.readSubExpr());
11047  C->setReductionOps(Vars);
11048  Vars.clear();
11049  for (unsigned I = 0; I != NumVars; ++I)
11050  Vars.push_back(Record.readSubExpr());
11051  C->setTaskgroupDescriptors(Vars);
11052 }
11053 
11054 void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
11056  C->setLParenLoc(Record.readSourceLocation());
11057  C->setColonLoc(Record.readSourceLocation());
11058  C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
11059  C->setModifierLoc(Record.readSourceLocation());
11060  unsigned NumVars = C->varlist_size();
11062  Vars.reserve(NumVars);
11063  for (unsigned i = 0; i != NumVars; ++i)
11064  Vars.push_back(Record.readSubExpr());
11065  C->setVarRefs(Vars);
11066  Vars.clear();
11067  for (unsigned i = 0; i != NumVars; ++i)
11068  Vars.push_back(Record.readSubExpr());
11069  C->setPrivates(Vars);
11070  Vars.clear();
11071  for (unsigned i = 0; i != NumVars; ++i)
11072  Vars.push_back(Record.readSubExpr());
11073  C->setInits(Vars);
11074  Vars.clear();
11075  for (unsigned i = 0; i != NumVars; ++i)
11076  Vars.push_back(Record.readSubExpr());
11077  C->setUpdates(Vars);
11078  Vars.clear();
11079  for (unsigned i = 0; i != NumVars; ++i)
11080  Vars.push_back(Record.readSubExpr());
11081  C->setFinals(Vars);
11082  C->setStep(Record.readSubExpr());
11083  C->setCalcStep(Record.readSubExpr());
11084  Vars.clear();
11085  for (unsigned I = 0; I != NumVars + 1; ++I)
11086  Vars.push_back(Record.readSubExpr());
11087  C->setUsedExprs(Vars);
11088 }
11089 
11090 void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
11091  C->setLParenLoc(Record.readSourceLocation());
11092  C->setColonLoc(Record.readSourceLocation());
11093  unsigned NumVars = C->varlist_size();
11095  Vars.reserve(NumVars);
11096  for (unsigned i = 0; i != NumVars; ++i)
11097  Vars.push_back(Record.readSubExpr());
11098  C->setVarRefs(Vars);
11099  C->setAlignment(Record.readSubExpr());
11100 }
11101 
11102 void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
11103  C->setLParenLoc(Record.readSourceLocation());
11104  unsigned NumVars = C->varlist_size();
11106  Exprs.reserve(NumVars);
11107  for (unsigned i = 0; i != NumVars; ++i)
11108  Exprs.push_back(Record.readSubExpr());
11109  C->setVarRefs(Exprs);
11110  Exprs.clear();
11111  for (unsigned i = 0; i != NumVars; ++i)
11112  Exprs.push_back(Record.readSubExpr());
11113  C->setSourceExprs(Exprs);
11114  Exprs.clear();
11115  for (unsigned i = 0; i != NumVars; ++i)
11116  Exprs.push_back(Record.readSubExpr());
11117  C->setDestinationExprs(Exprs);
11118  Exprs.clear();
11119  for (unsigned i = 0; i != NumVars; ++i)
11120  Exprs.push_back(Record.readSubExpr());
11121  C->setAssignmentOps(Exprs);
11122 }
11123 
11124 void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
11125  C->setLParenLoc(Record.readSourceLocation());
11126  unsigned NumVars = C->varlist_size();
11128  Exprs.reserve(NumVars);
11129  for (unsigned i = 0; i != NumVars; ++i)
11130  Exprs.push_back(Record.readSubExpr());
11131  C->setVarRefs(Exprs);
11132  Exprs.clear();
11133  for (unsigned i = 0; i != NumVars; ++i)
11134  Exprs.push_back(Record.readSubExpr());
11135  C->setSourceExprs(Exprs);
11136  Exprs.clear();
11137  for (unsigned i = 0; i != NumVars; ++i)
11138  Exprs.push_back(Record.readSubExpr());
11139  C->setDestinationExprs(Exprs);
11140  Exprs.clear();
11141  for (unsigned i = 0; i != NumVars; ++i)
11142  Exprs.push_back(Record.readSubExpr());
11143  C->setAssignmentOps(Exprs);
11144 }
11145 
11146 void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
11147  C->setLParenLoc(Record.readSourceLocation());
11148  unsigned NumVars = C->varlist_size();
11150  Vars.reserve(NumVars);
11151  for (unsigned i = 0; i != NumVars; ++i)
11152  Vars.push_back(Record.readSubExpr());
11153  C->setVarRefs(Vars);
11154 }
11155 
11156 void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
11157  C->setDepobj(Record.readSubExpr());
11158  C->setLParenLoc(Record.readSourceLocation());
11159 }
11160 
11161 void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
11162  C->setLParenLoc(Record.readSourceLocation());
11163  C->setModifier(Record.readSubExpr());
11164  C->setDependencyKind(
11165  static_cast<OpenMPDependClauseKind>(Record.readInt()));
11166  C->setDependencyLoc(Record.readSourceLocation());
11167  C->setColonLoc(Record.readSourceLocation());
11168  C->setOmpAllMemoryLoc(Record.readSourceLocation());
11169  unsigned NumVars = C->varlist_size();
11171  Vars.reserve(NumVars);
11172  for (unsigned I = 0; I != NumVars; ++I)
11173  Vars.push_back(Record.readSubExpr());
11174  C->setVarRefs(Vars);
11175  for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
11176  C->setLoopData(I, Record.readSubExpr());
11177 }
11178 
11179 void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
11181  C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
11182  C->setDevice(Record.readSubExpr());
11183  C->setModifierLoc(Record.readSourceLocation());
11184  C->setLParenLoc(Record.readSourceLocation());
11185 }
11186 
11187 void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
11188  C->setLParenLoc(Record.readSourceLocation());
11189  bool HasIteratorModifier = false;
11190  for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
11191  C->setMapTypeModifier(
11192  I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
11193  C->setMapTypeModifierLoc(I, Record.readSourceLocation());
11194  if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
11195  HasIteratorModifier = true;
11196  }
11197  C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11198  C->setMapperIdInfo(Record.readDeclarationNameInfo());
11199  C->setMapType(
11200  static_cast<OpenMPMapClauseKind>(Record.readInt()));
11201  C->setMapLoc(Record.readSourceLocation());
11202  C->setColonLoc(Record.readSourceLocation());
11203  auto NumVars = C->varlist_size();
11204  auto UniqueDecls = C->getUniqueDeclarationsNum();
11205  auto TotalLists = C->getTotalComponentListNum();
11206  auto TotalComponents = C->getTotalComponentsNum();
11207 
11209  Vars.reserve(NumVars);
11210  for (unsigned i = 0; i != NumVars; ++i)
11211  Vars.push_back(Record.readExpr());
11212  C->setVarRefs(Vars);
11213 
11214  SmallVector<Expr *, 16> UDMappers;
11215  UDMappers.reserve(NumVars);
11216  for (unsigned I = 0; I < NumVars; ++I)
11217  UDMappers.push_back(Record.readExpr());
11218  C->setUDMapperRefs(UDMappers);
11219 
11220  if (HasIteratorModifier)
11221  C->setIteratorModifier(Record.readExpr());
11222 
11224  Decls.reserve(UniqueDecls);
11225  for (unsigned i = 0; i < UniqueDecls; ++i)
11226  Decls.push_back(Record.readDeclAs<ValueDecl>());
11227  C->setUniqueDecls(Decls);
11228 
11229  SmallVector<unsigned, 16> ListsPerDecl;
11230  ListsPerDecl.reserve(UniqueDecls);
11231  for (unsigned i = 0; i < UniqueDecls; ++i)
11232  ListsPerDecl.push_back(Record.readInt());
11233  C->setDeclNumLists(ListsPerDecl);
11234 
11235  SmallVector<unsigned, 32> ListSizes;
11236  ListSizes.reserve(TotalLists);
11237  for (unsigned i = 0; i < TotalLists; ++i)
11238  ListSizes.push_back(Record.readInt());
11239  C->setComponentListSizes(ListSizes);
11240 
11242  Components.reserve(TotalComponents);
11243  for (unsigned i = 0; i < TotalComponents; ++i) {
11244  Expr *AssociatedExprPr = Record.readExpr();
11245  auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11246  Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11247  /*IsNonContiguous=*/false);
11248  }
11249  C->setComponents(Components, ListSizes);
11250 }
11251 
11252 void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
11253  C->setLParenLoc(Record.readSourceLocation());
11254  C->setColonLoc(Record.readSourceLocation());
11255  C->setAllocator(Record.readSubExpr());
11256  unsigned NumVars = C->varlist_size();
11258  Vars.reserve(NumVars);
11259  for (unsigned i = 0; i != NumVars; ++i)
11260  Vars.push_back(Record.readSubExpr());
11261  C->setVarRefs(Vars);
11262 }
11263 
11264 void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
11266  C->setNumTeams(Record.readSubExpr());
11267  C->setLParenLoc(Record.readSourceLocation());
11268 }
11269 
11270 void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
11272  C->setThreadLimit(Record.readSubExpr());
11273  C->setLParenLoc(Record.readSourceLocation());
11274 }
11275 
11276 void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
11278  C->setPriority(Record.readSubExpr());
11279  C->setLParenLoc(Record.readSourceLocation());
11280 }
11281 
11282 void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
11284  C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
11285  C->setGrainsize(Record.readSubExpr());
11286  C->setModifierLoc(Record.readSourceLocation());
11287  C->setLParenLoc(Record.readSourceLocation());
11288 }
11289 
11290 void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
11292  C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
11293  C->setNumTasks(Record.readSubExpr());
11294  C->setModifierLoc(Record.readSourceLocation());
11295  C->setLParenLoc(Record.readSourceLocation());
11296 }
11297 
11298 void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
11299  C->setHint(Record.readSubExpr());
11300  C->setLParenLoc(Record.readSourceLocation());
11301 }
11302 
11303 void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
11305  C->setDistScheduleKind(
11306  static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
11307  C->setChunkSize(Record.readSubExpr());
11308  C->setLParenLoc(Record.readSourceLocation());
11309  C->setDistScheduleKindLoc(Record.readSourceLocation());
11310  C->setCommaLoc(Record.readSourceLocation());
11311 }
11312 
11313 void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
11314  C->setDefaultmapKind(
11315  static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
11316  C->setDefaultmapModifier(
11317  static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
11318  C->setLParenLoc(Record.readSourceLocation());
11319  C->setDefaultmapModifierLoc(Record.readSourceLocation());
11320  C->setDefaultmapKindLoc(Record.readSourceLocation());
11321 }
11322 
11323 void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
11324  C->setLParenLoc(Record.readSourceLocation());
11325  for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11326  C->setMotionModifier(
11327  I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11328  C->setMotionModifierLoc(I, Record.readSourceLocation());
11329  }
11330  C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11331  C->setMapperIdInfo(Record.readDeclarationNameInfo());
11332  C->setColonLoc(Record.readSourceLocation());
11333  auto NumVars = C->varlist_size();
11334  auto UniqueDecls = C->getUniqueDeclarationsNum();
11335  auto TotalLists = C->getTotalComponentListNum();
11336  auto TotalComponents = C->getTotalComponentsNum();
11337 
11339  Vars.reserve(NumVars);
11340  for (unsigned i = 0; i != NumVars; ++i)
11341  Vars.push_back(Record.readSubExpr());
11342  C->setVarRefs(Vars);
11343 
11344  SmallVector<Expr *, 16> UDMappers;
11345  UDMappers.reserve(NumVars);
11346  for (unsigned I = 0; I < NumVars; ++I)
11347  UDMappers.push_back(Record.readSubExpr());
11348  C->setUDMapperRefs(UDMappers);
11349 
11351  Decls.reserve(UniqueDecls);
11352  for (unsigned i = 0; i < UniqueDecls; ++i)
11353  Decls.push_back(Record.readDeclAs<ValueDecl>());
11354  C->setUniqueDecls(Decls);
11355 
11356  SmallVector<unsigned, 16> ListsPerDecl;
11357  ListsPerDecl.reserve(UniqueDecls);
11358  for (unsigned i = 0; i < UniqueDecls; ++i)
11359  ListsPerDecl.push_back(Record.readInt());
11360  C->setDeclNumLists(ListsPerDecl);
11361 
11362  SmallVector<unsigned, 32> ListSizes;
11363  ListSizes.reserve(TotalLists);
11364  for (unsigned i = 0; i < TotalLists; ++i)
11365  ListSizes.push_back(Record.readInt());
11366  C->setComponentListSizes(ListSizes);
11367 
11369  Components.reserve(TotalComponents);
11370  for (unsigned i = 0; i < TotalComponents; ++i) {
11371  Expr *AssociatedExprPr = Record.readSubExpr();
11372  bool IsNonContiguous = Record.readBool();
11373  auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11374  Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11375  }
11376  C->setComponents(Components, ListSizes);
11377 }
11378 
11379 void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
11380  C->setLParenLoc(Record.readSourceLocation());
11381  for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11382  C->setMotionModifier(
11383  I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11384  C->setMotionModifierLoc(I, Record.readSourceLocation());
11385  }
11386  C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11387  C->setMapperIdInfo(Record.readDeclarationNameInfo());
11388  C->setColonLoc(Record.readSourceLocation());
11389  auto NumVars = C->varlist_size();
11390  auto UniqueDecls = C->getUniqueDeclarationsNum();
11391  auto TotalLists = C->getTotalComponentListNum();
11392  auto TotalComponents = C->getTotalComponentsNum();
11393 
11395  Vars.reserve(NumVars);
11396  for (unsigned i = 0; i != NumVars; ++i)
11397  Vars.push_back(Record.readSubExpr());
11398  C->setVarRefs(Vars);
11399 
11400  SmallVector<Expr *, 16> UDMappers;
11401  UDMappers.reserve(NumVars);
11402  for (unsigned I = 0; I < NumVars; ++I)
11403  UDMappers.push_back(Record.readSubExpr());
11404  C->setUDMapperRefs(UDMappers);
11405 
11407  Decls.reserve(UniqueDecls);
11408  for (unsigned i = 0; i < UniqueDecls; ++i)
11409  Decls.push_back(Record.readDeclAs<ValueDecl>());
11410  C->setUniqueDecls(Decls);
11411 
11412  SmallVector<unsigned, 16> ListsPerDecl;
11413  ListsPerDecl.reserve(UniqueDecls);
11414  for (unsigned i = 0; i < UniqueDecls; ++i)
11415  ListsPerDecl.push_back(Record.readInt());
11416  C->setDeclNumLists(ListsPerDecl);
11417 
11418  SmallVector<unsigned, 32> ListSizes;
11419  ListSizes.reserve(TotalLists);
11420  for (unsigned i = 0; i < TotalLists; ++i)
11421  ListSizes.push_back(Record.readInt());
11422  C->setComponentListSizes(ListSizes);
11423 
11425  Components.reserve(TotalComponents);
11426  for (unsigned i = 0; i < TotalComponents; ++i) {
11427  Expr *AssociatedExprPr = Record.readSubExpr();
11428  bool IsNonContiguous = Record.readBool();
11429  auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11430  Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
11431  }
11432  C->setComponents(Components, ListSizes);
11433 }
11434 
11435 void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
11436  C->setLParenLoc(Record.readSourceLocation());
11437  auto NumVars = C->varlist_size();
11438  auto UniqueDecls = C->getUniqueDeclarationsNum();
11439  auto TotalLists = C->getTotalComponentListNum();
11440  auto TotalComponents = C->getTotalComponentsNum();
11441 
11443  Vars.reserve(NumVars);
11444  for (unsigned i = 0; i != NumVars; ++i)
11445  Vars.push_back(Record.readSubExpr());
11446  C->setVarRefs(Vars);
11447  Vars.clear();
11448  for (unsigned i = 0; i != NumVars; ++i)
11449  Vars.push_back(Record.readSubExpr());
11450  C->setPrivateCopies(Vars);
11451  Vars.clear();
11452  for (unsigned i = 0; i != NumVars; ++i)
11453  Vars.push_back(Record.readSubExpr());
11454  C->setInits(Vars);
11455 
11457  Decls.reserve(UniqueDecls);
11458  for (unsigned i = 0; i < UniqueDecls; ++i)
11459  Decls.push_back(Record.readDeclAs<ValueDecl>());
11460  C->setUniqueDecls(Decls);
11461 
11462  SmallVector<unsigned, 16> ListsPerDecl;
11463  ListsPerDecl.reserve(UniqueDecls);
11464  for (unsigned i = 0; i < UniqueDecls; ++i)
11465  ListsPerDecl.push_back(Record.readInt());
11466  C->setDeclNumLists(ListsPerDecl);
11467 
11468  SmallVector<unsigned, 32> ListSizes;
11469  ListSizes.reserve(TotalLists);
11470  for (unsigned i = 0; i < TotalLists; ++i)
11471  ListSizes.push_back(Record.readInt());
11472  C->setComponentListSizes(ListSizes);
11473 
11475  Components.reserve(TotalComponents);
11476  for (unsigned i = 0; i < TotalComponents; ++i) {
11477  auto *AssociatedExprPr = Record.readSubExpr();
11478  auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11479  Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11480  /*IsNonContiguous=*/false);
11481  }
11482  C->setComponents(Components, ListSizes);
11483 }
11484 
11485 void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
11486  C->setLParenLoc(Record.readSourceLocation());
11487  auto NumVars = C->varlist_size();
11488  auto UniqueDecls = C->getUniqueDeclarationsNum();
11489  auto TotalLists = C->getTotalComponentListNum();
11490  auto TotalComponents = C->getTotalComponentsNum();
11491 
11493  Vars.reserve(NumVars);
11494  for (unsigned i = 0; i != NumVars; ++i)
11495  Vars.push_back(Record.readSubExpr());
11496  C->setVarRefs(Vars);
11497 
11499  Decls.reserve(UniqueDecls);
11500  for (unsigned i = 0; i < UniqueDecls; ++i)
11501  Decls.push_back(Record.readDeclAs<ValueDecl>());
11502  C->setUniqueDecls(Decls);
11503 
11504  SmallVector<unsigned, 16> ListsPerDecl;
11505  ListsPerDecl.reserve(UniqueDecls);
11506  for (unsigned i = 0; i < UniqueDecls; ++i)
11507  ListsPerDecl.push_back(Record.readInt());
11508  C->setDeclNumLists(ListsPerDecl);
11509 
11510  SmallVector<unsigned, 32> ListSizes;
11511  ListSizes.reserve(TotalLists);
11512  for (unsigned i = 0; i < TotalLists; ++i)
11513  ListSizes.push_back(Record.readInt());
11514  C->setComponentListSizes(ListSizes);
11515 
11517  Components.reserve(TotalComponents);
11518  for (unsigned i = 0; i < TotalComponents; ++i) {
11519  Expr *AssociatedExpr = Record.readSubExpr();
11520  auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11521  Components.emplace_back(AssociatedExpr, AssociatedDecl,
11522  /*IsNonContiguous*/ false);
11523  }
11524  C->setComponents(Components, ListSizes);
11525 }
11526 
11527 void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
11528  C->setLParenLoc(Record.readSourceLocation());
11529  auto NumVars = C->varlist_size();
11530  auto UniqueDecls = C->getUniqueDeclarationsNum();
11531  auto TotalLists = C->getTotalComponentListNum();
11532  auto TotalComponents = C->getTotalComponentsNum();
11533 
11535  Vars.reserve(NumVars);
11536  for (unsigned i = 0; i != NumVars; ++i)
11537  Vars.push_back(Record.readSubExpr());
11538  C->setVarRefs(Vars);
11539  Vars.clear();
11540 
11542  Decls.reserve(UniqueDecls);
11543  for (unsigned i = 0; i < UniqueDecls; ++i)
11544  Decls.push_back(Record.readDeclAs<ValueDecl>());
11545  C->setUniqueDecls(Decls);
11546 
11547  SmallVector<unsigned, 16> ListsPerDecl;
11548  ListsPerDecl.reserve(UniqueDecls);
11549  for (unsigned i = 0; i < UniqueDecls; ++i)
11550  ListsPerDecl.push_back(Record.readInt());
11551  C->setDeclNumLists(ListsPerDecl);
11552 
11553  SmallVector<unsigned, 32> ListSizes;
11554  ListSizes.reserve(TotalLists);
11555  for (unsigned i = 0; i < TotalLists; ++i)
11556  ListSizes.push_back(Record.readInt());
11557  C->setComponentListSizes(ListSizes);
11558 
11560  Components.reserve(TotalComponents);
11561  for (unsigned i = 0; i < TotalComponents; ++i) {
11562  Expr *AssociatedExpr = Record.readSubExpr();
11563  auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11564  Components.emplace_back(AssociatedExpr, AssociatedDecl,
11565  /*IsNonContiguous=*/false);
11566  }
11567  C->setComponents(Components, ListSizes);
11568 }
11569 
11570 void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
11571  C->setLParenLoc(Record.readSourceLocation());
11572  auto NumVars = C->varlist_size();
11573  auto UniqueDecls = C->getUniqueDeclarationsNum();
11574  auto TotalLists = C->getTotalComponentListNum();
11575  auto TotalComponents = C->getTotalComponentsNum();
11576 
11578  Vars.reserve(NumVars);
11579  for (unsigned I = 0; I != NumVars; ++I)
11580  Vars.push_back(Record.readSubExpr());
11581  C->setVarRefs(Vars);
11582  Vars.clear();
11583 
11585  Decls.reserve(UniqueDecls);
11586  for (unsigned I = 0; I < UniqueDecls; ++I)
11587  Decls.push_back(Record.readDeclAs<ValueDecl>());
11588  C->setUniqueDecls(Decls);
11589 
11590  SmallVector<unsigned, 16> ListsPerDecl;
11591  ListsPerDecl.reserve(UniqueDecls);
11592  for (unsigned I = 0; I < UniqueDecls; ++I)
11593  ListsPerDecl.push_back(Record.readInt());
11594  C->setDeclNumLists(ListsPerDecl);
11595 
11596  SmallVector<unsigned, 32> ListSizes;
11597  ListSizes.reserve(TotalLists);
11598  for (unsigned i = 0; i < TotalLists; ++i)
11599  ListSizes.push_back(Record.readInt());
11600  C->setComponentListSizes(ListSizes);
11601 
11603  Components.reserve(TotalComponents);
11604  for (unsigned I = 0; I < TotalComponents; ++I) {
11605  Expr *AssociatedExpr = Record.readSubExpr();
11606  auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11607  Components.emplace_back(AssociatedExpr, AssociatedDecl,
11608  /*IsNonContiguous=*/false);
11609  }
11610  C->setComponents(Components, ListSizes);
11611 }
11612 
11613 void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
11614  C->setLParenLoc(Record.readSourceLocation());
11615  unsigned NumVars = C->varlist_size();
11617  Vars.reserve(NumVars);
11618  for (unsigned i = 0; i != NumVars; ++i)
11619  Vars.push_back(Record.readSubExpr());
11620  C->setVarRefs(Vars);
11621  Vars.clear();
11622  Vars.reserve(NumVars);
11623  for (unsigned i = 0; i != NumVars; ++i)
11624  Vars.push_back(Record.readSubExpr());
11625  C->setPrivateRefs(Vars);
11626 }
11627 
11628 void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
11629  C->setLParenLoc(Record.readSourceLocation());
11630  unsigned NumVars = C->varlist_size();
11632  Vars.reserve(NumVars);
11633  for (unsigned i = 0; i != NumVars; ++i)
11634  Vars.push_back(Record.readSubExpr());
11635  C->setVarRefs(Vars);
11636 }
11637 
11638 void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
11639  C->setLParenLoc(Record.readSourceLocation());
11640  unsigned NumVars = C->varlist_size();
11642  Vars.reserve(NumVars);
11643  for (unsigned i = 0; i != NumVars; ++i)
11644  Vars.push_back(Record.readSubExpr());
11645  C->setVarRefs(Vars);
11646 }
11647 
11648 void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
11649  C->setLParenLoc(Record.readSourceLocation());
11650  unsigned NumOfAllocators = C->getNumberOfAllocators();
11652  Data.reserve(NumOfAllocators);
11653  for (unsigned I = 0; I != NumOfAllocators; ++I) {
11654  OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
11655  D.Allocator = Record.readSubExpr();
11656  D.AllocatorTraits = Record.readSubExpr();
11657  D.LParenLoc = Record.readSourceLocation();
11658  D.RParenLoc = Record.readSourceLocation();
11659  }
11660  C->setAllocatorsData(Data);
11661 }
11662 
11663 void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
11664  C->setLParenLoc(Record.readSourceLocation());
11665  C->setModifier(Record.readSubExpr());
11666  C->setColonLoc(Record.readSourceLocation());
11667  unsigned NumOfLocators = C->varlist_size();
11668  SmallVector<Expr *, 4> Locators;
11669  Locators.reserve(NumOfLocators);
11670  for (unsigned I = 0; I != NumOfLocators; ++I)
11671  Locators.push_back(Record.readSubExpr());
11672  C->setVarRefs(Locators);
11673 }
11674 
11675 void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
11676  C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
11677  C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
11678  C->setLParenLoc(Record.readSourceLocation());
11679  C->setKindKwLoc(Record.readSourceLocation());
11680  C->setModifierKwLoc(Record.readSourceLocation());
11681 }
11682 
11683 void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
11685  C->setThreadID(Record.readSubExpr());
11686  C->setLParenLoc(Record.readSourceLocation());
11687 }
11688 
11689 void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
11690  C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
11691  C->setLParenLoc(Record.readSourceLocation());
11692  C->setBindKindLoc(Record.readSourceLocation());
11693 }
11694 
11695 void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
11696  C->setAlignment(Record.readExpr());
11697  C->setLParenLoc(Record.readSourceLocation());
11698 }
11699 
11700 void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
11702  C->setSize(Record.readSubExpr());
11703  C->setLParenLoc(Record.readSourceLocation());
11704 }
11705 
11706 void OMPClauseReader::VisitOMPDoacrossClause(OMPDoacrossClause *C) {
11707  C->setLParenLoc(Record.readSourceLocation());
11708  C->setDependenceType(
11709  static_cast<OpenMPDoacrossClauseModifier>(Record.readInt()));
11710  C->setDependenceLoc(Record.readSourceLocation());
11711  C->setColonLoc(Record.readSourceLocation());
11712  unsigned NumVars = C->varlist_size();
11714  Vars.reserve(NumVars);
11715  for (unsigned I = 0; I != NumVars; ++I)
11716  Vars.push_back(Record.readSubExpr());
11717  C->setVarRefs(Vars);
11718  for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
11719  C->setLoopData(I, Record.readSubExpr());
11720 }
11721 
11722 void OMPClauseReader::VisitOMPXAttributeClause(OMPXAttributeClause *C) {
11723  AttrVec Attrs;
11724  Record.readAttributes(Attrs);
11725  C->setAttrs(Attrs);
11726  C->setLocStart(Record.readSourceLocation());
11727  C->setLParenLoc(Record.readSourceLocation());
11728  C->setLocEnd(Record.readSourceLocation());
11729 }
11730 
11731 void OMPClauseReader::VisitOMPXBareClause(OMPXBareClause *C) {}
11732 
11735  TI.Sets.resize(readUInt32());
11736  for (auto &Set : TI.Sets) {
11737  Set.Kind = readEnum<llvm::omp::TraitSet>();
11738  Set.Selectors.resize(readUInt32());
11739  for (auto &Selector : Set.Selectors) {
11740  Selector.Kind = readEnum<llvm::omp::TraitSelector>();
11741  Selector.ScoreOrCondition = nullptr;
11742  if (readBool())
11743  Selector.ScoreOrCondition = readExprRef();
11744  Selector.Properties.resize(readUInt32());
11745  for (auto &Property : Selector.Properties)
11746  Property.Kind = readEnum<llvm::omp::TraitProperty>();
11747  }
11748  }
11749  return &TI;
11750 }
11751 
11753  if (!Data)
11754  return;
11755  if (Reader->ReadingKind == ASTReader::Read_Stmt) {
11756  // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
11757  skipInts(3);
11758  }
11759  SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
11760  for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
11761  Clauses[I] = readOMPClause();
11762  Data->setClauses(Clauses);
11763  if (Data->hasAssociatedStmt())
11764  Data->setAssociatedStmt(readStmt());
11765  for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
11766  Data->getChildren()[I] = readStmt();
11767 }
11768 
11770  unsigned NumVars = readInt();
11771  llvm::SmallVector<Expr *> VarList;
11772  for (unsigned I = 0; I < NumVars; ++I)
11773  VarList.push_back(readSubExpr());
11774  return VarList;
11775 }
11776 
11778  unsigned NumExprs = readInt();
11779  llvm::SmallVector<Expr *> ExprList;
11780  for (unsigned I = 0; I < NumExprs; ++I)
11781  ExprList.push_back(readSubExpr());
11782  return ExprList;
11783 }
11784 
11786  OpenACCClauseKind ClauseKind = readEnum<OpenACCClauseKind>();
11787  SourceLocation BeginLoc = readSourceLocation();
11789 
11790  switch (ClauseKind) {
11792  SourceLocation LParenLoc = readSourceLocation();
11793  OpenACCDefaultClauseKind DCK = readEnum<OpenACCDefaultClauseKind>();
11794  return OpenACCDefaultClause::Create(getContext(), DCK, BeginLoc, LParenLoc,
11795  EndLoc);
11796  }
11797  case OpenACCClauseKind::If: {
11798  SourceLocation LParenLoc = readSourceLocation();
11799  Expr *CondExpr = readSubExpr();
11800  return OpenACCIfClause::Create(getContext(), BeginLoc, LParenLoc, CondExpr,
11801  EndLoc);
11802  }
11803  case OpenACCClauseKind::Self: {
11804  SourceLocation LParenLoc = readSourceLocation();
11805  Expr *CondExpr = readBool() ? readSubExpr() : nullptr;
11806  return OpenACCSelfClause::Create(getContext(), BeginLoc, LParenLoc,
11807  CondExpr, EndLoc);
11808  }
11810  SourceLocation LParenLoc = readSourceLocation();
11811  unsigned NumClauses = readInt();
11812  llvm::SmallVector<Expr *> IntExprs;
11813  for (unsigned I = 0; I < NumClauses; ++I)
11814  IntExprs.push_back(readSubExpr());
11815  return OpenACCNumGangsClause::Create(getContext(), BeginLoc, LParenLoc,
11816  IntExprs, EndLoc);
11817  }
11819  SourceLocation LParenLoc = readSourceLocation();
11820  Expr *IntExpr = readSubExpr();
11821  return OpenACCNumWorkersClause::Create(getContext(), BeginLoc, LParenLoc,
11822  IntExpr, EndLoc);
11823  }
11825  SourceLocation LParenLoc = readSourceLocation();
11826  Expr *IntExpr = readSubExpr();
11827  return OpenACCVectorLengthClause::Create(getContext(), BeginLoc, LParenLoc,
11828  IntExpr, EndLoc);
11829  }
11831  SourceLocation LParenLoc = readSourceLocation();
11833  return OpenACCPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
11834  VarList, EndLoc);
11835  }
11837  SourceLocation LParenLoc = readSourceLocation();
11839  return OpenACCFirstPrivateClause::Create(getContext(), BeginLoc, LParenLoc,
11840  VarList, EndLoc);
11841  }
11843  SourceLocation LParenLoc = readSourceLocation();
11845  return OpenACCAttachClause::Create(getContext(), BeginLoc, LParenLoc,
11846  VarList, EndLoc);
11847  }
11849  SourceLocation LParenLoc = readSourceLocation();
11851  return OpenACCDevicePtrClause::Create(getContext(), BeginLoc, LParenLoc,
11852  VarList, EndLoc);
11853  }
11855  SourceLocation LParenLoc = readSourceLocation();
11857  return OpenACCNoCreateClause::Create(getContext(), BeginLoc, LParenLoc,
11858  VarList, EndLoc);
11859  }
11861  SourceLocation LParenLoc = readSourceLocation();
11863  return OpenACCPresentClause::Create(getContext(), BeginLoc, LParenLoc,
11864  VarList, EndLoc);
11865  }
11868  case OpenACCClauseKind::Copy: {
11869  SourceLocation LParenLoc = readSourceLocation();
11871  return OpenACCCopyClause::Create(getContext(), ClauseKind, BeginLoc,
11872  LParenLoc, VarList, EndLoc);
11873  }
11877  SourceLocation LParenLoc = readSourceLocation();
11878  bool IsReadOnly = readBool();
11880  return OpenACCCopyInClause::Create(getContext(), ClauseKind, BeginLoc,
11881  LParenLoc, IsReadOnly, VarList, EndLoc);
11882  }
11886  SourceLocation LParenLoc = readSourceLocation();
11887  bool IsZero = readBool();
11889  return OpenACCCopyOutClause::Create(getContext(), ClauseKind, BeginLoc,
11890  LParenLoc, IsZero, VarList, EndLoc);
11891  }
11895  SourceLocation LParenLoc = readSourceLocation();
11896  bool IsZero = readBool();
11898  return OpenACCCreateClause::Create(getContext(), ClauseKind, BeginLoc,
11899  LParenLoc, IsZero, VarList, EndLoc);
11900  }
11901  case OpenACCClauseKind::Async: {
11902  SourceLocation LParenLoc = readSourceLocation();
11903  Expr *AsyncExpr = readBool() ? readSubExpr() : nullptr;
11904  return OpenACCAsyncClause::Create(getContext(), BeginLoc, LParenLoc,
11905  AsyncExpr, EndLoc);
11906  }
11907  case OpenACCClauseKind::Wait: {
11908  SourceLocation LParenLoc = readSourceLocation();
11909  Expr *DevNumExpr = readBool() ? readSubExpr() : nullptr;
11910  SourceLocation QueuesLoc = readSourceLocation();
11912  return OpenACCWaitClause::Create(getContext(), BeginLoc, LParenLoc,
11913  DevNumExpr, QueuesLoc, QueueIdExprs,
11914  EndLoc);
11915  }
11917  case OpenACCClauseKind::DType: {
11918  SourceLocation LParenLoc = readSourceLocation();
11920  unsigned NumArchs = readInt();
11921 
11922  for (unsigned I = 0; I < NumArchs; ++I) {
11923  IdentifierInfo *Ident = readBool() ? readIdentifier() : nullptr;
11925  Archs.emplace_back(Ident, Loc);
11926  }
11927 
11928  return OpenACCDeviceTypeClause::Create(getContext(), ClauseKind, BeginLoc,
11929  LParenLoc, Archs, EndLoc);
11930  }
11932  SourceLocation LParenLoc = readSourceLocation();
11933  OpenACCReductionOperator Op = readEnum<OpenACCReductionOperator>();
11935  return OpenACCReductionClause::Create(getContext(), BeginLoc, LParenLoc, Op,
11936  VarList, EndLoc);
11937  }
11938 
11961  llvm_unreachable("Clause serialization not yet implemented");
11962  }
11963  llvm_unreachable("Invalid Clause Kind");
11964 }
11965 
11968  for (unsigned I = 0; I < Clauses.size(); ++I)
11969  Clauses[I] = readOpenACCClause();
11970 }
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
ASTImporterLookupTable & LT
StringRef P
static unsigned moduleKindForDiagnostic(ModuleKind Kind)
Definition: ASTReader.cpp:4688
static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, ASTConsumer *Consumer)
Under non-PCH compilation the consumer receives the objc methods before receiving the implementation,...
Definition: ASTReader.cpp:8035
static bool checkModuleCachePath(llvm::vfs::FileSystem &VFS, StringRef SpecificModuleCachePath, StringRef ExistingModuleCachePath, DiagnosticsEngine *Diags, const LangOptions &LangOpts, const PreprocessorOptions &PPOpts)
Check that the specified and the existing module cache paths are equivalent.
Definition: ASTReader.cpp:837
static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream)
Whether Stream doesn't start with the AST/PCH file magic number 'CPCH'.
Definition: ASTReader.cpp:4670
static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags)
Definition: ASTReader.cpp:506
static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, bool IsSystem, bool SystemHeaderWarningsInModule, bool Complain)
Definition: ASTReader.cpp:513
static void updateModuleTimestamp(ModuleFile &MF)
Definition: ASTReader.cpp:4369
static void collectMacroDefinitions(const PreprocessorOptions &PPOpts, MacroDefinitionsMap &Macros, SmallVectorImpl< StringRef > *MacroNames=nullptr)
Collect the macro definitions provided by the given preprocessor options.
Definition: ASTReader.cpp:612
static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts, const PreprocessorOptions &ExistingPPOpts, bool ReadMacros, DiagnosticsEngine *Diags, FileManager &FileMgr, std::string &SuggestedPredefines, const LangOptions &LangOpts, OptionValidation Validation=OptionValidateContradictions)
Check the preprocessor options deserialized from the control block against the preprocessor options i...
Definition: ASTReader.cpp:663
static std::pair< unsigned, unsigned > readULEBKeyDataLength(const unsigned char *&P)
Read ULEB-encoded key length and data length.
Definition: ASTReader.cpp:887
static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, bool Complain)
Definition: ASTReader.cpp:476
static Module * getTopImportImplicitModule(ModuleManager &ModuleMgr, Preprocessor &PP)
Return the top import module if it is implicit, nullptr otherwise.
Definition: ASTReader.cpp:555
static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method)
Move the given method to the back of the global list of methods.
Definition: ASTReader.cpp:4233
static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps)
Definition: ASTReader.cpp:2701
static bool isInterestingIdentifier(ASTReader &Reader, const IdentifierInfo &II, bool IsModule)
Whether the given identifier is "interesting".
Definition: ASTReader.cpp:991
static bool parseModuleFileExtensionMetadata(const SmallVectorImpl< uint64_t > &Record, StringRef Blob, ModuleFileExtensionMetadata &Metadata)
Parse a record and blob containing module file extension metadata.
Definition: ASTReader.cpp:5009
static Decl * getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID)
Definition: ASTReader.cpp:7703
static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II)
Definition: ASTReader.cpp:1016
static void addMethodsToPool(Sema &S, ArrayRef< ObjCMethodDecl * > Methods, ObjCMethodList &List)
Add the given set of methods to the method list.
Definition: ASTReader.cpp:8557
static bool readBit(unsigned &Bits)
Definition: ASTReader.cpp:1003
static std::optional< Type::TypeClass > getTypeClassForCode(TypeCode code)
Definition: ASTReader.cpp:6676
static LLVM_DUMP_METHOD void dumpModuleIDMap(StringRef Name, const ContinuousRangeMap< Key, ModuleFile *, InitialCapacity > &Map)
Definition: ASTReader.cpp:8152
OptionValidation
Definition: ASTReader.cpp:647
@ OptionValidateStrictMatches
Definition: ASTReader.cpp:650
@ OptionValidateNone
Definition: ASTReader.cpp:648
@ OptionValidateContradictions
Definition: ASTReader.cpp:649
static bool checkTargetOptions(const TargetOptions &TargetOpts, const TargetOptions &ExistingTargetOpts, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of target options against an existing set of target options.
Definition: ASTReader.cpp:387
#define CHECK_TARGET_OPT(Field, Name)
static bool checkLanguageOptions(const LangOptions &LangOpts, const LangOptions &ExistingLangOpts, DiagnosticsEngine *Diags, bool AllowCompatibleDifferences=true)
Compare the given set of language options against an existing set of language options.
Definition: ASTReader.cpp:280
static ASTFileSignature readASTFileSignature(StringRef PCH)
Reads and return the signature record from PCH's control block, or else returns 0.
Definition: ASTReader.cpp:5235
static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID)
Given a cursor at the start of an AST file, scan ahead and drop the cursor into the start of the give...
Definition: ASTReader.cpp:4385
static uint64_t readULEB(const unsigned char *&P)
Definition: ASTReader.cpp:874
static StringRef bytes(const std::vector< T, Allocator > &v)
Definition: ASTWriter.cpp:127
static char ID
Definition: Arena.cpp:183
#define SM(sm)
Definition: Cuda.cpp:83
Defines the Diagnostic-related interfaces.
Defines the clang::CommentOptions interface.
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::FileManager interface and associated types.
Defines the clang::FileSystemOptions interface.
unsigned Offset
Definition: Format.cpp:2978
StringRef Filename
Definition: Format.cpp:2976
llvm::DenseSet< const void * > Visited
Definition: HTMLLogger.cpp:146
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
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.
llvm::MachO::FileType FileType
Definition: MachO.h:45
llvm::MachO::Record Record
Definition: MachO.h:31
Defines the clang::MacroInfo and clang::MacroDirective classes.
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
Defines some OpenACC-specific enums and functions.
This file defines OpenMP AST classes for clauses.
Defines some OpenMP-specific enums and functions.
Defines an enumeration for C++ overloaded operators.
static ParseState advance(ParseState S, size_t N)
Definition: Parsing.cpp:144
Defines the clang::Preprocessor interface.
static std::string getName(const CallEvent &Call)
Defines the clang::SanitizerKind enum.
This file declares semantic analysis for CUDA constructs.
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for Objective-C.
Defines the clang::SourceLocation class and associated facilities.
Defines implementation details of the clang::SourceManager class.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
const char * Data
Defines the clang::TargetOptions class.
Defines the clang::TokenKind enum and support functions.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
SourceLocation End
LineState State
Defines version macros and version-related utility functions for Clang.
__DEVICE__ int max(int __a, int __b)
__device__ __2f16 b
__SIZE_TYPE__ size_t
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:33
virtual void HandleInterestingDecl(DeclGroupRef D)
HandleInterestingDecl - Handle the specified interesting declaration.
Definition: ASTConsumer.cpp:22
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:185
CanQualType AccumTy
Definition: ASTContext.h:1107
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1126
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1125
CanQualType LongTy
Definition: ASTContext.h:1103
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
Definition: ASTContext.h:1103
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1116
BuiltinTemplateDecl * getMakeIntegerSeqDecl() const
ExternCContextDecl * getExternCContextDecl() const
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
Definition: ASTContext.h:1109
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
CanQualType SatAccumTy
Definition: ASTContext.h:1112
CanQualType ShortAccumTy
Definition: ASTContext.h:1107
CanQualType FloatTy
Definition: ASTContext.h:1106
CanQualType DoubleTy
Definition: ASTContext.h:1106
CanQualType SatLongAccumTy
Definition: ASTContext.h:1112
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:1990
CanQualType LongDoubleTy
Definition: ASTContext.h:1106
CanQualType OMPArrayShapingTy
Definition: ASTContext.h:1140
CanQualType Char16Ty
Definition: ASTContext.h:1101
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:1968
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:721
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1111
CanQualType DependentTy
Definition: ASTContext.h:1122
CanQualType NullPtrTy
Definition: ASTContext.h:1121
CanQualType OMPIteratorTy
Definition: ASTContext.h:1140
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:808
CanQualType SatShortFractTy
Definition: ASTContext.h:1115
CanQualType Ibm128Ty
Definition: ASTContext.h:1106
CanQualType SatUnsignedAccumTy
Definition: ASTContext.h:1113
CanQualType ArraySectionTy
Definition: ASTContext.h:1139
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1126
CanQualType BoolTy
Definition: ASTContext.h:1095
RecordDecl * getCFConstantStringTagDecl() const
CanQualType UnsignedFractTy
Definition: ASTContext.h:1111
CanQualType Float128Ty
Definition: ASTContext.h:1106
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1126
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1122
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:2002
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1104
CanQualType UnsignedLongAccumTy
Definition: ASTContext.h:1109
CanQualType ShortFractTy
Definition: ASTContext.h:1110
CanQualType BoundMemberTy
Definition: ASTContext.h:1122
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1116
CanQualType CharTy
Definition: ASTContext.h:1096
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
CanQualType IntTy
Definition: ASTContext.h:1103
CanQualType PseudoObjectTy
Definition: ASTContext.h:1125
CanQualType Float16Ty
Definition: ASTContext.h:1120
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2171
CanQualType SignedCharTy
Definition: ASTContext.h:1103
CanQualType OverloadTy
Definition: ASTContext.h:1122
CanQualType OCLClkEventTy
Definition: ASTContext.h:1136
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
TagDecl * getMSGuidTagDecl() const
Retrieve the implicitly-predeclared 'struct _GUID' declaration.
Definition: ASTContext.h:2152
CanQualType SatUnsignedShortAccumTy
Definition: ASTContext.h:1113
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1105
CanQualType BuiltinFnTy
Definition: ASTContext.h:1124
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
CanQualType OCLSamplerTy
Definition: ASTContext.h:1136
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1094
CanQualType UnsignedCharTy
Definition: ASTContext.h:1104
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1111
CanQualType UnsignedIntTy
Definition: ASTContext.h:1104
CanQualType UnknownAnyTy
Definition: ASTContext.h:1123
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1105
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1137
CanQualType UnsignedShortTy
Definition: ASTContext.h:1104
CanQualType SatUnsignedLongFractTy
Definition: ASTContext.h:1117
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1435
CanQualType ShortTy
Definition: ASTContext.h:1103
CanQualType FractTy
Definition: ASTContext.h:1110
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1218
DiagnosticsEngine & getDiagnostics() const
CanQualType LongAccumTy
Definition: ASTContext.h:1108
CanQualType Char32Ty
Definition: ASTContext.h:1102
CanQualType SatFractTy
Definition: ASTContext.h:1115
CanQualType SatLongFractTy
Definition: ASTContext.h:1115
CanQualType OCLQueueTy
Definition: ASTContext.h:1137
CanQualType LongFractTy
Definition: ASTContext.h:1110
CanQualType SatShortAccumTy
Definition: ASTContext.h:1112
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
Definition: ASTContext.h:1119
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1138
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:1978
BuiltinTemplateDecl * getTypePackElementDecl() const
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1114
CanQualType LongLongTy
Definition: ASTContext.h:1103
void deduplicateMergedDefinitonsFor(NamedDecl *ND)
Clean up the merged definition list.
CanQualType WCharTy
Definition: ASTContext.h:1097
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
void setPrimaryMergedDecl(Decl *D, Decl *Primary)
Definition: ASTContext.h:1042
CanQualType Char8Ty
Definition: ASTContext.h:1100
CanQualType HalfTy
Definition: ASTContext.h:1118
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1109
void setCFConstantStringType(QualType T)
CanQualType OCLEventTy
Definition: ASTContext.h:1136
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1076
virtual void MacroRead(serialization::MacroID ID, MacroInfo *MI)
A macro was read from the AST file.
virtual void SelectorRead(serialization::SelectorID iD, Selector Sel)
A selector was read from the AST file.
virtual void IdentifierRead(serialization::IdentifierID ID, IdentifierInfo *II)
An identifier was deserialized from the AST file.
An identifier-lookup iterator that enumerates all of the identifiers stored within a set of AST files...
Definition: ASTReader.cpp:8378
ASTIdentifierIterator(const ASTReader &Reader, bool SkipModules=false)
Definition: ASTReader.cpp:8406
StringRef Next() override
Retrieve the next string in the identifier table and advances the iterator for the following string.
Definition: ASTReader.cpp:8411
Abstract interface for callback invocations by the ASTReader.
Definition: ASTReader.h:114
virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain)
Receives the header search options.
Definition: ASTReader.h:174
virtual void ReadModuleMapFile(StringRef ModuleMapPath)
Definition: ASTReader.h:127
virtual bool needsInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.h:218
virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences)
Receives the target options.
Definition: ASTReader.h:142
virtual bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule)
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
Definition: ASTReader.h:230
virtual bool ReadHeaderSearchPaths(const HeaderSearchOptions &HSOpts, bool Complain)
Receives the header search paths.
Definition: ASTReader.h:189
virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain)
Receives the file system options.
Definition: ASTReader.h:161
virtual bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain)
Receives the diagnostic options.
Definition: ASTReader.h:152
virtual void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata)
Indicates that a particular module file extension has been read.
Definition: ASTReader.h:244
virtual bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences)
Receives the language options.
Definition: ASTReader.h:132
virtual void visitImport(StringRef ModuleName, StringRef Filename)
If needsImportVisitation returns true, this is called for each AST file imported by this AST file.
Definition: ASTReader.h:241
virtual void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind)
This is called for each AST file loaded.
Definition: ASTReader.h:213
virtual bool needsImportVisitation() const
Returns true if this ASTReaderListener wants to receive the imports of the AST file via visitImport,...
Definition: ASTReader.h:237
virtual bool ReadFullVersionInformation(StringRef FullVersion)
Receives the full Clang version information.
Definition: ASTReader.h:122
virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value)
Receives COUNTER value.
Definition: ASTReader.h:209
virtual void ReadModuleName(StringRef ModuleName)
Definition: ASTReader.h:126
virtual bool needsSystemInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.h:222
virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines)
Receives the preprocessor options.
Definition: ASTReader.h:202
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:366
std::optional< bool > isPreprocessedEntityInFileID(unsigned Index, FileID FID) override
Optionally returns true or false if the preallocated preprocessed entity with index Index came from f...
Definition: ASTReader.cpp:6471
SourceManager & getSourceManager() const
Definition: ASTReader.h:1600
PreprocessedEntity * ReadPreprocessedEntity(unsigned Index) override
Read a preallocated preprocessed entity from the external source.
Definition: ASTReader.cpp:6252
void markIdentifierUpToDate(const IdentifierInfo *II)
Note that this identifier is up-to-date.
Definition: ASTReader.cpp:2247
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:9540
void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership=false)
Set the AST deserialization listener.
Definition: ASTReader.cpp:899
serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) const
Retrieve the global submodule ID given a module and its local ID number.
Definition: ASTReader.cpp:8965
ExtKind hasExternalDefinitions(const Decl *D) override
Definition: ASTReader.cpp:9046
IdentifierTable & getIdentifierTable()
Retrieve the identifier table associated with the preprocessor.
Definition: ASTReader.cpp:9415
bool isDeclIDFromModule(GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
Definition: ASTReader.cpp:7666
friend class ASTIdentifierIterator
Definition: ASTReader.h:370
bool ReadSLocEntry(int ID) override
Read the source location entry with index ID.
Definition: ASTReader.cpp:1533
void RecordSwitchCaseID(SwitchCase *SC, unsigned ID)
Record that the given ID maps to the given switch-case statement.
Definition: ASTReader.cpp:9421
DiagnosticBuilder Diag(unsigned DiagID) const
Report a diagnostic.
Definition: ASTReader.cpp:9405
void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 >> &Exprs) override
Definition: ASTReader.cpp:8630
static std::string ReadString(const RecordDataImpl &Record, unsigned &Idx)
Definition: ASTReader.cpp:9364
void ReadDeclsToCheckForDeferredDiags(llvm::SmallSetVector< Decl *, 4 > &Decls) override
Read the set of decls to be checked for deferred diags.
Definition: ASTReader.cpp:8700
void InitializeSema(Sema &S) override
Initialize the semantic source with the Sema instance being used to perform semantic analysis on the ...
Definition: ASTReader.cpp:8208
@ ARR_Missing
The client can handle an AST file that cannot load because it is missing.
Definition: ASTReader.h:1615
@ ARR_ConfigurationMismatch
The client can handle an AST file that cannot load because it's compiled configuration doesn't match ...
Definition: ASTReader.h:1628
@ ARR_OutOfDate
The client can handle an AST file that cannot load because it is out-of-date relative to its input fi...
Definition: ASTReader.h:1619
@ ARR_VersionMismatch
The client can handle an AST file that cannot load because it was built with a different version of C...
Definition: ASTReader.h:1623
void FindFileRegionDecls(FileID File, unsigned Offset, unsigned Length, SmallVectorImpl< Decl * > &Decls) override
Get the decls that are contained in a file in the Offset/Length range.
Definition: ASTReader.cpp:7933
SourceRange ReadSkippedRange(unsigned Index) override
Read a preallocated skipped range from the external source.
Definition: ASTReader.cpp:6238
ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache, ASTContext *Context, const PCHContainerReader &PCHContainerRdr, ArrayRef< std::shared_ptr< ModuleFileExtension >> Extensions, StringRef isysroot="", DisableValidationForModuleKind DisableValidationKind=DisableValidationForModuleKind::None, bool AllowASTWithCompilerErrors=false, bool AllowConfigurationMismatch=false, bool ValidateSystemInputs=false, bool ValidateASTInputFilesContent=false, bool UseGlobalIndex=true, std::unique_ptr< llvm::Timer > ReadTimer={})
Load the AST file and validate its contents against the given Preprocessor.
void dump()
Dump information about the AST reader to standard error.
Definition: ASTReader.cpp:8172
serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, unsigned LocalID)
Definition: ASTReader.cpp:8908
void AssignedLambdaNumbering(const CXXRecordDecl *Lambda) override
Notify the external source that a lambda was assigned a mangling number.
Definition: ASTReader.cpp:8801
MacroInfo * ReadMacroRecord(ModuleFile &F, uint64_t Offset)
Reads the macro record located at the given offset.
Definition: ASTReader.cpp:1832
SmallVector< std::pair< llvm::BitstreamCursor, serialization::ModuleFile * >, 8 > CommentsCursors
Cursors for comments blocks.
Definition: ASTReader.h:2411
Selector getLocalSelector(ModuleFile &M, unsigned LocalID)
Retrieve a selector from the given module with its local ID number.
Definition: ASTReader.cpp:9053
void FindExternalLexicalDecls(const DeclContext *DC, llvm::function_ref< bool(Decl::Kind)> IsKindWeWant, SmallVectorImpl< Decl * > &Decls) override
Read all of the declarations lexically stored in a declaration context.
Definition: ASTReader.cpp:7857
std::optional< ASTSourceDescriptor > getSourceDescriptor(unsigned ID) override
Return a descriptor for the corresponding module.
Definition: ASTReader.cpp:9028
const serialization::reader::DeclContextLookupTable * getLoadedLookupTables(DeclContext *Primary) const
Get the loaded lookup tables for Primary, if any.
Definition: ASTReader.cpp:8026
void ClearSwitchCaseIDs()
Definition: ASTReader.cpp:9433
SourceLocation ReadSourceLocation(ModuleFile &MF, RawLocEncoding Raw, LocSeq *Seq=nullptr) const
Read a source location from raw form.
Definition: ASTReader.h:2242
void SetGloballyVisibleDecls(IdentifierInfo *II, const SmallVectorImpl< GlobalDeclID > &DeclIDs, SmallVectorImpl< Decl * > *Decls=nullptr)
Set the globally-visible declarations associated with the given identifier.
Definition: ASTReader.cpp:8841
void SetIdentifierInfo(unsigned ID, IdentifierInfo *II)
Definition: ASTReader.cpp:8817
bool loadGlobalIndex()
Attempts to load the global index.
Definition: ASTReader.cpp:4339
void ReadComments() override
Loads comments ranges.
Definition: ASTReader.cpp:9437
SourceLocation getSourceLocationForDeclID(GlobalDeclID ID)
Returns the source location for the decl ID.
Definition: ASTReader.cpp:7684
void makeModuleVisible(Module *Mod, Module::NameVisibilityKind NameVisibility, SourceLocation ImportLoc)
Make the entities in the given module and any of its (non-explicit) submodules visible to name lookup...
Definition: ASTReader.cpp:4275
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Definition: ASTReader.cpp:5229
void ReadPendingInstantiations(SmallVectorImpl< std::pair< ValueDecl *, SourceLocation >> &Pending) override
Definition: ASTReader.cpp:8759
Decl * GetLocalDecl(ModuleFile &F, LocalDeclID LocalID)
Reads a declaration with the given local ID in the given module.
Definition: ASTReader.h:1930
CXXCtorInitializer ** GetExternalCXXCtorInitializers(uint64_t Offset) override
Read the contents of a CXXCtorInitializer array.
Definition: ASTReader.cpp:7576
void visitInputFileInfos(serialization::ModuleFile &MF, bool IncludeSystem, llvm::function_ref< void(const serialization::InputFileInfo &IFI, bool IsSystem)> Visitor)
Visit all the input file infos of the given module file.
Definition: ASTReader.cpp:9509
void StartTranslationUnit(ASTConsumer *Consumer) override
Function that will be invoked when we begin parsing a new translation unit involving this external AS...
Definition: ASTReader.cpp:8052
LocalDeclID mapGlobalIDToModuleFileGlobalID(ModuleFile &M, GlobalDeclID GlobalID)
Map a global declaration ID into the declaration ID used to refer to this declaration within the give...
Definition: ASTReader.cpp:7808
void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo)
Definition: ASTReader.cpp:2258
bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) override
Finds all the visible declarations with a given name.
Definition: ASTReader.cpp:7974
void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs) override
Read the set of tentative definitions known to the external Sema source.
Definition: ASTReader.cpp:8646
Decl * GetExternalDecl(GlobalDeclID ID) override
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7517
llvm::Expected< SourceLocation::UIntTy > readSLocOffset(ModuleFile *F, unsigned Index)
Try to read the offset of the SLocEntry at the given index in the given module file.
Definition: ASTReader.cpp:1461
~ASTReader() override
void CompleteRedeclChain(const Decl *D) override
If any redeclarations of D have been imported since it was last checked, this digs out those redeclar...
Definition: ASTReader.cpp:7519
void ReadLateParsedTemplates(llvm::MapVector< const FunctionDecl *, std::unique_ptr< LateParsedTemplate >> &LPTMap) override
Read the set of late parsed template functions for this source.
Definition: ASTReader.cpp:8771
static llvm::Error ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID, uint64_t *StartOfBlockOffset=nullptr)
ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the specified cursor.
Definition: ASTReader.cpp:1753
serialization::PreprocessedEntityID getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const
Determine the global preprocessed entity ID that corresponds to the given local ID within the given m...
Definition: ASTReader.cpp:1963
std::pair< unsigned, unsigned > findPreprocessedEntitiesInRange(SourceRange Range) override
Returns a pair of [Begin, End) indices of preallocated preprocessed entities that Range encompasses.
Definition: ASTReader.cpp:6458
IdentifierInfo * get(StringRef Name) override
Retrieve the IdentifierInfo for the named identifier.
Definition: ASTReader.cpp:8339
void visitInputFiles(serialization::ModuleFile &MF, bool IncludeSystem, bool Complain, llvm::function_ref< void(const serialization::InputFile &IF, bool isSystem)> Visitor)
Visit all the input files of the given module file.
Definition: ASTReader.cpp:9525
Module * getModule(unsigned ID) override
Retrieve the module that corresponds to the given module ID.
Definition: ASTReader.cpp:8994
llvm::iterator_range< ModuleDeclIterator > getModuleFileLevelDecls(ModuleFile &Mod)
Definition: ASTReader.cpp:6231
GlobalDeclID ReadDeclID(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Reads a declaration ID from the given position in a record in the given module.
Definition: ASTReader.cpp:7826
Stmt * GetExternalDeclStmt(uint64_t Offset) override
Resolve the offset of a statement into a statement.
Definition: ASTReader.cpp:7841
Selector GetExternalSelector(serialization::SelectorID ID) override
Resolve a selector ID into a selector.
Definition: ASTReader.cpp:9082
unsigned getTotalNumSelectors() const
Returns the number of selectors found in the chain.
Definition: ASTReader.h:1874
MacroInfo * getMacro(serialization::MacroID ID)
Retrieve the macro with the given ID.
Definition: ASTReader.cpp:8923
void ReadUndefinedButUsed(llvm::MapVector< NamedDecl *, SourceLocation > &Undefined) override
Load the set of used but not defined functions or variables with internal linkage,...
Definition: ASTReader.cpp:8619
void ReadDelegatingConstructors(SmallVectorImpl< CXXConstructorDecl * > &Decls) override
Read the set of delegating constructors known to the external Sema source.
Definition: ASTReader.cpp:8667
QualType GetType(serialization::TypeID ID)
Resolve a type ID into a type, potentially building a new type.
Definition: ASTReader.cpp:7136
void addPendingMacro(IdentifierInfo *II, ModuleFile *M, uint32_t MacroDirectivesOffset)
Add a macro to deserialize its macro directive history.
Definition: ASTReader.cpp:2098
SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx, LocSeq *Seq=nullptr)
Read a source range.
Definition: ASTReader.cpp:9339
GlobalDeclID getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const
Map from a local declaration ID within a given module to a global declaration ID.
Definition: ASTReader.cpp:7650
void completeVisibleDeclsMap(const DeclContext *DC) override
Load all external visible decls in the given DeclContext.
Definition: ASTReader.cpp:8002
void ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector< const TypedefNameDecl *, 4 > &Decls) override
Read the set of potentially unused typedefs known to the source.
Definition: ASTReader.cpp:8688
IdentifierResolver & getIdResolver()
Get the identifier resolver used for name lookup / updates in the translation unit scope.
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const InMemoryModuleCache &ModuleCache, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions, unsigned ClientLoadCapabilities=ARR_ConfigurationMismatch|ARR_OutOfDate)
Read the control block for the named AST file.
Definition: ASTReader.cpp:5397
void ReadExtVectorDecls(SmallVectorImpl< TypedefNameDecl * > &Decls) override
Read the set of ext_vector type declarations known to the external Sema source.
Definition: ASTReader.cpp:8678
void ResolveImportedPath(ModuleFile &M, std::string &Filename)
If we are loading a relocatable PCH or module file, and the filename is not an absolute path,...
Definition: ASTReader.cpp:2685
Preprocessor & getPreprocessor() const
Retrieve the preprocessor.
Definition: ASTReader.h:1777
ModuleFile * getOwningModuleFile(const Decl *D)
Retrieve the module file that owns the given declaration, or NULL if the declaration is not from a mo...
Definition: ASTReader.cpp:7675
SmallVector< GlobalDeclID, 16 > PreloadedDeclIDs
Definition: ASTReader.h:2384
std::pair< SourceLocation, StringRef > getModuleImportLoc(int ID) override
Retrieve the module import location and module name for the given source manager entry ID.
Definition: ASTReader.cpp:1716
void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls) override
Read the set of unused file-scope declarations known to the external Sema source.
Definition: ASTReader.cpp:8656
Selector DecodeSelector(serialization::SelectorID Idx)
Definition: ASTReader.cpp:9057
ASTReadResult ReadAST(StringRef FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities, ModuleFile **NewLoadedModuleFile=nullptr)
Load the AST file designated by the given file name.
Definition: ASTReader.cpp:4430
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition: ASTReader.h:1781
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9371
unsigned getModuleFileID(ModuleFile *M)
Get an ID for the given module file.
Definition: ASTReader.cpp:9011
IdentifierInfo * DecodeIdentifierInfo(serialization::IdentifierID ID)
Definition: ASTReader.cpp:8873
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons.
Definition: ASTReader.h:384
@ Success
The control block was read successfully.
Definition: ASTReader.h:387
@ ConfigurationMismatch
The AST file was written with a different language/target configuration.
Definition: ASTReader.h:404
@ OutOfDate
The AST file is out-of-date relative to its input files, and needs to be regenerated.
Definition: ASTReader.h:397
@ Failure
The AST file itself appears corrupted.
Definition: ASTReader.h:390
@ VersionMismatch
The AST file was written by a different version of Clang.
Definition: ASTReader.h:400
@ HadErrors
The AST file has errors.
Definition: ASTReader.h:407
@ Missing
The AST file was missing.
Definition: ASTReader.h:393
static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx)
Read a version tuple.
Definition: ASTReader.cpp:9386
Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx)
Reads a token out of a record.
Definition: ASTReader.cpp:1780
SwitchCase * getSwitchCaseWithID(unsigned ID)
Retrieve the switch-case statement with the given ID.
Definition: ASTReader.cpp:9428
IdentifierIterator * getIdentifiers() override
Retrieve an iterator into the set of all identifiers in all loaded AST files.
Definition: ASTReader.cpp:8464
void ReadUsedVTables(SmallVectorImpl< ExternalVTableUse > &VTables) override
Read the set of used vtables known to the external Sema source.
Definition: ASTReader.cpp:8746
bool isGlobalIndexUnavailable() const
Determine whether we tried to load the global index, but failed, e.g., because it is out-of-date or d...
Definition: ASTReader.cpp:4364
uint32_t GetNumExternalSelectors() override
Returns the number of selectors known to the external AST source.
Definition: ASTReader.cpp:9086
void updateOutOfDateSelector(Selector Sel) override
Load the contents of the global method pool for a given selector if necessary.
Definition: ASTReader.cpp:8603
void ReadWeakUndeclaredIdentifiers(SmallVectorImpl< std::pair< IdentifierInfo *, WeakInfo >> &WeakIDs) override
Definition: ASTReader.cpp:8728
Decl * GetExistingDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration.
Definition: ASTReader.cpp:7762
static llvm::BitVector ReadBitVector(const RecordData &Record, const StringRef Blob)
Definition: ASTReader.cpp:9346
ModuleFile * getLocalModuleFile(ModuleFile &M, unsigned ID) const
Retrieve the module file with a given local ID within the specified ModuleFile.
Definition: ASTReader.cpp:8998
void LoadSelector(Selector Sel)
Load a selector from disk, registering its ID if it exists.
Definition: ASTReader.cpp:8812
void ReadReferencedSelectors(SmallVectorImpl< std::pair< Selector, SourceLocation >> &Sels) override
Definition: ASTReader.cpp:8710
IdentifierInfo * getLocalIdentifier(ModuleFile &M, unsigned LocalID)
Definition: ASTReader.cpp:8904
void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag)
Definition: ASTReader.cpp:6530
Sema * getSema()
Retrieve the semantic analysis object used to analyze the translation unit in which the precompiled h...
Definition: ASTReader.h:2389
void makeNamesVisible(const HiddenNames &Names, Module *Owner)
Make the names within this set of hidden names visible.
Definition: ASTReader.cpp:4261
void UpdateSema()
Update the state of Sema after loading some additional modules.
Definition: ASTReader.cpp:8234
Decl * GetDecl(GlobalDeclID ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:7787
int getSLocEntryID(SourceLocation::UIntTy SLocOffset) override
Get the index ID for the loaded SourceLocation offset.
Definition: ASTReader.cpp:1496
CXXTemporary * ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:9398
void ReadKnownNamespaces(SmallVectorImpl< NamespaceDecl * > &Namespaces) override
Load the set of namespaces that are known to the external source, which will be used during typo corr...
Definition: ASTReader.cpp:8608
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1773
QualType getLocalType(ModuleFile &F, unsigned LocalID)
Resolve a local type ID within a given AST file into a type.
Definition: ASTReader.cpp:7435
Module * getSubmodule(serialization::SubmoduleID GlobalID)
Retrieve the submodule that corresponds to a global submodule ID.
Definition: ASTReader.cpp:8980
void PrintStats() override
Print some statistics about AST usage.
Definition: ASTReader.cpp:8062
void mergeDefinitionVisibility(NamedDecl *Def, NamedDecl *MergedDef)
Note that MergedDef is a redefinition of the canonical definition Def, so Def should be visible whene...
Definition: ASTReader.cpp:4324
serialization::SelectorID getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const
Retrieve the global selector ID that corresponds to this the local selector ID in a given module.
Definition: ASTReader.cpp:9092
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Definition: ASTReader.h:2377
void StartedDeserializing() override
Notify ASTReader that we started deserialization of a decl or type so until FinishedDeserializing is ...
void ReadMethodPool(Selector Sel) override
Load the contents of the global method pool for a given selector.
Definition: ASTReader.cpp:8563
void InitializeContext()
Initializes the ASTContext.
Definition: ASTReader.cpp:5085
CXXBaseSpecifier * GetExternalCXXBaseSpecifiers(uint64_t Offset) override
Resolve the offset of a set of C++ base specifiers in the decl stream into an array of specifiers.
Definition: ASTReader.cpp:7608
serialization::TypeID getGlobalTypeID(ModuleFile &F, unsigned LocalID) const
Map a local type ID within a given AST file into a global type ID.
Definition: ASTReader.cpp:7440
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:5691
void FinishedDeserializing() override
Notify ASTReader that we finished the deserialization of a decl or type.
void updateOutOfDateIdentifier(const IdentifierInfo &II) override
Update an out-of-date identifier.
Definition: ASTReader.cpp:2222
void ReadDefinedMacros() override
Read the set of macros defined by this external macro source.
Definition: ASTReader.cpp:2104
HeaderFileInfo GetHeaderFileInfo(FileEntryRef FE) override
Read the header file information for the given file entry.
Definition: ASTReader.cpp:6521
serialization::MacroID getGlobalMacroID(ModuleFile &M, unsigned LocalID)
Retrieve the global macro ID corresponding to the given local ID within the given module file.
Definition: ASTReader.cpp:8950
An object for streaming information from a record.
bool readBool()
Read a boolean value, advancing Idx.
uint32_t readUInt32()
Read a 32-bit unsigned value; required to satisfy BasicReader.
llvm::APFloat readAPFloat(const llvm::fltSemantics &Sem)
Read an arbitrary constant value, advancing Idx.
Definition: ASTReader.cpp:9359
TemplateArgumentLoc readTemplateArgumentLoc()
Reads a TemplateArgumentLoc, advancing Idx.
Definition: ASTReader.cpp:7491
void readTypeLoc(TypeLoc TL, LocSeq *Seq=nullptr)
Reads the location information for a type.
Definition: ASTReader.cpp:7119
Expr * readExpr()
Reads an expression.
void readUnresolvedSet(LazyASTUnresolvedSet &Set)
Read a UnresolvedSet structure, advancing Idx.
Definition: ASTReader.cpp:9187
void readTemplateArgumentList(SmallVectorImpl< TemplateArgument > &TemplArgs, bool Canonicalize=false)
Read a template argument array, advancing Idx.
Definition: ASTReader.cpp:9177
void readQualifierInfo(QualifierInfo &Info)
Definition: ASTReader.cpp:9145
DeclarationNameLoc readDeclarationNameLoc(DeclarationName Name)
Read a declaration name, advancing Idx.
Definition: ASTReader.cpp:9108
CXXBaseSpecifier readCXXBaseSpecifier()
Read a C++ base specifier, advancing Idx.
Definition: ASTReader.cpp:9198
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Expr * readSubExpr()
Reads a sub-expression operand during statement reading.
Expected< unsigned > readRecord(llvm::BitstreamCursor &Cursor, unsigned AbbrevID)
Reads a record with id AbbrevID from Cursor, resetting the internal state.
DeclarationNameInfo readDeclarationNameInfo()
Definition: ASTReader.cpp:9133
IdentifierInfo * readIdentifier()
TemplateArgumentLocInfo readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind)
Reads a TemplateArgumentLocInfo appropriate for the given TemplateArgument kind, advancing Idx.
Definition: ASTReader.cpp:7459
TemplateArgument readTemplateArgument(bool Canonicalize)
TypeSourceInfo * readTypeSourceInfo()
Reads a declarator info from the given record, advancing Idx.
Definition: ASTReader.cpp:7126
void readTemplateArgumentListInfo(TemplateArgumentListInfo &Result)
Definition: ASTReader.cpp:7501
TypeCoupledDeclRefInfo readTypeCoupledDeclRefInfo()
Definition: ASTReader.cpp:9141
void skipInts(unsigned N)
Skips the specified number of values.
GlobalDeclID readDeclID()
Reads a declaration ID from the given position in this record.
SourceRange readSourceRange(LocSeq *Seq=nullptr)
Read a source range, advancing Idx.
NestedNameSpecifierLoc readNestedNameSpecifierLoc()
Return a nested name specifier, advancing Idx.
Definition: ASTReader.cpp:9278
ConceptReference * readConceptReference()
Definition: ASTReader.cpp:6962
void readOMPChildren(OMPChildren *Data)
Read an OpenMP children, advancing Idx.
OMPClause * readOMPClause()
Read an OpenMP clause, advancing Idx.
void readOpenACCClauseList(MutableArrayRef< const OpenACCClause * > Clauses)
Read a list of OpenACC clauses into the passed SmallVector.
OMPTraitInfo * readOMPTraitInfo()
Read an OMPTraitInfo object, advancing Idx.
TemplateParameterList * readTemplateParameterList()
Read a template parameter list, advancing Idx.
Definition: ASTReader.cpp:9158
OpenACCClause * readOpenACCClause()
Read an OpenACC clause, advancing Idx.
llvm::SmallVector< Expr * > readOpenACCVarList()
Read a list of Exprs used for a var-list.
CXXCtorInitializer ** readCXXCtorInitializers()
Read a CXXCtorInitializer array, advancing Idx.
Definition: ASTReader.cpp:9213
const ASTTemplateArgumentListInfo * readASTTemplateArgumentListInfo()
Definition: ASTReader.cpp:7511
Stmt * readStmt()
Reads a statement.
uint64_t readInt()
Returns the current value in this record, and advances to the next value.
Attr * readAttr()
Reads one attribute from the current stream position, advancing Idx.
SourceLocation readSourceLocation(LocSeq *Seq=nullptr)
Read a source location, advancing Idx.
llvm::SmallVector< Expr * > readOpenACCIntExprList()
Read a list of Exprs used for a int-expr-list.
Abstracts clang modules and precompiled header files and holds everything needed to generate debug in...
Definition: Module.h:874
Wrapper for source info for array parameter types.
Definition: TypeLoc.h:1617
Wrapper for source info for arrays.
Definition: TypeLoc.h:1561
void setLBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1567
void setRBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1575
void setSizeExpr(Expr *Size)
Definition: TypeLoc.h:1587
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2638
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2630
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2622
Attr - This represents one attribute.
Definition: Attr.h:46
Type source information for an attributed type.
Definition: TypeLoc.h:875
void setAttr(const Attr *A)
Definition: TypeLoc.h:901
void setConceptReference(ConceptReference *CR)
Definition: TypeLoc.h:2201
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2195
Type source information for an btf_tag attributed type.
Definition: TypeLoc.h:925
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1314
void setCaretLoc(SourceLocation Loc)
Definition: TypeLoc.h:1320
Wrapper for source info for builtin types.
Definition: TypeLoc.h:565
void setWrittenTypeSpec(TypeSpecifierType written)
Definition: TypeLoc.h:651
bool needsExtraLocalData() const
Definition: TypeLoc.h:594
void setModeAttr(bool written)
Definition: TypeLoc.h:663
void setBuiltinLoc(SourceLocation Loc)
Definition: TypeLoc.h:571
void setWrittenWidthSpec(TypeSpecifierWidth written)
Definition: TypeLoc.h:640
void setWrittenSignSpec(TypeSpecifierSign written)
Definition: TypeLoc.h:624
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2300
void setSourceOrder(int Pos)
Set the source order of this initializer.
Definition: DeclCXX.h:2487
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
Decl * getLambdaContextDecl() const
Retrieve the declaration that provides additional context for a lambda, when the normal declaration c...
Definition: DeclCXX.cpp:1685
unsigned getLambdaIndexInContext() const
Retrieve the index of this lambda within the context declaration returned by getLambdaContextDecl().
Definition: DeclCXX.h:1792
Represents a C++ temporary.
Definition: ExprCXX.h:1453
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition: ExprCXX.cpp:1043
bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden, bool isExplicitModule) override
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
Definition: ASTReader.cpp:244
bool ReadFullVersionInformation(StringRef FullVersion) override
Receives the full Clang version information.
Definition: ASTReader.cpp:157
bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) override
Receives the file system options.
Definition: ASTReader.cpp:198
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:213
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:222
void ReadModuleMapFile(StringRef ModuleMapPath) override
Definition: ASTReader.cpp:167
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:204
bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:182
void ReadModuleName(StringRef ModuleName) override
Definition: ASTReader.cpp:162
bool needsInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.cpp:228
bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:173
void readModuleFileExtension(const ModuleFileExtensionMetadata &Metadata) override
Indicates that a particular module file extension has been read.
Definition: ASTReader.cpp:260
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:191
void visitModuleFile(StringRef Filename, serialization::ModuleKind Kind) override
This is called for each AST file loaded.
Definition: ASTReader.cpp:238
bool needsSystemInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.cpp:233
A reference to a concept and its template args, as it appears in the code.
Definition: ASTConcept.h:128
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:94
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:421
A map from continuous integer ranges to some value, with a very specialized interface.
void insertOrReplace(const value_type &Val)
typename Representation::const_iterator const_iterator
typename Representation::iterator iterator
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1262
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1802
bool hasExternalVisibleStorage() const
Whether this DeclContext has external storage containing additional declarations that are visible in ...
Definition: DeclBase.h:2649
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1938
void setMustBuildLookupTable()
Mark that there are external lexical declarations that we need to include in our lookup table (and th...
Definition: DeclBase.h:2622
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition: DeclBase.h:2637
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1372
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
void setHasExternalLexicalStorage(bool ES=true) const
State whether this DeclContext has external storage for declarations lexically in this context.
Definition: DeclBase.h:2643
bool isDeclInLexicalTraversal(const Decl *D) const
Determine whether the given declaration is stored in the list of declarations lexically within this c...
Definition: DeclBase.h:2663
DeclID get() const
Definition: DeclID.h:117
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition: DeclBase.h:849
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
GlobalDeclID getGlobalID() const
Retrieve the global declaration ID associated with this declaration, which specifies where this Decl ...
Definition: DeclBase.h:780
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:776
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
SourceLocation getLocation() const
Definition: DeclBase.h:445
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1039
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:803
Kind getKind() const
Definition: DeclBase.h:448
DeclContext * getDeclContext()
Definition: DeclBase.h:454
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:860
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeNamedTypeLoc(TypeSourceInfo *TInfo)
Construct location information for a constructor, destructor or conversion operator.
static DeclarationNameLoc makeCXXLiteralOperatorNameLoc(SourceLocation Loc)
Construct location information for a literal C++ operator.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
The name of a declaration.
NameKind
The kind of the name stored in this DeclarationName.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:771
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2087
void setDecltypeLoc(SourceLocation Loc)
Definition: TypeLoc.h:2084
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2302
void setAttrNameLoc(SourceLocation loc)
Definition: TypeLoc.h:1773
void setAttrOperandParensRange(SourceRange range)
Definition: TypeLoc.h:1794
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2423
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2403
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2412
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1892
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2472
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2492
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2460
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2516
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2508
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:2524
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2500
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6535
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1864
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1277
Carries a Clang diagnostic in an llvm::Error.
static llvm::Error create(SourceLocation Loc, PartialDiagnostic Diag)
Creates a new DiagnosticError that contains the given diagnostic at the given location.
PartialDiagnosticAt & getDiagnostic()
bool wasUpgradedFromWarning() const
Whether this mapping attempted to map the diagnostic to a warning, but was overruled because the diag...
void setSeverity(diag::Severity Value)
static DiagnosticMapping deserialize(unsigned Bits)
Deserialize a mapping.
void setUpgradedFromWarning(bool Value)
Options for controlling the compiler diagnostics engine.
std::vector< std::string > SystemHeaderWarningsModules
The list of -Wsystem-header-in-module=...
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:193
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1553
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition: Diagnostic.h:563
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:568
bool getEnableAllWarnings() const
Definition: Diagnostic.h:670
Level
The level of the diagnostic, after it has been through mapping.
Definition: Diagnostic.h:196
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:937
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:696
bool getWarningsAsErrors() const
Definition: Diagnostic.h:678
diag::Severity getExtensionHandlingBehavior() const
Definition: Diagnostic.h:787
StringRef getName() const
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
Represents an enum.
Definition: Decl.h:3870
Wrapper for source info for enum types.
Definition: TypeLoc.h:749
This represents one expression.
Definition: Expr.h:110
RAII class for safely pairing a StartedDeserializing call with FinishedDeserializing.
MemoryBufferSizes getMemoryBufferSizes() const
Return the amount of memory used by memory buffers, breaking down by heap-backed versus mmap'ed memor...
uint32_t getGeneration() const
Get the current generation of this AST source.
Represents difference between two FPOptions values.
Definition: LangOptions.h:956
static FPOptionsOverride getFromOpaqueInt(storage_type I)
Definition: LangOptions.h:1019
FPOptions applyOverrides(FPOptions Base)
Definition: LangOptions.h:1026
static FPOptions getFromOpaqueInt(storage_type Value)
Definition: LangOptions.h:920
Represents a member of a struct/union/class.
Definition: Decl.h:3060
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition: FileEntry.h:57
time_t getModificationTime() const
Definition: FileEntry.h:348
off_t getSize() const
Definition: FileEntry.h:340
StringRef getName() const
The name of this FileEntry.
Definition: FileEntry.h:61
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:300
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isValid() const
bool isInvalid() const
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:240
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
llvm::vfs::FileSystem & getVirtualFileSystem() const
Definition: FileManager.h:251
FileEntryRef getVirtualFileRef(StringRef Filename, off_t Size, time_t ModificationTime)
Retrieve a file entry for a "virtual" file that acts as if there were a file with the given name on d...
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
Keeps track of options that affect how file operations are performed.
std::string WorkingDir
If set, paths are resolved as if the working directory was set to the value of WorkingDir.
Represents a function declaration or definition.
Definition: Decl.h:1972
void setLazyBody(uint64_t Offset)
Definition: Decl.h:2304
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4668
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4912
Wrapper for source info for functions.
Definition: TypeLoc.h:1428
unsigned getNumParams() const
Definition: TypeLoc.h:1500
void setLocalRangeBegin(SourceLocation L)
Definition: TypeLoc.h:1448
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1464
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1507
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1472
void setLocalRangeEnd(SourceLocation L)
Definition: TypeLoc.h:1456
void setExceptionSpecRange(SourceRange R)
Definition: TypeLoc.h:1486
static std::pair< GlobalModuleIndex *, llvm::Error > readIndex(llvm::StringRef Path)
Read a global index file for the given directory.
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
uint64_t BuildSessionTimestamp
The time in seconds when the build session started.
unsigned ImplicitModuleMaps
Implicit module maps.
std::vector< SystemHeaderPrefix > SystemHeaderPrefixes
User-specified system header prefixes.
unsigned EnablePrebuiltImplicitModules
Also search for prebuilt implicit modules in the prebuilt module cache path.
unsigned ModuleMapFileHomeIsCwd
Set the 'home directory' of a module map file to the current working directory (or the home directory...
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
std::string ModuleCachePath
The directory used for the module cache.
std::string ModuleUserBuildPath
The directory used for a user build.
std::vector< std::string > VFSOverlayFiles
The set of user-provided virtual filesystem overlay files.
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
unsigned UseBuiltinIncludes
Include the compiler builtin includes.
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
std::vector< Entry > UserEntries
User specified include entries.
std::string ResourceDir
The directory which holds the compiler resource files (builtin includes, etc.).
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
unsigned ModulesValidateOncePerBuildSession
If true, skip verifying input files used by modules if the module was already verified during this bu...
unsigned DisableModuleHash
Whether we should disable the use of the hash string within the module cache.
Module * lookupModule(StringRef ModuleName, SourceLocation ImportLoc=SourceLocation(), bool AllowSearch=true, bool AllowExtraModuleMapSearch=false)
Lookup a module Search for a module with the given name.
One of these records is kept for each identifier that is lexed.
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
bool isCPlusPlusOperatorKeyword() const
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
void setIsPoisoned(bool Value=true)
setIsPoisoned - Mark this identifier as poisoned.
bool isFromAST() const
Return true if the identifier in its current state was loaded from an AST file.
bool isPoisoned() const
Return true if this token has been poisoned.
bool hasRevertedTokenIDToIdentifier() const
True if revertTokenIDToIdentifier() was called.
tok::NotableIdentifierKind getNotableIdentifierID() const
void setOutOfDate(bool OOD)
Set whether the information for this identifier is out of date with respect to the external source.
tok::ObjCKeywordKind getObjCKeywordID() const
Return the Objective-C keyword ID for the this identifier.
void setObjCOrBuiltinID(unsigned ID)
void revertTokenIDToIdentifier()
Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2 compatibility.
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
void setChangedSinceDeserialization()
Note that this identifier has changed since it was loaded from an AST file.
StringRef getName() const
Return the actual identifier string.
bool isExtensionToken() const
get/setExtension - Initialize information about whether or not this language token is an extension.
void * getFETokenInfo() const
Get and set FETokenInfo.
An iterator that walks over all of the known identifiers in the lookup table.
IdentifierResolver - Keeps track of shadowed decls on enclosing scopes.
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
bool tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name)
Try to add the given declaration to the top level scope, if it (or a redeclaration of it) hasn't alre...
llvm::iterator_range< iterator > decls(DeclarationName Name)
Returns a range of decls with the name 'Name'.
Implements an efficient mapping from strings to IdentifierInfo nodes.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
In-memory cache for modules.
llvm::MemoryBuffer * lookupPCM(llvm::StringRef Filename) const
Get a pointer to the pCM if it exists; else nullptr.
Record the location of an inclusion directive, such as an #include or #import statement.
InclusionKind
The kind of inclusion directives known to the preprocessor.
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3344
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:705
void setAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1398
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:482
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:517
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:488
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:546
std::string OMPHostIRFile
Name of the IR file that contains the result of the OpenMP target host code generation.
Definition: LangOptions.h:560
std::vector< llvm::Triple > OMPTargetTriples
Triples of the OpenMP targets that the host code codegen should take into account in order to generat...
Definition: LangOptions.h:556
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:537
std::vector< std::string > ModuleFeatures
The names of any features to enable in module 'requires' decls in addition to the hard-coded list in ...
Definition: LangOptions.h:543
An UnresolvedSet-like class that might not have been loaded from the external AST source yet.
Used to hold and unique data used to represent #line information.
unsigned getLineTableFilenameID(StringRef Str)
void AddEntry(FileID FID, const std::vector< LineEntry > &Entries)
Add a new line entry that has already been encoded into the internal representation of the line table...
Record the location of a macro definition.
Encapsulates changes to the "macros namespace" (the location where the macro name became active,...
Definition: MacroInfo.h:313
void setPrevious(MacroDirective *Prev)
Set previous definition of the macro with the same name.
Definition: MacroInfo.h:351
Records the location of a macro expansion.
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:39
void setUsedForHeaderGuard(bool Val)
Definition: MacroInfo.h:296
void setHasCommaPasting()
Definition: MacroInfo.h:220
void setDefinitionEndLoc(SourceLocation EndLoc)
Set the location of the last token in the macro.
Definition: MacroInfo.h:128
void setParameterList(ArrayRef< IdentifierInfo * > List, llvm::BumpPtrAllocator &PPAllocator)
Set the specified list of identifiers as the parameter list for this macro.
Definition: MacroInfo.h:166
void setIsFunctionLike()
Function/Object-likeness.
Definition: MacroInfo.h:200
llvm::MutableArrayRef< Token > allocateTokens(unsigned NumTokens, llvm::BumpPtrAllocator &PPAllocator)
Definition: MacroInfo.h:254
void setIsGNUVarargs()
Definition: MacroInfo.h:206
void setIsC99Varargs()
Varargs querying methods. This can only be set for function-like macros.
Definition: MacroInfo.h:205
void setIsUsed(bool Val)
Set the value of the IsUsed flag.
Definition: MacroInfo.h:154
void setExpansionLoc(SourceLocation Loc)
Definition: TypeLoc.h:1171
void setAttrRowOperand(Expr *e)
Definition: TypeLoc.h:1927
void setAttrColumnOperand(Expr *e)
Definition: TypeLoc.h:1933
void setAttrOperandParensRange(SourceRange range)
Definition: TypeLoc.h:1942
void setAttrNameLoc(SourceLocation loc)
Definition: TypeLoc.h:1921
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1332
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1338
void setClassTInfo(TypeSourceInfo *TI)
Definition: TypeLoc.h:1350
void addLinkAsDependency(Module *Mod)
Make module to use export_as as the link dependency name if enough information is available or add it...
Definition: ModuleMap.cpp:69
std::pair< Module *, bool > findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Find a new module or submodule, or create it if it does not already exist.
Definition: ModuleMap.cpp:851
void setUmbrellaDirAsWritten(Module *Mod, DirectoryEntryRef UmbrellaDir, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory)
Sets the umbrella directory of the given module to the given directory.
Definition: ModuleMap.cpp:1201
void setUmbrellaHeaderAsWritten(Module *Mod, FileEntryRef UmbrellaHeader, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory)
Sets the umbrella header of the given module to the given header.
Definition: ModuleMap.cpp:1186
void resolveLinkAsDependencies(Module *Mod)
Use PendingLinkAsModule information to mark top level link names that are going to be replaced by exp...
Definition: ModuleMap.cpp:58
ModuleHeaderRole
Flags describing the role of a module header.
Definition: ModuleMap.h:127
void addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role, bool Imported=false)
Adds this header to the given module.
Definition: ModuleMap.cpp:1282
Describes a module or submodule.
Definition: Module.h:105
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:676
void addRequirement(StringRef Feature, bool RequiredState, const LangOptions &LangOpts, const TargetInfo &Target)
Add the given feature requirement to the list of features required by this module.
Definition: Module.cpp:319
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition: Module.h:350
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition: Module.h:472
unsigned IsUnimportable
Whether this module has declared itself unimportable, either because it's missing a requirement from ...
Definition: Module.h:305
NameVisibilityKind NameVisibility
The visibility of names within this particular module.
Definition: Module.h:395
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition: Module.h:387
@ Hidden
All of the names in this module are hidden.
Definition: Module.h:389
@ AllVisible
All of the names in this module are visible.
Definition: Module.h:391
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:111
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:285
ModuleKind Kind
The kind of this module.
Definition: Module.h:150
void addTopHeaderFilename(StringRef Filename)
Add a top-level header filename associated with this module.
Definition: Module.h:716
bool isUnimportable() const
Determine whether this module has been declared unimportable.
Definition: Module.h:506
void setASTFile(OptionalFileEntryRef File)
Set the serialized AST file for the top-level module of this module.
Definition: Module.h:686
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers).
Definition: Module.h:333
std::string Name
The name of this module.
Definition: Module.h:108
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "C"...
Definition: Module.h:339
unsigned ModuleMapIsPrivate
Whether this module came from a "private" module map, found next to a regular (public) module map.
Definition: Module.h:378
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used.
Definition: Module.h:464
SmallVector< UnresolvedExportDecl, 2 > UnresolvedExports
The set of export declarations that have yet to be resolved.
Definition: Module.h:433
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition: Module.h:296
OptionalDirectoryEntryRef Directory
The build directory of this module.
Definition: Module.h:159
std::optional< DirectoryName > getUmbrellaDirAsWritten() const
Retrieve the umbrella directory as written.
Definition: Module.h:692
unsigned NamedModuleHasInit
Whether this C++20 named modules doesn't need an initializer.
Definition: Module.h:383
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition: Module.h:368
std::string PresumedModuleMapFile
The presumed file name for the module map defining this module.
Definition: Module.h:163
ASTFileSignature Signature
The module signature.
Definition: Module.h:169
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e....
Definition: Module.h:360
void getExportedModules(SmallVectorImpl< Module * > &Exported) const
Appends this module's list of exported modules to Exported.
Definition: Module.cpp:402
std::vector< UnresolvedConflict > UnresolvedConflicts
The list of conflicts for which the module-id has not yet been resolved.
Definition: Module.h:485
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition: Module.h:320
llvm::PointerIntPair< Module *, 1, bool > ExportDecl
Describes an exported module.
Definition: Module.h:412
std::optional< Header > getUmbrellaHeaderAsWritten() const
Retrieve the umbrella header as written.
Definition: Module.h:700
std::string ExportAsModule
The module through which entities defined in this module will eventually be exposed,...
Definition: Module.h:179
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition: Module.h:316
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition: Module.h:355
OptionalFileEntryRef getASTFile() const
The serialized AST file for this module, if one was created.
Definition: Module.h:681
std::vector< Conflict > Conflicts
The list of conflicts.
Definition: Module.h:497
This represents a decl that may have a name.
Definition: Decl.h:249
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
Represents a C++ namespace alias.
Definition: DeclCXX.h:3120
Represent a C++ namespace.
Definition: Decl.h:548
Class that aids in the construction of nested-name-specifiers along with source-location information ...
A C++ nested-name-specifier augmented with source location information.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
static std::string getOwningModuleNameForDiagnostic(const Decl *D)
Get the best name we know for the module that owns the given declaration, or an empty string if the d...
This represents 'acq_rel' clause in the '#pragma omp atomic|flush' directives.
This represents 'acquire' clause in the '#pragma omp atomic|flush' directives.
This represents clause 'affinity' in the '#pragma omp task'-based directives.
static OMPAffinityClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N locator items.
This represents the 'align' clause in the '#pragma omp allocate' directive.
Definition: OpenMPClause.h:388
This represents clause 'aligned' in the '#pragma omp ...' directives.
static OMPAlignedClause * CreateEmpty(const ASTContext &C, unsigned NumVars)
Creates an empty clause with the place for NumVars variables.
This represents clause 'allocate' in the '#pragma omp ...' directives.
Definition: OpenMPClause.h:432
static OMPAllocateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'allocator' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:354
This represents 'at' clause in the '#pragma omp error' directive.
This represents 'atomic_default_mem_order' clause in the '#pragma omp requires' directive.
This represents 'bind' clause in the '#pragma omp ...' directives.
static OMPBindClause * CreateEmpty(const ASTContext &C)
Build an empty 'bind' clause.
This represents 'capture' clause in the '#pragma omp atomic' directive.
Contains data for OpenMP directives: clauses, children expressions/statements (helpers for codegen) a...
void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C)
OMPClauseReader(ASTRecordReader &Record)
OMPClause * readClause()
void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C)
RetTy Visit(PTR(OMPClause) S)
Class that handles post-update expression for some clauses, like 'lastprivate', 'reduction' etc.
Definition: OpenMPClause.h:233
Class that handles pre-initialization statement for some clauses, like 'shedule', 'firstprivate' etc.
Definition: OpenMPClause.h:195
This is a basic class for representing single OpenMP clause.
Definition: OpenMPClause.h:55
This represents 'collapse' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:977
This represents 'compare' clause in the '#pragma omp atomic' directive.
This represents clause 'copyin' in the '#pragma omp ...' directives.
static OMPCopyinClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents clause 'copyprivate' in the '#pragma omp ...' directives.
static OMPCopyprivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'default' clause in the '#pragma omp ...' directive.
This represents 'defaultmap' clause in the '#pragma omp ...' directive.
This represents implicit clause 'depend' for the '#pragma omp task' directive.
static OMPDependClause * CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops)
Creates an empty clause with N variables.
This represents implicit clause 'depobj' for the '#pragma omp depobj' directive.
static OMPDepobjClause * CreateEmpty(const ASTContext &C)
Creates an empty clause.
This represents 'destroy' clause in the '#pragma omp depobj' directive or the '#pragma omp interop' d...
This represents 'detach' clause in the '#pragma omp task' directive.
This represents 'device' clause in the '#pragma omp ...' directive.
This represents 'dist_schedule' clause in the '#pragma omp ...' directive.
This represents the 'doacross' clause for the '#pragma omp ordered' directive.
static OMPDoacrossClause * CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops)
Creates an empty clause with N expressions.
This represents 'dynamic_allocators' clause in the '#pragma omp requires' directive.
This represents clause 'exclusive' in the '#pragma omp scan' directive.
static OMPExclusiveClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'fail' clause in the '#pragma omp atomic' directive.
This represents 'filter' clause in the '#pragma omp ...' directive.
This represents 'final' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:630
This represents clause 'firstprivate' in the '#pragma omp ...' directives.
static OMPFirstprivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents implicit clause 'flush' for the '#pragma omp flush' directive.
static OMPFlushClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents clause 'from' in the '#pragma omp ...' directives.
static OMPFromClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
Representation of the 'full' clause of the '#pragma omp unroll' directive.
Definition: OpenMPClause.h:879
static OMPFullClause * CreateEmpty(const ASTContext &C)
Build an empty 'full' AST node for deserialization.
This represents 'grainsize' clause in the '#pragma omp ...' directive.
This represents clause 'has_device_ptr' in the '#pragma omp ...' directives.
static OMPHasDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents 'hint' clause in the '#pragma omp ...' directive.
This represents 'if' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:527
This represents clause 'in_reduction' in the '#pragma omp task' directives.
static OMPInReductionClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents clause 'inclusive' in the '#pragma omp scan' directive.
static OMPInclusiveClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents the 'init' clause in '#pragma omp ...' directives.
static OMPInitClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N expressions.
This represents clause 'is_device_ptr' in the '#pragma omp ...' directives.
static OMPIsDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents clause 'lastprivate' in the '#pragma omp ...' directives.
static OMPLastprivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents clause 'linear' in the '#pragma omp ...' directives.
static OMPLinearClause * CreateEmpty(const ASTContext &C, unsigned NumVars)
Creates an empty clause with the place for NumVars variables.
This represents clause 'map' in the '#pragma omp ...' directives.
static OMPMapClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars original expressions, NumUniqueDeclarations declar...
This represents 'mergeable' clause in the '#pragma omp ...' directive.
This represents 'message' clause in the '#pragma omp error' directive.
This represents 'nocontext' clause in the '#pragma omp ...' directive.
This represents 'nogroup' clause in the '#pragma omp ...' directive.
This represents clause 'nontemporal' in the '#pragma omp ...' directives.
static OMPNontemporalClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'novariants' clause in the '#pragma omp ...' directive.
This represents 'nowait' clause in the '#pragma omp ...' directive.
This represents 'num_tasks' clause in the '#pragma omp ...' directive.
This represents 'num_teams' clause in the '#pragma omp ...' directive.
This represents 'num_threads' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:676
This represents 'order' clause in the '#pragma omp ...' directive.
This represents 'ordered' clause in the '#pragma omp ...' directive.
static OMPOrderedClause * CreateEmpty(const ASTContext &C, unsigned NumLoops)
Build an empty clause.
Representation of the 'partial' clause of the '#pragma omp unroll' directive.
Definition: OpenMPClause.h:907
static OMPPartialClause * CreateEmpty(const ASTContext &C)
Build an empty 'partial' AST node for deserialization.
This represents 'priority' clause in the '#pragma omp ...' directive.
This represents clause 'private' in the '#pragma omp ...' directives.
static OMPPrivateClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'proc_bind' clause in the '#pragma omp ...' directive.
This represents 'read' clause in the '#pragma omp atomic' directive.
This represents clause 'reduction' in the '#pragma omp ...' directives.
static OMPReductionClause * CreateEmpty(const ASTContext &C, unsigned N, OpenMPReductionClauseModifier Modifier)
Creates an empty clause with the place for N variables.
This represents 'relaxed' clause in the '#pragma omp atomic' directives.
This represents 'release' clause in the '#pragma omp atomic|flush' directives.
This represents 'reverse_offload' clause in the '#pragma omp requires' directive.
This represents 'simd' clause in the '#pragma omp ...' directive.
This represents 'safelen' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:721
This represents 'schedule' clause in the '#pragma omp ...' directive.
This represents 'seq_cst' clause in the '#pragma omp atomic' directive.
This represents 'severity' clause in the '#pragma omp error' directive.
This represents clause 'shared' in the '#pragma omp ...' directives.
static OMPSharedClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with N variables.
This represents 'simdlen' clause in the '#pragma omp ...' directive.
Definition: OpenMPClause.h:756
This represents the 'sizes' clause in the '#pragma omp tile' directive.
Definition: OpenMPClause.h:788
static OMPSizesClause * CreateEmpty(const ASTContext &C, unsigned NumSizes)
Build an empty 'sizes' AST node for deserialization.
This represents clause 'task_reduction' in the '#pragma omp taskgroup' directives.
static OMPTaskReductionClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N variables.
This represents 'thread_limit' clause in the '#pragma omp ...' directive.
This represents 'threads' clause in the '#pragma omp ...' directive.
This represents clause 'to' in the '#pragma omp ...' directives.
static OMPToClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
llvm::SmallVector< OMPTraitSet, 2 > Sets
The outermost level of selector sets.
This represents 'unified_address' clause in the '#pragma omp requires' directive.
This represents 'unified_shared_memory' clause in the '#pragma omp requires' directive.
This represents 'untied' clause in the '#pragma omp ...' directive.
This represents 'update' clause in the '#pragma omp atomic' directive.
static OMPUpdateClause * CreateEmpty(const ASTContext &C, bool IsExtended)
Creates an empty clause with the place for N variables.
This represents the 'use' clause in '#pragma omp ...' directives.
This represents clause 'use_device_addr' in the '#pragma omp ...' directives.
static OMPUseDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents clause 'use_device_ptr' in the '#pragma omp ...' directives.
static OMPUseDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes)
Creates an empty clause with the place for NumVars variables.
This represents clause 'uses_allocators' in the '#pragma omp target'-based directives.
static OMPUsesAllocatorsClause * CreateEmpty(const ASTContext &C, unsigned N)
Creates an empty clause with the place for N allocators.
This represents 'weak' clause in the '#pragma omp atomic' directives.
This represents 'write' clause in the '#pragma omp atomic' directive.
This represents 'ompx_attribute' clause in a directive that might generate an outlined function.
This represents 'ompx_bare' clause in the '#pragma omp target teams ...' directive.
This represents 'ompx_dyn_cgroup_mem' clause in the '#pragma omp target ...' directive.
method_range methods() const
Definition: DeclObjC.h:1015
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
Wrapper for source info for ObjC interfaces.
Definition: TypeLoc.h:1091
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1101
void setNameEndLoc(SourceLocation Loc)
Definition: TypeLoc.h:1113
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6964
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1950
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
bool hasBody() const override
Determine whether this method has a body.
Definition: DeclObjC.h:523
Selector getSelector() const
Definition: DeclObjC.h:327
bool isInstanceMethod() const
Definition: DeclObjC.h:426
void setLazyBody(uint64_t Offset)
Definition: DeclObjC.h:528
Wraps an ObjCPointerType with source location information.
Definition: TypeLoc.h:1370
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1376
void setTypeArgsRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:984
unsigned getNumTypeArgs() const
Definition: TypeLoc.h:988
unsigned getNumProtocols() const
Definition: TypeLoc.h:1018
void setTypeArgsLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:976
void setTypeArgTInfo(unsigned i, TypeSourceInfo *TInfo)
Definition: TypeLoc.h:997
void setProtocolLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1006
void setProtocolRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1014
void setHasBaseTypeAsWritten(bool HasBaseType)
Definition: TypeLoc.h:1046
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition: TypeLoc.h:1027
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2082
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:28
Kind
The basic Objective-C runtimes that we know about.
Definition: ObjCRuntime.h:31
ProtocolLAngleLoc, ProtocolRAngleLoc, and the source locations for protocol qualifiers are stored aft...
Definition: TypeLoc.h:772
unsigned getNumProtocols() const
Definition: TypeLoc.h:809
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition: TypeLoc.h:818
void setProtocolLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:795
void setProtocolRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:805
static OpenACCAsyncClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCAttachClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
This is the base type for all OpenACC Clauses.
Definition: OpenACCClause.h:24
static OpenACCCopyClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyInClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, bool IsReadOnly, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCopyOutClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, bool IsZero, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCCreateClause * Create(const ASTContext &C, OpenACCClauseKind Spelling, SourceLocation BeginLoc, SourceLocation LParenLoc, bool IsZero, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDefaultClause * Create(const ASTContext &C, OpenACCDefaultClauseKind K, SourceLocation BeginLoc, SourceLocation LParenLoc, SourceLocation EndLoc)
static OpenACCDevicePtrClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCDeviceTypeClause * Create(const ASTContext &C, OpenACCClauseKind K, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< DeviceTypeArgument > Archs, SourceLocation EndLoc)
static OpenACCFirstPrivateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCIfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, SourceLocation EndLoc)
static OpenACCNoCreateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCNumGangsClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > IntExprs, SourceLocation EndLoc)
static OpenACCNumWorkersClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCPresentClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCPrivateClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCReductionClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, OpenACCReductionOperator Operator, ArrayRef< Expr * > VarList, SourceLocation EndLoc)
static OpenACCSelfClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *ConditionExpr, SourceLocation EndLoc)
static OpenACCVectorLengthClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *IntExpr, SourceLocation EndLoc)
static OpenACCWaitClause * Create(const ASTContext &C, SourceLocation BeginLoc, SourceLocation LParenLoc, Expr *DevNumExpr, SourceLocation QueuesLoc, ArrayRef< Expr * > QueueIdExprs, SourceLocation EndLoc)
This abstract interface provides operations for unwrapping containers for serialized ASTs (precompile...
virtual llvm::StringRef ExtractPCH(llvm::MemoryBufferRef Buffer) const =0
Returns the serialized AST inside the PCH container Buffer.
ASTReaderListener implementation to validate the information of the PCH file against an initialized P...
Definition: ASTReader.h:294
bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:459
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:866
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:814
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:856
bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:450
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:579
void setEllipsisLoc(SourceLocation Loc)
Definition: TypeLoc.h:2582
void setEllipsisLoc(SourceLocation Loc)
Definition: TypeLoc.h:2112
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1203
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1199
Represents a parameter to a function.
Definition: Decl.h:1762
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2674
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1307
Base class that describes a preprocessed entity, which may be a preprocessor directive or macro expan...
Iteration over the preprocessed entities.
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
std::vector< std::string > MacroIncludes
std::vector< std::string > Includes
ObjCXXARCStandardLibraryKind ObjCXXARCStandardLibrary
The Objective-C++ ARC standard library that we should support, by providing appropriate definitions t...
std::string PCHThroughHeader
If non-empty, the filename used in an #include directive in the primary source file (or command-line ...
bool DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
bool AllowPCHWithDifferentModulesCachePath
When true, a PCH with modules cache path different to the current compilation will not be rejected.
bool UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
std::vector< std::pair< std::string, bool > > Macros
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
HeaderSearch & getHeaderSearchInfo() const
IdentifierTable & getIdentifierTable()
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
const LangOptions & getLangOpts() const
A (possibly-)qualified type.
Definition: Type.h:940
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
Wrapper of type source information for a type with non-trivial direct qualifiers.
Definition: TypeLoc.h:289
The collection of all-type qualifiers we support.
Definition: Type.h:318
@ FastWidth
The width of the "fast" qualifier mask.
Definition: Type.h:362
@ FastMask
The fast qualifier mask.
Definition: Type.h:365
void setAmpAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1412
Represents a struct/union/class.
Definition: Decl.h:4171
Wrapper for source info for record types.
Definition: TypeLoc.h:741
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5561
void AddDecl(Decl *D)
Definition: Scope.h:345
This table allows us to fully hide how we implement multi-keyword caching.
Selector getNullarySelector(const IdentifierInfo *ID)
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Selector getUnarySelector(const IdentifierInfo *ID)
Smart pointer class that efficiently represents Objective-C method names.
iterator find(Selector Sel)
Definition: SemaObjC.h:194
llvm::DenseMap< Selector, Lists >::iterator iterator
Definition: SemaObjC.h:191
std::pair< ObjCMethodList, ObjCMethodList > Lists
Definition: SemaObjC.h:190
std::pair< iterator, bool > insert(std::pair< Selector, Lists > &&Val)
Definition: SemaObjC.h:195
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method)
Add the given method to the list of globally-known methods.
GlobalMethodPool MethodPool
Method Pool - allows efficient lookup when typechecking messages to "id".
Definition: SemaObjC.h:211
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:462
SemaObjC & ObjC()
Definition: Sema.h:1012
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:829
void addExternalSource(ExternalSemaSource *E)
Registers an external source.
Definition: Sema.cpp:592
IdentifierResolver IdResolver
Definition: Sema.h:2551
PragmaMsStackAction
Definition: Sema.h:1221
ASTReaderListenter implementation to set SuggestedPredefines of ASTReader which is required to use a ...
Definition: ASTReader.h:321
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool ReadMacros, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:824
This object establishes a SourceLocationSequence.
Serialized encoding of a sequence of SourceLocations.
Encodes a location in the source.
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location,...
void setExternalSLocEntrySource(ExternalSLocEntrySource *Source)
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
A trivial tuple used to represent a source range.
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
One instance of this struct is kept for every file loaded or used.
std::optional< llvm::MemoryBufferRef > getBufferIfLoaded() const
Return the buffer, only if it has been loaded.
OptionalFileEntryRef ContentsEntry
References the file which the contents were actually loaded from.
unsigned BufferOverridden
Indicates whether the buffer itself was provided to override the actual file contents.
OptionalFileEntryRef OrigEntry
Reference to the file entry representing this ContentCache.
Information about a FileID, basically just the logical file that it represents and include stack info...
void setHasLineDirectives()
Set the flag that indicates that this FileID has line table entries associated with it.
Stmt - This represents one statement.
Definition: Stmt.h:84
DiagnosticStorage * getStorage() const
Retrieve storage for this particular diagnostic.
Definition: Diagnostic.h:1166
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:864
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:857
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3587
TagDecl * getDecl() const
Definition: Type.cpp:4032
Options for controlling the target.
Definition: TargetOptions.h:26
std::string Triple
The name of the target triple to compile for.
Definition: TargetOptions.h:29
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
Definition: TargetOptions.h:58
std::string ABI
If given, the name of the target ABI to use.
Definition: TargetOptions.h:45
std::string TuneCPU
If given, the name of the target CPU to tune code for.
Definition: TargetOptions.h:39
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line.
Definition: TargetOptions.h:54
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
ArgKind
The kind of template argument we're storing.
Definition: TemplateBase.h:64
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1687
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1663
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1704
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1671
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1679
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6169
Wrapper for template type parameters.
Definition: TypeLoc.h:758
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
void setAnnotationEndLoc(SourceLocation L)
Definition: Token.h:150
void setLength(unsigned Len)
Definition: Token.h:141
void setKind(tok::TokenKind K)
Definition: Token.h:95
tok::TokenKind getKind() const
Definition: Token.h:94
void setLocation(SourceLocation L)
Definition: Token.h:140
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition: Token.h:121
void setAnnotationValue(void *val)
Definition: Token.h:238
void startToken()
Reset all flags to cleared.
Definition: Token.h:177
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:196
void setFlag(TokenFlags Flag)
Set the specified flag.
Definition: Token.h:244
[BoundsSafety] Represents information of declarations referenced by the arguments of the counted_by a...
Definition: Type.h:3179
void VisitArrayTypeLoc(ArrayTypeLoc)
Definition: ASTReader.cpp:6835
void VisitFunctionTypeLoc(FunctionTypeLoc)
Definition: ASTReader.cpp:6902
TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq)
Definition: ASTReader.cpp:6763
RetTy Visit(TypeLoc TyLoc)
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition: TypeLoc.h:170
bool isNull() const
Definition: TypeLoc.h:121
void setUnmodifiedTInfo(TypeSourceInfo *TI) const
Definition: TypeLoc.h:2061
A container of type source information.
Definition: Type.h:7342
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1813
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8160
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3435
Wrapper for source info for typedefs.
Definition: TypeLoc.h:693
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2004
void setTypeofLoc(SourceLocation Loc)
Definition: TypeLoc.h:1996
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2012
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2146
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2140
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition: TypeLoc.h:2152
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2143
Wrapper for source info for unresolved typename using decls.
Definition: TypeLoc.h:716
Wrapper for source info for types used via transparent aliases.
Definition: TypeLoc.h:682
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:707
Represents a variable declaration or definition.
Definition: Decl.h:919
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1841
Captures information about a #pragma weak directive.
Definition: Weak.h:25
Source location and bit offset of a declaration.
Definition: ASTBitCodes.h:228
A key used when looking up entities by DeclarationName.
Definition: ASTBitCodes.h:2025
unsigned getHash() const
Compute a fingerprint of this key for use in on-disk hash table.
Definition: ASTReader.cpp:1136
The input file that has been loaded from this AST file, along with bools indicating whether this was ...
Definition: ModuleFile.h:78
OptionalFileEntryRef getFile() const
Definition: ModuleFile.h:107
static InputFile getNotFound()
Definition: ModuleFile.h:101
Information about a module that has been loaded by the ASTReader.
Definition: ModuleFile.h:124
const PPEntityOffset * PreprocessedEntityOffsets
Definition: ModuleFile.h:375
void * IdentifierLookupTable
A pointer to an on-disk hash table of opaque type IdentifierHashTable.
Definition: ModuleFile.h:324
serialization::DeclID BaseDeclID
Base declaration ID for declarations local to this module.
Definition: ModuleFile.h:458
void * SelectorLookupTable
A pointer to an on-disk hash table of opaque type ASTSelectorLookupTable.
Definition: ModuleFile.h:438
std::vector< std::unique_ptr< ModuleFileExtensionReader > > ExtensionReaders
The list of extension readers that are attached to this module file.
Definition: ModuleFile.h:240
SourceLocation DirectImportLoc
The source location where the module was explicitly or implicitly imported in the local translation u...
Definition: ModuleFile.h:230
StringRef Data
The serialized bitstream data for this file.
Definition: ModuleFile.h:216
const serialization::ObjCCategoriesInfo * ObjCCategoriesMap
Array of category list location information within this module file, sorted by the definition ID.
Definition: ModuleFile.h:478
ContinuousRangeMap< uint32_t, int, 2 > PreprocessedEntityRemap
Remapping table for preprocessed entity IDs in this module.
Definition: ModuleFile.h:373
int SLocEntryBaseID
The base ID in the source manager's view of this module.
Definition: ModuleFile.h:285
serialization::IdentifierID BaseIdentifierID
Base identifier ID for identifiers local to this module.
Definition: ModuleFile.h:311
serialization::PreprocessedEntityID BasePreprocessedEntityID
Base preprocessed entity ID for preprocessed entities local to this module.
Definition: ModuleFile.h:370
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
Definition: ModuleFile.h:498
unsigned LocalNumObjCCategoriesInMap
The number of redeclaration info entries in ObjCCategoriesMap.
Definition: ModuleFile.h:481
uint64_t MacroOffsetsBase
Base file offset for the offsets in MacroOffsets.
Definition: ModuleFile.h:341
const llvm::support::unaligned_uint64_t * InputFileOffsets
Relative offsets for all of the input file entries in the AST file.
Definition: ModuleFile.h:255
std::vector< unsigned > PreloadIdentifierOffsets
Offsets of identifiers that we're going to preload within IdentifierTableData.
Definition: ModuleFile.h:328
unsigned LocalNumIdentifiers
The number of identifiers in this AST file.
Definition: ModuleFile.h:301
llvm::BitstreamCursor DeclsCursor
DeclsCursor - This is a cursor to the start of the DECLTYPES_BLOCK block.
Definition: ModuleFile.h:445
const unsigned char * IdentifierTableData
Actual data for the on-disk hash table of identifiers.
Definition: ModuleFile.h:320
uint64_t SLocEntryOffsetsBase
Base file offset for the offsets in SLocEntryOffsets.
Definition: ModuleFile.h:292
llvm::BitstreamCursor InputFilesCursor
The cursor to the start of the input-files block.
Definition: ModuleFile.h:249
std::vector< InputFile > InputFilesLoaded
The input files that have been loaded from this AST file.
Definition: ModuleFile.h:258
serialization::SelectorID BaseSelectorID
Base selector ID for selectors local to this module.
Definition: ModuleFile.h:423
llvm::SetVector< ModuleFile * > ImportedBy
List of modules which depend on this module.
Definition: ModuleFile.h:509
const char * HeaderFileInfoTableData
Actual data for the on-disk hash table of header file information.
Definition: ModuleFile.h:394
SourceLocation ImportLoc
The source location where this module was first imported.
Definition: ModuleFile.h:233
ContinuousRangeMap< uint32_t, int, 2 > TypeRemap
Remapping table for type IDs in this module.
Definition: ModuleFile.h:501
const uint32_t * SLocEntryOffsets
Offsets for all of the source location entries in the AST file.
Definition: ModuleFile.h:296
llvm::BitstreamCursor MacroCursor
The cursor to the start of the preprocessor block, which stores all of the macro definitions.
Definition: ModuleFile.h:334
FileID OriginalSourceFileID
The file ID for the original source file that was used to build this AST file.
Definition: ModuleFile.h:162
FileEntryRef File
The file entry for the module file.
Definition: ModuleFile.h:179
std::string ActualOriginalSourceFileName
The actual original source file name that was used to build this AST file.
Definition: ModuleFile.h:158
ContinuousRangeMap< uint32_t, int, 2 > IdentifierRemap
Remapping table for identifier IDs in this module.
Definition: ModuleFile.h:314
const LocalDeclID * FileSortedDecls
Array of file-level DeclIDs sorted by file.
Definition: ModuleFile.h:473
uint64_t PreprocessorDetailStartOffset
The offset of the start of the preprocessor detail cursor.
Definition: ModuleFile.h:366
std::vector< InputFileInfo > InputFileInfosLoaded
The input file infos that have been loaded from this AST file.
Definition: ModuleFile.h:261
unsigned LocalNumSubmodules
The number of submodules in this module.
Definition: ModuleFile.h:403
SourceLocation FirstLoc
The first source location in this module.
Definition: ModuleFile.h:236
ASTFileSignature ASTBlockHash
The signature of the AST block of the module file, this can be used to unique module files based on A...
Definition: ModuleFile.h:187
uint64_t SourceManagerBlockStartOffset
The bit offset to the start of the SOURCE_MANAGER_BLOCK.
Definition: ModuleFile.h:279
bool DidReadTopLevelSubmodule
Whether the top-level module has been read from the AST file.
Definition: ModuleFile.h:176
std::string OriginalSourceFileName
The original source file name that was used to build the primary AST file, which may have been modifi...
Definition: ModuleFile.h:154
bool isModule() const
Is this a module file for a module (rather than a PCH or similar).
Definition: ModuleFile.h:527
bool HasTimestamps
Whether timestamps are included in this module file.
Definition: ModuleFile.h:173
uint64_t InputFilesOffsetBase
Absolute offset of the start of the input-files block.
Definition: ModuleFile.h:252
llvm::BitstreamCursor SLocEntryCursor
Cursor used to read source location entries.
Definition: ModuleFile.h:276
bool RelocatablePCH
Whether this precompiled header is a relocatable PCH file.
Definition: ModuleFile.h:167
const uint32_t * SelectorOffsets
Offsets into the selector lookup table's data array where each selector resides.
Definition: ModuleFile.h:420
unsigned LocalNumSLocEntries
The number of source location entries in this AST file.
Definition: ModuleFile.h:282
void * HeaderFileInfoTable
The on-disk hash table that contains information about each of the header files.
Definition: ModuleFile.h:398
llvm::BitstreamCursor Stream
The main bitstream cursor for the main block.
Definition: ModuleFile.h:219
serialization::SubmoduleID BaseSubmoduleID
Base submodule ID for submodules local to this module.
Definition: ModuleFile.h:406
uint64_t SizeInBits
The size of this file, in bits.
Definition: ModuleFile.h:207
const UnalignedUInt64 * TypeOffsets
Offset of each type within the bitstream, indexed by the type ID, or the representation of a Type*.
Definition: ModuleFile.h:494
uint64_t GlobalBitOffset
The global bit offset (or base) of this module.
Definition: ModuleFile.h:210
bool StandardCXXModule
Whether this module file is a standard C++ module.
Definition: ModuleFile.h:170
unsigned LocalNumTypes
The number of types in this AST file.
Definition: ModuleFile.h:490
StringRef ModuleOffsetMap
The module offset map data for this file.
Definition: ModuleFile.h:244
const PPSkippedRange * PreprocessedSkippedRangeOffsets
Definition: ModuleFile.h:381
std::string FileName
The file name of the module file.
Definition: ModuleFile.h:139
uint64_t InputFilesValidationTimestamp
If non-zero, specifies the time when we last validated input files.
Definition: ModuleFile.h:271
llvm::BitstreamCursor PreprocessorDetailCursor
The cursor to the start of the (optional) detailed preprocessing record block.
Definition: ModuleFile.h:363
SourceLocation::UIntTy SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Definition: ModuleFile.h:288
const DeclOffset * DeclOffsets
Offset of each declaration within the bitstream, indexed by the declaration ID (-1).
Definition: ModuleFile.h:455
std::string getTimestampFilename() const
Definition: ModuleFile.h:147
uint64_t MacroStartOffset
The offset of the start of the set of defined macros.
Definition: ModuleFile.h:357
ASTFileSignature Signature
The signature of the module file, which may be used instead of the size and modification time to iden...
Definition: ModuleFile.h:183
unsigned LocalNumMacros
The number of macros in this AST file.
Definition: ModuleFile.h:337
ContinuousRangeMap< serialization::DeclID, int, 2 > DeclRemap
Remapping table for declaration IDs in this module.
Definition: ModuleFile.h:461
const unsigned char * SelectorLookupTableData
A pointer to the character data that comprises the selector table.
Definition: ModuleFile.h:431
void dump()
Dump debugging output for this module.
Definition: ModuleFile.cpp:47
unsigned LocalNumDecls
The number of declarations in this AST file.
Definition: ModuleFile.h:451
unsigned LocalNumHeaderFileInfos
The number of local HeaderFileInfo structures.
Definition: ModuleFile.h:387
llvm::BitVector SearchPathUsage
The bit vector denoting usage of each header search entry (true = used).
Definition: ModuleFile.h:190
unsigned Generation
The generation of which this module file is a part.
Definition: ModuleFile.h:200
const uint32_t * IdentifierOffsets
Offsets into the identifier table data.
Definition: ModuleFile.h:308
ContinuousRangeMap< uint32_t, int, 2 > SelectorRemap
Remapping table for selector IDs in this module.
Definition: ModuleFile.h:426
llvm::DenseMap< ModuleFile *, serialization::DeclID > GlobalToLocalDeclIDs
Mapping from the module files that this module file depends on to the base declaration ID for that mo...
Definition: ModuleFile.h:470
ContinuousRangeMap< uint32_t, int, 2 > MacroRemap
Remapping table for macro IDs in this module.
Definition: ModuleFile.h:354
const uint32_t * MacroOffsets
Offsets of macros in the preprocessor block.
Definition: ModuleFile.h:348
uint64_t ASTBlockStartOffset
The bit offset of the AST block of this module.
Definition: ModuleFile.h:213
ContinuousRangeMap< uint32_t, int, 2 > SubmoduleRemap
Remapping table for submodule IDs in this module.
Definition: ModuleFile.h:409
llvm::BitVector VFSUsage
The bit vector denoting usage of each VFS entry (true = used).
Definition: ModuleFile.h:193
uint64_t DeclsBlockStartOffset
The offset to the start of the DECLTYPES_BLOCK block.
Definition: ModuleFile.h:448
SmallVector< uint64_t, 8 > PragmaDiagMappings
Diagnostic IDs and their mappings that the user changed.
Definition: ModuleFile.h:506
unsigned BasePreprocessedSkippedRangeID
Base ID for preprocessed skipped ranges local to this module.
Definition: ModuleFile.h:379
unsigned LocalNumSelectors
The number of selectors new to this file.
Definition: ModuleFile.h:416
ModuleKind Kind
The type of this module.
Definition: ModuleFile.h:136
std::string ModuleName
The name of the module.
Definition: ModuleFile.h:142
serialization::MacroID BaseMacroID
Base macro ID for macros local to this module.
Definition: ModuleFile.h:351
SmallVector< uint64_t, 1 > ObjCCategories
The Objective-C category lists for categories known to this module.
Definition: ModuleFile.h:485
std::string BaseDirectory
The base directory of the module.
Definition: ModuleFile.h:145
llvm::SmallVector< ModuleFile *, 16 > TransitiveImports
List of modules which this modules dependent on.
Definition: ModuleFile.h:520
Manages the set of modules loaded by an AST reader.
Definition: ModuleManager.h:47
ModuleFile & getPrimaryModule()
Returns the primary module associated with the manager, that is, the first module loaded.
AddModuleResult
The result of attempting to add a new module.
@ Missing
The module file is missing.
@ OutOfDate
The module file is out-of-date.
@ NewlyLoaded
The module file was just loaded in response to this call.
@ AlreadyLoaded
The module file had already been loaded.
ModuleReverseIterator rbegin()
Reverse iterator to traverse all loaded modules.
llvm::iterator_range< SmallVectorImpl< ModuleFile * >::const_iterator > pch_modules() const
A range covering the PCH and preamble module files loaded.
void visit(llvm::function_ref< bool(ModuleFile &M)> Visitor, llvm::SmallPtrSetImpl< ModuleFile * > *ModuleFilesHit=nullptr)
Visit each of the modules.
unsigned size() const
Number of modules loaded.
Source range/offset of a preprocessed entity.
Definition: ASTBitCodes.h:187
RawLocEncoding getBegin() const
Definition: ASTBitCodes.h:203
RawLocEncoding getEnd() const
Definition: ASTBitCodes.h:204
Source range of a skipped preprocessor region.
Definition: ASTBitCodes.h:210
RawLocEncoding getBegin() const
Definition: ASTBitCodes.h:222
RawLocEncoding getEnd() const
Definition: ASTBitCodes.h:223
ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, unsigned PriorGeneration)
Definition: ASTReader.cpp:8492
ArrayRef< ObjCMethodDecl * > getFactoryMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:8539
ArrayRef< ObjCMethodDecl * > getInstanceMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:8534
static TypeIdx fromTypeID(TypeID ID)
Definition: ASTBitCodes.h:100
32 aligned uint64_t in the AST file.
Definition: ASTBitCodes.h:170
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:980
static hash_value_type ComputeHash(const internal_key_type &a)
Definition: ASTReader.cpp:975
static internal_key_type ReadKey(const unsigned char *d, unsigned n)
Definition: ASTReader.cpp:985
Class that performs lookup for an identifier stored in an AST file.
IdentifierID ReadIdentifierID(const unsigned char *d)
Definition: ASTReader.cpp:1009
data_type ReadData(const internal_key_type &k, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:1025
Class that performs lookup for a selector's entries in the global method pool stored in an AST file.
internal_key_type ReadKey(const unsigned char *d, unsigned)
Definition: ASTReader.cpp:915
data_type ReadData(Selector, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:937
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:910
static hash_value_type ComputeHash(Selector Sel)
Definition: ASTReader.cpp:905
Trait class used to search the on-disk hash table containing all of the header search information.
PredefinedTypeIDs
Predefined type IDs.
Definition: ASTBitCodes.h:843
CtorInitializerType
The different kinds of data that can occur in a CtorInitializer.
Definition: ASTBitCodes.h:1981
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
Definition: ASTBitCodes.h:1105
const unsigned NumSpecialTypeIDs
The number of special type IDs.
Definition: ASTBitCodes.h:1160
TypeCode
Record codes for each kind of type.
Definition: ASTBitCodes.h:1119
@ PREDEF_TYPE_LONG_ACCUM_ID
The 'long _Accum' type.
Definition: ASTBitCodes.h:989
@ PREDEF_TYPE_SAMPLER_ID
OpenCL sampler type.
Definition: ASTBitCodes.h:962
@ PREDEF_TYPE_INT128_ID
The '__int128_t' type.
Definition: ASTBitCodes.h:911
@ PREDEF_TYPE_CHAR32_ID
The C++ 'char32_t' type.
Definition: ASTBitCodes.h:920
@ PREDEF_TYPE_SAT_SHORT_ACCUM_ID
The '_Sat short _Accum' type.
Definition: ASTBitCodes.h:1019
@ PREDEF_TYPE_IBM128_ID
The '__ibm128' type.
Definition: ASTBitCodes.h:1067
@ PREDEF_TYPE_SHORT_FRACT_ID
The 'short _Fract' type.
Definition: ASTBitCodes.h:1001
@ PREDEF_TYPE_AUTO_RREF_DEDUCT
The "auto &&" deduction type.
Definition: ASTBitCodes.h:941
@ PREDEF_TYPE_BOUND_MEMBER
The placeholder type for bound member functions.
Definition: ASTBitCodes.h:935
@ PREDEF_TYPE_LONGLONG_ID
The (signed) 'long long' type.
Definition: ASTBitCodes.h:890
@ PREDEF_TYPE_FRACT_ID
The '_Fract' type.
Definition: ASTBitCodes.h:1004
@ PREDEF_TYPE_ARC_UNBRIDGED_CAST
ARC's unbridged-cast placeholder type.
Definition: ASTBitCodes.h:947
@ PREDEF_TYPE_USHORT_FRACT_ID
The 'unsigned short _Fract' type.
Definition: ASTBitCodes.h:1010
@ PREDEF_TYPE_SAT_ULONG_FRACT_ID
The '_Sat unsigned long _Fract' type.
Definition: ASTBitCodes.h:1052
@ PREDEF_TYPE_BOOL_ID
The 'bool' or '_Bool' type.
Definition: ASTBitCodes.h:851
@ PREDEF_TYPE_SAT_LONG_ACCUM_ID
The '_Sat long _Accum' type.
Definition: ASTBitCodes.h:1025
@ PREDEF_TYPE_SAT_LONG_FRACT_ID
The '_Sat long _Fract' type.
Definition: ASTBitCodes.h:1043
@ PREDEF_TYPE_SAT_SHORT_FRACT_ID
The '_Sat short _Fract' type.
Definition: ASTBitCodes.h:1037
@ PREDEF_TYPE_CHAR_U_ID
The 'char' type, when it is unsigned.
Definition: ASTBitCodes.h:854
@ PREDEF_TYPE_RESERVE_ID_ID
OpenCL reserve_id type.
Definition: ASTBitCodes.h:968
@ PREDEF_TYPE_SAT_ACCUM_ID
The '_Sat _Accum' type.
Definition: ASTBitCodes.h:1022
@ PREDEF_TYPE_BUILTIN_FN
The placeholder type for builtin functions.
Definition: ASTBitCodes.h:953
@ PREDEF_TYPE_SHORT_ACCUM_ID
The 'short _Accum' type.
Definition: ASTBitCodes.h:983
@ PREDEF_TYPE_FLOAT_ID
The 'float' type.
Definition: ASTBitCodes.h:893
@ PREDEF_TYPE_QUEUE_ID
OpenCL queue type.
Definition: ASTBitCodes.h:965
@ PREDEF_TYPE_INT_ID
The (signed) 'int' type.
Definition: ASTBitCodes.h:884
@ PREDEF_TYPE_OBJC_SEL
The ObjC 'SEL' type.
Definition: ASTBitCodes.h:929
@ PREDEF_TYPE_BFLOAT16_ID
The '__bf16' type.
Definition: ASTBitCodes.h:1064
@ PREDEF_TYPE_WCHAR_ID
The C++ 'wchar_t' type.
Definition: ASTBitCodes.h:878
@ PREDEF_TYPE_UCHAR_ID
The 'unsigned char' type.
Definition: ASTBitCodes.h:857
@ PREDEF_TYPE_UACCUM_ID
The 'unsigned _Accum' type.
Definition: ASTBitCodes.h:995
@ PREDEF_TYPE_SCHAR_ID
The 'signed char' type.
Definition: ASTBitCodes.h:875
@ PREDEF_TYPE_CHAR_S_ID
The 'char' type, when it is signed.
Definition: ASTBitCodes.h:872
@ PREDEF_TYPE_NULLPTR_ID
The type of 'nullptr'.
Definition: ASTBitCodes.h:914
@ PREDEF_TYPE_ULONG_FRACT_ID
The 'unsigned long _Fract' type.
Definition: ASTBitCodes.h:1016
@ PREDEF_TYPE_FLOAT16_ID
The '_Float16' type.
Definition: ASTBitCodes.h:977
@ PREDEF_TYPE_UINT_ID
The 'unsigned int' type.
Definition: ASTBitCodes.h:863
@ PREDEF_TYPE_FLOAT128_ID
The '__float128' type.
Definition: ASTBitCodes.h:974
@ PREDEF_TYPE_OBJC_ID
The ObjC 'id' type.
Definition: ASTBitCodes.h:923
@ PREDEF_TYPE_CHAR16_ID
The C++ 'char16_t' type.
Definition: ASTBitCodes.h:917
@ PREDEF_TYPE_ARRAY_SECTION
The placeholder type for an array section.
Definition: ASTBitCodes.h:971
@ PREDEF_TYPE_ULONGLONG_ID
The 'unsigned long long' type.
Definition: ASTBitCodes.h:869
@ PREDEF_TYPE_SAT_UFRACT_ID
The '_Sat unsigned _Fract' type.
Definition: ASTBitCodes.h:1049
@ PREDEF_TYPE_USHORT_ID
The 'unsigned short' type.
Definition: ASTBitCodes.h:860
@ PREDEF_TYPE_SHORT_ID
The (signed) 'short' type.
Definition: ASTBitCodes.h:881
@ PREDEF_TYPE_OMP_ARRAY_SHAPING
The placeholder type for OpenMP array shaping operation.
Definition: ASTBitCodes.h:1055
@ PREDEF_TYPE_DEPENDENT_ID
The placeholder type for dependent types.
Definition: ASTBitCodes.h:905
@ PREDEF_TYPE_LONGDOUBLE_ID
The 'long double' type.
Definition: ASTBitCodes.h:899
@ PREDEF_TYPE_DOUBLE_ID
The 'double' type.
Definition: ASTBitCodes.h:896
@ PREDEF_TYPE_UINT128_ID
The '__uint128_t' type.
Definition: ASTBitCodes.h:908
@ PREDEF_TYPE_HALF_ID
The OpenCL 'half' / ARM NEON __fp16 type.
Definition: ASTBitCodes.h:944
@ PREDEF_TYPE_VOID_ID
The void type.
Definition: ASTBitCodes.h:848
@ PREDEF_TYPE_SAT_USHORT_FRACT_ID
The '_Sat unsigned short _Fract' type.
Definition: ASTBitCodes.h:1046
@ PREDEF_TYPE_ACCUM_ID
The '_Accum' type.
Definition: ASTBitCodes.h:986
@ PREDEF_TYPE_SAT_FRACT_ID
The '_Sat _Fract' type.
Definition: ASTBitCodes.h:1040
@ PREDEF_TYPE_NULL_ID
The NULL type.
Definition: ASTBitCodes.h:845
@ PREDEF_TYPE_USHORT_ACCUM_ID
The 'unsigned short _Accum' type.
Definition: ASTBitCodes.h:992
@ PREDEF_TYPE_CHAR8_ID
The C++ 'char8_t' type.
Definition: ASTBitCodes.h:980
@ PREDEF_TYPE_UFRACT_ID
The 'unsigned _Fract' type.
Definition: ASTBitCodes.h:1013
@ PREDEF_TYPE_OVERLOAD_ID
The placeholder type for overloaded function sets.
Definition: ASTBitCodes.h:902
@ PREDEF_TYPE_INCOMPLETE_MATRIX_IDX
A placeholder type for incomplete matrix index operations.
Definition: ASTBitCodes.h:1061
@ PREDEF_TYPE_UNRESOLVED_TEMPLATE
The placeholder type for unresolved templates.
Definition: ASTBitCodes.h:1095
@ PREDEF_TYPE_SAT_USHORT_ACCUM_ID
The '_Sat unsigned short _Accum' type.
Definition: ASTBitCodes.h:1028
@ PREDEF_TYPE_LONG_ID
The (signed) 'long' type.
Definition: ASTBitCodes.h:887
@ PREDEF_TYPE_SAT_ULONG_ACCUM_ID
The '_Sat unsigned long _Accum' type.
Definition: ASTBitCodes.h:1034
@ PREDEF_TYPE_LONG_FRACT_ID
The 'long _Fract' type.
Definition: ASTBitCodes.h:1007
@ PREDEF_TYPE_UNKNOWN_ANY
The 'unknown any' placeholder type.
Definition: ASTBitCodes.h:932
@ PREDEF_TYPE_OMP_ITERATOR
The placeholder type for OpenMP iterator expression.
Definition: ASTBitCodes.h:1058
@ PREDEF_TYPE_PSEUDO_OBJECT
The pseudo-object placeholder type.
Definition: ASTBitCodes.h:950
@ PREDEF_TYPE_OBJC_CLASS
The ObjC 'Class' type.
Definition: ASTBitCodes.h:926
@ PREDEF_TYPE_ULONG_ID
The 'unsigned long' type.
Definition: ASTBitCodes.h:866
@ PREDEF_TYPE_SAT_UACCUM_ID
The '_Sat unsigned _Accum' type.
Definition: ASTBitCodes.h:1031
@ PREDEF_TYPE_CLK_EVENT_ID
OpenCL clk event type.
Definition: ASTBitCodes.h:959
@ PREDEF_TYPE_EVENT_ID
OpenCL event type.
Definition: ASTBitCodes.h:956
@ PREDEF_TYPE_ULONG_ACCUM_ID
The 'unsigned long _Accum' type.
Definition: ASTBitCodes.h:998
@ PREDEF_TYPE_AUTO_DEDUCT
The "auto" deduction type.
Definition: ASTBitCodes.h:938
@ DECL_CXX_BASE_SPECIFIERS
A record containing CXXBaseSpecifiers.
Definition: ASTBitCodes.h:1395
@ DECL_CONTEXT_LEXICAL
A record that stores the set of declarations that are lexically stored within a given DeclContext.
Definition: ASTBitCodes.h:1275
@ DECL_CXX_CTOR_INITIALIZERS
A record containing CXXCtorInitializers.
Definition: ASTBitCodes.h:1398
@ DECL_CONTEXT_VISIBLE
A record that stores the set of declarations that are visible from a given DeclContext.
Definition: ASTBitCodes.h:1284
@ TYPE_EXT_QUAL
An ExtQualType record.
Definition: ASTBitCodes.h:1125
@ SPECIAL_TYPE_OBJC_SEL_REDEFINITION
Objective-C "SEL" redefinition type.
Definition: ASTBitCodes.h:1153
@ SPECIAL_TYPE_UCONTEXT_T
C ucontext_t typedef type.
Definition: ASTBitCodes.h:1156
@ SPECIAL_TYPE_JMP_BUF
C jmp_buf typedef type.
Definition: ASTBitCodes.h:1141
@ SPECIAL_TYPE_FILE
C FILE typedef type.
Definition: ASTBitCodes.h:1138
@ SPECIAL_TYPE_SIGJMP_BUF
C sigjmp_buf typedef type.
Definition: ASTBitCodes.h:1144
@ SPECIAL_TYPE_OBJC_CLASS_REDEFINITION
Objective-C "Class" redefinition type.
Definition: ASTBitCodes.h:1150
@ SPECIAL_TYPE_CF_CONSTANT_STRING
CFConstantString type.
Definition: ASTBitCodes.h:1135
@ SPECIAL_TYPE_OBJC_ID_REDEFINITION
Objective-C "id" redefinition type.
Definition: ASTBitCodes.h:1147
Defines the clang::TargetInfo interface.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Definition: SourceManager.h:81
bool isSystem(CharacteristicKind CK)
Determine whether a file / directory characteristic is for system code.
Definition: SourceManager.h:90
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
BlockID
The various types of blocks that can occur within a API notes file.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
Severity
Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs to either Ignore (nothing),...
Definition: DiagnosticIDs.h:85
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
static void hash_combine(std::size_t &seed, const T &v)
IncludeDirGroup
IncludeDirGroup - Identifies the group an include Entry belongs to, representing its relative positiv...
llvm::APFloat APFloat
Definition: Floating.h:23
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.h:218
llvm::OnDiskChainedHashTable< HeaderFileInfoTrait > HeaderFileInfoLookupTable
The on-disk hash table used for known header files.
llvm::OnDiskIterableChainedHashTable< ASTIdentifierLookupTrait > ASTIdentifierLookupTable
The on-disk hash table used to contain information about all of the identifiers in the program.
llvm::OnDiskChainedHashTable< ASTSelectorLookupTrait > ASTSelectorLookupTable
The on-disk hash table used for the global method pool.
@ EXTENSION_METADATA
Metadata describing this particular extension.
Definition: ASTBitCodes.h:402
uint32_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:81
@ SUBMODULE_EXCLUDED_HEADER
Specifies a header that has been explicitly excluded from this submodule.
Definition: ASTBitCodes.h:792
@ SUBMODULE_TOPHEADER
Specifies a top-level header that falls into this (sub)module.
Definition: ASTBitCodes.h:774
@ SUBMODULE_PRIVATE_TEXTUAL_HEADER
Specifies a header that is private to this submodule but must be textually included.
Definition: ASTBitCodes.h:812
@ SUBMODULE_HEADER
Specifies a header that falls into this (sub)module.
Definition: ASTBitCodes.h:771
@ SUBMODULE_EXPORT_AS
Specifies the name of the module that will eventually re-export the entities in this module.
Definition: ASTBitCodes.h:820
@ SUBMODULE_UMBRELLA_DIR
Specifies an umbrella directory.
Definition: ASTBitCodes.h:777
@ SUBMODULE_UMBRELLA_HEADER
Specifies the umbrella header used to create this module, if any.
Definition: ASTBitCodes.h:768
@ SUBMODULE_METADATA
Metadata for submodules as a whole.
Definition: ASTBitCodes.h:760
@ SUBMODULE_REQUIRES
Specifies a required feature.
Definition: ASTBitCodes.h:788
@ SUBMODULE_PRIVATE_HEADER
Specifies a header that is private to this submodule.
Definition: ASTBitCodes.h:804
@ SUBMODULE_IMPORTS
Specifies the submodules that are imported by this submodule.
Definition: ASTBitCodes.h:781
@ SUBMODULE_CONFLICT
Specifies a conflict with another module.
Definition: ASTBitCodes.h:801
@ SUBMODULE_INITIALIZERS
Specifies some declarations with initializers that must be emitted to initialize the module.
Definition: ASTBitCodes.h:816
@ SUBMODULE_DEFINITION
Defines the major attributes of a submodule, including its name and parent.
Definition: ASTBitCodes.h:764
@ SUBMODULE_LINK_LIBRARY
Specifies a library or framework to link against.
Definition: ASTBitCodes.h:795
@ SUBMODULE_CONFIG_MACRO
Specifies a configuration macro for this module.
Definition: ASTBitCodes.h:798
@ SUBMODULE_EXPORTS
Specifies the submodules that are re-exported from this submodule.
Definition: ASTBitCodes.h:785
@ SUBMODULE_TEXTUAL_HEADER
Specifies a header that is part of the module but must be textually included.
Definition: ASTBitCodes.h:808
@ SUBMODULE_AFFECTING_MODULES
Specifies affecting modules that were not imported.
Definition: ASTBitCodes.h:823
const unsigned int NUM_PREDEF_IDENT_IDS
The number of predefined identifier IDs.
Definition: ASTBitCodes.h:65
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
Definition: ASTBitCodes.h:161
OptionsRecordTypes
Record types that occur within the options block inside the control block.
Definition: ASTBitCodes.h:353
@ FILE_SYSTEM_OPTIONS
Record code for the filesystem options table.
Definition: ASTBitCodes.h:366
@ TARGET_OPTIONS
Record code for the target options table.
Definition: ASTBitCodes.h:363
@ PREPROCESSOR_OPTIONS
Record code for the preprocessor options table.
Definition: ASTBitCodes.h:372
@ HEADER_SEARCH_OPTIONS
Record code for the headers search options table.
Definition: ASTBitCodes.h:369
@ LANGUAGE_OPTIONS
Record code for the language options table.
Definition: ASTBitCodes.h:360
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
Definition: ASTBitCodes.h:143
const unsigned int NUM_PREDEF_PP_ENTITY_IDS
The number of predefined preprocessed entity IDs.
Definition: ASTBitCodes.h:259
uint32_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
Definition: ASTBitCodes.h:158
const unsigned int NUM_PREDEF_SUBMODULE_IDS
The number of predefined submodule IDs.
Definition: ASTBitCodes.h:164
@ SUBMODULE_BLOCK_ID
The block containing the submodule structure.
Definition: ASTBitCodes.h:284
@ PREPROCESSOR_DETAIL_BLOCK_ID
The block containing the detailed preprocessing record.
Definition: ASTBitCodes.h:281
@ AST_BLOCK_ID
The AST block, which acts as a container around the full AST block.
Definition: ASTBitCodes.h:266
@ SOURCE_MANAGER_BLOCK_ID
The block containing information about the source manager.
Definition: ASTBitCodes.h:270
@ CONTROL_BLOCK_ID
The control block, which contains all of the information that needs to be validated prior to committi...
Definition: ASTBitCodes.h:292
@ DECLTYPES_BLOCK_ID
The block containing the definitions of all of the types and decls used within the AST file.
Definition: ASTBitCodes.h:278
@ PREPROCESSOR_BLOCK_ID
The block containing information about the preprocessor.
Definition: ASTBitCodes.h:274
@ COMMENTS_BLOCK_ID
The block containing comments.
Definition: ASTBitCodes.h:287
@ UNHASHED_CONTROL_BLOCK_ID
A block with unhashed content.
Definition: ASTBitCodes.h:314
@ EXTENSION_BLOCK_ID
A block containing a module file extension.
Definition: ASTBitCodes.h:308
@ OPTIONS_BLOCK_ID
The block of configuration options, used to check that a module is being used in a configuration comp...
Definition: ASTBitCodes.h:305
@ INPUT_FILES_BLOCK_ID
The block of input files, which were used as inputs to create this AST file.
Definition: ASTBitCodes.h:298
CommentRecordTypes
Record types used within a comments block.
Definition: ASTBitCodes.h:827
@ SM_SLOC_FILE_ENTRY
Describes a source location entry (SLocEntry) for a file.
Definition: ASTBitCodes.h:697
@ SM_SLOC_BUFFER_BLOB_COMPRESSED
Describes a zlib-compressed blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:711
@ SM_SLOC_BUFFER_ENTRY
Describes a source location entry (SLocEntry) for a buffer.
Definition: ASTBitCodes.h:701
@ SM_SLOC_BUFFER_BLOB
Describes a blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:707
@ SM_SLOC_EXPANSION_ENTRY
Describes a source location entry (SLocEntry) for a macro expansion.
Definition: ASTBitCodes.h:715
const unsigned int NUM_PREDEF_SELECTOR_IDS
The number of predefined selector IDs.
Definition: ASTBitCodes.h:146
bool needsAnonymousDeclarationNumber(const NamedDecl *D)
Determine whether the given declaration needs an anonymous declaration number.
Definition: ASTCommon.cpp:466
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition: ASTBitCodes.h:46
DeclIDBase::DeclID DeclID
An ID number that refers to a declaration in an AST file.
Definition: ASTBitCodes.h:69
PreprocessorRecordTypes
Record types used within a preprocessor block.
Definition: ASTBitCodes.h:719
@ PP_TOKEN
Describes one token.
Definition: ASTBitCodes.h:734
@ PP_MACRO_FUNCTION_LIKE
A function-like macro definition.
Definition: ASTBitCodes.h:730
@ PP_MACRO_OBJECT_LIKE
An object-like macro definition.
Definition: ASTBitCodes.h:725
@ PP_MACRO_DIRECTIVE_HISTORY
The macro directives history for a particular identifier.
Definition: ASTBitCodes.h:737
@ PP_MODULE_MACRO
A macro directive exported by a module.
Definition: ASTBitCodes.h:741
ControlRecordTypes
Record types that occur within the control block.
Definition: ASTBitCodes.h:318
@ MODULE_MAP_FILE
Record code for the module map file that was used to build this AST file.
Definition: ASTBitCodes.h:345
@ MODULE_DIRECTORY
Record code for the module build directory.
Definition: ASTBitCodes.h:348
@ IMPORTS
Record code for the list of other AST files imported by this AST file.
Definition: ASTBitCodes.h:325
@ ORIGINAL_FILE_ID
Record code for file ID of the file or buffer that was used to generate the AST file.
Definition: ASTBitCodes.h:334
@ MODULE_NAME
Record code for the module name.
Definition: ASTBitCodes.h:341
@ ORIGINAL_FILE
Record code for the original file that was used to generate the AST file, including both its file ID ...
Definition: ASTBitCodes.h:330
@ INPUT_FILE_OFFSETS
Offsets into the input-files block where input files reside.
Definition: ASTBitCodes.h:338
@ METADATA
AST file metadata, including the AST file version number and information about the compiler used to b...
Definition: ASTBitCodes.h:321
UnhashedControlBlockRecordTypes
Record codes for the unhashed control block.
Definition: ASTBitCodes.h:376
@ DIAGNOSTIC_OPTIONS
Record code for the diagnostic options table.
Definition: ASTBitCodes.h:384
@ HEADER_SEARCH_ENTRY_USAGE
Record code for the indices of used header search entries.
Definition: ASTBitCodes.h:393
@ AST_BLOCK_HASH
Record code for the content hash of the AST block.
Definition: ASTBitCodes.h:381
@ DIAG_PRAGMA_MAPPINGS
Record code for #pragma diagnostic mappings.
Definition: ASTBitCodes.h:390
@ SIGNATURE
Record code for the signature that identifiers this AST file.
Definition: ASTBitCodes.h:378
@ HEADER_SEARCH_PATHS
Record code for the headers search paths.
Definition: ASTBitCodes.h:387
@ VFS_USAGE
Record code for the indices of used VFSs.
Definition: ASTBitCodes.h:396
InputFileRecordTypes
Record types that occur within the input-files block inside the control block.
Definition: ASTBitCodes.h:410
@ INPUT_FILE_HASH
The input file content hash.
Definition: ASTBitCodes.h:415
@ INPUT_FILE
An input file.
Definition: ASTBitCodes.h:412
PreprocessorDetailRecordTypes
Record types used within a preprocessor detail block.
Definition: ASTBitCodes.h:745
@ PPD_INCLUSION_DIRECTIVE
Describes an inclusion directive within the preprocessing record.
Definition: ASTBitCodes.h:754
@ PPD_MACRO_EXPANSION
Describes a macro expansion within the preprocessing record.
Definition: ASTBitCodes.h:747
@ PPD_MACRO_DEFINITION
Describes a macro definition within the preprocessing record.
Definition: ASTBitCodes.h:750
ModuleKind
Specifies the kind of module that has been loaded.
Definition: ModuleFile.h:42
@ MK_PCH
File is a PCH file treated as such.
Definition: ModuleFile.h:50
@ MK_Preamble
File is a PCH file treated as the preamble.
Definition: ModuleFile.h:53
@ MK_MainFile
File is a PCH file treated as the actual main file.
Definition: ModuleFile.h:56
@ MK_ExplicitModule
File is an explicitly-loaded module.
Definition: ModuleFile.h:47
@ MK_ImplicitModule
File is an implicitly-loaded module.
Definition: ModuleFile.h:44
@ MK_PrebuiltModule
File is from a prebuilt module path.
Definition: ModuleFile.h:59
const unsigned int NUM_PREDEF_MACRO_IDS
The number of predefined macro IDs.
Definition: ASTBitCodes.h:140
ASTRecordTypes
Record types that occur within the AST block itself.
Definition: ASTBitCodes.h:419
@ DECL_UPDATE_OFFSETS
Record for offsets of DECL_UPDATES records for declarations that were modified after being deserializ...
Definition: ASTBitCodes.h:560
@ STATISTICS
Record code for the extra statistics we gather while generating an AST file.
Definition: ASTBitCodes.h:494
@ FLOAT_CONTROL_PRAGMA_OPTIONS
Record code for #pragma float_control options.
Definition: ASTBitCodes.h:680
@ KNOWN_NAMESPACES
Record code for the set of known namespaces, which are used for typo correction.
Definition: ASTBitCodes.h:586
@ SPECIAL_TYPES
Record code for the set of non-builtin, special types.
Definition: ASTBitCodes.h:490
@ PENDING_IMPLICIT_INSTANTIATIONS
Record code for pending implicit instantiations.
Definition: ASTBitCodes.h:549
@ TYPE_OFFSET
Record code for the offsets of each type.
Definition: ASTBitCodes.h:432
@ DELEGATING_CTORS
The list of delegating constructor declarations.
Definition: ASTBitCodes.h:582
@ PP_ASSUME_NONNULL_LOC
ID 66 used to be the list of included files.
Definition: ASTBitCodes.h:686
@ EXT_VECTOR_DECLS
Record code for the set of ext_vector type names.
Definition: ASTBitCodes.h:519
@ OPENCL_EXTENSIONS
Record code for enabled OpenCL extensions.
Definition: ASTBitCodes.h:579
@ FP_PRAGMA_OPTIONS
Record code for floating point #pragma options.
Definition: ASTBitCodes.h:576
@ VTABLE_USES
Record code for the array of VTable uses.
Definition: ASTBitCodes.h:529
@ LATE_PARSED_TEMPLATE
Record code for late parsed template functions.
Definition: ASTBitCodes.h:636
@ DECLS_TO_CHECK_FOR_DEFERRED_DIAGS
Record code for the Decls to be checked for deferred diags.
Definition: ASTBitCodes.h:677
@ DECL_OFFSET
Record code for the offsets of each decl.
Definition: ASTBitCodes.h:444
@ SOURCE_MANAGER_LINE_TABLE
Record code for the source manager line table information, which stores information about #line direc...
Definition: ASTBitCodes.h:596
@ PP_COUNTER_VALUE
The value of the next COUNTER to dispense.
Definition: ASTBitCodes.h:510
@ DELETE_EXPRS_TO_ANALYZE
Delete expressions that will be analyzed later.
Definition: ASTBitCodes.h:647
@ UPDATE_VISIBLE
Record code for an update to a decl context's lookup table.
Definition: ASTBitCodes.h:556
@ CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH
Number of unmatched #pragma clang cuda_force_host_device begin directives we've seen.
Definition: ASTBitCodes.h:657
@ MACRO_OFFSET
Record code for the table of offsets of each macro ID.
Definition: ASTBitCodes.h:624
@ PPD_ENTITIES_OFFSETS
Record code for the table of offsets to entries in the preprocessing record.
Definition: ASTBitCodes.h:526
@ IDENTIFIER_OFFSET
Record code for the table of offsets of each identifier ID.
Definition: ASTBitCodes.h:452
@ OBJC_CATEGORIES
Record code for the array of Objective-C categories (including extensions).
Definition: ASTBitCodes.h:617
@ METHOD_POOL
Record code for the Objective-C method pool,.
Definition: ASTBitCodes.h:506
@ DELAYED_NAMESPACE_LEXICAL_VISIBLE_RECORD
Record code for lexical and visible block for delayed namespace in reduced BMI.
Definition: ASTBitCodes.h:690
@ PP_CONDITIONAL_STACK
The stack of open #ifs/#ifdefs recorded in a preamble.
Definition: ASTBitCodes.h:671
@ REFERENCED_SELECTOR_POOL
Record code for referenced selector pool.
Definition: ASTBitCodes.h:534
@ SOURCE_LOCATION_OFFSETS
Record code for the table of offsets into the block of source-location information.
Definition: ASTBitCodes.h:514
@ WEAK_UNDECLARED_IDENTIFIERS
Record code for weak undeclared identifiers.
Definition: ASTBitCodes.h:546
@ UNDEFINED_BUT_USED
Record code for undefined but used functions and variables that need a definition in this TU.
Definition: ASTBitCodes.h:633
@ FILE_SORTED_DECLS
Record code for a file sorted array of DeclIDs in a module.
Definition: ASTBitCodes.h:603
@ MSSTRUCT_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:650
@ TENTATIVE_DEFINITIONS
Record code for the array of tentative definitions.
Definition: ASTBitCodes.h:497
@ UNUSED_FILESCOPED_DECLS
Record code for the array of unused file scoped decls.
Definition: ASTBitCodes.h:522
@ ALIGN_PACK_PRAGMA_OPTIONS
Record code for #pragma align/pack options.
Definition: ASTBitCodes.h:668
@ IMPORTED_MODULES
Record code for an array of all of the (sub)modules that were imported by the AST file.
Definition: ASTBitCodes.h:607
@ SELECTOR_OFFSETS
Record code for the table of offsets into the Objective-C method pool.
Definition: ASTBitCodes.h:503
@ UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES
Record code for potentially unused local typedef names.
Definition: ASTBitCodes.h:642
@ EAGERLY_DESERIALIZED_DECLS
Record code for the array of eagerly deserialized decls.
Definition: ASTBitCodes.h:481
@ INTERESTING_IDENTIFIERS
A list of "interesting" identifiers.
Definition: ASTBitCodes.h:629
@ HEADER_SEARCH_TABLE
Record code for header search information.
Definition: ASTBitCodes.h:573
@ OBJC_CATEGORIES_MAP
Record code for map of Objective-C class definition IDs to the ObjC categories in a module that are a...
Definition: ASTBitCodes.h:600
@ CUDA_SPECIAL_DECL_REFS
Record code for special CUDA declarations.
Definition: ASTBitCodes.h:570
@ TU_UPDATE_LEXICAL
Record code for an update to the TU's lexically contained declarations.
Definition: ASTBitCodes.h:538
@ PPD_SKIPPED_RANGES
A table of skipped ranges within the preprocessing record.
Definition: ASTBitCodes.h:674
@ IDENTIFIER_TABLE
Record code for the identifier table.
Definition: ASTBitCodes.h:471
@ SEMA_DECL_REFS
Record code for declarations that Sema keeps references of.
Definition: ASTBitCodes.h:543
@ OPTIMIZE_PRAGMA_OPTIONS
Record code for #pragma optimize options.
Definition: ASTBitCodes.h:639
@ MODULE_OFFSET_MAP
Record code for the remapping information used to relate loaded modules to the various offsets and ID...
Definition: ASTBitCodes.h:592
@ POINTERS_TO_MEMBERS_PRAGMA_OPTIONS
Record code for #pragma ms_struct options.
Definition: ASTBitCodes.h:653
uint32_t MacroID
An ID number that refers to a macro in an AST file.
Definition: ASTBitCodes.h:130
uint32_t IdentifierID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:62
unsigned ComputeHash(Selector Sel)
Definition: ASTCommon.cpp:291
std::string toString(const til::SExpr *E)
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
OpenACCClauseKind
Represents the kind of an OpenACC clause.
Definition: OpenACCKinds.h:164
@ Auto
'auto' clause, allowed on 'loop' directives.
@ Bind
'bind' clause, allowed on routine constructs.
@ Gang
'gang' clause, allowed on 'loop' and Combined constructs.
@ Wait
'wait' clause, allowed on Compute, Data, 'update', and Combined constructs.
@ DevicePtr
'deviceptr' clause, allowed on Compute and Combined Constructs, plus 'data' and 'declare'.
@ PCopyOut
'copyout' clause alias 'pcopyout'. Preserved for diagnostic purposes.
@ VectorLength
'vector_length' clause, allowed on 'parallel', 'kernels', 'parallel loop', and 'kernels loop' constru...
@ Async
'async' clause, allowed on Compute, Data, 'update', 'wait', and Combined constructs.
@ PresentOrCreate
'create' clause alias 'present_or_create'.
@ Collapse
'collapse' clause, allowed on 'loop' and Combined constructs.
@ NoHost
'nohost' clause, allowed on 'routine' directives.
@ PresentOrCopy
'copy' clause alias 'present_or_copy'. Preserved for diagnostic purposes.
@ DeviceNum
'device_num' clause, allowed on 'init', 'shutdown', and 'set' constructs.
@ Private
'private' clause, allowed on 'parallel', 'serial', 'loop', 'parallel loop', and 'serial loop' constru...
@ Invalid
Represents an invalid clause, for the purposes of parsing.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Copy
'copy' clause, allowed on Compute and Combined Constructs, plus 'data' and 'declare'.
@ Worker
'worker' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Create
'create' clause, allowed on Compute and Combined constructs, plus 'data', 'enter data',...
@ DeviceType
'device_type' clause, allowed on Compute, 'data', 'init', 'shutdown', 'set', update',...
@ DefaultAsync
'default_async' clause, allowed on 'set' construct.
@ Attach
'attach' clause, allowed on Compute and Combined constructs, plus 'data' and 'enter data'.
@ NumGangs
'num_gangs' clause, allowed on 'parallel', 'kernels', parallel loop', and 'kernels loop' constructs.
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
@ Default
'default' clause, allowed on parallel, serial, kernel (and compound) constructs.
@ UseDevice
'use_device' clause, allowed on 'host_data' construct.
@ NoCreate
'no_create' clause, allowed on allowed on Compute and Combined constructs, plus 'data'.
@ PresentOrCopyOut
'copyout' clause alias 'present_or_copyout'.
@ Link
'link' clause, allowed on 'declare' construct.
@ Reduction
'reduction' clause, allowed on Parallel, Serial, Loop, and the combined constructs.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ CopyOut
'copyout' clause, allowed on Compute and Combined constructs, plus 'data', 'exit data',...
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ FirstPrivate
'firstprivate' clause, allowed on 'parallel', 'serial', 'parallel loop', and 'serial loop' constructs...
@ Host
'host' clause, allowed on 'update' construct.
@ PCopy
'copy' clause alias 'pcopy'. Preserved for diagnostic purposes.
@ Tile
'tile' clause, allowed on 'loop' and Combined constructs.
@ PCopyIn
'copyin' clause alias 'pcopyin'. Preserved for diagnostic purposes.
@ DeviceResident
'device_resident' clause, allowed on the 'declare' construct.
@ PCreate
'create' clause alias 'pcreate'. Preserved for diagnostic purposes.
@ Present
'present' clause, allowed on Compute and Combined constructs, plus 'data' and 'declare'.
@ DType
'dtype' clause, an alias for 'device_type', stored separately for diagnostic purposes.
@ CopyIn
'copyin' clause, allowed on Compute and Combined constructs, plus 'data', 'enter data',...
@ Device
'device' clause, allowed on the 'update' construct.
@ Independent
'independent' clause, allowed on 'loop' directives.
@ NumWorkers
'num_workers' clause, allowed on 'parallel', 'kernels', parallel loop', and 'kernels loop' constructs...
@ IfPresent
'if_present' clause, allowed on 'host_data' and 'update' directives.
@ Detach
'detach' clause, allowed on the 'exit data' construct.
@ Delete
'delete' clause, allowed on the 'exit data' construct.
@ PresentOrCopyIn
'copyin' clause alias 'present_or_copyin'.
@ Finalize
'finalize' clause, allowed on 'exit data' directive.
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
SanitizerMask getPPTransparentSanitizers()
Return the sanitizers which do not affect preprocessing.
Definition: Sanitizers.h:198
@ CPlusPlus
Definition: LangStandard.h:55
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
llvm::omp::Directive OpenMPDirectiveKind
OpenMP directives.
Definition: OpenMPKinds.h:24
OpenMPDefaultmapClauseModifier
OpenMP modifiers for 'defaultmap' clause.
Definition: OpenMPKinds.h:118
OpenMPOrderClauseModifier
OpenMP modifiers for 'order' clause.
Definition: OpenMPKinds.h:171
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, bool ReportDiags=true)
ProcessWarningOptions - Initialize the diagnostic client and process the warning options specified on...
Definition: Warnings.cpp:44
OpenMPAtClauseKind
OpenMP attributes for 'at' clause.
Definition: OpenMPKinds.h:135
OpenMPReductionClauseModifier
OpenMP modifiers for 'reduction' clause.
Definition: OpenMPKinds.h:186
OpenMPScheduleClauseModifier
OpenMP modifiers for 'schedule' clause.
Definition: OpenMPKinds.h:38
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition: OpenMPKinds.h:27
OpenMPDistScheduleClauseKind
OpenMP attributes for 'dist_schedule' clause.
Definition: OpenMPKinds.h:103
OpenMPDoacrossClauseModifier
OpenMP dependence types for 'doacross' clause.
Definition: OpenMPKinds.h:219
static constexpr unsigned NumberOfOMPMapClauseModifiers
Number of allowed map-type-modifiers.
Definition: OpenMPKinds.h:87
const unsigned int NUM_PREDEF_DECL_IDS
The number of declaration IDs that are predefined.
Definition: DeclID.h:90
ObjCXXARCStandardLibraryKind
Enumerate the kinds of standard library that.
PredefinedDeclIDs
Predefined declaration IDs.
Definition: DeclID.h:30
@ PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID
The internal '__NSConstantString' tag type.
Definition: DeclID.h:80
@ PREDEF_DECL_TRANSLATION_UNIT_ID
The translation unit.
Definition: DeclID.h:35
@ PREDEF_DECL_TYPE_PACK_ELEMENT_ID
The internal '__type_pack_element' template.
Definition: DeclID.h:83
@ PREDEF_DECL_OBJC_CLASS_ID
The Objective-C 'Class' type.
Definition: DeclID.h:44
@ PREDEF_DECL_BUILTIN_MS_GUID_ID
The predeclared '_GUID' struct.
Definition: DeclID.h:68
@ PREDEF_DECL_OBJC_INSTANCETYPE_ID
The internal 'instancetype' typedef.
Definition: DeclID.h:56
@ PREDEF_DECL_OBJC_PROTOCOL_ID
The Objective-C 'Protocol' type.
Definition: DeclID.h:47
@ PREDEF_DECL_UNSIGNED_INT_128_ID
The unsigned 128-bit integer type.
Definition: DeclID.h:53
@ PREDEF_DECL_OBJC_SEL_ID
The Objective-C 'SEL' type.
Definition: DeclID.h:41
@ PREDEF_DECL_INT_128_ID
The signed 128-bit integer type.
Definition: DeclID.h:50
@ PREDEF_DECL_VA_LIST_TAG
The internal '__va_list_tag' struct, if any.
Definition: DeclID.h:62
@ PREDEF_DECL_BUILTIN_MS_VA_LIST_ID
The internal '__builtin_ms_va_list' typedef.
Definition: DeclID.h:65
@ PREDEF_DECL_CF_CONSTANT_STRING_ID
The internal '__NSConstantString' typedef.
Definition: DeclID.h:77
@ PREDEF_DECL_NULL_ID
The NULL declaration.
Definition: DeclID.h:32
@ PREDEF_DECL_BUILTIN_VA_LIST_ID
The internal '__builtin_va_list' typedef.
Definition: DeclID.h:59
@ PREDEF_DECL_EXTERN_C_CONTEXT_ID
The extern "C" context.
Definition: DeclID.h:71
@ PREDEF_DECL_OBJC_ID_ID
The Objective-C 'id' type.
Definition: DeclID.h:38
@ PREDEF_DECL_MAKE_INTEGER_SEQ_ID
The internal '__make_integer_seq' template.
Definition: DeclID.h:74
@ Property
The type of a property.
OpenMPBindClauseKind
OpenMP bindings for the 'bind' clause.
Definition: OpenMPKinds.h:200
OpenACCDefaultClauseKind
Definition: OpenACCKinds.h:462
OpenMPLastprivateModifier
OpenMP 'lastprivate' clause modifier.
Definition: OpenMPKinds.h:157
OpenMPDependClauseKind
OpenMP attributes for 'depend' clause.
Definition: OpenMPKinds.h:54
OpenMPGrainsizeClauseModifier
Definition: OpenMPKinds.h:206
OpenMPNumTasksClauseModifier
Definition: OpenMPKinds.h:212
OpenMPSeverityClauseKind
OpenMP attributes for 'severity' clause.
Definition: OpenMPKinds.h:142
static constexpr unsigned NumberOfOMPMotionModifiers
Number of allowed motion-modifiers.
Definition: OpenMPKinds.h:99
TypeSpecifierWidth
Specifies the width of a type, e.g., short, long, or long long.
Definition: Specifiers.h:47
OpenMPMotionModifierKind
OpenMP modifier kind for 'to' or 'from' clause.
Definition: OpenMPKinds.h:91
PragmaMSStructKind
Definition: PragmaKinds.h:23
OpenMPDefaultmapClauseKind
OpenMP attributes for 'defaultmap' clause.
Definition: OpenMPKinds.h:110
OpenMPLinearClauseKind
OpenMP attributes for 'linear' clause.
Definition: OpenMPKinds.h:62
TypeSpecifierSign
Specifies the signedness of a type, e.g., signed or unsigned.
Definition: Specifiers.h:50
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
const FunctionProtoType * T
OpenACCReductionOperator
Definition: OpenACCKinds.h:495
DisableValidationForModuleKind
Whether to disable the normal validation performed on precompiled headers and module files when they ...
@ None
Perform validation, don't disable it.
@ PCH
Disable validation for a precompiled header and the modules it depends on.
@ Module
Disable validation for module files.
bool shouldSkipCheckingODR(const Decl *D)
Definition: ASTReader.h:2481
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:68
OpenMPAtomicDefaultMemOrderClauseKind
OpenMP attributes for 'atomic_default_mem_order' clause.
Definition: OpenMPKinds.h:127
U cast(CodeGen::Address addr)
Definition: Address.h:291
OpenMPDeviceClauseModifier
OpenMP modifiers for 'device' clause.
Definition: OpenMPKinds.h:47
OpenMPMapModifierKind
OpenMP modifier kind for 'map' clause.
Definition: OpenMPKinds.h:78
OpenMPOrderClauseKind
OpenMP attributes for 'order' clause.
Definition: OpenMPKinds.h:164
OpenMPScheduleClauseKind
OpenMP attributes for 'schedule' clause.
Definition: OpenMPKinds.h:30
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:120
OpenMPMapClauseKind
OpenMP mapping kind for 'map' clause.
Definition: OpenMPKinds.h:70
unsigned long uint64_t
Definition: Format.h:5433
float __ovld __cnfn distance(float, float)
Returns the distance between p0 and p1.
#define true
Definition: stdbool.h:25
#define bool
Definition: stdbool.h:24
The signature of a module, which is a hash of the AST content.
Definition: Module.h:57
static constexpr size_t size
Definition: Module.h:60
static ASTFileSignature create(std::array< uint8_t, 20 > Bytes)
Definition: Module.h:75
static ASTFileSignature createDummy()
Definition: Module.h:85
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
bool ParseAllComments
Treat ordinary comments as documentation comments.
BlockCommandNamesTy BlockCommandNames
Command names to treat as block commands in comments.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setInfo(const DeclarationNameLoc &Info)
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
A simple structure that captures a vtable use for the purposes of the ExternalSemaSource.
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4754
The preprocessor keeps track of this information for each file that is #included.
Definition: HeaderSearch.h:58
void mergeModuleMembership(ModuleMap::ModuleHeaderRole Role)
Update the module membership bits based on the header role.
unsigned IndexHeaderMapHeader
Whether this is a header inside a framework that is currently being built.
Definition: HeaderSearch.h:116
unsigned DirInfo
Keep track of whether this is a system header, and if so, whether it is C++ clean or not.
Definition: HeaderSearch.h:80
unsigned isPragmaOnce
True if this is a #pragma once file.
Definition: HeaderSearch.h:73
unsigned IsValid
Whether this file has been looked up as a header.
Definition: HeaderSearch.h:120
unsigned isImport
True if this is a #import'd file.
Definition: HeaderSearch.h:69
StringRef Framework
If this header came from a framework include, this is the name of the framework.
Definition: HeaderSearch.h:141
unsigned ControllingMacroID
The ID number of the controlling macro.
Definition: HeaderSearch.h:127
unsigned External
Whether this header file info was supplied by an external source, and has not changed since.
Definition: HeaderSearch.h:85
static LineEntry get(unsigned Offs, unsigned Line, int Filename, SrcMgr::CharacteristicKind FileKind, unsigned IncludeOffset)
Metadata for a module file extension.
unsigned MajorVersion
The major version of the extension data.
std::string UserInfo
A string containing additional user information that will be stored with the metadata.
std::string BlockName
The name used to identify this particular extension block within the resulting module file.
unsigned MinorVersion
The minor version of the extension data.
A conflict between two modules.
Definition: Module.h:488
Module * Other
The module that this module conflicts with.
Definition: Module.h:490
std::string Message
The message provided to the user when there is a conflict.
Definition: Module.h:493
Information about a header directive as found in the module map file.
Definition: Module.h:250
This structure contains all sizes needed for by an OMPMappableExprListClause.
unsigned NumComponentLists
Number of component lists.
unsigned NumVars
Number of expressions listed.
unsigned NumUniqueDeclarations
Number of unique base declarations.
unsigned NumComponents
Total number of expression components.
Data for list of allocators.
SourceLocation LParenLoc
Locations of '(' and ')' symbols.
Expr * AllocatorTraits
Allocator traits.
a linked list of methods with the same selector name but different signatures.
A struct with extended info about a syntactic name qualifier, to be used for the case of out-of-line ...
Definition: Decl.h:744
TemplateParameterList ** TemplParamLists
A new-allocated array of size NumTemplParamLists, containing pointers to the "outer" template paramet...
Definition: Decl.h:758
NestedNameSpecifierLoc QualifierLoc
Definition: Decl.h:745
unsigned NumTemplParamLists
The number of "outer" template parameter lists.
Definition: Decl.h:751
void clear(SanitizerMask K=SanitizerKind::All)
Disable the sanitizers specified in K.
Definition: Sanitizers.h:176
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition: Sanitizers.h:182
Helper class that saves the current stream position and then restores it when destroyed.
PragmaMsStackAction Action
Definition: Sema.h:1232
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
The input file info that has been loaded from an AST file.
Definition: ModuleFile.h:63
Describes the categories of an Objective-C class.
Definition: ASTBitCodes.h:1992