clang API Documentation

ASTReader.cpp
Go to the documentation of this file.
00001 //===--- ASTReader.cpp - AST File Reader ----------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the ASTReader class, which reads AST files.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Serialization/ASTReader.h"
00015 #include "ASTCommon.h"
00016 #include "ASTReaderInternals.h"
00017 #include "clang/AST/ASTConsumer.h"
00018 #include "clang/AST/ASTContext.h"
00019 #include "clang/AST/DeclTemplate.h"
00020 #include "clang/AST/Expr.h"
00021 #include "clang/AST/ExprCXX.h"
00022 #include "clang/AST/NestedNameSpecifier.h"
00023 #include "clang/AST/Type.h"
00024 #include "clang/AST/TypeLocVisitor.h"
00025 #include "clang/Basic/DiagnosticOptions.h"
00026 #include "clang/Basic/FileManager.h"
00027 #include "clang/Basic/SourceManager.h"
00028 #include "clang/Basic/SourceManagerInternals.h"
00029 #include "clang/Basic/TargetInfo.h"
00030 #include "clang/Basic/TargetOptions.h"
00031 #include "clang/Basic/Version.h"
00032 #include "clang/Basic/VersionTuple.h"
00033 #include "clang/Frontend/Utils.h"
00034 #include "clang/Lex/HeaderSearch.h"
00035 #include "clang/Lex/HeaderSearchOptions.h"
00036 #include "clang/Lex/MacroInfo.h"
00037 #include "clang/Lex/PreprocessingRecord.h"
00038 #include "clang/Lex/Preprocessor.h"
00039 #include "clang/Lex/PreprocessorOptions.h"
00040 #include "clang/Sema/Scope.h"
00041 #include "clang/Sema/Sema.h"
00042 #include "clang/Serialization/ASTDeserializationListener.h"
00043 #include "clang/Serialization/GlobalModuleIndex.h"
00044 #include "clang/Serialization/ModuleManager.h"
00045 #include "clang/Serialization/SerializationDiagnostic.h"
00046 #include "llvm/ADT/Hashing.h"
00047 #include "llvm/ADT/StringExtras.h"
00048 #include "llvm/Bitcode/BitstreamReader.h"
00049 #include "llvm/Support/ErrorHandling.h"
00050 #include "llvm/Support/FileSystem.h"
00051 #include "llvm/Support/MemoryBuffer.h"
00052 #include "llvm/Support/Path.h"
00053 #include "llvm/Support/SaveAndRestore.h"
00054 #include "llvm/Support/raw_ostream.h"
00055 #include <algorithm>
00056 #include <cstdio>
00057 #include <iterator>
00058 #include <system_error>
00059 
00060 using namespace clang;
00061 using namespace clang::serialization;
00062 using namespace clang::serialization::reader;
00063 using llvm::BitstreamCursor;
00064 
00065 
00066 //===----------------------------------------------------------------------===//
00067 // ChainedASTReaderListener implementation
00068 //===----------------------------------------------------------------------===//
00069 
00070 bool
00071 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
00072   return First->ReadFullVersionInformation(FullVersion) ||
00073          Second->ReadFullVersionInformation(FullVersion);
00074 }
00075 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
00076   First->ReadModuleName(ModuleName);
00077   Second->ReadModuleName(ModuleName);
00078 }
00079 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
00080   First->ReadModuleMapFile(ModuleMapPath);
00081   Second->ReadModuleMapFile(ModuleMapPath);
00082 }
00083 bool
00084 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
00085                                               bool Complain,
00086                                               bool AllowCompatibleDifferences) {
00087   return First->ReadLanguageOptions(LangOpts, Complain,
00088                                     AllowCompatibleDifferences) ||
00089          Second->ReadLanguageOptions(LangOpts, Complain,
00090                                      AllowCompatibleDifferences);
00091 }
00092 bool
00093 ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
00094                                             bool Complain) {
00095   return First->ReadTargetOptions(TargetOpts, Complain) ||
00096          Second->ReadTargetOptions(TargetOpts, Complain);
00097 }
00098 bool ChainedASTReaderListener::ReadDiagnosticOptions(
00099     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
00100   return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
00101          Second->ReadDiagnosticOptions(DiagOpts, Complain);
00102 }
00103 bool
00104 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
00105                                                 bool Complain) {
00106   return First->ReadFileSystemOptions(FSOpts, Complain) ||
00107          Second->ReadFileSystemOptions(FSOpts, Complain);
00108 }
00109 
00110 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
00111     const HeaderSearchOptions &HSOpts, bool Complain) {
00112   return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
00113          Second->ReadHeaderSearchOptions(HSOpts, Complain);
00114 }
00115 bool ChainedASTReaderListener::ReadPreprocessorOptions(
00116     const PreprocessorOptions &PPOpts, bool Complain,
00117     std::string &SuggestedPredefines) {
00118   return First->ReadPreprocessorOptions(PPOpts, Complain,
00119                                         SuggestedPredefines) ||
00120          Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
00121 }
00122 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
00123                                            unsigned Value) {
00124   First->ReadCounter(M, Value);
00125   Second->ReadCounter(M, Value);
00126 }
00127 bool ChainedASTReaderListener::needsInputFileVisitation() {
00128   return First->needsInputFileVisitation() ||
00129          Second->needsInputFileVisitation();
00130 }
00131 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
00132   return First->needsSystemInputFileVisitation() ||
00133   Second->needsSystemInputFileVisitation();
00134 }
00135 void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
00136   First->visitModuleFile(Filename);
00137   Second->visitModuleFile(Filename);
00138 }
00139 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
00140                                               bool isSystem,
00141                                               bool isOverridden) {
00142   bool Continue = false;
00143   if (First->needsInputFileVisitation() &&
00144       (!isSystem || First->needsSystemInputFileVisitation()))
00145     Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
00146   if (Second->needsInputFileVisitation() &&
00147       (!isSystem || Second->needsSystemInputFileVisitation()))
00148     Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
00149   return Continue;
00150 }
00151 
00152 //===----------------------------------------------------------------------===//
00153 // PCH validator implementation
00154 //===----------------------------------------------------------------------===//
00155 
00156 ASTReaderListener::~ASTReaderListener() {}
00157 
00158 /// \brief Compare the given set of language options against an existing set of
00159 /// language options.
00160 ///
00161 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
00162 /// \param AllowCompatibleDifferences If true, differences between compatible
00163 ///        language options will be permitted.
00164 ///
00165 /// \returns true if the languagae options mis-match, false otherwise.
00166 static bool checkLanguageOptions(const LangOptions &LangOpts,
00167                                  const LangOptions &ExistingLangOpts,
00168                                  DiagnosticsEngine *Diags,
00169                                  bool AllowCompatibleDifferences = true) {
00170 #define LANGOPT(Name, Bits, Default, Description)                 \
00171   if (ExistingLangOpts.Name != LangOpts.Name) {                   \
00172     if (Diags)                                                    \
00173       Diags->Report(diag::err_pch_langopt_mismatch)               \
00174         << Description << LangOpts.Name << ExistingLangOpts.Name; \
00175     return true;                                                  \
00176   }
00177 
00178 #define VALUE_LANGOPT(Name, Bits, Default, Description)   \
00179   if (ExistingLangOpts.Name != LangOpts.Name) {           \
00180     if (Diags)                                            \
00181       Diags->Report(diag::err_pch_langopt_value_mismatch) \
00182         << Description;                                   \
00183     return true;                                          \
00184   }
00185 
00186 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description)   \
00187   if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) {  \
00188     if (Diags)                                                 \
00189       Diags->Report(diag::err_pch_langopt_value_mismatch)      \
00190         << Description;                                        \
00191     return true;                                               \
00192   }
00193 
00194 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description)  \
00195   if (!AllowCompatibleDifferences)                            \
00196     LANGOPT(Name, Bits, Default, Description)
00197 
00198 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description)  \
00199   if (!AllowCompatibleDifferences)                                 \
00200     ENUM_LANGOPT(Name, Bits, Default, Description)
00201 
00202 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
00203 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
00204 #include "clang/Basic/LangOptions.def"
00205 
00206   if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
00207     if (Diags)
00208       Diags->Report(diag::err_pch_langopt_value_mismatch)
00209       << "target Objective-C runtime";
00210     return true;
00211   }
00212 
00213   if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
00214       LangOpts.CommentOpts.BlockCommandNames) {
00215     if (Diags)
00216       Diags->Report(diag::err_pch_langopt_value_mismatch)
00217         << "block command names";
00218     return true;
00219   }
00220 
00221   return false;
00222 }
00223 
00224 /// \brief Compare the given set of target options against an existing set of
00225 /// target options.
00226 ///
00227 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
00228 ///
00229 /// \returns true if the target options mis-match, false otherwise.
00230 static bool checkTargetOptions(const TargetOptions &TargetOpts,
00231                                const TargetOptions &ExistingTargetOpts,
00232                                DiagnosticsEngine *Diags) {
00233 #define CHECK_TARGET_OPT(Field, Name)                             \
00234   if (TargetOpts.Field != ExistingTargetOpts.Field) {             \
00235     if (Diags)                                                    \
00236       Diags->Report(diag::err_pch_targetopt_mismatch)             \
00237         << Name << TargetOpts.Field << ExistingTargetOpts.Field;  \
00238     return true;                                                  \
00239   }
00240 
00241   CHECK_TARGET_OPT(Triple, "target");
00242   CHECK_TARGET_OPT(CPU, "target CPU");
00243   CHECK_TARGET_OPT(ABI, "target ABI");
00244 #undef CHECK_TARGET_OPT
00245 
00246   // Compare feature sets.
00247   SmallVector<StringRef, 4> ExistingFeatures(
00248                                              ExistingTargetOpts.FeaturesAsWritten.begin(),
00249                                              ExistingTargetOpts.FeaturesAsWritten.end());
00250   SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
00251                                          TargetOpts.FeaturesAsWritten.end());
00252   std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
00253   std::sort(ReadFeatures.begin(), ReadFeatures.end());
00254 
00255   unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
00256   unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
00257   while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
00258     if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
00259       ++ExistingIdx;
00260       ++ReadIdx;
00261       continue;
00262     }
00263 
00264     if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
00265       if (Diags)
00266         Diags->Report(diag::err_pch_targetopt_feature_mismatch)
00267           << false << ReadFeatures[ReadIdx];
00268       return true;
00269     }
00270 
00271     if (Diags)
00272       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
00273         << true << ExistingFeatures[ExistingIdx];
00274     return true;
00275   }
00276 
00277   if (ExistingIdx < ExistingN) {
00278     if (Diags)
00279       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
00280         << true << ExistingFeatures[ExistingIdx];
00281     return true;
00282   }
00283 
00284   if (ReadIdx < ReadN) {
00285     if (Diags)
00286       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
00287         << false << ReadFeatures[ReadIdx];
00288     return true;
00289   }
00290 
00291   return false;
00292 }
00293 
00294 bool
00295 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
00296                                   bool Complain,
00297                                   bool AllowCompatibleDifferences) {
00298   const LangOptions &ExistingLangOpts = PP.getLangOpts();
00299   return checkLanguageOptions(LangOpts, ExistingLangOpts,
00300                               Complain ? &Reader.Diags : nullptr,
00301                               AllowCompatibleDifferences);
00302 }
00303 
00304 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
00305                                      bool Complain) {
00306   const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
00307   return checkTargetOptions(TargetOpts, ExistingTargetOpts,
00308                             Complain? &Reader.Diags : nullptr);
00309 }
00310 
00311 namespace {
00312   typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
00313     MacroDefinitionsMap;
00314   typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
00315     DeclsMap;
00316 }
00317 
00318 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
00319                                          DiagnosticsEngine &Diags,
00320                                          bool Complain) {
00321   typedef DiagnosticsEngine::Level Level;
00322 
00323   // Check current mappings for new -Werror mappings, and the stored mappings
00324   // for cases that were explicitly mapped to *not* be errors that are now
00325   // errors because of options like -Werror.
00326   DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
00327 
00328   for (DiagnosticsEngine *MappingSource : MappingSources) {
00329     for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
00330       diag::kind DiagID = DiagIDMappingPair.first;
00331       Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
00332       if (CurLevel < DiagnosticsEngine::Error)
00333         continue; // not significant
00334       Level StoredLevel =
00335           StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
00336       if (StoredLevel < DiagnosticsEngine::Error) {
00337         if (Complain)
00338           Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
00339               Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
00340         return true;
00341       }
00342     }
00343   }
00344 
00345   return false;
00346 }
00347 
00348 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
00349   diag::Severity Ext = Diags.getExtensionHandlingBehavior();
00350   if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
00351     return true;
00352   return Ext >= diag::Severity::Error;
00353 }
00354 
00355 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
00356                                     DiagnosticsEngine &Diags,
00357                                     bool IsSystem, bool Complain) {
00358   // Top-level options
00359   if (IsSystem) {
00360     if (Diags.getSuppressSystemWarnings())
00361       return false;
00362     // If -Wsystem-headers was not enabled before, be conservative
00363     if (StoredDiags.getSuppressSystemWarnings()) {
00364       if (Complain)
00365         Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
00366       return true;
00367     }
00368   }
00369 
00370   if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
00371     if (Complain)
00372       Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
00373     return true;
00374   }
00375 
00376   if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
00377       !StoredDiags.getEnableAllWarnings()) {
00378     if (Complain)
00379       Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
00380     return true;
00381   }
00382 
00383   if (isExtHandlingFromDiagsError(Diags) &&
00384       !isExtHandlingFromDiagsError(StoredDiags)) {
00385     if (Complain)
00386       Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
00387     return true;
00388   }
00389 
00390   return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
00391 }
00392 
00393 bool PCHValidator::ReadDiagnosticOptions(
00394     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
00395   DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
00396   IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
00397   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
00398       new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
00399   // This should never fail, because we would have processed these options
00400   // before writing them to an ASTFile.
00401   ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
00402 
00403   ModuleManager &ModuleMgr = Reader.getModuleManager();
00404   assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
00405 
00406   // If the original import came from a file explicitly generated by the user,
00407   // don't check the diagnostic mappings.
00408   // FIXME: currently this is approximated by checking whether this is not a
00409   // module import of an implicitly-loaded module file.
00410   // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
00411   // the transitive closure of its imports, since unrelated modules cannot be
00412   // imported until after this module finishes validation.
00413   ModuleFile *TopImport = *ModuleMgr.rbegin();
00414   while (!TopImport->ImportedBy.empty())
00415     TopImport = TopImport->ImportedBy[0];
00416   if (TopImport->Kind != MK_ImplicitModule)
00417     return false;
00418 
00419   StringRef ModuleName = TopImport->ModuleName;
00420   assert(!ModuleName.empty() && "diagnostic options read before module name");
00421 
00422   Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
00423   assert(M && "missing module");
00424 
00425   // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
00426   // contains the union of their flags.
00427   return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
00428 }
00429 
00430 /// \brief Collect the macro definitions provided by the given preprocessor
00431 /// options.
00432 static void
00433 collectMacroDefinitions(const PreprocessorOptions &PPOpts,
00434                         MacroDefinitionsMap &Macros,
00435                         SmallVectorImpl<StringRef> *MacroNames = nullptr) {
00436   for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
00437     StringRef Macro = PPOpts.Macros[I].first;
00438     bool IsUndef = PPOpts.Macros[I].second;
00439 
00440     std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
00441     StringRef MacroName = MacroPair.first;
00442     StringRef MacroBody = MacroPair.second;
00443 
00444     // For an #undef'd macro, we only care about the name.
00445     if (IsUndef) {
00446       if (MacroNames && !Macros.count(MacroName))
00447         MacroNames->push_back(MacroName);
00448 
00449       Macros[MacroName] = std::make_pair("", true);
00450       continue;
00451     }
00452 
00453     // For a #define'd macro, figure out the actual definition.
00454     if (MacroName.size() == Macro.size())
00455       MacroBody = "1";
00456     else {
00457       // Note: GCC drops anything following an end-of-line character.
00458       StringRef::size_type End = MacroBody.find_first_of("\n\r");
00459       MacroBody = MacroBody.substr(0, End);
00460     }
00461 
00462     if (MacroNames && !Macros.count(MacroName))
00463       MacroNames->push_back(MacroName);
00464     Macros[MacroName] = std::make_pair(MacroBody, false);
00465   }
00466 }
00467          
00468 /// \brief Check the preprocessor options deserialized from the control block
00469 /// against the preprocessor options in an existing preprocessor.
00470 ///
00471 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
00472 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
00473                                      const PreprocessorOptions &ExistingPPOpts,
00474                                      DiagnosticsEngine *Diags,
00475                                      FileManager &FileMgr,
00476                                      std::string &SuggestedPredefines,
00477                                      const LangOptions &LangOpts) {
00478   // Check macro definitions.
00479   MacroDefinitionsMap ASTFileMacros;
00480   collectMacroDefinitions(PPOpts, ASTFileMacros);
00481   MacroDefinitionsMap ExistingMacros;
00482   SmallVector<StringRef, 4> ExistingMacroNames;
00483   collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
00484 
00485   for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
00486     // Dig out the macro definition in the existing preprocessor options.
00487     StringRef MacroName = ExistingMacroNames[I];
00488     std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
00489 
00490     // Check whether we know anything about this macro name or not.
00491     llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
00492       = ASTFileMacros.find(MacroName);
00493     if (Known == ASTFileMacros.end()) {
00494       // FIXME: Check whether this identifier was referenced anywhere in the
00495       // AST file. If so, we should reject the AST file. Unfortunately, this
00496       // information isn't in the control block. What shall we do about it?
00497 
00498       if (Existing.second) {
00499         SuggestedPredefines += "#undef ";
00500         SuggestedPredefines += MacroName.str();
00501         SuggestedPredefines += '\n';
00502       } else {
00503         SuggestedPredefines += "#define ";
00504         SuggestedPredefines += MacroName.str();
00505         SuggestedPredefines += ' ';
00506         SuggestedPredefines += Existing.first.str();
00507         SuggestedPredefines += '\n';
00508       }
00509       continue;
00510     }
00511 
00512     // If the macro was defined in one but undef'd in the other, we have a
00513     // conflict.
00514     if (Existing.second != Known->second.second) {
00515       if (Diags) {
00516         Diags->Report(diag::err_pch_macro_def_undef)
00517           << MacroName << Known->second.second;
00518       }
00519       return true;
00520     }
00521 
00522     // If the macro was #undef'd in both, or if the macro bodies are identical,
00523     // it's fine.
00524     if (Existing.second || Existing.first == Known->second.first)
00525       continue;
00526 
00527     // The macro bodies differ; complain.
00528     if (Diags) {
00529       Diags->Report(diag::err_pch_macro_def_conflict)
00530         << MacroName << Known->second.first << Existing.first;
00531     }
00532     return true;
00533   }
00534 
00535   // Check whether we're using predefines.
00536   if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
00537     if (Diags) {
00538       Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
00539     }
00540     return true;
00541   }
00542 
00543   // Detailed record is important since it is used for the module cache hash.
00544   if (LangOpts.Modules &&
00545       PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
00546     if (Diags) {
00547       Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
00548     }
00549     return true;
00550   }
00551 
00552   // Compute the #include and #include_macros lines we need.
00553   for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
00554     StringRef File = ExistingPPOpts.Includes[I];
00555     if (File == ExistingPPOpts.ImplicitPCHInclude)
00556       continue;
00557 
00558     if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
00559           != PPOpts.Includes.end())
00560       continue;
00561 
00562     SuggestedPredefines += "#include \"";
00563     SuggestedPredefines += File;
00564     SuggestedPredefines += "\"\n";
00565   }
00566 
00567   for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
00568     StringRef File = ExistingPPOpts.MacroIncludes[I];
00569     if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
00570                   File)
00571         != PPOpts.MacroIncludes.end())
00572       continue;
00573 
00574     SuggestedPredefines += "#__include_macros \"";
00575     SuggestedPredefines += File;
00576     SuggestedPredefines += "\"\n##\n";
00577   }
00578 
00579   return false;
00580 }
00581 
00582 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
00583                                            bool Complain,
00584                                            std::string &SuggestedPredefines) {
00585   const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
00586 
00587   return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
00588                                   Complain? &Reader.Diags : nullptr,
00589                                   PP.getFileManager(),
00590                                   SuggestedPredefines,
00591                                   PP.getLangOpts());
00592 }
00593 
00594 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
00595   PP.setCounterValue(Value);
00596 }
00597 
00598 //===----------------------------------------------------------------------===//
00599 // AST reader implementation
00600 //===----------------------------------------------------------------------===//
00601 
00602 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
00603                                            bool TakeOwnership) {
00604   DeserializationListener = Listener;
00605   OwnsDeserializationListener = TakeOwnership;
00606 }
00607 
00608 
00609 
00610 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
00611   return serialization::ComputeHash(Sel);
00612 }
00613 
00614 
00615 std::pair<unsigned, unsigned>
00616 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
00617   using namespace llvm::support;
00618   unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
00619   unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
00620   return std::make_pair(KeyLen, DataLen);
00621 }
00622 
00623 ASTSelectorLookupTrait::internal_key_type 
00624 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
00625   using namespace llvm::support;
00626   SelectorTable &SelTable = Reader.getContext().Selectors;
00627   unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
00628   IdentifierInfo *FirstII = Reader.getLocalIdentifier(
00629       F, endian::readNext<uint32_t, little, unaligned>(d));
00630   if (N == 0)
00631     return SelTable.getNullarySelector(FirstII);
00632   else if (N == 1)
00633     return SelTable.getUnarySelector(FirstII);
00634 
00635   SmallVector<IdentifierInfo *, 16> Args;
00636   Args.push_back(FirstII);
00637   for (unsigned I = 1; I != N; ++I)
00638     Args.push_back(Reader.getLocalIdentifier(
00639         F, endian::readNext<uint32_t, little, unaligned>(d)));
00640 
00641   return SelTable.getSelector(N, Args.data());
00642 }
00643 
00644 ASTSelectorLookupTrait::data_type 
00645 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d, 
00646                                  unsigned DataLen) {
00647   using namespace llvm::support;
00648 
00649   data_type Result;
00650 
00651   Result.ID = Reader.getGlobalSelectorID(
00652       F, endian::readNext<uint32_t, little, unaligned>(d));
00653   unsigned NumInstanceMethodsAndBits =
00654       endian::readNext<uint16_t, little, unaligned>(d);
00655   unsigned NumFactoryMethodsAndBits =
00656       endian::readNext<uint16_t, little, unaligned>(d);
00657   Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
00658   Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
00659   unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
00660   unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
00661 
00662   // Load instance methods
00663   for (unsigned I = 0; I != NumInstanceMethods; ++I) {
00664     if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
00665             F, endian::readNext<uint32_t, little, unaligned>(d)))
00666       Result.Instance.push_back(Method);
00667   }
00668 
00669   // Load factory methods
00670   for (unsigned I = 0; I != NumFactoryMethods; ++I) {
00671     if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
00672             F, endian::readNext<uint32_t, little, unaligned>(d)))
00673       Result.Factory.push_back(Method);
00674   }
00675 
00676   return Result;
00677 }
00678 
00679 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
00680   return llvm::HashString(a);
00681 }
00682 
00683 std::pair<unsigned, unsigned>
00684 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
00685   using namespace llvm::support;
00686   unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
00687   unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
00688   return std::make_pair(KeyLen, DataLen);
00689 }
00690 
00691 ASTIdentifierLookupTraitBase::internal_key_type
00692 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
00693   assert(n >= 2 && d[n-1] == '\0');
00694   return StringRef((const char*) d, n-1);
00695 }
00696 
00697 /// \brief Whether the given identifier is "interesting".
00698 static bool isInterestingIdentifier(IdentifierInfo &II) {
00699   return II.isPoisoned() ||
00700          II.isExtensionToken() ||
00701          II.getObjCOrBuiltinID() ||
00702          II.hasRevertedTokenIDToIdentifier() ||
00703          II.hadMacroDefinition() ||
00704          II.getFETokenInfo<void>();
00705 }
00706 
00707 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
00708                                                    const unsigned char* d,
00709                                                    unsigned DataLen) {
00710   using namespace llvm::support;
00711   unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
00712   bool IsInteresting = RawID & 0x01;
00713 
00714   // Wipe out the "is interesting" bit.
00715   RawID = RawID >> 1;
00716 
00717   IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
00718   if (!IsInteresting) {
00719     // For uninteresting identifiers, just build the IdentifierInfo
00720     // and associate it with the persistent ID.
00721     IdentifierInfo *II = KnownII;
00722     if (!II) {
00723       II = &Reader.getIdentifierTable().getOwn(k);
00724       KnownII = II;
00725     }
00726     Reader.SetIdentifierInfo(ID, II);
00727     if (!II->isFromAST()) {
00728       bool WasInteresting = isInterestingIdentifier(*II);
00729       II->setIsFromAST();
00730       if (WasInteresting)
00731         II->setChangedSinceDeserialization();
00732     }
00733     Reader.markIdentifierUpToDate(II);
00734     return II;
00735   }
00736 
00737   unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
00738   unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
00739   bool CPlusPlusOperatorKeyword = Bits & 0x01;
00740   Bits >>= 1;
00741   bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
00742   Bits >>= 1;
00743   bool Poisoned = Bits & 0x01;
00744   Bits >>= 1;
00745   bool ExtensionToken = Bits & 0x01;
00746   Bits >>= 1;
00747   bool hasSubmoduleMacros = Bits & 0x01;
00748   Bits >>= 1;
00749   bool hadMacroDefinition = Bits & 0x01;
00750   Bits >>= 1;
00751 
00752   assert(Bits == 0 && "Extra bits in the identifier?");
00753   DataLen -= 8;
00754 
00755   // Build the IdentifierInfo itself and link the identifier ID with
00756   // the new IdentifierInfo.
00757   IdentifierInfo *II = KnownII;
00758   if (!II) {
00759     II = &Reader.getIdentifierTable().getOwn(StringRef(k));
00760     KnownII = II;
00761   }
00762   Reader.markIdentifierUpToDate(II);
00763   if (!II->isFromAST()) {
00764     bool WasInteresting = isInterestingIdentifier(*II);
00765     II->setIsFromAST();
00766     if (WasInteresting)
00767       II->setChangedSinceDeserialization();
00768   }
00769 
00770   // Set or check the various bits in the IdentifierInfo structure.
00771   // Token IDs are read-only.
00772   if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
00773     II->RevertTokenIDToIdentifier();
00774   II->setObjCOrBuiltinID(ObjCOrBuiltinID);
00775   assert(II->isExtensionToken() == ExtensionToken &&
00776          "Incorrect extension token flag");
00777   (void)ExtensionToken;
00778   if (Poisoned)
00779     II->setIsPoisoned(true);
00780   assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
00781          "Incorrect C++ operator keyword flag");
00782   (void)CPlusPlusOperatorKeyword;
00783 
00784   // If this identifier is a macro, deserialize the macro
00785   // definition.
00786   if (hadMacroDefinition) {
00787     uint32_t MacroDirectivesOffset =
00788         endian::readNext<uint32_t, little, unaligned>(d);
00789     DataLen -= 4;
00790     SmallVector<uint32_t, 8> LocalMacroIDs;
00791     if (hasSubmoduleMacros) {
00792       while (true) {
00793         uint32_t LocalMacroID =
00794             endian::readNext<uint32_t, little, unaligned>(d);
00795         DataLen -= 4;
00796         if (LocalMacroID == 0xdeadbeef) break;
00797         LocalMacroIDs.push_back(LocalMacroID);
00798       }
00799     }
00800 
00801     if (F.Kind == MK_ImplicitModule || F.Kind == MK_ExplicitModule) {
00802       // Macro definitions are stored from newest to oldest, so reverse them
00803       // before registering them.
00804       llvm::SmallVector<unsigned, 8> MacroSizes;
00805       for (SmallVectorImpl<uint32_t>::iterator
00806              I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
00807         unsigned Size = 1;
00808 
00809         static const uint32_t HasOverridesFlag = 0x80000000U;
00810         if (I + 1 != E && (I[1] & HasOverridesFlag))
00811           Size += 1 + (I[1] & ~HasOverridesFlag);
00812 
00813         MacroSizes.push_back(Size);
00814         I += Size;
00815       }
00816 
00817       SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
00818       for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
00819                                                        SE = MacroSizes.rend();
00820            SI != SE; ++SI) {
00821         I -= *SI;
00822 
00823         uint32_t LocalMacroID = *I;
00824         ArrayRef<uint32_t> Overrides;
00825         if (*SI != 1)
00826           Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
00827         Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
00828       }
00829       assert(I == LocalMacroIDs.begin());
00830     } else {
00831       Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
00832     }
00833   }
00834 
00835   Reader.SetIdentifierInfo(ID, II);
00836 
00837   // Read all of the declarations visible at global scope with this
00838   // name.
00839   if (DataLen > 0) {
00840     SmallVector<uint32_t, 4> DeclIDs;
00841     for (; DataLen > 0; DataLen -= 4)
00842       DeclIDs.push_back(Reader.getGlobalDeclID(
00843           F, endian::readNext<uint32_t, little, unaligned>(d)));
00844     Reader.SetGloballyVisibleDecls(II, DeclIDs);
00845   }
00846 
00847   return II;
00848 }
00849 
00850 unsigned 
00851 ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
00852   llvm::FoldingSetNodeID ID;
00853   ID.AddInteger(Key.Kind);
00854 
00855   switch (Key.Kind) {
00856   case DeclarationName::Identifier:
00857   case DeclarationName::CXXLiteralOperatorName:
00858     ID.AddString(((IdentifierInfo*)Key.Data)->getName());
00859     break;
00860   case DeclarationName::ObjCZeroArgSelector:
00861   case DeclarationName::ObjCOneArgSelector:
00862   case DeclarationName::ObjCMultiArgSelector:
00863     ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
00864     break;
00865   case DeclarationName::CXXOperatorName:
00866     ID.AddInteger((OverloadedOperatorKind)Key.Data);
00867     break;
00868   case DeclarationName::CXXConstructorName:
00869   case DeclarationName::CXXDestructorName:
00870   case DeclarationName::CXXConversionFunctionName:
00871   case DeclarationName::CXXUsingDirective:
00872     break;
00873   }
00874 
00875   return ID.ComputeHash();
00876 }
00877 
00878 ASTDeclContextNameLookupTrait::internal_key_type 
00879 ASTDeclContextNameLookupTrait::GetInternalKey(
00880                                           const external_key_type& Name) const {
00881   DeclNameKey Key;
00882   Key.Kind = Name.getNameKind();
00883   switch (Name.getNameKind()) {
00884   case DeclarationName::Identifier:
00885     Key.Data = (uint64_t)Name.getAsIdentifierInfo();
00886     break;
00887   case DeclarationName::ObjCZeroArgSelector:
00888   case DeclarationName::ObjCOneArgSelector:
00889   case DeclarationName::ObjCMultiArgSelector:
00890     Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
00891     break;
00892   case DeclarationName::CXXOperatorName:
00893     Key.Data = Name.getCXXOverloadedOperator();
00894     break;
00895   case DeclarationName::CXXLiteralOperatorName:
00896     Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
00897     break;
00898   case DeclarationName::CXXConstructorName:
00899   case DeclarationName::CXXDestructorName:
00900   case DeclarationName::CXXConversionFunctionName:
00901   case DeclarationName::CXXUsingDirective:
00902     Key.Data = 0;
00903     break;
00904   }
00905 
00906   return Key;
00907 }
00908 
00909 std::pair<unsigned, unsigned>
00910 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
00911   using namespace llvm::support;
00912   unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
00913   unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
00914   return std::make_pair(KeyLen, DataLen);
00915 }
00916 
00917 ASTDeclContextNameLookupTrait::internal_key_type 
00918 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
00919   using namespace llvm::support;
00920 
00921   DeclNameKey Key;
00922   Key.Kind = (DeclarationName::NameKind)*d++;
00923   switch (Key.Kind) {
00924   case DeclarationName::Identifier:
00925     Key.Data = (uint64_t)Reader.getLocalIdentifier(
00926         F, endian::readNext<uint32_t, little, unaligned>(d));
00927     break;
00928   case DeclarationName::ObjCZeroArgSelector:
00929   case DeclarationName::ObjCOneArgSelector:
00930   case DeclarationName::ObjCMultiArgSelector:
00931     Key.Data =
00932         (uint64_t)Reader.getLocalSelector(
00933                              F, endian::readNext<uint32_t, little, unaligned>(
00934                                     d)).getAsOpaquePtr();
00935     break;
00936   case DeclarationName::CXXOperatorName:
00937     Key.Data = *d++; // OverloadedOperatorKind
00938     break;
00939   case DeclarationName::CXXLiteralOperatorName:
00940     Key.Data = (uint64_t)Reader.getLocalIdentifier(
00941         F, endian::readNext<uint32_t, little, unaligned>(d));
00942     break;
00943   case DeclarationName::CXXConstructorName:
00944   case DeclarationName::CXXDestructorName:
00945   case DeclarationName::CXXConversionFunctionName:
00946   case DeclarationName::CXXUsingDirective:
00947     Key.Data = 0;
00948     break;
00949   }
00950 
00951   return Key;
00952 }
00953 
00954 ASTDeclContextNameLookupTrait::data_type 
00955 ASTDeclContextNameLookupTrait::ReadData(internal_key_type, 
00956                                         const unsigned char* d,
00957                                         unsigned DataLen) {
00958   using namespace llvm::support;
00959   unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
00960   LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
00961                         const_cast<unsigned char *>(d));
00962   return std::make_pair(Start, Start + NumDecls);
00963 }
00964 
00965 bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
00966                                        BitstreamCursor &Cursor,
00967                                    const std::pair<uint64_t, uint64_t> &Offsets,
00968                                        DeclContextInfo &Info) {
00969   SavedStreamPosition SavedPosition(Cursor);
00970   // First the lexical decls.
00971   if (Offsets.first != 0) {
00972     Cursor.JumpToBit(Offsets.first);
00973 
00974     RecordData Record;
00975     StringRef Blob;
00976     unsigned Code = Cursor.ReadCode();
00977     unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
00978     if (RecCode != DECL_CONTEXT_LEXICAL) {
00979       Error("Expected lexical block");
00980       return true;
00981     }
00982 
00983     Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
00984     Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
00985   }
00986 
00987   // Now the lookup table.
00988   if (Offsets.second != 0) {
00989     Cursor.JumpToBit(Offsets.second);
00990 
00991     RecordData Record;
00992     StringRef Blob;
00993     unsigned Code = Cursor.ReadCode();
00994     unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
00995     if (RecCode != DECL_CONTEXT_VISIBLE) {
00996       Error("Expected visible lookup table block");
00997       return true;
00998     }
00999     Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
01000         (const unsigned char *)Blob.data() + Record[0],
01001         (const unsigned char *)Blob.data() + sizeof(uint32_t),
01002         (const unsigned char *)Blob.data(),
01003         ASTDeclContextNameLookupTrait(*this, M));
01004   }
01005 
01006   return false;
01007 }
01008 
01009 void ASTReader::Error(StringRef Msg) {
01010   Error(diag::err_fe_pch_malformed, Msg);
01011   if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
01012     Diag(diag::note_module_cache_path)
01013       << PP.getHeaderSearchInfo().getModuleCachePath();
01014   }
01015 }
01016 
01017 void ASTReader::Error(unsigned DiagID,
01018                       StringRef Arg1, StringRef Arg2) {
01019   if (Diags.isDiagnosticInFlight())
01020     Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
01021   else
01022     Diag(DiagID) << Arg1 << Arg2;
01023 }
01024 
01025 //===----------------------------------------------------------------------===//
01026 // Source Manager Deserialization
01027 //===----------------------------------------------------------------------===//
01028 
01029 /// \brief Read the line table in the source manager block.
01030 /// \returns true if there was an error.
01031 bool ASTReader::ParseLineTable(ModuleFile &F,
01032                                SmallVectorImpl<uint64_t> &Record) {
01033   unsigned Idx = 0;
01034   LineTableInfo &LineTable = SourceMgr.getLineTable();
01035 
01036   // Parse the file names
01037   std::map<int, int> FileIDs;
01038   for (int I = 0, N = Record[Idx++]; I != N; ++I) {
01039     // Extract the file name
01040     unsigned FilenameLen = Record[Idx++];
01041     std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
01042     Idx += FilenameLen;
01043     MaybeAddSystemRootToFilename(F, Filename);
01044     FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
01045   }
01046 
01047   // Parse the line entries
01048   std::vector<LineEntry> Entries;
01049   while (Idx < Record.size()) {
01050     int FID = Record[Idx++];
01051     assert(FID >= 0 && "Serialized line entries for non-local file.");
01052     // Remap FileID from 1-based old view.
01053     FID += F.SLocEntryBaseID - 1;
01054 
01055     // Extract the line entries
01056     unsigned NumEntries = Record[Idx++];
01057     assert(NumEntries && "Numentries is 00000");
01058     Entries.clear();
01059     Entries.reserve(NumEntries);
01060     for (unsigned I = 0; I != NumEntries; ++I) {
01061       unsigned FileOffset = Record[Idx++];
01062       unsigned LineNo = Record[Idx++];
01063       int FilenameID = FileIDs[Record[Idx++]];
01064       SrcMgr::CharacteristicKind FileKind
01065         = (SrcMgr::CharacteristicKind)Record[Idx++];
01066       unsigned IncludeOffset = Record[Idx++];
01067       Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
01068                                        FileKind, IncludeOffset));
01069     }
01070     LineTable.AddEntry(FileID::get(FID), Entries);
01071   }
01072 
01073   return false;
01074 }
01075 
01076 /// \brief Read a source manager block
01077 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
01078   using namespace SrcMgr;
01079 
01080   BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
01081 
01082   // Set the source-location entry cursor to the current position in
01083   // the stream. This cursor will be used to read the contents of the
01084   // source manager block initially, and then lazily read
01085   // source-location entries as needed.
01086   SLocEntryCursor = F.Stream;
01087 
01088   // The stream itself is going to skip over the source manager block.
01089   if (F.Stream.SkipBlock()) {
01090     Error("malformed block record in AST file");
01091     return true;
01092   }
01093 
01094   // Enter the source manager block.
01095   if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
01096     Error("malformed source manager block record in AST file");
01097     return true;
01098   }
01099 
01100   RecordData Record;
01101   while (true) {
01102     llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
01103     
01104     switch (E.Kind) {
01105     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
01106     case llvm::BitstreamEntry::Error:
01107       Error("malformed block record in AST file");
01108       return true;
01109     case llvm::BitstreamEntry::EndBlock:
01110       return false;
01111     case llvm::BitstreamEntry::Record:
01112       // The interesting case.
01113       break;
01114     }
01115     
01116     // Read a record.
01117     Record.clear();
01118     StringRef Blob;
01119     switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
01120     default:  // Default behavior: ignore.
01121       break;
01122 
01123     case SM_SLOC_FILE_ENTRY:
01124     case SM_SLOC_BUFFER_ENTRY:
01125     case SM_SLOC_EXPANSION_ENTRY:
01126       // Once we hit one of the source location entries, we're done.
01127       return false;
01128     }
01129   }
01130 }
01131 
01132 /// \brief If a header file is not found at the path that we expect it to be
01133 /// and the PCH file was moved from its original location, try to resolve the
01134 /// file by assuming that header+PCH were moved together and the header is in
01135 /// the same place relative to the PCH.
01136 static std::string
01137 resolveFileRelativeToOriginalDir(const std::string &Filename,
01138                                  const std::string &OriginalDir,
01139                                  const std::string &CurrDir) {
01140   assert(OriginalDir != CurrDir &&
01141          "No point trying to resolve the file if the PCH dir didn't change");
01142   using namespace llvm::sys;
01143   SmallString<128> filePath(Filename);
01144   fs::make_absolute(filePath);
01145   assert(path::is_absolute(OriginalDir));
01146   SmallString<128> currPCHPath(CurrDir);
01147 
01148   path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
01149                        fileDirE = path::end(path::parent_path(filePath));
01150   path::const_iterator origDirI = path::begin(OriginalDir),
01151                        origDirE = path::end(OriginalDir);
01152   // Skip the common path components from filePath and OriginalDir.
01153   while (fileDirI != fileDirE && origDirI != origDirE &&
01154          *fileDirI == *origDirI) {
01155     ++fileDirI;
01156     ++origDirI;
01157   }
01158   for (; origDirI != origDirE; ++origDirI)
01159     path::append(currPCHPath, "..");
01160   path::append(currPCHPath, fileDirI, fileDirE);
01161   path::append(currPCHPath, path::filename(Filename));
01162   return currPCHPath.str();
01163 }
01164 
01165 bool ASTReader::ReadSLocEntry(int ID) {
01166   if (ID == 0)
01167     return false;
01168 
01169   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
01170     Error("source location entry ID out-of-range for AST file");
01171     return true;
01172   }
01173 
01174   ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
01175   F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
01176   BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
01177   unsigned BaseOffset = F->SLocEntryBaseOffset;
01178 
01179   ++NumSLocEntriesRead;
01180   llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
01181   if (Entry.Kind != llvm::BitstreamEntry::Record) {
01182     Error("incorrectly-formatted source location entry in AST file");
01183     return true;
01184   }
01185   
01186   RecordData Record;
01187   StringRef Blob;
01188   switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
01189   default:
01190     Error("incorrectly-formatted source location entry in AST file");
01191     return true;
01192 
01193   case SM_SLOC_FILE_ENTRY: {
01194     // We will detect whether a file changed and return 'Failure' for it, but
01195     // we will also try to fail gracefully by setting up the SLocEntry.
01196     unsigned InputID = Record[4];
01197     InputFile IF = getInputFile(*F, InputID);
01198     const FileEntry *File = IF.getFile();
01199     bool OverriddenBuffer = IF.isOverridden();
01200 
01201     // Note that we only check if a File was returned. If it was out-of-date
01202     // we have complained but we will continue creating a FileID to recover
01203     // gracefully.
01204     if (!File)
01205       return true;
01206 
01207     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
01208     if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
01209       // This is the module's main file.
01210       IncludeLoc = getImportLocation(F);
01211     }
01212     SrcMgr::CharacteristicKind
01213       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
01214     FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
01215                                         ID, BaseOffset + Record[0]);
01216     SrcMgr::FileInfo &FileInfo =
01217           const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
01218     FileInfo.NumCreatedFIDs = Record[5];
01219     if (Record[3])
01220       FileInfo.setHasLineDirectives();
01221 
01222     const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
01223     unsigned NumFileDecls = Record[7];
01224     if (NumFileDecls) {
01225       assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
01226       FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
01227                                                              NumFileDecls));
01228     }
01229     
01230     const SrcMgr::ContentCache *ContentCache
01231       = SourceMgr.getOrCreateContentCache(File,
01232                               /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
01233     if (OverriddenBuffer && !ContentCache->BufferOverridden &&
01234         ContentCache->ContentsEntry == ContentCache->OrigEntry) {
01235       unsigned Code = SLocEntryCursor.ReadCode();
01236       Record.clear();
01237       unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
01238       
01239       if (RecCode != SM_SLOC_BUFFER_BLOB) {
01240         Error("AST record has invalid code");
01241         return true;
01242       }
01243       
01244       std::unique_ptr<llvm::MemoryBuffer> Buffer
01245         = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
01246       SourceMgr.overrideFileContents(File, std::move(Buffer));
01247     }
01248 
01249     break;
01250   }
01251 
01252   case SM_SLOC_BUFFER_ENTRY: {
01253     const char *Name = Blob.data();
01254     unsigned Offset = Record[0];
01255     SrcMgr::CharacteristicKind
01256       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
01257     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
01258     if (IncludeLoc.isInvalid() &&
01259         (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
01260       IncludeLoc = getImportLocation(F);
01261     }
01262     unsigned Code = SLocEntryCursor.ReadCode();
01263     Record.clear();
01264     unsigned RecCode
01265       = SLocEntryCursor.readRecord(Code, Record, &Blob);
01266 
01267     if (RecCode != SM_SLOC_BUFFER_BLOB) {
01268       Error("AST record has invalid code");
01269       return true;
01270     }
01271 
01272     std::unique_ptr<llvm::MemoryBuffer> Buffer =
01273         llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
01274     SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
01275                            BaseOffset + Offset, IncludeLoc);
01276     break;
01277   }
01278 
01279   case SM_SLOC_EXPANSION_ENTRY: {
01280     SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
01281     SourceMgr.createExpansionLoc(SpellingLoc,
01282                                      ReadSourceLocation(*F, Record[2]),
01283                                      ReadSourceLocation(*F, Record[3]),
01284                                      Record[4],
01285                                      ID,
01286                                      BaseOffset + Record[0]);
01287     break;
01288   }
01289   }
01290 
01291   return false;
01292 }
01293 
01294 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
01295   if (ID == 0)
01296     return std::make_pair(SourceLocation(), "");
01297 
01298   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
01299     Error("source location entry ID out-of-range for AST file");
01300     return std::make_pair(SourceLocation(), "");
01301   }
01302 
01303   // Find which module file this entry lands in.
01304   ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
01305   if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
01306     return std::make_pair(SourceLocation(), "");
01307 
01308   // FIXME: Can we map this down to a particular submodule? That would be
01309   // ideal.
01310   return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
01311 }
01312 
01313 /// \brief Find the location where the module F is imported.
01314 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
01315   if (F->ImportLoc.isValid())
01316     return F->ImportLoc;
01317   
01318   // Otherwise we have a PCH. It's considered to be "imported" at the first
01319   // location of its includer.
01320   if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
01321     // Main file is the importer.
01322     assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
01323     return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
01324   }
01325   return F->ImportedBy[0]->FirstLoc;
01326 }
01327 
01328 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
01329 /// specified cursor.  Read the abbreviations that are at the top of the block
01330 /// and then leave the cursor pointing into the block.
01331 bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
01332   if (Cursor.EnterSubBlock(BlockID)) {
01333     Error("malformed block record in AST file");
01334     return Failure;
01335   }
01336 
01337   while (true) {
01338     uint64_t Offset = Cursor.GetCurrentBitNo();
01339     unsigned Code = Cursor.ReadCode();
01340 
01341     // We expect all abbrevs to be at the start of the block.
01342     if (Code != llvm::bitc::DEFINE_ABBREV) {
01343       Cursor.JumpToBit(Offset);
01344       return false;
01345     }
01346     Cursor.ReadAbbrevRecord();
01347   }
01348 }
01349 
01350 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
01351                            unsigned &Idx) {
01352   Token Tok;
01353   Tok.startToken();
01354   Tok.setLocation(ReadSourceLocation(F, Record, Idx));
01355   Tok.setLength(Record[Idx++]);
01356   if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
01357     Tok.setIdentifierInfo(II);
01358   Tok.setKind((tok::TokenKind)Record[Idx++]);
01359   Tok.setFlag((Token::TokenFlags)Record[Idx++]);
01360   return Tok;
01361 }
01362 
01363 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
01364   BitstreamCursor &Stream = F.MacroCursor;
01365 
01366   // Keep track of where we are in the stream, then jump back there
01367   // after reading this macro.
01368   SavedStreamPosition SavedPosition(Stream);
01369 
01370   Stream.JumpToBit(Offset);
01371   RecordData Record;
01372   SmallVector<IdentifierInfo*, 16> MacroArgs;
01373   MacroInfo *Macro = nullptr;
01374 
01375   while (true) {
01376     // Advance to the next record, but if we get to the end of the block, don't
01377     // pop it (removing all the abbreviations from the cursor) since we want to
01378     // be able to reseek within the block and read entries.
01379     unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
01380     llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
01381     
01382     switch (Entry.Kind) {
01383     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
01384     case llvm::BitstreamEntry::Error:
01385       Error("malformed block record in AST file");
01386       return Macro;
01387     case llvm::BitstreamEntry::EndBlock:
01388       return Macro;
01389     case llvm::BitstreamEntry::Record:
01390       // The interesting case.
01391       break;
01392     }
01393 
01394     // Read a record.
01395     Record.clear();
01396     PreprocessorRecordTypes RecType =
01397       (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
01398     switch (RecType) {
01399     case PP_MACRO_DIRECTIVE_HISTORY:
01400       return Macro;
01401 
01402     case PP_MACRO_OBJECT_LIKE:
01403     case PP_MACRO_FUNCTION_LIKE: {
01404       // If we already have a macro, that means that we've hit the end
01405       // of the definition of the macro we were looking for. We're
01406       // done.
01407       if (Macro)
01408         return Macro;
01409 
01410       unsigned NextIndex = 1; // Skip identifier ID.
01411       SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
01412       SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
01413       MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
01414       MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
01415       MI->setIsUsed(Record[NextIndex++]);
01416       MI->setUsedForHeaderGuard(Record[NextIndex++]);
01417 
01418       if (RecType == PP_MACRO_FUNCTION_LIKE) {
01419         // Decode function-like macro info.
01420         bool isC99VarArgs = Record[NextIndex++];
01421         bool isGNUVarArgs = Record[NextIndex++];
01422         bool hasCommaPasting = Record[NextIndex++];
01423         MacroArgs.clear();
01424         unsigned NumArgs = Record[NextIndex++];
01425         for (unsigned i = 0; i != NumArgs; ++i)
01426           MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
01427 
01428         // Install function-like macro info.
01429         MI->setIsFunctionLike();
01430         if (isC99VarArgs) MI->setIsC99Varargs();
01431         if (isGNUVarArgs) MI->setIsGNUVarargs();
01432         if (hasCommaPasting) MI->setHasCommaPasting();
01433         MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
01434                             PP.getPreprocessorAllocator());
01435       }
01436 
01437       // Remember that we saw this macro last so that we add the tokens that
01438       // form its body to it.
01439       Macro = MI;
01440 
01441       if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
01442           Record[NextIndex]) {
01443         // We have a macro definition. Register the association
01444         PreprocessedEntityID
01445             GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
01446         PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
01447         PreprocessingRecord::PPEntityID
01448           PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
01449         MacroDefinition *PPDef =
01450           cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
01451         if (PPDef)
01452           PPRec.RegisterMacroDefinition(Macro, PPDef);
01453       }
01454 
01455       ++NumMacrosRead;
01456       break;
01457     }
01458 
01459     case PP_TOKEN: {
01460       // If we see a TOKEN before a PP_MACRO_*, then the file is
01461       // erroneous, just pretend we didn't see this.
01462       if (!Macro) break;
01463 
01464       unsigned Idx = 0;
01465       Token Tok = ReadToken(F, Record, Idx);
01466       Macro->AddTokenToBody(Tok);
01467       break;
01468     }
01469     }
01470   }
01471 }
01472 
01473 PreprocessedEntityID 
01474 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
01475   ContinuousRangeMap<uint32_t, int, 2>::const_iterator 
01476     I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
01477   assert(I != M.PreprocessedEntityRemap.end() 
01478          && "Invalid index into preprocessed entity index remap");
01479   
01480   return LocalID + I->second;
01481 }
01482 
01483 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
01484   return llvm::hash_combine(ikey.Size, ikey.ModTime);
01485 }
01486     
01487 HeaderFileInfoTrait::internal_key_type 
01488 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
01489   internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
01490                              FE->getName() };
01491   return ikey;
01492 }
01493     
01494 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
01495   if (a.Size != b.Size || a.ModTime != b.ModTime)
01496     return false;
01497 
01498   if (strcmp(a.Filename, b.Filename) == 0)
01499     return true;
01500   
01501   // Determine whether the actual files are equivalent.
01502   FileManager &FileMgr = Reader.getFileManager();
01503   const FileEntry *FEA = FileMgr.getFile(a.Filename);
01504   const FileEntry *FEB = FileMgr.getFile(b.Filename);
01505   return (FEA && FEA == FEB);
01506 }
01507     
01508 std::pair<unsigned, unsigned>
01509 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
01510   using namespace llvm::support;
01511   unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
01512   unsigned DataLen = (unsigned) *d++;
01513   return std::make_pair(KeyLen, DataLen);
01514 }
01515 
01516 HeaderFileInfoTrait::internal_key_type
01517 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
01518   using namespace llvm::support;
01519   internal_key_type ikey;
01520   ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
01521   ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
01522   ikey.Filename = (const char *)d;
01523   return ikey;
01524 }
01525 
01526 HeaderFileInfoTrait::data_type 
01527 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
01528                               unsigned DataLen) {
01529   const unsigned char *End = d + DataLen;
01530   using namespace llvm::support;
01531   HeaderFileInfo HFI;
01532   unsigned Flags = *d++;
01533   HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
01534                    ((Flags >> 6) & 0x03);
01535   HFI.isImport = (Flags >> 5) & 0x01;
01536   HFI.isPragmaOnce = (Flags >> 4) & 0x01;
01537   HFI.DirInfo = (Flags >> 2) & 0x03;
01538   HFI.Resolved = (Flags >> 1) & 0x01;
01539   HFI.IndexHeaderMapHeader = Flags & 0x01;
01540   HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
01541   HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
01542       M, endian::readNext<uint32_t, little, unaligned>(d));
01543   if (unsigned FrameworkOffset =
01544           endian::readNext<uint32_t, little, unaligned>(d)) {
01545     // The framework offset is 1 greater than the actual offset, 
01546     // since 0 is used as an indicator for "no framework name".
01547     StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
01548     HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
01549   }
01550   
01551   if (d != End) {
01552     uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
01553     if (LocalSMID) {
01554       // This header is part of a module. Associate it with the module to enable
01555       // implicit module import.
01556       SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
01557       Module *Mod = Reader.getSubmodule(GlobalSMID);
01558       HFI.isModuleHeader = true;
01559       FileManager &FileMgr = Reader.getFileManager();
01560       ModuleMap &ModMap =
01561           Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
01562       ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
01563     }
01564   }
01565 
01566   assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
01567   (void)End;
01568         
01569   // This HeaderFileInfo was externally loaded.
01570   HFI.External = true;
01571   return HFI;
01572 }
01573 
01574 void
01575 ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
01576                                      GlobalMacroID GMacID,
01577                                      ArrayRef<SubmoduleID> Overrides) {
01578   assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
01579   SubmoduleID *OverrideData = nullptr;
01580   if (!Overrides.empty()) {
01581     OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
01582     OverrideData[0] = Overrides.size();
01583     for (unsigned I = 0; I != Overrides.size(); ++I)
01584       OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
01585   }
01586   PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
01587 }
01588 
01589 void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
01590                                        ModuleFile *M,
01591                                        uint64_t MacroDirectivesOffset) {
01592   assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
01593   PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
01594 }
01595 
01596 void ASTReader::ReadDefinedMacros() {
01597   // Note that we are loading defined macros.
01598   Deserializing Macros(this);
01599 
01600   for (ModuleReverseIterator I = ModuleMgr.rbegin(),
01601       E = ModuleMgr.rend(); I != E; ++I) {
01602     BitstreamCursor &MacroCursor = (*I)->MacroCursor;
01603 
01604     // If there was no preprocessor block, skip this file.
01605     if (!MacroCursor.getBitStreamReader())
01606       continue;
01607 
01608     BitstreamCursor Cursor = MacroCursor;
01609     Cursor.JumpToBit((*I)->MacroStartOffset);
01610 
01611     RecordData Record;
01612     while (true) {
01613       llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
01614       
01615       switch (E.Kind) {
01616       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
01617       case llvm::BitstreamEntry::Error:
01618         Error("malformed block record in AST file");
01619         return;
01620       case llvm::BitstreamEntry::EndBlock:
01621         goto NextCursor;
01622         
01623       case llvm::BitstreamEntry::Record:
01624         Record.clear();
01625         switch (Cursor.readRecord(E.ID, Record)) {
01626         default:  // Default behavior: ignore.
01627           break;
01628           
01629         case PP_MACRO_OBJECT_LIKE:
01630         case PP_MACRO_FUNCTION_LIKE:
01631           getLocalIdentifier(**I, Record[0]);
01632           break;
01633           
01634         case PP_TOKEN:
01635           // Ignore tokens.
01636           break;
01637         }
01638         break;
01639       }
01640     }
01641     NextCursor:  ;
01642   }
01643 }
01644 
01645 namespace {
01646   /// \brief Visitor class used to look up identifirs in an AST file.
01647   class IdentifierLookupVisitor {
01648     StringRef Name;
01649     unsigned PriorGeneration;
01650     unsigned &NumIdentifierLookups;
01651     unsigned &NumIdentifierLookupHits;
01652     IdentifierInfo *Found;
01653 
01654   public:
01655     IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
01656                             unsigned &NumIdentifierLookups,
01657                             unsigned &NumIdentifierLookupHits)
01658       : Name(Name), PriorGeneration(PriorGeneration),
01659         NumIdentifierLookups(NumIdentifierLookups),
01660         NumIdentifierLookupHits(NumIdentifierLookupHits),
01661         Found()
01662     {
01663     }
01664     
01665     static bool visit(ModuleFile &M, void *UserData) {
01666       IdentifierLookupVisitor *This
01667         = static_cast<IdentifierLookupVisitor *>(UserData);
01668       
01669       // If we've already searched this module file, skip it now.
01670       if (M.Generation <= This->PriorGeneration)
01671         return true;
01672 
01673       ASTIdentifierLookupTable *IdTable
01674         = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
01675       if (!IdTable)
01676         return false;
01677       
01678       ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
01679                                      M, This->Found);
01680       ++This->NumIdentifierLookups;
01681       ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
01682       if (Pos == IdTable->end())
01683         return false;
01684       
01685       // Dereferencing the iterator has the effect of building the
01686       // IdentifierInfo node and populating it with the various
01687       // declarations it needs.
01688       ++This->NumIdentifierLookupHits;
01689       This->Found = *Pos;
01690       return true;
01691     }
01692     
01693     // \brief Retrieve the identifier info found within the module
01694     // files.
01695     IdentifierInfo *getIdentifierInfo() const { return Found; }
01696   };
01697 }
01698 
01699 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
01700   // Note that we are loading an identifier.
01701   Deserializing AnIdentifier(this);
01702 
01703   unsigned PriorGeneration = 0;
01704   if (getContext().getLangOpts().Modules)
01705     PriorGeneration = IdentifierGeneration[&II];
01706 
01707   // If there is a global index, look there first to determine which modules
01708   // provably do not have any results for this identifier.
01709   GlobalModuleIndex::HitSet Hits;
01710   GlobalModuleIndex::HitSet *HitsPtr = nullptr;
01711   if (!loadGlobalIndex()) {
01712     if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
01713       HitsPtr = &Hits;
01714     }
01715   }
01716 
01717   IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
01718                                   NumIdentifierLookups,
01719                                   NumIdentifierLookupHits);
01720   ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
01721   markIdentifierUpToDate(&II);
01722 }
01723 
01724 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
01725   if (!II)
01726     return;
01727   
01728   II->setOutOfDate(false);
01729 
01730   // Update the generation for this identifier.
01731   if (getContext().getLangOpts().Modules)
01732     IdentifierGeneration[II] = getGeneration();
01733 }
01734 
01735 struct ASTReader::ModuleMacroInfo {
01736   SubmoduleID SubModID;
01737   MacroInfo *MI;
01738   SubmoduleID *Overrides;
01739   // FIXME: Remove this.
01740   ModuleFile *F;
01741 
01742   bool isDefine() const { return MI; }
01743 
01744   SubmoduleID getSubmoduleID() const { return SubModID; }
01745 
01746   ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
01747     if (!Overrides)
01748       return None;
01749     return llvm::makeArrayRef(Overrides + 1, *Overrides);
01750   }
01751 
01752   MacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
01753     if (!MI)
01754       return PP.AllocateUndefMacroDirective(ImportLoc, SubModID,
01755                                             getOverriddenSubmodules());
01756     return PP.AllocateDefMacroDirective(MI, ImportLoc, SubModID,
01757                                         getOverriddenSubmodules());
01758   }
01759 };
01760 
01761 ASTReader::ModuleMacroInfo *
01762 ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
01763   ModuleMacroInfo Info;
01764 
01765   uint32_t ID = PMInfo.ModuleMacroData.MacID;
01766   if (ID & 1) {
01767     // Macro undefinition.
01768     Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
01769     Info.MI = nullptr;
01770   } else {
01771     // Macro definition.
01772     GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
01773     assert(GMacID);
01774 
01775     // If this macro has already been loaded, don't do so again.
01776     // FIXME: This is highly dubious. Multiple macro definitions can have the
01777     // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
01778     if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
01779       return nullptr;
01780 
01781     Info.MI = getMacro(GMacID);
01782     Info.SubModID = Info.MI->getOwningModuleID();
01783   }
01784   Info.Overrides = PMInfo.ModuleMacroData.Overrides;
01785   Info.F = PMInfo.M;
01786 
01787   return new (Context) ModuleMacroInfo(Info);
01788 }
01789 
01790 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
01791                                     const PendingMacroInfo &PMInfo) {
01792   assert(II);
01793 
01794   if (PMInfo.M->Kind != MK_ImplicitModule &&
01795       PMInfo.M->Kind != MK_ExplicitModule) {
01796     installPCHMacroDirectives(II, *PMInfo.M,
01797                               PMInfo.PCHMacroData.MacroDirectivesOffset);
01798     return;
01799   }
01800 
01801   // Module Macro.
01802 
01803   ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
01804   if (!MMI)
01805     return;
01806 
01807   Module *Owner = getSubmodule(MMI->getSubmoduleID());
01808   if (Owner && Owner->NameVisibility == Module::Hidden) {
01809     // Macros in the owning module are hidden. Just remember this macro to
01810     // install if we make this module visible.
01811     HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
01812   } else {
01813     installImportedMacro(II, MMI, Owner);
01814   }
01815 }
01816 
01817 void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
01818                                           ModuleFile &M, uint64_t Offset) {
01819   assert(M.Kind != MK_ImplicitModule && M.Kind != MK_ExplicitModule);
01820 
01821   BitstreamCursor &Cursor = M.MacroCursor;
01822   SavedStreamPosition SavedPosition(Cursor);
01823   Cursor.JumpToBit(Offset);
01824 
01825   llvm::BitstreamEntry Entry =
01826       Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
01827   if (Entry.Kind != llvm::BitstreamEntry::Record) {
01828     Error("malformed block record in AST file");
01829     return;
01830   }
01831 
01832   RecordData Record;
01833   PreprocessorRecordTypes RecType =
01834     (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
01835   if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
01836     Error("malformed block record in AST file");
01837     return;
01838   }
01839 
01840   // Deserialize the macro directives history in reverse source-order.
01841   MacroDirective *Latest = nullptr, *Earliest = nullptr;
01842   unsigned Idx = 0, N = Record.size();
01843   while (Idx < N) {
01844     MacroDirective *MD = nullptr;
01845     SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
01846     MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
01847     switch (K) {
01848     case MacroDirective::MD_Define: {
01849       GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
01850       MacroInfo *MI = getMacro(GMacID);
01851       SubmoduleID ImportedFrom = Record[Idx++];
01852       bool IsAmbiguous = Record[Idx++];
01853       llvm::SmallVector<unsigned, 4> Overrides;
01854       if (ImportedFrom) {
01855         Overrides.insert(Overrides.end(),
01856                          &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
01857         Idx += Overrides.size() + 1;
01858       }
01859       DefMacroDirective *DefMD =
01860           PP.AllocateDefMacroDirective(MI, Loc, ImportedFrom, Overrides);
01861       DefMD->setAmbiguous(IsAmbiguous);
01862       MD = DefMD;
01863       break;
01864     }
01865     case MacroDirective::MD_Undefine: {
01866       SubmoduleID ImportedFrom = Record[Idx++];
01867       llvm::SmallVector<unsigned, 4> Overrides;
01868       if (ImportedFrom) {
01869         Overrides.insert(Overrides.end(),
01870                          &Record[Idx] + 1, &Record[Idx] + 1 + Record[Idx]);
01871         Idx += Overrides.size() + 1;
01872       }
01873       MD = PP.AllocateUndefMacroDirective(Loc, ImportedFrom, Overrides);
01874       break;
01875     }
01876     case MacroDirective::MD_Visibility:
01877       bool isPublic = Record[Idx++];
01878       MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
01879       break;
01880     }
01881 
01882     if (!Latest)
01883       Latest = MD;
01884     if (Earliest)
01885       Earliest->setPrevious(MD);
01886     Earliest = MD;
01887   }
01888 
01889   PP.setLoadedMacroDirective(II, Latest);
01890 }
01891 
01892 /// \brief For the given macro definitions, check if they are both in system
01893 /// modules.
01894 static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
01895                                       Module *NewOwner, ASTReader &Reader) {
01896   assert(PrevMI && NewMI);
01897   Module *PrevOwner = nullptr;
01898   if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
01899     PrevOwner = Reader.getSubmodule(PrevModID);
01900   SourceManager &SrcMgr = Reader.getSourceManager();
01901   bool PrevInSystem
01902     = PrevOwner? PrevOwner->IsSystem
01903                : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
01904   bool NewInSystem
01905     = NewOwner? NewOwner->IsSystem
01906               : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
01907   if (PrevOwner && PrevOwner == NewOwner)
01908     return false;
01909   return PrevInSystem && NewInSystem;
01910 }
01911 
01912 void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
01913                                        SourceLocation ImportLoc,
01914                                        AmbiguousMacros &Ambig,
01915                                        ArrayRef<SubmoduleID> Overrides) {
01916   for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
01917     SubmoduleID OwnerID = Overrides[OI];
01918 
01919     // If this macro is not yet visible, remove it from the hidden names list.
01920     // It won't be there if we're in the middle of making the owner visible.
01921     Module *Owner = getSubmodule(OwnerID);
01922     auto HiddenIt = HiddenNamesMap.find(Owner);
01923     if (HiddenIt != HiddenNamesMap.end()) {
01924       HiddenNames &Hidden = HiddenIt->second;
01925       HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
01926       if (HI != Hidden.HiddenMacros.end()) {
01927         // Register the macro now so we don't lose it when we re-export.
01928         PP.appendMacroDirective(II, HI->second->import(PP, ImportLoc));
01929 
01930         auto SubOverrides = HI->second->getOverriddenSubmodules();
01931         Hidden.HiddenMacros.erase(HI);
01932         removeOverriddenMacros(II, ImportLoc, Ambig, SubOverrides);
01933       }
01934     }
01935 
01936     // If this macro is already in our list of conflicts, remove it from there.
01937     Ambig.erase(
01938         std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
01939           return MD->getInfo()->getOwningModuleID() == OwnerID;
01940         }),
01941         Ambig.end());
01942   }
01943 }
01944 
01945 ASTReader::AmbiguousMacros *
01946 ASTReader::removeOverriddenMacros(IdentifierInfo *II,
01947                                   SourceLocation ImportLoc,
01948                                   ArrayRef<SubmoduleID> Overrides) {
01949   MacroDirective *Prev = PP.getMacroDirective(II);
01950   if (!Prev && Overrides.empty())
01951     return nullptr;
01952 
01953   DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective()
01954                                     : nullptr;
01955   if (PrevDef && PrevDef->isAmbiguous()) {
01956     // We had a prior ambiguity. Check whether we resolve it (or make it worse).
01957     AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
01958     Ambig.push_back(PrevDef);
01959 
01960     removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
01961 
01962     if (!Ambig.empty())
01963       return &Ambig;
01964 
01965     AmbiguousMacroDefs.erase(II);
01966   } else {
01967     // There's no ambiguity yet. Maybe we're introducing one.
01968     AmbiguousMacros Ambig;
01969     if (PrevDef)
01970       Ambig.push_back(PrevDef);
01971 
01972     removeOverriddenMacros(II, ImportLoc, Ambig, Overrides);
01973 
01974     if (!Ambig.empty()) {
01975       AmbiguousMacros &Result = AmbiguousMacroDefs[II];
01976       std::swap(Result, Ambig);
01977       return &Result;
01978     }
01979   }
01980 
01981   // We ended up with no ambiguity.
01982   return nullptr;
01983 }
01984 
01985 void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
01986                                      Module *Owner) {
01987   assert(II && Owner);
01988 
01989   SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
01990   if (ImportLoc.isInvalid()) {
01991     // FIXME: If we made macros from this module visible but didn't provide a
01992     // source location for the import, we don't have a location for the macro.
01993     // Use the location at which the containing module file was first imported
01994     // for now.
01995     ImportLoc = MMI->F->DirectImportLoc;
01996     assert(ImportLoc.isValid() && "no import location for a visible macro?");
01997   }
01998 
01999   AmbiguousMacros *Prev =
02000       removeOverriddenMacros(II, ImportLoc, MMI->getOverriddenSubmodules());
02001 
02002   // Create a synthetic macro definition corresponding to the import (or null
02003   // if this was an undefinition of the macro).
02004   MacroDirective *Imported = MMI->import(PP, ImportLoc);
02005   DefMacroDirective *MD = dyn_cast<DefMacroDirective>(Imported);
02006 
02007   // If there's no ambiguity, just install the macro.
02008   if (!Prev) {
02009     PP.appendMacroDirective(II, Imported);
02010     return;
02011   }
02012   assert(!Prev->empty());
02013 
02014   if (!MD) {
02015     // We imported a #undef that didn't remove all prior definitions. The most
02016     // recent prior definition remains, and we install it in the place of the
02017     // imported directive, as if by a local #pragma pop_macro.
02018     MacroInfo *NewMI = Prev->back()->getInfo();
02019     Prev->pop_back();
02020     MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc);
02021 
02022     // Install our #undef first so that we don't lose track of it. We'll replace
02023     // this with whichever macro definition ends up winning.
02024     PP.appendMacroDirective(II, Imported);
02025   }
02026 
02027   // We're introducing a macro definition that creates or adds to an ambiguity.
02028   // We can resolve that ambiguity if this macro is token-for-token identical to
02029   // all of the existing definitions.
02030   MacroInfo *NewMI = MD->getInfo();
02031   assert(NewMI && "macro definition with no MacroInfo?");
02032   while (!Prev->empty()) {
02033     MacroInfo *PrevMI = Prev->back()->getInfo();
02034     assert(PrevMI && "macro definition with no MacroInfo?");
02035 
02036     // Before marking the macros as ambiguous, check if this is a case where
02037     // both macros are in system headers. If so, we trust that the system
02038     // did not get it wrong. This also handles cases where Clang's own
02039     // headers have a different spelling of certain system macros:
02040     //   #define LONG_MAX __LONG_MAX__ (clang's limits.h)
02041     //   #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
02042     //
02043     // FIXME: Remove the defined-in-system-headers check. clang's limits.h
02044     // overrides the system limits.h's macros, so there's no conflict here.
02045     if (NewMI != PrevMI &&
02046         !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
02047         !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
02048       break;
02049 
02050     // The previous definition is the same as this one (or both are defined in
02051     // system modules so we can assume they're equivalent); we don't need to
02052     // track it any more.
02053     Prev->pop_back();
02054   }
02055 
02056   if (!Prev->empty())
02057     MD->setAmbiguous(true);
02058 
02059   PP.appendMacroDirective(II, MD);
02060 }
02061 
02062 ASTReader::InputFileInfo
02063 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
02064   // Go find this input file.
02065   BitstreamCursor &Cursor = F.InputFilesCursor;
02066   SavedStreamPosition SavedPosition(Cursor);
02067   Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
02068 
02069   unsigned Code = Cursor.ReadCode();
02070   RecordData Record;
02071   StringRef Blob;
02072 
02073   unsigned Result = Cursor.readRecord(Code, Record, &Blob);
02074   assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
02075          "invalid record type for input file");
02076   (void)Result;
02077 
02078   std::string Filename;
02079   off_t StoredSize;
02080   time_t StoredTime;
02081   bool Overridden;
02082   
02083   assert(Record[0] == ID && "Bogus stored ID or offset");
02084   StoredSize = static_cast<off_t>(Record[1]);
02085   StoredTime = static_cast<time_t>(Record[2]);
02086   Overridden = static_cast<bool>(Record[3]);
02087   Filename = Blob;
02088   MaybeAddSystemRootToFilename(F, Filename);
02089   
02090   InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
02091   return R;
02092 }
02093 
02094 std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
02095   return readInputFileInfo(F, ID).Filename;
02096 }
02097 
02098 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
02099   // If this ID is bogus, just return an empty input file.
02100   if (ID == 0 || ID > F.InputFilesLoaded.size())
02101     return InputFile();
02102 
02103   // If we've already loaded this input file, return it.
02104   if (F.InputFilesLoaded[ID-1].getFile())
02105     return F.InputFilesLoaded[ID-1];
02106 
02107   if (F.InputFilesLoaded[ID-1].isNotFound())
02108     return InputFile();
02109 
02110   // Go find this input file.
02111   BitstreamCursor &Cursor = F.InputFilesCursor;
02112   SavedStreamPosition SavedPosition(Cursor);
02113   Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
02114   
02115   InputFileInfo FI = readInputFileInfo(F, ID);
02116   off_t StoredSize = FI.StoredSize;
02117   time_t StoredTime = FI.StoredTime;
02118   bool Overridden = FI.Overridden;
02119   StringRef Filename = FI.Filename;
02120 
02121   const FileEntry *File
02122     = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
02123                 : FileMgr.getFile(Filename, /*OpenFile=*/false);
02124 
02125   // If we didn't find the file, resolve it relative to the
02126   // original directory from which this AST file was created.
02127   if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
02128       F.OriginalDir != CurrentDir) {
02129     std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
02130                                                             F.OriginalDir,
02131                                                             CurrentDir);
02132     if (!Resolved.empty())
02133       File = FileMgr.getFile(Resolved);
02134   }
02135 
02136   // For an overridden file, create a virtual file with the stored
02137   // size/timestamp.
02138   if (Overridden && File == nullptr) {
02139     File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
02140   }
02141 
02142   if (File == nullptr) {
02143     if (Complain) {
02144       std::string ErrorStr = "could not find file '";
02145       ErrorStr += Filename;
02146       ErrorStr += "' referenced by AST file";
02147       Error(ErrorStr.c_str());
02148     }
02149     // Record that we didn't find the file.
02150     F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
02151     return InputFile();
02152   }
02153 
02154   // Check if there was a request to override the contents of the file
02155   // that was part of the precompiled header. Overridding such a file
02156   // can lead to problems when lexing using the source locations from the
02157   // PCH.
02158   SourceManager &SM = getSourceManager();
02159   if (!Overridden && SM.isFileOverridden(File)) {
02160     if (Complain)
02161       Error(diag::err_fe_pch_file_overridden, Filename);
02162     // After emitting the diagnostic, recover by disabling the override so
02163     // that the original file will be used.
02164     SM.disableFileContentsOverride(File);
02165     // The FileEntry is a virtual file entry with the size of the contents
02166     // that would override the original contents. Set it to the original's
02167     // size/time.
02168     FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
02169                             StoredSize, StoredTime);
02170   }
02171 
02172   bool IsOutOfDate = false;
02173 
02174   // For an overridden file, there is nothing to validate.
02175   if (!Overridden && //
02176       (StoredSize != File->getSize() ||
02177 #if defined(LLVM_ON_WIN32)
02178        false
02179 #else
02180        // In our regression testing, the Windows file system seems to
02181        // have inconsistent modification times that sometimes
02182        // erroneously trigger this error-handling path.
02183        //
02184        // This also happens in networked file systems, so disable this
02185        // check if validation is disabled or if we have an explicitly
02186        // built PCM file.
02187        //
02188        // FIXME: Should we also do this for PCH files? They could also
02189        // reasonably get shared across a network during a distributed build.
02190        (StoredTime != File->getModificationTime() && !DisableValidation &&
02191         F.Kind != MK_ExplicitModule)
02192 #endif
02193        )) {
02194     if (Complain) {
02195       // Build a list of the PCH imports that got us here (in reverse).
02196       SmallVector<ModuleFile *, 4> ImportStack(1, &F);
02197       while (ImportStack.back()->ImportedBy.size() > 0)
02198         ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
02199 
02200       // The top-level PCH is stale.
02201       StringRef TopLevelPCHName(ImportStack.back()->FileName);
02202       Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
02203 
02204       // Print the import stack.
02205       if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
02206         Diag(diag::note_pch_required_by)
02207           << Filename << ImportStack[0]->FileName;
02208         for (unsigned I = 1; I < ImportStack.size(); ++I)
02209           Diag(diag::note_pch_required_by)
02210             << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
02211       }
02212 
02213       if (!Diags.isDiagnosticInFlight())
02214         Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
02215     }
02216 
02217     IsOutOfDate = true;
02218   }
02219 
02220   InputFile IF = InputFile(File, Overridden, IsOutOfDate);
02221 
02222   // Note that we've loaded this input file.
02223   F.InputFilesLoaded[ID-1] = IF;
02224   return IF;
02225 }
02226 
02227 const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
02228   ModuleFile &M = ModuleMgr.getPrimaryModule();
02229   std::string Filename = filenameStrRef;
02230   MaybeAddSystemRootToFilename(M, Filename);
02231   const FileEntry *File = FileMgr.getFile(Filename);
02232   if (File == nullptr && !M.OriginalDir.empty() && !CurrentDir.empty() &&
02233       M.OriginalDir != CurrentDir) {
02234     std::string resolved = resolveFileRelativeToOriginalDir(Filename,
02235                                                             M.OriginalDir,
02236                                                             CurrentDir);
02237     if (!resolved.empty())
02238       File = FileMgr.getFile(resolved);
02239   }
02240 
02241   return File;
02242 }
02243 
02244 /// \brief If we are loading a relocatable PCH file, and the filename is
02245 /// not an absolute path, add the system root to the beginning of the file
02246 /// name.
02247 void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
02248                                              std::string &Filename) {
02249   // If this is not a relocatable PCH file, there's nothing to do.
02250   if (!M.RelocatablePCH)
02251     return;
02252 
02253   if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
02254     return;
02255 
02256   if (isysroot.empty()) {
02257     // If no system root was given, default to '/'
02258     Filename.insert(Filename.begin(), '/');
02259     return;
02260   }
02261 
02262   unsigned Length = isysroot.size();
02263   if (isysroot[Length - 1] != '/')
02264     Filename.insert(Filename.begin(), '/');
02265 
02266   Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
02267 }
02268 
02269 ASTReader::ASTReadResult
02270 ASTReader::ReadControlBlock(ModuleFile &F,
02271                             SmallVectorImpl<ImportedModule> &Loaded,
02272                             const ModuleFile *ImportedBy,
02273                             unsigned ClientLoadCapabilities) {
02274   BitstreamCursor &Stream = F.Stream;
02275 
02276   if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
02277     Error("malformed block record in AST file");
02278     return Failure;
02279   }
02280 
02281   // Should we allow the configuration of the module file to differ from the
02282   // configuration of the current translation unit in a compatible way?
02283   //
02284   // FIXME: Allow this for files explicitly specified with -include-pch too.
02285   bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
02286 
02287   // Read all of the records and blocks in the control block.
02288   RecordData Record;
02289   unsigned NumInputs = 0;
02290   unsigned NumUserInputs = 0;
02291   while (1) {
02292     llvm::BitstreamEntry Entry = Stream.advance();
02293     
02294     switch (Entry.Kind) {
02295     case llvm::BitstreamEntry::Error:
02296       Error("malformed block record in AST file");
02297       return Failure;
02298     case llvm::BitstreamEntry::EndBlock: {
02299       // Validate input files.
02300       const HeaderSearchOptions &HSOpts =
02301           PP.getHeaderSearchInfo().getHeaderSearchOpts();
02302 
02303       // All user input files reside at the index range [0, NumUserInputs), and
02304       // system input files reside at [NumUserInputs, NumInputs).
02305       if (!DisableValidation) {
02306         bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
02307 
02308         // If we are reading a module, we will create a verification timestamp,
02309         // so we verify all input files.  Otherwise, verify only user input
02310         // files.
02311 
02312         unsigned N = NumUserInputs;
02313         if (ValidateSystemInputs ||
02314             (HSOpts.ModulesValidateOncePerBuildSession &&
02315              F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
02316              F.Kind == MK_ImplicitModule))
02317           N = NumInputs;
02318 
02319         for (unsigned I = 0; I < N; ++I) {
02320           InputFile IF = getInputFile(F, I+1, Complain);
02321           if (!IF.getFile() || IF.isOutOfDate())
02322             return OutOfDate;
02323         }
02324       }
02325 
02326       if (Listener)
02327         Listener->visitModuleFile(F.FileName);
02328 
02329       if (Listener && Listener->needsInputFileVisitation()) {
02330         unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
02331                                                                 : NumUserInputs;
02332         for (unsigned I = 0; I < N; ++I) {
02333           bool IsSystem = I >= NumUserInputs;
02334           InputFileInfo FI = readInputFileInfo(F, I+1);
02335           Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
02336         }
02337       }
02338 
02339       return Success;
02340     }
02341 
02342     case llvm::BitstreamEntry::SubBlock:
02343       switch (Entry.ID) {
02344       case INPUT_FILES_BLOCK_ID:
02345         F.InputFilesCursor = Stream;
02346         if (Stream.SkipBlock() || // Skip with the main cursor
02347             // Read the abbreviations
02348             ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
02349           Error("malformed block record in AST file");
02350           return Failure;
02351         }
02352         continue;
02353           
02354       default:
02355         if (Stream.SkipBlock()) {
02356           Error("malformed block record in AST file");
02357           return Failure;
02358         }
02359         continue;
02360       }
02361       
02362     case llvm::BitstreamEntry::Record:
02363       // The interesting case.
02364       break;
02365     }
02366 
02367     // Read and process a record.
02368     Record.clear();
02369     StringRef Blob;
02370     switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
02371     case METADATA: {
02372       if (Record[0] != VERSION_MAJOR && !DisableValidation) {
02373         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
02374           Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
02375                                         : diag::err_pch_version_too_new);
02376         return VersionMismatch;
02377       }
02378 
02379       bool hasErrors = Record[5];
02380       if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
02381         Diag(diag::err_pch_with_compiler_errors);
02382         return HadErrors;
02383       }
02384 
02385       F.RelocatablePCH = Record[4];
02386 
02387       const std::string &CurBranch = getClangFullRepositoryVersion();
02388       StringRef ASTBranch = Blob;
02389       if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
02390         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
02391           Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
02392         return VersionMismatch;
02393       }
02394       break;
02395     }
02396 
02397     case SIGNATURE:
02398       assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
02399       F.Signature = Record[0];
02400       break;
02401 
02402     case IMPORTS: {
02403       // Load each of the imported PCH files. 
02404       unsigned Idx = 0, N = Record.size();
02405       while (Idx < N) {
02406         // Read information about the AST file.
02407         ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
02408         // The import location will be the local one for now; we will adjust
02409         // all import locations of module imports after the global source
02410         // location info are setup.
02411         SourceLocation ImportLoc =
02412             SourceLocation::getFromRawEncoding(Record[Idx++]);
02413         off_t StoredSize = (off_t)Record[Idx++];
02414         time_t StoredModTime = (time_t)Record[Idx++];
02415         ASTFileSignature StoredSignature = Record[Idx++];
02416         unsigned Length = Record[Idx++];
02417         SmallString<128> ImportedFile(Record.begin() + Idx,
02418                                       Record.begin() + Idx + Length);
02419         Idx += Length;
02420 
02421         // Load the AST file.
02422         switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
02423                            StoredSize, StoredModTime, StoredSignature,
02424                            ClientLoadCapabilities)) {
02425         case Failure: return Failure;
02426           // If we have to ignore the dependency, we'll have to ignore this too.
02427         case Missing:
02428         case OutOfDate: return OutOfDate;
02429         case VersionMismatch: return VersionMismatch;
02430         case ConfigurationMismatch: return ConfigurationMismatch;
02431         case HadErrors: return HadErrors;
02432         case Success: break;
02433         }
02434       }
02435       break;
02436     }
02437 
02438     case LANGUAGE_OPTIONS: {
02439       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
02440       // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
02441       if (Listener && &F == *ModuleMgr.begin() &&
02442           ParseLanguageOptions(Record, Complain, *Listener,
02443                                AllowCompatibleConfigurationMismatch) &&
02444           !DisableValidation && !AllowConfigurationMismatch)
02445         return ConfigurationMismatch;
02446       break;
02447     }
02448 
02449     case TARGET_OPTIONS: {
02450       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
02451       if (Listener && &F == *ModuleMgr.begin() &&
02452           ParseTargetOptions(Record, Complain, *Listener) &&
02453           !DisableValidation && !AllowConfigurationMismatch)
02454         return ConfigurationMismatch;
02455       break;
02456     }
02457 
02458     case DIAGNOSTIC_OPTIONS: {
02459       bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
02460       if (Listener && &F == *ModuleMgr.begin() &&
02461           !AllowCompatibleConfigurationMismatch &&
02462           ParseDiagnosticOptions(Record, Complain, *Listener) &&
02463           !DisableValidation)
02464         return OutOfDate;
02465       break;
02466     }
02467 
02468     case FILE_SYSTEM_OPTIONS: {
02469       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
02470       if (Listener && &F == *ModuleMgr.begin() &&
02471           !AllowCompatibleConfigurationMismatch &&
02472           ParseFileSystemOptions(Record, Complain, *Listener) &&
02473           !DisableValidation && !AllowConfigurationMismatch)
02474         return ConfigurationMismatch;
02475       break;
02476     }
02477 
02478     case HEADER_SEARCH_OPTIONS: {
02479       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
02480       if (Listener && &F == *ModuleMgr.begin() &&
02481           !AllowCompatibleConfigurationMismatch &&
02482           ParseHeaderSearchOptions(Record, Complain, *Listener) &&
02483           !DisableValidation && !AllowConfigurationMismatch)
02484         return ConfigurationMismatch;
02485       break;
02486     }
02487 
02488     case PREPROCESSOR_OPTIONS: {
02489       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
02490       if (Listener && &F == *ModuleMgr.begin() &&
02491           !AllowCompatibleConfigurationMismatch &&
02492           ParsePreprocessorOptions(Record, Complain, *Listener,
02493                                    SuggestedPredefines) &&
02494           !DisableValidation && !AllowConfigurationMismatch)
02495         return ConfigurationMismatch;
02496       break;
02497     }
02498 
02499     case ORIGINAL_FILE:
02500       F.OriginalSourceFileID = FileID::get(Record[0]);
02501       F.ActualOriginalSourceFileName = Blob;
02502       F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
02503       MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
02504       break;
02505 
02506     case ORIGINAL_FILE_ID:
02507       F.OriginalSourceFileID = FileID::get(Record[0]);
02508       break;
02509 
02510     case ORIGINAL_PCH_DIR:
02511       F.OriginalDir = Blob;
02512       break;
02513 
02514     case MODULE_NAME:
02515       F.ModuleName = Blob;
02516       if (Listener)
02517         Listener->ReadModuleName(F.ModuleName);
02518       break;
02519 
02520     case MODULE_MAP_FILE:
02521       if (ASTReadResult Result =
02522               ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
02523         return Result;
02524       break;
02525 
02526     case INPUT_FILE_OFFSETS:
02527       NumInputs = Record[0];
02528       NumUserInputs = Record[1];
02529       F.InputFileOffsets = (const uint32_t *)Blob.data();
02530       F.InputFilesLoaded.resize(NumInputs);
02531       break;
02532     }
02533   }
02534 }
02535 
02536 ASTReader::ASTReadResult
02537 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
02538   BitstreamCursor &Stream = F.Stream;
02539 
02540   if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
02541     Error("malformed block record in AST file");
02542     return Failure;
02543   }
02544 
02545   // Read all of the records and blocks for the AST file.
02546   RecordData Record;
02547   while (1) {
02548     llvm::BitstreamEntry Entry = Stream.advance();
02549     
02550     switch (Entry.Kind) {
02551     case llvm::BitstreamEntry::Error:
02552       Error("error at end of module block in AST file");
02553       return Failure;
02554     case llvm::BitstreamEntry::EndBlock: {
02555       // Outside of C++, we do not store a lookup map for the translation unit.
02556       // Instead, mark it as needing a lookup map to be built if this module
02557       // contains any declarations lexically within it (which it always does!).
02558       // This usually has no cost, since we very rarely need the lookup map for
02559       // the translation unit outside C++.
02560       DeclContext *DC = Context.getTranslationUnitDecl();
02561       if (DC->hasExternalLexicalStorage() &&
02562           !getContext().getLangOpts().CPlusPlus)
02563         DC->setMustBuildLookupTable();
02564       
02565       return Success;
02566     }
02567     case llvm::BitstreamEntry::SubBlock:
02568       switch (Entry.ID) {
02569       case DECLTYPES_BLOCK_ID:
02570         // We lazily load the decls block, but we want to set up the
02571         // DeclsCursor cursor to point into it.  Clone our current bitcode
02572         // cursor to it, enter the block and read the abbrevs in that block.
02573         // With the main cursor, we just skip over it.
02574         F.DeclsCursor = Stream;
02575         if (Stream.SkipBlock() ||  // Skip with the main cursor.
02576             // Read the abbrevs.
02577             ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
02578           Error("malformed block record in AST file");
02579           return Failure;
02580         }
02581         break;
02582 
02583       case PREPROCESSOR_BLOCK_ID:
02584         F.MacroCursor = Stream;
02585         if (!PP.getExternalSource())
02586           PP.setExternalSource(this);
02587         
02588         if (Stream.SkipBlock() ||
02589             ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
02590           Error("malformed block record in AST file");
02591           return Failure;
02592         }
02593         F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
02594         break;
02595         
02596       case PREPROCESSOR_DETAIL_BLOCK_ID:
02597         F.PreprocessorDetailCursor = Stream;
02598         if (Stream.SkipBlock() ||
02599             ReadBlockAbbrevs(F.PreprocessorDetailCursor,
02600                              PREPROCESSOR_DETAIL_BLOCK_ID)) {
02601               Error("malformed preprocessor detail record in AST file");
02602               return Failure;
02603             }
02604         F.PreprocessorDetailStartOffset
02605         = F.PreprocessorDetailCursor.GetCurrentBitNo();
02606         
02607         if (!PP.getPreprocessingRecord())
02608           PP.createPreprocessingRecord();
02609         if (!PP.getPreprocessingRecord()->getExternalSource())
02610           PP.getPreprocessingRecord()->SetExternalSource(*this);
02611         break;
02612         
02613       case SOURCE_MANAGER_BLOCK_ID:
02614         if (ReadSourceManagerBlock(F))
02615           return Failure;
02616         break;
02617         
02618       case SUBMODULE_BLOCK_ID:
02619         if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
02620           return Result;
02621         break;
02622         
02623       case COMMENTS_BLOCK_ID: {
02624         BitstreamCursor C = Stream;
02625         if (Stream.SkipBlock() ||
02626             ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
02627           Error("malformed comments block in AST file");
02628           return Failure;
02629         }
02630         CommentsCursors.push_back(std::make_pair(C, &F));
02631         break;
02632       }
02633         
02634       default:
02635         if (Stream.SkipBlock()) {
02636           Error("malformed block record in AST file");
02637           return Failure;
02638         }
02639         break;
02640       }
02641       continue;
02642     
02643     case llvm::BitstreamEntry::Record:
02644       // The interesting case.
02645       break;
02646     }
02647 
02648     // Read and process a record.
02649     Record.clear();
02650     StringRef Blob;
02651     switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
02652     default:  // Default behavior: ignore.
02653       break;
02654 
02655     case TYPE_OFFSET: {
02656       if (F.LocalNumTypes != 0) {
02657         Error("duplicate TYPE_OFFSET record in AST file");
02658         return Failure;
02659       }
02660       F.TypeOffsets = (const uint32_t *)Blob.data();
02661       F.LocalNumTypes = Record[0];
02662       unsigned LocalBaseTypeIndex = Record[1];
02663       F.BaseTypeIndex = getTotalNumTypes();
02664         
02665       if (F.LocalNumTypes > 0) {
02666         // Introduce the global -> local mapping for types within this module.
02667         GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
02668         
02669         // Introduce the local -> global mapping for types within this module.
02670         F.TypeRemap.insertOrReplace(
02671           std::make_pair(LocalBaseTypeIndex, 
02672                          F.BaseTypeIndex - LocalBaseTypeIndex));
02673 
02674         TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
02675       }
02676       break;
02677     }
02678         
02679     case DECL_OFFSET: {
02680       if (F.LocalNumDecls != 0) {
02681         Error("duplicate DECL_OFFSET record in AST file");
02682         return Failure;
02683       }
02684       F.DeclOffsets = (const DeclOffset *)Blob.data();
02685       F.LocalNumDecls = Record[0];
02686       unsigned LocalBaseDeclID = Record[1];
02687       F.BaseDeclID = getTotalNumDecls();
02688         
02689       if (F.LocalNumDecls > 0) {
02690         // Introduce the global -> local mapping for declarations within this 
02691         // module.
02692         GlobalDeclMap.insert(
02693           std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
02694         
02695         // Introduce the local -> global mapping for declarations within this
02696         // module.
02697         F.DeclRemap.insertOrReplace(
02698           std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
02699         
02700         // Introduce the global -> local mapping for declarations within this
02701         // module.
02702         F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
02703 
02704         DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
02705       }
02706       break;
02707     }
02708         
02709     case TU_UPDATE_LEXICAL: {
02710       DeclContext *TU = Context.getTranslationUnitDecl();
02711       DeclContextInfo &Info = F.DeclContextInfos[TU];
02712       Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
02713       Info.NumLexicalDecls 
02714         = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
02715       TU->setHasExternalLexicalStorage(true);
02716       break;
02717     }
02718 
02719     case UPDATE_VISIBLE: {
02720       unsigned Idx = 0;
02721       serialization::DeclID ID = ReadDeclID(F, Record, Idx);
02722       ASTDeclContextNameLookupTable *Table =
02723           ASTDeclContextNameLookupTable::Create(
02724               (const unsigned char *)Blob.data() + Record[Idx++],
02725               (const unsigned char *)Blob.data() + sizeof(uint32_t),
02726               (const unsigned char *)Blob.data(),
02727               ASTDeclContextNameLookupTrait(*this, F));
02728       if (Decl *D = GetExistingDecl(ID)) {
02729         auto *DC = cast<DeclContext>(D);
02730         DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
02731         auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
02732         delete LookupTable;
02733         LookupTable = Table;
02734       } else
02735         PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
02736       break;
02737     }
02738 
02739     case IDENTIFIER_TABLE:
02740       F.IdentifierTableData = Blob.data();
02741       if (Record[0]) {
02742         F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
02743             (const unsigned char *)F.IdentifierTableData + Record[0],
02744             (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
02745             (const unsigned char *)F.IdentifierTableData,
02746             ASTIdentifierLookupTrait(*this, F));
02747         
02748         PP.getIdentifierTable().setExternalIdentifierLookup(this);
02749       }
02750       break;
02751 
02752     case IDENTIFIER_OFFSET: {
02753       if (F.LocalNumIdentifiers != 0) {
02754         Error("duplicate IDENTIFIER_OFFSET record in AST file");
02755         return Failure;
02756       }
02757       F.IdentifierOffsets = (const uint32_t *)Blob.data();
02758       F.LocalNumIdentifiers = Record[0];
02759       unsigned LocalBaseIdentifierID = Record[1];
02760       F.BaseIdentifierID = getTotalNumIdentifiers();
02761         
02762       if (F.LocalNumIdentifiers > 0) {
02763         // Introduce the global -> local mapping for identifiers within this
02764         // module.
02765         GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1, 
02766                                                   &F));
02767         
02768         // Introduce the local -> global mapping for identifiers within this
02769         // module.
02770         F.IdentifierRemap.insertOrReplace(
02771           std::make_pair(LocalBaseIdentifierID,
02772                          F.BaseIdentifierID - LocalBaseIdentifierID));
02773 
02774         IdentifiersLoaded.resize(IdentifiersLoaded.size()
02775                                  + F.LocalNumIdentifiers);
02776       }
02777       break;
02778     }
02779 
02780     case EAGERLY_DESERIALIZED_DECLS:
02781       for (unsigned I = 0, N = Record.size(); I != N; ++I)
02782         EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
02783       break;
02784 
02785     case SPECIAL_TYPES:
02786       if (SpecialTypes.empty()) {
02787         for (unsigned I = 0, N = Record.size(); I != N; ++I)
02788           SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
02789         break;
02790       }
02791 
02792       if (SpecialTypes.size() != Record.size()) {
02793         Error("invalid special-types record");
02794         return Failure;
02795       }
02796 
02797       for (unsigned I = 0, N = Record.size(); I != N; ++I) {
02798         serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
02799         if (!SpecialTypes[I])
02800           SpecialTypes[I] = ID;
02801         // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
02802         // merge step?
02803       }
02804       break;
02805 
02806     case STATISTICS:
02807       TotalNumStatements += Record[0];
02808       TotalNumMacros += Record[1];
02809       TotalLexicalDeclContexts += Record[2];
02810       TotalVisibleDeclContexts += Record[3];
02811       break;
02812 
02813     case UNUSED_FILESCOPED_DECLS:
02814       for (unsigned I = 0, N = Record.size(); I != N; ++I)
02815         UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
02816       break;
02817 
02818     case DELEGATING_CTORS:
02819       for (unsigned I = 0, N = Record.size(); I != N; ++I)
02820         DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
02821       break;
02822 
02823     case WEAK_UNDECLARED_IDENTIFIERS:
02824       if (Record.size() % 4 != 0) {
02825         Error("invalid weak identifiers record");
02826         return Failure;
02827       }
02828         
02829       // FIXME: Ignore weak undeclared identifiers from non-original PCH 
02830       // files. This isn't the way to do it :)
02831       WeakUndeclaredIdentifiers.clear();
02832         
02833       // Translate the weak, undeclared identifiers into global IDs.
02834       for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
02835         WeakUndeclaredIdentifiers.push_back(
02836           getGlobalIdentifierID(F, Record[I++]));
02837         WeakUndeclaredIdentifiers.push_back(
02838           getGlobalIdentifierID(F, Record[I++]));
02839         WeakUndeclaredIdentifiers.push_back(
02840           ReadSourceLocation(F, Record, I).getRawEncoding());
02841         WeakUndeclaredIdentifiers.push_back(Record[I++]);
02842       }
02843       break;
02844 
02845     case LOCALLY_SCOPED_EXTERN_C_DECLS:
02846       for (unsigned I = 0, N = Record.size(); I != N; ++I)
02847         LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
02848       break;
02849 
02850     case SELECTOR_OFFSETS: {
02851       F.SelectorOffsets = (const uint32_t *)Blob.data();
02852       F.LocalNumSelectors = Record[0];
02853       unsigned LocalBaseSelectorID = Record[1];
02854       F.BaseSelectorID = getTotalNumSelectors();
02855         
02856       if (F.LocalNumSelectors > 0) {
02857         // Introduce the global -> local mapping for selectors within this 
02858         // module.
02859         GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
02860         
02861         // Introduce the local -> global mapping for selectors within this 
02862         // module.
02863         F.SelectorRemap.insertOrReplace(
02864           std::make_pair(LocalBaseSelectorID,
02865                          F.BaseSelectorID - LocalBaseSelectorID));
02866 
02867         SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
02868       }
02869       break;
02870     }
02871         
02872     case METHOD_POOL:
02873       F.SelectorLookupTableData = (const unsigned char *)Blob.data();
02874       if (Record[0])
02875         F.SelectorLookupTable
02876           = ASTSelectorLookupTable::Create(
02877                         F.SelectorLookupTableData + Record[0],
02878                         F.SelectorLookupTableData,
02879                         ASTSelectorLookupTrait(*this, F));
02880       TotalNumMethodPoolEntries += Record[1];
02881       break;
02882 
02883     case REFERENCED_SELECTOR_POOL:
02884       if (!Record.empty()) {
02885         for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
02886           ReferencedSelectorsData.push_back(getGlobalSelectorID(F, 
02887                                                                 Record[Idx++]));
02888           ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
02889                                               getRawEncoding());
02890         }
02891       }
02892       break;
02893 
02894     case PP_COUNTER_VALUE:
02895       if (!Record.empty() && Listener)
02896         Listener->ReadCounter(F, Record[0]);
02897       break;
02898       
02899     case FILE_SORTED_DECLS:
02900       F.FileSortedDecls = (const DeclID *)Blob.data();
02901       F.NumFileSortedDecls = Record[0];
02902       break;
02903 
02904     case SOURCE_LOCATION_OFFSETS: {
02905       F.SLocEntryOffsets = (const uint32_t *)Blob.data();
02906       F.LocalNumSLocEntries = Record[0];
02907       unsigned SLocSpaceSize = Record[1];
02908       std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
02909           SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
02910                                               SLocSpaceSize);
02911       // Make our entry in the range map. BaseID is negative and growing, so
02912       // we invert it. Because we invert it, though, we need the other end of
02913       // the range.
02914       unsigned RangeStart =
02915           unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
02916       GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
02917       F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
02918 
02919       // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
02920       assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
02921       GlobalSLocOffsetMap.insert(
02922           std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
02923                            - SLocSpaceSize,&F));
02924 
02925       // Initialize the remapping table.
02926       // Invalid stays invalid.
02927       F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
02928       // This module. Base was 2 when being compiled.
02929       F.SLocRemap.insertOrReplace(std::make_pair(2U,
02930                                   static_cast<int>(F.SLocEntryBaseOffset - 2)));
02931       
02932       TotalNumSLocEntries += F.LocalNumSLocEntries;
02933       break;
02934     }
02935 
02936     case MODULE_OFFSET_MAP: {
02937       // Additional remapping information.
02938       const unsigned char *Data = (const unsigned char*)Blob.data();
02939       const unsigned char *DataEnd = Data + Blob.size();
02940 
02941       // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
02942       if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
02943         F.SLocRemap.insert(std::make_pair(0U, 0));
02944         F.SLocRemap.insert(std::make_pair(2U, 1));
02945       }
02946 
02947       // Continuous range maps we may be updating in our module.
02948       typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
02949           RemapBuilder;
02950       RemapBuilder SLocRemap(F.SLocRemap);
02951       RemapBuilder IdentifierRemap(F.IdentifierRemap);
02952       RemapBuilder MacroRemap(F.MacroRemap);
02953       RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
02954       RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
02955       RemapBuilder SelectorRemap(F.SelectorRemap);
02956       RemapBuilder DeclRemap(F.DeclRemap);
02957       RemapBuilder TypeRemap(F.TypeRemap);
02958 
02959       while(Data < DataEnd) {
02960         using namespace llvm::support;
02961         uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
02962         StringRef Name = StringRef((const char*)Data, Len);
02963         Data += Len;
02964         ModuleFile *OM = ModuleMgr.lookup(Name);
02965         if (!OM) {
02966           Error("SourceLocation remap refers to unknown module");
02967           return Failure;
02968         }
02969 
02970         uint32_t SLocOffset =
02971             endian::readNext<uint32_t, little, unaligned>(Data);
02972         uint32_t IdentifierIDOffset =
02973             endian::readNext<uint32_t, little, unaligned>(Data);
02974         uint32_t MacroIDOffset =
02975             endian::readNext<uint32_t, little, unaligned>(Data);
02976         uint32_t PreprocessedEntityIDOffset =
02977             endian::readNext<uint32_t, little, unaligned>(Data);
02978         uint32_t SubmoduleIDOffset =
02979             endian::readNext<uint32_t, little, unaligned>(Data);
02980         uint32_t SelectorIDOffset =
02981             endian::readNext<uint32_t, little, unaligned>(Data);
02982         uint32_t DeclIDOffset =
02983             endian::readNext<uint32_t, little, unaligned>(Data);
02984         uint32_t TypeIndexOffset =
02985             endian::readNext<uint32_t, little, unaligned>(Data);
02986 
02987         uint32_t None = std::numeric_limits<uint32_t>::max();
02988 
02989         auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
02990                              RemapBuilder &Remap) {
02991           if (Offset != None)
02992             Remap.insert(std::make_pair(Offset,
02993                                         static_cast<int>(BaseOffset - Offset)));
02994         };
02995         mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
02996         mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
02997         mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
02998         mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
02999                   PreprocessedEntityRemap);
03000         mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
03001         mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
03002         mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
03003         mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
03004 
03005         // Global -> local mappings.
03006         F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
03007       }
03008       break;
03009     }
03010 
03011     case SOURCE_MANAGER_LINE_TABLE:
03012       if (ParseLineTable(F, Record))
03013         return Failure;
03014       break;
03015 
03016     case SOURCE_LOCATION_PRELOADS: {
03017       // Need to transform from the local view (1-based IDs) to the global view,
03018       // which is based off F.SLocEntryBaseID.
03019       if (!F.PreloadSLocEntries.empty()) {
03020         Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
03021         return Failure;
03022       }
03023       
03024       F.PreloadSLocEntries.swap(Record);
03025       break;
03026     }
03027 
03028     case EXT_VECTOR_DECLS:
03029       for (unsigned I = 0, N = Record.size(); I != N; ++I)
03030         ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
03031       break;
03032 
03033     case VTABLE_USES:
03034       if (Record.size() % 3 != 0) {
03035         Error("Invalid VTABLE_USES record");
03036         return Failure;
03037       }
03038         
03039       // Later tables overwrite earlier ones.
03040       // FIXME: Modules will have some trouble with this. This is clearly not
03041       // the right way to do this.
03042       VTableUses.clear();
03043         
03044       for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
03045         VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
03046         VTableUses.push_back(
03047           ReadSourceLocation(F, Record, Idx).getRawEncoding());
03048         VTableUses.push_back(Record[Idx++]);
03049       }
03050       break;
03051 
03052     case DYNAMIC_CLASSES:
03053       for (unsigned I = 0, N = Record.size(); I != N; ++I)
03054         DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
03055       break;
03056 
03057     case PENDING_IMPLICIT_INSTANTIATIONS:
03058       if (PendingInstantiations.size() % 2 != 0) {
03059         Error("Invalid existing PendingInstantiations");
03060         return Failure;
03061       }
03062 
03063       if (Record.size() % 2 != 0) {
03064         Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
03065         return Failure;
03066       }
03067 
03068       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
03069         PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
03070         PendingInstantiations.push_back(
03071           ReadSourceLocation(F, Record, I).getRawEncoding());
03072       }
03073       break;
03074 
03075     case SEMA_DECL_REFS:
03076       if (Record.size() != 2) {
03077         Error("Invalid SEMA_DECL_REFS block");
03078         return Failure;
03079       }
03080       for (unsigned I = 0, N = Record.size(); I != N; ++I)
03081         SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
03082       break;
03083 
03084     case PPD_ENTITIES_OFFSETS: {
03085       F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
03086       assert(Blob.size() % sizeof(PPEntityOffset) == 0);
03087       F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
03088 
03089       unsigned LocalBasePreprocessedEntityID = Record[0];
03090       
03091       unsigned StartingID;
03092       if (!PP.getPreprocessingRecord())
03093         PP.createPreprocessingRecord();
03094       if (!PP.getPreprocessingRecord()->getExternalSource())
03095         PP.getPreprocessingRecord()->SetExternalSource(*this);
03096       StartingID 
03097         = PP.getPreprocessingRecord()
03098             ->allocateLoadedEntities(F.NumPreprocessedEntities);
03099       F.BasePreprocessedEntityID = StartingID;
03100 
03101       if (F.NumPreprocessedEntities > 0) {
03102         // Introduce the global -> local mapping for preprocessed entities in
03103         // this module.
03104         GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
03105        
03106         // Introduce the local -> global mapping for preprocessed entities in
03107         // this module.
03108         F.PreprocessedEntityRemap.insertOrReplace(
03109           std::make_pair(LocalBasePreprocessedEntityID,
03110             F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
03111       }
03112 
03113       break;
03114     }
03115         
03116     case DECL_UPDATE_OFFSETS: {
03117       if (Record.size() % 2 != 0) {
03118         Error("invalid DECL_UPDATE_OFFSETS block in AST file");
03119         return Failure;
03120       }
03121       for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
03122         GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
03123         DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
03124 
03125         // If we've already loaded the decl, perform the updates when we finish
03126         // loading this block.
03127         if (Decl *D = GetExistingDecl(ID))
03128           PendingUpdateRecords.push_back(std::make_pair(ID, D));
03129       }
03130       break;
03131     }
03132 
03133     case DECL_REPLACEMENTS: {
03134       if (Record.size() % 3 != 0) {
03135         Error("invalid DECL_REPLACEMENTS block in AST file");
03136         return Failure;
03137       }
03138       for (unsigned I = 0, N = Record.size(); I != N; I += 3)
03139         ReplacedDecls[getGlobalDeclID(F, Record[I])]
03140           = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
03141       break;
03142     }
03143 
03144     case OBJC_CATEGORIES_MAP: {
03145       if (F.LocalNumObjCCategoriesInMap != 0) {
03146         Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
03147         return Failure;
03148       }
03149       
03150       F.LocalNumObjCCategoriesInMap = Record[0];
03151       F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
03152       break;
03153     }
03154         
03155     case OBJC_CATEGORIES:
03156       F.ObjCCategories.swap(Record);
03157       break;
03158         
03159     case CXX_BASE_SPECIFIER_OFFSETS: {
03160       if (F.LocalNumCXXBaseSpecifiers != 0) {
03161         Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
03162         return Failure;
03163       }
03164       
03165       F.LocalNumCXXBaseSpecifiers = Record[0];
03166       F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
03167       NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
03168       break;
03169     }
03170 
03171     case DIAG_PRAGMA_MAPPINGS:
03172       if (F.PragmaDiagMappings.empty())
03173         F.PragmaDiagMappings.swap(Record);
03174       else
03175         F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
03176                                     Record.begin(), Record.end());
03177       break;
03178         
03179     case CUDA_SPECIAL_DECL_REFS:
03180       // Later tables overwrite earlier ones.
03181       // FIXME: Modules will have trouble with this.
03182       CUDASpecialDeclRefs.clear();
03183       for (unsigned I = 0, N = Record.size(); I != N; ++I)
03184         CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
03185       break;
03186 
03187     case HEADER_SEARCH_TABLE: {
03188       F.HeaderFileInfoTableData = Blob.data();
03189       F.LocalNumHeaderFileInfos = Record[1];
03190       if (Record[0]) {
03191         F.HeaderFileInfoTable
03192           = HeaderFileInfoLookupTable::Create(
03193                    (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
03194                    (const unsigned char *)F.HeaderFileInfoTableData,
03195                    HeaderFileInfoTrait(*this, F, 
03196                                        &PP.getHeaderSearchInfo(),
03197                                        Blob.data() + Record[2]));
03198         
03199         PP.getHeaderSearchInfo().SetExternalSource(this);
03200         if (!PP.getHeaderSearchInfo().getExternalLookup())
03201           PP.getHeaderSearchInfo().SetExternalLookup(this);
03202       }
03203       break;
03204     }
03205         
03206     case FP_PRAGMA_OPTIONS:
03207       // Later tables overwrite earlier ones.
03208       FPPragmaOptions.swap(Record);
03209       break;
03210 
03211     case OPENCL_EXTENSIONS:
03212       // Later tables overwrite earlier ones.
03213       OpenCLExtensions.swap(Record);
03214       break;
03215 
03216     case TENTATIVE_DEFINITIONS:
03217       for (unsigned I = 0, N = Record.size(); I != N; ++I)
03218         TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
03219       break;
03220         
03221     case KNOWN_NAMESPACES:
03222       for (unsigned I = 0, N = Record.size(); I != N; ++I)
03223         KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
03224       break;
03225 
03226     case UNDEFINED_BUT_USED:
03227       if (UndefinedButUsed.size() % 2 != 0) {
03228         Error("Invalid existing UndefinedButUsed");
03229         return Failure;
03230       }
03231 
03232       if (Record.size() % 2 != 0) {
03233         Error("invalid undefined-but-used record");
03234         return Failure;
03235       }
03236       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
03237         UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
03238         UndefinedButUsed.push_back(
03239             ReadSourceLocation(F, Record, I).getRawEncoding());
03240       }
03241       break;
03242 
03243     case IMPORTED_MODULES: {
03244       if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
03245         // If we aren't loading a module (which has its own exports), make
03246         // all of the imported modules visible.
03247         // FIXME: Deal with macros-only imports.
03248         for (unsigned I = 0, N = Record.size(); I != N; /**/) {
03249           unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
03250           SourceLocation Loc = ReadSourceLocation(F, Record, I);
03251           if (GlobalID)
03252             ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
03253         }
03254       }
03255       break;
03256     }
03257 
03258     case LOCAL_REDECLARATIONS: {
03259       F.RedeclarationChains.swap(Record);
03260       break;
03261     }
03262         
03263     case LOCAL_REDECLARATIONS_MAP: {
03264       if (F.LocalNumRedeclarationsInMap != 0) {
03265         Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
03266         return Failure;
03267       }
03268       
03269       F.LocalNumRedeclarationsInMap = Record[0];
03270       F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
03271       break;
03272     }
03273         
03274     case MERGED_DECLARATIONS: {
03275       for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
03276         GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
03277         SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
03278         for (unsigned N = Record[Idx++]; N > 0; --N)
03279           Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
03280       }
03281       break;
03282     }
03283 
03284     case MACRO_OFFSET: {
03285       if (F.LocalNumMacros != 0) {
03286         Error("duplicate MACRO_OFFSET record in AST file");
03287         return Failure;
03288       }
03289       F.MacroOffsets = (const uint32_t *)Blob.data();
03290       F.LocalNumMacros = Record[0];
03291       unsigned LocalBaseMacroID = Record[1];
03292       F.BaseMacroID = getTotalNumMacros();
03293 
03294       if (F.LocalNumMacros > 0) {
03295         // Introduce the global -> local mapping for macros within this module.
03296         GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
03297 
03298         // Introduce the local -> global mapping for macros within this module.
03299         F.MacroRemap.insertOrReplace(
03300           std::make_pair(LocalBaseMacroID,
03301                          F.BaseMacroID - LocalBaseMacroID));
03302 
03303         MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
03304       }
03305       break;
03306     }
03307 
03308     case MACRO_TABLE: {
03309       // FIXME: Not used yet.
03310       break;
03311     }
03312 
03313     case LATE_PARSED_TEMPLATE: {
03314       LateParsedTemplates.append(Record.begin(), Record.end());
03315       break;
03316     }
03317 
03318     case OPTIMIZE_PRAGMA_OPTIONS:
03319       if (Record.size() != 1) {
03320         Error("invalid pragma optimize record");
03321         return Failure;
03322       }
03323       OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
03324       break;
03325 
03326     case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
03327       for (unsigned I = 0, N = Record.size(); I != N; ++I)
03328         UnusedLocalTypedefNameCandidates.push_back(
03329             getGlobalDeclID(F, Record[I]));
03330       break;
03331     }
03332   }
03333 }
03334 
03335 ASTReader::ASTReadResult
03336 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
03337                                   const ModuleFile *ImportedBy,
03338                                   unsigned ClientLoadCapabilities) {
03339   unsigned Idx = 0;
03340   F.ModuleMapPath = ReadString(Record, Idx);
03341 
03342   if (F.Kind == MK_ExplicitModule) {
03343     // For an explicitly-loaded module, we don't care whether the original
03344     // module map file exists or matches.
03345     return Success;
03346   }
03347 
03348   // Try to resolve ModuleName in the current header search context and
03349   // verify that it is found in the same module map file as we saved. If the
03350   // top-level AST file is a main file, skip this check because there is no
03351   // usable header search context.
03352   assert(!F.ModuleName.empty() &&
03353          "MODULE_NAME should come before MODULE_MAP_FILE");
03354   if (F.Kind == MK_ImplicitModule &&
03355       (*ModuleMgr.begin())->Kind != MK_MainFile) {
03356     // An implicitly-loaded module file should have its module listed in some
03357     // module map file that we've already loaded.
03358     Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
03359     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
03360     const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
03361     if (!ModMap) {
03362       assert(ImportedBy && "top-level import should be verified");
03363       if ((ClientLoadCapabilities & ARR_Missing) == 0)
03364         Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
03365                                                   << ImportedBy->FileName
03366                                                   << F.ModuleMapPath;
03367       return Missing;
03368     }
03369 
03370     assert(M->Name == F.ModuleName && "found module with different name");
03371 
03372     // Check the primary module map file.
03373     const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
03374     if (StoredModMap == nullptr || StoredModMap != ModMap) {
03375       assert(ModMap && "found module is missing module map file");
03376       assert(ImportedBy && "top-level import should be verified");
03377       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
03378         Diag(diag::err_imported_module_modmap_changed)
03379           << F.ModuleName << ImportedBy->FileName
03380           << ModMap->getName() << F.ModuleMapPath;
03381       return OutOfDate;
03382     }
03383 
03384     llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
03385     for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
03386       // FIXME: we should use input files rather than storing names.
03387       std::string Filename = ReadString(Record, Idx);
03388       const FileEntry *F =
03389           FileMgr.getFile(Filename, false, false);
03390       if (F == nullptr) {
03391         if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
03392           Error("could not find file '" + Filename +"' referenced by AST file");
03393         return OutOfDate;
03394       }
03395       AdditionalStoredMaps.insert(F);
03396     }
03397 
03398     // Check any additional module map files (e.g. module.private.modulemap)
03399     // that are not in the pcm.
03400     if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
03401       for (const FileEntry *ModMap : *AdditionalModuleMaps) {
03402         // Remove files that match
03403         // Note: SmallPtrSet::erase is really remove
03404         if (!AdditionalStoredMaps.erase(ModMap)) {
03405           if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
03406             Diag(diag::err_module_different_modmap)
03407               << F.ModuleName << /*new*/0 << ModMap->getName();
03408           return OutOfDate;
03409         }
03410       }
03411     }
03412 
03413     // Check any additional module map files that are in the pcm, but not
03414     // found in header search. Cases that match are already removed.
03415     for (const FileEntry *ModMap : AdditionalStoredMaps) {
03416       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
03417         Diag(diag::err_module_different_modmap)
03418           << F.ModuleName << /*not new*/1 << ModMap->getName();
03419       return OutOfDate;
03420     }
03421   }
03422 
03423   if (Listener)
03424     Listener->ReadModuleMapFile(F.ModuleMapPath);
03425   return Success;
03426 }
03427 
03428 
03429 /// \brief Move the given method to the back of the global list of methods.
03430 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
03431   // Find the entry for this selector in the method pool.
03432   Sema::GlobalMethodPool::iterator Known
03433     = S.MethodPool.find(Method->getSelector());
03434   if (Known == S.MethodPool.end())
03435     return;
03436 
03437   // Retrieve the appropriate method list.
03438   ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
03439                                                     : Known->second.second;
03440   bool Found = false;
03441   for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
03442     if (!Found) {
03443       if (List->Method == Method) {
03444         Found = true;
03445       } else {
03446         // Keep searching.
03447         continue;
03448       }
03449     }
03450 
03451     if (List->getNext())
03452       List->Method = List->getNext()->Method;
03453     else
03454       List->Method = Method;
03455   }
03456 }
03457 
03458 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner,
03459                                  bool FromFinalization) {
03460   // FIXME: Only do this if Owner->NameVisibility == AllVisible.
03461   for (Decl *D : Names.HiddenDecls) {
03462     bool wasHidden = D->Hidden;
03463     D->Hidden = false;
03464 
03465     if (wasHidden && SemaObj) {
03466       if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
03467         moveMethodToBackOfGlobalList(*SemaObj, Method);
03468       }
03469     }
03470   }
03471 
03472   assert((FromFinalization || Owner->NameVisibility >= Module::MacrosVisible) &&
03473          "nothing to make visible?");
03474   for (const auto &Macro : Names.HiddenMacros) {
03475     if (FromFinalization)
03476       PP.appendMacroDirective(Macro.first,
03477                               Macro.second->import(PP, SourceLocation()));
03478     else
03479       installImportedMacro(Macro.first, Macro.second, Owner);
03480   }
03481 }
03482 
03483 void ASTReader::makeModuleVisible(Module *Mod,
03484                                   Module::NameVisibilityKind NameVisibility,
03485                                   SourceLocation ImportLoc,
03486                                   bool Complain) {
03487   llvm::SmallPtrSet<Module *, 4> Visited;
03488   SmallVector<Module *, 4> Stack;
03489   Stack.push_back(Mod);
03490   while (!Stack.empty()) {
03491     Mod = Stack.pop_back_val();
03492 
03493     if (NameVisibility <= Mod->NameVisibility) {
03494       // This module already has this level of visibility (or greater), so
03495       // there is nothing more to do.
03496       continue;
03497     }
03498 
03499     if (!Mod->isAvailable()) {
03500       // Modules that aren't available cannot be made visible.
03501       continue;
03502     }
03503 
03504     // Update the module's name visibility.
03505     if (NameVisibility >= Module::MacrosVisible &&
03506         Mod->NameVisibility < Module::MacrosVisible)
03507       Mod->MacroVisibilityLoc = ImportLoc;
03508     Mod->NameVisibility = NameVisibility;
03509 
03510     // If we've already deserialized any names from this module,
03511     // mark them as visible.
03512     HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
03513     if (Hidden != HiddenNamesMap.end()) {
03514       auto HiddenNames = std::move(*Hidden);
03515       HiddenNamesMap.erase(Hidden);
03516       makeNamesVisible(HiddenNames.second, HiddenNames.first,
03517                        /*FromFinalization*/false);
03518       assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
03519              "making names visible added hidden names");
03520     }
03521 
03522     // Push any exported modules onto the stack to be marked as visible.
03523     SmallVector<Module *, 16> Exports;
03524     Mod->getExportedModules(Exports);
03525     for (SmallVectorImpl<Module *>::iterator
03526            I = Exports.begin(), E = Exports.end(); I != E; ++I) {
03527       Module *Exported = *I;
03528       if (Visited.insert(Exported))
03529         Stack.push_back(Exported);
03530     }
03531 
03532     // Detect any conflicts.
03533     if (Complain) {
03534       assert(ImportLoc.isValid() && "Missing import location");
03535       for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
03536         if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
03537           Diag(ImportLoc, diag::warn_module_conflict)
03538             << Mod->getFullModuleName()
03539             << Mod->Conflicts[I].Other->getFullModuleName()
03540             << Mod->Conflicts[I].Message;
03541           // FIXME: Need note where the other module was imported.
03542         }
03543       }
03544     }
03545   }
03546 }
03547 
03548 bool ASTReader::loadGlobalIndex() {
03549   if (GlobalIndex)
03550     return false;
03551 
03552   if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
03553       !Context.getLangOpts().Modules)
03554     return true;
03555   
03556   // Try to load the global index.
03557   TriedLoadingGlobalIndex = true;
03558   StringRef ModuleCachePath
03559     = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
03560   std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
03561     = GlobalModuleIndex::readIndex(ModuleCachePath);
03562   if (!Result.first)
03563     return true;
03564 
03565   GlobalIndex.reset(Result.first);
03566   ModuleMgr.setGlobalIndex(GlobalIndex.get());
03567   return false;
03568 }
03569 
03570 bool ASTReader::isGlobalIndexUnavailable() const {
03571   return Context.getLangOpts().Modules && UseGlobalIndex &&
03572          !hasGlobalIndex() && TriedLoadingGlobalIndex;
03573 }
03574 
03575 static void updateModuleTimestamp(ModuleFile &MF) {
03576   // Overwrite the timestamp file contents so that file's mtime changes.
03577   std::string TimestampFilename = MF.getTimestampFilename();
03578   std::error_code EC;
03579   llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
03580   if (EC)
03581     return;
03582   OS << "Timestamp file\n";
03583 }
03584 
03585 ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
03586                                             ModuleKind Type,
03587                                             SourceLocation ImportLoc,
03588                                             unsigned ClientLoadCapabilities) {
03589   llvm::SaveAndRestore<SourceLocation>
03590     SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
03591 
03592   // Defer any pending actions until we get to the end of reading the AST file.
03593   Deserializing AnASTFile(this);
03594 
03595   // Bump the generation number.
03596   unsigned PreviousGeneration = incrementGeneration(Context);
03597 
03598   unsigned NumModules = ModuleMgr.size();
03599   SmallVector<ImportedModule, 4> Loaded;
03600   switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
03601                                                 /*ImportedBy=*/nullptr, Loaded,
03602                                                 0, 0, 0,
03603                                                 ClientLoadCapabilities)) {
03604   case Failure:
03605   case Missing:
03606   case OutOfDate:
03607   case VersionMismatch:
03608   case ConfigurationMismatch:
03609   case HadErrors: {
03610     llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
03611     for (const ImportedModule &IM : Loaded)
03612       LoadedSet.insert(IM.Mod);
03613 
03614     ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
03615                             LoadedSet,
03616                             Context.getLangOpts().Modules
03617                               ? &PP.getHeaderSearchInfo().getModuleMap()
03618                               : nullptr);
03619 
03620     // If we find that any modules are unusable, the global index is going
03621     // to be out-of-date. Just remove it.
03622     GlobalIndex.reset();
03623     ModuleMgr.setGlobalIndex(nullptr);
03624     return ReadResult;
03625   }
03626   case Success:
03627     break;
03628   }
03629 
03630   // Here comes stuff that we only do once the entire chain is loaded.
03631 
03632   // Load the AST blocks of all of the modules that we loaded.
03633   for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
03634                                               MEnd = Loaded.end();
03635        M != MEnd; ++M) {
03636     ModuleFile &F = *M->Mod;
03637 
03638     // Read the AST block.
03639     if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
03640       return Result;
03641 
03642     // Once read, set the ModuleFile bit base offset and update the size in 
03643     // bits of all files we've seen.
03644     F.GlobalBitOffset = TotalModulesSizeInBits;
03645     TotalModulesSizeInBits += F.SizeInBits;
03646     GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
03647     
03648     // Preload SLocEntries.
03649     for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
03650       int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
03651       // Load it through the SourceManager and don't call ReadSLocEntry()
03652       // directly because the entry may have already been loaded in which case
03653       // calling ReadSLocEntry() directly would trigger an assertion in
03654       // SourceManager.
03655       SourceMgr.getLoadedSLocEntryByID(Index);
03656     }
03657   }
03658 
03659   // Setup the import locations and notify the module manager that we've
03660   // committed to these module files.
03661   for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
03662                                               MEnd = Loaded.end();
03663        M != MEnd; ++M) {
03664     ModuleFile &F = *M->Mod;
03665 
03666     ModuleMgr.moduleFileAccepted(&F);
03667 
03668     // Set the import location.
03669     F.DirectImportLoc = ImportLoc;
03670     if (!M->ImportedBy)
03671       F.ImportLoc = M->ImportLoc;
03672     else
03673       F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
03674                                        M->ImportLoc.getRawEncoding());
03675   }
03676 
03677   // Mark all of the identifiers in the identifier table as being out of date,
03678   // so that various accessors know to check the loaded modules when the
03679   // identifier is used.
03680   for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
03681                               IdEnd = PP.getIdentifierTable().end();
03682        Id != IdEnd; ++Id)
03683     Id->second->setOutOfDate(true);
03684   
03685   // Resolve any unresolved module exports.
03686   for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
03687     UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
03688     SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
03689     Module *ResolvedMod = getSubmodule(GlobalID);
03690 
03691     switch (Unresolved.Kind) {
03692     case UnresolvedModuleRef::Conflict:
03693       if (ResolvedMod) {
03694         Module::Conflict Conflict;
03695         Conflict.Other = ResolvedMod;
03696         Conflict.Message = Unresolved.String.str();
03697         Unresolved.Mod->Conflicts.push_back(Conflict);
03698       }
03699       continue;
03700 
03701     case UnresolvedModuleRef::Import:
03702       if (ResolvedMod)
03703         Unresolved.Mod->Imports.push_back(ResolvedMod);
03704       continue;
03705 
03706     case UnresolvedModuleRef::Export:
03707       if (ResolvedMod || Unresolved.IsWildcard)
03708         Unresolved.Mod->Exports.push_back(
03709           Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
03710       continue;
03711     }
03712   }
03713   UnresolvedModuleRefs.clear();
03714 
03715   // FIXME: How do we load the 'use'd modules? They may not be submodules.
03716   // Might be unnecessary as use declarations are only used to build the
03717   // module itself.
03718   
03719   InitializeContext();
03720 
03721   if (SemaObj)
03722     UpdateSema();
03723 
03724   if (DeserializationListener)
03725     DeserializationListener->ReaderInitialized(this);
03726 
03727   ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
03728   if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
03729     PrimaryModule.OriginalSourceFileID 
03730       = FileID::get(PrimaryModule.SLocEntryBaseID
03731                     + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
03732 
03733     // If this AST file is a precompiled preamble, then set the
03734     // preamble file ID of the source manager to the file source file
03735     // from which the preamble was built.
03736     if (Type == MK_Preamble) {
03737       SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
03738     } else if (Type == MK_MainFile) {
03739       SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
03740     }
03741   }
03742   
03743   // For any Objective-C class definitions we have already loaded, make sure
03744   // that we load any additional categories.
03745   for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
03746     loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(), 
03747                        ObjCClassesLoaded[I],
03748                        PreviousGeneration);
03749   }
03750 
03751   if (PP.getHeaderSearchInfo()
03752           .getHeaderSearchOpts()
03753           .ModulesValidateOncePerBuildSession) {
03754     // Now we are certain that the module and all modules it depends on are
03755     // up to date.  Create or update timestamp files for modules that are
03756     // located in the module cache (not for PCH files that could be anywhere
03757     // in the filesystem).
03758     for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
03759       ImportedModule &M = Loaded[I];
03760       if (M.Mod->Kind == MK_ImplicitModule) {
03761         updateModuleTimestamp(*M.Mod);
03762       }
03763     }
03764   }
03765 
03766   return Success;
03767 }
03768 
03769 static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
03770 
03771 ASTReader::ASTReadResult
03772 ASTReader::ReadASTCore(StringRef FileName,
03773                        ModuleKind Type,
03774                        SourceLocation ImportLoc,
03775                        ModuleFile *ImportedBy,
03776                        SmallVectorImpl<ImportedModule> &Loaded,
03777                        off_t ExpectedSize, time_t ExpectedModTime,
03778                        ASTFileSignature ExpectedSignature,
03779                        unsigned ClientLoadCapabilities) {
03780   ModuleFile *M;
03781   std::string ErrorStr;
03782   ModuleManager::AddModuleResult AddResult
03783     = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
03784                           getGeneration(), ExpectedSize, ExpectedModTime,
03785                           ExpectedSignature, readASTFileSignature,
03786                           M, ErrorStr);
03787 
03788   switch (AddResult) {
03789   case ModuleManager::AlreadyLoaded:
03790     return Success;
03791 
03792   case ModuleManager::NewlyLoaded:
03793     // Load module file below.
03794     break;
03795 
03796   case ModuleManager::Missing:
03797     // The module file was missing; if the client can handle that, return
03798     // it.
03799     if (ClientLoadCapabilities & ARR_Missing)
03800       return Missing;
03801 
03802     // Otherwise, return an error.
03803     {
03804       std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
03805                       + ErrorStr;
03806       Error(Msg);
03807     }
03808     return Failure;
03809 
03810   case ModuleManager::OutOfDate:
03811     // We couldn't load the module file because it is out-of-date. If the
03812     // client can handle out-of-date, return it.
03813     if (ClientLoadCapabilities & ARR_OutOfDate)
03814       return OutOfDate;
03815 
03816     // Otherwise, return an error.
03817     {
03818       std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
03819                       + ErrorStr;
03820       Error(Msg);
03821     }
03822     return Failure;
03823   }
03824 
03825   assert(M && "Missing module file");
03826 
03827   // FIXME: This seems rather a hack. Should CurrentDir be part of the
03828   // module?
03829   if (FileName != "-") {
03830     CurrentDir = llvm::sys::path::parent_path(FileName);
03831     if (CurrentDir.empty()) CurrentDir = ".";
03832   }
03833 
03834   ModuleFile &F = *M;
03835   BitstreamCursor &Stream = F.Stream;
03836   Stream.init(&F.StreamFile);
03837   F.SizeInBits = F.Buffer->getBufferSize() * 8;
03838   
03839   // Sniff for the signature.
03840   if (Stream.Read(8) != 'C' ||
03841       Stream.Read(8) != 'P' ||
03842       Stream.Read(8) != 'C' ||
03843       Stream.Read(8) != 'H') {
03844     Diag(diag::err_not_a_pch_file) << FileName;
03845     return Failure;
03846   }
03847 
03848   // This is used for compatibility with older PCH formats.
03849   bool HaveReadControlBlock = false;
03850 
03851   while (1) {
03852     llvm::BitstreamEntry Entry = Stream.advance();
03853     
03854     switch (Entry.Kind) {
03855     case llvm::BitstreamEntry::Error:
03856     case llvm::BitstreamEntry::EndBlock:
03857     case llvm::BitstreamEntry::Record:
03858       Error("invalid record at top-level of AST file");
03859       return Failure;
03860         
03861     case llvm::BitstreamEntry::SubBlock:
03862       break;
03863     }
03864 
03865     // We only know the control subblock ID.
03866     switch (Entry.ID) {
03867     case llvm::bitc::BLOCKINFO_BLOCK_ID:
03868       if (Stream.ReadBlockInfoBlock()) {
03869         Error("malformed BlockInfoBlock in AST file");
03870         return Failure;
03871       }
03872       break;
03873     case CONTROL_BLOCK_ID:
03874       HaveReadControlBlock = true;
03875       switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
03876       case Success:
03877         break;
03878 
03879       case Failure: return Failure;
03880       case Missing: return Missing;
03881       case OutOfDate: return OutOfDate;
03882       case VersionMismatch: return VersionMismatch;
03883       case ConfigurationMismatch: return ConfigurationMismatch;
03884       case HadErrors: return HadErrors;
03885       }
03886       break;
03887     case AST_BLOCK_ID:
03888       if (!HaveReadControlBlock) {
03889         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
03890           Diag(diag::err_pch_version_too_old);
03891         return VersionMismatch;
03892       }
03893 
03894       // Record that we've loaded this module.
03895       Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
03896       return Success;
03897 
03898     default:
03899       if (Stream.SkipBlock()) {
03900         Error("malformed block record in AST file");
03901         return Failure;
03902       }
03903       break;
03904     }
03905   }
03906   
03907   return Success;
03908 }
03909 
03910 void ASTReader::InitializeContext() {  
03911   // If there's a listener, notify them that we "read" the translation unit.
03912   if (DeserializationListener)
03913     DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID, 
03914                                       Context.getTranslationUnitDecl());
03915 
03916   // FIXME: Find a better way to deal with collisions between these
03917   // built-in types. Right now, we just ignore the problem.
03918   
03919   // Load the special types.
03920   if (SpecialTypes.size() >= NumSpecialTypeIDs) {
03921     if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
03922       if (!Context.CFConstantStringTypeDecl)
03923         Context.setCFConstantStringType(GetType(String));
03924     }
03925     
03926     if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
03927       QualType FileType = GetType(File);
03928       if (FileType.isNull()) {
03929         Error("FILE type is NULL");
03930         return;
03931       }
03932       
03933       if (!Context.FILEDecl) {
03934         if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
03935           Context.setFILEDecl(Typedef->getDecl());
03936         else {
03937           const TagType *Tag = FileType->getAs<TagType>();
03938           if (!Tag) {
03939             Error("Invalid FILE type in AST file");
03940             return;
03941           }
03942           Context.setFILEDecl(Tag->getDecl());
03943         }
03944       }
03945     }
03946     
03947     if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
03948       QualType Jmp_bufType = GetType(Jmp_buf);
03949       if (Jmp_bufType.isNull()) {
03950         Error("jmp_buf type is NULL");
03951         return;
03952       }
03953       
03954       if (!Context.jmp_bufDecl) {
03955         if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
03956           Context.setjmp_bufDecl(Typedef->getDecl());
03957         else {
03958           const TagType *Tag = Jmp_bufType->getAs<TagType>();
03959           if (!Tag) {
03960             Error("Invalid jmp_buf type in AST file");
03961             return;
03962           }
03963           Context.setjmp_bufDecl(Tag->getDecl());
03964         }
03965       }
03966     }
03967     
03968     if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
03969       QualType Sigjmp_bufType = GetType(Sigjmp_buf);
03970       if (Sigjmp_bufType.isNull()) {
03971         Error("sigjmp_buf type is NULL");
03972         return;
03973       }
03974       
03975       if (!Context.sigjmp_bufDecl) {
03976         if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
03977           Context.setsigjmp_bufDecl(Typedef->getDecl());
03978         else {
03979           const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
03980           assert(Tag && "Invalid sigjmp_buf type in AST file");
03981           Context.setsigjmp_bufDecl(Tag->getDecl());
03982         }
03983       }
03984     }
03985 
03986     if (unsigned ObjCIdRedef
03987           = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
03988       if (Context.ObjCIdRedefinitionType.isNull())
03989         Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
03990     }
03991 
03992     if (unsigned ObjCClassRedef
03993           = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
03994       if (Context.ObjCClassRedefinitionType.isNull())
03995         Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
03996     }
03997 
03998     if (unsigned ObjCSelRedef
03999           = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
04000       if (Context.ObjCSelRedefinitionType.isNull())
04001         Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
04002     }
04003 
04004     if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
04005       QualType Ucontext_tType = GetType(Ucontext_t);
04006       if (Ucontext_tType.isNull()) {
04007         Error("ucontext_t type is NULL");
04008         return;
04009       }
04010 
04011       if (!Context.ucontext_tDecl) {
04012         if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
04013           Context.setucontext_tDecl(Typedef->getDecl());
04014         else {
04015           const TagType *Tag = Ucontext_tType->getAs<TagType>();
04016           assert(Tag && "Invalid ucontext_t type in AST file");
04017           Context.setucontext_tDecl(Tag->getDecl());
04018         }
04019       }
04020     }
04021   }
04022   
04023   ReadPragmaDiagnosticMappings(Context.getDiagnostics());
04024 
04025   // If there were any CUDA special declarations, deserialize them.
04026   if (!CUDASpecialDeclRefs.empty()) {
04027     assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
04028     Context.setcudaConfigureCallDecl(
04029                            cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
04030   }
04031 
04032   // Re-export any modules that were imported by a non-module AST file.
04033   // FIXME: This does not make macro-only imports visible again. It also doesn't
04034   // make #includes mapped to module imports visible.
04035   for (auto &Import : ImportedModules) {
04036     if (Module *Imported = getSubmodule(Import.ID))
04037       makeModuleVisible(Imported, Module::AllVisible,
04038                         /*ImportLoc=*/Import.ImportLoc,
04039                         /*Complain=*/false);
04040   }
04041   ImportedModules.clear();
04042 }
04043 
04044 void ASTReader::finalizeForWriting() {
04045   while (!HiddenNamesMap.empty()) {
04046     auto HiddenNames = std::move(*HiddenNamesMap.begin());
04047     HiddenNamesMap.erase(HiddenNamesMap.begin());
04048     makeNamesVisible(HiddenNames.second, HiddenNames.first,
04049                      /*FromFinalization*/true);
04050   }
04051 }
04052 
04053 /// \brief Given a cursor at the start of an AST file, scan ahead and drop the
04054 /// cursor into the start of the given block ID, returning false on success and
04055 /// true on failure.
04056 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
04057   while (1) {
04058     llvm::BitstreamEntry Entry = Cursor.advance();
04059     switch (Entry.Kind) {
04060     case llvm::BitstreamEntry::Error:
04061     case llvm::BitstreamEntry::EndBlock:
04062       return true;
04063         
04064     case llvm::BitstreamEntry::Record:
04065       // Ignore top-level records.
04066       Cursor.skipRecord(Entry.ID);
04067       break;
04068         
04069     case llvm::BitstreamEntry::SubBlock:
04070       if (Entry.ID == BlockID) {
04071         if (Cursor.EnterSubBlock(BlockID))
04072           return true;
04073         // Found it!
04074         return false;
04075       }
04076       
04077       if (Cursor.SkipBlock())
04078         return true;
04079     }
04080   }
04081 }
04082 
04083 static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
04084   BitstreamCursor Stream(StreamFile);
04085   if (Stream.Read(8) != 'C' ||
04086       Stream.Read(8) != 'P' ||
04087       Stream.Read(8) != 'C' ||
04088       Stream.Read(8) != 'H') {
04089     return 0;
04090   }
04091 
04092   // Scan for the CONTROL_BLOCK_ID block.
04093   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
04094     return 0;
04095 
04096   // Scan for SIGNATURE inside the control block.
04097   ASTReader::RecordData Record;
04098   while (1) {
04099     llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
04100     if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
04101         Entry.Kind != llvm::BitstreamEntry::Record)
04102       return 0;
04103 
04104     Record.clear();
04105     StringRef Blob;
04106     if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
04107       return Record[0];
04108   }
04109 }
04110 
04111 /// \brief Retrieve the name of the original source file name
04112 /// directly from the AST file, without actually loading the AST
04113 /// file.
04114 std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
04115                                              FileManager &FileMgr,
04116                                              DiagnosticsEngine &Diags) {
04117   // Open the AST file.
04118   auto Buffer = FileMgr.getBufferForFile(ASTFileName);
04119   if (!Buffer) {
04120     Diags.Report(diag::err_fe_unable_to_read_pch_file)
04121         << ASTFileName << Buffer.getError().message();
04122     return std::string();
04123   }
04124 
04125   // Initialize the stream
04126   llvm::BitstreamReader StreamFile;
04127   StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
04128                   (const unsigned char *)(*Buffer)->getBufferEnd());
04129   BitstreamCursor Stream(StreamFile);
04130 
04131   // Sniff for the signature.
04132   if (Stream.Read(8) != 'C' ||
04133       Stream.Read(8) != 'P' ||
04134       Stream.Read(8) != 'C' ||
04135       Stream.Read(8) != 'H') {
04136     Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
04137     return std::string();
04138   }
04139   
04140   // Scan for the CONTROL_BLOCK_ID block.
04141   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
04142     Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
04143     return std::string();
04144   }
04145 
04146   // Scan for ORIGINAL_FILE inside the control block.
04147   RecordData Record;
04148   while (1) {
04149     llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
04150     if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
04151       return std::string();
04152     
04153     if (Entry.Kind != llvm::BitstreamEntry::Record) {
04154       Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
04155       return std::string();
04156     }
04157     
04158     Record.clear();
04159     StringRef Blob;
04160     if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
04161       return Blob.str();
04162   }
04163 }
04164 
04165 namespace {
04166   class SimplePCHValidator : public ASTReaderListener {
04167     const LangOptions &ExistingLangOpts;
04168     const TargetOptions &ExistingTargetOpts;
04169     const PreprocessorOptions &ExistingPPOpts;
04170     FileManager &FileMgr;
04171     
04172   public:
04173     SimplePCHValidator(const LangOptions &ExistingLangOpts,
04174                        const TargetOptions &ExistingTargetOpts,
04175                        const PreprocessorOptions &ExistingPPOpts,
04176                        FileManager &FileMgr)
04177       : ExistingLangOpts(ExistingLangOpts),
04178         ExistingTargetOpts(ExistingTargetOpts),
04179         ExistingPPOpts(ExistingPPOpts),
04180         FileMgr(FileMgr)
04181     {
04182     }
04183 
04184     bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
04185                              bool AllowCompatibleDifferences) override {
04186       return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
04187                                   AllowCompatibleDifferences);
04188     }
04189     bool ReadTargetOptions(const TargetOptions &TargetOpts,
04190                            bool Complain) override {
04191       return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr);
04192     }
04193     bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
04194                                  bool Complain,
04195                                  std::string &SuggestedPredefines) override {
04196       return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
04197                                       SuggestedPredefines, ExistingLangOpts);
04198     }
04199   };
04200 }
04201 
04202 bool ASTReader::readASTFileControlBlock(StringRef Filename,
04203                                         FileManager &FileMgr,
04204                                         ASTReaderListener &Listener) {
04205   // Open the AST file.
04206   auto Buffer = FileMgr.getBufferForFile(Filename);
04207   if (!Buffer) {
04208     return true;
04209   }
04210 
04211   // Initialize the stream
04212   llvm::BitstreamReader StreamFile;
04213   StreamFile.init((const unsigned char *)(*Buffer)->getBufferStart(),
04214                   (const unsigned char *)(*Buffer)->getBufferEnd());
04215   BitstreamCursor Stream(StreamFile);
04216 
04217   // Sniff for the signature.
04218   if (Stream.Read(8) != 'C' ||
04219       Stream.Read(8) != 'P' ||
04220       Stream.Read(8) != 'C' ||
04221       Stream.Read(8) != 'H') {
04222     return true;
04223   }
04224 
04225   // Scan for the CONTROL_BLOCK_ID block.
04226   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
04227     return true;
04228 
04229   bool NeedsInputFiles = Listener.needsInputFileVisitation();
04230   bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
04231   bool NeedsImports = Listener.needsImportVisitation();
04232   BitstreamCursor InputFilesCursor;
04233   if (NeedsInputFiles) {
04234     InputFilesCursor = Stream;
04235     if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
04236       return true;
04237 
04238     // Read the abbreviations
04239     while (true) {
04240       uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
04241       unsigned Code = InputFilesCursor.ReadCode();
04242 
04243       // We expect all abbrevs to be at the start of the block.
04244       if (Code != llvm::bitc::DEFINE_ABBREV) {
04245         InputFilesCursor.JumpToBit(Offset);
04246         break;
04247       }
04248       InputFilesCursor.ReadAbbrevRecord();
04249     }
04250   }
04251   
04252   // Scan for ORIGINAL_FILE inside the control block.
04253   RecordData Record;
04254   while (1) {
04255     llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
04256     if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
04257       return false;
04258     
04259     if (Entry.Kind != llvm::BitstreamEntry::Record)
04260       return true;
04261     
04262     Record.clear();
04263     StringRef Blob;
04264     unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
04265     switch ((ControlRecordTypes)RecCode) {
04266     case METADATA: {
04267       if (Record[0] != VERSION_MAJOR)
04268         return true;
04269 
04270       if (Listener.ReadFullVersionInformation(Blob))
04271         return true;
04272       
04273       break;
04274     }
04275     case MODULE_NAME:
04276       Listener.ReadModuleName(Blob);
04277       break;
04278     case MODULE_MAP_FILE: {
04279       unsigned Idx = 0;
04280       Listener.ReadModuleMapFile(ReadString(Record, Idx));
04281       break;
04282     }
04283     case LANGUAGE_OPTIONS:
04284       if (ParseLanguageOptions(Record, false, Listener,
04285                                /*AllowCompatibleConfigurationMismatch*/false))
04286         return true;
04287       break;
04288 
04289     case TARGET_OPTIONS:
04290       if (ParseTargetOptions(Record, false, Listener))
04291         return true;
04292       break;
04293 
04294     case DIAGNOSTIC_OPTIONS:
04295       if (ParseDiagnosticOptions(Record, false, Listener))
04296         return true;
04297       break;
04298 
04299     case FILE_SYSTEM_OPTIONS:
04300       if (ParseFileSystemOptions(Record, false, Listener))
04301         return true;
04302       break;
04303 
04304     case HEADER_SEARCH_OPTIONS:
04305       if (ParseHeaderSearchOptions(Record, false, Listener))
04306         return true;
04307       break;
04308 
04309     case PREPROCESSOR_OPTIONS: {
04310       std::string IgnoredSuggestedPredefines;
04311       if (ParsePreprocessorOptions(Record, false, Listener,
04312                                    IgnoredSuggestedPredefines))
04313         return true;
04314       break;
04315     }
04316 
04317     case INPUT_FILE_OFFSETS: {
04318       if (!NeedsInputFiles)
04319         break;
04320 
04321       unsigned NumInputFiles = Record[0];
04322       unsigned NumUserFiles = Record[1];
04323       const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
04324       for (unsigned I = 0; I != NumInputFiles; ++I) {
04325         // Go find this input file.
04326         bool isSystemFile = I >= NumUserFiles;
04327 
04328         if (isSystemFile && !NeedsSystemInputFiles)
04329           break; // the rest are system input files
04330 
04331         BitstreamCursor &Cursor = InputFilesCursor;
04332         SavedStreamPosition SavedPosition(Cursor);
04333         Cursor.JumpToBit(InputFileOffs[I]);
04334 
04335         unsigned Code = Cursor.ReadCode();
04336         RecordData Record;
04337         StringRef Blob;
04338         bool shouldContinue = false;
04339         switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
04340         case INPUT_FILE:
04341           bool Overridden = static_cast<bool>(Record[3]);
04342           shouldContinue = Listener.visitInputFile(Blob, isSystemFile, Overridden);
04343           break;
04344         }
04345         if (!shouldContinue)
04346           break;
04347       }
04348       break;
04349     }
04350 
04351     case IMPORTS: {
04352       if (!NeedsImports)
04353         break;
04354 
04355       unsigned Idx = 0, N = Record.size();
04356       while (Idx < N) {
04357         // Read information about the AST file.
04358         Idx += 5; // ImportLoc, Size, ModTime, Signature
04359         unsigned Length = Record[Idx++];
04360         SmallString<128> ImportedFile(Record.begin() + Idx,
04361                                       Record.begin() + Idx + Length);
04362         Idx += Length;
04363         Listener.visitImport(ImportedFile);
04364       }
04365       break;
04366     }
04367 
04368     default:
04369       // No other validation to perform.
04370       break;
04371     }
04372   }
04373 }
04374 
04375 
04376 bool ASTReader::isAcceptableASTFile(StringRef Filename,
04377                                     FileManager &FileMgr,
04378                                     const LangOptions &LangOpts,
04379                                     const TargetOptions &TargetOpts,
04380                                     const PreprocessorOptions &PPOpts) {
04381   SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
04382   return !readASTFileControlBlock(Filename, FileMgr, validator);
04383 }
04384 
04385 ASTReader::ASTReadResult
04386 ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
04387   // Enter the submodule block.
04388   if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
04389     Error("malformed submodule block record in AST file");
04390     return Failure;
04391   }
04392 
04393   ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
04394   bool First = true;
04395   Module *CurrentModule = nullptr;
04396   RecordData Record;
04397   while (true) {
04398     llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
04399     
04400     switch (Entry.Kind) {
04401     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
04402     case llvm::BitstreamEntry::Error:
04403       Error("malformed block record in AST file");
04404       return Failure;
04405     case llvm::BitstreamEntry::EndBlock:
04406       return Success;
04407     case llvm::BitstreamEntry::Record:
04408       // The interesting case.
04409       break;
04410     }
04411 
04412     // Read a record.
04413     StringRef Blob;
04414     Record.clear();
04415     auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
04416 
04417     if ((Kind == SUBMODULE_METADATA) != First) {
04418       Error("submodule metadata record should be at beginning of block");
04419       return Failure;
04420     }
04421     First = false;
04422 
04423     // Submodule information is only valid if we have a current module.
04424     // FIXME: Should we error on these cases?
04425     if (!CurrentModule && Kind != SUBMODULE_METADATA &&
04426         Kind != SUBMODULE_DEFINITION)
04427       continue;
04428 
04429     switch (Kind) {
04430     default:  // Default behavior: ignore.
04431       break;
04432 
04433     case SUBMODULE_DEFINITION: {
04434       if (Record.size() < 8) {
04435         Error("malformed module definition");
04436         return Failure;
04437       }
04438 
04439       StringRef Name = Blob;
04440       unsigned Idx = 0;
04441       SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
04442       SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
04443       bool IsFramework = Record[Idx++];
04444       bool IsExplicit = Record[Idx++];
04445       bool IsSystem = Record[Idx++];
04446       bool IsExternC = Record[Idx++];
04447       bool InferSubmodules = Record[Idx++];
04448       bool InferExplicitSubmodules = Record[Idx++];
04449       bool InferExportWildcard = Record[Idx++];
04450       bool ConfigMacrosExhaustive = Record[Idx++];
04451 
04452       Module *ParentModule = nullptr;
04453       if (Parent)
04454         ParentModule = getSubmodule(Parent);
04455 
04456       // Retrieve this (sub)module from the module map, creating it if
04457       // necessary.
04458       CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
04459                                                 IsExplicit).first;
04460 
04461       // FIXME: set the definition loc for CurrentModule, or call
04462       // ModMap.setInferredModuleAllowedBy()
04463 
04464       SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
04465       if (GlobalIndex >= SubmodulesLoaded.size() ||
04466           SubmodulesLoaded[GlobalIndex]) {
04467         Error("too many submodules");
04468         return Failure;
04469       }
04470 
04471       if (!ParentModule) {
04472         if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
04473           if (CurFile != F.File) {
04474             if (!Diags.isDiagnosticInFlight()) {
04475               Diag(diag::err_module_file_conflict)
04476                 << CurrentModule->getTopLevelModuleName()
04477                 << CurFile->getName()
04478                 << F.File->getName();
04479             }
04480             return Failure;
04481           }
04482         }
04483 
04484         CurrentModule->setASTFile(F.File);
04485       }
04486 
04487       CurrentModule->IsFromModuleFile = true;
04488       CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
04489       CurrentModule->IsExternC = IsExternC;
04490       CurrentModule->InferSubmodules = InferSubmodules;
04491       CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
04492       CurrentModule->InferExportWildcard = InferExportWildcard;
04493       CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
04494       if (DeserializationListener)
04495         DeserializationListener->ModuleRead(GlobalID, CurrentModule);
04496       
04497       SubmodulesLoaded[GlobalIndex] = CurrentModule;
04498 
04499       // Clear out data that will be replaced by what is the module file.
04500       CurrentModule->LinkLibraries.clear();
04501       CurrentModule->ConfigMacros.clear();
04502       CurrentModule->UnresolvedConflicts.clear();
04503       CurrentModule->Conflicts.clear();
04504       break;
04505     }
04506         
04507     case SUBMODULE_UMBRELLA_HEADER: {
04508       if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
04509         if (!CurrentModule->getUmbrellaHeader())
04510           ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
04511         else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
04512           if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
04513             Error("mismatched umbrella headers in submodule");
04514           return OutOfDate;
04515         }
04516       }
04517       break;
04518     }
04519         
04520     case SUBMODULE_HEADER:
04521     case SUBMODULE_EXCLUDED_HEADER:
04522     case SUBMODULE_PRIVATE_HEADER:
04523       // We lazily associate headers with their modules via the HeaderInfo table.
04524       // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
04525       // of complete filenames or remove it entirely.
04526       break;
04527 
04528     case SUBMODULE_TEXTUAL_HEADER:
04529     case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
04530       // FIXME: Textual headers are not marked in the HeaderInfo table. Load
04531       // them here.
04532       break;
04533 
04534     case SUBMODULE_TOPHEADER: {
04535       CurrentModule->addTopHeaderFilename(Blob);
04536       break;
04537     }
04538 
04539     case SUBMODULE_UMBRELLA_DIR: {
04540       if (const DirectoryEntry *Umbrella
04541                                   = PP.getFileManager().getDirectory(Blob)) {
04542         if (!CurrentModule->getUmbrellaDir())
04543           ModMap.setUmbrellaDir(CurrentModule, Umbrella);
04544         else if (CurrentModule->getUmbrellaDir() != Umbrella) {
04545           if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
04546             Error("mismatched umbrella directories in submodule");
04547           return OutOfDate;
04548         }
04549       }
04550       break;
04551     }
04552         
04553     case SUBMODULE_METADATA: {
04554       F.BaseSubmoduleID = getTotalNumSubmodules();
04555       F.LocalNumSubmodules = Record[0];
04556       unsigned LocalBaseSubmoduleID = Record[1];
04557       if (F.LocalNumSubmodules > 0) {
04558         // Introduce the global -> local mapping for submodules within this 
04559         // module.
04560         GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
04561         
04562         // Introduce the local -> global mapping for submodules within this 
04563         // module.
04564         F.SubmoduleRemap.insertOrReplace(
04565           std::make_pair(LocalBaseSubmoduleID,
04566                          F.BaseSubmoduleID - LocalBaseSubmoduleID));
04567 
04568         SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
04569       }
04570       break;
04571     }
04572         
04573     case SUBMODULE_IMPORTS: {
04574       for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
04575         UnresolvedModuleRef Unresolved;
04576         Unresolved.File = &F;
04577         Unresolved.Mod = CurrentModule;
04578         Unresolved.ID = Record[Idx];
04579         Unresolved.Kind = UnresolvedModuleRef::Import;
04580         Unresolved.IsWildcard = false;
04581         UnresolvedModuleRefs.push_back(Unresolved);
04582       }
04583       break;
04584     }
04585 
04586     case SUBMODULE_EXPORTS: {
04587       for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
04588         UnresolvedModuleRef Unresolved;
04589         Unresolved.File = &F;
04590         Unresolved.Mod = CurrentModule;
04591         Unresolved.ID = Record[Idx];
04592         Unresolved.Kind = UnresolvedModuleRef::Export;
04593         Unresolved.IsWildcard = Record[Idx + 1];
04594         UnresolvedModuleRefs.push_back(Unresolved);
04595       }
04596       
04597       // Once we've loaded the set of exports, there's no reason to keep 
04598       // the parsed, unresolved exports around.
04599       CurrentModule->UnresolvedExports.clear();
04600       break;
04601     }
04602     case SUBMODULE_REQUIRES: {
04603       CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
04604                                     Context.getTargetInfo());
04605       break;
04606     }
04607 
04608     case SUBMODULE_LINK_LIBRARY:
04609       CurrentModule->LinkLibraries.push_back(
04610                                          Module::LinkLibrary(Blob, Record[0]));
04611       break;
04612 
04613     case SUBMODULE_CONFIG_MACRO:
04614       CurrentModule->ConfigMacros.push_back(Blob.str());
04615       break;
04616 
04617     case SUBMODULE_CONFLICT: {
04618       UnresolvedModuleRef Unresolved;
04619       Unresolved.File = &F;
04620       Unresolved.Mod = CurrentModule;
04621       Unresolved.ID = Record[0];
04622       Unresolved.Kind = UnresolvedModuleRef::Conflict;
04623       Unresolved.IsWildcard = false;
04624       Unresolved.String = Blob;
04625       UnresolvedModuleRefs.push_back(Unresolved);
04626       break;
04627     }
04628     }
04629   }
04630 }
04631 
04632 /// \brief Parse the record that corresponds to a LangOptions data
04633 /// structure.
04634 ///
04635 /// This routine parses the language options from the AST file and then gives
04636 /// them to the AST listener if one is set.
04637 ///
04638 /// \returns true if the listener deems the file unacceptable, false otherwise.
04639 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
04640                                      bool Complain,
04641                                      ASTReaderListener &Listener,
04642                                      bool AllowCompatibleDifferences) {
04643   LangOptions LangOpts;
04644   unsigned Idx = 0;
04645 #define LANGOPT(Name, Bits, Default, Description) \
04646   LangOpts.Name = Record[Idx++];
04647 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
04648   LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
04649 #include "clang/Basic/LangOptions.def"
04650 #define SANITIZER(NAME, ID)                                                    \
04651   LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
04652 #include "clang/Basic/Sanitizers.def"
04653 
04654   ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
04655   VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
04656   LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
04657   
04658   unsigned Length = Record[Idx++];
04659   LangOpts.CurrentModule.assign(Record.begin() + Idx, 
04660                                 Record.begin() + Idx + Length);
04661 
04662   Idx += Length;
04663 
04664   // Comment options.
04665   for (unsigned N = Record[Idx++]; N; --N) {
04666     LangOpts.CommentOpts.BlockCommandNames.push_back(
04667       ReadString(Record, Idx));
04668   }
04669   LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
04670 
04671   return Listener.ReadLanguageOptions(LangOpts, Complain,
04672                                       AllowCompatibleDifferences);
04673 }
04674 
04675 bool ASTReader::ParseTargetOptions(const RecordData &Record,
04676                                    bool Complain,
04677                                    ASTReaderListener &Listener) {
04678   unsigned Idx = 0;
04679   TargetOptions TargetOpts;
04680   TargetOpts.Triple = ReadString(Record, Idx);
04681   TargetOpts.CPU = ReadString(Record, Idx);
04682   TargetOpts.ABI = ReadString(Record, Idx);
04683   for (unsigned N = Record[Idx++]; N; --N) {
04684     TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
04685   }
04686   for (unsigned N = Record[Idx++]; N; --N) {
04687     TargetOpts.Features.push_back(ReadString(Record, Idx));
04688   }
04689 
04690   return Listener.ReadTargetOptions(TargetOpts, Complain);
04691 }
04692 
04693 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
04694                                        ASTReaderListener &Listener) {
04695   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
04696   unsigned Idx = 0;
04697 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
04698 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
04699   DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
04700 #include "clang/Basic/DiagnosticOptions.def"
04701 
04702   for (unsigned N = Record[Idx++]; N; --N)
04703     DiagOpts->Warnings.push_back(ReadString(Record, Idx));
04704   for (unsigned N = Record[Idx++]; N; --N)
04705     DiagOpts->Remarks.push_back(ReadString(Record, Idx));
04706 
04707   return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
04708 }
04709 
04710 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
04711                                        ASTReaderListener &Listener) {
04712   FileSystemOptions FSOpts;
04713   unsigned Idx = 0;
04714   FSOpts.WorkingDir = ReadString(Record, Idx);
04715   return Listener.ReadFileSystemOptions(FSOpts, Complain);
04716 }
04717 
04718 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
04719                                          bool Complain,
04720                                          ASTReaderListener &Listener) {
04721   HeaderSearchOptions HSOpts;
04722   unsigned Idx = 0;
04723   HSOpts.Sysroot = ReadString(Record, Idx);
04724 
04725   // Include entries.
04726   for (unsigned N = Record[Idx++]; N; --N) {
04727     std::string Path = ReadString(Record, Idx);
04728     frontend::IncludeDirGroup Group
04729       = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
04730     bool IsFramework = Record[Idx++];
04731     bool IgnoreSysRoot = Record[Idx++];
04732     HSOpts.UserEntries.push_back(
04733       HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
04734   }
04735 
04736   // System header prefixes.
04737   for (unsigned N = Record[Idx++]; N; --N) {
04738     std::string Prefix = ReadString(Record, Idx);
04739     bool IsSystemHeader = Record[Idx++];
04740     HSOpts.SystemHeaderPrefixes.push_back(
04741       HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
04742   }
04743 
04744   HSOpts.ResourceDir = ReadString(Record, Idx);
04745   HSOpts.ModuleCachePath = ReadString(Record, Idx);
04746   HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
04747   HSOpts.DisableModuleHash = Record[Idx++];
04748   HSOpts.UseBuiltinIncludes = Record[Idx++];
04749   HSOpts.UseStandardSystemIncludes = Record[Idx++];
04750   HSOpts.UseStandardCXXIncludes = Record[Idx++];
04751   HSOpts.UseLibcxx = Record[Idx++];
04752 
04753   return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
04754 }
04755 
04756 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
04757                                          bool Complain,
04758                                          ASTReaderListener &Listener,
04759                                          std::string &SuggestedPredefines) {
04760   PreprocessorOptions PPOpts;
04761   unsigned Idx = 0;
04762 
04763   // Macro definitions/undefs
04764   for (unsigned N = Record[Idx++]; N; --N) {
04765     std::string Macro = ReadString(Record, Idx);
04766     bool IsUndef = Record[Idx++];
04767     PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
04768   }
04769 
04770   // Includes
04771   for (unsigned N = Record[Idx++]; N; --N) {
04772     PPOpts.Includes.push_back(ReadString(Record, Idx));
04773   }
04774 
04775   // Macro Includes
04776   for (unsigned N = Record[Idx++]; N; --N) {
04777     PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
04778   }
04779 
04780   PPOpts.UsePredefines = Record[Idx++];
04781   PPOpts.DetailedRecord = Record[Idx++];
04782   PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
04783   PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
04784   PPOpts.ObjCXXARCStandardLibrary =
04785     static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
04786   SuggestedPredefines.clear();
04787   return Listener.ReadPreprocessorOptions(PPOpts, Complain,
04788                                           SuggestedPredefines);
04789 }
04790 
04791 std::pair<ModuleFile *, unsigned>
04792 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
04793   GlobalPreprocessedEntityMapType::iterator
04794   I = GlobalPreprocessedEntityMap.find(GlobalIndex);
04795   assert(I != GlobalPreprocessedEntityMap.end() && 
04796          "Corrupted global preprocessed entity map");
04797   ModuleFile *M = I->second;
04798   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
04799   return std::make_pair(M, LocalIndex);
04800 }
04801 
04802 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
04803 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
04804   if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
04805     return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
04806                                              Mod.NumPreprocessedEntities);
04807 
04808   return std::make_pair(PreprocessingRecord::iterator(),
04809                         PreprocessingRecord::iterator());
04810 }
04811 
04812 std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
04813 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
04814   return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
04815                         ModuleDeclIterator(this, &Mod,
04816                                  Mod.FileSortedDecls + Mod.NumFileSortedDecls));
04817 }
04818 
04819 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
04820   PreprocessedEntityID PPID = Index+1;
04821   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
04822   ModuleFile &M = *PPInfo.first;
04823   unsigned LocalIndex = PPInfo.second;
04824   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
04825 
04826   if (!PP.getPreprocessingRecord()) {
04827     Error("no preprocessing record");
04828     return nullptr;
04829   }
04830   
04831   SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);  
04832   M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
04833 
04834   llvm::BitstreamEntry Entry =
04835     M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
04836   if (Entry.Kind != llvm::BitstreamEntry::Record)
04837     return nullptr;
04838 
04839   // Read the record.
04840   SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
04841                     ReadSourceLocation(M, PPOffs.End));
04842   PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
04843   StringRef Blob;
04844   RecordData Record;
04845   PreprocessorDetailRecordTypes RecType =
04846     (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
04847                                           Entry.ID, Record, &Blob);
04848   switch (RecType) {
04849   case PPD_MACRO_EXPANSION: {
04850     bool isBuiltin = Record[0];
04851     IdentifierInfo *Name = nullptr;
04852     MacroDefinition *Def = nullptr;
04853     if (isBuiltin)
04854       Name = getLocalIdentifier(M, Record[1]);
04855     else {
04856       PreprocessedEntityID
04857           GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
04858       Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
04859     }
04860 
04861     MacroExpansion *ME;
04862     if (isBuiltin)
04863       ME = new (PPRec) MacroExpansion(Name, Range);
04864     else
04865       ME = new (PPRec) MacroExpansion(Def, Range);
04866 
04867     return ME;
04868   }
04869       
04870   case PPD_MACRO_DEFINITION: {
04871     // Decode the identifier info and then check again; if the macro is
04872     // still defined and associated with the identifier,
04873     IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
04874     MacroDefinition *MD
04875       = new (PPRec) MacroDefinition(II, Range);
04876 
04877     if (DeserializationListener)
04878       DeserializationListener->MacroDefinitionRead(PPID, MD);
04879 
04880     return MD;
04881   }
04882       
04883   case PPD_INCLUSION_DIRECTIVE: {
04884     const char *FullFileNameStart = Blob.data() + Record[0];
04885     StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
04886     const FileEntry *File = nullptr;
04887     if (!FullFileName.empty())
04888       File = PP.getFileManager().getFile(FullFileName);
04889     
04890     // FIXME: Stable encoding
04891     InclusionDirective::InclusionKind Kind
04892       = static_cast<InclusionDirective::InclusionKind>(Record[2]);
04893     InclusionDirective *ID
04894       = new (PPRec) InclusionDirective(PPRec, Kind,
04895                                        StringRef(Blob.data(), Record[0]),
04896                                        Record[1], Record[3],
04897                                        File,
04898                                        Range);
04899     return ID;
04900   }
04901   }
04902 
04903   llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
04904 }
04905 
04906 /// \brief \arg SLocMapI points at a chunk of a module that contains no
04907 /// preprocessed entities or the entities it contains are not the ones we are
04908 /// looking for. Find the next module that contains entities and return the ID
04909 /// of the first entry.
04910 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
04911                        GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
04912   ++SLocMapI;
04913   for (GlobalSLocOffsetMapType::const_iterator
04914          EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
04915     ModuleFile &M = *SLocMapI->second;
04916     if (M.NumPreprocessedEntities)
04917       return M.BasePreprocessedEntityID;
04918   }
04919 
04920   return getTotalNumPreprocessedEntities();
04921 }
04922 
04923 namespace {
04924 
04925 template <unsigned PPEntityOffset::*PPLoc>
04926 struct PPEntityComp {
04927   const ASTReader &Reader;
04928   ModuleFile &M;
04929 
04930   PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
04931 
04932   bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
04933     SourceLocation LHS = getLoc(L);
04934     SourceLocation RHS = getLoc(R);
04935     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
04936   }
04937 
04938   bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
04939     SourceLocation LHS = getLoc(L);
04940     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
04941   }
04942 
04943   bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
04944     SourceLocation RHS = getLoc(R);
04945     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
04946   }
04947 
04948   SourceLocation getLoc(const PPEntityOffset &PPE) const {
04949     return Reader.ReadSourceLocation(M, PPE.*PPLoc);
04950   }
04951 };
04952 
04953 }
04954 
04955 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
04956                                                        bool EndsAfter) const {
04957   if (SourceMgr.isLocalSourceLocation(Loc))
04958     return getTotalNumPreprocessedEntities();
04959 
04960   GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
04961       SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
04962   assert(SLocMapI != GlobalSLocOffsetMap.end() &&
04963          "Corrupted global sloc offset map");
04964 
04965   if (SLocMapI->second->NumPreprocessedEntities == 0)
04966     return findNextPreprocessedEntity(SLocMapI);
04967 
04968   ModuleFile &M = *SLocMapI->second;
04969   typedef const PPEntityOffset *pp_iterator;
04970   pp_iterator pp_begin = M.PreprocessedEntityOffsets;
04971   pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
04972 
04973   size_t Count = M.NumPreprocessedEntities;
04974   size_t Half;
04975   pp_iterator First = pp_begin;
04976   pp_iterator PPI;
04977 
04978   if (EndsAfter) {
04979     PPI = std::upper_bound(pp_begin, pp_end, Loc,
04980                            PPEntityComp<&PPEntityOffset::Begin>(*this, M));
04981   } else {
04982     // Do a binary search manually instead of using std::lower_bound because
04983     // The end locations of entities may be unordered (when a macro expansion
04984     // is inside another macro argument), but for this case it is not important
04985     // whether we get the first macro expansion or its containing macro.
04986     while (Count > 0) {
04987       Half = Count / 2;
04988       PPI = First;
04989       std::advance(PPI, Half);
04990       if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
04991                                               Loc)) {
04992         First = PPI;
04993         ++First;
04994         Count = Count - Half - 1;
04995       } else
04996         Count = Half;
04997     }
04998   }
04999 
05000   if (PPI == pp_end)
05001     return findNextPreprocessedEntity(SLocMapI);
05002 
05003   return M.BasePreprocessedEntityID + (PPI - pp_begin);
05004 }
05005 
05006 /// \brief Returns a pair of [Begin, End) indices of preallocated
05007 /// preprocessed entities that \arg Range encompasses.
05008 std::pair<unsigned, unsigned>
05009     ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
05010   if (Range.isInvalid())
05011     return std::make_pair(0,0);
05012   assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
05013 
05014   PreprocessedEntityID BeginID =
05015       findPreprocessedEntity(Range.getBegin(), false);
05016   PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
05017   return std::make_pair(BeginID, EndID);
05018 }
05019 
05020 /// \brief Optionally returns true or false if the preallocated preprocessed
05021 /// entity with index \arg Index came from file \arg FID.
05022 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
05023                                                              FileID FID) {
05024   if (FID.isInvalid())
05025     return false;
05026 
05027   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
05028   ModuleFile &M = *PPInfo.first;
05029   unsigned LocalIndex = PPInfo.second;
05030   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
05031   
05032   SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
05033   if (Loc.isInvalid())
05034     return false;
05035   
05036   if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
05037     return true;
05038   else
05039     return false;
05040 }
05041 
05042 namespace {
05043   /// \brief Visitor used to search for information about a header file.
05044   class HeaderFileInfoVisitor {
05045     const FileEntry *FE;
05046     
05047     Optional<HeaderFileInfo> HFI;
05048     
05049   public:
05050     explicit HeaderFileInfoVisitor(const FileEntry *FE)
05051       : FE(FE) { }
05052     
05053     static bool visit(ModuleFile &M, void *UserData) {
05054       HeaderFileInfoVisitor *This
05055         = static_cast<HeaderFileInfoVisitor *>(UserData);
05056       
05057       HeaderFileInfoLookupTable *Table
05058         = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
05059       if (!Table)
05060         return false;
05061 
05062       // Look in the on-disk hash table for an entry for this file name.
05063       HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
05064       if (Pos == Table->end())
05065         return false;
05066 
05067       This->HFI = *Pos;
05068       return true;
05069     }
05070     
05071     Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
05072   };
05073 }
05074 
05075 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
05076   HeaderFileInfoVisitor Visitor(FE);
05077   ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
05078   if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
05079     return *HFI;
05080   
05081   return HeaderFileInfo();
05082 }
05083 
05084 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
05085   // FIXME: Make it work properly with modules.
05086   SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
05087   for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
05088     ModuleFile &F = *(*I);
05089     unsigned Idx = 0;
05090     DiagStates.clear();
05091     assert(!Diag.DiagStates.empty());
05092     DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
05093     while (Idx < F.PragmaDiagMappings.size()) {
05094       SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
05095       unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
05096       if (DiagStateID != 0) {
05097         Diag.DiagStatePoints.push_back(
05098                     DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
05099                     FullSourceLoc(Loc, SourceMgr)));
05100         continue;
05101       }
05102       
05103       assert(DiagStateID == 0);
05104       // A new DiagState was created here.
05105       Diag.DiagStates.push_back(*Diag.GetCurDiagState());
05106       DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
05107       DiagStates.push_back(NewState);
05108       Diag.DiagStatePoints.push_back(
05109           DiagnosticsEngine::DiagStatePoint(NewState,
05110                                             FullSourceLoc(Loc, SourceMgr)));
05111       while (1) {
05112         assert(Idx < F.PragmaDiagMappings.size() &&
05113                "Invalid data, didn't find '-1' marking end of diag/map pairs");
05114         if (Idx >= F.PragmaDiagMappings.size()) {
05115           break; // Something is messed up but at least avoid infinite loop in
05116                  // release build.
05117         }
05118         unsigned DiagID = F.PragmaDiagMappings[Idx++];
05119         if (DiagID == (unsigned)-1) {
05120           break; // no more diag/map pairs for this location.
05121         }
05122         diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
05123         DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
05124         Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
05125       }
05126     }
05127   }
05128 }
05129 
05130 /// \brief Get the correct cursor and offset for loading a type.
05131 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
05132   GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
05133   assert(I != GlobalTypeMap.end() && "Corrupted global type map");
05134   ModuleFile *M = I->second;
05135   return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
05136 }
05137 
05138 /// \brief Read and return the type with the given index..
05139 ///
05140 /// The index is the type ID, shifted and minus the number of predefs. This
05141 /// routine actually reads the record corresponding to the type at the given
05142 /// location. It is a helper routine for GetType, which deals with reading type
05143 /// IDs.
05144 QualType ASTReader::readTypeRecord(unsigned Index) {
05145   RecordLocation Loc = TypeCursorForIndex(Index);
05146   BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
05147 
05148   // Keep track of where we are in the stream, then jump back there
05149   // after reading this type.
05150   SavedStreamPosition SavedPosition(DeclsCursor);
05151 
05152   ReadingKindTracker ReadingKind(Read_Type, *this);
05153 
05154   // Note that we are loading a type record.
05155   Deserializing AType(this);
05156 
05157   unsigned Idx = 0;
05158   DeclsCursor.JumpToBit(Loc.Offset);
05159   RecordData Record;
05160   unsigned Code = DeclsCursor.ReadCode();
05161   switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
05162   case TYPE_EXT_QUAL: {
05163     if (Record.size() != 2) {
05164       Error("Incorrect encoding of extended qualifier type");
05165       return QualType();
05166     }
05167     QualType Base = readType(*Loc.F, Record, Idx);
05168     Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
05169     return Context.getQualifiedType(Base, Quals);
05170   }
05171 
05172   case TYPE_COMPLEX: {
05173     if (Record.size() != 1) {
05174       Error("Incorrect encoding of complex type");
05175       return QualType();
05176     }
05177     QualType ElemType = readType(*Loc.F, Record, Idx);
05178     return Context.getComplexType(ElemType);
05179   }
05180 
05181   case TYPE_POINTER: {
05182     if (Record.size() != 1) {
05183       Error("Incorrect encoding of pointer type");
05184       return QualType();
05185     }
05186     QualType PointeeType = readType(*Loc.F, Record, Idx);
05187     return Context.getPointerType(PointeeType);
05188   }
05189 
05190   case TYPE_DECAYED: {
05191     if (Record.size() != 1) {
05192       Error("Incorrect encoding of decayed type");
05193       return QualType();
05194     }
05195     QualType OriginalType = readType(*Loc.F, Record, Idx);
05196     QualType DT = Context.getAdjustedParameterType(OriginalType);
05197     if (!isa<DecayedType>(DT))
05198       Error("Decayed type does not decay");
05199     return DT;
05200   }
05201 
05202   case TYPE_ADJUSTED: {
05203     if (Record.size() != 2) {
05204       Error("Incorrect encoding of adjusted type");
05205       return QualType();
05206     }
05207     QualType OriginalTy = readType(*Loc.F, Record, Idx);
05208     QualType AdjustedTy = readType(*Loc.F, Record, Idx);
05209     return Context.getAdjustedType(OriginalTy, AdjustedTy);
05210   }
05211 
05212   case TYPE_BLOCK_POINTER: {
05213     if (Record.size() != 1) {
05214       Error("Incorrect encoding of block pointer type");
05215       return QualType();
05216     }
05217     QualType PointeeType = readType(*Loc.F, Record, Idx);
05218     return Context.getBlockPointerType(PointeeType);
05219   }
05220 
05221   case TYPE_LVALUE_REFERENCE: {
05222     if (Record.size() != 2) {
05223       Error("Incorrect encoding of lvalue reference type");
05224       return QualType();
05225     }
05226     QualType PointeeType = readType(*Loc.F, Record, Idx);
05227     return Context.getLValueReferenceType(PointeeType, Record[1]);
05228   }
05229 
05230   case TYPE_RVALUE_REFERENCE: {
05231     if (Record.size() != 1) {
05232       Error("Incorrect encoding of rvalue reference type");
05233       return QualType();
05234     }
05235     QualType PointeeType = readType(*Loc.F, Record, Idx);
05236     return Context.getRValueReferenceType(PointeeType);
05237   }
05238 
05239   case TYPE_MEMBER_POINTER: {
05240     if (Record.size() != 2) {
05241       Error("Incorrect encoding of member pointer type");
05242       return QualType();
05243     }
05244     QualType PointeeType = readType(*Loc.F, Record, Idx);
05245     QualType ClassType = readType(*Loc.F, Record, Idx);
05246     if (PointeeType.isNull() || ClassType.isNull())
05247       return QualType();
05248     
05249     return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
05250   }
05251 
05252   case TYPE_CONSTANT_ARRAY: {
05253     QualType ElementType = readType(*Loc.F, Record, Idx);
05254     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
05255     unsigned IndexTypeQuals = Record[2];
05256     unsigned Idx = 3;
05257     llvm::APInt Size = ReadAPInt(Record, Idx);
05258     return Context.getConstantArrayType(ElementType, Size,
05259                                          ASM, IndexTypeQuals);
05260   }
05261 
05262   case TYPE_INCOMPLETE_ARRAY: {
05263     QualType ElementType = readType(*Loc.F, Record, Idx);
05264     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
05265     unsigned IndexTypeQuals = Record[2];
05266     return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
05267   }
05268 
05269   case TYPE_VARIABLE_ARRAY: {
05270     QualType ElementType = readType(*Loc.F, Record, Idx);
05271     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
05272     unsigned IndexTypeQuals = Record[2];
05273     SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
05274     SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
05275     return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
05276                                          ASM, IndexTypeQuals,
05277                                          SourceRange(LBLoc, RBLoc));
05278   }
05279 
05280   case TYPE_VECTOR: {
05281     if (Record.size() != 3) {
05282       Error("incorrect encoding of vector type in AST file");
05283       return QualType();
05284     }
05285 
05286     QualType ElementType = readType(*Loc.F, Record, Idx);
05287     unsigned NumElements = Record[1];
05288     unsigned VecKind = Record[2];
05289     return Context.getVectorType(ElementType, NumElements,
05290                                   (VectorType::VectorKind)VecKind);
05291   }
05292 
05293   case TYPE_EXT_VECTOR: {
05294     if (Record.size() != 3) {
05295       Error("incorrect encoding of extended vector type in AST file");
05296       return QualType();
05297     }
05298 
05299     QualType ElementType = readType(*Loc.F, Record, Idx);
05300     unsigned NumElements = Record[1];
05301     return Context.getExtVectorType(ElementType, NumElements);
05302   }
05303 
05304   case TYPE_FUNCTION_NO_PROTO: {
05305     if (Record.size() != 6) {
05306       Error("incorrect encoding of no-proto function type");
05307       return QualType();
05308     }
05309     QualType ResultType = readType(*Loc.F, Record, Idx);
05310     FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
05311                                (CallingConv)Record[4], Record[5]);
05312     return Context.getFunctionNoProtoType(ResultType, Info);
05313   }
05314 
05315   case TYPE_FUNCTION_PROTO: {
05316     QualType ResultType = readType(*Loc.F, Record, Idx);
05317 
05318     FunctionProtoType::ExtProtoInfo EPI;
05319     EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
05320                                         /*hasregparm*/ Record[2],
05321                                         /*regparm*/ Record[3],
05322                                         static_cast<CallingConv>(Record[4]),
05323                                         /*produces*/ Record[5]);
05324 
05325     unsigned Idx = 6;
05326 
05327     EPI.Variadic = Record[Idx++];
05328     EPI.HasTrailingReturn = Record[Idx++];
05329     EPI.TypeQuals = Record[Idx++];
05330     EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
05331     SmallVector<QualType, 8> ExceptionStorage;
05332     readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
05333 
05334     unsigned NumParams = Record[Idx++];
05335     SmallVector<QualType, 16> ParamTypes;
05336     for (unsigned I = 0; I != NumParams; ++I)
05337       ParamTypes.push_back(readType(*Loc.F, Record, Idx));
05338 
05339     return Context.getFunctionType(ResultType, ParamTypes, EPI);
05340   }
05341 
05342   case TYPE_UNRESOLVED_USING: {
05343     unsigned Idx = 0;
05344     return Context.getTypeDeclType(
05345                   ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
05346   }
05347       
05348   case TYPE_TYPEDEF: {
05349     if (Record.size() != 2) {
05350       Error("incorrect encoding of typedef type");
05351       return QualType();
05352     }
05353     unsigned Idx = 0;
05354     TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
05355     QualType Canonical = readType(*Loc.F, Record, Idx);
05356     if (!Canonical.isNull())
05357       Canonical = Context.getCanonicalType(Canonical);
05358     return Context.getTypedefType(Decl, Canonical);
05359   }
05360 
05361   case TYPE_TYPEOF_EXPR:
05362     return Context.getTypeOfExprType(ReadExpr(*Loc.F));
05363 
05364   case TYPE_TYPEOF: {
05365     if (Record.size() != 1) {
05366       Error("incorrect encoding of typeof(type) in AST file");
05367       return QualType();
05368     }
05369     QualType UnderlyingType = readType(*Loc.F, Record, Idx);
05370     return Context.getTypeOfType(UnderlyingType);
05371   }
05372 
05373   case TYPE_DECLTYPE: {
05374     QualType UnderlyingType = readType(*Loc.F, Record, Idx);
05375     return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
05376   }
05377 
05378   case TYPE_UNARY_TRANSFORM: {
05379     QualType BaseType = readType(*Loc.F, Record, Idx);
05380     QualType UnderlyingType = readType(*Loc.F, Record, Idx);
05381     UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
05382     return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
05383   }
05384 
05385   case TYPE_AUTO: {
05386     QualType Deduced = readType(*Loc.F, Record, Idx);
05387     bool IsDecltypeAuto = Record[Idx++];
05388     bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
05389     return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
05390   }
05391 
05392   case TYPE_RECORD: {
05393     if (Record.size() != 2) {
05394       Error("incorrect encoding of record type");
05395       return QualType();
05396     }
05397     unsigned Idx = 0;
05398     bool IsDependent = Record[Idx++];
05399     RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
05400     RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
05401     QualType T = Context.getRecordType(RD);
05402     const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
05403     return T;
05404   }
05405 
05406   case TYPE_ENUM: {
05407     if (Record.size() != 2) {
05408       Error("incorrect encoding of enum type");
05409       return QualType();
05410     }
05411     unsigned Idx = 0;
05412     bool IsDependent = Record[Idx++];
05413     QualType T
05414       = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
05415     const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
05416     return T;
05417   }
05418 
05419   case TYPE_ATTRIBUTED: {
05420     if (Record.size() != 3) {
05421       Error("incorrect encoding of attributed type");
05422       return QualType();
05423     }
05424     QualType modifiedType = readType(*Loc.F, Record, Idx);
05425     QualType equivalentType = readType(*Loc.F, Record, Idx);
05426     AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
05427     return Context.getAttributedType(kind, modifiedType, equivalentType);
05428   }
05429 
05430   case TYPE_PAREN: {
05431     if (Record.size() != 1) {
05432       Error("incorrect encoding of paren type");
05433       return QualType();
05434     }
05435     QualType InnerType = readType(*Loc.F, Record, Idx);
05436     return Context.getParenType(InnerType);
05437   }
05438 
05439   case TYPE_PACK_EXPANSION: {
05440     if (Record.size() != 2) {
05441       Error("incorrect encoding of pack expansion type");
05442       return QualType();
05443     }
05444     QualType Pattern = readType(*Loc.F, Record, Idx);
05445     if (Pattern.isNull())
05446       return QualType();
05447     Optional<unsigned> NumExpansions;
05448     if (Record[1])
05449       NumExpansions = Record[1] - 1;
05450     return Context.getPackExpansionType(Pattern, NumExpansions);
05451   }
05452 
05453   case TYPE_ELABORATED: {
05454     unsigned Idx = 0;
05455     ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
05456     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
05457     QualType NamedType = readType(*Loc.F, Record, Idx);
05458     return Context.getElaboratedType(Keyword, NNS, NamedType);
05459   }
05460 
05461   case TYPE_OBJC_INTERFACE: {
05462     unsigned Idx = 0;
05463     ObjCInterfaceDecl *ItfD
05464       = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
05465     return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
05466   }
05467 
05468   case TYPE_OBJC_OBJECT: {
05469     unsigned Idx = 0;
05470     QualType Base = readType(*Loc.F, Record, Idx);
05471     unsigned NumProtos = Record[Idx++];
05472     SmallVector<ObjCProtocolDecl*, 4> Protos;
05473     for (unsigned I = 0; I != NumProtos; ++I)
05474       Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
05475     return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
05476   }
05477 
05478   case TYPE_OBJC_OBJECT_POINTER: {
05479     unsigned Idx = 0;
05480     QualType Pointee = readType(*Loc.F, Record, Idx);
05481     return Context.getObjCObjectPointerType(Pointee);
05482   }
05483 
05484   case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
05485     unsigned Idx = 0;
05486     QualType Parm = readType(*Loc.F, Record, Idx);
05487     QualType Replacement = readType(*Loc.F, Record, Idx);
05488     return Context.getSubstTemplateTypeParmType(
05489         cast<TemplateTypeParmType>(Parm),
05490         Context.getCanonicalType(Replacement));
05491   }
05492 
05493   case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
05494     unsigned Idx = 0;
05495     QualType Parm = readType(*Loc.F, Record, Idx);
05496     TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
05497     return Context.getSubstTemplateTypeParmPackType(
05498                                                cast<TemplateTypeParmType>(Parm),
05499                                                      ArgPack);
05500   }
05501 
05502   case TYPE_INJECTED_CLASS_NAME: {
05503     CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
05504     QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
05505     // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
05506     // for AST reading, too much interdependencies.
05507     const Type *T = nullptr;
05508     for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
05509       if (const Type *Existing = DI->getTypeForDecl()) {
05510         T = Existing;
05511         break;
05512       }
05513     }
05514     if (!T) {
05515       T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
05516       for (auto *DI = D; DI; DI = DI->getPreviousDecl())
05517         DI->setTypeForDecl(T);
05518     }
05519     return QualType(T, 0);
05520   }
05521 
05522   case TYPE_TEMPLATE_TYPE_PARM: {
05523     unsigned Idx = 0;
05524     unsigned Depth = Record[Idx++];
05525     unsigned Index = Record[Idx++];
05526     bool Pack = Record[Idx++];
05527     TemplateTypeParmDecl *D
05528       = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
05529     return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
05530   }
05531 
05532   case TYPE_DEPENDENT_NAME: {
05533     unsigned Idx = 0;
05534     ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
05535     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
05536     const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
05537     QualType Canon = readType(*Loc.F, Record, Idx);
05538     if (!Canon.isNull())
05539       Canon = Context.getCanonicalType(Canon);
05540     return Context.getDependentNameType(Keyword, NNS, Name, Canon);
05541   }
05542 
05543   case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
05544     unsigned Idx = 0;
05545     ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
05546     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
05547     const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
05548     unsigned NumArgs = Record[Idx++];
05549     SmallVector<TemplateArgument, 8> Args;
05550     Args.reserve(NumArgs);
05551     while (NumArgs--)
05552       Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
05553     return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
05554                                                       Args.size(), Args.data());
05555   }
05556 
05557   case TYPE_DEPENDENT_SIZED_ARRAY: {
05558     unsigned Idx = 0;
05559 
05560     // ArrayType
05561     QualType ElementType = readType(*Loc.F, Record, Idx);
05562     ArrayType::ArraySizeModifier ASM
05563       = (ArrayType::ArraySizeModifier)Record[Idx++];
05564     unsigned IndexTypeQuals = Record[Idx++];
05565 
05566     // DependentSizedArrayType
05567     Expr *NumElts = ReadExpr(*Loc.F);
05568     SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
05569 
05570     return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
05571                                                IndexTypeQuals, Brackets);
05572   }
05573 
05574   case TYPE_TEMPLATE_SPECIALIZATION: {
05575     unsigned Idx = 0;
05576     bool IsDependent = Record[Idx++];
05577     TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
05578     SmallVector<TemplateArgument, 8> Args;
05579     ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
05580     QualType Underlying = readType(*Loc.F, Record, Idx);
05581     QualType T;
05582     if (Underlying.isNull())
05583       T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
05584                                                           Args.size());
05585     else
05586       T = Context.getTemplateSpecializationType(Name, Args.data(),
05587                                                  Args.size(), Underlying);
05588     const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
05589     return T;
05590   }
05591 
05592   case TYPE_ATOMIC: {
05593     if (Record.size() != 1) {
05594       Error("Incorrect encoding of atomic type");
05595       return QualType();
05596     }
05597     QualType ValueType = readType(*Loc.F, Record, Idx);
05598     return Context.getAtomicType(ValueType);
05599   }
05600   }
05601   llvm_unreachable("Invalid TypeCode!");
05602 }
05603 
05604 void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
05605                                   SmallVectorImpl<QualType> &Exceptions,
05606                                   FunctionProtoType::ExceptionSpecInfo &ESI,
05607                                   const RecordData &Record, unsigned &Idx) {
05608   ExceptionSpecificationType EST =
05609       static_cast<ExceptionSpecificationType>(Record[Idx++]);
05610   ESI.Type = EST;
05611   if (EST == EST_Dynamic) {
05612     for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
05613       Exceptions.push_back(readType(ModuleFile, Record, Idx));
05614     ESI.Exceptions = Exceptions;
05615   } else if (EST == EST_ComputedNoexcept) {
05616     ESI.NoexceptExpr = ReadExpr(ModuleFile);
05617   } else if (EST == EST_Uninstantiated) {
05618     ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
05619     ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
05620   } else if (EST == EST_Unevaluated) {
05621     ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
05622   }
05623 }
05624 
05625 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
05626   ASTReader &Reader;
05627   ModuleFile &F;
05628   const ASTReader::RecordData &Record;
05629   unsigned &Idx;
05630 
05631   SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
05632                                     unsigned &I) {
05633     return Reader.ReadSourceLocation(F, R, I);
05634   }
05635 
05636   template<typename T>
05637   T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
05638     return Reader.ReadDeclAs<T>(F, Record, Idx);
05639   }
05640   
05641 public:
05642   TypeLocReader(ASTReader &Reader, ModuleFile &F,
05643                 const ASTReader::RecordData &Record, unsigned &Idx)
05644     : Reader(Reader), F(F), Record(Record), Idx(Idx)
05645   { }
05646 
05647   // We want compile-time assurance that we've enumerated all of
05648   // these, so unfortunately we have to declare them first, then
05649   // define them out-of-line.
05650 #define ABSTRACT_TYPELOC(CLASS, PARENT)
05651 #define TYPELOC(CLASS, PARENT) \
05652   void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
05653 #include "clang/AST/TypeLocNodes.def"
05654 
05655   void VisitFunctionTypeLoc(FunctionTypeLoc);
05656   void VisitArrayTypeLoc(ArrayTypeLoc);
05657 };
05658 
05659 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
05660   // nothing to do
05661 }
05662 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
05663   TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
05664   if (TL.needsExtraLocalData()) {
05665     TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
05666     TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
05667     TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
05668     TL.setModeAttr(Record[Idx++]);
05669   }
05670 }
05671 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
05672   TL.setNameLoc(ReadSourceLocation(Record, Idx));
05673 }
05674 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
05675   TL.setStarLoc(ReadSourceLocation(Record, Idx));
05676 }
05677 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
05678   // nothing to do
05679 }
05680 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
05681   // nothing to do
05682 }
05683 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
05684   TL.setCaretLoc(ReadSourceLocation(Record, Idx));
05685 }
05686 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
05687   TL.setAmpLoc(ReadSourceLocation(Record, Idx));
05688 }
05689 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
05690   TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
05691 }
05692 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
05693   TL.setStarLoc(ReadSourceLocation(Record, Idx));
05694   TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
05695 }
05696 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
05697   TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
05698   TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
05699   if (Record[Idx++])
05700     TL.setSizeExpr(Reader.ReadExpr(F));
05701   else
05702     TL.setSizeExpr(nullptr);
05703 }
05704 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
05705   VisitArrayTypeLoc(TL);
05706 }
05707 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
05708   VisitArrayTypeLoc(TL);
05709 }
05710 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
05711   VisitArrayTypeLoc(TL);
05712 }
05713 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
05714                                             DependentSizedArrayTypeLoc TL) {
05715   VisitArrayTypeLoc(TL);
05716 }
05717 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
05718                                         DependentSizedExtVectorTypeLoc TL) {
05719   TL.setNameLoc(ReadSourceLocation(Record, Idx));
05720 }
05721 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
05722   TL.setNameLoc(ReadSourceLocation(Record, Idx));
05723 }
05724 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
05725   TL.setNameLoc(ReadSourceLocation(Record, Idx));
05726 }
05727 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
05728   TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
05729   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
05730   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
05731   TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
05732   for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
05733     TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
05734   }
05735 }
05736 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
05737   VisitFunctionTypeLoc(TL);
05738 }
05739 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
05740   VisitFunctionTypeLoc(TL);
05741 }
05742 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
05743   TL.setNameLoc(ReadSourceLocation(Record, Idx));
05744 }
05745 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
05746   TL.setNameLoc(ReadSourceLocation(Record, Idx));
05747 }
05748 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
05749   TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
05750   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
05751   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
05752 }
05753 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
05754   TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
05755   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
05756   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
05757   TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
05758 }
05759 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
05760   TL.setNameLoc(ReadSourceLocation(Record, Idx));
05761 }
05762 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
05763   TL.setKWLoc(ReadSourceLocation(Record, Idx));
05764   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
05765   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
05766   TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
05767 }
05768 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
05769   TL.setNameLoc(ReadSourceLocation(Record, Idx));
05770 }
05771 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
05772   TL.setNameLoc(ReadSourceLocation(Record, Idx));
05773 }
05774 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
05775   TL.setNameLoc(ReadSourceLocation(Record, Idx));
05776 }
05777 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
05778   TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
05779   if (TL.hasAttrOperand()) {
05780     SourceRange range;
05781     range.setBegin(ReadSourceLocation(Record, Idx));
05782     range.setEnd(ReadSourceLocation(Record, Idx));
05783     TL.setAttrOperandParensRange(range);
05784   }
05785   if (TL.hasAttrExprOperand()) {
05786     if (Record[Idx++])
05787       TL.setAttrExprOperand(Reader.ReadExpr(F));
05788     else
05789       TL.setAttrExprOperand(nullptr);
05790   } else if (TL.hasAttrEnumOperand())
05791     TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
05792 }
05793 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
05794   TL.setNameLoc(ReadSourceLocation(Record, Idx));
05795 }
05796 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
05797                                             SubstTemplateTypeParmTypeLoc TL) {
05798   TL.setNameLoc(ReadSourceLocation(Record, Idx));
05799 }
05800 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
05801                                           SubstTemplateTypeParmPackTypeLoc TL) {
05802   TL.setNameLoc(ReadSourceLocation(Record, Idx));
05803 }
05804 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
05805                                            TemplateSpecializationTypeLoc TL) {
05806   TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
05807   TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
05808   TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
05809   TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
05810   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
05811     TL.setArgLocInfo(i,
05812         Reader.GetTemplateArgumentLocInfo(F,
05813                                           TL.getTypePtr()->getArg(i).getKind(),
05814                                           Record, Idx));
05815 }
05816 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
05817   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
05818   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
05819 }
05820 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
05821   TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
05822   TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
05823 }
05824 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
05825   TL.setNameLoc(ReadSourceLocation(Record, Idx));
05826 }
05827 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
05828   TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
05829   TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
05830   TL.setNameLoc(ReadSourceLocation(Record, Idx));
05831 }
05832 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
05833        DependentTemplateSpecializationTypeLoc TL) {
05834   TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
05835   TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
05836   TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
05837   TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
05838   TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
05839   TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
05840   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
05841     TL.setArgLocInfo(I,
05842         Reader.GetTemplateArgumentLocInfo(F,
05843                                           TL.getTypePtr()->getArg(I).getKind(),
05844                                           Record, Idx));
05845 }
05846 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
05847   TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
05848 }
05849 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
05850   TL.setNameLoc(ReadSourceLocation(Record, Idx));
05851 }
05852 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
05853   TL.setHasBaseTypeAsWritten(Record[Idx++]);
05854   TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
05855   TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
05856   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
05857     TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
05858 }
05859 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
05860   TL.setStarLoc(ReadSourceLocation(Record, Idx));
05861 }
05862 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
05863   TL.setKWLoc(ReadSourceLocation(Record, Idx));
05864   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
05865   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
05866 }
05867 
05868 TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
05869                                              const RecordData &Record,
05870                                              unsigned &Idx) {
05871   QualType InfoTy = readType(F, Record, Idx);
05872   if (InfoTy.isNull())
05873     return nullptr;
05874 
05875   TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
05876   TypeLocReader TLR(*this, F, Record, Idx);
05877   for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
05878     TLR.Visit(TL);
05879   return TInfo;
05880 }
05881 
05882 QualType ASTReader::GetType(TypeID ID) {
05883   unsigned FastQuals = ID & Qualifiers::FastMask;
05884   unsigned Index = ID >> Qualifiers::FastWidth;
05885 
05886   if (Index < NUM_PREDEF_TYPE_IDS) {
05887     QualType T;
05888     switch ((PredefinedTypeIDs)Index) {
05889     case PREDEF_TYPE_NULL_ID: return QualType();
05890     case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
05891     case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
05892 
05893     case PREDEF_TYPE_CHAR_U_ID:
05894     case PREDEF_TYPE_CHAR_S_ID:
05895       // FIXME: Check that the signedness of CharTy is correct!
05896       T = Context.CharTy;
05897       break;
05898 
05899     case PREDEF_TYPE_UCHAR_ID:      T = Context.UnsignedCharTy;     break;
05900     case PREDEF_TYPE_USHORT_ID:     T = Context.UnsignedShortTy;    break;
05901     case PREDEF_TYPE_UINT_ID:       T = Context.UnsignedIntTy;      break;
05902     case PREDEF_TYPE_ULONG_ID:      T = Context.UnsignedLongTy;     break;
05903     case PREDEF_TYPE_ULONGLONG_ID:  T = Context.UnsignedLongLongTy; break;
05904     case PREDEF_TYPE_UINT128_ID:    T = Context.UnsignedInt128Ty;   break;
05905     case PREDEF_TYPE_SCHAR_ID:      T = Context.SignedCharTy;       break;
05906     case PREDEF_TYPE_WCHAR_ID:      T = Context.WCharTy;            break;
05907     case PREDEF_TYPE_SHORT_ID:      T = Context.ShortTy;            break;
05908     case PREDEF_TYPE_INT_ID:        T = Context.IntTy;              break;
05909     case PREDEF_TYPE_LONG_ID:       T = Context.LongTy;             break;
05910     case PREDEF_TYPE_LONGLONG_ID:   T = Context.LongLongTy;         break;
05911     case PREDEF_TYPE_INT128_ID:     T = Context.Int128Ty;           break;
05912     case PREDEF_TYPE_HALF_ID:       T = Context.HalfTy;             break;
05913     case PREDEF_TYPE_FLOAT_ID:      T = Context.FloatTy;            break;
05914     case PREDEF_TYPE_DOUBLE_ID:     T = Context.DoubleTy;           break;
05915     case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy;       break;
05916     case PREDEF_TYPE_OVERLOAD_ID:   T = Context.OverloadTy;         break;
05917     case PREDEF_TYPE_BOUND_MEMBER:  T = Context.BoundMemberTy;      break;
05918     case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy;     break;
05919     case PREDEF_TYPE_DEPENDENT_ID:  T = Context.DependentTy;        break;
05920     case PREDEF_TYPE_UNKNOWN_ANY:   T = Context.UnknownAnyTy;       break;
05921     case PREDEF_TYPE_NULLPTR_ID:    T = Context.NullPtrTy;          break;
05922     case PREDEF_TYPE_CHAR16_ID:     T = Context.Char16Ty;           break;
05923     case PREDEF_TYPE_CHAR32_ID:     T = Context.Char32Ty;           break;
05924     case PREDEF_TYPE_OBJC_ID:       T = Context.ObjCBuiltinIdTy;    break;
05925     case PREDEF_TYPE_OBJC_CLASS:    T = Context.ObjCBuiltinClassTy; break;
05926     case PREDEF_TYPE_OBJC_SEL:      T = Context.ObjCBuiltinSelTy;   break;
05927     case PREDEF_TYPE_IMAGE1D_ID:    T = Context.OCLImage1dTy;       break;
05928     case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
05929     case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
05930     case PREDEF_TYPE_IMAGE2D_ID:    T = Context.OCLImage2dTy;       break;
05931     case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
05932     case PREDEF_TYPE_IMAGE3D_ID:    T = Context.OCLImage3dTy;       break;
05933     case PREDEF_TYPE_SAMPLER_ID:    T = Context.OCLSamplerTy;       break;
05934     case PREDEF_TYPE_EVENT_ID:      T = Context.OCLEventTy;         break;
05935     case PREDEF_TYPE_AUTO_DEDUCT:   T = Context.getAutoDeductType(); break;
05936         
05937     case PREDEF_TYPE_AUTO_RREF_DEDUCT: 
05938       T = Context.getAutoRRefDeductType(); 
05939       break;
05940 
05941     case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
05942       T = Context.ARCUnbridgedCastTy;
05943       break;
05944 
05945     case PREDEF_TYPE_VA_LIST_TAG:
05946       T = Context.getVaListTagType();
05947       break;
05948 
05949     case PREDEF_TYPE_BUILTIN_FN:
05950       T = Context.BuiltinFnTy;
05951       break;
05952     }
05953 
05954     assert(!T.isNull() && "Unknown predefined type");
05955     return T.withFastQualifiers(FastQuals);
05956   }
05957 
05958   Index -= NUM_PREDEF_TYPE_IDS;
05959   assert(Index < TypesLoaded.size() && "Type index out-of-range");
05960   if (TypesLoaded[Index].isNull()) {
05961     TypesLoaded[Index] = readTypeRecord(Index);
05962     if (TypesLoaded[Index].isNull())
05963       return QualType();
05964 
05965     TypesLoaded[Index]->setFromAST();
05966     if (DeserializationListener)
05967       DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
05968                                         TypesLoaded[Index]);
05969   }
05970 
05971   return TypesLoaded[Index].withFastQualifiers(FastQuals);
05972 }
05973 
05974 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
05975   return GetType(getGlobalTypeID(F, LocalID));
05976 }
05977 
05978 serialization::TypeID 
05979 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
05980   unsigned FastQuals = LocalID & Qualifiers::FastMask;
05981   unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
05982   
05983   if (LocalIndex < NUM_PREDEF_TYPE_IDS)
05984     return LocalID;
05985 
05986   ContinuousRangeMap<uint32_t, int, 2>::iterator I
05987     = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
05988   assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
05989   
05990   unsigned GlobalIndex = LocalIndex + I->second;
05991   return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
05992 }
05993 
05994 TemplateArgumentLocInfo
05995 ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
05996                                       TemplateArgument::ArgKind Kind,
05997                                       const RecordData &Record,
05998                                       unsigned &Index) {
05999   switch (Kind) {
06000   case TemplateArgument::Expression:
06001     return ReadExpr(F);
06002   case TemplateArgument::Type:
06003     return GetTypeSourceInfo(F, Record, Index);
06004   case TemplateArgument::Template: {
06005     NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, 
06006                                                                      Index);
06007     SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
06008     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
06009                                    SourceLocation());
06010   }
06011   case TemplateArgument::TemplateExpansion: {
06012     NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, 
06013                                                                      Index);
06014     SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
06015     SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
06016     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc, 
06017                                    EllipsisLoc);
06018   }
06019   case TemplateArgument::Null:
06020   case TemplateArgument::Integral:
06021   case TemplateArgument::Declaration:
06022   case TemplateArgument::NullPtr:
06023   case TemplateArgument::Pack:
06024     // FIXME: Is this right?
06025     return TemplateArgumentLocInfo();
06026   }
06027   llvm_unreachable("unexpected template argument loc");
06028 }
06029 
06030 TemplateArgumentLoc
06031 ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
06032                                    const RecordData &Record, unsigned &Index) {
06033   TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
06034 
06035   if (Arg.getKind() == TemplateArgument::Expression) {
06036     if (Record[Index++]) // bool InfoHasSameExpr.
06037       return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
06038   }
06039   return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
06040                                                              Record, Index));
06041 }
06042 
06043 const ASTTemplateArgumentListInfo*
06044 ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
06045                                            const RecordData &Record,
06046                                            unsigned &Index) {
06047   SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
06048   SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
06049   unsigned NumArgsAsWritten = Record[Index++];
06050   TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
06051   for (unsigned i = 0; i != NumArgsAsWritten; ++i)
06052     TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
06053   return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
06054 }
06055 
06056 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
06057   return GetDecl(ID);
06058 }
06059 
06060 void ASTReader::CompleteRedeclChain(const Decl *D) {
06061   if (NumCurrentElementsDeserializing) {
06062     // We arrange to not care about the complete redeclaration chain while we're
06063     // deserializing. Just remember that the AST has marked this one as complete
06064     // but that it's not actually complete yet, so we know we still need to
06065     // complete it later.
06066     PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
06067     return;
06068   }
06069 
06070   const DeclContext *DC = D->getDeclContext()->getRedeclContext();
06071 
06072   // If this is a named declaration, complete it by looking it up
06073   // within its context.
06074   //
06075   // FIXME: Merging a function definition should merge
06076   // all mergeable entities within it.
06077   if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
06078       isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
06079     if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
06080       auto *II = Name.getAsIdentifierInfo();
06081       if (isa<TranslationUnitDecl>(DC) && II) {
06082         // Outside of C++, we don't have a lookup table for the TU, so update
06083         // the identifier instead. In C++, either way should work fine.
06084         if (II->isOutOfDate())
06085           updateOutOfDateIdentifier(*II);
06086       } else
06087         DC->lookup(Name);
06088     } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
06089       // FIXME: It'd be nice to do something a bit more targeted here.
06090       D->getDeclContext()->decls_begin();
06091     }
06092   }
06093 }
06094 
06095 uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
06096                                           const RecordData &Record,
06097                                           unsigned &Idx) {
06098   if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
06099     Error("malformed AST file: missing C++ base specifier");
06100     return 0;
06101   }
06102 
06103   unsigned LocalID = Record[Idx++];
06104   return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
06105 }
06106 
06107 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
06108   RecordLocation Loc = getLocalBitOffset(Offset);
06109   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
06110   SavedStreamPosition SavedPosition(Cursor);
06111   Cursor.JumpToBit(Loc.Offset);
06112   ReadingKindTracker ReadingKind(Read_Decl, *this);
06113   RecordData Record;
06114   unsigned Code = Cursor.ReadCode();
06115   unsigned RecCode = Cursor.readRecord(Code, Record);
06116   if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
06117     Error("malformed AST file: missing C++ base specifiers");
06118     return nullptr;
06119   }
06120 
06121   unsigned Idx = 0;
06122   unsigned NumBases = Record[Idx++];
06123   void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
06124   CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
06125   for (unsigned I = 0; I != NumBases; ++I)
06126     Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
06127   return Bases;
06128 }
06129 
06130 serialization::DeclID 
06131 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
06132   if (LocalID < NUM_PREDEF_DECL_IDS)
06133     return LocalID;
06134 
06135   ContinuousRangeMap<uint32_t, int, 2>::iterator I
06136     = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
06137   assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
06138   
06139   return LocalID + I->second;
06140 }
06141 
06142 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
06143                                    ModuleFile &M) const {
06144   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
06145   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
06146   return &M == I->second;
06147 }
06148 
06149 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
06150   if (!D->isFromASTFile())
06151     return nullptr;
06152   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
06153   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
06154   return I->second;
06155 }
06156 
06157 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
06158   if (ID < NUM_PREDEF_DECL_IDS)
06159     return SourceLocation();
06160 
06161   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
06162 
06163   if (Index > DeclsLoaded.size()) {
06164     Error("declaration ID out-of-range for AST file");
06165     return SourceLocation();
06166   }
06167 
06168   if (Decl *D = DeclsLoaded[Index])
06169     return D->getLocation();
06170 
06171   unsigned RawLocation = 0;
06172   RecordLocation Rec = DeclCursorForID(ID, RawLocation);
06173   return ReadSourceLocation(*Rec.F, RawLocation);
06174 }
06175 
06176 Decl *ASTReader::GetExistingDecl(DeclID ID) {
06177   if (ID < NUM_PREDEF_DECL_IDS) {
06178     switch ((PredefinedDeclIDs)ID) {
06179     case PREDEF_DECL_NULL_ID:
06180       return nullptr;
06181 
06182     case PREDEF_DECL_TRANSLATION_UNIT_ID:
06183       return Context.getTranslationUnitDecl();
06184 
06185     case PREDEF_DECL_OBJC_ID_ID:
06186       return Context.getObjCIdDecl();
06187 
06188     case PREDEF_DECL_OBJC_SEL_ID:
06189       return Context.getObjCSelDecl();
06190 
06191     case PREDEF_DECL_OBJC_CLASS_ID:
06192       return Context.getObjCClassDecl();
06193 
06194     case PREDEF_DECL_OBJC_PROTOCOL_ID:
06195       return Context.getObjCProtocolDecl();
06196 
06197     case PREDEF_DECL_INT_128_ID:
06198       return Context.getInt128Decl();
06199 
06200     case PREDEF_DECL_UNSIGNED_INT_128_ID:
06201       return Context.getUInt128Decl();
06202 
06203     case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
06204       return Context.getObjCInstanceTypeDecl();
06205 
06206     case PREDEF_DECL_BUILTIN_VA_LIST_ID:
06207       return Context.getBuiltinVaListDecl();
06208     }
06209   }
06210 
06211   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
06212 
06213   if (Index >= DeclsLoaded.size()) {
06214     assert(0 && "declaration ID out-of-range for AST file");
06215     Error("declaration ID out-of-range for AST file");
06216     return nullptr;
06217   }
06218 
06219   return DeclsLoaded[Index];
06220 }
06221 
06222 Decl *ASTReader::GetDecl(DeclID ID) {
06223   if (ID < NUM_PREDEF_DECL_IDS)
06224     return GetExistingDecl(ID);
06225 
06226   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
06227 
06228   if (Index >= DeclsLoaded.size()) {
06229     assert(0 && "declaration ID out-of-range for AST file");
06230     Error("declaration ID out-of-range for AST file");
06231     return nullptr;
06232   }
06233 
06234   if (!DeclsLoaded[Index]) {
06235     ReadDeclRecord(ID);
06236     if (DeserializationListener)
06237       DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
06238   }
06239 
06240   return DeclsLoaded[Index];
06241 }
06242 
06243 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M, 
06244                                                   DeclID GlobalID) {
06245   if (GlobalID < NUM_PREDEF_DECL_IDS)
06246     return GlobalID;
06247   
06248   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
06249   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
06250   ModuleFile *Owner = I->second;
06251 
06252   llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
06253     = M.GlobalToLocalDeclIDs.find(Owner);
06254   if (Pos == M.GlobalToLocalDeclIDs.end())
06255     return 0;
06256       
06257   return GlobalID - Owner->BaseDeclID + Pos->second;
06258 }
06259 
06260 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F, 
06261                                             const RecordData &Record,
06262                                             unsigned &Idx) {
06263   if (Idx >= Record.size()) {
06264     Error("Corrupted AST file");
06265     return 0;
06266   }
06267   
06268   return getGlobalDeclID(F, Record[Idx++]);
06269 }
06270 
06271 /// \brief Resolve the offset of a statement into a statement.
06272 ///
06273 /// This operation will read a new statement from the external
06274 /// source each time it is called, and is meant to be used via a
06275 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
06276 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
06277   // Switch case IDs are per Decl.
06278   ClearSwitchCaseIDs();
06279 
06280   // Offset here is a global offset across the entire chain.
06281   RecordLocation Loc = getLocalBitOffset(Offset);
06282   Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
06283   return ReadStmtFromStream(*Loc.F);
06284 }
06285 
06286 namespace {
06287   class FindExternalLexicalDeclsVisitor {
06288     ASTReader &Reader;
06289     const DeclContext *DC;
06290     bool (*isKindWeWant)(Decl::Kind);
06291     
06292     SmallVectorImpl<Decl*> &Decls;
06293     bool PredefsVisited[NUM_PREDEF_DECL_IDS];
06294 
06295   public:
06296     FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
06297                                     bool (*isKindWeWant)(Decl::Kind),
06298                                     SmallVectorImpl<Decl*> &Decls)
06299       : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls) 
06300     {
06301       for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
06302         PredefsVisited[I] = false;
06303     }
06304 
06305     static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
06306       if (Preorder)
06307         return false;
06308 
06309       FindExternalLexicalDeclsVisitor *This
06310         = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
06311 
06312       ModuleFile::DeclContextInfosMap::iterator Info
06313         = M.DeclContextInfos.find(This->DC);
06314       if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
06315         return false;
06316 
06317       // Load all of the declaration IDs
06318       for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
06319                                *IDE = ID + Info->second.NumLexicalDecls; 
06320            ID != IDE; ++ID) {
06321         if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
06322           continue;
06323 
06324         // Don't add predefined declarations to the lexical context more
06325         // than once.
06326         if (ID->second < NUM_PREDEF_DECL_IDS) {
06327           if (This->PredefsVisited[ID->second])
06328             continue;
06329 
06330           This->PredefsVisited[ID->second] = true;
06331         }
06332 
06333         if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
06334           if (!This->DC->isDeclInLexicalTraversal(D))
06335             This->Decls.push_back(D);
06336         }
06337       }
06338 
06339       return false;
06340     }
06341   };
06342 }
06343 
06344 ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
06345                                          bool (*isKindWeWant)(Decl::Kind),
06346                                          SmallVectorImpl<Decl*> &Decls) {
06347   // There might be lexical decls in multiple modules, for the TU at
06348   // least. Walk all of the modules in the order they were loaded.
06349   FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
06350   ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
06351   ++NumLexicalDeclContextsRead;
06352   return ELR_Success;
06353 }
06354 
06355 namespace {
06356 
06357 class DeclIDComp {
06358   ASTReader &Reader;
06359   ModuleFile &Mod;
06360 
06361 public:
06362   DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
06363 
06364   bool operator()(LocalDeclID L, LocalDeclID R) const {
06365     SourceLocation LHS = getLocation(L);
06366     SourceLocation RHS = getLocation(R);
06367     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
06368   }
06369 
06370   bool operator()(SourceLocation LHS, LocalDeclID R) const {
06371     SourceLocation RHS = getLocation(R);
06372     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
06373   }
06374 
06375   bool operator()(LocalDeclID L, SourceLocation RHS) const {
06376     SourceLocation LHS = getLocation(L);
06377     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
06378   }
06379 
06380   SourceLocation getLocation(LocalDeclID ID) const {
06381     return Reader.getSourceManager().getFileLoc(
06382             Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
06383   }
06384 };
06385 
06386 }
06387 
06388 void ASTReader::FindFileRegionDecls(FileID File,
06389                                     unsigned Offset, unsigned Length,
06390                                     SmallVectorImpl<Decl *> &Decls) {
06391   SourceManager &SM = getSourceManager();
06392 
06393   llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
06394   if (I == FileDeclIDs.end())
06395     return;
06396 
06397   FileDeclsInfo &DInfo = I->second;
06398   if (DInfo.Decls.empty())
06399     return;
06400 
06401   SourceLocation
06402     BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
06403   SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
06404 
06405   DeclIDComp DIDComp(*this, *DInfo.Mod);
06406   ArrayRef<serialization::LocalDeclID>::iterator
06407     BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
06408                                BeginLoc, DIDComp);
06409   if (BeginIt != DInfo.Decls.begin())
06410     --BeginIt;
06411 
06412   // If we are pointing at a top-level decl inside an objc container, we need
06413   // to backtrack until we find it otherwise we will fail to report that the
06414   // region overlaps with an objc container.
06415   while (BeginIt != DInfo.Decls.begin() &&
06416          GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
06417              ->isTopLevelDeclInObjCContainer())
06418     --BeginIt;
06419 
06420   ArrayRef<serialization::LocalDeclID>::iterator
06421     EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
06422                              EndLoc, DIDComp);
06423   if (EndIt != DInfo.Decls.end())
06424     ++EndIt;
06425   
06426   for (ArrayRef<serialization::LocalDeclID>::iterator
06427          DIt = BeginIt; DIt != EndIt; ++DIt)
06428     Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
06429 }
06430 
06431 namespace {
06432   /// \brief ModuleFile visitor used to perform name lookup into a
06433   /// declaration context.
06434   class DeclContextNameLookupVisitor {
06435     ASTReader &Reader;
06436     ArrayRef<const DeclContext *> Contexts;
06437     DeclarationName Name;
06438     SmallVectorImpl<NamedDecl *> &Decls;
06439 
06440   public:
06441     DeclContextNameLookupVisitor(ASTReader &Reader,
06442                                  ArrayRef<const DeclContext *> Contexts,
06443                                  DeclarationName Name,
06444                                  SmallVectorImpl<NamedDecl *> &Decls)
06445       : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
06446 
06447     static bool visit(ModuleFile &M, void *UserData) {
06448       DeclContextNameLookupVisitor *This
06449         = static_cast<DeclContextNameLookupVisitor *>(UserData);
06450 
06451       // Check whether we have any visible declaration information for
06452       // this context in this module.
06453       ModuleFile::DeclContextInfosMap::iterator Info;
06454       bool FoundInfo = false;
06455       for (auto *DC : This->Contexts) {
06456         Info = M.DeclContextInfos.find(DC);
06457         if (Info != M.DeclContextInfos.end() &&
06458             Info->second.NameLookupTableData) {
06459           FoundInfo = true;
06460           break;
06461         }
06462       }
06463 
06464       if (!FoundInfo)
06465         return false;
06466 
06467       // Look for this name within this module.
06468       ASTDeclContextNameLookupTable *LookupTable =
06469         Info->second.NameLookupTableData;
06470       ASTDeclContextNameLookupTable::iterator Pos
06471         = LookupTable->find(This->Name);
06472       if (Pos == LookupTable->end())
06473         return false;
06474 
06475       bool FoundAnything = false;
06476       ASTDeclContextNameLookupTrait::data_type Data = *Pos;
06477       for (; Data.first != Data.second; ++Data.first) {
06478         NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
06479         if (!ND)
06480           continue;
06481 
06482         if (ND->getDeclName() != This->Name) {
06483           // A name might be null because the decl's redeclarable part is
06484           // currently read before reading its name. The lookup is triggered by
06485           // building that decl (likely indirectly), and so it is later in the
06486           // sense of "already existing" and can be ignored here.
06487           // FIXME: This should not happen; deserializing declarations should
06488           // not perform lookups since that can lead to deserialization cycles.
06489           continue;
06490         }
06491 
06492         // Record this declaration.
06493         FoundAnything = true;
06494         This->Decls.push_back(ND);
06495       }
06496 
06497       return FoundAnything;
06498     }
06499   };
06500 }
06501 
06502 /// \brief Retrieve the "definitive" module file for the definition of the
06503 /// given declaration context, if there is one.
06504 ///
06505 /// The "definitive" module file is the only place where we need to look to
06506 /// find information about the declarations within the given declaration
06507 /// context. For example, C++ and Objective-C classes, C structs/unions, and
06508 /// Objective-C protocols, categories, and extensions are all defined in a
06509 /// single place in the source code, so they have definitive module files
06510 /// associated with them. C++ namespaces, on the other hand, can have
06511 /// definitions in multiple different module files.
06512 ///
06513 /// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
06514 /// NDEBUG checking.
06515 static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
06516                                               ASTReader &Reader) {
06517   if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
06518     return Reader.getOwningModuleFile(cast<Decl>(DefDC));
06519 
06520   return nullptr;
06521 }
06522 
06523 bool
06524 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
06525                                           DeclarationName Name) {
06526   assert(DC->hasExternalVisibleStorage() &&
06527          "DeclContext has no visible decls in storage");
06528   if (!Name)
06529     return false;
06530 
06531   Deserializing LookupResults(this);
06532 
06533   SmallVector<NamedDecl *, 64> Decls;
06534 
06535   // Compute the declaration contexts we need to look into. Multiple such
06536   // declaration contexts occur when two declaration contexts from disjoint
06537   // modules get merged, e.g., when two namespaces with the same name are 
06538   // independently defined in separate modules.
06539   SmallVector<const DeclContext *, 2> Contexts;
06540   Contexts.push_back(DC);
06541 
06542   if (DC->isNamespace()) {
06543     auto Merged = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
06544     if (Merged != MergedDecls.end()) {
06545       for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
06546         Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
06547     }
06548   }
06549 
06550   auto LookUpInContexts = [&](ArrayRef<const DeclContext*> Contexts) {
06551     DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
06552 
06553     // If we can definitively determine which module file to look into,
06554     // only look there. Otherwise, look in all module files.
06555     ModuleFile *Definitive;
06556     if (Contexts.size() == 1 &&
06557         (Definitive = getDefinitiveModuleFileFor(Contexts[0], *this))) {
06558       DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
06559     } else {
06560       ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
06561     }
06562   };
06563 
06564   LookUpInContexts(Contexts);
06565 
06566   // If this might be an implicit special member function, then also search
06567   // all merged definitions of the surrounding class. We need to search them
06568   // individually, because finding an entity in one of them doesn't imply that
06569   // we can't find a different entity in another one.
06570   if (isa<CXXRecordDecl>(DC)) {
06571     auto Kind = Name.getNameKind();
06572     if (Kind == DeclarationName::CXXConstructorName ||
06573         Kind == DeclarationName::CXXDestructorName ||
06574         (Kind == DeclarationName::CXXOperatorName &&
06575          Name.getCXXOverloadedOperator() == OO_Equal)) {
06576       auto Merged = MergedLookups.find(DC);
06577       if (Merged != MergedLookups.end())
06578         for (auto *MergedDC : Merged->second)
06579           LookUpInContexts(MergedDC);
06580     }
06581   }
06582 
06583   ++NumVisibleDeclContextsRead;
06584   SetExternalVisibleDeclsForName(DC, Name, Decls);
06585   return !Decls.empty();
06586 }
06587 
06588 namespace {
06589   /// \brief ModuleFile visitor used to retrieve all visible names in a
06590   /// declaration context.
06591   class DeclContextAllNamesVisitor {
06592     ASTReader &Reader;
06593     SmallVectorImpl<const DeclContext *> &Contexts;
06594     DeclsMap &Decls;
06595     bool VisitAll;
06596 
06597   public:
06598     DeclContextAllNamesVisitor(ASTReader &Reader,
06599                                SmallVectorImpl<const DeclContext *> &Contexts,
06600                                DeclsMap &Decls, bool VisitAll)
06601       : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
06602 
06603     static bool visit(ModuleFile &M, void *UserData) {
06604       DeclContextAllNamesVisitor *This
06605         = static_cast<DeclContextAllNamesVisitor *>(UserData);
06606 
06607       // Check whether we have any visible declaration information for
06608       // this context in this module.
06609       ModuleFile::DeclContextInfosMap::iterator Info;
06610       bool FoundInfo = false;
06611       for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
06612         Info = M.DeclContextInfos.find(This->Contexts[I]);
06613         if (Info != M.DeclContextInfos.end() &&
06614             Info->second.NameLookupTableData) {
06615           FoundInfo = true;
06616           break;
06617         }
06618       }
06619 
06620       if (!FoundInfo)
06621         return false;
06622 
06623       ASTDeclContextNameLookupTable *LookupTable =
06624         Info->second.NameLookupTableData;
06625       bool FoundAnything = false;
06626       for (ASTDeclContextNameLookupTable::data_iterator
06627              I = LookupTable->data_begin(), E = LookupTable->data_end();
06628            I != E;
06629            ++I) {
06630         ASTDeclContextNameLookupTrait::data_type Data = *I;
06631         for (; Data.first != Data.second; ++Data.first) {
06632           NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
06633                                                                  *Data.first);
06634           if (!ND)
06635             continue;
06636 
06637           // Record this declaration.
06638           FoundAnything = true;
06639           This->Decls[ND->getDeclName()].push_back(ND);
06640         }
06641       }
06642 
06643       return FoundAnything && !This->VisitAll;
06644     }
06645   };
06646 }
06647 
06648 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
06649   if (!DC->hasExternalVisibleStorage())
06650     return;
06651   DeclsMap Decls;
06652 
06653   // Compute the declaration contexts we need to look into. Multiple such
06654   // declaration contexts occur when two declaration contexts from disjoint
06655   // modules get merged, e.g., when two namespaces with the same name are
06656   // independently defined in separate modules.
06657   SmallVector<const DeclContext *, 2> Contexts;
06658   Contexts.push_back(DC);
06659 
06660   if (DC->isNamespace()) {
06661     MergedDeclsMap::iterator Merged
06662       = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
06663     if (Merged != MergedDecls.end()) {
06664       for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
06665         Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
06666     }
06667   }
06668 
06669   DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
06670                                      /*VisitAll=*/DC->isFileContext());
06671   ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
06672   ++NumVisibleDeclContextsRead;
06673 
06674   for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
06675     SetExternalVisibleDeclsForName(DC, I->first, I->second);
06676   }
06677   const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
06678 }
06679 
06680 /// \brief Under non-PCH compilation the consumer receives the objc methods
06681 /// before receiving the implementation, and codegen depends on this.
06682 /// We simulate this by deserializing and passing to consumer the methods of the
06683 /// implementation before passing the deserialized implementation decl.
06684 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
06685                                        ASTConsumer *Consumer) {
06686   assert(ImplD && Consumer);
06687 
06688   for (auto *I : ImplD->methods())
06689     Consumer->HandleInterestingDecl(DeclGroupRef(I));
06690 
06691   Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
06692 }
06693 
06694 void ASTReader::PassInterestingDeclsToConsumer() {
06695   assert(Consumer);
06696 
06697   if (PassingDeclsToConsumer)
06698     return;
06699 
06700   // Guard variable to avoid recursively redoing the process of passing
06701   // decls to consumer.
06702   SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
06703                                                    true);
06704 
06705   while (!InterestingDecls.empty()) {
06706     Decl *D = InterestingDecls.front();
06707     InterestingDecls.pop_front();
06708 
06709     PassInterestingDeclToConsumer(D);
06710   }
06711 }
06712 
06713 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
06714   if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
06715     PassObjCImplDeclToConsumer(ImplD, Consumer);
06716   else
06717     Consumer->HandleInterestingDecl(DeclGroupRef(D));
06718 }
06719 
06720 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
06721   this->Consumer = Consumer;
06722 
06723   if (!Consumer)
06724     return;
06725 
06726   for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
06727     // Force deserialization of this decl, which will cause it to be queued for
06728     // passing to the consumer.
06729     GetDecl(EagerlyDeserializedDecls[I]);
06730   }
06731   EagerlyDeserializedDecls.clear();
06732 
06733   PassInterestingDeclsToConsumer();
06734 }
06735 
06736 void ASTReader::PrintStats() {
06737   std::fprintf(stderr, "*** AST File Statistics:\n");
06738 
06739   unsigned NumTypesLoaded
06740     = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
06741                                       QualType());
06742   unsigned NumDeclsLoaded
06743     = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
06744                                       (Decl *)nullptr);
06745   unsigned NumIdentifiersLoaded
06746     = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
06747                                             IdentifiersLoaded.end(),
06748                                             (IdentifierInfo *)nullptr);
06749   unsigned NumMacrosLoaded
06750     = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
06751                                        MacrosLoaded.end(),
06752                                        (MacroInfo *)nullptr);
06753   unsigned NumSelectorsLoaded
06754     = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
06755                                           SelectorsLoaded.end(),
06756                                           Selector());
06757 
06758   if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
06759     std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
06760                  NumSLocEntriesRead, TotalNumSLocEntries,
06761                  ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
06762   if (!TypesLoaded.empty())
06763     std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
06764                  NumTypesLoaded, (unsigned)TypesLoaded.size(),
06765                  ((float)NumTypesLoaded/TypesLoaded.size() * 100));
06766   if (!DeclsLoaded.empty())
06767     std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
06768                  NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
06769                  ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
06770   if (!IdentifiersLoaded.empty())
06771     std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
06772                  NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
06773                  ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
06774   if (!MacrosLoaded.empty())
06775     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
06776                  NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
06777                  ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
06778   if (!SelectorsLoaded.empty())
06779     std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
06780                  NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
06781                  ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
06782   if (TotalNumStatements)
06783     std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
06784                  NumStatementsRead, TotalNumStatements,
06785                  ((float)NumStatementsRead/TotalNumStatements * 100));
06786   if (TotalNumMacros)
06787     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
06788                  NumMacrosRead, TotalNumMacros,
06789                  ((float)NumMacrosRead/TotalNumMacros * 100));
06790   if (TotalLexicalDeclContexts)
06791     std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
06792                  NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
06793                  ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
06794                   * 100));
06795   if (TotalVisibleDeclContexts)
06796     std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
06797                  NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
06798                  ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
06799                   * 100));
06800   if (TotalNumMethodPoolEntries) {
06801     std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
06802                  NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
06803                  ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
06804                   * 100));
06805   }
06806   if (NumMethodPoolLookups) {
06807     std::fprintf(stderr, "  %u/%u method pool lookups succeeded (%f%%)\n",
06808                  NumMethodPoolHits, NumMethodPoolLookups,
06809                  ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
06810   }
06811   if (NumMethodPoolTableLookups) {
06812     std::fprintf(stderr, "  %u/%u method pool table lookups succeeded (%f%%)\n",
06813                  NumMethodPoolTableHits, NumMethodPoolTableLookups,
06814                  ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
06815                   * 100.0));
06816   }
06817 
06818   if (NumIdentifierLookupHits) {
06819     std::fprintf(stderr,
06820                  "  %u / %u identifier table lookups succeeded (%f%%)\n",
06821                  NumIdentifierLookupHits, NumIdentifierLookups,
06822                  (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
06823   }
06824 
06825   if (GlobalIndex) {
06826     std::fprintf(stderr, "\n");
06827     GlobalIndex->printStats();
06828   }
06829   
06830   std::fprintf(stderr, "\n");
06831   dump();
06832   std::fprintf(stderr, "\n");
06833 }
06834 
06835 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
06836 static void 
06837 dumpModuleIDMap(StringRef Name,
06838                 const ContinuousRangeMap<Key, ModuleFile *, 
06839                                          InitialCapacity> &Map) {
06840   if (Map.begin() == Map.end())
06841     return;
06842   
06843   typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
06844   llvm::errs() << Name << ":\n";
06845   for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end(); 
06846        I != IEnd; ++I) {
06847     llvm::errs() << "  " << I->first << " -> " << I->second->FileName
06848       << "\n";
06849   }
06850 }
06851 
06852 void ASTReader::dump() {
06853   llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
06854   dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
06855   dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
06856   dumpModuleIDMap("Global type map", GlobalTypeMap);
06857   dumpModuleIDMap("Global declaration map", GlobalDeclMap);
06858   dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
06859   dumpModuleIDMap("Global macro map", GlobalMacroMap);
06860   dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
06861   dumpModuleIDMap("Global selector map", GlobalSelectorMap);
06862   dumpModuleIDMap("Global preprocessed entity map", 
06863                   GlobalPreprocessedEntityMap);
06864   
06865   llvm::errs() << "\n*** PCH/Modules Loaded:";
06866   for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(), 
06867                                        MEnd = ModuleMgr.end();
06868        M != MEnd; ++M)
06869     (*M)->dump();
06870 }
06871 
06872 /// Return the amount of memory used by memory buffers, breaking down
06873 /// by heap-backed versus mmap'ed memory.
06874 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
06875   for (ModuleConstIterator I = ModuleMgr.begin(),
06876       E = ModuleMgr.end(); I != E; ++I) {
06877     if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
06878       size_t bytes = buf->getBufferSize();
06879       switch (buf->getBufferKind()) {
06880         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
06881           sizes.malloc_bytes += bytes;
06882           break;
06883         case llvm::MemoryBuffer::MemoryBuffer_MMap:
06884           sizes.mmap_bytes += bytes;
06885           break;
06886       }
06887     }
06888   }
06889 }
06890 
06891 void ASTReader::InitializeSema(Sema &S) {
06892   SemaObj = &S;
06893   S.addExternalSource(this);
06894 
06895   // Makes sure any declarations that were deserialized "too early"
06896   // still get added to the identifier's declaration chains.
06897   for (uint64_t ID : PreloadedDeclIDs) {
06898     NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
06899     pushExternalDeclIntoScope(D, D->getDeclName());
06900   }
06901   PreloadedDeclIDs.clear();
06902 
06903   // FIXME: What happens if these are changed by a module import?
06904   if (!FPPragmaOptions.empty()) {
06905     assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
06906     SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
06907   }
06908 
06909   // FIXME: What happens if these are changed by a module import?
06910   if (!OpenCLExtensions.empty()) {
06911     unsigned I = 0;
06912 #define OPENCLEXT(nm)  SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
06913 #include "clang/Basic/OpenCLExtensions.def"
06914 
06915     assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
06916   }
06917 
06918   UpdateSema();
06919 }
06920 
06921 void ASTReader::UpdateSema() {
06922   assert(SemaObj && "no Sema to update");
06923 
06924   // Load the offsets of the declarations that Sema references.
06925   // They will be lazily deserialized when needed.
06926   if (!SemaDeclRefs.empty()) {
06927     assert(SemaDeclRefs.size() % 2 == 0);
06928     for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
06929       if (!SemaObj->StdNamespace)
06930         SemaObj->StdNamespace = SemaDeclRefs[I];
06931       if (!SemaObj->StdBadAlloc)
06932         SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
06933     }
06934     SemaDeclRefs.clear();
06935   }
06936 
06937   // Update the state of 'pragma clang optimize'. Use the same API as if we had
06938   // encountered the pragma in the source.
06939   if(OptimizeOffPragmaLocation.isValid())
06940     SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
06941 }
06942 
06943 IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
06944   // Note that we are loading an identifier.
06945   Deserializing AnIdentifier(this);
06946   StringRef Name(NameStart, NameEnd - NameStart);
06947 
06948   // If there is a global index, look there first to determine which modules
06949   // provably do not have any results for this identifier.
06950   GlobalModuleIndex::HitSet Hits;
06951   GlobalModuleIndex::HitSet *HitsPtr = nullptr;
06952   if (!loadGlobalIndex()) {
06953     if (GlobalIndex->lookupIdentifier(Name, Hits)) {
06954       HitsPtr = &Hits;
06955     }
06956   }
06957   IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
06958                                   NumIdentifierLookups,
06959                                   NumIdentifierLookupHits);
06960   ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
06961   IdentifierInfo *II = Visitor.getIdentifierInfo();
06962   markIdentifierUpToDate(II);
06963   return II;
06964 }
06965 
06966 namespace clang {
06967   /// \brief An identifier-lookup iterator that enumerates all of the
06968   /// identifiers stored within a set of AST files.
06969   class ASTIdentifierIterator : public IdentifierIterator {
06970     /// \brief The AST reader whose identifiers are being enumerated.
06971     const ASTReader &Reader;
06972 
06973     /// \brief The current index into the chain of AST files stored in
06974     /// the AST reader.
06975     unsigned Index;
06976 
06977     /// \brief The current position within the identifier lookup table
06978     /// of the current AST file.
06979     ASTIdentifierLookupTable::key_iterator Current;
06980 
06981     /// \brief The end position within the identifier lookup table of
06982     /// the current AST file.
06983     ASTIdentifierLookupTable::key_iterator End;
06984 
06985   public:
06986     explicit ASTIdentifierIterator(const ASTReader &Reader);
06987 
06988     StringRef Next() override;
06989   };
06990 }
06991 
06992 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
06993   : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
06994   ASTIdentifierLookupTable *IdTable
06995     = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
06996   Current = IdTable->key_begin();
06997   End = IdTable->key_end();
06998 }
06999 
07000 StringRef ASTIdentifierIterator::Next() {
07001   while (Current == End) {
07002     // If we have exhausted all of our AST files, we're done.
07003     if (Index == 0)
07004       return StringRef();
07005 
07006     --Index;
07007     ASTIdentifierLookupTable *IdTable
07008       = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
07009         IdentifierLookupTable;
07010     Current = IdTable->key_begin();
07011     End = IdTable->key_end();
07012   }
07013 
07014   // We have any identifiers remaining in the current AST file; return
07015   // the next one.
07016   StringRef Result = *Current;
07017   ++Current;
07018   return Result;
07019 }
07020 
07021 IdentifierIterator *ASTReader::getIdentifiers() {
07022   if (!loadGlobalIndex())
07023     return GlobalIndex->createIdentifierIterator();
07024 
07025   return new ASTIdentifierIterator(*this);
07026 }
07027 
07028 namespace clang { namespace serialization {
07029   class ReadMethodPoolVisitor {
07030     ASTReader &Reader;
07031     Selector Sel;
07032     unsigned PriorGeneration;
07033     unsigned InstanceBits;
07034     unsigned FactoryBits;
07035     SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
07036     SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
07037 
07038   public:
07039     ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, 
07040                           unsigned PriorGeneration)
07041       : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
07042         InstanceBits(0), FactoryBits(0) { }
07043     
07044     static bool visit(ModuleFile &M, void *UserData) {
07045       ReadMethodPoolVisitor *This
07046         = static_cast<ReadMethodPoolVisitor *>(UserData);
07047       
07048       if (!M.SelectorLookupTable)
07049         return false;
07050       
07051       // If we've already searched this module file, skip it now.
07052       if (M.Generation <= This->PriorGeneration)
07053         return true;
07054 
07055       ++This->Reader.NumMethodPoolTableLookups;
07056       ASTSelectorLookupTable *PoolTable
07057         = (ASTSelectorLookupTable*)M.SelectorLookupTable;
07058       ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
07059       if (Pos == PoolTable->end())
07060         return false;
07061 
07062       ++This->Reader.NumMethodPoolTableHits;
07063       ++This->Reader.NumSelectorsRead;
07064       // FIXME: Not quite happy with the statistics here. We probably should
07065       // disable this tracking when called via LoadSelector.
07066       // Also, should entries without methods count as misses?
07067       ++This->Reader.NumMethodPoolEntriesRead;
07068       ASTSelectorLookupTrait::data_type Data = *Pos;
07069       if (This->Reader.DeserializationListener)
07070         This->Reader.DeserializationListener->SelectorRead(Data.ID, 
07071                                                            This->Sel);
07072       
07073       This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
07074       This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
07075       This->InstanceBits = Data.InstanceBits;
07076       This->FactoryBits = Data.FactoryBits;
07077       return true;
07078     }
07079     
07080     /// \brief Retrieve the instance methods found by this visitor.
07081     ArrayRef<ObjCMethodDecl *> getInstanceMethods() const { 
07082       return InstanceMethods; 
07083     }
07084 
07085     /// \brief Retrieve the instance methods found by this visitor.
07086     ArrayRef<ObjCMethodDecl *> getFactoryMethods() const { 
07087       return FactoryMethods;
07088     }
07089 
07090     unsigned getInstanceBits() const { return InstanceBits; }
07091     unsigned getFactoryBits() const { return FactoryBits; }
07092   };
07093 } } // end namespace clang::serialization
07094 
07095 /// \brief Add the given set of methods to the method list.
07096 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
07097                              ObjCMethodList &List) {
07098   for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
07099     S.addMethodToGlobalList(&List, Methods[I]);
07100   }
07101 }
07102                              
07103 void ASTReader::ReadMethodPool(Selector Sel) {
07104   // Get the selector generation and update it to the current generation.
07105   unsigned &Generation = SelectorGeneration[Sel];
07106   unsigned PriorGeneration = Generation;
07107   Generation = getGeneration();
07108   
07109   // Search for methods defined with this selector.
07110   ++NumMethodPoolLookups;
07111   ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
07112   ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
07113   
07114   if (Visitor.getInstanceMethods().empty() &&
07115       Visitor.getFactoryMethods().empty())
07116     return;
07117 
07118   ++NumMethodPoolHits;
07119 
07120   if (!getSema())
07121     return;
07122   
07123   Sema &S = *getSema();
07124   Sema::GlobalMethodPool::iterator Pos
07125     = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
07126   
07127   addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
07128   addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
07129   Pos->second.first.setBits(Visitor.getInstanceBits());
07130   Pos->second.second.setBits(Visitor.getFactoryBits());
07131 }
07132 
07133 void ASTReader::ReadKnownNamespaces(
07134                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
07135   Namespaces.clear();
07136   
07137   for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
07138     if (NamespaceDecl *Namespace 
07139                 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
07140       Namespaces.push_back(Namespace);
07141   }
07142 }
07143 
07144 void ASTReader::ReadUndefinedButUsed(
07145                         llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
07146   for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
07147     NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
07148     SourceLocation Loc =
07149         SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
07150     Undefined.insert(std::make_pair(D, Loc));
07151   }
07152 }
07153 
07154 void ASTReader::ReadTentativeDefinitions(
07155                   SmallVectorImpl<VarDecl *> &TentativeDefs) {
07156   for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
07157     VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
07158     if (Var)
07159       TentativeDefs.push_back(Var);
07160   }
07161   TentativeDefinitions.clear();
07162 }
07163 
07164 void ASTReader::ReadUnusedFileScopedDecls(
07165                                SmallVectorImpl<const DeclaratorDecl *> &Decls) {
07166   for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
07167     DeclaratorDecl *D
07168       = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
07169     if (D)
07170       Decls.push_back(D);
07171   }
07172   UnusedFileScopedDecls.clear();
07173 }
07174 
07175 void ASTReader::ReadDelegatingConstructors(
07176                                  SmallVectorImpl<CXXConstructorDecl *> &Decls) {
07177   for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
07178     CXXConstructorDecl *D
07179       = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
07180     if (D)
07181       Decls.push_back(D);
07182   }
07183   DelegatingCtorDecls.clear();
07184 }
07185 
07186 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
07187   for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
07188     TypedefNameDecl *D
07189       = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
07190     if (D)
07191       Decls.push_back(D);
07192   }
07193   ExtVectorDecls.clear();
07194 }
07195 
07196 void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
07197   for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
07198     CXXRecordDecl *D
07199       = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
07200     if (D)
07201       Decls.push_back(D);
07202   }
07203   DynamicClasses.clear();
07204 }
07205 
07206 void ASTReader::ReadUnusedLocalTypedefNameCandidates(
07207     llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
07208   for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
07209        ++I) {
07210     TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
07211         GetDecl(UnusedLocalTypedefNameCandidates[I]));
07212     if (D)
07213       Decls.insert(D);
07214   }
07215   UnusedLocalTypedefNameCandidates.clear();
07216 }
07217 
07218 void 
07219 ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
07220   for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
07221     NamedDecl *D
07222       = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
07223     if (D)
07224       Decls.push_back(D);
07225   }
07226   LocallyScopedExternCDecls.clear();
07227 }
07228 
07229 void ASTReader::ReadReferencedSelectors(
07230        SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
07231   if (ReferencedSelectorsData.empty())
07232     return;
07233   
07234   // If there are @selector references added them to its pool. This is for
07235   // implementation of -Wselector.
07236   unsigned int DataSize = ReferencedSelectorsData.size()-1;
07237   unsigned I = 0;
07238   while (I < DataSize) {
07239     Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
07240     SourceLocation SelLoc
07241       = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
07242     Sels.push_back(std::make_pair(Sel, SelLoc));
07243   }
07244   ReferencedSelectorsData.clear();
07245 }
07246 
07247 void ASTReader::ReadWeakUndeclaredIdentifiers(
07248        SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
07249   if (WeakUndeclaredIdentifiers.empty())
07250     return;
07251 
07252   for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
07253     IdentifierInfo *WeakId 
07254       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
07255     IdentifierInfo *AliasId 
07256       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
07257     SourceLocation Loc
07258       = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
07259     bool Used = WeakUndeclaredIdentifiers[I++];
07260     WeakInfo WI(AliasId, Loc);
07261     WI.setUsed(Used);
07262     WeakIDs.push_back(std::make_pair(WeakId, WI));
07263   }
07264   WeakUndeclaredIdentifiers.clear();
07265 }
07266 
07267 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
07268   for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
07269     ExternalVTableUse VT;
07270     VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
07271     VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
07272     VT.DefinitionRequired = VTableUses[Idx++];
07273     VTables.push_back(VT);
07274   }
07275   
07276   VTableUses.clear();
07277 }
07278 
07279 void ASTReader::ReadPendingInstantiations(
07280        SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
07281   for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
07282     ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
07283     SourceLocation Loc
07284       = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
07285 
07286     Pending.push_back(std::make_pair(D, Loc));
07287   }  
07288   PendingInstantiations.clear();
07289 }
07290 
07291 void ASTReader::ReadLateParsedTemplates(
07292     llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
07293   for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
07294        /* In loop */) {
07295     FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
07296 
07297     LateParsedTemplate *LT = new LateParsedTemplate;
07298     LT->D = GetDecl(LateParsedTemplates[Idx++]);
07299 
07300     ModuleFile *F = getOwningModuleFile(LT->D);
07301     assert(F && "No module");
07302 
07303     unsigned TokN = LateParsedTemplates[Idx++];
07304     LT->Toks.reserve(TokN);
07305     for (unsigned T = 0; T < TokN; ++T)
07306       LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
07307 
07308     LPTMap[FD] = LT;
07309   }
07310 
07311   LateParsedTemplates.clear();
07312 }
07313 
07314 void ASTReader::LoadSelector(Selector Sel) {
07315   // It would be complicated to avoid reading the methods anyway. So don't.
07316   ReadMethodPool(Sel);
07317 }
07318 
07319 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
07320   assert(ID && "Non-zero identifier ID required");
07321   assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
07322   IdentifiersLoaded[ID - 1] = II;
07323   if (DeserializationListener)
07324     DeserializationListener->IdentifierRead(ID, II);
07325 }
07326 
07327 /// \brief Set the globally-visible declarations associated with the given
07328 /// identifier.
07329 ///
07330 /// If the AST reader is currently in a state where the given declaration IDs
07331 /// cannot safely be resolved, they are queued until it is safe to resolve
07332 /// them.
07333 ///
07334 /// \param II an IdentifierInfo that refers to one or more globally-visible
07335 /// declarations.
07336 ///
07337 /// \param DeclIDs the set of declaration IDs with the name @p II that are
07338 /// visible at global scope.
07339 ///
07340 /// \param Decls if non-null, this vector will be populated with the set of
07341 /// deserialized declarations. These declarations will not be pushed into
07342 /// scope.
07343 void
07344 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
07345                               const SmallVectorImpl<uint32_t> &DeclIDs,
07346                                    SmallVectorImpl<Decl *> *Decls) {
07347   if (NumCurrentElementsDeserializing && !Decls) {
07348     PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
07349     return;
07350   }
07351 
07352   for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
07353     if (!SemaObj) {
07354       // Queue this declaration so that it will be added to the
07355       // translation unit scope and identifier's declaration chain
07356       // once a Sema object is known.
07357       PreloadedDeclIDs.push_back(DeclIDs[I]);
07358       continue;
07359     }
07360 
07361     NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
07362 
07363     // If we're simply supposed to record the declarations, do so now.
07364     if (Decls) {
07365       Decls->push_back(D);
07366       continue;
07367     }
07368 
07369     // Introduce this declaration into the translation-unit scope
07370     // and add it to the declaration chain for this identifier, so
07371     // that (unqualified) name lookup will find it.
07372     pushExternalDeclIntoScope(D, II);
07373   }
07374 }
07375 
07376 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
07377   if (ID == 0)
07378     return nullptr;
07379 
07380   if (IdentifiersLoaded.empty()) {
07381     Error("no identifier table in AST file");
07382     return nullptr;
07383   }
07384 
07385   ID -= 1;
07386   if (!IdentifiersLoaded[ID]) {
07387     GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
07388     assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
07389     ModuleFile *M = I->second;
07390     unsigned Index = ID - M->BaseIdentifierID;
07391     const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
07392 
07393     // All of the strings in the AST file are preceded by a 16-bit length.
07394     // Extract that 16-bit length to avoid having to execute strlen().
07395     // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
07396     //  unsigned integers.  This is important to avoid integer overflow when
07397     //  we cast them to 'unsigned'.
07398     const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
07399     unsigned StrLen = (((unsigned) StrLenPtr[0])
07400                        | (((unsigned) StrLenPtr[1]) << 8)) - 1;
07401     IdentifiersLoaded[ID]
07402       = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
07403     if (DeserializationListener)
07404       DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
07405   }
07406 
07407   return IdentifiersLoaded[ID];
07408 }
07409 
07410 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
07411   return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
07412 }
07413 
07414 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
07415   if (LocalID < NUM_PREDEF_IDENT_IDS)
07416     return LocalID;
07417   
07418   ContinuousRangeMap<uint32_t, int, 2>::iterator I
07419     = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
07420   assert(I != M.IdentifierRemap.end() 
07421          && "Invalid index into identifier index remap");
07422   
07423   return LocalID + I->second;
07424 }
07425 
07426 MacroInfo *ASTReader::getMacro(MacroID ID) {
07427   if (ID == 0)
07428     return nullptr;
07429 
07430   if (MacrosLoaded.empty()) {
07431     Error("no macro table in AST file");
07432     return nullptr;
07433   }
07434 
07435   ID -= NUM_PREDEF_MACRO_IDS;
07436   if (!MacrosLoaded[ID]) {
07437     GlobalMacroMapType::iterator I
07438       = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
07439     assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
07440     ModuleFile *M = I->second;
07441     unsigned Index = ID - M->BaseMacroID;
07442     MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
07443     
07444     if (DeserializationListener)
07445       DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
07446                                          MacrosLoaded[ID]);
07447   }
07448 
07449   return MacrosLoaded[ID];
07450 }
07451 
07452 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
07453   if (LocalID < NUM_PREDEF_MACRO_IDS)
07454     return LocalID;
07455 
07456   ContinuousRangeMap<uint32_t, int, 2>::iterator I
07457     = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
07458   assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
07459 
07460   return LocalID + I->second;
07461 }
07462 
07463 serialization::SubmoduleID
07464 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
07465   if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
07466     return LocalID;
07467   
07468   ContinuousRangeMap<uint32_t, int, 2>::iterator I
07469     = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
07470   assert(I != M.SubmoduleRemap.end() 
07471          && "Invalid index into submodule index remap");
07472   
07473   return LocalID + I->second;
07474 }
07475 
07476 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
07477   if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
07478     assert(GlobalID == 0 && "Unhandled global submodule ID");
07479     return nullptr;
07480   }
07481   
07482   if (GlobalID > SubmodulesLoaded.size()) {
07483     Error("submodule ID out of range in AST file");
07484     return nullptr;
07485   }
07486   
07487   return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
07488 }
07489 
07490 Module *ASTReader::getModule(unsigned ID) {
07491   return getSubmodule(ID);
07492 }
07493 
07494 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
07495   return DecodeSelector(getGlobalSelectorID(M, LocalID));
07496 }
07497 
07498 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
07499   if (ID == 0)
07500     return Selector();
07501 
07502   if (ID > SelectorsLoaded.size()) {
07503     Error("selector ID out of range in AST file");
07504     return Selector();
07505   }
07506 
07507   if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
07508     // Load this selector from the selector table.
07509     GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
07510     assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
07511     ModuleFile &M = *I->second;
07512     ASTSelectorLookupTrait Trait(*this, M);
07513     unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
07514     SelectorsLoaded[ID - 1] =
07515       Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
07516     if (DeserializationListener)
07517       DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
07518   }
07519 
07520   return SelectorsLoaded[ID - 1];
07521 }
07522 
07523 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
07524   return DecodeSelector(ID);
07525 }
07526 
07527 uint32_t ASTReader::GetNumExternalSelectors() {
07528   // ID 0 (the null selector) is considered an external selector.
07529   return getTotalNumSelectors() + 1;
07530 }
07531 
07532 serialization::SelectorID
07533 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
07534   if (LocalID < NUM_PREDEF_SELECTOR_IDS)
07535     return LocalID;
07536   
07537   ContinuousRangeMap<uint32_t, int, 2>::iterator I
07538     = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
07539   assert(I != M.SelectorRemap.end() 
07540          && "Invalid index into selector index remap");
07541   
07542   return LocalID + I->second;
07543 }
07544 
07545 DeclarationName
07546 ASTReader::ReadDeclarationName(ModuleFile &F, 
07547                                const RecordData &Record, unsigned &Idx) {
07548   DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
07549   switch (Kind) {
07550   case DeclarationName::Identifier:
07551     return DeclarationName(GetIdentifierInfo(F, Record, Idx));
07552 
07553   case DeclarationName::ObjCZeroArgSelector:
07554   case DeclarationName::ObjCOneArgSelector:
07555   case DeclarationName::ObjCMultiArgSelector:
07556     return DeclarationName(ReadSelector(F, Record, Idx));
07557 
07558   case DeclarationName::CXXConstructorName:
07559     return Context.DeclarationNames.getCXXConstructorName(
07560                           Context.getCanonicalType(readType(F, Record, Idx)));
07561 
07562   case DeclarationName::CXXDestructorName:
07563     return Context.DeclarationNames.getCXXDestructorName(
07564                           Context.getCanonicalType(readType(F, Record, Idx)));
07565 
07566   case DeclarationName::CXXConversionFunctionName:
07567     return Context.DeclarationNames.getCXXConversionFunctionName(
07568                           Context.getCanonicalType(readType(F, Record, Idx)));
07569 
07570   case DeclarationName::CXXOperatorName:
07571     return Context.DeclarationNames.getCXXOperatorName(
07572                                        (OverloadedOperatorKind)Record[Idx++]);
07573 
07574   case DeclarationName::CXXLiteralOperatorName:
07575     return Context.DeclarationNames.getCXXLiteralOperatorName(
07576                                        GetIdentifierInfo(F, Record, Idx));
07577 
07578   case DeclarationName::CXXUsingDirective:
07579     return DeclarationName::getUsingDirectiveName();
07580   }
07581 
07582   llvm_unreachable("Invalid NameKind!");
07583 }
07584 
07585 void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
07586                                        DeclarationNameLoc &DNLoc,
07587                                        DeclarationName Name,
07588                                       const RecordData &Record, unsigned &Idx) {
07589   switch (Name.getNameKind()) {
07590   case DeclarationName::CXXConstructorName:
07591   case DeclarationName::CXXDestructorName:
07592   case DeclarationName::CXXConversionFunctionName:
07593     DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
07594     break;
07595 
07596   case DeclarationName::CXXOperatorName:
07597     DNLoc.CXXOperatorName.BeginOpNameLoc
07598         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
07599     DNLoc.CXXOperatorName.EndOpNameLoc
07600         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
07601     break;
07602 
07603   case DeclarationName::CXXLiteralOperatorName:
07604     DNLoc.CXXLiteralOperatorName.OpNameLoc
07605         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
07606     break;
07607 
07608   case DeclarationName::Identifier:
07609   case DeclarationName::ObjCZeroArgSelector:
07610   case DeclarationName::ObjCOneArgSelector:
07611   case DeclarationName::ObjCMultiArgSelector:
07612   case DeclarationName::CXXUsingDirective:
07613     break;
07614   }
07615 }
07616 
07617 void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
07618                                         DeclarationNameInfo &NameInfo,
07619                                       const RecordData &Record, unsigned &Idx) {
07620   NameInfo.setName(ReadDeclarationName(F, Record, Idx));
07621   NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
07622   DeclarationNameLoc DNLoc;
07623   ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
07624   NameInfo.setInfo(DNLoc);
07625 }
07626 
07627 void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
07628                                   const RecordData &Record, unsigned &Idx) {
07629   Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
07630   unsigned NumTPLists = Record[Idx++];
07631   Info.NumTemplParamLists = NumTPLists;
07632   if (NumTPLists) {
07633     Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
07634     for (unsigned i=0; i != NumTPLists; ++i)
07635       Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
07636   }
07637 }
07638 
07639 TemplateName
07640 ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record, 
07641                             unsigned &Idx) {
07642   TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
07643   switch (Kind) {
07644   case TemplateName::Template:
07645       return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
07646 
07647   case TemplateName::OverloadedTemplate: {
07648     unsigned size = Record[Idx++];
07649     UnresolvedSet<8> Decls;
07650     while (size--)
07651       Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
07652 
07653     return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
07654   }
07655 
07656   case TemplateName::QualifiedTemplate: {
07657     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
07658     bool hasTemplKeyword = Record[Idx++];
07659     TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
07660     return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
07661   }
07662 
07663   case TemplateName::DependentTemplate: {
07664     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
07665     if (Record[Idx++])  // isIdentifier
07666       return Context.getDependentTemplateName(NNS,
07667                                                GetIdentifierInfo(F, Record, 
07668                                                                  Idx));
07669     return Context.getDependentTemplateName(NNS,
07670                                          (OverloadedOperatorKind)Record[Idx++]);
07671   }
07672 
07673   case TemplateName::SubstTemplateTemplateParm: {
07674     TemplateTemplateParmDecl *param
07675       = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
07676     if (!param) return TemplateName();
07677     TemplateName replacement = ReadTemplateName(F, Record, Idx);
07678     return Context.getSubstTemplateTemplateParm(param, replacement);
07679   }
07680       
07681   case TemplateName::SubstTemplateTemplateParmPack: {
07682     TemplateTemplateParmDecl *Param 
07683       = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
07684     if (!Param)
07685       return TemplateName();
07686     
07687     TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
07688     if (ArgPack.getKind() != TemplateArgument::Pack)
07689       return TemplateName();
07690     
07691     return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
07692   }
07693   }
07694 
07695   llvm_unreachable("Unhandled template name kind!");
07696 }
07697 
07698 TemplateArgument
07699 ASTReader::ReadTemplateArgument(ModuleFile &F,
07700                                 const RecordData &Record, unsigned &Idx) {
07701   TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
07702   switch (Kind) {
07703   case TemplateArgument::Null:
07704     return TemplateArgument();
07705   case TemplateArgument::Type:
07706     return TemplateArgument(readType(F, Record, Idx));
07707   case TemplateArgument::Declaration: {
07708     ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
07709     return TemplateArgument(D, readType(F, Record, Idx));
07710   }
07711   case TemplateArgument::NullPtr:
07712     return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
07713   case TemplateArgument::Integral: {
07714     llvm::APSInt Value = ReadAPSInt(Record, Idx);
07715     QualType T = readType(F, Record, Idx);
07716     return TemplateArgument(Context, Value, T);
07717   }
07718   case TemplateArgument::Template: 
07719     return TemplateArgument(ReadTemplateName(F, Record, Idx));
07720   case TemplateArgument::TemplateExpansion: {
07721     TemplateName Name = ReadTemplateName(F, Record, Idx);
07722     Optional<unsigned> NumTemplateExpansions;
07723     if (unsigned NumExpansions = Record[Idx++])
07724       NumTemplateExpansions = NumExpansions - 1;
07725     return TemplateArgument(Name, NumTemplateExpansions);
07726   }
07727   case TemplateArgument::Expression:
07728     return TemplateArgument(ReadExpr(F));
07729   case TemplateArgument::Pack: {
07730     unsigned NumArgs = Record[Idx++];
07731     TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
07732     for (unsigned I = 0; I != NumArgs; ++I)
07733       Args[I] = ReadTemplateArgument(F, Record, Idx);
07734     return TemplateArgument(Args, NumArgs);
07735   }
07736   }
07737 
07738   llvm_unreachable("Unhandled template argument kind!");
07739 }
07740 
07741 TemplateParameterList *
07742 ASTReader::ReadTemplateParameterList(ModuleFile &F,
07743                                      const RecordData &Record, unsigned &Idx) {
07744   SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
07745   SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
07746   SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
07747 
07748   unsigned NumParams = Record[Idx++];
07749   SmallVector<NamedDecl *, 16> Params;
07750   Params.reserve(NumParams);
07751   while (NumParams--)
07752     Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
07753 
07754   TemplateParameterList* TemplateParams =
07755     TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
07756                                   Params.data(), Params.size(), RAngleLoc);
07757   return TemplateParams;
07758 }
07759 
07760 void
07761 ASTReader::
07762 ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
07763                          ModuleFile &F, const RecordData &Record,
07764                          unsigned &Idx) {
07765   unsigned NumTemplateArgs = Record[Idx++];
07766   TemplArgs.reserve(NumTemplateArgs);
07767   while (NumTemplateArgs--)
07768     TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
07769 }
07770 
07771 /// \brief Read a UnresolvedSet structure.
07772 void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
07773                                   const RecordData &Record, unsigned &Idx) {
07774   unsigned NumDecls = Record[Idx++];
07775   Set.reserve(Context, NumDecls);
07776   while (NumDecls--) {
07777     DeclID ID = ReadDeclID(F, Record, Idx);
07778     AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
07779     Set.addLazyDecl(Context, ID, AS);
07780   }
07781 }
07782 
07783 CXXBaseSpecifier
07784 ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
07785                                 const RecordData &Record, unsigned &Idx) {
07786   bool isVirtual = static_cast<bool>(Record[Idx++]);
07787   bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
07788   AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
07789   bool inheritConstructors = static_cast<bool>(Record[Idx++]);
07790   TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
07791   SourceRange Range = ReadSourceRange(F, Record, Idx);
07792   SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
07793   CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo, 
07794                           EllipsisLoc);
07795   Result.setInheritConstructors(inheritConstructors);
07796   return Result;
07797 }
07798 
07799 std::pair<CXXCtorInitializer **, unsigned>
07800 ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
07801                                    unsigned &Idx) {
07802   CXXCtorInitializer **CtorInitializers = nullptr;
07803   unsigned NumInitializers = Record[Idx++];
07804   if (NumInitializers) {
07805     CtorInitializers
07806         = new (Context) CXXCtorInitializer*[NumInitializers];
07807     for (unsigned i=0; i != NumInitializers; ++i) {
07808       TypeSourceInfo *TInfo = nullptr;
07809       bool IsBaseVirtual = false;
07810       FieldDecl *Member = nullptr;
07811       IndirectFieldDecl *IndirectMember = nullptr;
07812 
07813       CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
07814       switch (Type) {
07815       case CTOR_INITIALIZER_BASE:
07816         TInfo = GetTypeSourceInfo(F, Record, Idx);
07817         IsBaseVirtual = Record[Idx++];
07818         break;
07819           
07820       case CTOR_INITIALIZER_DELEGATING:
07821         TInfo = GetTypeSourceInfo(F, Record, Idx);
07822         break;
07823 
07824        case CTOR_INITIALIZER_MEMBER:
07825         Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
07826         break;
07827 
07828        case CTOR_INITIALIZER_INDIRECT_MEMBER:
07829         IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
07830         break;
07831       }
07832 
07833       SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
07834       Expr *Init = ReadExpr(F);
07835       SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
07836       SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
07837       bool IsWritten = Record[Idx++];
07838       unsigned SourceOrderOrNumArrayIndices;
07839       SmallVector<VarDecl *, 8> Indices;
07840       if (IsWritten) {
07841         SourceOrderOrNumArrayIndices = Record[Idx++];
07842       } else {
07843         SourceOrderOrNumArrayIndices = Record[Idx++];
07844         Indices.reserve(SourceOrderOrNumArrayIndices);
07845         for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
07846           Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
07847       }
07848 
07849       CXXCtorInitializer *BOMInit;
07850       if (Type == CTOR_INITIALIZER_BASE) {
07851         BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
07852                                              LParenLoc, Init, RParenLoc,
07853                                              MemberOrEllipsisLoc);
07854       } else if (Type == CTOR_INITIALIZER_DELEGATING) {
07855         BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
07856                                                    Init, RParenLoc);
07857       } else if (IsWritten) {
07858         if (Member)
07859           BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
07860                                                LParenLoc, Init, RParenLoc);
07861         else 
07862           BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
07863                                                MemberOrEllipsisLoc, LParenLoc,
07864                                                Init, RParenLoc);
07865       } else {
07866         if (IndirectMember) {
07867           assert(Indices.empty() && "Indirect field improperly initialized");
07868           BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
07869                                                      MemberOrEllipsisLoc, LParenLoc,
07870                                                      Init, RParenLoc);
07871         } else {
07872           BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
07873                                                LParenLoc, Init, RParenLoc,
07874                                                Indices.data(), Indices.size());
07875         }
07876       }
07877 
07878       if (IsWritten)
07879         BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
07880       CtorInitializers[i] = BOMInit;
07881     }
07882   }
07883 
07884   return std::make_pair(CtorInitializers, NumInitializers);
07885 }
07886 
07887 NestedNameSpecifier *
07888 ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
07889                                    const RecordData &Record, unsigned &Idx) {
07890   unsigned N = Record[Idx++];
07891   NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
07892   for (unsigned I = 0; I != N; ++I) {
07893     NestedNameSpecifier::SpecifierKind Kind
07894       = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
07895     switch (Kind) {
07896     case NestedNameSpecifier::Identifier: {
07897       IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
07898       NNS = NestedNameSpecifier::Create(Context, Prev, II);
07899       break;
07900     }
07901 
07902     case NestedNameSpecifier::Namespace: {
07903       NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
07904       NNS = NestedNameSpecifier::Create(Context, Prev, NS);
07905       break;
07906     }
07907 
07908     case NestedNameSpecifier::NamespaceAlias: {
07909       NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
07910       NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
07911       break;
07912     }
07913 
07914     case NestedNameSpecifier::TypeSpec:
07915     case NestedNameSpecifier::TypeSpecWithTemplate: {
07916       const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
07917       if (!T)
07918         return nullptr;
07919 
07920       bool Template = Record[Idx++];
07921       NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
07922       break;
07923     }
07924 
07925     case NestedNameSpecifier::Global: {
07926       NNS = NestedNameSpecifier::GlobalSpecifier(Context);
07927       // No associated value, and there can't be a prefix.
07928       break;
07929     }
07930 
07931     case NestedNameSpecifier::Super: {
07932       CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
07933       NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
07934       break;
07935     }
07936     }
07937     Prev = NNS;
07938   }
07939   return NNS;
07940 }
07941 
07942 NestedNameSpecifierLoc
07943 ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record, 
07944                                       unsigned &Idx) {
07945   unsigned N = Record[Idx++];
07946   NestedNameSpecifierLocBuilder Builder;
07947   for (unsigned I = 0; I != N; ++I) {
07948     NestedNameSpecifier::SpecifierKind Kind
07949       = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
07950     switch (Kind) {
07951     case NestedNameSpecifier::Identifier: {
07952       IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);      
07953       SourceRange Range = ReadSourceRange(F, Record, Idx);
07954       Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
07955       break;
07956     }
07957 
07958     case NestedNameSpecifier::Namespace: {
07959       NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
07960       SourceRange Range = ReadSourceRange(F, Record, Idx);
07961       Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
07962       break;
07963     }
07964 
07965     case NestedNameSpecifier::NamespaceAlias: {
07966       NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
07967       SourceRange Range = ReadSourceRange(F, Record, Idx);
07968       Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
07969       break;
07970     }
07971 
07972     case NestedNameSpecifier::TypeSpec:
07973     case NestedNameSpecifier::TypeSpecWithTemplate: {
07974       bool Template = Record[Idx++];
07975       TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
07976       if (!T)
07977         return NestedNameSpecifierLoc();
07978       SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
07979 
07980       // FIXME: 'template' keyword location not saved anywhere, so we fake it.
07981       Builder.Extend(Context, 
07982                      Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
07983                      T->getTypeLoc(), ColonColonLoc);
07984       break;
07985     }
07986 
07987     case NestedNameSpecifier::Global: {
07988       SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
07989       Builder.MakeGlobal(Context, ColonColonLoc);
07990       break;
07991     }
07992 
07993     case NestedNameSpecifier::Super: {
07994       CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
07995       SourceRange Range = ReadSourceRange(F, Record, Idx);
07996       Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
07997       break;
07998     }
07999     }
08000   }
08001 
08002   return Builder.getWithLocInContext(Context);
08003 }
08004 
08005 SourceRange
08006 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
08007                            unsigned &Idx) {
08008   SourceLocation beg = ReadSourceLocation(F, Record, Idx);
08009   SourceLocation end = ReadSourceLocation(F, Record, Idx);
08010   return SourceRange(beg, end);
08011 }
08012 
08013 /// \brief Read an integral value
08014 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
08015   unsigned BitWidth = Record[Idx++];
08016   unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
08017   llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
08018   Idx += NumWords;
08019   return Result;
08020 }
08021 
08022 /// \brief Read a signed integral value
08023 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
08024   bool isUnsigned = Record[Idx++];
08025   return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
08026 }
08027 
08028 /// \brief Read a floating-point value
08029 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
08030                                      const llvm::fltSemantics &Sem,
08031                                      unsigned &Idx) {
08032   return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
08033 }
08034 
08035 // \brief Read a string
08036 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
08037   unsigned Len = Record[Idx++];
08038   std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
08039   Idx += Len;
08040   return Result;
08041 }
08042 
08043 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record, 
08044                                          unsigned &Idx) {
08045   unsigned Major = Record[Idx++];
08046   unsigned Minor = Record[Idx++];
08047   unsigned Subminor = Record[Idx++];
08048   if (Minor == 0)
08049     return VersionTuple(Major);
08050   if (Subminor == 0)
08051     return VersionTuple(Major, Minor - 1);
08052   return VersionTuple(Major, Minor - 1, Subminor - 1);
08053 }
08054 
08055 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F, 
08056                                           const RecordData &Record,
08057                                           unsigned &Idx) {
08058   CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
08059   return CXXTemporary::Create(Context, Decl);
08060 }
08061 
08062 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
08063   return Diag(CurrentImportLoc, DiagID);
08064 }
08065 
08066 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
08067   return Diags.Report(Loc, DiagID);
08068 }
08069 
08070 /// \brief Retrieve the identifier table associated with the
08071 /// preprocessor.
08072 IdentifierTable &ASTReader::getIdentifierTable() {
08073   return PP.getIdentifierTable();
08074 }
08075 
08076 /// \brief Record that the given ID maps to the given switch-case
08077 /// statement.
08078 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
08079   assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
08080          "Already have a SwitchCase with this ID");
08081   (*CurrSwitchCaseStmts)[ID] = SC;
08082 }
08083 
08084 /// \brief Retrieve the switch-case statement with the given ID.
08085 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
08086   assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
08087   return (*CurrSwitchCaseStmts)[ID];
08088 }
08089 
08090 void ASTReader::ClearSwitchCaseIDs() {
08091   CurrSwitchCaseStmts->clear();
08092 }
08093 
08094 void ASTReader::ReadComments() {
08095   std::vector<RawComment *> Comments;
08096   for (SmallVectorImpl<std::pair<BitstreamCursor,
08097                                  serialization::ModuleFile *> >::iterator
08098        I = CommentsCursors.begin(),
08099        E = CommentsCursors.end();
08100        I != E; ++I) {
08101     Comments.clear();
08102     BitstreamCursor &Cursor = I->first;
08103     serialization::ModuleFile &F = *I->second;
08104     SavedStreamPosition SavedPosition(Cursor);
08105 
08106     RecordData Record;
08107     while (true) {
08108       llvm::BitstreamEntry Entry =
08109         Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
08110 
08111       switch (Entry.Kind) {
08112       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
08113       case llvm::BitstreamEntry::Error:
08114         Error("malformed block record in AST file");
08115         return;
08116       case llvm::BitstreamEntry::EndBlock:
08117         goto NextCursor;
08118       case llvm::BitstreamEntry::Record:
08119         // The interesting case.
08120         break;
08121       }
08122 
08123       // Read a record.
08124       Record.clear();
08125       switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
08126       case COMMENTS_RAW_COMMENT: {
08127         unsigned Idx = 0;
08128         SourceRange SR = ReadSourceRange(F, Record, Idx);
08129         RawComment::CommentKind Kind =
08130             (RawComment::CommentKind) Record[Idx++];
08131         bool IsTrailingComment = Record[Idx++];
08132         bool IsAlmostTrailingComment = Record[Idx++];
08133         Comments.push_back(new (Context) RawComment(
08134             SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
08135             Context.getLangOpts().CommentOpts.ParseAllComments));
08136         break;
08137       }
08138       }
08139     }
08140   NextCursor:
08141     Context.Comments.addDeserializedComments(Comments);
08142   }
08143 }
08144 
08145 void ASTReader::getInputFiles(ModuleFile &F,
08146                              SmallVectorImpl<serialization::InputFile> &Files) {
08147   for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
08148     unsigned ID = I+1;
08149     Files.push_back(getInputFile(F, ID));
08150   }
08151 }
08152 
08153 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
08154   // If we know the owning module, use it.
08155   if (Module *M = D->getOwningModule())
08156     return M->getFullModuleName();
08157 
08158   // Otherwise, use the name of the top-level module the decl is within.
08159   if (ModuleFile *M = getOwningModuleFile(D))
08160     return M->ModuleName;
08161 
08162   // Not from a module.
08163   return "";
08164 }
08165 
08166 void ASTReader::finishPendingActions() {
08167   while (!PendingIdentifierInfos.empty() ||
08168          !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
08169          !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
08170          !PendingUpdateRecords.empty()) {
08171     // If any identifiers with corresponding top-level declarations have
08172     // been loaded, load those declarations now.
08173     typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
08174       TopLevelDeclsMap;
08175     TopLevelDeclsMap TopLevelDecls;
08176 
08177     while (!PendingIdentifierInfos.empty()) {
08178       IdentifierInfo *II = PendingIdentifierInfos.back().first;
08179       SmallVector<uint32_t, 4> DeclIDs =
08180           std::move(PendingIdentifierInfos.back().second);
08181       PendingIdentifierInfos.pop_back();
08182 
08183       SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
08184     }
08185 
08186     // For each decl chain that we wanted to complete while deserializing, mark
08187     // it as "still needs to be completed".
08188     for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
08189       markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
08190     }
08191     PendingIncompleteDeclChains.clear();
08192 
08193     // Load pending declaration chains.
08194     for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
08195       loadPendingDeclChain(PendingDeclChains[I]);
08196       PendingDeclChainsKnown.erase(PendingDeclChains[I]);
08197     }
08198     PendingDeclChains.clear();
08199 
08200     // Make the most recent of the top-level declarations visible.
08201     for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
08202            TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
08203       IdentifierInfo *II = TLD->first;
08204       for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
08205         pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
08206       }
08207     }
08208 
08209     // Load any pending macro definitions.
08210     for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
08211       IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
08212       SmallVector<PendingMacroInfo, 2> GlobalIDs;
08213       GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
08214       // Initialize the macro history from chained-PCHs ahead of module imports.
08215       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
08216            ++IDIdx) {
08217         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
08218         if (Info.M->Kind != MK_ImplicitModule &&
08219             Info.M->Kind != MK_ExplicitModule)
08220           resolvePendingMacro(II, Info);
08221       }
08222       // Handle module imports.
08223       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
08224            ++IDIdx) {
08225         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
08226         if (Info.M->Kind == MK_ImplicitModule ||
08227             Info.M->Kind == MK_ExplicitModule)
08228           resolvePendingMacro(II, Info);
08229       }
08230     }
08231     PendingMacroIDs.clear();
08232 
08233     // Wire up the DeclContexts for Decls that we delayed setting until
08234     // recursive loading is completed.
08235     while (!PendingDeclContextInfos.empty()) {
08236       PendingDeclContextInfo Info = PendingDeclContextInfos.front();
08237       PendingDeclContextInfos.pop_front();
08238       DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
08239       DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
08240       Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
08241     }
08242 
08243     // Perform any pending declaration updates.
08244     while (!PendingUpdateRecords.empty()) {
08245       auto Update = PendingUpdateRecords.pop_back_val();
08246       ReadingKindTracker ReadingKind(Read_Decl, *this);
08247       loadDeclUpdateRecords(Update.first, Update.second);
08248     }
08249   }
08250   
08251   // If we deserialized any C++ or Objective-C class definitions, any
08252   // Objective-C protocol definitions, or any redeclarable templates, make sure
08253   // that all redeclarations point to the definitions. Note that this can only 
08254   // happen now, after the redeclaration chains have been fully wired.
08255   for (Decl *D : PendingDefinitions) {
08256     if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
08257       if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
08258         // Make sure that the TagType points at the definition.
08259         const_cast<TagType*>(TagT)->decl = TD;
08260       }
08261       
08262       if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
08263         for (auto R : RD->redecls()) {
08264           assert((R == D) == R->isThisDeclarationADefinition() &&
08265                  "declaration thinks it's the definition but it isn't");
08266           cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
08267         }
08268       }
08269 
08270       continue;
08271     }
08272     
08273     if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
08274       // Make sure that the ObjCInterfaceType points at the definition.
08275       const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
08276         ->Decl = ID;
08277       
08278       for (auto R : ID->redecls())
08279         R->Data = ID->Data;
08280       
08281       continue;
08282     }
08283     
08284     if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
08285       for (auto R : PD->redecls())
08286         R->Data = PD->Data;
08287       
08288       continue;
08289     }
08290     
08291     auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
08292     for (auto R : RTD->redecls())
08293       R->Common = RTD->Common;
08294   }
08295   PendingDefinitions.clear();
08296 
08297   // Load the bodies of any functions or methods we've encountered. We do
08298   // this now (delayed) so that we can be sure that the declaration chains
08299   // have been fully wired up.
08300   for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
08301                                PBEnd = PendingBodies.end();
08302        PB != PBEnd; ++PB) {
08303     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
08304       // FIXME: Check for =delete/=default?
08305       // FIXME: Complain about ODR violations here?
08306       if (!getContext().getLangOpts().Modules || !FD->hasBody())
08307         FD->setLazyBody(PB->second);
08308       continue;
08309     }
08310 
08311     ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
08312     if (!getContext().getLangOpts().Modules || !MD->hasBody())
08313       MD->setLazyBody(PB->second);
08314   }
08315   PendingBodies.clear();
08316 }
08317 
08318 void ASTReader::diagnoseOdrViolations() {
08319   if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
08320     return;
08321 
08322   // Trigger the import of the full definition of each class that had any
08323   // odr-merging problems, so we can produce better diagnostics for them.
08324   // These updates may in turn find and diagnose some ODR failures, so take
08325   // ownership of the set first.
08326   auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
08327   PendingOdrMergeFailures.clear();
08328   for (auto &Merge : OdrMergeFailures) {
08329     Merge.first->buildLookup();
08330     Merge.first->decls_begin();
08331     Merge.first->bases_begin();
08332     Merge.first->vbases_begin();
08333     for (auto *RD : Merge.second) {
08334       RD->decls_begin();
08335       RD->bases_begin();
08336       RD->vbases_begin();
08337     }
08338   }
08339 
08340   // For each declaration from a merged context, check that the canonical
08341   // definition of that context also contains a declaration of the same
08342   // entity.
08343   //
08344   // Caution: this loop does things that might invalidate iterators into
08345   // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
08346   while (!PendingOdrMergeChecks.empty()) {
08347     NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
08348 
08349     // FIXME: Skip over implicit declarations for now. This matters for things
08350     // like implicitly-declared special member functions. This isn't entirely
08351     // correct; we can end up with multiple unmerged declarations of the same
08352     // implicit entity.
08353     if (D->isImplicit())
08354       continue;
08355 
08356     DeclContext *CanonDef = D->getDeclContext();
08357 
08358     bool Found = false;
08359     const Decl *DCanon = D->getCanonicalDecl();
08360 
08361     for (auto RI : D->redecls()) {
08362       if (RI->getLexicalDeclContext() == CanonDef) {
08363         Found = true;
08364         break;
08365       }
08366     }
08367     if (Found)
08368       continue;
08369 
08370     llvm::SmallVector<const NamedDecl*, 4> Candidates;
08371     DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
08372     for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
08373          !Found && I != E; ++I) {
08374       for (auto RI : (*I)->redecls()) {
08375         if (RI->getLexicalDeclContext() == CanonDef) {
08376           // This declaration is present in the canonical definition. If it's
08377           // in the same redecl chain, it's the one we're looking for.
08378           if (RI->getCanonicalDecl() == DCanon)
08379             Found = true;
08380           else
08381             Candidates.push_back(cast<NamedDecl>(RI));
08382           break;
08383         }
08384       }
08385     }
08386 
08387     if (!Found) {
08388       // The AST doesn't like TagDecls becoming invalid after they've been
08389       // completed. We only really need to mark FieldDecls as invalid here.
08390       if (!isa<TagDecl>(D))
08391         D->setInvalidDecl();
08392 
08393       std::string CanonDefModule =
08394           getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
08395       Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
08396         << D << getOwningModuleNameForDiagnostic(D)
08397         << CanonDef << CanonDefModule.empty() << CanonDefModule;
08398 
08399       if (Candidates.empty())
08400         Diag(cast<Decl>(CanonDef)->getLocation(),
08401              diag::note_module_odr_violation_no_possible_decls) << D;
08402       else {
08403         for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
08404           Diag(Candidates[I]->getLocation(),
08405                diag::note_module_odr_violation_possible_decl)
08406             << Candidates[I];
08407       }
08408 
08409       DiagnosedOdrMergeFailures.insert(CanonDef);
08410     }
08411   }
08412 
08413   // Issue any pending ODR-failure diagnostics.
08414   for (auto &Merge : OdrMergeFailures) {
08415     // If we've already pointed out a specific problem with this class, don't
08416     // bother issuing a general "something's different" diagnostic.
08417     if (!DiagnosedOdrMergeFailures.insert(Merge.first))
08418       continue;
08419 
08420     bool Diagnosed = false;
08421     for (auto *RD : Merge.second) {
08422       // Multiple different declarations got merged together; tell the user
08423       // where they came from.
08424       if (Merge.first != RD) {
08425         // FIXME: Walk the definition, figure out what's different,
08426         // and diagnose that.
08427         if (!Diagnosed) {
08428           std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
08429           Diag(Merge.first->getLocation(),
08430                diag::err_module_odr_violation_different_definitions)
08431             << Merge.first << Module.empty() << Module;
08432           Diagnosed = true;
08433         }
08434 
08435         Diag(RD->getLocation(),
08436              diag::note_module_odr_violation_different_definitions)
08437           << getOwningModuleNameForDiagnostic(RD);
08438       }
08439     }
08440 
08441     if (!Diagnosed) {
08442       // All definitions are updates to the same declaration. This happens if a
08443       // module instantiates the declaration of a class template specialization
08444       // and two or more other modules instantiate its definition.
08445       //
08446       // FIXME: Indicate which modules had instantiations of this definition.
08447       // FIXME: How can this even happen?
08448       Diag(Merge.first->getLocation(),
08449            diag::err_module_odr_violation_different_instantiations)
08450         << Merge.first;
08451     }
08452   }
08453 }
08454 
08455 void ASTReader::FinishedDeserializing() {
08456   assert(NumCurrentElementsDeserializing &&
08457          "FinishedDeserializing not paired with StartedDeserializing");
08458   if (NumCurrentElementsDeserializing == 1) {
08459     // We decrease NumCurrentElementsDeserializing only after pending actions
08460     // are finished, to avoid recursively re-calling finishPendingActions().
08461     finishPendingActions();
08462   }
08463   --NumCurrentElementsDeserializing;
08464 
08465   if (NumCurrentElementsDeserializing == 0) {
08466     diagnoseOdrViolations();
08467 
08468     // We are not in recursive loading, so it's safe to pass the "interesting"
08469     // decls to the consumer.
08470     if (Consumer)
08471       PassInterestingDeclsToConsumer();
08472   }
08473 }
08474 
08475 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
08476   D = D->getMostRecentDecl();
08477 
08478   if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
08479     SemaObj->TUScope->AddDecl(D);
08480   } else if (SemaObj->TUScope) {
08481     // Adding the decl to IdResolver may have failed because it was already in
08482     // (even though it was not added in scope). If it is already in, make sure
08483     // it gets in the scope as well.
08484     if (std::find(SemaObj->IdResolver.begin(Name),
08485                   SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
08486       SemaObj->TUScope->AddDecl(D);
08487   }
08488 }
08489 
08490 ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context, StringRef isysroot,
08491                      bool DisableValidation, bool AllowASTWithCompilerErrors,
08492                      bool AllowConfigurationMismatch, bool ValidateSystemInputs,
08493                      bool UseGlobalIndex)
08494     : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
08495       OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
08496       FileMgr(PP.getFileManager()), Diags(PP.getDiagnostics()),
08497       SemaObj(nullptr), PP(PP), Context(Context), Consumer(nullptr),
08498       ModuleMgr(PP.getFileManager()), isysroot(isysroot),
08499       DisableValidation(DisableValidation),
08500       AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
08501       AllowConfigurationMismatch(AllowConfigurationMismatch),
08502       ValidateSystemInputs(ValidateSystemInputs),
08503       UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
08504       CurrSwitchCaseStmts(&SwitchCaseStmts),
08505       NumSLocEntriesRead(0), TotalNumSLocEntries(0), NumStatementsRead(0),
08506       TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
08507       NumIdentifierLookups(0), NumIdentifierLookupHits(0), NumSelectorsRead(0),
08508       NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
08509       NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
08510       NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
08511       NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
08512       NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
08513       TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
08514       PassingDeclsToConsumer(false), NumCXXBaseSpecifiersLoaded(0),
08515       ReadingKind(Read_None) {
08516   SourceMgr.setExternalSLocEntrySource(this);
08517 }
08518 
08519 ASTReader::~ASTReader() {
08520   if (OwnsDeserializationListener)
08521     delete DeserializationListener;
08522 
08523   for (DeclContextVisibleUpdatesPending::iterator
08524            I = PendingVisibleUpdates.begin(),
08525            E = PendingVisibleUpdates.end();
08526        I != E; ++I) {
08527     for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
08528                                              F = I->second.end();
08529          J != F; ++J)
08530       delete J->first;
08531   }
08532 }