clang  3.7.0
ASTReader.cpp
Go to the documentation of this file.
1 //===-- ASTReader.cpp - AST File Reader ----------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ASTReader class, which reads AST files.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "ASTCommon.h"
16 #include "ASTReaderInternals.h"
17 #include "clang/AST/ASTConsumer.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/Type.h"
30 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Basic/Version.h"
34 #include "clang/Frontend/Utils.h"
35 #include "clang/Lex/HeaderSearch.h"
37 #include "clang/Lex/MacroInfo.h"
39 #include "clang/Lex/Preprocessor.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/Sema.h"
47 #include "llvm/ADT/Hashing.h"
48 #include "llvm/ADT/StringExtras.h"
49 #include "llvm/Bitcode/BitstreamReader.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/FileSystem.h"
52 #include "llvm/Support/MemoryBuffer.h"
53 #include "llvm/Support/Path.h"
54 #include "llvm/Support/SaveAndRestore.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include <algorithm>
57 #include <cstdio>
58 #include <iterator>
59 #include <system_error>
60 
61 using namespace clang;
62 using namespace clang::serialization;
63 using namespace clang::serialization::reader;
64 using llvm::BitstreamCursor;
65 
66 
67 //===----------------------------------------------------------------------===//
68 // ChainedASTReaderListener implementation
69 //===----------------------------------------------------------------------===//
70 
71 bool
73  return First->ReadFullVersionInformation(FullVersion) ||
74  Second->ReadFullVersionInformation(FullVersion);
75 }
76 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
77  First->ReadModuleName(ModuleName);
78  Second->ReadModuleName(ModuleName);
79 }
80 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
81  First->ReadModuleMapFile(ModuleMapPath);
82  Second->ReadModuleMapFile(ModuleMapPath);
83 }
84 bool
86  bool Complain,
87  bool AllowCompatibleDifferences) {
88  return First->ReadLanguageOptions(LangOpts, Complain,
89  AllowCompatibleDifferences) ||
90  Second->ReadLanguageOptions(LangOpts, Complain,
91  AllowCompatibleDifferences);
92 }
94  const TargetOptions &TargetOpts, bool Complain,
95  bool AllowCompatibleDifferences) {
96  return First->ReadTargetOptions(TargetOpts, Complain,
97  AllowCompatibleDifferences) ||
98  Second->ReadTargetOptions(TargetOpts, Complain,
99  AllowCompatibleDifferences);
100 }
102  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
103  return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
104  Second->ReadDiagnosticOptions(DiagOpts, Complain);
105 }
106 bool
108  bool Complain) {
109  return First->ReadFileSystemOptions(FSOpts, Complain) ||
110  Second->ReadFileSystemOptions(FSOpts, Complain);
111 }
112 
114  const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
115  bool Complain) {
116  return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
117  Complain) ||
118  Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
119  Complain);
120 }
122  const PreprocessorOptions &PPOpts, bool Complain,
123  std::string &SuggestedPredefines) {
124  return First->ReadPreprocessorOptions(PPOpts, Complain,
125  SuggestedPredefines) ||
126  Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
127 }
129  unsigned Value) {
130  First->ReadCounter(M, Value);
131  Second->ReadCounter(M, Value);
132 }
134  return First->needsInputFileVisitation() ||
135  Second->needsInputFileVisitation();
136 }
138  return First->needsSystemInputFileVisitation() ||
139  Second->needsSystemInputFileVisitation();
140 }
142  First->visitModuleFile(Filename);
143  Second->visitModuleFile(Filename);
144 }
146  bool isSystem,
147  bool isOverridden) {
148  bool Continue = false;
149  if (First->needsInputFileVisitation() &&
150  (!isSystem || First->needsSystemInputFileVisitation()))
151  Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
152  if (Second->needsInputFileVisitation() &&
153  (!isSystem || Second->needsSystemInputFileVisitation()))
154  Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
155  return Continue;
156 }
157 
158 //===----------------------------------------------------------------------===//
159 // PCH validator implementation
160 //===----------------------------------------------------------------------===//
161 
163 
164 /// \brief Compare the given set of language options against an existing set of
165 /// language options.
166 ///
167 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
168 /// \param AllowCompatibleDifferences If true, differences between compatible
169 /// language options will be permitted.
170 ///
171 /// \returns true if the languagae options mis-match, false otherwise.
172 static bool checkLanguageOptions(const LangOptions &LangOpts,
173  const LangOptions &ExistingLangOpts,
174  DiagnosticsEngine *Diags,
175  bool AllowCompatibleDifferences = true) {
176 #define LANGOPT(Name, Bits, Default, Description) \
177  if (ExistingLangOpts.Name != LangOpts.Name) { \
178  if (Diags) \
179  Diags->Report(diag::err_pch_langopt_mismatch) \
180  << Description << LangOpts.Name << ExistingLangOpts.Name; \
181  return true; \
182  }
183 
184 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
185  if (ExistingLangOpts.Name != LangOpts.Name) { \
186  if (Diags) \
187  Diags->Report(diag::err_pch_langopt_value_mismatch) \
188  << Description; \
189  return true; \
190  }
191 
192 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
193  if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
194  if (Diags) \
195  Diags->Report(diag::err_pch_langopt_value_mismatch) \
196  << Description; \
197  return true; \
198  }
199 
200 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
201  if (!AllowCompatibleDifferences) \
202  LANGOPT(Name, Bits, Default, Description)
203 
204 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
205  if (!AllowCompatibleDifferences) \
206  ENUM_LANGOPT(Name, Bits, Default, Description)
207 
208 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
209 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
210 #include "clang/Basic/LangOptions.def"
211 
212  if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
213  if (Diags)
214  Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
215  return true;
216  }
217 
218  if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
219  if (Diags)
220  Diags->Report(diag::err_pch_langopt_value_mismatch)
221  << "target Objective-C runtime";
222  return true;
223  }
224 
225  if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
226  LangOpts.CommentOpts.BlockCommandNames) {
227  if (Diags)
228  Diags->Report(diag::err_pch_langopt_value_mismatch)
229  << "block command names";
230  return true;
231  }
232 
233  return false;
234 }
235 
236 /// \brief Compare the given set of target options against an existing set of
237 /// target options.
238 ///
239 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
240 ///
241 /// \returns true if the target options mis-match, false otherwise.
242 static bool checkTargetOptions(const TargetOptions &TargetOpts,
243  const TargetOptions &ExistingTargetOpts,
244  DiagnosticsEngine *Diags,
245  bool AllowCompatibleDifferences = true) {
246 #define CHECK_TARGET_OPT(Field, Name) \
247  if (TargetOpts.Field != ExistingTargetOpts.Field) { \
248  if (Diags) \
249  Diags->Report(diag::err_pch_targetopt_mismatch) \
250  << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
251  return true; \
252  }
253 
254  // The triple and ABI must match exactly.
255  CHECK_TARGET_OPT(Triple, "target");
256  CHECK_TARGET_OPT(ABI, "target ABI");
257 
258  // We can tolerate different CPUs in many cases, notably when one CPU
259  // supports a strict superset of another. When allowing compatible
260  // differences skip this check.
261  if (!AllowCompatibleDifferences)
262  CHECK_TARGET_OPT(CPU, "target CPU");
263 
264 #undef CHECK_TARGET_OPT
265 
266  // Compare feature sets.
267  SmallVector<StringRef, 4> ExistingFeatures(
268  ExistingTargetOpts.FeaturesAsWritten.begin(),
269  ExistingTargetOpts.FeaturesAsWritten.end());
270  SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
271  TargetOpts.FeaturesAsWritten.end());
272  std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
273  std::sort(ReadFeatures.begin(), ReadFeatures.end());
274 
275  // We compute the set difference in both directions explicitly so that we can
276  // diagnose the differences differently.
277  SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
278  std::set_difference(
279  ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
280  ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
281  std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
282  ExistingFeatures.begin(), ExistingFeatures.end(),
283  std::back_inserter(UnmatchedReadFeatures));
284 
285  // If we are allowing compatible differences and the read feature set is
286  // a strict subset of the existing feature set, there is nothing to diagnose.
287  if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
288  return false;
289 
290  if (Diags) {
291  for (StringRef Feature : UnmatchedReadFeatures)
292  Diags->Report(diag::err_pch_targetopt_feature_mismatch)
293  << /* is-existing-feature */ false << Feature;
294  for (StringRef Feature : UnmatchedExistingFeatures)
295  Diags->Report(diag::err_pch_targetopt_feature_mismatch)
296  << /* is-existing-feature */ true << Feature;
297  }
298 
299  return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
300 }
301 
302 bool
304  bool Complain,
305  bool AllowCompatibleDifferences) {
306  const LangOptions &ExistingLangOpts = PP.getLangOpts();
307  return checkLanguageOptions(LangOpts, ExistingLangOpts,
308  Complain ? &Reader.Diags : nullptr,
309  AllowCompatibleDifferences);
310 }
311 
313  bool Complain,
314  bool AllowCompatibleDifferences) {
315  const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
316  return checkTargetOptions(TargetOpts, ExistingTargetOpts,
317  Complain ? &Reader.Diags : nullptr,
318  AllowCompatibleDifferences);
319 }
320 
321 namespace {
322  typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
323  MacroDefinitionsMap;
324  typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
325  DeclsMap;
326 }
327 
329  DiagnosticsEngine &Diags,
330  bool Complain) {
332 
333  // Check current mappings for new -Werror mappings, and the stored mappings
334  // for cases that were explicitly mapped to *not* be errors that are now
335  // errors because of options like -Werror.
336  DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
337 
338  for (DiagnosticsEngine *MappingSource : MappingSources) {
339  for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
340  diag::kind DiagID = DiagIDMappingPair.first;
341  Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
342  if (CurLevel < DiagnosticsEngine::Error)
343  continue; // not significant
344  Level StoredLevel =
345  StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
346  if (StoredLevel < DiagnosticsEngine::Error) {
347  if (Complain)
348  Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
349  Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
350  return true;
351  }
352  }
353  }
354 
355  return false;
356 }
357 
360  if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
361  return true;
362  return Ext >= diag::Severity::Error;
363 }
364 
366  DiagnosticsEngine &Diags,
367  bool IsSystem, bool Complain) {
368  // Top-level options
369  if (IsSystem) {
370  if (Diags.getSuppressSystemWarnings())
371  return false;
372  // If -Wsystem-headers was not enabled before, be conservative
373  if (StoredDiags.getSuppressSystemWarnings()) {
374  if (Complain)
375  Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
376  return true;
377  }
378  }
379 
380  if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
381  if (Complain)
382  Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
383  return true;
384  }
385 
386  if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
387  !StoredDiags.getEnableAllWarnings()) {
388  if (Complain)
389  Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
390  return true;
391  }
392 
393  if (isExtHandlingFromDiagsError(Diags) &&
394  !isExtHandlingFromDiagsError(StoredDiags)) {
395  if (Complain)
396  Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
397  return true;
398  }
399 
400  return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
401 }
402 
404  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
405  DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
406  IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
408  new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
409  // This should never fail, because we would have processed these options
410  // before writing them to an ASTFile.
411  ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
412 
413  ModuleManager &ModuleMgr = Reader.getModuleManager();
414  assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
415 
416  // If the original import came from a file explicitly generated by the user,
417  // don't check the diagnostic mappings.
418  // FIXME: currently this is approximated by checking whether this is not a
419  // module import of an implicitly-loaded module file.
420  // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
421  // the transitive closure of its imports, since unrelated modules cannot be
422  // imported until after this module finishes validation.
423  ModuleFile *TopImport = *ModuleMgr.rbegin();
424  while (!TopImport->ImportedBy.empty())
425  TopImport = TopImport->ImportedBy[0];
426  if (TopImport->Kind != MK_ImplicitModule)
427  return false;
428 
429  StringRef ModuleName = TopImport->ModuleName;
430  assert(!ModuleName.empty() && "diagnostic options read before module name");
431 
432  Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
433  assert(M && "missing module");
434 
435  // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
436  // contains the union of their flags.
437  return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
438 }
439 
440 /// \brief Collect the macro definitions provided by the given preprocessor
441 /// options.
442 static void
444  MacroDefinitionsMap &Macros,
445  SmallVectorImpl<StringRef> *MacroNames = nullptr) {
446  for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
447  StringRef Macro = PPOpts.Macros[I].first;
448  bool IsUndef = PPOpts.Macros[I].second;
449 
450  std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
451  StringRef MacroName = MacroPair.first;
452  StringRef MacroBody = MacroPair.second;
453 
454  // For an #undef'd macro, we only care about the name.
455  if (IsUndef) {
456  if (MacroNames && !Macros.count(MacroName))
457  MacroNames->push_back(MacroName);
458 
459  Macros[MacroName] = std::make_pair("", true);
460  continue;
461  }
462 
463  // For a #define'd macro, figure out the actual definition.
464  if (MacroName.size() == Macro.size())
465  MacroBody = "1";
466  else {
467  // Note: GCC drops anything following an end-of-line character.
468  StringRef::size_type End = MacroBody.find_first_of("\n\r");
469  MacroBody = MacroBody.substr(0, End);
470  }
471 
472  if (MacroNames && !Macros.count(MacroName))
473  MacroNames->push_back(MacroName);
474  Macros[MacroName] = std::make_pair(MacroBody, false);
475  }
476 }
477 
478 /// \brief Check the preprocessor options deserialized from the control block
479 /// against the preprocessor options in an existing preprocessor.
480 ///
481 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
483  const PreprocessorOptions &ExistingPPOpts,
484  DiagnosticsEngine *Diags,
485  FileManager &FileMgr,
486  std::string &SuggestedPredefines,
487  const LangOptions &LangOpts) {
488  // Check macro definitions.
489  MacroDefinitionsMap ASTFileMacros;
490  collectMacroDefinitions(PPOpts, ASTFileMacros);
491  MacroDefinitionsMap ExistingMacros;
492  SmallVector<StringRef, 4> ExistingMacroNames;
493  collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
494 
495  for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
496  // Dig out the macro definition in the existing preprocessor options.
497  StringRef MacroName = ExistingMacroNames[I];
498  std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
499 
500  // Check whether we know anything about this macro name or not.
501  llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
502  = ASTFileMacros.find(MacroName);
503  if (Known == ASTFileMacros.end()) {
504  // FIXME: Check whether this identifier was referenced anywhere in the
505  // AST file. If so, we should reject the AST file. Unfortunately, this
506  // information isn't in the control block. What shall we do about it?
507 
508  if (Existing.second) {
509  SuggestedPredefines += "#undef ";
510  SuggestedPredefines += MacroName.str();
511  SuggestedPredefines += '\n';
512  } else {
513  SuggestedPredefines += "#define ";
514  SuggestedPredefines += MacroName.str();
515  SuggestedPredefines += ' ';
516  SuggestedPredefines += Existing.first.str();
517  SuggestedPredefines += '\n';
518  }
519  continue;
520  }
521 
522  // If the macro was defined in one but undef'd in the other, we have a
523  // conflict.
524  if (Existing.second != Known->second.second) {
525  if (Diags) {
526  Diags->Report(diag::err_pch_macro_def_undef)
527  << MacroName << Known->second.second;
528  }
529  return true;
530  }
531 
532  // If the macro was #undef'd in both, or if the macro bodies are identical,
533  // it's fine.
534  if (Existing.second || Existing.first == Known->second.first)
535  continue;
536 
537  // The macro bodies differ; complain.
538  if (Diags) {
539  Diags->Report(diag::err_pch_macro_def_conflict)
540  << MacroName << Known->second.first << Existing.first;
541  }
542  return true;
543  }
544 
545  // Check whether we're using predefines.
546  if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
547  if (Diags) {
548  Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
549  }
550  return true;
551  }
552 
553  // Detailed record is important since it is used for the module cache hash.
554  if (LangOpts.Modules &&
555  PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
556  if (Diags) {
557  Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
558  }
559  return true;
560  }
561 
562  // Compute the #include and #include_macros lines we need.
563  for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
564  StringRef File = ExistingPPOpts.Includes[I];
565  if (File == ExistingPPOpts.ImplicitPCHInclude)
566  continue;
567 
568  if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
569  != PPOpts.Includes.end())
570  continue;
571 
572  SuggestedPredefines += "#include \"";
573  SuggestedPredefines += File;
574  SuggestedPredefines += "\"\n";
575  }
576 
577  for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
578  StringRef File = ExistingPPOpts.MacroIncludes[I];
579  if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
580  File)
581  != PPOpts.MacroIncludes.end())
582  continue;
583 
584  SuggestedPredefines += "#__include_macros \"";
585  SuggestedPredefines += File;
586  SuggestedPredefines += "\"\n##\n";
587  }
588 
589  return false;
590 }
591 
593  bool Complain,
594  std::string &SuggestedPredefines) {
595  const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
596 
597  return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
598  Complain? &Reader.Diags : nullptr,
599  PP.getFileManager(),
600  SuggestedPredefines,
601  PP.getLangOpts());
602 }
603 
604 /// Check the header search options deserialized from the control block
605 /// against the header search options in an existing preprocessor.
606 ///
607 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
609  StringRef SpecificModuleCachePath,
610  StringRef ExistingModuleCachePath,
611  DiagnosticsEngine *Diags,
612  const LangOptions &LangOpts) {
613  if (LangOpts.Modules) {
614  if (SpecificModuleCachePath != ExistingModuleCachePath) {
615  if (Diags)
616  Diags->Report(diag::err_pch_modulecache_mismatch)
617  << SpecificModuleCachePath << ExistingModuleCachePath;
618  return true;
619  }
620  }
621 
622  return false;
623 }
624 
626  StringRef SpecificModuleCachePath,
627  bool Complain) {
628  return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
629  PP.getHeaderSearchInfo().getModuleCachePath(),
630  Complain ? &Reader.Diags : nullptr,
631  PP.getLangOpts());
632 }
633 
634 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
635  PP.setCounterValue(Value);
636 }
637 
638 //===----------------------------------------------------------------------===//
639 // AST reader implementation
640 //===----------------------------------------------------------------------===//
641 
643  bool TakeOwnership) {
644  DeserializationListener = Listener;
645  OwnsDeserializationListener = TakeOwnership;
646 }
647 
648 
649 
651  return serialization::ComputeHash(Sel);
652 }
653 
654 
655 std::pair<unsigned, unsigned>
657  using namespace llvm::support;
658  unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
659  unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
660  return std::make_pair(KeyLen, DataLen);
661 }
662 
664 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
665  using namespace llvm::support;
666  SelectorTable &SelTable = Reader.getContext().Selectors;
667  unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
668  IdentifierInfo *FirstII = Reader.getLocalIdentifier(
669  F, endian::readNext<uint32_t, little, unaligned>(d));
670  if (N == 0)
671  return SelTable.getNullarySelector(FirstII);
672  else if (N == 1)
673  return SelTable.getUnarySelector(FirstII);
674 
676  Args.push_back(FirstII);
677  for (unsigned I = 1; I != N; ++I)
678  Args.push_back(Reader.getLocalIdentifier(
679  F, endian::readNext<uint32_t, little, unaligned>(d)));
680 
681  return SelTable.getSelector(N, Args.data());
682 }
683 
686  unsigned DataLen) {
687  using namespace llvm::support;
688 
690 
691  Result.ID = Reader.getGlobalSelectorID(
692  F, endian::readNext<uint32_t, little, unaligned>(d));
693  unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
694  unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
695  Result.InstanceBits = FullInstanceBits & 0x3;
696  Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
697  Result.FactoryBits = FullFactoryBits & 0x3;
698  Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
699  unsigned NumInstanceMethods = FullInstanceBits >> 3;
700  unsigned NumFactoryMethods = FullFactoryBits >> 3;
701 
702  // Load instance methods
703  for (unsigned I = 0; I != NumInstanceMethods; ++I) {
704  if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
705  F, endian::readNext<uint32_t, little, unaligned>(d)))
706  Result.Instance.push_back(Method);
707  }
708 
709  // Load factory methods
710  for (unsigned I = 0; I != NumFactoryMethods; ++I) {
711  if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
712  F, endian::readNext<uint32_t, little, unaligned>(d)))
713  Result.Factory.push_back(Method);
714  }
715 
716  return Result;
717 }
718 
720  return llvm::HashString(a);
721 }
722 
723 std::pair<unsigned, unsigned>
725  using namespace llvm::support;
726  unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
727  unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
728  return std::make_pair(KeyLen, DataLen);
729 }
730 
732 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
733  assert(n >= 2 && d[n-1] == '\0');
734  return StringRef((const char*) d, n-1);
735 }
736 
737 /// \brief Whether the given identifier is "interesting".
739  return II.isPoisoned() ||
740  II.isExtensionToken() ||
741  II.getObjCOrBuiltinID() ||
743  II.hadMacroDefinition() ||
744  II.getFETokenInfo<void>();
745 }
746 
748  const unsigned char* d,
749  unsigned DataLen) {
750  using namespace llvm::support;
751  unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
752  bool IsInteresting = RawID & 0x01;
753 
754  // Wipe out the "is interesting" bit.
755  RawID = RawID >> 1;
756 
757  IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
758  if (!IsInteresting) {
759  // For uninteresting identifiers, just build the IdentifierInfo
760  // and associate it with the persistent ID.
761  IdentifierInfo *II = KnownII;
762  if (!II) {
763  II = &Reader.getIdentifierTable().getOwn(k);
764  KnownII = II;
765  }
766  Reader.SetIdentifierInfo(ID, II);
767  if (!II->isFromAST()) {
768  bool WasInteresting = isInterestingIdentifier(*II);
769  II->setIsFromAST();
770  if (WasInteresting)
772  }
773  Reader.markIdentifierUpToDate(II);
774  return II;
775  }
776 
777  unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
778  unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
779  bool CPlusPlusOperatorKeyword = Bits & 0x01;
780  Bits >>= 1;
781  bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
782  Bits >>= 1;
783  bool Poisoned = Bits & 0x01;
784  Bits >>= 1;
785  bool ExtensionToken = Bits & 0x01;
786  Bits >>= 1;
787  bool hadMacroDefinition = Bits & 0x01;
788  Bits >>= 1;
789 
790  assert(Bits == 0 && "Extra bits in the identifier?");
791  DataLen -= 8;
792 
793  // Build the IdentifierInfo itself and link the identifier ID with
794  // the new IdentifierInfo.
795  IdentifierInfo *II = KnownII;
796  if (!II) {
797  II = &Reader.getIdentifierTable().getOwn(StringRef(k));
798  KnownII = II;
799  }
800  Reader.markIdentifierUpToDate(II);
801  if (!II->isFromAST()) {
802  bool WasInteresting = isInterestingIdentifier(*II);
803  II->setIsFromAST();
804  if (WasInteresting)
805  II->setChangedSinceDeserialization();
806  }
807 
808  // Set or check the various bits in the IdentifierInfo structure.
809  // Token IDs are read-only.
810  if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
811  II->RevertTokenIDToIdentifier();
812  II->setObjCOrBuiltinID(ObjCOrBuiltinID);
813  assert(II->isExtensionToken() == ExtensionToken &&
814  "Incorrect extension token flag");
815  (void)ExtensionToken;
816  if (Poisoned)
817  II->setIsPoisoned(true);
818  assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
819  "Incorrect C++ operator keyword flag");
820  (void)CPlusPlusOperatorKeyword;
821 
822  // If this identifier is a macro, deserialize the macro
823  // definition.
824  if (hadMacroDefinition) {
825  uint32_t MacroDirectivesOffset =
826  endian::readNext<uint32_t, little, unaligned>(d);
827  DataLen -= 4;
828 
829  Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
830  }
831 
832  Reader.SetIdentifierInfo(ID, II);
833 
834  // Read all of the declarations visible at global scope with this
835  // name.
836  if (DataLen > 0) {
837  SmallVector<uint32_t, 4> DeclIDs;
838  for (; DataLen > 0; DataLen -= 4)
839  DeclIDs.push_back(Reader.getGlobalDeclID(
840  F, endian::readNext<uint32_t, little, unaligned>(d)));
841  Reader.SetGloballyVisibleDecls(II, DeclIDs);
842  }
843 
844  return II;
845 }
846 
847 unsigned
849  llvm::FoldingSetNodeID ID;
850  ID.AddInteger(Key.Kind);
851 
852  switch (Key.Kind) {
855  ID.AddString(((IdentifierInfo*)Key.Data)->getName());
856  break;
860  ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
861  break;
863  ID.AddInteger((OverloadedOperatorKind)Key.Data);
864  break;
869  break;
870  }
871 
872  return ID.ComputeHash();
873 }
874 
877  const external_key_type& Name) {
878  DeclNameKey Key;
879  Key.Kind = Name.getNameKind();
880  switch (Name.getNameKind()) {
882  Key.Data = (uint64_t)Name.getAsIdentifierInfo();
883  break;
887  Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
888  break;
890  Key.Data = Name.getCXXOverloadedOperator();
891  break;
893  Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
894  break;
899  Key.Data = 0;
900  break;
901  }
902 
903  return Key;
904 }
905 
906 std::pair<unsigned, unsigned>
908  using namespace llvm::support;
909  unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
910  unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
911  return std::make_pair(KeyLen, DataLen);
912 }
913 
915 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
916  using namespace llvm::support;
917 
918  DeclNameKey Key;
919  Key.Kind = (DeclarationName::NameKind)*d++;
920  switch (Key.Kind) {
922  Key.Data = (uint64_t)Reader.getLocalIdentifier(
923  F, endian::readNext<uint32_t, little, unaligned>(d));
924  break;
928  Key.Data =
929  (uint64_t)Reader.getLocalSelector(
930  F, endian::readNext<uint32_t, little, unaligned>(
931  d)).getAsOpaquePtr();
932  break;
934  Key.Data = *d++; // OverloadedOperatorKind
935  break;
937  Key.Data = (uint64_t)Reader.getLocalIdentifier(
938  F, endian::readNext<uint32_t, little, unaligned>(d));
939  break;
944  Key.Data = 0;
945  break;
946  }
947 
948  return Key;
949 }
950 
953  const unsigned char* d,
954  unsigned DataLen) {
955  using namespace llvm::support;
956  unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
957  LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
958  const_cast<unsigned char *>(d));
959  return std::make_pair(Start, Start + NumDecls);
960 }
961 
962 bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
963  BitstreamCursor &Cursor,
964  const std::pair<uint64_t, uint64_t> &Offsets,
965  DeclContextInfo &Info) {
966  SavedStreamPosition SavedPosition(Cursor);
967  // First the lexical decls.
968  if (Offsets.first != 0) {
969  Cursor.JumpToBit(Offsets.first);
970 
971  RecordData Record;
972  StringRef Blob;
973  unsigned Code = Cursor.ReadCode();
974  unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
975  if (RecCode != DECL_CONTEXT_LEXICAL) {
976  Error("Expected lexical block");
977  return true;
978  }
979 
980  Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
981  Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
982  }
983 
984  // Now the lookup table.
985  if (Offsets.second != 0) {
986  Cursor.JumpToBit(Offsets.second);
987 
988  RecordData Record;
989  StringRef Blob;
990  unsigned Code = Cursor.ReadCode();
991  unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
992  if (RecCode != DECL_CONTEXT_VISIBLE) {
993  Error("Expected visible lookup table block");
994  return true;
995  }
997  (const unsigned char *)Blob.data() + Record[0],
998  (const unsigned char *)Blob.data() + sizeof(uint32_t),
999  (const unsigned char *)Blob.data(),
1000  ASTDeclContextNameLookupTrait(*this, M));
1001  }
1002 
1003  return false;
1004 }
1005 
1006 void ASTReader::Error(StringRef Msg) {
1007  Error(diag::err_fe_pch_malformed, Msg);
1008  if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
1009  Diag(diag::note_module_cache_path)
1010  << PP.getHeaderSearchInfo().getModuleCachePath();
1011  }
1012 }
1013 
1014 void ASTReader::Error(unsigned DiagID,
1015  StringRef Arg1, StringRef Arg2) {
1016  if (Diags.isDiagnosticInFlight())
1017  Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1018  else
1019  Diag(DiagID) << Arg1 << Arg2;
1020 }
1021 
1022 //===----------------------------------------------------------------------===//
1023 // Source Manager Deserialization
1024 //===----------------------------------------------------------------------===//
1025 
1026 /// \brief Read the line table in the source manager block.
1027 /// \returns true if there was an error.
1028 bool ASTReader::ParseLineTable(ModuleFile &F,
1029  const RecordData &Record) {
1030  unsigned Idx = 0;
1031  LineTableInfo &LineTable = SourceMgr.getLineTable();
1032 
1033  // Parse the file names
1034  std::map<int, int> FileIDs;
1035  for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1036  // Extract the file name
1037  auto Filename = ReadPath(F, Record, Idx);
1038  FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1039  }
1040 
1041  // Parse the line entries
1042  std::vector<LineEntry> Entries;
1043  while (Idx < Record.size()) {
1044  int FID = Record[Idx++];
1045  assert(FID >= 0 && "Serialized line entries for non-local file.");
1046  // Remap FileID from 1-based old view.
1047  FID += F.SLocEntryBaseID - 1;
1048 
1049  // Extract the line entries
1050  unsigned NumEntries = Record[Idx++];
1051  assert(NumEntries && "Numentries is 00000");
1052  Entries.clear();
1053  Entries.reserve(NumEntries);
1054  for (unsigned I = 0; I != NumEntries; ++I) {
1055  unsigned FileOffset = Record[Idx++];
1056  unsigned LineNo = Record[Idx++];
1057  int FilenameID = FileIDs[Record[Idx++]];
1059  = (SrcMgr::CharacteristicKind)Record[Idx++];
1060  unsigned IncludeOffset = Record[Idx++];
1061  Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1062  FileKind, IncludeOffset));
1063  }
1064  LineTable.AddEntry(FileID::get(FID), Entries);
1065  }
1066 
1067  return false;
1068 }
1069 
1070 /// \brief Read a source manager block
1071 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1072  using namespace SrcMgr;
1073 
1074  BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1075 
1076  // Set the source-location entry cursor to the current position in
1077  // the stream. This cursor will be used to read the contents of the
1078  // source manager block initially, and then lazily read
1079  // source-location entries as needed.
1080  SLocEntryCursor = F.Stream;
1081 
1082  // The stream itself is going to skip over the source manager block.
1083  if (F.Stream.SkipBlock()) {
1084  Error("malformed block record in AST file");
1085  return true;
1086  }
1087 
1088  // Enter the source manager block.
1089  if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1090  Error("malformed source manager block record in AST file");
1091  return true;
1092  }
1093 
1094  RecordData Record;
1095  while (true) {
1096  llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1097 
1098  switch (E.Kind) {
1099  case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1101  Error("malformed block record in AST file");
1102  return true;
1103  case llvm::BitstreamEntry::EndBlock:
1104  return false;
1105  case llvm::BitstreamEntry::Record:
1106  // The interesting case.
1107  break;
1108  }
1109 
1110  // Read a record.
1111  Record.clear();
1112  StringRef Blob;
1113  switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
1114  default: // Default behavior: ignore.
1115  break;
1116 
1117  case SM_SLOC_FILE_ENTRY:
1118  case SM_SLOC_BUFFER_ENTRY:
1120  // Once we hit one of the source location entries, we're done.
1121  return false;
1122  }
1123  }
1124 }
1125 
1126 /// \brief If a header file is not found at the path that we expect it to be
1127 /// and the PCH file was moved from its original location, try to resolve the
1128 /// file by assuming that header+PCH were moved together and the header is in
1129 /// the same place relative to the PCH.
1130 static std::string
1131 resolveFileRelativeToOriginalDir(const std::string &Filename,
1132  const std::string &OriginalDir,
1133  const std::string &CurrDir) {
1134  assert(OriginalDir != CurrDir &&
1135  "No point trying to resolve the file if the PCH dir didn't change");
1136  using namespace llvm::sys;
1137  SmallString<128> filePath(Filename);
1138  fs::make_absolute(filePath);
1139  assert(path::is_absolute(OriginalDir));
1140  SmallString<128> currPCHPath(CurrDir);
1141 
1142  path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1143  fileDirE = path::end(path::parent_path(filePath));
1144  path::const_iterator origDirI = path::begin(OriginalDir),
1145  origDirE = path::end(OriginalDir);
1146  // Skip the common path components from filePath and OriginalDir.
1147  while (fileDirI != fileDirE && origDirI != origDirE &&
1148  *fileDirI == *origDirI) {
1149  ++fileDirI;
1150  ++origDirI;
1151  }
1152  for (; origDirI != origDirE; ++origDirI)
1153  path::append(currPCHPath, "..");
1154  path::append(currPCHPath, fileDirI, fileDirE);
1155  path::append(currPCHPath, path::filename(Filename));
1156  return currPCHPath.str();
1157 }
1158 
1160  if (ID == 0)
1161  return false;
1162 
1163  if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1164  Error("source location entry ID out-of-range for AST file");
1165  return true;
1166  }
1167 
1168  ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1169  F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
1170  BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1171  unsigned BaseOffset = F->SLocEntryBaseOffset;
1172 
1173  ++NumSLocEntriesRead;
1174  llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1175  if (Entry.Kind != llvm::BitstreamEntry::Record) {
1176  Error("incorrectly-formatted source location entry in AST file");
1177  return true;
1178  }
1179 
1180  RecordData Record;
1181  StringRef Blob;
1182  switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
1183  default:
1184  Error("incorrectly-formatted source location entry in AST file");
1185  return true;
1186 
1187  case SM_SLOC_FILE_ENTRY: {
1188  // We will detect whether a file changed and return 'Failure' for it, but
1189  // we will also try to fail gracefully by setting up the SLocEntry.
1190  unsigned InputID = Record[4];
1191  InputFile IF = getInputFile(*F, InputID);
1192  const FileEntry *File = IF.getFile();
1193  bool OverriddenBuffer = IF.isOverridden();
1194 
1195  // Note that we only check if a File was returned. If it was out-of-date
1196  // we have complained but we will continue creating a FileID to recover
1197  // gracefully.
1198  if (!File)
1199  return true;
1200 
1201  SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1202  if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1203  // This is the module's main file.
1204  IncludeLoc = getImportLocation(F);
1205  }
1207  FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1208  FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1209  ID, BaseOffset + Record[0]);
1210  SrcMgr::FileInfo &FileInfo =
1211  const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1212  FileInfo.NumCreatedFIDs = Record[5];
1213  if (Record[3])
1214  FileInfo.setHasLineDirectives();
1215 
1216  const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1217  unsigned NumFileDecls = Record[7];
1218  if (NumFileDecls) {
1219  assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1220  FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1221  NumFileDecls));
1222  }
1223 
1224  const SrcMgr::ContentCache *ContentCache
1225  = SourceMgr.getOrCreateContentCache(File,
1226  /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1227  if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1228  ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1229  unsigned Code = SLocEntryCursor.ReadCode();
1230  Record.clear();
1231  unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1232 
1233  if (RecCode != SM_SLOC_BUFFER_BLOB) {
1234  Error("AST record has invalid code");
1235  return true;
1236  }
1237 
1238  std::unique_ptr<llvm::MemoryBuffer> Buffer
1239  = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
1240  SourceMgr.overrideFileContents(File, std::move(Buffer));
1241  }
1242 
1243  break;
1244  }
1245 
1246  case SM_SLOC_BUFFER_ENTRY: {
1247  const char *Name = Blob.data();
1248  unsigned Offset = Record[0];
1250  FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1251  SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1252  if (IncludeLoc.isInvalid() &&
1253  (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
1254  IncludeLoc = getImportLocation(F);
1255  }
1256  unsigned Code = SLocEntryCursor.ReadCode();
1257  Record.clear();
1258  unsigned RecCode
1259  = SLocEntryCursor.readRecord(Code, Record, &Blob);
1260 
1261  if (RecCode != SM_SLOC_BUFFER_BLOB) {
1262  Error("AST record has invalid code");
1263  return true;
1264  }
1265 
1266  std::unique_ptr<llvm::MemoryBuffer> Buffer =
1267  llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
1268  SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1269  BaseOffset + Offset, IncludeLoc);
1270  break;
1271  }
1272 
1273  case SM_SLOC_EXPANSION_ENTRY: {
1274  SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1275  SourceMgr.createExpansionLoc(SpellingLoc,
1276  ReadSourceLocation(*F, Record[2]),
1277  ReadSourceLocation(*F, Record[3]),
1278  Record[4],
1279  ID,
1280  BaseOffset + Record[0]);
1281  break;
1282  }
1283  }
1284 
1285  return false;
1286 }
1287 
1288 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1289  if (ID == 0)
1290  return std::make_pair(SourceLocation(), "");
1291 
1292  if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1293  Error("source location entry ID out-of-range for AST file");
1294  return std::make_pair(SourceLocation(), "");
1295  }
1296 
1297  // Find which module file this entry lands in.
1298  ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1299  if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
1300  return std::make_pair(SourceLocation(), "");
1301 
1302  // FIXME: Can we map this down to a particular submodule? That would be
1303  // ideal.
1304  return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1305 }
1306 
1307 /// \brief Find the location where the module F is imported.
1308 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1309  if (F->ImportLoc.isValid())
1310  return F->ImportLoc;
1311 
1312  // Otherwise we have a PCH. It's considered to be "imported" at the first
1313  // location of its includer.
1314  if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1315  // Main file is the importer.
1316  assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
1318  }
1319  return F->ImportedBy[0]->FirstLoc;
1320 }
1321 
1322 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1323 /// specified cursor. Read the abbreviations that are at the top of the block
1324 /// and then leave the cursor pointing into the block.
1325 bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
1326  if (Cursor.EnterSubBlock(BlockID)) {
1327  Error("malformed block record in AST file");
1328  return Failure;
1329  }
1330 
1331  while (true) {
1332  uint64_t Offset = Cursor.GetCurrentBitNo();
1333  unsigned Code = Cursor.ReadCode();
1334 
1335  // We expect all abbrevs to be at the start of the block.
1336  if (Code != llvm::bitc::DEFINE_ABBREV) {
1337  Cursor.JumpToBit(Offset);
1338  return false;
1339  }
1340  Cursor.ReadAbbrevRecord();
1341  }
1342 }
1343 
1345  unsigned &Idx) {
1346  Token Tok;
1347  Tok.startToken();
1348  Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1349  Tok.setLength(Record[Idx++]);
1350  if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1351  Tok.setIdentifierInfo(II);
1352  Tok.setKind((tok::TokenKind)Record[Idx++]);
1353  Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1354  return Tok;
1355 }
1356 
1358  BitstreamCursor &Stream = F.MacroCursor;
1359 
1360  // Keep track of where we are in the stream, then jump back there
1361  // after reading this macro.
1362  SavedStreamPosition SavedPosition(Stream);
1363 
1364  Stream.JumpToBit(Offset);
1365  RecordData Record;
1367  MacroInfo *Macro = nullptr;
1368 
1369  while (true) {
1370  // Advance to the next record, but if we get to the end of the block, don't
1371  // pop it (removing all the abbreviations from the cursor) since we want to
1372  // be able to reseek within the block and read entries.
1373  unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1374  llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1375 
1376  switch (Entry.Kind) {
1377  case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1379  Error("malformed block record in AST file");
1380  return Macro;
1381  case llvm::BitstreamEntry::EndBlock:
1382  return Macro;
1383  case llvm::BitstreamEntry::Record:
1384  // The interesting case.
1385  break;
1386  }
1387 
1388  // Read a record.
1389  Record.clear();
1390  PreprocessorRecordTypes RecType =
1391  (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
1392  switch (RecType) {
1393  case PP_MODULE_MACRO:
1395  return Macro;
1396 
1397  case PP_MACRO_OBJECT_LIKE:
1398  case PP_MACRO_FUNCTION_LIKE: {
1399  // If we already have a macro, that means that we've hit the end
1400  // of the definition of the macro we were looking for. We're
1401  // done.
1402  if (Macro)
1403  return Macro;
1404 
1405  unsigned NextIndex = 1; // Skip identifier ID.
1406  SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
1407  SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1408  MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
1409  MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1410  MI->setIsUsed(Record[NextIndex++]);
1411  MI->setUsedForHeaderGuard(Record[NextIndex++]);
1412 
1413  if (RecType == PP_MACRO_FUNCTION_LIKE) {
1414  // Decode function-like macro info.
1415  bool isC99VarArgs = Record[NextIndex++];
1416  bool isGNUVarArgs = Record[NextIndex++];
1417  bool hasCommaPasting = Record[NextIndex++];
1418  MacroArgs.clear();
1419  unsigned NumArgs = Record[NextIndex++];
1420  for (unsigned i = 0; i != NumArgs; ++i)
1421  MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1422 
1423  // Install function-like macro info.
1424  MI->setIsFunctionLike();
1425  if (isC99VarArgs) MI->setIsC99Varargs();
1426  if (isGNUVarArgs) MI->setIsGNUVarargs();
1427  if (hasCommaPasting) MI->setHasCommaPasting();
1428  MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1429  PP.getPreprocessorAllocator());
1430  }
1431 
1432  // Remember that we saw this macro last so that we add the tokens that
1433  // form its body to it.
1434  Macro = MI;
1435 
1436  if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1437  Record[NextIndex]) {
1438  // We have a macro definition. Register the association
1440  GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1441  PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1442  PreprocessingRecord::PPEntityID PPID =
1443  PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1444  MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1445  PPRec.getPreprocessedEntity(PPID));
1446  if (PPDef)
1447  PPRec.RegisterMacroDefinition(Macro, PPDef);
1448  }
1449 
1450  ++NumMacrosRead;
1451  break;
1452  }
1453 
1454  case PP_TOKEN: {
1455  // If we see a TOKEN before a PP_MACRO_*, then the file is
1456  // erroneous, just pretend we didn't see this.
1457  if (!Macro) break;
1458 
1459  unsigned Idx = 0;
1460  Token Tok = ReadToken(F, Record, Idx);
1461  Macro->AddTokenToBody(Tok);
1462  break;
1463  }
1464  }
1465  }
1466 }
1467 
1472  assert(I != M.PreprocessedEntityRemap.end()
1473  && "Invalid index into preprocessed entity index remap");
1474 
1475  return LocalID + I->second;
1476 }
1477 
1479  return llvm::hash_combine(ikey.Size, ikey.ModTime);
1480 }
1481 
1484  internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1485  FE->getName(), /*Imported*/false };
1486  return ikey;
1487 }
1488 
1490  if (a.Size != b.Size || a.ModTime != b.ModTime)
1491  return false;
1492 
1493  if (llvm::sys::path::is_absolute(a.Filename) &&
1494  strcmp(a.Filename, b.Filename) == 0)
1495  return true;
1496 
1497  // Determine whether the actual files are equivalent.
1498  FileManager &FileMgr = Reader.getFileManager();
1499  auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1500  if (!Key.Imported)
1501  return FileMgr.getFile(Key.Filename);
1502 
1503  std::string Resolved = Key.Filename;
1504  Reader.ResolveImportedPath(M, Resolved);
1505  return FileMgr.getFile(Resolved);
1506  };
1507 
1508  const FileEntry *FEA = GetFile(a);
1509  const FileEntry *FEB = GetFile(b);
1510  return FEA && FEA == FEB;
1511 }
1512 
1513 std::pair<unsigned, unsigned>
1514 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1515  using namespace llvm::support;
1516  unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1517  unsigned DataLen = (unsigned) *d++;
1518  return std::make_pair(KeyLen, DataLen);
1519 }
1520 
1522 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1523  using namespace llvm::support;
1524  internal_key_type ikey;
1525  ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1526  ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1527  ikey.Filename = (const char *)d;
1528  ikey.Imported = true;
1529  return ikey;
1530 }
1531 
1534  unsigned DataLen) {
1535  const unsigned char *End = d + DataLen;
1536  using namespace llvm::support;
1537  HeaderFileInfo HFI;
1538  unsigned Flags = *d++;
1539  HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1540  ((Flags >> 6) & 0x03);
1541  HFI.isImport = (Flags >> 5) & 0x01;
1542  HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1543  HFI.DirInfo = (Flags >> 2) & 0x03;
1544  HFI.Resolved = (Flags >> 1) & 0x01;
1545  HFI.IndexHeaderMapHeader = Flags & 0x01;
1546  HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1547  HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1548  M, endian::readNext<uint32_t, little, unaligned>(d));
1549  if (unsigned FrameworkOffset =
1550  endian::readNext<uint32_t, little, unaligned>(d)) {
1551  // The framework offset is 1 greater than the actual offset,
1552  // since 0 is used as an indicator for "no framework name".
1553  StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1554  HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1555  }
1556 
1557  if (d != End) {
1558  uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1559  if (LocalSMID) {
1560  // This header is part of a module. Associate it with the module to enable
1561  // implicit module import.
1562  SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1563  Module *Mod = Reader.getSubmodule(GlobalSMID);
1564  HFI.isModuleHeader = true;
1565  FileManager &FileMgr = Reader.getFileManager();
1566  ModuleMap &ModMap =
1567  Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1568  // FIXME: This information should be propagated through the
1569  // SUBMODULE_HEADER etc records rather than from here.
1570  // FIXME: We don't ever mark excluded headers.
1571  std::string Filename = key.Filename;
1572  if (key.Imported)
1573  Reader.ResolveImportedPath(M, Filename);
1574  Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
1575  ModMap.addHeader(Mod, H, HFI.getHeaderRole());
1576  }
1577  }
1578 
1579  assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1580  (void)End;
1581 
1582  // This HeaderFileInfo was externally loaded.
1583  HFI.External = true;
1584  return HFI;
1585 }
1586 
1588  ModuleFile *M,
1589  uint64_t MacroDirectivesOffset) {
1590  assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1591  PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1592 }
1593 
1595  // Note that we are loading defined macros.
1596  Deserializing Macros(this);
1597 
1598  for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1599  E = ModuleMgr.rend(); I != E; ++I) {
1600  BitstreamCursor &MacroCursor = (*I)->MacroCursor;
1601 
1602  // If there was no preprocessor block, skip this file.
1603  if (!MacroCursor.getBitStreamReader())
1604  continue;
1605 
1606  BitstreamCursor Cursor = MacroCursor;
1607  Cursor.JumpToBit((*I)->MacroStartOffset);
1608 
1609  RecordData Record;
1610  while (true) {
1611  llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1612 
1613  switch (E.Kind) {
1614  case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1616  Error("malformed block record in AST file");
1617  return;
1618  case llvm::BitstreamEntry::EndBlock:
1619  goto NextCursor;
1620 
1621  case llvm::BitstreamEntry::Record:
1622  Record.clear();
1623  switch (Cursor.readRecord(E.ID, Record)) {
1624  default: // Default behavior: ignore.
1625  break;
1626 
1627  case PP_MACRO_OBJECT_LIKE:
1629  getLocalIdentifier(**I, Record[0]);
1630  break;
1631 
1632  case PP_TOKEN:
1633  // Ignore tokens.
1634  break;
1635  }
1636  break;
1637  }
1638  }
1639  NextCursor: ;
1640  }
1641 }
1642 
1643 namespace {
1644  /// \brief Visitor class used to look up identifirs in an AST file.
1645  class IdentifierLookupVisitor {
1646  StringRef Name;
1647  unsigned NameHash;
1648  unsigned PriorGeneration;
1649  unsigned &NumIdentifierLookups;
1650  unsigned &NumIdentifierLookupHits;
1651  IdentifierInfo *Found;
1652 
1653  public:
1654  IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1655  unsigned &NumIdentifierLookups,
1656  unsigned &NumIdentifierLookupHits)
1657  : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1658  PriorGeneration(PriorGeneration),
1659  NumIdentifierLookups(NumIdentifierLookups),
1660  NumIdentifierLookupHits(NumIdentifierLookupHits),
1661  Found()
1662  {
1663  }
1664 
1665  static bool visit(ModuleFile &M, void *UserData) {
1666  IdentifierLookupVisitor *This
1667  = static_cast<IdentifierLookupVisitor *>(UserData);
1668 
1669  // If we've already searched this module file, skip it now.
1670  if (M.Generation <= This->PriorGeneration)
1671  return true;
1672 
1673  ASTIdentifierLookupTable *IdTable
1675  if (!IdTable)
1676  return false;
1677 
1678  ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1679  M, This->Found);
1680  ++This->NumIdentifierLookups;
1681  ASTIdentifierLookupTable::iterator Pos =
1682  IdTable->find_hashed(This->Name, This->NameHash, &Trait);
1683  if (Pos == IdTable->end())
1684  return false;
1685 
1686  // Dereferencing the iterator has the effect of building the
1687  // IdentifierInfo node and populating it with the various
1688  // declarations it needs.
1689  ++This->NumIdentifierLookupHits;
1690  This->Found = *Pos;
1691  return true;
1692  }
1693 
1694  // \brief Retrieve the identifier info found within the module
1695  // files.
1696  IdentifierInfo *getIdentifierInfo() const { return Found; }
1697  };
1698 }
1699 
1701  // Note that we are loading an identifier.
1702  Deserializing AnIdentifier(this);
1703 
1704  unsigned PriorGeneration = 0;
1705  if (getContext().getLangOpts().Modules)
1706  PriorGeneration = IdentifierGeneration[&II];
1707 
1708  // If there is a global index, look there first to determine which modules
1709  // provably do not have any results for this identifier.
1711  GlobalModuleIndex::HitSet *HitsPtr = nullptr;
1712  if (!loadGlobalIndex()) {
1713  if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1714  HitsPtr = &Hits;
1715  }
1716  }
1717 
1718  IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
1719  NumIdentifierLookups,
1720  NumIdentifierLookupHits);
1721  ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
1722  markIdentifierUpToDate(&II);
1723 }
1724 
1726  if (!II)
1727  return;
1728 
1729  II->setOutOfDate(false);
1730 
1731  // Update the generation for this identifier.
1732  if (getContext().getLangOpts().Modules)
1733  IdentifierGeneration[II] = getGeneration();
1734 }
1735 
1737  const PendingMacroInfo &PMInfo) {
1738  ModuleFile &M = *PMInfo.M;
1739 
1740  BitstreamCursor &Cursor = M.MacroCursor;
1741  SavedStreamPosition SavedPosition(Cursor);
1742  Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
1743 
1744  struct ModuleMacroRecord {
1745  SubmoduleID SubModID;
1746  MacroInfo *MI;
1747  SmallVector<SubmoduleID, 8> Overrides;
1748  };
1750 
1751  // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1752  // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1753  // macro histroy.
1754  RecordData Record;
1755  while (true) {
1756  llvm::BitstreamEntry Entry =
1757  Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1758  if (Entry.Kind != llvm::BitstreamEntry::Record) {
1759  Error("malformed block record in AST file");
1760  return;
1761  }
1762 
1763  Record.clear();
1764  switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
1766  break;
1767 
1768  case PP_MODULE_MACRO: {
1769  ModuleMacros.push_back(ModuleMacroRecord());
1770  auto &Info = ModuleMacros.back();
1771  Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1772  Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
1773  for (int I = 2, N = Record.size(); I != N; ++I)
1774  Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
1775  continue;
1776  }
1777 
1778  default:
1779  Error("malformed block record in AST file");
1780  return;
1781  }
1782 
1783  // We found the macro directive history; that's the last record
1784  // for this macro.
1785  break;
1786  }
1787 
1788  // Module macros are listed in reverse dependency order.
1789  {
1790  std::reverse(ModuleMacros.begin(), ModuleMacros.end());
1792  for (auto &MMR : ModuleMacros) {
1793  Overrides.clear();
1794  for (unsigned ModID : MMR.Overrides) {
1795  Module *Mod = getSubmodule(ModID);
1796  auto *Macro = PP.getModuleMacro(Mod, II);
1797  assert(Macro && "missing definition for overridden macro");
1798  Overrides.push_back(Macro);
1799  }
1800 
1801  bool Inserted = false;
1802  Module *Owner = getSubmodule(MMR.SubModID);
1803  PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
1804  }
1805  }
1806 
1807  // Don't read the directive history for a module; we don't have anywhere
1808  // to put it.
1809  if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1810  return;
1811 
1812  // Deserialize the macro directives history in reverse source-order.
1813  MacroDirective *Latest = nullptr, *Earliest = nullptr;
1814  unsigned Idx = 0, N = Record.size();
1815  while (Idx < N) {
1816  MacroDirective *MD = nullptr;
1817  SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
1818  MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1819  switch (K) {
1821  MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
1822  MD = PP.AllocateDefMacroDirective(MI, Loc);
1823  break;
1824  }
1826  MD = PP.AllocateUndefMacroDirective(Loc);
1827  break;
1828  }
1830  bool isPublic = Record[Idx++];
1831  MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1832  break;
1833  }
1834 
1835  if (!Latest)
1836  Latest = MD;
1837  if (Earliest)
1838  Earliest->setPrevious(MD);
1839  Earliest = MD;
1840  }
1841 
1842  if (Latest)
1843  PP.setLoadedMacroDirective(II, Latest);
1844 }
1845 
1846 ASTReader::InputFileInfo
1847 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
1848  // Go find this input file.
1849  BitstreamCursor &Cursor = F.InputFilesCursor;
1850  SavedStreamPosition SavedPosition(Cursor);
1851  Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1852 
1853  unsigned Code = Cursor.ReadCode();
1854  RecordData Record;
1855  StringRef Blob;
1856 
1857  unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1858  assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1859  "invalid record type for input file");
1860  (void)Result;
1861 
1862  std::string Filename;
1863  off_t StoredSize;
1864  time_t StoredTime;
1865  bool Overridden;
1866 
1867  assert(Record[0] == ID && "Bogus stored ID or offset");
1868  StoredSize = static_cast<off_t>(Record[1]);
1869  StoredTime = static_cast<time_t>(Record[2]);
1870  Overridden = static_cast<bool>(Record[3]);
1871  Filename = Blob;
1872  ResolveImportedPath(F, Filename);
1873 
1874  InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1875  return R;
1876 }
1877 
1878 std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
1879  return readInputFileInfo(F, ID).Filename;
1880 }
1881 
1882 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
1883  // If this ID is bogus, just return an empty input file.
1884  if (ID == 0 || ID > F.InputFilesLoaded.size())
1885  return InputFile();
1886 
1887  // If we've already loaded this input file, return it.
1888  if (F.InputFilesLoaded[ID-1].getFile())
1889  return F.InputFilesLoaded[ID-1];
1890 
1891  if (F.InputFilesLoaded[ID-1].isNotFound())
1892  return InputFile();
1893 
1894  // Go find this input file.
1895  BitstreamCursor &Cursor = F.InputFilesCursor;
1896  SavedStreamPosition SavedPosition(Cursor);
1897  Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1898 
1899  InputFileInfo FI = readInputFileInfo(F, ID);
1900  off_t StoredSize = FI.StoredSize;
1901  time_t StoredTime = FI.StoredTime;
1902  bool Overridden = FI.Overridden;
1903  StringRef Filename = FI.Filename;
1904 
1905  const FileEntry *File
1906  = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1907  : FileMgr.getFile(Filename, /*OpenFile=*/false);
1908 
1909  // If we didn't find the file, resolve it relative to the
1910  // original directory from which this AST file was created.
1911  if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1912  F.OriginalDir != CurrentDir) {
1913  std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1914  F.OriginalDir,
1915  CurrentDir);
1916  if (!Resolved.empty())
1917  File = FileMgr.getFile(Resolved);
1918  }
1919 
1920  // For an overridden file, create a virtual file with the stored
1921  // size/timestamp.
1922  if (Overridden && File == nullptr) {
1923  File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1924  }
1925 
1926  if (File == nullptr) {
1927  if (Complain) {
1928  std::string ErrorStr = "could not find file '";
1929  ErrorStr += Filename;
1930  ErrorStr += "' referenced by AST file";
1931  Error(ErrorStr.c_str());
1932  }
1933  // Record that we didn't find the file.
1935  return InputFile();
1936  }
1937 
1938  // Check if there was a request to override the contents of the file
1939  // that was part of the precompiled header. Overridding such a file
1940  // can lead to problems when lexing using the source locations from the
1941  // PCH.
1942  SourceManager &SM = getSourceManager();
1943  if (!Overridden && SM.isFileOverridden(File)) {
1944  if (Complain)
1945  Error(diag::err_fe_pch_file_overridden, Filename);
1946  // After emitting the diagnostic, recover by disabling the override so
1947  // that the original file will be used.
1948  SM.disableFileContentsOverride(File);
1949  // The FileEntry is a virtual file entry with the size of the contents
1950  // that would override the original contents. Set it to the original's
1951  // size/time.
1952  FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1953  StoredSize, StoredTime);
1954  }
1955 
1956  bool IsOutOfDate = false;
1957 
1958  // For an overridden file, there is nothing to validate.
1959  if (!Overridden && //
1960  (StoredSize != File->getSize() ||
1961 #if defined(LLVM_ON_WIN32)
1962  false
1963 #else
1964  // In our regression testing, the Windows file system seems to
1965  // have inconsistent modification times that sometimes
1966  // erroneously trigger this error-handling path.
1967  //
1968  // This also happens in networked file systems, so disable this
1969  // check if validation is disabled or if we have an explicitly
1970  // built PCM file.
1971  //
1972  // FIXME: Should we also do this for PCH files? They could also
1973  // reasonably get shared across a network during a distributed build.
1974  (StoredTime != File->getModificationTime() && !DisableValidation &&
1975  F.Kind != MK_ExplicitModule)
1976 #endif
1977  )) {
1978  if (Complain) {
1979  // Build a list of the PCH imports that got us here (in reverse).
1980  SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1981  while (ImportStack.back()->ImportedBy.size() > 0)
1982  ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
1983 
1984  // The top-level PCH is stale.
1985  StringRef TopLevelPCHName(ImportStack.back()->FileName);
1986  Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
1987 
1988  // Print the import stack.
1989  if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1990  Diag(diag::note_pch_required_by)
1991  << Filename << ImportStack[0]->FileName;
1992  for (unsigned I = 1; I < ImportStack.size(); ++I)
1993  Diag(diag::note_pch_required_by)
1994  << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
1995  }
1996 
1997  if (!Diags.isDiagnosticInFlight())
1998  Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
1999  }
2000 
2001  IsOutOfDate = true;
2002  }
2003 
2004  InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2005 
2006  // Note that we've loaded this input file.
2007  F.InputFilesLoaded[ID-1] = IF;
2008  return IF;
2009 }
2010 
2011 /// \brief If we are loading a relocatable PCH or module file, and the filename
2012 /// is not an absolute path, add the system or module root to the beginning of
2013 /// the file name.
2014 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2015  // Resolve relative to the base directory, if we have one.
2016  if (!M.BaseDirectory.empty())
2017  return ResolveImportedPath(Filename, M.BaseDirectory);
2018 }
2019 
2020 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2021  if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2022  return;
2023 
2024  SmallString<128> Buffer;
2025  llvm::sys::path::append(Buffer, Prefix, Filename);
2026  Filename.assign(Buffer.begin(), Buffer.end());
2027 }
2028 
2030 ASTReader::ReadControlBlock(ModuleFile &F,
2032  const ModuleFile *ImportedBy,
2033  unsigned ClientLoadCapabilities) {
2034  BitstreamCursor &Stream = F.Stream;
2035 
2036  if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2037  Error("malformed block record in AST file");
2038  return Failure;
2039  }
2040 
2041  // Should we allow the configuration of the module file to differ from the
2042  // configuration of the current translation unit in a compatible way?
2043  //
2044  // FIXME: Allow this for files explicitly specified with -include-pch too.
2045  bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2046 
2047  // Read all of the records and blocks in the control block.
2048  RecordData Record;
2049  unsigned NumInputs = 0;
2050  unsigned NumUserInputs = 0;
2051  while (1) {
2052  llvm::BitstreamEntry Entry = Stream.advance();
2053 
2054  switch (Entry.Kind) {
2056  Error("malformed block record in AST file");
2057  return Failure;
2058  case llvm::BitstreamEntry::EndBlock: {
2059  // Validate input files.
2060  const HeaderSearchOptions &HSOpts =
2061  PP.getHeaderSearchInfo().getHeaderSearchOpts();
2062 
2063  // All user input files reside at the index range [0, NumUserInputs), and
2064  // system input files reside at [NumUserInputs, NumInputs).
2065  if (!DisableValidation) {
2066  bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2067 
2068  // If we are reading a module, we will create a verification timestamp,
2069  // so we verify all input files. Otherwise, verify only user input
2070  // files.
2071 
2072  unsigned N = NumUserInputs;
2073  if (ValidateSystemInputs ||
2075  F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
2076  F.Kind == MK_ImplicitModule))
2077  N = NumInputs;
2078 
2079  for (unsigned I = 0; I < N; ++I) {
2080  InputFile IF = getInputFile(F, I+1, Complain);
2081  if (!IF.getFile() || IF.isOutOfDate())
2082  return OutOfDate;
2083  }
2084  }
2085 
2086  if (Listener)
2087  Listener->visitModuleFile(F.FileName);
2088 
2089  if (Listener && Listener->needsInputFileVisitation()) {
2090  unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2091  : NumUserInputs;
2092  for (unsigned I = 0; I < N; ++I) {
2093  bool IsSystem = I >= NumUserInputs;
2094  InputFileInfo FI = readInputFileInfo(F, I+1);
2095  Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
2096  }
2097  }
2098 
2099  return Success;
2100  }
2101 
2102  case llvm::BitstreamEntry::SubBlock:
2103  switch (Entry.ID) {
2104  case INPUT_FILES_BLOCK_ID:
2105  F.InputFilesCursor = Stream;
2106  if (Stream.SkipBlock() || // Skip with the main cursor
2107  // Read the abbreviations
2108  ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2109  Error("malformed block record in AST file");
2110  return Failure;
2111  }
2112  continue;
2113 
2114  default:
2115  if (Stream.SkipBlock()) {
2116  Error("malformed block record in AST file");
2117  return Failure;
2118  }
2119  continue;
2120  }
2121 
2122  case llvm::BitstreamEntry::Record:
2123  // The interesting case.
2124  break;
2125  }
2126 
2127  // Read and process a record.
2128  Record.clear();
2129  StringRef Blob;
2130  switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2131  case METADATA: {
2132  if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2133  if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2134  Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2135  : diag::err_pch_version_too_new);
2136  return VersionMismatch;
2137  }
2138 
2139  bool hasErrors = Record[5];
2140  if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2141  Diag(diag::err_pch_with_compiler_errors);
2142  return HadErrors;
2143  }
2144 
2145  F.RelocatablePCH = Record[4];
2146  // Relative paths in a relocatable PCH are relative to our sysroot.
2147  if (F.RelocatablePCH)
2148  F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
2149 
2150  const std::string &CurBranch = getClangFullRepositoryVersion();
2151  StringRef ASTBranch = Blob;
2152  if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2153  if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2154  Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2155  return VersionMismatch;
2156  }
2157  break;
2158  }
2159 
2160  case SIGNATURE:
2161  assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2162  F.Signature = Record[0];
2163  break;
2164 
2165  case IMPORTS: {
2166  // Load each of the imported PCH files.
2167  unsigned Idx = 0, N = Record.size();
2168  while (Idx < N) {
2169  // Read information about the AST file.
2170  ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2171  // The import location will be the local one for now; we will adjust
2172  // all import locations of module imports after the global source
2173  // location info are setup.
2174  SourceLocation ImportLoc =
2175  SourceLocation::getFromRawEncoding(Record[Idx++]);
2176  off_t StoredSize = (off_t)Record[Idx++];
2177  time_t StoredModTime = (time_t)Record[Idx++];
2178  ASTFileSignature StoredSignature = Record[Idx++];
2179  auto ImportedFile = ReadPath(F, Record, Idx);
2180 
2181  // Load the AST file.
2182  switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
2183  StoredSize, StoredModTime, StoredSignature,
2184  ClientLoadCapabilities)) {
2185  case Failure: return Failure;
2186  // If we have to ignore the dependency, we'll have to ignore this too.
2187  case Missing:
2188  case OutOfDate: return OutOfDate;
2189  case VersionMismatch: return VersionMismatch;
2190  case ConfigurationMismatch: return ConfigurationMismatch;
2191  case HadErrors: return HadErrors;
2192  case Success: break;
2193  }
2194  }
2195  break;
2196  }
2197 
2198  case KNOWN_MODULE_FILES:
2199  break;
2200 
2201  case LANGUAGE_OPTIONS: {
2202  bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2203  // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
2204  if (Listener && &F == *ModuleMgr.begin() &&
2205  ParseLanguageOptions(Record, Complain, *Listener,
2206  AllowCompatibleConfigurationMismatch) &&
2207  !DisableValidation && !AllowConfigurationMismatch)
2208  return ConfigurationMismatch;
2209  break;
2210  }
2211 
2212  case TARGET_OPTIONS: {
2213  bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2214  if (Listener && &F == *ModuleMgr.begin() &&
2215  ParseTargetOptions(Record, Complain, *Listener,
2216  AllowCompatibleConfigurationMismatch) &&
2217  !DisableValidation && !AllowConfigurationMismatch)
2218  return ConfigurationMismatch;
2219  break;
2220  }
2221 
2222  case DIAGNOSTIC_OPTIONS: {
2223  bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
2224  if (Listener && &F == *ModuleMgr.begin() &&
2225  !AllowCompatibleConfigurationMismatch &&
2226  ParseDiagnosticOptions(Record, Complain, *Listener) &&
2227  !DisableValidation)
2228  return OutOfDate;
2229  break;
2230  }
2231 
2232  case FILE_SYSTEM_OPTIONS: {
2233  bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2234  if (Listener && &F == *ModuleMgr.begin() &&
2235  !AllowCompatibleConfigurationMismatch &&
2236  ParseFileSystemOptions(Record, Complain, *Listener) &&
2237  !DisableValidation && !AllowConfigurationMismatch)
2238  return ConfigurationMismatch;
2239  break;
2240  }
2241 
2242  case HEADER_SEARCH_OPTIONS: {
2243  bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2244  if (Listener && &F == *ModuleMgr.begin() &&
2245  !AllowCompatibleConfigurationMismatch &&
2246  ParseHeaderSearchOptions(Record, Complain, *Listener) &&
2247  !DisableValidation && !AllowConfigurationMismatch)
2248  return ConfigurationMismatch;
2249  break;
2250  }
2251 
2252  case PREPROCESSOR_OPTIONS: {
2253  bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2254  if (Listener && &F == *ModuleMgr.begin() &&
2255  !AllowCompatibleConfigurationMismatch &&
2256  ParsePreprocessorOptions(Record, Complain, *Listener,
2257  SuggestedPredefines) &&
2258  !DisableValidation && !AllowConfigurationMismatch)
2259  return ConfigurationMismatch;
2260  break;
2261  }
2262 
2263  case ORIGINAL_FILE:
2264  F.OriginalSourceFileID = FileID::get(Record[0]);
2265  F.ActualOriginalSourceFileName = Blob;
2266  F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2267  ResolveImportedPath(F, F.OriginalSourceFileName);
2268  break;
2269 
2270  case ORIGINAL_FILE_ID:
2271  F.OriginalSourceFileID = FileID::get(Record[0]);
2272  break;
2273 
2274  case ORIGINAL_PCH_DIR:
2275  F.OriginalDir = Blob;
2276  break;
2277 
2278  case MODULE_NAME:
2279  F.ModuleName = Blob;
2280  if (Listener)
2281  Listener->ReadModuleName(F.ModuleName);
2282  break;
2283 
2284  case MODULE_DIRECTORY: {
2285  assert(!F.ModuleName.empty() &&
2286  "MODULE_DIRECTORY found before MODULE_NAME");
2287  // If we've already loaded a module map file covering this module, we may
2288  // have a better path for it (relative to the current build).
2289  Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2290  if (M && M->Directory) {
2291  // If we're implicitly loading a module, the base directory can't
2292  // change between the build and use.
2293  if (F.Kind != MK_ExplicitModule) {
2294  const DirectoryEntry *BuildDir =
2295  PP.getFileManager().getDirectory(Blob);
2296  if (!BuildDir || BuildDir != M->Directory) {
2297  if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2298  Diag(diag::err_imported_module_relocated)
2299  << F.ModuleName << Blob << M->Directory->getName();
2300  return OutOfDate;
2301  }
2302  }
2303  F.BaseDirectory = M->Directory->getName();
2304  } else {
2305  F.BaseDirectory = Blob;
2306  }
2307  break;
2308  }
2309 
2310  case MODULE_MAP_FILE:
2311  if (ASTReadResult Result =
2312  ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2313  return Result;
2314  break;
2315 
2316  case INPUT_FILE_OFFSETS:
2317  NumInputs = Record[0];
2318  NumUserInputs = Record[1];
2319  F.InputFileOffsets =
2320  (const llvm::support::unaligned_uint64_t *)Blob.data();
2321  F.InputFilesLoaded.resize(NumInputs);
2322  break;
2323  }
2324  }
2325 }
2326 
2328 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
2329  BitstreamCursor &Stream = F.Stream;
2330 
2331  if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2332  Error("malformed block record in AST file");
2333  return Failure;
2334  }
2335 
2336  // Read all of the records and blocks for the AST file.
2337  RecordData Record;
2338  while (1) {
2339  llvm::BitstreamEntry Entry = Stream.advance();
2340 
2341  switch (Entry.Kind) {
2343  Error("error at end of module block in AST file");
2344  return Failure;
2345  case llvm::BitstreamEntry::EndBlock: {
2346  // Outside of C++, we do not store a lookup map for the translation unit.
2347  // Instead, mark it as needing a lookup map to be built if this module
2348  // contains any declarations lexically within it (which it always does!).
2349  // This usually has no cost, since we very rarely need the lookup map for
2350  // the translation unit outside C++.
2352  if (DC->hasExternalLexicalStorage() &&
2353  !getContext().getLangOpts().CPlusPlus)
2355 
2356  return Success;
2357  }
2358  case llvm::BitstreamEntry::SubBlock:
2359  switch (Entry.ID) {
2360  case DECLTYPES_BLOCK_ID:
2361  // We lazily load the decls block, but we want to set up the
2362  // DeclsCursor cursor to point into it. Clone our current bitcode
2363  // cursor to it, enter the block and read the abbrevs in that block.
2364  // With the main cursor, we just skip over it.
2365  F.DeclsCursor = Stream;
2366  if (Stream.SkipBlock() || // Skip with the main cursor.
2367  // Read the abbrevs.
2368  ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2369  Error("malformed block record in AST file");
2370  return Failure;
2371  }
2372  break;
2373 
2374  case PREPROCESSOR_BLOCK_ID:
2375  F.MacroCursor = Stream;
2376  if (!PP.getExternalSource())
2377  PP.setExternalSource(this);
2378 
2379  if (Stream.SkipBlock() ||
2380  ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2381  Error("malformed block record in AST file");
2382  return Failure;
2383  }
2384  F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2385  break;
2386 
2388  F.PreprocessorDetailCursor = Stream;
2389  if (Stream.SkipBlock() ||
2390  ReadBlockAbbrevs(F.PreprocessorDetailCursor,
2392  Error("malformed preprocessor detail record in AST file");
2393  return Failure;
2394  }
2396  = F.PreprocessorDetailCursor.GetCurrentBitNo();
2397 
2398  if (!PP.getPreprocessingRecord())
2399  PP.createPreprocessingRecord();
2400  if (!PP.getPreprocessingRecord()->getExternalSource())
2401  PP.getPreprocessingRecord()->SetExternalSource(*this);
2402  break;
2403 
2405  if (ReadSourceManagerBlock(F))
2406  return Failure;
2407  break;
2408 
2409  case SUBMODULE_BLOCK_ID:
2410  if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2411  return Result;
2412  break;
2413 
2414  case COMMENTS_BLOCK_ID: {
2415  BitstreamCursor C = Stream;
2416  if (Stream.SkipBlock() ||
2417  ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2418  Error("malformed comments block in AST file");
2419  return Failure;
2420  }
2421  CommentsCursors.push_back(std::make_pair(C, &F));
2422  break;
2423  }
2424 
2425  default:
2426  if (Stream.SkipBlock()) {
2427  Error("malformed block record in AST file");
2428  return Failure;
2429  }
2430  break;
2431  }
2432  continue;
2433 
2434  case llvm::BitstreamEntry::Record:
2435  // The interesting case.
2436  break;
2437  }
2438 
2439  // Read and process a record.
2440  Record.clear();
2441  StringRef Blob;
2442  switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2443  default: // Default behavior: ignore.
2444  break;
2445 
2446  case TYPE_OFFSET: {
2447  if (F.LocalNumTypes != 0) {
2448  Error("duplicate TYPE_OFFSET record in AST file");
2449  return Failure;
2450  }
2451  F.TypeOffsets = (const uint32_t *)Blob.data();
2452  F.LocalNumTypes = Record[0];
2453  unsigned LocalBaseTypeIndex = Record[1];
2454  F.BaseTypeIndex = getTotalNumTypes();
2455 
2456  if (F.LocalNumTypes > 0) {
2457  // Introduce the global -> local mapping for types within this module.
2458  GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2459 
2460  // Introduce the local -> global mapping for types within this module.
2462  std::make_pair(LocalBaseTypeIndex,
2463  F.BaseTypeIndex - LocalBaseTypeIndex));
2464 
2465  TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2466  }
2467  break;
2468  }
2469 
2470  case DECL_OFFSET: {
2471  if (F.LocalNumDecls != 0) {
2472  Error("duplicate DECL_OFFSET record in AST file");
2473  return Failure;
2474  }
2475  F.DeclOffsets = (const DeclOffset *)Blob.data();
2476  F.LocalNumDecls = Record[0];
2477  unsigned LocalBaseDeclID = Record[1];
2478  F.BaseDeclID = getTotalNumDecls();
2479 
2480  if (F.LocalNumDecls > 0) {
2481  // Introduce the global -> local mapping for declarations within this
2482  // module.
2483  GlobalDeclMap.insert(
2484  std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2485 
2486  // Introduce the local -> global mapping for declarations within this
2487  // module.
2489  std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2490 
2491  // Introduce the global -> local mapping for declarations within this
2492  // module.
2493  F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2494 
2495  DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2496  }
2497  break;
2498  }
2499 
2500  case TU_UPDATE_LEXICAL: {
2502  DeclContextInfo &Info = F.DeclContextInfos[TU];
2503  Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
2504  Info.NumLexicalDecls
2505  = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
2506  TU->setHasExternalLexicalStorage(true);
2507  break;
2508  }
2509 
2510  case UPDATE_VISIBLE: {
2511  unsigned Idx = 0;
2512  serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2515  (const unsigned char *)Blob.data() + Record[Idx++],
2516  (const unsigned char *)Blob.data() + sizeof(uint32_t),
2517  (const unsigned char *)Blob.data(),
2518  ASTDeclContextNameLookupTrait(*this, F));
2519  if (Decl *D = GetExistingDecl(ID)) {
2520  auto *DC = cast<DeclContext>(D);
2522  auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
2523  delete LookupTable;
2524  LookupTable = Table;
2525  } else
2526  PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2527  break;
2528  }
2529 
2530  case IDENTIFIER_TABLE:
2531  F.IdentifierTableData = Blob.data();
2532  if (Record[0]) {
2534  (const unsigned char *)F.IdentifierTableData + Record[0],
2535  (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2536  (const unsigned char *)F.IdentifierTableData,
2537  ASTIdentifierLookupTrait(*this, F));
2538 
2539  PP.getIdentifierTable().setExternalIdentifierLookup(this);
2540  }
2541  break;
2542 
2543  case IDENTIFIER_OFFSET: {
2544  if (F.LocalNumIdentifiers != 0) {
2545  Error("duplicate IDENTIFIER_OFFSET record in AST file");
2546  return Failure;
2547  }
2548  F.IdentifierOffsets = (const uint32_t *)Blob.data();
2549  F.LocalNumIdentifiers = Record[0];
2550  unsigned LocalBaseIdentifierID = Record[1];
2551  F.BaseIdentifierID = getTotalNumIdentifiers();
2552 
2553  if (F.LocalNumIdentifiers > 0) {
2554  // Introduce the global -> local mapping for identifiers within this
2555  // module.
2556  GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2557  &F));
2558 
2559  // Introduce the local -> global mapping for identifiers within this
2560  // module.
2562  std::make_pair(LocalBaseIdentifierID,
2563  F.BaseIdentifierID - LocalBaseIdentifierID));
2564 
2565  IdentifiersLoaded.resize(IdentifiersLoaded.size()
2566  + F.LocalNumIdentifiers);
2567  }
2568  break;
2569  }
2570 
2572  // FIXME: Skip reading this record if our ASTConsumer doesn't care
2573  // about "interesting" decls (for instance, if we're building a module).
2574  for (unsigned I = 0, N = Record.size(); I != N; ++I)
2575  EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2576  break;
2577 
2578  case SPECIAL_TYPES:
2579  if (SpecialTypes.empty()) {
2580  for (unsigned I = 0, N = Record.size(); I != N; ++I)
2581  SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2582  break;
2583  }
2584 
2585  if (SpecialTypes.size() != Record.size()) {
2586  Error("invalid special-types record");
2587  return Failure;
2588  }
2589 
2590  for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2591  serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2592  if (!SpecialTypes[I])
2593  SpecialTypes[I] = ID;
2594  // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2595  // merge step?
2596  }
2597  break;
2598 
2599  case STATISTICS:
2600  TotalNumStatements += Record[0];
2601  TotalNumMacros += Record[1];
2602  TotalLexicalDeclContexts += Record[2];
2603  TotalVisibleDeclContexts += Record[3];
2604  break;
2605 
2607  for (unsigned I = 0, N = Record.size(); I != N; ++I)
2608  UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2609  break;
2610 
2611  case DELEGATING_CTORS:
2612  for (unsigned I = 0, N = Record.size(); I != N; ++I)
2613  DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2614  break;
2615 
2617  if (Record.size() % 4 != 0) {
2618  Error("invalid weak identifiers record");
2619  return Failure;
2620  }
2621 
2622  // FIXME: Ignore weak undeclared identifiers from non-original PCH
2623  // files. This isn't the way to do it :)
2624  WeakUndeclaredIdentifiers.clear();
2625 
2626  // Translate the weak, undeclared identifiers into global IDs.
2627  for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2628  WeakUndeclaredIdentifiers.push_back(
2629  getGlobalIdentifierID(F, Record[I++]));
2630  WeakUndeclaredIdentifiers.push_back(
2631  getGlobalIdentifierID(F, Record[I++]));
2632  WeakUndeclaredIdentifiers.push_back(
2633  ReadSourceLocation(F, Record, I).getRawEncoding());
2634  WeakUndeclaredIdentifiers.push_back(Record[I++]);
2635  }
2636  break;
2637 
2638  case SELECTOR_OFFSETS: {
2639  F.SelectorOffsets = (const uint32_t *)Blob.data();
2640  F.LocalNumSelectors = Record[0];
2641  unsigned LocalBaseSelectorID = Record[1];
2642  F.BaseSelectorID = getTotalNumSelectors();
2643 
2644  if (F.LocalNumSelectors > 0) {
2645  // Introduce the global -> local mapping for selectors within this
2646  // module.
2647  GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2648 
2649  // Introduce the local -> global mapping for selectors within this
2650  // module.
2652  std::make_pair(LocalBaseSelectorID,
2653  F.BaseSelectorID - LocalBaseSelectorID));
2654 
2655  SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2656  }
2657  break;
2658  }
2659 
2660  case METHOD_POOL:
2661  F.SelectorLookupTableData = (const unsigned char *)Blob.data();
2662  if (Record[0])
2665  F.SelectorLookupTableData + Record[0],
2667  ASTSelectorLookupTrait(*this, F));
2668  TotalNumMethodPoolEntries += Record[1];
2669  break;
2670 
2672  if (!Record.empty()) {
2673  for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2674  ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2675  Record[Idx++]));
2676  ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2677  getRawEncoding());
2678  }
2679  }
2680  break;
2681 
2682  case PP_COUNTER_VALUE:
2683  if (!Record.empty() && Listener)
2684  Listener->ReadCounter(F, Record[0]);
2685  break;
2686 
2687  case FILE_SORTED_DECLS:
2688  F.FileSortedDecls = (const DeclID *)Blob.data();
2689  F.NumFileSortedDecls = Record[0];
2690  break;
2691 
2692  case SOURCE_LOCATION_OFFSETS: {
2693  F.SLocEntryOffsets = (const uint32_t *)Blob.data();
2694  F.LocalNumSLocEntries = Record[0];
2695  unsigned SLocSpaceSize = Record[1];
2696  std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2698  SLocSpaceSize);
2699  // Make our entry in the range map. BaseID is negative and growing, so
2700  // we invert it. Because we invert it, though, we need the other end of
2701  // the range.
2702  unsigned RangeStart =
2704  GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2706 
2707  // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2708  assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2709  GlobalSLocOffsetMap.insert(
2710  std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2711  - SLocSpaceSize,&F));
2712 
2713  // Initialize the remapping table.
2714  // Invalid stays invalid.
2715  F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
2716  // This module. Base was 2 when being compiled.
2717  F.SLocRemap.insertOrReplace(std::make_pair(2U,
2718  static_cast<int>(F.SLocEntryBaseOffset - 2)));
2719 
2720  TotalNumSLocEntries += F.LocalNumSLocEntries;
2721  break;
2722  }
2723 
2724  case MODULE_OFFSET_MAP: {
2725  // Additional remapping information.
2726  const unsigned char *Data = (const unsigned char*)Blob.data();
2727  const unsigned char *DataEnd = Data + Blob.size();
2728 
2729  // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2730  if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2731  F.SLocRemap.insert(std::make_pair(0U, 0));
2732  F.SLocRemap.insert(std::make_pair(2U, 1));
2733  }
2734 
2735  // Continuous range maps we may be updating in our module.
2737  RemapBuilder;
2738  RemapBuilder SLocRemap(F.SLocRemap);
2739  RemapBuilder IdentifierRemap(F.IdentifierRemap);
2740  RemapBuilder MacroRemap(F.MacroRemap);
2741  RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2742  RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2743  RemapBuilder SelectorRemap(F.SelectorRemap);
2744  RemapBuilder DeclRemap(F.DeclRemap);
2745  RemapBuilder TypeRemap(F.TypeRemap);
2746 
2747  while(Data < DataEnd) {
2748  using namespace llvm::support;
2749  uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
2750  StringRef Name = StringRef((const char*)Data, Len);
2751  Data += Len;
2752  ModuleFile *OM = ModuleMgr.lookup(Name);
2753  if (!OM) {
2754  Error("SourceLocation remap refers to unknown module");
2755  return Failure;
2756  }
2757 
2758  uint32_t SLocOffset =
2759  endian::readNext<uint32_t, little, unaligned>(Data);
2760  uint32_t IdentifierIDOffset =
2761  endian::readNext<uint32_t, little, unaligned>(Data);
2762  uint32_t MacroIDOffset =
2763  endian::readNext<uint32_t, little, unaligned>(Data);
2764  uint32_t PreprocessedEntityIDOffset =
2765  endian::readNext<uint32_t, little, unaligned>(Data);
2766  uint32_t SubmoduleIDOffset =
2767  endian::readNext<uint32_t, little, unaligned>(Data);
2768  uint32_t SelectorIDOffset =
2769  endian::readNext<uint32_t, little, unaligned>(Data);
2770  uint32_t DeclIDOffset =
2771  endian::readNext<uint32_t, little, unaligned>(Data);
2772  uint32_t TypeIndexOffset =
2773  endian::readNext<uint32_t, little, unaligned>(Data);
2774 
2775  uint32_t None = std::numeric_limits<uint32_t>::max();
2776 
2777  auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2778  RemapBuilder &Remap) {
2779  if (Offset != None)
2780  Remap.insert(std::make_pair(Offset,
2781  static_cast<int>(BaseOffset - Offset)));
2782  };
2783  mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2784  mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2785  mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2786  mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2787  PreprocessedEntityRemap);
2788  mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2789  mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2790  mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2791  mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
2792 
2793  // Global -> local mappings.
2794  F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2795  }
2796  break;
2797  }
2798 
2800  if (ParseLineTable(F, Record))
2801  return Failure;
2802  break;
2803 
2804  case SOURCE_LOCATION_PRELOADS: {
2805  // Need to transform from the local view (1-based IDs) to the global view,
2806  // which is based off F.SLocEntryBaseID.
2807  if (!F.PreloadSLocEntries.empty()) {
2808  Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2809  return Failure;
2810  }
2811 
2812  F.PreloadSLocEntries.swap(Record);
2813  break;
2814  }
2815 
2816  case EXT_VECTOR_DECLS:
2817  for (unsigned I = 0, N = Record.size(); I != N; ++I)
2818  ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2819  break;
2820 
2821  case VTABLE_USES:
2822  if (Record.size() % 3 != 0) {
2823  Error("Invalid VTABLE_USES record");
2824  return Failure;
2825  }
2826 
2827  // Later tables overwrite earlier ones.
2828  // FIXME: Modules will have some trouble with this. This is clearly not
2829  // the right way to do this.
2830  VTableUses.clear();
2831 
2832  for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2833  VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2834  VTableUses.push_back(
2835  ReadSourceLocation(F, Record, Idx).getRawEncoding());
2836  VTableUses.push_back(Record[Idx++]);
2837  }
2838  break;
2839 
2841  if (PendingInstantiations.size() % 2 != 0) {
2842  Error("Invalid existing PendingInstantiations");
2843  return Failure;
2844  }
2845 
2846  if (Record.size() % 2 != 0) {
2847  Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2848  return Failure;
2849  }
2850 
2851  for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2852  PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2853  PendingInstantiations.push_back(
2854  ReadSourceLocation(F, Record, I).getRawEncoding());
2855  }
2856  break;
2857 
2858  case SEMA_DECL_REFS:
2859  if (Record.size() != 2) {
2860  Error("Invalid SEMA_DECL_REFS block");
2861  return Failure;
2862  }
2863  for (unsigned I = 0, N = Record.size(); I != N; ++I)
2864  SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2865  break;
2866 
2867  case PPD_ENTITIES_OFFSETS: {
2868  F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2869  assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2870  F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
2871 
2872  unsigned LocalBasePreprocessedEntityID = Record[0];
2873 
2874  unsigned StartingID;
2875  if (!PP.getPreprocessingRecord())
2876  PP.createPreprocessingRecord();
2877  if (!PP.getPreprocessingRecord()->getExternalSource())
2878  PP.getPreprocessingRecord()->SetExternalSource(*this);
2879  StartingID
2880  = PP.getPreprocessingRecord()
2881  ->allocateLoadedEntities(F.NumPreprocessedEntities);
2882  F.BasePreprocessedEntityID = StartingID;
2883 
2884  if (F.NumPreprocessedEntities > 0) {
2885  // Introduce the global -> local mapping for preprocessed entities in
2886  // this module.
2887  GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2888 
2889  // Introduce the local -> global mapping for preprocessed entities in
2890  // this module.
2892  std::make_pair(LocalBasePreprocessedEntityID,
2893  F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2894  }
2895 
2896  break;
2897  }
2898 
2899  case DECL_UPDATE_OFFSETS: {
2900  if (Record.size() % 2 != 0) {
2901  Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2902  return Failure;
2903  }
2904  for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2905  GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2906  DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2907 
2908  // If we've already loaded the decl, perform the updates when we finish
2909  // loading this block.
2910  if (Decl *D = GetExistingDecl(ID))
2911  PendingUpdateRecords.push_back(std::make_pair(ID, D));
2912  }
2913  break;
2914  }
2915 
2916  case DECL_REPLACEMENTS: {
2917  if (Record.size() % 3 != 0) {
2918  Error("invalid DECL_REPLACEMENTS block in AST file");
2919  return Failure;
2920  }
2921  for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2922  ReplacedDecls[getGlobalDeclID(F, Record[I])]
2923  = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2924  break;
2925  }
2926 
2927  case OBJC_CATEGORIES_MAP: {
2928  if (F.LocalNumObjCCategoriesInMap != 0) {
2929  Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2930  return Failure;
2931  }
2932 
2933  F.LocalNumObjCCategoriesInMap = Record[0];
2934  F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
2935  break;
2936  }
2937 
2938  case OBJC_CATEGORIES:
2939  F.ObjCCategories.swap(Record);
2940  break;
2941 
2943  if (F.LocalNumCXXBaseSpecifiers != 0) {
2944  Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2945  return Failure;
2946  }
2947 
2948  F.LocalNumCXXBaseSpecifiers = Record[0];
2949  F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
2950  break;
2951  }
2952 
2954  if (F.LocalNumCXXCtorInitializers != 0) {
2955  Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2956  return Failure;
2957  }
2958 
2959  F.LocalNumCXXCtorInitializers = Record[0];
2960  F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
2961  break;
2962  }
2963 
2964  case DIAG_PRAGMA_MAPPINGS:
2965  if (F.PragmaDiagMappings.empty())
2966  F.PragmaDiagMappings.swap(Record);
2967  else
2968  F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2969  Record.begin(), Record.end());
2970  break;
2971 
2973  // Later tables overwrite earlier ones.
2974  // FIXME: Modules will have trouble with this.
2975  CUDASpecialDeclRefs.clear();
2976  for (unsigned I = 0, N = Record.size(); I != N; ++I)
2977  CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2978  break;
2979 
2980  case HEADER_SEARCH_TABLE: {
2981  F.HeaderFileInfoTableData = Blob.data();
2982  F.LocalNumHeaderFileInfos = Record[1];
2983  if (Record[0]) {
2986  (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2987  (const unsigned char *)F.HeaderFileInfoTableData,
2988  HeaderFileInfoTrait(*this, F,
2989  &PP.getHeaderSearchInfo(),
2990  Blob.data() + Record[2]));
2991 
2992  PP.getHeaderSearchInfo().SetExternalSource(this);
2993  if (!PP.getHeaderSearchInfo().getExternalLookup())
2994  PP.getHeaderSearchInfo().SetExternalLookup(this);
2995  }
2996  break;
2997  }
2998 
2999  case FP_PRAGMA_OPTIONS:
3000  // Later tables overwrite earlier ones.
3001  FPPragmaOptions.swap(Record);
3002  break;
3003 
3004  case OPENCL_EXTENSIONS:
3005  // Later tables overwrite earlier ones.
3006  OpenCLExtensions.swap(Record);
3007  break;
3008 
3009  case TENTATIVE_DEFINITIONS:
3010  for (unsigned I = 0, N = Record.size(); I != N; ++I)
3011  TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3012  break;
3013 
3014  case KNOWN_NAMESPACES:
3015  for (unsigned I = 0, N = Record.size(); I != N; ++I)
3016  KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3017  break;
3018 
3019  case UNDEFINED_BUT_USED:
3020  if (UndefinedButUsed.size() % 2 != 0) {
3021  Error("Invalid existing UndefinedButUsed");
3022  return Failure;
3023  }
3024 
3025  if (Record.size() % 2 != 0) {
3026  Error("invalid undefined-but-used record");
3027  return Failure;
3028  }
3029  for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3030  UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3031  UndefinedButUsed.push_back(
3032  ReadSourceLocation(F, Record, I).getRawEncoding());
3033  }
3034  break;
3036  for (unsigned I = 0, N = Record.size(); I != N;) {
3037  DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3038  const uint64_t Count = Record[I++];
3039  DelayedDeleteExprs.push_back(Count);
3040  for (uint64_t C = 0; C < Count; ++C) {
3041  DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3042  bool IsArrayForm = Record[I++] == 1;
3043  DelayedDeleteExprs.push_back(IsArrayForm);
3044  }
3045  }
3046  break;
3047 
3048  case IMPORTED_MODULES: {
3049  if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
3050  // If we aren't loading a module (which has its own exports), make
3051  // all of the imported modules visible.
3052  // FIXME: Deal with macros-only imports.
3053  for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3054  unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3055  SourceLocation Loc = ReadSourceLocation(F, Record, I);
3056  if (GlobalID)
3057  ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3058  }
3059  }
3060  break;
3061  }
3062 
3063  case LOCAL_REDECLARATIONS: {
3064  F.RedeclarationChains.swap(Record);
3065  break;
3066  }
3067 
3068  case LOCAL_REDECLARATIONS_MAP: {
3069  if (F.LocalNumRedeclarationsInMap != 0) {
3070  Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
3071  return Failure;
3072  }
3073 
3074  F.LocalNumRedeclarationsInMap = Record[0];
3075  F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
3076  break;
3077  }
3078 
3079  case MACRO_OFFSET: {
3080  if (F.LocalNumMacros != 0) {
3081  Error("duplicate MACRO_OFFSET record in AST file");
3082  return Failure;
3083  }
3084  F.MacroOffsets = (const uint32_t *)Blob.data();
3085  F.LocalNumMacros = Record[0];
3086  unsigned LocalBaseMacroID = Record[1];
3087  F.BaseMacroID = getTotalNumMacros();
3088 
3089  if (F.LocalNumMacros > 0) {
3090  // Introduce the global -> local mapping for macros within this module.
3091  GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3092 
3093  // Introduce the local -> global mapping for macros within this module.
3095  std::make_pair(LocalBaseMacroID,
3096  F.BaseMacroID - LocalBaseMacroID));
3097 
3098  MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3099  }
3100  break;
3101  }
3102 
3103  case LATE_PARSED_TEMPLATE: {
3104  LateParsedTemplates.append(Record.begin(), Record.end());
3105  break;
3106  }
3107 
3109  if (Record.size() != 1) {
3110  Error("invalid pragma optimize record");
3111  return Failure;
3112  }
3113  OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3114  break;
3115 
3117  for (unsigned I = 0, N = Record.size(); I != N; ++I)
3118  UnusedLocalTypedefNameCandidates.push_back(
3119  getGlobalDeclID(F, Record[I]));
3120  break;
3121  }
3122  }
3123 }
3124 
3126 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3127  const ModuleFile *ImportedBy,
3128  unsigned ClientLoadCapabilities) {
3129  unsigned Idx = 0;
3130  F.ModuleMapPath = ReadPath(F, Record, Idx);
3131 
3132  if (F.Kind == MK_ExplicitModule) {
3133  // For an explicitly-loaded module, we don't care whether the original
3134  // module map file exists or matches.
3135  return Success;
3136  }
3137 
3138  // Try to resolve ModuleName in the current header search context and
3139  // verify that it is found in the same module map file as we saved. If the
3140  // top-level AST file is a main file, skip this check because there is no
3141  // usable header search context.
3142  assert(!F.ModuleName.empty() &&
3143  "MODULE_NAME should come before MODULE_MAP_FILE");
3144  if (F.Kind == MK_ImplicitModule &&
3145  (*ModuleMgr.begin())->Kind != MK_MainFile) {
3146  // An implicitly-loaded module file should have its module listed in some
3147  // module map file that we've already loaded.
3148  Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
3149  auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3150  const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3151  if (!ModMap) {
3152  assert(ImportedBy && "top-level import should be verified");
3153  if ((ClientLoadCapabilities & ARR_Missing) == 0)
3154  Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
3155  << ImportedBy->FileName
3156  << F.ModuleMapPath;
3157  return Missing;
3158  }
3159 
3160  assert(M->Name == F.ModuleName && "found module with different name");
3161 
3162  // Check the primary module map file.
3163  const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3164  if (StoredModMap == nullptr || StoredModMap != ModMap) {
3165  assert(ModMap && "found module is missing module map file");
3166  assert(ImportedBy && "top-level import should be verified");
3167  if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3168  Diag(diag::err_imported_module_modmap_changed)
3169  << F.ModuleName << ImportedBy->FileName
3170  << ModMap->getName() << F.ModuleMapPath;
3171  return OutOfDate;
3172  }
3173 
3174  llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3175  for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3176  // FIXME: we should use input files rather than storing names.
3177  std::string Filename = ReadPath(F, Record, Idx);
3178  const FileEntry *F =
3179  FileMgr.getFile(Filename, false, false);
3180  if (F == nullptr) {
3181  if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3182  Error("could not find file '" + Filename +"' referenced by AST file");
3183  return OutOfDate;
3184  }
3185  AdditionalStoredMaps.insert(F);
3186  }
3187 
3188  // Check any additional module map files (e.g. module.private.modulemap)
3189  // that are not in the pcm.
3190  if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3191  for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3192  // Remove files that match
3193  // Note: SmallPtrSet::erase is really remove
3194  if (!AdditionalStoredMaps.erase(ModMap)) {
3195  if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3196  Diag(diag::err_module_different_modmap)
3197  << F.ModuleName << /*new*/0 << ModMap->getName();
3198  return OutOfDate;
3199  }
3200  }
3201  }
3202 
3203  // Check any additional module map files that are in the pcm, but not
3204  // found in header search. Cases that match are already removed.
3205  for (const FileEntry *ModMap : AdditionalStoredMaps) {
3206  if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3207  Diag(diag::err_module_different_modmap)
3208  << F.ModuleName << /*not new*/1 << ModMap->getName();
3209  return OutOfDate;
3210  }
3211  }
3212 
3213  if (Listener)
3214  Listener->ReadModuleMapFile(F.ModuleMapPath);
3215  return Success;
3216 }
3217 
3218 
3219 /// \brief Move the given method to the back of the global list of methods.
3221  // Find the entry for this selector in the method pool.
3222  Sema::GlobalMethodPool::iterator Known
3223  = S.MethodPool.find(Method->getSelector());
3224  if (Known == S.MethodPool.end())
3225  return;
3226 
3227  // Retrieve the appropriate method list.
3228  ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3229  : Known->second.second;
3230  bool Found = false;
3231  for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
3232  if (!Found) {
3233  if (List->getMethod() == Method) {
3234  Found = true;
3235  } else {
3236  // Keep searching.
3237  continue;
3238  }
3239  }
3240 
3241  if (List->getNext())
3242  List->setMethod(List->getNext()->getMethod());
3243  else
3244  List->setMethod(Method);
3245  }
3246 }
3247 
3248 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
3249  assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
3250  for (Decl *D : Names) {
3251  bool wasHidden = D->Hidden;
3252  D->Hidden = false;
3253 
3254  if (wasHidden && SemaObj) {
3255  if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3256  moveMethodToBackOfGlobalList(*SemaObj, Method);
3257  }
3258  }
3259  }
3260 }
3261 
3263  Module::NameVisibilityKind NameVisibility,
3264  SourceLocation ImportLoc) {
3265  llvm::SmallPtrSet<Module *, 4> Visited;
3267  Stack.push_back(Mod);
3268  while (!Stack.empty()) {
3269  Mod = Stack.pop_back_val();
3270 
3271  if (NameVisibility <= Mod->NameVisibility) {
3272  // This module already has this level of visibility (or greater), so
3273  // there is nothing more to do.
3274  continue;
3275  }
3276 
3277  if (!Mod->isAvailable()) {
3278  // Modules that aren't available cannot be made visible.
3279  continue;
3280  }
3281 
3282  // Update the module's name visibility.
3283  Mod->NameVisibility = NameVisibility;
3284 
3285  // If we've already deserialized any names from this module,
3286  // mark them as visible.
3287  HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3288  if (Hidden != HiddenNamesMap.end()) {
3289  auto HiddenNames = std::move(*Hidden);
3290  HiddenNamesMap.erase(Hidden);
3291  makeNamesVisible(HiddenNames.second, HiddenNames.first);
3292  assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3293  "making names visible added hidden names");
3294  }
3295 
3296  // Push any exported modules onto the stack to be marked as visible.
3297  SmallVector<Module *, 16> Exports;
3298  Mod->getExportedModules(Exports);
3300  I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3301  Module *Exported = *I;
3302  if (Visited.insert(Exported).second)
3303  Stack.push_back(Exported);
3304  }
3305  }
3306 }
3307 
3309  if (GlobalIndex)
3310  return false;
3311 
3312  if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3313  !Context.getLangOpts().Modules)
3314  return true;
3315 
3316  // Try to load the global index.
3317  TriedLoadingGlobalIndex = true;
3318  StringRef ModuleCachePath
3319  = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3320  std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
3321  = GlobalModuleIndex::readIndex(ModuleCachePath);
3322  if (!Result.first)
3323  return true;
3324 
3325  GlobalIndex.reset(Result.first);
3326  ModuleMgr.setGlobalIndex(GlobalIndex.get());
3327  return false;
3328 }
3329 
3331  return Context.getLangOpts().Modules && UseGlobalIndex &&
3332  !hasGlobalIndex() && TriedLoadingGlobalIndex;
3333 }
3334 
3336  // Overwrite the timestamp file contents so that file's mtime changes.
3337  std::string TimestampFilename = MF.getTimestampFilename();
3338  std::error_code EC;
3339  llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3340  if (EC)
3341  return;
3342  OS << "Timestamp file\n";
3343 }
3344 
3345 ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3346  ModuleKind Type,
3347  SourceLocation ImportLoc,
3348  unsigned ClientLoadCapabilities) {
3350  SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3351 
3352  // Defer any pending actions until we get to the end of reading the AST file.
3353  Deserializing AnASTFile(this);
3354 
3355  // Bump the generation number.
3356  unsigned PreviousGeneration = incrementGeneration(Context);
3357 
3358  unsigned NumModules = ModuleMgr.size();
3360  switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3361  /*ImportedBy=*/nullptr, Loaded,
3362  0, 0, 0,
3363  ClientLoadCapabilities)) {
3364  case Failure:
3365  case Missing:
3366  case OutOfDate:
3367  case VersionMismatch:
3368  case ConfigurationMismatch:
3369  case HadErrors: {
3370  llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3371  for (const ImportedModule &IM : Loaded)
3372  LoadedSet.insert(IM.Mod);
3373 
3374  ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3375  LoadedSet,
3376  Context.getLangOpts().Modules
3377  ? &PP.getHeaderSearchInfo().getModuleMap()
3378  : nullptr);
3379 
3380  // If we find that any modules are unusable, the global index is going
3381  // to be out-of-date. Just remove it.
3382  GlobalIndex.reset();
3383  ModuleMgr.setGlobalIndex(nullptr);
3384  return ReadResult;
3385  }
3386  case Success:
3387  break;
3388  }
3389 
3390  // Here comes stuff that we only do once the entire chain is loaded.
3391 
3392  // Load the AST blocks of all of the modules that we loaded.
3393  for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3394  MEnd = Loaded.end();
3395  M != MEnd; ++M) {
3396  ModuleFile &F = *M->Mod;
3397 
3398  // Read the AST block.
3399  if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3400  return Result;
3401 
3402  // Once read, set the ModuleFile bit base offset and update the size in
3403  // bits of all files we've seen.
3404  F.GlobalBitOffset = TotalModulesSizeInBits;
3405  TotalModulesSizeInBits += F.SizeInBits;
3406  GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3407 
3408  // Preload SLocEntries.
3409  for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3410  int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3411  // Load it through the SourceManager and don't call ReadSLocEntry()
3412  // directly because the entry may have already been loaded in which case
3413  // calling ReadSLocEntry() directly would trigger an assertion in
3414  // SourceManager.
3415  SourceMgr.getLoadedSLocEntryByID(Index);
3416  }
3417  }
3418 
3419  // Setup the import locations and notify the module manager that we've
3420  // committed to these module files.
3421  for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3422  MEnd = Loaded.end();
3423  M != MEnd; ++M) {
3424  ModuleFile &F = *M->Mod;
3425 
3426  ModuleMgr.moduleFileAccepted(&F);
3427 
3428  // Set the import location.
3429  F.DirectImportLoc = ImportLoc;
3430  if (!M->ImportedBy)
3431  F.ImportLoc = M->ImportLoc;
3432  else
3433  F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3434  M->ImportLoc.getRawEncoding());
3435  }
3436 
3437  // Mark all of the identifiers in the identifier table as being out of date,
3438  // so that various accessors know to check the loaded modules when the
3439  // identifier is used.
3440  for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3441  IdEnd = PP.getIdentifierTable().end();
3442  Id != IdEnd; ++Id)
3443  Id->second->setOutOfDate(true);
3444 
3445  // Resolve any unresolved module exports.
3446  for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3447  UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
3448  SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3449  Module *ResolvedMod = getSubmodule(GlobalID);
3450 
3451  switch (Unresolved.Kind) {
3452  case UnresolvedModuleRef::Conflict:
3453  if (ResolvedMod) {
3454  Module::Conflict Conflict;
3455  Conflict.Other = ResolvedMod;
3456  Conflict.Message = Unresolved.String.str();
3457  Unresolved.Mod->Conflicts.push_back(Conflict);
3458  }
3459  continue;
3460 
3461  case UnresolvedModuleRef::Import:
3462  if (ResolvedMod)
3463  Unresolved.Mod->Imports.insert(ResolvedMod);
3464  continue;
3465 
3466  case UnresolvedModuleRef::Export:
3467  if (ResolvedMod || Unresolved.IsWildcard)
3468  Unresolved.Mod->Exports.push_back(
3469  Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3470  continue;
3471  }
3472  }
3473  UnresolvedModuleRefs.clear();
3474 
3475  // FIXME: How do we load the 'use'd modules? They may not be submodules.
3476  // Might be unnecessary as use declarations are only used to build the
3477  // module itself.
3478 
3479  InitializeContext();
3480 
3481  if (SemaObj)
3482  UpdateSema();
3483 
3484  if (DeserializationListener)
3485  DeserializationListener->ReaderInitialized(this);
3486 
3487  ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3488  if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3489  PrimaryModule.OriginalSourceFileID
3490  = FileID::get(PrimaryModule.SLocEntryBaseID
3491  + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3492 
3493  // If this AST file is a precompiled preamble, then set the
3494  // preamble file ID of the source manager to the file source file
3495  // from which the preamble was built.
3496  if (Type == MK_Preamble) {
3498  } else if (Type == MK_MainFile) {
3500  }
3501  }
3502 
3503  // For any Objective-C class definitions we have already loaded, make sure
3504  // that we load any additional categories.
3505  for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3506  loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3507  ObjCClassesLoaded[I],
3508  PreviousGeneration);
3509  }
3510 
3511  if (PP.getHeaderSearchInfo()
3512  .getHeaderSearchOpts()
3513  .ModulesValidateOncePerBuildSession) {
3514  // Now we are certain that the module and all modules it depends on are
3515  // up to date. Create or update timestamp files for modules that are
3516  // located in the module cache (not for PCH files that could be anywhere
3517  // in the filesystem).
3518  for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3519  ImportedModule &M = Loaded[I];
3520  if (M.Mod->Kind == MK_ImplicitModule) {
3521  updateModuleTimestamp(*M.Mod);
3522  }
3523  }
3524  }
3525 
3526  return Success;
3527 }
3528 
3529 static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
3530 
3531 /// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3532 static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3533  return Stream.Read(8) == 'C' &&
3534  Stream.Read(8) == 'P' &&
3535  Stream.Read(8) == 'C' &&
3536  Stream.Read(8) == 'H';
3537 }
3538 
3540 ASTReader::ReadASTCore(StringRef FileName,
3541  ModuleKind Type,
3542  SourceLocation ImportLoc,
3543  ModuleFile *ImportedBy,
3545  off_t ExpectedSize, time_t ExpectedModTime,
3546  ASTFileSignature ExpectedSignature,
3547  unsigned ClientLoadCapabilities) {
3548  ModuleFile *M;
3549  std::string ErrorStr;
3551  = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3552  getGeneration(), ExpectedSize, ExpectedModTime,
3553  ExpectedSignature, readASTFileSignature,
3554  M, ErrorStr);
3555 
3556  switch (AddResult) {
3558  return Success;
3559 
3561  // Load module file below.
3562  break;
3563 
3565  // The module file was missing; if the client can handle that, return
3566  // it.
3567  if (ClientLoadCapabilities & ARR_Missing)
3568  return Missing;
3569 
3570  // Otherwise, return an error.
3571  {
3572  std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3573  + ErrorStr;
3574  Error(Msg);
3575  }
3576  return Failure;
3577 
3579  // We couldn't load the module file because it is out-of-date. If the
3580  // client can handle out-of-date, return it.
3581  if (ClientLoadCapabilities & ARR_OutOfDate)
3582  return OutOfDate;
3583 
3584  // Otherwise, return an error.
3585  {
3586  std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3587  + ErrorStr;
3588  Error(Msg);
3589  }
3590  return Failure;
3591  }
3592 
3593  assert(M && "Missing module file");
3594 
3595  // FIXME: This seems rather a hack. Should CurrentDir be part of the
3596  // module?
3597  if (FileName != "-") {
3598  CurrentDir = llvm::sys::path::parent_path(FileName);
3599  if (CurrentDir.empty()) CurrentDir = ".";
3600  }
3601 
3602  ModuleFile &F = *M;
3603  BitstreamCursor &Stream = F.Stream;
3604  PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
3605  Stream.init(&F.StreamFile);
3606  F.SizeInBits = F.Buffer->getBufferSize() * 8;
3607 
3608  // Sniff for the signature.
3609  if (!startsWithASTFileMagic(Stream)) {
3610  Diag(diag::err_not_a_pch_file) << FileName;
3611  return Failure;
3612  }
3613 
3614  // This is used for compatibility with older PCH formats.
3615  bool HaveReadControlBlock = false;
3616 
3617  while (1) {
3618  llvm::BitstreamEntry Entry = Stream.advance();
3619 
3620  switch (Entry.Kind) {
3622  case llvm::BitstreamEntry::EndBlock:
3623  case llvm::BitstreamEntry::Record:
3624  Error("invalid record at top-level of AST file");
3625  return Failure;
3626 
3627  case llvm::BitstreamEntry::SubBlock:
3628  break;
3629  }
3630 
3631  // We only know the control subblock ID.
3632  switch (Entry.ID) {
3633  case llvm::bitc::BLOCKINFO_BLOCK_ID:
3634  if (Stream.ReadBlockInfoBlock()) {
3635  Error("malformed BlockInfoBlock in AST file");
3636  return Failure;
3637  }
3638  break;
3639  case CONTROL_BLOCK_ID:
3640  HaveReadControlBlock = true;
3641  switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
3642  case Success:
3643  break;
3644 
3645  case Failure: return Failure;
3646  case Missing: return Missing;
3647  case OutOfDate: return OutOfDate;
3648  case VersionMismatch: return VersionMismatch;
3649  case ConfigurationMismatch: return ConfigurationMismatch;
3650  case HadErrors: return HadErrors;
3651  }
3652  break;
3653  case AST_BLOCK_ID:
3654  if (!HaveReadControlBlock) {
3655  if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3656  Diag(diag::err_pch_version_too_old);
3657  return VersionMismatch;
3658  }
3659 
3660  // Record that we've loaded this module.
3661  Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3662  return Success;
3663 
3664  default:
3665  if (Stream.SkipBlock()) {
3666  Error("malformed block record in AST file");
3667  return Failure;
3668  }
3669  break;
3670  }
3671  }
3672 
3673  return Success;
3674 }
3675 
3677  // If there's a listener, notify them that we "read" the translation unit.
3678  if (DeserializationListener)
3679  DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3681 
3682  // FIXME: Find a better way to deal with collisions between these
3683  // built-in types. Right now, we just ignore the problem.
3684 
3685  // Load the special types.
3686  if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3687  if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3688  if (!Context.CFConstantStringTypeDecl)
3689  Context.setCFConstantStringType(GetType(String));
3690  }
3691 
3692  if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3693  QualType FileType = GetType(File);
3694  if (FileType.isNull()) {
3695  Error("FILE type is NULL");
3696  return;
3697  }
3698 
3699  if (!Context.FILEDecl) {
3700  if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3701  Context.setFILEDecl(Typedef->getDecl());
3702  else {
3703  const TagType *Tag = FileType->getAs<TagType>();
3704  if (!Tag) {
3705  Error("Invalid FILE type in AST file");
3706  return;
3707  }
3708  Context.setFILEDecl(Tag->getDecl());
3709  }
3710  }
3711  }
3712 
3713  if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3714  QualType Jmp_bufType = GetType(Jmp_buf);
3715  if (Jmp_bufType.isNull()) {
3716  Error("jmp_buf type is NULL");
3717  return;
3718  }
3719 
3720  if (!Context.jmp_bufDecl) {
3721  if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3722  Context.setjmp_bufDecl(Typedef->getDecl());
3723  else {
3724  const TagType *Tag = Jmp_bufType->getAs<TagType>();
3725  if (!Tag) {
3726  Error("Invalid jmp_buf type in AST file");
3727  return;
3728  }
3729  Context.setjmp_bufDecl(Tag->getDecl());
3730  }
3731  }
3732  }
3733 
3734  if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3735  QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3736  if (Sigjmp_bufType.isNull()) {
3737  Error("sigjmp_buf type is NULL");
3738  return;
3739  }
3740 
3741  if (!Context.sigjmp_bufDecl) {
3742  if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3743  Context.setsigjmp_bufDecl(Typedef->getDecl());
3744  else {
3745  const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3746  assert(Tag && "Invalid sigjmp_buf type in AST file");
3748  }
3749  }
3750  }
3751 
3752  if (unsigned ObjCIdRedef
3753  = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3754  if (Context.ObjCIdRedefinitionType.isNull())
3755  Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3756  }
3757 
3758  if (unsigned ObjCClassRedef
3759  = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3760  if (Context.ObjCClassRedefinitionType.isNull())
3761  Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3762  }
3763 
3764  if (unsigned ObjCSelRedef
3765  = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3766  if (Context.ObjCSelRedefinitionType.isNull())
3767  Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3768  }
3769 
3770  if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3771  QualType Ucontext_tType = GetType(Ucontext_t);
3772  if (Ucontext_tType.isNull()) {
3773  Error("ucontext_t type is NULL");
3774  return;
3775  }
3776 
3777  if (!Context.ucontext_tDecl) {
3778  if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3779  Context.setucontext_tDecl(Typedef->getDecl());
3780  else {
3781  const TagType *Tag = Ucontext_tType->getAs<TagType>();
3782  assert(Tag && "Invalid ucontext_t type in AST file");
3784  }
3785  }
3786  }
3787  }
3788 
3789  ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3790 
3791  // If there were any CUDA special declarations, deserialize them.
3792  if (!CUDASpecialDeclRefs.empty()) {
3793  assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3795  cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3796  }
3797 
3798  // Re-export any modules that were imported by a non-module AST file.
3799  // FIXME: This does not make macro-only imports visible again.
3800  for (auto &Import : ImportedModules) {
3801  if (Module *Imported = getSubmodule(Import.ID)) {
3802  makeModuleVisible(Imported, Module::AllVisible,
3803  /*ImportLoc=*/Import.ImportLoc);
3804  PP.makeModuleVisible(Imported, Import.ImportLoc);
3805  }
3806  }
3807  ImportedModules.clear();
3808 }
3809 
3811  // Nothing to do for now.
3812 }
3813 
3814 /// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3815 /// cursor into the start of the given block ID, returning false on success and
3816 /// true on failure.
3817 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3818  while (1) {
3819  llvm::BitstreamEntry Entry = Cursor.advance();
3820  switch (Entry.Kind) {
3822  case llvm::BitstreamEntry::EndBlock:
3823  return true;
3824 
3825  case llvm::BitstreamEntry::Record:
3826  // Ignore top-level records.
3827  Cursor.skipRecord(Entry.ID);
3828  break;
3829 
3830  case llvm::BitstreamEntry::SubBlock:
3831  if (Entry.ID == BlockID) {
3832  if (Cursor.EnterSubBlock(BlockID))
3833  return true;
3834  // Found it!
3835  return false;
3836  }
3837 
3838  if (Cursor.SkipBlock())
3839  return true;
3840  }
3841  }
3842 }
3843 
3844 /// \brief Reads and return the signature record from \p StreamFile's control
3845 /// block, or else returns 0.
3846 static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
3847  BitstreamCursor Stream(StreamFile);
3848  if (!startsWithASTFileMagic(Stream))
3849  return 0;
3850 
3851  // Scan for the CONTROL_BLOCK_ID block.
3852  if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3853  return 0;
3854 
3855  // Scan for SIGNATURE inside the control block.
3856  ASTReader::RecordData Record;
3857  while (1) {
3858  llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3859  if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
3860  Entry.Kind != llvm::BitstreamEntry::Record)
3861  return 0;
3862 
3863  Record.clear();
3864  StringRef Blob;
3865  if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
3866  return Record[0];
3867  }
3868 }
3869 
3870 /// \brief Retrieve the name of the original source file name
3871 /// directly from the AST file, without actually loading the AST
3872 /// file.
3874  const std::string &ASTFileName, FileManager &FileMgr,
3875  const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
3876  // Open the AST file.
3877  auto Buffer = FileMgr.getBufferForFile(ASTFileName);
3878  if (!Buffer) {
3879  Diags.Report(diag::err_fe_unable_to_read_pch_file)
3880  << ASTFileName << Buffer.getError().message();
3881  return std::string();
3882  }
3883 
3884  // Initialize the stream
3885  llvm::BitstreamReader StreamFile;
3886  PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
3887  BitstreamCursor Stream(StreamFile);
3888 
3889  // Sniff for the signature.
3890  if (!startsWithASTFileMagic(Stream)) {
3891  Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3892  return std::string();
3893  }
3894 
3895  // Scan for the CONTROL_BLOCK_ID block.
3896  if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
3897  Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3898  return std::string();
3899  }
3900 
3901  // Scan for ORIGINAL_FILE inside the control block.
3902  RecordData Record;
3903  while (1) {
3904  llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3905  if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3906  return std::string();
3907 
3908  if (Entry.Kind != llvm::BitstreamEntry::Record) {
3909  Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3910  return std::string();
3911  }
3912 
3913  Record.clear();
3914  StringRef Blob;
3915  if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3916  return Blob.str();
3917  }
3918 }
3919 
3920 namespace {
3921  class SimplePCHValidator : public ASTReaderListener {
3922  const LangOptions &ExistingLangOpts;
3923  const TargetOptions &ExistingTargetOpts;
3924  const PreprocessorOptions &ExistingPPOpts;
3925  std::string ExistingModuleCachePath;
3926  FileManager &FileMgr;
3927 
3928  public:
3929  SimplePCHValidator(const LangOptions &ExistingLangOpts,
3930  const TargetOptions &ExistingTargetOpts,
3931  const PreprocessorOptions &ExistingPPOpts,
3932  StringRef ExistingModuleCachePath,
3933  FileManager &FileMgr)
3934  : ExistingLangOpts(ExistingLangOpts),
3935  ExistingTargetOpts(ExistingTargetOpts),
3936  ExistingPPOpts(ExistingPPOpts),
3937  ExistingModuleCachePath(ExistingModuleCachePath),
3938  FileMgr(FileMgr)
3939  {
3940  }
3941 
3942  bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
3943  bool AllowCompatibleDifferences) override {
3944  return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
3945  AllowCompatibleDifferences);
3946  }
3947  bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
3948  bool AllowCompatibleDifferences) override {
3949  return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
3950  AllowCompatibleDifferences);
3951  }
3952  bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
3953  StringRef SpecificModuleCachePath,
3954  bool Complain) override {
3955  return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
3956  ExistingModuleCachePath,
3957  nullptr, ExistingLangOpts);
3958  }
3959  bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3960  bool Complain,
3961  std::string &SuggestedPredefines) override {
3962  return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
3963  SuggestedPredefines, ExistingLangOpts);
3964  }
3965  };
3966 }
3967 
3969  StringRef Filename, FileManager &FileMgr,
3970  const PCHContainerReader &PCHContainerRdr,
3971  ASTReaderListener &Listener) {
3972  // Open the AST file.
3973  // FIXME: This allows use of the VFS; we do not allow use of the
3974  // VFS when actually loading a module.
3975  auto Buffer = FileMgr.getBufferForFile(Filename);
3976  if (!Buffer) {
3977  return true;
3978  }
3979 
3980  // Initialize the stream
3981  llvm::BitstreamReader StreamFile;
3982  PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
3983  BitstreamCursor Stream(StreamFile);
3984 
3985  // Sniff for the signature.
3986  if (!startsWithASTFileMagic(Stream))
3987  return true;
3988 
3989  // Scan for the CONTROL_BLOCK_ID block.
3990  if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3991  return true;
3992 
3993  bool NeedsInputFiles = Listener.needsInputFileVisitation();
3994  bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
3995  bool NeedsImports = Listener.needsImportVisitation();
3996  BitstreamCursor InputFilesCursor;
3997  if (NeedsInputFiles) {
3998  InputFilesCursor = Stream;
3999  if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
4000  return true;
4001 
4002  // Read the abbreviations
4003  while (true) {
4004  uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
4005  unsigned Code = InputFilesCursor.ReadCode();
4006 
4007  // We expect all abbrevs to be at the start of the block.
4008  if (Code != llvm::bitc::DEFINE_ABBREV) {
4009  InputFilesCursor.JumpToBit(Offset);
4010  break;
4011  }
4012  InputFilesCursor.ReadAbbrevRecord();
4013  }
4014  }
4015 
4016  // Scan for ORIGINAL_FILE inside the control block.
4017  RecordData Record;
4018  std::string ModuleDir;
4019  while (1) {
4020  llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4021  if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4022  return false;
4023 
4024  if (Entry.Kind != llvm::BitstreamEntry::Record)
4025  return true;
4026 
4027  Record.clear();
4028  StringRef Blob;
4029  unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4030  switch ((ControlRecordTypes)RecCode) {
4031  case METADATA: {
4032  if (Record[0] != VERSION_MAJOR)
4033  return true;
4034 
4035  if (Listener.ReadFullVersionInformation(Blob))
4036  return true;
4037 
4038  break;
4039  }
4040  case MODULE_NAME:
4041  Listener.ReadModuleName(Blob);
4042  break;
4043  case MODULE_DIRECTORY:
4044  ModuleDir = Blob;
4045  break;
4046  case MODULE_MAP_FILE: {
4047  unsigned Idx = 0;
4048  auto Path = ReadString(Record, Idx);
4049  ResolveImportedPath(Path, ModuleDir);
4050  Listener.ReadModuleMapFile(Path);
4051  break;
4052  }
4053  case LANGUAGE_OPTIONS:
4054  if (ParseLanguageOptions(Record, false, Listener,
4055  /*AllowCompatibleConfigurationMismatch*/false))
4056  return true;
4057  break;
4058 
4059  case TARGET_OPTIONS:
4060  if (ParseTargetOptions(Record, false, Listener,
4061  /*AllowCompatibleConfigurationMismatch*/ false))
4062  return true;
4063  break;
4064 
4065  case DIAGNOSTIC_OPTIONS:
4066  if (ParseDiagnosticOptions(Record, false, Listener))
4067  return true;
4068  break;
4069 
4070  case FILE_SYSTEM_OPTIONS:
4071  if (ParseFileSystemOptions(Record, false, Listener))
4072  return true;
4073  break;
4074 
4075  case HEADER_SEARCH_OPTIONS:
4076  if (ParseHeaderSearchOptions(Record, false, Listener))
4077  return true;
4078  break;
4079 
4080  case PREPROCESSOR_OPTIONS: {
4081  std::string IgnoredSuggestedPredefines;
4082  if (ParsePreprocessorOptions(Record, false, Listener,
4083  IgnoredSuggestedPredefines))
4084  return true;
4085  break;
4086  }
4087 
4088  case INPUT_FILE_OFFSETS: {
4089  if (!NeedsInputFiles)
4090  break;
4091 
4092  unsigned NumInputFiles = Record[0];
4093  unsigned NumUserFiles = Record[1];
4094  const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
4095  for (unsigned I = 0; I != NumInputFiles; ++I) {
4096  // Go find this input file.
4097  bool isSystemFile = I >= NumUserFiles;
4098 
4099  if (isSystemFile && !NeedsSystemInputFiles)
4100  break; // the rest are system input files
4101 
4102  BitstreamCursor &Cursor = InputFilesCursor;
4103  SavedStreamPosition SavedPosition(Cursor);
4104  Cursor.JumpToBit(InputFileOffs[I]);
4105 
4106  unsigned Code = Cursor.ReadCode();
4107  RecordData Record;
4108  StringRef Blob;
4109  bool shouldContinue = false;
4110  switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4111  case INPUT_FILE:
4112  bool Overridden = static_cast<bool>(Record[3]);
4113  std::string Filename = Blob;
4114  ResolveImportedPath(Filename, ModuleDir);
4115  shouldContinue =
4116  Listener.visitInputFile(Filename, isSystemFile, Overridden);
4117  break;
4118  }
4119  if (!shouldContinue)
4120  break;
4121  }
4122  break;
4123  }
4124 
4125  case IMPORTS: {
4126  if (!NeedsImports)
4127  break;
4128 
4129  unsigned Idx = 0, N = Record.size();
4130  while (Idx < N) {
4131  // Read information about the AST file.
4132  Idx += 5; // ImportLoc, Size, ModTime, Signature
4133  std::string Filename = ReadString(Record, Idx);
4134  ResolveImportedPath(Filename, ModuleDir);
4135  Listener.visitImport(Filename);
4136  }
4137  break;
4138  }
4139 
4140  case KNOWN_MODULE_FILES: {
4141  // Known-but-not-technically-used module files are treated as imports.
4142  if (!NeedsImports)
4143  break;
4144 
4145  unsigned Idx = 0, N = Record.size();
4146  while (Idx < N) {
4147  std::string Filename = ReadString(Record, Idx);
4148  ResolveImportedPath(Filename, ModuleDir);
4149  Listener.visitImport(Filename);
4150  }
4151  break;
4152  }
4153 
4154  default:
4155  // No other validation to perform.
4156  break;
4157  }
4158  }
4159 }
4160 
4162  StringRef Filename, FileManager &FileMgr,
4163  const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
4164  const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4165  std::string ExistingModuleCachePath) {
4166  SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4167  ExistingModuleCachePath, FileMgr);
4168  return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
4169  validator);
4170 }
4171 
4173 ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
4174  // Enter the submodule block.
4175  if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4176  Error("malformed submodule block record in AST file");
4177  return Failure;
4178  }
4179 
4180  ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4181  bool First = true;
4182  Module *CurrentModule = nullptr;
4183  RecordData Record;
4184  while (true) {
4185  llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4186 
4187  switch (Entry.Kind) {
4188  case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4190  Error("malformed block record in AST file");
4191  return Failure;
4192  case llvm::BitstreamEntry::EndBlock:
4193  return Success;
4194  case llvm::BitstreamEntry::Record:
4195  // The interesting case.
4196  break;
4197  }
4198 
4199  // Read a record.
4200  StringRef Blob;
4201  Record.clear();
4202  auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4203 
4204  if ((Kind == SUBMODULE_METADATA) != First) {
4205  Error("submodule metadata record should be at beginning of block");
4206  return Failure;
4207  }
4208  First = false;
4209 
4210  // Submodule information is only valid if we have a current module.
4211  // FIXME: Should we error on these cases?
4212  if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4214  continue;
4215 
4216  switch (Kind) {
4217  default: // Default behavior: ignore.
4218  break;
4219 
4220  case SUBMODULE_DEFINITION: {
4221  if (Record.size() < 8) {
4222  Error("malformed module definition");
4223  return Failure;
4224  }
4225 
4226  StringRef Name = Blob;
4227  unsigned Idx = 0;
4228  SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4229  SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4230  bool IsFramework = Record[Idx++];
4231  bool IsExplicit = Record[Idx++];
4232  bool IsSystem = Record[Idx++];
4233  bool IsExternC = Record[Idx++];
4234  bool InferSubmodules = Record[Idx++];
4235  bool InferExplicitSubmodules = Record[Idx++];
4236  bool InferExportWildcard = Record[Idx++];
4237  bool ConfigMacrosExhaustive = Record[Idx++];
4238 
4239  Module *ParentModule = nullptr;
4240  if (Parent)
4241  ParentModule = getSubmodule(Parent);
4242 
4243  // Retrieve this (sub)module from the module map, creating it if
4244  // necessary.
4245  CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
4246  IsExplicit).first;
4247 
4248  // FIXME: set the definition loc for CurrentModule, or call
4249  // ModMap.setInferredModuleAllowedBy()
4250 
4251  SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4252  if (GlobalIndex >= SubmodulesLoaded.size() ||
4253  SubmodulesLoaded[GlobalIndex]) {
4254  Error("too many submodules");
4255  return Failure;
4256  }
4257 
4258  if (!ParentModule) {
4259  if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4260  if (CurFile != F.File) {
4261  if (!Diags.isDiagnosticInFlight()) {
4262  Diag(diag::err_module_file_conflict)
4263  << CurrentModule->getTopLevelModuleName()
4264  << CurFile->getName()
4265  << F.File->getName();
4266  }
4267  return Failure;
4268  }
4269  }
4270 
4271  CurrentModule->setASTFile(F.File);
4272  }
4273 
4274  CurrentModule->Signature = F.Signature;
4275  CurrentModule->IsFromModuleFile = true;
4276  CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
4277  CurrentModule->IsExternC = IsExternC;
4278  CurrentModule->InferSubmodules = InferSubmodules;
4279  CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4280  CurrentModule->InferExportWildcard = InferExportWildcard;
4281  CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
4282  if (DeserializationListener)
4283  DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4284 
4285  SubmodulesLoaded[GlobalIndex] = CurrentModule;
4286 
4287  // Clear out data that will be replaced by what is the module file.
4288  CurrentModule->LinkLibraries.clear();
4289  CurrentModule->ConfigMacros.clear();
4290  CurrentModule->UnresolvedConflicts.clear();
4291  CurrentModule->Conflicts.clear();
4292  break;
4293  }
4294 
4296  std::string Filename = Blob;
4297  ResolveImportedPath(F, Filename);
4298  if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
4299  if (!CurrentModule->getUmbrellaHeader())
4300  ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4301  else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
4302  // This can be a spurious difference caused by changing the VFS to
4303  // point to a different copy of the file, and it is too late to
4304  // to rebuild safely.
4305  // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4306  // after input file validation only real problems would remain and we
4307  // could just error. For now, assume it's okay.
4308  break;
4309  }
4310  }
4311  break;
4312  }
4313 
4314  case SUBMODULE_HEADER:
4317  // We lazily associate headers with their modules via the HeaderInfo table.
4318  // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4319  // of complete filenames or remove it entirely.
4320  break;
4321 
4324  // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4325  // them here.
4326  break;
4327 
4328  case SUBMODULE_TOPHEADER: {
4329  CurrentModule->addTopHeaderFilename(Blob);
4330  break;
4331  }
4332 
4333  case SUBMODULE_UMBRELLA_DIR: {
4334  std::string Dirname = Blob;
4335  ResolveImportedPath(F, Dirname);
4336  if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
4337  if (!CurrentModule->getUmbrellaDir())
4338  ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4339  else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
4340  if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4341  Error("mismatched umbrella directories in submodule");
4342  return OutOfDate;
4343  }
4344  }
4345  break;
4346  }
4347 
4348  case SUBMODULE_METADATA: {
4349  F.BaseSubmoduleID = getTotalNumSubmodules();
4350  F.LocalNumSubmodules = Record[0];
4351  unsigned LocalBaseSubmoduleID = Record[1];
4352  if (F.LocalNumSubmodules > 0) {
4353  // Introduce the global -> local mapping for submodules within this
4354  // module.
4355  GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4356 
4357  // Introduce the local -> global mapping for submodules within this
4358  // module.
4359  F.SubmoduleRemap.insertOrReplace(
4360  std::make_pair(LocalBaseSubmoduleID,
4361  F.BaseSubmoduleID - LocalBaseSubmoduleID));
4362 
4363  SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4364  }
4365  break;
4366  }
4367 
4368  case SUBMODULE_IMPORTS: {
4369  for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
4370  UnresolvedModuleRef Unresolved;
4371  Unresolved.File = &F;
4372  Unresolved.Mod = CurrentModule;
4373  Unresolved.ID = Record[Idx];
4374  Unresolved.Kind = UnresolvedModuleRef::Import;
4375  Unresolved.IsWildcard = false;
4376  UnresolvedModuleRefs.push_back(Unresolved);
4377  }
4378  break;
4379  }
4380 
4381  case SUBMODULE_EXPORTS: {
4382  for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
4383  UnresolvedModuleRef Unresolved;
4384  Unresolved.File = &F;
4385  Unresolved.Mod = CurrentModule;
4386  Unresolved.ID = Record[Idx];
4387  Unresolved.Kind = UnresolvedModuleRef::Export;
4388  Unresolved.IsWildcard = Record[Idx + 1];
4389  UnresolvedModuleRefs.push_back(Unresolved);
4390  }
4391 
4392  // Once we've loaded the set of exports, there's no reason to keep
4393  // the parsed, unresolved exports around.
4394  CurrentModule->UnresolvedExports.clear();
4395  break;
4396  }
4397  case SUBMODULE_REQUIRES: {
4398  CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
4400  break;
4401  }
4402 
4404  CurrentModule->LinkLibraries.push_back(
4405  Module::LinkLibrary(Blob, Record[0]));
4406  break;
4407 
4409  CurrentModule->ConfigMacros.push_back(Blob.str());
4410  break;
4411 
4412  case SUBMODULE_CONFLICT: {
4413  UnresolvedModuleRef Unresolved;
4414  Unresolved.File = &F;
4415  Unresolved.Mod = CurrentModule;
4416  Unresolved.ID = Record[0];
4417  Unresolved.Kind = UnresolvedModuleRef::Conflict;
4418  Unresolved.IsWildcard = false;
4419  Unresolved.String = Blob;
4420  UnresolvedModuleRefs.push_back(Unresolved);
4421  break;
4422  }
4423  }
4424  }
4425 }
4426 
4427 /// \brief Parse the record that corresponds to a LangOptions data
4428 /// structure.
4429 ///
4430 /// This routine parses the language options from the AST file and then gives
4431 /// them to the AST listener if one is set.
4432 ///
4433 /// \returns true if the listener deems the file unacceptable, false otherwise.
4434 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4435  bool Complain,
4436  ASTReaderListener &Listener,
4437  bool AllowCompatibleDifferences) {
4438  LangOptions LangOpts;
4439  unsigned Idx = 0;
4440 #define LANGOPT(Name, Bits, Default, Description) \
4441  LangOpts.Name = Record[Idx++];
4442 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4443  LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4444 #include "clang/Basic/LangOptions.def"
4445 #define SANITIZER(NAME, ID) \
4446  LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
4447 #include "clang/Basic/Sanitizers.def"
4448 
4449  for (unsigned N = Record[Idx++]; N; --N)
4450  LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4451 
4452  ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4453  VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4454  LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4455 
4456  LangOpts.CurrentModule = ReadString(Record, Idx);
4457 
4458  // Comment options.
4459  for (unsigned N = Record[Idx++]; N; --N) {
4460  LangOpts.CommentOpts.BlockCommandNames.push_back(
4461  ReadString(Record, Idx));
4462  }
4463  LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
4464 
4465  return Listener.ReadLanguageOptions(LangOpts, Complain,
4466  AllowCompatibleDifferences);
4467 }
4468 
4469 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4470  ASTReaderListener &Listener,
4471  bool AllowCompatibleDifferences) {
4472  unsigned Idx = 0;
4473  TargetOptions TargetOpts;
4474  TargetOpts.Triple = ReadString(Record, Idx);
4475  TargetOpts.CPU = ReadString(Record, Idx);
4476  TargetOpts.ABI = ReadString(Record, Idx);
4477  for (unsigned N = Record[Idx++]; N; --N) {
4478  TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4479  }
4480  for (unsigned N = Record[Idx++]; N; --N) {
4481  TargetOpts.Features.push_back(ReadString(Record, Idx));
4482  }
4483 
4484  return Listener.ReadTargetOptions(TargetOpts, Complain,
4485  AllowCompatibleDifferences);
4486 }
4487 
4488 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4489  ASTReaderListener &Listener) {
4491  unsigned Idx = 0;
4492 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
4493 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4494  DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
4495 #include "clang/Basic/DiagnosticOptions.def"
4496 
4497  for (unsigned N = Record[Idx++]; N; --N)
4498  DiagOpts->Warnings.push_back(ReadString(Record, Idx));
4499  for (unsigned N = Record[Idx++]; N; --N)
4500  DiagOpts->Remarks.push_back(ReadString(Record, Idx));
4501 
4502  return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4503 }
4504 
4505 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4506  ASTReaderListener &Listener) {
4507  FileSystemOptions FSOpts;
4508  unsigned Idx = 0;
4509  FSOpts.WorkingDir = ReadString(Record, Idx);
4510  return Listener.ReadFileSystemOptions(FSOpts, Complain);
4511 }
4512 
4513 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4514  bool Complain,
4515  ASTReaderListener &Listener) {
4516  HeaderSearchOptions HSOpts;
4517  unsigned Idx = 0;
4518  HSOpts.Sysroot = ReadString(Record, Idx);
4519 
4520  // Include entries.
4521  for (unsigned N = Record[Idx++]; N; --N) {
4522  std::string Path = ReadString(Record, Idx);
4524  = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
4525  bool IsFramework = Record[Idx++];
4526  bool IgnoreSysRoot = Record[Idx++];
4527  HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4528  IgnoreSysRoot);
4529  }
4530 
4531  // System header prefixes.
4532  for (unsigned N = Record[Idx++]; N; --N) {
4533  std::string Prefix = ReadString(Record, Idx);
4534  bool IsSystemHeader = Record[Idx++];
4535  HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
4536  }
4537 
4538  HSOpts.ResourceDir = ReadString(Record, Idx);
4539  HSOpts.ModuleCachePath = ReadString(Record, Idx);
4540  HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
4541  HSOpts.DisableModuleHash = Record[Idx++];
4542  HSOpts.UseBuiltinIncludes = Record[Idx++];
4543  HSOpts.UseStandardSystemIncludes = Record[Idx++];
4544  HSOpts.UseStandardCXXIncludes = Record[Idx++];
4545  HSOpts.UseLibcxx = Record[Idx++];
4546  std::string SpecificModuleCachePath = ReadString(Record, Idx);
4547 
4548  return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4549  Complain);
4550 }
4551 
4552 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4553  bool Complain,
4554  ASTReaderListener &Listener,
4555  std::string &SuggestedPredefines) {
4556  PreprocessorOptions PPOpts;
4557  unsigned Idx = 0;
4558 
4559  // Macro definitions/undefs
4560  for (unsigned N = Record[Idx++]; N; --N) {
4561  std::string Macro = ReadString(Record, Idx);
4562  bool IsUndef = Record[Idx++];
4563  PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4564  }
4565 
4566  // Includes
4567  for (unsigned N = Record[Idx++]; N; --N) {
4568  PPOpts.Includes.push_back(ReadString(Record, Idx));
4569  }
4570 
4571  // Macro Includes
4572  for (unsigned N = Record[Idx++]; N; --N) {
4573  PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4574  }
4575 
4576  PPOpts.UsePredefines = Record[Idx++];
4577  PPOpts.DetailedRecord = Record[Idx++];
4578  PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4579  PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4580  PPOpts.ObjCXXARCStandardLibrary =
4581  static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4582  SuggestedPredefines.clear();
4583  return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4584  SuggestedPredefines);
4585 }
4586 
4587 std::pair<ModuleFile *, unsigned>
4588 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4589  GlobalPreprocessedEntityMapType::iterator
4590  I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4591  assert(I != GlobalPreprocessedEntityMap.end() &&
4592  "Corrupted global preprocessed entity map");
4593  ModuleFile *M = I->second;
4594  unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4595  return std::make_pair(M, LocalIndex);
4596 }
4597 
4598 llvm::iterator_range<PreprocessingRecord::iterator>
4599 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4600  if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4601  return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4603 
4604  return llvm::make_range(PreprocessingRecord::iterator(),
4606 }
4607 
4608 llvm::iterator_range<ASTReader::ModuleDeclIterator>
4609 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4610  return llvm::make_range(
4611  ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4612  ModuleDeclIterator(this, &Mod,
4613  Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4614 }
4615 
4617  PreprocessedEntityID PPID = Index+1;
4618  std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4619  ModuleFile &M = *PPInfo.first;
4620  unsigned LocalIndex = PPInfo.second;
4621  const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4622 
4623  if (!PP.getPreprocessingRecord()) {
4624  Error("no preprocessing record");
4625  return nullptr;
4626  }
4627 
4629  M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4630 
4631  llvm::BitstreamEntry Entry =
4632  M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4633  if (Entry.Kind != llvm::BitstreamEntry::Record)
4634  return nullptr;
4635 
4636  // Read the record.
4637  SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4638  ReadSourceLocation(M, PPOffs.End));
4639  PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
4640  StringRef Blob;
4641  RecordData Record;
4644  Entry.ID, Record, &Blob);
4645  switch (RecType) {
4646  case PPD_MACRO_EXPANSION: {
4647  bool isBuiltin = Record[0];
4648  IdentifierInfo *Name = nullptr;
4649  MacroDefinitionRecord *Def = nullptr;
4650  if (isBuiltin)
4651  Name = getLocalIdentifier(M, Record[1]);
4652  else {
4653  PreprocessedEntityID GlobalID =
4654  getGlobalPreprocessedEntityID(M, Record[1]);
4655  Def = cast<MacroDefinitionRecord>(
4656  PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
4657  }
4658 
4659  MacroExpansion *ME;
4660  if (isBuiltin)
4661  ME = new (PPRec) MacroExpansion(Name, Range);
4662  else
4663  ME = new (PPRec) MacroExpansion(Def, Range);
4664 
4665  return ME;
4666  }
4667 
4668  case PPD_MACRO_DEFINITION: {
4669  // Decode the identifier info and then check again; if the macro is
4670  // still defined and associated with the identifier,
4671  IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4672  MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
4673 
4674  if (DeserializationListener)
4675  DeserializationListener->MacroDefinitionRead(PPID, MD);
4676 
4677  return MD;
4678  }
4679 
4680  case PPD_INCLUSION_DIRECTIVE: {
4681  const char *FullFileNameStart = Blob.data() + Record[0];
4682  StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
4683  const FileEntry *File = nullptr;
4684  if (!FullFileName.empty())
4685  File = PP.getFileManager().getFile(FullFileName);
4686 
4687  // FIXME: Stable encoding
4689  = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4690  InclusionDirective *ID
4691  = new (PPRec) InclusionDirective(PPRec, Kind,
4692  StringRef(Blob.data(), Record[0]),
4693  Record[1], Record[3],
4694  File,
4695  Range);
4696  return ID;
4697  }
4698  }
4699 
4700  llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4701 }
4702 
4703 /// \brief \arg SLocMapI points at a chunk of a module that contains no
4704 /// preprocessed entities or the entities it contains are not the ones we are
4705 /// looking for. Find the next module that contains entities and return the ID
4706 /// of the first entry.
4707 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4708  GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4709  ++SLocMapI;
4710  for (GlobalSLocOffsetMapType::const_iterator
4711  EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4712  ModuleFile &M = *SLocMapI->second;
4713  if (M.NumPreprocessedEntities)
4714  return M.BasePreprocessedEntityID;
4715  }
4716 
4717  return getTotalNumPreprocessedEntities();
4718 }
4719 
4720 namespace {
4721 
4722 template <unsigned PPEntityOffset::*PPLoc>
4723 struct PPEntityComp {
4724  const ASTReader &Reader;
4725  ModuleFile &M;
4726 
4727  PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4728 
4729  bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4730  SourceLocation LHS = getLoc(L);
4731  SourceLocation RHS = getLoc(R);
4732  return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4733  }
4734 
4735  bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4736  SourceLocation LHS = getLoc(L);
4737  return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4738  }
4739 
4740  bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4741  SourceLocation RHS = getLoc(R);
4742  return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4743  }
4744 
4745  SourceLocation getLoc(const PPEntityOffset &PPE) const {
4746  return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4747  }
4748 };
4749 
4750 }
4751 
4752 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
4753  bool EndsAfter) const {
4755  return getTotalNumPreprocessedEntities();
4756 
4757  GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
4758  SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
4759  assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4760  "Corrupted global sloc offset map");
4761 
4762  if (SLocMapI->second->NumPreprocessedEntities == 0)
4763  return findNextPreprocessedEntity(SLocMapI);
4764 
4765  ModuleFile &M = *SLocMapI->second;
4766  typedef const PPEntityOffset *pp_iterator;
4767  pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4768  pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4769 
4770  size_t Count = M.NumPreprocessedEntities;
4771  size_t Half;
4772  pp_iterator First = pp_begin;
4773  pp_iterator PPI;
4774 
4775  if (EndsAfter) {
4776  PPI = std::upper_bound(pp_begin, pp_end, Loc,
4777  PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4778  } else {
4779  // Do a binary search manually instead of using std::lower_bound because
4780  // The end locations of entities may be unordered (when a macro expansion
4781  // is inside another macro argument), but for this case it is not important
4782  // whether we get the first macro expansion or its containing macro.
4783  while (Count > 0) {
4784  Half = Count / 2;
4785  PPI = First;
4786  std::advance(PPI, Half);
4787  if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4788  Loc)) {
4789  First = PPI;
4790  ++First;
4791  Count = Count - Half - 1;
4792  } else
4793  Count = Half;
4794  }
4795  }
4796 
4797  if (PPI == pp_end)
4798  return findNextPreprocessedEntity(SLocMapI);
4799 
4800  return M.BasePreprocessedEntityID + (PPI - pp_begin);
4801 }
4802 
4803 /// \brief Returns a pair of [Begin, End) indices of preallocated
4804 /// preprocessed entities that \arg Range encompasses.
4805 std::pair<unsigned, unsigned>
4807  if (Range.isInvalid())
4808  return std::make_pair(0,0);
4809  assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4810 
4811  PreprocessedEntityID BeginID =
4812  findPreprocessedEntity(Range.getBegin(), false);
4813  PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
4814  return std::make_pair(BeginID, EndID);
4815 }
4816 
4817 /// \brief Optionally returns true or false if the preallocated preprocessed
4818 /// entity with index \arg Index came from file \arg FID.
4820  FileID FID) {
4821  if (FID.isInvalid())
4822  return false;
4823 
4824  std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4825  ModuleFile &M = *PPInfo.first;
4826  unsigned LocalIndex = PPInfo.second;
4827  const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4828 
4829  SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4830  if (Loc.isInvalid())
4831  return false;
4832 
4833  if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4834  return true;
4835  else
4836  return false;
4837 }
4838 
4839 namespace {
4840  /// \brief Visitor used to search for information about a header file.
4841  class HeaderFileInfoVisitor {
4842  const FileEntry *FE;
4843 
4845 
4846  public:
4847  explicit HeaderFileInfoVisitor(const FileEntry *FE)
4848  : FE(FE) { }
4849 
4850  static bool visit(ModuleFile &M, void *UserData) {
4851  HeaderFileInfoVisitor *This
4852  = static_cast<HeaderFileInfoVisitor *>(UserData);
4853 
4855  = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4856  if (!Table)
4857  return false;
4858 
4859  // Look in the on-disk hash table for an entry for this file name.
4860  HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
4861  if (Pos == Table->end())
4862  return false;
4863 
4864  This->HFI = *Pos;
4865  return true;
4866  }
4867 
4868  Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
4869  };
4870 }
4871 
4873  HeaderFileInfoVisitor Visitor(FE);
4874  ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
4875  if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
4876  return *HFI;
4877 
4878  return HeaderFileInfo();
4879 }
4880 
4882  // FIXME: Make it work properly with modules.
4884  for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4885  ModuleFile &F = *(*I);
4886  unsigned Idx = 0;
4887  DiagStates.clear();
4888  assert(!Diag.DiagStates.empty());
4889  DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4890  while (Idx < F.PragmaDiagMappings.size()) {
4891  SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4892  unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4893  if (DiagStateID != 0) {
4894  Diag.DiagStatePoints.push_back(
4895  DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4896  FullSourceLoc(Loc, SourceMgr)));
4897  continue;
4898  }
4899 
4900  assert(DiagStateID == 0);
4901  // A new DiagState was created here.
4902  Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4903  DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4904  DiagStates.push_back(NewState);
4905  Diag.DiagStatePoints.push_back(
4906  DiagnosticsEngine::DiagStatePoint(NewState,
4907  FullSourceLoc(Loc, SourceMgr)));
4908  while (1) {
4909  assert(Idx < F.PragmaDiagMappings.size() &&
4910  "Invalid data, didn't find '-1' marking end of diag/map pairs");
4911  if (Idx >= F.PragmaDiagMappings.size()) {
4912  break; // Something is messed up but at least avoid infinite loop in
4913  // release build.
4914  }
4915  unsigned DiagID = F.PragmaDiagMappings[Idx++];
4916  if (DiagID == (unsigned)-1) {
4917  break; // no more diag/map pairs for this location.
4918  }
4920  DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
4921  Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
4922  }
4923  }
4924  }
4925 }
4926 
4927 /// \brief Get the correct cursor and offset for loading a type.
4928 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4929  GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4930  assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4931  ModuleFile *M = I->second;
4932  return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4933 }
4934 
4935 /// \brief Read and return the type with the given index..
4936 ///
4937 /// The index is the type ID, shifted and minus the number of predefs. This
4938 /// routine actually reads the record corresponding to the type at the given
4939 /// location. It is a helper routine for GetType, which deals with reading type
4940 /// IDs.
4941 QualType ASTReader::readTypeRecord(unsigned Index) {
4942  RecordLocation Loc = TypeCursorForIndex(Index);
4943  BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
4944 
4945  // Keep track of where we are in the stream, then jump back there
4946  // after reading this type.
4947  SavedStreamPosition SavedPosition(DeclsCursor);
4948 
4949  ReadingKindTracker ReadingKind(Read_Type, *this);
4950 
4951  // Note that we are loading a type record.
4952  Deserializing AType(this);
4953 
4954  unsigned Idx = 0;
4955  DeclsCursor.JumpToBit(Loc.Offset);
4956  RecordData Record;
4957  unsigned Code = DeclsCursor.ReadCode();
4958  switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
4959  case TYPE_EXT_QUAL: {
4960  if (Record.size() != 2) {
4961  Error("Incorrect encoding of extended qualifier type");
4962  return QualType();
4963  }
4964  QualType Base = readType(*Loc.F, Record, Idx);
4965  Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4966  return Context.getQualifiedType(Base, Quals);
4967  }
4968 
4969  case TYPE_COMPLEX: {
4970  if (Record.size() != 1) {
4971  Error("Incorrect encoding of complex type");
4972  return QualType();
4973  }
4974  QualType ElemType = readType(*Loc.F, Record, Idx);
4975  return Context.getComplexType(ElemType);
4976  }
4977 
4978  case TYPE_POINTER: {
4979  if (Record.size() != 1) {
4980  Error("Incorrect encoding of pointer type");
4981  return QualType();
4982  }
4983  QualType PointeeType = readType(*Loc.F, Record, Idx);
4984  return Context.getPointerType(PointeeType);
4985  }
4986 
4987  case TYPE_DECAYED: {
4988  if (Record.size() != 1) {
4989  Error("Incorrect encoding of decayed type");
4990  return QualType();
4991  }
4992  QualType OriginalType = readType(*Loc.F, Record, Idx);
4993  QualType DT = Context.getAdjustedParameterType(OriginalType);
4994  if (!isa<DecayedType>(DT))
4995  Error("Decayed type does not decay");
4996  return DT;
4997  }
4998 
4999  case TYPE_ADJUSTED: {
5000  if (Record.size() != 2) {
5001  Error("Incorrect encoding of adjusted type");
5002  return QualType();
5003  }
5004  QualType OriginalTy = readType(*Loc.F, Record, Idx);
5005  QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5006  return Context.getAdjustedType(OriginalTy, AdjustedTy);
5007  }
5008 
5009  case TYPE_BLOCK_POINTER: {
5010  if (Record.size() != 1) {
5011  Error("Incorrect encoding of block pointer type");
5012  return QualType();
5013  }
5014  QualType PointeeType = readType(*Loc.F, Record, Idx);
5015  return Context.getBlockPointerType(PointeeType);
5016  }
5017 
5018  case TYPE_LVALUE_REFERENCE: {
5019  if (Record.size() != 2) {
5020  Error("Incorrect encoding of lvalue reference type");
5021  return QualType();
5022  }
5023  QualType PointeeType = readType(*Loc.F, Record, Idx);
5024  return Context.getLValueReferenceType(PointeeType, Record[1]);
5025  }
5026 
5027  case TYPE_RVALUE_REFERENCE: {
5028  if (Record.size() != 1) {
5029  Error("Incorrect encoding of rvalue reference type");
5030  return QualType();
5031  }
5032  QualType PointeeType = readType(*Loc.F, Record, Idx);
5033  return Context.getRValueReferenceType(PointeeType);
5034  }
5035 
5036  case TYPE_MEMBER_POINTER: {
5037  if (Record.size() != 2) {
5038  Error("Incorrect encoding of member pointer type");
5039  return QualType();
5040  }
5041  QualType PointeeType = readType(*Loc.F, Record, Idx);
5042  QualType ClassType = readType(*Loc.F, Record, Idx);
5043  if (PointeeType.isNull() || ClassType.isNull())
5044  return QualType();
5045 
5046  return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5047  }
5048 
5049  case TYPE_CONSTANT_ARRAY: {
5050  QualType ElementType = readType(*Loc.F, Record, Idx);
5052  unsigned IndexTypeQuals = Record[2];
5053  unsigned Idx = 3;
5054  llvm::APInt Size = ReadAPInt(Record, Idx);
5055  return Context.getConstantArrayType(ElementType, Size,
5056  ASM, IndexTypeQuals);
5057  }
5058 
5059  case TYPE_INCOMPLETE_ARRAY: {
5060  QualType ElementType = readType(*Loc.F, Record, Idx);
5062  unsigned IndexTypeQuals = Record[2];
5063  return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5064  }
5065 
5066  case TYPE_VARIABLE_ARRAY: {
5067  QualType ElementType = readType(*Loc.F, Record, Idx);
5069  unsigned IndexTypeQuals = Record[2];
5070  SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5071  SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5072  return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5073  ASM, IndexTypeQuals,
5074  SourceRange(LBLoc, RBLoc));
5075  }
5076 
5077  case TYPE_VECTOR: {
5078  if (Record.size() != 3) {
5079  Error("incorrect encoding of vector type in AST file");
5080  return QualType();
5081  }
5082 
5083  QualType ElementType = readType(*Loc.F, Record, Idx);
5084  unsigned NumElements = Record[1];
5085  unsigned VecKind = Record[2];
5086  return Context.getVectorType(ElementType, NumElements,
5087  (VectorType::VectorKind)VecKind);
5088  }
5089 
5090  case TYPE_EXT_VECTOR: {
5091  if (Record.size() != 3) {
5092  Error("incorrect encoding of extended vector type in AST file");
5093  return QualType();
5094  }
5095 
5096  QualType ElementType = readType(*Loc.F, Record, Idx);
5097  unsigned NumElements = Record[1];
5098  return Context.getExtVectorType(ElementType, NumElements);
5099  }
5100 
5101  case TYPE_FUNCTION_NO_PROTO: {
5102  if (Record.size() != 6) {
5103  Error("incorrect encoding of no-proto function type");
5104  return QualType();
5105  }
5106  QualType ResultType = readType(*Loc.F, Record, Idx);
5107  FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5108  (CallingConv)Record[4], Record[5]);
5109  return Context.getFunctionNoProtoType(ResultType, Info);
5110  }
5111 
5112  case TYPE_FUNCTION_PROTO: {
5113  QualType ResultType = readType(*Loc.F, Record, Idx);
5114 
5116  EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5117  /*hasregparm*/ Record[2],
5118  /*regparm*/ Record[3],
5119  static_cast<CallingConv>(Record[4]),
5120  /*produces*/ Record[5]);
5121 
5122  unsigned Idx = 6;
5123 
5124  EPI.Variadic = Record[Idx++];
5125  EPI.HasTrailingReturn = Record[Idx++];
5126  EPI.TypeQuals = Record[Idx++];
5127  EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
5128  SmallVector<QualType, 8> ExceptionStorage;
5129  readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
5130 
5131  unsigned NumParams = Record[Idx++];
5132  SmallVector<QualType, 16> ParamTypes;
5133  for (unsigned I = 0; I != NumParams; ++I)
5134  ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5135 
5136  return Context.getFunctionType(ResultType, ParamTypes, EPI);
5137  }
5138 
5139  case TYPE_UNRESOLVED_USING: {
5140  unsigned Idx = 0;
5141  return Context.getTypeDeclType(
5142  ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5143  }
5144 
5145  case TYPE_TYPEDEF: {
5146  if (Record.size() != 2) {
5147  Error("incorrect encoding of typedef type");
5148  return QualType();
5149  }
5150  unsigned Idx = 0;
5151  TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5152  QualType Canonical = readType(*Loc.F, Record, Idx);
5153  if (!Canonical.isNull())
5154  Canonical = Context.getCanonicalType(Canonical);
5155  return Context.getTypedefType(Decl, Canonical);
5156  }
5157 
5158  case TYPE_TYPEOF_EXPR:
5159  return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5160 
5161  case TYPE_TYPEOF: {
5162  if (Record.size() != 1) {
5163  Error("incorrect encoding of typeof(type) in AST file");
5164  return QualType();
5165  }
5166  QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5167  return Context.getTypeOfType(UnderlyingType);
5168  }
5169 
5170  case TYPE_DECLTYPE: {
5171  QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5172  return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5173  }
5174 
5175  case TYPE_UNARY_TRANSFORM: {
5176  QualType BaseType = readType(*Loc.F, Record, Idx);
5177  QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5179  return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5180  }
5181 
5182  case TYPE_AUTO: {
5183  QualType Deduced = readType(*Loc.F, Record, Idx);
5184  bool IsDecltypeAuto = Record[Idx++];
5185  bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5186  return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
5187  }
5188 
5189  case TYPE_RECORD: {
5190  if (Record.size() != 2) {
5191  Error("incorrect encoding of record type");
5192  return QualType();
5193  }
5194  unsigned Idx = 0;
5195  bool IsDependent = Record[Idx++];
5196  RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5197  RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5198  QualType T = Context.getRecordType(RD);
5199  const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5200  return T;
5201  }
5202 
5203  case TYPE_ENUM: {
5204  if (Record.size() != 2) {
5205  Error("incorrect encoding of enum type");
5206  return QualType();
5207  }
5208  unsigned Idx = 0;
5209  bool IsDependent = Record[Idx++];
5210  QualType T
5211  = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5212  const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5213  return T;
5214  }
5215 
5216  case TYPE_ATTRIBUTED: {
5217  if (Record.size() != 3) {
5218  Error("incorrect encoding of attributed type");
5219  return QualType();
5220  }
5221  QualType modifiedType = readType(*Loc.F, Record, Idx);
5222  QualType equivalentType = readType(*Loc.F, Record, Idx);
5223  AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5224  return Context.getAttributedType(kind, modifiedType, equivalentType);
5225  }
5226 
5227  case TYPE_PAREN: {
5228  if (Record.size() != 1) {
5229  Error("incorrect encoding of paren type");
5230  return QualType();
5231  }
5232  QualType InnerType = readType(*Loc.F, Record, Idx);
5233  return Context.getParenType(InnerType);
5234  }
5235 
5236  case TYPE_PACK_EXPANSION: {
5237  if (Record.size() != 2) {
5238  Error("incorrect encoding of pack expansion type");
5239  return QualType();
5240  }
5241  QualType Pattern = readType(*Loc.F, Record, Idx);
5242  if (Pattern.isNull())
5243  return QualType();
5244  Optional<unsigned> NumExpansions;
5245  if (Record[1])
5246  NumExpansions = Record[1] - 1;
5247  return Context.getPackExpansionType(Pattern, NumExpansions);
5248  }
5249 
5250  case TYPE_ELABORATED: {
5251  unsigned Idx = 0;
5252  ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5253  NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5254  QualType NamedType = readType(*Loc.F, Record, Idx);
5255  return Context.getElaboratedType(Keyword, NNS, NamedType);
5256  }
5257 
5258  case TYPE_OBJC_INTERFACE: {
5259  unsigned Idx = 0;
5260  ObjCInterfaceDecl *ItfD
5261  = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5263  }
5264 
5265  case TYPE_OBJC_OBJECT: {
5266  unsigned Idx = 0;
5267  QualType Base = readType(*Loc.F, Record, Idx);
5268  unsigned NumTypeArgs = Record[Idx++];
5269  SmallVector<QualType, 4> TypeArgs;
5270  for (unsigned I = 0; I != NumTypeArgs; ++I)
5271  TypeArgs.push_back(readType(*Loc.F, Record, Idx));
5272  unsigned NumProtos = Record[Idx++];
5274  for (unsigned I = 0; I != NumProtos; ++I)
5275  Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5276  bool IsKindOf = Record[Idx++];
5277  return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
5278  }
5279 
5280  case TYPE_OBJC_OBJECT_POINTER: {
5281  unsigned Idx = 0;
5282  QualType Pointee = readType(*Loc.F, Record, Idx);
5283  return Context.getObjCObjectPointerType(Pointee);
5284  }
5285 
5287  unsigned Idx = 0;
5288  QualType Parm = readType(*Loc.F, Record, Idx);
5289  QualType Replacement = readType(*Loc.F, Record, Idx);
5291  cast<TemplateTypeParmType>(Parm),
5292  Context.getCanonicalType(Replacement));
5293  }
5294 
5296  unsigned Idx = 0;
5297  QualType Parm = readType(*Loc.F, Record, Idx);
5298  TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5300  cast<TemplateTypeParmType>(Parm),
5301  ArgPack);
5302  }
5303 
5304  case TYPE_INJECTED_CLASS_NAME: {
5305  CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5306  QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5307  // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5308  // for AST reading, too much interdependencies.
5309  const Type *T = nullptr;
5310  for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5311  if (const Type *Existing = DI->getTypeForDecl()) {
5312  T = Existing;
5313  break;
5314  }
5315  }
5316  if (!T) {
5317  T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
5318  for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5319  DI->setTypeForDecl(T);
5320  }
5321  return QualType(T, 0);
5322  }
5323 
5324  case TYPE_TEMPLATE_TYPE_PARM: {
5325  unsigned Idx = 0;
5326  unsigned Depth = Record[Idx++];
5327  unsigned Index = Record[Idx++];
5328  bool Pack = Record[Idx++];
5330  = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5331  return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5332  }
5333 
5334  case TYPE_DEPENDENT_NAME: {
5335  unsigned Idx = 0;
5336  ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5337  NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5338  const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5339  QualType Canon = readType(*Loc.F, Record, Idx);
5340  if (!Canon.isNull())
5341  Canon = Context.getCanonicalType(Canon);
5342  return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5343  }
5344 
5346  unsigned Idx = 0;
5347  ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5348  NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5349  const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5350  unsigned NumArgs = Record[Idx++];
5352  Args.reserve(NumArgs);
5353  while (NumArgs--)
5354  Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5355  return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5356  Args.size(), Args.data());
5357  }
5358 
5360  unsigned Idx = 0;
5361 
5362  // ArrayType
5363  QualType ElementType = readType(*Loc.F, Record, Idx);
5365  = (ArrayType::ArraySizeModifier)Record[Idx++];
5366  unsigned IndexTypeQuals = Record[Idx++];
5367 
5368  // DependentSizedArrayType
5369  Expr *NumElts = ReadExpr(*Loc.F);
5370  SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5371 
5372  return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5373  IndexTypeQuals, Brackets);
5374  }
5375 
5377  unsigned Idx = 0;
5378  bool IsDependent = Record[Idx++];
5379  TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5381  ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5382  QualType Underlying = readType(*Loc.F, Record, Idx);
5383  QualType T;
5384  if (Underlying.isNull())
5385  T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5386  Args.size());
5387  else
5388  T = Context.getTemplateSpecializationType(Name, Args.data(),
5389  Args.size(), Underlying);
5390  const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5391  return T;
5392  }
5393 
5394  case TYPE_ATOMIC: {
5395  if (Record.size() != 1) {
5396  Error("Incorrect encoding of atomic type");
5397  return QualType();
5398  }
5399  QualType ValueType = readType(*Loc.F, Record, Idx);
5400  return Context.getAtomicType(ValueType);
5401  }
5402  }
5403  llvm_unreachable("Invalid TypeCode!");
5404 }
5405 
5406 void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5407  SmallVectorImpl<QualType> &Exceptions,
5409  const RecordData &Record, unsigned &Idx) {
5411  static_cast<ExceptionSpecificationType>(Record[Idx++]);
5412  ESI.Type = EST;
5413  if (EST == EST_Dynamic) {
5414  for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
5415  Exceptions.push_back(readType(ModuleFile, Record, Idx));
5416  ESI.Exceptions = Exceptions;
5417  } else if (EST == EST_ComputedNoexcept) {
5418  ESI.NoexceptExpr = ReadExpr(ModuleFile);
5419  } else if (EST == EST_Uninstantiated) {
5420  ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5421  ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5422  } else if (EST == EST_Unevaluated) {
5423  ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5424  }
5425 }
5426 
5427 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5428  ASTReader &Reader;
5429  ModuleFile &F;
5430  const ASTReader::RecordData &Record;
5431  unsigned &Idx;
5432 
5433  SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5434  unsigned &I) {
5435  return Reader.ReadSourceLocation(F, R, I);
5436  }
5437 
5438  template<typename T>
5439  T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5440  return Reader.ReadDeclAs<T>(F, Record, Idx);
5441  }
5442 
5443 public:
5444  TypeLocReader(ASTReader &Reader, ModuleFile &F,
5445  const ASTReader::RecordData &Record, unsigned &Idx)
5446  : Reader(Reader), F(F), Record(Record), Idx(Idx)
5447  { }
5448 
5449  // We want compile-time assurance that we've enumerated all of
5450  // these, so unfortunately we have to declare them first, then
5451  // define them out-of-line.
5452 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5453 #define TYPELOC(CLASS, PARENT) \
5454  void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5455 #include "clang/AST/TypeLocNodes.def"
5456 
5457  void VisitFunctionTypeLoc(FunctionTypeLoc);
5458  void VisitArrayTypeLoc(ArrayTypeLoc);
5459 };
5460 
5461 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5462  // nothing to do
5463 }
5464 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5465  TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5466  if (TL.needsExtraLocalData()) {
5467  TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5468  TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5469  TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5470  TL.setModeAttr(Record[Idx++]);
5471  }
5472 }
5473 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5474  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5475 }
5476 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5477  TL.setStarLoc(ReadSourceLocation(Record, Idx));
5478 }
5479 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5480  // nothing to do
5481 }
5482 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5483  // nothing to do
5484 }
5485 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5486  TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5487 }
5488 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5489  TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5490 }
5491 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5492  TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5493 }
5494 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5495  TL.setStarLoc(ReadSourceLocation(Record, Idx));
5496  TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5497 }
5499  TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5500  TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5501  if (Record[Idx++])
5502  TL.setSizeExpr(Reader.ReadExpr(F));
5503  else
5504  TL.setSizeExpr(nullptr);
5505 }
5506 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5507  VisitArrayTypeLoc(TL);
5508 }
5509 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5510  VisitArrayTypeLoc(TL);
5511 }
5512 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5513  VisitArrayTypeLoc(TL);
5514 }
5515 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5517  VisitArrayTypeLoc(TL);
5518 }
5519 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5521  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5522 }
5523 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5524  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5525 }
5526 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5527  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5528 }
5530  TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5531  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5532  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5533  TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
5534  for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5535  TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
5536  }
5537 }
5538 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5539  VisitFunctionTypeLoc(TL);
5540 }
5541 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5542  VisitFunctionTypeLoc(TL);
5543 }
5544 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5545  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5546 }
5547 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5548  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5549 }
5550 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5551  TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5552  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5553  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5554 }
5555 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5556  TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5557  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5558  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5559  TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5560 }
5561 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5562  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5563 }
5564 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5565  TL.setKWLoc(ReadSourceLocation(Record, Idx));
5566  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5567  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5568  TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5569 }
5570 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5571  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5572 }
5573 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5574  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5575 }
5576 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5577  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5578 }
5579 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5580  TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5581  if (TL.hasAttrOperand()) {
5582  SourceRange range;
5583  range.setBegin(ReadSourceLocation(Record, Idx));
5584  range.setEnd(ReadSourceLocation(Record, Idx));
5585  TL.setAttrOperandParensRange(range);
5586  }
5587  if (TL.hasAttrExprOperand()) {
5588  if (Record[Idx++])
5589  TL.setAttrExprOperand(Reader.ReadExpr(F));
5590  else
5591  TL.setAttrExprOperand(nullptr);
5592  } else if (TL.hasAttrEnumOperand())
5593  TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5594 }
5595 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5596  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5597 }
5598 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5600  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5601 }
5602 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5604  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5605 }
5606 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5608  TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5609  TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5610  TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5611  TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5612  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5613  TL.setArgLocInfo(i,
5614  Reader.GetTemplateArgumentLocInfo(F,
5615  TL.getTypePtr()->getArg(i).getKind(),
5616  Record, Idx));
5617 }
5618 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5619  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5620  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5621 }
5622 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5623  TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5624  TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5625 }
5626 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5627  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5628 }
5629 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5630  TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5631  TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5632  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5633 }
5634 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5636  TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5637  TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5638  TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5639  TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5640  TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5641  TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5642  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5643  TL.setArgLocInfo(I,
5644  Reader.GetTemplateArgumentLocInfo(F,
5645  TL.getTypePtr()->getArg(I).getKind(),
5646  Record, Idx));
5647 }
5648 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5649  TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5650 }
5651 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5652  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5653 }
5654 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5655  TL.setHasBaseTypeAsWritten(Record[Idx++]);
5656  TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
5657  TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
5658  for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
5659  TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
5660  TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
5661  TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
5662  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5663  TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5664 }
5665 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5666  TL.setStarLoc(ReadSourceLocation(Record, Idx));
5667 }
5668 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5669  TL.setKWLoc(ReadSourceLocation(Record, Idx));
5670  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5671  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5672 }
5673 
5675  const RecordData &Record,
5676  unsigned &Idx) {
5677  QualType InfoTy = readType(F, Record, Idx);
5678  if (InfoTy.isNull())
5679  return nullptr;
5680 
5681  TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5682  TypeLocReader TLR(*this, F, Record, Idx);
5683  for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5684  TLR.Visit(TL);
5685  return TInfo;
5686 }
5687 
5689  unsigned FastQuals = ID & Qualifiers::FastMask;
5690  unsigned Index = ID >> Qualifiers::FastWidth;
5691 
5692  if (Index < NUM_PREDEF_TYPE_IDS) {
5693  QualType T;
5694  switch ((PredefinedTypeIDs)Index) {
5695  case PREDEF_TYPE_NULL_ID: return QualType();
5696  case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5697  case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5698 
5699  case PREDEF_TYPE_CHAR_U_ID:
5700  case PREDEF_TYPE_CHAR_S_ID:
5701  // FIXME: Check that the signedness of CharTy is correct!
5702  T = Context.CharTy;
5703  break;
5704 
5705  case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
5707  case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
5708  case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
5711  case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
5712  case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
5713  case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
5714  case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
5715  case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
5716  case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
5717  case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
5718  case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
5719  case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
5720  case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
5722  case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
5725  case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
5726  case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
5727  case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
5728  case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
5729  case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
5730  case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
5733  case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
5736  case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
5738  case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
5739  case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
5740  case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
5742 
5745  break;
5746 
5749  break;
5750 
5752  T = Context.getVaListTagType();
5753  break;
5754 
5756  T = Context.BuiltinFnTy;
5757  break;
5758  }
5759 
5760  assert(!T.isNull() && "Unknown predefined type");
5761  return T.withFastQualifiers(FastQuals);
5762  }
5763 
5764  Index -= NUM_PREDEF_TYPE_IDS;
5765  assert(Index < TypesLoaded.size() && "Type index out-of-range");
5766  if (TypesLoaded[Index].isNull()) {
5767  TypesLoaded[Index] = readTypeRecord(Index);
5768  if (TypesLoaded[Index].isNull())
5769  return QualType();
5770 
5771  TypesLoaded[Index]->setFromAST();
5772  if (DeserializationListener)
5773  DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5774  TypesLoaded[Index]);
5775  }
5776 
5777  return TypesLoaded[Index].withFastQualifiers(FastQuals);
5778 }
5779 
5780 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5781  return GetType(getGlobalTypeID(F, LocalID));
5782 }
5783 
5785 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5786  unsigned FastQuals = LocalID & Qualifiers::FastMask;
5787  unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5788 
5789  if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5790  return LocalID;
5791 
5793  = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5794  assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5795 
5796  unsigned GlobalIndex = LocalIndex + I->second;
5797  return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5798 }
5799 
5803  const RecordData &Record,
5804  unsigned &Index) {
5805  switch (Kind) {
5807  return ReadExpr(F);
5809  return GetTypeSourceInfo(F, Record, Index);
5811  NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5812  Index);
5813  SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5814  return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5815  SourceLocation());
5816  }
5818  NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5819  Index);
5820  SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5821  SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5822  return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5823  EllipsisLoc);
5824  }
5830  // FIXME: Is this right?
5831  return TemplateArgumentLocInfo();
5832  }
5833  llvm_unreachable("unexpected template argument loc");
5834 }
5835 
5838  const RecordData &Record, unsigned &Index) {
5839  TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5840 
5841  if (Arg.getKind() == TemplateArgument::Expression) {
5842  if (Record[Index++]) // bool InfoHasSameExpr.
5844  }
5845  return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5846  Record, Index));
5847 }
5848 
5851  const RecordData &Record,
5852  unsigned &Index) {
5853  SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5854  SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5855  unsigned NumArgsAsWritten = Record[Index++];
5856  TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5857  for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5858  TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5859  return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5860 }
5861 
5862 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5863  return GetDecl(ID);
5864 }
5865 
5866 template<typename TemplateSpecializationDecl>
5868  if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5869  TSD->getSpecializedTemplate()->LoadLazySpecializations();
5870 }
5871 
5872 void ASTReader::CompleteRedeclChain(const Decl *D) {
5873  if (NumCurrentElementsDeserializing) {
5874  // We arrange to not care about the complete redeclaration chain while we're
5875  // deserializing. Just remember that the AST has marked this one as complete
5876  // but that it's not actually complete yet, so we know we still need to
5877  // complete it later.
5878  PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5879  return;
5880  }
5881 
5882  const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5883 
5884  // If this is a named declaration, complete it by looking it up
5885  // within its context.
5886  //
5887  // FIXME: Merging a function definition should merge
5888  // all mergeable entities within it.
5889  if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5890  isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5891  if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
5892  auto *II = Name.getAsIdentifierInfo();
5893  if (isa<TranslationUnitDecl>(DC) && II) {
5894  // Outside of C++, we don't have a lookup table for the TU, so update
5895  // the identifier instead. In C++, either way should work fine.
5896  if (II->isOutOfDate())
5897  updateOutOfDateIdentifier(*II);
5898  } else
5899  DC->lookup(Name);
5900  } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
5901  // FIXME: It'd be nice to do something a bit more targeted here.
5902  D->getDeclContext()->decls_begin();
5903  }
5904  }
5905 
5906  if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5907  CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5908  if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5909  VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5910  if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5911  if (auto *Template = FD->getPrimaryTemplate())
5912  Template->LoadLazySpecializations();
5913  }
5914 }
5915 
5917  const RecordData &Record,
5918  unsigned &Idx) {
5919  if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5920  Error("malformed AST file: missing C++ ctor initializers");
5921  return 0;
5922  }
5923 
5924  unsigned LocalID = Record[Idx++];
5925  return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
5926 }
5927 
5930  RecordLocation Loc = getLocalBitOffset(Offset);
5931  BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5932  SavedStreamPosition SavedPosition(Cursor);
5933  Cursor.JumpToBit(Loc.Offset);
5934  ReadingKindTracker ReadingKind(Read_Decl, *this);
5935 
5936  RecordData Record;
5937  unsigned Code = Cursor.ReadCode();
5938  unsigned RecCode = Cursor.readRecord(Code, Record);
5939  if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
5940  Error("malformed AST file: missing C++ ctor initializers");
5941  return nullptr;
5942  }
5943 
5944  unsigned Idx = 0;
5945  return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
5946 }
5947 
5948 uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
5949  const RecordData &Record,
5950  unsigned &Idx) {
5951  if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
5952  Error("malformed AST file: missing C++ base specifier");
5953  return 0;
5954  }
5955 
5956  unsigned LocalID = Record[Idx++];
5957  return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5958 }
5959 
5961  RecordLocation Loc = getLocalBitOffset(Offset);
5962  BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5963  SavedStreamPosition SavedPosition(Cursor);
5964  Cursor.JumpToBit(Loc.Offset);
5965  ReadingKindTracker ReadingKind(Read_Decl, *this);
5966  RecordData Record;
5967  unsigned Code = Cursor.ReadCode();
5968  unsigned RecCode = Cursor.readRecord(Code, Record);
5969  if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5970  Error("malformed AST file: missing C++ base specifiers");
5971  return nullptr;
5972  }
5973 
5974  unsigned Idx = 0;
5975  unsigned NumBases = Record[Idx++];
5976  void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5977  CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5978  for (unsigned I = 0; I != NumBases; ++I)
5979  Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5980  return Bases;
5981 }
5982 
5984 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5985  if (LocalID < NUM_PREDEF_DECL_IDS)
5986  return LocalID;
5987 
5989  = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5990  assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5991 
5992  return LocalID + I->second;
5993 }
5994 
5996  ModuleFile &M) const {
5997  // Predefined decls aren't from any module.
5998  if (ID < NUM_PREDEF_DECL_IDS)
5999  return false;
6000 
6001  return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6002  ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
6003 }
6004 
6005 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
6006  if (!D->isFromASTFile())
6007  return nullptr;
6008  GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6009  assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6010  return I->second;
6011 }
6012 
6014  if (ID < NUM_PREDEF_DECL_IDS)
6015  return SourceLocation();
6016 
6017  unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6018 
6019  if (Index > DeclsLoaded.size()) {
6020  Error("declaration ID out-of-range for AST file");
6021  return SourceLocation();
6022  }
6023 
6024  if (Decl *D = DeclsLoaded[Index])
6025  return D->getLocation();
6026 
6027  unsigned RawLocation = 0;
6028  RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6029  return ReadSourceLocation(*Rec.F, RawLocation);
6030 }
6031 
6033  switch (ID) {
6034  case PREDEF_DECL_NULL_ID:
6035  return nullptr;
6036 
6038  return Context.getTranslationUnitDecl();
6039 
6041  return Context.getObjCIdDecl();
6042 
6044  return Context.getObjCSelDecl();
6045 
6047  return Context.getObjCClassDecl();
6048 
6050  return Context.getObjCProtocolDecl();
6051 
6053  return Context.getInt128Decl();
6054 
6056  return Context.getUInt128Decl();
6057 
6059  return Context.getObjCInstanceTypeDecl();
6060 
6062  return Context.getBuiltinVaListDecl();
6063 
6065  return Context.getExternCContextDecl();
6066  }
6067  llvm_unreachable("PredefinedDeclIDs unknown enum value");
6068 }
6069 
6071  if (ID < NUM_PREDEF_DECL_IDS) {
6073  if (D) {
6074  // Track that we have merged the declaration with ID \p ID into the
6075  // pre-existing predefined declaration \p D.
6076  auto &Merged = KeyDecls[D->getCanonicalDecl()];
6077  if (Merged.empty())
6078  Merged.push_back(ID);
6079  }
6080  return D;
6081  }
6082 
6083  unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6084 
6085  if (Index >= DeclsLoaded.size()) {
6086  assert(0 && "declaration ID out-of-range for AST file");
6087  Error("declaration ID out-of-range for AST file");
6088  return nullptr;
6089  }
6090 
6091  return DeclsLoaded[Index];
6092 }
6093 
6095  if (ID < NUM_PREDEF_DECL_IDS)
6096  return GetExistingDecl(ID);
6097 
6098  unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6099 
6100  if (Index >= DeclsLoaded.size()) {
6101  assert(0 && "declaration ID out-of-range for AST file");
6102  Error("declaration ID out-of-range for AST file");
6103  return nullptr;
6104  }
6105 
6106  if (!DeclsLoaded[Index]) {
6107  ReadDeclRecord(ID);
6108  if (DeserializationListener)
6109  DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6110  }
6111 
6112  return DeclsLoaded[Index];
6113 }
6114 
6116  DeclID GlobalID) {
6117  if (GlobalID < NUM_PREDEF_DECL_IDS)
6118  return GlobalID;
6119 
6120  GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6121  assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6122  ModuleFile *Owner = I->second;
6123 
6124  llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6125  = M.GlobalToLocalDeclIDs.find(Owner);
6126  if (Pos == M.GlobalToLocalDeclIDs.end())
6127  return 0;
6128 
6129  return GlobalID - Owner->BaseDeclID + Pos->second;
6130 }
6131 
6133  const RecordData &Record,
6134  unsigned &Idx) {
6135  if (Idx >= Record.size()) {
6136  Error("Corrupted AST file");
6137  return 0;
6138  }
6139 
6140  return getGlobalDeclID(F, Record[Idx++]);
6141 }
6142 
6143 /// \brief Resolve the offset of a statement into a statement.
6144 ///
6145 /// This operation will read a new statement from the external
6146 /// source each time it is called, and is meant to be used via a
6147 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6149  // Switch case IDs are per Decl.
6150  ClearSwitchCaseIDs();
6151 
6152  // Offset here is a global offset across the entire chain.
6153  RecordLocation Loc = getLocalBitOffset(Offset);
6154  Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6155  return ReadStmtFromStream(*Loc.F);
6156 }
6157 
6158 namespace {
6159  class FindExternalLexicalDeclsVisitor {
6160  ASTReader &Reader;
6161  const DeclContext *DC;
6162  bool (*isKindWeWant)(Decl::Kind);
6163 
6164  SmallVectorImpl<Decl*> &Decls;
6165  bool PredefsVisited[NUM_PREDEF_DECL_IDS];
6166 
6167  public:
6168  FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
6169  bool (*isKindWeWant)(Decl::Kind),
6170  SmallVectorImpl<Decl*> &Decls)
6171  : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
6172  {
6173  for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
6174  PredefsVisited[I] = false;
6175  }
6176 
6177  static bool visitPostorder(ModuleFile &M, void *UserData) {
6178  FindExternalLexicalDeclsVisitor *This
6179  = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
6180 
6181  ModuleFile::DeclContextInfosMap::iterator Info
6182  = M.DeclContextInfos.find(This->DC);
6183  if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
6184  return false;
6185 
6186  // Load all of the declaration IDs
6187  for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
6188  *IDE = ID + Info->second.NumLexicalDecls;
6189  ID != IDE; ++ID) {
6190  if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
6191  continue;
6192 
6193  // Don't add predefined declarations to the lexical context more
6194  // than once.
6195  if (ID->second < NUM_PREDEF_DECL_IDS) {
6196  if (This->PredefsVisited[ID->second])
6197  continue;
6198 
6199  This->PredefsVisited[ID->second] = true;
6200  }
6201 
6202  if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
6203  if (!This->DC->isDeclInLexicalTraversal(D))
6204  This->Decls.push_back(D);
6205  }
6206  }
6207 
6208  return false;
6209  }
6210  };
6211 }
6212 
6214  bool (*isKindWeWant)(Decl::Kind),
6215  SmallVectorImpl<Decl*> &Decls) {
6216  // There might be lexical decls in multiple modules, for the TU at
6217  // least. Walk all of the modules in the order they were loaded.
6218  FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
6219  ModuleMgr.visitDepthFirst(
6220  nullptr, &FindExternalLexicalDeclsVisitor::visitPostorder, &Visitor);
6221  ++NumLexicalDeclContextsRead;
6222  return ELR_Success;
6223 }
6224 
6225 namespace {
6226 
6227 class DeclIDComp {
6228  ASTReader &Reader;
6229  ModuleFile &Mod;
6230 
6231 public:
6232  DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6233 
6234  bool operator()(LocalDeclID L, LocalDeclID R) const {
6235  SourceLocation LHS = getLocation(L);
6236  SourceLocation RHS = getLocation(R);
6237  return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6238  }
6239 
6240  bool operator()(SourceLocation LHS, LocalDeclID R) const {
6241  SourceLocation RHS = getLocation(R);
6242  return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6243  }
6244 
6245  bool operator()(LocalDeclID L, SourceLocation RHS) const {
6246  SourceLocation LHS = getLocation(L);
6247  return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6248  }
6249 
6250  SourceLocation getLocation(LocalDeclID ID) const {
6251  return Reader.getSourceManager().getFileLoc(
6252  Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6253  }
6254 };
6255 
6256 }
6257 
6259  unsigned Offset, unsigned Length,
6260  SmallVectorImpl<Decl *> &Decls) {
6261  SourceManager &SM = getSourceManager();
6262 
6263  llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6264  if (I == FileDeclIDs.end())
6265  return;
6266 
6267  FileDeclsInfo &DInfo = I->second;
6268  if (DInfo.Decls.empty())
6269  return;
6270 
6272  BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6273  SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6274 
6275  DeclIDComp DIDComp(*this, *DInfo.Mod);
6277  BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6278  BeginLoc, DIDComp);
6279  if (BeginIt != DInfo.Decls.begin())
6280  --BeginIt;
6281 
6282  // If we are pointing at a top-level decl inside an objc container, we need
6283  // to backtrack until we find it otherwise we will fail to report that the
6284  // region overlaps with an objc container.
6285  while (BeginIt != DInfo.Decls.begin() &&
6286  GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6287  ->isTopLevelDeclInObjCContainer())
6288  --BeginIt;
6289 
6291  EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6292  EndLoc, DIDComp);
6293  if (EndIt != DInfo.Decls.end())
6294  ++EndIt;
6295 
6297  DIt = BeginIt; DIt != EndIt; ++DIt)
6298  Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6299 }
6300 
6301 /// \brief Retrieve the "definitive" module file for the definition of the
6302 /// given declaration context, if there is one.
6303 ///
6304 /// The "definitive" module file is the only place where we need to look to
6305 /// find information about the declarations within the given declaration
6306 /// context. For example, C++ and Objective-C classes, C structs/unions, and
6307 /// Objective-C protocols, categories, and extensions are all defined in a
6308 /// single place in the source code, so they have definitive module files
6309 /// associated with them. C++ namespaces, on the other hand, can have
6310 /// definitions in multiple different module files.
6311 ///
6312 /// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6313 /// NDEBUG checking.
6314 static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6315  ASTReader &Reader) {
6316  if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6317  return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6318 
6319  return nullptr;
6320 }
6321 
6322 namespace {
6323  /// \brief ModuleFile visitor used to perform name lookup into a
6324  /// declaration context.
6325  class DeclContextNameLookupVisitor {
6326  ASTReader &Reader;
6328  DeclarationName Name;
6329  ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
6330  unsigned NameHash;
6332  llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
6333 
6334  public:
6335  DeclContextNameLookupVisitor(ASTReader &Reader,
6336  DeclarationName Name,
6338  llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6339  : Reader(Reader), Name(Name),
6341  NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
6342  Decls(Decls), DeclSet(DeclSet) {}
6343 
6344  void visitContexts(ArrayRef<const DeclContext*> Contexts) {
6345  if (Contexts.empty())
6346  return;
6347  this->Contexts = Contexts;
6348 
6349  // If we can definitively determine which module file to look into,
6350  // only look there. Otherwise, look in all module files.
6351  ModuleFile *Definitive;
6352  if (Contexts.size() == 1 &&
6353  (Definitive = getDefinitiveModuleFileFor(Contexts[0], Reader))) {
6354  visit(*Definitive, this);
6355  } else {
6356  Reader.getModuleManager().visit(&visit, this);
6357  }
6358  }
6359 
6360  private:
6361  static bool visit(ModuleFile &M, void *UserData) {
6362  DeclContextNameLookupVisitor *This
6363  = static_cast<DeclContextNameLookupVisitor *>(UserData);
6364 
6365  // Check whether we have any visible declaration information for
6366  // this context in this module.
6367  ModuleFile::DeclContextInfosMap::iterator Info;
6368  bool FoundInfo = false;
6369  for (auto *DC : This->Contexts) {
6370  Info = M.DeclContextInfos.find(DC);
6371  if (Info != M.DeclContextInfos.end() &&
6372  Info->second.NameLookupTableData) {
6373  FoundInfo = true;
6374  break;
6375  }
6376  }
6377 
6378  if (!FoundInfo)
6379  return false;
6380 
6381  // Look for this name within this module.
6382  ASTDeclContextNameLookupTable *LookupTable =
6383  Info->second.NameLookupTableData;
6384  ASTDeclContextNameLookupTable::iterator Pos
6385  = LookupTable->find_hashed(This->NameKey, This->NameHash);
6386  if (Pos == LookupTable->end())
6387  return false;
6388 
6389  bool FoundAnything = false;
6391  for (; Data.first != Data.second; ++Data.first) {
6392  NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6393  if (!ND)
6394  continue;
6395 
6396  if (ND->getDeclName() != This->Name) {
6397  // A name might be null because the decl's redeclarable part is
6398  // currently read before reading its name. The lookup is triggered by
6399  // building that decl (likely indirectly), and so it is later in the
6400  // sense of "already existing" and can be ignored here.
6401  // FIXME: This should not happen; deserializing declarations should
6402  // not perform lookups since that can lead to deserialization cycles.
6403  continue;
6404  }
6405 
6406  // Record this declaration.
6407  FoundAnything = true;
6408  if (This->DeclSet.insert(ND).second)
6409  This->Decls.push_back(ND);
6410  }
6411 
6412  return FoundAnything;
6413  }
6414  };
6415 }
6416 
6417 bool
6419  DeclarationName Name) {
6420  assert(DC->hasExternalVisibleStorage() &&
6421  "DeclContext has no visible decls in storage");
6422  if (!Name)
6423  return false;
6424 
6425  Deserializing LookupResults(this);
6426 
6428  llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
6429 
6430  // Compute the declaration contexts we need to look into. Multiple such
6431  // declaration contexts occur when two declaration contexts from disjoint
6432  // modules get merged, e.g., when two namespaces with the same name are
6433  // independently defined in separate modules.
6435  Contexts.push_back(DC);
6436 
6437  if (DC->isNamespace()) {
6438  auto Key = KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6439  if (Key != KeyDecls.end()) {
6440  for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6441  Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
6442  }
6443  }
6444 
6445  DeclContextNameLookupVisitor Visitor(*this, Name, Decls, DeclSet);
6446  Visitor.visitContexts(Contexts);
6447 
6448  // If this might be an implicit special member function, then also search
6449  // all merged definitions of the surrounding class. We need to search them
6450  // individually, because finding an entity in one of them doesn't imply that
6451  // we can't find a different entity in another one.
6452  if (isa<CXXRecordDecl>(DC)) {
6453  auto Merged = MergedLookups.find(DC);
6454  if (Merged != MergedLookups.end()) {
6455  for (unsigned I = 0; I != Merged->second.size(); ++I) {
6456  const DeclContext *Context = Merged->second[I];
6457  Visitor.visitContexts(Context);
6458  // We might have just added some more merged lookups. If so, our
6459  // iterator is now invalid, so grab a fresh one before continuing.
6460  Merged = MergedLookups.find(DC);
6461  }
6462  }
6463  }
6464 
6465  ++NumVisibleDeclContextsRead;
6466  SetExternalVisibleDeclsForName(DC, Name, Decls);
6467  return !Decls.empty();
6468 }
6469 
6470 namespace {
6471  /// \brief ModuleFile visitor used to retrieve all visible names in a
6472  /// declaration context.
6473  class DeclContextAllNamesVisitor {
6474  ASTReader &Reader;
6476  DeclsMap &Decls;
6477  llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
6478  bool VisitAll;
6479 
6480  public:
6481  DeclContextAllNamesVisitor(ASTReader &Reader,
6483  DeclsMap &Decls, bool VisitAll)
6484  : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
6485 
6486  static bool visit(ModuleFile &M, void *UserData) {
6487  DeclContextAllNamesVisitor *This
6488  = static_cast<DeclContextAllNamesVisitor *>(UserData);
6489 
6490  // Check whether we have any visible declaration information for
6491  // this context in this module.
6492  ModuleFile::DeclContextInfosMap::iterator Info;
6493  bool FoundInfo = false;
6494  for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6495  Info = M.DeclContextInfos.find(This->Contexts[I]);
6496  if (Info != M.DeclContextInfos.end() &&
6497  Info->second.NameLookupTableData) {
6498  FoundInfo = true;
6499  break;
6500  }
6501  }
6502 
6503  if (!FoundInfo)
6504  return false;
6505 
6506  ASTDeclContextNameLookupTable *LookupTable =
6507  Info->second.NameLookupTableData;
6508  bool FoundAnything = false;
6509  for (ASTDeclContextNameLookupTable::data_iterator
6510  I = LookupTable->data_begin(), E = LookupTable->data_end();
6511  I != E;
6512  ++I) {
6514  for (; Data.first != Data.second; ++Data.first) {
6515  NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6516  *Data.first);
6517  if (!ND)
6518  continue;
6519 
6520  // Record this declaration.
6521  FoundAnything = true;
6522  if (This->DeclSet.insert(ND).second)
6523  This->Decls[ND->getDeclName()].push_back(ND);
6524  }
6525  }
6526 
6527  return FoundAnything && !This->VisitAll;
6528  }
6529  };
6530 }
6531 
6533  if (!DC->hasExternalVisibleStorage())
6534  return;
6535  DeclsMap Decls;
6536 
6537  // Compute the declaration contexts we need to look into. Multiple such
6538  // declaration contexts occur when two declaration contexts from disjoint
6539  // modules get merged, e.g., when two namespaces with the same name are
6540  // independently defined in separate modules.
6542  Contexts.push_back(DC);
6543 
6544  if (DC->isNamespace()) {
6545  KeyDeclsMap::iterator Key =
6546  KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6547  if (Key != KeyDecls.end()) {
6548  for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6549  Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
6550  }
6551  }
6552 
6553  DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6554  /*VisitAll=*/DC->isFileContext());
6555  ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6556  ++NumVisibleDeclContextsRead;
6557 
6558  for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
6559  SetExternalVisibleDeclsForName(DC, I->first, I->second);
6560  }
6561  const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6562 }
6563 
6564 /// \brief Under non-PCH compilation the consumer receives the objc methods
6565 /// before receiving the implementation, and codegen depends on this.
6566 /// We simulate this by deserializing and passing to consumer the methods of the
6567 /// implementation before passing the deserialized implementation decl.
6569  ASTConsumer *Consumer) {
6570  assert(ImplD && Consumer);
6571 
6572  for (auto *I : ImplD->methods())
6573  Consumer->HandleInterestingDecl(DeclGroupRef(I));
6574 
6575  Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6576 }
6577 
6578 void ASTReader::PassInterestingDeclsToConsumer() {
6579  assert(Consumer);
6580 
6581  if (PassingDeclsToConsumer)
6582  return;
6583 
6584  // Guard variable to avoid recursively redoing the process of passing
6585  // decls to consumer.
6586  SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6587  true);
6588 
6589  // Ensure that we've loaded all potentially-interesting declarations
6590  // that need to be eagerly loaded.
6591  for (auto ID : EagerlyDeserializedDecls)
6592  GetDecl(ID);
6593  EagerlyDeserializedDecls.clear();
6594 
6595  while (!InterestingDecls.empty()) {
6596  Decl *D = InterestingDecls.front();
6597  InterestingDecls.pop_front();
6598 
6599  PassInterestingDeclToConsumer(D);
6600  }
6601 }
6602 
6603 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6604  if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6605  PassObjCImplDeclToConsumer(ImplD, Consumer);
6606  else
6607  Consumer->HandleInterestingDecl(DeclGroupRef(D));
6608 }
6609 
6611  this->Consumer = Consumer;
6612 
6613  if (Consumer)
6614  PassInterestingDeclsToConsumer();
6615 
6616  if (DeserializationListener)
6617  DeserializationListener->ReaderInitialized(this);
6618 }
6619 
6621  std::fprintf(stderr, "*** AST File Statistics:\n");
6622 
6623  unsigned NumTypesLoaded
6624  = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6625  QualType());
6626  unsigned NumDeclsLoaded
6627  = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6628  (Decl *)nullptr);
6629  unsigned NumIdentifiersLoaded
6630  = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6631  IdentifiersLoaded.end(),
6632  (IdentifierInfo *)nullptr);
6633  unsigned NumMacrosLoaded
6634  = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6635  MacrosLoaded.end(),
6636  (MacroInfo *)nullptr);
6637  unsigned NumSelectorsLoaded
6638  = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6639  SelectorsLoaded.end(),
6640  Selector());
6641 
6642  if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6643  std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
6644  NumSLocEntriesRead, TotalNumSLocEntries,
6645  ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6646  if (!TypesLoaded.empty())
6647  std::fprintf(stderr, " %u/%u types read (%f%%)\n",
6648  NumTypesLoaded, (unsigned)TypesLoaded.size(),
6649  ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6650  if (!DeclsLoaded.empty())
6651  std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
6652  NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6653  ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6654  if (!IdentifiersLoaded.empty())
6655  std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
6656  NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6657  ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6658  if (!MacrosLoaded.empty())
6659  std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6660  NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6661  ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6662  if (!SelectorsLoaded.empty())
6663  std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
6664  NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6665  ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6666  if (TotalNumStatements)
6667  std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
6668  NumStatementsRead, TotalNumStatements,
6669  ((float)NumStatementsRead/TotalNumStatements * 100));
6670  if (TotalNumMacros)
6671  std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
6672  NumMacrosRead, TotalNumMacros,
6673  ((float)NumMacrosRead/TotalNumMacros * 100));
6674  if (TotalLexicalDeclContexts)
6675  std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
6676  NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6677  ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6678  * 100));
6679  if (TotalVisibleDeclContexts)
6680  std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
6681  NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6682  ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6683  * 100));
6684  if (TotalNumMethodPoolEntries) {
6685  std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
6686  NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6687  ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6688  * 100));
6689  }
6690  if (NumMethodPoolLookups) {
6691  std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
6692  NumMethodPoolHits, NumMethodPoolLookups,
6693  ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6694  }
6695  if (NumMethodPoolTableLookups) {
6696  std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
6697  NumMethodPoolTableHits, NumMethodPoolTableLookups,
6698  ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6699  * 100.0));
6700  }
6701 
6702  if (NumIdentifierLookupHits) {
6703  std::fprintf(stderr,
6704  " %u / %u identifier table lookups succeeded (%f%%)\n",
6705  NumIdentifierLookupHits, NumIdentifierLookups,
6706  (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6707  }
6708 
6709  if (GlobalIndex) {
6710  std::fprintf(stderr, "\n");
6711  GlobalIndex->printStats();
6712  }
6713 
6714  std::fprintf(stderr, "\n");
6715  dump();
6716  std::fprintf(stderr, "\n");
6717 }
6718 
6719 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6720 static void
6721 dumpModuleIDMap(StringRef Name,
6722  const ContinuousRangeMap<Key, ModuleFile *,
6723  InitialCapacity> &Map) {
6724  if (Map.begin() == Map.end())
6725  return;
6726 
6728  llvm::errs() << Name << ":\n";
6729  for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6730  I != IEnd; ++I) {
6731  llvm::errs() << " " << I->first << " -> " << I->second->FileName
6732  << "\n";
6733  }
6734 }
6735 
6737  llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6738  dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6739  dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6740  dumpModuleIDMap("Global type map", GlobalTypeMap);
6741  dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6742  dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6743  dumpModuleIDMap("Global macro map", GlobalMacroMap);
6744  dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6745  dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6746  dumpModuleIDMap("Global preprocessed entity map",
6747  GlobalPreprocessedEntityMap);
6748 
6749  llvm::errs() << "\n*** PCH/Modules Loaded:";
6750  for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6751  MEnd = ModuleMgr.end();
6752  M != MEnd; ++M)
6753  (*M)->dump();
6754 }
6755 
6756 /// Return the amount of memory used by memory buffers, breaking down
6757 /// by heap-backed versus mmap'ed memory.
6759  for (ModuleConstIterator I = ModuleMgr.begin(),
6760  E = ModuleMgr.end(); I != E; ++I) {
6761  if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6762  size_t bytes = buf->getBufferSize();
6763  switch (buf->getBufferKind()) {
6764  case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6765  sizes.malloc_bytes += bytes;
6766  break;
6767  case llvm::MemoryBuffer::MemoryBuffer_MMap:
6768  sizes.mmap_bytes += bytes;
6769  break;
6770  }
6771  }
6772  }
6773 }
6774 
6776  SemaObj = &S;
6777  S.addExternalSource(this);
6778 
6779  // Makes sure any declarations that were deserialized "too early"
6780  // still get added to the identifier's declaration chains.
6781  for (uint64_t ID : PreloadedDeclIDs) {
6782  NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6783  pushExternalDeclIntoScope(D, D->getDeclName());
6784  }
6785  PreloadedDeclIDs.clear();
6786 
6787  // FIXME: What happens if these are changed by a module import?
6788  if (!FPPragmaOptions.empty()) {
6789  assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6790  SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6791  }
6792 
6793  // FIXME: What happens if these are changed by a module import?
6794  if (!OpenCLExtensions.empty()) {
6795  unsigned I = 0;
6796 #define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6797 #include "clang/Basic/OpenCLExtensions.def"
6798 
6799  assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6800  }
6801 
6802  UpdateSema();
6803 }
6804 
6806  assert(SemaObj && "no Sema to update");
6807 
6808  // Load the offsets of the declarations that Sema references.
6809  // They will be lazily deserialized when needed.
6810  if (!SemaDeclRefs.empty()) {
6811  assert(SemaDeclRefs.size() % 2 == 0);
6812  for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6813  if (!SemaObj->StdNamespace)
6814  SemaObj->StdNamespace = SemaDeclRefs[I];
6815  if (!SemaObj->StdBadAlloc)
6816  SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6817  }
6818  SemaDeclRefs.clear();
6819  }
6820 
6821  // Update the state of 'pragma clang optimize'. Use the same API as if we had
6822  // encountered the pragma in the source.
6823  if(OptimizeOffPragmaLocation.isValid())
6824  SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
6825 }
6826 
6827 IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6828  // Note that we are loading an identifier.
6829  Deserializing AnIdentifier(this);
6830  StringRef Name(NameStart, NameEnd - NameStart);
6831 
6832  // If there is a global index, look there first to determine which modules
6833  // provably do not have any results for this identifier.
6835  GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6836  if (!loadGlobalIndex()) {
6837  if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6838  HitsPtr = &Hits;
6839  }
6840  }
6841  IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
6842  NumIdentifierLookups,
6843  NumIdentifierLookupHits);
6844  ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
6845  IdentifierInfo *II = Visitor.getIdentifierInfo();
6846  markIdentifierUpToDate(II);
6847  return II;
6848 }
6849 
6850 namespace clang {
6851  /// \brief An identifier-lookup iterator that enumerates all of the
6852  /// identifiers stored within a set of AST files.
6854  /// \brief The AST reader whose identifiers are being enumerated.
6855  const ASTReader &Reader;
6856 
6857  /// \brief The current index into the chain of AST files stored in
6858  /// the AST reader.
6859  unsigned Index;
6860 
6861  /// \brief The current position within the identifier lookup table
6862  /// of the current AST file.
6863  ASTIdentifierLookupTable::key_iterator Current;
6864 
6865  /// \brief The end position within the identifier lookup table of
6866  /// the current AST file.
6867  ASTIdentifierLookupTable::key_iterator End;
6868 
6869  public:
6870  explicit ASTIdentifierIterator(const ASTReader &Reader);
6871 
6872  StringRef Next() override;
6873  };
6874 }
6875 
6877  : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6878  ASTIdentifierLookupTable *IdTable
6879  = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6880  Current = IdTable->key_begin();
6881  End = IdTable->key_end();
6882 }
6883 
6885  while (Current == End) {
6886  // If we have exhausted all of our AST files, we're done.
6887  if (Index == 0)
6888  return StringRef();
6889 
6890  --Index;
6891  ASTIdentifierLookupTable *IdTable
6892  = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6893  IdentifierLookupTable;
6894  Current = IdTable->key_begin();
6895  End = IdTable->key_end();
6896  }
6897 
6898  // We have any identifiers remaining in the current AST file; return
6899  // the next one.
6900  StringRef Result = *Current;
6901  ++Current;
6902  return Result;
6903 }
6904 
6906  if (!loadGlobalIndex())
6907  return GlobalIndex->createIdentifierIterator();
6908 
6909  return new ASTIdentifierIterator(*this);
6910 }
6911 
6912 namespace clang { namespace serialization {
6914  ASTReader &Reader;
6915  Selector Sel;
6916  unsigned PriorGeneration;
6917  unsigned InstanceBits;
6918  unsigned FactoryBits;
6919  bool InstanceHasMoreThanOneDecl;
6920  bool FactoryHasMoreThanOneDecl;
6921  SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6922  SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
6923 
6924  public:
6926  unsigned PriorGeneration)
6927  : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6928  InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6929  FactoryHasMoreThanOneDecl(false) {}
6930 
6931  static bool visit(ModuleFile &M, void *UserData) {
6932  ReadMethodPoolVisitor *This
6933  = static_cast<ReadMethodPoolVisitor *>(UserData);
6934 
6935  if (!M.SelectorLookupTable)
6936  return false;
6937 
6938  // If we've already searched this module file, skip it now.
6939  if (M.Generation <= This->PriorGeneration)
6940  return true;
6941 
6942  ++This->Reader.NumMethodPoolTableLookups;
6943  ASTSelectorLookupTable *PoolTable
6945  ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6946  if (Pos == PoolTable->end())
6947  return false;
6948 
6949  ++This->Reader.NumMethodPoolTableHits;
6950  ++This->Reader.NumSelectorsRead;
6951  // FIXME: Not quite happy with the statistics here. We probably should
6952  // disable this tracking when called via LoadSelector.
6953  // Also, should entries without methods count as misses?
6954  ++This->Reader.NumMethodPoolEntriesRead;
6956  if (This->Reader.DeserializationListener)
6957  This->Reader.DeserializationListener->SelectorRead(Data.ID,
6958  This->Sel);
6959 
6960  This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6961  This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6962  This->InstanceBits = Data.InstanceBits;
6963  This->FactoryBits = Data.FactoryBits;
6964  This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6965  This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
6966  return true;
6967  }
6968 
6969  /// \brief Retrieve the instance methods found by this visitor.
6971  return InstanceMethods;
6972  }
6973 
6974  /// \brief Retrieve the instance methods found by this visitor.
6976  return FactoryMethods;
6977  }
6978 
6979  unsigned getInstanceBits() const { return InstanceBits; }
6980  unsigned getFactoryBits() const { return FactoryBits; }
6982  return InstanceHasMoreThanOneDecl;
6983  }
6984  bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
6985  };
6986 } } // end namespace clang::serialization
6987 
6988 /// \brief Add the given set of methods to the method list.
6990  ObjCMethodList &List) {
6991  for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6992  S.addMethodToGlobalList(&List, Methods[I]);
6993  }
6994 }
6995 
6997  // Get the selector generation and update it to the current generation.
6998  unsigned &Generation = SelectorGeneration[Sel];
6999  unsigned PriorGeneration = Generation;
7000  Generation = getGeneration();
7001 
7002  // Search for methods defined with this selector.
7003  ++NumMethodPoolLookups;
7004  ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7005  ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
7006 
7007  if (Visitor.getInstanceMethods().empty() &&
7008  Visitor.getFactoryMethods().empty())
7009  return;
7010 
7011  ++NumMethodPoolHits;
7012 
7013  if (!getSema())
7014  return;
7015 
7016  Sema &S = *getSema();
7017  Sema::GlobalMethodPool::iterator Pos
7018  = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7019 
7020  Pos->second.first.setBits(Visitor.getInstanceBits());
7021  Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
7022  Pos->second.second.setBits(Visitor.getFactoryBits());
7023  Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
7024 
7025  // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7026  // when building a module we keep every method individually and may need to
7027  // update hasMoreThanOneDecl as we add the methods.
7028  addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7029  addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
7030 }
7031 
7033  SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7034  Namespaces.clear();
7035 
7036  for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7037  if (NamespaceDecl *Namespace
7038  = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7039  Namespaces.push_back(Namespace);
7040  }
7041 }
7042 
7044  llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
7045  for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7046  NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
7047  SourceLocation Loc =
7048  SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
7049  Undefined.insert(std::make_pair(D, Loc));
7050  }
7051 }
7052 
7054  FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7055  Exprs) {
7056  for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7057  FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7058  uint64_t Count = DelayedDeleteExprs[Idx++];
7059  for (uint64_t C = 0; C < Count; ++C) {
7060  SourceLocation DeleteLoc =
7061  SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7062  const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7063  Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7064  }
7065  }
7066 }
7067 
7069  SmallVectorImpl<VarDecl *> &TentativeDefs) {
7070  for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7071  VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7072  if (Var)
7073  TentativeDefs.push_back(Var);
7074  }
7075  TentativeDefinitions.clear();
7076 }
7077 
7080  for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7081  DeclaratorDecl *D
7082  = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7083  if (D)
7084  Decls.push_back(D);
7085  }
7086  UnusedFileScopedDecls.clear();
7087 }
7088 
7091  for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7093  = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7094  if (D)
7095  Decls.push_back(D);
7096  }
7097  DelegatingCtorDecls.clear();
7098 }
7099 
7101  for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7102  TypedefNameDecl *D
7103  = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7104  if (D)
7105  Decls.push_back(D);
7106  }
7107  ExtVectorDecls.clear();
7108 }
7109 
7112  for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7113  ++I) {
7114  TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7115  GetDecl(UnusedLocalTypedefNameCandidates[I]));
7116  if (D)
7117  Decls.insert(D);
7118  }
7119  UnusedLocalTypedefNameCandidates.clear();
7120 }
7121 
7123  SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7124  if (ReferencedSelectorsData.empty())
7125  return;
7126 
7127  // If there are @selector references added them to its pool. This is for
7128  // implementation of -Wselector.
7129  unsigned int DataSize = ReferencedSelectorsData.size()-1;
7130  unsigned I = 0;
7131  while (I < DataSize) {
7132  Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7133  SourceLocation SelLoc
7134  = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7135  Sels.push_back(std::make_pair(Sel, SelLoc));
7136  }
7137  ReferencedSelectorsData.clear();
7138 }
7139 
7141  SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7142  if (WeakUndeclaredIdentifiers.empty())
7143  return;
7144 
7145  for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7146  IdentifierInfo *WeakId
7147  = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7148  IdentifierInfo *AliasId
7149  = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7150  SourceLocation Loc
7151  = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7152  bool Used = WeakUndeclaredIdentifiers[I++];
7153  WeakInfo WI(AliasId, Loc);
7154  WI.setUsed(Used);
7155  WeakIDs.push_back(std::make_pair(WeakId, WI));
7156  }
7157  WeakUndeclaredIdentifiers.clear();
7158 }
7159 
7161  for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7162  ExternalVTableUse VT;
7163  VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7164  VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7165  VT.DefinitionRequired = VTableUses[Idx++];
7166  VTables.push_back(VT);
7167  }
7168 
7169  VTableUses.clear();
7170 }
7171 
7173  SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7174  for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7175  ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7176  SourceLocation Loc
7177  = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7178 
7179  Pending.push_back(std::make_pair(D, Loc));
7180  }
7181  PendingInstantiations.clear();
7182 }
7183 
7185  llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7186  for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7187  /* In loop */) {
7188  FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7189 
7191  LT->D = GetDecl(LateParsedTemplates[Idx++]);
7192 
7193  ModuleFile *F = getOwningModuleFile(LT->D);
7194  assert(F && "No module");
7195 
7196  unsigned TokN = LateParsedTemplates[Idx++];
7197  LT->Toks.reserve(TokN);
7198  for (unsigned T = 0; T < TokN; ++T)
7199  LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7200 
7201  LPTMap.insert(std::make_pair(FD, LT));
7202  }
7203 
7204  LateParsedTemplates.clear();
7205 }
7206 
7208  // It would be complicated to avoid reading the methods anyway. So don't.
7209  ReadMethodPool(Sel);
7210 }
7211 
7213  assert(ID && "Non-zero identifier ID required");
7214  assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7215  IdentifiersLoaded[ID - 1] = II;
7216  if (DeserializationListener)
7217  DeserializationListener->IdentifierRead(ID, II);
7218 }
7219 
7220 /// \brief Set the globally-visible declarations associated with the given
7221 /// identifier.
7222 ///
7223 /// If the AST reader is currently in a state where the given declaration IDs
7224 /// cannot safely be resolved, they are queued until it is safe to resolve
7225 /// them.
7226 ///
7227 /// \param II an IdentifierInfo that refers to one or more globally-visible
7228 /// declarations.
7229 ///
7230 /// \param DeclIDs the set of declaration IDs with the name @p II that are
7231 /// visible at global scope.
7232 ///
7233 /// \param Decls if non-null, this vector will be populated with the set of
7234 /// deserialized declarations. These declarations will not be pushed into
7235 /// scope.
7236 void
7238  const SmallVectorImpl<uint32_t> &DeclIDs,
7239  SmallVectorImpl<Decl *> *Decls) {
7240  if (NumCurrentElementsDeserializing && !Decls) {
7241  PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
7242  return;
7243  }
7244 
7245  for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7246  if (!SemaObj) {
7247  // Queue this declaration so that it will be added to the
7248  // translation unit scope and identifier's declaration chain
7249  // once a Sema object is known.
7250  PreloadedDeclIDs.push_back(DeclIDs[I]);
7251  continue;
7252  }
7253 
7254  NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7255 
7256  // If we're simply supposed to record the declarations, do so now.
7257  if (Decls) {
7258  Decls->push_back(D);
7259  continue;
7260  }
7261 
7262  // Introduce this declaration into the translation-unit scope
7263  // and add it to the declaration chain for this identifier, so
7264  // that (unqualified) name lookup will find it.
7265  pushExternalDeclIntoScope(D, II);
7266  }
7267 }
7268 
7270  if (ID == 0)
7271  return nullptr;
7272 
7273  if (IdentifiersLoaded.empty()) {
7274  Error("no identifier table in AST file");
7275  return nullptr;
7276  }
7277 
7278  ID -= 1;
7279  if (!IdentifiersLoaded[ID]) {
7280  GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7281  assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7282  ModuleFile *M = I->second;
7283  unsigned Index = ID - M->BaseIdentifierID;
7284  const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7285 
7286  // All of the strings in the AST file are preceded by a 16-bit length.
7287  // Extract that 16-bit length to avoid having to execute strlen().
7288  // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7289  // unsigned integers. This is important to avoid integer overflow when
7290  // we cast them to 'unsigned'.
7291  const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7292  unsigned StrLen = (((unsigned) StrLenPtr[0])
7293  | (((unsigned) StrLenPtr[1]) << 8)) - 1;
7294  IdentifiersLoaded[ID]
7295  = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
7296  if (DeserializationListener)
7297  DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7298  }
7299 
7300  return IdentifiersLoaded[ID];
7301 }
7302 
7303 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7304  return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
7305 }
7306 
7307 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7308  if (LocalID < NUM_PREDEF_IDENT_IDS)
7309  return LocalID;
7310 
7312  = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7313  assert(I != M.IdentifierRemap.end()
7314  && "Invalid index into identifier index remap");
7315 
7316  return LocalID + I->second;
7317 }
7318 
7320  if (ID == 0)
7321  return nullptr;
7322 
7323  if (MacrosLoaded.empty()) {
7324  Error("no macro table in AST file");
7325  return nullptr;
7326  }
7327 
7328  ID -= NUM_PREDEF_MACRO_IDS;
7329  if (!MacrosLoaded[ID]) {
7331  = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7332  assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7333  ModuleFile *M = I->second;
7334  unsigned Index = ID - M->BaseMacroID;
7335  MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7336 
7337  if (DeserializationListener)
7338  DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7339  MacrosLoaded[ID]);
7340  }
7341 
7342  return MacrosLoaded[ID];
7343 }
7344 
7345 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7346  if (LocalID < NUM_PREDEF_MACRO_IDS)
7347  return LocalID;
7348 
7350  = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7351  assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7352 
7353  return LocalID + I->second;
7354 }
7355 
7357 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7358  if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7359  return LocalID;
7360 
7362  = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7363  assert(I != M.SubmoduleRemap.end()
7364  && "Invalid index into submodule index remap");
7365 
7366  return LocalID + I->second;
7367 }
7368 
7370  if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7371  assert(GlobalID == 0 && "Unhandled global submodule ID");
7372  return nullptr;
7373  }
7374 
7375  if (GlobalID > SubmodulesLoaded.size()) {
7376  Error("submodule ID out of range in AST file");
7377  return nullptr;
7378  }
7379 
7380  return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7381 }
7382 
7384  return getSubmodule(ID);
7385 }
7386 
7389  StringRef Dir, Filename;
7390  if (M.Directory)
7391  Dir = M.Directory->getName();
7392  if (auto *File = M.getASTFile())
7393  Filename = File->getName();
7395  M.getFullModuleName(), Dir, Filename,
7396  M.Signature
7397  };
7398 }
7399 
7402  if (const Module *M = getSubmodule(ID))
7403  return getSourceDescriptor(*M);
7404 
7405  // If there is only a single PCH, return it instead.
7406  // Chained PCH are not suported.
7407  if (ModuleMgr.size() == 1) {
7408  ModuleFile &MF = ModuleMgr.getPrimaryModule();
7411  MF.FileName,
7412  MF.Signature
7413  };
7414  }
7415  return None;
7416 }
7417 
7418 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7419  return DecodeSelector(getGlobalSelectorID(M, LocalID));
7420 }
7421 
7423  if (ID == 0)
7424  return Selector();
7425 
7426  if (ID > SelectorsLoaded.size()) {
7427  Error("selector ID out of range in AST file");
7428  return Selector();
7429  }
7430 
7431  if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
7432  // Load this selector from the selector table.
7433  GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7434  assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7435  ModuleFile &M = *I->second;
7436  ASTSelectorLookupTrait Trait(*this, M);
7437  unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7438  SelectorsLoaded[ID - 1] =
7439  Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7440  if (DeserializationListener)
7441  DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7442  }
7443 
7444  return SelectorsLoaded[ID - 1];
7445 }
7446 
7448  return DecodeSelector(ID);
7449 }
7450 
7452  // ID 0 (the null selector) is considered an external selector.
7453  return getTotalNumSelectors() + 1;
7454 }
7455 
7457 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7458  if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7459  return LocalID;
7460 
7463  assert(I != M.SelectorRemap.end()
7464  && "Invalid index into selector index remap");
7465 
7466  return LocalID + I->second;
7467 }
7468 
7471  const RecordData &Record, unsigned &Idx) {
7473  switch (Kind) {
7475  return DeclarationName(GetIdentifierInfo(F, Record, Idx));
7476 
7480  return DeclarationName(ReadSelector(F, Record, Idx));
7481 
7483  return Context.DeclarationNames.getCXXConstructorName(
7484  Context.getCanonicalType(readType(F, Record, Idx)));
7485 
7487  return Context.DeclarationNames.getCXXDestructorName(
7488  Context.getCanonicalType(readType(F, Record, Idx)));
7489 
7492  Context.getCanonicalType(readType(F, Record, Idx)));
7493 
7495  return Context.DeclarationNames.getCXXOperatorName(
7496  (OverloadedOperatorKind)Record[Idx++]);
7497 
7500  GetIdentifierInfo(F, Record, Idx));
7501 
7504  }
7505 
7506  llvm_unreachable("Invalid NameKind!");
7507 }
7508 
7510  DeclarationNameLoc &DNLoc,
7511  DeclarationName Name,
7512  const RecordData &Record, unsigned &Idx) {
7513  switch (Name.getNameKind()) {
7517  DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7518  break;
7519 
7522  = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7524  = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7525  break;
7526 
7529  = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7530  break;
7531 
7537  break;
7538  }
7539 }
7540 
7542  DeclarationNameInfo &NameInfo,
7543  const RecordData &Record, unsigned &Idx) {
7544  NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7545  NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7546  DeclarationNameLoc DNLoc;
7547  ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7548  NameInfo.setInfo(DNLoc);
7549 }
7550 
7552  const RecordData &Record, unsigned &Idx) {
7553  Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7554  unsigned NumTPLists = Record[Idx++];
7555  Info.NumTemplParamLists = NumTPLists;
7556  if (NumTPLists) {
7557  Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7558  for (unsigned i=0; i != NumTPLists; ++i)
7559  Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7560  }
7561 }
7562 
7564 ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7565  unsigned &Idx) {
7567  switch (Kind) {
7569  return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7570 
7572  unsigned size = Record[Idx++];
7573  UnresolvedSet<8> Decls;
7574  while (size--)
7575  Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7576 
7577  return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7578  }
7579 
7581  NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7582  bool hasTemplKeyword = Record[Idx++];
7583  TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7584  return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7585  }
7586 
7588  NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7589  if (Record[Idx++]) // isIdentifier
7590  return Context.getDependentTemplateName(NNS,
7591  GetIdentifierInfo(F, Record,
7592  Idx));
7593  return Context.getDependentTemplateName(NNS,
7594  (OverloadedOperatorKind)Record[Idx++]);
7595  }
7596 
7599  = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7600  if (!param) return TemplateName();
7601  TemplateName replacement = ReadTemplateName(F, Record, Idx);
7602  return Context.getSubstTemplateTemplateParm(param, replacement);
7603  }
7604 
7606  TemplateTemplateParmDecl *Param
7607  = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7608  if (!Param)
7609  return TemplateName();
7610 
7611  TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7612  if (ArgPack.getKind() != TemplateArgument::Pack)
7613  return TemplateName();
7614 
7615  return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7616  }
7617  }
7618 
7619  llvm_unreachable("Unhandled template name kind!");
7620 }
7621 
7624  const RecordData &Record, unsigned &Idx) {
7626  switch (Kind) {
7628  return TemplateArgument();
7630  return TemplateArgument(readType(F, Record, Idx));
7632  ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7633  return TemplateArgument(D, readType(F, Record, Idx));
7634  }
7636  return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7638  llvm::APSInt Value = ReadAPSInt(Record, Idx);
7639  QualType T = readType(F, Record, Idx);
7640  return TemplateArgument(Context, Value, T);
7641  }
7643  return TemplateArgument(ReadTemplateName(F, Record, Idx));
7645  TemplateName Name = ReadTemplateName(F, Record, Idx);
7646  Optional<unsigned> NumTemplateExpansions;
7647  if (unsigned NumExpansions = Record[Idx++])
7648  NumTemplateExpansions = NumExpansions - 1;
7649  return TemplateArgument(Name, NumTemplateExpansions);
7650  }
7652  return TemplateArgument(ReadExpr(F));
7653  case TemplateArgument::Pack: {
7654  unsigned NumArgs = Record[Idx++];
7655  TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7656  for (unsigned I = 0; I != NumArgs; ++I)
7657  Args[I] = ReadTemplateArgument(F, Record, Idx);
7658  return TemplateArgument(Args, NumArgs);
7659  }
7660  }
7661 
7662  llvm_unreachable("Unhandled template argument kind!");
7663 }
7664 
7667  const RecordData &Record, unsigned &Idx) {
7668  SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7669  SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7670  SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7671 
7672  unsigned NumParams = Record[Idx++];
7674  Params.reserve(NumParams);
7675  while (NumParams--)
7676  Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7677 
7678  TemplateParameterList* TemplateParams =
7679  TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7680  Params.data(), Params.size(), RAngleLoc);
7681  return TemplateParams;
7682 }
7683 
7684 void
7687  ModuleFile &F, const RecordData &Record,
7688  unsigned &Idx) {
7689  unsigned NumTemplateArgs = Record[Idx++];
7690  TemplArgs.reserve(NumTemplateArgs);
7691  while (NumTemplateArgs--)
7692  TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7693 }
7694 
7695 /// \brief Read a UnresolvedSet structure.
7697  const RecordData &Record, unsigned &Idx) {
7698  unsigned NumDecls = Record[Idx++];
7699  Set.reserve(Context, NumDecls);
7700  while (NumDecls--) {
7701  DeclID ID = ReadDeclID(F, Record, Idx);
7702  AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
7703  Set.addLazyDecl(Context, ID, AS);
7704  }
7705 }
7706 
7709  const RecordData &Record, unsigned &Idx) {
7710  bool isVirtual = static_cast<bool>(Record[Idx++]);
7711  bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7712  AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7713  bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7714  TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7715  SourceRange Range = ReadSourceRange(F, Record, Idx);
7716  SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7717  CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7718  EllipsisLoc);
7719  Result.setInheritConstructors(inheritConstructors);
7720  return Result;
7721 }
7722 
7724 ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7725  unsigned &Idx) {
7726  unsigned NumInitializers = Record[Idx++];
7727  assert(NumInitializers && "wrote ctor initializers but have no inits");
7728  auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7729  for (unsigned i = 0; i != NumInitializers; ++i) {
7730  TypeSourceInfo *TInfo = nullptr;
7731  bool IsBaseVirtual = false;
7732  FieldDecl *Member = nullptr;
7733  IndirectFieldDecl *IndirectMember = nullptr;
7734 
7735  CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7736  switch (Type) {
7737  case CTOR_INITIALIZER_BASE:
7738  TInfo = GetTypeSourceInfo(F, Record, Idx);
7739  IsBaseVirtual = Record[Idx++];
7740  break;
7741 
7743  TInfo = GetTypeSourceInfo(F, Record, Idx);
7744  break;
7745 
7747  Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7748  break;
7749 
7751  IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7752  break;
7753  }
7754 
7755  SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7756  Expr *Init = ReadExpr(F);
7757  SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7758  SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7759  bool IsWritten = Record[Idx++];
7760  unsigned SourceOrderOrNumArrayIndices;
7761  SmallVector<VarDecl *, 8> Indices;
7762  if (IsWritten) {
7763  SourceOrderOrNumArrayIndices = Record[Idx++];
7764  } else {
7765  SourceOrderOrNumArrayIndices = Record[Idx++];
7766  Indices.reserve(SourceOrderOrNumArrayIndices);
7767  for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7768  Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7769  }
7770 
7771  CXXCtorInitializer *BOMInit;
7772  if (Type == CTOR_INITIALIZER_BASE) {
7773  BOMInit = new (Context)
7774  CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7775  RParenLoc, MemberOrEllipsisLoc);
7776  } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7777  BOMInit = new (Context)
7778  CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7779  } else if (IsWritten) {
7780  if (Member)
7781  BOMInit = new (Context) CXXCtorInitializer(
7782  Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7783  else
7784  BOMInit = new (Context)
7785  CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7786  LParenLoc, Init, RParenLoc);
7787  } else {
7788  if (IndirectMember) {
7789  assert(Indices.empty() && "Indirect field improperly initialized");
7790  BOMInit = new (Context)
7791  CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7792  LParenLoc, Init, RParenLoc);
7793  } else {
7794  BOMInit = CXXCtorInitializer::Create(
7795  Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7796  Indices.data(), Indices.size());
7797  }
7798  }
7799 
7800  if (IsWritten)
7801  BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7802  CtorInitializers[i] = BOMInit;
7803  }
7804 
7805  return CtorInitializers;
7806 }
7807 
7810  const RecordData &Record, unsigned &Idx) {
7811  unsigned N = Record[Idx++];
7812  NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
7813  for (unsigned I = 0; I != N; ++I) {
7815  = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7816  switch (Kind) {
7818  IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7819  NNS = NestedNameSpecifier::Create(Context, Prev, II);
7820  break;
7821  }
7822 
7824  NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7825  NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7826  break;
7827  }
7828 
7830  NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7831  NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7832  break;
7833  }
7834 
7837  const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7838  if (!T)
7839  return nullptr;
7840 
7841  bool Template = Record[Idx++];
7842  NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7843  break;
7844  }
7845 
7847  NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7848  // No associated value, and there can't be a prefix.
7849  break;
7850  }
7851 
7853  CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7854  NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7855  break;
7856  }
7857  }
7858  Prev = NNS;
7859  }
7860  return NNS;
7861 }
7862 
7865  unsigned &Idx) {
7866  unsigned N = Record[Idx++];
7868  for (unsigned I = 0; I != N; ++I) {
7870  = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7871  switch (Kind) {
7873  IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7874  SourceRange Range = ReadSourceRange(F, Record, Idx);
7875  Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7876  break;
7877  }
7878 
7880  NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7881  SourceRange Range = ReadSourceRange(F, Record, Idx);
7882  Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7883  break;
7884  }
7885 
7887  NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7888  SourceRange Range = ReadSourceRange(F, Record, Idx);
7889  Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7890  break;
7891  }
7892 
7895  bool Template = Record[Idx++];
7896  TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7897  if (!T)
7898  return NestedNameSpecifierLoc();
7899  SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7900 
7901  // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7902  Builder.Extend(Context,
7903  Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7904  T->getTypeLoc(), ColonColonLoc);
7905  break;
7906  }
7907 
7909  SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7910  Builder.MakeGlobal(Context, ColonColonLoc);
7911  break;
7912  }
7913 
7915  CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7916  SourceRange Range = ReadSourceRange(F, Record, Idx);
7917  Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7918  break;
7919  }
7920  }
7921  }
7922 
7923  return Builder.getWithLocInContext(Context);
7924 }
7925 
7927 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7928  unsigned &Idx) {
7929  SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7930  SourceLocation end = ReadSourceLocation(F, Record, Idx);
7931  return SourceRange(beg, end);
7932 }
7933 
7934 /// \brief Read an integral value
7935 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7936  unsigned BitWidth = Record[Idx++];
7937  unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7938  llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7939  Idx += NumWords;
7940  return Result;
7941 }
7942 
7943 /// \brief Read a signed integral value
7944 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7945  bool isUnsigned = Record[Idx++];
7946  return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7947 }
7948 
7949 /// \brief Read a floating-point value
7950 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7951  const llvm::fltSemantics &Sem,
7952  unsigned &Idx) {
7953  return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
7954 }
7955 
7956 // \brief Read a string
7957 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7958  unsigned Len = Record[Idx++];
7959  std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7960  Idx += Len;
7961  return Result;
7962 }
7963 
7964 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7965  unsigned &Idx) {
7966  std::string Filename = ReadString(Record, Idx);
7967  ResolveImportedPath(F, Filename);
7968  return Filename;
7969 }
7970 
7972  unsigned &Idx) {
7973  unsigned Major = Record[Idx++];
7974  unsigned Minor = Record[Idx++];
7975  unsigned Subminor = Record[Idx++];
7976  if (Minor == 0)
7977  return VersionTuple(Major);
7978  if (Subminor == 0)
7979  return VersionTuple(Major, Minor - 1);
7980  return VersionTuple(Major, Minor - 1, Subminor - 1);
7981 }
7982 
7984  const RecordData &Record,
7985  unsigned &Idx) {
7986  CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7987  return CXXTemporary::Create(Context, Decl);
7988 }
7989 
7991  return Diag(CurrentImportLoc, DiagID);
7992 }
7993 
7995  return Diags.Report(Loc, DiagID);
7996 }
7997 
7998 /// \brief Retrieve the identifier table associated with the
7999 /// preprocessor.
8001  return PP.getIdentifierTable();
8002 }
8003 
8004 /// \brief Record that the given ID maps to the given switch-case
8005 /// statement.
8007  assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
8008  "Already have a SwitchCase with this ID");
8009  (*CurrSwitchCaseStmts)[ID] = SC;
8010 }
8011 
8012 /// \brief Retrieve the switch-case statement with the given ID.
8014  assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
8015  return (*CurrSwitchCaseStmts)[ID];
8016 }
8017 
8019  CurrSwitchCaseStmts->clear();
8020 }
8021 
8023  std::vector<RawComment *> Comments;
8024  for (SmallVectorImpl<std::pair<BitstreamCursor,
8025  serialization::ModuleFile *> >::iterator
8026  I = CommentsCursors.begin(),
8027  E = CommentsCursors.end();
8028  I != E; ++I) {
8029  Comments.clear();
8030  BitstreamCursor &Cursor = I->first;
8031  serialization::ModuleFile &F = *I->second;
8032  SavedStreamPosition SavedPosition(Cursor);
8033 
8034  RecordData Record;
8035  while (true) {
8036  llvm::BitstreamEntry Entry =
8037  Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
8038 
8039  switch (Entry.Kind) {
8040  case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8042  Error("malformed block record in AST file");
8043  return;
8044  case llvm::BitstreamEntry::EndBlock:
8045  goto NextCursor;
8046  case llvm::BitstreamEntry::Record:
8047  // The interesting case.
8048  break;
8049  }
8050 
8051  // Read a record.
8052  Record.clear();
8053  switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
8054  case COMMENTS_RAW_COMMENT: {
8055  unsigned Idx = 0;
8056  SourceRange SR = ReadSourceRange(F, Record, Idx);
8058  (RawComment::CommentKind) Record[Idx++];
8059  bool IsTrailingComment = Record[Idx++];
8060  bool IsAlmostTrailingComment = Record[Idx++];
8061  Comments.push_back(new (Context) RawComment(
8062  SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8064  break;
8065  }
8066  }
8067  }
8068  NextCursor:
8069  Context.Comments.addDeserializedComments(Comments);
8070  }
8071 }
8072 
8073 void ASTReader::getInputFiles(ModuleFile &F,
8075  for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
8076  unsigned ID = I+1;
8077  Files.push_back(getInputFile(F, ID));
8078  }
8079 }
8080 
8082  // If we know the owning module, use it.
8083  if (Module *M = D->getImportedOwningModule())
8084  return M->getFullModuleName();
8085 
8086  // Otherwise, use the name of the top-level module the decl is within.
8087  if (ModuleFile *M = getOwningModuleFile(D))
8088  return M->ModuleName;
8089 
8090  // Not from a module.
8091  return "";
8092 }
8093 
8094 void ASTReader::finishPendingActions() {
8095  while (!PendingIdentifierInfos.empty() ||
8096  !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
8097  !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
8098  !PendingUpdateRecords.empty()) {
8099  // If any identifiers with corresponding top-level declarations have
8100  // been loaded, load those declarations now.
8101  typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8102  TopLevelDeclsMap;
8103  TopLevelDeclsMap TopLevelDecls;
8104 
8105  while (!PendingIdentifierInfos.empty()) {
8106  IdentifierInfo *II = PendingIdentifierInfos.back().first;
8107  SmallVector<uint32_t, 4> DeclIDs =
8108  std::move(PendingIdentifierInfos.back().second);
8109  PendingIdentifierInfos.pop_back();
8110 
8111  SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
8112  }
8113 
8114  // For each decl chain that we wanted to complete while deserializing, mark
8115  // it as "still needs to be completed".
8116  for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8117  markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8118  }
8119  PendingIncompleteDeclChains.clear();
8120 
8121  // Load pending declaration chains.
8122  for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8123  PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8124  loadPendingDeclChain(PendingDeclChains[I]);
8125  }
8126  assert(PendingDeclChainsKnown.empty());
8127  PendingDeclChains.clear();
8128 
8129  // Make the most recent of the top-level declarations visible.
8130  for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8131  TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
8132  IdentifierInfo *II = TLD->first;
8133  for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
8134  pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
8135  }
8136  }
8137 
8138  // Load any pending macro definitions.
8139  for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
8140  IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8142  GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8143  // Initialize the macro history from chained-PCHs ahead of module imports.
8144  for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8145  ++IDIdx) {
8146  const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8147  if (Info.M->Kind != MK_ImplicitModule &&
8148  Info.M->Kind != MK_ExplicitModule)
8149  resolvePendingMacro(II, Info);
8150  }
8151  // Handle module imports.
8152  for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8153  ++IDIdx) {
8154  const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8155  if (Info.M->Kind == MK_ImplicitModule ||
8156  Info.M->Kind == MK_ExplicitModule)
8157  resolvePendingMacro(II, Info);
8158  }
8159  }
8160  PendingMacroIDs.clear();
8161 
8162  // Wire up the DeclContexts for Decls that we delayed setting until
8163  // recursive loading is completed.
8164  while (!PendingDeclContextInfos.empty()) {
8165  PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8166  PendingDeclContextInfos.pop_front();
8167  DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8168  DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8169  Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8170  }
8171 
8172  // Perform any pending declaration updates.
8173  while (!PendingUpdateRecords.empty()) {
8174  auto Update = PendingUpdateRecords.pop_back_val();
8175  ReadingKindTracker ReadingKind(Read_Decl, *this);
8176  loadDeclUpdateRecords(Update.first, Update.second);
8177  }
8178  }
8179 
8180  // At this point, all update records for loaded decls are in place, so any
8181  // fake class definitions should have become real.
8182  assert(PendingFakeDefinitionData.empty() &&
8183  "faked up a class definition but never saw the real one");
8184 
8185  // If we deserialized any C++ or Objective-C class definitions, any
8186  // Objective-C protocol definitions, or any redeclarable templates, make sure
8187  // that all redeclarations point to the definitions. Note that this can only
8188  // happen now, after the redeclaration chains have been fully wired.
8189  for (Decl *D : PendingDefinitions) {
8190  if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8191  if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
8192  // Make sure that the TagType points at the definition.
8193  const_cast<TagType*>(TagT)->decl = TD;
8194  }
8195 
8196  if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
8197  for (auto *R = getMostRecentExistingDecl(RD); R;
8198  R = R->getPreviousDecl()) {
8199  assert((R == D) ==
8200  cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
8201  "declaration thinks it's the definition but it isn't");
8202  cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
8203  }
8204  }
8205 
8206  continue;
8207  }
8208 
8209  if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
8210  // Make sure that the ObjCInterfaceType points at the definition.
8211  const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8212  ->Decl = ID;
8213 
8214  for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8215  cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8216 
8217  continue;
8218  }
8219 
8220  if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
8221  for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8222  cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8223 
8224  continue;
8225  }
8226 
8227  auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
8228  for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8229  cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
8230  }
8231  PendingDefinitions.clear();
8232 
8233  // Load the bodies of any functions or methods we've encountered. We do
8234  // this now (delayed) so that we can be sure that the declaration chains
8235  // have been fully wired up.
8236  // FIXME: There seems to be no point in delaying this, it does not depend
8237  // on the redecl chains having been wired up.
8238  for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8239  PBEnd = PendingBodies.end();
8240  PB != PBEnd; ++PB) {
8241  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8242  // FIXME: Check for =delete/=default?
8243  // FIXME: Complain about ODR violations here?
8244  if (!getContext().getLangOpts().Modules || !FD->hasBody())
8245  FD->setLazyBody(PB->second);
8246  continue;
8247  }
8248 
8249  ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8250  if (!getContext().getLangOpts().Modules || !MD->hasBody())
8251  MD->setLazyBody(PB->second);
8252  }
8253  PendingBodies.clear();
8254 
8255  // Do some cleanup.
8256  for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8258  PendingMergedDefinitionsToDeduplicate.clear();
8259 }
8260 
8261 void ASTReader::diagnoseOdrViolations() {
8262  if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8263  return;
8264 
8265  // Trigger the import of the full definition of each class that had any
8266  // odr-merging problems, so we can produce better diagnostics for them.
8267  // These updates may in turn find and diagnose some ODR failures, so take
8268  // ownership of the set first.
8269  auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8270  PendingOdrMergeFailures.clear();
8271  for (auto &Merge : OdrMergeFailures) {
8272  Merge.first->buildLookup();
8273  Merge.first->decls_begin();
8274  Merge.first->bases_begin();
8275  Merge.first->vbases_begin();
8276  for (auto *RD : Merge.second) {
8277  RD->decls_begin();
8278  RD->bases_begin();
8279  RD->vbases_begin();
8280  }
8281  }
8282 
8283  // For each declaration from a merged context, check that the canonical
8284  // definition of that context also contains a declaration of the same
8285  // entity.
8286  //
8287  // Caution: this loop does things that might invalidate iterators into
8288  // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8289  while (!PendingOdrMergeChecks.empty()) {
8290  NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8291 
8292  // FIXME: Skip over implicit declarations for now. This matters for things
8293  // like implicitly-declared special member functions. This isn't entirely
8294  // correct; we can end up with multiple unmerged declarations of the same
8295  // implicit entity.
8296  if (D->isImplicit())
8297  continue;
8298 
8299  DeclContext *CanonDef = D->getDeclContext();
8300 
8301  bool Found = false;
8302  const Decl *DCanon = D->getCanonicalDecl();
8303 
8304  for (auto RI : D->redecls()) {
8305  if (RI->getLexicalDeclContext() == CanonDef) {
8306  Found = true;
8307  break;
8308  }
8309  }
8310  if (Found)
8311  continue;
8312 
8314  DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
8315  for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
8316  !Found && I != E; ++I) {
8317  for (auto RI : (*I)->redecls()) {
8318  if (RI->getLexicalDeclContext() == CanonDef) {
8319  // This declaration is present in the canonical definition. If it's
8320  // in the same redecl chain, it's the one we're looking for.
8321  if (RI->getCanonicalDecl() == DCanon)
8322  Found = true;
8323  else
8324  Candidates.push_back(cast<NamedDecl>(RI));
8325  break;
8326  }
8327  }
8328  }
8329 
8330  if (!Found) {
8331  // The AST doesn't like TagDecls becoming invalid after they've been
8332  // completed. We only really need to mark FieldDecls as invalid here.
8333  if (!isa<TagDecl>(D))
8334  D->setInvalidDecl();
8335 
8336  // Ensure we don't accidentally recursively enter deserialization while
8337  // we're producing our diagnostic.
8338  Deserializing RecursionGuard(this);
8339 
8340  std::string CanonDefModule =
8341  getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8342  Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8344  << CanonDef << CanonDefModule.empty() << CanonDefModule;
8345 
8346  if (Candidates.empty())
8347  Diag(cast<Decl>(CanonDef)->getLocation(),
8348  diag::note_module_odr_violation_no_possible_decls) << D;
8349  else {
8350  for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8351  Diag(Candidates[I]->getLocation(),
8352  diag::note_module_odr_violation_possible_decl)
8353  << Candidates[I];
8354  }
8355 
8356  DiagnosedOdrMergeFailures.insert(CanonDef);
8357  }
8358  }
8359 
8360  if (OdrMergeFailures.empty())
8361  return;
8362 
8363  // Ensure we don't accidentally recursively enter deserialization while
8364  // we're producing our diagnostics.
8365  Deserializing RecursionGuard(this);
8366 
8367  // Issue any pending ODR-failure diagnostics.
8368  for (auto &Merge : OdrMergeFailures) {
8369  // If we've already pointed out a specific problem with this class, don't
8370  // bother issuing a general "something's different" diagnostic.
8371  if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
8372  continue;
8373 
8374  bool Diagnosed = false;
8375  for (auto *RD : Merge.second) {
8376  // Multiple different declarations got merged together; tell the user
8377  // where they came from.
8378  if (Merge.first != RD) {
8379  // FIXME: Walk the definition, figure out what's different,
8380  // and diagnose that.
8381  if (!Diagnosed) {
8382  std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8383  Diag(Merge.first->getLocation(),
8384  diag::err_module_odr_violation_different_definitions)
8385  << Merge.first << Module.empty() << Module;
8386  Diagnosed = true;
8387  }
8388 
8389  Diag(RD->getLocation(),
8390  diag::note_module_odr_violation_different_definitions)
8392  }
8393  }
8394 
8395  if (!Diagnosed) {
8396  // All definitions are updates to the same declaration. This happens if a
8397  // module instantiates the declaration of a class template specialization
8398  // and two or more other modules instantiate its definition.
8399  //
8400  // FIXME: Indicate which modules had instantiations of this definition.
8401  // FIXME: How can this even happen?
8402  Diag(Merge.first->getLocation(),
8403  diag::err_module_odr_violation_different_instantiations)
8404  << Merge.first;
8405  }
8406  }
8407 }
8408 
8410  if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8411  ReadTimer->startTimer();
8412 }
8413 
8415  assert(NumCurrentElementsDeserializing &&
8416  "FinishedDeserializing not paired with StartedDeserializing");
8417  if (NumCurrentElementsDeserializing == 1) {
8418  // We decrease NumCurrentElementsDeserializing only after pending actions
8419  // are finished, to avoid recursively re-calling finishPendingActions().
8420  finishPendingActions();
8421  }
8422  --NumCurrentElementsDeserializing;
8423 
8424  if (NumCurrentElementsDeserializing == 0) {
8425  // Propagate exception specification updates along redeclaration chains.
8426  while (!PendingExceptionSpecUpdates.empty()) {
8427  auto Updates = std::move(PendingExceptionSpecUpdates);
8428  PendingExceptionSpecUpdates.clear();
8429  for (auto Update : Updates) {
8430  auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8431  SemaObj->UpdateExceptionSpec(Update.second,
8432  FPT->getExtProtoInfo().ExceptionSpec);
8433  }
8434  }
8435 
8436  diagnoseOdrViolations();
8437 
8438  if (ReadTimer)
8439  ReadTimer->stopTimer();
8440 
8441  // We are not in recursive loading, so it's safe to pass the "interesting"
8442  // decls to the consumer.
8443  if (Consumer)
8444  PassInterestingDeclsToConsumer();
8445  }
8446 }
8447 
8448 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
8449  if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8450  // Remove any fake results before adding any real ones.
8451  auto It = PendingFakeLookupResults.find(II);
8452  if (It != PendingFakeLookupResults.end()) {
8453  for (auto *ND : PendingFakeLookupResults[II])
8454  SemaObj->IdResolver.RemoveDecl(ND);
8455  // FIXME: this works around module+PCH performance issue.
8456  // Rather than erase the result from the map, which is O(n), just clear
8457  // the vector of NamedDecls.
8458  It->second.clear();
8459  }
8460  }
8461 
8462  if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8463  SemaObj->TUScope->AddDecl(D);
8464  } else if (SemaObj->TUScope) {
8465  // Adding the decl to IdResolver may have failed because it was already in
8466  // (even though it was not added in scope). If it is already in, make sure
8467  // it gets in the scope as well.
8468  if (std::find(SemaObj->IdResolver.begin(Name),
8469  SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8470  SemaObj->TUScope->AddDecl(D);
8471  }
8472 }
8473 
8474 ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
8475  const PCHContainerReader &PCHContainerRdr,
8476  StringRef isysroot, bool DisableValidation,
8477  bool AllowASTWithCompilerErrors,
8478  bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8479  bool UseGlobalIndex,
8480  std::unique_ptr<llvm::Timer> ReadTimer)
8481  : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
8482  OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
8483  FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
8484  Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
8485  Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
8486  ReadTimer(std::move(ReadTimer)),
8487  isysroot(isysroot), DisableValidation(DisableValidation),
8488  AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8489  AllowConfigurationMismatch(AllowConfigurationMismatch),
8490  ValidateSystemInputs(ValidateSystemInputs),
8491  UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
8492  CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8493  TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8494  NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8495  NumIdentifierLookupHits(0), NumSelectorsRead(0),
8496  NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8497  NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8498  NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8499  NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8500  NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8501  TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8502  PassingDeclsToConsumer(false), ReadingKind(Read_None) {
8503  SourceMgr.setExternalSLocEntrySource(this);
8504 }
8505 
8507  if (OwnsDeserializationListener)
8508  delete DeserializationListener;
8509 
8510  for (DeclContextVisibleUpdatesPending::iterator
8511  I = PendingVisibleUpdates.begin(),
8512  E = PendingVisibleUpdates.end();
8513  I != E; ++I) {
8514  for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
8515  F = I->second.end();
8516  J != F; ++J)
8517  delete J->first;
8518  }
8519 }
llvm::APInt ReadAPInt(const RecordData &Record, unsigned &Idx)
Read an integral value.
Definition: ASTReader.cpp:7935
Decl * GetExistingDecl(serialization::DeclID ID)
Resolve a declaration ID into a declaration. Return 0 if it's not been loaded yet.
Definition: ASTReader.cpp:6070
void addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role)
Adds this header to the given module.
Definition: ModuleMap.cpp:787
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
bool isPoisoned() const
Return true if this token has been poisoned.
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType) const
SmallVector< std::pair< llvm::BitstreamCursor, serialization::ModuleFile * >, 8 > CommentsCursors
Cursors for comments blocks.
Definition: ASTReader.h:2083
Defines the clang::ASTContext interface.
SourceLocation getEnd() const
bool FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name) override
Finds all the visible declarations with a given name. The current implementation of this method just ...
Definition: ASTReader.cpp:6418
ASTReadResult
The result of reading the control block of an AST file, which can fail for various reasons...
Definition: ASTReader.h:316
static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts, const PreprocessorOptions &ExistingPPOpts, DiagnosticsEngine *Diags, FileManager &FileMgr, std::string &SuggestedPredefines, const LangOptions &LangOpts)
Check the preprocessor options deserialized from the control block against the preprocessor options i...
Definition: ASTReader.cpp:482
unsigned HeaderRole
Whether this header is part of the module that we are building. This is an instance of ModuleMap::Mod...
Definition: HeaderSearch.h:63
SmallVector< UnresolvedExportDecl, 2 > UnresolvedExports
The set of export declarations that have yet to be resolved.
Definition: Basic/Module.h:247
CanQualType LongLongTy
Definition: ASTContext.h:825
void setInfo(const DeclarationNameLoc &Info)
std::string Name
The name of this module.
Definition: Basic/Module.h:52
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.
iterator begin() const
Definition: DeclBase.h:1070
Source range/offset of a preprocessed entity.
Definition: ASTBitCodes.h:168
Header getUmbrellaHeader() const
Retrieve the header that serves as the umbrella header for this module.
Definition: Basic/Module.h:394
std::vector< std::pair< std::string, bool > > Macros
IdentifierIterator * getIdentifiers() override
Retrieve an iterator into the set of all identifiers in all loaded AST files.
Definition: ASTReader.cpp:6905
Record code for the signature that identifiers this AST file.
Definition: ASTBitCodes.h:298
void * IdentifierLookupTable
A pointer to an on-disk hash table of opaque type IdentifierHashTable.
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:1405
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:113
Record code for potentially unused local typedef names.
Definition: ASTBitCodes.h:559
Record code for map of Objective-C class definition IDs to the ObjC categories in a module that are a...
Definition: ASTBitCodes.h:515
Smart pointer class that efficiently represents Objective-C method names.
static void updateModuleTimestamp(ModuleFile &MF)
Definition: ASTReader.cpp:3335
bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden) override
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
Definition: ASTReader.cpp:145
ASTReadResult ReadAST(const std::string &FileName, ModuleKind Type, SourceLocation ImportLoc, unsigned ClientLoadCapabilities)
Load the AST file designated by the given file name.
Definition: ASTReader.cpp:3345
static hash_value_type ComputeHash(Selector Sel)
Definition: ASTReader.cpp:650
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:242
A PointerType record.
Definition: ASTBitCodes.h:802
virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines)
Receives the preprocessor options.
Definition: ASTReader.h:171
CtorInitializerType
The different kinds of data that can occur in a CtorInitializer.
Definition: ASTBitCodes.h:1428
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
Definition: ASTContext.cpp:933
void setChangedSinceDeserialization()
Note that this identifier has changed since it was loaded from an AST file.
void AddTokenToBody(const Token &Tok)
Add the specified token to the replacement text for the macro.
Definition: MacroInfo.h:246
data_type ReadData(internal_key_type, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:952
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1194
NameKind
NameKind - The kind of name this object contains.
unsigned UseLibcxx
Use libc++ instead of the default libstdc++.
The macro directives history for a particular identifier.
Definition: ASTBitCodes.h:606
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:26
CanQualType OCLImage1dBufferTy
Definition: ASTContext.h:837
static bool startsWithASTFileMagic(BitstreamCursor &Stream)
Whether Stream starts with the AST/PCH file magic number 'CPCH'.
Definition: ASTReader.cpp:3532
void SetIdentifierInfo(unsigned ID, IdentifierInfo *II)
Definition: ASTReader.cpp:7212
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
Implements support for file system lookup, file system caching, and directory search management...
Definition: FileManager.h:115
The (signed) 'long long' type.
Definition: ASTBitCodes.h:720
A simple structure that captures a vtable use for the purposes of the ExternalSemaSource.
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
RAII class for safely pairing a StartedDeserializing call with FinishedDeserializing.
Defines the clang::FileManager interface and associated types.
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:5960
Record code for the source manager line table information, which stores information about #line direc...
Definition: ASTBitCodes.h:511
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type...
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...
ObjCXXARCStandardLibraryKind
Enumerate the kinds of standard library that.
DeclarationName getCXXConstructorName(CanQualType Ty)
The 'bool' or '_Bool' type.
Definition: ASTBitCodes.h:694
std::string ModuleUserBuildPath
The directory used for a user build.
CanQualType Char32Ty
Definition: ASTContext.h:824
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1581
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1272
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
Definition: ASTBitCodes.h:788
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1128
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:4819
void setArgumentList(IdentifierInfo *const *List, unsigned NumArgs, llvm::BumpPtrAllocator &PPAllocator)
Set the specified list of identifiers as the argument list for this macro.
Definition: MacroInfo.h:161
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1446
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:907
SourceLocation ReadSourceLocation(ModuleFile &ModuleFile, unsigned Raw) const
Read a source location from raw form.
Definition: ASTReader.h:1960
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type...
SourceLocation DirectImportLoc
The source location where the module was explicitly or implicitly imported in the local translation u...
const serialization::LocalRedeclarationsInfo * RedeclarationsMap
Array of redeclaration chain location information within this module file, sorted by the first declar...
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "...
Definition: Basic/Module.h:177
IdentifierInfo * getCXXLiteralIdentifier() const
ControlRecordTypes
Record types that occur within the control block.
Definition: ASTBitCodes.h:242
void addTopHeaderFilename(StringRef Filename)
Add a top-level header filename associated with this module.
Definition: Basic/Module.h:413
unsigned Generation
The generation of which this module file is a part.
void ReadComments() override
Loads comment ranges.
Definition: ASTReader.cpp:8022
std::vector< UnresolvedConflict > UnresolvedConflicts
The list of conflicts for which the module-id has not yet been resolved.
Definition: Basic/Module.h:291
Defines the SourceManager interface.
uint32_t IdentID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:125
The 'unknown any' placeholder type.
Definition: ASTBitCodes.h:748
void setWrittenWidthSpec(TypeSpecifierWidth written)
Definition: TypeLoc.h:573
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in...
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:1429
bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:93
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:546
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
Module * getSubmodule(serialization::SubmoduleID GlobalID)
Retrieve the submodule that corresponds to a global submodule ID.
Definition: ASTReader.cpp:7369
unsigned size() const
Number of modules loaded.
const unsigned int NUM_PREDEF_SELECTOR_IDS
The number of predefined selector IDs.
Definition: ASTBitCodes.h:147
SmallVector< uint64_t, 4 > PreloadSLocEntries
SLocEntries that we're going to preload.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, NamedDecl **Params, unsigned NumParams, SourceLocation RAngleLoc)
virtual void MacroRead(serialization::MacroID ID, MacroInfo *MI)
A macro was read from the AST file.
const SrcMgr::SLocEntry & getSLocEntry(FileID FID, bool *Invalid=nullptr) const
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:835
RetTy Visit(TypeLoc TyLoc)
ModuleManager::ModuleConstIterator ModuleConstIterator
Definition: ASTReader.h:352
void VisitFunctionTypeLoc(FunctionTypeLoc)
Definition: ASTReader.cpp:5529
ModuleKind Kind
The type of this module.
unsigned Begin
Raw source location of beginning of range.
Definition: ASTBitCodes.h:170
Defines the C++ template declaration subclasses.
Describes a source location entry (SLocEntry) for a macro expansion.
Definition: ASTBitCodes.h:584
Scope * TUScope
Definition: Sema.h:680
std::vector< std::string > Includes
An LValueReferenceType record.
Definition: ASTBitCodes.h:806
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration, or NULL if there is no previous declaration.
Definition: DeclBase.h:814
The placeholder type for builtin functions.
Definition: ASTBitCodes.h:764
void AddDecl(Decl *D)
Definition: Scope.h:272
static void completeRedeclChainForTemplateSpecialization(Decl *D)
Definition: ASTReader.cpp:5867
Defines the clang::MacroInfo and clang::MacroDirective classes.
Specifies the submodules that are imported by this submodule.
Definition: ASTBitCodes.h:644
std::string ModuleName
The name of the module.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:834
A record that stores the set of declarations that are lexically stored within a given DeclContext...
Definition: ASTBitCodes.h:1020
The module file is out-of-date.
IdentifierInfo * getAsIdentifierInfo() const
Specifies an umbrella directory.
Definition: ASTBitCodes.h:641
uint32_t DeclID
An ID number that refers to a declaration in an AST file.
Definition: ASTBitCodes.h:62
IdentifierInfo * getLocalIdentifier(ModuleFile &M, unsigned LocalID)
Definition: ASTReader.cpp:7303
CanQualType LongTy
Definition: ASTContext.h:825
unsigned LocalNumObjCCategoriesInMap
The number of redeclaration info entries in ObjCCategoriesMap.
void setHasLineDirectives()
Set the flag that indicates that this FileID has line table entries associated with it...
StringRef getOriginalSourceFile()
Retrieve the name of the original source file name for the primary module file.
Definition: ASTReader.h:1453
#define CHECK_TARGET_OPT(Field, Name)
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, ASTReaderListener &Listener)
Read the control block for the named AST file.
Definition: ASTReader.cpp:3968
A SubstTemplateTypeParmType record.
Definition: ASTBitCodes.h:844
QualType getRecordType(const RecordDecl *Decl) const
Decl * GetDecl(serialization::DeclID ID)
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:6094
Class that performs name lookup into a DeclContext stored in an AST file.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1118
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1862
void setFlag(TokenFlags Flag)
Set the specified flag.
Definition: Token.h:234
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:400
Wrapper for source info for typedefs.
Definition: TypeLoc.h:612
static hash_value_type ComputeHash(const DeclNameKey &Key)
Definition: ASTReader.cpp:848
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:83
A container of type source information.
Definition: Decl.h:60
Base class that describes a preprocessed entity, which may be a preprocessor directive or macro expan...
uint64_t GlobalBitOffset
The global bit offset (or base) of this module.
Record code for enabled OpenCL extensions.
Definition: ASTBitCodes.h:494
Record code for the module build directory.
Definition: ASTBitCodes.h:301
void * getAsOpaquePtr() const
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:3262
An ElaboratedType record.
Definition: ASTBitCodes.h:842
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:307
serialization::SelectorID BaseSelectorID
Base selector ID for selectors local to this module.
virtual void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II)
An identifier was deserialized from the AST file.
An UnresolvedUsingType record.
Definition: ASTBitCodes.h:846
unsigned getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it...
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1083
bool hasAttrEnumOperand() const
Definition: TypeLoc.h:730
ASTFileSignature Signature
The signature of the module file, which may be used along with size and modification time to identify...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2147
llvm::OnDiskIterableChainedHashTable< reader::ASTDeclContextNameLookupTrait > * NameLookupTableData
TypeLoc getNextTypeLoc() const
Definition: TypeLoc.h:367
An IncompleteArrayType record.
Definition: ASTBitCodes.h:814
A template template parameter that has been substituted for some other template name.
Definition: TemplateName.h:202
void addPendingMacro(IdentifierInfo *II, ModuleFile *M, uint64_t MacroDirectivesOffset)
Add a macro to deserialize its macro directive history.
Definition: ASTReader.cpp:1587
Specifies a header that is part of the module but must be textually included.
Definition: ASTBitCodes.h:663
const uint32_t * SLocEntryOffsets
Offsets for all of the source location entries in the AST file.
CXXBaseSpecifier ReadCXXBaseSpecifier(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Read a C++ base specifier.
Definition: ASTReader.cpp:7708
ARC's unbridged-cast placeholder type.
Definition: ASTBitCodes.h:758
CanQualType HalfTy
Definition: ASTContext.h:829
ArrayRef< ObjCMethodDecl * > getInstanceMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:6970
bool getWarningsAsErrors() const
Definition: Diagnostic.h:452
uint32_t IdentifierID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:54
An identifier, stored as an IdentifierInfo*.
The internal '__builtin_va_list' typedef.
Definition: ASTBitCodes.h:943
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.
void getExportedModules(SmallVectorImpl< Module * > &Exported) const
Appends this module's list of exported modules to Exported.
Manages the set of modules loaded by an AST reader.
Definition: ModuleManager.h:32
static Qualifiers fromOpaqueValue(unsigned opaque)
Definition: Type.h:215
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
QualType getVaListTagType() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
void ReadReferencedSelectors(SmallVectorImpl< std::pair< Selector, SourceLocation > > &Sels) override
Read the set of referenced selectors known to the external Sema source.
Definition: ASTReader.cpp:7122
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type...
const FileEntry * getASTFile() const
The serialized AST file for this module, if one was created.
Definition: Basic/Module.h:377
CXXCtorInitializer ** GetExternalCXXCtorInitializers(uint64_t Offset) override
Read the contents of a CXXCtorInitializer array.
Definition: ASTReader.cpp:5929
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1151
void VisitArrayTypeLoc(ArrayTypeLoc)
Definition: ASTReader.cpp:5498
void setPreambleFileID(FileID Preamble)
Set the file ID for the precompiled preamble.
Options for controlling the target.
Definition: TargetOptions.h:24
Wrapper of type source information for a type with non-trivial direct qualifiers. ...
Definition: TypeLoc.h:239
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:5785
bool hasAttrExprOperand() const
Definition: TypeLoc.h:725
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:5872
void dump()
Dump information about the AST reader to standard error.
Definition: ASTReader.cpp:6736
ModuleManager::ModuleReverseIterator ModuleReverseIterator
Definition: ASTReader.h:353
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:45
ExtProtoInfo - Extra information about a function prototype.
Definition: Type.h:3042
void InitializeSema(Sema &S) override
Initialize the semantic source with the Sema instance being used to perform semantic analysis on the ...
Definition: ASTReader.cpp:6775
const unsigned int NUM_PREDEF_DECL_IDS
The number of declaration IDs that are predefined.
Definition: ASTBitCodes.h:953
TemplateArgument ReadTemplateArgument(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Read a template argument.
Definition: ASTReader.cpp:7623
The value of the next COUNTER to dispense. [PP_COUNTER_VALUE, Val].
Definition: ASTBitCodes.h:407
unsigned getLineTableFilenameID(StringRef Str)
const DeclContext * getDefinitiveDeclContext(const DeclContext *DC)
Retrieve the "definitive" declaration that provides all of the visible entries for the given declarat...
Definition: ASTCommon.cpp:93
Specifies the umbrella header used to create this module, if any.
Definition: ASTBitCodes.h:635
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>". This is safe to be used inside an AST node, in contrast with TemplateArgumentListInfo.
Definition: TemplateBase.h:564
A namespace, stored as a NamespaceDecl*.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Definition: SourceManager.h:78
Record code for header search information.
Definition: ASTBitCodes.h:488
data_type ReadData(Selector, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:685
BlockCommandNamesTy BlockCommandNames
Command names to treat as block commands in comments. Should not include the leading backslash...
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:46
void setBegin(SourceLocation b)
std::string ModuleCachePath
The directory used for the module cache.
Describes a source location entry (SLocEntry) for a buffer.
Definition: ASTBitCodes.h:576
Used to hold and unique data used to represent #line information.
static StringRef bytes(const std::vector< T, Allocator > &v)
Definition: ASTWriter.cpp:63
bool hasAttrOperand() const
Definition: TypeLoc.h:735
off_t getSize() const
Definition: FileManager.h:86
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:634
Record code for the array of eagerly deserialized decls.
Definition: ASTBitCodes.h:378
static bool visit(ModuleFile &M, void *UserData)
Definition: ASTReader.cpp:6931
Defines the clang::Expr interface and subclasses for C++ expressions.
Selector ReadSelector(ModuleFile &M, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.h:1890
void setHasExternalVisibleStorage(bool ES=true)
State whether this DeclContext has external storage for declarations visible in this context...
Definition: DeclBase.h:1730
int SLocEntryBaseID
The base ID in the source manager's view of this module.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
ContinuousRangeMap< uint32_t, int, 2 > DeclRemap
Remapping table for declaration IDs in this module.
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1727
Record code for the array of redeclaration chains.
Definition: ASTBitCodes.h:530
MemoryBufferSizes getMemoryBufferSizes() const
void setTypeArgTInfo(unsigned i, TypeSourceInfo *TInfo)
Definition: TypeLoc.h:879
SourceLocation ImportLoc
The source location where this module was first imported.
void ReadTentativeDefinitions(SmallVectorImpl< VarDecl * > &TentativeDefs) override
Read the set of tentative definitions known to the external Sema source.
Definition: ASTReader.cpp:7068
An UnresolvedSet-like class that might not have been loaded from the external AST source yet...
iterator begin(DeclarationName Name)
begin - Returns an iterator for decls with the name 'Name'.
CanQualType OCLSamplerTy
Definition: ASTContext.h:840
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:40
void setIsGNUVarargs()
Definition: MacroInfo.h:202
std::string getFullModuleName() const
Retrieve the full name of this module, including the path from its top-level module.
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition: ASTBitCodes.h:38
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class...
DeclarationName getName() const
getName - Returns the embedded declaration name.
FunctionType::ExtInfo ExtInfo
Definition: Type.h:3057
A macro directive exported by a module. [PP_MODULE_MACRO, SubmoduleID, MacroID, (Overridden Submodule...
Definition: ASTBitCodes.h:610
void setLocalRangeEnd(SourceLocation L)
Definition: TypeLoc.h:1258
void addLazyDecl(ASTContext &C, uintptr_t ID, AccessSpecifier AS)
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:101
void disableFileContentsOverride(const FileEntry *File)
Disable overridding the contents of a file, previously enabled with overrideFileContents.
void setMainFileID(FileID FID)
Set the file ID for the main source file.
Specifies a top-level header that falls into this (sub)module.
Definition: ASTBitCodes.h:639
The block containing comments.
Definition: ASTBitCodes.h:227
SmallVectorImpl< ModuleFile * >::const_iterator ModuleConstIterator
This table allows us to fully hide how we implement multi-keyword caching.
AddModuleResult
The result of attempting to add a new module.
A library or framework to link against when an entity from this module is used.
Definition: Basic/Module.h:257
bool isNull() const
Definition: TypeLoc.h:95
void finalizeForWriting()
Finalizes the AST reader's state before writing an AST file to disk.
Definition: ASTReader.cpp:3810
bool isFromAST() const
Return true if the identifier in its current state was loaded from an AST file.
QualType getAutoType(QualType DeducedType, bool IsDecltypeAuto, bool IsDependent) const
C++11 deduced auto type.
CXXRecordDecl * getPreviousDecl()
Definition: DeclCXX.h:658
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:89
A C++ nested-name-specifier augmented with source location information.
Record the location of a macro definition.
CanQualType OCLImage2dArrayTy
Definition: ASTContext.h:838
The results of name lookup within a DeclContext. This is either a single result (with no stable stora...
Definition: DeclBase.h:1034
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition: DeclBase.h:1716
The 'char' type, when it is signed.
Definition: ASTBitCodes.h:708
static std::string resolveFileRelativeToOriginalDir(const std::string &Filename, const std::string &OriginalDir, const std::string &CurrDir)
If a header file is not found at the path that we expect it to be and the PCH file was moved from its...
Definition: ASTReader.cpp:1131
serialization::SelectorID getGlobalSelectorID(ModuleFile &F, unsigned LocalID) const
Retrieve the global selector ID that corresponds to this the local selector ID in a given module...
Definition: ASTReader.cpp:7457
void setBuiltinLoc(SourceLocation Loc)
Definition: TypeLoc.h:517
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1460
Specifies a header that has been explicitly excluded from this submodule.
Definition: ASTBitCodes.h:652
void setRBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1361
static SourceLocation getFromRawEncoding(unsigned Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size...
void ReadLateParsedTemplates(llvm::MapVector< const FunctionDecl *, LateParsedTemplate * > &LPTMap) override
Read the set of late parsed template functions for this source.
Definition: ASTReader.cpp:7184
The unsigned 128-bit integer type.
Definition: ASTBitCodes.h:937
ContinuousRangeMap< uint32_t, int, 2 > PreprocessedEntityRemap
Remapping table for preprocessed entity IDs in this module.
Record code for the module map file that was used to build this AST file.
Definition: ASTBitCodes.h:295
std::vector< Entry > UserEntries
User specified include entries.
An ExtVectorType record.
Definition: ASTBitCodes.h:820
Delete expressions that will be analyzed later.
Definition: ASTBitCodes.h:566
std::vector< SystemHeaderPrefix > SystemHeaderPrefixes
User-specified system header prefixes.
llvm::SmallPtrSet< ModuleFile *, 4 > HitSet
A set of module files in which we found a result.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
Definition: ASTMatchers.h:258
Helper class that saves the current stream position and then restores it when destroyed.
Definition: ASTReader.h:2095
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
CanQualType OCLEventTy
Definition: ASTContext.h:840
static CXXCtorInitializer * Create(ASTContext &Context, FieldDecl *Member, SourceLocation MemberLoc, SourceLocation L, Expr *Init, SourceLocation R, VarDecl **Indices, unsigned NumIndices)
Creates a new member initializer that optionally contains array indices used to describe an elementwi...
Definition: DeclCXX.cpp:1688
void ReadUndefinedButUsed(llvm::DenseMap< NamedDecl *, SourceLocation > &Undefined) override
Load the set of used but not defined functions or variables with internal linkage, or used but not defined internal functions.
Definition: ASTReader.cpp:7043
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1776
TemplateName ReadTemplateName(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Read a template name.
Definition: ASTReader.cpp:7564
bool isFileOverridden(const FileEntry *File)
Returns true if the file contents have been overridden.
virtual bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences)
Receives the language options.
Definition: ASTReader.h:119
DeclarationName getCXXDestructorName(CanQualType Ty)
method_range methods() const
Definition: DeclObjC.h:727
void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir, Twine NameAsWritten)
Sets the umbrella directory of the given module to the given directory.
Definition: ModuleMap.cpp:766
unsigned DetailedRecord
Whether we should maintain a detailed record of all macro definitions and expansions.
QualType getTypeOfType(QualType t) const
unsigned getNumProtocols() const
Definition: TypeLoc.h:898
Wrapper for source info for unresolved typename using decls.
Definition: TypeLoc.h:634
std::string OriginalDir
The directory that the PCH was originally created in. Used to allow resolving headers even after head...
void setKind(tok::TokenKind K)
Definition: Token.h:91
Sema * getSema()
Retrieve the semantic analysis object used to analyze the translation unit in which the precompiled h...
Definition: ASTReader.h:2066
void ReadExtVectorDecls(SmallVectorImpl< TypedefNameDecl * > &Decls) override
Read the set of ext_vector type declarations known to the external Sema source.
Definition: ASTReader.cpp:7100
An AttributedType record.
Definition: ASTBitCodes.h:866
An object-like macro definition. [PP_MACRO_OBJECT_LIKE, IdentInfoID, SLoc, IsUsed].
Definition: ASTBitCodes.h:594
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition: TypeLoc.h:1676
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1114
Describes one token. [PP_TOKEN, SLoc, Length, IdentInfoID, Kind, Flags].
Definition: ASTBitCodes.h:603
internal_key_type ReadKey(const unsigned char *d, unsigned)
Definition: ASTReader.cpp:664
An AdjustedType record.
Definition: ASTBitCodes.h:878
void ReadWeakUndeclaredIdentifiers(SmallVectorImpl< std::pair< IdentifierInfo *, WeakInfo > > &WI) override
Read the set of weak, undeclared identifiers known to the external Sema source.
Definition: ASTReader.cpp:7140
Describes a module or submodule.
Definition: Basic/Module.h:49
Record code for the diagnostic options table.
Definition: ASTBitCodes.h:279
void completeVisibleDeclsMap(const DeclContext *DC) override
Load all external visible decls in the given DeclContext.
Definition: ASTReader.cpp:6532
unsigned LocalNumHeaderFileInfos
The number of local HeaderFileInfo structures.
Record code for the set of ext_vector type names.
Definition: ASTBitCodes.h:422
static internal_key_type GetInternalKey(const FileEntry *FE)
Definition: ASTReader.cpp:1483
iterator end()
end - Returns an iterator that has 'finished'.
Record code for the headers search options table.
Definition: ASTBitCodes.h:285
static VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx)
Read a version tuple.
Definition: ASTReader.cpp:7971
llvm::Optional< ASTSourceDescriptor > getSourceDescriptor(unsigned ID) override
Return a descriptor for the corresponding module.
Definition: ASTReader.cpp:7401
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:443
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:170
const PPEntityOffset * PreprocessedEntityOffsets
Specifies the submodules that are re-exported from this submodule.
Definition: ASTBitCodes.h:647
TemplateParameterList ** TemplParamLists
Definition: Decl.h:566
serialization::MacroID BaseMacroID
Base macro ID for macros local to this module.
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
Definition: ASTBitCodes.h:162
QualType getParenType(QualType NamedType) const
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1994
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e...
Definition: Basic/Module.h:194
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:1514
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:488
A qualified template name, where the qualification is kept to describe the source code as written...
Definition: TemplateName.h:196
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:518
virtual void HandleInterestingDecl(DeclGroupRef D)
Definition: ASTConsumer.cpp:24
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
PreprocessedEntity * ReadPreprocessedEntity(unsigned Index) override
Read a preallocated preprocessed entity from the external source.
Definition: ASTReader.cpp:4616
CanQualType OCLImage2dTy
Definition: ASTContext.h:838
void setCaretLoc(SourceLocation Loc)
Definition: TypeLoc.h:1141
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1883
const LangOptions & getLangOpts() const
Definition: ASTContext.h:533
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:623
bool isAvailable() const
Determine whether this module is available for use within the current translation unit...
Definition: Basic/Module.h:313
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
TypeSourceInfo * GetTypeSourceInfo(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Reads a declarator info from the given record.
Definition: ASTReader.cpp:5674
bool isImplicit() const
Definition: DeclBase.h:503
const unsigned NumSpecialTypeIDs
The number of special type IDs.
Definition: ASTBitCodes.h:906
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1013
uint32_t Offset
Definition: CacheTokens.cpp:43
Describes a blob that contains the data for a buffer entry. This kind of record always directly follo...
Definition: ASTBitCodes.h:581
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1446
void ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:7551
std::string Message
The message provided to the user when there is a conflict.
Definition: Basic/Module.h:299
Wrapper for source info for functions.
Definition: TypeLoc.h:1243
Specifies a conflict with another module.
Definition: ASTBitCodes.h:658
The signed 128-bit integer type.
Definition: ASTBitCodes.h:934
CXXCtorInitializer ** ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Read a CXXCtorInitializer array.
Definition: ASTReader.cpp:7724
llvm::APSInt ReadAPSInt(const RecordData &Record, unsigned &Idx)
Read a signed integral value.
Definition: ASTReader.cpp:7944
A UnaryTransformType record.
Definition: ASTBitCodes.h:872
uint64_t readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record, unsigned &Idx)
Read a CXXBaseSpecifiers ID form the given record and return its global bit offset.
Definition: ASTReader.cpp:5948
An ObjCObjectType record.
Definition: ASTBitCodes.h:850
A ConstantArrayType record.
Definition: ASTBitCodes.h:812
std::string ReadPath(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:7964
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:592
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:696
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...
Definition: ASTReader.cpp:8081
TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, TemplateName replacement) const
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:135
serialization::SubmoduleID getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID)
Retrieve the global submodule ID given a module and its local ID number.
Definition: ASTReader.cpp:7357
Record code for #pragma optimize options.
Definition: ASTBitCodes.h:556
uint32_t BitOffset
Offset in the AST file.
Definition: ASTBitCodes.h:174
CXXTemporary * ReadCXXTemporary(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:7983
GlobalMethodPool MethodPool
Definition: Sema.h:958
Specifies a header that is private to this submodule but must be textually included.
Definition: ASTBitCodes.h:666
Record code for pending implicit instantiations.
Definition: ASTBitCodes.h:455
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:689
TypeLocReader(ASTReader &Reader, ModuleFile &F, const ASTReader::RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:5444
CanQualType PseudoObjectTy
Definition: ASTContext.h:834
bool needsExtraLocalData() const
Definition: TypeLoc.h:530
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1592
void setLazyBody(uint64_t Offset)
Definition: DeclObjC.h:491
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Definition: ASTReader.h:2057
Record code for #pragma diagnostic mappings.
Definition: ASTBitCodes.h:482
An ExtQualType record.
Definition: ASTBitCodes.h:798
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
Record code for floating point #pragma options.
Definition: ASTBitCodes.h:491
CommentRecordTypes
Record types used within a comments block.
Definition: ASTBitCodes.h:670
unsigned LocalNumRedeclarationsInMap
The number of redeclaration info entries in RedeclarationsMap.
data_type ReadData(internal_key_ref, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:1533
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr * > VL, ArrayRef< Expr * > IL, Expr *Step, Expr *CalcStep)
Creates clause with a list of variables VL and a linear step Step.
static internal_key_type ReadKey(const unsigned char *d, unsigned n)
Definition: ASTReader.cpp:732
CanQualType LongDoubleTy
Definition: ASTContext.h:828
void setMustBuildLookupTable()
Mark that there are external lexical declarations that we need to include in our lookup table (and th...
Definition: DeclBase.h:1701
void addExternalSource(ExternalSemaSource *E)
Registers an external source. If an external source already exists, creates a multiplex external sour...
Definition: Sema.cpp:312
unsigned IsFromModuleFile
Whether this module was loaded from a module file.
Definition: Basic/Module.h:162
std::string OriginalSourceFileName
The original source file name that was used to build the primary AST file, which may have been modifi...
Wrapper for source info for ObjC interfaces.
Definition: TypeLoc.h:969
Record code for the set of known namespaces, which are used for typo correction.
Definition: ASTBitCodes.h:501
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location...
Record code for an array of all of the (sub)modules that were imported by the AST file...
Definition: ASTBitCodes.h:522
serialization::DeclID BaseDeclID
Base declaration ID for declarations local to this module.
Present this diagnostic as an error.
ModuleManager::ModuleIterator ModuleIterator
Definition: ASTReader.h:351
SourceLocation FirstLoc
The first source location in this module.
void ReadPendingInstantiations(SmallVectorImpl< std::pair< ValueDecl *, SourceLocation > > &Pending) override
Read the set of pending instantiations known to the external Sema source.
Definition: ASTReader.cpp:7172
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition: Diagnostic.h:353
A BlockPointerType record.
Definition: ASTBitCodes.h:804
void setProtocolLoc(unsigned i, SourceLocation Loc)
Definition: TypeLoc.h:906
A MemberPointerType record.
Definition: ASTBitCodes.h:810
ContinuousRangeMap< uint32_t, int, 2 > SLocRemap
Remapping table for source locations in this module.
unsigned DisableModuleHash
Whether we should disable the use of the hash string within the module cache.
void setLocalRangeBegin(SourceLocation L)
Definition: TypeLoc.h:1251
void ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag)
Definition: ASTReader.cpp:4881
Represents an ObjC class declaration.
Definition: DeclObjC.h:851
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1141
unsigned getNumParams() const
Definition: TypeLoc.h:1289
void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 >> &Exprs) override
Definition: ASTReader.cpp:7053
The preprocessor keeps track of this information for each file that is #included. ...
Definition: HeaderSearch.h:39
uint64_t PreprocessorDetailStartOffset
The offset of the start of the preprocessor detail cursor.
CanQualType OCLImage3dTy
Definition: ASTContext.h:839
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type...
CanQualType UnsignedCharTy
Definition: ASTContext.h:826
Record code for the table of offsets into the block of source-location information.
Definition: ASTBitCodes.h:411
bool isInvalid() const
std::pair< uint32_t, DeclID > KindDeclIDPair
a Decl::Kind/DeclID pair.
Definition: ASTBitCodes.h:65
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:733
friend class ASTIdentifierIterator
Definition: ASTReader.h:340
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:1665
virtual bool needsInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.h:186
bool EqualKey(internal_key_ref a, internal_key_ref b)
Definition: ASTReader.cpp:1489
A SubstTemplateTypeParmPackType record.
Definition: ASTBitCodes.h:868
Objective-C "id" redefinition type.
Definition: ASTBitCodes.h:896
void ReadDelegatingConstructors(SmallVectorImpl< CXXConstructorDecl * > &Decls) override
Read the set of delegating constructors known to the external Sema source.
Definition: ASTReader.cpp:7089
static std::string ReadString(const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:7957
TypeCode
Record codes for each kind of type.
Definition: ASTBitCodes.h:796
Records the location of a macro expansion.
DiagnosticsEngine & getDiagnostics() const
virtual void SelectorRead(serialization::SelectorID iD, Selector Sel)
A selector was read from the AST file.
virtual bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain)
Receives the file system options.
Definition: ASTReader.h:148
void setUnderlyingTInfo(TypeSourceInfo *TI) const
Definition: TypeLoc.h:1637
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:107
Class that aids in the construction of nested-name-specifiers along with source-location information ...
unsigned getObjCOrBuiltinID() const
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
QualType getTemplateSpecializationType(TemplateName T, const TemplateArgument *Args, unsigned NumArgs, QualType Canon=QualType()) const
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers)...
Definition: Basic/Module.h:172
The block containing information about the source manager.
Definition: ASTBitCodes.h:210
IdentifierInfo * GetIdentifierInfo(ModuleFile &M, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.h:1829
Record code for the array describing the locations (in the LOCAL_REDECLARATIONS record) of the redecl...
Definition: ASTBitCodes.h:446
A VariableArrayType record.
Definition: ASTBitCodes.h:816
const FileEntry * getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:258
diag::Severity getExtensionHandlingBehavior() const
Definition: Diagnostic.h:516
const unsigned int NUM_PREDEF_PP_ENTITY_IDS
The number of predefined preprocessed entity IDs.
Definition: ASTBitCodes.h:199
bool isNamespace() const
Definition: DeclBase.h:1251
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
void setUsedForHeaderGuard(bool Val)
Definition: MacroInfo.h:275
ASTRecordTypes
Record types that occur within the AST block itself.
Definition: ASTBitCodes.h:316
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:866
Stmt * GetExternalDeclStmt(uint64_t Offset) override
Resolve the offset of a statement into a statement.
Definition: ASTReader.cpp:6148
unsigned NumTemplParamLists
Definition: Decl.h:559
Defines the major attributes of a submodule, including its name and parent.
Definition: ASTBitCodes.h:632
llvm::BitstreamCursor Stream
The main bitstream cursor for the main block.
std::string CurrentModule
The name of the current module.
Definition: LangOptions.h:96
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...
Represents a ValueDecl that came out of a declarator. Contains type source information through TypeSo...
Definition: Decl.h:586
ModuleHeaderRole
Flags describing the role of a module header.
Definition: ModuleMap.h:72
ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, unsigned PriorGeneration)
Definition: ASTReader.cpp:6925
ModuleKind
Specifies the kind of module that has been loaded.
A dependent template name that has not been resolved to a template (or set of templates).
Definition: TemplateName.h:199
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:442
Record code for the preprocessor options table.
Definition: ASTBitCodes.h:288
void SetGloballyVisibleDecls(IdentifierInfo *II, const SmallVectorImpl< uint32_t > &DeclIDs, SmallVectorImpl< Decl * > *Decls=nullptr)
Set the globally-visible declarations associated with the given identifier.
Definition: ASTReader.cpp:7237
ASTContext * Context
std::vector< bool > & Stack
void ReadModuleMapFile(StringRef ModuleMapPath) override
Definition: ASTReader.cpp:80
void setSizeExpr(Expr *Size)
Definition: TypeLoc.h:1372
unsigned LocalNumSLocEntries
The number of source location entries in this AST file.
void setCFConstantStringType(QualType T)
const SmallVectorImpl< AnnotatedLine * >::const_iterator End
Captures information about a #pragma weak directive.
Definition: Weak.h:25
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1891
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
static bool isAcceptableASTFile(StringRef Filename, FileManager &FileMgr, const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts, const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts, std::string ExistingModuleCachePath)
Determine whether the given AST file is acceptable to load into a translation unit with the given lan...
Definition: ASTReader.cpp:4161
ID
Defines the set of possible language-specific address spaces.
Definition: AddressSpaces.h:27
Record code for the table of offsets of each macro ID.
Definition: ASTBitCodes.h:544
const DirectoryEntry * Entry
Definition: Basic/Module.h:122
const uint32_t * TypeOffsets
Offset of each type within the bitstream, indexed by the type ID, or the representation of a Type*...
void resolvePendingMacro(IdentifierInfo *II, const PendingMacroInfo &PMInfo)
Definition: ASTReader.cpp:1736
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
SourceManager & SM
NameKind getNameKind() const
getNameKind - Determine what kind of name this is.
unsigned UsePredefines
Initialize the preprocessor with the compiler and target specific predefines.
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1869
static NestedNameSpecifier * SuperSpecifier(const ASTContext &Context, CXXRecordDecl *RD)
Returns the nested name specifier representing the __super scope for the given CXXRecordDecl.
bool isInFileID(SourceLocation Loc, FileID FID, unsigned *RelativeOffset=nullptr) const
Given a specific FileID, returns true if Loc is inside that FileID chunk and sets relative offset (of...
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:1469
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, const TemplateArgumentListInfo &Args) const
A record containing CXXBaseSpecifiers.
Definition: ASTBitCodes.h:1089
ASTReaderListener implementation to validate the information of the PCH file against an initialized P...
Definition: ASTReader.h:252
int * Depth
uint64_t Signature
The module signature.
Definition: Basic/Module.h:70
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:110
An TemplateSpecializationType record.
Definition: ASTBitCodes.h:854
An ObjCObjectPointerType record.
Definition: ASTBitCodes.h:838
Type source information for an attributed type.
Definition: TypeLoc.h:716
An ObjCInterfaceType record.
Definition: ASTBitCodes.h:836
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
const Type * getTypePtrOrNull() const
Definition: Type.h:5020
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1843
HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE) override
Read the header file information for the given file entry.
Definition: ASTReader.cpp:4872
StringRef getName() const
Return the actual identifier string.
Record code for the array of VTable uses.
Definition: ASTBitCodes.h:432
The 'char' type, when it is unsigned.
Definition: ASTBitCodes.h:696
void setHasCommaPasting()
Definition: MacroInfo.h:216
Record code for the target options table.
Definition: ASTBitCodes.h:260
void setModeAttr(bool written)
Definition: TypeLoc.h:593
SwitchCase * getSwitchCaseWithID(unsigned ID)
Retrieve the switch-case statement with the given ID.
Definition: ASTReader.cpp:8013
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:7345
The directory that the PCH was originally created in.
Definition: ASTBitCodes.h:268
ExternalLoadResult
Enumeration describing the result of loading information from an external source. ...
DiagnosticBuilder Diag(unsigned DiagID)
Report a diagnostic.
Definition: ASTReader.cpp:7990
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
virtual bool visitInputFile(StringRef Filename, bool isSystem, bool isOverridden)
if needsInputFileVisitation returns true, this is called for each non-system input file of the AST Fi...
Definition: ASTReader.h:196
CanQualType OCLImage1dTy
Definition: ASTContext.h:837
QualType readType(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Read a type from the current position in the given record, which was read from the given AST file...
Definition: ASTReader.h:1585
Declaration of a template type parameter.
FileID createFileID(const FileEntry *SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, unsigned LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
std::string WorkingDir
If set, paths are resolved as if the working directory was set to the value of WorkingDir.
unsigned LocalNumIdentifiers
The number of identifiers in this AST file.
void ReadUsedVTables(SmallVectorImpl< ExternalVTableUse > &VTables) override
Read the set of used vtables known to the external Sema source.
Definition: ASTReader.cpp:7160
The placeholder type for overloaded function sets.
Definition: ASTBitCodes.h:728
Implements an efficient mapping from strings to IdentifierInfo nodes.
Defines implementation details of the clang::SourceManager class.
SourceManager & SourceMgr
Definition: Format.cpp:1205
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:4143
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition: Basic/Module.h:201
Record code for the table of offsets to entries in the preprocessing record.
Definition: ASTBitCodes.h:429
unsigned LocalNumCXXBaseSpecifiers
The number of C++ base specifier sets in this AST file.
std::unique_ptr< llvm::MemoryBuffer > Buffer
The memory buffer that stores the data associated with this AST file.
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2358
Loading the external information has succeeded.
ContinuousRangeMap< uint32_t, int, 2 > IdentifierRemap
Remapping table for identifier IDs in this module.
llvm::BitstreamCursor SLocEntryCursor
Cursor used to read source location entries.
void setInvalidDecl(bool Invalid=true)
Definition: DeclBase.cpp:96
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:812
Defines version macros and version-related utility functions for Clang.
The OpenCL 'half' / ARM NEON __fp16 type.
Definition: ASTBitCodes.h:756
llvm::support::ulittle32_t LE32DeclID
Pair of begin/end iterators for DeclIDs.
Defines the clang::Preprocessor interface.
ArgKind
The kind of template argument we're storing.
Definition: TemplateBase.h:42
serialization::DeclID getGlobalDeclID(ModuleFile &F, serialization::LocalDeclID LocalID) const
Map from a local declaration ID within a given module to a global declaration ID. ...
Definition: ASTReader.cpp:5984
The block containing the detailed preprocessing record.
Definition: ASTBitCodes.h:221
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:218
#define bool
Definition: stdbool.h:31
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:1288
DeclContext * getDeclContext()
Definition: DeclBase.h:381
static LineEntry get(unsigned Offs, unsigned Line, int Filename, SrcMgr::CharacteristicKind FileKind, unsigned IncludeOffset)
void setWrittenSignSpec(TypeSpecifierSign written)
Definition: TypeLoc.h:559
llvm::BitstreamCursor InputFilesCursor
The cursor to the start of the input-files block.
unsigned LocalNumMacros
The number of macros in this AST file.
SourceRange ReadSourceRange(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Read a source range.
Definition: ASTReader.cpp:7927
A record containing CXXCtorInitializers.
Definition: ASTBitCodes.h:1091
CanQualType ShortTy
Definition: ASTContext.h:825
unsigned UseBuiltinIncludes
Include the compiler builtin includes.
Record code for the original file that was used to generate the AST file, including both its file ID ...
Definition: ASTBitCodes.h:265
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2001
Represents a C++ template name within the type system.
Definition: TemplateName.h:175
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used...
Definition: Basic/Module.h:274
QualType getLocalType(ModuleFile &F, unsigned LocalID)
Resolve a local type ID within a given AST file into a type.
Definition: ASTReader.cpp:5780
Information about a module that has been loaded by the ASTReader.
A namespace alias, stored as a NamespaceAliasDecl*.
void visit(bool(*Visitor)(ModuleFile &M, void *UserData), void *UserData, llvm::SmallPtrSetImpl< ModuleFile * > *ModuleFilesHit=nullptr)
Visit each of the modules.
void ReadCounter(const serialization::ModuleFile &M, unsigned Value) override
Receives COUNTER value.
Definition: ASTReader.cpp:128
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:827
An iterator that walks over all of the known identifiers in the lookup table.
SmallVector< uint64_t, 1 > ObjCCategories
The Objective-C category lists for categories known to this module.
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:982
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1585
FileID OriginalSourceFileID
The file ID for the original source file that was used to build this AST file.
A FunctionProtoType record.
Definition: ASTBitCodes.h:824
void setInheritConstructors(bool Inherit=true)
Set that this base class's constructors should be inherited.
Definition: DeclCXX.h:219
Describes a source location entry (SLocEntry) for a file.
Definition: ASTBitCodes.h:573
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
Wrapper for source info for enum types.
Definition: TypeLoc.h:672
bool isInstanceMethod() const
Definition: DeclObjC.h:419
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:85
std::string FileName
The file name of the module file.
void setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader, Twine NameAsWritten)
Sets the umbrella header of the given module to the given header.
Definition: ModuleMap.cpp:758
void setEllipsisLoc(SourceLocation Loc)
Definition: TypeLoc.h:1948
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:651
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:624
Record code for an update to a decl context's lookup table.
Definition: ASTBitCodes.h:467
void setHasBaseTypeAsWritten(bool HasBaseType)
Definition: TypeLoc.h:925
Record the location of an inclusion directive, such as an #include or #import statement.
bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the target options.
Definition: ASTReader.cpp:312
InclusionKind
The kind of inclusion directives known to the preprocessor.
The width of the "fast" qualifier mask.
Definition: Type.h:156
QualType withFastQualifiers(unsigned TQs) const
Definition: Type.h:779
unsigned ModulesValidateOncePerBuildSession
If true, skip verifying input files used by modules if the module was already verified during this bu...
SourceLocation createExpansionLoc(SourceLocation Loc, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd, unsigned TokLength, int LoadedID=0, unsigned LoadedOffset=0)
Return a new SourceLocation that encodes the fact that a token from SpellingLoc should actually be re...
Record code for the filesystem options table.
Definition: ASTBitCodes.h:282
struct CXXOpName CXXOperatorName
a DecltypeType record.
Definition: ASTBitCodes.h:840
DeclarationName getDeclName() const
Definition: Decl.h:189
Trait class used to search the on-disk hash table containing all of the header search information...
QualType getSubstTemplateTypeParmPackType(const TemplateTypeParmType *Replaced, const TemplateArgument &ArgPack)
Retrieve a.
void insertOrReplace(const value_type &Val)
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method)
Add the given method to the list of globally-known methods.
void deduplicateMergedDefinitonsFor(NamedDecl *ND)
Clean up the merged definition list. Call this if you might have added duplicates into the list...
Definition: ASTContext.cpp:881
void StartedDeserializing() override
Notify ASTReader that we started deserialization of a decl or type so until FinishedDeserializing is ...
Definition: ASTReader.cpp:8409
DirectoryName getUmbrellaDir() const
Retrieve the directory for which this module serves as the umbrella.
Information about a header directive as found in the module map file.
Definition: Basic/Module.h:111
The result type of a method or function.
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1668
unsigned SLocEntryBaseOffset
The base offset in the source manager's view of this module.
Record code for the table of offsets of each identifier ID.
Definition: ASTBitCodes.h:349
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1785
SmallVector< uint64_t, 16 > PreloadedDeclIDs
Definition: ASTReader.h:2061
Record code for undefined but used functions and variables that need a definition in this TU...
Definition: ASTBitCodes.h:550
void ReadDeclarationNameInfo(ModuleFile &F, DeclarationNameInfo &NameInfo, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:7541
A DependentNameType record.
Definition: ASTBitCodes.h:856
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:204
CanQualType SignedCharTy
Definition: ASTContext.h:825
Record code for the identifier table.
Definition: ASTBitCodes.h:368
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateDecl *Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Basic/Module.h:372
uint64_t BuildSessionTimestamp
The time in seconds when the build session started.
NestedNameSpecifier * ReadNestedNameSpecifier(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:7809
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...
The placeholder type for bound member functions.
Definition: ASTBitCodes.h:750
void setIsUsed(bool Val)
Set the value of the IsUsed flag.
Definition: MacroInfo.h:149
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:31
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:460
const DirectoryEntry * Directory
The build directory of this module. This is the directory in which the module is notionally built...
Definition: Basic/Module.h:64
void overrideFileContents(const FileEntry *SourceFile, llvm::MemoryBuffer *Buffer, bool DoNotFree)
Override the contents of the given source file by providing an already-allocated buffer.
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1158
QualType getPackExpansionType(QualType Pattern, Optional< unsigned > NumExpansions)
const unsigned int NUM_PREDEF_IDENT_IDS
The number of predefined identifier IDs.
Definition: ASTBitCodes.h:128
void setTypeofLoc(SourceLocation Loc)
Definition: TypeLoc.h:1578
SpecifierKind
The kind of specifier that completes this nested name specifier.
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:546
void makeNamesVisible(const HiddenNames &Names, Module *Owner)
Make the names within this set of hidden names visible.
Definition: ASTReader.cpp:3248
StringRef Next() override
Retrieve the next string in the identifier table and advances the iterator for the following string...
Definition: ASTReader.cpp:6884
The 'unsigned long long' type.
Definition: ASTBitCodes.h:706
A template template parameter pack that has been substituted for a template template argument pack...
Definition: TemplateName.h:206
Wrapper for source info for arrays.
Definition: TypeLoc.h:1346
virtual void ExtractPCH(llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const =0
Record code for the set of source location entries that need to be preloaded by the AST reader...
Definition: ASTBitCodes.h:419
CanQualType OverloadTy
Definition: ASTContext.h:832
Special internal key for declaration names. The hash table creates keys for comparison; we do not cre...
The list of delegating constructor declarations.
Definition: ASTBitCodes.h:497
Information about a FileID, basically just the logical file that it represents and include stack info...
void setSourceOrder(int pos)
Set the source order of this initializer.
Definition: DeclCXX.h:2093
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:208
void setAttrOperandParensRange(SourceRange range)
Definition: TypeLoc.h:789
void setIsFunctionLike()
Definition: MacroInfo.h:196
const unsigned char * SelectorLookupTableData
A pointer to the character data that comprises the selector table.
Encapsulates changes to the "macros namespace" (the location where the macro name became active...
Definition: MacroInfo.h:308
bool ReadFullVersionInformation(StringRef FullVersion) override
Receives the full Clang version information.
Definition: ASTReader.cpp:72
#define false
Definition: stdbool.h:33
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
CanQualType BuiltinFnTy
Definition: ASTContext.h:833
ContinuousRangeMap< uint32_t, int, 2 > SelectorRemap
Remapping table for selector IDs in this module.
ExternalLoadResult FindExternalLexicalDecls(const DeclContext *DC, bool(*isKindWeWant)(Decl::Kind), SmallVectorImpl< Decl * > &Decls) override
Read all of the declarations lexically stored in a declaration context.
Definition: ASTReader.cpp:6213
Kind
std::string ABI
If given, the name of the target ABI to use.
Definition: TargetOptions.h:37
void setASTFile(const FileEntry *File)
Set the serialized AST file for the top-level module of this module.
Definition: Basic/Module.h:382
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:3330
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:3028
void LoadSelector(Selector Sel)
Load a selector from disk, registering its ID if it exists.
Definition: ASTReader.cpp:7207
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1876
SmallVectorImpl< AnnotatedLine * >::const_iterator Next
serialization::IdentID BaseIdentifierID
Base identifier ID for identifiers local to this module.
MacroInfo * ReadMacroRecord(ModuleFile &F, uint64_t Offset)
Reads the macro record located at the given offset.
Definition: ASTReader.cpp:1357
const uint32_t * CXXCtorInitializersOffsets
Offset of each C++ ctor initializer list within the bitstream, indexed by the C++ ctor initializer li...
File is a PCH file treated as the preamble.
ContinuousRangeMap< unsigned, int, 2 > SLocRemap
Definition: ASTUnit.cpp:2511
const char * getName() const
Definition: FileManager.h:84
static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method)
Move the given method to the back of the global list of methods.
Definition: ASTReader.cpp:3220
void MakeSuper(ASTContext &Context, CXXRecordDecl *RD, SourceLocation SuperLoc, SourceLocation ColonColonLoc)
Turns this (empty) nested-name-specifier into '__super' nested-name-specifier.
ExternCContextDecl * getExternCContextDecl() const
Definition: ASTContext.cpp:894
Encodes a location in the source. The SourceManager can decode this to get at the full include stack...
unsigned UseStandardSystemIncludes
Include the system standard include search directories.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, StringRef ExistingModuleCachePath, DiagnosticsEngine *Diags, const LangOptions &LangOpts)
Definition: ASTReader.cpp:608
const Type * getTypePtr() const
Definition: Type.h:5016
Record code for the language options table.
Definition: ASTBitCodes.h:257
A record that stores the set of declarations that are visible from a given DeclContext.
Definition: ASTBitCodes.h:1028
CanQualType Int128Ty
Definition: ASTContext.h:825
void setLength(unsigned Len)
Definition: Token.h:133
Specifies a library or framework to link against.
Definition: ASTBitCodes.h:654
Record code for file ID of the file or buffer that was used to generate the AST file.
Definition: ASTBitCodes.h:272
Represents a C++ temporary.
Definition: ExprCXX.h:1001
void InitializeContext()
Initializes the ASTContext.
Definition: ASTReader.cpp:3676
Specifies a header that falls into this (sub)module.
Definition: ASTBitCodes.h:637
std::string ImplicitPCHInclude
The implicit PCH included at the start of the translation unit, or empty.
Record code for the table of offsets to CXXBaseSpecifier sets.
Definition: ASTBitCodes.h:479
ContinuousRangeMap< uint32_t, int, 2 > SubmoduleRemap
Remapping table for submodule IDs in this module.
void setUsed(bool Used=true)
Definition: Weak.h:36
A ComplexType record.
Definition: ASTBitCodes.h:800
Record code for special CUDA declarations.
Definition: ASTBitCodes.h:485
OverloadedOperatorKind getCXXOverloadedOperator() const
Options for controlling the compiler diagnostics engine.
NameVisibilityKind NameVisibility
The visibility of names within this particular module.
Definition: Basic/Module.h:213
An identifier-lookup iterator that enumerates all of the identifiers stored within a set of AST files...
Definition: ASTReader.cpp:6853
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2694
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template apply...
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:7032
PredefinedTypeIDs
Predefined type IDs.
Definition: ASTBitCodes.h:688
llvm::BitstreamReader StreamFile
The bitstream reader from which we'll read the AST file.
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
All of the names in this module are hidden.
Definition: Basic/Module.h:207
File is an implicitly-loaded module.
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:685
void setProtocolRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:894
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:53
bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain, std::string &SuggestedPredefines) override
Receives the preprocessor options.
Definition: ASTReader.cpp:121
void setIsC99Varargs()
Varargs querying methods. This can only be set for function-like macros.
Definition: MacroInfo.h:201
MacroInfo * getMacro(serialization::MacroID ID)
Retrieve the macro with the given ID.
Definition: ASTReader.cpp:7319
uint64_t SizeInBits
The size of this file, in bits.
TemplateParameterList * ReadTemplateParameterList(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Read a template parameter list.
Definition: ASTReader.cpp:7666
void ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, bool ReportDiags=true)
Definition: Warnings.cpp:44
bool isDeclIDFromModule(serialization::GlobalDeclID ID, ModuleFile &M) const
Returns true if global DeclID ID originated from module M.
Definition: ASTReader.cpp:5995
ModuleReverseIterator rbegin()
Reverse iterator to traverse all loaded modules. This is in source order.
Record code for the offsets of each decl.
Definition: ASTBitCodes.h:341
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:186
void ReadMethodPool(Selector Sel) override
Load the contents of the global method pool for a given selector.
Definition: ASTReader.cpp:6996
void * SelectorLookupTable
A pointer to an on-disk hash table of opaque type ASTSelectorLookupTable.
Metadata for submodules as a whole.
Definition: ASTBitCodes.h:629
const uint32_t * IdentifierOffsets
Offsets into the identifier table data.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
Class that performs lookup for a selector's entries in the global method pool stored in an AST file...
A TypeOfExprType record.
Definition: ASTBitCodes.h:828
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:90
Record code for late parsed template functions.
Definition: ASTBitCodes.h:553
CanQualType FloatTy
Definition: ASTContext.h:828
const FileEntry * Entry
Definition: Basic/Module.h:113
Defines the clang::TargetOptions class.
void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc)
Turn this (empty) nested-name-specifier into the global nested-name-specifier '::'.
QualType getIncompleteArrayType(QualType EltTy, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type...
void setDefinitionEndLoc(SourceLocation EndLoc)
Set the location of the last token in the macro.
Definition: MacroInfo.h:123
virtual bool ReadFullVersionInformation(StringRef FullVersion)
Receives the full Clang version information.
Definition: ASTReader.h:109
std::vector< std::string > Features
Definition: TargetOptions.h:47
unsigned LocalNumDecls
The number of declarations in this AST file.
The internal 'instancetype' typedef.
Definition: ASTBitCodes.h:940
CanQualType VoidTy
Definition: ASTContext.h:817
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:77
unsigned getNumTypeArgs() const
Definition: TypeLoc.h:870
Information about the contents of a DeclContext.
Describes the categories of an Objective-C class.
Definition: ASTBitCodes.h:1462
uint32_t MacroID
An ID number that refers to a macro in an AST file.
Definition: ASTBitCodes.h:131
const FileInfo & getFile() const
The AST block, which acts as a container around the full AST block.
Definition: ASTBitCodes.h:206
RefQualifierKind
The kind of C++0x ref-qualifier associated with a function type, which determines whether a member fu...
Definition: Type.h:1200
Record code for the list of other AST files made available by this AST file but not actually used by ...
Definition: ASTBitCodes.h:305
The __va_list_tag placeholder type.
Definition: ASTBitCodes.h:762
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1831
void setWrittenTypeSpec(TypeSpecifierType written)
Definition: TypeLoc.h:582
Objective-C "SEL" redefinition type.
Definition: ASTBitCodes.h:900
std::vector< std::string > FeaturesAsWritten
The list of target specific features to enable or disable, as written on the command line...
Definition: TargetOptions.h:43
SourceLocation getBegin() const
void setAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1216
lookup_result lookup(DeclarationName Name) const
Definition: DeclBase.cpp:1339
void setLBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1354
QualType getAttributedType(AttributedType::Kind attrKind, QualType modifiedType, QualType equivalentType)
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:172
Updates[]
Definition: OpenMPClause.h:303
An InjectedClassNameType record.
Definition: ASTBitCodes.h:848
FileID getMainFileID() const
Returns the FileID of the main source file.
bool isFileContext() const
Definition: DeclBase.h:1239
const serialization::DeclID * FileSortedDecls
Array of file-level DeclIDs sorted by file.
Record code for the extra statistics we gather while generating an AST file.
Definition: ASTBitCodes.h:391
bool getEnableAllWarnings() const
Definition: Diagnostic.h:448
static Decl * getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID)
Definition: ASTReader.cpp:6032
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
Definition: ASTContext.cpp:927
virtual void visitImport(StringRef Filename)
If needsImportVisitation returns true, this is called for each AST file imported by this AST file...
Definition: ASTReader.h:206
static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, bool Complain)
Definition: ASTReader.cpp:328
std::vector< InputFile > InputFilesLoaded
The input files that have been loaded from this AST file.
The module file was just loaded in response to this call.
virtual IdentifierInfo * get(const char *NameStart, const char *NameEnd)
Retrieve the IdentifierInfo for the named identifier.
Definition: ASTReader.cpp:6827
DeclarationName ReadDeclarationName(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Read a declaration name.
Definition: ASTReader.cpp:7470
HashTableTy::const_iterator iterator
unsigned ComputeHash(Selector Sel)
Definition: ASTCommon.cpp:81
ArrayRef< ObjCMethodDecl * > getFactoryMethods() const
Retrieve the instance methods found by this visitor.
Definition: ASTReader.cpp:6975
const char * HeaderFileInfoTableData
Actual data for the on-disk hash table of header file information.
void markIdentifierUpToDate(IdentifierInfo *II)
Note that this identifier is up-to-date.
Definition: ASTReader.cpp:1725
const llvm::support::unaligned_uint64_t * InputFileOffsets
Offsets for all of the input file entries in the AST file.
const char * getName() const
Definition: FileManager.h:45
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:555
File is a PCH file treated as the actual main file.
llvm::APFloat ReadAPFloat(const RecordData &Record, const llvm::fltSemantics &Sem, unsigned &Idx)
Read a floating-point value.
Definition: ASTReader.cpp:7950
Record code for referenced selector pool.
Definition: ASTBitCodes.h:437
The input file that has been loaded from this AST file, along with bools indicating whether this was ...
bool isLocalSourceLocation(SourceLocation Loc) const
Returns true if Loc did not come from a PCH/Module.
std::vector< std::string > MacroIncludes
The injected class name of a C++ class template or class template partial specialization. Used to record that a type was spelled with a bare identifier rather than as a template-id; the equivalent for non-templated classes is just RecordType.
Definition: Type.h:4082
Record code for the set of non-builtin, special types.
Definition: ASTBitCodes.h:387
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1265
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1439
void setTypeArgsLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:859
CanQualType UnsignedShortTy
Definition: ASTContext.h:826
const uint32_t * MacroOffsets
Offsets of macros in the preprocessor block.
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2576
unsigned LocalNumSelectors
The number of selectors new to this file.
Record code for a decl replacement block.
Definition: ASTBitCodes.h:462
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T-> getSizeExpr()))
CanQualType CharTy
Definition: ASTContext.h:819
unsigned NextIndex
Represents a template argument.
Definition: TemplateBase.h:39
Record code for the list of other AST files imported by this AST file.
Definition: ASTBitCodes.h:249
Selector getLocalSelector(ModuleFile &M, unsigned LocalID)
Retrieve a selector from the given module with its local ID number.
Definition: ASTReader.cpp:7418
Describes a macro definition within the preprocessing record.
Definition: ASTBitCodes.h:619
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl. It will iterate at least once ...
Definition: DeclBase.h:803
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
const ASTTemplateArgumentListInfo * ReadASTTemplateArgumentListInfo(ModuleFile &F, const RecordData &Record, unsigned &Index)
Definition: ASTReader.cpp:5850
A conflict between two modules.
Definition: Basic/Module.h:294
DeclContextInfosMap DeclContextInfos
Information about the lexical and visible declarations for each DeclContext.
void setClassTInfo(TypeSourceInfo *TI)
Definition: TypeLoc.h:1168
bool ReadSLocEntry(int ID) override
Read the source location entry with index ID.
Definition: ASTReader.cpp:1159
bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain) override
Receives the header search options.
Definition: ASTReader.cpp:625
Record code for the module name.
Definition: ASTBitCodes.h:291
Selector getObjCSelector() const
TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, const TemplateArgument &ArgPack) const
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:835
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:2014
void setDeserializationListener(ASTDeserializationListener *Listener, bool TakeOwnership=false)
Set the AST deserialization listener.
Definition: ASTReader.cpp:642
Describes an inclusion directive within the preprocessing record.
Definition: ASTBitCodes.h:623
QualType getCanonicalTemplateSpecializationType(TemplateName T, const TemplateArgument *Args, unsigned NumArgs) const
not evaluated yet, for special member function
Record code for a file sorted array of DeclIDs in a module.
Definition: ASTBitCodes.h:518
void setAmpAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1229
CanQualType NullPtrTy
Definition: ASTContext.h:831
Record code for the array of Objective-C categories (including extensions).
Definition: ASTBitCodes.h:537
void updateOutOfDateIdentifier(IdentifierInfo &II) override
Update an out-of-date identifier.
Definition: ASTReader.cpp:1700
void reserve(ASTContext &C, unsigned N)
Specifies a configuration macro for this module.
Definition: ASTBitCodes.h:656
void ReadDefinedMacros() override
Read the set of macros defined by this external macro source.
Definition: ASTReader.cpp:1594
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:311
PreprocessorDetailRecordTypes
Record types used within a preprocessor detail block.
Definition: ASTBitCodes.h:614
static std::pair< GlobalModuleIndex *, ErrorCode > readIndex(StringRef Path)
Read a global index file for the given directory.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:22
SmallVector< uint64_t, 1 > RedeclarationChains
The redeclaration chains for declarations local to this module file.
bool ReadFileSystemOptions(const FileSystemOptions &FSOpts, bool Complain) override
Receives the file system options.
Definition: ASTReader.cpp:107
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:25
uint64_t MacroStartOffset
The offset of the start of the set of defined macros.
Record code for the array of unused file scoped decls.
Definition: ASTBitCodes.h:425
A FunctionNoProtoType record.
Definition: ASTBitCodes.h:822
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:3817
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:302
File is an explicitly-loaded module.
Expr * ReadExpr(ModuleFile &F)
Reads an expression.
bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:303
ModuleFile & getPrimaryModule()
Returns the primary module associated with the manager, that is, the first module loaded...
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:827
QualType getEnumType(const EnumDecl *Decl) const
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const FileEntry *Entry, bool isVolatile=false, bool ShouldCloseOpenFile=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
void getInputFiles(ModuleFile &F, SmallVectorImpl< serialization::InputFile > &Files)
Return all input files for the given module file.
Definition: ASTReader.cpp:8073
uint64_t ReadCXXCtorInitializersRef(ModuleFile &M, const RecordData &Record, unsigned &Idx)
Read a CXXCtorInitializers ID from the given record and return its global bit offset.
Definition: ASTReader.cpp:5916
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
void visitModuleFile(StringRef Filename) override
This is called for each AST file loaded.
Definition: ASTReader.cpp:141
Record code for the Objective-C method pool,.
Definition: ASTBitCodes.h:403
virtual void ReadModuleMapFile(StringRef ModuleMapPath)
Definition: ASTReader.h:114
Specifies a header that is private to this submodule.
Definition: ASTBitCodes.h:660
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
bool needsInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the input files of the AST file via visitInpu...
Definition: ASTReader.cpp:133
Describes a macro expansion within the preprocessing record.
Definition: ASTBitCodes.h:616
QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
Selector getSelector() const
Definition: DeclObjC.h:328
SourceManager & getSourceManager() const
Definition: ASTReader.h:1301
An EnumType record.
Definition: ASTBitCodes.h:834
IdentifierTable & getIdentifierTable()
Retrieve the identifier table associated with the preprocessor.
Definition: ASTReader.cpp:8000
IdentifierResolver IdResolver
Definition: Sema.h:675
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:1855
A map from continuous integer ranges to some value, with a very specialized interface.
Class that performs lookup for an identifier stored in an AST file.
void setExternalSLocEntrySource(ExternalSLocEntrySource *Source)
ContinuousRangeMap< uint32_t, int, 2 > MacroRemap
Remapping table for macro IDs in this module.
An RValueReferenceType record.
Definition: ASTBitCodes.h:808
void ReadDeclarationNameLoc(ModuleFile &F, DeclarationNameLoc &DNLoc, DeclarationName Name, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:7509
A type that was preceded by the 'template' keyword, stored as a Type*.
void ClearSwitchCaseIDs()
Definition: ASTReader.cpp:8018
void setHasExternalLexicalStorage(bool ES=true)
State whether this DeclContext has external storage for declarations lexically in this context...
Definition: DeclBase.h:1720
bool isExtensionToken() const
unsigned getTotalNumSelectors() const
Returns the number of selectors found in the chain.
Definition: ASTReader.h:1538
unsigned Map[Count]
Definition: AddressSpaces.h:45
An AtomicType record.
Definition: ASTBitCodes.h:874
static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD, ASTConsumer *Consumer)
Under non-PCH compilation the consumer receives the objc methods before receiving the implementation...
Definition: ASTReader.cpp:6568
The placeholder type for dependent types.
Definition: ASTBitCodes.h:730
const TemplateArgument & getArg(unsigned Idx) const
Definition: TemplateBase.h:664
All of the names in this module are visible.
Definition: Basic/Module.h:209
SmallVector< Context, 8 > Contexts
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1795
Encapsulates the data about a macro definition (e.g. its tokens).
Definition: MacroInfo.h:34
Decl * GetExternalDecl(uint32_t ID) override
Resolve a declaration ID into a declaration, potentially building a new declaration.
Definition: ASTReader.cpp:5862
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:724
uint32_t getGeneration() const
Get the current generation of this AST source. This number is incremented each time the AST source la...
time_t getModificationTime() const
Definition: FileManager.h:90
void ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set, const RecordData &Record, unsigned &Idx)
Read a UnresolvedSet structure.
Definition: ASTReader.cpp:7696
void setAttrEnumOperandLoc(SourceLocation loc)
Definition: TypeLoc.h:776
struct CXXLitOpName CXXLiteralOperatorName
Abstract interface for callback invocations by the ASTReader.
Definition: ASTReader.h:101
CanQualType UnknownAnyTy
Definition: ASTContext.h:832
std::vector< Conflict > Conflicts
The list of conflicts.
Definition: Basic/Module.h:303
const T * getAs() const
Definition: Type.h:5555
NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Definition: ASTReader.cpp:7864
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:4806
Record code for the table of offsets into the Objective-C method pool.
Definition: ASTBitCodes.h:400
Represents a C++ base or member initializer.
Definition: DeclCXX.h:1901
A DependentSizedArrayType record.
Definition: ASTBitCodes.h:860
CanQualType UnsignedLongTy
Definition: ASTContext.h:826
Record code for the remapping information used to relate loaded modules to the various offsets and ID...
Definition: ASTBitCodes.h:507
bool isInvalid() const
virtual bool needsImportVisitation() const
Returns true if this ASTReaderListener wants to receive the imports of the AST file via visitImport...
Definition: ASTReader.h:203
Record code for declarations that Sema keeps references of.
Definition: ASTBitCodes.h:449
CanQualType DependentTy
Definition: ASTContext.h:832
void * HeaderFileInfoTable
The on-disk hash table that contains information about each of the header files.
CanQualType WCharTy
Definition: ASTContext.h:820
const unsigned int NUM_PREDEF_MACRO_IDS
The number of predefined macro IDs.
Definition: ASTBitCodes.h:141
bool hasBody() const override
Determine whether this method has a body.
Definition: DeclObjC.h:486
Offsets into the input-files block where input files reside.
Definition: ASTBitCodes.h:276
bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, bool AllowCompatibleDifferences) override
Receives the language options.
Definition: ASTReader.cpp:85
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:835
The fast qualifier mask.
Definition: Type.h:159
static std::pair< unsigned, unsigned > ReadKeyDataLength(const unsigned char *&d)
Definition: ASTReader.cpp:656
DeclContext * getRedeclContext()
Definition: DeclBase.cpp:1466
PreprocessorRecordTypes
Record types used within a preprocessor block.
Definition: ASTBitCodes.h:588
static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags)
Definition: ASTReader.cpp:358
CanQualType BoundMemberTy
Definition: ASTContext.h:832
The block containing the submodule structure.
Definition: ASTBitCodes.h:224
std::pair< int, unsigned > AllocateLoadedSLocEntries(unsigned NumSLocEntries, unsigned TotalSize)
Allocate a number of loaded SLocEntries, which will be actually loaded on demand from the external so...
void setTypeArgsRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:866
Wrapper for source info for record types.
Definition: TypeLoc.h:664
std::string BaseDirectory
The base directory of the module.
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1578
The template argument is a type.
Definition: TemplateBase.h:47
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
Wraps an ObjCPointerType with source location information.
Definition: TypeLoc.h:1186
const uint32_t * CXXBaseSpecifiersOffsets
Offset of each C++ base specifier set within the bitstream, indexed by the C++ base specifier set ID ...
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:371
ContinuousRangeMap< uint32_t, int, 2 > TypeRemap
Remapping table for type IDs in this module.
Selector DecodeSelector(serialization::SelectorID Idx)
Definition: ASTReader.cpp:7422
ObjCXXARCStandardLibraryKind ObjCXXARCStandardLibrary
The Objective-C++ ARC standard library that we should support, by providing appropriate definitions t...
bool isInvalid() const
serialization::PreprocessedEntityID BasePreprocessedEntityID
Base preprocessed entity ID for preprocessed entities local to this module.
const TemplateArgument & getArg(unsigned Idx) const
Retrieve a specific template argument as a type.
Definition: TemplateBase.h:658
Represents a base class of a C++ class.
Definition: DeclCXX.h:157
Cached information about one directory (either on disk or in the virtual file system).
Definition: FileManager.h:40
uint32_t GetNumExternalSelectors() override
Returns the number of selectors known to the external AST source.
Definition: ASTReader.cpp:7451
void PrintStats() override
Print some statistics about AST usage.
Definition: ASTReader.cpp:6620
void insert(const value_type &Val)
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:3030
Keeps track of options that affect how file operations are performed.
unsigned End
Raw source location of end of range.
Definition: ASTBitCodes.h:172
A TypedefType record.
Definition: ASTBitCodes.h:826
bool ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID)
Definition: ASTReader.cpp:1325
QualType GetType(serialization::TypeID ID)
Resolve a type ID into a type, potentially building a new type.
Definition: ASTReader.cpp:5688
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
IdentifierInfo * DecodeIdentifierInfo(serialization::IdentifierID ID)
Definition: ASTReader.cpp:7269
Expr * NoexceptExpr
Noexcept expression, if this is EST_ComputedNoexcept.
Definition: Type.h:3032
NestedNameSpecifierLoc QualifierLoc
Definition: Decl.h:553
virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath, bool Complain)
Receives the header search options.
Definition: ASTReader.h:157
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Canon=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
QualType getTypeOfExprType(Expr *e) const
GCC extension.
DeclarationName getCXXLiteralOperatorName(IdentifierInfo *II)
bool hasRevertedTokenIDToIdentifier() const
True if RevertTokenIDToIdentifier() was called.
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:1987
uint32_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
Definition: ASTBitCodes.h:159
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. Length can be 0 to indicate a ...
Definition: ASTReader.cpp:6258
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a variable array of the specified element type...
FormatToken * Current
FileManager & getFileManager() const
Definition: ASTReader.h:1302
TemplateArgumentLoc ReadTemplateArgumentLoc(ModuleFile &F, const RecordData &Record, unsigned &Idx)
Reads a TemplateArgumentLoc.
Definition: ASTReader.cpp:5837
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition: Basic/Module.h:186
void setEnd(SourceLocation e)
TemplateArgumentLocInfo GetTemplateArgumentLocInfo(ModuleFile &F, TemplateArgument::ArgKind Kind, const RecordData &Record, unsigned &Idx)
Reads a TemplateArgumentLocInfo appropriate for the given TemplateArgument kind.
Definition: ASTReader.cpp:5801
Represents a C++ struct/union/class.
Definition: DeclCXX.h:285
BoundNodesTreeBuilder *const Builder
Selector GetExternalSelector(serialization::SelectorID ID) override
Resolve a selector ID into a selector.
Definition: ASTReader.cpp:7447
static const ASTTemplateArgumentListInfo * Create(ASTContext &C, const TemplateArgumentListInfo &List)
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
Definition: ASTBitCodes.h:144
serialization::DeclID 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:6132
static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile)
Reads and return the signature record from StreamFile's control block, or else returns 0...
Definition: ASTReader.cpp:3846
virtual bool needsSystemInputFileVisitation()
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.h:189
An TemplateTypeParmType record.
Definition: ASTBitCodes.h:852
llvm::PointerIntPair< Module *, 1, bool > ExportDecl
Describes an exported module.
Definition: Basic/Module.h:226
Decl * D
The template function declaration to be late parsed.
Definition: Sema.h:9052
bool needsSystemInputFileVisitation() override
Returns true if this ASTReaderListener wants to receive the system input files of the AST file via vi...
Definition: ASTReader.cpp:137
void ReadTemplateArgumentList(SmallVectorImpl< TemplateArgument > &TemplArgs, ModuleFile &F, const RecordData &Record, unsigned &Idx)
Read a template argument array.
Definition: ASTReader.cpp:7686
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition: ExprCXX.cpp:783
SmallVector< uint64_t, 8 > PragmaDiagMappings
Diagnostic IDs and their mappings that the user changed.
static internal_key_type GetInternalKey(const external_key_type &Name)
Definition: ASTReader.cpp:876
static hash_value_type ComputeHash(const internal_key_type &a)
Definition: ASTReader.cpp:719
Token ReadToken(ModuleFile &M, const RecordDataImpl &Record, unsigned &Idx)
Reads a token out of a record.
Definition: ASTReader.cpp:1344
const char * IdentifierTableData
Actual data for the on-disk hash table of identifiers.
CanQualType OCLImage1dArrayTy
Definition: ASTContext.h:837
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1295
bool needsAnonymousDeclarationNumber(const NamedDecl *D)
Determine whether the given declaration needs an anonymous declaration number.
Definition: ASTCommon.cpp:231
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:501
const FileEntry * getFile() const
CanQualType Char16Ty
Definition: ASTContext.h:823
Level
The level of the diagnostic, after it has been through mapping.
Definition: Diagnostic.h:141
void setOutOfDate(bool OOD)
Set whether the information for this identifier is out of date with respect to the external source...
ASTIdentifierIterator(const ASTReader &Reader)
Definition: ASTReader.cpp:6876
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1019
const DeclOffset * DeclOffsets
Offset of each declaration within the bitstream, indexed by the declaration ID (-1).
Location information for a TemplateArgument.
Definition: TemplateBase.h:364
virtual bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, bool AllowCompatibleDifferences)
Receives the target options.
Definition: ASTReader.h:129
Record code for the offsets of each type.
Definition: ASTBitCodes.h:329
static ModuleFile * getDefinitiveModuleFileFor(const DeclContext *DC, ASTReader &Reader)
Retrieve the "definitive" module file for the definition of the given declaration context...
Definition: ASTReader.cpp:6314
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorType::VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
The block containing the definitions of all of the types and decls used within the AST file...
Definition: ASTBitCodes.h:218
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:43
Record code for the table of offsets to CXXCtorInitializers lists.
Definition: ASTBitCodes.h:563
virtual void ReadModuleName(StringRef ModuleName)
Definition: ASTReader.h:113
bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain) override
Receives the diagnostic options.
Definition: ASTReader.cpp:403
static internal_key_type ReadKey(const unsigned char *d, unsigned)
Definition: ASTReader.cpp:1522
The module file had already been loaded.
LineTableInfo & getLineTable()
Retrieve the stored line table.
Defines the clang::TargetInfo interface.
A SourceLocation and its associated SourceManager.
Defines the clang::VersionTuple class, which represents a version in the form major[.minor[.subminor]].
NameVisibilityKind
Describes the visibility of the various names within a particular module.
Definition: Basic/Module.h:205
void setPrevious(MacroDirective *Prev)
Set previous definition of the macro with the same name.
Definition: MacroInfo.h:340
Describes the redeclarations of a declaration.
Definition: ASTBitCodes.h:1436
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1671
a linked list of methods with the same selector name but different signatures.
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1453
std::pair< ObjCMethodList, ObjCMethodList > GlobalMethods
Definition: Sema.h:949
data_type ReadData(const internal_key_type &k, const unsigned char *d, unsigned DataLen)
Definition: ASTReader.cpp:747
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:76
Specifies a required feature.
Definition: ASTBitCodes.h:649
SourceLocation getSourceLocationForDeclID(serialization::GlobalDeclID ID)
Returns the source location for the decl ID.
Definition: ASTReader.cpp:6013
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition: Basic/Module.h:278
TagDecl * getDecl() const
Definition: Type.cpp:2858
CanQualType IntTy
Definition: ASTContext.h:825
Record for offsets of DECL_UPDATES records for declarations that were modified after being deserializ...
Definition: ASTBitCodes.h:471
internal_key_type ReadKey(const unsigned char *d, unsigned)
Definition: ASTReader.cpp:915
static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags, DiagnosticsEngine &Diags, bool IsSystem, bool Complain)
Definition: ASTReader.cpp:365
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
static void dumpModuleIDMap(StringRef Name, const ContinuousRangeMap< Key, ModuleFile *, InitialCapacity > &Map)
Definition: ASTReader.cpp:6721
llvm::BitstreamCursor PreprocessorDetailCursor
The cursor to the start of the (optional) detailed preprocessing record block.
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
void setProtocolLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:887
DeclContext * getPrimaryContext()
Definition: DeclBase.cpp:920
void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL, SourceLocation ColonColonLoc)
Extend the current nested-name-specifier by another nested-name-specifier component of the form 'type...
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file. ...
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:6005
Contains a late templated function. Will be parsed at the end of the translation unit, used by Sema & Parser.
Definition: Sema.h:9049
static const internal_key_type & GetInternalKey(const external_key_type &x)
Record code for weak undeclared identifiers.
Definition: ASTBitCodes.h:452
The block containing information about the preprocessor.
Definition: ASTBitCodes.h:214
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
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:6610
A DecayedType record.
Definition: ASTBitCodes.h:876
void setLocation(SourceLocation L)
Definition: Token.h:132
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment. In this case there should b...
uint32_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:82
unsigned getGlobalID() const
Retrieve the global declaration ID associated with this declaration, which specifies where in the...
Definition: DeclBase.h:628
Wrapper for source info for builtin types.
Definition: TypeLoc.h:509
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1022
A set of overloaded template declarations.
Definition: TemplateName.h:193
Wrapper for template type parameters.
Definition: TypeLoc.h:680
Module * Other
The module that this module conflicts with.
Definition: Basic/Module.h:296
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
Definition: DeclBase.h:372
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:1417
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:1395
AST file metadata, including the AST file version number and information about the compiler used to b...
Definition: ASTBitCodes.h:245
The block of input files, which were used as inputs to create this AST file.
Definition: ASTBitCodes.h:238
static DeclarationName getUsingDirectiveName()
getUsingDirectiveName - Return name for all using-directives.
Present this diagnostic as a warning.
ObjCMethodList * getNext() const
llvm::BitstreamCursor MacroCursor
The cursor to the start of the preprocessor block, which stores all of the macro definitions.
const uint32_t * SelectorOffsets
Offsets into the selector lookup table's data array where each selector resides.
CanQualType BoolTy
Definition: ASTContext.h:818
void UpdateSema()
Update the state of Sema after loading some additional modules.
Definition: ASTReader.cpp:6805
unsigned LocalNumTypes
The number of types in this AST file.
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:660
Represents a C++ namespace alias.
Definition: DeclCXX.h:2662
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1474
Kind
The basic Objective-C runtimes that we know about.
Definition: ObjCRuntime.h:28
static TypeIdx fromTypeID(TypeID ID)
Definition: ASTBitCodes.h:98
serialization::DeclID mapGlobalIDToModuleFileGlobalID(ModuleFile &M, serialization::DeclID GlobalID)
Map a global declaration ID into the declaration ID used to refer to this declaration within the give...
Definition: ASTReader.cpp:6115
InputFileRecordTypes
Record types that occur within the input-files block inside the control block.
Definition: ASTBitCodes.h:310
void ReadUnusedFileScopedDecls(SmallVectorImpl< const DeclaratorDecl * > &Decls) override
Read the set of unused file-scope declarations known to the external Sema source. ...
Definition: ASTReader.cpp:7078
void FinishedDeserializing() override
Notify ASTReader that we finished the deserialization of a decl or type. Must be paired with StartedD...
Definition: ASTReader.cpp:8414
CanQualType DoubleTy
Definition: ASTContext.h:828
A function-like macro definition. [PP_MACRO_FUNCTION_LIKE, <ObjectLikeStuff>, IsC99Varargs, IsGNUVarars, NumArgs, ArgIdentInfoID* ].
Definition: ASTBitCodes.h:599
bool isNull() const
isNull - Return true if this QualType doesn't point to a type yet.
Definition: Type.h:633
~ASTReader() override
Definition: ASTReader.cpp:8506
The Objective-C 'Protocol' type.
Definition: ASTBitCodes.h:931
unsigned UseStandardCXXIncludes
Include the system standard C++ library include search directories.
QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced, QualType Replacement) const
Retrieve a substitution-result type.
The global specifier '::'. There is no stored value.
T * getFETokenInfo() const
The control block, which contains all of the information that needs to be validated prior to committi...
Definition: ASTBitCodes.h:232
Wrapper for source info for pointers.
Definition: TypeLoc.h:1122
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1135
void ReadModuleName(StringRef ModuleName) override
Definition: ASTReader.cpp:76
static hash_value_type ComputeHash(internal_key_ref ikey)
Definition: ASTReader.cpp:1478
This class handles loading and caching of source files into memory.
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:3062
Holds everything needed to generate debug info for an imported module or precompiled header file...
PredefinedDeclIDs
Predefined declaration IDs.
Definition: ASTBitCodes.h:914
Record code for an update to the TU's lexically contained declarations.
Definition: ASTBitCodes.h:441
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1718
Source range/offset of a preprocessed entity.
Definition: ASTBitCodes.h:183
const serialization::ObjCCategoriesInfo * ObjCCategoriesMap
Array of category list location information within this module file, sorted by the definition ID...
bool loadGlobalIndex()
Attempts to load the global index.
Definition: ASTReader.cpp:3308
unsigned LocalNumCXXCtorInitializers
The number of C++ ctor initializer lists in this AST file.
void startToken()
Reset all flags to cleared.
Definition: Token.h:169
Module * getModule(unsigned ID) override
Retrieve the module that corresponds to the given module ID.
Definition: ASTReader.cpp:7383
Objective-C "Class" redefinition type.
Definition: ASTBitCodes.h:898
A PackExpansionType record.
Definition: ASTBitCodes.h:864
void ReadUnusedLocalTypedefNameCandidates(llvm::SmallSetVector< const TypedefNameDecl *, 4 > &Decls) override
Read the set of potentially unused typedefs known to the source.
Definition: ASTReader.cpp:7110
A single template declaration.
Definition: TemplateName.h:191
The pseudo-object placeholder type.
Definition: ASTBitCodes.h:760
const unsigned int NUM_PREDEF_SUBMODULE_IDS
The number of predefined submodule IDs.
Definition: ASTBitCodes.h:165
virtual bool ReadDiagnosticOptions(IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts, bool Complain)
Receives the diagnostic options.
Definition: ASTReader.h:139
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition: Basic/Module.h:190
void RecordSwitchCaseID(SwitchCase *SC, unsigned ID)
Record that the given ID maps to the given switch-case statement.
Definition: ASTReader.cpp:8006
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:96
A DependentTemplateSpecializationType record.
Definition: ASTBitCodes.h:858
CanQualType UnsignedIntTy
Definition: ASTContext.h:826
static bool isInterestingIdentifier(IdentifierInfo &II)
Whether the given identifier is "interesting".
Definition: ASTReader.cpp:738
bool ParseAllComments
Treat ordinary comments as documentation comments.
serialization::IdentifierID getGlobalIdentifierID(ModuleFile &M, unsigned LocalID)
Definition: ASTReader.cpp:7307
Record code for the array of tentative definitions.
Definition: ASTBitCodes.h:394
static void addMethodsToPool(Sema &S, ArrayRef< ObjCMethodDecl * > Methods, ObjCMethodList &List)
Add the given set of methods to the method list.
Definition: ASTReader.cpp:6989
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
bool hasExternalVisibleStorage() const
Whether this DeclContext has external storage containing additional declarations that are visible in ...
Definition: DeclBase.h:1726
static NestedNameSpecifier * GlobalSpecifier(const ASTContext &Context)
Returns the nested name specifier representing the global scope.