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