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