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