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