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