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 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
759                                                    const unsigned char* d,
760                                                    unsigned DataLen) {
761   using namespace llvm::support;
762   unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
763   bool IsInteresting = RawID & 0x01;
764 
765   // Wipe out the "is interesting" bit.
766   RawID = RawID >> 1;
767 
768   // Build the IdentifierInfo and link the identifier ID with it.
769   IdentifierInfo *II = KnownII;
770   if (!II) {
771     II = &Reader.getIdentifierTable().getOwn(k);
772     KnownII = II;
773   }
774   if (!II->isFromAST()) {
775     II->setIsFromAST();
776     if (isInterestingIdentifier(Reader, *II, F.isModule()))
777       II->setChangedSinceDeserialization();
778   }
779   Reader.markIdentifierUpToDate(II);
780 
781   IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
782   if (!IsInteresting) {
783     // For uninteresting identifiers, there's nothing else to do. Just notify
784     // the reader that we've finished loading this identifier.
785     Reader.SetIdentifierInfo(ID, II);
786     return II;
787   }
788 
789   unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
790   unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
791   bool CPlusPlusOperatorKeyword = readBit(Bits);
792   bool HasRevertedTokenIDToIdentifier = readBit(Bits);
793   bool HasRevertedBuiltin = readBit(Bits);
794   bool Poisoned = readBit(Bits);
795   bool ExtensionToken = readBit(Bits);
796   bool HadMacroDefinition = readBit(Bits);
797 
798   assert(Bits == 0 && "Extra bits in the identifier?");
799   DataLen -= 8;
800 
801   // Set or check the various bits in the IdentifierInfo structure.
802   // Token IDs are read-only.
803   if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
804     II->revertTokenIDToIdentifier();
805   if (!F.isModule())
806     II->setObjCOrBuiltinID(ObjCOrBuiltinID);
807   else if (HasRevertedBuiltin && II->getBuiltinID()) {
808     II->revertBuiltin();
809     assert((II->hasRevertedBuiltin() ||
810             II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
811            "Incorrect ObjC keyword or builtin ID");
812   }
813   assert(II->isExtensionToken() == ExtensionToken &&
814          "Incorrect extension token flag");
815   (void)ExtensionToken;
816   if (Poisoned)
817     II->setIsPoisoned(true);
818   assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
819          "Incorrect C++ operator keyword flag");
820   (void)CPlusPlusOperatorKeyword;
821 
822   // If this identifier is a macro, deserialize the macro
823   // definition.
824   if (HadMacroDefinition) {
825     uint32_t MacroDirectivesOffset =
826         endian::readNext<uint32_t, little, unaligned>(d);
827     DataLen -= 4;
828 
829     Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
830   }
831 
832   Reader.SetIdentifierInfo(ID, II);
833 
834   // Read all of the declarations visible at global scope with this
835   // name.
836   if (DataLen > 0) {
837     SmallVector<uint32_t, 4> DeclIDs;
838     for (; DataLen > 0; DataLen -= 4)
839       DeclIDs.push_back(Reader.getGlobalDeclID(
840           F, endian::readNext<uint32_t, little, unaligned>(d)));
841     Reader.SetGloballyVisibleDecls(II, DeclIDs);
842   }
843 
844   return II;
845 }
846 
847 unsigned
848 ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) {
849   llvm::FoldingSetNodeID ID;
850   ID.AddInteger(Key.Kind);
851 
852   switch (Key.Kind) {
853   case DeclarationName::Identifier:
854   case DeclarationName::CXXLiteralOperatorName:
855     ID.AddString(((IdentifierInfo*)Key.Data)->getName());
856     break;
857   case DeclarationName::ObjCZeroArgSelector:
858   case DeclarationName::ObjCOneArgSelector:
859   case DeclarationName::ObjCMultiArgSelector:
860     ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
861     break;
862   case DeclarationName::CXXOperatorName:
863     ID.AddInteger((OverloadedOperatorKind)Key.Data);
864     break;
865   case DeclarationName::CXXConstructorName:
866   case DeclarationName::CXXDestructorName:
867   case DeclarationName::CXXConversionFunctionName:
868   case DeclarationName::CXXUsingDirective:
869     break;
870   }
871 
872   return ID.ComputeHash();
873 }
874 
875 ASTDeclContextNameLookupTrait::internal_key_type
876 ASTDeclContextNameLookupTrait::GetInternalKey(
877                                           const external_key_type& Name) {
878   DeclNameKey Key;
879   Key.Kind = Name.getNameKind();
880   switch (Name.getNameKind()) {
881   case DeclarationName::Identifier:
882     Key.Data = (uint64_t)Name.getAsIdentifierInfo();
883     break;
884   case DeclarationName::ObjCZeroArgSelector:
885   case DeclarationName::ObjCOneArgSelector:
886   case DeclarationName::ObjCMultiArgSelector:
887     Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
888     break;
889   case DeclarationName::CXXOperatorName:
890     Key.Data = Name.getCXXOverloadedOperator();
891     break;
892   case DeclarationName::CXXLiteralOperatorName:
893     Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
894     break;
895   case DeclarationName::CXXConstructorName:
896   case DeclarationName::CXXDestructorName:
897   case DeclarationName::CXXConversionFunctionName:
898   case DeclarationName::CXXUsingDirective:
899     Key.Data = 0;
900     break;
901   }
902 
903   return Key;
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   DeclNameKey Key;
919   Key.Kind = (DeclarationName::NameKind)*d++;
920   switch (Key.Kind) {
921   case DeclarationName::Identifier:
922     Key.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     Key.Data =
929         (uint64_t)Reader.getLocalSelector(
930                              F, endian::readNext<uint32_t, little, unaligned>(
931                                     d)).getAsOpaquePtr();
932     break;
933   case DeclarationName::CXXOperatorName:
934     Key.Data = *d++; // OverloadedOperatorKind
935     break;
936   case DeclarationName::CXXLiteralOperatorName:
937     Key.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     Key.Data = 0;
945     break;
946   }
947 
948   return Key;
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   HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1560                    ((Flags >> 6) & 0x03);
1561   HFI.isImport = (Flags >> 5) & 0x01;
1562   HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1563   HFI.DirInfo = (Flags >> 2) & 0x03;
1564   HFI.Resolved = (Flags >> 1) & 0x01;
1565   HFI.IndexHeaderMapHeader = Flags & 0x01;
1566   HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
1567   HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1568       M, endian::readNext<uint32_t, little, unaligned>(d));
1569   if (unsigned FrameworkOffset =
1570           endian::readNext<uint32_t, little, unaligned>(d)) {
1571     // The framework offset is 1 greater than the actual offset,
1572     // since 0 is used as an indicator for "no framework name".
1573     StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1574     HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1575   }
1576 
1577   if (d != End) {
1578     uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1579     if (LocalSMID) {
1580       // This header is part of a module. Associate it with the module to enable
1581       // implicit module import.
1582       SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1583       Module *Mod = Reader.getSubmodule(GlobalSMID);
1584       HFI.isModuleHeader = true;
1585       FileManager &FileMgr = Reader.getFileManager();
1586       ModuleMap &ModMap =
1587           Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1588       // FIXME: This information should be propagated through the
1589       // SUBMODULE_HEADER etc records rather than from here.
1590       // FIXME: We don't ever mark excluded headers.
1591       std::string Filename = key.Filename;
1592       if (key.Imported)
1593         Reader.ResolveImportedPath(M, Filename);
1594       Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
1595       ModMap.addHeader(Mod, H, HFI.getHeaderRole());
1596     }
1597   }
1598 
1599   assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1600   (void)End;
1601 
1602   // This HeaderFileInfo was externally loaded.
1603   HFI.External = true;
1604   return HFI;
1605 }
1606 
1607 void ASTReader::addPendingMacro(IdentifierInfo *II,
1608                                 ModuleFile *M,
1609                                 uint64_t MacroDirectivesOffset) {
1610   assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1611   PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1612 }
1613 
1614 void ASTReader::ReadDefinedMacros() {
1615   // Note that we are loading defined macros.
1616   Deserializing Macros(this);
1617 
1618   for (auto &I : llvm::reverse(ModuleMgr)) {
1619     BitstreamCursor &MacroCursor = I->MacroCursor;
1620 
1621     // If there was no preprocessor block, skip this file.
1622     if (!MacroCursor.getBitStreamReader())
1623       continue;
1624 
1625     BitstreamCursor Cursor = MacroCursor;
1626     Cursor.JumpToBit(I->MacroStartOffset);
1627 
1628     RecordData Record;
1629     while (true) {
1630       llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1631 
1632       switch (E.Kind) {
1633       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1634       case llvm::BitstreamEntry::Error:
1635         Error("malformed block record in AST file");
1636         return;
1637       case llvm::BitstreamEntry::EndBlock:
1638         goto NextCursor;
1639 
1640       case llvm::BitstreamEntry::Record:
1641         Record.clear();
1642         switch (Cursor.readRecord(E.ID, Record)) {
1643         default:  // Default behavior: ignore.
1644           break;
1645 
1646         case PP_MACRO_OBJECT_LIKE:
1647         case PP_MACRO_FUNCTION_LIKE:
1648           getLocalIdentifier(*I, Record[0]);
1649           break;
1650 
1651         case PP_TOKEN:
1652           // Ignore tokens.
1653           break;
1654         }
1655         break;
1656       }
1657     }
1658     NextCursor:  ;
1659   }
1660 }
1661 
1662 namespace {
1663   /// \brief Visitor class used to look up identifirs in an AST file.
1664   class IdentifierLookupVisitor {
1665     StringRef Name;
1666     unsigned NameHash;
1667     unsigned PriorGeneration;
1668     unsigned &NumIdentifierLookups;
1669     unsigned &NumIdentifierLookupHits;
1670     IdentifierInfo *Found;
1671 
1672   public:
1673     IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1674                             unsigned &NumIdentifierLookups,
1675                             unsigned &NumIdentifierLookupHits)
1676       : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1677         PriorGeneration(PriorGeneration),
1678         NumIdentifierLookups(NumIdentifierLookups),
1679         NumIdentifierLookupHits(NumIdentifierLookupHits),
1680         Found()
1681     {
1682     }
1683 
1684     bool operator()(ModuleFile &M) {
1685       // If we've already searched this module file, skip it now.
1686       if (M.Generation <= PriorGeneration)
1687         return true;
1688 
1689       ASTIdentifierLookupTable *IdTable
1690         = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1691       if (!IdTable)
1692         return false;
1693 
1694       ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
1695                                      Found);
1696       ++NumIdentifierLookups;
1697       ASTIdentifierLookupTable::iterator Pos =
1698           IdTable->find_hashed(Name, NameHash, &Trait);
1699       if (Pos == IdTable->end())
1700         return false;
1701 
1702       // Dereferencing the iterator has the effect of building the
1703       // IdentifierInfo node and populating it with the various
1704       // declarations it needs.
1705       ++NumIdentifierLookupHits;
1706       Found = *Pos;
1707       return true;
1708     }
1709 
1710     // \brief Retrieve the identifier info found within the module
1711     // files.
1712     IdentifierInfo *getIdentifierInfo() const { return Found; }
1713   };
1714 }
1715 
1716 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1717   // Note that we are loading an identifier.
1718   Deserializing AnIdentifier(this);
1719 
1720   unsigned PriorGeneration = 0;
1721   if (getContext().getLangOpts().Modules)
1722     PriorGeneration = IdentifierGeneration[&II];
1723 
1724   // If there is a global index, look there first to determine which modules
1725   // provably do not have any results for this identifier.
1726   GlobalModuleIndex::HitSet Hits;
1727   GlobalModuleIndex::HitSet *HitsPtr = nullptr;
1728   if (!loadGlobalIndex()) {
1729     if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1730       HitsPtr = &Hits;
1731     }
1732   }
1733 
1734   IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
1735                                   NumIdentifierLookups,
1736                                   NumIdentifierLookupHits);
1737   ModuleMgr.visit(Visitor, HitsPtr);
1738   markIdentifierUpToDate(&II);
1739 }
1740 
1741 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1742   if (!II)
1743     return;
1744 
1745   II->setOutOfDate(false);
1746 
1747   // Update the generation for this identifier.
1748   if (getContext().getLangOpts().Modules)
1749     IdentifierGeneration[II] = getGeneration();
1750 }
1751 
1752 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1753                                     const PendingMacroInfo &PMInfo) {
1754   ModuleFile &M = *PMInfo.M;
1755 
1756   BitstreamCursor &Cursor = M.MacroCursor;
1757   SavedStreamPosition SavedPosition(Cursor);
1758   Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
1759 
1760   struct ModuleMacroRecord {
1761     SubmoduleID SubModID;
1762     MacroInfo *MI;
1763     SmallVector<SubmoduleID, 8> Overrides;
1764   };
1765   llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
1766 
1767   // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1768   // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1769   // macro histroy.
1770   RecordData Record;
1771   while (true) {
1772     llvm::BitstreamEntry Entry =
1773         Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1774     if (Entry.Kind != llvm::BitstreamEntry::Record) {
1775       Error("malformed block record in AST file");
1776       return;
1777     }
1778 
1779     Record.clear();
1780     switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
1781     case PP_MACRO_DIRECTIVE_HISTORY:
1782       break;
1783 
1784     case PP_MODULE_MACRO: {
1785       ModuleMacros.push_back(ModuleMacroRecord());
1786       auto &Info = ModuleMacros.back();
1787       Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1788       Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
1789       for (int I = 2, N = Record.size(); I != N; ++I)
1790         Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
1791       continue;
1792     }
1793 
1794     default:
1795       Error("malformed block record in AST file");
1796       return;
1797     }
1798 
1799     // We found the macro directive history; that's the last record
1800     // for this macro.
1801     break;
1802   }
1803 
1804   // Module macros are listed in reverse dependency order.
1805   {
1806     std::reverse(ModuleMacros.begin(), ModuleMacros.end());
1807     llvm::SmallVector<ModuleMacro*, 8> Overrides;
1808     for (auto &MMR : ModuleMacros) {
1809       Overrides.clear();
1810       for (unsigned ModID : MMR.Overrides) {
1811         Module *Mod = getSubmodule(ModID);
1812         auto *Macro = PP.getModuleMacro(Mod, II);
1813         assert(Macro && "missing definition for overridden macro");
1814         Overrides.push_back(Macro);
1815       }
1816 
1817       bool Inserted = false;
1818       Module *Owner = getSubmodule(MMR.SubModID);
1819       PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
1820     }
1821   }
1822 
1823   // Don't read the directive history for a module; we don't have anywhere
1824   // to put it.
1825   if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
1826     return;
1827 
1828   // Deserialize the macro directives history in reverse source-order.
1829   MacroDirective *Latest = nullptr, *Earliest = nullptr;
1830   unsigned Idx = 0, N = Record.size();
1831   while (Idx < N) {
1832     MacroDirective *MD = nullptr;
1833     SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
1834     MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1835     switch (K) {
1836     case MacroDirective::MD_Define: {
1837       MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
1838       MD = PP.AllocateDefMacroDirective(MI, Loc);
1839       break;
1840     }
1841     case MacroDirective::MD_Undefine: {
1842       MD = PP.AllocateUndefMacroDirective(Loc);
1843       break;
1844     }
1845     case MacroDirective::MD_Visibility:
1846       bool isPublic = Record[Idx++];
1847       MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1848       break;
1849     }
1850 
1851     if (!Latest)
1852       Latest = MD;
1853     if (Earliest)
1854       Earliest->setPrevious(MD);
1855     Earliest = MD;
1856   }
1857 
1858   if (Latest)
1859     PP.setLoadedMacroDirective(II, Latest);
1860 }
1861 
1862 ASTReader::InputFileInfo
1863 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
1864   // Go find this input file.
1865   BitstreamCursor &Cursor = F.InputFilesCursor;
1866   SavedStreamPosition SavedPosition(Cursor);
1867   Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1868 
1869   unsigned Code = Cursor.ReadCode();
1870   RecordData Record;
1871   StringRef Blob;
1872 
1873   unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1874   assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1875          "invalid record type for input file");
1876   (void)Result;
1877 
1878   std::string Filename;
1879   off_t StoredSize;
1880   time_t StoredTime;
1881   bool Overridden;
1882 
1883   assert(Record[0] == ID && "Bogus stored ID or offset");
1884   StoredSize = static_cast<off_t>(Record[1]);
1885   StoredTime = static_cast<time_t>(Record[2]);
1886   Overridden = static_cast<bool>(Record[3]);
1887   Filename = Blob;
1888   ResolveImportedPath(F, Filename);
1889 
1890   InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
1891   return R;
1892 }
1893 
1894 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
1895   // If this ID is bogus, just return an empty input file.
1896   if (ID == 0 || ID > F.InputFilesLoaded.size())
1897     return InputFile();
1898 
1899   // If we've already loaded this input file, return it.
1900   if (F.InputFilesLoaded[ID-1].getFile())
1901     return F.InputFilesLoaded[ID-1];
1902 
1903   if (F.InputFilesLoaded[ID-1].isNotFound())
1904     return InputFile();
1905 
1906   // Go find this input file.
1907   BitstreamCursor &Cursor = F.InputFilesCursor;
1908   SavedStreamPosition SavedPosition(Cursor);
1909   Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1910 
1911   InputFileInfo FI = readInputFileInfo(F, ID);
1912   off_t StoredSize = FI.StoredSize;
1913   time_t StoredTime = FI.StoredTime;
1914   bool Overridden = FI.Overridden;
1915   StringRef Filename = FI.Filename;
1916 
1917   const FileEntry *File
1918     = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1919                 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1920 
1921   // If we didn't find the file, resolve it relative to the
1922   // original directory from which this AST file was created.
1923   if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1924       F.OriginalDir != CurrentDir) {
1925     std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1926                                                             F.OriginalDir,
1927                                                             CurrentDir);
1928     if (!Resolved.empty())
1929       File = FileMgr.getFile(Resolved);
1930   }
1931 
1932   // For an overridden file, create a virtual file with the stored
1933   // size/timestamp.
1934   if (Overridden && File == nullptr) {
1935     File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1936   }
1937 
1938   if (File == nullptr) {
1939     if (Complain) {
1940       std::string ErrorStr = "could not find file '";
1941       ErrorStr += Filename;
1942       ErrorStr += "' referenced by AST file";
1943       Error(ErrorStr.c_str());
1944     }
1945     // Record that we didn't find the file.
1946     F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1947     return InputFile();
1948   }
1949 
1950   // Check if there was a request to override the contents of the file
1951   // that was part of the precompiled header. Overridding such a file
1952   // can lead to problems when lexing using the source locations from the
1953   // PCH.
1954   SourceManager &SM = getSourceManager();
1955   if (!Overridden && SM.isFileOverridden(File)) {
1956     if (Complain)
1957       Error(diag::err_fe_pch_file_overridden, Filename);
1958     // After emitting the diagnostic, recover by disabling the override so
1959     // that the original file will be used.
1960     SM.disableFileContentsOverride(File);
1961     // The FileEntry is a virtual file entry with the size of the contents
1962     // that would override the original contents. Set it to the original's
1963     // size/time.
1964     FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1965                             StoredSize, StoredTime);
1966   }
1967 
1968   bool IsOutOfDate = false;
1969 
1970   // For an overridden file, there is nothing to validate.
1971   if (!Overridden && //
1972       (StoredSize != File->getSize() ||
1973 #if defined(LLVM_ON_WIN32)
1974        false
1975 #else
1976        // In our regression testing, the Windows file system seems to
1977        // have inconsistent modification times that sometimes
1978        // erroneously trigger this error-handling path.
1979        //
1980        // FIXME: This probably also breaks HeaderFileInfo lookups on Windows.
1981        (StoredTime && StoredTime != File->getModificationTime() &&
1982         !DisableValidation)
1983 #endif
1984        )) {
1985     if (Complain) {
1986       // Build a list of the PCH imports that got us here (in reverse).
1987       SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1988       while (ImportStack.back()->ImportedBy.size() > 0)
1989         ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
1990 
1991       // The top-level PCH is stale.
1992       StringRef TopLevelPCHName(ImportStack.back()->FileName);
1993       Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
1994 
1995       // Print the import stack.
1996       if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
1997         Diag(diag::note_pch_required_by)
1998           << Filename << ImportStack[0]->FileName;
1999         for (unsigned I = 1; I < ImportStack.size(); ++I)
2000           Diag(diag::note_pch_required_by)
2001             << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2002       }
2003 
2004       if (!Diags.isDiagnosticInFlight())
2005         Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2006     }
2007 
2008     IsOutOfDate = true;
2009   }
2010 
2011   InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2012 
2013   // Note that we've loaded this input file.
2014   F.InputFilesLoaded[ID-1] = IF;
2015   return IF;
2016 }
2017 
2018 /// \brief If we are loading a relocatable PCH or module file, and the filename
2019 /// is not an absolute path, add the system or module root to the beginning of
2020 /// the file name.
2021 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2022   // Resolve relative to the base directory, if we have one.
2023   if (!M.BaseDirectory.empty())
2024     return ResolveImportedPath(Filename, M.BaseDirectory);
2025 }
2026 
2027 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2028   if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2029     return;
2030 
2031   SmallString<128> Buffer;
2032   llvm::sys::path::append(Buffer, Prefix, Filename);
2033   Filename.assign(Buffer.begin(), Buffer.end());
2034 }
2035 
2036 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2037   switch (ARR) {
2038   case ASTReader::Failure: return true;
2039   case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2040   case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2041   case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2042   case ASTReader::ConfigurationMismatch:
2043     return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2044   case ASTReader::HadErrors: return true;
2045   case ASTReader::Success: return false;
2046   }
2047 
2048   llvm_unreachable("unknown ASTReadResult");
2049 }
2050 
2051 ASTReader::ASTReadResult
2052 ASTReader::ReadControlBlock(ModuleFile &F,
2053                             SmallVectorImpl<ImportedModule> &Loaded,
2054                             const ModuleFile *ImportedBy,
2055                             unsigned ClientLoadCapabilities) {
2056   BitstreamCursor &Stream = F.Stream;
2057 
2058   if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2059     Error("malformed block record in AST file");
2060     return Failure;
2061   }
2062 
2063   // Should we allow the configuration of the module file to differ from the
2064   // configuration of the current translation unit in a compatible way?
2065   //
2066   // FIXME: Allow this for files explicitly specified with -include-pch too.
2067   bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
2068 
2069   // Read all of the records and blocks in the control block.
2070   RecordData Record;
2071   unsigned NumInputs = 0;
2072   unsigned NumUserInputs = 0;
2073   while (1) {
2074     llvm::BitstreamEntry Entry = Stream.advance();
2075 
2076     switch (Entry.Kind) {
2077     case llvm::BitstreamEntry::Error:
2078       Error("malformed block record in AST file");
2079       return Failure;
2080     case llvm::BitstreamEntry::EndBlock: {
2081       // Validate input files.
2082       const HeaderSearchOptions &HSOpts =
2083           PP.getHeaderSearchInfo().getHeaderSearchOpts();
2084 
2085       // All user input files reside at the index range [0, NumUserInputs), and
2086       // system input files reside at [NumUserInputs, NumInputs). For explicitly
2087       // loaded module files, ignore missing inputs.
2088       if (!DisableValidation && F.Kind != MK_ExplicitModule) {
2089         bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2090 
2091         // If we are reading a module, we will create a verification timestamp,
2092         // so we verify all input files.  Otherwise, verify only user input
2093         // files.
2094 
2095         unsigned N = NumUserInputs;
2096         if (ValidateSystemInputs ||
2097             (HSOpts.ModulesValidateOncePerBuildSession &&
2098              F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
2099              F.Kind == MK_ImplicitModule))
2100           N = NumInputs;
2101 
2102         for (unsigned I = 0; I < N; ++I) {
2103           InputFile IF = getInputFile(F, I+1, Complain);
2104           if (!IF.getFile() || IF.isOutOfDate())
2105             return OutOfDate;
2106         }
2107       }
2108 
2109       if (Listener)
2110         Listener->visitModuleFile(F.FileName, F.Kind);
2111 
2112       if (Listener && Listener->needsInputFileVisitation()) {
2113         unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2114                                                                 : NumUserInputs;
2115         for (unsigned I = 0; I < N; ++I) {
2116           bool IsSystem = I >= NumUserInputs;
2117           InputFileInfo FI = readInputFileInfo(F, I+1);
2118           Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2119                                    F.Kind == MK_ExplicitModule);
2120         }
2121       }
2122 
2123       return Success;
2124     }
2125 
2126     case llvm::BitstreamEntry::SubBlock:
2127       switch (Entry.ID) {
2128       case INPUT_FILES_BLOCK_ID:
2129         F.InputFilesCursor = Stream;
2130         if (Stream.SkipBlock() || // Skip with the main cursor
2131             // Read the abbreviations
2132             ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2133           Error("malformed block record in AST file");
2134           return Failure;
2135         }
2136         continue;
2137 
2138       default:
2139         if (Stream.SkipBlock()) {
2140           Error("malformed block record in AST file");
2141           return Failure;
2142         }
2143         continue;
2144       }
2145 
2146     case llvm::BitstreamEntry::Record:
2147       // The interesting case.
2148       break;
2149     }
2150 
2151     // Read and process a record.
2152     Record.clear();
2153     StringRef Blob;
2154     switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2155     case METADATA: {
2156       if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2157         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2158           Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2159                                         : diag::err_pch_version_too_new);
2160         return VersionMismatch;
2161       }
2162 
2163       bool hasErrors = Record[6];
2164       if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2165         Diag(diag::err_pch_with_compiler_errors);
2166         return HadErrors;
2167       }
2168 
2169       F.RelocatablePCH = Record[4];
2170       // Relative paths in a relocatable PCH are relative to our sysroot.
2171       if (F.RelocatablePCH)
2172         F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
2173 
2174       F.HasTimestamps = Record[5];
2175 
2176       const std::string &CurBranch = getClangFullRepositoryVersion();
2177       StringRef ASTBranch = Blob;
2178       if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2179         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2180           Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2181         return VersionMismatch;
2182       }
2183       break;
2184     }
2185 
2186     case SIGNATURE:
2187       assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2188       F.Signature = Record[0];
2189       break;
2190 
2191     case IMPORTS: {
2192       // Load each of the imported PCH files.
2193       unsigned Idx = 0, N = Record.size();
2194       while (Idx < N) {
2195         // Read information about the AST file.
2196         ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2197         // The import location will be the local one for now; we will adjust
2198         // all import locations of module imports after the global source
2199         // location info are setup.
2200         SourceLocation ImportLoc =
2201             SourceLocation::getFromRawEncoding(Record[Idx++]);
2202         off_t StoredSize = (off_t)Record[Idx++];
2203         time_t StoredModTime = (time_t)Record[Idx++];
2204         ASTFileSignature StoredSignature = Record[Idx++];
2205         auto ImportedFile = ReadPath(F, Record, Idx);
2206 
2207         // If our client can't cope with us being out of date, we can't cope with
2208         // our dependency being missing.
2209         unsigned Capabilities = ClientLoadCapabilities;
2210         if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2211           Capabilities &= ~ARR_Missing;
2212 
2213         // Load the AST file.
2214         auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2215                                   Loaded, StoredSize, StoredModTime,
2216                                   StoredSignature, Capabilities);
2217 
2218         // If we diagnosed a problem, produce a backtrace.
2219         if (isDiagnosedResult(Result, Capabilities))
2220           Diag(diag::note_module_file_imported_by)
2221               << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2222 
2223         switch (Result) {
2224         case Failure: return Failure;
2225           // If we have to ignore the dependency, we'll have to ignore this too.
2226         case Missing:
2227         case OutOfDate: return OutOfDate;
2228         case VersionMismatch: return VersionMismatch;
2229         case ConfigurationMismatch: return ConfigurationMismatch;
2230         case HadErrors: return HadErrors;
2231         case Success: break;
2232         }
2233       }
2234       break;
2235     }
2236 
2237     case LANGUAGE_OPTIONS: {
2238       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2239       // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
2240       if (Listener && &F == *ModuleMgr.begin() &&
2241           ParseLanguageOptions(Record, Complain, *Listener,
2242                                AllowCompatibleConfigurationMismatch) &&
2243           !DisableValidation && !AllowConfigurationMismatch)
2244         return ConfigurationMismatch;
2245       break;
2246     }
2247 
2248     case TARGET_OPTIONS: {
2249       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2250       if (Listener && &F == *ModuleMgr.begin() &&
2251           ParseTargetOptions(Record, Complain, *Listener,
2252                              AllowCompatibleConfigurationMismatch) &&
2253           !DisableValidation && !AllowConfigurationMismatch)
2254         return ConfigurationMismatch;
2255       break;
2256     }
2257 
2258     case DIAGNOSTIC_OPTIONS: {
2259       bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
2260       if (Listener && &F == *ModuleMgr.begin() &&
2261           !AllowCompatibleConfigurationMismatch &&
2262           ParseDiagnosticOptions(Record, Complain, *Listener) &&
2263           !DisableValidation)
2264         return OutOfDate;
2265       break;
2266     }
2267 
2268     case FILE_SYSTEM_OPTIONS: {
2269       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2270       if (Listener && &F == *ModuleMgr.begin() &&
2271           !AllowCompatibleConfigurationMismatch &&
2272           ParseFileSystemOptions(Record, Complain, *Listener) &&
2273           !DisableValidation && !AllowConfigurationMismatch)
2274         return ConfigurationMismatch;
2275       break;
2276     }
2277 
2278     case HEADER_SEARCH_OPTIONS: {
2279       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2280       if (Listener && &F == *ModuleMgr.begin() &&
2281           !AllowCompatibleConfigurationMismatch &&
2282           ParseHeaderSearchOptions(Record, Complain, *Listener) &&
2283           !DisableValidation && !AllowConfigurationMismatch)
2284         return ConfigurationMismatch;
2285       break;
2286     }
2287 
2288     case PREPROCESSOR_OPTIONS: {
2289       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2290       if (Listener && &F == *ModuleMgr.begin() &&
2291           !AllowCompatibleConfigurationMismatch &&
2292           ParsePreprocessorOptions(Record, Complain, *Listener,
2293                                    SuggestedPredefines) &&
2294           !DisableValidation && !AllowConfigurationMismatch)
2295         return ConfigurationMismatch;
2296       break;
2297     }
2298 
2299     case ORIGINAL_FILE:
2300       F.OriginalSourceFileID = FileID::get(Record[0]);
2301       F.ActualOriginalSourceFileName = Blob;
2302       F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2303       ResolveImportedPath(F, F.OriginalSourceFileName);
2304       break;
2305 
2306     case ORIGINAL_FILE_ID:
2307       F.OriginalSourceFileID = FileID::get(Record[0]);
2308       break;
2309 
2310     case ORIGINAL_PCH_DIR:
2311       F.OriginalDir = Blob;
2312       break;
2313 
2314     case MODULE_NAME:
2315       F.ModuleName = Blob;
2316       if (Listener)
2317         Listener->ReadModuleName(F.ModuleName);
2318       break;
2319 
2320     case MODULE_DIRECTORY: {
2321       assert(!F.ModuleName.empty() &&
2322              "MODULE_DIRECTORY found before MODULE_NAME");
2323       // If we've already loaded a module map file covering this module, we may
2324       // have a better path for it (relative to the current build).
2325       Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2326       if (M && M->Directory) {
2327         // If we're implicitly loading a module, the base directory can't
2328         // change between the build and use.
2329         if (F.Kind != MK_ExplicitModule) {
2330           const DirectoryEntry *BuildDir =
2331               PP.getFileManager().getDirectory(Blob);
2332           if (!BuildDir || BuildDir != M->Directory) {
2333             if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2334               Diag(diag::err_imported_module_relocated)
2335                   << F.ModuleName << Blob << M->Directory->getName();
2336             return OutOfDate;
2337           }
2338         }
2339         F.BaseDirectory = M->Directory->getName();
2340       } else {
2341         F.BaseDirectory = Blob;
2342       }
2343       break;
2344     }
2345 
2346     case MODULE_MAP_FILE:
2347       if (ASTReadResult Result =
2348               ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2349         return Result;
2350       break;
2351 
2352     case INPUT_FILE_OFFSETS:
2353       NumInputs = Record[0];
2354       NumUserInputs = Record[1];
2355       F.InputFileOffsets =
2356           (const llvm::support::unaligned_uint64_t *)Blob.data();
2357       F.InputFilesLoaded.resize(NumInputs);
2358       break;
2359     }
2360   }
2361 }
2362 
2363 ASTReader::ASTReadResult
2364 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
2365   BitstreamCursor &Stream = F.Stream;
2366 
2367   if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2368     Error("malformed block record in AST file");
2369     return Failure;
2370   }
2371 
2372   // Read all of the records and blocks for the AST file.
2373   RecordData Record;
2374   while (1) {
2375     llvm::BitstreamEntry Entry = Stream.advance();
2376 
2377     switch (Entry.Kind) {
2378     case llvm::BitstreamEntry::Error:
2379       Error("error at end of module block in AST file");
2380       return Failure;
2381     case llvm::BitstreamEntry::EndBlock: {
2382       // Outside of C++, we do not store a lookup map for the translation unit.
2383       // Instead, mark it as needing a lookup map to be built if this module
2384       // contains any declarations lexically within it (which it always does!).
2385       // This usually has no cost, since we very rarely need the lookup map for
2386       // the translation unit outside C++.
2387       DeclContext *DC = Context.getTranslationUnitDecl();
2388       if (DC->hasExternalLexicalStorage() &&
2389           !getContext().getLangOpts().CPlusPlus)
2390         DC->setMustBuildLookupTable();
2391 
2392       return Success;
2393     }
2394     case llvm::BitstreamEntry::SubBlock:
2395       switch (Entry.ID) {
2396       case DECLTYPES_BLOCK_ID:
2397         // We lazily load the decls block, but we want to set up the
2398         // DeclsCursor cursor to point into it.  Clone our current bitcode
2399         // cursor to it, enter the block and read the abbrevs in that block.
2400         // With the main cursor, we just skip over it.
2401         F.DeclsCursor = Stream;
2402         if (Stream.SkipBlock() ||  // Skip with the main cursor.
2403             // Read the abbrevs.
2404             ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2405           Error("malformed block record in AST file");
2406           return Failure;
2407         }
2408         break;
2409 
2410       case PREPROCESSOR_BLOCK_ID:
2411         F.MacroCursor = Stream;
2412         if (!PP.getExternalSource())
2413           PP.setExternalSource(this);
2414 
2415         if (Stream.SkipBlock() ||
2416             ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2417           Error("malformed block record in AST file");
2418           return Failure;
2419         }
2420         F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2421         break;
2422 
2423       case PREPROCESSOR_DETAIL_BLOCK_ID:
2424         F.PreprocessorDetailCursor = Stream;
2425         if (Stream.SkipBlock() ||
2426             ReadBlockAbbrevs(F.PreprocessorDetailCursor,
2427                              PREPROCESSOR_DETAIL_BLOCK_ID)) {
2428               Error("malformed preprocessor detail record in AST file");
2429               return Failure;
2430             }
2431         F.PreprocessorDetailStartOffset
2432         = F.PreprocessorDetailCursor.GetCurrentBitNo();
2433 
2434         if (!PP.getPreprocessingRecord())
2435           PP.createPreprocessingRecord();
2436         if (!PP.getPreprocessingRecord()->getExternalSource())
2437           PP.getPreprocessingRecord()->SetExternalSource(*this);
2438         break;
2439 
2440       case SOURCE_MANAGER_BLOCK_ID:
2441         if (ReadSourceManagerBlock(F))
2442           return Failure;
2443         break;
2444 
2445       case SUBMODULE_BLOCK_ID:
2446         if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
2447           return Result;
2448         break;
2449 
2450       case COMMENTS_BLOCK_ID: {
2451         BitstreamCursor C = Stream;
2452         if (Stream.SkipBlock() ||
2453             ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2454           Error("malformed comments block in AST file");
2455           return Failure;
2456         }
2457         CommentsCursors.push_back(std::make_pair(C, &F));
2458         break;
2459       }
2460 
2461       default:
2462         if (Stream.SkipBlock()) {
2463           Error("malformed block record in AST file");
2464           return Failure;
2465         }
2466         break;
2467       }
2468       continue;
2469 
2470     case llvm::BitstreamEntry::Record:
2471       // The interesting case.
2472       break;
2473     }
2474 
2475     // Read and process a record.
2476     Record.clear();
2477     StringRef Blob;
2478     switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2479     default:  // Default behavior: ignore.
2480       break;
2481 
2482     case TYPE_OFFSET: {
2483       if (F.LocalNumTypes != 0) {
2484         Error("duplicate TYPE_OFFSET record in AST file");
2485         return Failure;
2486       }
2487       F.TypeOffsets = (const uint32_t *)Blob.data();
2488       F.LocalNumTypes = Record[0];
2489       unsigned LocalBaseTypeIndex = Record[1];
2490       F.BaseTypeIndex = getTotalNumTypes();
2491 
2492       if (F.LocalNumTypes > 0) {
2493         // Introduce the global -> local mapping for types within this module.
2494         GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2495 
2496         // Introduce the local -> global mapping for types within this module.
2497         F.TypeRemap.insertOrReplace(
2498           std::make_pair(LocalBaseTypeIndex,
2499                          F.BaseTypeIndex - LocalBaseTypeIndex));
2500 
2501         TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2502       }
2503       break;
2504     }
2505 
2506     case DECL_OFFSET: {
2507       if (F.LocalNumDecls != 0) {
2508         Error("duplicate DECL_OFFSET record in AST file");
2509         return Failure;
2510       }
2511       F.DeclOffsets = (const DeclOffset *)Blob.data();
2512       F.LocalNumDecls = Record[0];
2513       unsigned LocalBaseDeclID = Record[1];
2514       F.BaseDeclID = getTotalNumDecls();
2515 
2516       if (F.LocalNumDecls > 0) {
2517         // Introduce the global -> local mapping for declarations within this
2518         // module.
2519         GlobalDeclMap.insert(
2520           std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2521 
2522         // Introduce the local -> global mapping for declarations within this
2523         // module.
2524         F.DeclRemap.insertOrReplace(
2525           std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2526 
2527         // Introduce the global -> local mapping for declarations within this
2528         // module.
2529         F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2530 
2531         DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2532       }
2533       break;
2534     }
2535 
2536     case TU_UPDATE_LEXICAL: {
2537       DeclContext *TU = Context.getTranslationUnitDecl();
2538       LexicalContents Contents(
2539           reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2540               Blob.data()),
2541           static_cast<unsigned int>(Blob.size() / 4));
2542       TULexicalDecls.push_back(std::make_pair(&F, Contents));
2543       TU->setHasExternalLexicalStorage(true);
2544       break;
2545     }
2546 
2547     case UPDATE_VISIBLE: {
2548       unsigned Idx = 0;
2549       serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2550       auto *Data = (const unsigned char*)Blob.data();
2551       unsigned BucketOffset = Record[Idx++];
2552       PendingVisibleUpdates[ID].push_back(
2553           PendingVisibleUpdate{&F, Data, BucketOffset});
2554       // If we've already loaded the decl, perform the updates when we finish
2555       // loading this block.
2556       if (Decl *D = GetExistingDecl(ID))
2557         PendingUpdateRecords.push_back(std::make_pair(ID, D));
2558       break;
2559     }
2560 
2561     case IDENTIFIER_TABLE:
2562       F.IdentifierTableData = Blob.data();
2563       if (Record[0]) {
2564         F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2565             (const unsigned char *)F.IdentifierTableData + Record[0],
2566             (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2567             (const unsigned char *)F.IdentifierTableData,
2568             ASTIdentifierLookupTrait(*this, F));
2569 
2570         PP.getIdentifierTable().setExternalIdentifierLookup(this);
2571       }
2572       break;
2573 
2574     case IDENTIFIER_OFFSET: {
2575       if (F.LocalNumIdentifiers != 0) {
2576         Error("duplicate IDENTIFIER_OFFSET record in AST file");
2577         return Failure;
2578       }
2579       F.IdentifierOffsets = (const uint32_t *)Blob.data();
2580       F.LocalNumIdentifiers = Record[0];
2581       unsigned LocalBaseIdentifierID = Record[1];
2582       F.BaseIdentifierID = getTotalNumIdentifiers();
2583 
2584       if (F.LocalNumIdentifiers > 0) {
2585         // Introduce the global -> local mapping for identifiers within this
2586         // module.
2587         GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2588                                                   &F));
2589 
2590         // Introduce the local -> global mapping for identifiers within this
2591         // module.
2592         F.IdentifierRemap.insertOrReplace(
2593           std::make_pair(LocalBaseIdentifierID,
2594                          F.BaseIdentifierID - LocalBaseIdentifierID));
2595 
2596         IdentifiersLoaded.resize(IdentifiersLoaded.size()
2597                                  + F.LocalNumIdentifiers);
2598       }
2599       break;
2600     }
2601 
2602     case INTERESTING_IDENTIFIERS:
2603       F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2604       break;
2605 
2606     case EAGERLY_DESERIALIZED_DECLS:
2607       // FIXME: Skip reading this record if our ASTConsumer doesn't care
2608       // about "interesting" decls (for instance, if we're building a module).
2609       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2610         EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2611       break;
2612 
2613     case SPECIAL_TYPES:
2614       if (SpecialTypes.empty()) {
2615         for (unsigned I = 0, N = Record.size(); I != N; ++I)
2616           SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2617         break;
2618       }
2619 
2620       if (SpecialTypes.size() != Record.size()) {
2621         Error("invalid special-types record");
2622         return Failure;
2623       }
2624 
2625       for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2626         serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2627         if (!SpecialTypes[I])
2628           SpecialTypes[I] = ID;
2629         // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2630         // merge step?
2631       }
2632       break;
2633 
2634     case STATISTICS:
2635       TotalNumStatements += Record[0];
2636       TotalNumMacros += Record[1];
2637       TotalLexicalDeclContexts += Record[2];
2638       TotalVisibleDeclContexts += Record[3];
2639       break;
2640 
2641     case UNUSED_FILESCOPED_DECLS:
2642       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2643         UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2644       break;
2645 
2646     case DELEGATING_CTORS:
2647       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2648         DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2649       break;
2650 
2651     case WEAK_UNDECLARED_IDENTIFIERS:
2652       if (Record.size() % 4 != 0) {
2653         Error("invalid weak identifiers record");
2654         return Failure;
2655       }
2656 
2657       // FIXME: Ignore weak undeclared identifiers from non-original PCH
2658       // files. This isn't the way to do it :)
2659       WeakUndeclaredIdentifiers.clear();
2660 
2661       // Translate the weak, undeclared identifiers into global IDs.
2662       for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2663         WeakUndeclaredIdentifiers.push_back(
2664           getGlobalIdentifierID(F, Record[I++]));
2665         WeakUndeclaredIdentifiers.push_back(
2666           getGlobalIdentifierID(F, Record[I++]));
2667         WeakUndeclaredIdentifiers.push_back(
2668           ReadSourceLocation(F, Record, I).getRawEncoding());
2669         WeakUndeclaredIdentifiers.push_back(Record[I++]);
2670       }
2671       break;
2672 
2673     case SELECTOR_OFFSETS: {
2674       F.SelectorOffsets = (const uint32_t *)Blob.data();
2675       F.LocalNumSelectors = Record[0];
2676       unsigned LocalBaseSelectorID = Record[1];
2677       F.BaseSelectorID = getTotalNumSelectors();
2678 
2679       if (F.LocalNumSelectors > 0) {
2680         // Introduce the global -> local mapping for selectors within this
2681         // module.
2682         GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2683 
2684         // Introduce the local -> global mapping for selectors within this
2685         // module.
2686         F.SelectorRemap.insertOrReplace(
2687           std::make_pair(LocalBaseSelectorID,
2688                          F.BaseSelectorID - LocalBaseSelectorID));
2689 
2690         SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2691       }
2692       break;
2693     }
2694 
2695     case METHOD_POOL:
2696       F.SelectorLookupTableData = (const unsigned char *)Blob.data();
2697       if (Record[0])
2698         F.SelectorLookupTable
2699           = ASTSelectorLookupTable::Create(
2700                         F.SelectorLookupTableData + Record[0],
2701                         F.SelectorLookupTableData,
2702                         ASTSelectorLookupTrait(*this, F));
2703       TotalNumMethodPoolEntries += Record[1];
2704       break;
2705 
2706     case REFERENCED_SELECTOR_POOL:
2707       if (!Record.empty()) {
2708         for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2709           ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2710                                                                 Record[Idx++]));
2711           ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2712                                               getRawEncoding());
2713         }
2714       }
2715       break;
2716 
2717     case PP_COUNTER_VALUE:
2718       if (!Record.empty() && Listener)
2719         Listener->ReadCounter(F, Record[0]);
2720       break;
2721 
2722     case FILE_SORTED_DECLS:
2723       F.FileSortedDecls = (const DeclID *)Blob.data();
2724       F.NumFileSortedDecls = Record[0];
2725       break;
2726 
2727     case SOURCE_LOCATION_OFFSETS: {
2728       F.SLocEntryOffsets = (const uint32_t *)Blob.data();
2729       F.LocalNumSLocEntries = Record[0];
2730       unsigned SLocSpaceSize = Record[1];
2731       std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2732           SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2733                                               SLocSpaceSize);
2734       if (!F.SLocEntryBaseID) {
2735         Error("ran out of source locations");
2736         break;
2737       }
2738       // Make our entry in the range map. BaseID is negative and growing, so
2739       // we invert it. Because we invert it, though, we need the other end of
2740       // the range.
2741       unsigned RangeStart =
2742           unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2743       GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2744       F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2745 
2746       // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2747       assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2748       GlobalSLocOffsetMap.insert(
2749           std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2750                            - SLocSpaceSize,&F));
2751 
2752       // Initialize the remapping table.
2753       // Invalid stays invalid.
2754       F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
2755       // This module. Base was 2 when being compiled.
2756       F.SLocRemap.insertOrReplace(std::make_pair(2U,
2757                                   static_cast<int>(F.SLocEntryBaseOffset - 2)));
2758 
2759       TotalNumSLocEntries += F.LocalNumSLocEntries;
2760       break;
2761     }
2762 
2763     case MODULE_OFFSET_MAP: {
2764       // Additional remapping information.
2765       const unsigned char *Data = (const unsigned char*)Blob.data();
2766       const unsigned char *DataEnd = Data + Blob.size();
2767 
2768       // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2769       if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2770         F.SLocRemap.insert(std::make_pair(0U, 0));
2771         F.SLocRemap.insert(std::make_pair(2U, 1));
2772       }
2773 
2774       // Continuous range maps we may be updating in our module.
2775       typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2776           RemapBuilder;
2777       RemapBuilder SLocRemap(F.SLocRemap);
2778       RemapBuilder IdentifierRemap(F.IdentifierRemap);
2779       RemapBuilder MacroRemap(F.MacroRemap);
2780       RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2781       RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2782       RemapBuilder SelectorRemap(F.SelectorRemap);
2783       RemapBuilder DeclRemap(F.DeclRemap);
2784       RemapBuilder TypeRemap(F.TypeRemap);
2785 
2786       while(Data < DataEnd) {
2787         using namespace llvm::support;
2788         uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
2789         StringRef Name = StringRef((const char*)Data, Len);
2790         Data += Len;
2791         ModuleFile *OM = ModuleMgr.lookup(Name);
2792         if (!OM) {
2793           Error("SourceLocation remap refers to unknown module");
2794           return Failure;
2795         }
2796 
2797         uint32_t SLocOffset =
2798             endian::readNext<uint32_t, little, unaligned>(Data);
2799         uint32_t IdentifierIDOffset =
2800             endian::readNext<uint32_t, little, unaligned>(Data);
2801         uint32_t MacroIDOffset =
2802             endian::readNext<uint32_t, little, unaligned>(Data);
2803         uint32_t PreprocessedEntityIDOffset =
2804             endian::readNext<uint32_t, little, unaligned>(Data);
2805         uint32_t SubmoduleIDOffset =
2806             endian::readNext<uint32_t, little, unaligned>(Data);
2807         uint32_t SelectorIDOffset =
2808             endian::readNext<uint32_t, little, unaligned>(Data);
2809         uint32_t DeclIDOffset =
2810             endian::readNext<uint32_t, little, unaligned>(Data);
2811         uint32_t TypeIndexOffset =
2812             endian::readNext<uint32_t, little, unaligned>(Data);
2813 
2814         uint32_t None = std::numeric_limits<uint32_t>::max();
2815 
2816         auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2817                              RemapBuilder &Remap) {
2818           if (Offset != None)
2819             Remap.insert(std::make_pair(Offset,
2820                                         static_cast<int>(BaseOffset - Offset)));
2821         };
2822         mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2823         mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2824         mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2825         mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2826                   PreprocessedEntityRemap);
2827         mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
2828         mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
2829         mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
2830         mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
2831 
2832         // Global -> local mappings.
2833         F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2834       }
2835       break;
2836     }
2837 
2838     case SOURCE_MANAGER_LINE_TABLE:
2839       if (ParseLineTable(F, Record))
2840         return Failure;
2841       break;
2842 
2843     case SOURCE_LOCATION_PRELOADS: {
2844       // Need to transform from the local view (1-based IDs) to the global view,
2845       // which is based off F.SLocEntryBaseID.
2846       if (!F.PreloadSLocEntries.empty()) {
2847         Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2848         return Failure;
2849       }
2850 
2851       F.PreloadSLocEntries.swap(Record);
2852       break;
2853     }
2854 
2855     case EXT_VECTOR_DECLS:
2856       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2857         ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2858       break;
2859 
2860     case VTABLE_USES:
2861       if (Record.size() % 3 != 0) {
2862         Error("Invalid VTABLE_USES record");
2863         return Failure;
2864       }
2865 
2866       // Later tables overwrite earlier ones.
2867       // FIXME: Modules will have some trouble with this. This is clearly not
2868       // the right way to do this.
2869       VTableUses.clear();
2870 
2871       for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2872         VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2873         VTableUses.push_back(
2874           ReadSourceLocation(F, Record, Idx).getRawEncoding());
2875         VTableUses.push_back(Record[Idx++]);
2876       }
2877       break;
2878 
2879     case PENDING_IMPLICIT_INSTANTIATIONS:
2880       if (PendingInstantiations.size() % 2 != 0) {
2881         Error("Invalid existing PendingInstantiations");
2882         return Failure;
2883       }
2884 
2885       if (Record.size() % 2 != 0) {
2886         Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2887         return Failure;
2888       }
2889 
2890       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2891         PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2892         PendingInstantiations.push_back(
2893           ReadSourceLocation(F, Record, I).getRawEncoding());
2894       }
2895       break;
2896 
2897     case SEMA_DECL_REFS:
2898       if (Record.size() != 2) {
2899         Error("Invalid SEMA_DECL_REFS block");
2900         return Failure;
2901       }
2902       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2903         SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2904       break;
2905 
2906     case PPD_ENTITIES_OFFSETS: {
2907       F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2908       assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2909       F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
2910 
2911       unsigned LocalBasePreprocessedEntityID = Record[0];
2912 
2913       unsigned StartingID;
2914       if (!PP.getPreprocessingRecord())
2915         PP.createPreprocessingRecord();
2916       if (!PP.getPreprocessingRecord()->getExternalSource())
2917         PP.getPreprocessingRecord()->SetExternalSource(*this);
2918       StartingID
2919         = PP.getPreprocessingRecord()
2920             ->allocateLoadedEntities(F.NumPreprocessedEntities);
2921       F.BasePreprocessedEntityID = StartingID;
2922 
2923       if (F.NumPreprocessedEntities > 0) {
2924         // Introduce the global -> local mapping for preprocessed entities in
2925         // this module.
2926         GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2927 
2928         // Introduce the local -> global mapping for preprocessed entities in
2929         // this module.
2930         F.PreprocessedEntityRemap.insertOrReplace(
2931           std::make_pair(LocalBasePreprocessedEntityID,
2932             F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2933       }
2934 
2935       break;
2936     }
2937 
2938     case DECL_UPDATE_OFFSETS: {
2939       if (Record.size() % 2 != 0) {
2940         Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2941         return Failure;
2942       }
2943       for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
2944         GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
2945         DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
2946 
2947         // If we've already loaded the decl, perform the updates when we finish
2948         // loading this block.
2949         if (Decl *D = GetExistingDecl(ID))
2950           PendingUpdateRecords.push_back(std::make_pair(ID, D));
2951       }
2952       break;
2953     }
2954 
2955     case DECL_REPLACEMENTS: {
2956       if (Record.size() % 3 != 0) {
2957         Error("invalid DECL_REPLACEMENTS block in AST file");
2958         return Failure;
2959       }
2960       for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2961         ReplacedDecls[getGlobalDeclID(F, Record[I])]
2962           = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2963       break;
2964     }
2965 
2966     case OBJC_CATEGORIES_MAP: {
2967       if (F.LocalNumObjCCategoriesInMap != 0) {
2968         Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2969         return Failure;
2970       }
2971 
2972       F.LocalNumObjCCategoriesInMap = Record[0];
2973       F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
2974       break;
2975     }
2976 
2977     case OBJC_CATEGORIES:
2978       F.ObjCCategories.swap(Record);
2979       break;
2980 
2981     case CXX_BASE_SPECIFIER_OFFSETS: {
2982       if (F.LocalNumCXXBaseSpecifiers != 0) {
2983         Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2984         return Failure;
2985       }
2986 
2987       F.LocalNumCXXBaseSpecifiers = Record[0];
2988       F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
2989       break;
2990     }
2991 
2992     case CXX_CTOR_INITIALIZERS_OFFSETS: {
2993       if (F.LocalNumCXXCtorInitializers != 0) {
2994         Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
2995         return Failure;
2996       }
2997 
2998       F.LocalNumCXXCtorInitializers = Record[0];
2999       F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
3000       break;
3001     }
3002 
3003     case DIAG_PRAGMA_MAPPINGS:
3004       if (F.PragmaDiagMappings.empty())
3005         F.PragmaDiagMappings.swap(Record);
3006       else
3007         F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3008                                     Record.begin(), Record.end());
3009       break;
3010 
3011     case CUDA_SPECIAL_DECL_REFS:
3012       // Later tables overwrite earlier ones.
3013       // FIXME: Modules will have trouble with this.
3014       CUDASpecialDeclRefs.clear();
3015       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3016         CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3017       break;
3018 
3019     case HEADER_SEARCH_TABLE: {
3020       F.HeaderFileInfoTableData = Blob.data();
3021       F.LocalNumHeaderFileInfos = Record[1];
3022       if (Record[0]) {
3023         F.HeaderFileInfoTable
3024           = HeaderFileInfoLookupTable::Create(
3025                    (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3026                    (const unsigned char *)F.HeaderFileInfoTableData,
3027                    HeaderFileInfoTrait(*this, F,
3028                                        &PP.getHeaderSearchInfo(),
3029                                        Blob.data() + Record[2]));
3030 
3031         PP.getHeaderSearchInfo().SetExternalSource(this);
3032         if (!PP.getHeaderSearchInfo().getExternalLookup())
3033           PP.getHeaderSearchInfo().SetExternalLookup(this);
3034       }
3035       break;
3036     }
3037 
3038     case FP_PRAGMA_OPTIONS:
3039       // Later tables overwrite earlier ones.
3040       FPPragmaOptions.swap(Record);
3041       break;
3042 
3043     case OPENCL_EXTENSIONS:
3044       // Later tables overwrite earlier ones.
3045       OpenCLExtensions.swap(Record);
3046       break;
3047 
3048     case TENTATIVE_DEFINITIONS:
3049       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3050         TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3051       break;
3052 
3053     case KNOWN_NAMESPACES:
3054       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3055         KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3056       break;
3057 
3058     case UNDEFINED_BUT_USED:
3059       if (UndefinedButUsed.size() % 2 != 0) {
3060         Error("Invalid existing UndefinedButUsed");
3061         return Failure;
3062       }
3063 
3064       if (Record.size() % 2 != 0) {
3065         Error("invalid undefined-but-used record");
3066         return Failure;
3067       }
3068       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3069         UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3070         UndefinedButUsed.push_back(
3071             ReadSourceLocation(F, Record, I).getRawEncoding());
3072       }
3073       break;
3074     case DELETE_EXPRS_TO_ANALYZE:
3075       for (unsigned I = 0, N = Record.size(); I != N;) {
3076         DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3077         const uint64_t Count = Record[I++];
3078         DelayedDeleteExprs.push_back(Count);
3079         for (uint64_t C = 0; C < Count; ++C) {
3080           DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3081           bool IsArrayForm = Record[I++] == 1;
3082           DelayedDeleteExprs.push_back(IsArrayForm);
3083         }
3084       }
3085       break;
3086 
3087     case IMPORTED_MODULES: {
3088       if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
3089         // If we aren't loading a module (which has its own exports), make
3090         // all of the imported modules visible.
3091         // FIXME: Deal with macros-only imports.
3092         for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3093           unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3094           SourceLocation Loc = ReadSourceLocation(F, Record, I);
3095           if (GlobalID)
3096             ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3097         }
3098       }
3099       break;
3100     }
3101 
3102     case LOCAL_REDECLARATIONS: {
3103       F.RedeclarationChains.swap(Record);
3104       break;
3105     }
3106 
3107     case LOCAL_REDECLARATIONS_MAP: {
3108       if (F.LocalNumRedeclarationsInMap != 0) {
3109         Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
3110         return Failure;
3111       }
3112 
3113       F.LocalNumRedeclarationsInMap = Record[0];
3114       F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
3115       break;
3116     }
3117 
3118     case MACRO_OFFSET: {
3119       if (F.LocalNumMacros != 0) {
3120         Error("duplicate MACRO_OFFSET record in AST file");
3121         return Failure;
3122       }
3123       F.MacroOffsets = (const uint32_t *)Blob.data();
3124       F.LocalNumMacros = Record[0];
3125       unsigned LocalBaseMacroID = Record[1];
3126       F.BaseMacroID = getTotalNumMacros();
3127 
3128       if (F.LocalNumMacros > 0) {
3129         // Introduce the global -> local mapping for macros within this module.
3130         GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3131 
3132         // Introduce the local -> global mapping for macros within this module.
3133         F.MacroRemap.insertOrReplace(
3134           std::make_pair(LocalBaseMacroID,
3135                          F.BaseMacroID - LocalBaseMacroID));
3136 
3137         MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3138       }
3139       break;
3140     }
3141 
3142     case LATE_PARSED_TEMPLATE: {
3143       LateParsedTemplates.append(Record.begin(), Record.end());
3144       break;
3145     }
3146 
3147     case OPTIMIZE_PRAGMA_OPTIONS:
3148       if (Record.size() != 1) {
3149         Error("invalid pragma optimize record");
3150         return Failure;
3151       }
3152       OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3153       break;
3154 
3155     case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3156       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3157         UnusedLocalTypedefNameCandidates.push_back(
3158             getGlobalDeclID(F, Record[I]));
3159       break;
3160     }
3161   }
3162 }
3163 
3164 ASTReader::ASTReadResult
3165 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3166                                   const ModuleFile *ImportedBy,
3167                                   unsigned ClientLoadCapabilities) {
3168   unsigned Idx = 0;
3169   F.ModuleMapPath = ReadPath(F, Record, Idx);
3170 
3171   if (F.Kind == MK_ExplicitModule) {
3172     // For an explicitly-loaded module, we don't care whether the original
3173     // module map file exists or matches.
3174     return Success;
3175   }
3176 
3177   // Try to resolve ModuleName in the current header search context and
3178   // verify that it is found in the same module map file as we saved. If the
3179   // top-level AST file is a main file, skip this check because there is no
3180   // usable header search context.
3181   assert(!F.ModuleName.empty() &&
3182          "MODULE_NAME should come before MODULE_MAP_FILE");
3183   if (F.Kind == MK_ImplicitModule &&
3184       (*ModuleMgr.begin())->Kind != MK_MainFile) {
3185     // An implicitly-loaded module file should have its module listed in some
3186     // module map file that we've already loaded.
3187     Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
3188     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3189     const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3190     if (!ModMap) {
3191       assert(ImportedBy && "top-level import should be verified");
3192       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3193         if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3194           // This module was defined by an imported (explicit) module.
3195           Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3196                                                << ASTFE->getName();
3197         else
3198           // This module was built with a different module map.
3199           Diag(diag::err_imported_module_not_found)
3200               << F.ModuleName << F.FileName << ImportedBy->FileName
3201               << F.ModuleMapPath;
3202       }
3203       return OutOfDate;
3204     }
3205 
3206     assert(M->Name == F.ModuleName && "found module with different name");
3207 
3208     // Check the primary module map file.
3209     const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3210     if (StoredModMap == nullptr || StoredModMap != ModMap) {
3211       assert(ModMap && "found module is missing module map file");
3212       assert(ImportedBy && "top-level import should be verified");
3213       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3214         Diag(diag::err_imported_module_modmap_changed)
3215           << F.ModuleName << ImportedBy->FileName
3216           << ModMap->getName() << F.ModuleMapPath;
3217       return OutOfDate;
3218     }
3219 
3220     llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3221     for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3222       // FIXME: we should use input files rather than storing names.
3223       std::string Filename = ReadPath(F, Record, Idx);
3224       const FileEntry *F =
3225           FileMgr.getFile(Filename, false, false);
3226       if (F == nullptr) {
3227         if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3228           Error("could not find file '" + Filename +"' referenced by AST file");
3229         return OutOfDate;
3230       }
3231       AdditionalStoredMaps.insert(F);
3232     }
3233 
3234     // Check any additional module map files (e.g. module.private.modulemap)
3235     // that are not in the pcm.
3236     if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3237       for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3238         // Remove files that match
3239         // Note: SmallPtrSet::erase is really remove
3240         if (!AdditionalStoredMaps.erase(ModMap)) {
3241           if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3242             Diag(diag::err_module_different_modmap)
3243               << F.ModuleName << /*new*/0 << ModMap->getName();
3244           return OutOfDate;
3245         }
3246       }
3247     }
3248 
3249     // Check any additional module map files that are in the pcm, but not
3250     // found in header search. Cases that match are already removed.
3251     for (const FileEntry *ModMap : AdditionalStoredMaps) {
3252       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3253         Diag(diag::err_module_different_modmap)
3254           << F.ModuleName << /*not new*/1 << ModMap->getName();
3255       return OutOfDate;
3256     }
3257   }
3258 
3259   if (Listener)
3260     Listener->ReadModuleMapFile(F.ModuleMapPath);
3261   return Success;
3262 }
3263 
3264 
3265 /// \brief Move the given method to the back of the global list of methods.
3266 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3267   // Find the entry for this selector in the method pool.
3268   Sema::GlobalMethodPool::iterator Known
3269     = S.MethodPool.find(Method->getSelector());
3270   if (Known == S.MethodPool.end())
3271     return;
3272 
3273   // Retrieve the appropriate method list.
3274   ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3275                                                     : Known->second.second;
3276   bool Found = false;
3277   for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
3278     if (!Found) {
3279       if (List->getMethod() == Method) {
3280         Found = true;
3281       } else {
3282         // Keep searching.
3283         continue;
3284       }
3285     }
3286 
3287     if (List->getNext())
3288       List->setMethod(List->getNext()->getMethod());
3289     else
3290       List->setMethod(Method);
3291   }
3292 }
3293 
3294 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
3295   assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
3296   for (Decl *D : Names) {
3297     bool wasHidden = D->Hidden;
3298     D->Hidden = false;
3299 
3300     if (wasHidden && SemaObj) {
3301       if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3302         moveMethodToBackOfGlobalList(*SemaObj, Method);
3303       }
3304     }
3305   }
3306 }
3307 
3308 void ASTReader::makeModuleVisible(Module *Mod,
3309                                   Module::NameVisibilityKind NameVisibility,
3310                                   SourceLocation ImportLoc) {
3311   llvm::SmallPtrSet<Module *, 4> Visited;
3312   SmallVector<Module *, 4> Stack;
3313   Stack.push_back(Mod);
3314   while (!Stack.empty()) {
3315     Mod = Stack.pop_back_val();
3316 
3317     if (NameVisibility <= Mod->NameVisibility) {
3318       // This module already has this level of visibility (or greater), so
3319       // there is nothing more to do.
3320       continue;
3321     }
3322 
3323     if (!Mod->isAvailable()) {
3324       // Modules that aren't available cannot be made visible.
3325       continue;
3326     }
3327 
3328     // Update the module's name visibility.
3329     Mod->NameVisibility = NameVisibility;
3330 
3331     // If we've already deserialized any names from this module,
3332     // mark them as visible.
3333     HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3334     if (Hidden != HiddenNamesMap.end()) {
3335       auto HiddenNames = std::move(*Hidden);
3336       HiddenNamesMap.erase(Hidden);
3337       makeNamesVisible(HiddenNames.second, HiddenNames.first);
3338       assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3339              "making names visible added hidden names");
3340     }
3341 
3342     // Push any exported modules onto the stack to be marked as visible.
3343     SmallVector<Module *, 16> Exports;
3344     Mod->getExportedModules(Exports);
3345     for (SmallVectorImpl<Module *>::iterator
3346            I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3347       Module *Exported = *I;
3348       if (Visited.insert(Exported).second)
3349         Stack.push_back(Exported);
3350     }
3351   }
3352 }
3353 
3354 bool ASTReader::loadGlobalIndex() {
3355   if (GlobalIndex)
3356     return false;
3357 
3358   if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3359       !Context.getLangOpts().Modules)
3360     return true;
3361 
3362   // Try to load the global index.
3363   TriedLoadingGlobalIndex = true;
3364   StringRef ModuleCachePath
3365     = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3366   std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
3367     = GlobalModuleIndex::readIndex(ModuleCachePath);
3368   if (!Result.first)
3369     return true;
3370 
3371   GlobalIndex.reset(Result.first);
3372   ModuleMgr.setGlobalIndex(GlobalIndex.get());
3373   return false;
3374 }
3375 
3376 bool ASTReader::isGlobalIndexUnavailable() const {
3377   return Context.getLangOpts().Modules && UseGlobalIndex &&
3378          !hasGlobalIndex() && TriedLoadingGlobalIndex;
3379 }
3380 
3381 static void updateModuleTimestamp(ModuleFile &MF) {
3382   // Overwrite the timestamp file contents so that file's mtime changes.
3383   std::string TimestampFilename = MF.getTimestampFilename();
3384   std::error_code EC;
3385   llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3386   if (EC)
3387     return;
3388   OS << "Timestamp file\n";
3389 }
3390 
3391 ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3392                                             ModuleKind Type,
3393                                             SourceLocation ImportLoc,
3394                                             unsigned ClientLoadCapabilities) {
3395   llvm::SaveAndRestore<SourceLocation>
3396     SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3397 
3398   // Defer any pending actions until we get to the end of reading the AST file.
3399   Deserializing AnASTFile(this);
3400 
3401   // Bump the generation number.
3402   unsigned PreviousGeneration = incrementGeneration(Context);
3403 
3404   unsigned NumModules = ModuleMgr.size();
3405   SmallVector<ImportedModule, 4> Loaded;
3406   switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3407                                                 /*ImportedBy=*/nullptr, Loaded,
3408                                                 0, 0, 0,
3409                                                 ClientLoadCapabilities)) {
3410   case Failure:
3411   case Missing:
3412   case OutOfDate:
3413   case VersionMismatch:
3414   case ConfigurationMismatch:
3415   case HadErrors: {
3416     llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3417     for (const ImportedModule &IM : Loaded)
3418       LoadedSet.insert(IM.Mod);
3419 
3420     ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3421                             LoadedSet,
3422                             Context.getLangOpts().Modules
3423                               ? &PP.getHeaderSearchInfo().getModuleMap()
3424                               : nullptr);
3425 
3426     // If we find that any modules are unusable, the global index is going
3427     // to be out-of-date. Just remove it.
3428     GlobalIndex.reset();
3429     ModuleMgr.setGlobalIndex(nullptr);
3430     return ReadResult;
3431   }
3432   case Success:
3433     break;
3434   }
3435 
3436   // Here comes stuff that we only do once the entire chain is loaded.
3437 
3438   // Load the AST blocks of all of the modules that we loaded.
3439   for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3440                                               MEnd = Loaded.end();
3441        M != MEnd; ++M) {
3442     ModuleFile &F = *M->Mod;
3443 
3444     // Read the AST block.
3445     if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3446       return Result;
3447 
3448     // Once read, set the ModuleFile bit base offset and update the size in
3449     // bits of all files we've seen.
3450     F.GlobalBitOffset = TotalModulesSizeInBits;
3451     TotalModulesSizeInBits += F.SizeInBits;
3452     GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3453 
3454     // Preload SLocEntries.
3455     for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3456       int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3457       // Load it through the SourceManager and don't call ReadSLocEntry()
3458       // directly because the entry may have already been loaded in which case
3459       // calling ReadSLocEntry() directly would trigger an assertion in
3460       // SourceManager.
3461       SourceMgr.getLoadedSLocEntryByID(Index);
3462     }
3463 
3464     // Preload all the pending interesting identifiers by marking them out of
3465     // date.
3466     for (auto Offset : F.PreloadIdentifierOffsets) {
3467       const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3468           F.IdentifierTableData + Offset);
3469 
3470       ASTIdentifierLookupTrait Trait(*this, F);
3471       auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3472       auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3473       PP.getIdentifierTable().getOwn(Key).setOutOfDate(true);
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 
5825     assert(!T.isNull() && "Unknown predefined type");
5826     return T.withFastQualifiers(FastQuals);
5827   }
5828 
5829   Index -= NUM_PREDEF_TYPE_IDS;
5830   assert(Index < TypesLoaded.size() && "Type index out-of-range");
5831   if (TypesLoaded[Index].isNull()) {
5832     TypesLoaded[Index] = readTypeRecord(Index);
5833     if (TypesLoaded[Index].isNull())
5834       return QualType();
5835 
5836     TypesLoaded[Index]->setFromAST();
5837     if (DeserializationListener)
5838       DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5839                                         TypesLoaded[Index]);
5840   }
5841 
5842   return TypesLoaded[Index].withFastQualifiers(FastQuals);
5843 }
5844 
5845 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5846   return GetType(getGlobalTypeID(F, LocalID));
5847 }
5848 
5849 serialization::TypeID
5850 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5851   unsigned FastQuals = LocalID & Qualifiers::FastMask;
5852   unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5853 
5854   if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5855     return LocalID;
5856 
5857   ContinuousRangeMap<uint32_t, int, 2>::iterator I
5858     = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5859   assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5860 
5861   unsigned GlobalIndex = LocalIndex + I->second;
5862   return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5863 }
5864 
5865 TemplateArgumentLocInfo
5866 ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5867                                       TemplateArgument::ArgKind Kind,
5868                                       const RecordData &Record,
5869                                       unsigned &Index) {
5870   switch (Kind) {
5871   case TemplateArgument::Expression:
5872     return ReadExpr(F);
5873   case TemplateArgument::Type:
5874     return GetTypeSourceInfo(F, Record, Index);
5875   case TemplateArgument::Template: {
5876     NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5877                                                                      Index);
5878     SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5879     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5880                                    SourceLocation());
5881   }
5882   case TemplateArgument::TemplateExpansion: {
5883     NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5884                                                                      Index);
5885     SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5886     SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5887     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5888                                    EllipsisLoc);
5889   }
5890   case TemplateArgument::Null:
5891   case TemplateArgument::Integral:
5892   case TemplateArgument::Declaration:
5893   case TemplateArgument::NullPtr:
5894   case TemplateArgument::Pack:
5895     // FIXME: Is this right?
5896     return TemplateArgumentLocInfo();
5897   }
5898   llvm_unreachable("unexpected template argument loc");
5899 }
5900 
5901 TemplateArgumentLoc
5902 ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5903                                    const RecordData &Record, unsigned &Index) {
5904   TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5905 
5906   if (Arg.getKind() == TemplateArgument::Expression) {
5907     if (Record[Index++]) // bool InfoHasSameExpr.
5908       return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5909   }
5910   return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5911                                                              Record, Index));
5912 }
5913 
5914 const ASTTemplateArgumentListInfo*
5915 ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5916                                            const RecordData &Record,
5917                                            unsigned &Index) {
5918   SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5919   SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5920   unsigned NumArgsAsWritten = Record[Index++];
5921   TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5922   for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5923     TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5924   return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5925 }
5926 
5927 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5928   return GetDecl(ID);
5929 }
5930 
5931 template<typename TemplateSpecializationDecl>
5932 static void completeRedeclChainForTemplateSpecialization(Decl *D) {
5933   if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
5934     TSD->getSpecializedTemplate()->LoadLazySpecializations();
5935 }
5936 
5937 void ASTReader::CompleteRedeclChain(const Decl *D) {
5938   if (NumCurrentElementsDeserializing) {
5939     // We arrange to not care about the complete redeclaration chain while we're
5940     // deserializing. Just remember that the AST has marked this one as complete
5941     // but that it's not actually complete yet, so we know we still need to
5942     // complete it later.
5943     PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
5944     return;
5945   }
5946 
5947   const DeclContext *DC = D->getDeclContext()->getRedeclContext();
5948 
5949   // If this is a named declaration, complete it by looking it up
5950   // within its context.
5951   //
5952   // FIXME: Merging a function definition should merge
5953   // all mergeable entities within it.
5954   if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
5955       isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
5956     if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
5957       if (!getContext().getLangOpts().CPlusPlus &&
5958           isa<TranslationUnitDecl>(DC)) {
5959         // Outside of C++, we don't have a lookup table for the TU, so update
5960         // the identifier instead. (For C++ modules, we don't store decls
5961         // in the serialized identifier table, so we do the lookup in the TU.)
5962         auto *II = Name.getAsIdentifierInfo();
5963         assert(II && "non-identifier name in C?");
5964         if (II->isOutOfDate())
5965           updateOutOfDateIdentifier(*II);
5966       } else
5967         DC->lookup(Name);
5968     } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
5969       // Find all declarations of this kind from the relevant context.
5970       for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
5971         auto *DC = cast<DeclContext>(DCDecl);
5972         SmallVector<Decl*, 8> Decls;
5973         FindExternalLexicalDecls(
5974             DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
5975       }
5976     }
5977   }
5978 
5979   if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
5980     CTSD->getSpecializedTemplate()->LoadLazySpecializations();
5981   if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
5982     VTSD->getSpecializedTemplate()->LoadLazySpecializations();
5983   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5984     if (auto *Template = FD->getPrimaryTemplate())
5985       Template->LoadLazySpecializations();
5986   }
5987 }
5988 
5989 uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
5990                                                const RecordData &Record,
5991                                                unsigned &Idx) {
5992   if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
5993     Error("malformed AST file: missing C++ ctor initializers");
5994     return 0;
5995   }
5996 
5997   unsigned LocalID = Record[Idx++];
5998   return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
5999 }
6000 
6001 CXXCtorInitializer **
6002 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6003   RecordLocation Loc = getLocalBitOffset(Offset);
6004   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6005   SavedStreamPosition SavedPosition(Cursor);
6006   Cursor.JumpToBit(Loc.Offset);
6007   ReadingKindTracker ReadingKind(Read_Decl, *this);
6008 
6009   RecordData Record;
6010   unsigned Code = Cursor.ReadCode();
6011   unsigned RecCode = Cursor.readRecord(Code, Record);
6012   if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6013     Error("malformed AST file: missing C++ ctor initializers");
6014     return nullptr;
6015   }
6016 
6017   unsigned Idx = 0;
6018   return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6019 }
6020 
6021 uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
6022                                           const RecordData &Record,
6023                                           unsigned &Idx) {
6024   if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
6025     Error("malformed AST file: missing C++ base specifier");
6026     return 0;
6027   }
6028 
6029   unsigned LocalID = Record[Idx++];
6030   return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
6031 }
6032 
6033 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6034   RecordLocation Loc = getLocalBitOffset(Offset);
6035   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6036   SavedStreamPosition SavedPosition(Cursor);
6037   Cursor.JumpToBit(Loc.Offset);
6038   ReadingKindTracker ReadingKind(Read_Decl, *this);
6039   RecordData Record;
6040   unsigned Code = Cursor.ReadCode();
6041   unsigned RecCode = Cursor.readRecord(Code, Record);
6042   if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
6043     Error("malformed AST file: missing C++ base specifiers");
6044     return nullptr;
6045   }
6046 
6047   unsigned Idx = 0;
6048   unsigned NumBases = Record[Idx++];
6049   void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6050   CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6051   for (unsigned I = 0; I != NumBases; ++I)
6052     Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6053   return Bases;
6054 }
6055 
6056 serialization::DeclID
6057 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6058   if (LocalID < NUM_PREDEF_DECL_IDS)
6059     return LocalID;
6060 
6061   ContinuousRangeMap<uint32_t, int, 2>::iterator I
6062     = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6063   assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6064 
6065   return LocalID + I->second;
6066 }
6067 
6068 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6069                                    ModuleFile &M) const {
6070   // Predefined decls aren't from any module.
6071   if (ID < NUM_PREDEF_DECL_IDS)
6072     return false;
6073 
6074   return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6075          ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
6076 }
6077 
6078 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
6079   if (!D->isFromASTFile())
6080     return nullptr;
6081   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6082   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6083   return I->second;
6084 }
6085 
6086 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6087   if (ID < NUM_PREDEF_DECL_IDS)
6088     return SourceLocation();
6089 
6090   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6091 
6092   if (Index > DeclsLoaded.size()) {
6093     Error("declaration ID out-of-range for AST file");
6094     return SourceLocation();
6095   }
6096 
6097   if (Decl *D = DeclsLoaded[Index])
6098     return D->getLocation();
6099 
6100   unsigned RawLocation = 0;
6101   RecordLocation Rec = DeclCursorForID(ID, RawLocation);
6102   return ReadSourceLocation(*Rec.F, RawLocation);
6103 }
6104 
6105 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6106   switch (ID) {
6107   case PREDEF_DECL_NULL_ID:
6108     return nullptr;
6109 
6110   case PREDEF_DECL_TRANSLATION_UNIT_ID:
6111     return Context.getTranslationUnitDecl();
6112 
6113   case PREDEF_DECL_OBJC_ID_ID:
6114     return Context.getObjCIdDecl();
6115 
6116   case PREDEF_DECL_OBJC_SEL_ID:
6117     return Context.getObjCSelDecl();
6118 
6119   case PREDEF_DECL_OBJC_CLASS_ID:
6120     return Context.getObjCClassDecl();
6121 
6122   case PREDEF_DECL_OBJC_PROTOCOL_ID:
6123     return Context.getObjCProtocolDecl();
6124 
6125   case PREDEF_DECL_INT_128_ID:
6126     return Context.getInt128Decl();
6127 
6128   case PREDEF_DECL_UNSIGNED_INT_128_ID:
6129     return Context.getUInt128Decl();
6130 
6131   case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6132     return Context.getObjCInstanceTypeDecl();
6133 
6134   case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6135     return Context.getBuiltinVaListDecl();
6136 
6137   case PREDEF_DECL_VA_LIST_TAG:
6138     return Context.getVaListTagDecl();
6139 
6140   case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6141     return Context.getExternCContextDecl();
6142   }
6143   llvm_unreachable("PredefinedDeclIDs unknown enum value");
6144 }
6145 
6146 Decl *ASTReader::GetExistingDecl(DeclID ID) {
6147   if (ID < NUM_PREDEF_DECL_IDS) {
6148     Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6149     if (D) {
6150       // Track that we have merged the declaration with ID \p ID into the
6151       // pre-existing predefined declaration \p D.
6152       auto &Merged = KeyDecls[D->getCanonicalDecl()];
6153       if (Merged.empty())
6154         Merged.push_back(ID);
6155     }
6156     return D;
6157   }
6158 
6159   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6160 
6161   if (Index >= DeclsLoaded.size()) {
6162     assert(0 && "declaration ID out-of-range for AST file");
6163     Error("declaration ID out-of-range for AST file");
6164     return nullptr;
6165   }
6166 
6167   return DeclsLoaded[Index];
6168 }
6169 
6170 Decl *ASTReader::GetDecl(DeclID ID) {
6171   if (ID < NUM_PREDEF_DECL_IDS)
6172     return GetExistingDecl(ID);
6173 
6174   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6175 
6176   if (Index >= DeclsLoaded.size()) {
6177     assert(0 && "declaration ID out-of-range for AST file");
6178     Error("declaration ID out-of-range for AST file");
6179     return nullptr;
6180   }
6181 
6182   if (!DeclsLoaded[Index]) {
6183     ReadDeclRecord(ID);
6184     if (DeserializationListener)
6185       DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6186   }
6187 
6188   return DeclsLoaded[Index];
6189 }
6190 
6191 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
6192                                                   DeclID GlobalID) {
6193   if (GlobalID < NUM_PREDEF_DECL_IDS)
6194     return GlobalID;
6195 
6196   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6197   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6198   ModuleFile *Owner = I->second;
6199 
6200   llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6201     = M.GlobalToLocalDeclIDs.find(Owner);
6202   if (Pos == M.GlobalToLocalDeclIDs.end())
6203     return 0;
6204 
6205   return GlobalID - Owner->BaseDeclID + Pos->second;
6206 }
6207 
6208 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
6209                                             const RecordData &Record,
6210                                             unsigned &Idx) {
6211   if (Idx >= Record.size()) {
6212     Error("Corrupted AST file");
6213     return 0;
6214   }
6215 
6216   return getGlobalDeclID(F, Record[Idx++]);
6217 }
6218 
6219 /// \brief Resolve the offset of a statement into a statement.
6220 ///
6221 /// This operation will read a new statement from the external
6222 /// source each time it is called, and is meant to be used via a
6223 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6224 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6225   // Switch case IDs are per Decl.
6226   ClearSwitchCaseIDs();
6227 
6228   // Offset here is a global offset across the entire chain.
6229   RecordLocation Loc = getLocalBitOffset(Offset);
6230   Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6231   return ReadStmtFromStream(*Loc.F);
6232 }
6233 
6234 void ASTReader::FindExternalLexicalDecls(
6235     const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6236     SmallVectorImpl<Decl *> &Decls) {
6237   bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6238 
6239   auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
6240     assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6241     for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6242       auto K = (Decl::Kind)+LexicalDecls[I];
6243       if (!IsKindWeWant(K))
6244         continue;
6245 
6246       auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6247 
6248       // Don't add predefined declarations to the lexical context more
6249       // than once.
6250       if (ID < NUM_PREDEF_DECL_IDS) {
6251         if (PredefsVisited[ID])
6252           continue;
6253 
6254         PredefsVisited[ID] = true;
6255       }
6256 
6257       if (Decl *D = GetLocalDecl(*M, ID)) {
6258         assert(D->getKind() == K && "wrong kind for lexical decl");
6259         if (!DC->isDeclInLexicalTraversal(D))
6260           Decls.push_back(D);
6261       }
6262     }
6263   };
6264 
6265   if (isa<TranslationUnitDecl>(DC)) {
6266     for (auto Lexical : TULexicalDecls)
6267       Visit(Lexical.first, Lexical.second);
6268   } else {
6269     auto I = LexicalDecls.find(DC);
6270     if (I != LexicalDecls.end())
6271       Visit(I->second.first, I->second.second);
6272   }
6273 
6274   ++NumLexicalDeclContextsRead;
6275 }
6276 
6277 namespace {
6278 
6279 class DeclIDComp {
6280   ASTReader &Reader;
6281   ModuleFile &Mod;
6282 
6283 public:
6284   DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6285 
6286   bool operator()(LocalDeclID L, LocalDeclID R) const {
6287     SourceLocation LHS = getLocation(L);
6288     SourceLocation RHS = getLocation(R);
6289     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6290   }
6291 
6292   bool operator()(SourceLocation LHS, LocalDeclID R) const {
6293     SourceLocation RHS = getLocation(R);
6294     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6295   }
6296 
6297   bool operator()(LocalDeclID L, SourceLocation RHS) const {
6298     SourceLocation LHS = getLocation(L);
6299     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6300   }
6301 
6302   SourceLocation getLocation(LocalDeclID ID) const {
6303     return Reader.getSourceManager().getFileLoc(
6304             Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6305   }
6306 };
6307 
6308 }
6309 
6310 void ASTReader::FindFileRegionDecls(FileID File,
6311                                     unsigned Offset, unsigned Length,
6312                                     SmallVectorImpl<Decl *> &Decls) {
6313   SourceManager &SM = getSourceManager();
6314 
6315   llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6316   if (I == FileDeclIDs.end())
6317     return;
6318 
6319   FileDeclsInfo &DInfo = I->second;
6320   if (DInfo.Decls.empty())
6321     return;
6322 
6323   SourceLocation
6324     BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6325   SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6326 
6327   DeclIDComp DIDComp(*this, *DInfo.Mod);
6328   ArrayRef<serialization::LocalDeclID>::iterator
6329     BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6330                                BeginLoc, DIDComp);
6331   if (BeginIt != DInfo.Decls.begin())
6332     --BeginIt;
6333 
6334   // If we are pointing at a top-level decl inside an objc container, we need
6335   // to backtrack until we find it otherwise we will fail to report that the
6336   // region overlaps with an objc container.
6337   while (BeginIt != DInfo.Decls.begin() &&
6338          GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6339              ->isTopLevelDeclInObjCContainer())
6340     --BeginIt;
6341 
6342   ArrayRef<serialization::LocalDeclID>::iterator
6343     EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6344                              EndLoc, DIDComp);
6345   if (EndIt != DInfo.Decls.end())
6346     ++EndIt;
6347 
6348   for (ArrayRef<serialization::LocalDeclID>::iterator
6349          DIt = BeginIt; DIt != EndIt; ++DIt)
6350     Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6351 }
6352 
6353 /// \brief Retrieve the "definitive" module file for the definition of the
6354 /// given declaration context, if there is one.
6355 ///
6356 /// The "definitive" module file is the only place where we need to look to
6357 /// find information about the declarations within the given declaration
6358 /// context. For example, C++ and Objective-C classes, C structs/unions, and
6359 /// Objective-C protocols, categories, and extensions are all defined in a
6360 /// single place in the source code, so they have definitive module files
6361 /// associated with them. C++ namespaces, on the other hand, can have
6362 /// definitions in multiple different module files.
6363 ///
6364 /// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6365 /// NDEBUG checking.
6366 static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6367                                               ASTReader &Reader) {
6368   if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6369     return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6370 
6371   return nullptr;
6372 }
6373 
6374 namespace {
6375   /// \brief ModuleFile visitor used to perform name lookup into a
6376   /// declaration context.
6377   class DeclContextNameLookupVisitor {
6378     ASTReader &Reader;
6379     const DeclContext *Context;
6380     DeclarationName Name;
6381     ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
6382     unsigned NameHash;
6383     SmallVectorImpl<NamedDecl *> &Decls;
6384     llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
6385 
6386   public:
6387     DeclContextNameLookupVisitor(ASTReader &Reader,
6388                                  const DeclContext *Context,
6389                                  DeclarationName Name,
6390                                  SmallVectorImpl<NamedDecl *> &Decls,
6391                                  llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
6392       : Reader(Reader), Context(Context), Name(Name),
6393         NameKey(ASTDeclContextNameLookupTrait::GetInternalKey(Name)),
6394         NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
6395         Decls(Decls), DeclSet(DeclSet) {}
6396 
6397     bool operator()(ModuleFile &M) {
6398       // Check whether we have any visible declaration information for
6399       // this context in this module.
6400       auto Info = M.DeclContextInfos.find(Context);
6401       if (Info == M.DeclContextInfos.end() || !Info->second.NameLookupTableData)
6402         return false;
6403 
6404       // Look for this name within this module.
6405       ASTDeclContextNameLookupTable *LookupTable =
6406           Info->second.NameLookupTableData;
6407       ASTDeclContextNameLookupTable::iterator Pos =
6408           LookupTable->find_hashed(NameKey, NameHash);
6409       if (Pos == LookupTable->end())
6410         return false;
6411 
6412       bool FoundAnything = false;
6413       ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6414       for (; Data.first != Data.second; ++Data.first) {
6415         NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6416         if (!ND)
6417           continue;
6418 
6419         if (ND->getDeclName() != Name) {
6420           // A name might be null because the decl's redeclarable part is
6421           // currently read before reading its name. The lookup is triggered by
6422           // building that decl (likely indirectly), and so it is later in the
6423           // sense of "already existing" and can be ignored here.
6424           // FIXME: This should not happen; deserializing declarations should
6425           // not perform lookups since that can lead to deserialization cycles.
6426           continue;
6427         }
6428 
6429         // Record this declaration.
6430         FoundAnything = true;
6431         if (DeclSet.insert(ND).second)
6432           Decls.push_back(ND);
6433       }
6434 
6435       return FoundAnything;
6436     }
6437   };
6438 }
6439 
6440 bool
6441 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6442                                           DeclarationName Name) {
6443   assert(DC->hasExternalVisibleStorage() &&
6444          "DeclContext has no visible decls in storage");
6445   if (!Name)
6446     return false;
6447 
6448   Deserializing LookupResults(this);
6449 
6450   SmallVector<NamedDecl *, 64> Decls;
6451   llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
6452 
6453   DeclContextNameLookupVisitor Visitor(*this, DC, Name, Decls, DeclSet);
6454 
6455   // If we can definitively determine which module file to look into,
6456   // only look there. Otherwise, look in all module files.
6457   if (ModuleFile *Definitive = getDefinitiveModuleFileFor(DC, *this))
6458     Visitor(*Definitive);
6459   else
6460     ModuleMgr.visit(Visitor);
6461 
6462   ++NumVisibleDeclContextsRead;
6463   SetExternalVisibleDeclsForName(DC, Name, Decls);
6464   return !Decls.empty();
6465 }
6466 
6467 namespace {
6468   /// \brief ModuleFile visitor used to retrieve all visible names in a
6469   /// declaration context.
6470   class DeclContextAllNamesVisitor {
6471     ASTReader &Reader;
6472     SmallVectorImpl<const DeclContext *> &Contexts;
6473     DeclsMap &Decls;
6474     llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
6475     bool VisitAll;
6476 
6477   public:
6478     DeclContextAllNamesVisitor(ASTReader &Reader,
6479                                SmallVectorImpl<const DeclContext *> &Contexts,
6480                                DeclsMap &Decls, bool VisitAll)
6481       : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
6482 
6483     bool operator()(ModuleFile &M) {
6484       // Check whether we have any visible declaration information for
6485       // this context in this module.
6486       ModuleFile::DeclContextInfosMap::iterator Info;
6487       bool FoundInfo = false;
6488       for (unsigned I = 0, N = Contexts.size(); I != N; ++I) {
6489         Info = M.DeclContextInfos.find(Contexts[I]);
6490         if (Info != M.DeclContextInfos.end() &&
6491             Info->second.NameLookupTableData) {
6492           FoundInfo = true;
6493           break;
6494         }
6495       }
6496 
6497       if (!FoundInfo)
6498         return false;
6499 
6500       ASTDeclContextNameLookupTable *LookupTable =
6501         Info->second.NameLookupTableData;
6502       bool FoundAnything = false;
6503       for (ASTDeclContextNameLookupTable::data_iterator
6504              I = LookupTable->data_begin(), E = LookupTable->data_end();
6505            I != E;
6506            ++I) {
6507         ASTDeclContextNameLookupTrait::data_type Data = *I;
6508         for (; Data.first != Data.second; ++Data.first) {
6509           NamedDecl *ND = Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6510           if (!ND)
6511             continue;
6512 
6513           // Record this declaration.
6514           FoundAnything = true;
6515           if (DeclSet.insert(ND).second)
6516             Decls[ND->getDeclName()].push_back(ND);
6517         }
6518       }
6519 
6520       return FoundAnything && !VisitAll;
6521     }
6522   };
6523 }
6524 
6525 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6526   if (!DC->hasExternalVisibleStorage())
6527     return;
6528   DeclsMap Decls;
6529 
6530   // Compute the declaration contexts we need to look into. Multiple such
6531   // declaration contexts occur when two declaration contexts from disjoint
6532   // modules get merged, e.g., when two namespaces with the same name are
6533   // independently defined in separate modules.
6534   SmallVector<const DeclContext *, 2> Contexts;
6535   Contexts.push_back(DC);
6536 
6537   if (DC->isNamespace()) {
6538     KeyDeclsMap::iterator Key =
6539         KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6540     if (Key != KeyDecls.end()) {
6541       for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
6542         Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
6543     }
6544   }
6545 
6546   DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6547                                      /*VisitAll=*/DC->isFileContext());
6548   ModuleMgr.visit(Visitor);
6549   ++NumVisibleDeclContextsRead;
6550 
6551   for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
6552     SetExternalVisibleDeclsForName(DC, I->first, I->second);
6553   }
6554   const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6555 }
6556 
6557 /// \brief Under non-PCH compilation the consumer receives the objc methods
6558 /// before receiving the implementation, and codegen depends on this.
6559 /// We simulate this by deserializing and passing to consumer the methods of the
6560 /// implementation before passing the deserialized implementation decl.
6561 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6562                                        ASTConsumer *Consumer) {
6563   assert(ImplD && Consumer);
6564 
6565   for (auto *I : ImplD->methods())
6566     Consumer->HandleInterestingDecl(DeclGroupRef(I));
6567 
6568   Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6569 }
6570 
6571 void ASTReader::PassInterestingDeclsToConsumer() {
6572   assert(Consumer);
6573 
6574   if (PassingDeclsToConsumer)
6575     return;
6576 
6577   // Guard variable to avoid recursively redoing the process of passing
6578   // decls to consumer.
6579   SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
6580                                                    true);
6581 
6582   // Ensure that we've loaded all potentially-interesting declarations
6583   // that need to be eagerly loaded.
6584   for (auto ID : EagerlyDeserializedDecls)
6585     GetDecl(ID);
6586   EagerlyDeserializedDecls.clear();
6587 
6588   while (!InterestingDecls.empty()) {
6589     Decl *D = InterestingDecls.front();
6590     InterestingDecls.pop_front();
6591 
6592     PassInterestingDeclToConsumer(D);
6593   }
6594 }
6595 
6596 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6597   if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6598     PassObjCImplDeclToConsumer(ImplD, Consumer);
6599   else
6600     Consumer->HandleInterestingDecl(DeclGroupRef(D));
6601 }
6602 
6603 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6604   this->Consumer = Consumer;
6605 
6606   if (Consumer)
6607     PassInterestingDeclsToConsumer();
6608 
6609   if (DeserializationListener)
6610     DeserializationListener->ReaderInitialized(this);
6611 }
6612 
6613 void ASTReader::PrintStats() {
6614   std::fprintf(stderr, "*** AST File Statistics:\n");
6615 
6616   unsigned NumTypesLoaded
6617     = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6618                                       QualType());
6619   unsigned NumDeclsLoaded
6620     = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6621                                       (Decl *)nullptr);
6622   unsigned NumIdentifiersLoaded
6623     = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6624                                             IdentifiersLoaded.end(),
6625                                             (IdentifierInfo *)nullptr);
6626   unsigned NumMacrosLoaded
6627     = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6628                                        MacrosLoaded.end(),
6629                                        (MacroInfo *)nullptr);
6630   unsigned NumSelectorsLoaded
6631     = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6632                                           SelectorsLoaded.end(),
6633                                           Selector());
6634 
6635   if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6636     std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
6637                  NumSLocEntriesRead, TotalNumSLocEntries,
6638                  ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6639   if (!TypesLoaded.empty())
6640     std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
6641                  NumTypesLoaded, (unsigned)TypesLoaded.size(),
6642                  ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6643   if (!DeclsLoaded.empty())
6644     std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
6645                  NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6646                  ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6647   if (!IdentifiersLoaded.empty())
6648     std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
6649                  NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6650                  ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6651   if (!MacrosLoaded.empty())
6652     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
6653                  NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6654                  ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6655   if (!SelectorsLoaded.empty())
6656     std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
6657                  NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6658                  ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6659   if (TotalNumStatements)
6660     std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
6661                  NumStatementsRead, TotalNumStatements,
6662                  ((float)NumStatementsRead/TotalNumStatements * 100));
6663   if (TotalNumMacros)
6664     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
6665                  NumMacrosRead, TotalNumMacros,
6666                  ((float)NumMacrosRead/TotalNumMacros * 100));
6667   if (TotalLexicalDeclContexts)
6668     std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
6669                  NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6670                  ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6671                   * 100));
6672   if (TotalVisibleDeclContexts)
6673     std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
6674                  NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6675                  ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6676                   * 100));
6677   if (TotalNumMethodPoolEntries) {
6678     std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
6679                  NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6680                  ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6681                   * 100));
6682   }
6683   if (NumMethodPoolLookups) {
6684     std::fprintf(stderr, "  %u/%u method pool lookups succeeded (%f%%)\n",
6685                  NumMethodPoolHits, NumMethodPoolLookups,
6686                  ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6687   }
6688   if (NumMethodPoolTableLookups) {
6689     std::fprintf(stderr, "  %u/%u method pool table lookups succeeded (%f%%)\n",
6690                  NumMethodPoolTableHits, NumMethodPoolTableLookups,
6691                  ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6692                   * 100.0));
6693   }
6694 
6695   if (NumIdentifierLookupHits) {
6696     std::fprintf(stderr,
6697                  "  %u / %u identifier table lookups succeeded (%f%%)\n",
6698                  NumIdentifierLookupHits, NumIdentifierLookups,
6699                  (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6700   }
6701 
6702   if (GlobalIndex) {
6703     std::fprintf(stderr, "\n");
6704     GlobalIndex->printStats();
6705   }
6706 
6707   std::fprintf(stderr, "\n");
6708   dump();
6709   std::fprintf(stderr, "\n");
6710 }
6711 
6712 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6713 static void
6714 dumpModuleIDMap(StringRef Name,
6715                 const ContinuousRangeMap<Key, ModuleFile *,
6716                                          InitialCapacity> &Map) {
6717   if (Map.begin() == Map.end())
6718     return;
6719 
6720   typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6721   llvm::errs() << Name << ":\n";
6722   for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6723        I != IEnd; ++I) {
6724     llvm::errs() << "  " << I->first << " -> " << I->second->FileName
6725       << "\n";
6726   }
6727 }
6728 
6729 void ASTReader::dump() {
6730   llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6731   dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6732   dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6733   dumpModuleIDMap("Global type map", GlobalTypeMap);
6734   dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6735   dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6736   dumpModuleIDMap("Global macro map", GlobalMacroMap);
6737   dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6738   dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6739   dumpModuleIDMap("Global preprocessed entity map",
6740                   GlobalPreprocessedEntityMap);
6741 
6742   llvm::errs() << "\n*** PCH/Modules Loaded:";
6743   for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6744                                        MEnd = ModuleMgr.end();
6745        M != MEnd; ++M)
6746     (*M)->dump();
6747 }
6748 
6749 /// Return the amount of memory used by memory buffers, breaking down
6750 /// by heap-backed versus mmap'ed memory.
6751 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6752   for (ModuleConstIterator I = ModuleMgr.begin(),
6753       E = ModuleMgr.end(); I != E; ++I) {
6754     if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6755       size_t bytes = buf->getBufferSize();
6756       switch (buf->getBufferKind()) {
6757         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6758           sizes.malloc_bytes += bytes;
6759           break;
6760         case llvm::MemoryBuffer::MemoryBuffer_MMap:
6761           sizes.mmap_bytes += bytes;
6762           break;
6763       }
6764     }
6765   }
6766 }
6767 
6768 void ASTReader::InitializeSema(Sema &S) {
6769   SemaObj = &S;
6770   S.addExternalSource(this);
6771 
6772   // Makes sure any declarations that were deserialized "too early"
6773   // still get added to the identifier's declaration chains.
6774   for (uint64_t ID : PreloadedDeclIDs) {
6775     NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
6776     pushExternalDeclIntoScope(D, D->getDeclName());
6777   }
6778   PreloadedDeclIDs.clear();
6779 
6780   // FIXME: What happens if these are changed by a module import?
6781   if (!FPPragmaOptions.empty()) {
6782     assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6783     SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6784   }
6785 
6786   // FIXME: What happens if these are changed by a module import?
6787   if (!OpenCLExtensions.empty()) {
6788     unsigned I = 0;
6789 #define OPENCLEXT(nm)  SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6790 #include "clang/Basic/OpenCLExtensions.def"
6791 
6792     assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6793   }
6794 
6795   UpdateSema();
6796 }
6797 
6798 void ASTReader::UpdateSema() {
6799   assert(SemaObj && "no Sema to update");
6800 
6801   // Load the offsets of the declarations that Sema references.
6802   // They will be lazily deserialized when needed.
6803   if (!SemaDeclRefs.empty()) {
6804     assert(SemaDeclRefs.size() % 2 == 0);
6805     for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6806       if (!SemaObj->StdNamespace)
6807         SemaObj->StdNamespace = SemaDeclRefs[I];
6808       if (!SemaObj->StdBadAlloc)
6809         SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6810     }
6811     SemaDeclRefs.clear();
6812   }
6813 
6814   // Update the state of 'pragma clang optimize'. Use the same API as if we had
6815   // encountered the pragma in the source.
6816   if(OptimizeOffPragmaLocation.isValid())
6817     SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
6818 }
6819 
6820 IdentifierInfo *ASTReader::get(StringRef Name) {
6821   // Note that we are loading an identifier.
6822   Deserializing AnIdentifier(this);
6823 
6824   IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
6825                                   NumIdentifierLookups,
6826                                   NumIdentifierLookupHits);
6827 
6828   // We don't need to do identifier table lookups in C++ modules (we preload
6829   // all interesting declarations, and don't need to use the scope for name
6830   // lookups). Perform the lookup in PCH files, though, since we don't build
6831   // a complete initial identifier table if we're carrying on from a PCH.
6832   if (Context.getLangOpts().CPlusPlus) {
6833     for (auto F : ModuleMgr.pch_modules())
6834       if (Visitor(*F))
6835         break;
6836   } else {
6837     // If there is a global index, look there first to determine which modules
6838     // provably do not have any results for this identifier.
6839     GlobalModuleIndex::HitSet Hits;
6840     GlobalModuleIndex::HitSet *HitsPtr = nullptr;
6841     if (!loadGlobalIndex()) {
6842       if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6843         HitsPtr = &Hits;
6844       }
6845     }
6846 
6847     ModuleMgr.visit(Visitor, HitsPtr);
6848   }
6849 
6850   IdentifierInfo *II = Visitor.getIdentifierInfo();
6851   markIdentifierUpToDate(II);
6852   return II;
6853 }
6854 
6855 namespace clang {
6856   /// \brief An identifier-lookup iterator that enumerates all of the
6857   /// identifiers stored within a set of AST files.
6858   class ASTIdentifierIterator : public IdentifierIterator {
6859     /// \brief The AST reader whose identifiers are being enumerated.
6860     const ASTReader &Reader;
6861 
6862     /// \brief The current index into the chain of AST files stored in
6863     /// the AST reader.
6864     unsigned Index;
6865 
6866     /// \brief The current position within the identifier lookup table
6867     /// of the current AST file.
6868     ASTIdentifierLookupTable::key_iterator Current;
6869 
6870     /// \brief The end position within the identifier lookup table of
6871     /// the current AST file.
6872     ASTIdentifierLookupTable::key_iterator End;
6873 
6874   public:
6875     explicit ASTIdentifierIterator(const ASTReader &Reader);
6876 
6877     StringRef Next() override;
6878   };
6879 }
6880 
6881 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6882   : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6883   ASTIdentifierLookupTable *IdTable
6884     = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6885   Current = IdTable->key_begin();
6886   End = IdTable->key_end();
6887 }
6888 
6889 StringRef ASTIdentifierIterator::Next() {
6890   while (Current == End) {
6891     // If we have exhausted all of our AST files, we're done.
6892     if (Index == 0)
6893       return StringRef();
6894 
6895     --Index;
6896     ASTIdentifierLookupTable *IdTable
6897       = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6898         IdentifierLookupTable;
6899     Current = IdTable->key_begin();
6900     End = IdTable->key_end();
6901   }
6902 
6903   // We have any identifiers remaining in the current AST file; return
6904   // the next one.
6905   StringRef Result = *Current;
6906   ++Current;
6907   return Result;
6908 }
6909 
6910 IdentifierIterator *ASTReader::getIdentifiers() {
6911   if (!loadGlobalIndex())
6912     return GlobalIndex->createIdentifierIterator();
6913 
6914   return new ASTIdentifierIterator(*this);
6915 }
6916 
6917 namespace clang { namespace serialization {
6918   class ReadMethodPoolVisitor {
6919     ASTReader &Reader;
6920     Selector Sel;
6921     unsigned PriorGeneration;
6922     unsigned InstanceBits;
6923     unsigned FactoryBits;
6924     bool InstanceHasMoreThanOneDecl;
6925     bool FactoryHasMoreThanOneDecl;
6926     SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6927     SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
6928 
6929   public:
6930     ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6931                           unsigned PriorGeneration)
6932         : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6933           InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
6934           FactoryHasMoreThanOneDecl(false) {}
6935 
6936     bool operator()(ModuleFile &M) {
6937       if (!M.SelectorLookupTable)
6938         return false;
6939 
6940       // If we've already searched this module file, skip it now.
6941       if (M.Generation <= PriorGeneration)
6942         return true;
6943 
6944       ++Reader.NumMethodPoolTableLookups;
6945       ASTSelectorLookupTable *PoolTable
6946         = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6947       ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
6948       if (Pos == PoolTable->end())
6949         return false;
6950 
6951       ++Reader.NumMethodPoolTableHits;
6952       ++Reader.NumSelectorsRead;
6953       // FIXME: Not quite happy with the statistics here. We probably should
6954       // disable this tracking when called via LoadSelector.
6955       // Also, should entries without methods count as misses?
6956       ++Reader.NumMethodPoolEntriesRead;
6957       ASTSelectorLookupTrait::data_type Data = *Pos;
6958       if (Reader.DeserializationListener)
6959         Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
6960 
6961       InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6962       FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6963       InstanceBits = Data.InstanceBits;
6964       FactoryBits = Data.FactoryBits;
6965       InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
6966       FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
6967       return true;
6968     }
6969 
6970     /// \brief Retrieve the instance methods found by this visitor.
6971     ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6972       return InstanceMethods;
6973     }
6974 
6975     /// \brief Retrieve the instance methods found by this visitor.
6976     ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6977       return FactoryMethods;
6978     }
6979 
6980     unsigned getInstanceBits() const { return InstanceBits; }
6981     unsigned getFactoryBits() const { return FactoryBits; }
6982     bool instanceHasMoreThanOneDecl() const {
6983       return InstanceHasMoreThanOneDecl;
6984     }
6985     bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
6986   };
6987 } } // end namespace clang::serialization
6988 
6989 /// \brief Add the given set of methods to the method list.
6990 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6991                              ObjCMethodList &List) {
6992   for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6993     S.addMethodToGlobalList(&List, Methods[I]);
6994   }
6995 }
6996 
6997 void ASTReader::ReadMethodPool(Selector Sel) {
6998   // Get the selector generation and update it to the current generation.
6999   unsigned &Generation = SelectorGeneration[Sel];
7000   unsigned PriorGeneration = Generation;
7001   Generation = getGeneration();
7002 
7003   // Search for methods defined with this selector.
7004   ++NumMethodPoolLookups;
7005   ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7006   ModuleMgr.visit(Visitor);
7007 
7008   if (Visitor.getInstanceMethods().empty() &&
7009       Visitor.getFactoryMethods().empty())
7010     return;
7011 
7012   ++NumMethodPoolHits;
7013 
7014   if (!getSema())
7015     return;
7016 
7017   Sema &S = *getSema();
7018   Sema::GlobalMethodPool::iterator Pos
7019     = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7020 
7021   Pos->second.first.setBits(Visitor.getInstanceBits());
7022   Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
7023   Pos->second.second.setBits(Visitor.getFactoryBits());
7024   Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
7025 
7026   // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7027   // when building a module we keep every method individually and may need to
7028   // update hasMoreThanOneDecl as we add the methods.
7029   addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7030   addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
7031 }
7032 
7033 void ASTReader::ReadKnownNamespaces(
7034                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7035   Namespaces.clear();
7036 
7037   for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7038     if (NamespaceDecl *Namespace
7039                 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7040       Namespaces.push_back(Namespace);
7041   }
7042 }
7043 
7044 void ASTReader::ReadUndefinedButUsed(
7045                         llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
7046   for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7047     NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
7048     SourceLocation Loc =
7049         SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
7050     Undefined.insert(std::make_pair(D, Loc));
7051   }
7052 }
7053 
7054 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7055     FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7056                                                      Exprs) {
7057   for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7058     FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7059     uint64_t Count = DelayedDeleteExprs[Idx++];
7060     for (uint64_t C = 0; C < Count; ++C) {
7061       SourceLocation DeleteLoc =
7062           SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7063       const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7064       Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7065     }
7066   }
7067 }
7068 
7069 void ASTReader::ReadTentativeDefinitions(
7070                   SmallVectorImpl<VarDecl *> &TentativeDefs) {
7071   for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7072     VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7073     if (Var)
7074       TentativeDefs.push_back(Var);
7075   }
7076   TentativeDefinitions.clear();
7077 }
7078 
7079 void ASTReader::ReadUnusedFileScopedDecls(
7080                                SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7081   for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7082     DeclaratorDecl *D
7083       = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7084     if (D)
7085       Decls.push_back(D);
7086   }
7087   UnusedFileScopedDecls.clear();
7088 }
7089 
7090 void ASTReader::ReadDelegatingConstructors(
7091                                  SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7092   for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7093     CXXConstructorDecl *D
7094       = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7095     if (D)
7096       Decls.push_back(D);
7097   }
7098   DelegatingCtorDecls.clear();
7099 }
7100 
7101 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7102   for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7103     TypedefNameDecl *D
7104       = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7105     if (D)
7106       Decls.push_back(D);
7107   }
7108   ExtVectorDecls.clear();
7109 }
7110 
7111 void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7112     llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7113   for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7114        ++I) {
7115     TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7116         GetDecl(UnusedLocalTypedefNameCandidates[I]));
7117     if (D)
7118       Decls.insert(D);
7119   }
7120   UnusedLocalTypedefNameCandidates.clear();
7121 }
7122 
7123 void ASTReader::ReadReferencedSelectors(
7124        SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7125   if (ReferencedSelectorsData.empty())
7126     return;
7127 
7128   // If there are @selector references added them to its pool. This is for
7129   // implementation of -Wselector.
7130   unsigned int DataSize = ReferencedSelectorsData.size()-1;
7131   unsigned I = 0;
7132   while (I < DataSize) {
7133     Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7134     SourceLocation SelLoc
7135       = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7136     Sels.push_back(std::make_pair(Sel, SelLoc));
7137   }
7138   ReferencedSelectorsData.clear();
7139 }
7140 
7141 void ASTReader::ReadWeakUndeclaredIdentifiers(
7142        SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7143   if (WeakUndeclaredIdentifiers.empty())
7144     return;
7145 
7146   for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7147     IdentifierInfo *WeakId
7148       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7149     IdentifierInfo *AliasId
7150       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7151     SourceLocation Loc
7152       = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7153     bool Used = WeakUndeclaredIdentifiers[I++];
7154     WeakInfo WI(AliasId, Loc);
7155     WI.setUsed(Used);
7156     WeakIDs.push_back(std::make_pair(WeakId, WI));
7157   }
7158   WeakUndeclaredIdentifiers.clear();
7159 }
7160 
7161 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7162   for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7163     ExternalVTableUse VT;
7164     VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7165     VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7166     VT.DefinitionRequired = VTableUses[Idx++];
7167     VTables.push_back(VT);
7168   }
7169 
7170   VTableUses.clear();
7171 }
7172 
7173 void ASTReader::ReadPendingInstantiations(
7174        SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7175   for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7176     ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7177     SourceLocation Loc
7178       = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7179 
7180     Pending.push_back(std::make_pair(D, Loc));
7181   }
7182   PendingInstantiations.clear();
7183 }
7184 
7185 void ASTReader::ReadLateParsedTemplates(
7186     llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
7187   for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7188        /* In loop */) {
7189     FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7190 
7191     LateParsedTemplate *LT = new LateParsedTemplate;
7192     LT->D = GetDecl(LateParsedTemplates[Idx++]);
7193 
7194     ModuleFile *F = getOwningModuleFile(LT->D);
7195     assert(F && "No module");
7196 
7197     unsigned TokN = LateParsedTemplates[Idx++];
7198     LT->Toks.reserve(TokN);
7199     for (unsigned T = 0; T < TokN; ++T)
7200       LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7201 
7202     LPTMap.insert(std::make_pair(FD, LT));
7203   }
7204 
7205   LateParsedTemplates.clear();
7206 }
7207 
7208 void ASTReader::LoadSelector(Selector Sel) {
7209   // It would be complicated to avoid reading the methods anyway. So don't.
7210   ReadMethodPool(Sel);
7211 }
7212 
7213 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7214   assert(ID && "Non-zero identifier ID required");
7215   assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7216   IdentifiersLoaded[ID - 1] = II;
7217   if (DeserializationListener)
7218     DeserializationListener->IdentifierRead(ID, II);
7219 }
7220 
7221 /// \brief Set the globally-visible declarations associated with the given
7222 /// identifier.
7223 ///
7224 /// If the AST reader is currently in a state where the given declaration IDs
7225 /// cannot safely be resolved, they are queued until it is safe to resolve
7226 /// them.
7227 ///
7228 /// \param II an IdentifierInfo that refers to one or more globally-visible
7229 /// declarations.
7230 ///
7231 /// \param DeclIDs the set of declaration IDs with the name @p II that are
7232 /// visible at global scope.
7233 ///
7234 /// \param Decls if non-null, this vector will be populated with the set of
7235 /// deserialized declarations. These declarations will not be pushed into
7236 /// scope.
7237 void
7238 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7239                               const SmallVectorImpl<uint32_t> &DeclIDs,
7240                                    SmallVectorImpl<Decl *> *Decls) {
7241   if (NumCurrentElementsDeserializing && !Decls) {
7242     PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
7243     return;
7244   }
7245 
7246   for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
7247     if (!SemaObj) {
7248       // Queue this declaration so that it will be added to the
7249       // translation unit scope and identifier's declaration chain
7250       // once a Sema object is known.
7251       PreloadedDeclIDs.push_back(DeclIDs[I]);
7252       continue;
7253     }
7254 
7255     NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7256 
7257     // If we're simply supposed to record the declarations, do so now.
7258     if (Decls) {
7259       Decls->push_back(D);
7260       continue;
7261     }
7262 
7263     // Introduce this declaration into the translation-unit scope
7264     // and add it to the declaration chain for this identifier, so
7265     // that (unqualified) name lookup will find it.
7266     pushExternalDeclIntoScope(D, II);
7267   }
7268 }
7269 
7270 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
7271   if (ID == 0)
7272     return nullptr;
7273 
7274   if (IdentifiersLoaded.empty()) {
7275     Error("no identifier table in AST file");
7276     return nullptr;
7277   }
7278 
7279   ID -= 1;
7280   if (!IdentifiersLoaded[ID]) {
7281     GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7282     assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7283     ModuleFile *M = I->second;
7284     unsigned Index = ID - M->BaseIdentifierID;
7285     const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7286 
7287     // All of the strings in the AST file are preceded by a 16-bit length.
7288     // Extract that 16-bit length to avoid having to execute strlen().
7289     // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7290     //  unsigned integers.  This is important to avoid integer overflow when
7291     //  we cast them to 'unsigned'.
7292     const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7293     unsigned StrLen = (((unsigned) StrLenPtr[0])
7294                        | (((unsigned) StrLenPtr[1]) << 8)) - 1;
7295     IdentifiersLoaded[ID]
7296       = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
7297     if (DeserializationListener)
7298       DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
7299   }
7300 
7301   return IdentifiersLoaded[ID];
7302 }
7303 
7304 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7305   return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
7306 }
7307 
7308 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7309   if (LocalID < NUM_PREDEF_IDENT_IDS)
7310     return LocalID;
7311 
7312   ContinuousRangeMap<uint32_t, int, 2>::iterator I
7313     = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
7314   assert(I != M.IdentifierRemap.end()
7315          && "Invalid index into identifier index remap");
7316 
7317   return LocalID + I->second;
7318 }
7319 
7320 MacroInfo *ASTReader::getMacro(MacroID ID) {
7321   if (ID == 0)
7322     return nullptr;
7323 
7324   if (MacrosLoaded.empty()) {
7325     Error("no macro table in AST file");
7326     return nullptr;
7327   }
7328 
7329   ID -= NUM_PREDEF_MACRO_IDS;
7330   if (!MacrosLoaded[ID]) {
7331     GlobalMacroMapType::iterator I
7332       = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7333     assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7334     ModuleFile *M = I->second;
7335     unsigned Index = ID - M->BaseMacroID;
7336     MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7337 
7338     if (DeserializationListener)
7339       DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7340                                          MacrosLoaded[ID]);
7341   }
7342 
7343   return MacrosLoaded[ID];
7344 }
7345 
7346 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7347   if (LocalID < NUM_PREDEF_MACRO_IDS)
7348     return LocalID;
7349 
7350   ContinuousRangeMap<uint32_t, int, 2>::iterator I
7351     = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7352   assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7353 
7354   return LocalID + I->second;
7355 }
7356 
7357 serialization::SubmoduleID
7358 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7359   if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7360     return LocalID;
7361 
7362   ContinuousRangeMap<uint32_t, int, 2>::iterator I
7363     = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7364   assert(I != M.SubmoduleRemap.end()
7365          && "Invalid index into submodule index remap");
7366 
7367   return LocalID + I->second;
7368 }
7369 
7370 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7371   if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7372     assert(GlobalID == 0 && "Unhandled global submodule ID");
7373     return nullptr;
7374   }
7375 
7376   if (GlobalID > SubmodulesLoaded.size()) {
7377     Error("submodule ID out of range in AST file");
7378     return nullptr;
7379   }
7380 
7381   return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7382 }
7383 
7384 Module *ASTReader::getModule(unsigned ID) {
7385   return getSubmodule(ID);
7386 }
7387 
7388 ExternalASTSource::ASTSourceDescriptor
7389 ASTReader::getSourceDescriptor(const Module &M) {
7390   StringRef Dir, Filename;
7391   if (M.Directory)
7392     Dir = M.Directory->getName();
7393   if (auto *File = M.getASTFile())
7394     Filename = File->getName();
7395   return ASTReader::ASTSourceDescriptor{
7396              M.getFullModuleName(), Dir, Filename,
7397              M.Signature
7398          };
7399 }
7400 
7401 llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7402 ASTReader::getSourceDescriptor(unsigned ID) {
7403   if (const Module *M = getSubmodule(ID))
7404     return getSourceDescriptor(*M);
7405 
7406   // If there is only a single PCH, return it instead.
7407   // Chained PCH are not suported.
7408   if (ModuleMgr.size() == 1) {
7409     ModuleFile &MF = ModuleMgr.getPrimaryModule();
7410     return ASTReader::ASTSourceDescriptor{
7411       MF.OriginalSourceFileName, MF.OriginalDir,
7412       MF.FileName,
7413       MF.Signature
7414     };
7415   }
7416   return None;
7417 }
7418 
7419 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7420   return DecodeSelector(getGlobalSelectorID(M, LocalID));
7421 }
7422 
7423 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7424   if (ID == 0)
7425     return Selector();
7426 
7427   if (ID > SelectorsLoaded.size()) {
7428     Error("selector ID out of range in AST file");
7429     return Selector();
7430   }
7431 
7432   if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
7433     // Load this selector from the selector table.
7434     GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7435     assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7436     ModuleFile &M = *I->second;
7437     ASTSelectorLookupTrait Trait(*this, M);
7438     unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7439     SelectorsLoaded[ID - 1] =
7440       Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7441     if (DeserializationListener)
7442       DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7443   }
7444 
7445   return SelectorsLoaded[ID - 1];
7446 }
7447 
7448 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7449   return DecodeSelector(ID);
7450 }
7451 
7452 uint32_t ASTReader::GetNumExternalSelectors() {
7453   // ID 0 (the null selector) is considered an external selector.
7454   return getTotalNumSelectors() + 1;
7455 }
7456 
7457 serialization::SelectorID
7458 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7459   if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7460     return LocalID;
7461 
7462   ContinuousRangeMap<uint32_t, int, 2>::iterator I
7463     = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7464   assert(I != M.SelectorRemap.end()
7465          && "Invalid index into selector index remap");
7466 
7467   return LocalID + I->second;
7468 }
7469 
7470 DeclarationName
7471 ASTReader::ReadDeclarationName(ModuleFile &F,
7472                                const RecordData &Record, unsigned &Idx) {
7473   DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7474   switch (Kind) {
7475   case DeclarationName::Identifier:
7476     return DeclarationName(GetIdentifierInfo(F, Record, Idx));
7477 
7478   case DeclarationName::ObjCZeroArgSelector:
7479   case DeclarationName::ObjCOneArgSelector:
7480   case DeclarationName::ObjCMultiArgSelector:
7481     return DeclarationName(ReadSelector(F, Record, Idx));
7482 
7483   case DeclarationName::CXXConstructorName:
7484     return Context.DeclarationNames.getCXXConstructorName(
7485                           Context.getCanonicalType(readType(F, Record, Idx)));
7486 
7487   case DeclarationName::CXXDestructorName:
7488     return Context.DeclarationNames.getCXXDestructorName(
7489                           Context.getCanonicalType(readType(F, Record, Idx)));
7490 
7491   case DeclarationName::CXXConversionFunctionName:
7492     return Context.DeclarationNames.getCXXConversionFunctionName(
7493                           Context.getCanonicalType(readType(F, Record, Idx)));
7494 
7495   case DeclarationName::CXXOperatorName:
7496     return Context.DeclarationNames.getCXXOperatorName(
7497                                        (OverloadedOperatorKind)Record[Idx++]);
7498 
7499   case DeclarationName::CXXLiteralOperatorName:
7500     return Context.DeclarationNames.getCXXLiteralOperatorName(
7501                                        GetIdentifierInfo(F, Record, Idx));
7502 
7503   case DeclarationName::CXXUsingDirective:
7504     return DeclarationName::getUsingDirectiveName();
7505   }
7506 
7507   llvm_unreachable("Invalid NameKind!");
7508 }
7509 
7510 void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7511                                        DeclarationNameLoc &DNLoc,
7512                                        DeclarationName Name,
7513                                       const RecordData &Record, unsigned &Idx) {
7514   switch (Name.getNameKind()) {
7515   case DeclarationName::CXXConstructorName:
7516   case DeclarationName::CXXDestructorName:
7517   case DeclarationName::CXXConversionFunctionName:
7518     DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7519     break;
7520 
7521   case DeclarationName::CXXOperatorName:
7522     DNLoc.CXXOperatorName.BeginOpNameLoc
7523         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7524     DNLoc.CXXOperatorName.EndOpNameLoc
7525         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7526     break;
7527 
7528   case DeclarationName::CXXLiteralOperatorName:
7529     DNLoc.CXXLiteralOperatorName.OpNameLoc
7530         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7531     break;
7532 
7533   case DeclarationName::Identifier:
7534   case DeclarationName::ObjCZeroArgSelector:
7535   case DeclarationName::ObjCOneArgSelector:
7536   case DeclarationName::ObjCMultiArgSelector:
7537   case DeclarationName::CXXUsingDirective:
7538     break;
7539   }
7540 }
7541 
7542 void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7543                                         DeclarationNameInfo &NameInfo,
7544                                       const RecordData &Record, unsigned &Idx) {
7545   NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7546   NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7547   DeclarationNameLoc DNLoc;
7548   ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7549   NameInfo.setInfo(DNLoc);
7550 }
7551 
7552 void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7553                                   const RecordData &Record, unsigned &Idx) {
7554   Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7555   unsigned NumTPLists = Record[Idx++];
7556   Info.NumTemplParamLists = NumTPLists;
7557   if (NumTPLists) {
7558     Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7559     for (unsigned i=0; i != NumTPLists; ++i)
7560       Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7561   }
7562 }
7563 
7564 TemplateName
7565 ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7566                             unsigned &Idx) {
7567   TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7568   switch (Kind) {
7569   case TemplateName::Template:
7570       return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7571 
7572   case TemplateName::OverloadedTemplate: {
7573     unsigned size = Record[Idx++];
7574     UnresolvedSet<8> Decls;
7575     while (size--)
7576       Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7577 
7578     return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7579   }
7580 
7581   case TemplateName::QualifiedTemplate: {
7582     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7583     bool hasTemplKeyword = Record[Idx++];
7584     TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7585     return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7586   }
7587 
7588   case TemplateName::DependentTemplate: {
7589     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7590     if (Record[Idx++])  // isIdentifier
7591       return Context.getDependentTemplateName(NNS,
7592                                                GetIdentifierInfo(F, Record,
7593                                                                  Idx));
7594     return Context.getDependentTemplateName(NNS,
7595                                          (OverloadedOperatorKind)Record[Idx++]);
7596   }
7597 
7598   case TemplateName::SubstTemplateTemplateParm: {
7599     TemplateTemplateParmDecl *param
7600       = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7601     if (!param) return TemplateName();
7602     TemplateName replacement = ReadTemplateName(F, Record, Idx);
7603     return Context.getSubstTemplateTemplateParm(param, replacement);
7604   }
7605 
7606   case TemplateName::SubstTemplateTemplateParmPack: {
7607     TemplateTemplateParmDecl *Param
7608       = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7609     if (!Param)
7610       return TemplateName();
7611 
7612     TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7613     if (ArgPack.getKind() != TemplateArgument::Pack)
7614       return TemplateName();
7615 
7616     return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7617   }
7618   }
7619 
7620   llvm_unreachable("Unhandled template name kind!");
7621 }
7622 
7623 TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
7624                                                  const RecordData &Record,
7625                                                  unsigned &Idx,
7626                                                  bool Canonicalize) {
7627   if (Canonicalize) {
7628     // The caller wants a canonical template argument. Sometimes the AST only
7629     // wants template arguments in canonical form (particularly as the template
7630     // argument lists of template specializations) so ensure we preserve that
7631     // canonical form across serialization.
7632     TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
7633     return Context.getCanonicalTemplateArgument(Arg);
7634   }
7635 
7636   TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7637   switch (Kind) {
7638   case TemplateArgument::Null:
7639     return TemplateArgument();
7640   case TemplateArgument::Type:
7641     return TemplateArgument(readType(F, Record, Idx));
7642   case TemplateArgument::Declaration: {
7643     ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7644     return TemplateArgument(D, readType(F, Record, Idx));
7645   }
7646   case TemplateArgument::NullPtr:
7647     return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7648   case TemplateArgument::Integral: {
7649     llvm::APSInt Value = ReadAPSInt(Record, Idx);
7650     QualType T = readType(F, Record, Idx);
7651     return TemplateArgument(Context, Value, T);
7652   }
7653   case TemplateArgument::Template:
7654     return TemplateArgument(ReadTemplateName(F, Record, Idx));
7655   case TemplateArgument::TemplateExpansion: {
7656     TemplateName Name = ReadTemplateName(F, Record, Idx);
7657     Optional<unsigned> NumTemplateExpansions;
7658     if (unsigned NumExpansions = Record[Idx++])
7659       NumTemplateExpansions = NumExpansions - 1;
7660     return TemplateArgument(Name, NumTemplateExpansions);
7661   }
7662   case TemplateArgument::Expression:
7663     return TemplateArgument(ReadExpr(F));
7664   case TemplateArgument::Pack: {
7665     unsigned NumArgs = Record[Idx++];
7666     TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7667     for (unsigned I = 0; I != NumArgs; ++I)
7668       Args[I] = ReadTemplateArgument(F, Record, Idx);
7669     return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
7670   }
7671   }
7672 
7673   llvm_unreachable("Unhandled template argument kind!");
7674 }
7675 
7676 TemplateParameterList *
7677 ASTReader::ReadTemplateParameterList(ModuleFile &F,
7678                                      const RecordData &Record, unsigned &Idx) {
7679   SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7680   SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7681   SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7682 
7683   unsigned NumParams = Record[Idx++];
7684   SmallVector<NamedDecl *, 16> Params;
7685   Params.reserve(NumParams);
7686   while (NumParams--)
7687     Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7688 
7689   TemplateParameterList* TemplateParams =
7690     TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7691                                   Params.data(), Params.size(), RAngleLoc);
7692   return TemplateParams;
7693 }
7694 
7695 void
7696 ASTReader::
7697 ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
7698                          ModuleFile &F, const RecordData &Record,
7699                          unsigned &Idx, bool Canonicalize) {
7700   unsigned NumTemplateArgs = Record[Idx++];
7701   TemplArgs.reserve(NumTemplateArgs);
7702   while (NumTemplateArgs--)
7703     TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
7704 }
7705 
7706 /// \brief Read a UnresolvedSet structure.
7707 void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
7708                                   const RecordData &Record, unsigned &Idx) {
7709   unsigned NumDecls = Record[Idx++];
7710   Set.reserve(Context, NumDecls);
7711   while (NumDecls--) {
7712     DeclID ID = ReadDeclID(F, Record, Idx);
7713     AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
7714     Set.addLazyDecl(Context, ID, AS);
7715   }
7716 }
7717 
7718 CXXBaseSpecifier
7719 ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7720                                 const RecordData &Record, unsigned &Idx) {
7721   bool isVirtual = static_cast<bool>(Record[Idx++]);
7722   bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7723   AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7724   bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7725   TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7726   SourceRange Range = ReadSourceRange(F, Record, Idx);
7727   SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7728   CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7729                           EllipsisLoc);
7730   Result.setInheritConstructors(inheritConstructors);
7731   return Result;
7732 }
7733 
7734 CXXCtorInitializer **
7735 ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7736                                    unsigned &Idx) {
7737   unsigned NumInitializers = Record[Idx++];
7738   assert(NumInitializers && "wrote ctor initializers but have no inits");
7739   auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
7740   for (unsigned i = 0; i != NumInitializers; ++i) {
7741     TypeSourceInfo *TInfo = nullptr;
7742     bool IsBaseVirtual = false;
7743     FieldDecl *Member = nullptr;
7744     IndirectFieldDecl *IndirectMember = nullptr;
7745 
7746     CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7747     switch (Type) {
7748     case CTOR_INITIALIZER_BASE:
7749       TInfo = GetTypeSourceInfo(F, Record, Idx);
7750       IsBaseVirtual = Record[Idx++];
7751       break;
7752 
7753     case CTOR_INITIALIZER_DELEGATING:
7754       TInfo = GetTypeSourceInfo(F, Record, Idx);
7755       break;
7756 
7757      case CTOR_INITIALIZER_MEMBER:
7758       Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7759       break;
7760 
7761      case CTOR_INITIALIZER_INDIRECT_MEMBER:
7762       IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7763       break;
7764     }
7765 
7766     SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7767     Expr *Init = ReadExpr(F);
7768     SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7769     SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7770     bool IsWritten = Record[Idx++];
7771     unsigned SourceOrderOrNumArrayIndices;
7772     SmallVector<VarDecl *, 8> Indices;
7773     if (IsWritten) {
7774       SourceOrderOrNumArrayIndices = Record[Idx++];
7775     } else {
7776       SourceOrderOrNumArrayIndices = Record[Idx++];
7777       Indices.reserve(SourceOrderOrNumArrayIndices);
7778       for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7779         Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7780     }
7781 
7782     CXXCtorInitializer *BOMInit;
7783     if (Type == CTOR_INITIALIZER_BASE) {
7784       BOMInit = new (Context)
7785           CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
7786                              RParenLoc, MemberOrEllipsisLoc);
7787     } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7788       BOMInit = new (Context)
7789           CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
7790     } else if (IsWritten) {
7791       if (Member)
7792         BOMInit = new (Context) CXXCtorInitializer(
7793             Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
7794       else
7795         BOMInit = new (Context)
7796             CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7797                                LParenLoc, Init, RParenLoc);
7798     } else {
7799       if (IndirectMember) {
7800         assert(Indices.empty() && "Indirect field improperly initialized");
7801         BOMInit = new (Context)
7802             CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
7803                                LParenLoc, Init, RParenLoc);
7804       } else {
7805         BOMInit = CXXCtorInitializer::Create(
7806             Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
7807             Indices.data(), Indices.size());
7808       }
7809     }
7810 
7811     if (IsWritten)
7812       BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7813     CtorInitializers[i] = BOMInit;
7814   }
7815 
7816   return CtorInitializers;
7817 }
7818 
7819 NestedNameSpecifier *
7820 ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7821                                    const RecordData &Record, unsigned &Idx) {
7822   unsigned N = Record[Idx++];
7823   NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
7824   for (unsigned I = 0; I != N; ++I) {
7825     NestedNameSpecifier::SpecifierKind Kind
7826       = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7827     switch (Kind) {
7828     case NestedNameSpecifier::Identifier: {
7829       IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7830       NNS = NestedNameSpecifier::Create(Context, Prev, II);
7831       break;
7832     }
7833 
7834     case NestedNameSpecifier::Namespace: {
7835       NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7836       NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7837       break;
7838     }
7839 
7840     case NestedNameSpecifier::NamespaceAlias: {
7841       NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7842       NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7843       break;
7844     }
7845 
7846     case NestedNameSpecifier::TypeSpec:
7847     case NestedNameSpecifier::TypeSpecWithTemplate: {
7848       const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7849       if (!T)
7850         return nullptr;
7851 
7852       bool Template = Record[Idx++];
7853       NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7854       break;
7855     }
7856 
7857     case NestedNameSpecifier::Global: {
7858       NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7859       // No associated value, and there can't be a prefix.
7860       break;
7861     }
7862 
7863     case NestedNameSpecifier::Super: {
7864       CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7865       NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
7866       break;
7867     }
7868     }
7869     Prev = NNS;
7870   }
7871   return NNS;
7872 }
7873 
7874 NestedNameSpecifierLoc
7875 ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7876                                       unsigned &Idx) {
7877   unsigned N = Record[Idx++];
7878   NestedNameSpecifierLocBuilder Builder;
7879   for (unsigned I = 0; I != N; ++I) {
7880     NestedNameSpecifier::SpecifierKind Kind
7881       = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7882     switch (Kind) {
7883     case NestedNameSpecifier::Identifier: {
7884       IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7885       SourceRange Range = ReadSourceRange(F, Record, Idx);
7886       Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7887       break;
7888     }
7889 
7890     case NestedNameSpecifier::Namespace: {
7891       NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7892       SourceRange Range = ReadSourceRange(F, Record, Idx);
7893       Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7894       break;
7895     }
7896 
7897     case NestedNameSpecifier::NamespaceAlias: {
7898       NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7899       SourceRange Range = ReadSourceRange(F, Record, Idx);
7900       Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7901       break;
7902     }
7903 
7904     case NestedNameSpecifier::TypeSpec:
7905     case NestedNameSpecifier::TypeSpecWithTemplate: {
7906       bool Template = Record[Idx++];
7907       TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7908       if (!T)
7909         return NestedNameSpecifierLoc();
7910       SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7911 
7912       // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7913       Builder.Extend(Context,
7914                      Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7915                      T->getTypeLoc(), ColonColonLoc);
7916       break;
7917     }
7918 
7919     case NestedNameSpecifier::Global: {
7920       SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7921       Builder.MakeGlobal(Context, ColonColonLoc);
7922       break;
7923     }
7924 
7925     case NestedNameSpecifier::Super: {
7926       CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
7927       SourceRange Range = ReadSourceRange(F, Record, Idx);
7928       Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
7929       break;
7930     }
7931     }
7932   }
7933 
7934   return Builder.getWithLocInContext(Context);
7935 }
7936 
7937 SourceRange
7938 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7939                            unsigned &Idx) {
7940   SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7941   SourceLocation end = ReadSourceLocation(F, Record, Idx);
7942   return SourceRange(beg, end);
7943 }
7944 
7945 /// \brief Read an integral value
7946 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7947   unsigned BitWidth = Record[Idx++];
7948   unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7949   llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7950   Idx += NumWords;
7951   return Result;
7952 }
7953 
7954 /// \brief Read a signed integral value
7955 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7956   bool isUnsigned = Record[Idx++];
7957   return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7958 }
7959 
7960 /// \brief Read a floating-point value
7961 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7962                                      const llvm::fltSemantics &Sem,
7963                                      unsigned &Idx) {
7964   return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
7965 }
7966 
7967 // \brief Read a string
7968 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7969   unsigned Len = Record[Idx++];
7970   std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7971   Idx += Len;
7972   return Result;
7973 }
7974 
7975 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
7976                                 unsigned &Idx) {
7977   std::string Filename = ReadString(Record, Idx);
7978   ResolveImportedPath(F, Filename);
7979   return Filename;
7980 }
7981 
7982 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7983                                          unsigned &Idx) {
7984   unsigned Major = Record[Idx++];
7985   unsigned Minor = Record[Idx++];
7986   unsigned Subminor = Record[Idx++];
7987   if (Minor == 0)
7988     return VersionTuple(Major);
7989   if (Subminor == 0)
7990     return VersionTuple(Major, Minor - 1);
7991   return VersionTuple(Major, Minor - 1, Subminor - 1);
7992 }
7993 
7994 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7995                                           const RecordData &Record,
7996                                           unsigned &Idx) {
7997   CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7998   return CXXTemporary::Create(Context, Decl);
7999 }
8000 
8001 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
8002   return Diag(CurrentImportLoc, DiagID);
8003 }
8004 
8005 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8006   return Diags.Report(Loc, DiagID);
8007 }
8008 
8009 /// \brief Retrieve the identifier table associated with the
8010 /// preprocessor.
8011 IdentifierTable &ASTReader::getIdentifierTable() {
8012   return PP.getIdentifierTable();
8013 }
8014 
8015 /// \brief Record that the given ID maps to the given switch-case
8016 /// statement.
8017 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
8018   assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
8019          "Already have a SwitchCase with this ID");
8020   (*CurrSwitchCaseStmts)[ID] = SC;
8021 }
8022 
8023 /// \brief Retrieve the switch-case statement with the given ID.
8024 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
8025   assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
8026   return (*CurrSwitchCaseStmts)[ID];
8027 }
8028 
8029 void ASTReader::ClearSwitchCaseIDs() {
8030   CurrSwitchCaseStmts->clear();
8031 }
8032 
8033 void ASTReader::ReadComments() {
8034   std::vector<RawComment *> Comments;
8035   for (SmallVectorImpl<std::pair<BitstreamCursor,
8036                                  serialization::ModuleFile *> >::iterator
8037        I = CommentsCursors.begin(),
8038        E = CommentsCursors.end();
8039        I != E; ++I) {
8040     Comments.clear();
8041     BitstreamCursor &Cursor = I->first;
8042     serialization::ModuleFile &F = *I->second;
8043     SavedStreamPosition SavedPosition(Cursor);
8044 
8045     RecordData Record;
8046     while (true) {
8047       llvm::BitstreamEntry Entry =
8048         Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
8049 
8050       switch (Entry.Kind) {
8051       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8052       case llvm::BitstreamEntry::Error:
8053         Error("malformed block record in AST file");
8054         return;
8055       case llvm::BitstreamEntry::EndBlock:
8056         goto NextCursor;
8057       case llvm::BitstreamEntry::Record:
8058         // The interesting case.
8059         break;
8060       }
8061 
8062       // Read a record.
8063       Record.clear();
8064       switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
8065       case COMMENTS_RAW_COMMENT: {
8066         unsigned Idx = 0;
8067         SourceRange SR = ReadSourceRange(F, Record, Idx);
8068         RawComment::CommentKind Kind =
8069             (RawComment::CommentKind) Record[Idx++];
8070         bool IsTrailingComment = Record[Idx++];
8071         bool IsAlmostTrailingComment = Record[Idx++];
8072         Comments.push_back(new (Context) RawComment(
8073             SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8074             Context.getLangOpts().CommentOpts.ParseAllComments));
8075         break;
8076       }
8077       }
8078     }
8079   NextCursor:
8080     Context.Comments.addDeserializedComments(Comments);
8081   }
8082 }
8083 
8084 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8085   // If we know the owning module, use it.
8086   if (Module *M = D->getImportedOwningModule())
8087     return M->getFullModuleName();
8088 
8089   // Otherwise, use the name of the top-level module the decl is within.
8090   if (ModuleFile *M = getOwningModuleFile(D))
8091     return M->ModuleName;
8092 
8093   // Not from a module.
8094   return "";
8095 }
8096 
8097 void ASTReader::finishPendingActions() {
8098   while (!PendingIdentifierInfos.empty() ||
8099          !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
8100          !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
8101          !PendingUpdateRecords.empty()) {
8102     // If any identifiers with corresponding top-level declarations have
8103     // been loaded, load those declarations now.
8104     typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8105       TopLevelDeclsMap;
8106     TopLevelDeclsMap TopLevelDecls;
8107 
8108     while (!PendingIdentifierInfos.empty()) {
8109       IdentifierInfo *II = PendingIdentifierInfos.back().first;
8110       SmallVector<uint32_t, 4> DeclIDs =
8111           std::move(PendingIdentifierInfos.back().second);
8112       PendingIdentifierInfos.pop_back();
8113 
8114       SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
8115     }
8116 
8117     // For each decl chain that we wanted to complete while deserializing, mark
8118     // it as "still needs to be completed".
8119     for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8120       markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8121     }
8122     PendingIncompleteDeclChains.clear();
8123 
8124     // Load pending declaration chains.
8125     for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
8126       PendingDeclChainsKnown.erase(PendingDeclChains[I]);
8127       loadPendingDeclChain(PendingDeclChains[I]);
8128     }
8129     assert(PendingDeclChainsKnown.empty());
8130     PendingDeclChains.clear();
8131 
8132     assert(RedeclsDeserialized.empty() && "some redecls not wired up");
8133 
8134     // Make the most recent of the top-level declarations visible.
8135     for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8136            TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
8137       IdentifierInfo *II = TLD->first;
8138       for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
8139         pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
8140       }
8141     }
8142 
8143     // Load any pending macro definitions.
8144     for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
8145       IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8146       SmallVector<PendingMacroInfo, 2> GlobalIDs;
8147       GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8148       // Initialize the macro history from chained-PCHs ahead of module imports.
8149       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8150            ++IDIdx) {
8151         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8152         if (Info.M->Kind != MK_ImplicitModule &&
8153             Info.M->Kind != MK_ExplicitModule)
8154           resolvePendingMacro(II, Info);
8155       }
8156       // Handle module imports.
8157       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8158            ++IDIdx) {
8159         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8160         if (Info.M->Kind == MK_ImplicitModule ||
8161             Info.M->Kind == MK_ExplicitModule)
8162           resolvePendingMacro(II, Info);
8163       }
8164     }
8165     PendingMacroIDs.clear();
8166 
8167     // Wire up the DeclContexts for Decls that we delayed setting until
8168     // recursive loading is completed.
8169     while (!PendingDeclContextInfos.empty()) {
8170       PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8171       PendingDeclContextInfos.pop_front();
8172       DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8173       DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8174       Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8175     }
8176 
8177     // Perform any pending declaration updates.
8178     while (!PendingUpdateRecords.empty()) {
8179       auto Update = PendingUpdateRecords.pop_back_val();
8180       ReadingKindTracker ReadingKind(Read_Decl, *this);
8181       loadDeclUpdateRecords(Update.first, Update.second);
8182     }
8183   }
8184 
8185   // At this point, all update records for loaded decls are in place, so any
8186   // fake class definitions should have become real.
8187   assert(PendingFakeDefinitionData.empty() &&
8188          "faked up a class definition but never saw the real one");
8189 
8190   // If we deserialized any C++ or Objective-C class definitions, any
8191   // Objective-C protocol definitions, or any redeclarable templates, make sure
8192   // that all redeclarations point to the definitions. Note that this can only
8193   // happen now, after the redeclaration chains have been fully wired.
8194   for (Decl *D : PendingDefinitions) {
8195     if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8196       if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
8197         // Make sure that the TagType points at the definition.
8198         const_cast<TagType*>(TagT)->decl = TD;
8199       }
8200 
8201       if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
8202         for (auto *R = getMostRecentExistingDecl(RD); R;
8203              R = R->getPreviousDecl()) {
8204           assert((R == D) ==
8205                      cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
8206                  "declaration thinks it's the definition but it isn't");
8207           cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
8208         }
8209       }
8210 
8211       continue;
8212     }
8213 
8214     if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
8215       // Make sure that the ObjCInterfaceType points at the definition.
8216       const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8217         ->Decl = ID;
8218 
8219       for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8220         cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8221 
8222       continue;
8223     }
8224 
8225     if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
8226       for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8227         cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8228 
8229       continue;
8230     }
8231 
8232     auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
8233     for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8234       cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
8235   }
8236   PendingDefinitions.clear();
8237 
8238   // Load the bodies of any functions or methods we've encountered. We do
8239   // this now (delayed) so that we can be sure that the declaration chains
8240   // have been fully wired up.
8241   // FIXME: There seems to be no point in delaying this, it does not depend
8242   // on the redecl chains having been wired up.
8243   for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8244                                PBEnd = PendingBodies.end();
8245        PB != PBEnd; ++PB) {
8246     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8247       // FIXME: Check for =delete/=default?
8248       // FIXME: Complain about ODR violations here?
8249       if (!getContext().getLangOpts().Modules || !FD->hasBody())
8250         FD->setLazyBody(PB->second);
8251       continue;
8252     }
8253 
8254     ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8255     if (!getContext().getLangOpts().Modules || !MD->hasBody())
8256       MD->setLazyBody(PB->second);
8257   }
8258   PendingBodies.clear();
8259 
8260   // Do some cleanup.
8261   for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8262     getContext().deduplicateMergedDefinitonsFor(ND);
8263   PendingMergedDefinitionsToDeduplicate.clear();
8264 }
8265 
8266 void ASTReader::diagnoseOdrViolations() {
8267   if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8268     return;
8269 
8270   // Trigger the import of the full definition of each class that had any
8271   // odr-merging problems, so we can produce better diagnostics for them.
8272   // These updates may in turn find and diagnose some ODR failures, so take
8273   // ownership of the set first.
8274   auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8275   PendingOdrMergeFailures.clear();
8276   for (auto &Merge : OdrMergeFailures) {
8277     Merge.first->buildLookup();
8278     Merge.first->decls_begin();
8279     Merge.first->bases_begin();
8280     Merge.first->vbases_begin();
8281     for (auto *RD : Merge.second) {
8282       RD->decls_begin();
8283       RD->bases_begin();
8284       RD->vbases_begin();
8285     }
8286   }
8287 
8288   // For each declaration from a merged context, check that the canonical
8289   // definition of that context also contains a declaration of the same
8290   // entity.
8291   //
8292   // Caution: this loop does things that might invalidate iterators into
8293   // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8294   while (!PendingOdrMergeChecks.empty()) {
8295     NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8296 
8297     // FIXME: Skip over implicit declarations for now. This matters for things
8298     // like implicitly-declared special member functions. This isn't entirely
8299     // correct; we can end up with multiple unmerged declarations of the same
8300     // implicit entity.
8301     if (D->isImplicit())
8302       continue;
8303 
8304     DeclContext *CanonDef = D->getDeclContext();
8305 
8306     bool Found = false;
8307     const Decl *DCanon = D->getCanonicalDecl();
8308 
8309     for (auto RI : D->redecls()) {
8310       if (RI->getLexicalDeclContext() == CanonDef) {
8311         Found = true;
8312         break;
8313       }
8314     }
8315     if (Found)
8316       continue;
8317 
8318     // Quick check failed, time to do the slow thing. Note, we can't just
8319     // look up the name of D in CanonDef here, because the member that is
8320     // in CanonDef might not be found by name lookup (it might have been
8321     // replaced by a more recent declaration in the lookup table), and we
8322     // can't necessarily find it in the redeclaration chain because it might
8323     // be merely mergeable, not redeclarable.
8324     llvm::SmallVector<const NamedDecl*, 4> Candidates;
8325     for (auto *CanonMember : CanonDef->decls()) {
8326       if (CanonMember->getCanonicalDecl() == DCanon) {
8327         // This can happen if the declaration is merely mergeable and not
8328         // actually redeclarable (we looked for redeclarations earlier).
8329         //
8330         // FIXME: We should be able to detect this more efficiently, without
8331         // pulling in all of the members of CanonDef.
8332         Found = true;
8333         break;
8334       }
8335       if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8336         if (ND->getDeclName() == D->getDeclName())
8337           Candidates.push_back(ND);
8338     }
8339 
8340     if (!Found) {
8341       // The AST doesn't like TagDecls becoming invalid after they've been
8342       // completed. We only really need to mark FieldDecls as invalid here.
8343       if (!isa<TagDecl>(D))
8344         D->setInvalidDecl();
8345 
8346       // Ensure we don't accidentally recursively enter deserialization while
8347       // we're producing our diagnostic.
8348       Deserializing RecursionGuard(this);
8349 
8350       std::string CanonDefModule =
8351           getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8352       Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8353         << D << getOwningModuleNameForDiagnostic(D)
8354         << CanonDef << CanonDefModule.empty() << CanonDefModule;
8355 
8356       if (Candidates.empty())
8357         Diag(cast<Decl>(CanonDef)->getLocation(),
8358              diag::note_module_odr_violation_no_possible_decls) << D;
8359       else {
8360         for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8361           Diag(Candidates[I]->getLocation(),
8362                diag::note_module_odr_violation_possible_decl)
8363             << Candidates[I];
8364       }
8365 
8366       DiagnosedOdrMergeFailures.insert(CanonDef);
8367     }
8368   }
8369 
8370   if (OdrMergeFailures.empty())
8371     return;
8372 
8373   // Ensure we don't accidentally recursively enter deserialization while
8374   // we're producing our diagnostics.
8375   Deserializing RecursionGuard(this);
8376 
8377   // Issue any pending ODR-failure diagnostics.
8378   for (auto &Merge : OdrMergeFailures) {
8379     // If we've already pointed out a specific problem with this class, don't
8380     // bother issuing a general "something's different" diagnostic.
8381     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
8382       continue;
8383 
8384     bool Diagnosed = false;
8385     for (auto *RD : Merge.second) {
8386       // Multiple different declarations got merged together; tell the user
8387       // where they came from.
8388       if (Merge.first != RD) {
8389         // FIXME: Walk the definition, figure out what's different,
8390         // and diagnose that.
8391         if (!Diagnosed) {
8392           std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8393           Diag(Merge.first->getLocation(),
8394                diag::err_module_odr_violation_different_definitions)
8395             << Merge.first << Module.empty() << Module;
8396           Diagnosed = true;
8397         }
8398 
8399         Diag(RD->getLocation(),
8400              diag::note_module_odr_violation_different_definitions)
8401           << getOwningModuleNameForDiagnostic(RD);
8402       }
8403     }
8404 
8405     if (!Diagnosed) {
8406       // All definitions are updates to the same declaration. This happens if a
8407       // module instantiates the declaration of a class template specialization
8408       // and two or more other modules instantiate its definition.
8409       //
8410       // FIXME: Indicate which modules had instantiations of this definition.
8411       // FIXME: How can this even happen?
8412       Diag(Merge.first->getLocation(),
8413            diag::err_module_odr_violation_different_instantiations)
8414         << Merge.first;
8415     }
8416   }
8417 }
8418 
8419 void ASTReader::StartedDeserializing() {
8420   if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
8421     ReadTimer->startTimer();
8422 }
8423 
8424 void ASTReader::FinishedDeserializing() {
8425   assert(NumCurrentElementsDeserializing &&
8426          "FinishedDeserializing not paired with StartedDeserializing");
8427   if (NumCurrentElementsDeserializing == 1) {
8428     // We decrease NumCurrentElementsDeserializing only after pending actions
8429     // are finished, to avoid recursively re-calling finishPendingActions().
8430     finishPendingActions();
8431   }
8432   --NumCurrentElementsDeserializing;
8433 
8434   if (NumCurrentElementsDeserializing == 0) {
8435     // Propagate exception specification updates along redeclaration chains.
8436     while (!PendingExceptionSpecUpdates.empty()) {
8437       auto Updates = std::move(PendingExceptionSpecUpdates);
8438       PendingExceptionSpecUpdates.clear();
8439       for (auto Update : Updates) {
8440         auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
8441         SemaObj->UpdateExceptionSpec(Update.second,
8442                                      FPT->getExtProtoInfo().ExceptionSpec);
8443       }
8444     }
8445 
8446     if (ReadTimer)
8447       ReadTimer->stopTimer();
8448 
8449     diagnoseOdrViolations();
8450 
8451     // We are not in recursive loading, so it's safe to pass the "interesting"
8452     // decls to the consumer.
8453     if (Consumer)
8454       PassInterestingDeclsToConsumer();
8455   }
8456 }
8457 
8458 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
8459   if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8460     // Remove any fake results before adding any real ones.
8461     auto It = PendingFakeLookupResults.find(II);
8462     if (It != PendingFakeLookupResults.end()) {
8463       for (auto *ND : It->second)
8464         SemaObj->IdResolver.RemoveDecl(ND);
8465       // FIXME: this works around module+PCH performance issue.
8466       // Rather than erase the result from the map, which is O(n), just clear
8467       // the vector of NamedDecls.
8468       It->second.clear();
8469     }
8470   }
8471 
8472   if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8473     SemaObj->TUScope->AddDecl(D);
8474   } else if (SemaObj->TUScope) {
8475     // Adding the decl to IdResolver may have failed because it was already in
8476     // (even though it was not added in scope). If it is already in, make sure
8477     // it gets in the scope as well.
8478     if (std::find(SemaObj->IdResolver.begin(Name),
8479                   SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8480       SemaObj->TUScope->AddDecl(D);
8481   }
8482 }
8483 
8484 ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
8485                      const PCHContainerReader &PCHContainerRdr,
8486                      StringRef isysroot, bool DisableValidation,
8487                      bool AllowASTWithCompilerErrors,
8488                      bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8489                      bool UseGlobalIndex,
8490                      std::unique_ptr<llvm::Timer> ReadTimer)
8491     : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
8492       OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
8493       FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
8494       Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
8495       Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
8496       ReadTimer(std::move(ReadTimer)),
8497       isysroot(isysroot), DisableValidation(DisableValidation),
8498       AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
8499       AllowConfigurationMismatch(AllowConfigurationMismatch),
8500       ValidateSystemInputs(ValidateSystemInputs),
8501       UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
8502       CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
8503       TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
8504       NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
8505       NumIdentifierLookupHits(0), NumSelectorsRead(0),
8506       NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
8507       NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
8508       NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
8509       NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
8510       NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
8511       TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
8512       PassingDeclsToConsumer(false), ReadingKind(Read_None) {
8513   SourceMgr.setExternalSLocEntrySource(this);
8514 }
8515 
8516 ASTReader::~ASTReader() {
8517   if (OwnsDeserializationListener)
8518     delete DeserializationListener;
8519 }
8520