clang API Documentation

ASTReader.cpp
Go to the documentation of this file.
00001 //===--- ASTReader.cpp - AST File Reader ------------------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the ASTReader class, which reads AST files.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Serialization/ASTReader.h"
00015 #include "clang/Serialization/ASTDeserializationListener.h"
00016 #include "clang/Serialization/ModuleManager.h"
00017 #include "clang/Serialization/SerializationDiagnostic.h"
00018 #include "ASTCommon.h"
00019 #include "ASTReaderInternals.h"
00020 #include "clang/Sema/Sema.h"
00021 #include "clang/Sema/Scope.h"
00022 #include "clang/AST/ASTConsumer.h"
00023 #include "clang/AST/ASTContext.h"
00024 #include "clang/AST/DeclTemplate.h"
00025 #include "clang/AST/Expr.h"
00026 #include "clang/AST/ExprCXX.h"
00027 #include "clang/AST/NestedNameSpecifier.h"
00028 #include "clang/AST/Type.h"
00029 #include "clang/AST/TypeLocVisitor.h"
00030 #include "clang/Lex/MacroInfo.h"
00031 #include "clang/Lex/PreprocessingRecord.h"
00032 #include "clang/Lex/Preprocessor.h"
00033 #include "clang/Lex/HeaderSearch.h"
00034 #include "clang/Basic/OnDiskHashTable.h"
00035 #include "clang/Basic/SourceManager.h"
00036 #include "clang/Basic/SourceManagerInternals.h"
00037 #include "clang/Basic/FileManager.h"
00038 #include "clang/Basic/FileSystemStatCache.h"
00039 #include "clang/Basic/TargetInfo.h"
00040 #include "clang/Basic/Version.h"
00041 #include "clang/Basic/VersionTuple.h"
00042 #include "llvm/ADT/StringExtras.h"
00043 #include "llvm/Bitcode/BitstreamReader.h"
00044 #include "llvm/Support/MemoryBuffer.h"
00045 #include "llvm/Support/ErrorHandling.h"
00046 #include "llvm/Support/FileSystem.h"
00047 #include "llvm/Support/Path.h"
00048 #include "llvm/Support/SaveAndRestore.h"
00049 #include "llvm/Support/system_error.h"
00050 #include <algorithm>
00051 #include <iterator>
00052 #include <cstdio>
00053 #include <sys/stat.h>
00054 
00055 using namespace clang;
00056 using namespace clang::serialization;
00057 using namespace clang::serialization::reader;
00058 
00059 //===----------------------------------------------------------------------===//
00060 // PCH validator implementation
00061 //===----------------------------------------------------------------------===//
00062 
00063 ASTReaderListener::~ASTReaderListener() {}
00064 
00065 bool
00066 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
00067   const LangOptions &PPLangOpts = PP.getLangOpts();
00068   
00069 #define LANGOPT(Name, Bits, Default, Description)         \
00070   if (PPLangOpts.Name != LangOpts.Name) {                 \
00071     Reader.Diag(diag::err_pch_langopt_mismatch)           \
00072       << Description << LangOpts.Name << PPLangOpts.Name; \
00073     return true;                                          \
00074   }
00075 
00076 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
00077   if (PPLangOpts.Name != LangOpts.Name) {               \
00078     Reader.Diag(diag::err_pch_langopt_value_mismatch)   \
00079       << Description;                                   \
00080   return true;                                          \
00081 }
00082 
00083 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
00084   if (PPLangOpts.get##Name() != LangOpts.get##Name()) {      \
00085     Reader.Diag(diag::err_pch_langopt_value_mismatch)        \
00086       << Description;                                        \
00087     return true;                                             \
00088   }
00089 
00090 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
00091 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
00092 #include "clang/Basic/LangOptions.def"
00093   
00094   return false;
00095 }
00096 
00097 bool PCHValidator::ReadTargetTriple(StringRef Triple) {
00098   if (Triple == PP.getTargetInfo().getTriple().str())
00099     return false;
00100 
00101   Reader.Diag(diag::warn_pch_target_triple)
00102     << Triple << PP.getTargetInfo().getTriple().str();
00103   return true;
00104 }
00105 
00106 namespace {
00107   struct EmptyStringRef {
00108     bool operator ()(StringRef r) const { return r.empty(); }
00109   };
00110   struct EmptyBlock {
00111     bool operator ()(const PCHPredefinesBlock &r) const {return r.Data.empty();}
00112   };
00113 }
00114 
00115 static bool EqualConcatenations(SmallVector<StringRef, 2> L,
00116                                 PCHPredefinesBlocks R) {
00117   // First, sum up the lengths.
00118   unsigned LL = 0, RL = 0;
00119   for (unsigned I = 0, N = L.size(); I != N; ++I) {
00120     LL += L[I].size();
00121   }
00122   for (unsigned I = 0, N = R.size(); I != N; ++I) {
00123     RL += R[I].Data.size();
00124   }
00125   if (LL != RL)
00126     return false;
00127   if (LL == 0 && RL == 0)
00128     return true;
00129 
00130   // Kick out empty parts, they confuse the algorithm below.
00131   L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
00132   R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
00133 
00134   // Do it the hard way. At this point, both vectors must be non-empty.
00135   StringRef LR = L[0], RR = R[0].Data;
00136   unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
00137   (void) RN;
00138   for (;;) {
00139     // Compare the current pieces.
00140     if (LR.size() == RR.size()) {
00141       // If they're the same length, it's pretty easy.
00142       if (LR != RR)
00143         return false;
00144       // Both pieces are done, advance.
00145       ++LI;
00146       ++RI;
00147       // If either string is done, they're both done, since they're the same
00148       // length.
00149       if (LI == LN) {
00150         assert(RI == RN && "Strings not the same length after all?");
00151         return true;
00152       }
00153       LR = L[LI];
00154       RR = R[RI].Data;
00155     } else if (LR.size() < RR.size()) {
00156       // Right piece is longer.
00157       if (!RR.startswith(LR))
00158         return false;
00159       ++LI;
00160       assert(LI != LN && "Strings not the same length after all?");
00161       RR = RR.substr(LR.size());
00162       LR = L[LI];
00163     } else {
00164       // Left piece is longer.
00165       if (!LR.startswith(RR))
00166         return false;
00167       ++RI;
00168       assert(RI != RN && "Strings not the same length after all?");
00169       LR = LR.substr(RR.size());
00170       RR = R[RI].Data;
00171     }
00172   }
00173 }
00174 
00175 static std::pair<FileID, StringRef::size_type>
00176 FindMacro(const PCHPredefinesBlocks &Buffers, StringRef MacroDef) {
00177   std::pair<FileID, StringRef::size_type> Res;
00178   for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
00179     Res.second = Buffers[I].Data.find(MacroDef);
00180     if (Res.second != StringRef::npos) {
00181       Res.first = Buffers[I].BufferID;
00182       break;
00183     }
00184   }
00185   return Res;
00186 }
00187 
00188 bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
00189                                         StringRef OriginalFileName,
00190                                         std::string &SuggestedPredefines,
00191                                         FileManager &FileMgr) {
00192   // We are in the context of an implicit include, so the predefines buffer will
00193   // have a #include entry for the PCH file itself (as normalized by the
00194   // preprocessor initialization). Find it and skip over it in the checking
00195   // below.
00196   SmallString<256> PCHInclude;
00197   PCHInclude += "#include \"";
00198   PCHInclude += HeaderSearch::NormalizeDashIncludePath(OriginalFileName,
00199                                                        FileMgr);
00200   PCHInclude += "\"\n";
00201   std::pair<StringRef,StringRef> Split =
00202     StringRef(PP.getPredefines()).split(PCHInclude.str());
00203   StringRef Left =  Split.first, Right = Split.second;
00204   if (Left == PP.getPredefines()) {
00205     Error("Missing PCH include entry!");
00206     return true;
00207   }
00208 
00209   // If the concatenation of all the PCH buffers is equal to the adjusted
00210   // command line, we're done.
00211   SmallVector<StringRef, 2> CommandLine;
00212   CommandLine.push_back(Left);
00213   CommandLine.push_back(Right);
00214   if (EqualConcatenations(CommandLine, Buffers))
00215     return false;
00216 
00217   SourceManager &SourceMgr = PP.getSourceManager();
00218 
00219   // The predefines buffers are different. Determine what the differences are,
00220   // and whether they require us to reject the PCH file.
00221   SmallVector<StringRef, 8> PCHLines;
00222   for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
00223     Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
00224 
00225   SmallVector<StringRef, 8> CmdLineLines;
00226   Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
00227 
00228   // Pick out implicit #includes after the PCH and don't consider them for
00229   // validation; we will insert them into SuggestedPredefines so that the
00230   // preprocessor includes them.
00231   std::string IncludesAfterPCH;
00232   SmallVector<StringRef, 8> AfterPCHLines;
00233   Right.split(AfterPCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
00234   for (unsigned i = 0, e = AfterPCHLines.size(); i != e; ++i) {
00235     if (AfterPCHLines[i].startswith("#include ")) {
00236       IncludesAfterPCH += AfterPCHLines[i];
00237       IncludesAfterPCH += '\n';
00238     } else {
00239       CmdLineLines.push_back(AfterPCHLines[i]);
00240     }
00241   }
00242 
00243   // Make sure we add the includes last into SuggestedPredefines before we
00244   // exit this function.
00245   struct AddIncludesRAII {
00246     std::string &SuggestedPredefines;
00247     std::string &IncludesAfterPCH;
00248 
00249     AddIncludesRAII(std::string &SuggestedPredefines,
00250                     std::string &IncludesAfterPCH)
00251       : SuggestedPredefines(SuggestedPredefines),
00252         IncludesAfterPCH(IncludesAfterPCH) { }
00253     ~AddIncludesRAII() {
00254       SuggestedPredefines += IncludesAfterPCH;
00255     }
00256   } AddIncludes(SuggestedPredefines, IncludesAfterPCH);
00257 
00258   // Sort both sets of predefined buffer lines, since we allow some extra
00259   // definitions and they may appear at any point in the output.
00260   std::sort(CmdLineLines.begin(), CmdLineLines.end());
00261   std::sort(PCHLines.begin(), PCHLines.end());
00262 
00263   // Determine which predefines that were used to build the PCH file are missing
00264   // from the command line.
00265   std::vector<StringRef> MissingPredefines;
00266   std::set_difference(PCHLines.begin(), PCHLines.end(),
00267                       CmdLineLines.begin(), CmdLineLines.end(),
00268                       std::back_inserter(MissingPredefines));
00269 
00270   bool MissingDefines = false;
00271   bool ConflictingDefines = false;
00272   for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
00273     StringRef Missing = MissingPredefines[I];
00274     if (Missing.startswith("#include ")) {
00275       // An -include was specified when generating the PCH; it is included in
00276       // the PCH, just ignore it.
00277       continue;
00278     }
00279     if (!Missing.startswith("#define ")) {
00280       Reader.Diag(diag::warn_pch_compiler_options_mismatch);
00281       return true;
00282     }
00283 
00284     // This is a macro definition. Determine the name of the macro we're
00285     // defining.
00286     std::string::size_type StartOfMacroName = strlen("#define ");
00287     std::string::size_type EndOfMacroName
00288       = Missing.find_first_of("( \n\r", StartOfMacroName);
00289     assert(EndOfMacroName != std::string::npos &&
00290            "Couldn't find the end of the macro name");
00291     StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
00292 
00293     // Determine whether this macro was given a different definition on the
00294     // command line.
00295     std::string MacroDefStart = "#define " + MacroName.str();
00296     std::string::size_type MacroDefLen = MacroDefStart.size();
00297     SmallVector<StringRef, 8>::iterator ConflictPos
00298       = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
00299                          MacroDefStart);
00300     for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
00301       if (!ConflictPos->startswith(MacroDefStart)) {
00302         // Different macro; we're done.
00303         ConflictPos = CmdLineLines.end();
00304         break;
00305       }
00306 
00307       assert(ConflictPos->size() > MacroDefLen &&
00308              "Invalid #define in predefines buffer?");
00309       if ((*ConflictPos)[MacroDefLen] != ' ' &&
00310           (*ConflictPos)[MacroDefLen] != '(')
00311         continue; // Longer macro name; keep trying.
00312 
00313       // We found a conflicting macro definition.
00314       break;
00315     }
00316 
00317     if (ConflictPos != CmdLineLines.end()) {
00318       Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
00319           << MacroName;
00320 
00321       // Show the definition of this macro within the PCH file.
00322       std::pair<FileID, StringRef::size_type> MacroLoc =
00323           FindMacro(Buffers, Missing);
00324       assert(MacroLoc.second!=StringRef::npos && "Unable to find macro!");
00325       SourceLocation PCHMissingLoc =
00326           SourceMgr.getLocForStartOfFile(MacroLoc.first)
00327             .getLocWithOffset(MacroLoc.second);
00328       Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
00329 
00330       ConflictingDefines = true;
00331       continue;
00332     }
00333 
00334     // If the macro doesn't conflict, then we'll just pick up the macro
00335     // definition from the PCH file. Warn the user that they made a mistake.
00336     if (ConflictingDefines)
00337       continue; // Don't complain if there are already conflicting defs
00338 
00339     if (!MissingDefines) {
00340       Reader.Diag(diag::warn_cmdline_missing_macro_defs);
00341       MissingDefines = true;
00342     }
00343 
00344     // Show the definition of this macro within the PCH file.
00345     std::pair<FileID, StringRef::size_type> MacroLoc =
00346         FindMacro(Buffers, Missing);
00347     assert(MacroLoc.second!=StringRef::npos && "Unable to find macro!");
00348     SourceLocation PCHMissingLoc =
00349         SourceMgr.getLocForStartOfFile(MacroLoc.first)
00350           .getLocWithOffset(MacroLoc.second);
00351     Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
00352   }
00353 
00354   if (ConflictingDefines)
00355     return true;
00356 
00357   // Determine what predefines were introduced based on command-line
00358   // parameters that were not present when building the PCH
00359   // file. Extra #defines are okay, so long as the identifiers being
00360   // defined were not used within the precompiled header.
00361   std::vector<StringRef> ExtraPredefines;
00362   std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
00363                       PCHLines.begin(), PCHLines.end(),
00364                       std::back_inserter(ExtraPredefines));
00365   for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
00366     StringRef &Extra = ExtraPredefines[I];
00367     if (!Extra.startswith("#define ")) {
00368       Reader.Diag(diag::warn_pch_compiler_options_mismatch);
00369       return true;
00370     }
00371 
00372     // This is an extra macro definition. Determine the name of the
00373     // macro we're defining.
00374     std::string::size_type StartOfMacroName = strlen("#define ");
00375     std::string::size_type EndOfMacroName
00376       = Extra.find_first_of("( \n\r", StartOfMacroName);
00377     assert(EndOfMacroName != std::string::npos &&
00378            "Couldn't find the end of the macro name");
00379     StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
00380 
00381     // Check whether this name was used somewhere in the PCH file. If
00382     // so, defining it as a macro could change behavior, so we reject
00383     // the PCH file.
00384     if (IdentifierInfo *II = Reader.get(MacroName)) {
00385       Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
00386       return true;
00387     }
00388 
00389     // Add this definition to the suggested predefines buffer.
00390     SuggestedPredefines += Extra;
00391     SuggestedPredefines += '\n';
00392   }
00393 
00394   // If we get here, it's because the predefines buffer had compatible
00395   // contents. Accept the PCH file.
00396   return false;
00397 }
00398 
00399 void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
00400                                       unsigned ID) {
00401   PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
00402   ++NumHeaderInfos;
00403 }
00404 
00405 void PCHValidator::ReadCounter(unsigned Value) {
00406   PP.setCounterValue(Value);
00407 }
00408 
00409 //===----------------------------------------------------------------------===//
00410 // AST reader implementation
00411 //===----------------------------------------------------------------------===//
00412 
00413 void
00414 ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
00415   DeserializationListener = Listener;
00416 }
00417 
00418 
00419 
00420 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
00421   return serialization::ComputeHash(Sel);
00422 }
00423 
00424 
00425 std::pair<unsigned, unsigned>
00426 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
00427   using namespace clang::io;
00428   unsigned KeyLen = ReadUnalignedLE16(d);
00429   unsigned DataLen = ReadUnalignedLE16(d);
00430   return std::make_pair(KeyLen, DataLen);
00431 }
00432 
00433 ASTSelectorLookupTrait::internal_key_type 
00434 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
00435   using namespace clang::io;
00436   SelectorTable &SelTable = Reader.getContext().Selectors;
00437   unsigned N = ReadUnalignedLE16(d);
00438   IdentifierInfo *FirstII
00439     = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
00440   if (N == 0)
00441     return SelTable.getNullarySelector(FirstII);
00442   else if (N == 1)
00443     return SelTable.getUnarySelector(FirstII);
00444 
00445   SmallVector<IdentifierInfo *, 16> Args;
00446   Args.push_back(FirstII);
00447   for (unsigned I = 1; I != N; ++I)
00448     Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
00449 
00450   return SelTable.getSelector(N, Args.data());
00451 }
00452 
00453 ASTSelectorLookupTrait::data_type 
00454 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d, 
00455                                  unsigned DataLen) {
00456   using namespace clang::io;
00457 
00458   data_type Result;
00459 
00460   Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
00461   unsigned NumInstanceMethods = ReadUnalignedLE16(d);
00462   unsigned NumFactoryMethods = ReadUnalignedLE16(d);
00463 
00464   // Load instance methods
00465   for (unsigned I = 0; I != NumInstanceMethods; ++I) {
00466     if (ObjCMethodDecl *Method
00467           = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
00468       Result.Instance.push_back(Method);
00469   }
00470 
00471   // Load factory methods
00472   for (unsigned I = 0; I != NumFactoryMethods; ++I) {
00473     if (ObjCMethodDecl *Method
00474           = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
00475       Result.Factory.push_back(Method);
00476   }
00477 
00478   return Result;
00479 }
00480 
00481 unsigned ASTIdentifierLookupTrait::ComputeHash(const internal_key_type& a) {
00482   return llvm::HashString(StringRef(a.first, a.second));
00483 }
00484 
00485 std::pair<unsigned, unsigned>
00486 ASTIdentifierLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
00487   using namespace clang::io;
00488   unsigned DataLen = ReadUnalignedLE16(d);
00489   unsigned KeyLen = ReadUnalignedLE16(d);
00490   return std::make_pair(KeyLen, DataLen);
00491 }
00492 
00493 std::pair<const char*, unsigned>
00494 ASTIdentifierLookupTrait::ReadKey(const unsigned char* d, unsigned n) {
00495   assert(n >= 2 && d[n-1] == '\0');
00496   return std::make_pair((const char*) d, n-1);
00497 }
00498 
00499 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
00500                                                    const unsigned char* d,
00501                                                    unsigned DataLen) {
00502   using namespace clang::io;
00503   unsigned RawID = ReadUnalignedLE32(d);
00504   bool IsInteresting = RawID & 0x01;
00505 
00506   // Wipe out the "is interesting" bit.
00507   RawID = RawID >> 1;
00508 
00509   IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
00510   if (!IsInteresting) {
00511     // For uninteresting identifiers, just build the IdentifierInfo
00512     // and associate it with the persistent ID.
00513     IdentifierInfo *II = KnownII;
00514     if (!II) {
00515       II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
00516       KnownII = II;
00517     }
00518     Reader.SetIdentifierInfo(ID, II);
00519     II->setIsFromAST();
00520     Reader.markIdentifierUpToDate(II);    
00521     return II;
00522   }
00523 
00524   unsigned Bits = ReadUnalignedLE16(d);
00525   bool CPlusPlusOperatorKeyword = Bits & 0x01;
00526   Bits >>= 1;
00527   bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
00528   Bits >>= 1;
00529   bool Poisoned = Bits & 0x01;
00530   Bits >>= 1;
00531   bool ExtensionToken = Bits & 0x01;
00532   Bits >>= 1;
00533   bool hasMacroDefinition = Bits & 0x01;
00534   Bits >>= 1;
00535   unsigned ObjCOrBuiltinID = Bits & 0x7FF;
00536   Bits >>= 11;
00537 
00538   assert(Bits == 0 && "Extra bits in the identifier?");
00539   DataLen -= 6;
00540 
00541   // Build the IdentifierInfo itself and link the identifier ID with
00542   // the new IdentifierInfo.
00543   IdentifierInfo *II = KnownII;
00544   if (!II) {
00545     II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
00546     KnownII = II;
00547   }
00548   Reader.markIdentifierUpToDate(II);
00549   II->setIsFromAST();
00550 
00551   // Set or check the various bits in the IdentifierInfo structure.
00552   // Token IDs are read-only.
00553   if (HasRevertedTokenIDToIdentifier)
00554     II->RevertTokenIDToIdentifier();
00555   II->setObjCOrBuiltinID(ObjCOrBuiltinID);
00556   assert(II->isExtensionToken() == ExtensionToken &&
00557          "Incorrect extension token flag");
00558   (void)ExtensionToken;
00559   if (Poisoned)
00560     II->setIsPoisoned(true);
00561   assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
00562          "Incorrect C++ operator keyword flag");
00563   (void)CPlusPlusOperatorKeyword;
00564 
00565   // If this identifier is a macro, deserialize the macro
00566   // definition.
00567   if (hasMacroDefinition) {
00568     // FIXME: Check for conflicts?
00569     uint32_t Offset = ReadUnalignedLE32(d);
00570     unsigned LocalSubmoduleID = ReadUnalignedLE32(d);
00571     
00572     // Determine whether this macro definition should be visible now, or
00573     // whether it is in a hidden submodule.
00574     bool Visible = true;
00575     if (SubmoduleID GlobalSubmoduleID
00576           = Reader.getGlobalSubmoduleID(F, LocalSubmoduleID)) {
00577       if (Module *Owner = Reader.getSubmodule(GlobalSubmoduleID)) {
00578         if (Owner->NameVisibility == Module::Hidden) {
00579           // The owning module is not visible, and this macro definition should
00580           // not be, either.
00581           Visible = false;
00582           
00583           // Note that this macro definition was hidden because its owning 
00584           // module is not yet visible.
00585           Reader.HiddenNamesMap[Owner].push_back(II);
00586         }
00587       } 
00588     }
00589     
00590     Reader.setIdentifierIsMacro(II, F, Offset, Visible);
00591     DataLen -= 8;
00592   }
00593 
00594   Reader.SetIdentifierInfo(ID, II);
00595 
00596   // Read all of the declarations visible at global scope with this
00597   // name.
00598   if (DataLen > 0) {
00599     SmallVector<uint32_t, 4> DeclIDs;
00600     for (; DataLen > 0; DataLen -= 4)
00601       DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
00602     Reader.SetGloballyVisibleDecls(II, DeclIDs);
00603   }
00604 
00605   return II;
00606 }
00607 
00608 unsigned 
00609 ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
00610   llvm::FoldingSetNodeID ID;
00611   ID.AddInteger(Key.Kind);
00612 
00613   switch (Key.Kind) {
00614   case DeclarationName::Identifier:
00615   case DeclarationName::CXXLiteralOperatorName:
00616     ID.AddString(((IdentifierInfo*)Key.Data)->getName());
00617     break;
00618   case DeclarationName::ObjCZeroArgSelector:
00619   case DeclarationName::ObjCOneArgSelector:
00620   case DeclarationName::ObjCMultiArgSelector:
00621     ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
00622     break;
00623   case DeclarationName::CXXOperatorName:
00624     ID.AddInteger((OverloadedOperatorKind)Key.Data);
00625     break;
00626   case DeclarationName::CXXConstructorName:
00627   case DeclarationName::CXXDestructorName:
00628   case DeclarationName::CXXConversionFunctionName:
00629   case DeclarationName::CXXUsingDirective:
00630     break;
00631   }
00632 
00633   return ID.ComputeHash();
00634 }
00635 
00636 ASTDeclContextNameLookupTrait::internal_key_type 
00637 ASTDeclContextNameLookupTrait::GetInternalKey(
00638                                           const external_key_type& Name) const {
00639   DeclNameKey Key;
00640   Key.Kind = Name.getNameKind();
00641   switch (Name.getNameKind()) {
00642   case DeclarationName::Identifier:
00643     Key.Data = (uint64_t)Name.getAsIdentifierInfo();
00644     break;
00645   case DeclarationName::ObjCZeroArgSelector:
00646   case DeclarationName::ObjCOneArgSelector:
00647   case DeclarationName::ObjCMultiArgSelector:
00648     Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
00649     break;
00650   case DeclarationName::CXXOperatorName:
00651     Key.Data = Name.getCXXOverloadedOperator();
00652     break;
00653   case DeclarationName::CXXLiteralOperatorName:
00654     Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
00655     break;
00656   case DeclarationName::CXXConstructorName:
00657   case DeclarationName::CXXDestructorName:
00658   case DeclarationName::CXXConversionFunctionName:
00659   case DeclarationName::CXXUsingDirective:
00660     Key.Data = 0;
00661     break;
00662   }
00663 
00664   return Key;
00665 }
00666 
00667 std::pair<unsigned, unsigned>
00668 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
00669   using namespace clang::io;
00670   unsigned KeyLen = ReadUnalignedLE16(d);
00671   unsigned DataLen = ReadUnalignedLE16(d);
00672   return std::make_pair(KeyLen, DataLen);
00673 }
00674 
00675 ASTDeclContextNameLookupTrait::internal_key_type 
00676 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
00677   using namespace clang::io;
00678 
00679   DeclNameKey Key;
00680   Key.Kind = (DeclarationName::NameKind)*d++;
00681   switch (Key.Kind) {
00682   case DeclarationName::Identifier:
00683     Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
00684     break;
00685   case DeclarationName::ObjCZeroArgSelector:
00686   case DeclarationName::ObjCOneArgSelector:
00687   case DeclarationName::ObjCMultiArgSelector:
00688     Key.Data =
00689        (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
00690                    .getAsOpaquePtr();
00691     break;
00692   case DeclarationName::CXXOperatorName:
00693     Key.Data = *d++; // OverloadedOperatorKind
00694     break;
00695   case DeclarationName::CXXLiteralOperatorName:
00696     Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
00697     break;
00698   case DeclarationName::CXXConstructorName:
00699   case DeclarationName::CXXDestructorName:
00700   case DeclarationName::CXXConversionFunctionName:
00701   case DeclarationName::CXXUsingDirective:
00702     Key.Data = 0;
00703     break;
00704   }
00705 
00706   return Key;
00707 }
00708 
00709 ASTDeclContextNameLookupTrait::data_type 
00710 ASTDeclContextNameLookupTrait::ReadData(internal_key_type, 
00711                                         const unsigned char* d,
00712                                         unsigned DataLen) {
00713   using namespace clang::io;
00714   unsigned NumDecls = ReadUnalignedLE16(d);
00715   LE32DeclID *Start = (LE32DeclID *)d;
00716   return std::make_pair(Start, Start + NumDecls);
00717 }
00718 
00719 bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
00720                                        llvm::BitstreamCursor &Cursor,
00721                                    const std::pair<uint64_t, uint64_t> &Offsets,
00722                                        DeclContextInfo &Info) {
00723   SavedStreamPosition SavedPosition(Cursor);
00724   // First the lexical decls.
00725   if (Offsets.first != 0) {
00726     Cursor.JumpToBit(Offsets.first);
00727 
00728     RecordData Record;
00729     const char *Blob;
00730     unsigned BlobLen;
00731     unsigned Code = Cursor.ReadCode();
00732     unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
00733     if (RecCode != DECL_CONTEXT_LEXICAL) {
00734       Error("Expected lexical block");
00735       return true;
00736     }
00737 
00738     Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob);
00739     Info.NumLexicalDecls = BlobLen / sizeof(KindDeclIDPair);
00740   }
00741 
00742   // Now the lookup table.
00743   if (Offsets.second != 0) {
00744     Cursor.JumpToBit(Offsets.second);
00745 
00746     RecordData Record;
00747     const char *Blob;
00748     unsigned BlobLen;
00749     unsigned Code = Cursor.ReadCode();
00750     unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
00751     if (RecCode != DECL_CONTEXT_VISIBLE) {
00752       Error("Expected visible lookup table block");
00753       return true;
00754     }
00755     Info.NameLookupTableData
00756       = ASTDeclContextNameLookupTable::Create(
00757                     (const unsigned char *)Blob + Record[0],
00758                     (const unsigned char *)Blob,
00759                     ASTDeclContextNameLookupTrait(*this, M));
00760   }
00761 
00762   return false;
00763 }
00764 
00765 void ASTReader::Error(StringRef Msg) {
00766   Error(diag::err_fe_pch_malformed, Msg);
00767 }
00768 
00769 void ASTReader::Error(unsigned DiagID,
00770                       StringRef Arg1, StringRef Arg2) {
00771   if (Diags.isDiagnosticInFlight())
00772     Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
00773   else
00774     Diag(DiagID) << Arg1 << Arg2;
00775 }
00776 
00777 /// \brief Tell the AST listener about the predefines buffers in the chain.
00778 bool ASTReader::CheckPredefinesBuffers() {
00779   if (Listener)
00780     return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
00781                                           ActualOriginalFileName,
00782                                           SuggestedPredefines,
00783                                           FileMgr);
00784   return false;
00785 }
00786 
00787 //===----------------------------------------------------------------------===//
00788 // Source Manager Deserialization
00789 //===----------------------------------------------------------------------===//
00790 
00791 /// \brief Read the line table in the source manager block.
00792 /// \returns true if there was an error.
00793 bool ASTReader::ParseLineTable(ModuleFile &F,
00794                                SmallVectorImpl<uint64_t> &Record) {
00795   unsigned Idx = 0;
00796   LineTableInfo &LineTable = SourceMgr.getLineTable();
00797 
00798   // Parse the file names
00799   std::map<int, int> FileIDs;
00800   for (int I = 0, N = Record[Idx++]; I != N; ++I) {
00801     // Extract the file name
00802     unsigned FilenameLen = Record[Idx++];
00803     std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
00804     Idx += FilenameLen;
00805     MaybeAddSystemRootToFilename(Filename);
00806     FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
00807   }
00808 
00809   // Parse the line entries
00810   std::vector<LineEntry> Entries;
00811   while (Idx < Record.size()) {
00812     int FID = Record[Idx++];
00813     assert(FID >= 0 && "Serialized line entries for non-local file.");
00814     // Remap FileID from 1-based old view.
00815     FID += F.SLocEntryBaseID - 1;
00816 
00817     // Extract the line entries
00818     unsigned NumEntries = Record[Idx++];
00819     assert(NumEntries && "Numentries is 00000");
00820     Entries.clear();
00821     Entries.reserve(NumEntries);
00822     for (unsigned I = 0; I != NumEntries; ++I) {
00823       unsigned FileOffset = Record[Idx++];
00824       unsigned LineNo = Record[Idx++];
00825       int FilenameID = FileIDs[Record[Idx++]];
00826       SrcMgr::CharacteristicKind FileKind
00827         = (SrcMgr::CharacteristicKind)Record[Idx++];
00828       unsigned IncludeOffset = Record[Idx++];
00829       Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
00830                                        FileKind, IncludeOffset));
00831     }
00832     LineTable.AddEntry(FID, Entries);
00833   }
00834 
00835   return false;
00836 }
00837 
00838 namespace {
00839 
00840 class ASTStatData {
00841 public:
00842   const ino_t ino;
00843   const dev_t dev;
00844   const mode_t mode;
00845   const time_t mtime;
00846   const off_t size;
00847 
00848   ASTStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
00849     : ino(i), dev(d), mode(mo), mtime(m), size(s) {}
00850 };
00851 
00852 class ASTStatLookupTrait {
00853  public:
00854   typedef const char *external_key_type;
00855   typedef const char *internal_key_type;
00856 
00857   typedef ASTStatData data_type;
00858 
00859   static unsigned ComputeHash(const char *path) {
00860     return llvm::HashString(path);
00861   }
00862 
00863   static internal_key_type GetInternalKey(const char *path) { return path; }
00864 
00865   static bool EqualKey(internal_key_type a, internal_key_type b) {
00866     return strcmp(a, b) == 0;
00867   }
00868 
00869   static std::pair<unsigned, unsigned>
00870   ReadKeyDataLength(const unsigned char*& d) {
00871     unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
00872     unsigned DataLen = (unsigned) *d++;
00873     return std::make_pair(KeyLen + 1, DataLen);
00874   }
00875 
00876   static internal_key_type ReadKey(const unsigned char *d, unsigned) {
00877     return (const char *)d;
00878   }
00879 
00880   static data_type ReadData(const internal_key_type, const unsigned char *d,
00881                             unsigned /*DataLen*/) {
00882     using namespace clang::io;
00883 
00884     ino_t ino = (ino_t) ReadUnalignedLE32(d);
00885     dev_t dev = (dev_t) ReadUnalignedLE32(d);
00886     mode_t mode = (mode_t) ReadUnalignedLE16(d);
00887     time_t mtime = (time_t) ReadUnalignedLE64(d);
00888     off_t size = (off_t) ReadUnalignedLE64(d);
00889     return data_type(ino, dev, mode, mtime, size);
00890   }
00891 };
00892 
00893 /// \brief stat() cache for precompiled headers.
00894 ///
00895 /// This cache is very similar to the stat cache used by pretokenized
00896 /// headers.
00897 class ASTStatCache : public FileSystemStatCache {
00898   typedef OnDiskChainedHashTable<ASTStatLookupTrait> CacheTy;
00899   CacheTy *Cache;
00900 
00901   unsigned &NumStatHits, &NumStatMisses;
00902 public:
00903   ASTStatCache(const unsigned char *Buckets, const unsigned char *Base,
00904                unsigned &NumStatHits, unsigned &NumStatMisses)
00905     : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
00906     Cache = CacheTy::Create(Buckets, Base);
00907   }
00908 
00909   ~ASTStatCache() { delete Cache; }
00910 
00911   LookupResult getStat(const char *Path, struct stat &StatBuf,
00912                        int *FileDescriptor) {
00913     // Do the lookup for the file's data in the AST file.
00914     CacheTy::iterator I = Cache->find(Path);
00915 
00916     // If we don't get a hit in the AST file just forward to 'stat'.
00917     if (I == Cache->end()) {
00918       ++NumStatMisses;
00919       return statChained(Path, StatBuf, FileDescriptor);
00920     }
00921 
00922     ++NumStatHits;
00923     ASTStatData Data = *I;
00924 
00925     StatBuf.st_ino = Data.ino;
00926     StatBuf.st_dev = Data.dev;
00927     StatBuf.st_mtime = Data.mtime;
00928     StatBuf.st_mode = Data.mode;
00929     StatBuf.st_size = Data.size;
00930     return CacheExists;
00931   }
00932 };
00933 } // end anonymous namespace
00934 
00935 
00936 /// \brief Read a source manager block
00937 ASTReader::ASTReadResult ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
00938   using namespace SrcMgr;
00939 
00940   llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
00941 
00942   // Set the source-location entry cursor to the current position in
00943   // the stream. This cursor will be used to read the contents of the
00944   // source manager block initially, and then lazily read
00945   // source-location entries as needed.
00946   SLocEntryCursor = F.Stream;
00947 
00948   // The stream itself is going to skip over the source manager block.
00949   if (F.Stream.SkipBlock()) {
00950     Error("malformed block record in AST file");
00951     return Failure;
00952   }
00953 
00954   // Enter the source manager block.
00955   if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
00956     Error("malformed source manager block record in AST file");
00957     return Failure;
00958   }
00959 
00960   RecordData Record;
00961   while (true) {
00962     unsigned Code = SLocEntryCursor.ReadCode();
00963     if (Code == llvm::bitc::END_BLOCK) {
00964       if (SLocEntryCursor.ReadBlockEnd()) {
00965         Error("error at end of Source Manager block in AST file");
00966         return Failure;
00967       }
00968       return Success;
00969     }
00970 
00971     if (Code == llvm::bitc::ENTER_SUBBLOCK) {
00972       // No known subblocks, always skip them.
00973       SLocEntryCursor.ReadSubBlockID();
00974       if (SLocEntryCursor.SkipBlock()) {
00975         Error("malformed block record in AST file");
00976         return Failure;
00977       }
00978       continue;
00979     }
00980 
00981     if (Code == llvm::bitc::DEFINE_ABBREV) {
00982       SLocEntryCursor.ReadAbbrevRecord();
00983       continue;
00984     }
00985 
00986     // Read a record.
00987     const char *BlobStart;
00988     unsigned BlobLen;
00989     Record.clear();
00990     switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
00991     default:  // Default behavior: ignore.
00992       break;
00993 
00994     case SM_SLOC_FILE_ENTRY:
00995     case SM_SLOC_BUFFER_ENTRY:
00996     case SM_SLOC_EXPANSION_ENTRY:
00997       // Once we hit one of the source location entries, we're done.
00998       return Success;
00999     }
01000   }
01001 }
01002 
01003 /// \brief If a header file is not found at the path that we expect it to be
01004 /// and the PCH file was moved from its original location, try to resolve the
01005 /// file by assuming that header+PCH were moved together and the header is in
01006 /// the same place relative to the PCH.
01007 static std::string
01008 resolveFileRelativeToOriginalDir(const std::string &Filename,
01009                                  const std::string &OriginalDir,
01010                                  const std::string &CurrDir) {
01011   assert(OriginalDir != CurrDir &&
01012          "No point trying to resolve the file if the PCH dir didn't change");
01013   using namespace llvm::sys;
01014   SmallString<128> filePath(Filename);
01015   fs::make_absolute(filePath);
01016   assert(path::is_absolute(OriginalDir));
01017   SmallString<128> currPCHPath(CurrDir);
01018 
01019   path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
01020                        fileDirE = path::end(path::parent_path(filePath));
01021   path::const_iterator origDirI = path::begin(OriginalDir),
01022                        origDirE = path::end(OriginalDir);
01023   // Skip the common path components from filePath and OriginalDir.
01024   while (fileDirI != fileDirE && origDirI != origDirE &&
01025          *fileDirI == *origDirI) {
01026     ++fileDirI;
01027     ++origDirI;
01028   }
01029   for (; origDirI != origDirE; ++origDirI)
01030     path::append(currPCHPath, "..");
01031   path::append(currPCHPath, fileDirI, fileDirE);
01032   path::append(currPCHPath, path::filename(Filename));
01033   return currPCHPath.str();
01034 }
01035 
01036 /// \brief Read in the source location entry with the given ID.
01037 ASTReader::ASTReadResult ASTReader::ReadSLocEntryRecord(int ID) {
01038   if (ID == 0)
01039     return Success;
01040 
01041   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
01042     Error("source location entry ID out-of-range for AST file");
01043     return Failure;
01044   }
01045 
01046   ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
01047   F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
01048   llvm::BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
01049   unsigned BaseOffset = F->SLocEntryBaseOffset;
01050 
01051   ++NumSLocEntriesRead;
01052   unsigned Code = SLocEntryCursor.ReadCode();
01053   if (Code == llvm::bitc::END_BLOCK ||
01054       Code == llvm::bitc::ENTER_SUBBLOCK ||
01055       Code == llvm::bitc::DEFINE_ABBREV) {
01056     Error("incorrectly-formatted source location entry in AST file");
01057     return Failure;
01058   }
01059 
01060   RecordData Record;
01061   const char *BlobStart;
01062   unsigned BlobLen;
01063   switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
01064   default:
01065     Error("incorrectly-formatted source location entry in AST file");
01066     return Failure;
01067 
01068   case SM_SLOC_FILE_ENTRY: {
01069     if (Record.size() < 7) {
01070       Error("source location entry is incorrect");
01071       return Failure;
01072     }
01073 
01074     // We will detect whether a file changed and return 'Failure' for it, but
01075     // we will also try to fail gracefully by setting up the SLocEntry.
01076     ASTReader::ASTReadResult Result = Success;
01077 
01078     bool OverriddenBuffer = Record[6];
01079     
01080     std::string OrigFilename(BlobStart, BlobStart + BlobLen);
01081     std::string Filename = OrigFilename;
01082     MaybeAddSystemRootToFilename(Filename);
01083     const FileEntry *File = 
01084       OverriddenBuffer? FileMgr.getVirtualFile(Filename, (off_t)Record[4],
01085                                                (time_t)Record[5])
01086                       : FileMgr.getFile(Filename, /*OpenFile=*/false);
01087     if (File == 0 && !OriginalDir.empty() && !CurrentDir.empty() &&
01088         OriginalDir != CurrentDir) {
01089       std::string resolved = resolveFileRelativeToOriginalDir(Filename,
01090                                                               OriginalDir,
01091                                                               CurrentDir);
01092       if (!resolved.empty())
01093         File = FileMgr.getFile(resolved);
01094     }
01095     if (File == 0)
01096       File = FileMgr.getVirtualFile(Filename, (off_t)Record[4],
01097                                     (time_t)Record[5]);
01098     if (File == 0) {
01099       std::string ErrorStr = "could not find file '";
01100       ErrorStr += Filename;
01101       ErrorStr += "' referenced by AST file";
01102       Error(ErrorStr.c_str());
01103       return Failure;
01104     }
01105 
01106     if (!DisableValidation &&
01107         ((off_t)Record[4] != File->getSize()
01108 #if !defined(LLVM_ON_WIN32)
01109         // In our regression testing, the Windows file system seems to
01110         // have inconsistent modification times that sometimes
01111         // erroneously trigger this error-handling path.
01112          || (time_t)Record[5] != File->getModificationTime()
01113 #endif
01114         )) {
01115       Error(diag::err_fe_pch_file_modified, Filename);
01116       Result = Failure;
01117     }
01118 
01119     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
01120     if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
01121       // This is the module's main file.
01122       IncludeLoc = getImportLocation(F);
01123     }
01124     FileID FID = SourceMgr.createFileID(File, IncludeLoc,
01125                                         (SrcMgr::CharacteristicKind)Record[2],
01126                                         ID, BaseOffset + Record[0]);
01127     SrcMgr::FileInfo &FileInfo =
01128           const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
01129     FileInfo.NumCreatedFIDs = Record[7];
01130     if (Record[3])
01131       FileInfo.setHasLineDirectives();
01132 
01133     const DeclID *FirstDecl = F->FileSortedDecls + Record[8];
01134     unsigned NumFileDecls = Record[9];
01135     if (NumFileDecls) {
01136       assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
01137       FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
01138                                                              NumFileDecls));
01139     }
01140     
01141     const SrcMgr::ContentCache *ContentCache
01142       = SourceMgr.getOrCreateContentCache(File);
01143     if (OverriddenBuffer && !ContentCache->BufferOverridden &&
01144         ContentCache->ContentsEntry == ContentCache->OrigEntry) {
01145       unsigned Code = SLocEntryCursor.ReadCode();
01146       Record.clear();
01147       unsigned RecCode
01148         = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
01149       
01150       if (RecCode != SM_SLOC_BUFFER_BLOB) {
01151         Error("AST record has invalid code");
01152         return Failure;
01153       }
01154       
01155       llvm::MemoryBuffer *Buffer
01156         = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
01157                                            Filename);
01158       SourceMgr.overrideFileContents(File, Buffer);
01159     }
01160 
01161     if (Result == Failure)
01162       return Failure;
01163     break;
01164   }
01165 
01166   case SM_SLOC_BUFFER_ENTRY: {
01167     const char *Name = BlobStart;
01168     unsigned Offset = Record[0];
01169     unsigned Code = SLocEntryCursor.ReadCode();
01170     Record.clear();
01171     unsigned RecCode
01172       = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
01173 
01174     if (RecCode != SM_SLOC_BUFFER_BLOB) {
01175       Error("AST record has invalid code");
01176       return Failure;
01177     }
01178 
01179     llvm::MemoryBuffer *Buffer
01180       = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
01181                                          Name);
01182     FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID,
01183                                                          BaseOffset + Offset);
01184 
01185     if (strcmp(Name, "<built-in>") == 0 && F->Kind == MK_PCH) {
01186       PCHPredefinesBlock Block = {
01187         BufferID,
01188         StringRef(BlobStart, BlobLen - 1)
01189       };
01190       PCHPredefinesBuffers.push_back(Block);
01191     }
01192 
01193     break;
01194   }
01195 
01196   case SM_SLOC_EXPANSION_ENTRY: {
01197     SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
01198     SourceMgr.createExpansionLoc(SpellingLoc,
01199                                      ReadSourceLocation(*F, Record[2]),
01200                                      ReadSourceLocation(*F, Record[3]),
01201                                      Record[4],
01202                                      ID,
01203                                      BaseOffset + Record[0]);
01204     break;
01205   }
01206   }
01207 
01208   return Success;
01209 }
01210 
01211 /// \brief Find the location where the module F is imported.
01212 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
01213   if (F->ImportLoc.isValid())
01214     return F->ImportLoc;
01215   
01216   // Otherwise we have a PCH. It's considered to be "imported" at the first
01217   // location of its includer.
01218   if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
01219     // Main file is the importer. We assume that it is the first entry in the
01220     // entry table. We can't ask the manager, because at the time of PCH loading
01221     // the main file entry doesn't exist yet.
01222     // The very first entry is the invalid instantiation loc, which takes up
01223     // offsets 0 and 1.
01224     return SourceLocation::getFromRawEncoding(2U);
01225   }
01226   //return F->Loaders[0]->FirstLoc;
01227   return F->ImportedBy[0]->FirstLoc;
01228 }
01229 
01230 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
01231 /// specified cursor.  Read the abbreviations that are at the top of the block
01232 /// and then leave the cursor pointing into the block.
01233 bool ASTReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
01234                                  unsigned BlockID) {
01235   if (Cursor.EnterSubBlock(BlockID)) {
01236     Error("malformed block record in AST file");
01237     return Failure;
01238   }
01239 
01240   while (true) {
01241     uint64_t Offset = Cursor.GetCurrentBitNo();
01242     unsigned Code = Cursor.ReadCode();
01243 
01244     // We expect all abbrevs to be at the start of the block.
01245     if (Code != llvm::bitc::DEFINE_ABBREV) {
01246       Cursor.JumpToBit(Offset);
01247       return false;
01248     }
01249     Cursor.ReadAbbrevRecord();
01250   }
01251 }
01252 
01253 void ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
01254   llvm::BitstreamCursor &Stream = F.MacroCursor;
01255 
01256   // Keep track of where we are in the stream, then jump back there
01257   // after reading this macro.
01258   SavedStreamPosition SavedPosition(Stream);
01259 
01260   Stream.JumpToBit(Offset);
01261   RecordData Record;
01262   SmallVector<IdentifierInfo*, 16> MacroArgs;
01263   MacroInfo *Macro = 0;
01264 
01265   while (true) {
01266     unsigned Code = Stream.ReadCode();
01267     switch (Code) {
01268     case llvm::bitc::END_BLOCK:
01269       return;
01270 
01271     case llvm::bitc::ENTER_SUBBLOCK:
01272       // No known subblocks, always skip them.
01273       Stream.ReadSubBlockID();
01274       if (Stream.SkipBlock()) {
01275         Error("malformed block record in AST file");
01276         return;
01277       }
01278       continue;
01279 
01280     case llvm::bitc::DEFINE_ABBREV:
01281       Stream.ReadAbbrevRecord();
01282       continue;
01283     default: break;
01284     }
01285 
01286     // Read a record.
01287     const char *BlobStart = 0;
01288     unsigned BlobLen = 0;
01289     Record.clear();
01290     PreprocessorRecordTypes RecType =
01291       (PreprocessorRecordTypes)Stream.ReadRecord(Code, Record, BlobStart,
01292                                                  BlobLen);
01293     switch (RecType) {
01294     case PP_MACRO_OBJECT_LIKE:
01295     case PP_MACRO_FUNCTION_LIKE: {
01296       // If we already have a macro, that means that we've hit the end
01297       // of the definition of the macro we were looking for. We're
01298       // done.
01299       if (Macro)
01300         return;
01301 
01302       IdentifierInfo *II = getLocalIdentifier(F, Record[0]);
01303       if (II == 0) {
01304         Error("macro must have a name in AST file");
01305         return;
01306       }
01307       
01308       SourceLocation Loc = ReadSourceLocation(F, Record[1]);
01309       bool isUsed = Record[2];
01310 
01311       MacroInfo *MI = PP.AllocateMacroInfo(Loc);
01312       MI->setIsUsed(isUsed);
01313       MI->setIsFromAST();
01314 
01315       bool IsPublic = Record[3];
01316       unsigned NextIndex = 4;
01317       MI->setVisibility(IsPublic, ReadSourceLocation(F, Record, NextIndex));
01318       
01319       if (RecType == PP_MACRO_FUNCTION_LIKE) {
01320         // Decode function-like macro info.
01321         bool isC99VarArgs = Record[NextIndex++];
01322         bool isGNUVarArgs = Record[NextIndex++];
01323         MacroArgs.clear();
01324         unsigned NumArgs = Record[NextIndex++];
01325         for (unsigned i = 0; i != NumArgs; ++i)
01326           MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
01327 
01328         // Install function-like macro info.
01329         MI->setIsFunctionLike();
01330         if (isC99VarArgs) MI->setIsC99Varargs();
01331         if (isGNUVarArgs) MI->setIsGNUVarargs();
01332         MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
01333                             PP.getPreprocessorAllocator());
01334       }
01335 
01336       // Finally, install the macro.
01337       PP.setMacroInfo(II, MI, /*LoadedFromAST=*/true);
01338 
01339       // Remember that we saw this macro last so that we add the tokens that
01340       // form its body to it.
01341       Macro = MI;
01342 
01343       if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
01344           Record[NextIndex]) {
01345         // We have a macro definition. Register the association
01346         PreprocessedEntityID
01347             GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
01348         PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
01349         PPRec.RegisterMacroDefinition(Macro,
01350                             PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true));
01351       }
01352 
01353       ++NumMacrosRead;
01354       break;
01355     }
01356 
01357     case PP_TOKEN: {
01358       // If we see a TOKEN before a PP_MACRO_*, then the file is
01359       // erroneous, just pretend we didn't see this.
01360       if (Macro == 0) break;
01361 
01362       Token Tok;
01363       Tok.startToken();
01364       Tok.setLocation(ReadSourceLocation(F, Record[0]));
01365       Tok.setLength(Record[1]);
01366       if (IdentifierInfo *II = getLocalIdentifier(F, Record[2]))
01367         Tok.setIdentifierInfo(II);
01368       Tok.setKind((tok::TokenKind)Record[3]);
01369       Tok.setFlag((Token::TokenFlags)Record[4]);
01370       Macro->AddTokenToBody(Tok);
01371       break;
01372     }
01373     }
01374   }
01375 }
01376 
01377 PreprocessedEntityID 
01378 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
01379   ContinuousRangeMap<uint32_t, int, 2>::const_iterator 
01380     I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
01381   assert(I != M.PreprocessedEntityRemap.end() 
01382          && "Invalid index into preprocessed entity index remap");
01383   
01384   return LocalID + I->second;
01385 }
01386 
01387 unsigned HeaderFileInfoTrait::ComputeHash(const char *path) {
01388   return llvm::HashString(llvm::sys::path::filename(path));
01389 }
01390     
01391 HeaderFileInfoTrait::internal_key_type 
01392 HeaderFileInfoTrait::GetInternalKey(const char *path) { return path; }
01393     
01394 bool HeaderFileInfoTrait::EqualKey(internal_key_type a, internal_key_type b) {
01395   if (strcmp(a, b) == 0)
01396     return true;
01397   
01398   if (llvm::sys::path::filename(a) != llvm::sys::path::filename(b))
01399     return false;
01400 
01401   // Determine whether the actual files are equivalent.
01402   bool Result = false;
01403   if (llvm::sys::fs::equivalent(a, b, Result))
01404     return false;
01405   
01406   return Result;
01407 }
01408     
01409 std::pair<unsigned, unsigned>
01410 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
01411   unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
01412   unsigned DataLen = (unsigned) *d++;
01413   return std::make_pair(KeyLen + 1, DataLen);
01414 }
01415     
01416 HeaderFileInfoTrait::data_type 
01417 HeaderFileInfoTrait::ReadData(const internal_key_type, const unsigned char *d,
01418                               unsigned DataLen) {
01419   const unsigned char *End = d + DataLen;
01420   using namespace clang::io;
01421   HeaderFileInfo HFI;
01422   unsigned Flags = *d++;
01423   HFI.isImport = (Flags >> 5) & 0x01;
01424   HFI.isPragmaOnce = (Flags >> 4) & 0x01;
01425   HFI.DirInfo = (Flags >> 2) & 0x03;
01426   HFI.Resolved = (Flags >> 1) & 0x01;
01427   HFI.IndexHeaderMapHeader = Flags & 0x01;
01428   HFI.NumIncludes = ReadUnalignedLE16(d);
01429   HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M, 
01430                                                         ReadUnalignedLE32(d));
01431   if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
01432     // The framework offset is 1 greater than the actual offset, 
01433     // since 0 is used as an indicator for "no framework name".
01434     StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
01435     HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
01436   }
01437   
01438   assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
01439   (void)End;
01440         
01441   // This HeaderFileInfo was externally loaded.
01442   HFI.External = true;
01443   return HFI;
01444 }
01445 
01446 void ASTReader::setIdentifierIsMacro(IdentifierInfo *II, ModuleFile &F,
01447                                      uint64_t LocalOffset, bool Visible) {
01448   if (Visible) {
01449     // Note that this identifier has a macro definition.
01450     II->setHasMacroDefinition(true);
01451   }
01452   
01453   // Adjust the offset to a global offset.
01454   UnreadMacroRecordOffsets[II] = F.GlobalBitOffset + LocalOffset;
01455 }
01456 
01457 void ASTReader::ReadDefinedMacros() {
01458   for (ModuleReverseIterator I = ModuleMgr.rbegin(),
01459       E = ModuleMgr.rend(); I != E; ++I) {
01460     llvm::BitstreamCursor &MacroCursor = (*I)->MacroCursor;
01461 
01462     // If there was no preprocessor block, skip this file.
01463     if (!MacroCursor.getBitStreamReader())
01464       continue;
01465 
01466     llvm::BitstreamCursor Cursor = MacroCursor;
01467     Cursor.JumpToBit((*I)->MacroStartOffset);
01468 
01469     RecordData Record;
01470     while (true) {
01471       unsigned Code = Cursor.ReadCode();
01472       if (Code == llvm::bitc::END_BLOCK)
01473         break;
01474 
01475       if (Code == llvm::bitc::ENTER_SUBBLOCK) {
01476         // No known subblocks, always skip them.
01477         Cursor.ReadSubBlockID();
01478         if (Cursor.SkipBlock()) {
01479           Error("malformed block record in AST file");
01480           return;
01481         }
01482         continue;
01483       }
01484 
01485       if (Code == llvm::bitc::DEFINE_ABBREV) {
01486         Cursor.ReadAbbrevRecord();
01487         continue;
01488       }
01489 
01490       // Read a record.
01491       const char *BlobStart;
01492       unsigned BlobLen;
01493       Record.clear();
01494       switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
01495       default:  // Default behavior: ignore.
01496         break;
01497 
01498       case PP_MACRO_OBJECT_LIKE:
01499       case PP_MACRO_FUNCTION_LIKE:
01500         getLocalIdentifier(**I, Record[0]);
01501         break;
01502 
01503       case PP_TOKEN:
01504         // Ignore tokens.
01505         break;
01506       }
01507     }
01508   }
01509   
01510   // Drain the unread macro-record offsets map.
01511   while (!UnreadMacroRecordOffsets.empty())
01512     LoadMacroDefinition(UnreadMacroRecordOffsets.begin());
01513 }
01514 
01515 void ASTReader::LoadMacroDefinition(
01516                     llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos) {
01517   assert(Pos != UnreadMacroRecordOffsets.end() && "Unknown macro definition");
01518   uint64_t Offset = Pos->second;
01519   UnreadMacroRecordOffsets.erase(Pos);
01520   
01521   RecordLocation Loc = getLocalBitOffset(Offset);
01522   ReadMacroRecord(*Loc.F, Loc.Offset);
01523 }
01524 
01525 void ASTReader::LoadMacroDefinition(IdentifierInfo *II) {
01526   llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos
01527     = UnreadMacroRecordOffsets.find(II);
01528   LoadMacroDefinition(Pos);
01529 }
01530 
01531 namespace {
01532   /// \brief Visitor class used to look up identifirs in an AST file.
01533   class IdentifierLookupVisitor {
01534     StringRef Name;
01535     unsigned PriorGeneration;
01536     IdentifierInfo *Found;
01537   public:
01538     IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration) 
01539       : Name(Name), PriorGeneration(PriorGeneration), Found() { }
01540     
01541     static bool visit(ModuleFile &M, void *UserData) {
01542       IdentifierLookupVisitor *This
01543         = static_cast<IdentifierLookupVisitor *>(UserData);
01544       
01545       // If we've already searched this module file, skip it now.
01546       if (M.Generation <= This->PriorGeneration)
01547         return true;
01548       
01549       ASTIdentifierLookupTable *IdTable
01550         = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
01551       if (!IdTable)
01552         return false;
01553       
01554       ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
01555                                      M, This->Found);
01556                                      
01557       std::pair<const char*, unsigned> Key(This->Name.begin(), 
01558                                            This->Name.size());
01559       ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Trait);
01560       if (Pos == IdTable->end())
01561         return false;
01562       
01563       // Dereferencing the iterator has the effect of building the
01564       // IdentifierInfo node and populating it with the various
01565       // declarations it needs.
01566       This->Found = *Pos;
01567       return true;
01568     }
01569     
01570     // \brief Retrieve the identifier info found within the module
01571     // files.
01572     IdentifierInfo *getIdentifierInfo() const { return Found; }
01573   };
01574 }
01575 
01576 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
01577   unsigned PriorGeneration = 0;
01578   if (getContext().getLangOpts().Modules)
01579     PriorGeneration = IdentifierGeneration[&II];
01580   
01581   IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration);
01582   ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
01583   markIdentifierUpToDate(&II);
01584 }
01585 
01586 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
01587   if (!II)
01588     return;
01589   
01590   II->setOutOfDate(false);
01591 
01592   // Update the generation for this identifier.
01593   if (getContext().getLangOpts().Modules)
01594     IdentifierGeneration[II] = CurrentGeneration;
01595 }
01596 
01597 const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
01598   std::string Filename = filenameStrRef;
01599   MaybeAddSystemRootToFilename(Filename);
01600   const FileEntry *File = FileMgr.getFile(Filename);
01601   if (File == 0 && !OriginalDir.empty() && !CurrentDir.empty() &&
01602       OriginalDir != CurrentDir) {
01603     std::string resolved = resolveFileRelativeToOriginalDir(Filename,
01604                                                             OriginalDir,
01605                                                             CurrentDir);
01606     if (!resolved.empty())
01607       File = FileMgr.getFile(resolved);
01608   }
01609 
01610   return File;
01611 }
01612 
01613 /// \brief If we are loading a relocatable PCH file, and the filename is
01614 /// not an absolute path, add the system root to the beginning of the file
01615 /// name.
01616 void ASTReader::MaybeAddSystemRootToFilename(std::string &Filename) {
01617   // If this is not a relocatable PCH file, there's nothing to do.
01618   if (!RelocatablePCH)
01619     return;
01620 
01621   if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
01622     return;
01623 
01624   if (isysroot.empty()) {
01625     // If no system root was given, default to '/'
01626     Filename.insert(Filename.begin(), '/');
01627     return;
01628   }
01629 
01630   unsigned Length = isysroot.size();
01631   if (isysroot[Length - 1] != '/')
01632     Filename.insert(Filename.begin(), '/');
01633 
01634   Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
01635 }
01636 
01637 ASTReader::ASTReadResult
01638 ASTReader::ReadASTBlock(ModuleFile &F) {
01639   llvm::BitstreamCursor &Stream = F.Stream;
01640 
01641   if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
01642     Error("malformed block record in AST file");
01643     return Failure;
01644   }
01645 
01646   // Read all of the records and blocks for the ASt file.
01647   RecordData Record;
01648   while (!Stream.AtEndOfStream()) {
01649     unsigned Code = Stream.ReadCode();
01650     if (Code == llvm::bitc::END_BLOCK) {
01651       if (Stream.ReadBlockEnd()) {
01652         Error("error at end of module block in AST file");
01653         return Failure;
01654       }
01655 
01656       return Success;
01657     }
01658 
01659     if (Code == llvm::bitc::ENTER_SUBBLOCK) {
01660       switch (Stream.ReadSubBlockID()) {
01661       case DECLTYPES_BLOCK_ID:
01662         // We lazily load the decls block, but we want to set up the
01663         // DeclsCursor cursor to point into it.  Clone our current bitcode
01664         // cursor to it, enter the block and read the abbrevs in that block.
01665         // With the main cursor, we just skip over it.
01666         F.DeclsCursor = Stream;
01667         if (Stream.SkipBlock() ||  // Skip with the main cursor.
01668             // Read the abbrevs.
01669             ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
01670           Error("malformed block record in AST file");
01671           return Failure;
01672         }
01673         break;
01674 
01675       case DECL_UPDATES_BLOCK_ID:
01676         if (Stream.SkipBlock()) {
01677           Error("malformed block record in AST file");
01678           return Failure;
01679         }
01680         break;
01681 
01682       case PREPROCESSOR_BLOCK_ID:
01683         F.MacroCursor = Stream;
01684         if (!PP.getExternalSource())
01685           PP.setExternalSource(this);
01686 
01687         if (Stream.SkipBlock() ||
01688             ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
01689           Error("malformed block record in AST file");
01690           return Failure;
01691         }
01692         F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
01693         break;
01694 
01695       case PREPROCESSOR_DETAIL_BLOCK_ID:
01696         F.PreprocessorDetailCursor = Stream;
01697         if (Stream.SkipBlock() ||
01698             ReadBlockAbbrevs(F.PreprocessorDetailCursor, 
01699                              PREPROCESSOR_DETAIL_BLOCK_ID)) {
01700           Error("malformed preprocessor detail record in AST file");
01701           return Failure;
01702         }
01703         F.PreprocessorDetailStartOffset
01704           = F.PreprocessorDetailCursor.GetCurrentBitNo();
01705           
01706         if (!PP.getPreprocessingRecord())
01707           PP.createPreprocessingRecord(/*RecordConditionalDirectives=*/false);
01708         if (!PP.getPreprocessingRecord()->getExternalSource())
01709           PP.getPreprocessingRecord()->SetExternalSource(*this);
01710         break;
01711         
01712       case SOURCE_MANAGER_BLOCK_ID:
01713         switch (ReadSourceManagerBlock(F)) {
01714         case Success:
01715           break;
01716 
01717         case Failure:
01718           Error("malformed source manager block in AST file");
01719           return Failure;
01720 
01721         case IgnorePCH:
01722           return IgnorePCH;
01723         }
01724         break;
01725 
01726       case SUBMODULE_BLOCK_ID:
01727         switch (ReadSubmoduleBlock(F)) {
01728         case Success:
01729           break;
01730           
01731         case Failure:
01732           Error("malformed submodule block in AST file");
01733           return Failure;
01734           
01735         case IgnorePCH:
01736           return IgnorePCH;            
01737         }
01738         break;
01739 
01740       default:
01741         if (!Stream.SkipBlock())
01742           break;
01743         Error("malformed block record in AST file");
01744         return Failure;
01745       }
01746       continue;
01747     }
01748 
01749     if (Code == llvm::bitc::DEFINE_ABBREV) {
01750       Stream.ReadAbbrevRecord();
01751       continue;
01752     }
01753 
01754     // Read and process a record.
01755     Record.clear();
01756     const char *BlobStart = 0;
01757     unsigned BlobLen = 0;
01758     switch ((ASTRecordTypes)Stream.ReadRecord(Code, Record,
01759                                               &BlobStart, &BlobLen)) {
01760     default:  // Default behavior: ignore.
01761       break;
01762 
01763     case METADATA: {
01764       if (Record[0] != VERSION_MAJOR && !DisableValidation) {
01765         Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
01766                                            : diag::warn_pch_version_too_new);
01767         return IgnorePCH;
01768       }
01769 
01770       bool hasErrors = Record[5];
01771       if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
01772         Diag(diag::err_pch_with_compiler_errors);
01773         return IgnorePCH;
01774       }
01775 
01776       RelocatablePCH = Record[4];
01777       if (Listener) {
01778         std::string TargetTriple(BlobStart, BlobLen);
01779         if (Listener->ReadTargetTriple(TargetTriple))
01780           return IgnorePCH;
01781       }
01782       break;
01783     }
01784 
01785     case IMPORTS: {
01786       // Load each of the imported PCH files. 
01787       unsigned Idx = 0, N = Record.size();
01788       while (Idx < N) {
01789         // Read information about the AST file.
01790         ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
01791         unsigned Length = Record[Idx++];
01792         SmallString<128> ImportedFile(Record.begin() + Idx,
01793                                             Record.begin() + Idx + Length);
01794         Idx += Length;
01795 
01796         // Load the AST file.
01797         switch(ReadASTCore(ImportedFile, ImportedKind, &F)) {
01798         case Failure: return Failure;
01799           // If we have to ignore the dependency, we'll have to ignore this too.
01800         case IgnorePCH: return IgnorePCH;
01801         case Success: break;
01802         }
01803       }
01804       break;
01805     }
01806 
01807     case TYPE_OFFSET: {
01808       if (F.LocalNumTypes != 0) {
01809         Error("duplicate TYPE_OFFSET record in AST file");
01810         return Failure;
01811       }
01812       F.TypeOffsets = (const uint32_t *)BlobStart;
01813       F.LocalNumTypes = Record[0];
01814       unsigned LocalBaseTypeIndex = Record[1];
01815       F.BaseTypeIndex = getTotalNumTypes();
01816         
01817       if (F.LocalNumTypes > 0) {
01818         // Introduce the global -> local mapping for types within this module.
01819         GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
01820         
01821         // Introduce the local -> global mapping for types within this module.
01822         F.TypeRemap.insertOrReplace(
01823           std::make_pair(LocalBaseTypeIndex, 
01824                          F.BaseTypeIndex - LocalBaseTypeIndex));
01825         
01826         TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
01827       }
01828       break;
01829     }
01830         
01831     case DECL_OFFSET: {
01832       if (F.LocalNumDecls != 0) {
01833         Error("duplicate DECL_OFFSET record in AST file");
01834         return Failure;
01835       }
01836       F.DeclOffsets = (const DeclOffset *)BlobStart;
01837       F.LocalNumDecls = Record[0];
01838       unsigned LocalBaseDeclID = Record[1];
01839       F.BaseDeclID = getTotalNumDecls();
01840         
01841       if (F.LocalNumDecls > 0) {
01842         // Introduce the global -> local mapping for declarations within this 
01843         // module.
01844         GlobalDeclMap.insert(
01845           std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
01846         
01847         // Introduce the local -> global mapping for declarations within this
01848         // module.
01849         F.DeclRemap.insertOrReplace(
01850           std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
01851         
01852         // Introduce the global -> local mapping for declarations within this
01853         // module.
01854         F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
01855         
01856         DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
01857       }
01858       break;
01859     }
01860         
01861     case TU_UPDATE_LEXICAL: {
01862       DeclContext *TU = Context.getTranslationUnitDecl();
01863       DeclContextInfo &Info = F.DeclContextInfos[TU];
01864       Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(BlobStart);
01865       Info.NumLexicalDecls 
01866         = static_cast<unsigned int>(BlobLen / sizeof(KindDeclIDPair));
01867       TU->setHasExternalLexicalStorage(true);
01868       break;
01869     }
01870 
01871     case UPDATE_VISIBLE: {
01872       unsigned Idx = 0;
01873       serialization::DeclID ID = ReadDeclID(F, Record, Idx);
01874       ASTDeclContextNameLookupTable *Table =
01875         ASTDeclContextNameLookupTable::Create(
01876                         (const unsigned char *)BlobStart + Record[Idx++],
01877                         (const unsigned char *)BlobStart,
01878                         ASTDeclContextNameLookupTrait(*this, F));
01879       if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
01880         DeclContext *TU = Context.getTranslationUnitDecl();
01881         F.DeclContextInfos[TU].NameLookupTableData = Table;
01882         TU->setHasExternalVisibleStorage(true);
01883       } else
01884         PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
01885       break;
01886     }
01887 
01888     case LANGUAGE_OPTIONS:
01889       if (ParseLanguageOptions(Record) && !DisableValidation)
01890         return IgnorePCH;
01891       break;
01892 
01893     case IDENTIFIER_TABLE:
01894       F.IdentifierTableData = BlobStart;
01895       if (Record[0]) {
01896         F.IdentifierLookupTable
01897           = ASTIdentifierLookupTable::Create(
01898                        (const unsigned char *)F.IdentifierTableData + Record[0],
01899                        (const unsigned char *)F.IdentifierTableData,
01900                        ASTIdentifierLookupTrait(*this, F));
01901         
01902         PP.getIdentifierTable().setExternalIdentifierLookup(this);
01903       }
01904       break;
01905 
01906     case IDENTIFIER_OFFSET: {
01907       if (F.LocalNumIdentifiers != 0) {
01908         Error("duplicate IDENTIFIER_OFFSET record in AST file");
01909         return Failure;
01910       }
01911       F.IdentifierOffsets = (const uint32_t *)BlobStart;
01912       F.LocalNumIdentifiers = Record[0];
01913       unsigned LocalBaseIdentifierID = Record[1];
01914       F.BaseIdentifierID = getTotalNumIdentifiers();
01915         
01916       if (F.LocalNumIdentifiers > 0) {
01917         // Introduce the global -> local mapping for identifiers within this
01918         // module.
01919         GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1, 
01920                                                   &F));
01921         
01922         // Introduce the local -> global mapping for identifiers within this
01923         // module.
01924         F.IdentifierRemap.insertOrReplace(
01925           std::make_pair(LocalBaseIdentifierID,
01926                          F.BaseIdentifierID - LocalBaseIdentifierID));
01927         
01928         IdentifiersLoaded.resize(IdentifiersLoaded.size() 
01929                                  + F.LocalNumIdentifiers);
01930       }
01931       break;
01932     }
01933         
01934     case EXTERNAL_DEFINITIONS:
01935       for (unsigned I = 0, N = Record.size(); I != N; ++I)
01936         ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
01937       break;
01938 
01939     case SPECIAL_TYPES:
01940       for (unsigned I = 0, N = Record.size(); I != N; ++I)
01941         SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
01942       break;
01943 
01944     case STATISTICS:
01945       TotalNumStatements += Record[0];
01946       TotalNumMacros += Record[1];
01947       TotalLexicalDeclContexts += Record[2];
01948       TotalVisibleDeclContexts += Record[3];
01949       break;
01950 
01951     case UNUSED_FILESCOPED_DECLS:
01952       for (unsigned I = 0, N = Record.size(); I != N; ++I)
01953         UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
01954       break;
01955 
01956     case DELEGATING_CTORS:
01957       for (unsigned I = 0, N = Record.size(); I != N; ++I)
01958         DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
01959       break;
01960 
01961     case WEAK_UNDECLARED_IDENTIFIERS:
01962       if (Record.size() % 4 != 0) {
01963         Error("invalid weak identifiers record");
01964         return Failure;
01965       }
01966         
01967       // FIXME: Ignore weak undeclared identifiers from non-original PCH 
01968       // files. This isn't the way to do it :)
01969       WeakUndeclaredIdentifiers.clear();
01970         
01971       // Translate the weak, undeclared identifiers into global IDs.
01972       for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
01973         WeakUndeclaredIdentifiers.push_back(
01974           getGlobalIdentifierID(F, Record[I++]));
01975         WeakUndeclaredIdentifiers.push_back(
01976           getGlobalIdentifierID(F, Record[I++]));
01977         WeakUndeclaredIdentifiers.push_back(
01978           ReadSourceLocation(F, Record, I).getRawEncoding());
01979         WeakUndeclaredIdentifiers.push_back(Record[I++]);
01980       }
01981       break;
01982 
01983     case LOCALLY_SCOPED_EXTERNAL_DECLS:
01984       for (unsigned I = 0, N = Record.size(); I != N; ++I)
01985         LocallyScopedExternalDecls.push_back(getGlobalDeclID(F, Record[I]));
01986       break;
01987 
01988     case SELECTOR_OFFSETS: {
01989       F.SelectorOffsets = (const uint32_t *)BlobStart;
01990       F.LocalNumSelectors = Record[0];
01991       unsigned LocalBaseSelectorID = Record[1];
01992       F.BaseSelectorID = getTotalNumSelectors();
01993         
01994       if (F.LocalNumSelectors > 0) {
01995         // Introduce the global -> local mapping for selectors within this 
01996         // module.
01997         GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
01998         
01999         // Introduce the local -> global mapping for selectors within this 
02000         // module.
02001         F.SelectorRemap.insertOrReplace(
02002           std::make_pair(LocalBaseSelectorID,
02003                          F.BaseSelectorID - LocalBaseSelectorID));
02004 
02005         SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);        
02006       }
02007       break;
02008     }
02009         
02010     case METHOD_POOL:
02011       F.SelectorLookupTableData = (const unsigned char *)BlobStart;
02012       if (Record[0])
02013         F.SelectorLookupTable
02014           = ASTSelectorLookupTable::Create(
02015                         F.SelectorLookupTableData + Record[0],
02016                         F.SelectorLookupTableData,
02017                         ASTSelectorLookupTrait(*this, F));
02018       TotalNumMethodPoolEntries += Record[1];
02019       break;
02020 
02021     case REFERENCED_SELECTOR_POOL:
02022       if (!Record.empty()) {
02023         for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
02024           ReferencedSelectorsData.push_back(getGlobalSelectorID(F, 
02025                                                                 Record[Idx++]));
02026           ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
02027                                               getRawEncoding());
02028         }
02029       }
02030       break;
02031 
02032     case PP_COUNTER_VALUE:
02033       if (!Record.empty() && Listener)
02034         Listener->ReadCounter(Record[0]);
02035       break;
02036       
02037     case FILE_SORTED_DECLS:
02038       F.FileSortedDecls = (const DeclID *)BlobStart;
02039       break;
02040 
02041     case SOURCE_LOCATION_OFFSETS: {
02042       F.SLocEntryOffsets = (const uint32_t *)BlobStart;
02043       F.LocalNumSLocEntries = Record[0];
02044       unsigned SLocSpaceSize = Record[1];
02045       llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
02046           SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
02047                                               SLocSpaceSize);
02048       // Make our entry in the range map. BaseID is negative and growing, so
02049       // we invert it. Because we invert it, though, we need the other end of
02050       // the range.
02051       unsigned RangeStart =
02052           unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
02053       GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
02054       F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
02055 
02056       // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
02057       assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
02058       GlobalSLocOffsetMap.insert(
02059           std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
02060                            - SLocSpaceSize,&F));
02061 
02062       // Initialize the remapping table.
02063       // Invalid stays invalid.
02064       F.SLocRemap.insert(std::make_pair(0U, 0));
02065       // This module. Base was 2 when being compiled.
02066       F.SLocRemap.insert(std::make_pair(2U,
02067                                   static_cast<int>(F.SLocEntryBaseOffset - 2)));
02068       
02069       TotalNumSLocEntries += F.LocalNumSLocEntries;
02070       break;
02071     }
02072 
02073     case MODULE_OFFSET_MAP: {
02074       // Additional remapping information.
02075       const unsigned char *Data = (const unsigned char*)BlobStart;
02076       const unsigned char *DataEnd = Data + BlobLen;
02077       
02078       // Continuous range maps we may be updating in our module.
02079       ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
02080       ContinuousRangeMap<uint32_t, int, 2>::Builder 
02081         IdentifierRemap(F.IdentifierRemap);
02082       ContinuousRangeMap<uint32_t, int, 2>::Builder 
02083         PreprocessedEntityRemap(F.PreprocessedEntityRemap);
02084       ContinuousRangeMap<uint32_t, int, 2>::Builder 
02085         SubmoduleRemap(F.SubmoduleRemap);
02086       ContinuousRangeMap<uint32_t, int, 2>::Builder 
02087         SelectorRemap(F.SelectorRemap);
02088       ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
02089       ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
02090 
02091       while(Data < DataEnd) {
02092         uint16_t Len = io::ReadUnalignedLE16(Data);
02093         StringRef Name = StringRef((const char*)Data, Len);
02094         Data += Len;
02095         ModuleFile *OM = ModuleMgr.lookup(Name);
02096         if (!OM) {
02097           Error("SourceLocation remap refers to unknown module");
02098           return Failure;
02099         }
02100 
02101         uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
02102         uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
02103         uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
02104         uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
02105         uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
02106         uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
02107         uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
02108         
02109         // Source location offset is mapped to OM->SLocEntryBaseOffset.
02110         SLocRemap.insert(std::make_pair(SLocOffset,
02111           static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
02112         IdentifierRemap.insert(
02113           std::make_pair(IdentifierIDOffset, 
02114                          OM->BaseIdentifierID - IdentifierIDOffset));
02115         PreprocessedEntityRemap.insert(
02116           std::make_pair(PreprocessedEntityIDOffset, 
02117             OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
02118         SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset, 
02119                                       OM->BaseSubmoduleID - SubmoduleIDOffset));
02120         SelectorRemap.insert(std::make_pair(SelectorIDOffset, 
02121                                OM->BaseSelectorID - SelectorIDOffset));
02122         DeclRemap.insert(std::make_pair(DeclIDOffset, 
02123                                         OM->BaseDeclID - DeclIDOffset));
02124         
02125         TypeRemap.insert(std::make_pair(TypeIndexOffset, 
02126                                     OM->BaseTypeIndex - TypeIndexOffset));
02127 
02128         // Global -> local mappings.
02129         F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
02130       }
02131       break;
02132     }
02133 
02134     case SOURCE_MANAGER_LINE_TABLE:
02135       if (ParseLineTable(F, Record))
02136         return Failure;
02137       break;
02138 
02139     case FILE_SOURCE_LOCATION_OFFSETS:
02140       F.SLocFileOffsets = (const uint32_t *)BlobStart;
02141       F.LocalNumSLocFileEntries = Record[0];
02142       break;
02143 
02144     case SOURCE_LOCATION_PRELOADS: {
02145       // Need to transform from the local view (1-based IDs) to the global view,
02146       // which is based off F.SLocEntryBaseID.
02147       if (!F.PreloadSLocEntries.empty()) {
02148         Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
02149         return Failure;
02150       }
02151       
02152       F.PreloadSLocEntries.swap(Record);
02153       break;
02154     }
02155 
02156     case STAT_CACHE: {
02157       if (!DisableStatCache) {
02158         ASTStatCache *MyStatCache =
02159           new ASTStatCache((const unsigned char *)BlobStart + Record[0],
02160                            (const unsigned char *)BlobStart,
02161                            NumStatHits, NumStatMisses);
02162         FileMgr.addStatCache(MyStatCache);
02163         F.StatCache = MyStatCache;
02164       }
02165       break;
02166     }
02167 
02168     case EXT_VECTOR_DECLS:
02169       for (unsigned I = 0, N = Record.size(); I != N; ++I)
02170         ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
02171       break;
02172 
02173     case VTABLE_USES:
02174       if (Record.size() % 3 != 0) {
02175         Error("Invalid VTABLE_USES record");
02176         return Failure;
02177       }
02178         
02179       // Later tables overwrite earlier ones.
02180       // FIXME: Modules will have some trouble with this. This is clearly not
02181       // the right way to do this.
02182       VTableUses.clear();
02183         
02184       for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
02185         VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
02186         VTableUses.push_back(
02187           ReadSourceLocation(F, Record, Idx).getRawEncoding());
02188         VTableUses.push_back(Record[Idx++]);
02189       }
02190       break;
02191 
02192     case DYNAMIC_CLASSES:
02193       for (unsigned I = 0, N = Record.size(); I != N; ++I)
02194         DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
02195       break;
02196 
02197     case PENDING_IMPLICIT_INSTANTIATIONS:
02198       if (PendingInstantiations.size() % 2 != 0) {
02199         Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
02200         return Failure;
02201       }
02202         
02203       // Later lists of pending instantiations overwrite earlier ones.
02204       // FIXME: This is most certainly wrong for modules.
02205       PendingInstantiations.clear();
02206       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
02207         PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
02208         PendingInstantiations.push_back(
02209           ReadSourceLocation(F, Record, I).getRawEncoding());
02210       }
02211       break;
02212 
02213     case SEMA_DECL_REFS:
02214       // Later tables overwrite earlier ones.
02215       // FIXME: Modules will have some trouble with this.
02216       SemaDeclRefs.clear();
02217       for (unsigned I = 0, N = Record.size(); I != N; ++I)
02218         SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
02219       break;
02220 
02221     case ORIGINAL_FILE_NAME:
02222       // The primary AST will be the last to get here, so it will be the one
02223       // that's used.
02224       ActualOriginalFileName.assign(BlobStart, BlobLen);
02225       OriginalFileName = ActualOriginalFileName;
02226       MaybeAddSystemRootToFilename(OriginalFileName);
02227       break;
02228 
02229     case ORIGINAL_FILE_ID:
02230       OriginalFileID = FileID::get(Record[0]);
02231       break;
02232         
02233     case ORIGINAL_PCH_DIR:
02234       // The primary AST will be the last to get here, so it will be the one
02235       // that's used.
02236       OriginalDir.assign(BlobStart, BlobLen);
02237       break;
02238 
02239     case VERSION_CONTROL_BRANCH_REVISION: {
02240       const std::string &CurBranch = getClangFullRepositoryVersion();
02241       StringRef ASTBranch(BlobStart, BlobLen);
02242       if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
02243         Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
02244         return IgnorePCH;
02245       }
02246       break;
02247     }
02248 
02249     case PPD_ENTITIES_OFFSETS: {
02250       F.PreprocessedEntityOffsets = (const PPEntityOffset *)BlobStart;
02251       assert(BlobLen % sizeof(PPEntityOffset) == 0);
02252       F.NumPreprocessedEntities = BlobLen / sizeof(PPEntityOffset);
02253 
02254       unsigned LocalBasePreprocessedEntityID = Record[0];
02255       
02256       unsigned StartingID;
02257       if (!PP.getPreprocessingRecord())
02258         PP.createPreprocessingRecord(/*RecordConditionalDirectives=*/false);
02259       if (!PP.getPreprocessingRecord()->getExternalSource())
02260         PP.getPreprocessingRecord()->SetExternalSource(*this);
02261       StartingID 
02262         = PP.getPreprocessingRecord()
02263             ->allocateLoadedEntities(F.NumPreprocessedEntities);
02264       F.BasePreprocessedEntityID = StartingID;
02265 
02266       if (F.NumPreprocessedEntities > 0) {
02267         // Introduce the global -> local mapping for preprocessed entities in
02268         // this module.
02269         GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
02270        
02271         // Introduce the local -> global mapping for preprocessed entities in
02272         // this module.
02273         F.PreprocessedEntityRemap.insertOrReplace(
02274           std::make_pair(LocalBasePreprocessedEntityID,
02275             F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
02276       }
02277 
02278       break;
02279     }
02280         
02281     case DECL_UPDATE_OFFSETS: {
02282       if (Record.size() % 2 != 0) {
02283         Error("invalid DECL_UPDATE_OFFSETS block in AST file");
02284         return Failure;
02285       }
02286       for (unsigned I = 0, N = Record.size(); I != N; I += 2)
02287         DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
02288           .push_back(std::make_pair(&F, Record[I+1]));
02289       break;
02290     }
02291 
02292     case DECL_REPLACEMENTS: {
02293       if (Record.size() % 3 != 0) {
02294         Error("invalid DECL_REPLACEMENTS block in AST file");
02295         return Failure;
02296       }
02297       for (unsigned I = 0, N = Record.size(); I != N; I += 3)
02298         ReplacedDecls[getGlobalDeclID(F, Record[I])]
02299           = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
02300       break;
02301     }
02302 
02303     case OBJC_CATEGORIES_MAP: {
02304       if (F.LocalNumObjCCategoriesInMap != 0) {
02305         Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
02306         return Failure;
02307       }
02308       
02309       F.LocalNumObjCCategoriesInMap = Record[0];
02310       F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)BlobStart;
02311       break;
02312     }
02313         
02314     case OBJC_CATEGORIES:
02315       F.ObjCCategories.swap(Record);
02316       break;
02317         
02318     case CXX_BASE_SPECIFIER_OFFSETS: {
02319       if (F.LocalNumCXXBaseSpecifiers != 0) {
02320         Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
02321         return Failure;
02322       }
02323       
02324       F.LocalNumCXXBaseSpecifiers = Record[0];
02325       F.CXXBaseSpecifiersOffsets = (const uint32_t *)BlobStart;
02326       NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
02327       break;
02328     }
02329 
02330     case DIAG_PRAGMA_MAPPINGS:
02331       if (Record.size() % 2 != 0) {
02332         Error("invalid DIAG_USER_MAPPINGS block in AST file");
02333         return Failure;
02334       }
02335         
02336       if (F.PragmaDiagMappings.empty())
02337         F.PragmaDiagMappings.swap(Record);
02338       else
02339         F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
02340                                     Record.begin(), Record.end());
02341       break;
02342         
02343     case CUDA_SPECIAL_DECL_REFS:
02344       // Later tables overwrite earlier ones.
02345       // FIXME: Modules will have trouble with this.
02346       CUDASpecialDeclRefs.clear();
02347       for (unsigned I = 0, N = Record.size(); I != N; ++I)
02348         CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
02349       break;
02350 
02351     case HEADER_SEARCH_TABLE: {
02352       F.HeaderFileInfoTableData = BlobStart;
02353       F.LocalNumHeaderFileInfos = Record[1];
02354       F.HeaderFileFrameworkStrings = BlobStart + Record[2];
02355       if (Record[0]) {
02356         F.HeaderFileInfoTable
02357           = HeaderFileInfoLookupTable::Create(
02358                    (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
02359                    (const unsigned char *)F.HeaderFileInfoTableData,
02360                    HeaderFileInfoTrait(*this, F, 
02361                                        &PP.getHeaderSearchInfo(),
02362                                        BlobStart + Record[2]));
02363         
02364         PP.getHeaderSearchInfo().SetExternalSource(this);
02365         if (!PP.getHeaderSearchInfo().getExternalLookup())
02366           PP.getHeaderSearchInfo().SetExternalLookup(this);
02367       }
02368       break;
02369     }
02370         
02371     case FP_PRAGMA_OPTIONS:
02372       // Later tables overwrite earlier ones.
02373       FPPragmaOptions.swap(Record);
02374       break;
02375 
02376     case OPENCL_EXTENSIONS:
02377       // Later tables overwrite earlier ones.
02378       OpenCLExtensions.swap(Record);
02379       break;
02380 
02381     case TENTATIVE_DEFINITIONS:
02382       for (unsigned I = 0, N = Record.size(); I != N; ++I)
02383         TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
02384       break;
02385         
02386     case KNOWN_NAMESPACES:
02387       for (unsigned I = 0, N = Record.size(); I != N; ++I)
02388         KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
02389       break;
02390         
02391     case IMPORTED_MODULES: {
02392       if (F.Kind != MK_Module) {
02393         // If we aren't loading a module (which has its own exports), make
02394         // all of the imported modules visible.
02395         // FIXME: Deal with macros-only imports.
02396         for (unsigned I = 0, N = Record.size(); I != N; ++I) {
02397           if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
02398             ImportedModules.push_back(GlobalID);
02399         }
02400       }
02401       break;
02402     }
02403 
02404     case LOCAL_REDECLARATIONS: {
02405       F.RedeclarationChains.swap(Record);
02406       break;
02407     }
02408         
02409     case LOCAL_REDECLARATIONS_MAP: {
02410       if (F.LocalNumRedeclarationsInMap != 0) {
02411         Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
02412         return Failure;
02413       }
02414       
02415       F.LocalNumRedeclarationsInMap = Record[0];
02416       F.RedeclarationsMap = (const LocalRedeclarationsInfo *)BlobStart;
02417       break;
02418     }
02419         
02420     case MERGED_DECLARATIONS: {
02421       for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
02422         GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
02423         SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
02424         for (unsigned N = Record[Idx++]; N > 0; --N)
02425           Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
02426       }
02427       break;
02428     }
02429     }
02430   }
02431   Error("premature end of bitstream in AST file");
02432   return Failure;
02433 }
02434 
02435 ASTReader::ASTReadResult ASTReader::validateFileEntries(ModuleFile &M) {
02436   llvm::BitstreamCursor &SLocEntryCursor = M.SLocEntryCursor;
02437 
02438   for (unsigned i = 0, e = M.LocalNumSLocFileEntries; i != e; ++i) {
02439     SLocEntryCursor.JumpToBit(M.SLocFileOffsets[i]);
02440     unsigned Code = SLocEntryCursor.ReadCode();
02441     if (Code == llvm::bitc::END_BLOCK ||
02442         Code == llvm::bitc::ENTER_SUBBLOCK ||
02443         Code == llvm::bitc::DEFINE_ABBREV) {
02444       Error("incorrectly-formatted source location entry in AST file");
02445       return Failure;
02446     }
02447 
02448     RecordData Record;
02449     const char *BlobStart;
02450     unsigned BlobLen;
02451     switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
02452     default:
02453       Error("incorrectly-formatted source location entry in AST file");
02454       return Failure;
02455 
02456     case SM_SLOC_FILE_ENTRY: {
02457       // If the buffer was overridden, the file need not exist.
02458       if (Record[6])
02459         break;
02460       
02461       StringRef Filename(BlobStart, BlobLen);
02462       const FileEntry *File = getFileEntry(Filename);
02463 
02464       if (File == 0) {
02465         std::string ErrorStr = "could not find file '";
02466         ErrorStr += Filename;
02467         ErrorStr += "' referenced by AST file";
02468         Error(ErrorStr.c_str());
02469         return IgnorePCH;
02470       }
02471 
02472       if (Record.size() < 7) {
02473         Error("source location entry is incorrect");
02474         return Failure;
02475       }
02476       
02477       off_t StoredSize = (off_t)Record[4];
02478       time_t StoredTime = (time_t)Record[5];
02479 
02480       // Check if there was a request to override the contents of the file
02481       // that was part of the precompiled header. Overridding such a file
02482       // can lead to problems when lexing using the source locations from the
02483       // PCH.
02484       SourceManager &SM = getSourceManager();
02485       if (SM.isFileOverridden(File)) {
02486         Error(diag::err_fe_pch_file_overridden, Filename);
02487         // After emitting the diagnostic, recover by disabling the override so
02488         // that the original file will be used.
02489         SM.disableFileContentsOverride(File);
02490         // The FileEntry is a virtual file entry with the size of the contents
02491         // that would override the original contents. Set it to the original's
02492         // size/time.
02493         FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
02494                                 StoredSize, StoredTime);
02495       }
02496 
02497       // The stat info from the FileEntry came from the cached stat
02498       // info of the PCH, so we cannot trust it.
02499       struct stat StatBuf;
02500       if (::stat(File->getName(), &StatBuf) != 0) {
02501         StatBuf.st_size = File->getSize();
02502         StatBuf.st_mtime = File->getModificationTime();
02503       }
02504 
02505       if ((StoredSize != StatBuf.st_size
02506 #if !defined(LLVM_ON_WIN32)
02507           // In our regression testing, the Windows file system seems to
02508           // have inconsistent modification times that sometimes
02509           // erroneously trigger this error-handling path.
02510            || StoredTime != StatBuf.st_mtime
02511 #endif
02512           )) {
02513         Error(diag::err_fe_pch_file_modified, Filename);
02514         return IgnorePCH;
02515       }
02516 
02517       break;
02518     }
02519     }
02520   }
02521 
02522   return Success;
02523 }
02524 
02525 void ASTReader::makeNamesVisible(const HiddenNames &Names) {
02526   for (unsigned I = 0, N = Names.size(); I != N; ++I) {
02527     if (Decl *D = Names[I].dyn_cast<Decl *>())
02528       D->Hidden = false;
02529     else {
02530       IdentifierInfo *II = Names[I].get<IdentifierInfo *>();
02531       if (!II->hasMacroDefinition()) {
02532         II->setHasMacroDefinition(true);
02533         if (DeserializationListener)
02534           DeserializationListener->MacroVisible(II);
02535       }
02536     }
02537   }
02538 }
02539 
02540 void ASTReader::makeModuleVisible(Module *Mod, 
02541                                   Module::NameVisibilityKind NameVisibility) {
02542   llvm::SmallPtrSet<Module *, 4> Visited;
02543   llvm::SmallVector<Module *, 4> Stack;
02544   Stack.push_back(Mod);  
02545   while (!Stack.empty()) {
02546     Mod = Stack.back();
02547     Stack.pop_back();
02548 
02549     if (NameVisibility <= Mod->NameVisibility) {
02550       // This module already has this level of visibility (or greater), so 
02551       // there is nothing more to do.
02552       continue;
02553     }
02554     
02555     if (!Mod->isAvailable()) {
02556       // Modules that aren't available cannot be made visible.
02557       continue;
02558     }
02559 
02560     // Update the module's name visibility.
02561     Mod->NameVisibility = NameVisibility;
02562     
02563     // If we've already deserialized any names from this module,
02564     // mark them as visible.
02565     HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
02566     if (Hidden != HiddenNamesMap.end()) {
02567       makeNamesVisible(Hidden->second);
02568       HiddenNamesMap.erase(Hidden);
02569     }
02570     
02571     // Push any non-explicit submodules onto the stack to be marked as
02572     // visible.
02573     for (Module::submodule_iterator Sub = Mod->submodule_begin(),
02574                                  SubEnd = Mod->submodule_end();
02575          Sub != SubEnd; ++Sub) {
02576       if (!(*Sub)->IsExplicit && Visited.insert(*Sub))
02577         Stack.push_back(*Sub);
02578     }
02579     
02580     // Push any exported modules onto the stack to be marked as visible.
02581     bool AnyWildcard = false;
02582     bool UnrestrictedWildcard = false;
02583     llvm::SmallVector<Module *, 4> WildcardRestrictions;
02584     for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
02585       Module *Exported = Mod->Exports[I].getPointer();
02586       if (!Mod->Exports[I].getInt()) {
02587         // Export a named module directly; no wildcards involved.
02588         if (Visited.insert(Exported))
02589           Stack.push_back(Exported);
02590         
02591         continue;
02592       }
02593       
02594       // Wildcard export: export all of the imported modules that match
02595       // the given pattern.
02596       AnyWildcard = true;
02597       if (UnrestrictedWildcard)
02598         continue;
02599 
02600       if (Module *Restriction = Mod->Exports[I].getPointer())
02601         WildcardRestrictions.push_back(Restriction);
02602       else {
02603         WildcardRestrictions.clear();
02604         UnrestrictedWildcard = true;
02605       }
02606     }
02607     
02608     // If there were any wildcards, push any imported modules that were
02609     // re-exported by the wildcard restriction.
02610     if (!AnyWildcard)
02611       continue;
02612     
02613     for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
02614       Module *Imported = Mod->Imports[I];
02615       if (Visited.count(Imported))
02616         continue;
02617       
02618       bool Acceptable = UnrestrictedWildcard;
02619       if (!Acceptable) {
02620         // Check whether this module meets one of the restrictions.
02621         for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
02622           Module *Restriction = WildcardRestrictions[R];
02623           if (Imported == Restriction || Imported->isSubModuleOf(Restriction)) {
02624             Acceptable = true;
02625             break;
02626           }
02627         }
02628       }
02629       
02630       if (!Acceptable)
02631         continue;
02632       
02633       Visited.insert(Imported);
02634       Stack.push_back(Imported);
02635     }
02636   }
02637 }
02638 
02639 ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
02640                                             ModuleKind Type) {
02641   // Bump the generation number.
02642   unsigned PreviousGeneration = CurrentGeneration++;
02643   
02644   switch(ReadASTCore(FileName, Type, /*ImportedBy=*/0)) {
02645   case Failure: return Failure;
02646   case IgnorePCH: return IgnorePCH;
02647   case Success: break;
02648   }
02649 
02650   // Here comes stuff that we only do once the entire chain is loaded.
02651 
02652   // Check the predefines buffers.
02653   if (!DisableValidation && Type == MK_PCH &&
02654       // FIXME: CheckPredefinesBuffers also sets the SuggestedPredefines;
02655       // if DisableValidation is true, defines that were set on command-line
02656       // but not in the PCH file will not be added to SuggestedPredefines.
02657       CheckPredefinesBuffers())
02658     return IgnorePCH;
02659 
02660   // Mark all of the identifiers in the identifier table as being out of date,
02661   // so that various accessors know to check the loaded modules when the
02662   // identifier is used.
02663   for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
02664                               IdEnd = PP.getIdentifierTable().end();
02665        Id != IdEnd; ++Id)
02666     Id->second->setOutOfDate(true);
02667   
02668   // Resolve any unresolved module exports.
02669   for (unsigned I = 0, N = UnresolvedModuleImportExports.size(); I != N; ++I) {
02670     UnresolvedModuleImportExport &Unresolved = UnresolvedModuleImportExports[I];
02671     SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
02672     Module *ResolvedMod = getSubmodule(GlobalID);
02673     
02674     if (Unresolved.IsImport) {
02675       if (ResolvedMod)
02676         Unresolved.Mod->Imports.push_back(ResolvedMod);
02677       continue;
02678     }
02679 
02680     if (ResolvedMod || Unresolved.IsWildcard)
02681       Unresolved.Mod->Exports.push_back(
02682         Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
02683   }
02684   UnresolvedModuleImportExports.clear();
02685   
02686   InitializeContext();
02687 
02688   if (DeserializationListener)
02689     DeserializationListener->ReaderInitialized(this);
02690 
02691   if (!OriginalFileID.isInvalid()) {
02692     OriginalFileID = FileID::get(ModuleMgr.getPrimaryModule().SLocEntryBaseID
02693                                       + OriginalFileID.getOpaqueValue() - 1);
02694 
02695     // If this AST file is a precompiled preamble, then set the preamble file ID
02696     // of the source manager to the file source file from which the preamble was
02697     // built.
02698     if (Type == MK_Preamble) {
02699       SourceMgr.setPreambleFileID(OriginalFileID);
02700     } else if (Type == MK_MainFile) {
02701       SourceMgr.setMainFileID(OriginalFileID);
02702     }
02703   }
02704   
02705   // For any Objective-C class definitions we have already loaded, make sure
02706   // that we load any additional categories.
02707   for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
02708     loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(), 
02709                        ObjCClassesLoaded[I],
02710                        PreviousGeneration);
02711   }
02712   
02713   return Success;
02714 }
02715 
02716 ASTReader::ASTReadResult ASTReader::ReadASTCore(StringRef FileName,
02717                                                 ModuleKind Type,
02718                                                 ModuleFile *ImportedBy) {
02719   ModuleFile *M;
02720   bool NewModule;
02721   std::string ErrorStr;
02722   llvm::tie(M, NewModule) = ModuleMgr.addModule(FileName, Type, ImportedBy,
02723                                                 CurrentGeneration, ErrorStr);
02724 
02725   if (!M) {
02726     // We couldn't load the module.
02727     std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
02728       + ErrorStr;
02729     Error(Msg);
02730     return Failure;
02731   }
02732 
02733   if (!NewModule) {
02734     // We've already loaded this module.
02735     return Success;
02736   }
02737 
02738   // FIXME: This seems rather a hack. Should CurrentDir be part of the
02739   // module?
02740   if (FileName != "-") {
02741     CurrentDir = llvm::sys::path::parent_path(FileName);
02742     if (CurrentDir.empty()) CurrentDir = ".";
02743   }
02744 
02745   ModuleFile &F = *M;
02746   llvm::BitstreamCursor &Stream = F.Stream;
02747   Stream.init(F.StreamFile);
02748   F.SizeInBits = F.Buffer->getBufferSize() * 8;
02749   
02750   // Sniff for the signature.
02751   if (Stream.Read(8) != 'C' ||
02752       Stream.Read(8) != 'P' ||
02753       Stream.Read(8) != 'C' ||
02754       Stream.Read(8) != 'H') {
02755     Diag(diag::err_not_a_pch_file) << FileName;
02756     return Failure;
02757   }
02758 
02759   while (!Stream.AtEndOfStream()) {
02760     unsigned Code = Stream.ReadCode();
02761 
02762     if (Code != llvm::bitc::ENTER_SUBBLOCK) {
02763       Error("invalid record at top-level of AST file");
02764       return Failure;
02765     }
02766 
02767     unsigned BlockID = Stream.ReadSubBlockID();
02768 
02769     // We only know the AST subblock ID.
02770     switch (BlockID) {
02771     case llvm::bitc::BLOCKINFO_BLOCK_ID:
02772       if (Stream.ReadBlockInfoBlock()) {
02773         Error("malformed BlockInfoBlock in AST file");
02774         return Failure;
02775       }
02776       break;
02777     case AST_BLOCK_ID:
02778       switch (ReadASTBlock(F)) {
02779       case Success:
02780         break;
02781 
02782       case Failure:
02783         return Failure;
02784 
02785       case IgnorePCH:
02786         // FIXME: We could consider reading through to the end of this
02787         // AST block, skipping subblocks, to see if there are other
02788         // AST blocks elsewhere.
02789 
02790         // FIXME: We can't clear loaded slocentries anymore.
02791         //SourceMgr.ClearPreallocatedSLocEntries();
02792 
02793         // Remove the stat cache.
02794         if (F.StatCache)
02795           FileMgr.removeStatCache((ASTStatCache*)F.StatCache);
02796 
02797         return IgnorePCH;
02798       }
02799       break;
02800     default:
02801       if (Stream.SkipBlock()) {
02802         Error("malformed block record in AST file");
02803         return Failure;
02804       }
02805       break;
02806     }
02807   }
02808   
02809   // Once read, set the ModuleFile bit base offset and update the size in 
02810   // bits of all files we've seen.
02811   F.GlobalBitOffset = TotalModulesSizeInBits;
02812   TotalModulesSizeInBits += F.SizeInBits;
02813   GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
02814 
02815   // Make sure that the files this module was built against are still available.
02816   if (!DisableValidation) {
02817     switch(validateFileEntries(*M)) {
02818     case Failure: return Failure;
02819     case IgnorePCH: return IgnorePCH;
02820     case Success: break;
02821     }
02822   }
02823   
02824   // Preload SLocEntries.
02825   for (unsigned I = 0, N = M->PreloadSLocEntries.size(); I != N; ++I) {
02826     int Index = int(M->PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
02827     // Load it through the SourceManager and don't call ReadSLocEntryRecord()
02828     // directly because the entry may have already been loaded in which case
02829     // calling ReadSLocEntryRecord() directly would trigger an assertion in
02830     // SourceManager.
02831     SourceMgr.getLoadedSLocEntryByID(Index);
02832   }
02833 
02834 
02835   return Success;
02836 }
02837 
02838 void ASTReader::InitializeContext() {  
02839   // If there's a listener, notify them that we "read" the translation unit.
02840   if (DeserializationListener)
02841     DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID, 
02842                                       Context.getTranslationUnitDecl());
02843 
02844   // Make sure we load the declaration update records for the translation unit,
02845   // if there are any.
02846   loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID, 
02847                         Context.getTranslationUnitDecl());
02848   
02849   // FIXME: Find a better way to deal with collisions between these
02850   // built-in types. Right now, we just ignore the problem.
02851   
02852   // Load the special types.
02853   if (SpecialTypes.size() >= NumSpecialTypeIDs) {
02854     if (Context.getBuiltinVaListType().isNull()) {
02855       Context.setBuiltinVaListType(
02856         GetType(SpecialTypes[SPECIAL_TYPE_BUILTIN_VA_LIST]));
02857     }
02858     
02859     if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
02860       if (!Context.CFConstantStringTypeDecl)
02861         Context.setCFConstantStringType(GetType(String));
02862     }
02863     
02864     if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
02865       QualType FileType = GetType(File);
02866       if (FileType.isNull()) {
02867         Error("FILE type is NULL");
02868         return;
02869       }
02870       
02871       if (!Context.FILEDecl) {
02872         if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
02873           Context.setFILEDecl(Typedef->getDecl());
02874         else {
02875           const TagType *Tag = FileType->getAs<TagType>();
02876           if (!Tag) {
02877             Error("Invalid FILE type in AST file");
02878             return;
02879           }
02880           Context.setFILEDecl(Tag->getDecl());
02881         }
02882       }
02883     }
02884     
02885     if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
02886       QualType Jmp_bufType = GetType(Jmp_buf);
02887       if (Jmp_bufType.isNull()) {
02888         Error("jmp_buf type is NULL");
02889         return;
02890       }
02891       
02892       if (!Context.jmp_bufDecl) {
02893         if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
02894           Context.setjmp_bufDecl(Typedef->getDecl());
02895         else {
02896           const TagType *Tag = Jmp_bufType->getAs<TagType>();
02897           if (!Tag) {
02898             Error("Invalid jmp_buf type in AST file");
02899             return;
02900           }
02901           Context.setjmp_bufDecl(Tag->getDecl());
02902         }
02903       }
02904     }
02905     
02906     if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
02907       QualType Sigjmp_bufType = GetType(Sigjmp_buf);
02908       if (Sigjmp_bufType.isNull()) {
02909         Error("sigjmp_buf type is NULL");
02910         return;
02911       }
02912       
02913       if (!Context.sigjmp_bufDecl) {
02914         if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
02915           Context.setsigjmp_bufDecl(Typedef->getDecl());
02916         else {
02917           const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
02918           assert(Tag && "Invalid sigjmp_buf type in AST file");
02919           Context.setsigjmp_bufDecl(Tag->getDecl());
02920         }
02921       }
02922     }
02923 
02924     if (unsigned ObjCIdRedef
02925           = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
02926       if (Context.ObjCIdRedefinitionType.isNull())
02927         Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
02928     }
02929 
02930     if (unsigned ObjCClassRedef
02931           = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
02932       if (Context.ObjCClassRedefinitionType.isNull())
02933         Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
02934     }
02935 
02936     if (unsigned ObjCSelRedef
02937           = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
02938       if (Context.ObjCSelRedefinitionType.isNull())
02939         Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
02940     }
02941 
02942     if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
02943       QualType Ucontext_tType = GetType(Ucontext_t);
02944       if (Ucontext_tType.isNull()) {
02945         Error("ucontext_t type is NULL");
02946         return;
02947       }
02948 
02949       if (!Context.ucontext_tDecl) {
02950         if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
02951           Context.setucontext_tDecl(Typedef->getDecl());
02952         else {
02953           const TagType *Tag = Ucontext_tType->getAs<TagType>();
02954           assert(Tag && "Invalid ucontext_t type in AST file");
02955           Context.setucontext_tDecl(Tag->getDecl());
02956         }
02957       }
02958     }
02959   }
02960   
02961   ReadPragmaDiagnosticMappings(Context.getDiagnostics());
02962 
02963   // If there were any CUDA special declarations, deserialize them.
02964   if (!CUDASpecialDeclRefs.empty()) {
02965     assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
02966     Context.setcudaConfigureCallDecl(
02967                            cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
02968   }
02969   
02970   // Re-export any modules that were imported by a non-module AST file.
02971   for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
02972     if (Module *Imported = getSubmodule(ImportedModules[I]))
02973       makeModuleVisible(Imported, Module::AllVisible);
02974   }
02975   ImportedModules.clear();
02976 }
02977 
02978 void ASTReader::finalizeForWriting() {
02979   for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
02980                                  HiddenEnd = HiddenNamesMap.end();
02981        Hidden != HiddenEnd; ++Hidden) {
02982     makeNamesVisible(Hidden->second);
02983   }
02984   HiddenNamesMap.clear();
02985 }
02986 
02987 /// \brief Retrieve the name of the original source file name
02988 /// directly from the AST file, without actually loading the AST
02989 /// file.
02990 std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
02991                                              FileManager &FileMgr,
02992                                              DiagnosticsEngine &Diags) {
02993   // Open the AST file.
02994   std::string ErrStr;
02995   OwningPtr<llvm::MemoryBuffer> Buffer;
02996   Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
02997   if (!Buffer) {
02998     Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
02999     return std::string();
03000   }
03001 
03002   // Initialize the stream
03003   llvm::BitstreamReader StreamFile;
03004   llvm::BitstreamCursor Stream;
03005   StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
03006                   (const unsigned char *)Buffer->getBufferEnd());
03007   Stream.init(StreamFile);
03008 
03009   // Sniff for the signature.
03010   if (Stream.Read(8) != 'C' ||
03011       Stream.Read(8) != 'P' ||
03012       Stream.Read(8) != 'C' ||
03013       Stream.Read(8) != 'H') {
03014     Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
03015     return std::string();
03016   }
03017 
03018   RecordData Record;
03019   while (!Stream.AtEndOfStream()) {
03020     unsigned Code = Stream.ReadCode();
03021 
03022     if (Code == llvm::bitc::ENTER_SUBBLOCK) {
03023       unsigned BlockID = Stream.ReadSubBlockID();
03024 
03025       // We only know the AST subblock ID.
03026       switch (BlockID) {
03027       case AST_BLOCK_ID:
03028         if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
03029           Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
03030           return std::string();
03031         }
03032         break;
03033 
03034       default:
03035         if (Stream.SkipBlock()) {
03036           Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
03037           return std::string();
03038         }
03039         break;
03040       }
03041       continue;
03042     }
03043 
03044     if (Code == llvm::bitc::END_BLOCK) {
03045       if (Stream.ReadBlockEnd()) {
03046         Diags.Report(diag::err_fe_pch_error_at_end_block) << ASTFileName;
03047         return std::string();
03048       }
03049       continue;
03050     }
03051 
03052     if (Code == llvm::bitc::DEFINE_ABBREV) {
03053       Stream.ReadAbbrevRecord();
03054       continue;
03055     }
03056 
03057     Record.clear();
03058     const char *BlobStart = 0;
03059     unsigned BlobLen = 0;
03060     if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
03061           == ORIGINAL_FILE_NAME)
03062       return std::string(BlobStart, BlobLen);
03063   }
03064 
03065   return std::string();
03066 }
03067 
03068 ASTReader::ASTReadResult ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
03069   // Enter the submodule block.
03070   if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
03071     Error("malformed submodule block record in AST file");
03072     return Failure;
03073   }
03074 
03075   ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
03076   bool First = true;
03077   Module *CurrentModule = 0;
03078   RecordData Record;
03079   while (true) {
03080     unsigned Code = F.Stream.ReadCode();
03081     if (Code == llvm::bitc::END_BLOCK) {
03082       if (F.Stream.ReadBlockEnd()) {
03083         Error("error at end of submodule block in AST file");
03084         return Failure;
03085       }
03086       return Success;
03087     }
03088     
03089     if (Code == llvm::bitc::ENTER_SUBBLOCK) {
03090       // No known subblocks, always skip them.
03091       F.Stream.ReadSubBlockID();
03092       if (F.Stream.SkipBlock()) {
03093         Error("malformed block record in AST file");
03094         return Failure;
03095       }
03096       continue;
03097     }
03098     
03099     if (Code == llvm::bitc::DEFINE_ABBREV) {
03100       F.Stream.ReadAbbrevRecord();
03101       continue;
03102     }
03103     
03104     // Read a record.
03105     const char *BlobStart;
03106     unsigned BlobLen;
03107     Record.clear();
03108     switch (F.Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
03109     default:  // Default behavior: ignore.
03110       break;
03111       
03112     case SUBMODULE_DEFINITION: {
03113       if (First) {
03114         Error("missing submodule metadata record at beginning of block");
03115         return Failure;
03116       }
03117 
03118       if (Record.size() < 7) {
03119         Error("malformed module definition");
03120         return Failure;
03121       }
03122       
03123       StringRef Name(BlobStart, BlobLen);
03124       SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
03125       SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
03126       bool IsFramework = Record[2];
03127       bool IsExplicit = Record[3];
03128       bool IsSystem = Record[4];
03129       bool InferSubmodules = Record[5];
03130       bool InferExplicitSubmodules = Record[6];
03131       bool InferExportWildcard = Record[7];
03132       
03133       Module *ParentModule = 0;
03134       if (Parent)
03135         ParentModule = getSubmodule(Parent);
03136       
03137       // Retrieve this (sub)module from the module map, creating it if
03138       // necessary.
03139       CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, 
03140                                                 IsFramework, 
03141                                                 IsExplicit).first;
03142       SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
03143       if (GlobalIndex >= SubmodulesLoaded.size() ||
03144           SubmodulesLoaded[GlobalIndex]) {
03145         Error("too many submodules");
03146         return Failure;
03147       }
03148       
03149       CurrentModule->IsFromModuleFile = true;
03150       CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
03151       CurrentModule->InferSubmodules = InferSubmodules;
03152       CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
03153       CurrentModule->InferExportWildcard = InferExportWildcard;
03154       if (DeserializationListener)
03155         DeserializationListener->ModuleRead(GlobalID, CurrentModule);
03156       
03157       SubmodulesLoaded[GlobalIndex] = CurrentModule;
03158       break;
03159     }
03160         
03161     case SUBMODULE_UMBRELLA_HEADER: {
03162       if (First) {
03163         Error("missing submodule metadata record at beginning of block");
03164         return Failure;
03165       }
03166 
03167       if (!CurrentModule)
03168         break;
03169       
03170       StringRef FileName(BlobStart, BlobLen);
03171       if (const FileEntry *Umbrella = PP.getFileManager().getFile(FileName)) {
03172         if (!CurrentModule->getUmbrellaHeader())
03173           ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
03174         else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
03175           Error("mismatched umbrella headers in submodule");
03176           return Failure;
03177         }
03178       }
03179       break;
03180     }
03181         
03182     case SUBMODULE_HEADER: {
03183       if (First) {
03184         Error("missing submodule metadata record at beginning of block");
03185         return Failure;
03186       }
03187 
03188       if (!CurrentModule)
03189         break;
03190       
03191       // FIXME: Be more lazy about this!
03192       StringRef FileName(BlobStart, BlobLen);
03193       if (const FileEntry *File = PP.getFileManager().getFile(FileName)) {
03194         if (std::find(CurrentModule->Headers.begin(), 
03195                       CurrentModule->Headers.end(), 
03196                       File) == CurrentModule->Headers.end())
03197           ModMap.addHeader(CurrentModule, File);
03198       }
03199       break;      
03200     }
03201         
03202     case SUBMODULE_UMBRELLA_DIR: {
03203       if (First) {
03204         Error("missing submodule metadata record at beginning of block");
03205         return Failure;
03206       }
03207       
03208       if (!CurrentModule)
03209         break;
03210       
03211       StringRef DirName(BlobStart, BlobLen);
03212       if (const DirectoryEntry *Umbrella
03213                                   = PP.getFileManager().getDirectory(DirName)) {
03214         if (!CurrentModule->getUmbrellaDir())
03215           ModMap.setUmbrellaDir(CurrentModule, Umbrella);
03216         else if (CurrentModule->getUmbrellaDir() != Umbrella) {
03217           Error("mismatched umbrella directories in submodule");
03218           return Failure;
03219         }
03220       }
03221       break;
03222     }
03223         
03224     case SUBMODULE_METADATA: {
03225       if (!First) {
03226         Error("submodule metadata record not at beginning of block");
03227         return Failure;
03228       }
03229       First = false;
03230       
03231       F.BaseSubmoduleID = getTotalNumSubmodules();
03232       F.LocalNumSubmodules = Record[0];
03233       unsigned LocalBaseSubmoduleID = Record[1];
03234       if (F.LocalNumSubmodules > 0) {
03235         // Introduce the global -> local mapping for submodules within this 
03236         // module.
03237         GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
03238         
03239         // Introduce the local -> global mapping for submodules within this 
03240         // module.
03241         F.SubmoduleRemap.insertOrReplace(
03242           std::make_pair(LocalBaseSubmoduleID,
03243                          F.BaseSubmoduleID - LocalBaseSubmoduleID));
03244         
03245         SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
03246       }      
03247       break;
03248     }
03249         
03250     case SUBMODULE_IMPORTS: {
03251       if (First) {
03252         Error("missing submodule metadata record at beginning of block");
03253         return Failure;
03254       }
03255       
03256       if (!CurrentModule)
03257         break;
03258       
03259       for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
03260         UnresolvedModuleImportExport Unresolved;
03261         Unresolved.File = &F;
03262         Unresolved.Mod = CurrentModule;
03263         Unresolved.ID = Record[Idx];
03264         Unresolved.IsImport = true;
03265         Unresolved.IsWildcard = false;
03266         UnresolvedModuleImportExports.push_back(Unresolved);
03267       }
03268       break;
03269     }
03270 
03271     case SUBMODULE_EXPORTS: {
03272       if (First) {
03273         Error("missing submodule metadata record at beginning of block");
03274         return Failure;
03275       }
03276       
03277       if (!CurrentModule)
03278         break;
03279       
03280       for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
03281         UnresolvedModuleImportExport Unresolved;
03282         Unresolved.File = &F;
03283         Unresolved.Mod = CurrentModule;
03284         Unresolved.ID = Record[Idx];
03285         Unresolved.IsImport = false;
03286         Unresolved.IsWildcard = Record[Idx + 1];
03287         UnresolvedModuleImportExports.push_back(Unresolved);
03288       }
03289       
03290       // Once we've loaded the set of exports, there's no reason to keep 
03291       // the parsed, unresolved exports around.
03292       CurrentModule->UnresolvedExports.clear();
03293       break;
03294     }
03295     case SUBMODULE_REQUIRES: {
03296       if (First) {
03297         Error("missing submodule metadata record at beginning of block");
03298         return Failure;
03299       }
03300 
03301       if (!CurrentModule)
03302         break;
03303 
03304       CurrentModule->addRequirement(StringRef(BlobStart, BlobLen), 
03305                                     Context.getLangOpts(),
03306                                     Context.getTargetInfo());
03307       break;
03308     }
03309     }
03310   }
03311 }
03312 
03313 /// \brief Parse the record that corresponds to a LangOptions data
03314 /// structure.
03315 ///
03316 /// This routine parses the language options from the AST file and then gives
03317 /// them to the AST listener if one is set.
03318 ///
03319 /// \returns true if the listener deems the file unacceptable, false otherwise.
03320 bool ASTReader::ParseLanguageOptions(
03321                              const SmallVectorImpl<uint64_t> &Record) {
03322   if (Listener) {
03323     LangOptions LangOpts;
03324     unsigned Idx = 0;
03325 #define LANGOPT(Name, Bits, Default, Description) \
03326   LangOpts.Name = Record[Idx++];
03327 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
03328   LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
03329 #include "clang/Basic/LangOptions.def"
03330     
03331     unsigned Length = Record[Idx++];
03332     LangOpts.CurrentModule.assign(Record.begin() + Idx, 
03333                                   Record.begin() + Idx + Length);
03334     return Listener->ReadLanguageOptions(LangOpts);
03335   }
03336 
03337   return false;
03338 }
03339 
03340 std::pair<ModuleFile *, unsigned>
03341 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
03342   GlobalPreprocessedEntityMapType::iterator
03343   I = GlobalPreprocessedEntityMap.find(GlobalIndex);
03344   assert(I != GlobalPreprocessedEntityMap.end() && 
03345          "Corrupted global preprocessed entity map");
03346   ModuleFile *M = I->second;
03347   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
03348   return std::make_pair(M, LocalIndex);
03349 }
03350 
03351 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
03352   PreprocessedEntityID PPID = Index+1;
03353   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
03354   ModuleFile &M = *PPInfo.first;
03355   unsigned LocalIndex = PPInfo.second;
03356   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
03357 
03358   SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);  
03359   M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
03360 
03361   unsigned Code = M.PreprocessorDetailCursor.ReadCode();
03362   switch (Code) {
03363   case llvm::bitc::END_BLOCK:
03364     return 0;
03365     
03366   case llvm::bitc::ENTER_SUBBLOCK:
03367     Error("unexpected subblock record in preprocessor detail block");
03368     return 0;
03369       
03370   case llvm::bitc::DEFINE_ABBREV:
03371     Error("unexpected abbrevation record in preprocessor detail block");
03372     return 0;
03373       
03374   default:
03375     break;
03376   }
03377 
03378   if (!PP.getPreprocessingRecord()) {
03379     Error("no preprocessing record");
03380     return 0;
03381   }
03382   
03383   // Read the record.
03384   SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
03385                     ReadSourceLocation(M, PPOffs.End));
03386   PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
03387   const char *BlobStart = 0;
03388   unsigned BlobLen = 0;
03389   RecordData Record;
03390   PreprocessorDetailRecordTypes RecType =
03391     (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.ReadRecord(
03392                                              Code, Record, BlobStart, BlobLen);
03393   switch (RecType) {
03394   case PPD_MACRO_EXPANSION: {
03395     bool isBuiltin = Record[0];
03396     IdentifierInfo *Name = 0;
03397     MacroDefinition *Def = 0;
03398     if (isBuiltin)
03399       Name = getLocalIdentifier(M, Record[1]);
03400     else {
03401       PreprocessedEntityID
03402           GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
03403       Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
03404     }
03405 
03406     MacroExpansion *ME;
03407     if (isBuiltin)
03408       ME = new (PPRec) MacroExpansion(Name, Range);
03409     else
03410       ME = new (PPRec) MacroExpansion(Def, Range);
03411 
03412     return ME;
03413   }
03414       
03415   case PPD_MACRO_DEFINITION: {
03416     // Decode the identifier info and then check again; if the macro is
03417     // still defined and associated with the identifier,
03418     IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
03419     MacroDefinition *MD
03420       = new (PPRec) MacroDefinition(II, Range);
03421 
03422     if (DeserializationListener)
03423       DeserializationListener->MacroDefinitionRead(PPID, MD);
03424 
03425     return MD;
03426   }
03427       
03428   case PPD_INCLUSION_DIRECTIVE: {
03429     const char *FullFileNameStart = BlobStart + Record[0];
03430     StringRef FullFileName(FullFileNameStart, BlobLen - Record[0]);
03431     const FileEntry *File = 0;
03432     if (!FullFileName.empty())
03433       File = PP.getFileManager().getFile(FullFileName);
03434     
03435     // FIXME: Stable encoding
03436     InclusionDirective::InclusionKind Kind
03437       = static_cast<InclusionDirective::InclusionKind>(Record[2]);
03438     InclusionDirective *ID
03439       = new (PPRec) InclusionDirective(PPRec, Kind,
03440                                        StringRef(BlobStart, Record[0]),
03441                                        Record[1],
03442                                        File,
03443                                        Range);
03444     return ID;
03445   }
03446   }
03447 
03448   llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
03449 }
03450 
03451 /// \brief \arg SLocMapI points at a chunk of a module that contains no
03452 /// preprocessed entities or the entities it contains are not the ones we are
03453 /// looking for. Find the next module that contains entities and return the ID
03454 /// of the first entry.
03455 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
03456                        GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
03457   ++SLocMapI;
03458   for (GlobalSLocOffsetMapType::const_iterator
03459          EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
03460     ModuleFile &M = *SLocMapI->second;
03461     if (M.NumPreprocessedEntities)
03462       return getGlobalPreprocessedEntityID(M, M.BasePreprocessedEntityID);
03463   }
03464 
03465   return getTotalNumPreprocessedEntities();
03466 }
03467 
03468 namespace {
03469 
03470 template <unsigned PPEntityOffset::*PPLoc>
03471 struct PPEntityComp {
03472   const ASTReader &Reader;
03473   ModuleFile &M;
03474 
03475   PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
03476 
03477   bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
03478     SourceLocation LHS = getLoc(L);
03479     SourceLocation RHS = getLoc(R);
03480     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
03481   }
03482 
03483   bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
03484     SourceLocation LHS = getLoc(L);
03485     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
03486   }
03487 
03488   bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
03489     SourceLocation RHS = getLoc(R);
03490     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
03491   }
03492 
03493   SourceLocation getLoc(const PPEntityOffset &PPE) const {
03494     return Reader.ReadSourceLocation(M, PPE.*PPLoc);
03495   }
03496 };
03497 
03498 }
03499 
03500 /// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
03501 PreprocessedEntityID
03502 ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
03503   if (SourceMgr.isLocalSourceLocation(BLoc))
03504     return getTotalNumPreprocessedEntities();
03505 
03506   GlobalSLocOffsetMapType::const_iterator
03507     SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
03508                                         BLoc.getOffset());
03509   assert(SLocMapI != GlobalSLocOffsetMap.end() &&
03510          "Corrupted global sloc offset map");
03511 
03512   if (SLocMapI->second->NumPreprocessedEntities == 0)
03513     return findNextPreprocessedEntity(SLocMapI);
03514 
03515   ModuleFile &M = *SLocMapI->second;
03516   typedef const PPEntityOffset *pp_iterator;
03517   pp_iterator pp_begin = M.PreprocessedEntityOffsets;
03518   pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
03519 
03520   size_t Count = M.NumPreprocessedEntities;
03521   size_t Half;
03522   pp_iterator First = pp_begin;
03523   pp_iterator PPI;
03524 
03525   // Do a binary search manually instead of using std::lower_bound because
03526   // The end locations of entities may be unordered (when a macro expansion
03527   // is inside another macro argument), but for this case it is not important
03528   // whether we get the first macro expansion or its containing macro.
03529   while (Count > 0) {
03530     Half = Count/2;
03531     PPI = First;
03532     std::advance(PPI, Half);
03533     if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
03534                                             BLoc)){
03535       First = PPI;
03536       ++First;
03537       Count = Count - Half - 1;
03538     } else
03539       Count = Half;
03540   }
03541 
03542   if (PPI == pp_end)
03543     return findNextPreprocessedEntity(SLocMapI);
03544 
03545   return getGlobalPreprocessedEntityID(M,
03546                                  M.BasePreprocessedEntityID + (PPI - pp_begin));
03547 }
03548 
03549 /// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
03550 PreprocessedEntityID
03551 ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
03552   if (SourceMgr.isLocalSourceLocation(ELoc))
03553     return getTotalNumPreprocessedEntities();
03554 
03555   GlobalSLocOffsetMapType::const_iterator
03556     SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
03557                                         ELoc.getOffset());
03558   assert(SLocMapI != GlobalSLocOffsetMap.end() &&
03559          "Corrupted global sloc offset map");
03560 
03561   if (SLocMapI->second->NumPreprocessedEntities == 0)
03562     return findNextPreprocessedEntity(SLocMapI);
03563 
03564   ModuleFile &M = *SLocMapI->second;
03565   typedef const PPEntityOffset *pp_iterator;
03566   pp_iterator pp_begin = M.PreprocessedEntityOffsets;
03567   pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
03568   pp_iterator PPI =
03569       std::upper_bound(pp_begin, pp_end, ELoc,
03570                        PPEntityComp<&PPEntityOffset::Begin>(*this, M));
03571 
03572   if (PPI == pp_end)
03573     return findNextPreprocessedEntity(SLocMapI);
03574 
03575   return getGlobalPreprocessedEntityID(M,
03576                                  M.BasePreprocessedEntityID + (PPI - pp_begin));
03577 }
03578 
03579 /// \brief Returns a pair of [Begin, End) indices of preallocated
03580 /// preprocessed entities that \arg Range encompasses.
03581 std::pair<unsigned, unsigned>
03582     ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
03583   if (Range.isInvalid())
03584     return std::make_pair(0,0);
03585   assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
03586 
03587   PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
03588   PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
03589   return std::make_pair(BeginID, EndID);
03590 }
03591 
03592 /// \brief Optionally returns true or false if the preallocated preprocessed
03593 /// entity with index \arg Index came from file \arg FID.
03594 llvm::Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
03595                                                              FileID FID) {
03596   if (FID.isInvalid())
03597     return false;
03598 
03599   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
03600   ModuleFile &M = *PPInfo.first;
03601   unsigned LocalIndex = PPInfo.second;
03602   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
03603   
03604   SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
03605   if (Loc.isInvalid())
03606     return false;
03607   
03608   if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
03609     return true;
03610   else
03611     return false;
03612 }
03613 
03614 namespace {
03615   /// \brief Visitor used to search for information about a header file.
03616   class HeaderFileInfoVisitor {
03617     ASTReader &Reader;
03618     const FileEntry *FE;
03619     
03620     llvm::Optional<HeaderFileInfo> HFI;
03621     
03622   public:
03623     HeaderFileInfoVisitor(ASTReader &Reader, const FileEntry *FE)
03624       : Reader(Reader), FE(FE) { }
03625     
03626     static bool visit(ModuleFile &M, void *UserData) {
03627       HeaderFileInfoVisitor *This
03628         = static_cast<HeaderFileInfoVisitor *>(UserData);
03629       
03630       HeaderFileInfoTrait Trait(This->Reader, M, 
03631                                 &This->Reader.getPreprocessor().getHeaderSearchInfo(),
03632                                 M.HeaderFileFrameworkStrings,
03633                                 This->FE->getName());
03634       
03635       HeaderFileInfoLookupTable *Table
03636         = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
03637       if (!Table)
03638         return false;
03639 
03640       // Look in the on-disk hash table for an entry for this file name.
03641       HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE->getName(),
03642                                                             &Trait);
03643       if (Pos == Table->end())
03644         return false;
03645 
03646       This->HFI = *Pos;
03647       return true;
03648     }
03649     
03650     llvm::Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
03651   };
03652 }
03653 
03654 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
03655   HeaderFileInfoVisitor Visitor(*this, FE);
03656   ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
03657   if (llvm::Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) {
03658     if (Listener)
03659       Listener->ReadHeaderFileInfo(*HFI, FE->getUID());
03660     return *HFI;
03661   }
03662   
03663   return HeaderFileInfo();
03664 }
03665 
03666 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
03667   for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
03668     ModuleFile &F = *(*I);
03669     unsigned Idx = 0;
03670     while (Idx < F.PragmaDiagMappings.size()) {
03671       SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
03672       Diag.DiagStates.push_back(*Diag.GetCurDiagState());
03673       Diag.DiagStatePoints.push_back(
03674           DiagnosticsEngine::DiagStatePoint(&Diag.DiagStates.back(),
03675                                             FullSourceLoc(Loc, SourceMgr)));
03676       while (1) {
03677         assert(Idx < F.PragmaDiagMappings.size() &&
03678                "Invalid data, didn't find '-1' marking end of diag/map pairs");
03679         if (Idx >= F.PragmaDiagMappings.size()) {
03680           break; // Something is messed up but at least avoid infinite loop in
03681                  // release build.
03682         }
03683         unsigned DiagID = F.PragmaDiagMappings[Idx++];
03684         if (DiagID == (unsigned)-1) {
03685           break; // no more diag/map pairs for this location.
03686         }
03687         diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
03688         DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
03689         Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
03690       }
03691     }
03692   }
03693 }
03694 
03695 /// \brief Get the correct cursor and offset for loading a type.
03696 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
03697   GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
03698   assert(I != GlobalTypeMap.end() && "Corrupted global type map");
03699   ModuleFile *M = I->second;
03700   return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
03701 }
03702 
03703 /// \brief Read and return the type with the given index..
03704 ///
03705 /// The index is the type ID, shifted and minus the number of predefs. This
03706 /// routine actually reads the record corresponding to the type at the given
03707 /// location. It is a helper routine for GetType, which deals with reading type
03708 /// IDs.
03709 QualType ASTReader::readTypeRecord(unsigned Index) {
03710   RecordLocation Loc = TypeCursorForIndex(Index);
03711   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
03712 
03713   // Keep track of where we are in the stream, then jump back there
03714   // after reading this type.
03715   SavedStreamPosition SavedPosition(DeclsCursor);
03716 
03717   ReadingKindTracker ReadingKind(Read_Type, *this);
03718 
03719   // Note that we are loading a type record.
03720   Deserializing AType(this);
03721 
03722   unsigned Idx = 0;
03723   DeclsCursor.JumpToBit(Loc.Offset);
03724   RecordData Record;
03725   unsigned Code = DeclsCursor.ReadCode();
03726   switch ((TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
03727   case TYPE_EXT_QUAL: {
03728     if (Record.size() != 2) {
03729       Error("Incorrect encoding of extended qualifier type");
03730       return QualType();
03731     }
03732     QualType Base = readType(*Loc.F, Record, Idx);
03733     Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
03734     return Context.getQualifiedType(Base, Quals);
03735   }
03736 
03737   case TYPE_COMPLEX: {
03738     if (Record.size() != 1) {
03739       Error("Incorrect encoding of complex type");
03740       return QualType();
03741     }
03742     QualType ElemType = readType(*Loc.F, Record, Idx);
03743     return Context.getComplexType(ElemType);
03744   }
03745 
03746   case TYPE_POINTER: {
03747     if (Record.size() != 1) {
03748       Error("Incorrect encoding of pointer type");
03749       return QualType();
03750     }
03751     QualType PointeeType = readType(*Loc.F, Record, Idx);
03752     return Context.getPointerType(PointeeType);
03753   }
03754 
03755   case TYPE_BLOCK_POINTER: {
03756     if (Record.size() != 1) {
03757       Error("Incorrect encoding of block pointer type");
03758       return QualType();
03759     }
03760     QualType PointeeType = readType(*Loc.F, Record, Idx);
03761     return Context.getBlockPointerType(PointeeType);
03762   }
03763 
03764   case TYPE_LVALUE_REFERENCE: {
03765     if (Record.size() != 2) {
03766       Error("Incorrect encoding of lvalue reference type");
03767       return QualType();
03768     }
03769     QualType PointeeType = readType(*Loc.F, Record, Idx);
03770     return Context.getLValueReferenceType(PointeeType, Record[1]);
03771   }
03772 
03773   case TYPE_RVALUE_REFERENCE: {
03774     if (Record.size() != 1) {
03775       Error("Incorrect encoding of rvalue reference type");
03776       return QualType();
03777     }
03778     QualType PointeeType = readType(*Loc.F, Record, Idx);
03779     return Context.getRValueReferenceType(PointeeType);
03780   }
03781 
03782   case TYPE_MEMBER_POINTER: {
03783     if (Record.size() != 2) {
03784       Error("Incorrect encoding of member pointer type");
03785       return QualType();
03786     }
03787     QualType PointeeType = readType(*Loc.F, Record, Idx);
03788     QualType ClassType = readType(*Loc.F, Record, Idx);
03789     if (PointeeType.isNull() || ClassType.isNull())
03790       return QualType();
03791     
03792     return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
03793   }
03794 
03795   case TYPE_CONSTANT_ARRAY: {
03796     QualType ElementType = readType(*Loc.F, Record, Idx);
03797     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
03798     unsigned IndexTypeQuals = Record[2];
03799     unsigned Idx = 3;
03800     llvm::APInt Size = ReadAPInt(Record, Idx);
03801     return Context.getConstantArrayType(ElementType, Size,
03802                                          ASM, IndexTypeQuals);
03803   }
03804 
03805   case TYPE_INCOMPLETE_ARRAY: {
03806     QualType ElementType = readType(*Loc.F, Record, Idx);
03807     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
03808     unsigned IndexTypeQuals = Record[2];
03809     return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
03810   }
03811 
03812   case TYPE_VARIABLE_ARRAY: {
03813     QualType ElementType = readType(*Loc.F, Record, Idx);
03814     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
03815     unsigned IndexTypeQuals = Record[2];
03816     SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
03817     SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
03818     return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
03819                                          ASM, IndexTypeQuals,
03820                                          SourceRange(LBLoc, RBLoc));
03821   }
03822 
03823   case TYPE_VECTOR: {
03824     if (Record.size() != 3) {
03825       Error("incorrect encoding of vector type in AST file");
03826       return QualType();
03827     }
03828 
03829     QualType ElementType = readType(*Loc.F, Record, Idx);
03830     unsigned NumElements = Record[1];
03831     unsigned VecKind = Record[2];
03832     return Context.getVectorType(ElementType, NumElements,
03833                                   (VectorType::VectorKind)VecKind);
03834   }
03835 
03836   case TYPE_EXT_VECTOR: {
03837     if (Record.size() != 3) {
03838       Error("incorrect encoding of extended vector type in AST file");
03839       return QualType();
03840     }
03841 
03842     QualType ElementType = readType(*Loc.F, Record, Idx);
03843     unsigned NumElements = Record[1];
03844     return Context.getExtVectorType(ElementType, NumElements);
03845   }
03846 
03847   case TYPE_FUNCTION_NO_PROTO: {
03848     if (Record.size() != 6) {
03849       Error("incorrect encoding of no-proto function type");
03850       return QualType();
03851     }
03852     QualType ResultType = readType(*Loc.F, Record, Idx);
03853     FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
03854                                (CallingConv)Record[4], Record[5]);
03855     return Context.getFunctionNoProtoType(ResultType, Info);
03856   }
03857 
03858   case TYPE_FUNCTION_PROTO: {
03859     QualType ResultType = readType(*Loc.F, Record, Idx);
03860 
03861     FunctionProtoType::ExtProtoInfo EPI;
03862     EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
03863                                         /*hasregparm*/ Record[2],
03864                                         /*regparm*/ Record[3],
03865                                         static_cast<CallingConv>(Record[4]),
03866                                         /*produces*/ Record[5]);
03867 
03868     unsigned Idx = 6;
03869     unsigned NumParams = Record[Idx++];
03870     SmallVector<QualType, 16> ParamTypes;
03871     for (unsigned I = 0; I != NumParams; ++I)
03872       ParamTypes.push_back(readType(*Loc.F, Record, Idx));
03873 
03874     EPI.Variadic = Record[Idx++];
03875     EPI.HasTrailingReturn = Record[Idx++];
03876     EPI.TypeQuals = Record[Idx++];
03877     EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
03878     ExceptionSpecificationType EST =
03879         static_cast<ExceptionSpecificationType>(Record[Idx++]);
03880     EPI.ExceptionSpecType = EST;
03881     SmallVector<QualType, 2> Exceptions;
03882     if (EST == EST_Dynamic) {
03883       EPI.NumExceptions = Record[Idx++];
03884       for (unsigned I = 0; I != EPI.NumExceptions; ++I)
03885         Exceptions.push_back(readType(*Loc.F, Record, Idx));
03886       EPI.Exceptions = Exceptions.data();
03887     } else if (EST == EST_ComputedNoexcept) {
03888       EPI.NoexceptExpr = ReadExpr(*Loc.F);
03889     } else if (EST == EST_Uninstantiated) {
03890       EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
03891       EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
03892     }
03893     return Context.getFunctionType(ResultType, ParamTypes.data(), NumParams,
03894                                     EPI);
03895   }
03896 
03897   case TYPE_UNRESOLVED_USING: {
03898     unsigned Idx = 0;
03899     return Context.getTypeDeclType(
03900                   ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
03901   }
03902       
03903   case TYPE_TYPEDEF: {
03904     if (Record.size() != 2) {
03905       Error("incorrect encoding of typedef type");
03906       return QualType();
03907     }
03908     unsigned Idx = 0;
03909     TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
03910     QualType Canonical = readType(*Loc.F, Record, Idx);
03911     if (!Canonical.isNull())
03912       Canonical = Context.getCanonicalType(Canonical);
03913     return Context.getTypedefType(Decl, Canonical);
03914   }
03915 
03916   case TYPE_TYPEOF_EXPR:
03917     return Context.getTypeOfExprType(ReadExpr(*Loc.F));
03918 
03919   case TYPE_TYPEOF: {
03920     if (Record.size() != 1) {
03921       Error("incorrect encoding of typeof(type) in AST file");
03922       return QualType();
03923     }
03924     QualType UnderlyingType = readType(*Loc.F, Record, Idx);
03925     return Context.getTypeOfType(UnderlyingType);
03926   }
03927 
03928   case TYPE_DECLTYPE: {
03929     QualType UnderlyingType = readType(*Loc.F, Record, Idx);
03930     return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
03931   }
03932 
03933   case TYPE_UNARY_TRANSFORM: {
03934     QualType BaseType = readType(*Loc.F, Record, Idx);
03935     QualType UnderlyingType = readType(*Loc.F, Record, Idx);
03936     UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
03937     return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
03938   }
03939 
03940   case TYPE_AUTO:
03941     return Context.getAutoType(readType(*Loc.F, Record, Idx));
03942 
03943   case TYPE_RECORD: {
03944     if (Record.size() != 2) {
03945       Error("incorrect encoding of record type");
03946       return QualType();
03947     }
03948     unsigned Idx = 0;
03949     bool IsDependent = Record[Idx++];
03950     RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
03951     RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
03952     QualType T = Context.getRecordType(RD);
03953     const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
03954     return T;
03955   }
03956 
03957   case TYPE_ENUM: {
03958     if (Record.size() != 2) {
03959       Error("incorrect encoding of enum type");
03960       return QualType();
03961     }
03962     unsigned Idx = 0;
03963     bool IsDependent = Record[Idx++];
03964     QualType T
03965       = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
03966     const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
03967     return T;
03968   }
03969 
03970   case TYPE_ATTRIBUTED: {
03971     if (Record.size() != 3) {
03972       Error("incorrect encoding of attributed type");
03973       return QualType();
03974     }
03975     QualType modifiedType = readType(*Loc.F, Record, Idx);
03976     QualType equivalentType = readType(*Loc.F, Record, Idx);
03977     AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
03978     return Context.getAttributedType(kind, modifiedType, equivalentType);
03979   }
03980 
03981   case TYPE_PAREN: {
03982     if (Record.size() != 1) {
03983       Error("incorrect encoding of paren type");
03984       return QualType();
03985     }
03986     QualType InnerType = readType(*Loc.F, Record, Idx);
03987     return Context.getParenType(InnerType);
03988   }
03989 
03990   case TYPE_PACK_EXPANSION: {
03991     if (Record.size() != 2) {
03992       Error("incorrect encoding of pack expansion type");
03993       return QualType();
03994     }
03995     QualType Pattern = readType(*Loc.F, Record, Idx);
03996     if (Pattern.isNull())
03997       return QualType();
03998     llvm::Optional<unsigned> NumExpansions;
03999     if (Record[1])
04000       NumExpansions = Record[1] - 1;
04001     return Context.getPackExpansionType(Pattern, NumExpansions);
04002   }
04003 
04004   case TYPE_ELABORATED: {
04005     unsigned Idx = 0;
04006     ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
04007     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
04008     QualType NamedType = readType(*Loc.F, Record, Idx);
04009     return Context.getElaboratedType(Keyword, NNS, NamedType);
04010   }
04011 
04012   case TYPE_OBJC_INTERFACE: {
04013     unsigned Idx = 0;
04014     ObjCInterfaceDecl *ItfD
04015       = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
04016     return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
04017   }
04018 
04019   case TYPE_OBJC_OBJECT: {
04020     unsigned Idx = 0;
04021     QualType Base = readType(*Loc.F, Record, Idx);
04022     unsigned NumProtos = Record[Idx++];
04023     SmallVector<ObjCProtocolDecl*, 4> Protos;
04024     for (unsigned I = 0; I != NumProtos; ++I)
04025       Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
04026     return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
04027   }
04028 
04029   case TYPE_OBJC_OBJECT_POINTER: {
04030     unsigned Idx = 0;
04031     QualType Pointee = readType(*Loc.F, Record, Idx);
04032     return Context.getObjCObjectPointerType(Pointee);
04033   }
04034 
04035   case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
04036     unsigned Idx = 0;
04037     QualType Parm = readType(*Loc.F, Record, Idx);
04038     QualType Replacement = readType(*Loc.F, Record, Idx);
04039     return
04040       Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
04041                                             Replacement);
04042   }
04043 
04044   case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
04045     unsigned Idx = 0;
04046     QualType Parm = readType(*Loc.F, Record, Idx);
04047     TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
04048     return Context.getSubstTemplateTypeParmPackType(
04049                                                cast<TemplateTypeParmType>(Parm),
04050                                                      ArgPack);
04051   }
04052 
04053   case TYPE_INJECTED_CLASS_NAME: {
04054     CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
04055     QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
04056     // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
04057     // for AST reading, too much interdependencies.
04058     return
04059       QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
04060   }
04061 
04062   case TYPE_TEMPLATE_TYPE_PARM: {
04063     unsigned Idx = 0;
04064     unsigned Depth = Record[Idx++];
04065     unsigned Index = Record[Idx++];
04066     bool Pack = Record[Idx++];
04067     TemplateTypeParmDecl *D
04068       = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
04069     return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
04070   }
04071 
04072   case TYPE_DEPENDENT_NAME: {
04073     unsigned Idx = 0;
04074     ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
04075     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
04076     const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
04077     QualType Canon = readType(*Loc.F, Record, Idx);
04078     if (!Canon.isNull())
04079       Canon = Context.getCanonicalType(Canon);
04080     return Context.getDependentNameType(Keyword, NNS, Name, Canon);
04081   }
04082 
04083   case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
04084     unsigned Idx = 0;
04085     ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
04086     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
04087     const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
04088     unsigned NumArgs = Record[Idx++];
04089     SmallVector<TemplateArgument, 8> Args;
04090     Args.reserve(NumArgs);
04091     while (NumArgs--)
04092       Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
04093     return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
04094                                                       Args.size(), Args.data());
04095   }
04096 
04097   case TYPE_DEPENDENT_SIZED_ARRAY: {
04098     unsigned Idx = 0;
04099 
04100     // ArrayType
04101     QualType ElementType = readType(*Loc.F, Record, Idx);
04102     ArrayType::ArraySizeModifier ASM
04103       = (ArrayType::ArraySizeModifier)Record[Idx++];
04104     unsigned IndexTypeQuals = Record[Idx++];
04105 
04106     // DependentSizedArrayType
04107     Expr *NumElts = ReadExpr(*Loc.F);
04108     SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
04109 
04110     return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
04111                                                IndexTypeQuals, Brackets);
04112   }
04113 
04114   case TYPE_TEMPLATE_SPECIALIZATION: {
04115     unsigned Idx = 0;
04116     bool IsDependent = Record[Idx++];
04117     TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
04118     SmallVector<TemplateArgument, 8> Args;
04119     ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
04120     QualType Underlying = readType(*Loc.F, Record, Idx);
04121     QualType T;
04122     if (Underlying.isNull())
04123       T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
04124                                                           Args.size());
04125     else
04126       T = Context.getTemplateSpecializationType(Name, Args.data(),
04127                                                  Args.size(), Underlying);
04128     const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
04129     return T;
04130   }
04131 
04132   case TYPE_ATOMIC: {
04133     if (Record.size() != 1) {
04134       Error("Incorrect encoding of atomic type");
04135       return QualType();
04136     }
04137     QualType ValueType = readType(*Loc.F, Record, Idx);
04138     return Context.getAtomicType(ValueType);
04139   }
04140   }
04141   llvm_unreachable("Invalid TypeCode!");
04142 }
04143 
04144 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
04145   ASTReader &Reader;
04146   ModuleFile &F;
04147   llvm::BitstreamCursor &DeclsCursor;
04148   const ASTReader::RecordData &Record;
04149   unsigned &Idx;
04150 
04151   SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
04152                                     unsigned &I) {
04153     return Reader.ReadSourceLocation(F, R, I);
04154   }
04155 
04156   template<typename T>
04157   T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
04158     return Reader.ReadDeclAs<T>(F, Record, Idx);
04159   }
04160   
04161 public:
04162   TypeLocReader(ASTReader &Reader, ModuleFile &F,
04163                 const ASTReader::RecordData &Record, unsigned &Idx)
04164     : Reader(Reader), F(F), DeclsCursor(F.DeclsCursor), Record(Record), Idx(Idx)
04165   { }
04166 
04167   // We want compile-time assurance that we've enumerated all of
04168   // these, so unfortunately we have to declare them first, then
04169   // define them out-of-line.
04170 #define ABSTRACT_TYPELOC(CLASS, PARENT)
04171 #define TYPELOC(CLASS, PARENT) \
04172   void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
04173 #include "clang/AST/TypeLocNodes.def"
04174 
04175   void VisitFunctionTypeLoc(FunctionTypeLoc);
04176   void VisitArrayTypeLoc(ArrayTypeLoc);
04177 };
04178 
04179 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
04180   // nothing to do
04181 }
04182 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
04183   TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
04184   if (TL.needsExtraLocalData()) {
04185     TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
04186     TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
04187     TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
04188     TL.setModeAttr(Record[Idx++]);
04189   }
04190 }
04191 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
04192   TL.setNameLoc(ReadSourceLocation(Record, Idx));
04193 }
04194 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
04195   TL.setStarLoc(ReadSourceLocation(Record, Idx));
04196 }
04197 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
04198   TL.setCaretLoc(ReadSourceLocation(Record, Idx));
04199 }
04200 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
04201   TL.setAmpLoc(ReadSourceLocation(Record, Idx));
04202 }
04203 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
04204   TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
04205 }
04206 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
04207   TL.setStarLoc(ReadSourceLocation(Record, Idx));
04208   TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
04209 }
04210 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
04211   TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
04212   TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
04213   if (Record[Idx++])
04214     TL.setSizeExpr(Reader.ReadExpr(F));
04215   else
04216     TL.setSizeExpr(0);
04217 }
04218 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
04219   VisitArrayTypeLoc(TL);
04220 }
04221 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
04222   VisitArrayTypeLoc(TL);
04223 }
04224 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
04225   VisitArrayTypeLoc(TL);
04226 }
04227 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
04228                                             DependentSizedArrayTypeLoc TL) {
04229   VisitArrayTypeLoc(TL);
04230 }
04231 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
04232                                         DependentSizedExtVectorTypeLoc TL) {
04233   TL.setNameLoc(ReadSourceLocation(Record, Idx));
04234 }
04235 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
04236   TL.setNameLoc(ReadSourceLocation(Record, Idx));
04237 }
04238 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
04239   TL.setNameLoc(ReadSourceLocation(Record, Idx));
04240 }
04241 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
04242   TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
04243   TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
04244   TL.setTrailingReturn(Record[Idx++]);
04245   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
04246     TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
04247   }
04248 }
04249 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
04250   VisitFunctionTypeLoc(TL);
04251 }
04252 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
04253   VisitFunctionTypeLoc(TL);
04254 }
04255 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
04256   TL.setNameLoc(ReadSourceLocation(Record, Idx));
04257 }
04258 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
04259   TL.setNameLoc(ReadSourceLocation(Record, Idx));
04260 }
04261 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
04262   TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
04263   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
04264   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
04265 }
04266 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
04267   TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
04268   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
04269   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
04270   TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
04271 }
04272 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
04273   TL.setNameLoc(ReadSourceLocation(Record, Idx));
04274 }
04275 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
04276   TL.setKWLoc(ReadSourceLocation(Record, Idx));
04277   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
04278   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
04279   TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
04280 }
04281 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
04282   TL.setNameLoc(ReadSourceLocation(Record, Idx));
04283 }
04284 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
04285   TL.setNameLoc(ReadSourceLocation(Record, Idx));
04286 }
04287 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
04288   TL.setNameLoc(ReadSourceLocation(Record, Idx));
04289 }
04290 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
04291   TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
04292   if (TL.hasAttrOperand()) {
04293     SourceRange range;
04294     range.setBegin(ReadSourceLocation(Record, Idx));
04295     range.setEnd(ReadSourceLocation(Record, Idx));
04296     TL.setAttrOperandParensRange(range);
04297   }
04298   if (TL.hasAttrExprOperand()) {
04299     if (Record[Idx++])
04300       TL.setAttrExprOperand(Reader.ReadExpr(F));
04301     else
04302       TL.setAttrExprOperand(0);
04303   } else if (TL.hasAttrEnumOperand())
04304     TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
04305 }
04306 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
04307   TL.setNameLoc(ReadSourceLocation(Record, Idx));
04308 }
04309 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
04310                                             SubstTemplateTypeParmTypeLoc TL) {
04311   TL.setNameLoc(ReadSourceLocation(Record, Idx));
04312 }
04313 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
04314                                           SubstTemplateTypeParmPackTypeLoc TL) {
04315   TL.setNameLoc(ReadSourceLocation(Record, Idx));
04316 }
04317 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
04318                                            TemplateSpecializationTypeLoc TL) {
04319   TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
04320   TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
04321   TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
04322   TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
04323   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
04324     TL.setArgLocInfo(i,
04325         Reader.GetTemplateArgumentLocInfo(F,
04326                                           TL.getTypePtr()->getArg(i).getKind(),
04327                                           Record, Idx));
04328 }
04329 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
04330   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
04331   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
04332 }
04333 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
04334   TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
04335   TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
04336 }
04337 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
04338   TL.setNameLoc(ReadSourceLocation(Record, Idx));
04339 }
04340 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
04341   TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
04342   TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
04343   TL.setNameLoc(ReadSourceLocation(Record, Idx));
04344 }
04345 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
04346        DependentTemplateSpecializationTypeLoc TL) {
04347   TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
04348   TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
04349   TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
04350   TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
04351   TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
04352   TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
04353   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
04354     TL.setArgLocInfo(I,
04355         Reader.GetTemplateArgumentLocInfo(F,
04356                                           TL.getTypePtr()->getArg(I).getKind(),
04357                                           Record, Idx));
04358 }
04359 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
04360   TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
04361 }
04362 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
04363   TL.setNameLoc(ReadSourceLocation(Record, Idx));
04364 }
04365 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
04366   TL.setHasBaseTypeAsWritten(Record[Idx++]);
04367   TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
04368   TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
04369   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
04370     TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
04371 }
04372 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
04373   TL.setStarLoc(ReadSourceLocation(Record, Idx));
04374 }
04375 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
04376   TL.setKWLoc(ReadSourceLocation(Record, Idx));
04377   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
04378   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
04379 }
04380 
04381 TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
04382                                              const RecordData &Record,
04383                                              unsigned &Idx) {
04384   QualType InfoTy = readType(F, Record, Idx);
04385   if (InfoTy.isNull())
04386     return 0;
04387 
04388   TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
04389   TypeLocReader TLR(*this, F, Record, Idx);
04390   for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
04391     TLR.Visit(TL);
04392   return TInfo;
04393 }
04394 
04395 QualType ASTReader::GetType(TypeID ID) {
04396   unsigned FastQuals = ID & Qualifiers::FastMask;
04397   unsigned Index = ID >> Qualifiers::FastWidth;
04398 
04399   if (Index < NUM_PREDEF_TYPE_IDS) {
04400     QualType T;
04401     switch ((PredefinedTypeIDs)Index) {
04402     case PREDEF_TYPE_NULL_ID: return QualType();
04403     case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
04404     case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
04405 
04406     case PREDEF_TYPE_CHAR_U_ID:
04407     case PREDEF_TYPE_CHAR_S_ID:
04408       // FIXME: Check that the signedness of CharTy is correct!
04409       T = Context.CharTy;
04410       break;
04411 
04412     case PREDEF_TYPE_UCHAR_ID:      T = Context.UnsignedCharTy;     break;
04413     case PREDEF_TYPE_USHORT_ID:     T = Context.UnsignedShortTy;    break;
04414     case PREDEF_TYPE_UINT_ID:       T = Context.UnsignedIntTy;      break;
04415     case PREDEF_TYPE_ULONG_ID:      T = Context.UnsignedLongTy;     break;
04416     case PREDEF_TYPE_ULONGLONG_ID:  T = Context.UnsignedLongLongTy; break;
04417     case PREDEF_TYPE_UINT128_ID:    T = Context.UnsignedInt128Ty;   break;
04418     case PREDEF_TYPE_SCHAR_ID:      T = Context.SignedCharTy;       break;
04419     case PREDEF_TYPE_WCHAR_ID:      T = Context.WCharTy;            break;
04420     case PREDEF_TYPE_SHORT_ID:      T = Context.ShortTy;            break;
04421     case PREDEF_TYPE_INT_ID:        T = Context.IntTy;              break;
04422     case PREDEF_TYPE_LONG_ID:       T = Context.LongTy;             break;
04423     case PREDEF_TYPE_LONGLONG_ID:   T = Context.LongLongTy;         break;
04424     case PREDEF_TYPE_INT128_ID:     T = Context.Int128Ty;           break;
04425     case PREDEF_TYPE_HALF_ID:       T = Context.HalfTy;             break;
04426     case PREDEF_TYPE_FLOAT_ID:      T = Context.FloatTy;            break;
04427     case PREDEF_TYPE_DOUBLE_ID:     T = Context.DoubleTy;           break;
04428     case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy;       break;
04429     case PREDEF_TYPE_OVERLOAD_ID:   T = Context.OverloadTy;         break;
04430     case PREDEF_TYPE_BOUND_MEMBER:  T = Context.BoundMemberTy;      break;
04431     case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy;     break;
04432     case PREDEF_TYPE_DEPENDENT_ID:  T = Context.DependentTy;        break;
04433     case PREDEF_TYPE_UNKNOWN_ANY:   T = Context.UnknownAnyTy;       break;
04434     case PREDEF_TYPE_NULLPTR_ID:    T = Context.NullPtrTy;          break;
04435     case PREDEF_TYPE_CHAR16_ID:     T = Context.Char16Ty;           break;
04436     case PREDEF_TYPE_CHAR32_ID:     T = Context.Char32Ty;           break;
04437     case PREDEF_TYPE_OBJC_ID:       T = Context.ObjCBuiltinIdTy;    break;
04438     case PREDEF_TYPE_OBJC_CLASS:    T = Context.ObjCBuiltinClassTy; break;
04439     case PREDEF_TYPE_OBJC_SEL:      T = Context.ObjCBuiltinSelTy;   break;
04440     case PREDEF_TYPE_AUTO_DEDUCT:   T = Context.getAutoDeductType(); break;
04441         
04442     case PREDEF_TYPE_AUTO_RREF_DEDUCT: 
04443       T = Context.getAutoRRefDeductType(); 
04444       break;
04445 
04446     case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
04447       T = Context.ARCUnbridgedCastTy;
04448       break;
04449 
04450     }
04451 
04452     assert(!T.isNull() && "Unknown predefined type");
04453     return T.withFastQualifiers(FastQuals);
04454   }
04455 
04456   Index -= NUM_PREDEF_TYPE_IDS;
04457   assert(Index < TypesLoaded.size() && "Type index out-of-range");
04458   if (TypesLoaded[Index].isNull()) {
04459     TypesLoaded[Index] = readTypeRecord(Index);
04460     if (TypesLoaded[Index].isNull())
04461       return QualType();
04462 
04463     TypesLoaded[Index]->setFromAST();
04464     if (DeserializationListener)
04465       DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
04466                                         TypesLoaded[Index]);
04467   }
04468 
04469   return TypesLoaded[Index].withFastQualifiers(FastQuals);
04470 }
04471 
04472 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
04473   return GetType(getGlobalTypeID(F, LocalID));
04474 }
04475 
04476 serialization::TypeID 
04477 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
04478   unsigned FastQuals = LocalID & Qualifiers::FastMask;
04479   unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
04480   
04481   if (LocalIndex < NUM_PREDEF_TYPE_IDS)
04482     return LocalID;
04483 
04484   ContinuousRangeMap<uint32_t, int, 2>::iterator I
04485     = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
04486   assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
04487   
04488   unsigned GlobalIndex = LocalIndex + I->second;
04489   return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
04490 }
04491 
04492 TemplateArgumentLocInfo
04493 ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
04494                                       TemplateArgument::ArgKind Kind,
04495                                       const RecordData &Record,
04496                                       unsigned &Index) {
04497   switch (Kind) {
04498   case TemplateArgument::Expression:
04499     return ReadExpr(F);
04500   case TemplateArgument::Type:
04501     return GetTypeSourceInfo(F, Record, Index);
04502   case TemplateArgument::Template: {
04503     NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, 
04504                                                                      Index);
04505     SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
04506     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
04507                                    SourceLocation());
04508   }
04509   case TemplateArgument::TemplateExpansion: {
04510     NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, 
04511                                                                      Index);
04512     SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
04513     SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
04514     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc, 
04515                                    EllipsisLoc);
04516   }
04517   case TemplateArgument::Null:
04518   case TemplateArgument::Integral:
04519   case TemplateArgument::Declaration:
04520   case TemplateArgument::Pack:
04521     return TemplateArgumentLocInfo();
04522   }
04523   llvm_unreachable("unexpected template argument loc");
04524 }
04525 
04526 TemplateArgumentLoc
04527 ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
04528                                    const RecordData &Record, unsigned &Index) {
04529   TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
04530 
04531   if (Arg.getKind() == TemplateArgument::Expression) {
04532     if (Record[Index++]) // bool InfoHasSameExpr.
04533       return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
04534   }
04535   return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
04536                                                              Record, Index));
04537 }
04538 
04539 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
04540   return GetDecl(ID);
04541 }
04542 
04543 uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record, 
04544                                           unsigned &Idx){
04545   if (Idx >= Record.size())
04546     return 0;
04547   
04548   unsigned LocalID = Record[Idx++];
04549   return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
04550 }
04551 
04552 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
04553   RecordLocation Loc = getLocalBitOffset(Offset);
04554   llvm::BitstreamCursor &Cursor = Loc.F->DeclsCursor;
04555   SavedStreamPosition SavedPosition(Cursor);
04556   Cursor.JumpToBit(Loc.Offset);
04557   ReadingKindTracker ReadingKind(Read_Decl, *this);
04558   RecordData Record;
04559   unsigned Code = Cursor.ReadCode();
04560   unsigned RecCode = Cursor.ReadRecord(Code, Record);
04561   if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
04562     Error("Malformed AST file: missing C++ base specifiers");
04563     return 0;
04564   }
04565 
04566   unsigned Idx = 0;
04567   unsigned NumBases = Record[Idx++];
04568   void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
04569   CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
04570   for (unsigned I = 0; I != NumBases; ++I)
04571     Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
04572   return Bases;
04573 }
04574 
04575 serialization::DeclID 
04576 ASTReader::getGlobalDeclID(ModuleFile &F, unsigned LocalID) const {
04577   if (LocalID < NUM_PREDEF_DECL_IDS)
04578     return LocalID;
04579 
04580   ContinuousRangeMap<uint32_t, int, 2>::iterator I
04581     = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
04582   assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
04583   
04584   return LocalID + I->second;
04585 }
04586 
04587 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
04588                                    ModuleFile &M) const {
04589   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
04590   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
04591   return &M == I->second;
04592 }
04593 
04594 ModuleFile *ASTReader::getOwningModuleFile(Decl *D) {
04595   if (!D->isFromASTFile())
04596     return 0;
04597   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
04598   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
04599   return I->second;
04600 }
04601 
04602 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
04603   if (ID < NUM_PREDEF_DECL_IDS)
04604     return SourceLocation();
04605   
04606   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
04607 
04608   if (Index > DeclsLoaded.size()) {
04609     Error("declaration ID out-of-range for AST file");
04610     return SourceLocation();
04611   }
04612   
04613   if (Decl *D = DeclsLoaded[Index])
04614     return D->getLocation();
04615 
04616   unsigned RawLocation = 0;
04617   RecordLocation Rec = DeclCursorForID(ID, RawLocation);
04618   return ReadSourceLocation(*Rec.F, RawLocation);
04619 }
04620 
04621 Decl *ASTReader::GetDecl(DeclID ID) {
04622   if (ID < NUM_PREDEF_DECL_IDS) {    
04623     switch ((PredefinedDeclIDs)ID) {
04624     case PREDEF_DECL_NULL_ID:
04625       return 0;
04626         
04627     case PREDEF_DECL_TRANSLATION_UNIT_ID:
04628       return Context.getTranslationUnitDecl();
04629         
04630     case PREDEF_DECL_OBJC_ID_ID:
04631       return Context.getObjCIdDecl();
04632 
04633     case PREDEF_DECL_OBJC_SEL_ID:
04634       return Context.getObjCSelDecl();
04635 
04636     case PREDEF_DECL_OBJC_CLASS_ID:
04637       return Context.getObjCClassDecl();
04638         
04639     case PREDEF_DECL_OBJC_PROTOCOL_ID:
04640       return Context.getObjCProtocolDecl();
04641         
04642     case PREDEF_DECL_INT_128_ID:
04643       return Context.getInt128Decl();
04644 
04645     case PREDEF_DECL_UNSIGNED_INT_128_ID:
04646       return Context.getUInt128Decl();
04647         
04648     case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
04649       return Context.getObjCInstanceTypeDecl();
04650     }
04651   }
04652   
04653   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
04654 
04655   if (Index >= DeclsLoaded.size()) {
04656     Error("declaration ID out-of-range for AST file");
04657   }
04658   
04659   if (!DeclsLoaded[Index]) {
04660     ReadDeclRecord(ID);
04661     if (DeserializationListener)
04662       DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
04663   }
04664 
04665   return DeclsLoaded[Index];
04666 }
04667 
04668 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M, 
04669                                                   DeclID GlobalID) {
04670   if (GlobalID < NUM_PREDEF_DECL_IDS)
04671     return GlobalID;
04672   
04673   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
04674   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
04675   ModuleFile *Owner = I->second;
04676 
04677   llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
04678     = M.GlobalToLocalDeclIDs.find(Owner);
04679   if (Pos == M.GlobalToLocalDeclIDs.end())
04680     return 0;
04681       
04682   return GlobalID - Owner->BaseDeclID + Pos->second;
04683 }
04684 
04685 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F, 
04686                                             const RecordData &Record,
04687                                             unsigned &Idx) {
04688   if (Idx >= Record.size()) {
04689     Error("Corrupted AST file");
04690     return 0;
04691   }
04692   
04693   return getGlobalDeclID(F, Record[Idx++]);
04694 }
04695 
04696 /// \brief Resolve the offset of a statement into a statement.
04697 ///
04698 /// This operation will read a new statement from the external
04699 /// source each time it is called, and is meant to be used via a
04700 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
04701 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
04702   // Switch case IDs are per Decl.
04703   ClearSwitchCaseIDs();
04704 
04705   // Offset here is a global offset across the entire chain.
04706   RecordLocation Loc = getLocalBitOffset(Offset);
04707   Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
04708   return ReadStmtFromStream(*Loc.F);
04709 }
04710 
04711 namespace {
04712   class FindExternalLexicalDeclsVisitor {
04713     ASTReader &Reader;
04714     const DeclContext *DC;
04715     bool (*isKindWeWant)(Decl::Kind);
04716     
04717     SmallVectorImpl<Decl*> &Decls;
04718     bool PredefsVisited[NUM_PREDEF_DECL_IDS];
04719 
04720   public:
04721     FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
04722                                     bool (*isKindWeWant)(Decl::Kind),
04723                                     SmallVectorImpl<Decl*> &Decls)
04724       : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls) 
04725     {
04726       for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
04727         PredefsVisited[I] = false;
04728     }
04729 
04730     static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
04731       if (Preorder)
04732         return false;
04733 
04734       FindExternalLexicalDeclsVisitor *This
04735         = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
04736 
04737       ModuleFile::DeclContextInfosMap::iterator Info
04738         = M.DeclContextInfos.find(This->DC);
04739       if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
04740         return false;
04741 
04742       // Load all of the declaration IDs
04743       for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
04744                                *IDE = ID + Info->second.NumLexicalDecls; 
04745            ID != IDE; ++ID) {
04746         if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
04747           continue;
04748 
04749         // Don't add predefined declarations to the lexical context more
04750         // than once.
04751         if (ID->second < NUM_PREDEF_DECL_IDS) {
04752           if (This->PredefsVisited[ID->second])
04753             continue;
04754 
04755           This->PredefsVisited[ID->second] = true;
04756         }
04757 
04758         if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
04759           if (!This->DC->isDeclInLexicalTraversal(D))
04760             This->Decls.push_back(D);
04761         }
04762       }
04763 
04764       return false;
04765     }
04766   };
04767 }
04768 
04769 ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
04770                                          bool (*isKindWeWant)(Decl::Kind),
04771                                          SmallVectorImpl<Decl*> &Decls) {
04772   // There might be lexical decls in multiple modules, for the TU at
04773   // least. Walk all of the modules in the order they were loaded.
04774   FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
04775   ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
04776   ++NumLexicalDeclContextsRead;
04777   return ELR_Success;
04778 }
04779 
04780 namespace {
04781 
04782 class DeclIDComp {
04783   ASTReader &Reader;
04784   ModuleFile &Mod;
04785 
04786 public:
04787   DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
04788 
04789   bool operator()(LocalDeclID L, LocalDeclID R) const {
04790     SourceLocation LHS = getLocation(L);
04791     SourceLocation RHS = getLocation(R);
04792     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
04793   }
04794 
04795   bool operator()(SourceLocation LHS, LocalDeclID R) const {
04796     SourceLocation RHS = getLocation(R);
04797     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
04798   }
04799 
04800   bool operator()(LocalDeclID L, SourceLocation RHS) const {
04801     SourceLocation LHS = getLocation(L);
04802     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
04803   }
04804 
04805   SourceLocation getLocation(LocalDeclID ID) const {
04806     return Reader.getSourceManager().getFileLoc(
04807             Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
04808   }
04809 };
04810 
04811 }
04812 
04813 void ASTReader::FindFileRegionDecls(FileID File,
04814                                     unsigned Offset, unsigned Length,
04815                                     SmallVectorImpl<Decl *> &Decls) {
04816   SourceManager &SM = getSourceManager();
04817 
04818   llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
04819   if (I == FileDeclIDs.end())
04820     return;
04821 
04822   FileDeclsInfo &DInfo = I->second;
04823   if (DInfo.Decls.empty())
04824     return;
04825 
04826   SourceLocation
04827     BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
04828   SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
04829 
04830   DeclIDComp DIDComp(*this, *DInfo.Mod);
04831   ArrayRef<serialization::LocalDeclID>::iterator
04832     BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
04833                                BeginLoc, DIDComp);
04834   if (BeginIt != DInfo.Decls.begin())
04835     --BeginIt;
04836 
04837   // If we are pointing at a top-level decl inside an objc container, we need
04838   // to backtrack until we find it otherwise we will fail to report that the
04839   // region overlaps with an objc container.
04840   while (BeginIt != DInfo.Decls.begin() &&
04841          GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
04842              ->isTopLevelDeclInObjCContainer())
04843     --BeginIt;
04844 
04845   ArrayRef<serialization::LocalDeclID>::iterator
04846     EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
04847                              EndLoc, DIDComp);
04848   if (EndIt != DInfo.Decls.end())
04849     ++EndIt;
04850   
04851   for (ArrayRef<serialization::LocalDeclID>::iterator
04852          DIt = BeginIt; DIt != EndIt; ++DIt)
04853     Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
04854 }
04855 
04856 namespace {
04857   /// \brief ModuleFile visitor used to perform name lookup into a
04858   /// declaration context.
04859   class DeclContextNameLookupVisitor {
04860     ASTReader &Reader;
04861     llvm::SmallVectorImpl<const DeclContext *> &Contexts;
04862     const DeclContext *DC;
04863     DeclarationName Name;
04864     SmallVectorImpl<NamedDecl *> &Decls;
04865 
04866   public:
04867     DeclContextNameLookupVisitor(ASTReader &Reader, 
04868                                  SmallVectorImpl<const DeclContext *> &Contexts, 
04869                                  DeclarationName Name,
04870                                  SmallVectorImpl<NamedDecl *> &Decls)
04871       : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
04872 
04873     static bool visit(ModuleFile &M, void *UserData) {
04874       DeclContextNameLookupVisitor *This
04875         = static_cast<DeclContextNameLookupVisitor *>(UserData);
04876 
04877       // Check whether we have any visible declaration information for
04878       // this context in this module.
04879       ModuleFile::DeclContextInfosMap::iterator Info;
04880       bool FoundInfo = false;
04881       for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
04882         Info = M.DeclContextInfos.find(This->Contexts[I]);
04883         if (Info != M.DeclContextInfos.end() && 
04884             Info->second.NameLookupTableData) {
04885           FoundInfo = true;
04886           break;
04887         }
04888       }
04889 
04890       if (!FoundInfo)
04891         return false;
04892       
04893       // Look for this name within this module.
04894       ASTDeclContextNameLookupTable *LookupTable =
04895         Info->second.NameLookupTableData;
04896       ASTDeclContextNameLookupTable::iterator Pos
04897         = LookupTable->find(This->Name);
04898       if (Pos == LookupTable->end())
04899         return false;
04900 
04901       bool FoundAnything = false;
04902       ASTDeclContextNameLookupTrait::data_type Data = *Pos;
04903       for (; Data.first != Data.second; ++Data.first) {
04904         NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
04905         if (!ND)
04906           continue;
04907 
04908         if (ND->getDeclName() != This->Name) {
04909           assert(!This->Name.getCXXNameType().isNull() && 
04910                  "Name mismatch without a type");
04911           continue;
04912         }
04913       
04914         // Record this declaration.
04915         FoundAnything = true;
04916         This->Decls.push_back(ND);
04917       }
04918 
04919       return FoundAnything;
04920     }
04921   };
04922 }
04923 
04924 DeclContext::lookup_result
04925 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
04926                                           DeclarationName Name) {
04927   assert(DC->hasExternalVisibleStorage() &&
04928          "DeclContext has no visible decls in storage");
04929   if (!Name)
04930     return DeclContext::lookup_result(DeclContext::lookup_iterator(0),
04931                                       DeclContext::lookup_iterator(0));
04932 
04933   SmallVector<NamedDecl *, 64> Decls;
04934   
04935   // Compute the declaration contexts we need to look into. Multiple such
04936   // declaration contexts occur when two declaration contexts from disjoint
04937   // modules get merged, e.g., when two namespaces with the same name are 
04938   // independently defined in separate modules.
04939   SmallVector<const DeclContext *, 2> Contexts;
04940   Contexts.push_back(DC);
04941   
04942   if (DC->isNamespace()) {
04943     MergedDeclsMap::iterator Merged
04944       = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
04945     if (Merged != MergedDecls.end()) {
04946       for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
04947         Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
04948     }
04949   }
04950   
04951   DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
04952   ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
04953   ++NumVisibleDeclContextsRead;
04954   SetExternalVisibleDeclsForName(DC, Name, Decls);
04955   return const_cast<DeclContext*>(DC)->lookup(Name);
04956 }
04957 
04958 namespace {
04959   /// \brief ModuleFile visitor used to retrieve all visible names in a
04960   /// declaration context.
04961   class DeclContextAllNamesVisitor {
04962     ASTReader &Reader;
04963     llvm::SmallVectorImpl<const DeclContext *> &Contexts;
04964     const DeclContext *DC;
04965     llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > &Decls;
04966 
04967   public:
04968     DeclContextAllNamesVisitor(ASTReader &Reader,
04969                                SmallVectorImpl<const DeclContext *> &Contexts,
04970                                llvm::DenseMap<DeclarationName,
04971                                            SmallVector<NamedDecl *, 8> > &Decls)
04972       : Reader(Reader), Contexts(Contexts), Decls(Decls) { }
04973 
04974     static bool visit(ModuleFile &M, void *UserData) {
04975       DeclContextAllNamesVisitor *This
04976         = static_cast<DeclContextAllNamesVisitor *>(UserData);
04977 
04978       // Check whether we have any visible declaration information for
04979       // this context in this module.
04980       ModuleFile::DeclContextInfosMap::iterator Info;
04981       bool FoundInfo = false;
04982       for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
04983         Info = M.DeclContextInfos.find(This->Contexts[I]);
04984         if (Info != M.DeclContextInfos.end() &&
04985             Info->second.NameLookupTableData) {
04986           FoundInfo = true;
04987           break;
04988         }
04989       }
04990 
04991       if (!FoundInfo)
04992         return false;
04993 
04994       ASTDeclContextNameLookupTable *LookupTable =
04995         Info->second.NameLookupTableData;
04996       bool FoundAnything = false;
04997       for (ASTDeclContextNameLookupTable::data_iterator
04998        I = LookupTable->data_begin(), E = LookupTable->data_end();
04999      I != E; ++I) {
05000         ASTDeclContextNameLookupTrait::data_type Data = *I;
05001         for (; Data.first != Data.second; ++Data.first) {
05002           NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
05003                                                                  *Data.first);
05004           if (!ND)
05005             continue;
05006 
05007           // Record this declaration.
05008           FoundAnything = true;
05009           This->Decls[ND->getDeclName()].push_back(ND);
05010         }
05011       }
05012 
05013       return FoundAnything;
05014     }
05015   };
05016 }
05017 
05018 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
05019   if (!DC->hasExternalVisibleStorage())
05020     return;
05021   llvm::DenseMap<DeclarationName, llvm::SmallVector<NamedDecl*, 8> > Decls;
05022 
05023   // Compute the declaration contexts we need to look into. Multiple such
05024   // declaration contexts occur when two declaration contexts from disjoint
05025   // modules get merged, e.g., when two namespaces with the same name are
05026   // independently defined in separate modules.
05027   SmallVector<const DeclContext *, 2> Contexts;
05028   Contexts.push_back(DC);
05029 
05030   if (DC->isNamespace()) {
05031     MergedDeclsMap::iterator Merged
05032       = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
05033     if (Merged != MergedDecls.end()) {
05034       for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
05035         Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
05036     }
05037   }
05038 
05039   DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls);
05040   ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
05041   ++NumVisibleDeclContextsRead;
05042 
05043   for (llvm::DenseMap<DeclarationName,
05044                       llvm::SmallVector<NamedDecl*, 8> >::iterator
05045          I = Decls.begin(), E = Decls.end(); I != E; ++I) {
05046     SetExternalVisibleDeclsForName(DC, I->first, I->second);
05047   }
05048   const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
05049 }
05050 
05051 /// \brief Under non-PCH compilation the consumer receives the objc methods
05052 /// before receiving the implementation, and codegen depends on this.
05053 /// We simulate this by deserializing and passing to consumer the methods of the
05054 /// implementation before passing the deserialized implementation decl.
05055 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
05056                                        ASTConsumer *Consumer) {
05057   assert(ImplD && Consumer);
05058 
05059   for (ObjCImplDecl::method_iterator
05060          I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
05061     Consumer->HandleInterestingDecl(DeclGroupRef(&*I));
05062 
05063   Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
05064 }
05065 
05066 void ASTReader::PassInterestingDeclsToConsumer() {
05067   assert(Consumer);
05068   while (!InterestingDecls.empty()) {
05069     Decl *D = InterestingDecls.front();
05070     InterestingDecls.pop_front();
05071 
05072     PassInterestingDeclToConsumer(D);
05073   }
05074 }
05075 
05076 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
05077   if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
05078     PassObjCImplDeclToConsumer(ImplD, Consumer);
05079   else
05080     Consumer->HandleInterestingDecl(DeclGroupRef(D));
05081 }
05082 
05083 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
05084   this->Consumer = Consumer;
05085 
05086   if (!Consumer)
05087     return;
05088 
05089   for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
05090     // Force deserialization of this decl, which will cause it to be queued for
05091     // passing to the consumer.
05092     GetDecl(ExternalDefinitions[I]);
05093   }
05094   ExternalDefinitions.clear();
05095 
05096   PassInterestingDeclsToConsumer();
05097 }
05098 
05099 void ASTReader::PrintStats() {
05100   std::fprintf(stderr, "*** AST File Statistics:\n");
05101 
05102   unsigned NumTypesLoaded
05103     = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
05104                                       QualType());
05105   unsigned NumDeclsLoaded
05106     = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
05107                                       (Decl *)0);
05108   unsigned NumIdentifiersLoaded
05109     = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
05110                                             IdentifiersLoaded.end(),
05111                                             (IdentifierInfo *)0);
05112   unsigned NumSelectorsLoaded
05113     = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
05114                                           SelectorsLoaded.end(),
05115                                           Selector());
05116 
05117   std::fprintf(stderr, "  %u stat cache hits\n", NumStatHits);
05118   std::fprintf(stderr, "  %u stat cache misses\n", NumStatMisses);
05119   if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
05120     std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
05121                  NumSLocEntriesRead, TotalNumSLocEntries,
05122                  ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
05123   if (!TypesLoaded.empty())
05124     std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
05125                  NumTypesLoaded, (unsigned)TypesLoaded.size(),
05126                  ((float)NumTypesLoaded/TypesLoaded.size() * 100));
05127   if (!DeclsLoaded.empty())
05128     std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
05129                  NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
05130                  ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
05131   if (!IdentifiersLoaded.empty())
05132     std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
05133                  NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
05134                  ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
05135   if (!SelectorsLoaded.empty())
05136     std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
05137                  NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
05138                  ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
05139   if (TotalNumStatements)
05140     std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
05141                  NumStatementsRead, TotalNumStatements,
05142                  ((float)NumStatementsRead/TotalNumStatements * 100));
05143   if (TotalNumMacros)
05144     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
05145                  NumMacrosRead, TotalNumMacros,
05146                  ((float)NumMacrosRead/TotalNumMacros * 100));
05147   if (TotalLexicalDeclContexts)
05148     std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
05149                  NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
05150                  ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
05151                   * 100));
05152   if (TotalVisibleDeclContexts)
05153     std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
05154                  NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
05155                  ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
05156                   * 100));
05157   if (TotalNumMethodPoolEntries) {
05158     std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
05159                  NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
05160                  ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
05161                   * 100));
05162     std::fprintf(stderr, "  %u method pool misses\n", NumMethodPoolMisses);
05163   }
05164   std::fprintf(stderr, "\n");
05165   dump();
05166   std::fprintf(stderr, "\n");
05167 }
05168 
05169 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
05170 static void 
05171 dumpModuleIDMap(StringRef Name,
05172                 const ContinuousRangeMap<Key, ModuleFile *, 
05173                                          InitialCapacity> &Map) {
05174   if (Map.begin() == Map.end())
05175     return;
05176   
05177   typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
05178   llvm::errs() << Name << ":\n";
05179   for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end(); 
05180        I != IEnd; ++I) {
05181     llvm::errs() << "  " << I->first << " -> " << I->second->FileName
05182       << "\n";
05183   }
05184 }
05185 
05186 void ASTReader::dump() {
05187   llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
05188   dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
05189   dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
05190   dumpModuleIDMap("Global type map", GlobalTypeMap);
05191   dumpModuleIDMap("Global declaration map", GlobalDeclMap);
05192   dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
05193   dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
05194   dumpModuleIDMap("Global selector map", GlobalSelectorMap);
05195   dumpModuleIDMap("Global preprocessed entity map", 
05196                   GlobalPreprocessedEntityMap);
05197   
05198   llvm::errs() << "\n*** PCH/Modules Loaded:";
05199   for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(), 
05200                                        MEnd = ModuleMgr.end();
05201        M != MEnd; ++M)
05202     (*M)->dump();
05203 }
05204 
05205 /// Return the amount of memory used by memory buffers, breaking down
05206 /// by heap-backed versus mmap'ed memory.
05207 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
05208   for (ModuleConstIterator I = ModuleMgr.begin(),
05209       E = ModuleMgr.end(); I != E; ++I) {
05210     if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
05211       size_t bytes = buf->getBufferSize();
05212       switch (buf->getBufferKind()) {
05213         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
05214           sizes.malloc_bytes += bytes;
05215           break;
05216         case llvm::MemoryBuffer::MemoryBuffer_MMap:
05217           sizes.mmap_bytes += bytes;
05218           break;
05219       }
05220     }
05221   }
05222 }
05223 
05224 void ASTReader::InitializeSema(Sema &S) {
05225   SemaObj = &S;
05226   S.ExternalSource = this;
05227 
05228   // Makes sure any declarations that were deserialized "too early"
05229   // still get added to the identifier's declaration chains.
05230   for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
05231     SemaObj->pushExternalDeclIntoScope(PreloadedDecls[I], 
05232                                        PreloadedDecls[I]->getDeclName());
05233   }
05234   PreloadedDecls.clear();
05235 
05236   // Load the offsets of the declarations that Sema references.
05237   // They will be lazily deserialized when needed.
05238   if (!SemaDeclRefs.empty()) {
05239     assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
05240     if (!SemaObj->StdNamespace)
05241       SemaObj->StdNamespace = SemaDeclRefs[0];
05242     if (!SemaObj->StdBadAlloc)
05243       SemaObj->StdBadAlloc = SemaDeclRefs[1];
05244   }
05245 
05246   if (!FPPragmaOptions.empty()) {
05247     assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
05248     SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
05249   }
05250 
05251   if (!OpenCLExtensions.empty()) {
05252     unsigned I = 0;
05253 #define OPENCLEXT(nm)  SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
05254 #include "clang/Basic/OpenCLExtensions.def"
05255 
05256     assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
05257   }
05258 }
05259 
05260 IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
05261   IdentifierLookupVisitor Visitor(StringRef(NameStart, NameEnd - NameStart),
05262                                   /*PriorGeneration=*/0);
05263   ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
05264   IdentifierInfo *II = Visitor.getIdentifierInfo();
05265   markIdentifierUpToDate(II);
05266   return II;
05267 }
05268 
05269 namespace clang {
05270   /// \brief An identifier-lookup iterator that enumerates all of the
05271   /// identifiers stored within a set of AST files.
05272   class ASTIdentifierIterator : public IdentifierIterator {
05273     /// \brief The AST reader whose identifiers are being enumerated.
05274     const ASTReader &Reader;
05275 
05276     /// \brief The current index into the chain of AST files stored in
05277     /// the AST reader.
05278     unsigned Index;
05279 
05280     /// \brief The current position within the identifier lookup table
05281     /// of the current AST file.
05282     ASTIdentifierLookupTable::key_iterator Current;
05283 
05284     /// \brief The end position within the identifier lookup table of
05285     /// the current AST file.
05286     ASTIdentifierLookupTable::key_iterator End;
05287 
05288   public:
05289     explicit ASTIdentifierIterator(const ASTReader &Reader);
05290 
05291     virtual StringRef Next();
05292   };
05293 }
05294 
05295 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
05296   : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
05297   ASTIdentifierLookupTable *IdTable
05298     = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
05299   Current = IdTable->key_begin();
05300   End = IdTable->key_end();
05301 }
05302 
05303 StringRef ASTIdentifierIterator::Next() {
05304   while (Current == End) {
05305     // If we have exhausted all of our AST files, we're done.
05306     if (Index == 0)
05307       return StringRef();
05308 
05309     --Index;
05310     ASTIdentifierLookupTable *IdTable
05311       = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
05312         IdentifierLookupTable;
05313     Current = IdTable->key_begin();
05314     End = IdTable->key_end();
05315   }
05316 
05317   // We have any identifiers remaining in the current AST file; return
05318   // the next one.
05319   std::pair<const char*, unsigned> Key = *Current;
05320   ++Current;
05321   return StringRef(Key.first, Key.second);
05322 }
05323 
05324 IdentifierIterator *ASTReader::getIdentifiers() const {
05325   return new ASTIdentifierIterator(*this);
05326 }
05327 
05328 namespace clang { namespace serialization {
05329   class ReadMethodPoolVisitor {
05330     ASTReader &Reader;
05331     Selector Sel;
05332     unsigned PriorGeneration;
05333     llvm::SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
05334     llvm::SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
05335 
05336   public:
05337     ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel, 
05338                           unsigned PriorGeneration)
05339       : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) { }
05340     
05341     static bool visit(ModuleFile &M, void *UserData) {
05342       ReadMethodPoolVisitor *This
05343         = static_cast<ReadMethodPoolVisitor *>(UserData);
05344       
05345       if (!M.SelectorLookupTable)
05346         return false;
05347       
05348       // If we've already searched this module file, skip it now.
05349       if (M.Generation <= This->PriorGeneration)
05350         return true;
05351 
05352       ASTSelectorLookupTable *PoolTable
05353         = (ASTSelectorLookupTable*)M.SelectorLookupTable;
05354       ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
05355       if (Pos == PoolTable->end())
05356         return false;
05357       
05358       ++This->Reader.NumSelectorsRead;
05359       // FIXME: Not quite happy with the statistics here. We probably should
05360       // disable this tracking when called via LoadSelector.
05361       // Also, should entries without methods count as misses?
05362       ++This->Reader.NumMethodPoolEntriesRead;
05363       ASTSelectorLookupTrait::data_type Data = *Pos;
05364       if (This->Reader.DeserializationListener)
05365         This->Reader.DeserializationListener->SelectorRead(Data.ID, 
05366                                                            This->Sel);
05367       
05368       This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
05369       This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
05370       return true;
05371     }
05372     
05373     /// \brief Retrieve the instance methods found by this visitor.
05374     ArrayRef<ObjCMethodDecl *> getInstanceMethods() const { 
05375       return InstanceMethods; 
05376     }
05377 
05378     /// \brief Retrieve the instance methods found by this visitor.
05379     ArrayRef<ObjCMethodDecl *> getFactoryMethods() const { 
05380       return FactoryMethods;
05381     }
05382   };
05383 } } // end namespace clang::serialization
05384 
05385 /// \brief Add the given set of methods to the method list.
05386 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
05387                              ObjCMethodList &List) {
05388   for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
05389     S.addMethodToGlobalList(&List, Methods[I]);
05390   }
05391 }
05392                              
05393 void ASTReader::ReadMethodPool(Selector Sel) {
05394   // Get the selector generation and update it to the current generation.
05395   unsigned &Generation = SelectorGeneration[Sel];
05396   unsigned PriorGeneration = Generation;
05397   Generation = CurrentGeneration;
05398   
05399   // Search for methods defined with this selector.
05400   ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
05401   ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
05402   
05403   if (Visitor.getInstanceMethods().empty() &&
05404       Visitor.getFactoryMethods().empty()) {
05405     ++NumMethodPoolMisses;
05406     return;
05407   }
05408   
05409   if (!getSema())
05410     return;
05411   
05412   Sema &S = *getSema();
05413   Sema::GlobalMethodPool::iterator Pos
05414     = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
05415   
05416   addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
05417   addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
05418 }
05419 
05420 void ASTReader::ReadKnownNamespaces(
05421                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
05422   Namespaces.clear();
05423   
05424   for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
05425     if (NamespaceDecl *Namespace 
05426                 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
05427       Namespaces.push_back(Namespace);
05428   }
05429 }
05430 
05431 void ASTReader::ReadTentativeDefinitions(
05432                   SmallVectorImpl<VarDecl *> &TentativeDefs) {
05433   for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
05434     VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
05435     if (Var)
05436       TentativeDefs.push_back(Var);
05437   }
05438   TentativeDefinitions.clear();
05439 }
05440 
05441 void ASTReader::ReadUnusedFileScopedDecls(
05442                                SmallVectorImpl<const DeclaratorDecl *> &Decls) {
05443   for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
05444     DeclaratorDecl *D
05445       = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
05446     if (D)
05447       Decls.push_back(D);
05448   }
05449   UnusedFileScopedDecls.clear();
05450 }
05451 
05452 void ASTReader::ReadDelegatingConstructors(
05453                                  SmallVectorImpl<CXXConstructorDecl *> &Decls) {
05454   for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
05455     CXXConstructorDecl *D
05456       = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
05457     if (D)
05458       Decls.push_back(D);
05459   }
05460   DelegatingCtorDecls.clear();
05461 }
05462 
05463 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
05464   for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
05465     TypedefNameDecl *D
05466       = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
05467     if (D)
05468       Decls.push_back(D);
05469   }
05470   ExtVectorDecls.clear();
05471 }
05472 
05473 void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
05474   for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
05475     CXXRecordDecl *D
05476       = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
05477     if (D)
05478       Decls.push_back(D);
05479   }
05480   DynamicClasses.clear();
05481 }
05482 
05483 void 
05484 ASTReader::ReadLocallyScopedExternalDecls(SmallVectorImpl<NamedDecl *> &Decls) {
05485   for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
05486     NamedDecl *D 
05487       = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
05488     if (D)
05489       Decls.push_back(D);
05490   }
05491   LocallyScopedExternalDecls.clear();
05492 }
05493 
05494 void ASTReader::ReadReferencedSelectors(
05495        SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
05496   if (ReferencedSelectorsData.empty())
05497     return;
05498   
05499   // If there are @selector references added them to its pool. This is for
05500   // implementation of -Wselector.
05501   unsigned int DataSize = ReferencedSelectorsData.size()-1;
05502   unsigned I = 0;
05503   while (I < DataSize) {
05504     Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
05505     SourceLocation SelLoc
05506       = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
05507     Sels.push_back(std::make_pair(Sel, SelLoc));
05508   }
05509   ReferencedSelectorsData.clear();
05510 }
05511 
05512 void ASTReader::ReadWeakUndeclaredIdentifiers(
05513        SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
05514   if (WeakUndeclaredIdentifiers.empty())
05515     return;
05516 
05517   for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
05518     IdentifierInfo *WeakId 
05519       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
05520     IdentifierInfo *AliasId 
05521       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
05522     SourceLocation Loc
05523       = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
05524     bool Used = WeakUndeclaredIdentifiers[I++];
05525     WeakInfo WI(AliasId, Loc);
05526     WI.setUsed(Used);
05527     WeakIDs.push_back(std::make_pair(WeakId, WI));
05528   }
05529   WeakUndeclaredIdentifiers.clear();
05530 }
05531 
05532 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
05533   for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
05534     ExternalVTableUse VT;
05535     VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
05536     VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
05537     VT.DefinitionRequired = VTableUses[Idx++];
05538     VTables.push_back(VT);
05539   }
05540   
05541   VTableUses.clear();
05542 }
05543 
05544 void ASTReader::ReadPendingInstantiations(
05545        SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
05546   for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
05547     ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
05548     SourceLocation Loc
05549       = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
05550     Pending.push_back(std::make_pair(D, Loc));
05551   }  
05552   PendingInstantiations.clear();
05553 }
05554 
05555 void ASTReader::LoadSelector(Selector Sel) {
05556   // It would be complicated to avoid reading the methods anyway. So don't.
05557   ReadMethodPool(Sel);
05558 }
05559 
05560 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
05561   assert(ID && "Non-zero identifier ID required");
05562   assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
05563   IdentifiersLoaded[ID - 1] = II;
05564   if (DeserializationListener)
05565     DeserializationListener->IdentifierRead(ID, II);
05566 }
05567 
05568 /// \brief Set the globally-visible declarations associated with the given
05569 /// identifier.
05570 ///
05571 /// If the AST reader is currently in a state where the given declaration IDs
05572 /// cannot safely be resolved, they are queued until it is safe to resolve
05573 /// them.
05574 ///
05575 /// \param II an IdentifierInfo that refers to one or more globally-visible
05576 /// declarations.
05577 ///
05578 /// \param DeclIDs the set of declaration IDs with the name @p II that are
05579 /// visible at global scope.
05580 ///
05581 /// \param Nonrecursive should be true to indicate that the caller knows that
05582 /// this call is non-recursive, and therefore the globally-visible declarations
05583 /// will not be placed onto the pending queue.
05584 void
05585 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
05586                               const SmallVectorImpl<uint32_t> &DeclIDs,
05587                                    bool Nonrecursive) {
05588   if (NumCurrentElementsDeserializing && !Nonrecursive) {
05589     PendingIdentifierInfos.push_back(PendingIdentifierInfo());
05590     PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
05591     PII.II = II;
05592     PII.DeclIDs.append(DeclIDs.begin(), DeclIDs.end());
05593     return;
05594   }
05595 
05596   for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
05597     NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
05598     if (SemaObj) {
05599       // Introduce this declaration into the translation-unit scope
05600       // and add it to the declaration chain for this identifier, so
05601       // that (unqualified) name lookup will find it.
05602       SemaObj->pushExternalDeclIntoScope(D, II);
05603     } else {
05604       // Queue this declaration so that it will be added to the
05605       // translation unit scope and identifier's declaration chain
05606       // once a Sema object is known.
05607       PreloadedDecls.push_back(D);
05608     }
05609   }
05610 }
05611 
05612 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
05613   if (ID == 0)
05614     return 0;
05615 
05616   if (IdentifiersLoaded.empty()) {
05617     Error("no identifier table in AST file");
05618     return 0;
05619   }
05620 
05621   ID -= 1;
05622   if (!IdentifiersLoaded[ID]) {
05623     GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
05624     assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
05625     ModuleFile *M = I->second;
05626     unsigned Index = ID - M->BaseIdentifierID;
05627     const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
05628 
05629     // All of the strings in the AST file are preceded by a 16-bit length.
05630     // Extract that 16-bit length to avoid having to execute strlen().
05631     // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
05632     //  unsigned integers.  This is important to avoid integer overflow when
05633     //  we cast them to 'unsigned'.
05634     const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
05635     unsigned StrLen = (((unsigned) StrLenPtr[0])
05636                        | (((unsigned) StrLenPtr[1]) << 8)) - 1;
05637     IdentifiersLoaded[ID]
05638       = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
05639     if (DeserializationListener)
05640       DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
05641   }
05642 
05643   return IdentifiersLoaded[ID];
05644 }
05645 
05646 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
05647   return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
05648 }
05649 
05650 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
05651   if (LocalID < NUM_PREDEF_IDENT_IDS)
05652     return LocalID;
05653   
05654   ContinuousRangeMap<uint32_t, int, 2>::iterator I
05655     = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
05656   assert(I != M.IdentifierRemap.end() 
05657          && "Invalid index into identifier index remap");
05658   
05659   return LocalID + I->second;
05660 }
05661 
05662 bool ASTReader::ReadSLocEntry(int ID) {
05663   return ReadSLocEntryRecord(ID) != Success;
05664 }
05665 
05666 serialization::SubmoduleID
05667 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
05668   if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
05669     return LocalID;
05670   
05671   ContinuousRangeMap<uint32_t, int, 2>::iterator I
05672     = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
05673   assert(I != M.SubmoduleRemap.end() 
05674          && "Invalid index into identifier index remap");
05675   
05676   return LocalID + I->second;
05677 }
05678 
05679 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
05680   if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
05681     assert(GlobalID == 0 && "Unhandled global submodule ID");
05682     return 0;
05683   }
05684   
05685   if (GlobalID > SubmodulesLoaded.size()) {
05686     Error("submodule ID out of range in AST file");
05687     return 0;
05688   }
05689   
05690   return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
05691 }
05692                                
05693 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
05694   return DecodeSelector(getGlobalSelectorID(M, LocalID));
05695 }
05696 
05697 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
05698   if (ID == 0)
05699     return Selector();
05700 
05701   if (ID > SelectorsLoaded.size()) {
05702     Error("selector ID out of range in AST file");
05703     return Selector();
05704   }
05705 
05706   if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
05707     // Load this selector from the selector table.
05708     GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
05709     assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
05710     ModuleFile &M = *I->second;
05711     ASTSelectorLookupTrait Trait(*this, M);
05712     unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
05713     SelectorsLoaded[ID - 1] =
05714       Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
05715     if (DeserializationListener)
05716       DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
05717   }
05718 
05719   return SelectorsLoaded[ID - 1];
05720 }
05721 
05722 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
05723   return DecodeSelector(ID);
05724 }
05725 
05726 uint32_t ASTReader::GetNumExternalSelectors() {
05727   // ID 0 (the null selector) is considered an external selector.
05728   return getTotalNumSelectors() + 1;
05729 }
05730 
05731 serialization::SelectorID
05732 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
05733   if (LocalID < NUM_PREDEF_SELECTOR_IDS)
05734     return LocalID;
05735   
05736   ContinuousRangeMap<uint32_t, int, 2>::iterator I
05737     = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
05738   assert(I != M.SelectorRemap.end() 
05739          && "Invalid index into identifier index remap");
05740   
05741   return LocalID + I->second;
05742 }
05743 
05744 DeclarationName
05745 ASTReader::ReadDeclarationName(ModuleFile &F, 
05746                                const RecordData &Record, unsigned &Idx) {
05747   DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
05748   switch (Kind) {
05749   case DeclarationName::Identifier:
05750     return DeclarationName(GetIdentifierInfo(F, Record, Idx));
05751 
05752   case DeclarationName::ObjCZeroArgSelector:
05753   case DeclarationName::ObjCOneArgSelector:
05754   case DeclarationName::ObjCMultiArgSelector:
05755     return DeclarationName(ReadSelector(F, Record, Idx));
05756 
05757   case DeclarationName::CXXConstructorName:
05758     return Context.DeclarationNames.getCXXConstructorName(
05759                           Context.getCanonicalType(readType(F, Record, Idx)));
05760 
05761   case DeclarationName::CXXDestructorName:
05762     return Context.DeclarationNames.getCXXDestructorName(
05763                           Context.getCanonicalType(readType(F, Record, Idx)));
05764 
05765   case DeclarationName::CXXConversionFunctionName:
05766     return Context.DeclarationNames.getCXXConversionFunctionName(
05767                           Context.getCanonicalType(readType(F, Record, Idx)));
05768 
05769   case DeclarationName::CXXOperatorName:
05770     return Context.DeclarationNames.getCXXOperatorName(
05771                                        (OverloadedOperatorKind)Record[Idx++]);
05772 
05773   case DeclarationName::CXXLiteralOperatorName:
05774     return Context.DeclarationNames.getCXXLiteralOperatorName(
05775                                        GetIdentifierInfo(F, Record, Idx));
05776 
05777   case DeclarationName::CXXUsingDirective:
05778     return DeclarationName::getUsingDirectiveName();
05779   }
05780 
05781   llvm_unreachable("Invalid NameKind!");
05782 }
05783 
05784 void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
05785                                        DeclarationNameLoc &DNLoc,
05786                                        DeclarationName Name,
05787                                       const RecordData &Record, unsigned &Idx) {
05788   switch (Name.getNameKind()) {
05789   case DeclarationName::CXXConstructorName:
05790   case DeclarationName::CXXDestructorName:
05791   case DeclarationName::CXXConversionFunctionName:
05792     DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
05793     break;
05794 
05795   case DeclarationName::CXXOperatorName:
05796     DNLoc.CXXOperatorName.BeginOpNameLoc
05797         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
05798     DNLoc.CXXOperatorName.EndOpNameLoc
05799         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
05800     break;
05801 
05802   case DeclarationName::CXXLiteralOperatorName:
05803     DNLoc.CXXLiteralOperatorName.OpNameLoc
05804         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
05805     break;
05806 
05807   case DeclarationName::Identifier:
05808   case DeclarationName::ObjCZeroArgSelector:
05809   case DeclarationName::ObjCOneArgSelector:
05810   case DeclarationName::ObjCMultiArgSelector:
05811   case DeclarationName::CXXUsingDirective:
05812     break;
05813   }
05814 }
05815 
05816 void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
05817                                         DeclarationNameInfo &NameInfo,
05818                                       const RecordData &Record, unsigned &Idx) {
05819   NameInfo.setName(ReadDeclarationName(F, Record, Idx));
05820   NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
05821   DeclarationNameLoc DNLoc;
05822   ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
05823   NameInfo.setInfo(DNLoc);
05824 }
05825 
05826 void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
05827                                   const RecordData &Record, unsigned &Idx) {
05828   Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
05829   unsigned NumTPLists = Record[Idx++];
05830   Info.NumTemplParamLists = NumTPLists;
05831   if (NumTPLists) {
05832     Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
05833     for (unsigned i=0; i != NumTPLists; ++i)
05834       Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
05835   }
05836 }
05837 
05838 TemplateName
05839 ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record, 
05840                             unsigned &Idx) {
05841   TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
05842   switch (Kind) {
05843   case TemplateName::Template:
05844       return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
05845 
05846   case TemplateName::OverloadedTemplate: {
05847     unsigned size = Record[Idx++];
05848     UnresolvedSet<8> Decls;
05849     while (size--)
05850       Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
05851 
05852     return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
05853   }
05854 
05855   case TemplateName::QualifiedTemplate: {
05856     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
05857     bool hasTemplKeyword = Record[Idx++];
05858     TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
05859     return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
05860   }
05861 
05862   case TemplateName::DependentTemplate: {
05863     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
05864     if (Record[Idx++])  // isIdentifier
05865       return Context.getDependentTemplateName(NNS,
05866                                                GetIdentifierInfo(F, Record, 
05867                                                                  Idx));
05868     return Context.getDependentTemplateName(NNS,
05869                                          (OverloadedOperatorKind)Record[Idx++]);
05870   }
05871 
05872   case TemplateName::SubstTemplateTemplateParm: {
05873     TemplateTemplateParmDecl *param
05874       = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
05875     if (!param) return TemplateName();
05876     TemplateName replacement = ReadTemplateName(F, Record, Idx);
05877     return Context.getSubstTemplateTemplateParm(param, replacement);
05878   }
05879       
05880   case TemplateName::SubstTemplateTemplateParmPack: {
05881     TemplateTemplateParmDecl *Param 
05882       = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
05883     if (!Param)
05884       return TemplateName();
05885     
05886     TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
05887     if (ArgPack.getKind() != TemplateArgument::Pack)
05888       return TemplateName();
05889     
05890     return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
05891   }
05892   }
05893 
05894   llvm_unreachable("Unhandled template name kind!");
05895 }
05896 
05897 TemplateArgument
05898 ASTReader::ReadTemplateArgument(ModuleFile &F,
05899                                 const RecordData &Record, unsigned &Idx) {
05900   TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
05901   switch (Kind) {
05902   case TemplateArgument::Null:
05903     return TemplateArgument();
05904   case TemplateArgument::Type:
05905     return TemplateArgument(readType(F, Record, Idx));
05906   case TemplateArgument::Declaration:
05907     return TemplateArgument(ReadDecl(F, Record, Idx));
05908   case TemplateArgument::Integral: {
05909     llvm::APSInt Value = ReadAPSInt(Record, Idx);
05910     QualType T = readType(F, Record, Idx);
05911     return TemplateArgument(Value, T);
05912   }
05913   case TemplateArgument::Template: 
05914     return TemplateArgument(ReadTemplateName(F, Record, Idx));
05915   case TemplateArgument::TemplateExpansion: {
05916     TemplateName Name = ReadTemplateName(F, Record, Idx);
05917     llvm::Optional<unsigned> NumTemplateExpansions;
05918     if (unsigned NumExpansions = Record[Idx++])
05919       NumTemplateExpansions = NumExpansions - 1;
05920     return TemplateArgument(Name, NumTemplateExpansions);
05921   }
05922   case TemplateArgument::Expression:
05923     return TemplateArgument(ReadExpr(F));
05924   case TemplateArgument::Pack: {
05925     unsigned NumArgs = Record[Idx++];
05926     TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
05927     for (unsigned I = 0; I != NumArgs; ++I)
05928       Args[I] = ReadTemplateArgument(F, Record, Idx);
05929     return TemplateArgument(Args, NumArgs);
05930   }
05931   }
05932 
05933   llvm_unreachable("Unhandled template argument kind!");
05934 }
05935 
05936 TemplateParameterList *
05937 ASTReader::ReadTemplateParameterList(ModuleFile &F,
05938                                      const RecordData &Record, unsigned &Idx) {
05939   SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
05940   SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
05941   SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
05942 
05943   unsigned NumParams = Record[Idx++];
05944   SmallVector<NamedDecl *, 16> Params;
05945   Params.reserve(NumParams);
05946   while (NumParams--)
05947     Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
05948 
05949   TemplateParameterList* TemplateParams =
05950     TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
05951                                   Params.data(), Params.size(), RAngleLoc);
05952   return TemplateParams;
05953 }
05954 
05955 void
05956 ASTReader::
05957 ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
05958                          ModuleFile &F, const RecordData &Record,
05959                          unsigned &Idx) {
05960   unsigned NumTemplateArgs = Record[Idx++];
05961   TemplArgs.reserve(NumTemplateArgs);
05962   while (NumTemplateArgs--)
05963     TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
05964 }
05965 
05966 /// \brief Read a UnresolvedSet structure.
05967 void ASTReader::ReadUnresolvedSet(ModuleFile &F, UnresolvedSetImpl &Set,
05968                                   const RecordData &Record, unsigned &Idx) {
05969   unsigned NumDecls = Record[Idx++];
05970   while (NumDecls--) {
05971     NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
05972     AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
05973     Set.addDecl(D, AS);
05974   }
05975 }
05976 
05977 CXXBaseSpecifier
05978 ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
05979                                 const RecordData &Record, unsigned &Idx) {
05980   bool isVirtual = static_cast<bool>(Record[Idx++]);
05981   bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
05982   AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
05983   bool inheritConstructors = static_cast<bool>(Record[Idx++]);
05984   TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
05985   SourceRange Range = ReadSourceRange(F, Record, Idx);
05986   SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
05987   CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo, 
05988                           EllipsisLoc);
05989   Result.setInheritConstructors(inheritConstructors);
05990   return Result;
05991 }
05992 
05993 std::pair<CXXCtorInitializer **, unsigned>
05994 ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
05995                                    unsigned &Idx) {
05996   CXXCtorInitializer **CtorInitializers = 0;
05997   unsigned NumInitializers = Record[Idx++];
05998   if (NumInitializers) {
05999     CtorInitializers
06000         = new (Context) CXXCtorInitializer*[NumInitializers];
06001     for (unsigned i=0; i != NumInitializers; ++i) {
06002       TypeSourceInfo *TInfo = 0;
06003       bool IsBaseVirtual = false;
06004       FieldDecl *Member = 0;
06005       IndirectFieldDecl *IndirectMember = 0;
06006 
06007       CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
06008       switch (Type) {
06009       case CTOR_INITIALIZER_BASE:
06010         TInfo = GetTypeSourceInfo(F, Record, Idx);
06011         IsBaseVirtual = Record[Idx++];
06012         break;
06013           
06014       case CTOR_INITIALIZER_DELEGATING:
06015         TInfo = GetTypeSourceInfo(F, Record, Idx);
06016         break;
06017 
06018        case CTOR_INITIALIZER_MEMBER:
06019         Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
06020         break;
06021 
06022        case CTOR_INITIALIZER_INDIRECT_MEMBER:
06023         IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
06024         break;
06025       }
06026 
06027       SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
06028       Expr *Init = ReadExpr(F);
06029       SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
06030       SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
06031       bool IsWritten = Record[Idx++];
06032       unsigned SourceOrderOrNumArrayIndices;
06033       SmallVector<VarDecl *, 8> Indices;
06034       if (IsWritten) {
06035         SourceOrderOrNumArrayIndices = Record[Idx++];
06036       } else {
06037         SourceOrderOrNumArrayIndices = Record[Idx++];
06038         Indices.reserve(SourceOrderOrNumArrayIndices);
06039         for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
06040           Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
06041       }
06042 
06043       CXXCtorInitializer *BOMInit;
06044       if (Type == CTOR_INITIALIZER_BASE) {
06045         BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
06046                                              LParenLoc, Init, RParenLoc,
06047                                              MemberOrEllipsisLoc);
06048       } else if (Type == CTOR_INITIALIZER_DELEGATING) {
06049         BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
06050                                                    Init, RParenLoc);
06051       } else if (IsWritten) {
06052         if (Member)
06053           BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
06054                                                LParenLoc, Init, RParenLoc);
06055         else 
06056           BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
06057                                                MemberOrEllipsisLoc, LParenLoc,
06058                                                Init, RParenLoc);
06059       } else {
06060         BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
06061                                              LParenLoc, Init, RParenLoc,
06062                                              Indices.data(), Indices.size());
06063       }
06064 
06065       if (IsWritten)
06066         BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
06067       CtorInitializers[i] = BOMInit;
06068     }
06069   }
06070 
06071   return std::make_pair(CtorInitializers, NumInitializers);
06072 }
06073 
06074 NestedNameSpecifier *
06075 ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
06076                                    const RecordData &Record, unsigned &Idx) {
06077   unsigned N = Record[Idx++];
06078   NestedNameSpecifier *NNS = 0, *Prev = 0;
06079   for (unsigned I = 0; I != N; ++I) {
06080     NestedNameSpecifier::SpecifierKind Kind
06081       = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
06082     switch (Kind) {
06083     case NestedNameSpecifier::Identifier: {
06084       IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
06085       NNS = NestedNameSpecifier::Create(Context, Prev, II);
06086       break;
06087     }
06088 
06089     case NestedNameSpecifier::Namespace: {
06090       NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
06091       NNS = NestedNameSpecifier::Create(Context, Prev, NS);
06092       break;
06093     }
06094 
06095     case NestedNameSpecifier::NamespaceAlias: {
06096       NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
06097       NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
06098       break;
06099     }
06100 
06101     case NestedNameSpecifier::TypeSpec:
06102     case NestedNameSpecifier::TypeSpecWithTemplate: {
06103       const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
06104       if (!T)
06105         return 0;
06106       
06107       bool Template = Record[Idx++];
06108       NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
06109       break;
06110     }
06111 
06112     case NestedNameSpecifier::Global: {
06113       NNS = NestedNameSpecifier::GlobalSpecifier(Context);
06114       // No associated value, and there can't be a prefix.
06115       break;
06116     }
06117     }
06118     Prev = NNS;
06119   }
06120   return NNS;
06121 }
06122 
06123 NestedNameSpecifierLoc
06124 ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record, 
06125                                       unsigned &Idx) {
06126   unsigned N = Record[Idx++];
06127   NestedNameSpecifierLocBuilder Builder;
06128   for (unsigned I = 0; I != N; ++I) {
06129     NestedNameSpecifier::SpecifierKind Kind
06130       = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
06131     switch (Kind) {
06132     case NestedNameSpecifier::Identifier: {
06133       IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);      
06134       SourceRange Range = ReadSourceRange(F, Record, Idx);
06135       Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
06136       break;
06137     }
06138 
06139     case NestedNameSpecifier::Namespace: {
06140       NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
06141       SourceRange Range = ReadSourceRange(F, Record, Idx);
06142       Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
06143       break;
06144     }
06145 
06146     case NestedNameSpecifier::NamespaceAlias: {
06147       NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
06148       SourceRange Range = ReadSourceRange(F, Record, Idx);
06149       Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
06150       break;
06151     }
06152 
06153     case NestedNameSpecifier::TypeSpec:
06154     case NestedNameSpecifier::TypeSpecWithTemplate: {
06155       bool Template = Record[Idx++];
06156       TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
06157       if (!T)
06158         return NestedNameSpecifierLoc();
06159       SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
06160 
06161       // FIXME: 'template' keyword location not saved anywhere, so we fake it.
06162       Builder.Extend(Context, 
06163                      Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
06164                      T->getTypeLoc(), ColonColonLoc);
06165       break;
06166     }
06167 
06168     case NestedNameSpecifier::Global: {
06169       SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
06170       Builder.MakeGlobal(Context, ColonColonLoc);
06171       break;
06172     }
06173     }
06174   }
06175   
06176   return Builder.getWithLocInContext(Context);
06177 }
06178 
06179 SourceRange
06180 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
06181                            unsigned &Idx) {
06182   SourceLocation beg = ReadSourceLocation(F, Record, Idx);
06183   SourceLocation end = ReadSourceLocation(F, Record, Idx);
06184   return SourceRange(beg, end);
06185 }
06186 
06187 /// \brief Read an integral value
06188 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
06189   unsigned BitWidth = Record[Idx++];
06190   unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
06191   llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
06192   Idx += NumWords;
06193   return Result;
06194 }
06195 
06196 /// \brief Read a signed integral value
06197 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
06198   bool isUnsigned = Record[Idx++];
06199   return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
06200 }
06201 
06202 /// \brief Read a floating-point value
06203 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
06204   return llvm::APFloat(ReadAPInt(Record, Idx));
06205 }
06206 
06207 // \brief Read a string
06208 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
06209   unsigned Len = Record[Idx++];
06210   std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
06211   Idx += Len;
06212   return Result;
06213 }
06214 
06215 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record, 
06216                                          unsigned &Idx) {
06217   unsigned Major = Record[Idx++];
06218   unsigned Minor = Record[Idx++];
06219   unsigned Subminor = Record[Idx++];
06220   if (Minor == 0)
06221     return VersionTuple(Major);
06222   if (Subminor == 0)
06223     return VersionTuple(Major, Minor - 1);
06224   return VersionTuple(Major, Minor - 1, Subminor - 1);
06225 }
06226 
06227 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F, 
06228                                           const RecordData &Record,
06229                                           unsigned &Idx) {
06230   CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
06231   return CXXTemporary::Create(Context, Decl);
06232 }
06233 
06234 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
06235   return Diag(SourceLocation(), DiagID);
06236 }
06237 
06238 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
06239   return Diags.Report(Loc, DiagID);
06240 }
06241 
06242 /// \brief Retrieve the identifier table associated with the
06243 /// preprocessor.
06244 IdentifierTable &ASTReader::getIdentifierTable() {
06245   return PP.getIdentifierTable();
06246 }
06247 
06248 /// \brief Record that the given ID maps to the given switch-case
06249 /// statement.
06250 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
06251   assert((*CurrSwitchCaseStmts)[ID] == 0 &&
06252          "Already have a SwitchCase with this ID");
06253   (*CurrSwitchCaseStmts)[ID] = SC;
06254 }
06255 
06256 /// \brief Retrieve the switch-case statement with the given ID.
06257 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
06258   assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
06259   return (*CurrSwitchCaseStmts)[ID];
06260 }
06261 
06262 void ASTReader::ClearSwitchCaseIDs() {
06263   CurrSwitchCaseStmts->clear();
06264 }
06265 
06266 void ASTReader::finishPendingActions() {
06267   while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty()) {
06268     // If any identifiers with corresponding top-level declarations have
06269     // been loaded, load those declarations now.
06270     while (!PendingIdentifierInfos.empty()) {
06271       SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
06272                               PendingIdentifierInfos.front().DeclIDs, true);
06273       PendingIdentifierInfos.pop_front();
06274     }
06275   
06276     // Load pending declaration chains.
06277     for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
06278       loadPendingDeclChain(PendingDeclChains[I]);
06279       PendingDeclChainsKnown.erase(PendingDeclChains[I]);
06280     }
06281     PendingDeclChains.clear();
06282   }
06283   
06284   // If we deserialized any C++ or Objective-C class definitions, any
06285   // Objective-C protocol definitions, or any redeclarable templates, make sure
06286   // that all redeclarations point to the definitions. Note that this can only 
06287   // happen now, after the redeclaration chains have been fully wired.
06288   for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
06289                                            DEnd = PendingDefinitions.end();
06290        D != DEnd; ++D) {
06291     if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
06292       if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
06293         // Make sure that the TagType points at the definition.
06294         const_cast<TagType*>(TagT)->decl = TD;
06295       }
06296       
06297       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
06298         for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
06299                                          REnd = RD->redecls_end();
06300              R != REnd; ++R)
06301           cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
06302         
06303       }
06304 
06305       continue;
06306     }
06307     
06308     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
06309       // Make sure that the ObjCInterfaceType points at the definition.
06310       const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
06311         ->Decl = ID;
06312       
06313       for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
06314                                            REnd = ID->redecls_end();
06315            R != REnd; ++R)
06316         R->Data = ID->Data;
06317       
06318       continue;
06319     }
06320     
06321     if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
06322       for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
06323                                           REnd = PD->redecls_end();
06324            R != REnd; ++R)
06325         R->Data = PD->Data;
06326       
06327       continue;
06328     }
06329     
06330     RedeclarableTemplateDecl *RTD
06331       = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
06332     for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
06333                                                 REnd = RTD->redecls_end();
06334          R != REnd; ++R)
06335       R->Common = RTD->Common;    
06336   }
06337   PendingDefinitions.clear();
06338 }
06339 
06340 void ASTReader::FinishedDeserializing() {
06341   assert(NumCurrentElementsDeserializing &&
06342          "FinishedDeserializing not paired with StartedDeserializing");
06343   if (NumCurrentElementsDeserializing == 1) {
06344     // We decrease NumCurrentElementsDeserializing only after pending actions
06345     // are finished, to avoid recursively re-calling finishPendingActions().
06346     finishPendingActions();
06347   }
06348   --NumCurrentElementsDeserializing;
06349 
06350   if (NumCurrentElementsDeserializing == 0 &&
06351       Consumer && !PassingDeclsToConsumer) {
06352     // Guard variable to avoid recursively redoing the process of passing
06353     // decls to consumer.
06354     SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
06355                                                      true);
06356 
06357     while (!InterestingDecls.empty()) {
06358       // We are not in recursive loading, so it's safe to pass the "interesting"
06359       // decls to the consumer.
06360       Decl *D = InterestingDecls.front();
06361       InterestingDecls.pop_front();
06362       PassInterestingDeclToConsumer(D);
06363     }
06364   }
06365 }
06366 
06367 ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
06368                      StringRef isysroot, bool DisableValidation,
06369                      bool DisableStatCache, bool AllowASTWithCompilerErrors)
06370   : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
06371     SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
06372     Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
06373     Consumer(0), ModuleMgr(FileMgr.getFileSystemOptions()),
06374     RelocatablePCH(false), isysroot(isysroot),
06375     DisableValidation(DisableValidation),
06376     DisableStatCache(DisableStatCache),
06377     AllowASTWithCompilerErrors(AllowASTWithCompilerErrors), 
06378     CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
06379     NumStatHits(0), NumStatMisses(0), 
06380     NumSLocEntriesRead(0), TotalNumSLocEntries(0), 
06381     NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0), 
06382     TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0), 
06383     NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0), 
06384     NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0), 
06385     NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
06386     TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
06387     PassingDeclsToConsumer(false),
06388     NumCXXBaseSpecifiersLoaded(0)
06389 {
06390   SourceMgr.setExternalSLocEntrySource(this);
06391 }
06392 
06393 ASTReader::~ASTReader() {
06394   for (DeclContextVisibleUpdatesPending::iterator
06395            I = PendingVisibleUpdates.begin(),
06396            E = PendingVisibleUpdates.end();
06397        I != E; ++I) {
06398     for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
06399                                              F = I->second.end();
06400          J != F; ++J)
06401       delete J->first;
06402   }
06403 }