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