1 //===- ASTReader.cpp - AST File Reader ------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines the ASTReader class, which reads AST files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Basic/OpenMPKinds.h"
14 #include "clang/Serialization/ASTRecordReader.h"
15 #include "ASTCommon.h"
16 #include "ASTReaderInternals.h"
17 #include "clang/AST/AbstractTypeReader.h"
18 #include "clang/AST/ASTConsumer.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/ASTMutationListener.h"
21 #include "clang/AST/ASTUnresolvedSet.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclBase.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/DeclFriend.h"
26 #include "clang/AST/DeclGroup.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/AST/DeclTemplate.h"
29 #include "clang/AST/DeclarationName.h"
30 #include "clang/AST/Expr.h"
31 #include "clang/AST/ExprCXX.h"
32 #include "clang/AST/ExternalASTSource.h"
33 #include "clang/AST/NestedNameSpecifier.h"
34 #include "clang/AST/OpenMPClause.h"
35 #include "clang/AST/ODRHash.h"
36 #include "clang/AST/RawCommentList.h"
37 #include "clang/AST/TemplateBase.h"
38 #include "clang/AST/TemplateName.h"
39 #include "clang/AST/Type.h"
40 #include "clang/AST/TypeLoc.h"
41 #include "clang/AST/TypeLocVisitor.h"
42 #include "clang/AST/UnresolvedSet.h"
43 #include "clang/Basic/CommentOptions.h"
44 #include "clang/Basic/Diagnostic.h"
45 #include "clang/Basic/DiagnosticOptions.h"
46 #include "clang/Basic/ExceptionSpecificationType.h"
47 #include "clang/Basic/FileManager.h"
48 #include "clang/Basic/FileSystemOptions.h"
49 #include "clang/Basic/IdentifierTable.h"
50 #include "clang/Basic/LLVM.h"
51 #include "clang/Basic/LangOptions.h"
52 #include "clang/Basic/Module.h"
53 #include "clang/Basic/ObjCRuntime.h"
54 #include "clang/Basic/OperatorKinds.h"
55 #include "clang/Basic/PragmaKinds.h"
56 #include "clang/Basic/Sanitizers.h"
57 #include "clang/Basic/SourceLocation.h"
58 #include "clang/Basic/SourceManager.h"
59 #include "clang/Basic/SourceManagerInternals.h"
60 #include "clang/Basic/Specifiers.h"
61 #include "clang/Basic/TargetInfo.h"
62 #include "clang/Basic/TargetOptions.h"
63 #include "clang/Basic/TokenKinds.h"
64 #include "clang/Basic/Version.h"
65 #include "clang/Lex/HeaderSearch.h"
66 #include "clang/Lex/HeaderSearchOptions.h"
67 #include "clang/Lex/MacroInfo.h"
68 #include "clang/Lex/ModuleMap.h"
69 #include "clang/Lex/PreprocessingRecord.h"
70 #include "clang/Lex/Preprocessor.h"
71 #include "clang/Lex/PreprocessorOptions.h"
72 #include "clang/Lex/Token.h"
73 #include "clang/Sema/ObjCMethodList.h"
74 #include "clang/Sema/Scope.h"
75 #include "clang/Sema/Sema.h"
76 #include "clang/Sema/Weak.h"
77 #include "clang/Serialization/ASTBitCodes.h"
78 #include "clang/Serialization/ASTDeserializationListener.h"
79 #include "clang/Serialization/ContinuousRangeMap.h"
80 #include "clang/Serialization/GlobalModuleIndex.h"
81 #include "clang/Serialization/InMemoryModuleCache.h"
82 #include "clang/Serialization/ModuleFile.h"
83 #include "clang/Serialization/ModuleFileExtension.h"
84 #include "clang/Serialization/ModuleManager.h"
85 #include "clang/Serialization/PCHContainerOperations.h"
86 #include "clang/Serialization/SerializationDiagnostic.h"
87 #include "llvm/ADT/APFloat.h"
88 #include "llvm/ADT/APInt.h"
89 #include "llvm/ADT/APSInt.h"
90 #include "llvm/ADT/ArrayRef.h"
91 #include "llvm/ADT/DenseMap.h"
92 #include "llvm/ADT/FoldingSet.h"
93 #include "llvm/ADT/Hashing.h"
94 #include "llvm/ADT/IntrusiveRefCntPtr.h"
95 #include "llvm/ADT/None.h"
96 #include "llvm/ADT/Optional.h"
97 #include "llvm/ADT/STLExtras.h"
98 #include "llvm/ADT/ScopeExit.h"
99 #include "llvm/ADT/SmallPtrSet.h"
100 #include "llvm/ADT/SmallString.h"
101 #include "llvm/ADT/SmallVector.h"
102 #include "llvm/ADT/StringExtras.h"
103 #include "llvm/ADT/StringMap.h"
104 #include "llvm/ADT/StringRef.h"
105 #include "llvm/ADT/Triple.h"
106 #include "llvm/ADT/iterator_range.h"
107 #include "llvm/Bitstream/BitstreamReader.h"
108 #include "llvm/Support/Casting.h"
109 #include "llvm/Support/Compiler.h"
110 #include "llvm/Support/Compression.h"
111 #include "llvm/Support/DJB.h"
112 #include "llvm/Support/Endian.h"
113 #include "llvm/Support/Error.h"
114 #include "llvm/Support/ErrorHandling.h"
115 #include "llvm/Support/FileSystem.h"
116 #include "llvm/Support/MemoryBuffer.h"
117 #include "llvm/Support/Path.h"
118 #include "llvm/Support/SaveAndRestore.h"
119 #include "llvm/Support/Timer.h"
120 #include "llvm/Support/VersionTuple.h"
121 #include "llvm/Support/raw_ostream.h"
122 #include <algorithm>
123 #include <cassert>
124 #include <cstddef>
125 #include <cstdint>
126 #include <cstdio>
127 #include <ctime>
128 #include <iterator>
129 #include <limits>
130 #include <map>
131 #include <memory>
132 #include <string>
133 #include <system_error>
134 #include <tuple>
135 #include <utility>
136 #include <vector>
137 
138 using namespace clang;
139 using namespace clang::serialization;
140 using namespace clang::serialization::reader;
141 using llvm::BitstreamCursor;
142 
143 //===----------------------------------------------------------------------===//
144 // ChainedASTReaderListener implementation
145 //===----------------------------------------------------------------------===//
146 
147 bool
148 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
149   return First->ReadFullVersionInformation(FullVersion) ||
150          Second->ReadFullVersionInformation(FullVersion);
151 }
152 
153 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
154   First->ReadModuleName(ModuleName);
155   Second->ReadModuleName(ModuleName);
156 }
157 
158 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
159   First->ReadModuleMapFile(ModuleMapPath);
160   Second->ReadModuleMapFile(ModuleMapPath);
161 }
162 
163 bool
164 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
165                                               bool Complain,
166                                               bool AllowCompatibleDifferences) {
167   return First->ReadLanguageOptions(LangOpts, Complain,
168                                     AllowCompatibleDifferences) ||
169          Second->ReadLanguageOptions(LangOpts, Complain,
170                                      AllowCompatibleDifferences);
171 }
172 
173 bool ChainedASTReaderListener::ReadTargetOptions(
174     const TargetOptions &TargetOpts, bool Complain,
175     bool AllowCompatibleDifferences) {
176   return First->ReadTargetOptions(TargetOpts, Complain,
177                                   AllowCompatibleDifferences) ||
178          Second->ReadTargetOptions(TargetOpts, Complain,
179                                    AllowCompatibleDifferences);
180 }
181 
182 bool ChainedASTReaderListener::ReadDiagnosticOptions(
183     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
184   return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
185          Second->ReadDiagnosticOptions(DiagOpts, Complain);
186 }
187 
188 bool
189 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
190                                                 bool Complain) {
191   return First->ReadFileSystemOptions(FSOpts, Complain) ||
192          Second->ReadFileSystemOptions(FSOpts, Complain);
193 }
194 
195 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
196     const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
197     bool Complain) {
198   return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
199                                         Complain) ||
200          Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
201                                          Complain);
202 }
203 
204 bool ChainedASTReaderListener::ReadPreprocessorOptions(
205     const PreprocessorOptions &PPOpts, bool Complain,
206     std::string &SuggestedPredefines) {
207   return First->ReadPreprocessorOptions(PPOpts, Complain,
208                                         SuggestedPredefines) ||
209          Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
210 }
211 
212 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
213                                            unsigned Value) {
214   First->ReadCounter(M, Value);
215   Second->ReadCounter(M, Value);
216 }
217 
218 bool ChainedASTReaderListener::needsInputFileVisitation() {
219   return First->needsInputFileVisitation() ||
220          Second->needsInputFileVisitation();
221 }
222 
223 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
224   return First->needsSystemInputFileVisitation() ||
225   Second->needsSystemInputFileVisitation();
226 }
227 
228 void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
229                                                ModuleKind Kind) {
230   First->visitModuleFile(Filename, Kind);
231   Second->visitModuleFile(Filename, Kind);
232 }
233 
234 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
235                                               bool isSystem,
236                                               bool isOverridden,
237                                               bool isExplicitModule) {
238   bool Continue = false;
239   if (First->needsInputFileVisitation() &&
240       (!isSystem || First->needsSystemInputFileVisitation()))
241     Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
242                                       isExplicitModule);
243   if (Second->needsInputFileVisitation() &&
244       (!isSystem || Second->needsSystemInputFileVisitation()))
245     Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
246                                        isExplicitModule);
247   return Continue;
248 }
249 
250 void ChainedASTReaderListener::readModuleFileExtension(
251        const ModuleFileExtensionMetadata &Metadata) {
252   First->readModuleFileExtension(Metadata);
253   Second->readModuleFileExtension(Metadata);
254 }
255 
256 //===----------------------------------------------------------------------===//
257 // PCH validator implementation
258 //===----------------------------------------------------------------------===//
259 
260 ASTReaderListener::~ASTReaderListener() = default;
261 
262 /// Compare the given set of language options against an existing set of
263 /// language options.
264 ///
265 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
266 /// \param AllowCompatibleDifferences If true, differences between compatible
267 ///        language options will be permitted.
268 ///
269 /// \returns true if the languagae options mis-match, false otherwise.
270 static bool checkLanguageOptions(const LangOptions &LangOpts,
271                                  const LangOptions &ExistingLangOpts,
272                                  DiagnosticsEngine *Diags,
273                                  bool AllowCompatibleDifferences = true) {
274 #define LANGOPT(Name, Bits, Default, Description)                 \
275   if (ExistingLangOpts.Name != LangOpts.Name) {                   \
276     if (Diags)                                                    \
277       Diags->Report(diag::err_pch_langopt_mismatch)               \
278         << Description << LangOpts.Name << ExistingLangOpts.Name; \
279     return true;                                                  \
280   }
281 
282 #define VALUE_LANGOPT(Name, Bits, Default, Description)   \
283   if (ExistingLangOpts.Name != LangOpts.Name) {           \
284     if (Diags)                                            \
285       Diags->Report(diag::err_pch_langopt_value_mismatch) \
286         << Description;                                   \
287     return true;                                          \
288   }
289 
290 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description)   \
291   if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) {  \
292     if (Diags)                                                 \
293       Diags->Report(diag::err_pch_langopt_value_mismatch)      \
294         << Description;                                        \
295     return true;                                               \
296   }
297 
298 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description)  \
299   if (!AllowCompatibleDifferences)                            \
300     LANGOPT(Name, Bits, Default, Description)
301 
302 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description)  \
303   if (!AllowCompatibleDifferences)                                 \
304     ENUM_LANGOPT(Name, Bits, Default, Description)
305 
306 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
307   if (!AllowCompatibleDifferences)                                 \
308     VALUE_LANGOPT(Name, Bits, Default, Description)
309 
310 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
311 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
312 #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
313 #include "clang/Basic/LangOptions.def"
314 
315   if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
316     if (Diags)
317       Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
318     return true;
319   }
320 
321   if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
322     if (Diags)
323       Diags->Report(diag::err_pch_langopt_value_mismatch)
324       << "target Objective-C runtime";
325     return true;
326   }
327 
328   if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
329       LangOpts.CommentOpts.BlockCommandNames) {
330     if (Diags)
331       Diags->Report(diag::err_pch_langopt_value_mismatch)
332         << "block command names";
333     return true;
334   }
335 
336   // Sanitizer feature mismatches are treated as compatible differences. If
337   // compatible differences aren't allowed, we still only want to check for
338   // mismatches of non-modular sanitizers (the only ones which can affect AST
339   // generation).
340   if (!AllowCompatibleDifferences) {
341     SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
342     SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
343     SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
344     ExistingSanitizers.clear(ModularSanitizers);
345     ImportedSanitizers.clear(ModularSanitizers);
346     if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
347       const std::string Flag = "-fsanitize=";
348       if (Diags) {
349 #define SANITIZER(NAME, ID)                                                    \
350   {                                                                            \
351     bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID);         \
352     bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID);         \
353     if (InExistingModule != InImportedModule)                                  \
354       Diags->Report(diag::err_pch_targetopt_feature_mismatch)                  \
355           << InExistingModule << (Flag + NAME);                                \
356   }
357 #include "clang/Basic/Sanitizers.def"
358       }
359       return true;
360     }
361   }
362 
363   return false;
364 }
365 
366 /// Compare the given set of target options against an existing set of
367 /// target options.
368 ///
369 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
370 ///
371 /// \returns true if the target options mis-match, false otherwise.
372 static bool checkTargetOptions(const TargetOptions &TargetOpts,
373                                const TargetOptions &ExistingTargetOpts,
374                                DiagnosticsEngine *Diags,
375                                bool AllowCompatibleDifferences = true) {
376 #define CHECK_TARGET_OPT(Field, Name)                             \
377   if (TargetOpts.Field != ExistingTargetOpts.Field) {             \
378     if (Diags)                                                    \
379       Diags->Report(diag::err_pch_targetopt_mismatch)             \
380         << Name << TargetOpts.Field << ExistingTargetOpts.Field;  \
381     return true;                                                  \
382   }
383 
384   // The triple and ABI must match exactly.
385   CHECK_TARGET_OPT(Triple, "target");
386   CHECK_TARGET_OPT(ABI, "target ABI");
387 
388   // We can tolerate different CPUs in many cases, notably when one CPU
389   // supports a strict superset of another. When allowing compatible
390   // differences skip this check.
391   if (!AllowCompatibleDifferences)
392     CHECK_TARGET_OPT(CPU, "target CPU");
393 
394 #undef CHECK_TARGET_OPT
395 
396   // Compare feature sets.
397   SmallVector<StringRef, 4> ExistingFeatures(
398                                              ExistingTargetOpts.FeaturesAsWritten.begin(),
399                                              ExistingTargetOpts.FeaturesAsWritten.end());
400   SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
401                                          TargetOpts.FeaturesAsWritten.end());
402   llvm::sort(ExistingFeatures);
403   llvm::sort(ReadFeatures);
404 
405   // We compute the set difference in both directions explicitly so that we can
406   // diagnose the differences differently.
407   SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
408   std::set_difference(
409       ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
410       ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
411   std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
412                       ExistingFeatures.begin(), ExistingFeatures.end(),
413                       std::back_inserter(UnmatchedReadFeatures));
414 
415   // If we are allowing compatible differences and the read feature set is
416   // a strict subset of the existing feature set, there is nothing to diagnose.
417   if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
418     return false;
419 
420   if (Diags) {
421     for (StringRef Feature : UnmatchedReadFeatures)
422       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
423           << /* is-existing-feature */ false << Feature;
424     for (StringRef Feature : UnmatchedExistingFeatures)
425       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
426           << /* is-existing-feature */ true << Feature;
427   }
428 
429   return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
430 }
431 
432 bool
433 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
434                                   bool Complain,
435                                   bool AllowCompatibleDifferences) {
436   const LangOptions &ExistingLangOpts = PP.getLangOpts();
437   return checkLanguageOptions(LangOpts, ExistingLangOpts,
438                               Complain ? &Reader.Diags : nullptr,
439                               AllowCompatibleDifferences);
440 }
441 
442 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
443                                      bool Complain,
444                                      bool AllowCompatibleDifferences) {
445   const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
446   return checkTargetOptions(TargetOpts, ExistingTargetOpts,
447                             Complain ? &Reader.Diags : nullptr,
448                             AllowCompatibleDifferences);
449 }
450 
451 namespace {
452 
453 using MacroDefinitionsMap =
454     llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
455 using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
456 
457 } // namespace
458 
459 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
460                                          DiagnosticsEngine &Diags,
461                                          bool Complain) {
462   using Level = DiagnosticsEngine::Level;
463 
464   // Check current mappings for new -Werror mappings, and the stored mappings
465   // for cases that were explicitly mapped to *not* be errors that are now
466   // errors because of options like -Werror.
467   DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
468 
469   for (DiagnosticsEngine *MappingSource : MappingSources) {
470     for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
471       diag::kind DiagID = DiagIDMappingPair.first;
472       Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
473       if (CurLevel < DiagnosticsEngine::Error)
474         continue; // not significant
475       Level StoredLevel =
476           StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
477       if (StoredLevel < DiagnosticsEngine::Error) {
478         if (Complain)
479           Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
480               Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
481         return true;
482       }
483     }
484   }
485 
486   return false;
487 }
488 
489 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
490   diag::Severity Ext = Diags.getExtensionHandlingBehavior();
491   if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
492     return true;
493   return Ext >= diag::Severity::Error;
494 }
495 
496 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
497                                     DiagnosticsEngine &Diags,
498                                     bool IsSystem, bool Complain) {
499   // Top-level options
500   if (IsSystem) {
501     if (Diags.getSuppressSystemWarnings())
502       return false;
503     // If -Wsystem-headers was not enabled before, be conservative
504     if (StoredDiags.getSuppressSystemWarnings()) {
505       if (Complain)
506         Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
507       return true;
508     }
509   }
510 
511   if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
512     if (Complain)
513       Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
514     return true;
515   }
516 
517   if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
518       !StoredDiags.getEnableAllWarnings()) {
519     if (Complain)
520       Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
521     return true;
522   }
523 
524   if (isExtHandlingFromDiagsError(Diags) &&
525       !isExtHandlingFromDiagsError(StoredDiags)) {
526     if (Complain)
527       Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
528     return true;
529   }
530 
531   return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
532 }
533 
534 /// Return the top import module if it is implicit, nullptr otherwise.
535 static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
536                                           Preprocessor &PP) {
537   // If the original import came from a file explicitly generated by the user,
538   // don't check the diagnostic mappings.
539   // FIXME: currently this is approximated by checking whether this is not a
540   // module import of an implicitly-loaded module file.
541   // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
542   // the transitive closure of its imports, since unrelated modules cannot be
543   // imported until after this module finishes validation.
544   ModuleFile *TopImport = &*ModuleMgr.rbegin();
545   while (!TopImport->ImportedBy.empty())
546     TopImport = TopImport->ImportedBy[0];
547   if (TopImport->Kind != MK_ImplicitModule)
548     return nullptr;
549 
550   StringRef ModuleName = TopImport->ModuleName;
551   assert(!ModuleName.empty() && "diagnostic options read before module name");
552 
553   Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
554   assert(M && "missing module");
555   return M;
556 }
557 
558 bool PCHValidator::ReadDiagnosticOptions(
559     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
560   DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
561   IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
562   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
563       new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
564   // This should never fail, because we would have processed these options
565   // before writing them to an ASTFile.
566   ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
567 
568   ModuleManager &ModuleMgr = Reader.getModuleManager();
569   assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
570 
571   Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
572   if (!TopM)
573     return false;
574 
575   // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
576   // contains the union of their flags.
577   return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
578                                  Complain);
579 }
580 
581 /// Collect the macro definitions provided by the given preprocessor
582 /// options.
583 static void
584 collectMacroDefinitions(const PreprocessorOptions &PPOpts,
585                         MacroDefinitionsMap &Macros,
586                         SmallVectorImpl<StringRef> *MacroNames = nullptr) {
587   for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
588     StringRef Macro = PPOpts.Macros[I].first;
589     bool IsUndef = PPOpts.Macros[I].second;
590 
591     std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
592     StringRef MacroName = MacroPair.first;
593     StringRef MacroBody = MacroPair.second;
594 
595     // For an #undef'd macro, we only care about the name.
596     if (IsUndef) {
597       if (MacroNames && !Macros.count(MacroName))
598         MacroNames->push_back(MacroName);
599 
600       Macros[MacroName] = std::make_pair("", true);
601       continue;
602     }
603 
604     // For a #define'd macro, figure out the actual definition.
605     if (MacroName.size() == Macro.size())
606       MacroBody = "1";
607     else {
608       // Note: GCC drops anything following an end-of-line character.
609       StringRef::size_type End = MacroBody.find_first_of("\n\r");
610       MacroBody = MacroBody.substr(0, End);
611     }
612 
613     if (MacroNames && !Macros.count(MacroName))
614       MacroNames->push_back(MacroName);
615     Macros[MacroName] = std::make_pair(MacroBody, false);
616   }
617 }
618 
619 /// Check the preprocessor options deserialized from the control block
620 /// against the preprocessor options in an existing preprocessor.
621 ///
622 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
623 /// \param Validate If true, validate preprocessor options. If false, allow
624 ///        macros defined by \p ExistingPPOpts to override those defined by
625 ///        \p PPOpts in SuggestedPredefines.
626 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
627                                      const PreprocessorOptions &ExistingPPOpts,
628                                      DiagnosticsEngine *Diags,
629                                      FileManager &FileMgr,
630                                      std::string &SuggestedPredefines,
631                                      const LangOptions &LangOpts,
632                                      bool Validate = true) {
633   // Check macro definitions.
634   MacroDefinitionsMap ASTFileMacros;
635   collectMacroDefinitions(PPOpts, ASTFileMacros);
636   MacroDefinitionsMap ExistingMacros;
637   SmallVector<StringRef, 4> ExistingMacroNames;
638   collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
639 
640   for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
641     // Dig out the macro definition in the existing preprocessor options.
642     StringRef MacroName = ExistingMacroNames[I];
643     std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
644 
645     // Check whether we know anything about this macro name or not.
646     llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
647         ASTFileMacros.find(MacroName);
648     if (!Validate || Known == ASTFileMacros.end()) {
649       // FIXME: Check whether this identifier was referenced anywhere in the
650       // AST file. If so, we should reject the AST file. Unfortunately, this
651       // information isn't in the control block. What shall we do about it?
652 
653       if (Existing.second) {
654         SuggestedPredefines += "#undef ";
655         SuggestedPredefines += MacroName.str();
656         SuggestedPredefines += '\n';
657       } else {
658         SuggestedPredefines += "#define ";
659         SuggestedPredefines += MacroName.str();
660         SuggestedPredefines += ' ';
661         SuggestedPredefines += Existing.first.str();
662         SuggestedPredefines += '\n';
663       }
664       continue;
665     }
666 
667     // If the macro was defined in one but undef'd in the other, we have a
668     // conflict.
669     if (Existing.second != Known->second.second) {
670       if (Diags) {
671         Diags->Report(diag::err_pch_macro_def_undef)
672           << MacroName << Known->second.second;
673       }
674       return true;
675     }
676 
677     // If the macro was #undef'd in both, or if the macro bodies are identical,
678     // it's fine.
679     if (Existing.second || Existing.first == Known->second.first)
680       continue;
681 
682     // The macro bodies differ; complain.
683     if (Diags) {
684       Diags->Report(diag::err_pch_macro_def_conflict)
685         << MacroName << Known->second.first << Existing.first;
686     }
687     return true;
688   }
689 
690   // Check whether we're using predefines.
691   if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
692     if (Diags) {
693       Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
694     }
695     return true;
696   }
697 
698   // Detailed record is important since it is used for the module cache hash.
699   if (LangOpts.Modules &&
700       PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
701     if (Diags) {
702       Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
703     }
704     return true;
705   }
706 
707   // Compute the #include and #include_macros lines we need.
708   for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
709     StringRef File = ExistingPPOpts.Includes[I];
710 
711     if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
712         !ExistingPPOpts.PCHThroughHeader.empty()) {
713       // In case the through header is an include, we must add all the includes
714       // to the predefines so the start point can be determined.
715       SuggestedPredefines += "#include \"";
716       SuggestedPredefines += File;
717       SuggestedPredefines += "\"\n";
718       continue;
719     }
720 
721     if (File == ExistingPPOpts.ImplicitPCHInclude)
722       continue;
723 
724     if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
725           != PPOpts.Includes.end())
726       continue;
727 
728     SuggestedPredefines += "#include \"";
729     SuggestedPredefines += File;
730     SuggestedPredefines += "\"\n";
731   }
732 
733   for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
734     StringRef File = ExistingPPOpts.MacroIncludes[I];
735     if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
736                   File)
737         != PPOpts.MacroIncludes.end())
738       continue;
739 
740     SuggestedPredefines += "#__include_macros \"";
741     SuggestedPredefines += File;
742     SuggestedPredefines += "\"\n##\n";
743   }
744 
745   return false;
746 }
747 
748 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
749                                            bool Complain,
750                                            std::string &SuggestedPredefines) {
751   const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
752 
753   return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
754                                   Complain? &Reader.Diags : nullptr,
755                                   PP.getFileManager(),
756                                   SuggestedPredefines,
757                                   PP.getLangOpts());
758 }
759 
760 bool SimpleASTReaderListener::ReadPreprocessorOptions(
761                                   const PreprocessorOptions &PPOpts,
762                                   bool Complain,
763                                   std::string &SuggestedPredefines) {
764   return checkPreprocessorOptions(PPOpts,
765                                   PP.getPreprocessorOpts(),
766                                   nullptr,
767                                   PP.getFileManager(),
768                                   SuggestedPredefines,
769                                   PP.getLangOpts(),
770                                   false);
771 }
772 
773 /// Check the header search options deserialized from the control block
774 /// against the header search options in an existing preprocessor.
775 ///
776 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
777 static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
778                                      StringRef SpecificModuleCachePath,
779                                      StringRef ExistingModuleCachePath,
780                                      DiagnosticsEngine *Diags,
781                                      const LangOptions &LangOpts) {
782   if (LangOpts.Modules) {
783     if (SpecificModuleCachePath != ExistingModuleCachePath) {
784       if (Diags)
785         Diags->Report(diag::err_pch_modulecache_mismatch)
786           << SpecificModuleCachePath << ExistingModuleCachePath;
787       return true;
788     }
789   }
790 
791   return false;
792 }
793 
794 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
795                                            StringRef SpecificModuleCachePath,
796                                            bool Complain) {
797   return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
798                                   PP.getHeaderSearchInfo().getModuleCachePath(),
799                                   Complain ? &Reader.Diags : nullptr,
800                                   PP.getLangOpts());
801 }
802 
803 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
804   PP.setCounterValue(Value);
805 }
806 
807 //===----------------------------------------------------------------------===//
808 // AST reader implementation
809 //===----------------------------------------------------------------------===//
810 
811 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
812                                            bool TakeOwnership) {
813   DeserializationListener = Listener;
814   OwnsDeserializationListener = TakeOwnership;
815 }
816 
817 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
818   return serialization::ComputeHash(Sel);
819 }
820 
821 std::pair<unsigned, unsigned>
822 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
823   using namespace llvm::support;
824 
825   unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
826   unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
827   return std::make_pair(KeyLen, DataLen);
828 }
829 
830 ASTSelectorLookupTrait::internal_key_type
831 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
832   using namespace llvm::support;
833 
834   SelectorTable &SelTable = Reader.getContext().Selectors;
835   unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
836   IdentifierInfo *FirstII = Reader.getLocalIdentifier(
837       F, endian::readNext<uint32_t, little, unaligned>(d));
838   if (N == 0)
839     return SelTable.getNullarySelector(FirstII);
840   else if (N == 1)
841     return SelTable.getUnarySelector(FirstII);
842 
843   SmallVector<IdentifierInfo *, 16> Args;
844   Args.push_back(FirstII);
845   for (unsigned I = 1; I != N; ++I)
846     Args.push_back(Reader.getLocalIdentifier(
847         F, endian::readNext<uint32_t, little, unaligned>(d)));
848 
849   return SelTable.getSelector(N, Args.data());
850 }
851 
852 ASTSelectorLookupTrait::data_type
853 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
854                                  unsigned DataLen) {
855   using namespace llvm::support;
856 
857   data_type Result;
858 
859   Result.ID = Reader.getGlobalSelectorID(
860       F, endian::readNext<uint32_t, little, unaligned>(d));
861   unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
862   unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
863   Result.InstanceBits = FullInstanceBits & 0x3;
864   Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
865   Result.FactoryBits = FullFactoryBits & 0x3;
866   Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
867   unsigned NumInstanceMethods = FullInstanceBits >> 3;
868   unsigned NumFactoryMethods = FullFactoryBits >> 3;
869 
870   // Load instance methods
871   for (unsigned I = 0; I != NumInstanceMethods; ++I) {
872     if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
873             F, endian::readNext<uint32_t, little, unaligned>(d)))
874       Result.Instance.push_back(Method);
875   }
876 
877   // Load factory methods
878   for (unsigned I = 0; I != NumFactoryMethods; ++I) {
879     if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
880             F, endian::readNext<uint32_t, little, unaligned>(d)))
881       Result.Factory.push_back(Method);
882   }
883 
884   return Result;
885 }
886 
887 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
888   return llvm::djbHash(a);
889 }
890 
891 std::pair<unsigned, unsigned>
892 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
893   using namespace llvm::support;
894 
895   unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
896   unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
897   return std::make_pair(KeyLen, DataLen);
898 }
899 
900 ASTIdentifierLookupTraitBase::internal_key_type
901 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
902   assert(n >= 2 && d[n-1] == '\0');
903   return StringRef((const char*) d, n-1);
904 }
905 
906 /// Whether the given identifier is "interesting".
907 static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
908                                     bool IsModule) {
909   return II.hadMacroDefinition() ||
910          II.isPoisoned() ||
911          (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
912          II.hasRevertedTokenIDToIdentifier() ||
913          (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
914           II.getFETokenInfo());
915 }
916 
917 static bool readBit(unsigned &Bits) {
918   bool Value = Bits & 0x1;
919   Bits >>= 1;
920   return Value;
921 }
922 
923 IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
924   using namespace llvm::support;
925 
926   unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
927   return Reader.getGlobalIdentifierID(F, RawID >> 1);
928 }
929 
930 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
931   if (!II.isFromAST()) {
932     II.setIsFromAST();
933     bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
934     if (isInterestingIdentifier(Reader, II, IsModule))
935       II.setChangedSinceDeserialization();
936   }
937 }
938 
939 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
940                                                    const unsigned char* d,
941                                                    unsigned DataLen) {
942   using namespace llvm::support;
943 
944   unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
945   bool IsInteresting = RawID & 0x01;
946 
947   // Wipe out the "is interesting" bit.
948   RawID = RawID >> 1;
949 
950   // Build the IdentifierInfo and link the identifier ID with it.
951   IdentifierInfo *II = KnownII;
952   if (!II) {
953     II = &Reader.getIdentifierTable().getOwn(k);
954     KnownII = II;
955   }
956   markIdentifierFromAST(Reader, *II);
957   Reader.markIdentifierUpToDate(II);
958 
959   IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
960   if (!IsInteresting) {
961     // For uninteresting identifiers, there's nothing else to do. Just notify
962     // the reader that we've finished loading this identifier.
963     Reader.SetIdentifierInfo(ID, II);
964     return II;
965   }
966 
967   unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
968   unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
969   bool CPlusPlusOperatorKeyword = readBit(Bits);
970   bool HasRevertedTokenIDToIdentifier = readBit(Bits);
971   bool HasRevertedBuiltin = readBit(Bits);
972   bool Poisoned = readBit(Bits);
973   bool ExtensionToken = readBit(Bits);
974   bool HadMacroDefinition = readBit(Bits);
975 
976   assert(Bits == 0 && "Extra bits in the identifier?");
977   DataLen -= 8;
978 
979   // Set or check the various bits in the IdentifierInfo structure.
980   // Token IDs are read-only.
981   if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
982     II->revertTokenIDToIdentifier();
983   if (!F.isModule())
984     II->setObjCOrBuiltinID(ObjCOrBuiltinID);
985   else if (HasRevertedBuiltin && II->getBuiltinID()) {
986     II->revertBuiltin();
987     assert((II->hasRevertedBuiltin() ||
988             II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
989            "Incorrect ObjC keyword or builtin ID");
990   }
991   assert(II->isExtensionToken() == ExtensionToken &&
992          "Incorrect extension token flag");
993   (void)ExtensionToken;
994   if (Poisoned)
995     II->setIsPoisoned(true);
996   assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
997          "Incorrect C++ operator keyword flag");
998   (void)CPlusPlusOperatorKeyword;
999 
1000   // If this identifier is a macro, deserialize the macro
1001   // definition.
1002   if (HadMacroDefinition) {
1003     uint32_t MacroDirectivesOffset =
1004         endian::readNext<uint32_t, little, unaligned>(d);
1005     DataLen -= 4;
1006 
1007     Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1008   }
1009 
1010   Reader.SetIdentifierInfo(ID, II);
1011 
1012   // Read all of the declarations visible at global scope with this
1013   // name.
1014   if (DataLen > 0) {
1015     SmallVector<uint32_t, 4> DeclIDs;
1016     for (; DataLen > 0; DataLen -= 4)
1017       DeclIDs.push_back(Reader.getGlobalDeclID(
1018           F, endian::readNext<uint32_t, little, unaligned>(d)));
1019     Reader.SetGloballyVisibleDecls(II, DeclIDs);
1020   }
1021 
1022   return II;
1023 }
1024 
1025 DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1026     : Kind(Name.getNameKind()) {
1027   switch (Kind) {
1028   case DeclarationName::Identifier:
1029     Data = (uint64_t)Name.getAsIdentifierInfo();
1030     break;
1031   case DeclarationName::ObjCZeroArgSelector:
1032   case DeclarationName::ObjCOneArgSelector:
1033   case DeclarationName::ObjCMultiArgSelector:
1034     Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1035     break;
1036   case DeclarationName::CXXOperatorName:
1037     Data = Name.getCXXOverloadedOperator();
1038     break;
1039   case DeclarationName::CXXLiteralOperatorName:
1040     Data = (uint64_t)Name.getCXXLiteralIdentifier();
1041     break;
1042   case DeclarationName::CXXDeductionGuideName:
1043     Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1044                ->getDeclName().getAsIdentifierInfo();
1045     break;
1046   case DeclarationName::CXXConstructorName:
1047   case DeclarationName::CXXDestructorName:
1048   case DeclarationName::CXXConversionFunctionName:
1049   case DeclarationName::CXXUsingDirective:
1050     Data = 0;
1051     break;
1052   }
1053 }
1054 
1055 unsigned DeclarationNameKey::getHash() const {
1056   llvm::FoldingSetNodeID ID;
1057   ID.AddInteger(Kind);
1058 
1059   switch (Kind) {
1060   case DeclarationName::Identifier:
1061   case DeclarationName::CXXLiteralOperatorName:
1062   case DeclarationName::CXXDeductionGuideName:
1063     ID.AddString(((IdentifierInfo*)Data)->getName());
1064     break;
1065   case DeclarationName::ObjCZeroArgSelector:
1066   case DeclarationName::ObjCOneArgSelector:
1067   case DeclarationName::ObjCMultiArgSelector:
1068     ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1069     break;
1070   case DeclarationName::CXXOperatorName:
1071     ID.AddInteger((OverloadedOperatorKind)Data);
1072     break;
1073   case DeclarationName::CXXConstructorName:
1074   case DeclarationName::CXXDestructorName:
1075   case DeclarationName::CXXConversionFunctionName:
1076   case DeclarationName::CXXUsingDirective:
1077     break;
1078   }
1079 
1080   return ID.ComputeHash();
1081 }
1082 
1083 ModuleFile *
1084 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1085   using namespace llvm::support;
1086 
1087   uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1088   return Reader.getLocalModuleFile(F, ModuleFileID);
1089 }
1090 
1091 std::pair<unsigned, unsigned>
1092 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1093   using namespace llvm::support;
1094 
1095   unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1096   unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
1097   return std::make_pair(KeyLen, DataLen);
1098 }
1099 
1100 ASTDeclContextNameLookupTrait::internal_key_type
1101 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1102   using namespace llvm::support;
1103 
1104   auto Kind = (DeclarationName::NameKind)*d++;
1105   uint64_t Data;
1106   switch (Kind) {
1107   case DeclarationName::Identifier:
1108   case DeclarationName::CXXLiteralOperatorName:
1109   case DeclarationName::CXXDeductionGuideName:
1110     Data = (uint64_t)Reader.getLocalIdentifier(
1111         F, endian::readNext<uint32_t, little, unaligned>(d));
1112     break;
1113   case DeclarationName::ObjCZeroArgSelector:
1114   case DeclarationName::ObjCOneArgSelector:
1115   case DeclarationName::ObjCMultiArgSelector:
1116     Data =
1117         (uint64_t)Reader.getLocalSelector(
1118                              F, endian::readNext<uint32_t, little, unaligned>(
1119                                     d)).getAsOpaquePtr();
1120     break;
1121   case DeclarationName::CXXOperatorName:
1122     Data = *d++; // OverloadedOperatorKind
1123     break;
1124   case DeclarationName::CXXConstructorName:
1125   case DeclarationName::CXXDestructorName:
1126   case DeclarationName::CXXConversionFunctionName:
1127   case DeclarationName::CXXUsingDirective:
1128     Data = 0;
1129     break;
1130   }
1131 
1132   return DeclarationNameKey(Kind, Data);
1133 }
1134 
1135 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1136                                                  const unsigned char *d,
1137                                                  unsigned DataLen,
1138                                                  data_type_builder &Val) {
1139   using namespace llvm::support;
1140 
1141   for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1142     uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1143     Val.insert(Reader.getGlobalDeclID(F, LocalID));
1144   }
1145 }
1146 
1147 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1148                                               BitstreamCursor &Cursor,
1149                                               uint64_t Offset,
1150                                               DeclContext *DC) {
1151   assert(Offset != 0);
1152 
1153   SavedStreamPosition SavedPosition(Cursor);
1154   if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1155     Error(std::move(Err));
1156     return true;
1157   }
1158 
1159   RecordData Record;
1160   StringRef Blob;
1161   Expected<unsigned> MaybeCode = Cursor.ReadCode();
1162   if (!MaybeCode) {
1163     Error(MaybeCode.takeError());
1164     return true;
1165   }
1166   unsigned Code = MaybeCode.get();
1167 
1168   Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1169   if (!MaybeRecCode) {
1170     Error(MaybeRecCode.takeError());
1171     return true;
1172   }
1173   unsigned RecCode = MaybeRecCode.get();
1174   if (RecCode != DECL_CONTEXT_LEXICAL) {
1175     Error("Expected lexical block");
1176     return true;
1177   }
1178 
1179   assert(!isa<TranslationUnitDecl>(DC) &&
1180          "expected a TU_UPDATE_LEXICAL record for TU");
1181   // If we are handling a C++ class template instantiation, we can see multiple
1182   // lexical updates for the same record. It's important that we select only one
1183   // of them, so that field numbering works properly. Just pick the first one we
1184   // see.
1185   auto &Lex = LexicalDecls[DC];
1186   if (!Lex.first) {
1187     Lex = std::make_pair(
1188         &M, llvm::makeArrayRef(
1189                 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1190                     Blob.data()),
1191                 Blob.size() / 4));
1192   }
1193   DC->setHasExternalLexicalStorage(true);
1194   return false;
1195 }
1196 
1197 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1198                                               BitstreamCursor &Cursor,
1199                                               uint64_t Offset,
1200                                               DeclID ID) {
1201   assert(Offset != 0);
1202 
1203   SavedStreamPosition SavedPosition(Cursor);
1204   if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1205     Error(std::move(Err));
1206     return true;
1207   }
1208 
1209   RecordData Record;
1210   StringRef Blob;
1211   Expected<unsigned> MaybeCode = Cursor.ReadCode();
1212   if (!MaybeCode) {
1213     Error(MaybeCode.takeError());
1214     return true;
1215   }
1216   unsigned Code = MaybeCode.get();
1217 
1218   Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1219   if (!MaybeRecCode) {
1220     Error(MaybeRecCode.takeError());
1221     return true;
1222   }
1223   unsigned RecCode = MaybeRecCode.get();
1224   if (RecCode != DECL_CONTEXT_VISIBLE) {
1225     Error("Expected visible lookup table block");
1226     return true;
1227   }
1228 
1229   // We can't safely determine the primary context yet, so delay attaching the
1230   // lookup table until we're done with recursive deserialization.
1231   auto *Data = (const unsigned char*)Blob.data();
1232   PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1233   return false;
1234 }
1235 
1236 void ASTReader::Error(StringRef Msg) const {
1237   Error(diag::err_fe_pch_malformed, Msg);
1238   if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1239       !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1240     Diag(diag::note_module_cache_path)
1241       << PP.getHeaderSearchInfo().getModuleCachePath();
1242   }
1243 }
1244 
1245 void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1246                       StringRef Arg3) const {
1247   if (Diags.isDiagnosticInFlight())
1248     Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
1249   else
1250     Diag(DiagID) << Arg1 << Arg2 << Arg3;
1251 }
1252 
1253 void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1254                       unsigned Select) const {
1255   if (!Diags.isDiagnosticInFlight())
1256     Diag(DiagID) << Arg1 << Arg2 << Select;
1257 }
1258 
1259 void ASTReader::Error(llvm::Error &&Err) const {
1260   Error(toString(std::move(Err)));
1261 }
1262 
1263 //===----------------------------------------------------------------------===//
1264 // Source Manager Deserialization
1265 //===----------------------------------------------------------------------===//
1266 
1267 /// Read the line table in the source manager block.
1268 /// \returns true if there was an error.
1269 bool ASTReader::ParseLineTable(ModuleFile &F,
1270                                const RecordData &Record) {
1271   unsigned Idx = 0;
1272   LineTableInfo &LineTable = SourceMgr.getLineTable();
1273 
1274   // Parse the file names
1275   std::map<int, int> FileIDs;
1276   FileIDs[-1] = -1; // For unspecified filenames.
1277   for (unsigned I = 0; Record[Idx]; ++I) {
1278     // Extract the file name
1279     auto Filename = ReadPath(F, Record, Idx);
1280     FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1281   }
1282   ++Idx;
1283 
1284   // Parse the line entries
1285   std::vector<LineEntry> Entries;
1286   while (Idx < Record.size()) {
1287     int FID = Record[Idx++];
1288     assert(FID >= 0 && "Serialized line entries for non-local file.");
1289     // Remap FileID from 1-based old view.
1290     FID += F.SLocEntryBaseID - 1;
1291 
1292     // Extract the line entries
1293     unsigned NumEntries = Record[Idx++];
1294     assert(NumEntries && "no line entries for file ID");
1295     Entries.clear();
1296     Entries.reserve(NumEntries);
1297     for (unsigned I = 0; I != NumEntries; ++I) {
1298       unsigned FileOffset = Record[Idx++];
1299       unsigned LineNo = Record[Idx++];
1300       int FilenameID = FileIDs[Record[Idx++]];
1301       SrcMgr::CharacteristicKind FileKind
1302         = (SrcMgr::CharacteristicKind)Record[Idx++];
1303       unsigned IncludeOffset = Record[Idx++];
1304       Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1305                                        FileKind, IncludeOffset));
1306     }
1307     LineTable.AddEntry(FileID::get(FID), Entries);
1308   }
1309 
1310   return false;
1311 }
1312 
1313 /// Read a source manager block
1314 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1315   using namespace SrcMgr;
1316 
1317   BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1318 
1319   // Set the source-location entry cursor to the current position in
1320   // the stream. This cursor will be used to read the contents of the
1321   // source manager block initially, and then lazily read
1322   // source-location entries as needed.
1323   SLocEntryCursor = F.Stream;
1324 
1325   // The stream itself is going to skip over the source manager block.
1326   if (llvm::Error Err = F.Stream.SkipBlock()) {
1327     Error(std::move(Err));
1328     return true;
1329   }
1330 
1331   // Enter the source manager block.
1332   if (llvm::Error Err =
1333           SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1334     Error(std::move(Err));
1335     return true;
1336   }
1337 
1338   RecordData Record;
1339   while (true) {
1340     Expected<llvm::BitstreamEntry> MaybeE =
1341         SLocEntryCursor.advanceSkippingSubblocks();
1342     if (!MaybeE) {
1343       Error(MaybeE.takeError());
1344       return true;
1345     }
1346     llvm::BitstreamEntry E = MaybeE.get();
1347 
1348     switch (E.Kind) {
1349     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1350     case llvm::BitstreamEntry::Error:
1351       Error("malformed block record in AST file");
1352       return true;
1353     case llvm::BitstreamEntry::EndBlock:
1354       return false;
1355     case llvm::BitstreamEntry::Record:
1356       // The interesting case.
1357       break;
1358     }
1359 
1360     // Read a record.
1361     Record.clear();
1362     StringRef Blob;
1363     Expected<unsigned> MaybeRecord =
1364         SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1365     if (!MaybeRecord) {
1366       Error(MaybeRecord.takeError());
1367       return true;
1368     }
1369     switch (MaybeRecord.get()) {
1370     default:  // Default behavior: ignore.
1371       break;
1372 
1373     case SM_SLOC_FILE_ENTRY:
1374     case SM_SLOC_BUFFER_ENTRY:
1375     case SM_SLOC_EXPANSION_ENTRY:
1376       // Once we hit one of the source location entries, we're done.
1377       return false;
1378     }
1379   }
1380 }
1381 
1382 /// If a header file is not found at the path that we expect it to be
1383 /// and the PCH file was moved from its original location, try to resolve the
1384 /// file by assuming that header+PCH were moved together and the header is in
1385 /// the same place relative to the PCH.
1386 static std::string
1387 resolveFileRelativeToOriginalDir(const std::string &Filename,
1388                                  const std::string &OriginalDir,
1389                                  const std::string &CurrDir) {
1390   assert(OriginalDir != CurrDir &&
1391          "No point trying to resolve the file if the PCH dir didn't change");
1392 
1393   using namespace llvm::sys;
1394 
1395   SmallString<128> filePath(Filename);
1396   fs::make_absolute(filePath);
1397   assert(path::is_absolute(OriginalDir));
1398   SmallString<128> currPCHPath(CurrDir);
1399 
1400   path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1401                        fileDirE = path::end(path::parent_path(filePath));
1402   path::const_iterator origDirI = path::begin(OriginalDir),
1403                        origDirE = path::end(OriginalDir);
1404   // Skip the common path components from filePath and OriginalDir.
1405   while (fileDirI != fileDirE && origDirI != origDirE &&
1406          *fileDirI == *origDirI) {
1407     ++fileDirI;
1408     ++origDirI;
1409   }
1410   for (; origDirI != origDirE; ++origDirI)
1411     path::append(currPCHPath, "..");
1412   path::append(currPCHPath, fileDirI, fileDirE);
1413   path::append(currPCHPath, path::filename(Filename));
1414   return currPCHPath.str();
1415 }
1416 
1417 bool ASTReader::ReadSLocEntry(int ID) {
1418   if (ID == 0)
1419     return false;
1420 
1421   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1422     Error("source location entry ID out-of-range for AST file");
1423     return true;
1424   }
1425 
1426   // Local helper to read the (possibly-compressed) buffer data following the
1427   // entry record.
1428   auto ReadBuffer = [this](
1429       BitstreamCursor &SLocEntryCursor,
1430       StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1431     RecordData Record;
1432     StringRef Blob;
1433     Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1434     if (!MaybeCode) {
1435       Error(MaybeCode.takeError());
1436       return nullptr;
1437     }
1438     unsigned Code = MaybeCode.get();
1439 
1440     Expected<unsigned> MaybeRecCode =
1441         SLocEntryCursor.readRecord(Code, Record, &Blob);
1442     if (!MaybeRecCode) {
1443       Error(MaybeRecCode.takeError());
1444       return nullptr;
1445     }
1446     unsigned RecCode = MaybeRecCode.get();
1447 
1448     if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1449       if (!llvm::zlib::isAvailable()) {
1450         Error("zlib is not available");
1451         return nullptr;
1452       }
1453       SmallString<0> Uncompressed;
1454       if (llvm::Error E =
1455               llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1456         Error("could not decompress embedded file contents: " +
1457               llvm::toString(std::move(E)));
1458         return nullptr;
1459       }
1460       return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1461     } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1462       return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1463     } else {
1464       Error("AST record has invalid code");
1465       return nullptr;
1466     }
1467   };
1468 
1469   ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1470   if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1471           F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1472     Error(std::move(Err));
1473     return true;
1474   }
1475 
1476   BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1477   unsigned BaseOffset = F->SLocEntryBaseOffset;
1478 
1479   ++NumSLocEntriesRead;
1480   Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1481   if (!MaybeEntry) {
1482     Error(MaybeEntry.takeError());
1483     return true;
1484   }
1485   llvm::BitstreamEntry Entry = MaybeEntry.get();
1486 
1487   if (Entry.Kind != llvm::BitstreamEntry::Record) {
1488     Error("incorrectly-formatted source location entry in AST file");
1489     return true;
1490   }
1491 
1492   RecordData Record;
1493   StringRef Blob;
1494   Expected<unsigned> MaybeSLOC =
1495       SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1496   if (!MaybeSLOC) {
1497     Error(MaybeSLOC.takeError());
1498     return true;
1499   }
1500   switch (MaybeSLOC.get()) {
1501   default:
1502     Error("incorrectly-formatted source location entry in AST file");
1503     return true;
1504 
1505   case SM_SLOC_FILE_ENTRY: {
1506     // We will detect whether a file changed and return 'Failure' for it, but
1507     // we will also try to fail gracefully by setting up the SLocEntry.
1508     unsigned InputID = Record[4];
1509     InputFile IF = getInputFile(*F, InputID);
1510     const FileEntry *File = IF.getFile();
1511     bool OverriddenBuffer = IF.isOverridden();
1512 
1513     // Note that we only check if a File was returned. If it was out-of-date
1514     // we have complained but we will continue creating a FileID to recover
1515     // gracefully.
1516     if (!File)
1517       return true;
1518 
1519     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1520     if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1521       // This is the module's main file.
1522       IncludeLoc = getImportLocation(F);
1523     }
1524     SrcMgr::CharacteristicKind
1525       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1526     // FIXME: The FileID should be created from the FileEntryRef.
1527     FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1528                                         ID, BaseOffset + Record[0]);
1529     SrcMgr::FileInfo &FileInfo =
1530           const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1531     FileInfo.NumCreatedFIDs = Record[5];
1532     if (Record[3])
1533       FileInfo.setHasLineDirectives();
1534 
1535     unsigned NumFileDecls = Record[7];
1536     if (NumFileDecls && ContextObj) {
1537       const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1538       assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1539       FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1540                                                              NumFileDecls));
1541     }
1542 
1543     const SrcMgr::ContentCache *ContentCache
1544       = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
1545     if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1546         ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1547         !ContentCache->getRawBuffer()) {
1548       auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1549       if (!Buffer)
1550         return true;
1551       SourceMgr.overrideFileContents(File, std::move(Buffer));
1552     }
1553 
1554     break;
1555   }
1556 
1557   case SM_SLOC_BUFFER_ENTRY: {
1558     const char *Name = Blob.data();
1559     unsigned Offset = Record[0];
1560     SrcMgr::CharacteristicKind
1561       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1562     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1563     if (IncludeLoc.isInvalid() && F->isModule()) {
1564       IncludeLoc = getImportLocation(F);
1565     }
1566 
1567     auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1568     if (!Buffer)
1569       return true;
1570     SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1571                            BaseOffset + Offset, IncludeLoc);
1572     break;
1573   }
1574 
1575   case SM_SLOC_EXPANSION_ENTRY: {
1576     SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1577     SourceMgr.createExpansionLoc(SpellingLoc,
1578                                      ReadSourceLocation(*F, Record[2]),
1579                                      ReadSourceLocation(*F, Record[3]),
1580                                      Record[5],
1581                                      Record[4],
1582                                      ID,
1583                                      BaseOffset + Record[0]);
1584     break;
1585   }
1586   }
1587 
1588   return false;
1589 }
1590 
1591 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1592   if (ID == 0)
1593     return std::make_pair(SourceLocation(), "");
1594 
1595   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1596     Error("source location entry ID out-of-range for AST file");
1597     return std::make_pair(SourceLocation(), "");
1598   }
1599 
1600   // Find which module file this entry lands in.
1601   ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1602   if (!M->isModule())
1603     return std::make_pair(SourceLocation(), "");
1604 
1605   // FIXME: Can we map this down to a particular submodule? That would be
1606   // ideal.
1607   return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1608 }
1609 
1610 /// Find the location where the module F is imported.
1611 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1612   if (F->ImportLoc.isValid())
1613     return F->ImportLoc;
1614 
1615   // Otherwise we have a PCH. It's considered to be "imported" at the first
1616   // location of its includer.
1617   if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1618     // Main file is the importer.
1619     assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1620     return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1621   }
1622   return F->ImportedBy[0]->FirstLoc;
1623 }
1624 
1625 /// Enter a subblock of the specified BlockID with the specified cursor. Read
1626 /// the abbreviations that are at the top of the block and then leave the cursor
1627 /// pointing into the block.
1628 bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
1629   if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
1630     // FIXME this drops errors on the floor.
1631     consumeError(std::move(Err));
1632     return true;
1633   }
1634 
1635   while (true) {
1636     uint64_t Offset = Cursor.GetCurrentBitNo();
1637     Expected<unsigned> MaybeCode = Cursor.ReadCode();
1638     if (!MaybeCode) {
1639       // FIXME this drops errors on the floor.
1640       consumeError(MaybeCode.takeError());
1641       return true;
1642     }
1643     unsigned Code = MaybeCode.get();
1644 
1645     // We expect all abbrevs to be at the start of the block.
1646     if (Code != llvm::bitc::DEFINE_ABBREV) {
1647       if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1648         // FIXME this drops errors on the floor.
1649         consumeError(std::move(Err));
1650         return true;
1651       }
1652       return false;
1653     }
1654     if (llvm::Error Err = Cursor.ReadAbbrevRecord()) {
1655       // FIXME this drops errors on the floor.
1656       consumeError(std::move(Err));
1657       return true;
1658     }
1659   }
1660 }
1661 
1662 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1663                            unsigned &Idx) {
1664   Token Tok;
1665   Tok.startToken();
1666   Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1667   Tok.setLength(Record[Idx++]);
1668   if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1669     Tok.setIdentifierInfo(II);
1670   Tok.setKind((tok::TokenKind)Record[Idx++]);
1671   Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1672   return Tok;
1673 }
1674 
1675 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1676   BitstreamCursor &Stream = F.MacroCursor;
1677 
1678   // Keep track of where we are in the stream, then jump back there
1679   // after reading this macro.
1680   SavedStreamPosition SavedPosition(Stream);
1681 
1682   if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1683     // FIXME this drops errors on the floor.
1684     consumeError(std::move(Err));
1685     return nullptr;
1686   }
1687   RecordData Record;
1688   SmallVector<IdentifierInfo*, 16> MacroParams;
1689   MacroInfo *Macro = nullptr;
1690 
1691   while (true) {
1692     // Advance to the next record, but if we get to the end of the block, don't
1693     // pop it (removing all the abbreviations from the cursor) since we want to
1694     // be able to reseek within the block and read entries.
1695     unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1696     Expected<llvm::BitstreamEntry> MaybeEntry =
1697         Stream.advanceSkippingSubblocks(Flags);
1698     if (!MaybeEntry) {
1699       Error(MaybeEntry.takeError());
1700       return Macro;
1701     }
1702     llvm::BitstreamEntry Entry = MaybeEntry.get();
1703 
1704     switch (Entry.Kind) {
1705     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1706     case llvm::BitstreamEntry::Error:
1707       Error("malformed block record in AST file");
1708       return Macro;
1709     case llvm::BitstreamEntry::EndBlock:
1710       return Macro;
1711     case llvm::BitstreamEntry::Record:
1712       // The interesting case.
1713       break;
1714     }
1715 
1716     // Read a record.
1717     Record.clear();
1718     PreprocessorRecordTypes RecType;
1719     if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1720       RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1721     else {
1722       Error(MaybeRecType.takeError());
1723       return Macro;
1724     }
1725     switch (RecType) {
1726     case PP_MODULE_MACRO:
1727     case PP_MACRO_DIRECTIVE_HISTORY:
1728       return Macro;
1729 
1730     case PP_MACRO_OBJECT_LIKE:
1731     case PP_MACRO_FUNCTION_LIKE: {
1732       // If we already have a macro, that means that we've hit the end
1733       // of the definition of the macro we were looking for. We're
1734       // done.
1735       if (Macro)
1736         return Macro;
1737 
1738       unsigned NextIndex = 1; // Skip identifier ID.
1739       SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1740       MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1741       MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1742       MI->setIsUsed(Record[NextIndex++]);
1743       MI->setUsedForHeaderGuard(Record[NextIndex++]);
1744 
1745       if (RecType == PP_MACRO_FUNCTION_LIKE) {
1746         // Decode function-like macro info.
1747         bool isC99VarArgs = Record[NextIndex++];
1748         bool isGNUVarArgs = Record[NextIndex++];
1749         bool hasCommaPasting = Record[NextIndex++];
1750         MacroParams.clear();
1751         unsigned NumArgs = Record[NextIndex++];
1752         for (unsigned i = 0; i != NumArgs; ++i)
1753           MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1754 
1755         // Install function-like macro info.
1756         MI->setIsFunctionLike();
1757         if (isC99VarArgs) MI->setIsC99Varargs();
1758         if (isGNUVarArgs) MI->setIsGNUVarargs();
1759         if (hasCommaPasting) MI->setHasCommaPasting();
1760         MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
1761       }
1762 
1763       // Remember that we saw this macro last so that we add the tokens that
1764       // form its body to it.
1765       Macro = MI;
1766 
1767       if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1768           Record[NextIndex]) {
1769         // We have a macro definition. Register the association
1770         PreprocessedEntityID
1771             GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1772         PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1773         PreprocessingRecord::PPEntityID PPID =
1774             PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1775         MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1776             PPRec.getPreprocessedEntity(PPID));
1777         if (PPDef)
1778           PPRec.RegisterMacroDefinition(Macro, PPDef);
1779       }
1780 
1781       ++NumMacrosRead;
1782       break;
1783     }
1784 
1785     case PP_TOKEN: {
1786       // If we see a TOKEN before a PP_MACRO_*, then the file is
1787       // erroneous, just pretend we didn't see this.
1788       if (!Macro) break;
1789 
1790       unsigned Idx = 0;
1791       Token Tok = ReadToken(F, Record, Idx);
1792       Macro->AddTokenToBody(Tok);
1793       break;
1794     }
1795     }
1796   }
1797 }
1798 
1799 PreprocessedEntityID
1800 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1801                                          unsigned LocalID) const {
1802   if (!M.ModuleOffsetMap.empty())
1803     ReadModuleOffsetMap(M);
1804 
1805   ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1806     I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1807   assert(I != M.PreprocessedEntityRemap.end()
1808          && "Invalid index into preprocessed entity index remap");
1809 
1810   return LocalID + I->second;
1811 }
1812 
1813 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1814   return llvm::hash_combine(ikey.Size, ikey.ModTime);
1815 }
1816 
1817 HeaderFileInfoTrait::internal_key_type
1818 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1819   internal_key_type ikey = {FE->getSize(),
1820                             M.HasTimestamps ? FE->getModificationTime() : 0,
1821                             FE->getName(), /*Imported*/ false};
1822   return ikey;
1823 }
1824 
1825 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1826   if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
1827     return false;
1828 
1829   if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
1830     return true;
1831 
1832   // Determine whether the actual files are equivalent.
1833   FileManager &FileMgr = Reader.getFileManager();
1834   auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1835     if (!Key.Imported) {
1836       if (auto File = FileMgr.getFile(Key.Filename))
1837         return *File;
1838       return nullptr;
1839     }
1840 
1841     std::string Resolved = Key.Filename;
1842     Reader.ResolveImportedPath(M, Resolved);
1843     if (auto File = FileMgr.getFile(Resolved))
1844       return *File;
1845     return nullptr;
1846   };
1847 
1848   const FileEntry *FEA = GetFile(a);
1849   const FileEntry *FEB = GetFile(b);
1850   return FEA && FEA == FEB;
1851 }
1852 
1853 std::pair<unsigned, unsigned>
1854 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1855   using namespace llvm::support;
1856 
1857   unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1858   unsigned DataLen = (unsigned) *d++;
1859   return std::make_pair(KeyLen, DataLen);
1860 }
1861 
1862 HeaderFileInfoTrait::internal_key_type
1863 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1864   using namespace llvm::support;
1865 
1866   internal_key_type ikey;
1867   ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1868   ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1869   ikey.Filename = (const char *)d;
1870   ikey.Imported = true;
1871   return ikey;
1872 }
1873 
1874 HeaderFileInfoTrait::data_type
1875 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1876                               unsigned DataLen) {
1877   using namespace llvm::support;
1878 
1879   const unsigned char *End = d + DataLen;
1880   HeaderFileInfo HFI;
1881   unsigned Flags = *d++;
1882   // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1883   HFI.isImport |= (Flags >> 5) & 0x01;
1884   HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1885   HFI.DirInfo = (Flags >> 1) & 0x07;
1886   HFI.IndexHeaderMapHeader = Flags & 0x01;
1887   // FIXME: Find a better way to handle this. Maybe just store a
1888   // "has been included" flag?
1889   HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1890                              HFI.NumIncludes);
1891   HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1892       M, endian::readNext<uint32_t, little, unaligned>(d));
1893   if (unsigned FrameworkOffset =
1894           endian::readNext<uint32_t, little, unaligned>(d)) {
1895     // The framework offset is 1 greater than the actual offset,
1896     // since 0 is used as an indicator for "no framework name".
1897     StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1898     HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1899   }
1900 
1901   assert((End - d) % 4 == 0 &&
1902          "Wrong data length in HeaderFileInfo deserialization");
1903   while (d != End) {
1904     uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1905     auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1906     LocalSMID >>= 2;
1907 
1908     // This header is part of a module. Associate it with the module to enable
1909     // implicit module import.
1910     SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1911     Module *Mod = Reader.getSubmodule(GlobalSMID);
1912     FileManager &FileMgr = Reader.getFileManager();
1913     ModuleMap &ModMap =
1914         Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1915 
1916     std::string Filename = key.Filename;
1917     if (key.Imported)
1918       Reader.ResolveImportedPath(M, Filename);
1919     // FIXME: This is not always the right filename-as-written, but we're not
1920     // going to use this information to rebuild the module, so it doesn't make
1921     // a lot of difference.
1922     Module::Header H = { key.Filename, *FileMgr.getFile(Filename) };
1923     ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1924     HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
1925   }
1926 
1927   // This HeaderFileInfo was externally loaded.
1928   HFI.External = true;
1929   HFI.IsValid = true;
1930   return HFI;
1931 }
1932 
1933 void ASTReader::addPendingMacro(IdentifierInfo *II,
1934                                 ModuleFile *M,
1935                                 uint64_t MacroDirectivesOffset) {
1936   assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1937   PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1938 }
1939 
1940 void ASTReader::ReadDefinedMacros() {
1941   // Note that we are loading defined macros.
1942   Deserializing Macros(this);
1943 
1944   for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1945     BitstreamCursor &MacroCursor = I.MacroCursor;
1946 
1947     // If there was no preprocessor block, skip this file.
1948     if (MacroCursor.getBitcodeBytes().empty())
1949       continue;
1950 
1951     BitstreamCursor Cursor = MacroCursor;
1952     if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
1953       Error(std::move(Err));
1954       return;
1955     }
1956 
1957     RecordData Record;
1958     while (true) {
1959       Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
1960       if (!MaybeE) {
1961         Error(MaybeE.takeError());
1962         return;
1963       }
1964       llvm::BitstreamEntry E = MaybeE.get();
1965 
1966       switch (E.Kind) {
1967       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1968       case llvm::BitstreamEntry::Error:
1969         Error("malformed block record in AST file");
1970         return;
1971       case llvm::BitstreamEntry::EndBlock:
1972         goto NextCursor;
1973 
1974       case llvm::BitstreamEntry::Record: {
1975         Record.clear();
1976         Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
1977         if (!MaybeRecord) {
1978           Error(MaybeRecord.takeError());
1979           return;
1980         }
1981         switch (MaybeRecord.get()) {
1982         default:  // Default behavior: ignore.
1983           break;
1984 
1985         case PP_MACRO_OBJECT_LIKE:
1986         case PP_MACRO_FUNCTION_LIKE: {
1987           IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
1988           if (II->isOutOfDate())
1989             updateOutOfDateIdentifier(*II);
1990           break;
1991         }
1992 
1993         case PP_TOKEN:
1994           // Ignore tokens.
1995           break;
1996         }
1997         break;
1998       }
1999       }
2000     }
2001     NextCursor:  ;
2002   }
2003 }
2004 
2005 namespace {
2006 
2007   /// Visitor class used to look up identifirs in an AST file.
2008   class IdentifierLookupVisitor {
2009     StringRef Name;
2010     unsigned NameHash;
2011     unsigned PriorGeneration;
2012     unsigned &NumIdentifierLookups;
2013     unsigned &NumIdentifierLookupHits;
2014     IdentifierInfo *Found = nullptr;
2015 
2016   public:
2017     IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2018                             unsigned &NumIdentifierLookups,
2019                             unsigned &NumIdentifierLookupHits)
2020       : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2021         PriorGeneration(PriorGeneration),
2022         NumIdentifierLookups(NumIdentifierLookups),
2023         NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2024 
2025     bool operator()(ModuleFile &M) {
2026       // If we've already searched this module file, skip it now.
2027       if (M.Generation <= PriorGeneration)
2028         return true;
2029 
2030       ASTIdentifierLookupTable *IdTable
2031         = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
2032       if (!IdTable)
2033         return false;
2034 
2035       ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2036                                      Found);
2037       ++NumIdentifierLookups;
2038       ASTIdentifierLookupTable::iterator Pos =
2039           IdTable->find_hashed(Name, NameHash, &Trait);
2040       if (Pos == IdTable->end())
2041         return false;
2042 
2043       // Dereferencing the iterator has the effect of building the
2044       // IdentifierInfo node and populating it with the various
2045       // declarations it needs.
2046       ++NumIdentifierLookupHits;
2047       Found = *Pos;
2048       return true;
2049     }
2050 
2051     // Retrieve the identifier info found within the module
2052     // files.
2053     IdentifierInfo *getIdentifierInfo() const { return Found; }
2054   };
2055 
2056 } // namespace
2057 
2058 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
2059   // Note that we are loading an identifier.
2060   Deserializing AnIdentifier(this);
2061 
2062   unsigned PriorGeneration = 0;
2063   if (getContext().getLangOpts().Modules)
2064     PriorGeneration = IdentifierGeneration[&II];
2065 
2066   // If there is a global index, look there first to determine which modules
2067   // provably do not have any results for this identifier.
2068   GlobalModuleIndex::HitSet Hits;
2069   GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2070   if (!loadGlobalIndex()) {
2071     if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2072       HitsPtr = &Hits;
2073     }
2074   }
2075 
2076   IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2077                                   NumIdentifierLookups,
2078                                   NumIdentifierLookupHits);
2079   ModuleMgr.visit(Visitor, HitsPtr);
2080   markIdentifierUpToDate(&II);
2081 }
2082 
2083 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
2084   if (!II)
2085     return;
2086 
2087   II->setOutOfDate(false);
2088 
2089   // Update the generation for this identifier.
2090   if (getContext().getLangOpts().Modules)
2091     IdentifierGeneration[II] = getGeneration();
2092 }
2093 
2094 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
2095                                     const PendingMacroInfo &PMInfo) {
2096   ModuleFile &M = *PMInfo.M;
2097 
2098   BitstreamCursor &Cursor = M.MacroCursor;
2099   SavedStreamPosition SavedPosition(Cursor);
2100   if (llvm::Error Err = Cursor.JumpToBit(PMInfo.MacroDirectivesOffset)) {
2101     Error(std::move(Err));
2102     return;
2103   }
2104 
2105   struct ModuleMacroRecord {
2106     SubmoduleID SubModID;
2107     MacroInfo *MI;
2108     SmallVector<SubmoduleID, 8> Overrides;
2109   };
2110   llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
2111 
2112   // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2113   // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2114   // macro histroy.
2115   RecordData Record;
2116   while (true) {
2117     Expected<llvm::BitstreamEntry> MaybeEntry =
2118         Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2119     if (!MaybeEntry) {
2120       Error(MaybeEntry.takeError());
2121       return;
2122     }
2123     llvm::BitstreamEntry Entry = MaybeEntry.get();
2124 
2125     if (Entry.Kind != llvm::BitstreamEntry::Record) {
2126       Error("malformed block record in AST file");
2127       return;
2128     }
2129 
2130     Record.clear();
2131     Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2132     if (!MaybePP) {
2133       Error(MaybePP.takeError());
2134       return;
2135     }
2136     switch ((PreprocessorRecordTypes)MaybePP.get()) {
2137     case PP_MACRO_DIRECTIVE_HISTORY:
2138       break;
2139 
2140     case PP_MODULE_MACRO: {
2141       ModuleMacros.push_back(ModuleMacroRecord());
2142       auto &Info = ModuleMacros.back();
2143       Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2144       Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
2145       for (int I = 2, N = Record.size(); I != N; ++I)
2146         Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2147       continue;
2148     }
2149 
2150     default:
2151       Error("malformed block record in AST file");
2152       return;
2153     }
2154 
2155     // We found the macro directive history; that's the last record
2156     // for this macro.
2157     break;
2158   }
2159 
2160   // Module macros are listed in reverse dependency order.
2161   {
2162     std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2163     llvm::SmallVector<ModuleMacro*, 8> Overrides;
2164     for (auto &MMR : ModuleMacros) {
2165       Overrides.clear();
2166       for (unsigned ModID : MMR.Overrides) {
2167         Module *Mod = getSubmodule(ModID);
2168         auto *Macro = PP.getModuleMacro(Mod, II);
2169         assert(Macro && "missing definition for overridden macro");
2170         Overrides.push_back(Macro);
2171       }
2172 
2173       bool Inserted = false;
2174       Module *Owner = getSubmodule(MMR.SubModID);
2175       PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2176     }
2177   }
2178 
2179   // Don't read the directive history for a module; we don't have anywhere
2180   // to put it.
2181   if (M.isModule())
2182     return;
2183 
2184   // Deserialize the macro directives history in reverse source-order.
2185   MacroDirective *Latest = nullptr, *Earliest = nullptr;
2186   unsigned Idx = 0, N = Record.size();
2187   while (Idx < N) {
2188     MacroDirective *MD = nullptr;
2189     SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
2190     MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
2191     switch (K) {
2192     case MacroDirective::MD_Define: {
2193       MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2194       MD = PP.AllocateDefMacroDirective(MI, Loc);
2195       break;
2196     }
2197     case MacroDirective::MD_Undefine:
2198       MD = PP.AllocateUndefMacroDirective(Loc);
2199       break;
2200     case MacroDirective::MD_Visibility:
2201       bool isPublic = Record[Idx++];
2202       MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2203       break;
2204     }
2205 
2206     if (!Latest)
2207       Latest = MD;
2208     if (Earliest)
2209       Earliest->setPrevious(MD);
2210     Earliest = MD;
2211   }
2212 
2213   if (Latest)
2214     PP.setLoadedMacroDirective(II, Earliest, Latest);
2215 }
2216 
2217 ASTReader::InputFileInfo
2218 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
2219   // Go find this input file.
2220   BitstreamCursor &Cursor = F.InputFilesCursor;
2221   SavedStreamPosition SavedPosition(Cursor);
2222   if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2223     // FIXME this drops errors on the floor.
2224     consumeError(std::move(Err));
2225   }
2226 
2227   Expected<unsigned> MaybeCode = Cursor.ReadCode();
2228   if (!MaybeCode) {
2229     // FIXME this drops errors on the floor.
2230     consumeError(MaybeCode.takeError());
2231   }
2232   unsigned Code = MaybeCode.get();
2233   RecordData Record;
2234   StringRef Blob;
2235 
2236   if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2237     assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2238            "invalid record type for input file");
2239   else {
2240     // FIXME this drops errors on the floor.
2241     consumeError(Maybe.takeError());
2242   }
2243 
2244   assert(Record[0] == ID && "Bogus stored ID or offset");
2245   InputFileInfo R;
2246   R.StoredSize = static_cast<off_t>(Record[1]);
2247   R.StoredTime = static_cast<time_t>(Record[2]);
2248   R.Overridden = static_cast<bool>(Record[3]);
2249   R.Transient = static_cast<bool>(Record[4]);
2250   R.TopLevelModuleMap = static_cast<bool>(Record[5]);
2251   R.Filename = Blob;
2252   ResolveImportedPath(F, R.Filename);
2253 
2254   Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2255   if (!MaybeEntry) // FIXME this drops errors on the floor.
2256     consumeError(MaybeEntry.takeError());
2257   llvm::BitstreamEntry Entry = MaybeEntry.get();
2258   assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2259          "expected record type for input file hash");
2260 
2261   Record.clear();
2262   if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2263     assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2264            "invalid record type for input file hash");
2265   else {
2266     // FIXME this drops errors on the floor.
2267     consumeError(Maybe.takeError());
2268   }
2269   R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2270                   static_cast<uint64_t>(Record[0]);
2271   return R;
2272 }
2273 
2274 static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2275 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2276   // If this ID is bogus, just return an empty input file.
2277   if (ID == 0 || ID > F.InputFilesLoaded.size())
2278     return InputFile();
2279 
2280   // If we've already loaded this input file, return it.
2281   if (F.InputFilesLoaded[ID-1].getFile())
2282     return F.InputFilesLoaded[ID-1];
2283 
2284   if (F.InputFilesLoaded[ID-1].isNotFound())
2285     return InputFile();
2286 
2287   // Go find this input file.
2288   BitstreamCursor &Cursor = F.InputFilesCursor;
2289   SavedStreamPosition SavedPosition(Cursor);
2290   if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2291     // FIXME this drops errors on the floor.
2292     consumeError(std::move(Err));
2293   }
2294 
2295   InputFileInfo FI = readInputFileInfo(F, ID);
2296   off_t StoredSize = FI.StoredSize;
2297   time_t StoredTime = FI.StoredTime;
2298   bool Overridden = FI.Overridden;
2299   bool Transient = FI.Transient;
2300   StringRef Filename = FI.Filename;
2301   uint64_t StoredContentHash = FI.ContentHash;
2302 
2303   const FileEntry *File = nullptr;
2304   if (auto FE = FileMgr.getFile(Filename, /*OpenFile=*/false))
2305     File = *FE;
2306 
2307   // If we didn't find the file, resolve it relative to the
2308   // original directory from which this AST file was created.
2309   if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2310       F.OriginalDir != F.BaseDirectory) {
2311     std::string Resolved = resolveFileRelativeToOriginalDir(
2312         Filename, F.OriginalDir, F.BaseDirectory);
2313     if (!Resolved.empty())
2314       if (auto FE = FileMgr.getFile(Resolved))
2315         File = *FE;
2316   }
2317 
2318   // For an overridden file, create a virtual file with the stored
2319   // size/timestamp.
2320   if ((Overridden || Transient) && File == nullptr)
2321     File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2322 
2323   if (File == nullptr) {
2324     if (Complain) {
2325       std::string ErrorStr = "could not find file '";
2326       ErrorStr += Filename;
2327       ErrorStr += "' referenced by AST file '";
2328       ErrorStr += F.FileName;
2329       ErrorStr += "'";
2330       Error(ErrorStr);
2331     }
2332     // Record that we didn't find the file.
2333     F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2334     return InputFile();
2335   }
2336 
2337   // Check if there was a request to override the contents of the file
2338   // that was part of the precompiled header. Overriding such a file
2339   // can lead to problems when lexing using the source locations from the
2340   // PCH.
2341   SourceManager &SM = getSourceManager();
2342   // FIXME: Reject if the overrides are different.
2343   if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
2344     if (Complain)
2345       Error(diag::err_fe_pch_file_overridden, Filename);
2346 
2347     // After emitting the diagnostic, bypass the overriding file to recover
2348     // (this creates a separate FileEntry).
2349     File = SM.bypassFileContentsOverride(*File);
2350     if (!File) {
2351       F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
2352       return InputFile();
2353     }
2354   }
2355 
2356   enum ModificationType {
2357     Size,
2358     ModTime,
2359     Content,
2360     None,
2361   };
2362   auto HasInputFileChanged = [&]() {
2363     if (StoredSize != File->getSize())
2364       return ModificationType::Size;
2365     if (!DisableValidation && StoredTime &&
2366         StoredTime != File->getModificationTime()) {
2367       // In case the modification time changes but not the content,
2368       // accept the cached file as legit.
2369       if (ValidateASTInputFilesContent &&
2370           StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) {
2371         auto MemBuffOrError = FileMgr.getBufferForFile(File);
2372         if (!MemBuffOrError) {
2373           if (!Complain)
2374             return ModificationType::ModTime;
2375           std::string ErrorStr = "could not get buffer for file '";
2376           ErrorStr += File->getName();
2377           ErrorStr += "'";
2378           Error(ErrorStr);
2379           return ModificationType::ModTime;
2380         }
2381 
2382         auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2383         if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2384           return ModificationType::None;
2385         return ModificationType::Content;
2386       }
2387       return ModificationType::ModTime;
2388     }
2389     return ModificationType::None;
2390   };
2391 
2392   bool IsOutOfDate = false;
2393   auto FileChange = HasInputFileChanged();
2394   // For an overridden file, there is nothing to validate.
2395   if (!Overridden && FileChange != ModificationType::None) {
2396     if (Complain) {
2397       // Build a list of the PCH imports that got us here (in reverse).
2398       SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2399       while (!ImportStack.back()->ImportedBy.empty())
2400         ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2401 
2402       // The top-level PCH is stale.
2403       StringRef TopLevelPCHName(ImportStack.back()->FileName);
2404       unsigned DiagnosticKind =
2405           moduleKindForDiagnostic(ImportStack.back()->Kind);
2406       if (DiagnosticKind == 0)
2407         Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName,
2408               (unsigned)FileChange);
2409       else if (DiagnosticKind == 1)
2410         Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName,
2411               (unsigned)FileChange);
2412       else
2413         Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName,
2414               (unsigned)FileChange);
2415 
2416       // Print the import stack.
2417       if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2418         Diag(diag::note_pch_required_by)
2419           << Filename << ImportStack[0]->FileName;
2420         for (unsigned I = 1; I < ImportStack.size(); ++I)
2421           Diag(diag::note_pch_required_by)
2422             << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2423       }
2424 
2425       if (!Diags.isDiagnosticInFlight())
2426         Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2427     }
2428 
2429     IsOutOfDate = true;
2430   }
2431   // FIXME: If the file is overridden and we've already opened it,
2432   // issue an error (or split it into a separate FileEntry).
2433 
2434   InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
2435 
2436   // Note that we've loaded this input file.
2437   F.InputFilesLoaded[ID-1] = IF;
2438   return IF;
2439 }
2440 
2441 /// If we are loading a relocatable PCH or module file, and the filename
2442 /// is not an absolute path, add the system or module root to the beginning of
2443 /// the file name.
2444 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2445   // Resolve relative to the base directory, if we have one.
2446   if (!M.BaseDirectory.empty())
2447     return ResolveImportedPath(Filename, M.BaseDirectory);
2448 }
2449 
2450 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2451   if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2452     return;
2453 
2454   SmallString<128> Buffer;
2455   llvm::sys::path::append(Buffer, Prefix, Filename);
2456   Filename.assign(Buffer.begin(), Buffer.end());
2457 }
2458 
2459 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2460   switch (ARR) {
2461   case ASTReader::Failure: return true;
2462   case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2463   case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2464   case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2465   case ASTReader::ConfigurationMismatch:
2466     return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2467   case ASTReader::HadErrors: return true;
2468   case ASTReader::Success: return false;
2469   }
2470 
2471   llvm_unreachable("unknown ASTReadResult");
2472 }
2473 
2474 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2475     BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2476     bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2477     std::string &SuggestedPredefines) {
2478   if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2479     // FIXME this drops errors on the floor.
2480     consumeError(std::move(Err));
2481     return Failure;
2482   }
2483 
2484   // Read all of the records in the options block.
2485   RecordData Record;
2486   ASTReadResult Result = Success;
2487   while (true) {
2488     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2489     if (!MaybeEntry) {
2490       // FIXME this drops errors on the floor.
2491       consumeError(MaybeEntry.takeError());
2492       return Failure;
2493     }
2494     llvm::BitstreamEntry Entry = MaybeEntry.get();
2495 
2496     switch (Entry.Kind) {
2497     case llvm::BitstreamEntry::Error:
2498     case llvm::BitstreamEntry::SubBlock:
2499       return Failure;
2500 
2501     case llvm::BitstreamEntry::EndBlock:
2502       return Result;
2503 
2504     case llvm::BitstreamEntry::Record:
2505       // The interesting case.
2506       break;
2507     }
2508 
2509     // Read and process a record.
2510     Record.clear();
2511     Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2512     if (!MaybeRecordType) {
2513       // FIXME this drops errors on the floor.
2514       consumeError(MaybeRecordType.takeError());
2515       return Failure;
2516     }
2517     switch ((OptionsRecordTypes)MaybeRecordType.get()) {
2518     case LANGUAGE_OPTIONS: {
2519       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2520       if (ParseLanguageOptions(Record, Complain, Listener,
2521                                AllowCompatibleConfigurationMismatch))
2522         Result = ConfigurationMismatch;
2523       break;
2524     }
2525 
2526     case TARGET_OPTIONS: {
2527       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2528       if (ParseTargetOptions(Record, Complain, Listener,
2529                              AllowCompatibleConfigurationMismatch))
2530         Result = ConfigurationMismatch;
2531       break;
2532     }
2533 
2534     case FILE_SYSTEM_OPTIONS: {
2535       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2536       if (!AllowCompatibleConfigurationMismatch &&
2537           ParseFileSystemOptions(Record, Complain, Listener))
2538         Result = ConfigurationMismatch;
2539       break;
2540     }
2541 
2542     case HEADER_SEARCH_OPTIONS: {
2543       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2544       if (!AllowCompatibleConfigurationMismatch &&
2545           ParseHeaderSearchOptions(Record, Complain, Listener))
2546         Result = ConfigurationMismatch;
2547       break;
2548     }
2549 
2550     case PREPROCESSOR_OPTIONS:
2551       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2552       if (!AllowCompatibleConfigurationMismatch &&
2553           ParsePreprocessorOptions(Record, Complain, Listener,
2554                                    SuggestedPredefines))
2555         Result = ConfigurationMismatch;
2556       break;
2557     }
2558   }
2559 }
2560 
2561 ASTReader::ASTReadResult
2562 ASTReader::ReadControlBlock(ModuleFile &F,
2563                             SmallVectorImpl<ImportedModule> &Loaded,
2564                             const ModuleFile *ImportedBy,
2565                             unsigned ClientLoadCapabilities) {
2566   BitstreamCursor &Stream = F.Stream;
2567 
2568   if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2569     Error(std::move(Err));
2570     return Failure;
2571   }
2572 
2573   // Lambda to read the unhashed control block the first time it's called.
2574   //
2575   // For PCM files, the unhashed control block cannot be read until after the
2576   // MODULE_NAME record.  However, PCH files have no MODULE_NAME, and yet still
2577   // need to look ahead before reading the IMPORTS record.  For consistency,
2578   // this block is always read somehow (see BitstreamEntry::EndBlock).
2579   bool HasReadUnhashedControlBlock = false;
2580   auto readUnhashedControlBlockOnce = [&]() {
2581     if (!HasReadUnhashedControlBlock) {
2582       HasReadUnhashedControlBlock = true;
2583       if (ASTReadResult Result =
2584               readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2585         return Result;
2586     }
2587     return Success;
2588   };
2589 
2590   // Read all of the records and blocks in the control block.
2591   RecordData Record;
2592   unsigned NumInputs = 0;
2593   unsigned NumUserInputs = 0;
2594   StringRef BaseDirectoryAsWritten;
2595   while (true) {
2596     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2597     if (!MaybeEntry) {
2598       Error(MaybeEntry.takeError());
2599       return Failure;
2600     }
2601     llvm::BitstreamEntry Entry = MaybeEntry.get();
2602 
2603     switch (Entry.Kind) {
2604     case llvm::BitstreamEntry::Error:
2605       Error("malformed block record in AST file");
2606       return Failure;
2607     case llvm::BitstreamEntry::EndBlock: {
2608       // Validate the module before returning.  This call catches an AST with
2609       // no module name and no imports.
2610       if (ASTReadResult Result = readUnhashedControlBlockOnce())
2611         return Result;
2612 
2613       // Validate input files.
2614       const HeaderSearchOptions &HSOpts =
2615           PP.getHeaderSearchInfo().getHeaderSearchOpts();
2616 
2617       // All user input files reside at the index range [0, NumUserInputs), and
2618       // system input files reside at [NumUserInputs, NumInputs). For explicitly
2619       // loaded module files, ignore missing inputs.
2620       if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2621           F.Kind != MK_PrebuiltModule) {
2622         bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2623 
2624         // If we are reading a module, we will create a verification timestamp,
2625         // so we verify all input files.  Otherwise, verify only user input
2626         // files.
2627 
2628         unsigned N = NumUserInputs;
2629         if (ValidateSystemInputs ||
2630             (HSOpts.ModulesValidateOncePerBuildSession &&
2631              F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
2632              F.Kind == MK_ImplicitModule))
2633           N = NumInputs;
2634 
2635         for (unsigned I = 0; I < N; ++I) {
2636           InputFile IF = getInputFile(F, I+1, Complain);
2637           if (!IF.getFile() || IF.isOutOfDate())
2638             return OutOfDate;
2639         }
2640       }
2641 
2642       if (Listener)
2643         Listener->visitModuleFile(F.FileName, F.Kind);
2644 
2645       if (Listener && Listener->needsInputFileVisitation()) {
2646         unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2647                                                                 : NumUserInputs;
2648         for (unsigned I = 0; I < N; ++I) {
2649           bool IsSystem = I >= NumUserInputs;
2650           InputFileInfo FI = readInputFileInfo(F, I+1);
2651           Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2652                                    F.Kind == MK_ExplicitModule ||
2653                                    F.Kind == MK_PrebuiltModule);
2654         }
2655       }
2656 
2657       return Success;
2658     }
2659 
2660     case llvm::BitstreamEntry::SubBlock:
2661       switch (Entry.ID) {
2662       case INPUT_FILES_BLOCK_ID:
2663         F.InputFilesCursor = Stream;
2664         if (llvm::Error Err = Stream.SkipBlock()) {
2665           Error(std::move(Err));
2666           return Failure;
2667         }
2668         if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2669           Error("malformed block record in AST file");
2670           return Failure;
2671         }
2672         continue;
2673 
2674       case OPTIONS_BLOCK_ID:
2675         // If we're reading the first module for this group, check its options
2676         // are compatible with ours. For modules it imports, no further checking
2677         // is required, because we checked them when we built it.
2678         if (Listener && !ImportedBy) {
2679           // Should we allow the configuration of the module file to differ from
2680           // the configuration of the current translation unit in a compatible
2681           // way?
2682           //
2683           // FIXME: Allow this for files explicitly specified with -include-pch.
2684           bool AllowCompatibleConfigurationMismatch =
2685               F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
2686 
2687           ASTReadResult Result =
2688               ReadOptionsBlock(Stream, ClientLoadCapabilities,
2689                                AllowCompatibleConfigurationMismatch, *Listener,
2690                                SuggestedPredefines);
2691           if (Result == Failure) {
2692             Error("malformed block record in AST file");
2693             return Result;
2694           }
2695 
2696           if (DisableValidation ||
2697               (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2698             Result = Success;
2699 
2700           // If we can't load the module, exit early since we likely
2701           // will rebuild the module anyway. The stream may be in the
2702           // middle of a block.
2703           if (Result != Success)
2704             return Result;
2705         } else if (llvm::Error Err = Stream.SkipBlock()) {
2706           Error(std::move(Err));
2707           return Failure;
2708         }
2709         continue;
2710 
2711       default:
2712         if (llvm::Error Err = Stream.SkipBlock()) {
2713           Error(std::move(Err));
2714           return Failure;
2715         }
2716         continue;
2717       }
2718 
2719     case llvm::BitstreamEntry::Record:
2720       // The interesting case.
2721       break;
2722     }
2723 
2724     // Read and process a record.
2725     Record.clear();
2726     StringRef Blob;
2727     Expected<unsigned> MaybeRecordType =
2728         Stream.readRecord(Entry.ID, Record, &Blob);
2729     if (!MaybeRecordType) {
2730       Error(MaybeRecordType.takeError());
2731       return Failure;
2732     }
2733     switch ((ControlRecordTypes)MaybeRecordType.get()) {
2734     case METADATA: {
2735       if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2736         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2737           Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2738                                         : diag::err_pch_version_too_new);
2739         return VersionMismatch;
2740       }
2741 
2742       bool hasErrors = Record[7];
2743       if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2744         Diag(diag::err_pch_with_compiler_errors);
2745         return HadErrors;
2746       }
2747       if (hasErrors) {
2748         Diags.ErrorOccurred = true;
2749         Diags.UncompilableErrorOccurred = true;
2750         Diags.UnrecoverableErrorOccurred = true;
2751       }
2752 
2753       F.RelocatablePCH = Record[4];
2754       // Relative paths in a relocatable PCH are relative to our sysroot.
2755       if (F.RelocatablePCH)
2756         F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
2757 
2758       F.HasTimestamps = Record[5];
2759 
2760       F.PCHHasObjectFile = Record[6];
2761 
2762       const std::string &CurBranch = getClangFullRepositoryVersion();
2763       StringRef ASTBranch = Blob;
2764       if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2765         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2766           Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2767         return VersionMismatch;
2768       }
2769       break;
2770     }
2771 
2772     case IMPORTS: {
2773       // Validate the AST before processing any imports (otherwise, untangling
2774       // them can be error-prone and expensive).  A module will have a name and
2775       // will already have been validated, but this catches the PCH case.
2776       if (ASTReadResult Result = readUnhashedControlBlockOnce())
2777         return Result;
2778 
2779       // Load each of the imported PCH files.
2780       unsigned Idx = 0, N = Record.size();
2781       while (Idx < N) {
2782         // Read information about the AST file.
2783         ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2784         // The import location will be the local one for now; we will adjust
2785         // all import locations of module imports after the global source
2786         // location info are setup, in ReadAST.
2787         SourceLocation ImportLoc =
2788             ReadUntranslatedSourceLocation(Record[Idx++]);
2789         off_t StoredSize = (off_t)Record[Idx++];
2790         time_t StoredModTime = (time_t)Record[Idx++];
2791         ASTFileSignature StoredSignature = {
2792             {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2793               (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2794               (uint32_t)Record[Idx++]}}};
2795 
2796         std::string ImportedName = ReadString(Record, Idx);
2797         std::string ImportedFile;
2798 
2799         // For prebuilt and explicit modules first consult the file map for
2800         // an override. Note that here we don't search prebuilt module
2801         // directories, only the explicit name to file mappings. Also, we will
2802         // still verify the size/signature making sure it is essentially the
2803         // same file but perhaps in a different location.
2804         if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2805           ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2806             ImportedName, /*FileMapOnly*/ true);
2807 
2808         if (ImportedFile.empty())
2809           // Use BaseDirectoryAsWritten to ensure we use the same path in the
2810           // ModuleCache as when writing.
2811           ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
2812         else
2813           SkipPath(Record, Idx);
2814 
2815         // If our client can't cope with us being out of date, we can't cope with
2816         // our dependency being missing.
2817         unsigned Capabilities = ClientLoadCapabilities;
2818         if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2819           Capabilities &= ~ARR_Missing;
2820 
2821         // Load the AST file.
2822         auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2823                                   Loaded, StoredSize, StoredModTime,
2824                                   StoredSignature, Capabilities);
2825 
2826         // If we diagnosed a problem, produce a backtrace.
2827         if (isDiagnosedResult(Result, Capabilities))
2828           Diag(diag::note_module_file_imported_by)
2829               << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2830 
2831         switch (Result) {
2832         case Failure: return Failure;
2833           // If we have to ignore the dependency, we'll have to ignore this too.
2834         case Missing:
2835         case OutOfDate: return OutOfDate;
2836         case VersionMismatch: return VersionMismatch;
2837         case ConfigurationMismatch: return ConfigurationMismatch;
2838         case HadErrors: return HadErrors;
2839         case Success: break;
2840         }
2841       }
2842       break;
2843     }
2844 
2845     case ORIGINAL_FILE:
2846       F.OriginalSourceFileID = FileID::get(Record[0]);
2847       F.ActualOriginalSourceFileName = Blob;
2848       F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2849       ResolveImportedPath(F, F.OriginalSourceFileName);
2850       break;
2851 
2852     case ORIGINAL_FILE_ID:
2853       F.OriginalSourceFileID = FileID::get(Record[0]);
2854       break;
2855 
2856     case ORIGINAL_PCH_DIR:
2857       F.OriginalDir = Blob;
2858       break;
2859 
2860     case MODULE_NAME:
2861       F.ModuleName = Blob;
2862       Diag(diag::remark_module_import)
2863           << F.ModuleName << F.FileName << (ImportedBy ? true : false)
2864           << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
2865       if (Listener)
2866         Listener->ReadModuleName(F.ModuleName);
2867 
2868       // Validate the AST as soon as we have a name so we can exit early on
2869       // failure.
2870       if (ASTReadResult Result = readUnhashedControlBlockOnce())
2871         return Result;
2872 
2873       break;
2874 
2875     case MODULE_DIRECTORY: {
2876       // Save the BaseDirectory as written in the PCM for computing the module
2877       // filename for the ModuleCache.
2878       BaseDirectoryAsWritten = Blob;
2879       assert(!F.ModuleName.empty() &&
2880              "MODULE_DIRECTORY found before MODULE_NAME");
2881       // If we've already loaded a module map file covering this module, we may
2882       // have a better path for it (relative to the current build).
2883       Module *M = PP.getHeaderSearchInfo().lookupModule(
2884           F.ModuleName, /*AllowSearch*/ true,
2885           /*AllowExtraModuleMapSearch*/ true);
2886       if (M && M->Directory) {
2887         // If we're implicitly loading a module, the base directory can't
2888         // change between the build and use.
2889         // Don't emit module relocation error if we have -fno-validate-pch
2890         if (!PP.getPreprocessorOpts().DisablePCHValidation &&
2891             F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
2892           auto BuildDir = PP.getFileManager().getDirectory(Blob);
2893           if (!BuildDir || *BuildDir != M->Directory) {
2894             if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2895               Diag(diag::err_imported_module_relocated)
2896                   << F.ModuleName << Blob << M->Directory->getName();
2897             return OutOfDate;
2898           }
2899         }
2900         F.BaseDirectory = M->Directory->getName();
2901       } else {
2902         F.BaseDirectory = Blob;
2903       }
2904       break;
2905     }
2906 
2907     case MODULE_MAP_FILE:
2908       if (ASTReadResult Result =
2909               ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2910         return Result;
2911       break;
2912 
2913     case INPUT_FILE_OFFSETS:
2914       NumInputs = Record[0];
2915       NumUserInputs = Record[1];
2916       F.InputFileOffsets =
2917           (const llvm::support::unaligned_uint64_t *)Blob.data();
2918       F.InputFilesLoaded.resize(NumInputs);
2919       F.NumUserInputFiles = NumUserInputs;
2920       break;
2921     }
2922   }
2923 }
2924 
2925 ASTReader::ASTReadResult
2926 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
2927   BitstreamCursor &Stream = F.Stream;
2928 
2929   if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID)) {
2930     Error(std::move(Err));
2931     return Failure;
2932   }
2933 
2934   // Read all of the records and blocks for the AST file.
2935   RecordData Record;
2936   while (true) {
2937     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2938     if (!MaybeEntry) {
2939       Error(MaybeEntry.takeError());
2940       return Failure;
2941     }
2942     llvm::BitstreamEntry Entry = MaybeEntry.get();
2943 
2944     switch (Entry.Kind) {
2945     case llvm::BitstreamEntry::Error:
2946       Error("error at end of module block in AST file");
2947       return Failure;
2948     case llvm::BitstreamEntry::EndBlock:
2949       // Outside of C++, we do not store a lookup map for the translation unit.
2950       // Instead, mark it as needing a lookup map to be built if this module
2951       // contains any declarations lexically within it (which it always does!).
2952       // This usually has no cost, since we very rarely need the lookup map for
2953       // the translation unit outside C++.
2954       if (ASTContext *Ctx = ContextObj) {
2955         DeclContext *DC = Ctx->getTranslationUnitDecl();
2956         if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2957           DC->setMustBuildLookupTable();
2958       }
2959 
2960       return Success;
2961     case llvm::BitstreamEntry::SubBlock:
2962       switch (Entry.ID) {
2963       case DECLTYPES_BLOCK_ID:
2964         // We lazily load the decls block, but we want to set up the
2965         // DeclsCursor cursor to point into it.  Clone our current bitcode
2966         // cursor to it, enter the block and read the abbrevs in that block.
2967         // With the main cursor, we just skip over it.
2968         F.DeclsCursor = Stream;
2969         if (llvm::Error Err = Stream.SkipBlock()) {
2970           Error(std::move(Err));
2971           return Failure;
2972         }
2973         if (ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2974           Error("malformed block record in AST file");
2975           return Failure;
2976         }
2977         break;
2978 
2979       case PREPROCESSOR_BLOCK_ID:
2980         F.MacroCursor = Stream;
2981         if (!PP.getExternalSource())
2982           PP.setExternalSource(this);
2983 
2984         if (llvm::Error Err = Stream.SkipBlock()) {
2985           Error(std::move(Err));
2986           return Failure;
2987         }
2988         if (ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2989           Error("malformed block record in AST file");
2990           return Failure;
2991         }
2992         F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2993         break;
2994 
2995       case PREPROCESSOR_DETAIL_BLOCK_ID:
2996         F.PreprocessorDetailCursor = Stream;
2997 
2998         if (llvm::Error Err = Stream.SkipBlock()) {
2999           Error(std::move(Err));
3000           return Failure;
3001         }
3002         if (ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3003                              PREPROCESSOR_DETAIL_BLOCK_ID)) {
3004           Error("malformed preprocessor detail record in AST file");
3005           return Failure;
3006         }
3007         F.PreprocessorDetailStartOffset
3008         = F.PreprocessorDetailCursor.GetCurrentBitNo();
3009 
3010         if (!PP.getPreprocessingRecord())
3011           PP.createPreprocessingRecord();
3012         if (!PP.getPreprocessingRecord()->getExternalSource())
3013           PP.getPreprocessingRecord()->SetExternalSource(*this);
3014         break;
3015 
3016       case SOURCE_MANAGER_BLOCK_ID:
3017         if (ReadSourceManagerBlock(F))
3018           return Failure;
3019         break;
3020 
3021       case SUBMODULE_BLOCK_ID:
3022         if (ASTReadResult Result =
3023                 ReadSubmoduleBlock(F, ClientLoadCapabilities))
3024           return Result;
3025         break;
3026 
3027       case COMMENTS_BLOCK_ID: {
3028         BitstreamCursor C = Stream;
3029 
3030         if (llvm::Error Err = Stream.SkipBlock()) {
3031           Error(std::move(Err));
3032           return Failure;
3033         }
3034         if (ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
3035           Error("malformed comments block in AST file");
3036           return Failure;
3037         }
3038         CommentsCursors.push_back(std::make_pair(C, &F));
3039         break;
3040       }
3041 
3042       default:
3043         if (llvm::Error Err = Stream.SkipBlock()) {
3044           Error(std::move(Err));
3045           return Failure;
3046         }
3047         break;
3048       }
3049       continue;
3050 
3051     case llvm::BitstreamEntry::Record:
3052       // The interesting case.
3053       break;
3054     }
3055 
3056     // Read and process a record.
3057     Record.clear();
3058     StringRef Blob;
3059     Expected<unsigned> MaybeRecordType =
3060         Stream.readRecord(Entry.ID, Record, &Blob);
3061     if (!MaybeRecordType) {
3062       Error(MaybeRecordType.takeError());
3063       return Failure;
3064     }
3065     ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3066 
3067     // If we're not loading an AST context, we don't care about most records.
3068     if (!ContextObj) {
3069       switch (RecordType) {
3070       case IDENTIFIER_TABLE:
3071       case IDENTIFIER_OFFSET:
3072       case INTERESTING_IDENTIFIERS:
3073       case STATISTICS:
3074       case PP_CONDITIONAL_STACK:
3075       case PP_COUNTER_VALUE:
3076       case SOURCE_LOCATION_OFFSETS:
3077       case MODULE_OFFSET_MAP:
3078       case SOURCE_MANAGER_LINE_TABLE:
3079       case SOURCE_LOCATION_PRELOADS:
3080       case PPD_ENTITIES_OFFSETS:
3081       case HEADER_SEARCH_TABLE:
3082       case IMPORTED_MODULES:
3083       case MACRO_OFFSET:
3084         break;
3085       default:
3086         continue;
3087       }
3088     }
3089 
3090     switch (RecordType) {
3091     default:  // Default behavior: ignore.
3092       break;
3093 
3094     case TYPE_OFFSET: {
3095       if (F.LocalNumTypes != 0) {
3096         Error("duplicate TYPE_OFFSET record in AST file");
3097         return Failure;
3098       }
3099       F.TypeOffsets = (const uint32_t *)Blob.data();
3100       F.LocalNumTypes = Record[0];
3101       unsigned LocalBaseTypeIndex = Record[1];
3102       F.BaseTypeIndex = getTotalNumTypes();
3103 
3104       if (F.LocalNumTypes > 0) {
3105         // Introduce the global -> local mapping for types within this module.
3106         GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
3107 
3108         // Introduce the local -> global mapping for types within this module.
3109         F.TypeRemap.insertOrReplace(
3110           std::make_pair(LocalBaseTypeIndex,
3111                          F.BaseTypeIndex - LocalBaseTypeIndex));
3112 
3113         TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3114       }
3115       break;
3116     }
3117 
3118     case DECL_OFFSET: {
3119       if (F.LocalNumDecls != 0) {
3120         Error("duplicate DECL_OFFSET record in AST file");
3121         return Failure;
3122       }
3123       F.DeclOffsets = (const DeclOffset *)Blob.data();
3124       F.LocalNumDecls = Record[0];
3125       unsigned LocalBaseDeclID = Record[1];
3126       F.BaseDeclID = getTotalNumDecls();
3127 
3128       if (F.LocalNumDecls > 0) {
3129         // Introduce the global -> local mapping for declarations within this
3130         // module.
3131         GlobalDeclMap.insert(
3132           std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
3133 
3134         // Introduce the local -> global mapping for declarations within this
3135         // module.
3136         F.DeclRemap.insertOrReplace(
3137           std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
3138 
3139         // Introduce the global -> local mapping for declarations within this
3140         // module.
3141         F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
3142 
3143         DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3144       }
3145       break;
3146     }
3147 
3148     case TU_UPDATE_LEXICAL: {
3149       DeclContext *TU = ContextObj->getTranslationUnitDecl();
3150       LexicalContents Contents(
3151           reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
3152               Blob.data()),
3153           static_cast<unsigned int>(Blob.size() / 4));
3154       TULexicalDecls.push_back(std::make_pair(&F, Contents));
3155       TU->setHasExternalLexicalStorage(true);
3156       break;
3157     }
3158 
3159     case UPDATE_VISIBLE: {
3160       unsigned Idx = 0;
3161       serialization::DeclID ID = ReadDeclID(F, Record, Idx);
3162       auto *Data = (const unsigned char*)Blob.data();
3163       PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
3164       // If we've already loaded the decl, perform the updates when we finish
3165       // loading this block.
3166       if (Decl *D = GetExistingDecl(ID))
3167         PendingUpdateRecords.push_back(
3168             PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3169       break;
3170     }
3171 
3172     case IDENTIFIER_TABLE:
3173       F.IdentifierTableData = Blob.data();
3174       if (Record[0]) {
3175         F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3176             (const unsigned char *)F.IdentifierTableData + Record[0],
3177             (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
3178             (const unsigned char *)F.IdentifierTableData,
3179             ASTIdentifierLookupTrait(*this, F));
3180 
3181         PP.getIdentifierTable().setExternalIdentifierLookup(this);
3182       }
3183       break;
3184 
3185     case IDENTIFIER_OFFSET: {
3186       if (F.LocalNumIdentifiers != 0) {
3187         Error("duplicate IDENTIFIER_OFFSET record in AST file");
3188         return Failure;
3189       }
3190       F.IdentifierOffsets = (const uint32_t *)Blob.data();
3191       F.LocalNumIdentifiers = Record[0];
3192       unsigned LocalBaseIdentifierID = Record[1];
3193       F.BaseIdentifierID = getTotalNumIdentifiers();
3194 
3195       if (F.LocalNumIdentifiers > 0) {
3196         // Introduce the global -> local mapping for identifiers within this
3197         // module.
3198         GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
3199                                                   &F));
3200 
3201         // Introduce the local -> global mapping for identifiers within this
3202         // module.
3203         F.IdentifierRemap.insertOrReplace(
3204           std::make_pair(LocalBaseIdentifierID,
3205                          F.BaseIdentifierID - LocalBaseIdentifierID));
3206 
3207         IdentifiersLoaded.resize(IdentifiersLoaded.size()
3208                                  + F.LocalNumIdentifiers);
3209       }
3210       break;
3211     }
3212 
3213     case INTERESTING_IDENTIFIERS:
3214       F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3215       break;
3216 
3217     case EAGERLY_DESERIALIZED_DECLS:
3218       // FIXME: Skip reading this record if our ASTConsumer doesn't care
3219       // about "interesting" decls (for instance, if we're building a module).
3220       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3221         EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3222       break;
3223 
3224     case MODULAR_CODEGEN_DECLS:
3225       // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3226       // them (ie: if we're not codegenerating this module).
3227       if (F.Kind == MK_MainFile ||
3228           getContext().getLangOpts().BuildingPCHWithObjectFile)
3229         for (unsigned I = 0, N = Record.size(); I != N; ++I)
3230           EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3231       break;
3232 
3233     case SPECIAL_TYPES:
3234       if (SpecialTypes.empty()) {
3235         for (unsigned I = 0, N = Record.size(); I != N; ++I)
3236           SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3237         break;
3238       }
3239 
3240       if (SpecialTypes.size() != Record.size()) {
3241         Error("invalid special-types record");
3242         return Failure;
3243       }
3244 
3245       for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3246         serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3247         if (!SpecialTypes[I])
3248           SpecialTypes[I] = ID;
3249         // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3250         // merge step?
3251       }
3252       break;
3253 
3254     case STATISTICS:
3255       TotalNumStatements += Record[0];
3256       TotalNumMacros += Record[1];
3257       TotalLexicalDeclContexts += Record[2];
3258       TotalVisibleDeclContexts += Record[3];
3259       break;
3260 
3261     case UNUSED_FILESCOPED_DECLS:
3262       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3263         UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
3264       break;
3265 
3266     case DELEGATING_CTORS:
3267       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3268         DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
3269       break;
3270 
3271     case WEAK_UNDECLARED_IDENTIFIERS:
3272       if (Record.size() % 4 != 0) {
3273         Error("invalid weak identifiers record");
3274         return Failure;
3275       }
3276 
3277       // FIXME: Ignore weak undeclared identifiers from non-original PCH
3278       // files. This isn't the way to do it :)
3279       WeakUndeclaredIdentifiers.clear();
3280 
3281       // Translate the weak, undeclared identifiers into global IDs.
3282       for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3283         WeakUndeclaredIdentifiers.push_back(
3284           getGlobalIdentifierID(F, Record[I++]));
3285         WeakUndeclaredIdentifiers.push_back(
3286           getGlobalIdentifierID(F, Record[I++]));
3287         WeakUndeclaredIdentifiers.push_back(
3288           ReadSourceLocation(F, Record, I).getRawEncoding());
3289         WeakUndeclaredIdentifiers.push_back(Record[I++]);
3290       }
3291       break;
3292 
3293     case SELECTOR_OFFSETS: {
3294       F.SelectorOffsets = (const uint32_t *)Blob.data();
3295       F.LocalNumSelectors = Record[0];
3296       unsigned LocalBaseSelectorID = Record[1];
3297       F.BaseSelectorID = getTotalNumSelectors();
3298 
3299       if (F.LocalNumSelectors > 0) {
3300         // Introduce the global -> local mapping for selectors within this
3301         // module.
3302         GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3303 
3304         // Introduce the local -> global mapping for selectors within this
3305         // module.
3306         F.SelectorRemap.insertOrReplace(
3307           std::make_pair(LocalBaseSelectorID,
3308                          F.BaseSelectorID - LocalBaseSelectorID));
3309 
3310         SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3311       }
3312       break;
3313     }
3314 
3315     case METHOD_POOL:
3316       F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3317       if (Record[0])
3318         F.SelectorLookupTable
3319           = ASTSelectorLookupTable::Create(
3320                         F.SelectorLookupTableData + Record[0],
3321                         F.SelectorLookupTableData,
3322                         ASTSelectorLookupTrait(*this, F));
3323       TotalNumMethodPoolEntries += Record[1];
3324       break;
3325 
3326     case REFERENCED_SELECTOR_POOL:
3327       if (!Record.empty()) {
3328         for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3329           ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3330                                                                 Record[Idx++]));
3331           ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3332                                               getRawEncoding());
3333         }
3334       }
3335       break;
3336 
3337     case PP_CONDITIONAL_STACK:
3338       if (!Record.empty()) {
3339         unsigned Idx = 0, End = Record.size() - 1;
3340         bool ReachedEOFWhileSkipping = Record[Idx++];
3341         llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3342         if (ReachedEOFWhileSkipping) {
3343           SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3344           SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3345           bool FoundNonSkipPortion = Record[Idx++];
3346           bool FoundElse = Record[Idx++];
3347           SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3348           SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3349                            FoundElse, ElseLoc);
3350         }
3351         SmallVector<PPConditionalInfo, 4> ConditionalStack;
3352         while (Idx < End) {
3353           auto Loc = ReadSourceLocation(F, Record, Idx);
3354           bool WasSkipping = Record[Idx++];
3355           bool FoundNonSkip = Record[Idx++];
3356           bool FoundElse = Record[Idx++];
3357           ConditionalStack.push_back(
3358               {Loc, WasSkipping, FoundNonSkip, FoundElse});
3359         }
3360         PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
3361       }
3362       break;
3363 
3364     case PP_COUNTER_VALUE:
3365       if (!Record.empty() && Listener)
3366         Listener->ReadCounter(F, Record[0]);
3367       break;
3368 
3369     case FILE_SORTED_DECLS:
3370       F.FileSortedDecls = (const DeclID *)Blob.data();
3371       F.NumFileSortedDecls = Record[0];
3372       break;
3373 
3374     case SOURCE_LOCATION_OFFSETS: {
3375       F.SLocEntryOffsets = (const uint32_t *)Blob.data();
3376       F.LocalNumSLocEntries = Record[0];
3377       unsigned SLocSpaceSize = Record[1];
3378       std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
3379           SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
3380                                               SLocSpaceSize);
3381       if (!F.SLocEntryBaseID) {
3382         Error("ran out of source locations");
3383         break;
3384       }
3385       // Make our entry in the range map. BaseID is negative and growing, so
3386       // we invert it. Because we invert it, though, we need the other end of
3387       // the range.
3388       unsigned RangeStart =
3389           unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3390       GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3391       F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3392 
3393       // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3394       assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3395       GlobalSLocOffsetMap.insert(
3396           std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3397                            - SLocSpaceSize,&F));
3398 
3399       // Initialize the remapping table.
3400       // Invalid stays invalid.
3401       F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
3402       // This module. Base was 2 when being compiled.
3403       F.SLocRemap.insertOrReplace(std::make_pair(2U,
3404                                   static_cast<int>(F.SLocEntryBaseOffset - 2)));
3405 
3406       TotalNumSLocEntries += F.LocalNumSLocEntries;
3407       break;
3408     }
3409 
3410     case MODULE_OFFSET_MAP:
3411       F.ModuleOffsetMap = Blob;
3412       break;
3413 
3414     case SOURCE_MANAGER_LINE_TABLE:
3415       if (ParseLineTable(F, Record)) {
3416         Error("malformed SOURCE_MANAGER_LINE_TABLE in AST file");
3417         return Failure;
3418       }
3419       break;
3420 
3421     case SOURCE_LOCATION_PRELOADS: {
3422       // Need to transform from the local view (1-based IDs) to the global view,
3423       // which is based off F.SLocEntryBaseID.
3424       if (!F.PreloadSLocEntries.empty()) {
3425         Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
3426         return Failure;
3427       }
3428 
3429       F.PreloadSLocEntries.swap(Record);
3430       break;
3431     }
3432 
3433     case EXT_VECTOR_DECLS:
3434       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3435         ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3436       break;
3437 
3438     case VTABLE_USES:
3439       if (Record.size() % 3 != 0) {
3440         Error("Invalid VTABLE_USES record");
3441         return Failure;
3442       }
3443 
3444       // Later tables overwrite earlier ones.
3445       // FIXME: Modules will have some trouble with this. This is clearly not
3446       // the right way to do this.
3447       VTableUses.clear();
3448 
3449       for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3450         VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3451         VTableUses.push_back(
3452           ReadSourceLocation(F, Record, Idx).getRawEncoding());
3453         VTableUses.push_back(Record[Idx++]);
3454       }
3455       break;
3456 
3457     case PENDING_IMPLICIT_INSTANTIATIONS:
3458       if (PendingInstantiations.size() % 2 != 0) {
3459         Error("Invalid existing PendingInstantiations");
3460         return Failure;
3461       }
3462 
3463       if (Record.size() % 2 != 0) {
3464         Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3465         return Failure;
3466       }
3467 
3468       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3469         PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3470         PendingInstantiations.push_back(
3471           ReadSourceLocation(F, Record, I).getRawEncoding());
3472       }
3473       break;
3474 
3475     case SEMA_DECL_REFS:
3476       if (Record.size() != 3) {
3477         Error("Invalid SEMA_DECL_REFS block");
3478         return Failure;
3479       }
3480       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3481         SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3482       break;
3483 
3484     case PPD_ENTITIES_OFFSETS: {
3485       F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3486       assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3487       F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3488 
3489       unsigned LocalBasePreprocessedEntityID = Record[0];
3490 
3491       unsigned StartingID;
3492       if (!PP.getPreprocessingRecord())
3493         PP.createPreprocessingRecord();
3494       if (!PP.getPreprocessingRecord()->getExternalSource())
3495         PP.getPreprocessingRecord()->SetExternalSource(*this);
3496       StartingID
3497         = PP.getPreprocessingRecord()
3498             ->allocateLoadedEntities(F.NumPreprocessedEntities);
3499       F.BasePreprocessedEntityID = StartingID;
3500 
3501       if (F.NumPreprocessedEntities > 0) {
3502         // Introduce the global -> local mapping for preprocessed entities in
3503         // this module.
3504         GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3505 
3506         // Introduce the local -> global mapping for preprocessed entities in
3507         // this module.
3508         F.PreprocessedEntityRemap.insertOrReplace(
3509           std::make_pair(LocalBasePreprocessedEntityID,
3510             F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3511       }
3512 
3513       break;
3514     }
3515 
3516     case PPD_SKIPPED_RANGES: {
3517       F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3518       assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3519       F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3520 
3521       if (!PP.getPreprocessingRecord())
3522         PP.createPreprocessingRecord();
3523       if (!PP.getPreprocessingRecord()->getExternalSource())
3524         PP.getPreprocessingRecord()->SetExternalSource(*this);
3525       F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3526           ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
3527 
3528       if (F.NumPreprocessedSkippedRanges > 0)
3529         GlobalSkippedRangeMap.insert(
3530             std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3531       break;
3532     }
3533 
3534     case DECL_UPDATE_OFFSETS:
3535       if (Record.size() % 2 != 0) {
3536         Error("invalid DECL_UPDATE_OFFSETS block in AST file");
3537         return Failure;
3538       }
3539       for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3540         GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3541         DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3542 
3543         // If we've already loaded the decl, perform the updates when we finish
3544         // loading this block.
3545         if (Decl *D = GetExistingDecl(ID))
3546           PendingUpdateRecords.push_back(
3547               PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3548       }
3549       break;
3550 
3551     case OBJC_CATEGORIES_MAP:
3552       if (F.LocalNumObjCCategoriesInMap != 0) {
3553         Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
3554         return Failure;
3555       }
3556 
3557       F.LocalNumObjCCategoriesInMap = Record[0];
3558       F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3559       break;
3560 
3561     case OBJC_CATEGORIES:
3562       F.ObjCCategories.swap(Record);
3563       break;
3564 
3565     case CUDA_SPECIAL_DECL_REFS:
3566       // Later tables overwrite earlier ones.
3567       // FIXME: Modules will have trouble with this.
3568       CUDASpecialDeclRefs.clear();
3569       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3570         CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3571       break;
3572 
3573     case HEADER_SEARCH_TABLE:
3574       F.HeaderFileInfoTableData = Blob.data();
3575       F.LocalNumHeaderFileInfos = Record[1];
3576       if (Record[0]) {
3577         F.HeaderFileInfoTable
3578           = HeaderFileInfoLookupTable::Create(
3579                    (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3580                    (const unsigned char *)F.HeaderFileInfoTableData,
3581                    HeaderFileInfoTrait(*this, F,
3582                                        &PP.getHeaderSearchInfo(),
3583                                        Blob.data() + Record[2]));
3584 
3585         PP.getHeaderSearchInfo().SetExternalSource(this);
3586         if (!PP.getHeaderSearchInfo().getExternalLookup())
3587           PP.getHeaderSearchInfo().SetExternalLookup(this);
3588       }
3589       break;
3590 
3591     case FP_PRAGMA_OPTIONS:
3592       // Later tables overwrite earlier ones.
3593       FPPragmaOptions.swap(Record);
3594       break;
3595 
3596     case OPENCL_EXTENSIONS:
3597       for (unsigned I = 0, E = Record.size(); I != E; ) {
3598         auto Name = ReadString(Record, I);
3599         auto &Opt = OpenCLExtensions.OptMap[Name];
3600         Opt.Supported = Record[I++] != 0;
3601         Opt.Enabled = Record[I++] != 0;
3602         Opt.Avail = Record[I++];
3603         Opt.Core = Record[I++];
3604       }
3605       break;
3606 
3607     case OPENCL_EXTENSION_TYPES:
3608       for (unsigned I = 0, E = Record.size(); I != E;) {
3609         auto TypeID = static_cast<::TypeID>(Record[I++]);
3610         auto *Type = GetType(TypeID).getTypePtr();
3611         auto NumExt = static_cast<unsigned>(Record[I++]);
3612         for (unsigned II = 0; II != NumExt; ++II) {
3613           auto Ext = ReadString(Record, I);
3614           OpenCLTypeExtMap[Type].insert(Ext);
3615         }
3616       }
3617       break;
3618 
3619     case OPENCL_EXTENSION_DECLS:
3620       for (unsigned I = 0, E = Record.size(); I != E;) {
3621         auto DeclID = static_cast<::DeclID>(Record[I++]);
3622         auto *Decl = GetDecl(DeclID);
3623         auto NumExt = static_cast<unsigned>(Record[I++]);
3624         for (unsigned II = 0; II != NumExt; ++II) {
3625           auto Ext = ReadString(Record, I);
3626           OpenCLDeclExtMap[Decl].insert(Ext);
3627         }
3628       }
3629       break;
3630 
3631     case TENTATIVE_DEFINITIONS:
3632       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3633         TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3634       break;
3635 
3636     case KNOWN_NAMESPACES:
3637       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3638         KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3639       break;
3640 
3641     case UNDEFINED_BUT_USED:
3642       if (UndefinedButUsed.size() % 2 != 0) {
3643         Error("Invalid existing UndefinedButUsed");
3644         return Failure;
3645       }
3646 
3647       if (Record.size() % 2 != 0) {
3648         Error("invalid undefined-but-used record");
3649         return Failure;
3650       }
3651       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3652         UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3653         UndefinedButUsed.push_back(
3654             ReadSourceLocation(F, Record, I).getRawEncoding());
3655       }
3656       break;
3657 
3658     case DELETE_EXPRS_TO_ANALYZE:
3659       for (unsigned I = 0, N = Record.size(); I != N;) {
3660         DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3661         const uint64_t Count = Record[I++];
3662         DelayedDeleteExprs.push_back(Count);
3663         for (uint64_t C = 0; C < Count; ++C) {
3664           DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3665           bool IsArrayForm = Record[I++] == 1;
3666           DelayedDeleteExprs.push_back(IsArrayForm);
3667         }
3668       }
3669       break;
3670 
3671     case IMPORTED_MODULES:
3672       if (!F.isModule()) {
3673         // If we aren't loading a module (which has its own exports), make
3674         // all of the imported modules visible.
3675         // FIXME: Deal with macros-only imports.
3676         for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3677           unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3678           SourceLocation Loc = ReadSourceLocation(F, Record, I);
3679           if (GlobalID) {
3680             ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3681             if (DeserializationListener)
3682               DeserializationListener->ModuleImportRead(GlobalID, Loc);
3683           }
3684         }
3685       }
3686       break;
3687 
3688     case MACRO_OFFSET: {
3689       if (F.LocalNumMacros != 0) {
3690         Error("duplicate MACRO_OFFSET record in AST file");
3691         return Failure;
3692       }
3693       F.MacroOffsets = (const uint32_t *)Blob.data();
3694       F.LocalNumMacros = Record[0];
3695       unsigned LocalBaseMacroID = Record[1];
3696       F.BaseMacroID = getTotalNumMacros();
3697 
3698       if (F.LocalNumMacros > 0) {
3699         // Introduce the global -> local mapping for macros within this module.
3700         GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3701 
3702         // Introduce the local -> global mapping for macros within this module.
3703         F.MacroRemap.insertOrReplace(
3704           std::make_pair(LocalBaseMacroID,
3705                          F.BaseMacroID - LocalBaseMacroID));
3706 
3707         MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3708       }
3709       break;
3710     }
3711 
3712     case LATE_PARSED_TEMPLATE:
3713       LateParsedTemplates.append(Record.begin(), Record.end());
3714       break;
3715 
3716     case OPTIMIZE_PRAGMA_OPTIONS:
3717       if (Record.size() != 1) {
3718         Error("invalid pragma optimize record");
3719         return Failure;
3720       }
3721       OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3722       break;
3723 
3724     case MSSTRUCT_PRAGMA_OPTIONS:
3725       if (Record.size() != 1) {
3726         Error("invalid pragma ms_struct record");
3727         return Failure;
3728       }
3729       PragmaMSStructState = Record[0];
3730       break;
3731 
3732     case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3733       if (Record.size() != 2) {
3734         Error("invalid pragma ms_struct record");
3735         return Failure;
3736       }
3737       PragmaMSPointersToMembersState = Record[0];
3738       PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3739       break;
3740 
3741     case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3742       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3743         UnusedLocalTypedefNameCandidates.push_back(
3744             getGlobalDeclID(F, Record[I]));
3745       break;
3746 
3747     case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3748       if (Record.size() != 1) {
3749         Error("invalid cuda pragma options record");
3750         return Failure;
3751       }
3752       ForceCUDAHostDeviceDepth = Record[0];
3753       break;
3754 
3755     case PACK_PRAGMA_OPTIONS: {
3756       if (Record.size() < 3) {
3757         Error("invalid pragma pack record");
3758         return Failure;
3759       }
3760       PragmaPackCurrentValue = Record[0];
3761       PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3762       unsigned NumStackEntries = Record[2];
3763       unsigned Idx = 3;
3764       // Reset the stack when importing a new module.
3765       PragmaPackStack.clear();
3766       for (unsigned I = 0; I < NumStackEntries; ++I) {
3767         PragmaPackStackEntry Entry;
3768         Entry.Value = Record[Idx++];
3769         Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3770         Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
3771         PragmaPackStrings.push_back(ReadString(Record, Idx));
3772         Entry.SlotLabel = PragmaPackStrings.back();
3773         PragmaPackStack.push_back(Entry);
3774       }
3775       break;
3776     }
3777     }
3778   }
3779 }
3780 
3781 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3782   assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3783 
3784   // Additional remapping information.
3785   const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3786   const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3787   F.ModuleOffsetMap = StringRef();
3788 
3789   // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3790   if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3791     F.SLocRemap.insert(std::make_pair(0U, 0));
3792     F.SLocRemap.insert(std::make_pair(2U, 1));
3793   }
3794 
3795   // Continuous range maps we may be updating in our module.
3796   using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
3797   RemapBuilder SLocRemap(F.SLocRemap);
3798   RemapBuilder IdentifierRemap(F.IdentifierRemap);
3799   RemapBuilder MacroRemap(F.MacroRemap);
3800   RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3801   RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3802   RemapBuilder SelectorRemap(F.SelectorRemap);
3803   RemapBuilder DeclRemap(F.DeclRemap);
3804   RemapBuilder TypeRemap(F.TypeRemap);
3805 
3806   while (Data < DataEnd) {
3807     // FIXME: Looking up dependency modules by filename is horrible. Let's
3808     // start fixing this with prebuilt and explicit modules and see how it
3809     // goes...
3810     using namespace llvm::support;
3811     ModuleKind Kind = static_cast<ModuleKind>(
3812       endian::readNext<uint8_t, little, unaligned>(Data));
3813     uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3814     StringRef Name = StringRef((const char*)Data, Len);
3815     Data += Len;
3816     ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3817                       ? ModuleMgr.lookupByModuleName(Name)
3818                       : ModuleMgr.lookupByFileName(Name));
3819     if (!OM) {
3820       std::string Msg =
3821           "SourceLocation remap refers to unknown module, cannot find ";
3822       Msg.append(Name);
3823       Error(Msg);
3824       return;
3825     }
3826 
3827     uint32_t SLocOffset =
3828         endian::readNext<uint32_t, little, unaligned>(Data);
3829     uint32_t IdentifierIDOffset =
3830         endian::readNext<uint32_t, little, unaligned>(Data);
3831     uint32_t MacroIDOffset =
3832         endian::readNext<uint32_t, little, unaligned>(Data);
3833     uint32_t PreprocessedEntityIDOffset =
3834         endian::readNext<uint32_t, little, unaligned>(Data);
3835     uint32_t SubmoduleIDOffset =
3836         endian::readNext<uint32_t, little, unaligned>(Data);
3837     uint32_t SelectorIDOffset =
3838         endian::readNext<uint32_t, little, unaligned>(Data);
3839     uint32_t DeclIDOffset =
3840         endian::readNext<uint32_t, little, unaligned>(Data);
3841     uint32_t TypeIndexOffset =
3842         endian::readNext<uint32_t, little, unaligned>(Data);
3843 
3844     uint32_t None = std::numeric_limits<uint32_t>::max();
3845 
3846     auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3847                          RemapBuilder &Remap) {
3848       if (Offset != None)
3849         Remap.insert(std::make_pair(Offset,
3850                                     static_cast<int>(BaseOffset - Offset)));
3851     };
3852     mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3853     mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3854     mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3855     mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3856               PreprocessedEntityRemap);
3857     mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3858     mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3859     mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3860     mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3861 
3862     // Global -> local mappings.
3863     F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3864   }
3865 }
3866 
3867 ASTReader::ASTReadResult
3868 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3869                                   const ModuleFile *ImportedBy,
3870                                   unsigned ClientLoadCapabilities) {
3871   unsigned Idx = 0;
3872   F.ModuleMapPath = ReadPath(F, Record, Idx);
3873 
3874   // Try to resolve ModuleName in the current header search context and
3875   // verify that it is found in the same module map file as we saved. If the
3876   // top-level AST file is a main file, skip this check because there is no
3877   // usable header search context.
3878   assert(!F.ModuleName.empty() &&
3879          "MODULE_NAME should come before MODULE_MAP_FILE");
3880   if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
3881     // An implicitly-loaded module file should have its module listed in some
3882     // module map file that we've already loaded.
3883     Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
3884     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3885     const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3886     // Don't emit module relocation error if we have -fno-validate-pch
3887     if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) {
3888       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3889         if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
3890           // This module was defined by an imported (explicit) module.
3891           Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3892                                                << ASTFE->getName();
3893         } else {
3894           // This module was built with a different module map.
3895           Diag(diag::err_imported_module_not_found)
3896               << F.ModuleName << F.FileName
3897               << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
3898               << !ImportedBy;
3899           // In case it was imported by a PCH, there's a chance the user is
3900           // just missing to include the search path to the directory containing
3901           // the modulemap.
3902           if (ImportedBy && ImportedBy->Kind == MK_PCH)
3903             Diag(diag::note_imported_by_pch_module_not_found)
3904                 << llvm::sys::path::parent_path(F.ModuleMapPath);
3905         }
3906       }
3907       return OutOfDate;
3908     }
3909 
3910     assert(M->Name == F.ModuleName && "found module with different name");
3911 
3912     // Check the primary module map file.
3913     auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3914     if (!StoredModMap || *StoredModMap != ModMap) {
3915       assert(ModMap && "found module is missing module map file");
3916       assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
3917              "top-level import should be verified");
3918       bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
3919       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3920         Diag(diag::err_imported_module_modmap_changed)
3921             << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
3922             << ModMap->getName() << F.ModuleMapPath << NotImported;
3923       return OutOfDate;
3924     }
3925 
3926     llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3927     for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3928       // FIXME: we should use input files rather than storing names.
3929       std::string Filename = ReadPath(F, Record, Idx);
3930       auto F = FileMgr.getFile(Filename, false, false);
3931       if (!F) {
3932         if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3933           Error("could not find file '" + Filename +"' referenced by AST file");
3934         return OutOfDate;
3935       }
3936       AdditionalStoredMaps.insert(*F);
3937     }
3938 
3939     // Check any additional module map files (e.g. module.private.modulemap)
3940     // that are not in the pcm.
3941     if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3942       for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3943         // Remove files that match
3944         // Note: SmallPtrSet::erase is really remove
3945         if (!AdditionalStoredMaps.erase(ModMap)) {
3946           if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3947             Diag(diag::err_module_different_modmap)
3948               << F.ModuleName << /*new*/0 << ModMap->getName();
3949           return OutOfDate;
3950         }
3951       }
3952     }
3953 
3954     // Check any additional module map files that are in the pcm, but not
3955     // found in header search. Cases that match are already removed.
3956     for (const FileEntry *ModMap : AdditionalStoredMaps) {
3957       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3958         Diag(diag::err_module_different_modmap)
3959           << F.ModuleName << /*not new*/1 << ModMap->getName();
3960       return OutOfDate;
3961     }
3962   }
3963 
3964   if (Listener)
3965     Listener->ReadModuleMapFile(F.ModuleMapPath);
3966   return Success;
3967 }
3968 
3969 /// Move the given method to the back of the global list of methods.
3970 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3971   // Find the entry for this selector in the method pool.
3972   Sema::GlobalMethodPool::iterator Known
3973     = S.MethodPool.find(Method->getSelector());
3974   if (Known == S.MethodPool.end())
3975     return;
3976 
3977   // Retrieve the appropriate method list.
3978   ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3979                                                     : Known->second.second;
3980   bool Found = false;
3981   for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
3982     if (!Found) {
3983       if (List->getMethod() == Method) {
3984         Found = true;
3985       } else {
3986         // Keep searching.
3987         continue;
3988       }
3989     }
3990 
3991     if (List->getNext())
3992       List->setMethod(List->getNext()->getMethod());
3993     else
3994       List->setMethod(Method);
3995   }
3996 }
3997 
3998 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
3999   assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4000   for (Decl *D : Names) {
4001     bool wasHidden = D->isHidden();
4002     D->setVisibleDespiteOwningModule();
4003 
4004     if (wasHidden && SemaObj) {
4005       if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4006         moveMethodToBackOfGlobalList(*SemaObj, Method);
4007       }
4008     }
4009   }
4010 }
4011 
4012 void ASTReader::makeModuleVisible(Module *Mod,
4013                                   Module::NameVisibilityKind NameVisibility,
4014                                   SourceLocation ImportLoc) {
4015   llvm::SmallPtrSet<Module *, 4> Visited;
4016   SmallVector<Module *, 4> Stack;
4017   Stack.push_back(Mod);
4018   while (!Stack.empty()) {
4019     Mod = Stack.pop_back_val();
4020 
4021     if (NameVisibility <= Mod->NameVisibility) {
4022       // This module already has this level of visibility (or greater), so
4023       // there is nothing more to do.
4024       continue;
4025     }
4026 
4027     if (!Mod->isAvailable()) {
4028       // Modules that aren't available cannot be made visible.
4029       continue;
4030     }
4031 
4032     // Update the module's name visibility.
4033     Mod->NameVisibility = NameVisibility;
4034 
4035     // If we've already deserialized any names from this module,
4036     // mark them as visible.
4037     HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4038     if (Hidden != HiddenNamesMap.end()) {
4039       auto HiddenNames = std::move(*Hidden);
4040       HiddenNamesMap.erase(Hidden);
4041       makeNamesVisible(HiddenNames.second, HiddenNames.first);
4042       assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
4043              "making names visible added hidden names");
4044     }
4045 
4046     // Push any exported modules onto the stack to be marked as visible.
4047     SmallVector<Module *, 16> Exports;
4048     Mod->getExportedModules(Exports);
4049     for (SmallVectorImpl<Module *>::iterator
4050            I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4051       Module *Exported = *I;
4052       if (Visited.insert(Exported).second)
4053         Stack.push_back(Exported);
4054     }
4055   }
4056 }
4057 
4058 /// We've merged the definition \p MergedDef into the existing definition
4059 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4060 /// visible.
4061 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
4062                                           NamedDecl *MergedDef) {
4063   if (Def->isHidden()) {
4064     // If MergedDef is visible or becomes visible, make the definition visible.
4065     if (!MergedDef->isHidden())
4066       Def->setVisibleDespiteOwningModule();
4067     else {
4068       getContext().mergeDefinitionIntoModule(
4069           Def, MergedDef->getImportedOwningModule(),
4070           /*NotifyListeners*/ false);
4071       PendingMergedDefinitionsToDeduplicate.insert(Def);
4072     }
4073   }
4074 }
4075 
4076 bool ASTReader::loadGlobalIndex() {
4077   if (GlobalIndex)
4078     return false;
4079 
4080   if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4081       !PP.getLangOpts().Modules)
4082     return true;
4083 
4084   // Try to load the global index.
4085   TriedLoadingGlobalIndex = true;
4086   StringRef ModuleCachePath
4087     = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4088   std::pair<GlobalModuleIndex *, llvm::Error> Result =
4089       GlobalModuleIndex::readIndex(ModuleCachePath);
4090   if (llvm::Error Err = std::move(Result.second)) {
4091     assert(!Result.first);
4092     consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4093     return true;
4094   }
4095 
4096   GlobalIndex.reset(Result.first);
4097   ModuleMgr.setGlobalIndex(GlobalIndex.get());
4098   return false;
4099 }
4100 
4101 bool ASTReader::isGlobalIndexUnavailable() const {
4102   return PP.getLangOpts().Modules && UseGlobalIndex &&
4103          !hasGlobalIndex() && TriedLoadingGlobalIndex;
4104 }
4105 
4106 static void updateModuleTimestamp(ModuleFile &MF) {
4107   // Overwrite the timestamp file contents so that file's mtime changes.
4108   std::string TimestampFilename = MF.getTimestampFilename();
4109   std::error_code EC;
4110   llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::OF_Text);
4111   if (EC)
4112     return;
4113   OS << "Timestamp file\n";
4114   OS.close();
4115   OS.clear_error(); // Avoid triggering a fatal error.
4116 }
4117 
4118 /// Given a cursor at the start of an AST file, scan ahead and drop the
4119 /// cursor into the start of the given block ID, returning false on success and
4120 /// true on failure.
4121 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4122   while (true) {
4123     Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4124     if (!MaybeEntry) {
4125       // FIXME this drops errors on the floor.
4126       consumeError(MaybeEntry.takeError());
4127       return true;
4128     }
4129     llvm::BitstreamEntry Entry = MaybeEntry.get();
4130 
4131     switch (Entry.Kind) {
4132     case llvm::BitstreamEntry::Error:
4133     case llvm::BitstreamEntry::EndBlock:
4134       return true;
4135 
4136     case llvm::BitstreamEntry::Record:
4137       // Ignore top-level records.
4138       if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4139         break;
4140       else {
4141         // FIXME this drops errors on the floor.
4142         consumeError(Skipped.takeError());
4143         return true;
4144       }
4145 
4146     case llvm::BitstreamEntry::SubBlock:
4147       if (Entry.ID == BlockID) {
4148         if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4149           // FIXME this drops the error on the floor.
4150           consumeError(std::move(Err));
4151           return true;
4152         }
4153         // Found it!
4154         return false;
4155       }
4156 
4157       if (llvm::Error Err = Cursor.SkipBlock()) {
4158         // FIXME this drops the error on the floor.
4159         consumeError(std::move(Err));
4160         return true;
4161       }
4162     }
4163   }
4164 }
4165 
4166 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
4167                                             ModuleKind Type,
4168                                             SourceLocation ImportLoc,
4169                                             unsigned ClientLoadCapabilities,
4170                                             SmallVectorImpl<ImportedSubmodule> *Imported) {
4171   llvm::SaveAndRestore<SourceLocation>
4172     SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4173 
4174   // Defer any pending actions until we get to the end of reading the AST file.
4175   Deserializing AnASTFile(this);
4176 
4177   // Bump the generation number.
4178   unsigned PreviousGeneration = 0;
4179   if (ContextObj)
4180     PreviousGeneration = incrementGeneration(*ContextObj);
4181 
4182   unsigned NumModules = ModuleMgr.size();
4183   auto removeModulesAndReturn = [&](ASTReadResult ReadResult) {
4184     assert(ReadResult && "expected to return error");
4185     ModuleMgr.removeModules(ModuleMgr.begin() + NumModules,
4186                             PP.getLangOpts().Modules
4187                                 ? &PP.getHeaderSearchInfo().getModuleMap()
4188                                 : nullptr);
4189 
4190     // If we find that any modules are unusable, the global index is going
4191     // to be out-of-date. Just remove it.
4192     GlobalIndex.reset();
4193     ModuleMgr.setGlobalIndex(nullptr);
4194     return ReadResult;
4195   };
4196 
4197   SmallVector<ImportedModule, 4> Loaded;
4198   switch (ASTReadResult ReadResult =
4199               ReadASTCore(FileName, Type, ImportLoc,
4200                           /*ImportedBy=*/nullptr, Loaded, 0, 0,
4201                           ASTFileSignature(), ClientLoadCapabilities)) {
4202   case Failure:
4203   case Missing:
4204   case OutOfDate:
4205   case VersionMismatch:
4206   case ConfigurationMismatch:
4207   case HadErrors:
4208     return removeModulesAndReturn(ReadResult);
4209   case Success:
4210     break;
4211   }
4212 
4213   // Here comes stuff that we only do once the entire chain is loaded.
4214 
4215   // Load the AST blocks of all of the modules that we loaded.  We can still
4216   // hit errors parsing the ASTs at this point.
4217   for (ImportedModule &M : Loaded) {
4218     ModuleFile &F = *M.Mod;
4219 
4220     // Read the AST block.
4221     if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
4222       return removeModulesAndReturn(Result);
4223 
4224     // The AST block should always have a definition for the main module.
4225     if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4226       Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4227       return removeModulesAndReturn(Failure);
4228     }
4229 
4230     // Read the extension blocks.
4231     while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4232       if (ASTReadResult Result = ReadExtensionBlock(F))
4233         return removeModulesAndReturn(Result);
4234     }
4235 
4236     // Once read, set the ModuleFile bit base offset and update the size in
4237     // bits of all files we've seen.
4238     F.GlobalBitOffset = TotalModulesSizeInBits;
4239     TotalModulesSizeInBits += F.SizeInBits;
4240     GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4241   }
4242 
4243   // Preload source locations and interesting indentifiers.
4244   for (ImportedModule &M : Loaded) {
4245     ModuleFile &F = *M.Mod;
4246 
4247     // Preload SLocEntries.
4248     for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
4249       int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
4250       // Load it through the SourceManager and don't call ReadSLocEntry()
4251       // directly because the entry may have already been loaded in which case
4252       // calling ReadSLocEntry() directly would trigger an assertion in
4253       // SourceManager.
4254       SourceMgr.getLoadedSLocEntryByID(Index);
4255     }
4256 
4257     // Map the original source file ID into the ID space of the current
4258     // compilation.
4259     if (F.OriginalSourceFileID.isValid()) {
4260       F.OriginalSourceFileID = FileID::get(
4261           F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
4262     }
4263 
4264     // Preload all the pending interesting identifiers by marking them out of
4265     // date.
4266     for (auto Offset : F.PreloadIdentifierOffsets) {
4267       const unsigned char *Data = reinterpret_cast<const unsigned char *>(
4268           F.IdentifierTableData + Offset);
4269 
4270       ASTIdentifierLookupTrait Trait(*this, F);
4271       auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4272       auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4273       auto &II = PP.getIdentifierTable().getOwn(Key);
4274       II.setOutOfDate(true);
4275 
4276       // Mark this identifier as being from an AST file so that we can track
4277       // whether we need to serialize it.
4278       markIdentifierFromAST(*this, II);
4279 
4280       // Associate the ID with the identifier so that the writer can reuse it.
4281       auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4282       SetIdentifierInfo(ID, &II);
4283     }
4284   }
4285 
4286   // Setup the import locations and notify the module manager that we've
4287   // committed to these module files.
4288   for (ImportedModule &M : Loaded) {
4289     ModuleFile &F = *M.Mod;
4290 
4291     ModuleMgr.moduleFileAccepted(&F);
4292 
4293     // Set the import location.
4294     F.DirectImportLoc = ImportLoc;
4295     // FIXME: We assume that locations from PCH / preamble do not need
4296     // any translation.
4297     if (!M.ImportedBy)
4298       F.ImportLoc = M.ImportLoc;
4299     else
4300       F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4301   }
4302 
4303   if (!PP.getLangOpts().CPlusPlus ||
4304       (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
4305        Type != MK_PrebuiltModule)) {
4306     // Mark all of the identifiers in the identifier table as being out of date,
4307     // so that various accessors know to check the loaded modules when the
4308     // identifier is used.
4309     //
4310     // For C++ modules, we don't need information on many identifiers (just
4311     // those that provide macros or are poisoned), so we mark all of
4312     // the interesting ones via PreloadIdentifierOffsets.
4313     for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4314                                 IdEnd = PP.getIdentifierTable().end();
4315          Id != IdEnd; ++Id)
4316       Id->second->setOutOfDate(true);
4317   }
4318   // Mark selectors as out of date.
4319   for (auto Sel : SelectorGeneration)
4320     SelectorOutOfDate[Sel.first] = true;
4321 
4322   // Resolve any unresolved module exports.
4323   for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4324     UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4325     SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4326     Module *ResolvedMod = getSubmodule(GlobalID);
4327 
4328     switch (Unresolved.Kind) {
4329     case UnresolvedModuleRef::Conflict:
4330       if (ResolvedMod) {
4331         Module::Conflict Conflict;
4332         Conflict.Other = ResolvedMod;
4333         Conflict.Message = Unresolved.String.str();
4334         Unresolved.Mod->Conflicts.push_back(Conflict);
4335       }
4336       continue;
4337 
4338     case UnresolvedModuleRef::Import:
4339       if (ResolvedMod)
4340         Unresolved.Mod->Imports.insert(ResolvedMod);
4341       continue;
4342 
4343     case UnresolvedModuleRef::Export:
4344       if (ResolvedMod || Unresolved.IsWildcard)
4345         Unresolved.Mod->Exports.push_back(
4346           Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4347       continue;
4348     }
4349   }
4350   UnresolvedModuleRefs.clear();
4351 
4352   if (Imported)
4353     Imported->append(ImportedModules.begin(),
4354                      ImportedModules.end());
4355 
4356   // FIXME: How do we load the 'use'd modules? They may not be submodules.
4357   // Might be unnecessary as use declarations are only used to build the
4358   // module itself.
4359 
4360   if (ContextObj)
4361     InitializeContext();
4362 
4363   if (SemaObj)
4364     UpdateSema();
4365 
4366   if (DeserializationListener)
4367     DeserializationListener->ReaderInitialized(this);
4368 
4369   ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
4370   if (PrimaryModule.OriginalSourceFileID.isValid()) {
4371     // If this AST file is a precompiled preamble, then set the
4372     // preamble file ID of the source manager to the file source file
4373     // from which the preamble was built.
4374     if (Type == MK_Preamble) {
4375       SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4376     } else if (Type == MK_MainFile) {
4377       SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4378     }
4379   }
4380 
4381   // For any Objective-C class definitions we have already loaded, make sure
4382   // that we load any additional categories.
4383   if (ContextObj) {
4384     for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4385       loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4386                          ObjCClassesLoaded[I],
4387                          PreviousGeneration);
4388     }
4389   }
4390 
4391   if (PP.getHeaderSearchInfo()
4392           .getHeaderSearchOpts()
4393           .ModulesValidateOncePerBuildSession) {
4394     // Now we are certain that the module and all modules it depends on are
4395     // up to date.  Create or update timestamp files for modules that are
4396     // located in the module cache (not for PCH files that could be anywhere
4397     // in the filesystem).
4398     for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4399       ImportedModule &M = Loaded[I];
4400       if (M.Mod->Kind == MK_ImplicitModule) {
4401         updateModuleTimestamp(*M.Mod);
4402       }
4403     }
4404   }
4405 
4406   return Success;
4407 }
4408 
4409 static ASTFileSignature readASTFileSignature(StringRef PCH);
4410 
4411 /// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4412 static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4413   // FIXME checking magic headers is done in other places such as
4414   // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4415   // always done the same. Unify it all with a helper.
4416   if (!Stream.canSkipToPos(4))
4417     return llvm::createStringError(std::errc::illegal_byte_sequence,
4418                                    "file too small to contain AST file magic");
4419   for (unsigned C : {'C', 'P', 'C', 'H'})
4420     if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4421       if (Res.get() != C)
4422         return llvm::createStringError(
4423             std::errc::illegal_byte_sequence,
4424             "file doesn't start with AST file magic");
4425     } else
4426       return Res.takeError();
4427   return llvm::Error::success();
4428 }
4429 
4430 static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4431   switch (Kind) {
4432   case MK_PCH:
4433     return 0; // PCH
4434   case MK_ImplicitModule:
4435   case MK_ExplicitModule:
4436   case MK_PrebuiltModule:
4437     return 1; // module
4438   case MK_MainFile:
4439   case MK_Preamble:
4440     return 2; // main source file
4441   }
4442   llvm_unreachable("unknown module kind");
4443 }
4444 
4445 ASTReader::ASTReadResult
4446 ASTReader::ReadASTCore(StringRef FileName,
4447                        ModuleKind Type,
4448                        SourceLocation ImportLoc,
4449                        ModuleFile *ImportedBy,
4450                        SmallVectorImpl<ImportedModule> &Loaded,
4451                        off_t ExpectedSize, time_t ExpectedModTime,
4452                        ASTFileSignature ExpectedSignature,
4453                        unsigned ClientLoadCapabilities) {
4454   ModuleFile *M;
4455   std::string ErrorStr;
4456   ModuleManager::AddModuleResult AddResult
4457     = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
4458                           getGeneration(), ExpectedSize, ExpectedModTime,
4459                           ExpectedSignature, readASTFileSignature,
4460                           M, ErrorStr);
4461 
4462   switch (AddResult) {
4463   case ModuleManager::AlreadyLoaded:
4464     Diag(diag::remark_module_import)
4465         << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4466         << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
4467     return Success;
4468 
4469   case ModuleManager::NewlyLoaded:
4470     // Load module file below.
4471     break;
4472 
4473   case ModuleManager::Missing:
4474     // The module file was missing; if the client can handle that, return
4475     // it.
4476     if (ClientLoadCapabilities & ARR_Missing)
4477       return Missing;
4478 
4479     // Otherwise, return an error.
4480     Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
4481                                           << FileName << !ErrorStr.empty()
4482                                           << ErrorStr;
4483     return Failure;
4484 
4485   case ModuleManager::OutOfDate:
4486     // We couldn't load the module file because it is out-of-date. If the
4487     // client can handle out-of-date, return it.
4488     if (ClientLoadCapabilities & ARR_OutOfDate)
4489       return OutOfDate;
4490 
4491     // Otherwise, return an error.
4492     Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
4493                                             << FileName << !ErrorStr.empty()
4494                                             << ErrorStr;
4495     return Failure;
4496   }
4497 
4498   assert(M && "Missing module file");
4499 
4500   bool ShouldFinalizePCM = false;
4501   auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4502     auto &MC = getModuleManager().getModuleCache();
4503     if (ShouldFinalizePCM)
4504       MC.finalizePCM(FileName);
4505     else
4506       MC.tryToDropPCM(FileName);
4507   });
4508   ModuleFile &F = *M;
4509   BitstreamCursor &Stream = F.Stream;
4510   Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4511   F.SizeInBits = F.Buffer->getBufferSize() * 8;
4512 
4513   // Sniff for the signature.
4514   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4515     Diag(diag::err_module_file_invalid)
4516         << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
4517     return Failure;
4518   }
4519 
4520   // This is used for compatibility with older PCH formats.
4521   bool HaveReadControlBlock = false;
4522   while (true) {
4523     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4524     if (!MaybeEntry) {
4525       Error(MaybeEntry.takeError());
4526       return Failure;
4527     }
4528     llvm::BitstreamEntry Entry = MaybeEntry.get();
4529 
4530     switch (Entry.Kind) {
4531     case llvm::BitstreamEntry::Error:
4532     case llvm::BitstreamEntry::Record:
4533     case llvm::BitstreamEntry::EndBlock:
4534       Error("invalid record at top-level of AST file");
4535       return Failure;
4536 
4537     case llvm::BitstreamEntry::SubBlock:
4538       break;
4539     }
4540 
4541     switch (Entry.ID) {
4542     case CONTROL_BLOCK_ID:
4543       HaveReadControlBlock = true;
4544       switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4545       case Success:
4546         // Check that we didn't try to load a non-module AST file as a module.
4547         //
4548         // FIXME: Should we also perform the converse check? Loading a module as
4549         // a PCH file sort of works, but it's a bit wonky.
4550         if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4551              Type == MK_PrebuiltModule) &&
4552             F.ModuleName.empty()) {
4553           auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4554           if (Result != OutOfDate ||
4555               (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4556             Diag(diag::err_module_file_not_module) << FileName;
4557           return Result;
4558         }
4559         break;
4560 
4561       case Failure: return Failure;
4562       case Missing: return Missing;
4563       case OutOfDate: return OutOfDate;
4564       case VersionMismatch: return VersionMismatch;
4565       case ConfigurationMismatch: return ConfigurationMismatch;
4566       case HadErrors: return HadErrors;
4567       }
4568       break;
4569 
4570     case AST_BLOCK_ID:
4571       if (!HaveReadControlBlock) {
4572         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4573           Diag(diag::err_pch_version_too_old);
4574         return VersionMismatch;
4575       }
4576 
4577       // Record that we've loaded this module.
4578       Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4579       ShouldFinalizePCM = true;
4580       return Success;
4581 
4582     case UNHASHED_CONTROL_BLOCK_ID:
4583       // This block is handled using look-ahead during ReadControlBlock.  We
4584       // shouldn't get here!
4585       Error("malformed block record in AST file");
4586       return Failure;
4587 
4588     default:
4589       if (llvm::Error Err = Stream.SkipBlock()) {
4590         Error(std::move(Err));
4591         return Failure;
4592       }
4593       break;
4594     }
4595   }
4596 
4597   llvm_unreachable("unexpected break; expected return");
4598 }
4599 
4600 ASTReader::ASTReadResult
4601 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4602                                     unsigned ClientLoadCapabilities) {
4603   const HeaderSearchOptions &HSOpts =
4604       PP.getHeaderSearchInfo().getHeaderSearchOpts();
4605   bool AllowCompatibleConfigurationMismatch =
4606       F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4607 
4608   ASTReadResult Result = readUnhashedControlBlockImpl(
4609       &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4610       Listener.get(),
4611       WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4612 
4613   // If F was directly imported by another module, it's implicitly validated by
4614   // the importing module.
4615   if (DisableValidation || WasImportedBy ||
4616       (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4617     return Success;
4618 
4619   if (Result == Failure) {
4620     Error("malformed block record in AST file");
4621     return Failure;
4622   }
4623 
4624   if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4625     // If this module has already been finalized in the ModuleCache, we're stuck
4626     // with it; we can only load a single version of each module.
4627     //
4628     // This can happen when a module is imported in two contexts: in one, as a
4629     // user module; in another, as a system module (due to an import from
4630     // another module marked with the [system] flag).  It usually indicates a
4631     // bug in the module map: this module should also be marked with [system].
4632     //
4633     // If -Wno-system-headers (the default), and the first import is as a
4634     // system module, then validation will fail during the as-user import,
4635     // since -Werror flags won't have been validated.  However, it's reasonable
4636     // to treat this consistently as a system module.
4637     //
4638     // If -Wsystem-headers, the PCM on disk was built with
4639     // -Wno-system-headers, and the first import is as a user module, then
4640     // validation will fail during the as-system import since the PCM on disk
4641     // doesn't guarantee that -Werror was respected.  However, the -Werror
4642     // flags were checked during the initial as-user import.
4643     if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
4644       Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4645       return Success;
4646     }
4647   }
4648 
4649   return Result;
4650 }
4651 
4652 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4653     ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4654     bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4655     bool ValidateDiagnosticOptions) {
4656   // Initialize a stream.
4657   BitstreamCursor Stream(StreamData);
4658 
4659   // Sniff for the signature.
4660   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4661     // FIXME this drops the error on the floor.
4662     consumeError(std::move(Err));
4663     return Failure;
4664   }
4665 
4666   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4667   if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4668     return Failure;
4669 
4670   // Read all of the records in the options block.
4671   RecordData Record;
4672   ASTReadResult Result = Success;
4673   while (true) {
4674     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4675     if (!MaybeEntry) {
4676       // FIXME this drops the error on the floor.
4677       consumeError(MaybeEntry.takeError());
4678       return Failure;
4679     }
4680     llvm::BitstreamEntry Entry = MaybeEntry.get();
4681 
4682     switch (Entry.Kind) {
4683     case llvm::BitstreamEntry::Error:
4684     case llvm::BitstreamEntry::SubBlock:
4685       return Failure;
4686 
4687     case llvm::BitstreamEntry::EndBlock:
4688       return Result;
4689 
4690     case llvm::BitstreamEntry::Record:
4691       // The interesting case.
4692       break;
4693     }
4694 
4695     // Read and process a record.
4696     Record.clear();
4697     Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
4698     if (!MaybeRecordType) {
4699       // FIXME this drops the error.
4700       return Failure;
4701     }
4702     switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
4703     case SIGNATURE:
4704       if (F)
4705         std::copy(Record.begin(), Record.end(), F->Signature.data());
4706       break;
4707     case DIAGNOSTIC_OPTIONS: {
4708       bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4709       if (Listener && ValidateDiagnosticOptions &&
4710           !AllowCompatibleConfigurationMismatch &&
4711           ParseDiagnosticOptions(Record, Complain, *Listener))
4712         Result = OutOfDate; // Don't return early.  Read the signature.
4713       break;
4714     }
4715     case DIAG_PRAGMA_MAPPINGS:
4716       if (!F)
4717         break;
4718       if (F->PragmaDiagMappings.empty())
4719         F->PragmaDiagMappings.swap(Record);
4720       else
4721         F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4722                                      Record.begin(), Record.end());
4723       break;
4724     }
4725   }
4726 }
4727 
4728 /// Parse a record and blob containing module file extension metadata.
4729 static bool parseModuleFileExtensionMetadata(
4730               const SmallVectorImpl<uint64_t> &Record,
4731               StringRef Blob,
4732               ModuleFileExtensionMetadata &Metadata) {
4733   if (Record.size() < 4) return true;
4734 
4735   Metadata.MajorVersion = Record[0];
4736   Metadata.MinorVersion = Record[1];
4737 
4738   unsigned BlockNameLen = Record[2];
4739   unsigned UserInfoLen = Record[3];
4740 
4741   if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4742 
4743   Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4744   Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4745                                   Blob.data() + BlockNameLen + UserInfoLen);
4746   return false;
4747 }
4748 
4749 ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4750   BitstreamCursor &Stream = F.Stream;
4751 
4752   RecordData Record;
4753   while (true) {
4754     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4755     if (!MaybeEntry) {
4756       Error(MaybeEntry.takeError());
4757       return Failure;
4758     }
4759     llvm::BitstreamEntry Entry = MaybeEntry.get();
4760 
4761     switch (Entry.Kind) {
4762     case llvm::BitstreamEntry::SubBlock:
4763       if (llvm::Error Err = Stream.SkipBlock()) {
4764         Error(std::move(Err));
4765         return Failure;
4766       }
4767       continue;
4768 
4769     case llvm::BitstreamEntry::EndBlock:
4770       return Success;
4771 
4772     case llvm::BitstreamEntry::Error:
4773       return HadErrors;
4774 
4775     case llvm::BitstreamEntry::Record:
4776       break;
4777     }
4778 
4779     Record.clear();
4780     StringRef Blob;
4781     Expected<unsigned> MaybeRecCode =
4782         Stream.readRecord(Entry.ID, Record, &Blob);
4783     if (!MaybeRecCode) {
4784       Error(MaybeRecCode.takeError());
4785       return Failure;
4786     }
4787     switch (MaybeRecCode.get()) {
4788     case EXTENSION_METADATA: {
4789       ModuleFileExtensionMetadata Metadata;
4790       if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) {
4791         Error("malformed EXTENSION_METADATA in AST file");
4792         return Failure;
4793       }
4794 
4795       // Find a module file extension with this block name.
4796       auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4797       if (Known == ModuleFileExtensions.end()) break;
4798 
4799       // Form a reader.
4800       if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4801                                                              F, Stream)) {
4802         F.ExtensionReaders.push_back(std::move(Reader));
4803       }
4804 
4805       break;
4806     }
4807     }
4808   }
4809 
4810   return Success;
4811 }
4812 
4813 void ASTReader::InitializeContext() {
4814   assert(ContextObj && "no context to initialize");
4815   ASTContext &Context = *ContextObj;
4816 
4817   // If there's a listener, notify them that we "read" the translation unit.
4818   if (DeserializationListener)
4819     DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
4820                                       Context.getTranslationUnitDecl());
4821 
4822   // FIXME: Find a better way to deal with collisions between these
4823   // built-in types. Right now, we just ignore the problem.
4824 
4825   // Load the special types.
4826   if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4827     if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4828       if (!Context.CFConstantStringTypeDecl)
4829         Context.setCFConstantStringType(GetType(String));
4830     }
4831 
4832     if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4833       QualType FileType = GetType(File);
4834       if (FileType.isNull()) {
4835         Error("FILE type is NULL");
4836         return;
4837       }
4838 
4839       if (!Context.FILEDecl) {
4840         if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4841           Context.setFILEDecl(Typedef->getDecl());
4842         else {
4843           const TagType *Tag = FileType->getAs<TagType>();
4844           if (!Tag) {
4845             Error("Invalid FILE type in AST file");
4846             return;
4847           }
4848           Context.setFILEDecl(Tag->getDecl());
4849         }
4850       }
4851     }
4852 
4853     if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4854       QualType Jmp_bufType = GetType(Jmp_buf);
4855       if (Jmp_bufType.isNull()) {
4856         Error("jmp_buf type is NULL");
4857         return;
4858       }
4859 
4860       if (!Context.jmp_bufDecl) {
4861         if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4862           Context.setjmp_bufDecl(Typedef->getDecl());
4863         else {
4864           const TagType *Tag = Jmp_bufType->getAs<TagType>();
4865           if (!Tag) {
4866             Error("Invalid jmp_buf type in AST file");
4867             return;
4868           }
4869           Context.setjmp_bufDecl(Tag->getDecl());
4870         }
4871       }
4872     }
4873 
4874     if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4875       QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4876       if (Sigjmp_bufType.isNull()) {
4877         Error("sigjmp_buf type is NULL");
4878         return;
4879       }
4880 
4881       if (!Context.sigjmp_bufDecl) {
4882         if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4883           Context.setsigjmp_bufDecl(Typedef->getDecl());
4884         else {
4885           const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4886           assert(Tag && "Invalid sigjmp_buf type in AST file");
4887           Context.setsigjmp_bufDecl(Tag->getDecl());
4888         }
4889       }
4890     }
4891 
4892     if (unsigned ObjCIdRedef
4893           = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4894       if (Context.ObjCIdRedefinitionType.isNull())
4895         Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4896     }
4897 
4898     if (unsigned ObjCClassRedef
4899           = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4900       if (Context.ObjCClassRedefinitionType.isNull())
4901         Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4902     }
4903 
4904     if (unsigned ObjCSelRedef
4905           = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4906       if (Context.ObjCSelRedefinitionType.isNull())
4907         Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4908     }
4909 
4910     if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4911       QualType Ucontext_tType = GetType(Ucontext_t);
4912       if (Ucontext_tType.isNull()) {
4913         Error("ucontext_t type is NULL");
4914         return;
4915       }
4916 
4917       if (!Context.ucontext_tDecl) {
4918         if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4919           Context.setucontext_tDecl(Typedef->getDecl());
4920         else {
4921           const TagType *Tag = Ucontext_tType->getAs<TagType>();
4922           assert(Tag && "Invalid ucontext_t type in AST file");
4923           Context.setucontext_tDecl(Tag->getDecl());
4924         }
4925       }
4926     }
4927   }
4928 
4929   ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4930 
4931   // If there were any CUDA special declarations, deserialize them.
4932   if (!CUDASpecialDeclRefs.empty()) {
4933     assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4934     Context.setcudaConfigureCallDecl(
4935                            cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4936   }
4937 
4938   // Re-export any modules that were imported by a non-module AST file.
4939   // FIXME: This does not make macro-only imports visible again.
4940   for (auto &Import : ImportedModules) {
4941     if (Module *Imported = getSubmodule(Import.ID)) {
4942       makeModuleVisible(Imported, Module::AllVisible,
4943                         /*ImportLoc=*/Import.ImportLoc);
4944       if (Import.ImportLoc.isValid())
4945         PP.makeModuleVisible(Imported, Import.ImportLoc);
4946       // FIXME: should we tell Sema to make the module visible too?
4947     }
4948   }
4949   ImportedModules.clear();
4950 }
4951 
4952 void ASTReader::finalizeForWriting() {
4953   // Nothing to do for now.
4954 }
4955 
4956 /// Reads and return the signature record from \p PCH's control block, or
4957 /// else returns 0.
4958 static ASTFileSignature readASTFileSignature(StringRef PCH) {
4959   BitstreamCursor Stream(PCH);
4960   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4961     // FIXME this drops the error on the floor.
4962     consumeError(std::move(Err));
4963     return ASTFileSignature();
4964   }
4965 
4966   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4967   if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4968     return ASTFileSignature();
4969 
4970   // Scan for SIGNATURE inside the diagnostic options block.
4971   ASTReader::RecordData Record;
4972   while (true) {
4973     Expected<llvm::BitstreamEntry> MaybeEntry =
4974         Stream.advanceSkippingSubblocks();
4975     if (!MaybeEntry) {
4976       // FIXME this drops the error on the floor.
4977       consumeError(MaybeEntry.takeError());
4978       return ASTFileSignature();
4979     }
4980     llvm::BitstreamEntry Entry = MaybeEntry.get();
4981 
4982     if (Entry.Kind != llvm::BitstreamEntry::Record)
4983       return ASTFileSignature();
4984 
4985     Record.clear();
4986     StringRef Blob;
4987     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
4988     if (!MaybeRecord) {
4989       // FIXME this drops the error on the floor.
4990       consumeError(MaybeRecord.takeError());
4991       return ASTFileSignature();
4992     }
4993     if (SIGNATURE == MaybeRecord.get())
4994       return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4995                 (uint32_t)Record[3], (uint32_t)Record[4]}}};
4996   }
4997 }
4998 
4999 /// Retrieve the name of the original source file name
5000 /// directly from the AST file, without actually loading the AST
5001 /// file.
5002 std::string ASTReader::getOriginalSourceFile(
5003     const std::string &ASTFileName, FileManager &FileMgr,
5004     const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5005   // Open the AST file.
5006   auto Buffer = FileMgr.getBufferForFile(ASTFileName);
5007   if (!Buffer) {
5008     Diags.Report(diag::err_fe_unable_to_read_pch_file)
5009         << ASTFileName << Buffer.getError().message();
5010     return std::string();
5011   }
5012 
5013   // Initialize the stream
5014   BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5015 
5016   // Sniff for the signature.
5017   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5018     Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5019     return std::string();
5020   }
5021 
5022   // Scan for the CONTROL_BLOCK_ID block.
5023   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5024     Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5025     return std::string();
5026   }
5027 
5028   // Scan for ORIGINAL_FILE inside the control block.
5029   RecordData Record;
5030   while (true) {
5031     Expected<llvm::BitstreamEntry> MaybeEntry =
5032         Stream.advanceSkippingSubblocks();
5033     if (!MaybeEntry) {
5034       // FIXME this drops errors on the floor.
5035       consumeError(MaybeEntry.takeError());
5036       return std::string();
5037     }
5038     llvm::BitstreamEntry Entry = MaybeEntry.get();
5039 
5040     if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5041       return std::string();
5042 
5043     if (Entry.Kind != llvm::BitstreamEntry::Record) {
5044       Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5045       return std::string();
5046     }
5047 
5048     Record.clear();
5049     StringRef Blob;
5050     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5051     if (!MaybeRecord) {
5052       // FIXME this drops the errors on the floor.
5053       consumeError(MaybeRecord.takeError());
5054       return std::string();
5055     }
5056     if (ORIGINAL_FILE == MaybeRecord.get())
5057       return Blob.str();
5058   }
5059 }
5060 
5061 namespace {
5062 
5063   class SimplePCHValidator : public ASTReaderListener {
5064     const LangOptions &ExistingLangOpts;
5065     const TargetOptions &ExistingTargetOpts;
5066     const PreprocessorOptions &ExistingPPOpts;
5067     std::string ExistingModuleCachePath;
5068     FileManager &FileMgr;
5069 
5070   public:
5071     SimplePCHValidator(const LangOptions &ExistingLangOpts,
5072                        const TargetOptions &ExistingTargetOpts,
5073                        const PreprocessorOptions &ExistingPPOpts,
5074                        StringRef ExistingModuleCachePath,
5075                        FileManager &FileMgr)
5076       : ExistingLangOpts(ExistingLangOpts),
5077         ExistingTargetOpts(ExistingTargetOpts),
5078         ExistingPPOpts(ExistingPPOpts),
5079         ExistingModuleCachePath(ExistingModuleCachePath),
5080         FileMgr(FileMgr) {}
5081 
5082     bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5083                              bool AllowCompatibleDifferences) override {
5084       return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5085                                   AllowCompatibleDifferences);
5086     }
5087 
5088     bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5089                            bool AllowCompatibleDifferences) override {
5090       return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5091                                 AllowCompatibleDifferences);
5092     }
5093 
5094     bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5095                                  StringRef SpecificModuleCachePath,
5096                                  bool Complain) override {
5097       return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5098                                       ExistingModuleCachePath,
5099                                       nullptr, ExistingLangOpts);
5100     }
5101 
5102     bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5103                                  bool Complain,
5104                                  std::string &SuggestedPredefines) override {
5105       return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
5106                                       SuggestedPredefines, ExistingLangOpts);
5107     }
5108   };
5109 
5110 } // namespace
5111 
5112 bool ASTReader::readASTFileControlBlock(
5113     StringRef Filename, FileManager &FileMgr,
5114     const PCHContainerReader &PCHContainerRdr,
5115     bool FindModuleFileExtensions,
5116     ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
5117   // Open the AST file.
5118   // FIXME: This allows use of the VFS; we do not allow use of the
5119   // VFS when actually loading a module.
5120   auto Buffer = FileMgr.getBufferForFile(Filename);
5121   if (!Buffer) {
5122     return true;
5123   }
5124 
5125   // Initialize the stream
5126   StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
5127   BitstreamCursor Stream(Bytes);
5128 
5129   // Sniff for the signature.
5130   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5131     consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5132     return true;
5133   }
5134 
5135   // Scan for the CONTROL_BLOCK_ID block.
5136   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
5137     return true;
5138 
5139   bool NeedsInputFiles = Listener.needsInputFileVisitation();
5140   bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5141   bool NeedsImports = Listener.needsImportVisitation();
5142   BitstreamCursor InputFilesCursor;
5143 
5144   RecordData Record;
5145   std::string ModuleDir;
5146   bool DoneWithControlBlock = false;
5147   while (!DoneWithControlBlock) {
5148     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5149     if (!MaybeEntry) {
5150       // FIXME this drops the error on the floor.
5151       consumeError(MaybeEntry.takeError());
5152       return true;
5153     }
5154     llvm::BitstreamEntry Entry = MaybeEntry.get();
5155 
5156     switch (Entry.Kind) {
5157     case llvm::BitstreamEntry::SubBlock: {
5158       switch (Entry.ID) {
5159       case OPTIONS_BLOCK_ID: {
5160         std::string IgnoredSuggestedPredefines;
5161         if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
5162                              /*AllowCompatibleConfigurationMismatch*/ false,
5163                              Listener, IgnoredSuggestedPredefines) != Success)
5164           return true;
5165         break;
5166       }
5167 
5168       case INPUT_FILES_BLOCK_ID:
5169         InputFilesCursor = Stream;
5170         if (llvm::Error Err = Stream.SkipBlock()) {
5171           // FIXME this drops the error on the floor.
5172           consumeError(std::move(Err));
5173           return true;
5174         }
5175         if (NeedsInputFiles &&
5176             ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5177           return true;
5178         break;
5179 
5180       default:
5181         if (llvm::Error Err = Stream.SkipBlock()) {
5182           // FIXME this drops the error on the floor.
5183           consumeError(std::move(Err));
5184           return true;
5185         }
5186         break;
5187       }
5188 
5189       continue;
5190     }
5191 
5192     case llvm::BitstreamEntry::EndBlock:
5193       DoneWithControlBlock = true;
5194       break;
5195 
5196     case llvm::BitstreamEntry::Error:
5197       return true;
5198 
5199     case llvm::BitstreamEntry::Record:
5200       break;
5201     }
5202 
5203     if (DoneWithControlBlock) break;
5204 
5205     Record.clear();
5206     StringRef Blob;
5207     Expected<unsigned> MaybeRecCode =
5208         Stream.readRecord(Entry.ID, Record, &Blob);
5209     if (!MaybeRecCode) {
5210       // FIXME this drops the error.
5211       return Failure;
5212     }
5213     switch ((ControlRecordTypes)MaybeRecCode.get()) {
5214     case METADATA:
5215       if (Record[0] != VERSION_MAJOR)
5216         return true;
5217       if (Listener.ReadFullVersionInformation(Blob))
5218         return true;
5219       break;
5220     case MODULE_NAME:
5221       Listener.ReadModuleName(Blob);
5222       break;
5223     case MODULE_DIRECTORY:
5224       ModuleDir = Blob;
5225       break;
5226     case MODULE_MAP_FILE: {
5227       unsigned Idx = 0;
5228       auto Path = ReadString(Record, Idx);
5229       ResolveImportedPath(Path, ModuleDir);
5230       Listener.ReadModuleMapFile(Path);
5231       break;
5232     }
5233     case INPUT_FILE_OFFSETS: {
5234       if (!NeedsInputFiles)
5235         break;
5236 
5237       unsigned NumInputFiles = Record[0];
5238       unsigned NumUserFiles = Record[1];
5239       const llvm::support::unaligned_uint64_t *InputFileOffs =
5240           (const llvm::support::unaligned_uint64_t *)Blob.data();
5241       for (unsigned I = 0; I != NumInputFiles; ++I) {
5242         // Go find this input file.
5243         bool isSystemFile = I >= NumUserFiles;
5244 
5245         if (isSystemFile && !NeedsSystemInputFiles)
5246           break; // the rest are system input files
5247 
5248         BitstreamCursor &Cursor = InputFilesCursor;
5249         SavedStreamPosition SavedPosition(Cursor);
5250         if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
5251           // FIXME this drops errors on the floor.
5252           consumeError(std::move(Err));
5253         }
5254 
5255         Expected<unsigned> MaybeCode = Cursor.ReadCode();
5256         if (!MaybeCode) {
5257           // FIXME this drops errors on the floor.
5258           consumeError(MaybeCode.takeError());
5259         }
5260         unsigned Code = MaybeCode.get();
5261 
5262         RecordData Record;
5263         StringRef Blob;
5264         bool shouldContinue = false;
5265         Expected<unsigned> MaybeRecordType =
5266             Cursor.readRecord(Code, Record, &Blob);
5267         if (!MaybeRecordType) {
5268           // FIXME this drops errors on the floor.
5269           consumeError(MaybeRecordType.takeError());
5270         }
5271         switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5272         case INPUT_FILE_HASH:
5273           break;
5274         case INPUT_FILE:
5275           bool Overridden = static_cast<bool>(Record[3]);
5276           std::string Filename = Blob;
5277           ResolveImportedPath(Filename, ModuleDir);
5278           shouldContinue = Listener.visitInputFile(
5279               Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
5280           break;
5281         }
5282         if (!shouldContinue)
5283           break;
5284       }
5285       break;
5286     }
5287 
5288     case IMPORTS: {
5289       if (!NeedsImports)
5290         break;
5291 
5292       unsigned Idx = 0, N = Record.size();
5293       while (Idx < N) {
5294         // Read information about the AST file.
5295         Idx += 1+1+1+1+5; // Kind, ImportLoc, Size, ModTime, Signature
5296         std::string ModuleName = ReadString(Record, Idx);
5297         std::string Filename = ReadString(Record, Idx);
5298         ResolveImportedPath(Filename, ModuleDir);
5299         Listener.visitImport(ModuleName, Filename);
5300       }
5301       break;
5302     }
5303 
5304     default:
5305       // No other validation to perform.
5306       break;
5307     }
5308   }
5309 
5310   // Look for module file extension blocks, if requested.
5311   if (FindModuleFileExtensions) {
5312     BitstreamCursor SavedStream = Stream;
5313     while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5314       bool DoneWithExtensionBlock = false;
5315       while (!DoneWithExtensionBlock) {
5316         Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5317         if (!MaybeEntry) {
5318           // FIXME this drops the error.
5319           return true;
5320         }
5321         llvm::BitstreamEntry Entry = MaybeEntry.get();
5322 
5323         switch (Entry.Kind) {
5324         case llvm::BitstreamEntry::SubBlock:
5325           if (llvm::Error Err = Stream.SkipBlock()) {
5326             // FIXME this drops the error on the floor.
5327             consumeError(std::move(Err));
5328             return true;
5329           }
5330           continue;
5331 
5332         case llvm::BitstreamEntry::EndBlock:
5333           DoneWithExtensionBlock = true;
5334           continue;
5335 
5336         case llvm::BitstreamEntry::Error:
5337           return true;
5338 
5339         case llvm::BitstreamEntry::Record:
5340           break;
5341         }
5342 
5343        Record.clear();
5344        StringRef Blob;
5345        Expected<unsigned> MaybeRecCode =
5346            Stream.readRecord(Entry.ID, Record, &Blob);
5347        if (!MaybeRecCode) {
5348          // FIXME this drops the error.
5349          return true;
5350        }
5351        switch (MaybeRecCode.get()) {
5352        case EXTENSION_METADATA: {
5353          ModuleFileExtensionMetadata Metadata;
5354          if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5355            return true;
5356 
5357          Listener.readModuleFileExtension(Metadata);
5358          break;
5359        }
5360        }
5361       }
5362     }
5363     Stream = SavedStream;
5364   }
5365 
5366   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5367   if (readUnhashedControlBlockImpl(
5368           nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
5369           /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5370           ValidateDiagnosticOptions) != Success)
5371     return true;
5372 
5373   return false;
5374 }
5375 
5376 bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5377                                     const PCHContainerReader &PCHContainerRdr,
5378                                     const LangOptions &LangOpts,
5379                                     const TargetOptions &TargetOpts,
5380                                     const PreprocessorOptions &PPOpts,
5381                                     StringRef ExistingModuleCachePath) {
5382   SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5383                                ExistingModuleCachePath, FileMgr);
5384   return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
5385                                   /*FindModuleFileExtensions=*/false,
5386                                   validator,
5387                                   /*ValidateDiagnosticOptions=*/true);
5388 }
5389 
5390 ASTReader::ASTReadResult
5391 ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
5392   // Enter the submodule block.
5393   if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
5394     Error(std::move(Err));
5395     return Failure;
5396   }
5397 
5398   ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5399   bool First = true;
5400   Module *CurrentModule = nullptr;
5401   RecordData Record;
5402   while (true) {
5403     Expected<llvm::BitstreamEntry> MaybeEntry =
5404         F.Stream.advanceSkippingSubblocks();
5405     if (!MaybeEntry) {
5406       Error(MaybeEntry.takeError());
5407       return Failure;
5408     }
5409     llvm::BitstreamEntry Entry = MaybeEntry.get();
5410 
5411     switch (Entry.Kind) {
5412     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5413     case llvm::BitstreamEntry::Error:
5414       Error("malformed block record in AST file");
5415       return Failure;
5416     case llvm::BitstreamEntry::EndBlock:
5417       return Success;
5418     case llvm::BitstreamEntry::Record:
5419       // The interesting case.
5420       break;
5421     }
5422 
5423     // Read a record.
5424     StringRef Blob;
5425     Record.clear();
5426     Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5427     if (!MaybeKind) {
5428       Error(MaybeKind.takeError());
5429       return Failure;
5430     }
5431     unsigned Kind = MaybeKind.get();
5432 
5433     if ((Kind == SUBMODULE_METADATA) != First) {
5434       Error("submodule metadata record should be at beginning of block");
5435       return Failure;
5436     }
5437     First = false;
5438 
5439     // Submodule information is only valid if we have a current module.
5440     // FIXME: Should we error on these cases?
5441     if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5442         Kind != SUBMODULE_DEFINITION)
5443       continue;
5444 
5445     switch (Kind) {
5446     default:  // Default behavior: ignore.
5447       break;
5448 
5449     case SUBMODULE_DEFINITION: {
5450       if (Record.size() < 12) {
5451         Error("malformed module definition");
5452         return Failure;
5453       }
5454 
5455       StringRef Name = Blob;
5456       unsigned Idx = 0;
5457       SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5458       SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
5459       Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
5460       bool IsFramework = Record[Idx++];
5461       bool IsExplicit = Record[Idx++];
5462       bool IsSystem = Record[Idx++];
5463       bool IsExternC = Record[Idx++];
5464       bool InferSubmodules = Record[Idx++];
5465       bool InferExplicitSubmodules = Record[Idx++];
5466       bool InferExportWildcard = Record[Idx++];
5467       bool ConfigMacrosExhaustive = Record[Idx++];
5468       bool ModuleMapIsPrivate = Record[Idx++];
5469 
5470       Module *ParentModule = nullptr;
5471       if (Parent)
5472         ParentModule = getSubmodule(Parent);
5473 
5474       // Retrieve this (sub)module from the module map, creating it if
5475       // necessary.
5476       CurrentModule =
5477           ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5478               .first;
5479 
5480       // FIXME: set the definition loc for CurrentModule, or call
5481       // ModMap.setInferredModuleAllowedBy()
5482 
5483       SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5484       if (GlobalIndex >= SubmodulesLoaded.size() ||
5485           SubmodulesLoaded[GlobalIndex]) {
5486         Error("too many submodules");
5487         return Failure;
5488       }
5489 
5490       if (!ParentModule) {
5491         if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
5492           // Don't emit module relocation error if we have -fno-validate-pch
5493           if (!PP.getPreprocessorOpts().DisablePCHValidation &&
5494               CurFile != F.File) {
5495             Error(diag::err_module_file_conflict,
5496                   CurrentModule->getTopLevelModuleName(), CurFile->getName(),
5497                   F.File->getName());
5498             return Failure;
5499           }
5500         }
5501 
5502         F.DidReadTopLevelSubmodule = true;
5503         CurrentModule->setASTFile(F.File);
5504         CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
5505       }
5506 
5507       CurrentModule->Kind = Kind;
5508       CurrentModule->Signature = F.Signature;
5509       CurrentModule->IsFromModuleFile = true;
5510       CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
5511       CurrentModule->IsExternC = IsExternC;
5512       CurrentModule->InferSubmodules = InferSubmodules;
5513       CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5514       CurrentModule->InferExportWildcard = InferExportWildcard;
5515       CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
5516       CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
5517       if (DeserializationListener)
5518         DeserializationListener->ModuleRead(GlobalID, CurrentModule);
5519 
5520       SubmodulesLoaded[GlobalIndex] = CurrentModule;
5521 
5522       // Clear out data that will be replaced by what is in the module file.
5523       CurrentModule->LinkLibraries.clear();
5524       CurrentModule->ConfigMacros.clear();
5525       CurrentModule->UnresolvedConflicts.clear();
5526       CurrentModule->Conflicts.clear();
5527 
5528       // The module is available unless it's missing a requirement; relevant
5529       // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5530       // Missing headers that were present when the module was built do not
5531       // make it unavailable -- if we got this far, this must be an explicitly
5532       // imported module file.
5533       CurrentModule->Requirements.clear();
5534       CurrentModule->MissingHeaders.clear();
5535       CurrentModule->IsMissingRequirement =
5536           ParentModule && ParentModule->IsMissingRequirement;
5537       CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
5538       break;
5539     }
5540 
5541     case SUBMODULE_UMBRELLA_HEADER: {
5542       std::string Filename = Blob;
5543       ResolveImportedPath(F, Filename);
5544       if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
5545         if (!CurrentModule->getUmbrellaHeader())
5546           ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob);
5547         else if (CurrentModule->getUmbrellaHeader().Entry != *Umbrella) {
5548           if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5549             Error("mismatched umbrella headers in submodule");
5550           return OutOfDate;
5551         }
5552       }
5553       break;
5554     }
5555 
5556     case SUBMODULE_HEADER:
5557     case SUBMODULE_EXCLUDED_HEADER:
5558     case SUBMODULE_PRIVATE_HEADER:
5559       // We lazily associate headers with their modules via the HeaderInfo table.
5560       // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5561       // of complete filenames or remove it entirely.
5562       break;
5563 
5564     case SUBMODULE_TEXTUAL_HEADER:
5565     case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5566       // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5567       // them here.
5568       break;
5569 
5570     case SUBMODULE_TOPHEADER:
5571       CurrentModule->addTopHeaderFilename(Blob);
5572       break;
5573 
5574     case SUBMODULE_UMBRELLA_DIR: {
5575       std::string Dirname = Blob;
5576       ResolveImportedPath(F, Dirname);
5577       if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
5578         if (!CurrentModule->getUmbrellaDir())
5579           ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob);
5580         else if (CurrentModule->getUmbrellaDir().Entry != *Umbrella) {
5581           if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5582             Error("mismatched umbrella directories in submodule");
5583           return OutOfDate;
5584         }
5585       }
5586       break;
5587     }
5588 
5589     case SUBMODULE_METADATA: {
5590       F.BaseSubmoduleID = getTotalNumSubmodules();
5591       F.LocalNumSubmodules = Record[0];
5592       unsigned LocalBaseSubmoduleID = Record[1];
5593       if (F.LocalNumSubmodules > 0) {
5594         // Introduce the global -> local mapping for submodules within this
5595         // module.
5596         GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
5597 
5598         // Introduce the local -> global mapping for submodules within this
5599         // module.
5600         F.SubmoduleRemap.insertOrReplace(
5601           std::make_pair(LocalBaseSubmoduleID,
5602                          F.BaseSubmoduleID - LocalBaseSubmoduleID));
5603 
5604         SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5605       }
5606       break;
5607     }
5608 
5609     case SUBMODULE_IMPORTS:
5610       for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5611         UnresolvedModuleRef Unresolved;
5612         Unresolved.File = &F;
5613         Unresolved.Mod = CurrentModule;
5614         Unresolved.ID = Record[Idx];
5615         Unresolved.Kind = UnresolvedModuleRef::Import;
5616         Unresolved.IsWildcard = false;
5617         UnresolvedModuleRefs.push_back(Unresolved);
5618       }
5619       break;
5620 
5621     case SUBMODULE_EXPORTS:
5622       for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
5623         UnresolvedModuleRef Unresolved;
5624         Unresolved.File = &F;
5625         Unresolved.Mod = CurrentModule;
5626         Unresolved.ID = Record[Idx];
5627         Unresolved.Kind = UnresolvedModuleRef::Export;
5628         Unresolved.IsWildcard = Record[Idx + 1];
5629         UnresolvedModuleRefs.push_back(Unresolved);
5630       }
5631 
5632       // Once we've loaded the set of exports, there's no reason to keep
5633       // the parsed, unresolved exports around.
5634       CurrentModule->UnresolvedExports.clear();
5635       break;
5636 
5637     case SUBMODULE_REQUIRES:
5638       CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5639                                     PP.getTargetInfo());
5640       break;
5641 
5642     case SUBMODULE_LINK_LIBRARY:
5643       ModMap.resolveLinkAsDependencies(CurrentModule);
5644       CurrentModule->LinkLibraries.push_back(
5645                                          Module::LinkLibrary(Blob, Record[0]));
5646       break;
5647 
5648     case SUBMODULE_CONFIG_MACRO:
5649       CurrentModule->ConfigMacros.push_back(Blob.str());
5650       break;
5651 
5652     case SUBMODULE_CONFLICT: {
5653       UnresolvedModuleRef Unresolved;
5654       Unresolved.File = &F;
5655       Unresolved.Mod = CurrentModule;
5656       Unresolved.ID = Record[0];
5657       Unresolved.Kind = UnresolvedModuleRef::Conflict;
5658       Unresolved.IsWildcard = false;
5659       Unresolved.String = Blob;
5660       UnresolvedModuleRefs.push_back(Unresolved);
5661       break;
5662     }
5663 
5664     case SUBMODULE_INITIALIZERS: {
5665       if (!ContextObj)
5666         break;
5667       SmallVector<uint32_t, 16> Inits;
5668       for (auto &ID : Record)
5669         Inits.push_back(getGlobalDeclID(F, ID));
5670       ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
5671       break;
5672     }
5673 
5674     case SUBMODULE_EXPORT_AS:
5675       CurrentModule->ExportAsModule = Blob.str();
5676       ModMap.addLinkAsDependency(CurrentModule);
5677       break;
5678     }
5679   }
5680 }
5681 
5682 /// Parse the record that corresponds to a LangOptions data
5683 /// structure.
5684 ///
5685 /// This routine parses the language options from the AST file and then gives
5686 /// them to the AST listener if one is set.
5687 ///
5688 /// \returns true if the listener deems the file unacceptable, false otherwise.
5689 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5690                                      bool Complain,
5691                                      ASTReaderListener &Listener,
5692                                      bool AllowCompatibleDifferences) {
5693   LangOptions LangOpts;
5694   unsigned Idx = 0;
5695 #define LANGOPT(Name, Bits, Default, Description) \
5696   LangOpts.Name = Record[Idx++];
5697 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5698   LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5699 #include "clang/Basic/LangOptions.def"
5700 #define SANITIZER(NAME, ID)                                                    \
5701   LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
5702 #include "clang/Basic/Sanitizers.def"
5703 
5704   for (unsigned N = Record[Idx++]; N; --N)
5705     LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5706 
5707   ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5708   VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5709   LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
5710 
5711   LangOpts.CurrentModule = ReadString(Record, Idx);
5712 
5713   // Comment options.
5714   for (unsigned N = Record[Idx++]; N; --N) {
5715     LangOpts.CommentOpts.BlockCommandNames.push_back(
5716       ReadString(Record, Idx));
5717   }
5718   LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
5719 
5720   // OpenMP offloading options.
5721   for (unsigned N = Record[Idx++]; N; --N) {
5722     LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5723   }
5724 
5725   LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5726 
5727   return Listener.ReadLanguageOptions(LangOpts, Complain,
5728                                       AllowCompatibleDifferences);
5729 }
5730 
5731 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5732                                    ASTReaderListener &Listener,
5733                                    bool AllowCompatibleDifferences) {
5734   unsigned Idx = 0;
5735   TargetOptions TargetOpts;
5736   TargetOpts.Triple = ReadString(Record, Idx);
5737   TargetOpts.CPU = ReadString(Record, Idx);
5738   TargetOpts.ABI = ReadString(Record, Idx);
5739   for (unsigned N = Record[Idx++]; N; --N) {
5740     TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5741   }
5742   for (unsigned N = Record[Idx++]; N; --N) {
5743     TargetOpts.Features.push_back(ReadString(Record, Idx));
5744   }
5745 
5746   return Listener.ReadTargetOptions(TargetOpts, Complain,
5747                                     AllowCompatibleDifferences);
5748 }
5749 
5750 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5751                                        ASTReaderListener &Listener) {
5752   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
5753   unsigned Idx = 0;
5754 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
5755 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
5756   DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
5757 #include "clang/Basic/DiagnosticOptions.def"
5758 
5759   for (unsigned N = Record[Idx++]; N; --N)
5760     DiagOpts->Warnings.push_back(ReadString(Record, Idx));
5761   for (unsigned N = Record[Idx++]; N; --N)
5762     DiagOpts->Remarks.push_back(ReadString(Record, Idx));
5763 
5764   return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5765 }
5766 
5767 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5768                                        ASTReaderListener &Listener) {
5769   FileSystemOptions FSOpts;
5770   unsigned Idx = 0;
5771   FSOpts.WorkingDir = ReadString(Record, Idx);
5772   return Listener.ReadFileSystemOptions(FSOpts, Complain);
5773 }
5774 
5775 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5776                                          bool Complain,
5777                                          ASTReaderListener &Listener) {
5778   HeaderSearchOptions HSOpts;
5779   unsigned Idx = 0;
5780   HSOpts.Sysroot = ReadString(Record, Idx);
5781 
5782   // Include entries.
5783   for (unsigned N = Record[Idx++]; N; --N) {
5784     std::string Path = ReadString(Record, Idx);
5785     frontend::IncludeDirGroup Group
5786       = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
5787     bool IsFramework = Record[Idx++];
5788     bool IgnoreSysRoot = Record[Idx++];
5789     HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5790                                     IgnoreSysRoot);
5791   }
5792 
5793   // System header prefixes.
5794   for (unsigned N = Record[Idx++]; N; --N) {
5795     std::string Prefix = ReadString(Record, Idx);
5796     bool IsSystemHeader = Record[Idx++];
5797     HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
5798   }
5799 
5800   HSOpts.ResourceDir = ReadString(Record, Idx);
5801   HSOpts.ModuleCachePath = ReadString(Record, Idx);
5802   HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
5803   HSOpts.DisableModuleHash = Record[Idx++];
5804   HSOpts.ImplicitModuleMaps = Record[Idx++];
5805   HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
5806   HSOpts.UseBuiltinIncludes = Record[Idx++];
5807   HSOpts.UseStandardSystemIncludes = Record[Idx++];
5808   HSOpts.UseStandardCXXIncludes = Record[Idx++];
5809   HSOpts.UseLibcxx = Record[Idx++];
5810   std::string SpecificModuleCachePath = ReadString(Record, Idx);
5811 
5812   return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5813                                           Complain);
5814 }
5815 
5816 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5817                                          bool Complain,
5818                                          ASTReaderListener &Listener,
5819                                          std::string &SuggestedPredefines) {
5820   PreprocessorOptions PPOpts;
5821   unsigned Idx = 0;
5822 
5823   // Macro definitions/undefs
5824   for (unsigned N = Record[Idx++]; N; --N) {
5825     std::string Macro = ReadString(Record, Idx);
5826     bool IsUndef = Record[Idx++];
5827     PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5828   }
5829 
5830   // Includes
5831   for (unsigned N = Record[Idx++]; N; --N) {
5832     PPOpts.Includes.push_back(ReadString(Record, Idx));
5833   }
5834 
5835   // Macro Includes
5836   for (unsigned N = Record[Idx++]; N; --N) {
5837     PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5838   }
5839 
5840   PPOpts.UsePredefines = Record[Idx++];
5841   PPOpts.DetailedRecord = Record[Idx++];
5842   PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5843   PPOpts.ObjCXXARCStandardLibrary =
5844     static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5845   SuggestedPredefines.clear();
5846   return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5847                                           SuggestedPredefines);
5848 }
5849 
5850 std::pair<ModuleFile *, unsigned>
5851 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5852   GlobalPreprocessedEntityMapType::iterator
5853   I = GlobalPreprocessedEntityMap.find(GlobalIndex);
5854   assert(I != GlobalPreprocessedEntityMap.end() &&
5855          "Corrupted global preprocessed entity map");
5856   ModuleFile *M = I->second;
5857   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5858   return std::make_pair(M, LocalIndex);
5859 }
5860 
5861 llvm::iterator_range<PreprocessingRecord::iterator>
5862 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5863   if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5864     return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5865                                              Mod.NumPreprocessedEntities);
5866 
5867   return llvm::make_range(PreprocessingRecord::iterator(),
5868                           PreprocessingRecord::iterator());
5869 }
5870 
5871 llvm::iterator_range<ASTReader::ModuleDeclIterator>
5872 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
5873   return llvm::make_range(
5874       ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5875       ModuleDeclIterator(this, &Mod,
5876                          Mod.FileSortedDecls + Mod.NumFileSortedDecls));
5877 }
5878 
5879 SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5880   auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5881   assert(I != GlobalSkippedRangeMap.end() &&
5882     "Corrupted global skipped range map");
5883   ModuleFile *M = I->second;
5884   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5885   assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5886   PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5887   SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5888                     TranslateSourceLocation(*M, RawRange.getEnd()));
5889   assert(Range.isValid());
5890   return Range;
5891 }
5892 
5893 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5894   PreprocessedEntityID PPID = Index+1;
5895   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5896   ModuleFile &M = *PPInfo.first;
5897   unsigned LocalIndex = PPInfo.second;
5898   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5899 
5900   if (!PP.getPreprocessingRecord()) {
5901     Error("no preprocessing record");
5902     return nullptr;
5903   }
5904 
5905   SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
5906   if (llvm::Error Err =
5907           M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset)) {
5908     Error(std::move(Err));
5909     return nullptr;
5910   }
5911 
5912   Expected<llvm::BitstreamEntry> MaybeEntry =
5913       M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5914   if (!MaybeEntry) {
5915     Error(MaybeEntry.takeError());
5916     return nullptr;
5917   }
5918   llvm::BitstreamEntry Entry = MaybeEntry.get();
5919 
5920   if (Entry.Kind != llvm::BitstreamEntry::Record)
5921     return nullptr;
5922 
5923   // Read the record.
5924   SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5925                     TranslateSourceLocation(M, PPOffs.getEnd()));
5926   PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
5927   StringRef Blob;
5928   RecordData Record;
5929   Expected<unsigned> MaybeRecType =
5930       M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
5931   if (!MaybeRecType) {
5932     Error(MaybeRecType.takeError());
5933     return nullptr;
5934   }
5935   switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
5936   case PPD_MACRO_EXPANSION: {
5937     bool isBuiltin = Record[0];
5938     IdentifierInfo *Name = nullptr;
5939     MacroDefinitionRecord *Def = nullptr;
5940     if (isBuiltin)
5941       Name = getLocalIdentifier(M, Record[1]);
5942     else {
5943       PreprocessedEntityID GlobalID =
5944           getGlobalPreprocessedEntityID(M, Record[1]);
5945       Def = cast<MacroDefinitionRecord>(
5946           PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
5947     }
5948 
5949     MacroExpansion *ME;
5950     if (isBuiltin)
5951       ME = new (PPRec) MacroExpansion(Name, Range);
5952     else
5953       ME = new (PPRec) MacroExpansion(Def, Range);
5954 
5955     return ME;
5956   }
5957 
5958   case PPD_MACRO_DEFINITION: {
5959     // Decode the identifier info and then check again; if the macro is
5960     // still defined and associated with the identifier,
5961     IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
5962     MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
5963 
5964     if (DeserializationListener)
5965       DeserializationListener->MacroDefinitionRead(PPID, MD);
5966 
5967     return MD;
5968   }
5969 
5970   case PPD_INCLUSION_DIRECTIVE: {
5971     const char *FullFileNameStart = Blob.data() + Record[0];
5972     StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
5973     const FileEntry *File = nullptr;
5974     if (!FullFileName.empty())
5975       if (auto FE = PP.getFileManager().getFile(FullFileName))
5976         File = *FE;
5977 
5978     // FIXME: Stable encoding
5979     InclusionDirective::InclusionKind Kind
5980       = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5981     InclusionDirective *ID
5982       = new (PPRec) InclusionDirective(PPRec, Kind,
5983                                        StringRef(Blob.data(), Record[0]),
5984                                        Record[1], Record[3],
5985                                        File,
5986                                        Range);
5987     return ID;
5988   }
5989   }
5990 
5991   llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5992 }
5993 
5994 /// Find the next module that contains entities and return the ID
5995 /// of the first entry.
5996 ///
5997 /// \param SLocMapI points at a chunk of a module that contains no
5998 /// preprocessed entities or the entities it contains are not the ones we are
5999 /// looking for.
6000 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6001                        GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6002   ++SLocMapI;
6003   for (GlobalSLocOffsetMapType::const_iterator
6004          EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6005     ModuleFile &M = *SLocMapI->second;
6006     if (M.NumPreprocessedEntities)
6007       return M.BasePreprocessedEntityID;
6008   }
6009 
6010   return getTotalNumPreprocessedEntities();
6011 }
6012 
6013 namespace {
6014 
6015 struct PPEntityComp {
6016   const ASTReader &Reader;
6017   ModuleFile &M;
6018 
6019   PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6020 
6021   bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6022     SourceLocation LHS = getLoc(L);
6023     SourceLocation RHS = getLoc(R);
6024     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6025   }
6026 
6027   bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6028     SourceLocation LHS = getLoc(L);
6029     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6030   }
6031 
6032   bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6033     SourceLocation RHS = getLoc(R);
6034     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6035   }
6036 
6037   SourceLocation getLoc(const PPEntityOffset &PPE) const {
6038     return Reader.TranslateSourceLocation(M, PPE.getBegin());
6039   }
6040 };
6041 
6042 } // namespace
6043 
6044 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6045                                                        bool EndsAfter) const {
6046   if (SourceMgr.isLocalSourceLocation(Loc))
6047     return getTotalNumPreprocessedEntities();
6048 
6049   GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6050       SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6051   assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6052          "Corrupted global sloc offset map");
6053 
6054   if (SLocMapI->second->NumPreprocessedEntities == 0)
6055     return findNextPreprocessedEntity(SLocMapI);
6056 
6057   ModuleFile &M = *SLocMapI->second;
6058 
6059   using pp_iterator = const PPEntityOffset *;
6060 
6061   pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6062   pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6063 
6064   size_t Count = M.NumPreprocessedEntities;
6065   size_t Half;
6066   pp_iterator First = pp_begin;
6067   pp_iterator PPI;
6068 
6069   if (EndsAfter) {
6070     PPI = std::upper_bound(pp_begin, pp_end, Loc,
6071                            PPEntityComp(*this, M));
6072   } else {
6073     // Do a binary search manually instead of using std::lower_bound because
6074     // The end locations of entities may be unordered (when a macro expansion
6075     // is inside another macro argument), but for this case it is not important
6076     // whether we get the first macro expansion or its containing macro.
6077     while (Count > 0) {
6078       Half = Count / 2;
6079       PPI = First;
6080       std::advance(PPI, Half);
6081       if (SourceMgr.isBeforeInTranslationUnit(
6082               TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
6083         First = PPI;
6084         ++First;
6085         Count = Count - Half - 1;
6086       } else
6087         Count = Half;
6088     }
6089   }
6090 
6091   if (PPI == pp_end)
6092     return findNextPreprocessedEntity(SLocMapI);
6093 
6094   return M.BasePreprocessedEntityID + (PPI - pp_begin);
6095 }
6096 
6097 /// Returns a pair of [Begin, End) indices of preallocated
6098 /// preprocessed entities that \arg Range encompasses.
6099 std::pair<unsigned, unsigned>
6100     ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6101   if (Range.isInvalid())
6102     return std::make_pair(0,0);
6103   assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6104 
6105   PreprocessedEntityID BeginID =
6106       findPreprocessedEntity(Range.getBegin(), false);
6107   PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
6108   return std::make_pair(BeginID, EndID);
6109 }
6110 
6111 /// Optionally returns true or false if the preallocated preprocessed
6112 /// entity with index \arg Index came from file \arg FID.
6113 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6114                                                              FileID FID) {
6115   if (FID.isInvalid())
6116     return false;
6117 
6118   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6119   ModuleFile &M = *PPInfo.first;
6120   unsigned LocalIndex = PPInfo.second;
6121   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6122 
6123   SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
6124   if (Loc.isInvalid())
6125     return false;
6126 
6127   if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6128     return true;
6129   else
6130     return false;
6131 }
6132 
6133 namespace {
6134 
6135   /// Visitor used to search for information about a header file.
6136   class HeaderFileInfoVisitor {
6137     const FileEntry *FE;
6138     Optional<HeaderFileInfo> HFI;
6139 
6140   public:
6141     explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
6142 
6143     bool operator()(ModuleFile &M) {
6144       HeaderFileInfoLookupTable *Table
6145         = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
6146       if (!Table)
6147         return false;
6148 
6149       // Look in the on-disk hash table for an entry for this file name.
6150       HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
6151       if (Pos == Table->end())
6152         return false;
6153 
6154       HFI = *Pos;
6155       return true;
6156     }
6157 
6158     Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
6159   };
6160 
6161 } // namespace
6162 
6163 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
6164   HeaderFileInfoVisitor Visitor(FE);
6165   ModuleMgr.visit(Visitor);
6166   if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
6167     return *HFI;
6168 
6169   return HeaderFileInfo();
6170 }
6171 
6172 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
6173   using DiagState = DiagnosticsEngine::DiagState;
6174   SmallVector<DiagState *, 32> DiagStates;
6175 
6176   for (ModuleFile &F : ModuleMgr) {
6177     unsigned Idx = 0;
6178     auto &Record = F.PragmaDiagMappings;
6179     if (Record.empty())
6180       continue;
6181 
6182     DiagStates.clear();
6183 
6184     auto ReadDiagState =
6185         [&](const DiagState &BasedOn, SourceLocation Loc,
6186             bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
6187       unsigned BackrefID = Record[Idx++];
6188       if (BackrefID != 0)
6189         return DiagStates[BackrefID - 1];
6190 
6191       // A new DiagState was created here.
6192       Diag.DiagStates.push_back(BasedOn);
6193       DiagState *NewState = &Diag.DiagStates.back();
6194       DiagStates.push_back(NewState);
6195       unsigned Size = Record[Idx++];
6196       assert(Idx + Size * 2 <= Record.size() &&
6197              "Invalid data, not enough diag/map pairs");
6198       while (Size--) {
6199         unsigned DiagID = Record[Idx++];
6200         DiagnosticMapping NewMapping =
6201             DiagnosticMapping::deserialize(Record[Idx++]);
6202         if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6203           continue;
6204 
6205         DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6206 
6207         // If this mapping was specified as a warning but the severity was
6208         // upgraded due to diagnostic settings, simulate the current diagnostic
6209         // settings (and use a warning).
6210         if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6211           NewMapping.setSeverity(diag::Severity::Warning);
6212           NewMapping.setUpgradedFromWarning(false);
6213         }
6214 
6215         Mapping = NewMapping;
6216       }
6217       return NewState;
6218     };
6219 
6220     // Read the first state.
6221     DiagState *FirstState;
6222     if (F.Kind == MK_ImplicitModule) {
6223       // Implicitly-built modules are reused with different diagnostic
6224       // settings.  Use the initial diagnostic state from Diag to simulate this
6225       // compilation's diagnostic settings.
6226       FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6227       DiagStates.push_back(FirstState);
6228 
6229       // Skip the initial diagnostic state from the serialized module.
6230       assert(Record[1] == 0 &&
6231              "Invalid data, unexpected backref in initial state");
6232       Idx = 3 + Record[2] * 2;
6233       assert(Idx < Record.size() &&
6234              "Invalid data, not enough state change pairs in initial state");
6235     } else if (F.isModule()) {
6236       // For an explicit module, preserve the flags from the module build
6237       // command line (-w, -Weverything, -Werror, ...) along with any explicit
6238       // -Wblah flags.
6239       unsigned Flags = Record[Idx++];
6240       DiagState Initial;
6241       Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6242       Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6243       Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6244       Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6245       Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6246       Initial.ExtBehavior = (diag::Severity)Flags;
6247       FirstState = ReadDiagState(Initial, SourceLocation(), true);
6248 
6249       assert(F.OriginalSourceFileID.isValid());
6250 
6251       // Set up the root buffer of the module to start with the initial
6252       // diagnostic state of the module itself, to cover files that contain no
6253       // explicit transitions (for which we did not serialize anything).
6254       Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6255           .StateTransitions.push_back({FirstState, 0});
6256     } else {
6257       // For prefix ASTs, start with whatever the user configured on the
6258       // command line.
6259       Idx++; // Skip flags.
6260       FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
6261                                  SourceLocation(), false);
6262     }
6263 
6264     // Read the state transitions.
6265     unsigned NumLocations = Record[Idx++];
6266     while (NumLocations--) {
6267       assert(Idx < Record.size() &&
6268              "Invalid data, missing pragma diagnostic states");
6269       SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
6270       auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
6271       assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
6272       assert(IDAndOffset.second == 0 && "not a start location for a FileID");
6273       unsigned Transitions = Record[Idx++];
6274 
6275       // Note that we don't need to set up Parent/ParentOffset here, because
6276       // we won't be changing the diagnostic state within imported FileIDs
6277       // (other than perhaps appending to the main source file, which has no
6278       // parent).
6279       auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
6280       F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6281       for (unsigned I = 0; I != Transitions; ++I) {
6282         unsigned Offset = Record[Idx++];
6283         auto *State =
6284             ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
6285         F.StateTransitions.push_back({State, Offset});
6286       }
6287     }
6288 
6289     // Read the final state.
6290     assert(Idx < Record.size() &&
6291            "Invalid data, missing final pragma diagnostic state");
6292     SourceLocation CurStateLoc =
6293         ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
6294     auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
6295 
6296     if (!F.isModule()) {
6297       Diag.DiagStatesByLoc.CurDiagState = CurState;
6298       Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6299 
6300       // Preserve the property that the imaginary root file describes the
6301       // current state.
6302       FileID NullFile;
6303       auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
6304       if (T.empty())
6305         T.push_back({CurState, 0});
6306       else
6307         T[0].State = CurState;
6308     }
6309 
6310     // Don't try to read these mappings again.
6311     Record.clear();
6312   }
6313 }
6314 
6315 /// Get the correct cursor and offset for loading a type.
6316 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6317   GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6318   assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6319   ModuleFile *M = I->second;
6320   return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
6321 }
6322 
6323 static llvm::Optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6324   switch (code) {
6325 #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6326   case TYPE_##CODE_ID: return Type::CLASS_ID;
6327 #include "clang/Serialization/TypeBitCodes.def"
6328   default: return llvm::None;
6329   }
6330 }
6331 
6332 /// Read and return the type with the given index..
6333 ///
6334 /// The index is the type ID, shifted and minus the number of predefs. This
6335 /// routine actually reads the record corresponding to the type at the given
6336 /// location. It is a helper routine for GetType, which deals with reading type
6337 /// IDs.
6338 QualType ASTReader::readTypeRecord(unsigned Index) {
6339   assert(ContextObj && "reading type with no AST context");
6340   ASTContext &Context = *ContextObj;
6341   RecordLocation Loc = TypeCursorForIndex(Index);
6342   BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
6343 
6344   // Keep track of where we are in the stream, then jump back there
6345   // after reading this type.
6346   SavedStreamPosition SavedPosition(DeclsCursor);
6347 
6348   ReadingKindTracker ReadingKind(Read_Type, *this);
6349 
6350   // Note that we are loading a type record.
6351   Deserializing AType(this);
6352 
6353   if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6354     Error(std::move(Err));
6355     return QualType();
6356   }
6357   Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6358   if (!RawCode) {
6359     Error(RawCode.takeError());
6360     return QualType();
6361   }
6362 
6363   ASTRecordReader Record(*this, *Loc.F);
6364   Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6365   if (!Code) {
6366     Error(Code.takeError());
6367     return QualType();
6368   }
6369   if (Code.get() == TYPE_EXT_QUAL) {
6370     QualType baseType = Record.readQualType();
6371     Qualifiers quals = Record.readQualifiers();
6372     return Context.getQualifiedType(baseType, quals);
6373   }
6374 
6375   auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6376   if (!maybeClass) {
6377     Error("Unexpected code for type");
6378     return QualType();
6379   }
6380 
6381   serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
6382   return TypeReader.read(*maybeClass);
6383 }
6384 
6385 namespace clang {
6386 
6387 class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6388   ASTRecordReader &Reader;
6389 
6390   SourceLocation readSourceLocation() {
6391     return Reader.readSourceLocation();
6392   }
6393 
6394   TypeSourceInfo *GetTypeSourceInfo() {
6395     return Reader.readTypeSourceInfo();
6396   }
6397 
6398   NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6399     return Reader.readNestedNameSpecifierLoc();
6400   }
6401 
6402   Attr *ReadAttr() {
6403     return Reader.readAttr();
6404   }
6405 
6406 public:
6407   TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
6408 
6409   // We want compile-time assurance that we've enumerated all of
6410   // these, so unfortunately we have to declare them first, then
6411   // define them out-of-line.
6412 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6413 #define TYPELOC(CLASS, PARENT) \
6414   void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6415 #include "clang/AST/TypeLocNodes.def"
6416 
6417   void VisitFunctionTypeLoc(FunctionTypeLoc);
6418   void VisitArrayTypeLoc(ArrayTypeLoc);
6419 };
6420 
6421 } // namespace clang
6422 
6423 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6424   // nothing to do
6425 }
6426 
6427 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6428   TL.setBuiltinLoc(readSourceLocation());
6429   if (TL.needsExtraLocalData()) {
6430     TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6431     TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Reader.readInt()));
6432     TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Reader.readInt()));
6433     TL.setModeAttr(Reader.readInt());
6434   }
6435 }
6436 
6437 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6438   TL.setNameLoc(readSourceLocation());
6439 }
6440 
6441 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6442   TL.setStarLoc(readSourceLocation());
6443 }
6444 
6445 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6446   // nothing to do
6447 }
6448 
6449 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6450   // nothing to do
6451 }
6452 
6453 void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6454   TL.setExpansionLoc(readSourceLocation());
6455 }
6456 
6457 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6458   TL.setCaretLoc(readSourceLocation());
6459 }
6460 
6461 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6462   TL.setAmpLoc(readSourceLocation());
6463 }
6464 
6465 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6466   TL.setAmpAmpLoc(readSourceLocation());
6467 }
6468 
6469 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6470   TL.setStarLoc(readSourceLocation());
6471   TL.setClassTInfo(GetTypeSourceInfo());
6472 }
6473 
6474 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
6475   TL.setLBracketLoc(readSourceLocation());
6476   TL.setRBracketLoc(readSourceLocation());
6477   if (Reader.readBool())
6478     TL.setSizeExpr(Reader.readExpr());
6479   else
6480     TL.setSizeExpr(nullptr);
6481 }
6482 
6483 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6484   VisitArrayTypeLoc(TL);
6485 }
6486 
6487 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6488   VisitArrayTypeLoc(TL);
6489 }
6490 
6491 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6492   VisitArrayTypeLoc(TL);
6493 }
6494 
6495 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6496                                             DependentSizedArrayTypeLoc TL) {
6497   VisitArrayTypeLoc(TL);
6498 }
6499 
6500 void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6501     DependentAddressSpaceTypeLoc TL) {
6502 
6503     TL.setAttrNameLoc(readSourceLocation());
6504     TL.setAttrOperandParensRange(Reader.readSourceRange());
6505     TL.setAttrExprOperand(Reader.readExpr());
6506 }
6507 
6508 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6509                                         DependentSizedExtVectorTypeLoc TL) {
6510   TL.setNameLoc(readSourceLocation());
6511 }
6512 
6513 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6514   TL.setNameLoc(readSourceLocation());
6515 }
6516 
6517 void TypeLocReader::VisitDependentVectorTypeLoc(
6518     DependentVectorTypeLoc TL) {
6519   TL.setNameLoc(readSourceLocation());
6520 }
6521 
6522 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6523   TL.setNameLoc(readSourceLocation());
6524 }
6525 
6526 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6527   TL.setLocalRangeBegin(readSourceLocation());
6528   TL.setLParenLoc(readSourceLocation());
6529   TL.setRParenLoc(readSourceLocation());
6530   TL.setExceptionSpecRange(Reader.readSourceRange());
6531   TL.setLocalRangeEnd(readSourceLocation());
6532   for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6533     TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
6534   }
6535 }
6536 
6537 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6538   VisitFunctionTypeLoc(TL);
6539 }
6540 
6541 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6542   VisitFunctionTypeLoc(TL);
6543 }
6544 
6545 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6546   TL.setNameLoc(readSourceLocation());
6547 }
6548 
6549 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6550   TL.setNameLoc(readSourceLocation());
6551 }
6552 
6553 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6554   TL.setTypeofLoc(readSourceLocation());
6555   TL.setLParenLoc(readSourceLocation());
6556   TL.setRParenLoc(readSourceLocation());
6557 }
6558 
6559 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6560   TL.setTypeofLoc(readSourceLocation());
6561   TL.setLParenLoc(readSourceLocation());
6562   TL.setRParenLoc(readSourceLocation());
6563   TL.setUnderlyingTInfo(GetTypeSourceInfo());
6564 }
6565 
6566 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6567   TL.setNameLoc(readSourceLocation());
6568 }
6569 
6570 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6571   TL.setKWLoc(readSourceLocation());
6572   TL.setLParenLoc(readSourceLocation());
6573   TL.setRParenLoc(readSourceLocation());
6574   TL.setUnderlyingTInfo(GetTypeSourceInfo());
6575 }
6576 
6577 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6578   TL.setNameLoc(readSourceLocation());
6579 }
6580 
6581 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6582     DeducedTemplateSpecializationTypeLoc TL) {
6583   TL.setTemplateNameLoc(readSourceLocation());
6584 }
6585 
6586 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6587   TL.setNameLoc(readSourceLocation());
6588 }
6589 
6590 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6591   TL.setNameLoc(readSourceLocation());
6592 }
6593 
6594 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6595   TL.setAttr(ReadAttr());
6596 }
6597 
6598 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6599   TL.setNameLoc(readSourceLocation());
6600 }
6601 
6602 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6603                                             SubstTemplateTypeParmTypeLoc TL) {
6604   TL.setNameLoc(readSourceLocation());
6605 }
6606 
6607 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6608                                           SubstTemplateTypeParmPackTypeLoc TL) {
6609   TL.setNameLoc(readSourceLocation());
6610 }
6611 
6612 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6613                                            TemplateSpecializationTypeLoc TL) {
6614   TL.setTemplateKeywordLoc(readSourceLocation());
6615   TL.setTemplateNameLoc(readSourceLocation());
6616   TL.setLAngleLoc(readSourceLocation());
6617   TL.setRAngleLoc(readSourceLocation());
6618   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6619     TL.setArgLocInfo(
6620         i,
6621         Reader.readTemplateArgumentLocInfo(
6622           TL.getTypePtr()->getArg(i).getKind()));
6623 }
6624 
6625 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
6626   TL.setLParenLoc(readSourceLocation());
6627   TL.setRParenLoc(readSourceLocation());
6628 }
6629 
6630 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6631   TL.setElaboratedKeywordLoc(readSourceLocation());
6632   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6633 }
6634 
6635 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
6636   TL.setNameLoc(readSourceLocation());
6637 }
6638 
6639 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6640   TL.setElaboratedKeywordLoc(readSourceLocation());
6641   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6642   TL.setNameLoc(readSourceLocation());
6643 }
6644 
6645 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6646        DependentTemplateSpecializationTypeLoc TL) {
6647   TL.setElaboratedKeywordLoc(readSourceLocation());
6648   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6649   TL.setTemplateKeywordLoc(readSourceLocation());
6650   TL.setTemplateNameLoc(readSourceLocation());
6651   TL.setLAngleLoc(readSourceLocation());
6652   TL.setRAngleLoc(readSourceLocation());
6653   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
6654     TL.setArgLocInfo(
6655         I,
6656         Reader.readTemplateArgumentLocInfo(
6657             TL.getTypePtr()->getArg(I).getKind()));
6658 }
6659 
6660 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
6661   TL.setEllipsisLoc(readSourceLocation());
6662 }
6663 
6664 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6665   TL.setNameLoc(readSourceLocation());
6666 }
6667 
6668 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6669   if (TL.getNumProtocols()) {
6670     TL.setProtocolLAngleLoc(readSourceLocation());
6671     TL.setProtocolRAngleLoc(readSourceLocation());
6672   }
6673   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6674     TL.setProtocolLoc(i, readSourceLocation());
6675 }
6676 
6677 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6678   TL.setHasBaseTypeAsWritten(Reader.readBool());
6679   TL.setTypeArgsLAngleLoc(readSourceLocation());
6680   TL.setTypeArgsRAngleLoc(readSourceLocation());
6681   for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
6682     TL.setTypeArgTInfo(i, GetTypeSourceInfo());
6683   TL.setProtocolLAngleLoc(readSourceLocation());
6684   TL.setProtocolRAngleLoc(readSourceLocation());
6685   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6686     TL.setProtocolLoc(i, readSourceLocation());
6687 }
6688 
6689 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6690   TL.setStarLoc(readSourceLocation());
6691 }
6692 
6693 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6694   TL.setKWLoc(readSourceLocation());
6695   TL.setLParenLoc(readSourceLocation());
6696   TL.setRParenLoc(readSourceLocation());
6697 }
6698 
6699 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
6700   TL.setKWLoc(readSourceLocation());
6701 }
6702 
6703 void ASTRecordReader::readTypeLoc(TypeLoc TL) {
6704   TypeLocReader TLR(*this);
6705   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
6706     TLR.Visit(TL);
6707 }
6708 
6709 TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {
6710   QualType InfoTy = readType();
6711   if (InfoTy.isNull())
6712     return nullptr;
6713 
6714   TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
6715   readTypeLoc(TInfo->getTypeLoc());
6716   return TInfo;
6717 }
6718 
6719 QualType ASTReader::GetType(TypeID ID) {
6720   assert(ContextObj && "reading type with no AST context");
6721   ASTContext &Context = *ContextObj;
6722 
6723   unsigned FastQuals = ID & Qualifiers::FastMask;
6724   unsigned Index = ID >> Qualifiers::FastWidth;
6725 
6726   if (Index < NUM_PREDEF_TYPE_IDS) {
6727     QualType T;
6728     switch ((PredefinedTypeIDs)Index) {
6729     case PREDEF_TYPE_NULL_ID:
6730       return QualType();
6731     case PREDEF_TYPE_VOID_ID:
6732       T = Context.VoidTy;
6733       break;
6734     case PREDEF_TYPE_BOOL_ID:
6735       T = Context.BoolTy;
6736       break;
6737     case PREDEF_TYPE_CHAR_U_ID:
6738     case PREDEF_TYPE_CHAR_S_ID:
6739       // FIXME: Check that the signedness of CharTy is correct!
6740       T = Context.CharTy;
6741       break;
6742     case PREDEF_TYPE_UCHAR_ID:
6743       T = Context.UnsignedCharTy;
6744       break;
6745     case PREDEF_TYPE_USHORT_ID:
6746       T = Context.UnsignedShortTy;
6747       break;
6748     case PREDEF_TYPE_UINT_ID:
6749       T = Context.UnsignedIntTy;
6750       break;
6751     case PREDEF_TYPE_ULONG_ID:
6752       T = Context.UnsignedLongTy;
6753       break;
6754     case PREDEF_TYPE_ULONGLONG_ID:
6755       T = Context.UnsignedLongLongTy;
6756       break;
6757     case PREDEF_TYPE_UINT128_ID:
6758       T = Context.UnsignedInt128Ty;
6759       break;
6760     case PREDEF_TYPE_SCHAR_ID:
6761       T = Context.SignedCharTy;
6762       break;
6763     case PREDEF_TYPE_WCHAR_ID:
6764       T = Context.WCharTy;
6765       break;
6766     case PREDEF_TYPE_SHORT_ID:
6767       T = Context.ShortTy;
6768       break;
6769     case PREDEF_TYPE_INT_ID:
6770       T = Context.IntTy;
6771       break;
6772     case PREDEF_TYPE_LONG_ID:
6773       T = Context.LongTy;
6774       break;
6775     case PREDEF_TYPE_LONGLONG_ID:
6776       T = Context.LongLongTy;
6777       break;
6778     case PREDEF_TYPE_INT128_ID:
6779       T = Context.Int128Ty;
6780       break;
6781     case PREDEF_TYPE_HALF_ID:
6782       T = Context.HalfTy;
6783       break;
6784     case PREDEF_TYPE_FLOAT_ID:
6785       T = Context.FloatTy;
6786       break;
6787     case PREDEF_TYPE_DOUBLE_ID:
6788       T = Context.DoubleTy;
6789       break;
6790     case PREDEF_TYPE_LONGDOUBLE_ID:
6791       T = Context.LongDoubleTy;
6792       break;
6793     case PREDEF_TYPE_SHORT_ACCUM_ID:
6794       T = Context.ShortAccumTy;
6795       break;
6796     case PREDEF_TYPE_ACCUM_ID:
6797       T = Context.AccumTy;
6798       break;
6799     case PREDEF_TYPE_LONG_ACCUM_ID:
6800       T = Context.LongAccumTy;
6801       break;
6802     case PREDEF_TYPE_USHORT_ACCUM_ID:
6803       T = Context.UnsignedShortAccumTy;
6804       break;
6805     case PREDEF_TYPE_UACCUM_ID:
6806       T = Context.UnsignedAccumTy;
6807       break;
6808     case PREDEF_TYPE_ULONG_ACCUM_ID:
6809       T = Context.UnsignedLongAccumTy;
6810       break;
6811     case PREDEF_TYPE_SHORT_FRACT_ID:
6812       T = Context.ShortFractTy;
6813       break;
6814     case PREDEF_TYPE_FRACT_ID:
6815       T = Context.FractTy;
6816       break;
6817     case PREDEF_TYPE_LONG_FRACT_ID:
6818       T = Context.LongFractTy;
6819       break;
6820     case PREDEF_TYPE_USHORT_FRACT_ID:
6821       T = Context.UnsignedShortFractTy;
6822       break;
6823     case PREDEF_TYPE_UFRACT_ID:
6824       T = Context.UnsignedFractTy;
6825       break;
6826     case PREDEF_TYPE_ULONG_FRACT_ID:
6827       T = Context.UnsignedLongFractTy;
6828       break;
6829     case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
6830       T = Context.SatShortAccumTy;
6831       break;
6832     case PREDEF_TYPE_SAT_ACCUM_ID:
6833       T = Context.SatAccumTy;
6834       break;
6835     case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
6836       T = Context.SatLongAccumTy;
6837       break;
6838     case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
6839       T = Context.SatUnsignedShortAccumTy;
6840       break;
6841     case PREDEF_TYPE_SAT_UACCUM_ID:
6842       T = Context.SatUnsignedAccumTy;
6843       break;
6844     case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
6845       T = Context.SatUnsignedLongAccumTy;
6846       break;
6847     case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
6848       T = Context.SatShortFractTy;
6849       break;
6850     case PREDEF_TYPE_SAT_FRACT_ID:
6851       T = Context.SatFractTy;
6852       break;
6853     case PREDEF_TYPE_SAT_LONG_FRACT_ID:
6854       T = Context.SatLongFractTy;
6855       break;
6856     case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
6857       T = Context.SatUnsignedShortFractTy;
6858       break;
6859     case PREDEF_TYPE_SAT_UFRACT_ID:
6860       T = Context.SatUnsignedFractTy;
6861       break;
6862     case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
6863       T = Context.SatUnsignedLongFractTy;
6864       break;
6865     case PREDEF_TYPE_FLOAT16_ID:
6866       T = Context.Float16Ty;
6867       break;
6868     case PREDEF_TYPE_FLOAT128_ID:
6869       T = Context.Float128Ty;
6870       break;
6871     case PREDEF_TYPE_OVERLOAD_ID:
6872       T = Context.OverloadTy;
6873       break;
6874     case PREDEF_TYPE_BOUND_MEMBER:
6875       T = Context.BoundMemberTy;
6876       break;
6877     case PREDEF_TYPE_PSEUDO_OBJECT:
6878       T = Context.PseudoObjectTy;
6879       break;
6880     case PREDEF_TYPE_DEPENDENT_ID:
6881       T = Context.DependentTy;
6882       break;
6883     case PREDEF_TYPE_UNKNOWN_ANY:
6884       T = Context.UnknownAnyTy;
6885       break;
6886     case PREDEF_TYPE_NULLPTR_ID:
6887       T = Context.NullPtrTy;
6888       break;
6889     case PREDEF_TYPE_CHAR8_ID:
6890       T = Context.Char8Ty;
6891       break;
6892     case PREDEF_TYPE_CHAR16_ID:
6893       T = Context.Char16Ty;
6894       break;
6895     case PREDEF_TYPE_CHAR32_ID:
6896       T = Context.Char32Ty;
6897       break;
6898     case PREDEF_TYPE_OBJC_ID:
6899       T = Context.ObjCBuiltinIdTy;
6900       break;
6901     case PREDEF_TYPE_OBJC_CLASS:
6902       T = Context.ObjCBuiltinClassTy;
6903       break;
6904     case PREDEF_TYPE_OBJC_SEL:
6905       T = Context.ObjCBuiltinSelTy;
6906       break;
6907 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6908     case PREDEF_TYPE_##Id##_ID: \
6909       T = Context.SingletonId; \
6910       break;
6911 #include "clang/Basic/OpenCLImageTypes.def"
6912 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6913     case PREDEF_TYPE_##Id##_ID: \
6914       T = Context.Id##Ty; \
6915       break;
6916 #include "clang/Basic/OpenCLExtensionTypes.def"
6917     case PREDEF_TYPE_SAMPLER_ID:
6918       T = Context.OCLSamplerTy;
6919       break;
6920     case PREDEF_TYPE_EVENT_ID:
6921       T = Context.OCLEventTy;
6922       break;
6923     case PREDEF_TYPE_CLK_EVENT_ID:
6924       T = Context.OCLClkEventTy;
6925       break;
6926     case PREDEF_TYPE_QUEUE_ID:
6927       T = Context.OCLQueueTy;
6928       break;
6929     case PREDEF_TYPE_RESERVE_ID_ID:
6930       T = Context.OCLReserveIDTy;
6931       break;
6932     case PREDEF_TYPE_AUTO_DEDUCT:
6933       T = Context.getAutoDeductType();
6934       break;
6935     case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6936       T = Context.getAutoRRefDeductType();
6937       break;
6938     case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6939       T = Context.ARCUnbridgedCastTy;
6940       break;
6941     case PREDEF_TYPE_BUILTIN_FN:
6942       T = Context.BuiltinFnTy;
6943       break;
6944     case PREDEF_TYPE_OMP_ARRAY_SECTION:
6945       T = Context.OMPArraySectionTy;
6946       break;
6947 #define SVE_TYPE(Name, Id, SingletonId) \
6948     case PREDEF_TYPE_##Id##_ID: \
6949       T = Context.SingletonId; \
6950       break;
6951 #include "clang/Basic/AArch64SVEACLETypes.def"
6952     }
6953 
6954     assert(!T.isNull() && "Unknown predefined type");
6955     return T.withFastQualifiers(FastQuals);
6956   }
6957 
6958   Index -= NUM_PREDEF_TYPE_IDS;
6959   assert(Index < TypesLoaded.size() && "Type index out-of-range");
6960   if (TypesLoaded[Index].isNull()) {
6961     TypesLoaded[Index] = readTypeRecord(Index);
6962     if (TypesLoaded[Index].isNull())
6963       return QualType();
6964 
6965     TypesLoaded[Index]->setFromAST();
6966     if (DeserializationListener)
6967       DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6968                                         TypesLoaded[Index]);
6969   }
6970 
6971   return TypesLoaded[Index].withFastQualifiers(FastQuals);
6972 }
6973 
6974 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6975   return GetType(getGlobalTypeID(F, LocalID));
6976 }
6977 
6978 serialization::TypeID
6979 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6980   unsigned FastQuals = LocalID & Qualifiers::FastMask;
6981   unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6982 
6983   if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6984     return LocalID;
6985 
6986   if (!F.ModuleOffsetMap.empty())
6987     ReadModuleOffsetMap(F);
6988 
6989   ContinuousRangeMap<uint32_t, int, 2>::iterator I
6990     = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6991   assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6992 
6993   unsigned GlobalIndex = LocalIndex + I->second;
6994   return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6995 }
6996 
6997 TemplateArgumentLocInfo
6998 ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
6999   switch (Kind) {
7000   case TemplateArgument::Expression:
7001     return readExpr();
7002   case TemplateArgument::Type:
7003     return readTypeSourceInfo();
7004   case TemplateArgument::Template: {
7005     NestedNameSpecifierLoc QualifierLoc =
7006       readNestedNameSpecifierLoc();
7007     SourceLocation TemplateNameLoc = readSourceLocation();
7008     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
7009                                    SourceLocation());
7010   }
7011   case TemplateArgument::TemplateExpansion: {
7012     NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7013     SourceLocation TemplateNameLoc = readSourceLocation();
7014     SourceLocation EllipsisLoc = readSourceLocation();
7015     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
7016                                    EllipsisLoc);
7017   }
7018   case TemplateArgument::Null:
7019   case TemplateArgument::Integral:
7020   case TemplateArgument::Declaration:
7021   case TemplateArgument::NullPtr:
7022   case TemplateArgument::Pack:
7023     // FIXME: Is this right?
7024     return TemplateArgumentLocInfo();
7025   }
7026   llvm_unreachable("unexpected template argument loc");
7027 }
7028 
7029 TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {
7030   TemplateArgument Arg = readTemplateArgument();
7031 
7032   if (Arg.getKind() == TemplateArgument::Expression) {
7033     if (readBool()) // bool InfoHasSameExpr.
7034       return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7035   }
7036   return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
7037 }
7038 
7039 const ASTTemplateArgumentListInfo *
7040 ASTRecordReader::readASTTemplateArgumentListInfo() {
7041   SourceLocation LAngleLoc = readSourceLocation();
7042   SourceLocation RAngleLoc = readSourceLocation();
7043   unsigned NumArgsAsWritten = readInt();
7044   TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7045   for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7046     TemplArgsInfo.addArgument(readTemplateArgumentLoc());
7047   return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7048 }
7049 
7050 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7051   return GetDecl(ID);
7052 }
7053 
7054 void ASTReader::CompleteRedeclChain(const Decl *D) {
7055   if (NumCurrentElementsDeserializing) {
7056     // We arrange to not care about the complete redeclaration chain while we're
7057     // deserializing. Just remember that the AST has marked this one as complete
7058     // but that it's not actually complete yet, so we know we still need to
7059     // complete it later.
7060     PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7061     return;
7062   }
7063 
7064   const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7065 
7066   // If this is a named declaration, complete it by looking it up
7067   // within its context.
7068   //
7069   // FIXME: Merging a function definition should merge
7070   // all mergeable entities within it.
7071   if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7072       isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7073     if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
7074       if (!getContext().getLangOpts().CPlusPlus &&
7075           isa<TranslationUnitDecl>(DC)) {
7076         // Outside of C++, we don't have a lookup table for the TU, so update
7077         // the identifier instead. (For C++ modules, we don't store decls
7078         // in the serialized identifier table, so we do the lookup in the TU.)
7079         auto *II = Name.getAsIdentifierInfo();
7080         assert(II && "non-identifier name in C?");
7081         if (II->isOutOfDate())
7082           updateOutOfDateIdentifier(*II);
7083       } else
7084         DC->lookup(Name);
7085     } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
7086       // Find all declarations of this kind from the relevant context.
7087       for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7088         auto *DC = cast<DeclContext>(DCDecl);
7089         SmallVector<Decl*, 8> Decls;
7090         FindExternalLexicalDecls(
7091             DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7092       }
7093     }
7094   }
7095 
7096   if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7097     CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7098   if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7099     VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7100   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7101     if (auto *Template = FD->getPrimaryTemplate())
7102       Template->LoadLazySpecializations();
7103   }
7104 }
7105 
7106 CXXCtorInitializer **
7107 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7108   RecordLocation Loc = getLocalBitOffset(Offset);
7109   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7110   SavedStreamPosition SavedPosition(Cursor);
7111   if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7112     Error(std::move(Err));
7113     return nullptr;
7114   }
7115   ReadingKindTracker ReadingKind(Read_Decl, *this);
7116 
7117   Expected<unsigned> MaybeCode = Cursor.ReadCode();
7118   if (!MaybeCode) {
7119     Error(MaybeCode.takeError());
7120     return nullptr;
7121   }
7122   unsigned Code = MaybeCode.get();
7123 
7124   ASTRecordReader Record(*this, *Loc.F);
7125   Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7126   if (!MaybeRecCode) {
7127     Error(MaybeRecCode.takeError());
7128     return nullptr;
7129   }
7130   if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
7131     Error("malformed AST file: missing C++ ctor initializers");
7132     return nullptr;
7133   }
7134 
7135   return Record.readCXXCtorInitializers();
7136 }
7137 
7138 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
7139   assert(ContextObj && "reading base specifiers with no AST context");
7140   ASTContext &Context = *ContextObj;
7141 
7142   RecordLocation Loc = getLocalBitOffset(Offset);
7143   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7144   SavedStreamPosition SavedPosition(Cursor);
7145   if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7146     Error(std::move(Err));
7147     return nullptr;
7148   }
7149   ReadingKindTracker ReadingKind(Read_Decl, *this);
7150 
7151   Expected<unsigned> MaybeCode = Cursor.ReadCode();
7152   if (!MaybeCode) {
7153     Error(MaybeCode.takeError());
7154     return nullptr;
7155   }
7156   unsigned Code = MaybeCode.get();
7157 
7158   ASTRecordReader Record(*this, *Loc.F);
7159   Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7160   if (!MaybeRecCode) {
7161     Error(MaybeCode.takeError());
7162     return nullptr;
7163   }
7164   unsigned RecCode = MaybeRecCode.get();
7165 
7166   if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
7167     Error("malformed AST file: missing C++ base specifiers");
7168     return nullptr;
7169   }
7170 
7171   unsigned NumBases = Record.readInt();
7172   void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
7173   CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
7174   for (unsigned I = 0; I != NumBases; ++I)
7175     Bases[I] = Record.readCXXBaseSpecifier();
7176   return Bases;
7177 }
7178 
7179 serialization::DeclID
7180 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7181   if (LocalID < NUM_PREDEF_DECL_IDS)
7182     return LocalID;
7183 
7184   if (!F.ModuleOffsetMap.empty())
7185     ReadModuleOffsetMap(F);
7186 
7187   ContinuousRangeMap<uint32_t, int, 2>::iterator I
7188     = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7189   assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
7190 
7191   return LocalID + I->second;
7192 }
7193 
7194 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7195                                    ModuleFile &M) const {
7196   // Predefined decls aren't from any module.
7197   if (ID < NUM_PREDEF_DECL_IDS)
7198     return false;
7199 
7200   return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
7201          ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
7202 }
7203 
7204 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
7205   if (!D->isFromASTFile())
7206     return nullptr;
7207   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7208   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7209   return I->second;
7210 }
7211 
7212 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7213   if (ID < NUM_PREDEF_DECL_IDS)
7214     return SourceLocation();
7215 
7216   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7217 
7218   if (Index > DeclsLoaded.size()) {
7219     Error("declaration ID out-of-range for AST file");
7220     return SourceLocation();
7221   }
7222 
7223   if (Decl *D = DeclsLoaded[Index])
7224     return D->getLocation();
7225 
7226   SourceLocation Loc;
7227   DeclCursorForID(ID, Loc);
7228   return Loc;
7229 }
7230 
7231 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7232   switch (ID) {
7233   case PREDEF_DECL_NULL_ID:
7234     return nullptr;
7235 
7236   case PREDEF_DECL_TRANSLATION_UNIT_ID:
7237     return Context.getTranslationUnitDecl();
7238 
7239   case PREDEF_DECL_OBJC_ID_ID:
7240     return Context.getObjCIdDecl();
7241 
7242   case PREDEF_DECL_OBJC_SEL_ID:
7243     return Context.getObjCSelDecl();
7244 
7245   case PREDEF_DECL_OBJC_CLASS_ID:
7246     return Context.getObjCClassDecl();
7247 
7248   case PREDEF_DECL_OBJC_PROTOCOL_ID:
7249     return Context.getObjCProtocolDecl();
7250 
7251   case PREDEF_DECL_INT_128_ID:
7252     return Context.getInt128Decl();
7253 
7254   case PREDEF_DECL_UNSIGNED_INT_128_ID:
7255     return Context.getUInt128Decl();
7256 
7257   case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7258     return Context.getObjCInstanceTypeDecl();
7259 
7260   case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7261     return Context.getBuiltinVaListDecl();
7262 
7263   case PREDEF_DECL_VA_LIST_TAG:
7264     return Context.getVaListTagDecl();
7265 
7266   case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7267     return Context.getBuiltinMSVaListDecl();
7268 
7269   case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7270     return Context.getExternCContextDecl();
7271 
7272   case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7273     return Context.getMakeIntegerSeqDecl();
7274 
7275   case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7276     return Context.getCFConstantStringDecl();
7277 
7278   case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7279     return Context.getCFConstantStringTagDecl();
7280 
7281   case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7282     return Context.getTypePackElementDecl();
7283   }
7284   llvm_unreachable("PredefinedDeclIDs unknown enum value");
7285 }
7286 
7287 Decl *ASTReader::GetExistingDecl(DeclID ID) {
7288   assert(ContextObj && "reading decl with no AST context");
7289   if (ID < NUM_PREDEF_DECL_IDS) {
7290     Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
7291     if (D) {
7292       // Track that we have merged the declaration with ID \p ID into the
7293       // pre-existing predefined declaration \p D.
7294       auto &Merged = KeyDecls[D->getCanonicalDecl()];
7295       if (Merged.empty())
7296         Merged.push_back(ID);
7297     }
7298     return D;
7299   }
7300 
7301   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7302 
7303   if (Index >= DeclsLoaded.size()) {
7304     assert(0 && "declaration ID out-of-range for AST file");
7305     Error("declaration ID out-of-range for AST file");
7306     return nullptr;
7307   }
7308 
7309   return DeclsLoaded[Index];
7310 }
7311 
7312 Decl *ASTReader::GetDecl(DeclID ID) {
7313   if (ID < NUM_PREDEF_DECL_IDS)
7314     return GetExistingDecl(ID);
7315 
7316   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7317 
7318   if (Index >= DeclsLoaded.size()) {
7319     assert(0 && "declaration ID out-of-range for AST file");
7320     Error("declaration ID out-of-range for AST file");
7321     return nullptr;
7322   }
7323 
7324   if (!DeclsLoaded[Index]) {
7325     ReadDeclRecord(ID);
7326     if (DeserializationListener)
7327       DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7328   }
7329 
7330   return DeclsLoaded[Index];
7331 }
7332 
7333 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
7334                                                   DeclID GlobalID) {
7335   if (GlobalID < NUM_PREDEF_DECL_IDS)
7336     return GlobalID;
7337 
7338   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7339   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7340   ModuleFile *Owner = I->second;
7341 
7342   llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7343     = M.GlobalToLocalDeclIDs.find(Owner);
7344   if (Pos == M.GlobalToLocalDeclIDs.end())
7345     return 0;
7346 
7347   return GlobalID - Owner->BaseDeclID + Pos->second;
7348 }
7349 
7350 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
7351                                             const RecordData &Record,
7352                                             unsigned &Idx) {
7353   if (Idx >= Record.size()) {
7354     Error("Corrupted AST file");
7355     return 0;
7356   }
7357 
7358   return getGlobalDeclID(F, Record[Idx++]);
7359 }
7360 
7361 /// Resolve the offset of a statement into a statement.
7362 ///
7363 /// This operation will read a new statement from the external
7364 /// source each time it is called, and is meant to be used via a
7365 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7366 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7367   // Switch case IDs are per Decl.
7368   ClearSwitchCaseIDs();
7369 
7370   // Offset here is a global offset across the entire chain.
7371   RecordLocation Loc = getLocalBitOffset(Offset);
7372   if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7373     Error(std::move(Err));
7374     return nullptr;
7375   }
7376   assert(NumCurrentElementsDeserializing == 0 &&
7377          "should not be called while already deserializing");
7378   Deserializing D(this);
7379   return ReadStmtFromStream(*Loc.F);
7380 }
7381 
7382 void ASTReader::FindExternalLexicalDecls(
7383     const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7384     SmallVectorImpl<Decl *> &Decls) {
7385   bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7386 
7387   auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
7388     assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7389     for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7390       auto K = (Decl::Kind)+LexicalDecls[I];
7391       if (!IsKindWeWant(K))
7392         continue;
7393 
7394       auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7395 
7396       // Don't add predefined declarations to the lexical context more
7397       // than once.
7398       if (ID < NUM_PREDEF_DECL_IDS) {
7399         if (PredefsVisited[ID])
7400           continue;
7401 
7402         PredefsVisited[ID] = true;
7403       }
7404 
7405       if (Decl *D = GetLocalDecl(*M, ID)) {
7406         assert(D->getKind() == K && "wrong kind for lexical decl");
7407         if (!DC->isDeclInLexicalTraversal(D))
7408           Decls.push_back(D);
7409       }
7410     }
7411   };
7412 
7413   if (isa<TranslationUnitDecl>(DC)) {
7414     for (auto Lexical : TULexicalDecls)
7415       Visit(Lexical.first, Lexical.second);
7416   } else {
7417     auto I = LexicalDecls.find(DC);
7418     if (I != LexicalDecls.end())
7419       Visit(I->second.first, I->second.second);
7420   }
7421 
7422   ++NumLexicalDeclContextsRead;
7423 }
7424 
7425 namespace {
7426 
7427 class DeclIDComp {
7428   ASTReader &Reader;
7429   ModuleFile &Mod;
7430 
7431 public:
7432   DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7433 
7434   bool operator()(LocalDeclID L, LocalDeclID R) const {
7435     SourceLocation LHS = getLocation(L);
7436     SourceLocation RHS = getLocation(R);
7437     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7438   }
7439 
7440   bool operator()(SourceLocation LHS, LocalDeclID R) const {
7441     SourceLocation RHS = getLocation(R);
7442     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7443   }
7444 
7445   bool operator()(LocalDeclID L, SourceLocation RHS) const {
7446     SourceLocation LHS = getLocation(L);
7447     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7448   }
7449 
7450   SourceLocation getLocation(LocalDeclID ID) const {
7451     return Reader.getSourceManager().getFileLoc(
7452             Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7453   }
7454 };
7455 
7456 } // namespace
7457 
7458 void ASTReader::FindFileRegionDecls(FileID File,
7459                                     unsigned Offset, unsigned Length,
7460                                     SmallVectorImpl<Decl *> &Decls) {
7461   SourceManager &SM = getSourceManager();
7462 
7463   llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7464   if (I == FileDeclIDs.end())
7465     return;
7466 
7467   FileDeclsInfo &DInfo = I->second;
7468   if (DInfo.Decls.empty())
7469     return;
7470 
7471   SourceLocation
7472     BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7473   SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7474 
7475   DeclIDComp DIDComp(*this, *DInfo.Mod);
7476   ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
7477       llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
7478   if (BeginIt != DInfo.Decls.begin())
7479     --BeginIt;
7480 
7481   // If we are pointing at a top-level decl inside an objc container, we need
7482   // to backtrack until we find it otherwise we will fail to report that the
7483   // region overlaps with an objc container.
7484   while (BeginIt != DInfo.Decls.begin() &&
7485          GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7486              ->isTopLevelDeclInObjCContainer())
7487     --BeginIt;
7488 
7489   ArrayRef<serialization::LocalDeclID>::iterator EndIt =
7490       llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
7491   if (EndIt != DInfo.Decls.end())
7492     ++EndIt;
7493 
7494   for (ArrayRef<serialization::LocalDeclID>::iterator
7495          DIt = BeginIt; DIt != EndIt; ++DIt)
7496     Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7497 }
7498 
7499 bool
7500 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7501                                           DeclarationName Name) {
7502   assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
7503          "DeclContext has no visible decls in storage");
7504   if (!Name)
7505     return false;
7506 
7507   auto It = Lookups.find(DC);
7508   if (It == Lookups.end())
7509     return false;
7510 
7511   Deserializing LookupResults(this);
7512 
7513   // Load the list of declarations.
7514   SmallVector<NamedDecl *, 64> Decls;
7515   for (DeclID ID : It->second.Table.find(Name)) {
7516     NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7517     if (ND->getDeclName() == Name)
7518       Decls.push_back(ND);
7519   }
7520 
7521   ++NumVisibleDeclContextsRead;
7522   SetExternalVisibleDeclsForName(DC, Name, Decls);
7523   return !Decls.empty();
7524 }
7525 
7526 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7527   if (!DC->hasExternalVisibleStorage())
7528     return;
7529 
7530   auto It = Lookups.find(DC);
7531   assert(It != Lookups.end() &&
7532          "have external visible storage but no lookup tables");
7533 
7534   DeclsMap Decls;
7535 
7536   for (DeclID ID : It->second.Table.findAll()) {
7537     NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7538     Decls[ND->getDeclName()].push_back(ND);
7539   }
7540 
7541   ++NumVisibleDeclContextsRead;
7542 
7543   for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7544     SetExternalVisibleDeclsForName(DC, I->first, I->second);
7545   }
7546   const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7547 }
7548 
7549 const serialization::reader::DeclContextLookupTable *
7550 ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7551   auto I = Lookups.find(Primary);
7552   return I == Lookups.end() ? nullptr : &I->second;
7553 }
7554 
7555 /// Under non-PCH compilation the consumer receives the objc methods
7556 /// before receiving the implementation, and codegen depends on this.
7557 /// We simulate this by deserializing and passing to consumer the methods of the
7558 /// implementation before passing the deserialized implementation decl.
7559 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7560                                        ASTConsumer *Consumer) {
7561   assert(ImplD && Consumer);
7562 
7563   for (auto *I : ImplD->methods())
7564     Consumer->HandleInterestingDecl(DeclGroupRef(I));
7565 
7566   Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7567 }
7568 
7569 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7570   if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7571     PassObjCImplDeclToConsumer(ImplD, Consumer);
7572   else
7573     Consumer->HandleInterestingDecl(DeclGroupRef(D));
7574 }
7575 
7576 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7577   this->Consumer = Consumer;
7578 
7579   if (Consumer)
7580     PassInterestingDeclsToConsumer();
7581 
7582   if (DeserializationListener)
7583     DeserializationListener->ReaderInitialized(this);
7584 }
7585 
7586 void ASTReader::PrintStats() {
7587   std::fprintf(stderr, "*** AST File Statistics:\n");
7588 
7589   unsigned NumTypesLoaded
7590     = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7591                                       QualType());
7592   unsigned NumDeclsLoaded
7593     = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
7594                                       (Decl *)nullptr);
7595   unsigned NumIdentifiersLoaded
7596     = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7597                                             IdentifiersLoaded.end(),
7598                                             (IdentifierInfo *)nullptr);
7599   unsigned NumMacrosLoaded
7600     = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7601                                        MacrosLoaded.end(),
7602                                        (MacroInfo *)nullptr);
7603   unsigned NumSelectorsLoaded
7604     = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7605                                           SelectorsLoaded.end(),
7606                                           Selector());
7607 
7608   if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7609     std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
7610                  NumSLocEntriesRead, TotalNumSLocEntries,
7611                  ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7612   if (!TypesLoaded.empty())
7613     std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
7614                  NumTypesLoaded, (unsigned)TypesLoaded.size(),
7615                  ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7616   if (!DeclsLoaded.empty())
7617     std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
7618                  NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7619                  ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7620   if (!IdentifiersLoaded.empty())
7621     std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
7622                  NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7623                  ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7624   if (!MacrosLoaded.empty())
7625     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
7626                  NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7627                  ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7628   if (!SelectorsLoaded.empty())
7629     std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
7630                  NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7631                  ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7632   if (TotalNumStatements)
7633     std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
7634                  NumStatementsRead, TotalNumStatements,
7635                  ((float)NumStatementsRead/TotalNumStatements * 100));
7636   if (TotalNumMacros)
7637     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
7638                  NumMacrosRead, TotalNumMacros,
7639                  ((float)NumMacrosRead/TotalNumMacros * 100));
7640   if (TotalLexicalDeclContexts)
7641     std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
7642                  NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7643                  ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7644                   * 100));
7645   if (TotalVisibleDeclContexts)
7646     std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
7647                  NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7648                  ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7649                   * 100));
7650   if (TotalNumMethodPoolEntries)
7651     std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
7652                  NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7653                  ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7654                   * 100));
7655   if (NumMethodPoolLookups)
7656     std::fprintf(stderr, "  %u/%u method pool lookups succeeded (%f%%)\n",
7657                  NumMethodPoolHits, NumMethodPoolLookups,
7658                  ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7659   if (NumMethodPoolTableLookups)
7660     std::fprintf(stderr, "  %u/%u method pool table lookups succeeded (%f%%)\n",
7661                  NumMethodPoolTableHits, NumMethodPoolTableLookups,
7662                  ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7663                   * 100.0));
7664   if (NumIdentifierLookupHits)
7665     std::fprintf(stderr,
7666                  "  %u / %u identifier table lookups succeeded (%f%%)\n",
7667                  NumIdentifierLookupHits, NumIdentifierLookups,
7668                  (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7669 
7670   if (GlobalIndex) {
7671     std::fprintf(stderr, "\n");
7672     GlobalIndex->printStats();
7673   }
7674 
7675   std::fprintf(stderr, "\n");
7676   dump();
7677   std::fprintf(stderr, "\n");
7678 }
7679 
7680 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
7681 LLVM_DUMP_METHOD static void
7682 dumpModuleIDMap(StringRef Name,
7683                 const ContinuousRangeMap<Key, ModuleFile *,
7684                                          InitialCapacity> &Map) {
7685   if (Map.begin() == Map.end())
7686     return;
7687 
7688   using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7689 
7690   llvm::errs() << Name << ":\n";
7691   for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7692        I != IEnd; ++I) {
7693     llvm::errs() << "  " << I->first << " -> " << I->second->FileName
7694       << "\n";
7695   }
7696 }
7697 
7698 LLVM_DUMP_METHOD void ASTReader::dump() {
7699   llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7700   dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7701   dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7702   dumpModuleIDMap("Global type map", GlobalTypeMap);
7703   dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7704   dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7705   dumpModuleIDMap("Global macro map", GlobalMacroMap);
7706   dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7707   dumpModuleIDMap("Global selector map", GlobalSelectorMap);
7708   dumpModuleIDMap("Global preprocessed entity map",
7709                   GlobalPreprocessedEntityMap);
7710 
7711   llvm::errs() << "\n*** PCH/Modules Loaded:";
7712   for (ModuleFile &M : ModuleMgr)
7713     M.dump();
7714 }
7715 
7716 /// Return the amount of memory used by memory buffers, breaking down
7717 /// by heap-backed versus mmap'ed memory.
7718 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7719   for (ModuleFile &I : ModuleMgr) {
7720     if (llvm::MemoryBuffer *buf = I.Buffer) {
7721       size_t bytes = buf->getBufferSize();
7722       switch (buf->getBufferKind()) {
7723         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7724           sizes.malloc_bytes += bytes;
7725           break;
7726         case llvm::MemoryBuffer::MemoryBuffer_MMap:
7727           sizes.mmap_bytes += bytes;
7728           break;
7729       }
7730     }
7731   }
7732 }
7733 
7734 void ASTReader::InitializeSema(Sema &S) {
7735   SemaObj = &S;
7736   S.addExternalSource(this);
7737 
7738   // Makes sure any declarations that were deserialized "too early"
7739   // still get added to the identifier's declaration chains.
7740   for (uint64_t ID : PreloadedDeclIDs) {
7741     NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7742     pushExternalDeclIntoScope(D, D->getDeclName());
7743   }
7744   PreloadedDeclIDs.clear();
7745 
7746   // FIXME: What happens if these are changed by a module import?
7747   if (!FPPragmaOptions.empty()) {
7748     assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7749     SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
7750   }
7751 
7752   SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7753   SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7754   SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
7755 
7756   UpdateSema();
7757 }
7758 
7759 void ASTReader::UpdateSema() {
7760   assert(SemaObj && "no Sema to update");
7761 
7762   // Load the offsets of the declarations that Sema references.
7763   // They will be lazily deserialized when needed.
7764   if (!SemaDeclRefs.empty()) {
7765     assert(SemaDeclRefs.size() % 3 == 0);
7766     for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
7767       if (!SemaObj->StdNamespace)
7768         SemaObj->StdNamespace = SemaDeclRefs[I];
7769       if (!SemaObj->StdBadAlloc)
7770         SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7771       if (!SemaObj->StdAlignValT)
7772         SemaObj->StdAlignValT = SemaDeclRefs[I+2];
7773     }
7774     SemaDeclRefs.clear();
7775   }
7776 
7777   // Update the state of pragmas. Use the same API as if we had encountered the
7778   // pragma in the source.
7779   if(OptimizeOffPragmaLocation.isValid())
7780     SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
7781   if (PragmaMSStructState != -1)
7782     SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
7783   if (PointersToMembersPragmaLocation.isValid()) {
7784     SemaObj->ActOnPragmaMSPointersToMembers(
7785         (LangOptions::PragmaMSPointersToMembersKind)
7786             PragmaMSPointersToMembersState,
7787         PointersToMembersPragmaLocation);
7788   }
7789   SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
7790 
7791   if (PragmaPackCurrentValue) {
7792     // The bottom of the stack might have a default value. It must be adjusted
7793     // to the current value to ensure that the packing state is preserved after
7794     // popping entries that were included/imported from a PCH/module.
7795     bool DropFirst = false;
7796     if (!PragmaPackStack.empty() &&
7797         PragmaPackStack.front().Location.isInvalid()) {
7798       assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7799              "Expected a default alignment value");
7800       SemaObj->PackStack.Stack.emplace_back(
7801           PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
7802           SemaObj->PackStack.CurrentPragmaLocation,
7803           PragmaPackStack.front().PushLocation);
7804       DropFirst = true;
7805     }
7806     for (const auto &Entry :
7807          llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7808       SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
7809                                             Entry.Location, Entry.PushLocation);
7810     if (PragmaPackCurrentLocation.isInvalid()) {
7811       assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7812              "Expected a default alignment value");
7813       // Keep the current values.
7814     } else {
7815       SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7816       SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7817     }
7818   }
7819 }
7820 
7821 IdentifierInfo *ASTReader::get(StringRef Name) {
7822   // Note that we are loading an identifier.
7823   Deserializing AnIdentifier(this);
7824 
7825   IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
7826                                   NumIdentifierLookups,
7827                                   NumIdentifierLookupHits);
7828 
7829   // We don't need to do identifier table lookups in C++ modules (we preload
7830   // all interesting declarations, and don't need to use the scope for name
7831   // lookups). Perform the lookup in PCH files, though, since we don't build
7832   // a complete initial identifier table if we're carrying on from a PCH.
7833   if (PP.getLangOpts().CPlusPlus) {
7834     for (auto F : ModuleMgr.pch_modules())
7835       if (Visitor(*F))
7836         break;
7837   } else {
7838     // If there is a global index, look there first to determine which modules
7839     // provably do not have any results for this identifier.
7840     GlobalModuleIndex::HitSet Hits;
7841     GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7842     if (!loadGlobalIndex()) {
7843       if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7844         HitsPtr = &Hits;
7845       }
7846     }
7847 
7848     ModuleMgr.visit(Visitor, HitsPtr);
7849   }
7850 
7851   IdentifierInfo *II = Visitor.getIdentifierInfo();
7852   markIdentifierUpToDate(II);
7853   return II;
7854 }
7855 
7856 namespace clang {
7857 
7858   /// An identifier-lookup iterator that enumerates all of the
7859   /// identifiers stored within a set of AST files.
7860   class ASTIdentifierIterator : public IdentifierIterator {
7861     /// The AST reader whose identifiers are being enumerated.
7862     const ASTReader &Reader;
7863 
7864     /// The current index into the chain of AST files stored in
7865     /// the AST reader.
7866     unsigned Index;
7867 
7868     /// The current position within the identifier lookup table
7869     /// of the current AST file.
7870     ASTIdentifierLookupTable::key_iterator Current;
7871 
7872     /// The end position within the identifier lookup table of
7873     /// the current AST file.
7874     ASTIdentifierLookupTable::key_iterator End;
7875 
7876     /// Whether to skip any modules in the ASTReader.
7877     bool SkipModules;
7878 
7879   public:
7880     explicit ASTIdentifierIterator(const ASTReader &Reader,
7881                                    bool SkipModules = false);
7882 
7883     StringRef Next() override;
7884   };
7885 
7886 } // namespace clang
7887 
7888 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7889                                              bool SkipModules)
7890     : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
7891 }
7892 
7893 StringRef ASTIdentifierIterator::Next() {
7894   while (Current == End) {
7895     // If we have exhausted all of our AST files, we're done.
7896     if (Index == 0)
7897       return StringRef();
7898 
7899     --Index;
7900     ModuleFile &F = Reader.ModuleMgr[Index];
7901     if (SkipModules && F.isModule())
7902       continue;
7903 
7904     ASTIdentifierLookupTable *IdTable =
7905         (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
7906     Current = IdTable->key_begin();
7907     End = IdTable->key_end();
7908   }
7909 
7910   // We have any identifiers remaining in the current AST file; return
7911   // the next one.
7912   StringRef Result = *Current;
7913   ++Current;
7914   return Result;
7915 }
7916 
7917 namespace {
7918 
7919 /// A utility for appending two IdentifierIterators.
7920 class ChainedIdentifierIterator : public IdentifierIterator {
7921   std::unique_ptr<IdentifierIterator> Current;
7922   std::unique_ptr<IdentifierIterator> Queued;
7923 
7924 public:
7925   ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7926                             std::unique_ptr<IdentifierIterator> Second)
7927       : Current(std::move(First)), Queued(std::move(Second)) {}
7928 
7929   StringRef Next() override {
7930     if (!Current)
7931       return StringRef();
7932 
7933     StringRef result = Current->Next();
7934     if (!result.empty())
7935       return result;
7936 
7937     // Try the queued iterator, which may itself be empty.
7938     Current.reset();
7939     std::swap(Current, Queued);
7940     return Next();
7941   }
7942 };
7943 
7944 } // namespace
7945 
7946 IdentifierIterator *ASTReader::getIdentifiers() {
7947   if (!loadGlobalIndex()) {
7948     std::unique_ptr<IdentifierIterator> ReaderIter(
7949         new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7950     std::unique_ptr<IdentifierIterator> ModulesIter(
7951         GlobalIndex->createIdentifierIterator());
7952     return new ChainedIdentifierIterator(std::move(ReaderIter),
7953                                          std::move(ModulesIter));
7954   }
7955 
7956   return new ASTIdentifierIterator(*this);
7957 }
7958 
7959 namespace clang {
7960 namespace serialization {
7961 
7962   class ReadMethodPoolVisitor {
7963     ASTReader &Reader;
7964     Selector Sel;
7965     unsigned PriorGeneration;
7966     unsigned InstanceBits = 0;
7967     unsigned FactoryBits = 0;
7968     bool InstanceHasMoreThanOneDecl = false;
7969     bool FactoryHasMoreThanOneDecl = false;
7970     SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7971     SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
7972 
7973   public:
7974     ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
7975                           unsigned PriorGeneration)
7976         : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
7977 
7978     bool operator()(ModuleFile &M) {
7979       if (!M.SelectorLookupTable)
7980         return false;
7981 
7982       // If we've already searched this module file, skip it now.
7983       if (M.Generation <= PriorGeneration)
7984         return true;
7985 
7986       ++Reader.NumMethodPoolTableLookups;
7987       ASTSelectorLookupTable *PoolTable
7988         = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7989       ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
7990       if (Pos == PoolTable->end())
7991         return false;
7992 
7993       ++Reader.NumMethodPoolTableHits;
7994       ++Reader.NumSelectorsRead;
7995       // FIXME: Not quite happy with the statistics here. We probably should
7996       // disable this tracking when called via LoadSelector.
7997       // Also, should entries without methods count as misses?
7998       ++Reader.NumMethodPoolEntriesRead;
7999       ASTSelectorLookupTrait::data_type Data = *Pos;
8000       if (Reader.DeserializationListener)
8001         Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
8002 
8003       InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
8004       FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
8005       InstanceBits = Data.InstanceBits;
8006       FactoryBits = Data.FactoryBits;
8007       InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8008       FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
8009       return true;
8010     }
8011 
8012     /// Retrieve the instance methods found by this visitor.
8013     ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8014       return InstanceMethods;
8015     }
8016 
8017     /// Retrieve the instance methods found by this visitor.
8018     ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
8019       return FactoryMethods;
8020     }
8021 
8022     unsigned getInstanceBits() const { return InstanceBits; }
8023     unsigned getFactoryBits() const { return FactoryBits; }
8024 
8025     bool instanceHasMoreThanOneDecl() const {
8026       return InstanceHasMoreThanOneDecl;
8027     }
8028 
8029     bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
8030   };
8031 
8032 } // namespace serialization
8033 } // namespace clang
8034 
8035 /// Add the given set of methods to the method list.
8036 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8037                              ObjCMethodList &List) {
8038   for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
8039     S.addMethodToGlobalList(&List, Methods[I]);
8040   }
8041 }
8042 
8043 void ASTReader::ReadMethodPool(Selector Sel) {
8044   // Get the selector generation and update it to the current generation.
8045   unsigned &Generation = SelectorGeneration[Sel];
8046   unsigned PriorGeneration = Generation;
8047   Generation = getGeneration();
8048   SelectorOutOfDate[Sel] = false;
8049 
8050   // Search for methods defined with this selector.
8051   ++NumMethodPoolLookups;
8052   ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
8053   ModuleMgr.visit(Visitor);
8054 
8055   if (Visitor.getInstanceMethods().empty() &&
8056       Visitor.getFactoryMethods().empty())
8057     return;
8058 
8059   ++NumMethodPoolHits;
8060 
8061   if (!getSema())
8062     return;
8063 
8064   Sema &S = *getSema();
8065   Sema::GlobalMethodPool::iterator Pos
8066     = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
8067 
8068   Pos->second.first.setBits(Visitor.getInstanceBits());
8069   Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
8070   Pos->second.second.setBits(Visitor.getFactoryBits());
8071   Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
8072 
8073   // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8074   // when building a module we keep every method individually and may need to
8075   // update hasMoreThanOneDecl as we add the methods.
8076   addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8077   addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
8078 }
8079 
8080 void ASTReader::updateOutOfDateSelector(Selector Sel) {
8081   if (SelectorOutOfDate[Sel])
8082     ReadMethodPool(Sel);
8083 }
8084 
8085 void ASTReader::ReadKnownNamespaces(
8086                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8087   Namespaces.clear();
8088 
8089   for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8090     if (NamespaceDecl *Namespace
8091                 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
8092       Namespaces.push_back(Namespace);
8093   }
8094 }
8095 
8096 void ASTReader::ReadUndefinedButUsed(
8097     llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
8098   for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
8099     NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
8100     SourceLocation Loc =
8101         SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
8102     Undefined.insert(std::make_pair(D, Loc));
8103   }
8104 }
8105 
8106 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8107     FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8108                                                      Exprs) {
8109   for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
8110     FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
8111     uint64_t Count = DelayedDeleteExprs[Idx++];
8112     for (uint64_t C = 0; C < Count; ++C) {
8113       SourceLocation DeleteLoc =
8114           SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8115       const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8116       Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8117     }
8118   }
8119 }
8120 
8121 void ASTReader::ReadTentativeDefinitions(
8122                   SmallVectorImpl<VarDecl *> &TentativeDefs) {
8123   for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8124     VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
8125     if (Var)
8126       TentativeDefs.push_back(Var);
8127   }
8128   TentativeDefinitions.clear();
8129 }
8130 
8131 void ASTReader::ReadUnusedFileScopedDecls(
8132                                SmallVectorImpl<const DeclaratorDecl *> &Decls) {
8133   for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8134     DeclaratorDecl *D
8135       = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
8136     if (D)
8137       Decls.push_back(D);
8138   }
8139   UnusedFileScopedDecls.clear();
8140 }
8141 
8142 void ASTReader::ReadDelegatingConstructors(
8143                                  SmallVectorImpl<CXXConstructorDecl *> &Decls) {
8144   for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8145     CXXConstructorDecl *D
8146       = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
8147     if (D)
8148       Decls.push_back(D);
8149   }
8150   DelegatingCtorDecls.clear();
8151 }
8152 
8153 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
8154   for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8155     TypedefNameDecl *D
8156       = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
8157     if (D)
8158       Decls.push_back(D);
8159   }
8160   ExtVectorDecls.clear();
8161 }
8162 
8163 void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8164     llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
8165   for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8166        ++I) {
8167     TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8168         GetDecl(UnusedLocalTypedefNameCandidates[I]));
8169     if (D)
8170       Decls.insert(D);
8171   }
8172   UnusedLocalTypedefNameCandidates.clear();
8173 }
8174 
8175 void ASTReader::ReadReferencedSelectors(
8176        SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
8177   if (ReferencedSelectorsData.empty())
8178     return;
8179 
8180   // If there are @selector references added them to its pool. This is for
8181   // implementation of -Wselector.
8182   unsigned int DataSize = ReferencedSelectorsData.size()-1;
8183   unsigned I = 0;
8184   while (I < DataSize) {
8185     Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8186     SourceLocation SelLoc
8187       = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8188     Sels.push_back(std::make_pair(Sel, SelLoc));
8189   }
8190   ReferencedSelectorsData.clear();
8191 }
8192 
8193 void ASTReader::ReadWeakUndeclaredIdentifiers(
8194        SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
8195   if (WeakUndeclaredIdentifiers.empty())
8196     return;
8197 
8198   for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
8199     IdentifierInfo *WeakId
8200       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8201     IdentifierInfo *AliasId
8202       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8203     SourceLocation Loc
8204       = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8205     bool Used = WeakUndeclaredIdentifiers[I++];
8206     WeakInfo WI(AliasId, Loc);
8207     WI.setUsed(Used);
8208     WeakIDs.push_back(std::make_pair(WeakId, WI));
8209   }
8210   WeakUndeclaredIdentifiers.clear();
8211 }
8212 
8213 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8214   for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8215     ExternalVTableUse VT;
8216     VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8217     VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8218     VT.DefinitionRequired = VTableUses[Idx++];
8219     VTables.push_back(VT);
8220   }
8221 
8222   VTableUses.clear();
8223 }
8224 
8225 void ASTReader::ReadPendingInstantiations(
8226        SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
8227   for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8228     ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
8229     SourceLocation Loc
8230       = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8231 
8232     Pending.push_back(std::make_pair(D, Loc));
8233   }
8234   PendingInstantiations.clear();
8235 }
8236 
8237 void ASTReader::ReadLateParsedTemplates(
8238     llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8239         &LPTMap) {
8240   for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8241        /* In loop */) {
8242     FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
8243 
8244     auto LT = std::make_unique<LateParsedTemplate>();
8245     LT->D = GetDecl(LateParsedTemplates[Idx++]);
8246 
8247     ModuleFile *F = getOwningModuleFile(LT->D);
8248     assert(F && "No module");
8249 
8250     unsigned TokN = LateParsedTemplates[Idx++];
8251     LT->Toks.reserve(TokN);
8252     for (unsigned T = 0; T < TokN; ++T)
8253       LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8254 
8255     LPTMap.insert(std::make_pair(FD, std::move(LT)));
8256   }
8257 
8258   LateParsedTemplates.clear();
8259 }
8260 
8261 void ASTReader::LoadSelector(Selector Sel) {
8262   // It would be complicated to avoid reading the methods anyway. So don't.
8263   ReadMethodPool(Sel);
8264 }
8265 
8266 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8267   assert(ID && "Non-zero identifier ID required");
8268   assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8269   IdentifiersLoaded[ID - 1] = II;
8270   if (DeserializationListener)
8271     DeserializationListener->IdentifierRead(ID, II);
8272 }
8273 
8274 /// Set the globally-visible declarations associated with the given
8275 /// identifier.
8276 ///
8277 /// If the AST reader is currently in a state where the given declaration IDs
8278 /// cannot safely be resolved, they are queued until it is safe to resolve
8279 /// them.
8280 ///
8281 /// \param II an IdentifierInfo that refers to one or more globally-visible
8282 /// declarations.
8283 ///
8284 /// \param DeclIDs the set of declaration IDs with the name @p II that are
8285 /// visible at global scope.
8286 ///
8287 /// \param Decls if non-null, this vector will be populated with the set of
8288 /// deserialized declarations. These declarations will not be pushed into
8289 /// scope.
8290 void
8291 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8292                               const SmallVectorImpl<uint32_t> &DeclIDs,
8293                                    SmallVectorImpl<Decl *> *Decls) {
8294   if (NumCurrentElementsDeserializing && !Decls) {
8295     PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
8296     return;
8297   }
8298 
8299   for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
8300     if (!SemaObj) {
8301       // Queue this declaration so that it will be added to the
8302       // translation unit scope and identifier's declaration chain
8303       // once a Sema object is known.
8304       PreloadedDeclIDs.push_back(DeclIDs[I]);
8305       continue;
8306     }
8307 
8308     NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8309 
8310     // If we're simply supposed to record the declarations, do so now.
8311     if (Decls) {
8312       Decls->push_back(D);
8313       continue;
8314     }
8315 
8316     // Introduce this declaration into the translation-unit scope
8317     // and add it to the declaration chain for this identifier, so
8318     // that (unqualified) name lookup will find it.
8319     pushExternalDeclIntoScope(D, II);
8320   }
8321 }
8322 
8323 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
8324   if (ID == 0)
8325     return nullptr;
8326 
8327   if (IdentifiersLoaded.empty()) {
8328     Error("no identifier table in AST file");
8329     return nullptr;
8330   }
8331 
8332   ID -= 1;
8333   if (!IdentifiersLoaded[ID]) {
8334     GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8335     assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8336     ModuleFile *M = I->second;
8337     unsigned Index = ID - M->BaseIdentifierID;
8338     const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8339 
8340     // All of the strings in the AST file are preceded by a 16-bit length.
8341     // Extract that 16-bit length to avoid having to execute strlen().
8342     // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8343     //  unsigned integers.  This is important to avoid integer overflow when
8344     //  we cast them to 'unsigned'.
8345     const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8346     unsigned StrLen = (((unsigned) StrLenPtr[0])
8347                        | (((unsigned) StrLenPtr[1]) << 8)) - 1;
8348     auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8349     IdentifiersLoaded[ID] = &II;
8350     markIdentifierFromAST(*this,  II);
8351     if (DeserializationListener)
8352       DeserializationListener->IdentifierRead(ID + 1, &II);
8353   }
8354 
8355   return IdentifiersLoaded[ID];
8356 }
8357 
8358 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8359   return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
8360 }
8361 
8362 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8363   if (LocalID < NUM_PREDEF_IDENT_IDS)
8364     return LocalID;
8365 
8366   if (!M.ModuleOffsetMap.empty())
8367     ReadModuleOffsetMap(M);
8368 
8369   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8370     = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
8371   assert(I != M.IdentifierRemap.end()
8372          && "Invalid index into identifier index remap");
8373 
8374   return LocalID + I->second;
8375 }
8376 
8377 MacroInfo *ASTReader::getMacro(MacroID ID) {
8378   if (ID == 0)
8379     return nullptr;
8380 
8381   if (MacrosLoaded.empty()) {
8382     Error("no macro table in AST file");
8383     return nullptr;
8384   }
8385 
8386   ID -= NUM_PREDEF_MACRO_IDS;
8387   if (!MacrosLoaded[ID]) {
8388     GlobalMacroMapType::iterator I
8389       = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8390     assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8391     ModuleFile *M = I->second;
8392     unsigned Index = ID - M->BaseMacroID;
8393     MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
8394 
8395     if (DeserializationListener)
8396       DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8397                                          MacrosLoaded[ID]);
8398   }
8399 
8400   return MacrosLoaded[ID];
8401 }
8402 
8403 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8404   if (LocalID < NUM_PREDEF_MACRO_IDS)
8405     return LocalID;
8406 
8407   if (!M.ModuleOffsetMap.empty())
8408     ReadModuleOffsetMap(M);
8409 
8410   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8411     = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8412   assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8413 
8414   return LocalID + I->second;
8415 }
8416 
8417 serialization::SubmoduleID
8418 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8419   if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8420     return LocalID;
8421 
8422   if (!M.ModuleOffsetMap.empty())
8423     ReadModuleOffsetMap(M);
8424 
8425   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8426     = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
8427   assert(I != M.SubmoduleRemap.end()
8428          && "Invalid index into submodule index remap");
8429 
8430   return LocalID + I->second;
8431 }
8432 
8433 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8434   if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8435     assert(GlobalID == 0 && "Unhandled global submodule ID");
8436     return nullptr;
8437   }
8438 
8439   if (GlobalID > SubmodulesLoaded.size()) {
8440     Error("submodule ID out of range in AST file");
8441     return nullptr;
8442   }
8443 
8444   return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8445 }
8446 
8447 Module *ASTReader::getModule(unsigned ID) {
8448   return getSubmodule(ID);
8449 }
8450 
8451 bool ASTReader::DeclIsFromPCHWithObjectFile(const Decl *D) {
8452   ModuleFile *MF = getOwningModuleFile(D);
8453   return MF && MF->PCHHasObjectFile;
8454 }
8455 
8456 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8457   if (ID & 1) {
8458     // It's a module, look it up by submodule ID.
8459     auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8460     return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8461   } else {
8462     // It's a prefix (preamble, PCH, ...). Look it up by index.
8463     unsigned IndexFromEnd = ID >> 1;
8464     assert(IndexFromEnd && "got reference to unknown module file");
8465     return getModuleManager().pch_modules().end()[-IndexFromEnd];
8466   }
8467 }
8468 
8469 unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8470   if (!F)
8471     return 1;
8472 
8473   // For a file representing a module, use the submodule ID of the top-level
8474   // module as the file ID. For any other kind of file, the number of such
8475   // files loaded beforehand will be the same on reload.
8476   // FIXME: Is this true even if we have an explicit module file and a PCH?
8477   if (F->isModule())
8478     return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8479 
8480   auto PCHModules = getModuleManager().pch_modules();
8481   auto I = llvm::find(PCHModules, F);
8482   assert(I != PCHModules.end() && "emitting reference to unknown file");
8483   return (I - PCHModules.end()) << 1;
8484 }
8485 
8486 llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8487 ASTReader::getSourceDescriptor(unsigned ID) {
8488   if (const Module *M = getSubmodule(ID))
8489     return ExternalASTSource::ASTSourceDescriptor(*M);
8490 
8491   // If there is only a single PCH, return it instead.
8492   // Chained PCH are not supported.
8493   const auto &PCHChain = ModuleMgr.pch_modules();
8494   if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
8495     ModuleFile &MF = ModuleMgr.getPrimaryModule();
8496     StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
8497     StringRef FileName = llvm::sys::path::filename(MF.FileName);
8498     return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8499                                           MF.Signature);
8500   }
8501   return None;
8502 }
8503 
8504 ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
8505   auto I = DefinitionSource.find(FD);
8506   if (I == DefinitionSource.end())
8507     return EK_ReplyHazy;
8508   return I->second ? EK_Never : EK_Always;
8509 }
8510 
8511 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8512   return DecodeSelector(getGlobalSelectorID(M, LocalID));
8513 }
8514 
8515 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8516   if (ID == 0)
8517     return Selector();
8518 
8519   if (ID > SelectorsLoaded.size()) {
8520     Error("selector ID out of range in AST file");
8521     return Selector();
8522   }
8523 
8524   if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
8525     // Load this selector from the selector table.
8526     GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8527     assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8528     ModuleFile &M = *I->second;
8529     ASTSelectorLookupTrait Trait(*this, M);
8530     unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8531     SelectorsLoaded[ID - 1] =
8532       Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8533     if (DeserializationListener)
8534       DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8535   }
8536 
8537   return SelectorsLoaded[ID - 1];
8538 }
8539 
8540 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8541   return DecodeSelector(ID);
8542 }
8543 
8544 uint32_t ASTReader::GetNumExternalSelectors() {
8545   // ID 0 (the null selector) is considered an external selector.
8546   return getTotalNumSelectors() + 1;
8547 }
8548 
8549 serialization::SelectorID
8550 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8551   if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8552     return LocalID;
8553 
8554   if (!M.ModuleOffsetMap.empty())
8555     ReadModuleOffsetMap(M);
8556 
8557   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8558     = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
8559   assert(I != M.SelectorRemap.end()
8560          && "Invalid index into selector index remap");
8561 
8562   return LocalID + I->second;
8563 }
8564 
8565 DeclarationNameLoc
8566 ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
8567   DeclarationNameLoc DNLoc;
8568   switch (Name.getNameKind()) {
8569   case DeclarationName::CXXConstructorName:
8570   case DeclarationName::CXXDestructorName:
8571   case DeclarationName::CXXConversionFunctionName:
8572     DNLoc.NamedType.TInfo = readTypeSourceInfo();
8573     break;
8574 
8575   case DeclarationName::CXXOperatorName:
8576     DNLoc.CXXOperatorName.BeginOpNameLoc
8577       = readSourceLocation().getRawEncoding();
8578     DNLoc.CXXOperatorName.EndOpNameLoc
8579       = readSourceLocation().getRawEncoding();
8580     break;
8581 
8582   case DeclarationName::CXXLiteralOperatorName:
8583     DNLoc.CXXLiteralOperatorName.OpNameLoc
8584       = readSourceLocation().getRawEncoding();
8585     break;
8586 
8587   case DeclarationName::Identifier:
8588   case DeclarationName::ObjCZeroArgSelector:
8589   case DeclarationName::ObjCOneArgSelector:
8590   case DeclarationName::ObjCMultiArgSelector:
8591   case DeclarationName::CXXUsingDirective:
8592   case DeclarationName::CXXDeductionGuideName:
8593     break;
8594   }
8595   return DNLoc;
8596 }
8597 
8598 DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
8599   DeclarationNameInfo NameInfo;
8600   NameInfo.setName(readDeclarationName());
8601   NameInfo.setLoc(readSourceLocation());
8602   NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
8603   return NameInfo;
8604 }
8605 
8606 void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {
8607   Info.QualifierLoc = readNestedNameSpecifierLoc();
8608   unsigned NumTPLists = readInt();
8609   Info.NumTemplParamLists = NumTPLists;
8610   if (NumTPLists) {
8611     Info.TemplParamLists =
8612         new (getContext()) TemplateParameterList *[NumTPLists];
8613     for (unsigned i = 0; i != NumTPLists; ++i)
8614       Info.TemplParamLists[i] = readTemplateParameterList();
8615   }
8616 }
8617 
8618 TemplateParameterList *
8619 ASTRecordReader::readTemplateParameterList() {
8620   SourceLocation TemplateLoc = readSourceLocation();
8621   SourceLocation LAngleLoc = readSourceLocation();
8622   SourceLocation RAngleLoc = readSourceLocation();
8623 
8624   unsigned NumParams = readInt();
8625   SmallVector<NamedDecl *, 16> Params;
8626   Params.reserve(NumParams);
8627   while (NumParams--)
8628     Params.push_back(readDeclAs<NamedDecl>());
8629 
8630   bool HasRequiresClause = readBool();
8631   Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
8632 
8633   TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8634       getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
8635   return TemplateParams;
8636 }
8637 
8638 void ASTRecordReader::readTemplateArgumentList(
8639                         SmallVectorImpl<TemplateArgument> &TemplArgs,
8640                         bool Canonicalize) {
8641   unsigned NumTemplateArgs = readInt();
8642   TemplArgs.reserve(NumTemplateArgs);
8643   while (NumTemplateArgs--)
8644     TemplArgs.push_back(readTemplateArgument(Canonicalize));
8645 }
8646 
8647 /// Read a UnresolvedSet structure.
8648 void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {
8649   unsigned NumDecls = readInt();
8650   Set.reserve(getContext(), NumDecls);
8651   while (NumDecls--) {
8652     DeclID ID = readDeclID();
8653     AccessSpecifier AS = (AccessSpecifier) readInt();
8654     Set.addLazyDecl(getContext(), ID, AS);
8655   }
8656 }
8657 
8658 CXXBaseSpecifier
8659 ASTRecordReader::readCXXBaseSpecifier() {
8660   bool isVirtual = readBool();
8661   bool isBaseOfClass = readBool();
8662   AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
8663   bool inheritConstructors = readBool();
8664   TypeSourceInfo *TInfo = readTypeSourceInfo();
8665   SourceRange Range = readSourceRange();
8666   SourceLocation EllipsisLoc = readSourceLocation();
8667   CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
8668                           EllipsisLoc);
8669   Result.setInheritConstructors(inheritConstructors);
8670   return Result;
8671 }
8672 
8673 CXXCtorInitializer **
8674 ASTRecordReader::readCXXCtorInitializers() {
8675   ASTContext &Context = getContext();
8676   unsigned NumInitializers = readInt();
8677   assert(NumInitializers && "wrote ctor initializers but have no inits");
8678   auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8679   for (unsigned i = 0; i != NumInitializers; ++i) {
8680     TypeSourceInfo *TInfo = nullptr;
8681     bool IsBaseVirtual = false;
8682     FieldDecl *Member = nullptr;
8683     IndirectFieldDecl *IndirectMember = nullptr;
8684 
8685     CtorInitializerType Type = (CtorInitializerType) readInt();
8686     switch (Type) {
8687     case CTOR_INITIALIZER_BASE:
8688       TInfo = readTypeSourceInfo();
8689       IsBaseVirtual = readBool();
8690       break;
8691 
8692     case CTOR_INITIALIZER_DELEGATING:
8693       TInfo = readTypeSourceInfo();
8694       break;
8695 
8696      case CTOR_INITIALIZER_MEMBER:
8697       Member = readDeclAs<FieldDecl>();
8698       break;
8699 
8700      case CTOR_INITIALIZER_INDIRECT_MEMBER:
8701       IndirectMember = readDeclAs<IndirectFieldDecl>();
8702       break;
8703     }
8704 
8705     SourceLocation MemberOrEllipsisLoc = readSourceLocation();
8706     Expr *Init = readExpr();
8707     SourceLocation LParenLoc = readSourceLocation();
8708     SourceLocation RParenLoc = readSourceLocation();
8709 
8710     CXXCtorInitializer *BOMInit;
8711     if (Type == CTOR_INITIALIZER_BASE)
8712       BOMInit = new (Context)
8713           CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8714                              RParenLoc, MemberOrEllipsisLoc);
8715     else if (Type == CTOR_INITIALIZER_DELEGATING)
8716       BOMInit = new (Context)
8717           CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
8718     else if (Member)
8719       BOMInit = new (Context)
8720           CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8721                              Init, RParenLoc);
8722     else
8723       BOMInit = new (Context)
8724           CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8725                              LParenLoc, Init, RParenLoc);
8726 
8727     if (/*IsWritten*/readBool()) {
8728       unsigned SourceOrder = readInt();
8729       BOMInit->setSourceOrder(SourceOrder);
8730     }
8731 
8732     CtorInitializers[i] = BOMInit;
8733   }
8734 
8735   return CtorInitializers;
8736 }
8737 
8738 NestedNameSpecifierLoc
8739 ASTRecordReader::readNestedNameSpecifierLoc() {
8740   ASTContext &Context = getContext();
8741   unsigned N = readInt();
8742   NestedNameSpecifierLocBuilder Builder;
8743   for (unsigned I = 0; I != N; ++I) {
8744     auto Kind = readNestedNameSpecifierKind();
8745     switch (Kind) {
8746     case NestedNameSpecifier::Identifier: {
8747       IdentifierInfo *II = readIdentifier();
8748       SourceRange Range = readSourceRange();
8749       Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8750       break;
8751     }
8752 
8753     case NestedNameSpecifier::Namespace: {
8754       NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
8755       SourceRange Range = readSourceRange();
8756       Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8757       break;
8758     }
8759 
8760     case NestedNameSpecifier::NamespaceAlias: {
8761       NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
8762       SourceRange Range = readSourceRange();
8763       Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8764       break;
8765     }
8766 
8767     case NestedNameSpecifier::TypeSpec:
8768     case NestedNameSpecifier::TypeSpecWithTemplate: {
8769       bool Template = readBool();
8770       TypeSourceInfo *T = readTypeSourceInfo();
8771       if (!T)
8772         return NestedNameSpecifierLoc();
8773       SourceLocation ColonColonLoc = readSourceLocation();
8774 
8775       // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8776       Builder.Extend(Context,
8777                      Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8778                      T->getTypeLoc(), ColonColonLoc);
8779       break;
8780     }
8781 
8782     case NestedNameSpecifier::Global: {
8783       SourceLocation ColonColonLoc = readSourceLocation();
8784       Builder.MakeGlobal(Context, ColonColonLoc);
8785       break;
8786     }
8787 
8788     case NestedNameSpecifier::Super: {
8789       CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
8790       SourceRange Range = readSourceRange();
8791       Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8792       break;
8793     }
8794     }
8795   }
8796 
8797   return Builder.getWithLocInContext(Context);
8798 }
8799 
8800 SourceRange
8801 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8802                            unsigned &Idx) {
8803   SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8804   SourceLocation end = ReadSourceLocation(F, Record, Idx);
8805   return SourceRange(beg, end);
8806 }
8807 
8808 static FixedPointSemantics
8809 ReadFixedPointSemantics(const SmallVectorImpl<uint64_t> &Record,
8810                         unsigned &Idx) {
8811   unsigned Width = Record[Idx++];
8812   unsigned Scale = Record[Idx++];
8813   uint64_t Tmp = Record[Idx++];
8814   bool IsSigned = Tmp & 0x1;
8815   bool IsSaturated = Tmp & 0x2;
8816   bool HasUnsignedPadding = Tmp & 0x4;
8817   return FixedPointSemantics(Width, Scale, IsSigned, IsSaturated,
8818                              HasUnsignedPadding);
8819 }
8820 
8821 static const llvm::fltSemantics &
8822 readAPFloatSemantics(ASTRecordReader &reader) {
8823   return llvm::APFloatBase::EnumToSemantics(
8824     static_cast<llvm::APFloatBase::Semantics>(reader.readInt()));
8825 }
8826 
8827 APValue ASTRecordReader::readAPValue() {
8828   unsigned Kind = readInt();
8829   switch ((APValue::ValueKind) Kind) {
8830   case APValue::None:
8831     return APValue();
8832   case APValue::Indeterminate:
8833     return APValue::IndeterminateValue();
8834   case APValue::Int:
8835     return APValue(readAPSInt());
8836   case APValue::Float: {
8837     const llvm::fltSemantics &FloatSema = readAPFloatSemantics(*this);
8838     return APValue(readAPFloat(FloatSema));
8839   }
8840   case APValue::FixedPoint: {
8841     FixedPointSemantics FPSema = ReadFixedPointSemantics(Record, Idx);
8842     return APValue(APFixedPoint(readAPInt(), FPSema));
8843   }
8844   case APValue::ComplexInt: {
8845     llvm::APSInt First = readAPSInt();
8846     return APValue(std::move(First), readAPSInt());
8847   }
8848   case APValue::ComplexFloat: {
8849     const llvm::fltSemantics &FloatSema1 = readAPFloatSemantics(*this);
8850     llvm::APFloat First = readAPFloat(FloatSema1);
8851     const llvm::fltSemantics &FloatSema2 = readAPFloatSemantics(*this);
8852     return APValue(std::move(First), readAPFloat(FloatSema2));
8853   }
8854   case APValue::LValue:
8855   case APValue::Vector:
8856   case APValue::Array:
8857   case APValue::Struct:
8858   case APValue::Union:
8859   case APValue::MemberPointer:
8860   case APValue::AddrLabelDiff:
8861     // TODO : Handle all these APValue::ValueKind.
8862     return APValue();
8863   }
8864   llvm_unreachable("Invalid APValue::ValueKind");
8865 }
8866 
8867 /// Read a floating-point value
8868 llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
8869   return llvm::APFloat(Sem, readAPInt());
8870 }
8871 
8872 // Read a string
8873 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8874   unsigned Len = Record[Idx++];
8875   std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8876   Idx += Len;
8877   return Result;
8878 }
8879 
8880 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8881                                 unsigned &Idx) {
8882   std::string Filename = ReadString(Record, Idx);
8883   ResolveImportedPath(F, Filename);
8884   return Filename;
8885 }
8886 
8887 std::string ASTReader::ReadPath(StringRef BaseDirectory,
8888                                 const RecordData &Record, unsigned &Idx) {
8889   std::string Filename = ReadString(Record, Idx);
8890   if (!BaseDirectory.empty())
8891     ResolveImportedPath(Filename, BaseDirectory);
8892   return Filename;
8893 }
8894 
8895 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8896                                          unsigned &Idx) {
8897   unsigned Major = Record[Idx++];
8898   unsigned Minor = Record[Idx++];
8899   unsigned Subminor = Record[Idx++];
8900   if (Minor == 0)
8901     return VersionTuple(Major);
8902   if (Subminor == 0)
8903     return VersionTuple(Major, Minor - 1);
8904   return VersionTuple(Major, Minor - 1, Subminor - 1);
8905 }
8906 
8907 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8908                                           const RecordData &Record,
8909                                           unsigned &Idx) {
8910   CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8911   return CXXTemporary::Create(getContext(), Decl);
8912 }
8913 
8914 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
8915   return Diag(CurrentImportLoc, DiagID);
8916 }
8917 
8918 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
8919   return Diags.Report(Loc, DiagID);
8920 }
8921 
8922 /// Retrieve the identifier table associated with the
8923 /// preprocessor.
8924 IdentifierTable &ASTReader::getIdentifierTable() {
8925   return PP.getIdentifierTable();
8926 }
8927 
8928 /// Record that the given ID maps to the given switch-case
8929 /// statement.
8930 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
8931   assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
8932          "Already have a SwitchCase with this ID");
8933   (*CurrSwitchCaseStmts)[ID] = SC;
8934 }
8935 
8936 /// Retrieve the switch-case statement with the given ID.
8937 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
8938   assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
8939   return (*CurrSwitchCaseStmts)[ID];
8940 }
8941 
8942 void ASTReader::ClearSwitchCaseIDs() {
8943   CurrSwitchCaseStmts->clear();
8944 }
8945 
8946 void ASTReader::ReadComments() {
8947   ASTContext &Context = getContext();
8948   std::vector<RawComment *> Comments;
8949   for (SmallVectorImpl<std::pair<BitstreamCursor,
8950                                  serialization::ModuleFile *>>::iterator
8951        I = CommentsCursors.begin(),
8952        E = CommentsCursors.end();
8953        I != E; ++I) {
8954     Comments.clear();
8955     BitstreamCursor &Cursor = I->first;
8956     serialization::ModuleFile &F = *I->second;
8957     SavedStreamPosition SavedPosition(Cursor);
8958 
8959     RecordData Record;
8960     while (true) {
8961       Expected<llvm::BitstreamEntry> MaybeEntry =
8962           Cursor.advanceSkippingSubblocks(
8963               BitstreamCursor::AF_DontPopBlockAtEnd);
8964       if (!MaybeEntry) {
8965         Error(MaybeEntry.takeError());
8966         return;
8967       }
8968       llvm::BitstreamEntry Entry = MaybeEntry.get();
8969 
8970       switch (Entry.Kind) {
8971       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8972       case llvm::BitstreamEntry::Error:
8973         Error("malformed block record in AST file");
8974         return;
8975       case llvm::BitstreamEntry::EndBlock:
8976         goto NextCursor;
8977       case llvm::BitstreamEntry::Record:
8978         // The interesting case.
8979         break;
8980       }
8981 
8982       // Read a record.
8983       Record.clear();
8984       Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
8985       if (!MaybeComment) {
8986         Error(MaybeComment.takeError());
8987         return;
8988       }
8989       switch ((CommentRecordTypes)MaybeComment.get()) {
8990       case COMMENTS_RAW_COMMENT: {
8991         unsigned Idx = 0;
8992         SourceRange SR = ReadSourceRange(F, Record, Idx);
8993         RawComment::CommentKind Kind =
8994             (RawComment::CommentKind) Record[Idx++];
8995         bool IsTrailingComment = Record[Idx++];
8996         bool IsAlmostTrailingComment = Record[Idx++];
8997         Comments.push_back(new (Context) RawComment(
8998             SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
8999         break;
9000       }
9001       }
9002     }
9003   NextCursor:
9004     llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9005         FileToOffsetToComment;
9006     for (RawComment *C : Comments) {
9007       SourceLocation CommentLoc = C->getBeginLoc();
9008       if (CommentLoc.isValid()) {
9009         std::pair<FileID, unsigned> Loc =
9010             SourceMgr.getDecomposedLoc(CommentLoc);
9011         if (Loc.first.isValid())
9012           Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9013       }
9014     }
9015   }
9016 }
9017 
9018 void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9019                                 bool IncludeSystem, bool Complain,
9020                     llvm::function_ref<void(const serialization::InputFile &IF,
9021                                             bool isSystem)> Visitor) {
9022   unsigned NumUserInputs = MF.NumUserInputFiles;
9023   unsigned NumInputs = MF.InputFilesLoaded.size();
9024   assert(NumUserInputs <= NumInputs);
9025   unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9026   for (unsigned I = 0; I < N; ++I) {
9027     bool IsSystem = I >= NumUserInputs;
9028     InputFile IF = getInputFile(MF, I+1, Complain);
9029     Visitor(IF, IsSystem);
9030   }
9031 }
9032 
9033 void ASTReader::visitTopLevelModuleMaps(
9034     serialization::ModuleFile &MF,
9035     llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9036   unsigned NumInputs = MF.InputFilesLoaded.size();
9037   for (unsigned I = 0; I < NumInputs; ++I) {
9038     InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9039     if (IFI.TopLevelModuleMap)
9040       // FIXME: This unnecessarily re-reads the InputFileInfo.
9041       if (auto *FE = getInputFile(MF, I + 1).getFile())
9042         Visitor(FE);
9043   }
9044 }
9045 
9046 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9047   // If we know the owning module, use it.
9048   if (Module *M = D->getImportedOwningModule())
9049     return M->getFullModuleName();
9050 
9051   // Otherwise, use the name of the top-level module the decl is within.
9052   if (ModuleFile *M = getOwningModuleFile(D))
9053     return M->ModuleName;
9054 
9055   // Not from a module.
9056   return {};
9057 }
9058 
9059 void ASTReader::finishPendingActions() {
9060   while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
9061          !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
9062          !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
9063          !PendingUpdateRecords.empty()) {
9064     // If any identifiers with corresponding top-level declarations have
9065     // been loaded, load those declarations now.
9066     using TopLevelDeclsMap =
9067         llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
9068     TopLevelDeclsMap TopLevelDecls;
9069 
9070     while (!PendingIdentifierInfos.empty()) {
9071       IdentifierInfo *II = PendingIdentifierInfos.back().first;
9072       SmallVector<uint32_t, 4> DeclIDs =
9073           std::move(PendingIdentifierInfos.back().second);
9074       PendingIdentifierInfos.pop_back();
9075 
9076       SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
9077     }
9078 
9079     // Load each function type that we deferred loading because it was a
9080     // deduced type that might refer to a local type declared within itself.
9081     for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9082       auto *FD = PendingFunctionTypes[I].first;
9083       FD->setType(GetType(PendingFunctionTypes[I].second));
9084 
9085       // If we gave a function a deduced return type, remember that we need to
9086       // propagate that along the redeclaration chain.
9087       auto *DT = FD->getReturnType()->getContainedDeducedType();
9088       if (DT && DT->isDeduced())
9089         PendingDeducedTypeUpdates.insert(
9090             {FD->getCanonicalDecl(), FD->getReturnType()});
9091     }
9092     PendingFunctionTypes.clear();
9093 
9094     // For each decl chain that we wanted to complete while deserializing, mark
9095     // it as "still needs to be completed".
9096     for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9097       markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9098     }
9099     PendingIncompleteDeclChains.clear();
9100 
9101     // Load pending declaration chains.
9102     for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
9103       loadPendingDeclChain(PendingDeclChains[I].first,
9104                            PendingDeclChains[I].second);
9105     PendingDeclChains.clear();
9106 
9107     // Make the most recent of the top-level declarations visible.
9108     for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9109            TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9110       IdentifierInfo *II = TLD->first;
9111       for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9112         pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
9113       }
9114     }
9115 
9116     // Load any pending macro definitions.
9117     for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
9118       IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9119       SmallVector<PendingMacroInfo, 2> GlobalIDs;
9120       GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9121       // Initialize the macro history from chained-PCHs ahead of module imports.
9122       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9123            ++IDIdx) {
9124         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9125         if (!Info.M->isModule())
9126           resolvePendingMacro(II, Info);
9127       }
9128       // Handle module imports.
9129       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9130            ++IDIdx) {
9131         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9132         if (Info.M->isModule())
9133           resolvePendingMacro(II, Info);
9134       }
9135     }
9136     PendingMacroIDs.clear();
9137 
9138     // Wire up the DeclContexts for Decls that we delayed setting until
9139     // recursive loading is completed.
9140     while (!PendingDeclContextInfos.empty()) {
9141       PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9142       PendingDeclContextInfos.pop_front();
9143       DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9144       DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9145       Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9146     }
9147 
9148     // Perform any pending declaration updates.
9149     while (!PendingUpdateRecords.empty()) {
9150       auto Update = PendingUpdateRecords.pop_back_val();
9151       ReadingKindTracker ReadingKind(Read_Decl, *this);
9152       loadDeclUpdateRecords(Update);
9153     }
9154   }
9155 
9156   // At this point, all update records for loaded decls are in place, so any
9157   // fake class definitions should have become real.
9158   assert(PendingFakeDefinitionData.empty() &&
9159          "faked up a class definition but never saw the real one");
9160 
9161   // If we deserialized any C++ or Objective-C class definitions, any
9162   // Objective-C protocol definitions, or any redeclarable templates, make sure
9163   // that all redeclarations point to the definitions. Note that this can only
9164   // happen now, after the redeclaration chains have been fully wired.
9165   for (Decl *D : PendingDefinitions) {
9166     if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9167       if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
9168         // Make sure that the TagType points at the definition.
9169         const_cast<TagType*>(TagT)->decl = TD;
9170       }
9171 
9172       if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
9173         for (auto *R = getMostRecentExistingDecl(RD); R;
9174              R = R->getPreviousDecl()) {
9175           assert((R == D) ==
9176                      cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
9177                  "declaration thinks it's the definition but it isn't");
9178           cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
9179         }
9180       }
9181 
9182       continue;
9183     }
9184 
9185     if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
9186       // Make sure that the ObjCInterfaceType points at the definition.
9187       const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9188         ->Decl = ID;
9189 
9190       for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9191         cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9192 
9193       continue;
9194     }
9195 
9196     if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
9197       for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9198         cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9199 
9200       continue;
9201     }
9202 
9203     auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9204     for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9205       cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9206   }
9207   PendingDefinitions.clear();
9208 
9209   // Load the bodies of any functions or methods we've encountered. We do
9210   // this now (delayed) so that we can be sure that the declaration chains
9211   // have been fully wired up (hasBody relies on this).
9212   // FIXME: We shouldn't require complete redeclaration chains here.
9213   for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9214                                PBEnd = PendingBodies.end();
9215        PB != PBEnd; ++PB) {
9216     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9217       // For a function defined inline within a class template, force the
9218       // canonical definition to be the one inside the canonical definition of
9219       // the template. This ensures that we instantiate from a correct view
9220       // of the template.
9221       //
9222       // Sadly we can't do this more generally: we can't be sure that all
9223       // copies of an arbitrary class definition will have the same members
9224       // defined (eg, some member functions may not be instantiated, and some
9225       // special members may or may not have been implicitly defined).
9226       if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9227         if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9228           continue;
9229 
9230       // FIXME: Check for =delete/=default?
9231       // FIXME: Complain about ODR violations here?
9232       const FunctionDecl *Defn = nullptr;
9233       if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9234         FD->setLazyBody(PB->second);
9235       } else {
9236         auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
9237         mergeDefinitionVisibility(NonConstDefn, FD);
9238 
9239         if (!FD->isLateTemplateParsed() &&
9240             !NonConstDefn->isLateTemplateParsed() &&
9241             FD->getODRHash() != NonConstDefn->getODRHash()) {
9242           if (!isa<CXXMethodDecl>(FD)) {
9243             PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9244           } else if (FD->getLexicalParent()->isFileContext() &&
9245                      NonConstDefn->getLexicalParent()->isFileContext()) {
9246             // Only diagnose out-of-line method definitions.  If they are
9247             // in class definitions, then an error will be generated when
9248             // processing the class bodies.
9249             PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9250           }
9251         }
9252       }
9253       continue;
9254     }
9255 
9256     ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9257     if (!getContext().getLangOpts().Modules || !MD->hasBody())
9258       MD->setLazyBody(PB->second);
9259   }
9260   PendingBodies.clear();
9261 
9262   // Do some cleanup.
9263   for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9264     getContext().deduplicateMergedDefinitonsFor(ND);
9265   PendingMergedDefinitionsToDeduplicate.clear();
9266 }
9267 
9268 void ASTReader::diagnoseOdrViolations() {
9269   if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9270       PendingFunctionOdrMergeFailures.empty() &&
9271       PendingEnumOdrMergeFailures.empty())
9272     return;
9273 
9274   // Trigger the import of the full definition of each class that had any
9275   // odr-merging problems, so we can produce better diagnostics for them.
9276   // These updates may in turn find and diagnose some ODR failures, so take
9277   // ownership of the set first.
9278   auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9279   PendingOdrMergeFailures.clear();
9280   for (auto &Merge : OdrMergeFailures) {
9281     Merge.first->buildLookup();
9282     Merge.first->decls_begin();
9283     Merge.first->bases_begin();
9284     Merge.first->vbases_begin();
9285     for (auto &RecordPair : Merge.second) {
9286       auto *RD = RecordPair.first;
9287       RD->decls_begin();
9288       RD->bases_begin();
9289       RD->vbases_begin();
9290     }
9291   }
9292 
9293   // Trigger the import of functions.
9294   auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9295   PendingFunctionOdrMergeFailures.clear();
9296   for (auto &Merge : FunctionOdrMergeFailures) {
9297     Merge.first->buildLookup();
9298     Merge.first->decls_begin();
9299     Merge.first->getBody();
9300     for (auto &FD : Merge.second) {
9301       FD->buildLookup();
9302       FD->decls_begin();
9303       FD->getBody();
9304     }
9305   }
9306 
9307   // Trigger the import of enums.
9308   auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9309   PendingEnumOdrMergeFailures.clear();
9310   for (auto &Merge : EnumOdrMergeFailures) {
9311     Merge.first->decls_begin();
9312     for (auto &Enum : Merge.second) {
9313       Enum->decls_begin();
9314     }
9315   }
9316 
9317   // For each declaration from a merged context, check that the canonical
9318   // definition of that context also contains a declaration of the same
9319   // entity.
9320   //
9321   // Caution: this loop does things that might invalidate iterators into
9322   // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9323   while (!PendingOdrMergeChecks.empty()) {
9324     NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9325 
9326     // FIXME: Skip over implicit declarations for now. This matters for things
9327     // like implicitly-declared special member functions. This isn't entirely
9328     // correct; we can end up with multiple unmerged declarations of the same
9329     // implicit entity.
9330     if (D->isImplicit())
9331       continue;
9332 
9333     DeclContext *CanonDef = D->getDeclContext();
9334 
9335     bool Found = false;
9336     const Decl *DCanon = D->getCanonicalDecl();
9337 
9338     for (auto RI : D->redecls()) {
9339       if (RI->getLexicalDeclContext() == CanonDef) {
9340         Found = true;
9341         break;
9342       }
9343     }
9344     if (Found)
9345       continue;
9346 
9347     // Quick check failed, time to do the slow thing. Note, we can't just
9348     // look up the name of D in CanonDef here, because the member that is
9349     // in CanonDef might not be found by name lookup (it might have been
9350     // replaced by a more recent declaration in the lookup table), and we
9351     // can't necessarily find it in the redeclaration chain because it might
9352     // be merely mergeable, not redeclarable.
9353     llvm::SmallVector<const NamedDecl*, 4> Candidates;
9354     for (auto *CanonMember : CanonDef->decls()) {
9355       if (CanonMember->getCanonicalDecl() == DCanon) {
9356         // This can happen if the declaration is merely mergeable and not
9357         // actually redeclarable (we looked for redeclarations earlier).
9358         //
9359         // FIXME: We should be able to detect this more efficiently, without
9360         // pulling in all of the members of CanonDef.
9361         Found = true;
9362         break;
9363       }
9364       if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9365         if (ND->getDeclName() == D->getDeclName())
9366           Candidates.push_back(ND);
9367     }
9368 
9369     if (!Found) {
9370       // The AST doesn't like TagDecls becoming invalid after they've been
9371       // completed. We only really need to mark FieldDecls as invalid here.
9372       if (!isa<TagDecl>(D))
9373         D->setInvalidDecl();
9374 
9375       // Ensure we don't accidentally recursively enter deserialization while
9376       // we're producing our diagnostic.
9377       Deserializing RecursionGuard(this);
9378 
9379       std::string CanonDefModule =
9380           getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9381       Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9382         << D << getOwningModuleNameForDiagnostic(D)
9383         << CanonDef << CanonDefModule.empty() << CanonDefModule;
9384 
9385       if (Candidates.empty())
9386         Diag(cast<Decl>(CanonDef)->getLocation(),
9387              diag::note_module_odr_violation_no_possible_decls) << D;
9388       else {
9389         for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9390           Diag(Candidates[I]->getLocation(),
9391                diag::note_module_odr_violation_possible_decl)
9392             << Candidates[I];
9393       }
9394 
9395       DiagnosedOdrMergeFailures.insert(CanonDef);
9396     }
9397   }
9398 
9399   if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
9400       EnumOdrMergeFailures.empty())
9401     return;
9402 
9403   // Ensure we don't accidentally recursively enter deserialization while
9404   // we're producing our diagnostics.
9405   Deserializing RecursionGuard(this);
9406 
9407   // Common code for hashing helpers.
9408   ODRHash Hash;
9409   auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9410     Hash.clear();
9411     Hash.AddQualType(Ty);
9412     return Hash.CalculateHash();
9413   };
9414 
9415   auto ComputeODRHash = [&Hash](const Stmt *S) {
9416     assert(S);
9417     Hash.clear();
9418     Hash.AddStmt(S);
9419     return Hash.CalculateHash();
9420   };
9421 
9422   auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
9423     assert(D);
9424     Hash.clear();
9425     Hash.AddSubDecl(D);
9426     return Hash.CalculateHash();
9427   };
9428 
9429   auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
9430     Hash.clear();
9431     Hash.AddTemplateArgument(TA);
9432     return Hash.CalculateHash();
9433   };
9434 
9435   auto ComputeTemplateParameterListODRHash =
9436       [&Hash](const TemplateParameterList *TPL) {
9437         assert(TPL);
9438         Hash.clear();
9439         Hash.AddTemplateParameterList(TPL);
9440         return Hash.CalculateHash();
9441       };
9442 
9443   // Issue any pending ODR-failure diagnostics.
9444   for (auto &Merge : OdrMergeFailures) {
9445     // If we've already pointed out a specific problem with this class, don't
9446     // bother issuing a general "something's different" diagnostic.
9447     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9448       continue;
9449 
9450     bool Diagnosed = false;
9451     CXXRecordDecl *FirstRecord = Merge.first;
9452     std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
9453     for (auto &RecordPair : Merge.second) {
9454       CXXRecordDecl *SecondRecord = RecordPair.first;
9455       // Multiple different declarations got merged together; tell the user
9456       // where they came from.
9457       if (FirstRecord == SecondRecord)
9458         continue;
9459 
9460       std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
9461 
9462       auto *FirstDD = FirstRecord->DefinitionData;
9463       auto *SecondDD = RecordPair.second;
9464 
9465       assert(FirstDD && SecondDD && "Definitions without DefinitionData");
9466 
9467       // Diagnostics from DefinitionData are emitted here.
9468       if (FirstDD != SecondDD) {
9469         enum ODRDefinitionDataDifference {
9470           NumBases,
9471           NumVBases,
9472           BaseType,
9473           BaseVirtual,
9474           BaseAccess,
9475         };
9476         auto ODRDiagError = [FirstRecord, &FirstModule,
9477                              this](SourceLocation Loc, SourceRange Range,
9478                                    ODRDefinitionDataDifference DiffType) {
9479           return Diag(Loc, diag::err_module_odr_violation_definition_data)
9480                  << FirstRecord << FirstModule.empty() << FirstModule << Range
9481                  << DiffType;
9482         };
9483         auto ODRDiagNote = [&SecondModule,
9484                             this](SourceLocation Loc, SourceRange Range,
9485                                   ODRDefinitionDataDifference DiffType) {
9486           return Diag(Loc, diag::note_module_odr_violation_definition_data)
9487                  << SecondModule << Range << DiffType;
9488         };
9489 
9490         unsigned FirstNumBases = FirstDD->NumBases;
9491         unsigned FirstNumVBases = FirstDD->NumVBases;
9492         unsigned SecondNumBases = SecondDD->NumBases;
9493         unsigned SecondNumVBases = SecondDD->NumVBases;
9494 
9495         auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
9496           unsigned NumBases = DD->NumBases;
9497           if (NumBases == 0) return SourceRange();
9498           auto bases = DD->bases();
9499           return SourceRange(bases[0].getBeginLoc(),
9500                              bases[NumBases - 1].getEndLoc());
9501         };
9502 
9503         if (FirstNumBases != SecondNumBases) {
9504           ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9505                        NumBases)
9506               << FirstNumBases;
9507           ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9508                       NumBases)
9509               << SecondNumBases;
9510           Diagnosed = true;
9511           break;
9512         }
9513 
9514         if (FirstNumVBases != SecondNumVBases) {
9515           ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9516                        NumVBases)
9517               << FirstNumVBases;
9518           ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9519                       NumVBases)
9520               << SecondNumVBases;
9521           Diagnosed = true;
9522           break;
9523         }
9524 
9525         auto FirstBases = FirstDD->bases();
9526         auto SecondBases = SecondDD->bases();
9527         unsigned i = 0;
9528         for (i = 0; i < FirstNumBases; ++i) {
9529           auto FirstBase = FirstBases[i];
9530           auto SecondBase = SecondBases[i];
9531           if (ComputeQualTypeODRHash(FirstBase.getType()) !=
9532               ComputeQualTypeODRHash(SecondBase.getType())) {
9533             ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9534                          BaseType)
9535                 << (i + 1) << FirstBase.getType();
9536             ODRDiagNote(SecondRecord->getLocation(),
9537                         SecondBase.getSourceRange(), BaseType)
9538                 << (i + 1) << SecondBase.getType();
9539             break;
9540           }
9541 
9542           if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
9543             ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9544                          BaseVirtual)
9545                 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
9546             ODRDiagNote(SecondRecord->getLocation(),
9547                         SecondBase.getSourceRange(), BaseVirtual)
9548                 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
9549             break;
9550           }
9551 
9552           if (FirstBase.getAccessSpecifierAsWritten() !=
9553               SecondBase.getAccessSpecifierAsWritten()) {
9554             ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9555                          BaseAccess)
9556                 << (i + 1) << FirstBase.getType()
9557                 << (int)FirstBase.getAccessSpecifierAsWritten();
9558             ODRDiagNote(SecondRecord->getLocation(),
9559                         SecondBase.getSourceRange(), BaseAccess)
9560                 << (i + 1) << SecondBase.getType()
9561                 << (int)SecondBase.getAccessSpecifierAsWritten();
9562             break;
9563           }
9564         }
9565 
9566         if (i != FirstNumBases) {
9567           Diagnosed = true;
9568           break;
9569         }
9570       }
9571 
9572       using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
9573 
9574       const ClassTemplateDecl *FirstTemplate =
9575           FirstRecord->getDescribedClassTemplate();
9576       const ClassTemplateDecl *SecondTemplate =
9577           SecondRecord->getDescribedClassTemplate();
9578 
9579       assert(!FirstTemplate == !SecondTemplate &&
9580              "Both pointers should be null or non-null");
9581 
9582       enum ODRTemplateDifference {
9583         ParamEmptyName,
9584         ParamName,
9585         ParamSingleDefaultArgument,
9586         ParamDifferentDefaultArgument,
9587       };
9588 
9589       if (FirstTemplate && SecondTemplate) {
9590         DeclHashes FirstTemplateHashes;
9591         DeclHashes SecondTemplateHashes;
9592 
9593         auto PopulateTemplateParameterHashs =
9594             [&ComputeSubDeclODRHash](DeclHashes &Hashes,
9595                                      const ClassTemplateDecl *TD) {
9596               for (auto *D : TD->getTemplateParameters()->asArray()) {
9597                 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
9598               }
9599             };
9600 
9601         PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
9602         PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
9603 
9604         assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
9605                "Number of template parameters should be equal.");
9606 
9607         auto FirstIt = FirstTemplateHashes.begin();
9608         auto FirstEnd = FirstTemplateHashes.end();
9609         auto SecondIt = SecondTemplateHashes.begin();
9610         for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
9611           if (FirstIt->second == SecondIt->second)
9612             continue;
9613 
9614           auto ODRDiagError = [FirstRecord, &FirstModule,
9615                                this](SourceLocation Loc, SourceRange Range,
9616                                      ODRTemplateDifference DiffType) {
9617             return Diag(Loc, diag::err_module_odr_violation_template_parameter)
9618                    << FirstRecord << FirstModule.empty() << FirstModule << Range
9619                    << DiffType;
9620           };
9621           auto ODRDiagNote = [&SecondModule,
9622                               this](SourceLocation Loc, SourceRange Range,
9623                                     ODRTemplateDifference DiffType) {
9624             return Diag(Loc, diag::note_module_odr_violation_template_parameter)
9625                    << SecondModule << Range << DiffType;
9626           };
9627 
9628           const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
9629           const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
9630 
9631           assert(FirstDecl->getKind() == SecondDecl->getKind() &&
9632                  "Parameter Decl's should be the same kind.");
9633 
9634           DeclarationName FirstName = FirstDecl->getDeclName();
9635           DeclarationName SecondName = SecondDecl->getDeclName();
9636 
9637           if (FirstName != SecondName) {
9638             const bool FirstNameEmpty =
9639                 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
9640             const bool SecondNameEmpty =
9641                 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
9642             assert((!FirstNameEmpty || !SecondNameEmpty) &&
9643                    "Both template parameters cannot be unnamed.");
9644             ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9645                          FirstNameEmpty ? ParamEmptyName : ParamName)
9646                 << FirstName;
9647             ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9648                         SecondNameEmpty ? ParamEmptyName : ParamName)
9649                 << SecondName;
9650             break;
9651           }
9652 
9653           switch (FirstDecl->getKind()) {
9654           default:
9655             llvm_unreachable("Invalid template parameter type.");
9656           case Decl::TemplateTypeParm: {
9657             const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
9658             const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
9659             const bool HasFirstDefaultArgument =
9660                 FirstParam->hasDefaultArgument() &&
9661                 !FirstParam->defaultArgumentWasInherited();
9662             const bool HasSecondDefaultArgument =
9663                 SecondParam->hasDefaultArgument() &&
9664                 !SecondParam->defaultArgumentWasInherited();
9665 
9666             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9667               ODRDiagError(FirstDecl->getLocation(),
9668                            FirstDecl->getSourceRange(),
9669                            ParamSingleDefaultArgument)
9670                   << HasFirstDefaultArgument;
9671               ODRDiagNote(SecondDecl->getLocation(),
9672                           SecondDecl->getSourceRange(),
9673                           ParamSingleDefaultArgument)
9674                   << HasSecondDefaultArgument;
9675               break;
9676             }
9677 
9678             assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9679                    "Expecting default arguments.");
9680 
9681             ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9682                          ParamDifferentDefaultArgument);
9683             ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9684                         ParamDifferentDefaultArgument);
9685 
9686             break;
9687           }
9688           case Decl::NonTypeTemplateParm: {
9689             const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
9690             const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
9691             const bool HasFirstDefaultArgument =
9692                 FirstParam->hasDefaultArgument() &&
9693                 !FirstParam->defaultArgumentWasInherited();
9694             const bool HasSecondDefaultArgument =
9695                 SecondParam->hasDefaultArgument() &&
9696                 !SecondParam->defaultArgumentWasInherited();
9697 
9698             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9699               ODRDiagError(FirstDecl->getLocation(),
9700                            FirstDecl->getSourceRange(),
9701                            ParamSingleDefaultArgument)
9702                   << HasFirstDefaultArgument;
9703               ODRDiagNote(SecondDecl->getLocation(),
9704                           SecondDecl->getSourceRange(),
9705                           ParamSingleDefaultArgument)
9706                   << HasSecondDefaultArgument;
9707               break;
9708             }
9709 
9710             assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9711                    "Expecting default arguments.");
9712 
9713             ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9714                          ParamDifferentDefaultArgument);
9715             ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9716                         ParamDifferentDefaultArgument);
9717 
9718             break;
9719           }
9720           case Decl::TemplateTemplateParm: {
9721             const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
9722             const auto *SecondParam =
9723                 cast<TemplateTemplateParmDecl>(SecondDecl);
9724             const bool HasFirstDefaultArgument =
9725                 FirstParam->hasDefaultArgument() &&
9726                 !FirstParam->defaultArgumentWasInherited();
9727             const bool HasSecondDefaultArgument =
9728                 SecondParam->hasDefaultArgument() &&
9729                 !SecondParam->defaultArgumentWasInherited();
9730 
9731             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9732               ODRDiagError(FirstDecl->getLocation(),
9733                            FirstDecl->getSourceRange(),
9734                            ParamSingleDefaultArgument)
9735                   << HasFirstDefaultArgument;
9736               ODRDiagNote(SecondDecl->getLocation(),
9737                           SecondDecl->getSourceRange(),
9738                           ParamSingleDefaultArgument)
9739                   << HasSecondDefaultArgument;
9740               break;
9741             }
9742 
9743             assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9744                    "Expecting default arguments.");
9745 
9746             ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9747                          ParamDifferentDefaultArgument);
9748             ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9749                         ParamDifferentDefaultArgument);
9750 
9751             break;
9752           }
9753           }
9754 
9755           break;
9756         }
9757 
9758         if (FirstIt != FirstEnd) {
9759           Diagnosed = true;
9760           break;
9761         }
9762       }
9763 
9764       DeclHashes FirstHashes;
9765       DeclHashes SecondHashes;
9766 
9767       auto PopulateHashes = [&ComputeSubDeclODRHash, FirstRecord](
9768                                 DeclHashes &Hashes, CXXRecordDecl *Record) {
9769         for (auto *D : Record->decls()) {
9770           // Due to decl merging, the first CXXRecordDecl is the parent of
9771           // Decls in both records.
9772           if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9773             continue;
9774           Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
9775         }
9776       };
9777       PopulateHashes(FirstHashes, FirstRecord);
9778       PopulateHashes(SecondHashes, SecondRecord);
9779 
9780       // Used with err_module_odr_violation_mismatch_decl and
9781       // note_module_odr_violation_mismatch_decl
9782       // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
9783       enum {
9784         EndOfClass,
9785         PublicSpecifer,
9786         PrivateSpecifer,
9787         ProtectedSpecifer,
9788         StaticAssert,
9789         Field,
9790         CXXMethod,
9791         TypeAlias,
9792         TypeDef,
9793         Var,
9794         Friend,
9795         FunctionTemplate,
9796         Other
9797       } FirstDiffType = Other,
9798         SecondDiffType = Other;
9799 
9800       auto DifferenceSelector = [](Decl *D) {
9801         assert(D && "valid Decl required");
9802         switch (D->getKind()) {
9803         default:
9804           return Other;
9805         case Decl::AccessSpec:
9806           switch (D->getAccess()) {
9807           case AS_public:
9808             return PublicSpecifer;
9809           case AS_private:
9810             return PrivateSpecifer;
9811           case AS_protected:
9812             return ProtectedSpecifer;
9813           case AS_none:
9814             break;
9815           }
9816           llvm_unreachable("Invalid access specifier");
9817         case Decl::StaticAssert:
9818           return StaticAssert;
9819         case Decl::Field:
9820           return Field;
9821         case Decl::CXXMethod:
9822         case Decl::CXXConstructor:
9823         case Decl::CXXDestructor:
9824           return CXXMethod;
9825         case Decl::TypeAlias:
9826           return TypeAlias;
9827         case Decl::Typedef:
9828           return TypeDef;
9829         case Decl::Var:
9830           return Var;
9831         case Decl::Friend:
9832           return Friend;
9833         case Decl::FunctionTemplate:
9834           return FunctionTemplate;
9835         }
9836       };
9837 
9838       Decl *FirstDecl = nullptr;
9839       Decl *SecondDecl = nullptr;
9840       auto FirstIt = FirstHashes.begin();
9841       auto SecondIt = SecondHashes.begin();
9842 
9843       // If there is a diagnoseable difference, FirstDiffType and
9844       // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9845       // filled in if not EndOfClass.
9846       while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
9847         if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9848             FirstIt->second == SecondIt->second) {
9849           ++FirstIt;
9850           ++SecondIt;
9851           continue;
9852         }
9853 
9854         FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9855         SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9856 
9857         FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9858         SecondDiffType =
9859             SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9860 
9861         break;
9862       }
9863 
9864       if (FirstDiffType == Other || SecondDiffType == Other) {
9865         // Reaching this point means an unexpected Decl was encountered
9866         // or no difference was detected.  This causes a generic error
9867         // message to be emitted.
9868         Diag(FirstRecord->getLocation(),
9869              diag::err_module_odr_violation_different_definitions)
9870             << FirstRecord << FirstModule.empty() << FirstModule;
9871 
9872         if (FirstDecl) {
9873           Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
9874               << FirstRecord << FirstDecl->getSourceRange();
9875         }
9876 
9877         Diag(SecondRecord->getLocation(),
9878              diag::note_module_odr_violation_different_definitions)
9879             << SecondModule;
9880 
9881         if (SecondDecl) {
9882           Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
9883               << SecondDecl->getSourceRange();
9884         }
9885 
9886         Diagnosed = true;
9887         break;
9888       }
9889 
9890       if (FirstDiffType != SecondDiffType) {
9891         SourceLocation FirstLoc;
9892         SourceRange FirstRange;
9893         if (FirstDiffType == EndOfClass) {
9894           FirstLoc = FirstRecord->getBraceRange().getEnd();
9895         } else {
9896           FirstLoc = FirstIt->first->getLocation();
9897           FirstRange = FirstIt->first->getSourceRange();
9898         }
9899         Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9900             << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9901             << FirstDiffType;
9902 
9903         SourceLocation SecondLoc;
9904         SourceRange SecondRange;
9905         if (SecondDiffType == EndOfClass) {
9906           SecondLoc = SecondRecord->getBraceRange().getEnd();
9907         } else {
9908           SecondLoc = SecondDecl->getLocation();
9909           SecondRange = SecondDecl->getSourceRange();
9910         }
9911         Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9912             << SecondModule << SecondRange << SecondDiffType;
9913         Diagnosed = true;
9914         break;
9915       }
9916 
9917       assert(FirstDiffType == SecondDiffType);
9918 
9919       // Used with err_module_odr_violation_mismatch_decl_diff and
9920       // note_module_odr_violation_mismatch_decl_diff
9921       enum ODRDeclDifference {
9922         StaticAssertCondition,
9923         StaticAssertMessage,
9924         StaticAssertOnlyMessage,
9925         FieldName,
9926         FieldTypeName,
9927         FieldSingleBitField,
9928         FieldDifferentWidthBitField,
9929         FieldSingleMutable,
9930         FieldSingleInitializer,
9931         FieldDifferentInitializers,
9932         MethodName,
9933         MethodDeleted,
9934         MethodDefaulted,
9935         MethodVirtual,
9936         MethodStatic,
9937         MethodVolatile,
9938         MethodConst,
9939         MethodInline,
9940         MethodNumberParameters,
9941         MethodParameterType,
9942         MethodParameterName,
9943         MethodParameterSingleDefaultArgument,
9944         MethodParameterDifferentDefaultArgument,
9945         MethodNoTemplateArguments,
9946         MethodDifferentNumberTemplateArguments,
9947         MethodDifferentTemplateArgument,
9948         MethodSingleBody,
9949         MethodDifferentBody,
9950         TypedefName,
9951         TypedefType,
9952         VarName,
9953         VarType,
9954         VarSingleInitializer,
9955         VarDifferentInitializer,
9956         VarConstexpr,
9957         FriendTypeFunction,
9958         FriendType,
9959         FriendFunction,
9960         FunctionTemplateDifferentNumberParameters,
9961         FunctionTemplateParameterDifferentKind,
9962         FunctionTemplateParameterName,
9963         FunctionTemplateParameterSingleDefaultArgument,
9964         FunctionTemplateParameterDifferentDefaultArgument,
9965         FunctionTemplateParameterDifferentType,
9966         FunctionTemplatePackParameter,
9967       };
9968 
9969       // These lambdas have the common portions of the ODR diagnostics.  This
9970       // has the same return as Diag(), so addition parameters can be passed
9971       // in with operator<<
9972       auto ODRDiagError = [FirstRecord, &FirstModule, this](
9973           SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9974         return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9975                << FirstRecord << FirstModule.empty() << FirstModule << Range
9976                << DiffType;
9977       };
9978       auto ODRDiagNote = [&SecondModule, this](
9979           SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9980         return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9981                << SecondModule << Range << DiffType;
9982       };
9983 
9984       switch (FirstDiffType) {
9985       case Other:
9986       case EndOfClass:
9987       case PublicSpecifer:
9988       case PrivateSpecifer:
9989       case ProtectedSpecifer:
9990         llvm_unreachable("Invalid diff type");
9991 
9992       case StaticAssert: {
9993         StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9994         StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
9995 
9996         Expr *FirstExpr = FirstSA->getAssertExpr();
9997         Expr *SecondExpr = SecondSA->getAssertExpr();
9998         unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9999         unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10000         if (FirstODRHash != SecondODRHash) {
10001           ODRDiagError(FirstExpr->getBeginLoc(), FirstExpr->getSourceRange(),
10002                        StaticAssertCondition);
10003           ODRDiagNote(SecondExpr->getBeginLoc(), SecondExpr->getSourceRange(),
10004                       StaticAssertCondition);
10005           Diagnosed = true;
10006           break;
10007         }
10008 
10009         StringLiteral *FirstStr = FirstSA->getMessage();
10010         StringLiteral *SecondStr = SecondSA->getMessage();
10011         assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10012         if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10013           SourceLocation FirstLoc, SecondLoc;
10014           SourceRange FirstRange, SecondRange;
10015           if (FirstStr) {
10016             FirstLoc = FirstStr->getBeginLoc();
10017             FirstRange = FirstStr->getSourceRange();
10018           } else {
10019             FirstLoc = FirstSA->getBeginLoc();
10020             FirstRange = FirstSA->getSourceRange();
10021           }
10022           if (SecondStr) {
10023             SecondLoc = SecondStr->getBeginLoc();
10024             SecondRange = SecondStr->getSourceRange();
10025           } else {
10026             SecondLoc = SecondSA->getBeginLoc();
10027             SecondRange = SecondSA->getSourceRange();
10028           }
10029           ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
10030               << (FirstStr == nullptr);
10031           ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
10032               << (SecondStr == nullptr);
10033           Diagnosed = true;
10034           break;
10035         }
10036 
10037         if (FirstStr && SecondStr &&
10038             FirstStr->getString() != SecondStr->getString()) {
10039           ODRDiagError(FirstStr->getBeginLoc(), FirstStr->getSourceRange(),
10040                        StaticAssertMessage);
10041           ODRDiagNote(SecondStr->getBeginLoc(), SecondStr->getSourceRange(),
10042                       StaticAssertMessage);
10043           Diagnosed = true;
10044           break;
10045         }
10046         break;
10047       }
10048       case Field: {
10049         FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
10050         FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
10051         IdentifierInfo *FirstII = FirstField->getIdentifier();
10052         IdentifierInfo *SecondII = SecondField->getIdentifier();
10053         if (FirstII->getName() != SecondII->getName()) {
10054           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10055                        FieldName)
10056               << FirstII;
10057           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10058                       FieldName)
10059               << SecondII;
10060 
10061           Diagnosed = true;
10062           break;
10063         }
10064 
10065         assert(getContext().hasSameType(FirstField->getType(),
10066                                         SecondField->getType()));
10067 
10068         QualType FirstType = FirstField->getType();
10069         QualType SecondType = SecondField->getType();
10070         if (ComputeQualTypeODRHash(FirstType) !=
10071             ComputeQualTypeODRHash(SecondType)) {
10072           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10073                        FieldTypeName)
10074               << FirstII << FirstType;
10075           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10076                       FieldTypeName)
10077               << SecondII << SecondType;
10078 
10079           Diagnosed = true;
10080           break;
10081         }
10082 
10083         const bool IsFirstBitField = FirstField->isBitField();
10084         const bool IsSecondBitField = SecondField->isBitField();
10085         if (IsFirstBitField != IsSecondBitField) {
10086           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10087                        FieldSingleBitField)
10088               << FirstII << IsFirstBitField;
10089           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10090                       FieldSingleBitField)
10091               << SecondII << IsSecondBitField;
10092           Diagnosed = true;
10093           break;
10094         }
10095 
10096         if (IsFirstBitField && IsSecondBitField) {
10097           unsigned FirstBitWidthHash =
10098               ComputeODRHash(FirstField->getBitWidth());
10099           unsigned SecondBitWidthHash =
10100               ComputeODRHash(SecondField->getBitWidth());
10101           if (FirstBitWidthHash != SecondBitWidthHash) {
10102             ODRDiagError(FirstField->getLocation(),
10103                          FirstField->getSourceRange(),
10104                          FieldDifferentWidthBitField)
10105                 << FirstII << FirstField->getBitWidth()->getSourceRange();
10106             ODRDiagNote(SecondField->getLocation(),
10107                         SecondField->getSourceRange(),
10108                         FieldDifferentWidthBitField)
10109                 << SecondII << SecondField->getBitWidth()->getSourceRange();
10110             Diagnosed = true;
10111             break;
10112           }
10113         }
10114 
10115         const bool IsFirstMutable = FirstField->isMutable();
10116         const bool IsSecondMutable = SecondField->isMutable();
10117         if (IsFirstMutable != IsSecondMutable) {
10118           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10119                        FieldSingleMutable)
10120               << FirstII << IsFirstMutable;
10121           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10122                       FieldSingleMutable)
10123               << SecondII << IsSecondMutable;
10124           Diagnosed = true;
10125           break;
10126         }
10127 
10128         const Expr *FirstInitializer = FirstField->getInClassInitializer();
10129         const Expr *SecondInitializer = SecondField->getInClassInitializer();
10130         if ((!FirstInitializer && SecondInitializer) ||
10131             (FirstInitializer && !SecondInitializer)) {
10132           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10133                        FieldSingleInitializer)
10134               << FirstII << (FirstInitializer != nullptr);
10135           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10136                       FieldSingleInitializer)
10137               << SecondII << (SecondInitializer != nullptr);
10138           Diagnosed = true;
10139           break;
10140         }
10141 
10142         if (FirstInitializer && SecondInitializer) {
10143           unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
10144           unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
10145           if (FirstInitHash != SecondInitHash) {
10146             ODRDiagError(FirstField->getLocation(),
10147                          FirstField->getSourceRange(),
10148                          FieldDifferentInitializers)
10149                 << FirstII << FirstInitializer->getSourceRange();
10150             ODRDiagNote(SecondField->getLocation(),
10151                         SecondField->getSourceRange(),
10152                         FieldDifferentInitializers)
10153                 << SecondII << SecondInitializer->getSourceRange();
10154             Diagnosed = true;
10155             break;
10156           }
10157         }
10158 
10159         break;
10160       }
10161       case CXXMethod: {
10162         enum {
10163           DiagMethod,
10164           DiagConstructor,
10165           DiagDestructor,
10166         } FirstMethodType,
10167             SecondMethodType;
10168         auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10169           if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10170           if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10171           return DiagMethod;
10172         };
10173         const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10174         const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
10175         FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10176         SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
10177         auto FirstName = FirstMethod->getDeclName();
10178         auto SecondName = SecondMethod->getDeclName();
10179         if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
10180           ODRDiagError(FirstMethod->getLocation(),
10181                        FirstMethod->getSourceRange(), MethodName)
10182               << FirstMethodType << FirstName;
10183           ODRDiagNote(SecondMethod->getLocation(),
10184                       SecondMethod->getSourceRange(), MethodName)
10185               << SecondMethodType << SecondName;
10186 
10187           Diagnosed = true;
10188           break;
10189         }
10190 
10191         const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
10192         const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
10193         if (FirstDeleted != SecondDeleted) {
10194           ODRDiagError(FirstMethod->getLocation(),
10195                        FirstMethod->getSourceRange(), MethodDeleted)
10196               << FirstMethodType << FirstName << FirstDeleted;
10197 
10198           ODRDiagNote(SecondMethod->getLocation(),
10199                       SecondMethod->getSourceRange(), MethodDeleted)
10200               << SecondMethodType << SecondName << SecondDeleted;
10201           Diagnosed = true;
10202           break;
10203         }
10204 
10205         const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
10206         const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
10207         if (FirstDefaulted != SecondDefaulted) {
10208           ODRDiagError(FirstMethod->getLocation(),
10209                        FirstMethod->getSourceRange(), MethodDefaulted)
10210               << FirstMethodType << FirstName << FirstDefaulted;
10211 
10212           ODRDiagNote(SecondMethod->getLocation(),
10213                       SecondMethod->getSourceRange(), MethodDefaulted)
10214               << SecondMethodType << SecondName << SecondDefaulted;
10215           Diagnosed = true;
10216           break;
10217         }
10218 
10219         const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10220         const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10221         const bool FirstPure = FirstMethod->isPure();
10222         const bool SecondPure = SecondMethod->isPure();
10223         if ((FirstVirtual || SecondVirtual) &&
10224             (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10225           ODRDiagError(FirstMethod->getLocation(),
10226                        FirstMethod->getSourceRange(), MethodVirtual)
10227               << FirstMethodType << FirstName << FirstPure << FirstVirtual;
10228           ODRDiagNote(SecondMethod->getLocation(),
10229                       SecondMethod->getSourceRange(), MethodVirtual)
10230               << SecondMethodType << SecondName << SecondPure << SecondVirtual;
10231           Diagnosed = true;
10232           break;
10233         }
10234 
10235         // CXXMethodDecl::isStatic uses the canonical Decl.  With Decl merging,
10236         // FirstDecl is the canonical Decl of SecondDecl, so the storage
10237         // class needs to be checked instead.
10238         const auto FirstStorage = FirstMethod->getStorageClass();
10239         const auto SecondStorage = SecondMethod->getStorageClass();
10240         const bool FirstStatic = FirstStorage == SC_Static;
10241         const bool SecondStatic = SecondStorage == SC_Static;
10242         if (FirstStatic != SecondStatic) {
10243           ODRDiagError(FirstMethod->getLocation(),
10244                        FirstMethod->getSourceRange(), MethodStatic)
10245               << FirstMethodType << FirstName << FirstStatic;
10246           ODRDiagNote(SecondMethod->getLocation(),
10247                       SecondMethod->getSourceRange(), MethodStatic)
10248               << SecondMethodType << SecondName << SecondStatic;
10249           Diagnosed = true;
10250           break;
10251         }
10252 
10253         const bool FirstVolatile = FirstMethod->isVolatile();
10254         const bool SecondVolatile = SecondMethod->isVolatile();
10255         if (FirstVolatile != SecondVolatile) {
10256           ODRDiagError(FirstMethod->getLocation(),
10257                        FirstMethod->getSourceRange(), MethodVolatile)
10258               << FirstMethodType << FirstName << FirstVolatile;
10259           ODRDiagNote(SecondMethod->getLocation(),
10260                       SecondMethod->getSourceRange(), MethodVolatile)
10261               << SecondMethodType << SecondName << SecondVolatile;
10262           Diagnosed = true;
10263           break;
10264         }
10265 
10266         const bool FirstConst = FirstMethod->isConst();
10267         const bool SecondConst = SecondMethod->isConst();
10268         if (FirstConst != SecondConst) {
10269           ODRDiagError(FirstMethod->getLocation(),
10270                        FirstMethod->getSourceRange(), MethodConst)
10271               << FirstMethodType << FirstName << FirstConst;
10272           ODRDiagNote(SecondMethod->getLocation(),
10273                       SecondMethod->getSourceRange(), MethodConst)
10274               << SecondMethodType << SecondName << SecondConst;
10275           Diagnosed = true;
10276           break;
10277         }
10278 
10279         const bool FirstInline = FirstMethod->isInlineSpecified();
10280         const bool SecondInline = SecondMethod->isInlineSpecified();
10281         if (FirstInline != SecondInline) {
10282           ODRDiagError(FirstMethod->getLocation(),
10283                        FirstMethod->getSourceRange(), MethodInline)
10284               << FirstMethodType << FirstName << FirstInline;
10285           ODRDiagNote(SecondMethod->getLocation(),
10286                       SecondMethod->getSourceRange(), MethodInline)
10287               << SecondMethodType << SecondName << SecondInline;
10288           Diagnosed = true;
10289           break;
10290         }
10291 
10292         const unsigned FirstNumParameters = FirstMethod->param_size();
10293         const unsigned SecondNumParameters = SecondMethod->param_size();
10294         if (FirstNumParameters != SecondNumParameters) {
10295           ODRDiagError(FirstMethod->getLocation(),
10296                        FirstMethod->getSourceRange(), MethodNumberParameters)
10297               << FirstMethodType << FirstName << FirstNumParameters;
10298           ODRDiagNote(SecondMethod->getLocation(),
10299                       SecondMethod->getSourceRange(), MethodNumberParameters)
10300               << SecondMethodType << SecondName << SecondNumParameters;
10301           Diagnosed = true;
10302           break;
10303         }
10304 
10305         // Need this status boolean to know when break out of the switch.
10306         bool ParameterMismatch = false;
10307         for (unsigned I = 0; I < FirstNumParameters; ++I) {
10308           const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10309           const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10310 
10311           QualType FirstParamType = FirstParam->getType();
10312           QualType SecondParamType = SecondParam->getType();
10313           if (FirstParamType != SecondParamType &&
10314               ComputeQualTypeODRHash(FirstParamType) !=
10315                   ComputeQualTypeODRHash(SecondParamType)) {
10316             if (const DecayedType *ParamDecayedType =
10317                     FirstParamType->getAs<DecayedType>()) {
10318               ODRDiagError(FirstMethod->getLocation(),
10319                            FirstMethod->getSourceRange(), MethodParameterType)
10320                   << FirstMethodType << FirstName << (I + 1) << FirstParamType
10321                   << true << ParamDecayedType->getOriginalType();
10322             } else {
10323               ODRDiagError(FirstMethod->getLocation(),
10324                            FirstMethod->getSourceRange(), MethodParameterType)
10325                   << FirstMethodType << FirstName << (I + 1) << FirstParamType
10326                   << false;
10327             }
10328 
10329             if (const DecayedType *ParamDecayedType =
10330                     SecondParamType->getAs<DecayedType>()) {
10331               ODRDiagNote(SecondMethod->getLocation(),
10332                           SecondMethod->getSourceRange(), MethodParameterType)
10333                   << SecondMethodType << SecondName << (I + 1)
10334                   << SecondParamType << true
10335                   << ParamDecayedType->getOriginalType();
10336             } else {
10337               ODRDiagNote(SecondMethod->getLocation(),
10338                           SecondMethod->getSourceRange(), MethodParameterType)
10339                   << SecondMethodType << SecondName << (I + 1)
10340                   << SecondParamType << false;
10341             }
10342             ParameterMismatch = true;
10343             break;
10344           }
10345 
10346           DeclarationName FirstParamName = FirstParam->getDeclName();
10347           DeclarationName SecondParamName = SecondParam->getDeclName();
10348           if (FirstParamName != SecondParamName) {
10349             ODRDiagError(FirstMethod->getLocation(),
10350                          FirstMethod->getSourceRange(), MethodParameterName)
10351                 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
10352             ODRDiagNote(SecondMethod->getLocation(),
10353                         SecondMethod->getSourceRange(), MethodParameterName)
10354                 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
10355             ParameterMismatch = true;
10356             break;
10357           }
10358 
10359           const Expr *FirstInit = FirstParam->getInit();
10360           const Expr *SecondInit = SecondParam->getInit();
10361           if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10362             ODRDiagError(FirstMethod->getLocation(),
10363                          FirstMethod->getSourceRange(),
10364                          MethodParameterSingleDefaultArgument)
10365                 << FirstMethodType << FirstName << (I + 1)
10366                 << (FirstInit == nullptr)
10367                 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10368             ODRDiagNote(SecondMethod->getLocation(),
10369                         SecondMethod->getSourceRange(),
10370                         MethodParameterSingleDefaultArgument)
10371                 << SecondMethodType << SecondName << (I + 1)
10372                 << (SecondInit == nullptr)
10373                 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10374             ParameterMismatch = true;
10375             break;
10376           }
10377 
10378           if (FirstInit && SecondInit &&
10379               ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10380             ODRDiagError(FirstMethod->getLocation(),
10381                          FirstMethod->getSourceRange(),
10382                          MethodParameterDifferentDefaultArgument)
10383                 << FirstMethodType << FirstName << (I + 1)
10384                 << FirstInit->getSourceRange();
10385             ODRDiagNote(SecondMethod->getLocation(),
10386                         SecondMethod->getSourceRange(),
10387                         MethodParameterDifferentDefaultArgument)
10388                 << SecondMethodType << SecondName << (I + 1)
10389                 << SecondInit->getSourceRange();
10390             ParameterMismatch = true;
10391             break;
10392 
10393           }
10394         }
10395 
10396         if (ParameterMismatch) {
10397           Diagnosed = true;
10398           break;
10399         }
10400 
10401         const auto *FirstTemplateArgs =
10402             FirstMethod->getTemplateSpecializationArgs();
10403         const auto *SecondTemplateArgs =
10404             SecondMethod->getTemplateSpecializationArgs();
10405 
10406         if ((FirstTemplateArgs && !SecondTemplateArgs) ||
10407             (!FirstTemplateArgs && SecondTemplateArgs)) {
10408           ODRDiagError(FirstMethod->getLocation(),
10409                        FirstMethod->getSourceRange(), MethodNoTemplateArguments)
10410               << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
10411           ODRDiagNote(SecondMethod->getLocation(),
10412                       SecondMethod->getSourceRange(), MethodNoTemplateArguments)
10413               << SecondMethodType << SecondName
10414               << (SecondTemplateArgs != nullptr);
10415 
10416           Diagnosed = true;
10417           break;
10418         }
10419 
10420         if (FirstTemplateArgs && SecondTemplateArgs) {
10421           // Remove pack expansions from argument list.
10422           auto ExpandTemplateArgumentList =
10423               [](const TemplateArgumentList *TAL) {
10424                 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
10425                 for (const TemplateArgument &TA : TAL->asArray()) {
10426                   if (TA.getKind() != TemplateArgument::Pack) {
10427                     ExpandedList.push_back(&TA);
10428                     continue;
10429                   }
10430                   for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
10431                     ExpandedList.push_back(&PackTA);
10432                   }
10433                 }
10434                 return ExpandedList;
10435               };
10436           llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
10437               ExpandTemplateArgumentList(FirstTemplateArgs);
10438           llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
10439               ExpandTemplateArgumentList(SecondTemplateArgs);
10440 
10441           if (FirstExpandedList.size() != SecondExpandedList.size()) {
10442             ODRDiagError(FirstMethod->getLocation(),
10443                          FirstMethod->getSourceRange(),
10444                          MethodDifferentNumberTemplateArguments)
10445                 << FirstMethodType << FirstName
10446                 << (unsigned)FirstExpandedList.size();
10447             ODRDiagNote(SecondMethod->getLocation(),
10448                         SecondMethod->getSourceRange(),
10449                         MethodDifferentNumberTemplateArguments)
10450                 << SecondMethodType << SecondName
10451                 << (unsigned)SecondExpandedList.size();
10452 
10453             Diagnosed = true;
10454             break;
10455           }
10456 
10457           bool TemplateArgumentMismatch = false;
10458           for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
10459             const TemplateArgument &FirstTA = *FirstExpandedList[i],
10460                                    &SecondTA = *SecondExpandedList[i];
10461             if (ComputeTemplateArgumentODRHash(FirstTA) ==
10462                 ComputeTemplateArgumentODRHash(SecondTA)) {
10463               continue;
10464             }
10465 
10466             ODRDiagError(FirstMethod->getLocation(),
10467                          FirstMethod->getSourceRange(),
10468                          MethodDifferentTemplateArgument)
10469                 << FirstMethodType << FirstName << FirstTA << i + 1;
10470             ODRDiagNote(SecondMethod->getLocation(),
10471                         SecondMethod->getSourceRange(),
10472                         MethodDifferentTemplateArgument)
10473                 << SecondMethodType << SecondName << SecondTA << i + 1;
10474 
10475             TemplateArgumentMismatch = true;
10476             break;
10477           }
10478 
10479           if (TemplateArgumentMismatch) {
10480             Diagnosed = true;
10481             break;
10482           }
10483         }
10484 
10485         // Compute the hash of the method as if it has no body.
10486         auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
10487           Hash.clear();
10488           Hash.AddFunctionDecl(D, true /*SkipBody*/);
10489           return Hash.CalculateHash();
10490         };
10491 
10492         // Compare the hash generated to the hash stored.  A difference means
10493         // that a body was present in the original source.  Due to merging,
10494         // the stardard way of detecting a body will not work.
10495         const bool HasFirstBody =
10496             ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
10497         const bool HasSecondBody =
10498             ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
10499 
10500         if (HasFirstBody != HasSecondBody) {
10501           ODRDiagError(FirstMethod->getLocation(),
10502                        FirstMethod->getSourceRange(), MethodSingleBody)
10503               << FirstMethodType << FirstName << HasFirstBody;
10504           ODRDiagNote(SecondMethod->getLocation(),
10505                       SecondMethod->getSourceRange(), MethodSingleBody)
10506               << SecondMethodType << SecondName << HasSecondBody;
10507           Diagnosed = true;
10508           break;
10509         }
10510 
10511         if (HasFirstBody && HasSecondBody) {
10512           ODRDiagError(FirstMethod->getLocation(),
10513                        FirstMethod->getSourceRange(), MethodDifferentBody)
10514               << FirstMethodType << FirstName;
10515           ODRDiagNote(SecondMethod->getLocation(),
10516                       SecondMethod->getSourceRange(), MethodDifferentBody)
10517               << SecondMethodType << SecondName;
10518           Diagnosed = true;
10519           break;
10520         }
10521 
10522         break;
10523       }
10524       case TypeAlias:
10525       case TypeDef: {
10526         TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
10527         TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
10528         auto FirstName = FirstTD->getDeclName();
10529         auto SecondName = SecondTD->getDeclName();
10530         if (FirstName != SecondName) {
10531           ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10532                        TypedefName)
10533               << (FirstDiffType == TypeAlias) << FirstName;
10534           ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10535                       TypedefName)
10536               << (FirstDiffType == TypeAlias) << SecondName;
10537           Diagnosed = true;
10538           break;
10539         }
10540 
10541         QualType FirstType = FirstTD->getUnderlyingType();
10542         QualType SecondType = SecondTD->getUnderlyingType();
10543         if (ComputeQualTypeODRHash(FirstType) !=
10544             ComputeQualTypeODRHash(SecondType)) {
10545           ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10546                        TypedefType)
10547               << (FirstDiffType == TypeAlias) << FirstName << FirstType;
10548           ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10549                       TypedefType)
10550               << (FirstDiffType == TypeAlias) << SecondName << SecondType;
10551           Diagnosed = true;
10552           break;
10553         }
10554         break;
10555       }
10556       case Var: {
10557         VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
10558         VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
10559         auto FirstName = FirstVD->getDeclName();
10560         auto SecondName = SecondVD->getDeclName();
10561         if (FirstName != SecondName) {
10562           ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10563                        VarName)
10564               << FirstName;
10565           ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10566                       VarName)
10567               << SecondName;
10568           Diagnosed = true;
10569           break;
10570         }
10571 
10572         QualType FirstType = FirstVD->getType();
10573         QualType SecondType = SecondVD->getType();
10574         if (ComputeQualTypeODRHash(FirstType) !=
10575                         ComputeQualTypeODRHash(SecondType)) {
10576           ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10577                        VarType)
10578               << FirstName << FirstType;
10579           ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10580                       VarType)
10581               << SecondName << SecondType;
10582           Diagnosed = true;
10583           break;
10584         }
10585 
10586         const Expr *FirstInit = FirstVD->getInit();
10587         const Expr *SecondInit = SecondVD->getInit();
10588         if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10589           ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10590                        VarSingleInitializer)
10591               << FirstName << (FirstInit == nullptr)
10592               << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
10593           ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10594                       VarSingleInitializer)
10595               << SecondName << (SecondInit == nullptr)
10596               << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10597           Diagnosed = true;
10598           break;
10599         }
10600 
10601         if (FirstInit && SecondInit &&
10602             ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10603           ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10604                        VarDifferentInitializer)
10605               << FirstName << FirstInit->getSourceRange();
10606           ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10607                       VarDifferentInitializer)
10608               << SecondName << SecondInit->getSourceRange();
10609           Diagnosed = true;
10610           break;
10611         }
10612 
10613         const bool FirstIsConstexpr = FirstVD->isConstexpr();
10614         const bool SecondIsConstexpr = SecondVD->isConstexpr();
10615         if (FirstIsConstexpr != SecondIsConstexpr) {
10616           ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10617                        VarConstexpr)
10618               << FirstName << FirstIsConstexpr;
10619           ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10620                       VarConstexpr)
10621               << SecondName << SecondIsConstexpr;
10622           Diagnosed = true;
10623           break;
10624         }
10625         break;
10626       }
10627       case Friend: {
10628         FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10629         FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
10630 
10631         NamedDecl *FirstND = FirstFriend->getFriendDecl();
10632         NamedDecl *SecondND = SecondFriend->getFriendDecl();
10633 
10634         TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10635         TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10636 
10637         if (FirstND && SecondND) {
10638           ODRDiagError(FirstFriend->getFriendLoc(),
10639                        FirstFriend->getSourceRange(), FriendFunction)
10640               << FirstND;
10641           ODRDiagNote(SecondFriend->getFriendLoc(),
10642                       SecondFriend->getSourceRange(), FriendFunction)
10643               << SecondND;
10644 
10645           Diagnosed = true;
10646           break;
10647         }
10648 
10649         if (FirstTSI && SecondTSI) {
10650           QualType FirstFriendType = FirstTSI->getType();
10651           QualType SecondFriendType = SecondTSI->getType();
10652           assert(ComputeQualTypeODRHash(FirstFriendType) !=
10653                  ComputeQualTypeODRHash(SecondFriendType));
10654           ODRDiagError(FirstFriend->getFriendLoc(),
10655                        FirstFriend->getSourceRange(), FriendType)
10656               << FirstFriendType;
10657           ODRDiagNote(SecondFriend->getFriendLoc(),
10658                       SecondFriend->getSourceRange(), FriendType)
10659               << SecondFriendType;
10660           Diagnosed = true;
10661           break;
10662         }
10663 
10664         ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
10665                      FriendTypeFunction)
10666             << (FirstTSI == nullptr);
10667         ODRDiagNote(SecondFriend->getFriendLoc(),
10668                     SecondFriend->getSourceRange(), FriendTypeFunction)
10669             << (SecondTSI == nullptr);
10670 
10671         Diagnosed = true;
10672         break;
10673       }
10674       case FunctionTemplate: {
10675         FunctionTemplateDecl *FirstTemplate =
10676             cast<FunctionTemplateDecl>(FirstDecl);
10677         FunctionTemplateDecl *SecondTemplate =
10678             cast<FunctionTemplateDecl>(SecondDecl);
10679 
10680         TemplateParameterList *FirstTPL =
10681             FirstTemplate->getTemplateParameters();
10682         TemplateParameterList *SecondTPL =
10683             SecondTemplate->getTemplateParameters();
10684 
10685         if (FirstTPL->size() != SecondTPL->size()) {
10686           ODRDiagError(FirstTemplate->getLocation(),
10687                        FirstTemplate->getSourceRange(),
10688                        FunctionTemplateDifferentNumberParameters)
10689               << FirstTemplate << FirstTPL->size();
10690           ODRDiagNote(SecondTemplate->getLocation(),
10691                       SecondTemplate->getSourceRange(),
10692                       FunctionTemplateDifferentNumberParameters)
10693               << SecondTemplate  << SecondTPL->size();
10694 
10695           Diagnosed = true;
10696           break;
10697         }
10698 
10699         bool ParameterMismatch = false;
10700         for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
10701           NamedDecl *FirstParam = FirstTPL->getParam(i);
10702           NamedDecl *SecondParam = SecondTPL->getParam(i);
10703 
10704           if (FirstParam->getKind() != SecondParam->getKind()) {
10705             enum {
10706               TemplateTypeParameter,
10707               NonTypeTemplateParameter,
10708               TemplateTemplateParameter,
10709             };
10710             auto GetParamType = [](NamedDecl *D) {
10711               switch (D->getKind()) {
10712                 default:
10713                   llvm_unreachable("Unexpected template parameter type");
10714                 case Decl::TemplateTypeParm:
10715                   return TemplateTypeParameter;
10716                 case Decl::NonTypeTemplateParm:
10717                   return NonTypeTemplateParameter;
10718                 case Decl::TemplateTemplateParm:
10719                   return TemplateTemplateParameter;
10720               }
10721             };
10722 
10723             ODRDiagError(FirstTemplate->getLocation(),
10724                          FirstTemplate->getSourceRange(),
10725                          FunctionTemplateParameterDifferentKind)
10726                 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
10727             ODRDiagNote(SecondTemplate->getLocation(),
10728                         SecondTemplate->getSourceRange(),
10729                         FunctionTemplateParameterDifferentKind)
10730                 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
10731 
10732             ParameterMismatch = true;
10733             break;
10734           }
10735 
10736           if (FirstParam->getName() != SecondParam->getName()) {
10737             ODRDiagError(FirstTemplate->getLocation(),
10738                          FirstTemplate->getSourceRange(),
10739                          FunctionTemplateParameterName)
10740                 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
10741                 << FirstParam;
10742             ODRDiagNote(SecondTemplate->getLocation(),
10743                         SecondTemplate->getSourceRange(),
10744                         FunctionTemplateParameterName)
10745                 << SecondTemplate << (i + 1)
10746                 << (bool)SecondParam->getIdentifier() << SecondParam;
10747             ParameterMismatch = true;
10748             break;
10749           }
10750 
10751           if (isa<TemplateTypeParmDecl>(FirstParam) &&
10752               isa<TemplateTypeParmDecl>(SecondParam)) {
10753             TemplateTypeParmDecl *FirstTTPD =
10754                 cast<TemplateTypeParmDecl>(FirstParam);
10755             TemplateTypeParmDecl *SecondTTPD =
10756                 cast<TemplateTypeParmDecl>(SecondParam);
10757             bool HasFirstDefaultArgument =
10758                 FirstTTPD->hasDefaultArgument() &&
10759                 !FirstTTPD->defaultArgumentWasInherited();
10760             bool HasSecondDefaultArgument =
10761                 SecondTTPD->hasDefaultArgument() &&
10762                 !SecondTTPD->defaultArgumentWasInherited();
10763             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10764               ODRDiagError(FirstTemplate->getLocation(),
10765                            FirstTemplate->getSourceRange(),
10766                            FunctionTemplateParameterSingleDefaultArgument)
10767                   << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10768               ODRDiagNote(SecondTemplate->getLocation(),
10769                           SecondTemplate->getSourceRange(),
10770                           FunctionTemplateParameterSingleDefaultArgument)
10771                   << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10772               ParameterMismatch = true;
10773               break;
10774             }
10775 
10776             if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10777               QualType FirstType = FirstTTPD->getDefaultArgument();
10778               QualType SecondType = SecondTTPD->getDefaultArgument();
10779               if (ComputeQualTypeODRHash(FirstType) !=
10780                   ComputeQualTypeODRHash(SecondType)) {
10781                 ODRDiagError(FirstTemplate->getLocation(),
10782                              FirstTemplate->getSourceRange(),
10783                              FunctionTemplateParameterDifferentDefaultArgument)
10784                     << FirstTemplate << (i + 1) << FirstType;
10785                 ODRDiagNote(SecondTemplate->getLocation(),
10786                             SecondTemplate->getSourceRange(),
10787                             FunctionTemplateParameterDifferentDefaultArgument)
10788                     << SecondTemplate << (i + 1) << SecondType;
10789                 ParameterMismatch = true;
10790                 break;
10791               }
10792             }
10793 
10794             if (FirstTTPD->isParameterPack() !=
10795                 SecondTTPD->isParameterPack()) {
10796               ODRDiagError(FirstTemplate->getLocation(),
10797                            FirstTemplate->getSourceRange(),
10798                            FunctionTemplatePackParameter)
10799                   << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
10800               ODRDiagNote(SecondTemplate->getLocation(),
10801                           SecondTemplate->getSourceRange(),
10802                           FunctionTemplatePackParameter)
10803                   << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
10804               ParameterMismatch = true;
10805               break;
10806             }
10807           }
10808 
10809           if (isa<TemplateTemplateParmDecl>(FirstParam) &&
10810               isa<TemplateTemplateParmDecl>(SecondParam)) {
10811             TemplateTemplateParmDecl *FirstTTPD =
10812                 cast<TemplateTemplateParmDecl>(FirstParam);
10813             TemplateTemplateParmDecl *SecondTTPD =
10814                 cast<TemplateTemplateParmDecl>(SecondParam);
10815 
10816             TemplateParameterList *FirstTPL =
10817                 FirstTTPD->getTemplateParameters();
10818             TemplateParameterList *SecondTPL =
10819                 SecondTTPD->getTemplateParameters();
10820 
10821             if (ComputeTemplateParameterListODRHash(FirstTPL) !=
10822                 ComputeTemplateParameterListODRHash(SecondTPL)) {
10823               ODRDiagError(FirstTemplate->getLocation(),
10824                            FirstTemplate->getSourceRange(),
10825                            FunctionTemplateParameterDifferentType)
10826                   << FirstTemplate << (i + 1);
10827               ODRDiagNote(SecondTemplate->getLocation(),
10828                           SecondTemplate->getSourceRange(),
10829                           FunctionTemplateParameterDifferentType)
10830                   << SecondTemplate << (i + 1);
10831               ParameterMismatch = true;
10832               break;
10833             }
10834 
10835             bool HasFirstDefaultArgument =
10836                 FirstTTPD->hasDefaultArgument() &&
10837                 !FirstTTPD->defaultArgumentWasInherited();
10838             bool HasSecondDefaultArgument =
10839                 SecondTTPD->hasDefaultArgument() &&
10840                 !SecondTTPD->defaultArgumentWasInherited();
10841             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10842               ODRDiagError(FirstTemplate->getLocation(),
10843                            FirstTemplate->getSourceRange(),
10844                            FunctionTemplateParameterSingleDefaultArgument)
10845                   << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10846               ODRDiagNote(SecondTemplate->getLocation(),
10847                           SecondTemplate->getSourceRange(),
10848                           FunctionTemplateParameterSingleDefaultArgument)
10849                   << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10850               ParameterMismatch = true;
10851               break;
10852             }
10853 
10854             if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10855               TemplateArgument FirstTA =
10856                   FirstTTPD->getDefaultArgument().getArgument();
10857               TemplateArgument SecondTA =
10858                   SecondTTPD->getDefaultArgument().getArgument();
10859               if (ComputeTemplateArgumentODRHash(FirstTA) !=
10860                   ComputeTemplateArgumentODRHash(SecondTA)) {
10861                 ODRDiagError(FirstTemplate->getLocation(),
10862                              FirstTemplate->getSourceRange(),
10863                              FunctionTemplateParameterDifferentDefaultArgument)
10864                     << FirstTemplate << (i + 1) << FirstTA;
10865                 ODRDiagNote(SecondTemplate->getLocation(),
10866                             SecondTemplate->getSourceRange(),
10867                             FunctionTemplateParameterDifferentDefaultArgument)
10868                     << SecondTemplate << (i + 1) << SecondTA;
10869                 ParameterMismatch = true;
10870                 break;
10871               }
10872             }
10873 
10874             if (FirstTTPD->isParameterPack() !=
10875                 SecondTTPD->isParameterPack()) {
10876               ODRDiagError(FirstTemplate->getLocation(),
10877                            FirstTemplate->getSourceRange(),
10878                            FunctionTemplatePackParameter)
10879                   << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
10880               ODRDiagNote(SecondTemplate->getLocation(),
10881                           SecondTemplate->getSourceRange(),
10882                           FunctionTemplatePackParameter)
10883                   << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
10884               ParameterMismatch = true;
10885               break;
10886             }
10887           }
10888 
10889           if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
10890               isa<NonTypeTemplateParmDecl>(SecondParam)) {
10891             NonTypeTemplateParmDecl *FirstNTTPD =
10892                 cast<NonTypeTemplateParmDecl>(FirstParam);
10893             NonTypeTemplateParmDecl *SecondNTTPD =
10894                 cast<NonTypeTemplateParmDecl>(SecondParam);
10895 
10896             QualType FirstType = FirstNTTPD->getType();
10897             QualType SecondType = SecondNTTPD->getType();
10898             if (ComputeQualTypeODRHash(FirstType) !=
10899                 ComputeQualTypeODRHash(SecondType)) {
10900               ODRDiagError(FirstTemplate->getLocation(),
10901                            FirstTemplate->getSourceRange(),
10902                            FunctionTemplateParameterDifferentType)
10903                   << FirstTemplate << (i + 1);
10904               ODRDiagNote(SecondTemplate->getLocation(),
10905                           SecondTemplate->getSourceRange(),
10906                           FunctionTemplateParameterDifferentType)
10907                   << SecondTemplate << (i + 1);
10908               ParameterMismatch = true;
10909               break;
10910             }
10911 
10912             bool HasFirstDefaultArgument =
10913                 FirstNTTPD->hasDefaultArgument() &&
10914                 !FirstNTTPD->defaultArgumentWasInherited();
10915             bool HasSecondDefaultArgument =
10916                 SecondNTTPD->hasDefaultArgument() &&
10917                 !SecondNTTPD->defaultArgumentWasInherited();
10918             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10919               ODRDiagError(FirstTemplate->getLocation(),
10920                            FirstTemplate->getSourceRange(),
10921                            FunctionTemplateParameterSingleDefaultArgument)
10922                   << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10923               ODRDiagNote(SecondTemplate->getLocation(),
10924                           SecondTemplate->getSourceRange(),
10925                           FunctionTemplateParameterSingleDefaultArgument)
10926                   << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10927               ParameterMismatch = true;
10928               break;
10929             }
10930 
10931             if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10932               Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
10933               Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
10934               if (ComputeODRHash(FirstDefaultArgument) !=
10935                   ComputeODRHash(SecondDefaultArgument)) {
10936                 ODRDiagError(FirstTemplate->getLocation(),
10937                              FirstTemplate->getSourceRange(),
10938                              FunctionTemplateParameterDifferentDefaultArgument)
10939                     << FirstTemplate << (i + 1) << FirstDefaultArgument;
10940                 ODRDiagNote(SecondTemplate->getLocation(),
10941                             SecondTemplate->getSourceRange(),
10942                             FunctionTemplateParameterDifferentDefaultArgument)
10943                     << SecondTemplate << (i + 1) << SecondDefaultArgument;
10944                 ParameterMismatch = true;
10945                 break;
10946               }
10947             }
10948 
10949             if (FirstNTTPD->isParameterPack() !=
10950                 SecondNTTPD->isParameterPack()) {
10951               ODRDiagError(FirstTemplate->getLocation(),
10952                            FirstTemplate->getSourceRange(),
10953                            FunctionTemplatePackParameter)
10954                   << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
10955               ODRDiagNote(SecondTemplate->getLocation(),
10956                           SecondTemplate->getSourceRange(),
10957                           FunctionTemplatePackParameter)
10958                   << SecondTemplate << (i + 1)
10959                   << SecondNTTPD->isParameterPack();
10960               ParameterMismatch = true;
10961               break;
10962             }
10963           }
10964         }
10965 
10966         if (ParameterMismatch) {
10967           Diagnosed = true;
10968           break;
10969         }
10970 
10971         break;
10972       }
10973       }
10974 
10975       if (Diagnosed)
10976         continue;
10977 
10978       Diag(FirstDecl->getLocation(),
10979            diag::err_module_odr_violation_mismatch_decl_unknown)
10980           << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
10981           << FirstDecl->getSourceRange();
10982       Diag(SecondDecl->getLocation(),
10983            diag::note_module_odr_violation_mismatch_decl_unknown)
10984           << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
10985       Diagnosed = true;
10986     }
10987 
10988     if (!Diagnosed) {
10989       // All definitions are updates to the same declaration. This happens if a
10990       // module instantiates the declaration of a class template specialization
10991       // and two or more other modules instantiate its definition.
10992       //
10993       // FIXME: Indicate which modules had instantiations of this definition.
10994       // FIXME: How can this even happen?
10995       Diag(Merge.first->getLocation(),
10996            diag::err_module_odr_violation_different_instantiations)
10997         << Merge.first;
10998     }
10999   }
11000 
11001   // Issue ODR failures diagnostics for functions.
11002   for (auto &Merge : FunctionOdrMergeFailures) {
11003     enum ODRFunctionDifference {
11004       ReturnType,
11005       ParameterName,
11006       ParameterType,
11007       ParameterSingleDefaultArgument,
11008       ParameterDifferentDefaultArgument,
11009       FunctionBody,
11010     };
11011 
11012     FunctionDecl *FirstFunction = Merge.first;
11013     std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
11014 
11015     bool Diagnosed = false;
11016     for (auto &SecondFunction : Merge.second) {
11017 
11018       if (FirstFunction == SecondFunction)
11019         continue;
11020 
11021       std::string SecondModule =
11022           getOwningModuleNameForDiagnostic(SecondFunction);
11023 
11024       auto ODRDiagError = [FirstFunction, &FirstModule,
11025                            this](SourceLocation Loc, SourceRange Range,
11026                                  ODRFunctionDifference DiffType) {
11027         return Diag(Loc, diag::err_module_odr_violation_function)
11028                << FirstFunction << FirstModule.empty() << FirstModule << Range
11029                << DiffType;
11030       };
11031       auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11032                                                SourceRange Range,
11033                                                ODRFunctionDifference DiffType) {
11034         return Diag(Loc, diag::note_module_odr_violation_function)
11035                << SecondModule << Range << DiffType;
11036       };
11037 
11038       if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11039           ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11040         ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11041                      FirstFunction->getReturnTypeSourceRange(), ReturnType)
11042             << FirstFunction->getReturnType();
11043         ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11044                     SecondFunction->getReturnTypeSourceRange(), ReturnType)
11045             << SecondFunction->getReturnType();
11046         Diagnosed = true;
11047         break;
11048       }
11049 
11050       assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11051              "Merged functions with different number of parameters");
11052 
11053       auto ParamSize = FirstFunction->param_size();
11054       bool ParameterMismatch = false;
11055       for (unsigned I = 0; I < ParamSize; ++I) {
11056         auto *FirstParam = FirstFunction->getParamDecl(I);
11057         auto *SecondParam = SecondFunction->getParamDecl(I);
11058 
11059         assert(getContext().hasSameType(FirstParam->getType(),
11060                                       SecondParam->getType()) &&
11061                "Merged function has different parameter types.");
11062 
11063         if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11064           ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11065                        ParameterName)
11066               << I + 1 << FirstParam->getDeclName();
11067           ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11068                       ParameterName)
11069               << I + 1 << SecondParam->getDeclName();
11070           ParameterMismatch = true;
11071           break;
11072         };
11073 
11074         QualType FirstParamType = FirstParam->getType();
11075         QualType SecondParamType = SecondParam->getType();
11076         if (FirstParamType != SecondParamType &&
11077             ComputeQualTypeODRHash(FirstParamType) !=
11078                 ComputeQualTypeODRHash(SecondParamType)) {
11079           if (const DecayedType *ParamDecayedType =
11080                   FirstParamType->getAs<DecayedType>()) {
11081             ODRDiagError(FirstParam->getLocation(),
11082                          FirstParam->getSourceRange(), ParameterType)
11083                 << (I + 1) << FirstParamType << true
11084                 << ParamDecayedType->getOriginalType();
11085           } else {
11086             ODRDiagError(FirstParam->getLocation(),
11087                          FirstParam->getSourceRange(), ParameterType)
11088                 << (I + 1) << FirstParamType << false;
11089           }
11090 
11091           if (const DecayedType *ParamDecayedType =
11092                   SecondParamType->getAs<DecayedType>()) {
11093             ODRDiagNote(SecondParam->getLocation(),
11094                         SecondParam->getSourceRange(), ParameterType)
11095                 << (I + 1) << SecondParamType << true
11096                 << ParamDecayedType->getOriginalType();
11097           } else {
11098             ODRDiagNote(SecondParam->getLocation(),
11099                         SecondParam->getSourceRange(), ParameterType)
11100                 << (I + 1) << SecondParamType << false;
11101           }
11102           ParameterMismatch = true;
11103           break;
11104         }
11105 
11106         const Expr *FirstInit = FirstParam->getInit();
11107         const Expr *SecondInit = SecondParam->getInit();
11108         if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11109           ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11110                        ParameterSingleDefaultArgument)
11111               << (I + 1) << (FirstInit == nullptr)
11112               << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11113           ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11114                       ParameterSingleDefaultArgument)
11115               << (I + 1) << (SecondInit == nullptr)
11116               << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11117           ParameterMismatch = true;
11118           break;
11119         }
11120 
11121         if (FirstInit && SecondInit &&
11122             ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11123           ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11124                        ParameterDifferentDefaultArgument)
11125               << (I + 1) << FirstInit->getSourceRange();
11126           ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11127                       ParameterDifferentDefaultArgument)
11128               << (I + 1) << SecondInit->getSourceRange();
11129           ParameterMismatch = true;
11130           break;
11131         }
11132 
11133         assert(ComputeSubDeclODRHash(FirstParam) ==
11134                    ComputeSubDeclODRHash(SecondParam) &&
11135                "Undiagnosed parameter difference.");
11136       }
11137 
11138       if (ParameterMismatch) {
11139         Diagnosed = true;
11140         break;
11141       }
11142 
11143       // If no error has been generated before now, assume the problem is in
11144       // the body and generate a message.
11145       ODRDiagError(FirstFunction->getLocation(),
11146                    FirstFunction->getSourceRange(), FunctionBody);
11147       ODRDiagNote(SecondFunction->getLocation(),
11148                   SecondFunction->getSourceRange(), FunctionBody);
11149       Diagnosed = true;
11150       break;
11151     }
11152     (void)Diagnosed;
11153     assert(Diagnosed && "Unable to emit ODR diagnostic.");
11154   }
11155 
11156   // Issue ODR failures diagnostics for enums.
11157   for (auto &Merge : EnumOdrMergeFailures) {
11158     enum ODREnumDifference {
11159       SingleScopedEnum,
11160       EnumTagKeywordMismatch,
11161       SingleSpecifiedType,
11162       DifferentSpecifiedTypes,
11163       DifferentNumberEnumConstants,
11164       EnumConstantName,
11165       EnumConstantSingleInitilizer,
11166       EnumConstantDifferentInitilizer,
11167     };
11168 
11169     // If we've already pointed out a specific problem with this enum, don't
11170     // bother issuing a general "something's different" diagnostic.
11171     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11172       continue;
11173 
11174     EnumDecl *FirstEnum = Merge.first;
11175     std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
11176 
11177     using DeclHashes =
11178         llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
11179     auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
11180                               DeclHashes &Hashes, EnumDecl *Enum) {
11181       for (auto *D : Enum->decls()) {
11182         // Due to decl merging, the first EnumDecl is the parent of
11183         // Decls in both records.
11184         if (!ODRHash::isWhitelistedDecl(D, FirstEnum))
11185           continue;
11186         assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
11187         Hashes.emplace_back(cast<EnumConstantDecl>(D),
11188                             ComputeSubDeclODRHash(D));
11189       }
11190     };
11191     DeclHashes FirstHashes;
11192     PopulateHashes(FirstHashes, FirstEnum);
11193     bool Diagnosed = false;
11194     for (auto &SecondEnum : Merge.second) {
11195 
11196       if (FirstEnum == SecondEnum)
11197         continue;
11198 
11199       std::string SecondModule =
11200           getOwningModuleNameForDiagnostic(SecondEnum);
11201 
11202       auto ODRDiagError = [FirstEnum, &FirstModule,
11203                            this](SourceLocation Loc, SourceRange Range,
11204                                  ODREnumDifference DiffType) {
11205         return Diag(Loc, diag::err_module_odr_violation_enum)
11206                << FirstEnum << FirstModule.empty() << FirstModule << Range
11207                << DiffType;
11208       };
11209       auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11210                                                SourceRange Range,
11211                                                ODREnumDifference DiffType) {
11212         return Diag(Loc, diag::note_module_odr_violation_enum)
11213                << SecondModule << Range << DiffType;
11214       };
11215 
11216       if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
11217         ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11218                      SingleScopedEnum)
11219             << FirstEnum->isScoped();
11220         ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11221                     SingleScopedEnum)
11222             << SecondEnum->isScoped();
11223         Diagnosed = true;
11224         continue;
11225       }
11226 
11227       if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
11228         if (FirstEnum->isScopedUsingClassTag() !=
11229             SecondEnum->isScopedUsingClassTag()) {
11230           ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11231                        EnumTagKeywordMismatch)
11232               << FirstEnum->isScopedUsingClassTag();
11233           ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11234                       EnumTagKeywordMismatch)
11235               << SecondEnum->isScopedUsingClassTag();
11236           Diagnosed = true;
11237           continue;
11238         }
11239       }
11240 
11241       QualType FirstUnderlyingType =
11242           FirstEnum->getIntegerTypeSourceInfo()
11243               ? FirstEnum->getIntegerTypeSourceInfo()->getType()
11244               : QualType();
11245       QualType SecondUnderlyingType =
11246           SecondEnum->getIntegerTypeSourceInfo()
11247               ? SecondEnum->getIntegerTypeSourceInfo()->getType()
11248               : QualType();
11249       if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
11250           ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11251                        SingleSpecifiedType)
11252               << !FirstUnderlyingType.isNull();
11253           ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11254                       SingleSpecifiedType)
11255               << !SecondUnderlyingType.isNull();
11256           Diagnosed = true;
11257           continue;
11258       }
11259 
11260       if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
11261         if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
11262             ComputeQualTypeODRHash(SecondUnderlyingType)) {
11263           ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11264                        DifferentSpecifiedTypes)
11265               << FirstUnderlyingType;
11266           ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11267                       DifferentSpecifiedTypes)
11268               << SecondUnderlyingType;
11269           Diagnosed = true;
11270           continue;
11271         }
11272       }
11273 
11274       DeclHashes SecondHashes;
11275       PopulateHashes(SecondHashes, SecondEnum);
11276 
11277       if (FirstHashes.size() != SecondHashes.size()) {
11278         ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11279                      DifferentNumberEnumConstants)
11280             << (int)FirstHashes.size();
11281         ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11282                     DifferentNumberEnumConstants)
11283             << (int)SecondHashes.size();
11284         Diagnosed = true;
11285         continue;
11286       }
11287 
11288       for (unsigned I = 0; I < FirstHashes.size(); ++I) {
11289         if (FirstHashes[I].second == SecondHashes[I].second)
11290           continue;
11291         const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
11292         const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
11293 
11294         if (FirstEnumConstant->getDeclName() !=
11295             SecondEnumConstant->getDeclName()) {
11296 
11297           ODRDiagError(FirstEnumConstant->getLocation(),
11298                        FirstEnumConstant->getSourceRange(), EnumConstantName)
11299               << I + 1 << FirstEnumConstant;
11300           ODRDiagNote(SecondEnumConstant->getLocation(),
11301                       SecondEnumConstant->getSourceRange(), EnumConstantName)
11302               << I + 1 << SecondEnumConstant;
11303           Diagnosed = true;
11304           break;
11305         }
11306 
11307         const Expr *FirstInit = FirstEnumConstant->getInitExpr();
11308         const Expr *SecondInit = SecondEnumConstant->getInitExpr();
11309         if (!FirstInit && !SecondInit)
11310           continue;
11311 
11312         if (!FirstInit || !SecondInit) {
11313           ODRDiagError(FirstEnumConstant->getLocation(),
11314                        FirstEnumConstant->getSourceRange(),
11315                        EnumConstantSingleInitilizer)
11316               << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
11317           ODRDiagNote(SecondEnumConstant->getLocation(),
11318                       SecondEnumConstant->getSourceRange(),
11319                       EnumConstantSingleInitilizer)
11320               << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
11321           Diagnosed = true;
11322           break;
11323         }
11324 
11325         if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11326           ODRDiagError(FirstEnumConstant->getLocation(),
11327                        FirstEnumConstant->getSourceRange(),
11328                        EnumConstantDifferentInitilizer)
11329               << I + 1 << FirstEnumConstant;
11330           ODRDiagNote(SecondEnumConstant->getLocation(),
11331                       SecondEnumConstant->getSourceRange(),
11332                       EnumConstantDifferentInitilizer)
11333               << I + 1 << SecondEnumConstant;
11334           Diagnosed = true;
11335           break;
11336         }
11337       }
11338     }
11339 
11340     (void)Diagnosed;
11341     assert(Diagnosed && "Unable to emit ODR diagnostic.");
11342   }
11343 }
11344 
11345 void ASTReader::StartedDeserializing() {
11346   if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
11347     ReadTimer->startTimer();
11348 }
11349 
11350 void ASTReader::FinishedDeserializing() {
11351   assert(NumCurrentElementsDeserializing &&
11352          "FinishedDeserializing not paired with StartedDeserializing");
11353   if (NumCurrentElementsDeserializing == 1) {
11354     // We decrease NumCurrentElementsDeserializing only after pending actions
11355     // are finished, to avoid recursively re-calling finishPendingActions().
11356     finishPendingActions();
11357   }
11358   --NumCurrentElementsDeserializing;
11359 
11360   if (NumCurrentElementsDeserializing == 0) {
11361     // Propagate exception specification and deduced type updates along
11362     // redeclaration chains.
11363     //
11364     // We do this now rather than in finishPendingActions because we want to
11365     // be able to walk the complete redeclaration chains of the updated decls.
11366     while (!PendingExceptionSpecUpdates.empty() ||
11367            !PendingDeducedTypeUpdates.empty()) {
11368       auto ESUpdates = std::move(PendingExceptionSpecUpdates);
11369       PendingExceptionSpecUpdates.clear();
11370       for (auto Update : ESUpdates) {
11371         ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11372         auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
11373         auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
11374         if (auto *Listener = getContext().getASTMutationListener())
11375           Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
11376         for (auto *Redecl : Update.second->redecls())
11377           getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
11378       }
11379 
11380       auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11381       PendingDeducedTypeUpdates.clear();
11382       for (auto Update : DTUpdates) {
11383         ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11384         // FIXME: If the return type is already deduced, check that it matches.
11385         getContext().adjustDeducedFunctionResultType(Update.first,
11386                                                      Update.second);
11387       }
11388     }
11389 
11390     if (ReadTimer)
11391       ReadTimer->stopTimer();
11392 
11393     diagnoseOdrViolations();
11394 
11395     // We are not in recursive loading, so it's safe to pass the "interesting"
11396     // decls to the consumer.
11397     if (Consumer)
11398       PassInterestingDeclsToConsumer();
11399   }
11400 }
11401 
11402 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
11403   if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11404     // Remove any fake results before adding any real ones.
11405     auto It = PendingFakeLookupResults.find(II);
11406     if (It != PendingFakeLookupResults.end()) {
11407       for (auto *ND : It->second)
11408         SemaObj->IdResolver.RemoveDecl(ND);
11409       // FIXME: this works around module+PCH performance issue.
11410       // Rather than erase the result from the map, which is O(n), just clear
11411       // the vector of NamedDecls.
11412       It->second.clear();
11413     }
11414   }
11415 
11416   if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11417     SemaObj->TUScope->AddDecl(D);
11418   } else if (SemaObj->TUScope) {
11419     // Adding the decl to IdResolver may have failed because it was already in
11420     // (even though it was not added in scope). If it is already in, make sure
11421     // it gets in the scope as well.
11422     if (std::find(SemaObj->IdResolver.begin(Name),
11423                   SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
11424       SemaObj->TUScope->AddDecl(D);
11425   }
11426 }
11427 
11428 ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
11429                      ASTContext *Context,
11430                      const PCHContainerReader &PCHContainerRdr,
11431                      ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11432                      StringRef isysroot, bool DisableValidation,
11433                      bool AllowASTWithCompilerErrors,
11434                      bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11435                      bool ValidateASTInputFilesContent, bool UseGlobalIndex,
11436                      std::unique_ptr<llvm::Timer> ReadTimer)
11437     : Listener(DisableValidation
11438                    ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
11439                    : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
11440       SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
11441       PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
11442       ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
11443                                      PCHContainerRdr, PP.getHeaderSearchInfo()),
11444       DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
11445       DisableValidation(DisableValidation),
11446       AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11447       AllowConfigurationMismatch(AllowConfigurationMismatch),
11448       ValidateSystemInputs(ValidateSystemInputs),
11449       ValidateASTInputFilesContent(ValidateASTInputFilesContent),
11450       UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
11451   SourceMgr.setExternalSLocEntrySource(this);
11452 
11453   for (const auto &Ext : Extensions) {
11454     auto BlockName = Ext->getExtensionMetadata().BlockName;
11455     auto Known = ModuleFileExtensions.find(BlockName);
11456     if (Known != ModuleFileExtensions.end()) {
11457       Diags.Report(diag::warn_duplicate_module_file_extension)
11458         << BlockName;
11459       continue;
11460     }
11461 
11462     ModuleFileExtensions.insert({BlockName, Ext});
11463   }
11464 }
11465 
11466 ASTReader::~ASTReader() {
11467   if (OwnsDeserializationListener)
11468     delete DeserializationListener;
11469 }
11470 
11471 IdentifierResolver &ASTReader::getIdResolver() {
11472   return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11473 }
11474 
11475 Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
11476                                                unsigned AbbrevID) {
11477   Idx = 0;
11478   Record.clear();
11479   return Cursor.readRecord(AbbrevID, Record);
11480 }
11481 //===----------------------------------------------------------------------===//
11482 //// OMPClauseReader implementation
11483 ////===----------------------------------------------------------------------===//
11484 
11485 // This has to be in namespace clang because it's friended by all
11486 // of the OMP clauses.
11487 namespace clang {
11488 
11489 class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11490   ASTRecordReader &Record;
11491   ASTContext &Context;
11492 
11493 public:
11494   OMPClauseReader(ASTRecordReader &Record)
11495       : Record(Record), Context(Record.getContext()) {}
11496 
11497 #define OPENMP_CLAUSE(Name, Class) void Visit##Class(Class *C);
11498 #include "clang/Basic/OpenMPKinds.def"
11499   OMPClause *readClause();
11500   void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
11501   void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
11502 };
11503 
11504 } // end namespace clang
11505 
11506 OMPClause *ASTRecordReader::readOMPClause() {
11507   return OMPClauseReader(*this).readClause();
11508 }
11509 
11510 OMPClause *OMPClauseReader::readClause() {
11511   OMPClause *C = nullptr;
11512   switch (Record.readInt()) {
11513   case OMPC_if:
11514     C = new (Context) OMPIfClause();
11515     break;
11516   case OMPC_final:
11517     C = new (Context) OMPFinalClause();
11518     break;
11519   case OMPC_num_threads:
11520     C = new (Context) OMPNumThreadsClause();
11521     break;
11522   case OMPC_safelen:
11523     C = new (Context) OMPSafelenClause();
11524     break;
11525   case OMPC_simdlen:
11526     C = new (Context) OMPSimdlenClause();
11527     break;
11528   case OMPC_allocator:
11529     C = new (Context) OMPAllocatorClause();
11530     break;
11531   case OMPC_collapse:
11532     C = new (Context) OMPCollapseClause();
11533     break;
11534   case OMPC_default:
11535     C = new (Context) OMPDefaultClause();
11536     break;
11537   case OMPC_proc_bind:
11538     C = new (Context) OMPProcBindClause();
11539     break;
11540   case OMPC_schedule:
11541     C = new (Context) OMPScheduleClause();
11542     break;
11543   case OMPC_ordered:
11544     C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11545     break;
11546   case OMPC_nowait:
11547     C = new (Context) OMPNowaitClause();
11548     break;
11549   case OMPC_untied:
11550     C = new (Context) OMPUntiedClause();
11551     break;
11552   case OMPC_mergeable:
11553     C = new (Context) OMPMergeableClause();
11554     break;
11555   case OMPC_read:
11556     C = new (Context) OMPReadClause();
11557     break;
11558   case OMPC_write:
11559     C = new (Context) OMPWriteClause();
11560     break;
11561   case OMPC_update:
11562     C = new (Context) OMPUpdateClause();
11563     break;
11564   case OMPC_capture:
11565     C = new (Context) OMPCaptureClause();
11566     break;
11567   case OMPC_seq_cst:
11568     C = new (Context) OMPSeqCstClause();
11569     break;
11570   case OMPC_threads:
11571     C = new (Context) OMPThreadsClause();
11572     break;
11573   case OMPC_simd:
11574     C = new (Context) OMPSIMDClause();
11575     break;
11576   case OMPC_nogroup:
11577     C = new (Context) OMPNogroupClause();
11578     break;
11579   case OMPC_unified_address:
11580     C = new (Context) OMPUnifiedAddressClause();
11581     break;
11582   case OMPC_unified_shared_memory:
11583     C = new (Context) OMPUnifiedSharedMemoryClause();
11584     break;
11585   case OMPC_reverse_offload:
11586     C = new (Context) OMPReverseOffloadClause();
11587     break;
11588   case OMPC_dynamic_allocators:
11589     C = new (Context) OMPDynamicAllocatorsClause();
11590     break;
11591   case OMPC_atomic_default_mem_order:
11592     C = new (Context) OMPAtomicDefaultMemOrderClause();
11593     break;
11594  case OMPC_private:
11595     C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11596     break;
11597   case OMPC_firstprivate:
11598     C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11599     break;
11600   case OMPC_lastprivate:
11601     C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11602     break;
11603   case OMPC_shared:
11604     C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11605     break;
11606   case OMPC_reduction:
11607     C = OMPReductionClause::CreateEmpty(Context, Record.readInt());
11608     break;
11609   case OMPC_task_reduction:
11610     C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11611     break;
11612   case OMPC_in_reduction:
11613     C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11614     break;
11615   case OMPC_linear:
11616     C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11617     break;
11618   case OMPC_aligned:
11619     C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11620     break;
11621   case OMPC_copyin:
11622     C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11623     break;
11624   case OMPC_copyprivate:
11625     C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11626     break;
11627   case OMPC_flush:
11628     C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11629     break;
11630   case OMPC_depend: {
11631     unsigned NumVars = Record.readInt();
11632     unsigned NumLoops = Record.readInt();
11633     C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11634     break;
11635   }
11636   case OMPC_device:
11637     C = new (Context) OMPDeviceClause();
11638     break;
11639   case OMPC_map: {
11640     OMPMappableExprListSizeTy Sizes;
11641     Sizes.NumVars = Record.readInt();
11642     Sizes.NumUniqueDeclarations = Record.readInt();
11643     Sizes.NumComponentLists = Record.readInt();
11644     Sizes.NumComponents = Record.readInt();
11645     C = OMPMapClause::CreateEmpty(Context, Sizes);
11646     break;
11647   }
11648   case OMPC_num_teams:
11649     C = new (Context) OMPNumTeamsClause();
11650     break;
11651   case OMPC_thread_limit:
11652     C = new (Context) OMPThreadLimitClause();
11653     break;
11654   case OMPC_priority:
11655     C = new (Context) OMPPriorityClause();
11656     break;
11657   case OMPC_grainsize:
11658     C = new (Context) OMPGrainsizeClause();
11659     break;
11660   case OMPC_num_tasks:
11661     C = new (Context) OMPNumTasksClause();
11662     break;
11663   case OMPC_hint:
11664     C = new (Context) OMPHintClause();
11665     break;
11666   case OMPC_dist_schedule:
11667     C = new (Context) OMPDistScheduleClause();
11668     break;
11669   case OMPC_defaultmap:
11670     C = new (Context) OMPDefaultmapClause();
11671     break;
11672   case OMPC_to: {
11673     OMPMappableExprListSizeTy Sizes;
11674     Sizes.NumVars = Record.readInt();
11675     Sizes.NumUniqueDeclarations = Record.readInt();
11676     Sizes.NumComponentLists = Record.readInt();
11677     Sizes.NumComponents = Record.readInt();
11678     C = OMPToClause::CreateEmpty(Context, Sizes);
11679     break;
11680   }
11681   case OMPC_from: {
11682     OMPMappableExprListSizeTy Sizes;
11683     Sizes.NumVars = Record.readInt();
11684     Sizes.NumUniqueDeclarations = Record.readInt();
11685     Sizes.NumComponentLists = Record.readInt();
11686     Sizes.NumComponents = Record.readInt();
11687     C = OMPFromClause::CreateEmpty(Context, Sizes);
11688     break;
11689   }
11690   case OMPC_use_device_ptr: {
11691     OMPMappableExprListSizeTy Sizes;
11692     Sizes.NumVars = Record.readInt();
11693     Sizes.NumUniqueDeclarations = Record.readInt();
11694     Sizes.NumComponentLists = Record.readInt();
11695     Sizes.NumComponents = Record.readInt();
11696     C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
11697     break;
11698   }
11699   case OMPC_is_device_ptr: {
11700     OMPMappableExprListSizeTy Sizes;
11701     Sizes.NumVars = Record.readInt();
11702     Sizes.NumUniqueDeclarations = Record.readInt();
11703     Sizes.NumComponentLists = Record.readInt();
11704     Sizes.NumComponents = Record.readInt();
11705     C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
11706     break;
11707   }
11708   case OMPC_allocate:
11709     C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11710     break;
11711   case OMPC_nontemporal:
11712     C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11713     break;
11714   }
11715   assert(C && "Unknown OMPClause type");
11716 
11717   Visit(C);
11718   C->setLocStart(Record.readSourceLocation());
11719   C->setLocEnd(Record.readSourceLocation());
11720 
11721   return C;
11722 }
11723 
11724 void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
11725   C->setPreInitStmt(Record.readSubStmt(),
11726                     static_cast<OpenMPDirectiveKind>(Record.readInt()));
11727 }
11728 
11729 void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
11730   VisitOMPClauseWithPreInit(C);
11731   C->setPostUpdateExpr(Record.readSubExpr());
11732 }
11733 
11734 void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11735   VisitOMPClauseWithPreInit(C);
11736   C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11737   C->setNameModifierLoc(Record.readSourceLocation());
11738   C->setColonLoc(Record.readSourceLocation());
11739   C->setCondition(Record.readSubExpr());
11740   C->setLParenLoc(Record.readSourceLocation());
11741 }
11742 
11743 void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11744   VisitOMPClauseWithPreInit(C);
11745   C->setCondition(Record.readSubExpr());
11746   C->setLParenLoc(Record.readSourceLocation());
11747 }
11748 
11749 void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11750   VisitOMPClauseWithPreInit(C);
11751   C->setNumThreads(Record.readSubExpr());
11752   C->setLParenLoc(Record.readSourceLocation());
11753 }
11754 
11755 void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11756   C->setSafelen(Record.readSubExpr());
11757   C->setLParenLoc(Record.readSourceLocation());
11758 }
11759 
11760 void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11761   C->setSimdlen(Record.readSubExpr());
11762   C->setLParenLoc(Record.readSourceLocation());
11763 }
11764 
11765 void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
11766   C->setAllocator(Record.readExpr());
11767   C->setLParenLoc(Record.readSourceLocation());
11768 }
11769 
11770 void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11771   C->setNumForLoops(Record.readSubExpr());
11772   C->setLParenLoc(Record.readSourceLocation());
11773 }
11774 
11775 void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11776   C->setDefaultKind(
11777        static_cast<OpenMPDefaultClauseKind>(Record.readInt()));
11778   C->setLParenLoc(Record.readSourceLocation());
11779   C->setDefaultKindKwLoc(Record.readSourceLocation());
11780 }
11781 
11782 void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11783   C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
11784   C->setLParenLoc(Record.readSourceLocation());
11785   C->setProcBindKindKwLoc(Record.readSourceLocation());
11786 }
11787 
11788 void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11789   VisitOMPClauseWithPreInit(C);
11790   C->setScheduleKind(
11791        static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11792   C->setFirstScheduleModifier(
11793       static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11794   C->setSecondScheduleModifier(
11795       static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11796   C->setChunkSize(Record.readSubExpr());
11797   C->setLParenLoc(Record.readSourceLocation());
11798   C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11799   C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11800   C->setScheduleKindLoc(Record.readSourceLocation());
11801   C->setCommaLoc(Record.readSourceLocation());
11802 }
11803 
11804 void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11805   C->setNumForLoops(Record.readSubExpr());
11806   for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11807     C->setLoopNumIterations(I, Record.readSubExpr());
11808   for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11809     C->setLoopCounter(I, Record.readSubExpr());
11810   C->setLParenLoc(Record.readSourceLocation());
11811 }
11812 
11813 void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
11814 
11815 void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
11816 
11817 void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
11818 
11819 void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
11820 
11821 void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
11822 
11823 void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *) {}
11824 
11825 void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
11826 
11827 void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
11828 
11829 void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
11830 
11831 void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
11832 
11833 void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
11834 
11835 void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
11836 
11837 void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
11838     OMPUnifiedSharedMemoryClause *) {}
11839 
11840 void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
11841 
11842 void
11843 OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
11844 }
11845 
11846 void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
11847     OMPAtomicDefaultMemOrderClause *C) {
11848   C->setAtomicDefaultMemOrderKind(
11849       static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
11850   C->setLParenLoc(Record.readSourceLocation());
11851   C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
11852 }
11853 
11854 void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
11855   C->setLParenLoc(Record.readSourceLocation());
11856   unsigned NumVars = C->varlist_size();
11857   SmallVector<Expr *, 16> Vars;
11858   Vars.reserve(NumVars);
11859   for (unsigned i = 0; i != NumVars; ++i)
11860     Vars.push_back(Record.readSubExpr());
11861   C->setVarRefs(Vars);
11862   Vars.clear();
11863   for (unsigned i = 0; i != NumVars; ++i)
11864     Vars.push_back(Record.readSubExpr());
11865   C->setPrivateCopies(Vars);
11866 }
11867 
11868 void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
11869   VisitOMPClauseWithPreInit(C);
11870   C->setLParenLoc(Record.readSourceLocation());
11871   unsigned NumVars = C->varlist_size();
11872   SmallVector<Expr *, 16> Vars;
11873   Vars.reserve(NumVars);
11874   for (unsigned i = 0; i != NumVars; ++i)
11875     Vars.push_back(Record.readSubExpr());
11876   C->setVarRefs(Vars);
11877   Vars.clear();
11878   for (unsigned i = 0; i != NumVars; ++i)
11879     Vars.push_back(Record.readSubExpr());
11880   C->setPrivateCopies(Vars);
11881   Vars.clear();
11882   for (unsigned i = 0; i != NumVars; ++i)
11883     Vars.push_back(Record.readSubExpr());
11884   C->setInits(Vars);
11885 }
11886 
11887 void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
11888   VisitOMPClauseWithPostUpdate(C);
11889   C->setLParenLoc(Record.readSourceLocation());
11890   C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
11891   C->setKindLoc(Record.readSourceLocation());
11892   C->setColonLoc(Record.readSourceLocation());
11893   unsigned NumVars = C->varlist_size();
11894   SmallVector<Expr *, 16> Vars;
11895   Vars.reserve(NumVars);
11896   for (unsigned i = 0; i != NumVars; ++i)
11897     Vars.push_back(Record.readSubExpr());
11898   C->setVarRefs(Vars);
11899   Vars.clear();
11900   for (unsigned i = 0; i != NumVars; ++i)
11901     Vars.push_back(Record.readSubExpr());
11902   C->setPrivateCopies(Vars);
11903   Vars.clear();
11904   for (unsigned i = 0; i != NumVars; ++i)
11905     Vars.push_back(Record.readSubExpr());
11906   C->setSourceExprs(Vars);
11907   Vars.clear();
11908   for (unsigned i = 0; i != NumVars; ++i)
11909     Vars.push_back(Record.readSubExpr());
11910   C->setDestinationExprs(Vars);
11911   Vars.clear();
11912   for (unsigned i = 0; i != NumVars; ++i)
11913     Vars.push_back(Record.readSubExpr());
11914   C->setAssignmentOps(Vars);
11915 }
11916 
11917 void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
11918   C->setLParenLoc(Record.readSourceLocation());
11919   unsigned NumVars = C->varlist_size();
11920   SmallVector<Expr *, 16> Vars;
11921   Vars.reserve(NumVars);
11922   for (unsigned i = 0; i != NumVars; ++i)
11923     Vars.push_back(Record.readSubExpr());
11924   C->setVarRefs(Vars);
11925 }
11926 
11927 void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
11928   VisitOMPClauseWithPostUpdate(C);
11929   C->setLParenLoc(Record.readSourceLocation());
11930   C->setColonLoc(Record.readSourceLocation());
11931   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11932   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11933   C->setQualifierLoc(NNSL);
11934   C->setNameInfo(DNI);
11935 
11936   unsigned NumVars = C->varlist_size();
11937   SmallVector<Expr *, 16> Vars;
11938   Vars.reserve(NumVars);
11939   for (unsigned i = 0; i != NumVars; ++i)
11940     Vars.push_back(Record.readSubExpr());
11941   C->setVarRefs(Vars);
11942   Vars.clear();
11943   for (unsigned i = 0; i != NumVars; ++i)
11944     Vars.push_back(Record.readSubExpr());
11945   C->setPrivates(Vars);
11946   Vars.clear();
11947   for (unsigned i = 0; i != NumVars; ++i)
11948     Vars.push_back(Record.readSubExpr());
11949   C->setLHSExprs(Vars);
11950   Vars.clear();
11951   for (unsigned i = 0; i != NumVars; ++i)
11952     Vars.push_back(Record.readSubExpr());
11953   C->setRHSExprs(Vars);
11954   Vars.clear();
11955   for (unsigned i = 0; i != NumVars; ++i)
11956     Vars.push_back(Record.readSubExpr());
11957   C->setReductionOps(Vars);
11958 }
11959 
11960 void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
11961   VisitOMPClauseWithPostUpdate(C);
11962   C->setLParenLoc(Record.readSourceLocation());
11963   C->setColonLoc(Record.readSourceLocation());
11964   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11965   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11966   C->setQualifierLoc(NNSL);
11967   C->setNameInfo(DNI);
11968 
11969   unsigned NumVars = C->varlist_size();
11970   SmallVector<Expr *, 16> Vars;
11971   Vars.reserve(NumVars);
11972   for (unsigned I = 0; I != NumVars; ++I)
11973     Vars.push_back(Record.readSubExpr());
11974   C->setVarRefs(Vars);
11975   Vars.clear();
11976   for (unsigned I = 0; I != NumVars; ++I)
11977     Vars.push_back(Record.readSubExpr());
11978   C->setPrivates(Vars);
11979   Vars.clear();
11980   for (unsigned I = 0; I != NumVars; ++I)
11981     Vars.push_back(Record.readSubExpr());
11982   C->setLHSExprs(Vars);
11983   Vars.clear();
11984   for (unsigned I = 0; I != NumVars; ++I)
11985     Vars.push_back(Record.readSubExpr());
11986   C->setRHSExprs(Vars);
11987   Vars.clear();
11988   for (unsigned I = 0; I != NumVars; ++I)
11989     Vars.push_back(Record.readSubExpr());
11990   C->setReductionOps(Vars);
11991 }
11992 
11993 void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
11994   VisitOMPClauseWithPostUpdate(C);
11995   C->setLParenLoc(Record.readSourceLocation());
11996   C->setColonLoc(Record.readSourceLocation());
11997   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11998   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11999   C->setQualifierLoc(NNSL);
12000   C->setNameInfo(DNI);
12001 
12002   unsigned NumVars = C->varlist_size();
12003   SmallVector<Expr *, 16> Vars;
12004   Vars.reserve(NumVars);
12005   for (unsigned I = 0; I != NumVars; ++I)
12006     Vars.push_back(Record.readSubExpr());
12007   C->setVarRefs(Vars);
12008   Vars.clear();
12009   for (unsigned I = 0; I != NumVars; ++I)
12010     Vars.push_back(Record.readSubExpr());
12011   C->setPrivates(Vars);
12012   Vars.clear();
12013   for (unsigned I = 0; I != NumVars; ++I)
12014     Vars.push_back(Record.readSubExpr());
12015   C->setLHSExprs(Vars);
12016   Vars.clear();
12017   for (unsigned I = 0; I != NumVars; ++I)
12018     Vars.push_back(Record.readSubExpr());
12019   C->setRHSExprs(Vars);
12020   Vars.clear();
12021   for (unsigned I = 0; I != NumVars; ++I)
12022     Vars.push_back(Record.readSubExpr());
12023   C->setReductionOps(Vars);
12024   Vars.clear();
12025   for (unsigned I = 0; I != NumVars; ++I)
12026     Vars.push_back(Record.readSubExpr());
12027   C->setTaskgroupDescriptors(Vars);
12028 }
12029 
12030 void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12031   VisitOMPClauseWithPostUpdate(C);
12032   C->setLParenLoc(Record.readSourceLocation());
12033   C->setColonLoc(Record.readSourceLocation());
12034   C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12035   C->setModifierLoc(Record.readSourceLocation());
12036   unsigned NumVars = C->varlist_size();
12037   SmallVector<Expr *, 16> Vars;
12038   Vars.reserve(NumVars);
12039   for (unsigned i = 0; i != NumVars; ++i)
12040     Vars.push_back(Record.readSubExpr());
12041   C->setVarRefs(Vars);
12042   Vars.clear();
12043   for (unsigned i = 0; i != NumVars; ++i)
12044     Vars.push_back(Record.readSubExpr());
12045   C->setPrivates(Vars);
12046   Vars.clear();
12047   for (unsigned i = 0; i != NumVars; ++i)
12048     Vars.push_back(Record.readSubExpr());
12049   C->setInits(Vars);
12050   Vars.clear();
12051   for (unsigned i = 0; i != NumVars; ++i)
12052     Vars.push_back(Record.readSubExpr());
12053   C->setUpdates(Vars);
12054   Vars.clear();
12055   for (unsigned i = 0; i != NumVars; ++i)
12056     Vars.push_back(Record.readSubExpr());
12057   C->setFinals(Vars);
12058   C->setStep(Record.readSubExpr());
12059   C->setCalcStep(Record.readSubExpr());
12060   Vars.clear();
12061   for (unsigned I = 0; I != NumVars + 1; ++I)
12062     Vars.push_back(Record.readSubExpr());
12063   C->setUsedExprs(Vars);
12064 }
12065 
12066 void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12067   C->setLParenLoc(Record.readSourceLocation());
12068   C->setColonLoc(Record.readSourceLocation());
12069   unsigned NumVars = C->varlist_size();
12070   SmallVector<Expr *, 16> Vars;
12071   Vars.reserve(NumVars);
12072   for (unsigned i = 0; i != NumVars; ++i)
12073     Vars.push_back(Record.readSubExpr());
12074   C->setVarRefs(Vars);
12075   C->setAlignment(Record.readSubExpr());
12076 }
12077 
12078 void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12079   C->setLParenLoc(Record.readSourceLocation());
12080   unsigned NumVars = C->varlist_size();
12081   SmallVector<Expr *, 16> Exprs;
12082   Exprs.reserve(NumVars);
12083   for (unsigned i = 0; i != NumVars; ++i)
12084     Exprs.push_back(Record.readSubExpr());
12085   C->setVarRefs(Exprs);
12086   Exprs.clear();
12087   for (unsigned i = 0; i != NumVars; ++i)
12088     Exprs.push_back(Record.readSubExpr());
12089   C->setSourceExprs(Exprs);
12090   Exprs.clear();
12091   for (unsigned i = 0; i != NumVars; ++i)
12092     Exprs.push_back(Record.readSubExpr());
12093   C->setDestinationExprs(Exprs);
12094   Exprs.clear();
12095   for (unsigned i = 0; i != NumVars; ++i)
12096     Exprs.push_back(Record.readSubExpr());
12097   C->setAssignmentOps(Exprs);
12098 }
12099 
12100 void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12101   C->setLParenLoc(Record.readSourceLocation());
12102   unsigned NumVars = C->varlist_size();
12103   SmallVector<Expr *, 16> Exprs;
12104   Exprs.reserve(NumVars);
12105   for (unsigned i = 0; i != NumVars; ++i)
12106     Exprs.push_back(Record.readSubExpr());
12107   C->setVarRefs(Exprs);
12108   Exprs.clear();
12109   for (unsigned i = 0; i != NumVars; ++i)
12110     Exprs.push_back(Record.readSubExpr());
12111   C->setSourceExprs(Exprs);
12112   Exprs.clear();
12113   for (unsigned i = 0; i != NumVars; ++i)
12114     Exprs.push_back(Record.readSubExpr());
12115   C->setDestinationExprs(Exprs);
12116   Exprs.clear();
12117   for (unsigned i = 0; i != NumVars; ++i)
12118     Exprs.push_back(Record.readSubExpr());
12119   C->setAssignmentOps(Exprs);
12120 }
12121 
12122 void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12123   C->setLParenLoc(Record.readSourceLocation());
12124   unsigned NumVars = C->varlist_size();
12125   SmallVector<Expr *, 16> Vars;
12126   Vars.reserve(NumVars);
12127   for (unsigned i = 0; i != NumVars; ++i)
12128     Vars.push_back(Record.readSubExpr());
12129   C->setVarRefs(Vars);
12130 }
12131 
12132 void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12133   C->setLParenLoc(Record.readSourceLocation());
12134   C->setDependencyKind(
12135       static_cast<OpenMPDependClauseKind>(Record.readInt()));
12136   C->setDependencyLoc(Record.readSourceLocation());
12137   C->setColonLoc(Record.readSourceLocation());
12138   unsigned NumVars = C->varlist_size();
12139   SmallVector<Expr *, 16> Vars;
12140   Vars.reserve(NumVars);
12141   for (unsigned I = 0; I != NumVars; ++I)
12142     Vars.push_back(Record.readSubExpr());
12143   C->setVarRefs(Vars);
12144   for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12145     C->setLoopData(I, Record.readSubExpr());
12146 }
12147 
12148 void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12149   VisitOMPClauseWithPreInit(C);
12150   C->setDevice(Record.readSubExpr());
12151   C->setLParenLoc(Record.readSourceLocation());
12152 }
12153 
12154 void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12155   C->setLParenLoc(Record.readSourceLocation());
12156   for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
12157     C->setMapTypeModifier(
12158         I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12159     C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12160   }
12161   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12162   C->setMapperIdInfo(Record.readDeclarationNameInfo());
12163   C->setMapType(
12164      static_cast<OpenMPMapClauseKind>(Record.readInt()));
12165   C->setMapLoc(Record.readSourceLocation());
12166   C->setColonLoc(Record.readSourceLocation());
12167   auto NumVars = C->varlist_size();
12168   auto UniqueDecls = C->getUniqueDeclarationsNum();
12169   auto TotalLists = C->getTotalComponentListNum();
12170   auto TotalComponents = C->getTotalComponentsNum();
12171 
12172   SmallVector<Expr *, 16> Vars;
12173   Vars.reserve(NumVars);
12174   for (unsigned i = 0; i != NumVars; ++i)
12175     Vars.push_back(Record.readExpr());
12176   C->setVarRefs(Vars);
12177 
12178   SmallVector<Expr *, 16> UDMappers;
12179   UDMappers.reserve(NumVars);
12180   for (unsigned I = 0; I < NumVars; ++I)
12181     UDMappers.push_back(Record.readExpr());
12182   C->setUDMapperRefs(UDMappers);
12183 
12184   SmallVector<ValueDecl *, 16> Decls;
12185   Decls.reserve(UniqueDecls);
12186   for (unsigned i = 0; i < UniqueDecls; ++i)
12187     Decls.push_back(Record.readDeclAs<ValueDecl>());
12188   C->setUniqueDecls(Decls);
12189 
12190   SmallVector<unsigned, 16> ListsPerDecl;
12191   ListsPerDecl.reserve(UniqueDecls);
12192   for (unsigned i = 0; i < UniqueDecls; ++i)
12193     ListsPerDecl.push_back(Record.readInt());
12194   C->setDeclNumLists(ListsPerDecl);
12195 
12196   SmallVector<unsigned, 32> ListSizes;
12197   ListSizes.reserve(TotalLists);
12198   for (unsigned i = 0; i < TotalLists; ++i)
12199     ListSizes.push_back(Record.readInt());
12200   C->setComponentListSizes(ListSizes);
12201 
12202   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12203   Components.reserve(TotalComponents);
12204   for (unsigned i = 0; i < TotalComponents; ++i) {
12205     Expr *AssociatedExpr = Record.readExpr();
12206     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12207     Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12208         AssociatedExpr, AssociatedDecl));
12209   }
12210   C->setComponents(Components, ListSizes);
12211 }
12212 
12213 void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12214   C->setLParenLoc(Record.readSourceLocation());
12215   C->setColonLoc(Record.readSourceLocation());
12216   C->setAllocator(Record.readSubExpr());
12217   unsigned NumVars = C->varlist_size();
12218   SmallVector<Expr *, 16> Vars;
12219   Vars.reserve(NumVars);
12220   for (unsigned i = 0; i != NumVars; ++i)
12221     Vars.push_back(Record.readSubExpr());
12222   C->setVarRefs(Vars);
12223 }
12224 
12225 void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12226   VisitOMPClauseWithPreInit(C);
12227   C->setNumTeams(Record.readSubExpr());
12228   C->setLParenLoc(Record.readSourceLocation());
12229 }
12230 
12231 void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12232   VisitOMPClauseWithPreInit(C);
12233   C->setThreadLimit(Record.readSubExpr());
12234   C->setLParenLoc(Record.readSourceLocation());
12235 }
12236 
12237 void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12238   VisitOMPClauseWithPreInit(C);
12239   C->setPriority(Record.readSubExpr());
12240   C->setLParenLoc(Record.readSourceLocation());
12241 }
12242 
12243 void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12244   VisitOMPClauseWithPreInit(C);
12245   C->setGrainsize(Record.readSubExpr());
12246   C->setLParenLoc(Record.readSourceLocation());
12247 }
12248 
12249 void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12250   VisitOMPClauseWithPreInit(C);
12251   C->setNumTasks(Record.readSubExpr());
12252   C->setLParenLoc(Record.readSourceLocation());
12253 }
12254 
12255 void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12256   C->setHint(Record.readSubExpr());
12257   C->setLParenLoc(Record.readSourceLocation());
12258 }
12259 
12260 void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12261   VisitOMPClauseWithPreInit(C);
12262   C->setDistScheduleKind(
12263       static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12264   C->setChunkSize(Record.readSubExpr());
12265   C->setLParenLoc(Record.readSourceLocation());
12266   C->setDistScheduleKindLoc(Record.readSourceLocation());
12267   C->setCommaLoc(Record.readSourceLocation());
12268 }
12269 
12270 void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12271   C->setDefaultmapKind(
12272        static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12273   C->setDefaultmapModifier(
12274       static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12275   C->setLParenLoc(Record.readSourceLocation());
12276   C->setDefaultmapModifierLoc(Record.readSourceLocation());
12277   C->setDefaultmapKindLoc(Record.readSourceLocation());
12278 }
12279 
12280 void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12281   C->setLParenLoc(Record.readSourceLocation());
12282   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12283   C->setMapperIdInfo(Record.readDeclarationNameInfo());
12284   auto NumVars = C->varlist_size();
12285   auto UniqueDecls = C->getUniqueDeclarationsNum();
12286   auto TotalLists = C->getTotalComponentListNum();
12287   auto TotalComponents = C->getTotalComponentsNum();
12288 
12289   SmallVector<Expr *, 16> Vars;
12290   Vars.reserve(NumVars);
12291   for (unsigned i = 0; i != NumVars; ++i)
12292     Vars.push_back(Record.readSubExpr());
12293   C->setVarRefs(Vars);
12294 
12295   SmallVector<Expr *, 16> UDMappers;
12296   UDMappers.reserve(NumVars);
12297   for (unsigned I = 0; I < NumVars; ++I)
12298     UDMappers.push_back(Record.readSubExpr());
12299   C->setUDMapperRefs(UDMappers);
12300 
12301   SmallVector<ValueDecl *, 16> Decls;
12302   Decls.reserve(UniqueDecls);
12303   for (unsigned i = 0; i < UniqueDecls; ++i)
12304     Decls.push_back(Record.readDeclAs<ValueDecl>());
12305   C->setUniqueDecls(Decls);
12306 
12307   SmallVector<unsigned, 16> ListsPerDecl;
12308   ListsPerDecl.reserve(UniqueDecls);
12309   for (unsigned i = 0; i < UniqueDecls; ++i)
12310     ListsPerDecl.push_back(Record.readInt());
12311   C->setDeclNumLists(ListsPerDecl);
12312 
12313   SmallVector<unsigned, 32> ListSizes;
12314   ListSizes.reserve(TotalLists);
12315   for (unsigned i = 0; i < TotalLists; ++i)
12316     ListSizes.push_back(Record.readInt());
12317   C->setComponentListSizes(ListSizes);
12318 
12319   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12320   Components.reserve(TotalComponents);
12321   for (unsigned i = 0; i < TotalComponents; ++i) {
12322     Expr *AssociatedExpr = Record.readSubExpr();
12323     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12324     Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12325         AssociatedExpr, AssociatedDecl));
12326   }
12327   C->setComponents(Components, ListSizes);
12328 }
12329 
12330 void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12331   C->setLParenLoc(Record.readSourceLocation());
12332   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12333   C->setMapperIdInfo(Record.readDeclarationNameInfo());
12334   auto NumVars = C->varlist_size();
12335   auto UniqueDecls = C->getUniqueDeclarationsNum();
12336   auto TotalLists = C->getTotalComponentListNum();
12337   auto TotalComponents = C->getTotalComponentsNum();
12338 
12339   SmallVector<Expr *, 16> Vars;
12340   Vars.reserve(NumVars);
12341   for (unsigned i = 0; i != NumVars; ++i)
12342     Vars.push_back(Record.readSubExpr());
12343   C->setVarRefs(Vars);
12344 
12345   SmallVector<Expr *, 16> UDMappers;
12346   UDMappers.reserve(NumVars);
12347   for (unsigned I = 0; I < NumVars; ++I)
12348     UDMappers.push_back(Record.readSubExpr());
12349   C->setUDMapperRefs(UDMappers);
12350 
12351   SmallVector<ValueDecl *, 16> Decls;
12352   Decls.reserve(UniqueDecls);
12353   for (unsigned i = 0; i < UniqueDecls; ++i)
12354     Decls.push_back(Record.readDeclAs<ValueDecl>());
12355   C->setUniqueDecls(Decls);
12356 
12357   SmallVector<unsigned, 16> ListsPerDecl;
12358   ListsPerDecl.reserve(UniqueDecls);
12359   for (unsigned i = 0; i < UniqueDecls; ++i)
12360     ListsPerDecl.push_back(Record.readInt());
12361   C->setDeclNumLists(ListsPerDecl);
12362 
12363   SmallVector<unsigned, 32> ListSizes;
12364   ListSizes.reserve(TotalLists);
12365   for (unsigned i = 0; i < TotalLists; ++i)
12366     ListSizes.push_back(Record.readInt());
12367   C->setComponentListSizes(ListSizes);
12368 
12369   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12370   Components.reserve(TotalComponents);
12371   for (unsigned i = 0; i < TotalComponents; ++i) {
12372     Expr *AssociatedExpr = Record.readSubExpr();
12373     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12374     Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12375         AssociatedExpr, AssociatedDecl));
12376   }
12377   C->setComponents(Components, ListSizes);
12378 }
12379 
12380 void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12381   C->setLParenLoc(Record.readSourceLocation());
12382   auto NumVars = C->varlist_size();
12383   auto UniqueDecls = C->getUniqueDeclarationsNum();
12384   auto TotalLists = C->getTotalComponentListNum();
12385   auto TotalComponents = C->getTotalComponentsNum();
12386 
12387   SmallVector<Expr *, 16> Vars;
12388   Vars.reserve(NumVars);
12389   for (unsigned i = 0; i != NumVars; ++i)
12390     Vars.push_back(Record.readSubExpr());
12391   C->setVarRefs(Vars);
12392   Vars.clear();
12393   for (unsigned i = 0; i != NumVars; ++i)
12394     Vars.push_back(Record.readSubExpr());
12395   C->setPrivateCopies(Vars);
12396   Vars.clear();
12397   for (unsigned i = 0; i != NumVars; ++i)
12398     Vars.push_back(Record.readSubExpr());
12399   C->setInits(Vars);
12400 
12401   SmallVector<ValueDecl *, 16> Decls;
12402   Decls.reserve(UniqueDecls);
12403   for (unsigned i = 0; i < UniqueDecls; ++i)
12404     Decls.push_back(Record.readDeclAs<ValueDecl>());
12405   C->setUniqueDecls(Decls);
12406 
12407   SmallVector<unsigned, 16> ListsPerDecl;
12408   ListsPerDecl.reserve(UniqueDecls);
12409   for (unsigned i = 0; i < UniqueDecls; ++i)
12410     ListsPerDecl.push_back(Record.readInt());
12411   C->setDeclNumLists(ListsPerDecl);
12412 
12413   SmallVector<unsigned, 32> ListSizes;
12414   ListSizes.reserve(TotalLists);
12415   for (unsigned i = 0; i < TotalLists; ++i)
12416     ListSizes.push_back(Record.readInt());
12417   C->setComponentListSizes(ListSizes);
12418 
12419   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12420   Components.reserve(TotalComponents);
12421   for (unsigned i = 0; i < TotalComponents; ++i) {
12422     Expr *AssociatedExpr = Record.readSubExpr();
12423     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12424     Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12425         AssociatedExpr, AssociatedDecl));
12426   }
12427   C->setComponents(Components, ListSizes);
12428 }
12429 
12430 void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12431   C->setLParenLoc(Record.readSourceLocation());
12432   auto NumVars = C->varlist_size();
12433   auto UniqueDecls = C->getUniqueDeclarationsNum();
12434   auto TotalLists = C->getTotalComponentListNum();
12435   auto TotalComponents = C->getTotalComponentsNum();
12436 
12437   SmallVector<Expr *, 16> Vars;
12438   Vars.reserve(NumVars);
12439   for (unsigned i = 0; i != NumVars; ++i)
12440     Vars.push_back(Record.readSubExpr());
12441   C->setVarRefs(Vars);
12442   Vars.clear();
12443 
12444   SmallVector<ValueDecl *, 16> Decls;
12445   Decls.reserve(UniqueDecls);
12446   for (unsigned i = 0; i < UniqueDecls; ++i)
12447     Decls.push_back(Record.readDeclAs<ValueDecl>());
12448   C->setUniqueDecls(Decls);
12449 
12450   SmallVector<unsigned, 16> ListsPerDecl;
12451   ListsPerDecl.reserve(UniqueDecls);
12452   for (unsigned i = 0; i < UniqueDecls; ++i)
12453     ListsPerDecl.push_back(Record.readInt());
12454   C->setDeclNumLists(ListsPerDecl);
12455 
12456   SmallVector<unsigned, 32> ListSizes;
12457   ListSizes.reserve(TotalLists);
12458   for (unsigned i = 0; i < TotalLists; ++i)
12459     ListSizes.push_back(Record.readInt());
12460   C->setComponentListSizes(ListSizes);
12461 
12462   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12463   Components.reserve(TotalComponents);
12464   for (unsigned i = 0; i < TotalComponents; ++i) {
12465     Expr *AssociatedExpr = Record.readSubExpr();
12466     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12467     Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12468         AssociatedExpr, AssociatedDecl));
12469   }
12470   C->setComponents(Components, ListSizes);
12471 }
12472 
12473 void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12474   C->setLParenLoc(Record.readSourceLocation());
12475   unsigned NumVars = C->varlist_size();
12476   SmallVector<Expr *, 16> Vars;
12477   Vars.reserve(NumVars);
12478   for (unsigned i = 0; i != NumVars; ++i)
12479     Vars.push_back(Record.readSubExpr());
12480   C->setVarRefs(Vars);
12481   Vars.clear();
12482   Vars.reserve(NumVars);
12483   for (unsigned i = 0; i != NumVars; ++i)
12484     Vars.push_back(Record.readSubExpr());
12485   C->setPrivateRefs(Vars);
12486 }
12487