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