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