1 //===--- ASTReader.cpp - AST File Reader ------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the ASTReader class, which reads AST files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Serialization/ASTReader.h"
15 #include "clang/Serialization/ASTDeserializationListener.h"
16 #include "clang/Serialization/ModuleManager.h"
17 #include "ASTCommon.h"
18 #include "ASTReaderInternals.h"
19 #include "clang/Frontend/FrontendDiagnostic.h"
20 #include "clang/Frontend/Utils.h"
21 #include "clang/Sema/Sema.h"
22 #include "clang/Sema/Scope.h"
23 #include "clang/AST/ASTConsumer.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/NestedNameSpecifier.h"
29 #include "clang/AST/Type.h"
30 #include "clang/AST/TypeLocVisitor.h"
31 #include "clang/Lex/MacroInfo.h"
32 #include "clang/Lex/PreprocessingRecord.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Lex/HeaderSearch.h"
35 #include "clang/Basic/OnDiskHashTable.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/SourceManagerInternals.h"
38 #include "clang/Basic/FileManager.h"
39 #include "clang/Basic/FileSystemStatCache.h"
40 #include "clang/Basic/TargetInfo.h"
41 #include "clang/Basic/Version.h"
42 #include "clang/Basic/VersionTuple.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include "llvm/Bitcode/BitstreamReader.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/Path.h"
49 #include "llvm/Support/system_error.h"
50 #include <algorithm>
51 #include <iterator>
52 #include <cstdio>
53 #include <sys/stat.h>
54 
55 using namespace clang;
56 using namespace clang::serialization;
57 using namespace clang::serialization::reader;
58 
59 //===----------------------------------------------------------------------===//
60 // PCH validator implementation
61 //===----------------------------------------------------------------------===//
62 
63 ASTReaderListener::~ASTReaderListener() {}
64 
65 bool
66 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
67   const LangOptions &PPLangOpts = PP.getLangOptions();
68 
69 #define LANGOPT(Name, Bits, Default, Description)         \
70   if (PPLangOpts.Name != LangOpts.Name) {                 \
71     Reader.Diag(diag::err_pch_langopt_mismatch)           \
72       << Description << LangOpts.Name << PPLangOpts.Name; \
73     return true;                                          \
74   }
75 
76 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
77   if (PPLangOpts.Name != LangOpts.Name) {               \
78     Reader.Diag(diag::err_pch_langopt_value_mismatch)   \
79       << Description;                                   \
80   return true;                                          \
81 }
82 
83 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
84   if (PPLangOpts.get##Name() != LangOpts.get##Name()) {      \
85     Reader.Diag(diag::err_pch_langopt_value_mismatch)        \
86       << Description;                                        \
87     return true;                                             \
88   }
89 
90 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
91 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
92 #include "clang/Basic/LangOptions.def"
93 
94   return false;
95 }
96 
97 bool PCHValidator::ReadTargetTriple(StringRef Triple) {
98   if (Triple == PP.getTargetInfo().getTriple().str())
99     return false;
100 
101   Reader.Diag(diag::warn_pch_target_triple)
102     << Triple << PP.getTargetInfo().getTriple().str();
103   return true;
104 }
105 
106 namespace {
107   struct EmptyStringRef {
108     bool operator ()(StringRef r) const { return r.empty(); }
109   };
110   struct EmptyBlock {
111     bool operator ()(const PCHPredefinesBlock &r) const {return r.Data.empty();}
112   };
113 }
114 
115 static bool EqualConcatenations(SmallVector<StringRef, 2> L,
116                                 PCHPredefinesBlocks R) {
117   // First, sum up the lengths.
118   unsigned LL = 0, RL = 0;
119   for (unsigned I = 0, N = L.size(); I != N; ++I) {
120     LL += L[I].size();
121   }
122   for (unsigned I = 0, N = R.size(); I != N; ++I) {
123     RL += R[I].Data.size();
124   }
125   if (LL != RL)
126     return false;
127   if (LL == 0 && RL == 0)
128     return true;
129 
130   // Kick out empty parts, they confuse the algorithm below.
131   L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
132   R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
133 
134   // Do it the hard way. At this point, both vectors must be non-empty.
135   StringRef LR = L[0], RR = R[0].Data;
136   unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
137   (void) RN;
138   for (;;) {
139     // Compare the current pieces.
140     if (LR.size() == RR.size()) {
141       // If they're the same length, it's pretty easy.
142       if (LR != RR)
143         return false;
144       // Both pieces are done, advance.
145       ++LI;
146       ++RI;
147       // If either string is done, they're both done, since they're the same
148       // length.
149       if (LI == LN) {
150         assert(RI == RN && "Strings not the same length after all?");
151         return true;
152       }
153       LR = L[LI];
154       RR = R[RI].Data;
155     } else if (LR.size() < RR.size()) {
156       // Right piece is longer.
157       if (!RR.startswith(LR))
158         return false;
159       ++LI;
160       assert(LI != LN && "Strings not the same length after all?");
161       RR = RR.substr(LR.size());
162       LR = L[LI];
163     } else {
164       // Left piece is longer.
165       if (!LR.startswith(RR))
166         return false;
167       ++RI;
168       assert(RI != RN && "Strings not the same length after all?");
169       LR = LR.substr(RR.size());
170       RR = R[RI].Data;
171     }
172   }
173 }
174 
175 static std::pair<FileID, StringRef::size_type>
176 FindMacro(const PCHPredefinesBlocks &Buffers, StringRef MacroDef) {
177   std::pair<FileID, StringRef::size_type> Res;
178   for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
179     Res.second = Buffers[I].Data.find(MacroDef);
180     if (Res.second != StringRef::npos) {
181       Res.first = Buffers[I].BufferID;
182       break;
183     }
184   }
185   return Res;
186 }
187 
188 bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
189                                         StringRef OriginalFileName,
190                                         std::string &SuggestedPredefines,
191                                         FileManager &FileMgr) {
192   // We are in the context of an implicit include, so the predefines buffer will
193   // have a #include entry for the PCH file itself (as normalized by the
194   // preprocessor initialization). Find it and skip over it in the checking
195   // below.
196   llvm::SmallString<256> PCHInclude;
197   PCHInclude += "#include \"";
198   PCHInclude += NormalizeDashIncludePath(OriginalFileName, FileMgr);
199   PCHInclude += "\"\n";
200   std::pair<StringRef,StringRef> Split =
201     StringRef(PP.getPredefines()).split(PCHInclude.str());
202   StringRef Left =  Split.first, Right = Split.second;
203   if (Left == PP.getPredefines()) {
204     Error("Missing PCH include entry!");
205     return true;
206   }
207 
208   // If the concatenation of all the PCH buffers is equal to the adjusted
209   // command line, we're done.
210   SmallVector<StringRef, 2> CommandLine;
211   CommandLine.push_back(Left);
212   CommandLine.push_back(Right);
213   if (EqualConcatenations(CommandLine, Buffers))
214     return false;
215 
216   SourceManager &SourceMgr = PP.getSourceManager();
217 
218   // The predefines buffers are different. Determine what the differences are,
219   // and whether they require us to reject the PCH file.
220   SmallVector<StringRef, 8> PCHLines;
221   for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
222     Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
223 
224   SmallVector<StringRef, 8> CmdLineLines;
225   Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
226 
227   // Pick out implicit #includes after the PCH and don't consider them for
228   // validation; we will insert them into SuggestedPredefines so that the
229   // preprocessor includes them.
230   std::string IncludesAfterPCH;
231   SmallVector<StringRef, 8> AfterPCHLines;
232   Right.split(AfterPCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
233   for (unsigned i = 0, e = AfterPCHLines.size(); i != e; ++i) {
234     if (AfterPCHLines[i].startswith("#include ")) {
235       IncludesAfterPCH += AfterPCHLines[i];
236       IncludesAfterPCH += '\n';
237     } else {
238       CmdLineLines.push_back(AfterPCHLines[i]);
239     }
240   }
241 
242   // Make sure we add the includes last into SuggestedPredefines before we
243   // exit this function.
244   struct AddIncludesRAII {
245     std::string &SuggestedPredefines;
246     std::string &IncludesAfterPCH;
247 
248     AddIncludesRAII(std::string &SuggestedPredefines,
249                     std::string &IncludesAfterPCH)
250       : SuggestedPredefines(SuggestedPredefines),
251         IncludesAfterPCH(IncludesAfterPCH) { }
252     ~AddIncludesRAII() {
253       SuggestedPredefines += IncludesAfterPCH;
254     }
255   } AddIncludes(SuggestedPredefines, IncludesAfterPCH);
256 
257   // Sort both sets of predefined buffer lines, since we allow some extra
258   // definitions and they may appear at any point in the output.
259   std::sort(CmdLineLines.begin(), CmdLineLines.end());
260   std::sort(PCHLines.begin(), PCHLines.end());
261 
262   // Determine which predefines that were used to build the PCH file are missing
263   // from the command line.
264   std::vector<StringRef> MissingPredefines;
265   std::set_difference(PCHLines.begin(), PCHLines.end(),
266                       CmdLineLines.begin(), CmdLineLines.end(),
267                       std::back_inserter(MissingPredefines));
268 
269   bool MissingDefines = false;
270   bool ConflictingDefines = false;
271   for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
272     StringRef Missing = MissingPredefines[I];
273     if (Missing.startswith("#include ")) {
274       // An -include was specified when generating the PCH; it is included in
275       // the PCH, just ignore it.
276       continue;
277     }
278     if (!Missing.startswith("#define ")) {
279       Reader.Diag(diag::warn_pch_compiler_options_mismatch);
280       return true;
281     }
282 
283     // This is a macro definition. Determine the name of the macro we're
284     // defining.
285     std::string::size_type StartOfMacroName = strlen("#define ");
286     std::string::size_type EndOfMacroName
287       = Missing.find_first_of("( \n\r", StartOfMacroName);
288     assert(EndOfMacroName != std::string::npos &&
289            "Couldn't find the end of the macro name");
290     StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
291 
292     // Determine whether this macro was given a different definition on the
293     // command line.
294     std::string MacroDefStart = "#define " + MacroName.str();
295     std::string::size_type MacroDefLen = MacroDefStart.size();
296     SmallVector<StringRef, 8>::iterator ConflictPos
297       = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
298                          MacroDefStart);
299     for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
300       if (!ConflictPos->startswith(MacroDefStart)) {
301         // Different macro; we're done.
302         ConflictPos = CmdLineLines.end();
303         break;
304       }
305 
306       assert(ConflictPos->size() > MacroDefLen &&
307              "Invalid #define in predefines buffer?");
308       if ((*ConflictPos)[MacroDefLen] != ' ' &&
309           (*ConflictPos)[MacroDefLen] != '(')
310         continue; // Longer macro name; keep trying.
311 
312       // We found a conflicting macro definition.
313       break;
314     }
315 
316     if (ConflictPos != CmdLineLines.end()) {
317       Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
318           << MacroName;
319 
320       // Show the definition of this macro within the PCH file.
321       std::pair<FileID, StringRef::size_type> MacroLoc =
322           FindMacro(Buffers, Missing);
323       assert(MacroLoc.second!=StringRef::npos && "Unable to find macro!");
324       SourceLocation PCHMissingLoc =
325           SourceMgr.getLocForStartOfFile(MacroLoc.first)
326             .getLocWithOffset(MacroLoc.second);
327       Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
328 
329       ConflictingDefines = true;
330       continue;
331     }
332 
333     // If the macro doesn't conflict, then we'll just pick up the macro
334     // definition from the PCH file. Warn the user that they made a mistake.
335     if (ConflictingDefines)
336       continue; // Don't complain if there are already conflicting defs
337 
338     if (!MissingDefines) {
339       Reader.Diag(diag::warn_cmdline_missing_macro_defs);
340       MissingDefines = true;
341     }
342 
343     // Show the definition of this macro within the PCH file.
344     std::pair<FileID, StringRef::size_type> MacroLoc =
345         FindMacro(Buffers, Missing);
346     assert(MacroLoc.second!=StringRef::npos && "Unable to find macro!");
347     SourceLocation PCHMissingLoc =
348         SourceMgr.getLocForStartOfFile(MacroLoc.first)
349           .getLocWithOffset(MacroLoc.second);
350     Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
351   }
352 
353   if (ConflictingDefines)
354     return true;
355 
356   // Determine what predefines were introduced based on command-line
357   // parameters that were not present when building the PCH
358   // file. Extra #defines are okay, so long as the identifiers being
359   // defined were not used within the precompiled header.
360   std::vector<StringRef> ExtraPredefines;
361   std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
362                       PCHLines.begin(), PCHLines.end(),
363                       std::back_inserter(ExtraPredefines));
364   for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
365     StringRef &Extra = ExtraPredefines[I];
366     if (!Extra.startswith("#define ")) {
367       Reader.Diag(diag::warn_pch_compiler_options_mismatch);
368       return true;
369     }
370 
371     // This is an extra macro definition. Determine the name of the
372     // macro we're defining.
373     std::string::size_type StartOfMacroName = strlen("#define ");
374     std::string::size_type EndOfMacroName
375       = Extra.find_first_of("( \n\r", StartOfMacroName);
376     assert(EndOfMacroName != std::string::npos &&
377            "Couldn't find the end of the macro name");
378     StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
379 
380     // Check whether this name was used somewhere in the PCH file. If
381     // so, defining it as a macro could change behavior, so we reject
382     // the PCH file.
383     if (IdentifierInfo *II = Reader.get(MacroName)) {
384       Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
385       return true;
386     }
387 
388     // Add this definition to the suggested predefines buffer.
389     SuggestedPredefines += Extra;
390     SuggestedPredefines += '\n';
391   }
392 
393   // If we get here, it's because the predefines buffer had compatible
394   // contents. Accept the PCH file.
395   return false;
396 }
397 
398 void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
399                                       unsigned ID) {
400   PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
401   ++NumHeaderInfos;
402 }
403 
404 void PCHValidator::ReadCounter(unsigned Value) {
405   PP.setCounterValue(Value);
406 }
407 
408 //===----------------------------------------------------------------------===//
409 // AST reader implementation
410 //===----------------------------------------------------------------------===//
411 
412 void
413 ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
414   DeserializationListener = Listener;
415 }
416 
417 
418 
419 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
420   return serialization::ComputeHash(Sel);
421 }
422 
423 
424 std::pair<unsigned, unsigned>
425 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
426   using namespace clang::io;
427   unsigned KeyLen = ReadUnalignedLE16(d);
428   unsigned DataLen = ReadUnalignedLE16(d);
429   return std::make_pair(KeyLen, DataLen);
430 }
431 
432 ASTSelectorLookupTrait::internal_key_type
433 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
434   using namespace clang::io;
435   SelectorTable &SelTable = Reader.getContext().Selectors;
436   unsigned N = ReadUnalignedLE16(d);
437   IdentifierInfo *FirstII
438     = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
439   if (N == 0)
440     return SelTable.getNullarySelector(FirstII);
441   else if (N == 1)
442     return SelTable.getUnarySelector(FirstII);
443 
444   SmallVector<IdentifierInfo *, 16> Args;
445   Args.push_back(FirstII);
446   for (unsigned I = 1; I != N; ++I)
447     Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
448 
449   return SelTable.getSelector(N, Args.data());
450 }
451 
452 ASTSelectorLookupTrait::data_type
453 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
454                                  unsigned DataLen) {
455   using namespace clang::io;
456 
457   data_type Result;
458 
459   Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
460   unsigned NumInstanceMethods = ReadUnalignedLE16(d);
461   unsigned NumFactoryMethods = ReadUnalignedLE16(d);
462 
463   // Load instance methods
464   for (unsigned I = 0; I != NumInstanceMethods; ++I) {
465     if (ObjCMethodDecl *Method
466           = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
467       Result.Instance.push_back(Method);
468   }
469 
470   // Load factory methods
471   for (unsigned I = 0; I != NumFactoryMethods; ++I) {
472     if (ObjCMethodDecl *Method
473           = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
474       Result.Factory.push_back(Method);
475   }
476 
477   return Result;
478 }
479 
480 unsigned ASTIdentifierLookupTrait::ComputeHash(const internal_key_type& a) {
481   return llvm::HashString(StringRef(a.first, a.second));
482 }
483 
484 std::pair<unsigned, unsigned>
485 ASTIdentifierLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
486   using namespace clang::io;
487   unsigned DataLen = ReadUnalignedLE16(d);
488   unsigned KeyLen = ReadUnalignedLE16(d);
489   return std::make_pair(KeyLen, DataLen);
490 }
491 
492 std::pair<const char*, unsigned>
493 ASTIdentifierLookupTrait::ReadKey(const unsigned char* d, unsigned n) {
494   assert(n >= 2 && d[n-1] == '\0');
495   return std::make_pair((const char*) d, n-1);
496 }
497 
498 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
499                                                    const unsigned char* d,
500                                                    unsigned DataLen) {
501   using namespace clang::io;
502   unsigned RawID = ReadUnalignedLE32(d);
503   bool IsInteresting = RawID & 0x01;
504 
505   // Wipe out the "is interesting" bit.
506   RawID = RawID >> 1;
507 
508   IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
509   if (!IsInteresting) {
510     // For uninteresting identifiers, just build the IdentifierInfo
511     // and associate it with the persistent ID.
512     IdentifierInfo *II = KnownII;
513     if (!II)
514       II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
515     Reader.SetIdentifierInfo(ID, II);
516     II->setIsFromAST();
517     II->setOutOfDate(false);
518     return II;
519   }
520 
521   unsigned Bits = ReadUnalignedLE16(d);
522   bool CPlusPlusOperatorKeyword = Bits & 0x01;
523   Bits >>= 1;
524   bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
525   Bits >>= 1;
526   bool Poisoned = Bits & 0x01;
527   Bits >>= 1;
528   bool ExtensionToken = Bits & 0x01;
529   Bits >>= 1;
530   bool hasMacroDefinition = Bits & 0x01;
531   Bits >>= 1;
532   unsigned ObjCOrBuiltinID = Bits & 0x3FF;
533   Bits >>= 10;
534 
535   assert(Bits == 0 && "Extra bits in the identifier?");
536   DataLen -= 6;
537 
538   // Build the IdentifierInfo itself and link the identifier ID with
539   // the new IdentifierInfo.
540   IdentifierInfo *II = KnownII;
541   if (!II)
542     II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
543   II->setOutOfDate(false);
544   II->setIsFromAST();
545 
546   // Set or check the various bits in the IdentifierInfo structure.
547   // Token IDs are read-only.
548   if (HasRevertedTokenIDToIdentifier)
549     II->RevertTokenIDToIdentifier();
550   II->setObjCOrBuiltinID(ObjCOrBuiltinID);
551   assert(II->isExtensionToken() == ExtensionToken &&
552          "Incorrect extension token flag");
553   (void)ExtensionToken;
554   if (Poisoned)
555     II->setIsPoisoned(true);
556   assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
557          "Incorrect C++ operator keyword flag");
558   (void)CPlusPlusOperatorKeyword;
559 
560   // If this identifier is a macro, deserialize the macro
561   // definition.
562   if (hasMacroDefinition) {
563     // FIXME: Check for conflicts?
564     uint32_t Offset = ReadUnalignedLE32(d);
565     Reader.SetIdentifierIsMacro(II, F, Offset);
566     DataLen -= 4;
567   }
568 
569   Reader.SetIdentifierInfo(ID, II);
570 
571   // Read all of the declarations visible at global scope with this
572   // name.
573   if (DataLen > 0) {
574     SmallVector<uint32_t, 4> DeclIDs;
575     for (; DataLen > 0; DataLen -= 4)
576       DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
577     Reader.SetGloballyVisibleDecls(II, DeclIDs);
578   }
579 
580   return II;
581 }
582 
583 unsigned
584 ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
585   llvm::FoldingSetNodeID ID;
586   ID.AddInteger(Key.Kind);
587 
588   switch (Key.Kind) {
589   case DeclarationName::Identifier:
590   case DeclarationName::CXXLiteralOperatorName:
591     ID.AddString(((IdentifierInfo*)Key.Data)->getName());
592     break;
593   case DeclarationName::ObjCZeroArgSelector:
594   case DeclarationName::ObjCOneArgSelector:
595   case DeclarationName::ObjCMultiArgSelector:
596     ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
597     break;
598   case DeclarationName::CXXOperatorName:
599     ID.AddInteger((OverloadedOperatorKind)Key.Data);
600     break;
601   case DeclarationName::CXXConstructorName:
602   case DeclarationName::CXXDestructorName:
603   case DeclarationName::CXXConversionFunctionName:
604   case DeclarationName::CXXUsingDirective:
605     break;
606   }
607 
608   return ID.ComputeHash();
609 }
610 
611 ASTDeclContextNameLookupTrait::internal_key_type
612 ASTDeclContextNameLookupTrait::GetInternalKey(
613                                           const external_key_type& Name) const {
614   DeclNameKey Key;
615   Key.Kind = Name.getNameKind();
616   switch (Name.getNameKind()) {
617   case DeclarationName::Identifier:
618     Key.Data = (uint64_t)Name.getAsIdentifierInfo();
619     break;
620   case DeclarationName::ObjCZeroArgSelector:
621   case DeclarationName::ObjCOneArgSelector:
622   case DeclarationName::ObjCMultiArgSelector:
623     Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
624     break;
625   case DeclarationName::CXXOperatorName:
626     Key.Data = Name.getCXXOverloadedOperator();
627     break;
628   case DeclarationName::CXXLiteralOperatorName:
629     Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
630     break;
631   case DeclarationName::CXXConstructorName:
632   case DeclarationName::CXXDestructorName:
633   case DeclarationName::CXXConversionFunctionName:
634   case DeclarationName::CXXUsingDirective:
635     Key.Data = 0;
636     break;
637   }
638 
639   return Key;
640 }
641 
642 ASTDeclContextNameLookupTrait::external_key_type
643 ASTDeclContextNameLookupTrait::GetExternalKey(
644                                           const internal_key_type& Key) const {
645   ASTContext &Context = Reader.getContext();
646   switch (Key.Kind) {
647   case DeclarationName::Identifier:
648     return DeclarationName((IdentifierInfo*)Key.Data);
649 
650   case DeclarationName::ObjCZeroArgSelector:
651   case DeclarationName::ObjCOneArgSelector:
652   case DeclarationName::ObjCMultiArgSelector:
653     return DeclarationName(Selector(Key.Data));
654 
655   case DeclarationName::CXXConstructorName:
656     return Context.DeclarationNames.getCXXConstructorName(
657              Context.getCanonicalType(Reader.getLocalType(F, Key.Data)));
658 
659   case DeclarationName::CXXDestructorName:
660     return Context.DeclarationNames.getCXXDestructorName(
661              Context.getCanonicalType(Reader.getLocalType(F, Key.Data)));
662 
663   case DeclarationName::CXXConversionFunctionName:
664     return Context.DeclarationNames.getCXXConversionFunctionName(
665              Context.getCanonicalType(Reader.getLocalType(F, Key.Data)));
666 
667   case DeclarationName::CXXOperatorName:
668     return Context.DeclarationNames.getCXXOperatorName(
669                                        (OverloadedOperatorKind)Key.Data);
670 
671   case DeclarationName::CXXLiteralOperatorName:
672     return Context.DeclarationNames.getCXXLiteralOperatorName(
673                                                    (IdentifierInfo*)Key.Data);
674 
675   case DeclarationName::CXXUsingDirective:
676     return DeclarationName::getUsingDirectiveName();
677   }
678 
679   llvm_unreachable("Invalid Name Kind ?");
680 }
681 
682 std::pair<unsigned, unsigned>
683 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
684   using namespace clang::io;
685   unsigned KeyLen = ReadUnalignedLE16(d);
686   unsigned DataLen = ReadUnalignedLE16(d);
687   return std::make_pair(KeyLen, DataLen);
688 }
689 
690 ASTDeclContextNameLookupTrait::internal_key_type
691 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
692   using namespace clang::io;
693 
694   DeclNameKey Key;
695   Key.Kind = (DeclarationName::NameKind)*d++;
696   switch (Key.Kind) {
697   case DeclarationName::Identifier:
698     Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
699     break;
700   case DeclarationName::ObjCZeroArgSelector:
701   case DeclarationName::ObjCOneArgSelector:
702   case DeclarationName::ObjCMultiArgSelector:
703     Key.Data =
704        (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
705                    .getAsOpaquePtr();
706     break;
707   case DeclarationName::CXXOperatorName:
708     Key.Data = *d++; // OverloadedOperatorKind
709     break;
710   case DeclarationName::CXXLiteralOperatorName:
711     Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
712     break;
713   case DeclarationName::CXXConstructorName:
714   case DeclarationName::CXXDestructorName:
715   case DeclarationName::CXXConversionFunctionName:
716   case DeclarationName::CXXUsingDirective:
717     Key.Data = 0;
718     break;
719   }
720 
721   return Key;
722 }
723 
724 ASTDeclContextNameLookupTrait::data_type
725 ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
726                                         const unsigned char* d,
727                                       unsigned DataLen) {
728   using namespace clang::io;
729   unsigned NumDecls = ReadUnalignedLE16(d);
730   DeclID *Start = (DeclID *)d;
731   return std::make_pair(Start, Start + NumDecls);
732 }
733 
734 bool ASTReader::ReadDeclContextStorage(Module &M,
735                                        llvm::BitstreamCursor &Cursor,
736                                    const std::pair<uint64_t, uint64_t> &Offsets,
737                                        DeclContextInfo &Info) {
738   SavedStreamPosition SavedPosition(Cursor);
739   // First the lexical decls.
740   if (Offsets.first != 0) {
741     Cursor.JumpToBit(Offsets.first);
742 
743     RecordData Record;
744     const char *Blob;
745     unsigned BlobLen;
746     unsigned Code = Cursor.ReadCode();
747     unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
748     if (RecCode != DECL_CONTEXT_LEXICAL) {
749       Error("Expected lexical block");
750       return true;
751     }
752 
753     Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob);
754     Info.NumLexicalDecls = BlobLen / sizeof(KindDeclIDPair);
755   }
756 
757   // Now the lookup table.
758   if (Offsets.second != 0) {
759     Cursor.JumpToBit(Offsets.second);
760 
761     RecordData Record;
762     const char *Blob;
763     unsigned BlobLen;
764     unsigned Code = Cursor.ReadCode();
765     unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
766     if (RecCode != DECL_CONTEXT_VISIBLE) {
767       Error("Expected visible lookup table block");
768       return true;
769     }
770     Info.NameLookupTableData
771       = ASTDeclContextNameLookupTable::Create(
772                     (const unsigned char *)Blob + Record[0],
773                     (const unsigned char *)Blob,
774                     ASTDeclContextNameLookupTrait(*this, M));
775   }
776 
777   return false;
778 }
779 
780 void ASTReader::Error(StringRef Msg) {
781   Error(diag::err_fe_pch_malformed, Msg);
782 }
783 
784 void ASTReader::Error(unsigned DiagID,
785                       StringRef Arg1, StringRef Arg2) {
786   if (Diags.isDiagnosticInFlight())
787     Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
788   else
789     Diag(DiagID) << Arg1 << Arg2;
790 }
791 
792 /// \brief Tell the AST listener about the predefines buffers in the chain.
793 bool ASTReader::CheckPredefinesBuffers() {
794   if (Listener)
795     return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
796                                           ActualOriginalFileName,
797                                           SuggestedPredefines,
798                                           FileMgr);
799   return false;
800 }
801 
802 //===----------------------------------------------------------------------===//
803 // Source Manager Deserialization
804 //===----------------------------------------------------------------------===//
805 
806 /// \brief Read the line table in the source manager block.
807 /// \returns true if there was an error.
808 bool ASTReader::ParseLineTable(Module &F,
809                                SmallVectorImpl<uint64_t> &Record) {
810   unsigned Idx = 0;
811   LineTableInfo &LineTable = SourceMgr.getLineTable();
812 
813   // Parse the file names
814   std::map<int, int> FileIDs;
815   for (int I = 0, N = Record[Idx++]; I != N; ++I) {
816     // Extract the file name
817     unsigned FilenameLen = Record[Idx++];
818     std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
819     Idx += FilenameLen;
820     MaybeAddSystemRootToFilename(Filename);
821     FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
822   }
823 
824   // Parse the line entries
825   std::vector<LineEntry> Entries;
826   while (Idx < Record.size()) {
827     int FID = Record[Idx++];
828     assert(FID >= 0 && "Serialized line entries for non-local file.");
829     // Remap FileID from 1-based old view.
830     FID += F.SLocEntryBaseID - 1;
831 
832     // Extract the line entries
833     unsigned NumEntries = Record[Idx++];
834     assert(NumEntries && "Numentries is 00000");
835     Entries.clear();
836     Entries.reserve(NumEntries);
837     for (unsigned I = 0; I != NumEntries; ++I) {
838       unsigned FileOffset = Record[Idx++];
839       unsigned LineNo = Record[Idx++];
840       int FilenameID = FileIDs[Record[Idx++]];
841       SrcMgr::CharacteristicKind FileKind
842         = (SrcMgr::CharacteristicKind)Record[Idx++];
843       unsigned IncludeOffset = Record[Idx++];
844       Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
845                                        FileKind, IncludeOffset));
846     }
847     LineTable.AddEntry(FID, Entries);
848   }
849 
850   return false;
851 }
852 
853 namespace {
854 
855 class ASTStatData {
856 public:
857   const ino_t ino;
858   const dev_t dev;
859   const mode_t mode;
860   const time_t mtime;
861   const off_t size;
862 
863   ASTStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
864     : ino(i), dev(d), mode(mo), mtime(m), size(s) {}
865 };
866 
867 class ASTStatLookupTrait {
868  public:
869   typedef const char *external_key_type;
870   typedef const char *internal_key_type;
871 
872   typedef ASTStatData data_type;
873 
874   static unsigned ComputeHash(const char *path) {
875     return llvm::HashString(path);
876   }
877 
878   static internal_key_type GetInternalKey(const char *path) { return path; }
879 
880   static bool EqualKey(internal_key_type a, internal_key_type b) {
881     return strcmp(a, b) == 0;
882   }
883 
884   static std::pair<unsigned, unsigned>
885   ReadKeyDataLength(const unsigned char*& d) {
886     unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
887     unsigned DataLen = (unsigned) *d++;
888     return std::make_pair(KeyLen + 1, DataLen);
889   }
890 
891   static internal_key_type ReadKey(const unsigned char *d, unsigned) {
892     return (const char *)d;
893   }
894 
895   static data_type ReadData(const internal_key_type, const unsigned char *d,
896                             unsigned /*DataLen*/) {
897     using namespace clang::io;
898 
899     ino_t ino = (ino_t) ReadUnalignedLE32(d);
900     dev_t dev = (dev_t) ReadUnalignedLE32(d);
901     mode_t mode = (mode_t) ReadUnalignedLE16(d);
902     time_t mtime = (time_t) ReadUnalignedLE64(d);
903     off_t size = (off_t) ReadUnalignedLE64(d);
904     return data_type(ino, dev, mode, mtime, size);
905   }
906 };
907 
908 /// \brief stat() cache for precompiled headers.
909 ///
910 /// This cache is very similar to the stat cache used by pretokenized
911 /// headers.
912 class ASTStatCache : public FileSystemStatCache {
913   typedef OnDiskChainedHashTable<ASTStatLookupTrait> CacheTy;
914   CacheTy *Cache;
915 
916   unsigned &NumStatHits, &NumStatMisses;
917 public:
918   ASTStatCache(const unsigned char *Buckets, const unsigned char *Base,
919                unsigned &NumStatHits, unsigned &NumStatMisses)
920     : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
921     Cache = CacheTy::Create(Buckets, Base);
922   }
923 
924   ~ASTStatCache() { delete Cache; }
925 
926   LookupResult getStat(const char *Path, struct stat &StatBuf,
927                        int *FileDescriptor) {
928     // Do the lookup for the file's data in the AST file.
929     CacheTy::iterator I = Cache->find(Path);
930 
931     // If we don't get a hit in the AST file just forward to 'stat'.
932     if (I == Cache->end()) {
933       ++NumStatMisses;
934       return statChained(Path, StatBuf, FileDescriptor);
935     }
936 
937     ++NumStatHits;
938     ASTStatData Data = *I;
939 
940     StatBuf.st_ino = Data.ino;
941     StatBuf.st_dev = Data.dev;
942     StatBuf.st_mtime = Data.mtime;
943     StatBuf.st_mode = Data.mode;
944     StatBuf.st_size = Data.size;
945     return CacheExists;
946   }
947 };
948 } // end anonymous namespace
949 
950 
951 /// \brief Read a source manager block
952 ASTReader::ASTReadResult ASTReader::ReadSourceManagerBlock(Module &F) {
953   using namespace SrcMgr;
954 
955   llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
956 
957   // Set the source-location entry cursor to the current position in
958   // the stream. This cursor will be used to read the contents of the
959   // source manager block initially, and then lazily read
960   // source-location entries as needed.
961   SLocEntryCursor = F.Stream;
962 
963   // The stream itself is going to skip over the source manager block.
964   if (F.Stream.SkipBlock()) {
965     Error("malformed block record in AST file");
966     return Failure;
967   }
968 
969   // Enter the source manager block.
970   if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
971     Error("malformed source manager block record in AST file");
972     return Failure;
973   }
974 
975   RecordData Record;
976   while (true) {
977     unsigned Code = SLocEntryCursor.ReadCode();
978     if (Code == llvm::bitc::END_BLOCK) {
979       if (SLocEntryCursor.ReadBlockEnd()) {
980         Error("error at end of Source Manager block in AST file");
981         return Failure;
982       }
983       return Success;
984     }
985 
986     if (Code == llvm::bitc::ENTER_SUBBLOCK) {
987       // No known subblocks, always skip them.
988       SLocEntryCursor.ReadSubBlockID();
989       if (SLocEntryCursor.SkipBlock()) {
990         Error("malformed block record in AST file");
991         return Failure;
992       }
993       continue;
994     }
995 
996     if (Code == llvm::bitc::DEFINE_ABBREV) {
997       SLocEntryCursor.ReadAbbrevRecord();
998       continue;
999     }
1000 
1001     // Read a record.
1002     const char *BlobStart;
1003     unsigned BlobLen;
1004     Record.clear();
1005     switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1006     default:  // Default behavior: ignore.
1007       break;
1008 
1009     case SM_SLOC_FILE_ENTRY:
1010     case SM_SLOC_BUFFER_ENTRY:
1011     case SM_SLOC_EXPANSION_ENTRY:
1012       // Once we hit one of the source location entries, we're done.
1013       return Success;
1014     }
1015   }
1016 }
1017 
1018 /// \brief If a header file is not found at the path that we expect it to be
1019 /// and the PCH file was moved from its original location, try to resolve the
1020 /// file by assuming that header+PCH were moved together and the header is in
1021 /// the same place relative to the PCH.
1022 static std::string
1023 resolveFileRelativeToOriginalDir(const std::string &Filename,
1024                                  const std::string &OriginalDir,
1025                                  const std::string &CurrDir) {
1026   assert(OriginalDir != CurrDir &&
1027          "No point trying to resolve the file if the PCH dir didn't change");
1028   using namespace llvm::sys;
1029   llvm::SmallString<128> filePath(Filename);
1030   fs::make_absolute(filePath);
1031   assert(path::is_absolute(OriginalDir));
1032   llvm::SmallString<128> currPCHPath(CurrDir);
1033 
1034   path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1035                        fileDirE = path::end(path::parent_path(filePath));
1036   path::const_iterator origDirI = path::begin(OriginalDir),
1037                        origDirE = path::end(OriginalDir);
1038   // Skip the common path components from filePath and OriginalDir.
1039   while (fileDirI != fileDirE && origDirI != origDirE &&
1040          *fileDirI == *origDirI) {
1041     ++fileDirI;
1042     ++origDirI;
1043   }
1044   for (; origDirI != origDirE; ++origDirI)
1045     path::append(currPCHPath, "..");
1046   path::append(currPCHPath, fileDirI, fileDirE);
1047   path::append(currPCHPath, path::filename(Filename));
1048   return currPCHPath.str();
1049 }
1050 
1051 /// \brief Read in the source location entry with the given ID.
1052 ASTReader::ASTReadResult ASTReader::ReadSLocEntryRecord(int ID) {
1053   if (ID == 0)
1054     return Success;
1055 
1056   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1057     Error("source location entry ID out-of-range for AST file");
1058     return Failure;
1059   }
1060 
1061   Module *F = GlobalSLocEntryMap.find(-ID)->second;
1062   F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
1063   llvm::BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1064   unsigned BaseOffset = F->SLocEntryBaseOffset;
1065 
1066   ++NumSLocEntriesRead;
1067   unsigned Code = SLocEntryCursor.ReadCode();
1068   if (Code == llvm::bitc::END_BLOCK ||
1069       Code == llvm::bitc::ENTER_SUBBLOCK ||
1070       Code == llvm::bitc::DEFINE_ABBREV) {
1071     Error("incorrectly-formatted source location entry in AST file");
1072     return Failure;
1073   }
1074 
1075   RecordData Record;
1076   const char *BlobStart;
1077   unsigned BlobLen;
1078   switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1079   default:
1080     Error("incorrectly-formatted source location entry in AST file");
1081     return Failure;
1082 
1083   case SM_SLOC_FILE_ENTRY: {
1084     if (Record.size() < 7) {
1085       Error("source location entry is incorrect");
1086       return Failure;
1087     }
1088 
1089     bool OverriddenBuffer = Record[6];
1090 
1091     std::string OrigFilename(BlobStart, BlobStart + BlobLen);
1092     std::string Filename = OrigFilename;
1093     MaybeAddSystemRootToFilename(Filename);
1094     const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false,
1095                                             /*CacheFailure=*/!OverriddenBuffer);
1096     if (File == 0 && !OriginalDir.empty() && !CurrentDir.empty() &&
1097         OriginalDir != CurrentDir) {
1098       std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1099                                                               OriginalDir,
1100                                                               CurrentDir);
1101       if (!resolved.empty())
1102         File = FileMgr.getFile(resolved);
1103     }
1104     if (File == 0)
1105       File = FileMgr.getVirtualFile(Filename, (off_t)Record[4],
1106                                     (time_t)Record[5]);
1107     if (File == 0) {
1108       std::string ErrorStr = "could not find file '";
1109       ErrorStr += Filename;
1110       ErrorStr += "' referenced by AST file";
1111       Error(ErrorStr.c_str());
1112       return Failure;
1113     }
1114 
1115     if (!DisableValidation &&
1116         ((off_t)Record[4] != File->getSize()
1117 #if !defined(LLVM_ON_WIN32)
1118         // In our regression testing, the Windows file system seems to
1119         // have inconsistent modification times that sometimes
1120         // erroneously trigger this error-handling path.
1121          || (time_t)Record[5] != File->getModificationTime()
1122 #endif
1123         )) {
1124       Error(diag::err_fe_pch_file_modified, Filename);
1125       return Failure;
1126     }
1127 
1128     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1129     if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1130       // This is the module's main file.
1131       IncludeLoc = getImportLocation(F);
1132     }
1133     FileID FID = SourceMgr.createFileID(File, IncludeLoc,
1134                                         (SrcMgr::CharacteristicKind)Record[2],
1135                                         ID, BaseOffset + Record[0]);
1136     SrcMgr::FileInfo &FileInfo =
1137           const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1138     FileInfo.NumCreatedFIDs = Record[7];
1139     if (Record[3])
1140       FileInfo.setHasLineDirectives();
1141 
1142     const DeclID *FirstDecl = F->FileSortedDecls + Record[8];
1143     unsigned NumFileDecls = Record[9];
1144     if (NumFileDecls) {
1145       assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1146       FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1147                                                              NumFileDecls));
1148     }
1149 
1150     if (OverriddenBuffer &&
1151         !SourceMgr.getOrCreateContentCache(File)->BufferOverridden) {
1152       unsigned Code = SLocEntryCursor.ReadCode();
1153       Record.clear();
1154       unsigned RecCode
1155         = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
1156 
1157       if (RecCode != SM_SLOC_BUFFER_BLOB) {
1158         Error("AST record has invalid code");
1159         return Failure;
1160       }
1161 
1162       llvm::MemoryBuffer *Buffer
1163         = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
1164                                            Filename);
1165       SourceMgr.overrideFileContents(File, Buffer);
1166     }
1167     break;
1168   }
1169 
1170   case SM_SLOC_BUFFER_ENTRY: {
1171     const char *Name = BlobStart;
1172     unsigned Offset = Record[0];
1173     unsigned Code = SLocEntryCursor.ReadCode();
1174     Record.clear();
1175     unsigned RecCode
1176       = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
1177 
1178     if (RecCode != SM_SLOC_BUFFER_BLOB) {
1179       Error("AST record has invalid code");
1180       return Failure;
1181     }
1182 
1183     llvm::MemoryBuffer *Buffer
1184       = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
1185                                          Name);
1186     FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID,
1187                                                          BaseOffset + Offset);
1188 
1189     if (strcmp(Name, "<built-in>") == 0) {
1190       PCHPredefinesBlock Block = {
1191         BufferID,
1192         StringRef(BlobStart, BlobLen - 1)
1193       };
1194       PCHPredefinesBuffers.push_back(Block);
1195     }
1196 
1197     break;
1198   }
1199 
1200   case SM_SLOC_EXPANSION_ENTRY: {
1201     SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1202     SourceMgr.createExpansionLoc(SpellingLoc,
1203                                      ReadSourceLocation(*F, Record[2]),
1204                                      ReadSourceLocation(*F, Record[3]),
1205                                      Record[4],
1206                                      ID,
1207                                      BaseOffset + Record[0]);
1208     break;
1209   }
1210   }
1211 
1212   return Success;
1213 }
1214 
1215 /// \brief Find the location where the module F is imported.
1216 SourceLocation ASTReader::getImportLocation(Module *F) {
1217   if (F->ImportLoc.isValid())
1218     return F->ImportLoc;
1219 
1220   // Otherwise we have a PCH. It's considered to be "imported" at the first
1221   // location of its includer.
1222   if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1223     // Main file is the importer. We assume that it is the first entry in the
1224     // entry table. We can't ask the manager, because at the time of PCH loading
1225     // the main file entry doesn't exist yet.
1226     // The very first entry is the invalid instantiation loc, which takes up
1227     // offsets 0 and 1.
1228     return SourceLocation::getFromRawEncoding(2U);
1229   }
1230   //return F->Loaders[0]->FirstLoc;
1231   return F->ImportedBy[0]->FirstLoc;
1232 }
1233 
1234 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1235 /// specified cursor.  Read the abbreviations that are at the top of the block
1236 /// and then leave the cursor pointing into the block.
1237 bool ASTReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1238                                  unsigned BlockID) {
1239   if (Cursor.EnterSubBlock(BlockID)) {
1240     Error("malformed block record in AST file");
1241     return Failure;
1242   }
1243 
1244   while (true) {
1245     uint64_t Offset = Cursor.GetCurrentBitNo();
1246     unsigned Code = Cursor.ReadCode();
1247 
1248     // We expect all abbrevs to be at the start of the block.
1249     if (Code != llvm::bitc::DEFINE_ABBREV) {
1250       Cursor.JumpToBit(Offset);
1251       return false;
1252     }
1253     Cursor.ReadAbbrevRecord();
1254   }
1255 }
1256 
1257 void ASTReader::ReadMacroRecord(Module &F, uint64_t Offset) {
1258   llvm::BitstreamCursor &Stream = F.MacroCursor;
1259 
1260   // Keep track of where we are in the stream, then jump back there
1261   // after reading this macro.
1262   SavedStreamPosition SavedPosition(Stream);
1263 
1264   Stream.JumpToBit(Offset);
1265   RecordData Record;
1266   SmallVector<IdentifierInfo*, 16> MacroArgs;
1267   MacroInfo *Macro = 0;
1268 
1269   while (true) {
1270     unsigned Code = Stream.ReadCode();
1271     switch (Code) {
1272     case llvm::bitc::END_BLOCK:
1273       return;
1274 
1275     case llvm::bitc::ENTER_SUBBLOCK:
1276       // No known subblocks, always skip them.
1277       Stream.ReadSubBlockID();
1278       if (Stream.SkipBlock()) {
1279         Error("malformed block record in AST file");
1280         return;
1281       }
1282       continue;
1283 
1284     case llvm::bitc::DEFINE_ABBREV:
1285       Stream.ReadAbbrevRecord();
1286       continue;
1287     default: break;
1288     }
1289 
1290     // Read a record.
1291     const char *BlobStart = 0;
1292     unsigned BlobLen = 0;
1293     Record.clear();
1294     PreprocessorRecordTypes RecType =
1295       (PreprocessorRecordTypes)Stream.ReadRecord(Code, Record, BlobStart,
1296                                                  BlobLen);
1297     switch (RecType) {
1298     case PP_MACRO_OBJECT_LIKE:
1299     case PP_MACRO_FUNCTION_LIKE: {
1300       // If we already have a macro, that means that we've hit the end
1301       // of the definition of the macro we were looking for. We're
1302       // done.
1303       if (Macro)
1304         return;
1305 
1306       IdentifierInfo *II = getLocalIdentifier(F, Record[0]);
1307       if (II == 0) {
1308         Error("macro must have a name in AST file");
1309         return;
1310       }
1311 
1312       SourceLocation Loc = ReadSourceLocation(F, Record[1]);
1313       bool isUsed = Record[2];
1314 
1315       MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1316       MI->setIsUsed(isUsed);
1317       MI->setIsFromAST();
1318 
1319       bool IsPublic = Record[3];
1320       unsigned NextIndex = 4;
1321       MI->setVisibility(IsPublic, ReadSourceLocation(F, Record, NextIndex));
1322 
1323       if (RecType == PP_MACRO_FUNCTION_LIKE) {
1324         // Decode function-like macro info.
1325         bool isC99VarArgs = Record[NextIndex++];
1326         bool isGNUVarArgs = Record[NextIndex++];
1327         MacroArgs.clear();
1328         unsigned NumArgs = Record[NextIndex++];
1329         for (unsigned i = 0; i != NumArgs; ++i)
1330           MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1331 
1332         // Install function-like macro info.
1333         MI->setIsFunctionLike();
1334         if (isC99VarArgs) MI->setIsC99Varargs();
1335         if (isGNUVarArgs) MI->setIsGNUVarargs();
1336         MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1337                             PP.getPreprocessorAllocator());
1338       }
1339 
1340       // Finally, install the macro.
1341       PP.setMacroInfo(II, MI);
1342 
1343       // Remember that we saw this macro last so that we add the tokens that
1344       // form its body to it.
1345       Macro = MI;
1346 
1347       if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1348           Record[NextIndex]) {
1349         // We have a macro definition. Register the association
1350         PreprocessedEntityID
1351             GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1352         PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1353         PPRec.RegisterMacroDefinition(Macro,
1354                             PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true));
1355       }
1356 
1357       ++NumMacrosRead;
1358       break;
1359     }
1360 
1361     case PP_TOKEN: {
1362       // If we see a TOKEN before a PP_MACRO_*, then the file is
1363       // erroneous, just pretend we didn't see this.
1364       if (Macro == 0) break;
1365 
1366       Token Tok;
1367       Tok.startToken();
1368       Tok.setLocation(ReadSourceLocation(F, Record[0]));
1369       Tok.setLength(Record[1]);
1370       if (IdentifierInfo *II = getLocalIdentifier(F, Record[2]))
1371         Tok.setIdentifierInfo(II);
1372       Tok.setKind((tok::TokenKind)Record[3]);
1373       Tok.setFlag((Token::TokenFlags)Record[4]);
1374       Macro->AddTokenToBody(Tok);
1375       break;
1376     }
1377   }
1378   }
1379 
1380   return;
1381 }
1382 
1383 PreprocessedEntityID
1384 ASTReader::getGlobalPreprocessedEntityID(Module &M, unsigned LocalID) const {
1385   ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1386     I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1387   assert(I != M.PreprocessedEntityRemap.end()
1388          && "Invalid index into preprocessed entity index remap");
1389 
1390   return LocalID + I->second;
1391 }
1392 
1393 unsigned HeaderFileInfoTrait::ComputeHash(const char *path) {
1394   return llvm::HashString(llvm::sys::path::filename(path));
1395 }
1396 
1397 HeaderFileInfoTrait::internal_key_type
1398 HeaderFileInfoTrait::GetInternalKey(const char *path) { return path; }
1399 
1400 bool HeaderFileInfoTrait::EqualKey(internal_key_type a, internal_key_type b) {
1401   if (strcmp(a, b) == 0)
1402     return true;
1403 
1404   if (llvm::sys::path::filename(a) != llvm::sys::path::filename(b))
1405     return false;
1406 
1407   // The file names match, but the path names don't. stat() the files to
1408   // see if they are the same.
1409   struct stat StatBufA, StatBufB;
1410   if (StatSimpleCache(a, &StatBufA) || StatSimpleCache(b, &StatBufB))
1411     return false;
1412 
1413   return StatBufA.st_ino == StatBufB.st_ino;
1414 }
1415 
1416 std::pair<unsigned, unsigned>
1417 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1418   unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1419   unsigned DataLen = (unsigned) *d++;
1420   return std::make_pair(KeyLen + 1, DataLen);
1421 }
1422 
1423 HeaderFileInfoTrait::data_type
1424 HeaderFileInfoTrait::ReadData(const internal_key_type, const unsigned char *d,
1425                               unsigned DataLen) {
1426   const unsigned char *End = d + DataLen;
1427   using namespace clang::io;
1428   HeaderFileInfo HFI;
1429   unsigned Flags = *d++;
1430   HFI.isImport = (Flags >> 5) & 0x01;
1431   HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1432   HFI.DirInfo = (Flags >> 2) & 0x03;
1433   HFI.Resolved = (Flags >> 1) & 0x01;
1434   HFI.IndexHeaderMapHeader = Flags & 0x01;
1435   HFI.NumIncludes = ReadUnalignedLE16(d);
1436   HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1437                                                         ReadUnalignedLE32(d));
1438   if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1439     // The framework offset is 1 greater than the actual offset,
1440     // since 0 is used as an indicator for "no framework name".
1441     StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1442     HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1443   }
1444 
1445   assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1446   (void)End;
1447 
1448   // This HeaderFileInfo was externally loaded.
1449   HFI.External = true;
1450   return HFI;
1451 }
1452 
1453 void ASTReader::SetIdentifierIsMacro(IdentifierInfo *II, Module &F,
1454                                      uint64_t LocalOffset) {
1455   // Note that this identifier has a macro definition.
1456   II->setHasMacroDefinition(true);
1457 
1458   // Adjust the offset to a global offset.
1459   UnreadMacroRecordOffsets[II] = F.GlobalBitOffset + LocalOffset;
1460 }
1461 
1462 void ASTReader::ReadDefinedMacros() {
1463   for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1464       E = ModuleMgr.rend(); I != E; ++I) {
1465     llvm::BitstreamCursor &MacroCursor = (*I)->MacroCursor;
1466 
1467     // If there was no preprocessor block, skip this file.
1468     if (!MacroCursor.getBitStreamReader())
1469       continue;
1470 
1471     llvm::BitstreamCursor Cursor = MacroCursor;
1472     Cursor.JumpToBit((*I)->MacroStartOffset);
1473 
1474     RecordData Record;
1475     while (true) {
1476       unsigned Code = Cursor.ReadCode();
1477       if (Code == llvm::bitc::END_BLOCK)
1478         break;
1479 
1480       if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1481         // No known subblocks, always skip them.
1482         Cursor.ReadSubBlockID();
1483         if (Cursor.SkipBlock()) {
1484           Error("malformed block record in AST file");
1485           return;
1486         }
1487         continue;
1488       }
1489 
1490       if (Code == llvm::bitc::DEFINE_ABBREV) {
1491         Cursor.ReadAbbrevRecord();
1492         continue;
1493       }
1494 
1495       // Read a record.
1496       const char *BlobStart;
1497       unsigned BlobLen;
1498       Record.clear();
1499       switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1500       default:  // Default behavior: ignore.
1501         break;
1502 
1503       case PP_MACRO_OBJECT_LIKE:
1504       case PP_MACRO_FUNCTION_LIKE:
1505         getLocalIdentifier(**I, Record[0]);
1506         break;
1507 
1508       case PP_TOKEN:
1509         // Ignore tokens.
1510         break;
1511       }
1512     }
1513   }
1514 
1515   // Drain the unread macro-record offsets map.
1516   while (!UnreadMacroRecordOffsets.empty())
1517     LoadMacroDefinition(UnreadMacroRecordOffsets.begin());
1518 }
1519 
1520 void ASTReader::LoadMacroDefinition(
1521                      llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos) {
1522   assert(Pos != UnreadMacroRecordOffsets.end() && "Unknown macro definition");
1523   uint64_t Offset = Pos->second;
1524   UnreadMacroRecordOffsets.erase(Pos);
1525 
1526   RecordLocation Loc = getLocalBitOffset(Offset);
1527   ReadMacroRecord(*Loc.F, Loc.Offset);
1528 }
1529 
1530 void ASTReader::LoadMacroDefinition(IdentifierInfo *II) {
1531   llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos
1532     = UnreadMacroRecordOffsets.find(II);
1533   LoadMacroDefinition(Pos);
1534 }
1535 
1536 namespace {
1537   /// \brief Visitor class used to look up identifirs in an AST file.
1538   class IdentifierLookupVisitor {
1539     StringRef Name;
1540     IdentifierInfo *Found;
1541   public:
1542     explicit IdentifierLookupVisitor(StringRef Name) : Name(Name), Found() { }
1543 
1544     static bool visit(Module &M, void *UserData) {
1545       IdentifierLookupVisitor *This
1546         = static_cast<IdentifierLookupVisitor *>(UserData);
1547 
1548       ASTIdentifierLookupTable *IdTable
1549         = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1550       if (!IdTable)
1551         return false;
1552 
1553       std::pair<const char*, unsigned> Key(This->Name.begin(),
1554                                            This->Name.size());
1555       ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key);
1556       if (Pos == IdTable->end())
1557         return false;
1558 
1559       // Dereferencing the iterator has the effect of building the
1560       // IdentifierInfo node and populating it with the various
1561       // declarations it needs.
1562       This->Found = *Pos;
1563       return true;
1564     }
1565 
1566     // \brief Retrieve the identifier info found within the module
1567     // files.
1568     IdentifierInfo *getIdentifierInfo() const { return Found; }
1569   };
1570 }
1571 
1572 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1573   get(II.getName());
1574 }
1575 
1576 const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
1577   std::string Filename = filenameStrRef;
1578   MaybeAddSystemRootToFilename(Filename);
1579   const FileEntry *File = FileMgr.getFile(Filename);
1580   if (File == 0 && !OriginalDir.empty() && !CurrentDir.empty() &&
1581       OriginalDir != CurrentDir) {
1582     std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1583                                                             OriginalDir,
1584                                                             CurrentDir);
1585     if (!resolved.empty())
1586       File = FileMgr.getFile(resolved);
1587   }
1588 
1589   return File;
1590 }
1591 
1592 /// \brief If we are loading a relocatable PCH file, and the filename is
1593 /// not an absolute path, add the system root to the beginning of the file
1594 /// name.
1595 void ASTReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1596   // If this is not a relocatable PCH file, there's nothing to do.
1597   if (!RelocatablePCH)
1598     return;
1599 
1600   if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1601     return;
1602 
1603   if (isysroot.empty()) {
1604     // If no system root was given, default to '/'
1605     Filename.insert(Filename.begin(), '/');
1606     return;
1607   }
1608 
1609   unsigned Length = isysroot.size();
1610   if (isysroot[Length - 1] != '/')
1611     Filename.insert(Filename.begin(), '/');
1612 
1613   Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
1614 }
1615 
1616 ASTReader::ASTReadResult
1617 ASTReader::ReadASTBlock(Module &F) {
1618   llvm::BitstreamCursor &Stream = F.Stream;
1619 
1620   if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
1621     Error("malformed block record in AST file");
1622     return Failure;
1623   }
1624 
1625   // Read all of the records and blocks for the ASt file.
1626   RecordData Record;
1627   while (!Stream.AtEndOfStream()) {
1628     unsigned Code = Stream.ReadCode();
1629     if (Code == llvm::bitc::END_BLOCK) {
1630       if (Stream.ReadBlockEnd()) {
1631         Error("error at end of module block in AST file");
1632         return Failure;
1633       }
1634 
1635       return Success;
1636     }
1637 
1638     if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1639       switch (Stream.ReadSubBlockID()) {
1640       case DECLTYPES_BLOCK_ID:
1641         // We lazily load the decls block, but we want to set up the
1642         // DeclsCursor cursor to point into it.  Clone our current bitcode
1643         // cursor to it, enter the block and read the abbrevs in that block.
1644         // With the main cursor, we just skip over it.
1645         F.DeclsCursor = Stream;
1646         if (Stream.SkipBlock() ||  // Skip with the main cursor.
1647             // Read the abbrevs.
1648             ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
1649           Error("malformed block record in AST file");
1650           return Failure;
1651         }
1652         break;
1653 
1654       case DECL_UPDATES_BLOCK_ID:
1655         if (Stream.SkipBlock()) {
1656           Error("malformed block record in AST file");
1657           return Failure;
1658         }
1659         break;
1660 
1661       case PREPROCESSOR_BLOCK_ID:
1662         F.MacroCursor = Stream;
1663         if (!PP.getExternalSource())
1664           PP.setExternalSource(this);
1665 
1666         if (Stream.SkipBlock() ||
1667             ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
1668           Error("malformed block record in AST file");
1669           return Failure;
1670         }
1671         F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
1672         break;
1673 
1674       case PREPROCESSOR_DETAIL_BLOCK_ID:
1675         F.PreprocessorDetailCursor = Stream;
1676         if (Stream.SkipBlock() ||
1677             ReadBlockAbbrevs(F.PreprocessorDetailCursor,
1678                              PREPROCESSOR_DETAIL_BLOCK_ID)) {
1679           Error("malformed preprocessor detail record in AST file");
1680           return Failure;
1681         }
1682         F.PreprocessorDetailStartOffset
1683           = F.PreprocessorDetailCursor.GetCurrentBitNo();
1684 
1685         if (!PP.getPreprocessingRecord())
1686           PP.createPreprocessingRecord(true);
1687         if (!PP.getPreprocessingRecord()->getExternalSource())
1688           PP.getPreprocessingRecord()->SetExternalSource(*this);
1689         break;
1690 
1691       case SOURCE_MANAGER_BLOCK_ID:
1692         switch (ReadSourceManagerBlock(F)) {
1693         case Success:
1694           break;
1695 
1696         case Failure:
1697           Error("malformed source manager block in AST file");
1698           return Failure;
1699 
1700         case IgnorePCH:
1701           return IgnorePCH;
1702         }
1703         break;
1704       }
1705       continue;
1706     }
1707 
1708     if (Code == llvm::bitc::DEFINE_ABBREV) {
1709       Stream.ReadAbbrevRecord();
1710       continue;
1711     }
1712 
1713     // Read and process a record.
1714     Record.clear();
1715     const char *BlobStart = 0;
1716     unsigned BlobLen = 0;
1717     switch ((ASTRecordTypes)Stream.ReadRecord(Code, Record,
1718                                               &BlobStart, &BlobLen)) {
1719     default:  // Default behavior: ignore.
1720       break;
1721 
1722     case METADATA: {
1723       if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1724         Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1725                                            : diag::warn_pch_version_too_new);
1726         return IgnorePCH;
1727       }
1728 
1729       RelocatablePCH = Record[4];
1730       if (Listener) {
1731         std::string TargetTriple(BlobStart, BlobLen);
1732         if (Listener->ReadTargetTriple(TargetTriple))
1733           return IgnorePCH;
1734       }
1735       break;
1736     }
1737 
1738     case IMPORTS: {
1739       // Load each of the imported PCH files.
1740       unsigned Idx = 0, N = Record.size();
1741       while (Idx < N) {
1742         // Read information about the AST file.
1743         ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
1744         unsigned Length = Record[Idx++];
1745         llvm::SmallString<128> ImportedFile(Record.begin() + Idx,
1746                                             Record.begin() + Idx + Length);
1747         Idx += Length;
1748 
1749         // Load the AST file.
1750         switch(ReadASTCore(ImportedFile, ImportedKind, &F)) {
1751         case Failure: return Failure;
1752           // If we have to ignore the dependency, we'll have to ignore this too.
1753         case IgnorePCH: return IgnorePCH;
1754         case Success: break;
1755         }
1756       }
1757       break;
1758     }
1759 
1760     case TYPE_OFFSET: {
1761       if (F.LocalNumTypes != 0) {
1762         Error("duplicate TYPE_OFFSET record in AST file");
1763         return Failure;
1764       }
1765       F.TypeOffsets = (const uint32_t *)BlobStart;
1766       F.LocalNumTypes = Record[0];
1767       unsigned LocalBaseTypeIndex = Record[1];
1768       F.BaseTypeIndex = getTotalNumTypes();
1769 
1770       if (F.LocalNumTypes > 0) {
1771         // Introduce the global -> local mapping for types within this module.
1772         GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
1773 
1774         // Introduce the local -> global mapping for types within this module.
1775         F.TypeRemap.insert(std::make_pair(LocalBaseTypeIndex,
1776                              F.BaseTypeIndex - LocalBaseTypeIndex));
1777 
1778         TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
1779       }
1780       break;
1781     }
1782 
1783     case DECL_OFFSET: {
1784       if (F.LocalNumDecls != 0) {
1785         Error("duplicate DECL_OFFSET record in AST file");
1786         return Failure;
1787       }
1788       F.DeclOffsets = (const DeclOffset *)BlobStart;
1789       F.LocalNumDecls = Record[0];
1790       unsigned LocalBaseDeclID = Record[1];
1791       F.BaseDeclID = getTotalNumDecls();
1792 
1793       if (F.LocalNumDecls > 0) {
1794         // Introduce the global -> local mapping for declarations within this
1795         // module.
1796         GlobalDeclMap.insert(
1797           std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
1798 
1799         // Introduce the local -> global mapping for declarations within this
1800         // module.
1801         F.DeclRemap.insert(std::make_pair(LocalBaseDeclID,
1802                                           F.BaseDeclID - LocalBaseDeclID));
1803 
1804         DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
1805       }
1806       break;
1807     }
1808 
1809     case TU_UPDATE_LEXICAL: {
1810       DeclContext *TU = Context.getTranslationUnitDecl();
1811       DeclContextInfo &Info = F.DeclContextInfos[TU];
1812       Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(BlobStart);
1813       Info.NumLexicalDecls
1814         = static_cast<unsigned int>(BlobLen / sizeof(KindDeclIDPair));
1815       TU->setHasExternalLexicalStorage(true);
1816       break;
1817     }
1818 
1819     case UPDATE_VISIBLE: {
1820       unsigned Idx = 0;
1821       serialization::DeclID ID = ReadDeclID(F, Record, Idx);
1822       void *Table = ASTDeclContextNameLookupTable::Create(
1823                         (const unsigned char *)BlobStart + Record[Idx++],
1824                         (const unsigned char *)BlobStart,
1825                         ASTDeclContextNameLookupTrait(*this, F));
1826       if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
1827         DeclContext *TU = Context.getTranslationUnitDecl();
1828         F.DeclContextInfos[TU].NameLookupTableData = Table;
1829         TU->setHasExternalVisibleStorage(true);
1830       } else
1831         PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
1832       break;
1833     }
1834 
1835     case REDECLS_UPDATE_LATEST: {
1836       assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs");
1837       for (unsigned i = 0, e = Record.size(); i < e; /* in loop */) {
1838         DeclID First = ReadDeclID(F, Record, i);
1839         DeclID Latest = ReadDeclID(F, Record, i);
1840         FirstLatestDeclIDs[First] = Latest;
1841       }
1842       break;
1843     }
1844 
1845     case LANGUAGE_OPTIONS:
1846       if (ParseLanguageOptions(Record) && !DisableValidation)
1847         return IgnorePCH;
1848       break;
1849 
1850     case IDENTIFIER_TABLE:
1851       F.IdentifierTableData = BlobStart;
1852       if (Record[0]) {
1853         F.IdentifierLookupTable
1854           = ASTIdentifierLookupTable::Create(
1855                        (const unsigned char *)F.IdentifierTableData + Record[0],
1856                        (const unsigned char *)F.IdentifierTableData,
1857                        ASTIdentifierLookupTrait(*this, F));
1858 
1859         PP.getIdentifierTable().setExternalIdentifierLookup(this);
1860       }
1861       break;
1862 
1863     case IDENTIFIER_OFFSET: {
1864       if (F.LocalNumIdentifiers != 0) {
1865         Error("duplicate IDENTIFIER_OFFSET record in AST file");
1866         return Failure;
1867       }
1868       F.IdentifierOffsets = (const uint32_t *)BlobStart;
1869       F.LocalNumIdentifiers = Record[0];
1870       unsigned LocalBaseIdentifierID = Record[1];
1871       F.BaseIdentifierID = getTotalNumIdentifiers();
1872 
1873       if (F.LocalNumIdentifiers > 0) {
1874         // Introduce the global -> local mapping for identifiers within this
1875         // module.
1876         GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
1877                                                   &F));
1878 
1879         // Introduce the local -> global mapping for identifiers within this
1880         // module.
1881         F.IdentifierRemap.insert(
1882                             std::make_pair(LocalBaseIdentifierID,
1883                               F.BaseIdentifierID - LocalBaseIdentifierID));
1884 
1885         IdentifiersLoaded.resize(IdentifiersLoaded.size()
1886                                  + F.LocalNumIdentifiers);
1887       }
1888       break;
1889     }
1890 
1891     case EXTERNAL_DEFINITIONS:
1892       for (unsigned I = 0, N = Record.size(); I != N; ++I)
1893         ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
1894       break;
1895 
1896     case SPECIAL_TYPES:
1897       for (unsigned I = 0, N = Record.size(); I != N; ++I)
1898         SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
1899       break;
1900 
1901     case STATISTICS:
1902       TotalNumStatements += Record[0];
1903       TotalNumMacros += Record[1];
1904       TotalLexicalDeclContexts += Record[2];
1905       TotalVisibleDeclContexts += Record[3];
1906       break;
1907 
1908     case UNUSED_FILESCOPED_DECLS:
1909       for (unsigned I = 0, N = Record.size(); I != N; ++I)
1910         UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
1911       break;
1912 
1913     case DELEGATING_CTORS:
1914       for (unsigned I = 0, N = Record.size(); I != N; ++I)
1915         DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
1916       break;
1917 
1918     case WEAK_UNDECLARED_IDENTIFIERS:
1919       if (Record.size() % 4 != 0) {
1920         Error("invalid weak identifiers record");
1921         return Failure;
1922       }
1923 
1924       // FIXME: Ignore weak undeclared identifiers from non-original PCH
1925       // files. This isn't the way to do it :)
1926       WeakUndeclaredIdentifiers.clear();
1927 
1928       // Translate the weak, undeclared identifiers into global IDs.
1929       for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
1930         WeakUndeclaredIdentifiers.push_back(
1931           getGlobalIdentifierID(F, Record[I++]));
1932         WeakUndeclaredIdentifiers.push_back(
1933           getGlobalIdentifierID(F, Record[I++]));
1934         WeakUndeclaredIdentifiers.push_back(
1935           ReadSourceLocation(F, Record, I).getRawEncoding());
1936         WeakUndeclaredIdentifiers.push_back(Record[I++]);
1937       }
1938       break;
1939 
1940     case LOCALLY_SCOPED_EXTERNAL_DECLS:
1941       for (unsigned I = 0, N = Record.size(); I != N; ++I)
1942         LocallyScopedExternalDecls.push_back(getGlobalDeclID(F, Record[I]));
1943       break;
1944 
1945     case SELECTOR_OFFSETS: {
1946       F.SelectorOffsets = (const uint32_t *)BlobStart;
1947       F.LocalNumSelectors = Record[0];
1948       unsigned LocalBaseSelectorID = Record[1];
1949       F.BaseSelectorID = getTotalNumSelectors();
1950 
1951       if (F.LocalNumSelectors > 0) {
1952         // Introduce the global -> local mapping for selectors within this
1953         // module.
1954         GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
1955 
1956         // Introduce the local -> global mapping for selectors within this
1957         // module.
1958         F.SelectorRemap.insert(std::make_pair(LocalBaseSelectorID,
1959                                  F.BaseSelectorID - LocalBaseSelectorID));
1960 
1961         SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
1962       }
1963       break;
1964     }
1965 
1966     case METHOD_POOL:
1967       F.SelectorLookupTableData = (const unsigned char *)BlobStart;
1968       if (Record[0])
1969         F.SelectorLookupTable
1970           = ASTSelectorLookupTable::Create(
1971                         F.SelectorLookupTableData + Record[0],
1972                         F.SelectorLookupTableData,
1973                         ASTSelectorLookupTrait(*this, F));
1974       TotalNumMethodPoolEntries += Record[1];
1975       break;
1976 
1977     case REFERENCED_SELECTOR_POOL:
1978       if (!Record.empty()) {
1979         for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
1980           ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
1981                                                                 Record[Idx++]));
1982           ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
1983                                               getRawEncoding());
1984         }
1985       }
1986       break;
1987 
1988     case PP_COUNTER_VALUE:
1989       if (!Record.empty() && Listener)
1990         Listener->ReadCounter(Record[0]);
1991       break;
1992 
1993     case FILE_SORTED_DECLS:
1994       F.FileSortedDecls = (const DeclID *)BlobStart;
1995       break;
1996 
1997     case SOURCE_LOCATION_OFFSETS: {
1998       F.SLocEntryOffsets = (const uint32_t *)BlobStart;
1999       F.LocalNumSLocEntries = Record[0];
2000       unsigned SLocSpaceSize = Record[1];
2001       llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2002           SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2003                                               SLocSpaceSize);
2004       // Make our entry in the range map. BaseID is negative and growing, so
2005       // we invert it. Because we invert it, though, we need the other end of
2006       // the range.
2007       unsigned RangeStart =
2008           unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2009       GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2010       F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2011 
2012       // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2013       assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2014       GlobalSLocOffsetMap.insert(
2015           std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2016                            - SLocSpaceSize,&F));
2017 
2018       // Initialize the remapping table.
2019       // Invalid stays invalid.
2020       F.SLocRemap.insert(std::make_pair(0U, 0));
2021       // This module. Base was 2 when being compiled.
2022       F.SLocRemap.insert(std::make_pair(2U,
2023                                   static_cast<int>(F.SLocEntryBaseOffset - 2)));
2024 
2025       TotalNumSLocEntries += F.LocalNumSLocEntries;
2026       break;
2027     }
2028 
2029     case MODULE_OFFSET_MAP: {
2030       // Additional remapping information.
2031       const unsigned char *Data = (const unsigned char*)BlobStart;
2032       const unsigned char *DataEnd = Data + BlobLen;
2033 
2034       // Continuous range maps we may be updating in our module.
2035       ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2036       ContinuousRangeMap<uint32_t, int, 2>::Builder
2037         IdentifierRemap(F.IdentifierRemap);
2038       ContinuousRangeMap<uint32_t, int, 2>::Builder
2039         PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2040       ContinuousRangeMap<uint32_t, int, 2>::Builder
2041         SelectorRemap(F.SelectorRemap);
2042       ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2043       ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2044 
2045       while(Data < DataEnd) {
2046         uint16_t Len = io::ReadUnalignedLE16(Data);
2047         StringRef Name = StringRef((const char*)Data, Len);
2048         Data += Len;
2049         Module *OM = ModuleMgr.lookup(Name);
2050         if (!OM) {
2051           Error("SourceLocation remap refers to unknown module");
2052           return Failure;
2053         }
2054 
2055         uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2056         uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2057         uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2058         uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2059         uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2060         uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2061 
2062         // Source location offset is mapped to OM->SLocEntryBaseOffset.
2063         SLocRemap.insert(std::make_pair(SLocOffset,
2064           static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2065         IdentifierRemap.insert(
2066           std::make_pair(IdentifierIDOffset,
2067                          OM->BaseIdentifierID - IdentifierIDOffset));
2068         PreprocessedEntityRemap.insert(
2069           std::make_pair(PreprocessedEntityIDOffset,
2070             OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2071         SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2072                                OM->BaseSelectorID - SelectorIDOffset));
2073         DeclRemap.insert(std::make_pair(DeclIDOffset,
2074                                         OM->BaseDeclID - DeclIDOffset));
2075 
2076         TypeRemap.insert(std::make_pair(TypeIndexOffset,
2077                                     OM->BaseTypeIndex - TypeIndexOffset));
2078       }
2079       break;
2080     }
2081 
2082     case SOURCE_MANAGER_LINE_TABLE:
2083       if (ParseLineTable(F, Record))
2084         return Failure;
2085       break;
2086 
2087     case FILE_SOURCE_LOCATION_OFFSETS:
2088       F.SLocFileOffsets = (const uint32_t *)BlobStart;
2089       F.LocalNumSLocFileEntries = Record[0];
2090       break;
2091 
2092     case SOURCE_LOCATION_PRELOADS: {
2093       // Need to transform from the local view (1-based IDs) to the global view,
2094       // which is based off F.SLocEntryBaseID.
2095       if (!F.PreloadSLocEntries.empty()) {
2096         Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2097         return Failure;
2098       }
2099 
2100       F.PreloadSLocEntries.swap(Record);
2101       break;
2102     }
2103 
2104     case STAT_CACHE: {
2105       if (!DisableStatCache) {
2106         ASTStatCache *MyStatCache =
2107           new ASTStatCache((const unsigned char *)BlobStart + Record[0],
2108                            (const unsigned char *)BlobStart,
2109                            NumStatHits, NumStatMisses);
2110         FileMgr.addStatCache(MyStatCache);
2111         F.StatCache = MyStatCache;
2112       }
2113       break;
2114     }
2115 
2116     case EXT_VECTOR_DECLS:
2117       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2118         ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2119       break;
2120 
2121     case VTABLE_USES:
2122       if (Record.size() % 3 != 0) {
2123         Error("Invalid VTABLE_USES record");
2124         return Failure;
2125       }
2126 
2127       // Later tables overwrite earlier ones.
2128       // FIXME: Modules will have some trouble with this. This is clearly not
2129       // the right way to do this.
2130       VTableUses.clear();
2131 
2132       for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2133         VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2134         VTableUses.push_back(
2135           ReadSourceLocation(F, Record, Idx).getRawEncoding());
2136         VTableUses.push_back(Record[Idx++]);
2137       }
2138       break;
2139 
2140     case DYNAMIC_CLASSES:
2141       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2142         DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2143       break;
2144 
2145     case PENDING_IMPLICIT_INSTANTIATIONS:
2146       if (PendingInstantiations.size() % 2 != 0) {
2147         Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2148         return Failure;
2149       }
2150 
2151       // Later lists of pending instantiations overwrite earlier ones.
2152       // FIXME: This is most certainly wrong for modules.
2153       PendingInstantiations.clear();
2154       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2155         PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2156         PendingInstantiations.push_back(
2157           ReadSourceLocation(F, Record, I).getRawEncoding());
2158       }
2159       break;
2160 
2161     case SEMA_DECL_REFS:
2162       // Later tables overwrite earlier ones.
2163       // FIXME: Modules will have some trouble with this.
2164       SemaDeclRefs.clear();
2165       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2166         SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2167       break;
2168 
2169     case ORIGINAL_FILE_NAME:
2170       // The primary AST will be the last to get here, so it will be the one
2171       // that's used.
2172       ActualOriginalFileName.assign(BlobStart, BlobLen);
2173       OriginalFileName = ActualOriginalFileName;
2174       MaybeAddSystemRootToFilename(OriginalFileName);
2175       break;
2176 
2177     case ORIGINAL_FILE_ID:
2178       OriginalFileID = FileID::get(Record[0]);
2179       break;
2180 
2181     case ORIGINAL_PCH_DIR:
2182       // The primary AST will be the last to get here, so it will be the one
2183       // that's used.
2184       OriginalDir.assign(BlobStart, BlobLen);
2185       break;
2186 
2187     case VERSION_CONTROL_BRANCH_REVISION: {
2188       const std::string &CurBranch = getClangFullRepositoryVersion();
2189       StringRef ASTBranch(BlobStart, BlobLen);
2190       if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2191         Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
2192         return IgnorePCH;
2193       }
2194       break;
2195     }
2196 
2197     case PPD_ENTITIES_OFFSETS: {
2198       F.PreprocessedEntityOffsets = (const PPEntityOffset *)BlobStart;
2199       assert(BlobLen % sizeof(PPEntityOffset) == 0);
2200       F.NumPreprocessedEntities = BlobLen / sizeof(PPEntityOffset);
2201 
2202       unsigned LocalBasePreprocessedEntityID = Record[0];
2203 
2204       unsigned StartingID;
2205       if (!PP.getPreprocessingRecord())
2206         PP.createPreprocessingRecord(true);
2207       if (!PP.getPreprocessingRecord()->getExternalSource())
2208         PP.getPreprocessingRecord()->SetExternalSource(*this);
2209       StartingID
2210         = PP.getPreprocessingRecord()
2211             ->allocateLoadedEntities(F.NumPreprocessedEntities);
2212       F.BasePreprocessedEntityID = StartingID;
2213 
2214       if (F.NumPreprocessedEntities > 0) {
2215         // Introduce the global -> local mapping for preprocessed entities in
2216         // this module.
2217         GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2218 
2219         // Introduce the local -> global mapping for preprocessed entities in
2220         // this module.
2221         F.PreprocessedEntityRemap.insert(
2222           std::make_pair(LocalBasePreprocessedEntityID,
2223             F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2224       }
2225 
2226       break;
2227     }
2228 
2229     case DECL_UPDATE_OFFSETS: {
2230       if (Record.size() % 2 != 0) {
2231         Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2232         return Failure;
2233       }
2234       for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2235         DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2236           .push_back(std::make_pair(&F, Record[I+1]));
2237       break;
2238     }
2239 
2240     case DECL_REPLACEMENTS: {
2241       if (Record.size() % 3 != 0) {
2242         Error("invalid DECL_REPLACEMENTS block in AST file");
2243         return Failure;
2244       }
2245       for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2246         ReplacedDecls[getGlobalDeclID(F, Record[I])]
2247           = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2248       break;
2249     }
2250 
2251     case OBJC_CHAINED_CATEGORIES: {
2252       if (Record.size() % 3 != 0) {
2253         Error("invalid OBJC_CHAINED_CATEGORIES block in AST file");
2254         return Failure;
2255       }
2256       for (unsigned I = 0, N = Record.size(); I != N; I += 3) {
2257         serialization::GlobalDeclID GlobID = getGlobalDeclID(F, Record[I]);
2258         F.ChainedObjCCategories[GlobID] = std::make_pair(Record[I+1],
2259                                                          Record[I+2]);
2260         ObjCChainedCategoriesInterfaces.insert(GlobID);
2261       }
2262       break;
2263     }
2264 
2265     case CXX_BASE_SPECIFIER_OFFSETS: {
2266       if (F.LocalNumCXXBaseSpecifiers != 0) {
2267         Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2268         return Failure;
2269       }
2270 
2271       F.LocalNumCXXBaseSpecifiers = Record[0];
2272       F.CXXBaseSpecifiersOffsets = (const uint32_t *)BlobStart;
2273       NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2274       break;
2275     }
2276 
2277     case DIAG_PRAGMA_MAPPINGS:
2278       if (Record.size() % 2 != 0) {
2279         Error("invalid DIAG_USER_MAPPINGS block in AST file");
2280         return Failure;
2281       }
2282 
2283       if (F.PragmaDiagMappings.empty())
2284         F.PragmaDiagMappings.swap(Record);
2285       else
2286         F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2287                                     Record.begin(), Record.end());
2288       break;
2289 
2290     case CUDA_SPECIAL_DECL_REFS:
2291       // Later tables overwrite earlier ones.
2292       // FIXME: Modules will have trouble with this.
2293       CUDASpecialDeclRefs.clear();
2294       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2295         CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2296       break;
2297 
2298     case HEADER_SEARCH_TABLE: {
2299       F.HeaderFileInfoTableData = BlobStart;
2300       F.LocalNumHeaderFileInfos = Record[1];
2301       F.HeaderFileFrameworkStrings = BlobStart + Record[2];
2302       if (Record[0]) {
2303         F.HeaderFileInfoTable
2304           = HeaderFileInfoLookupTable::Create(
2305                    (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2306                    (const unsigned char *)F.HeaderFileInfoTableData,
2307                    HeaderFileInfoTrait(*this, F,
2308                                        &PP.getHeaderSearchInfo(),
2309                                        BlobStart + Record[2]));
2310 
2311         PP.getHeaderSearchInfo().SetExternalSource(this);
2312         if (!PP.getHeaderSearchInfo().getExternalLookup())
2313           PP.getHeaderSearchInfo().SetExternalLookup(this);
2314       }
2315       break;
2316     }
2317 
2318     case FP_PRAGMA_OPTIONS:
2319       // Later tables overwrite earlier ones.
2320       FPPragmaOptions.swap(Record);
2321       break;
2322 
2323     case OPENCL_EXTENSIONS:
2324       // Later tables overwrite earlier ones.
2325       OpenCLExtensions.swap(Record);
2326       break;
2327 
2328     case TENTATIVE_DEFINITIONS:
2329       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2330         TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2331       break;
2332 
2333     case KNOWN_NAMESPACES:
2334       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2335         KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2336       break;
2337     }
2338   }
2339   Error("premature end of bitstream in AST file");
2340   return Failure;
2341 }
2342 
2343 ASTReader::ASTReadResult ASTReader::validateFileEntries(Module &M) {
2344   llvm::BitstreamCursor &SLocEntryCursor = M.SLocEntryCursor;
2345 
2346   for (unsigned i = 0, e = M.LocalNumSLocFileEntries; i != e; ++i) {
2347     SLocEntryCursor.JumpToBit(M.SLocFileOffsets[i]);
2348     unsigned Code = SLocEntryCursor.ReadCode();
2349     if (Code == llvm::bitc::END_BLOCK ||
2350         Code == llvm::bitc::ENTER_SUBBLOCK ||
2351         Code == llvm::bitc::DEFINE_ABBREV) {
2352       Error("incorrectly-formatted source location entry in AST file");
2353       return Failure;
2354     }
2355 
2356     RecordData Record;
2357     const char *BlobStart;
2358     unsigned BlobLen;
2359     switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
2360     default:
2361       Error("incorrectly-formatted source location entry in AST file");
2362       return Failure;
2363 
2364     case SM_SLOC_FILE_ENTRY: {
2365       // If the buffer was overridden, the file need not exist.
2366       if (Record[6])
2367         break;
2368 
2369       StringRef Filename(BlobStart, BlobLen);
2370       const FileEntry *File = getFileEntry(Filename);
2371 
2372       if (File == 0) {
2373         std::string ErrorStr = "could not find file '";
2374         ErrorStr += Filename;
2375         ErrorStr += "' referenced by AST file";
2376         Error(ErrorStr.c_str());
2377         return IgnorePCH;
2378       }
2379 
2380       if (Record.size() < 7) {
2381         Error("source location entry is incorrect");
2382         return Failure;
2383       }
2384 
2385       // The stat info from the FileEntry came from the cached stat
2386       // info of the PCH, so we cannot trust it.
2387       struct stat StatBuf;
2388       if (::stat(File->getName(), &StatBuf) != 0) {
2389         StatBuf.st_size = File->getSize();
2390         StatBuf.st_mtime = File->getModificationTime();
2391       }
2392 
2393       if (((off_t)Record[4] != StatBuf.st_size
2394 #if !defined(LLVM_ON_WIN32)
2395           // In our regression testing, the Windows file system seems to
2396           // have inconsistent modification times that sometimes
2397           // erroneously trigger this error-handling path.
2398            || (time_t)Record[5] != StatBuf.st_mtime
2399 #endif
2400           )) {
2401         Error(diag::err_fe_pch_file_modified, Filename);
2402         return IgnorePCH;
2403       }
2404 
2405       break;
2406     }
2407     }
2408   }
2409 
2410   return Success;
2411 }
2412 
2413 ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
2414                                             ModuleKind Type) {
2415   switch(ReadASTCore(FileName, Type, /*ImportedBy=*/0)) {
2416   case Failure: return Failure;
2417   case IgnorePCH: return IgnorePCH;
2418   case Success: break;
2419   }
2420 
2421   // Here comes stuff that we only do once the entire chain is loaded.
2422 
2423   // Check the predefines buffers.
2424   if (!DisableValidation && Type != MK_Module && Type != MK_Preamble &&
2425       // FIXME: CheckPredefinesBuffers also sets the SuggestedPredefines;
2426       // if DisableValidation is true, defines that were set on command-line
2427       // but not in the PCH file will not be added to SuggestedPredefines.
2428       CheckPredefinesBuffers())
2429     return IgnorePCH;
2430 
2431   // Mark all of the identifiers in the identifier table as being out of date,
2432   // so that various accessors know to check the loaded modules when the
2433   // identifier is used.
2434   for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
2435                               IdEnd = PP.getIdentifierTable().end();
2436        Id != IdEnd; ++Id)
2437     Id->second->setOutOfDate(true);
2438 
2439   InitializeContext();
2440 
2441   if (DeserializationListener)
2442     DeserializationListener->ReaderInitialized(this);
2443 
2444   // If this AST file is a precompiled preamble, then set the preamble file ID
2445   // of the source manager to the file source file from which the preamble was
2446   // built.
2447   if (Type == MK_Preamble) {
2448     if (!OriginalFileID.isInvalid()) {
2449       OriginalFileID = FileID::get(ModuleMgr.getPrimaryModule().SLocEntryBaseID
2450                                         + OriginalFileID.getOpaqueValue() - 1);
2451       SourceMgr.setPreambleFileID(OriginalFileID);
2452     }
2453   }
2454 
2455   return Success;
2456 }
2457 
2458 ASTReader::ASTReadResult ASTReader::ReadASTCore(StringRef FileName,
2459                                                 ModuleKind Type,
2460                                                 Module *ImportedBy) {
2461   Module *M;
2462   bool NewModule;
2463   std::string ErrorStr;
2464   llvm::tie(M, NewModule) = ModuleMgr.addModule(FileName, Type, ImportedBy,
2465                                                 ErrorStr);
2466 
2467   if (!M) {
2468     // We couldn't load the module.
2469     std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
2470       + ErrorStr;
2471     Error(Msg);
2472     return Failure;
2473   }
2474 
2475   if (!NewModule) {
2476     // We've already loaded this module.
2477     return Success;
2478   }
2479 
2480   // FIXME: This seems rather a hack. Should CurrentDir be part of the
2481   // module?
2482   if (FileName != "-") {
2483     CurrentDir = llvm::sys::path::parent_path(FileName);
2484     if (CurrentDir.empty()) CurrentDir = ".";
2485   }
2486 
2487   Module &F = *M;
2488   llvm::BitstreamCursor &Stream = F.Stream;
2489   Stream.init(F.StreamFile);
2490   F.SizeInBits = F.Buffer->getBufferSize() * 8;
2491 
2492   // Sniff for the signature.
2493   if (Stream.Read(8) != 'C' ||
2494       Stream.Read(8) != 'P' ||
2495       Stream.Read(8) != 'C' ||
2496       Stream.Read(8) != 'H') {
2497     Diag(diag::err_not_a_pch_file) << FileName;
2498     return Failure;
2499   }
2500 
2501   while (!Stream.AtEndOfStream()) {
2502     unsigned Code = Stream.ReadCode();
2503 
2504     if (Code != llvm::bitc::ENTER_SUBBLOCK) {
2505       Error("invalid record at top-level of AST file");
2506       return Failure;
2507     }
2508 
2509     unsigned BlockID = Stream.ReadSubBlockID();
2510 
2511     // We only know the AST subblock ID.
2512     switch (BlockID) {
2513     case llvm::bitc::BLOCKINFO_BLOCK_ID:
2514       if (Stream.ReadBlockInfoBlock()) {
2515         Error("malformed BlockInfoBlock in AST file");
2516         return Failure;
2517       }
2518       break;
2519     case AST_BLOCK_ID:
2520       switch (ReadASTBlock(F)) {
2521       case Success:
2522         break;
2523 
2524       case Failure:
2525         return Failure;
2526 
2527       case IgnorePCH:
2528         // FIXME: We could consider reading through to the end of this
2529         // AST block, skipping subblocks, to see if there are other
2530         // AST blocks elsewhere.
2531 
2532         // FIXME: We can't clear loaded slocentries anymore.
2533         //SourceMgr.ClearPreallocatedSLocEntries();
2534 
2535         // Remove the stat cache.
2536         if (F.StatCache)
2537           FileMgr.removeStatCache((ASTStatCache*)F.StatCache);
2538 
2539         return IgnorePCH;
2540       }
2541       break;
2542     default:
2543       if (Stream.SkipBlock()) {
2544         Error("malformed block record in AST file");
2545         return Failure;
2546       }
2547       break;
2548     }
2549   }
2550 
2551   // Once read, set the Module bit base offset and update the size in
2552   // bits of all files we've seen.
2553   F.GlobalBitOffset = TotalModulesSizeInBits;
2554   TotalModulesSizeInBits += F.SizeInBits;
2555   GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
2556 
2557   // Make sure that the files this module was built against are still available.
2558   if (!DisableValidation) {
2559     switch(validateFileEntries(*M)) {
2560     case Failure: return Failure;
2561     case IgnorePCH: return IgnorePCH;
2562     case Success: break;
2563     }
2564   }
2565 
2566   // Preload SLocEntries.
2567   for (unsigned I = 0, N = M->PreloadSLocEntries.size(); I != N; ++I) {
2568     int Index = int(M->PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
2569     // Load it through the SourceManager and don't call ReadSLocEntryRecord()
2570     // directly because the entry may have already been loaded in which case
2571     // calling ReadSLocEntryRecord() directly would trigger an assertion in
2572     // SourceManager.
2573     SourceMgr.getLoadedSLocEntryByID(Index);
2574   }
2575 
2576 
2577   return Success;
2578 }
2579 
2580 void ASTReader::InitializeContext() {
2581   // If there's a listener, notify them that we "read" the translation unit.
2582   if (DeserializationListener)
2583     DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
2584                                       Context.getTranslationUnitDecl());
2585 
2586   // Make sure we load the declaration update records for the translation unit,
2587   // if there are any.
2588   loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
2589                         Context.getTranslationUnitDecl());
2590 
2591   // FIXME: Find a better way to deal with collisions between these
2592   // built-in types. Right now, we just ignore the problem.
2593 
2594   // Load the special types.
2595   if (SpecialTypes.size() > NumSpecialTypeIDs) {
2596     if (Context.getBuiltinVaListType().isNull()) {
2597       Context.setBuiltinVaListType(
2598         GetType(SpecialTypes[SPECIAL_TYPE_BUILTIN_VA_LIST]));
2599     }
2600 
2601     if (unsigned Proto = SpecialTypes[SPECIAL_TYPE_OBJC_PROTOCOL]) {
2602       if (Context.ObjCProtoType.isNull())
2603         Context.ObjCProtoType = GetType(Proto);
2604     }
2605 
2606     if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
2607       if (!Context.CFConstantStringTypeDecl)
2608         Context.setCFConstantStringType(GetType(String));
2609     }
2610 
2611     if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
2612       QualType FileType = GetType(File);
2613       if (FileType.isNull()) {
2614         Error("FILE type is NULL");
2615         return;
2616       }
2617 
2618       if (!Context.FILEDecl) {
2619         if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
2620           Context.setFILEDecl(Typedef->getDecl());
2621         else {
2622           const TagType *Tag = FileType->getAs<TagType>();
2623           if (!Tag) {
2624             Error("Invalid FILE type in AST file");
2625             return;
2626           }
2627           Context.setFILEDecl(Tag->getDecl());
2628         }
2629       }
2630     }
2631 
2632     if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
2633       QualType Jmp_bufType = GetType(Jmp_buf);
2634       if (Jmp_bufType.isNull()) {
2635         Error("jmp_buf type is NULL");
2636         return;
2637       }
2638 
2639       if (!Context.jmp_bufDecl) {
2640         if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
2641           Context.setjmp_bufDecl(Typedef->getDecl());
2642         else {
2643           const TagType *Tag = Jmp_bufType->getAs<TagType>();
2644           if (!Tag) {
2645             Error("Invalid jmp_buf type in AST file");
2646             return;
2647           }
2648           Context.setjmp_bufDecl(Tag->getDecl());
2649         }
2650       }
2651     }
2652 
2653     if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
2654       QualType Sigjmp_bufType = GetType(Sigjmp_buf);
2655       if (Sigjmp_bufType.isNull()) {
2656         Error("sigjmp_buf type is NULL");
2657         return;
2658       }
2659 
2660       if (!Context.sigjmp_bufDecl) {
2661         if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
2662           Context.setsigjmp_bufDecl(Typedef->getDecl());
2663         else {
2664           const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
2665           assert(Tag && "Invalid sigjmp_buf type in AST file");
2666           Context.setsigjmp_bufDecl(Tag->getDecl());
2667         }
2668       }
2669     }
2670 
2671     if (unsigned ObjCIdRedef
2672           = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
2673       if (Context.ObjCIdRedefinitionType.isNull())
2674         Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
2675     }
2676 
2677     if (unsigned ObjCClassRedef
2678           = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
2679       if (Context.ObjCClassRedefinitionType.isNull())
2680         Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
2681     }
2682 
2683     if (unsigned ObjCSelRedef
2684           = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
2685       if (Context.ObjCSelRedefinitionType.isNull())
2686         Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2687     }
2688 
2689     if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
2690       QualType Ucontext_tType = GetType(Ucontext_t);
2691       if (Ucontext_tType.isNull()) {
2692         Error("ucontext_t type is NULL");
2693         return;
2694       }
2695 
2696       if (!Context.ucontext_tDecl) {
2697         if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
2698           Context.setucontext_tDecl(Typedef->getDecl());
2699         else {
2700           const TagType *Tag = Ucontext_tType->getAs<TagType>();
2701           assert(Tag && "Invalid ucontext_t type in AST file");
2702           Context.setucontext_tDecl(Tag->getDecl());
2703         }
2704       }
2705     }
2706   }
2707 
2708   ReadPragmaDiagnosticMappings(Context.getDiagnostics());
2709 
2710   // If there were any CUDA special declarations, deserialize them.
2711   if (!CUDASpecialDeclRefs.empty()) {
2712     assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
2713     Context.setcudaConfigureCallDecl(
2714                            cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
2715   }
2716 }
2717 
2718 /// \brief Retrieve the name of the original source file name
2719 /// directly from the AST file, without actually loading the AST
2720 /// file.
2721 std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
2722                                              FileManager &FileMgr,
2723                                              DiagnosticsEngine &Diags) {
2724   // Open the AST file.
2725   std::string ErrStr;
2726   llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2727   Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
2728   if (!Buffer) {
2729     Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
2730     return std::string();
2731   }
2732 
2733   // Initialize the stream
2734   llvm::BitstreamReader StreamFile;
2735   llvm::BitstreamCursor Stream;
2736   StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
2737                   (const unsigned char *)Buffer->getBufferEnd());
2738   Stream.init(StreamFile);
2739 
2740   // Sniff for the signature.
2741   if (Stream.Read(8) != 'C' ||
2742       Stream.Read(8) != 'P' ||
2743       Stream.Read(8) != 'C' ||
2744       Stream.Read(8) != 'H') {
2745     Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
2746     return std::string();
2747   }
2748 
2749   RecordData Record;
2750   while (!Stream.AtEndOfStream()) {
2751     unsigned Code = Stream.ReadCode();
2752 
2753     if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2754       unsigned BlockID = Stream.ReadSubBlockID();
2755 
2756       // We only know the AST subblock ID.
2757       switch (BlockID) {
2758       case AST_BLOCK_ID:
2759         if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2760           Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
2761           return std::string();
2762         }
2763         break;
2764 
2765       default:
2766         if (Stream.SkipBlock()) {
2767           Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
2768           return std::string();
2769         }
2770         break;
2771       }
2772       continue;
2773     }
2774 
2775     if (Code == llvm::bitc::END_BLOCK) {
2776       if (Stream.ReadBlockEnd()) {
2777         Diags.Report(diag::err_fe_pch_error_at_end_block) << ASTFileName;
2778         return std::string();
2779       }
2780       continue;
2781     }
2782 
2783     if (Code == llvm::bitc::DEFINE_ABBREV) {
2784       Stream.ReadAbbrevRecord();
2785       continue;
2786     }
2787 
2788     Record.clear();
2789     const char *BlobStart = 0;
2790     unsigned BlobLen = 0;
2791     if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
2792           == ORIGINAL_FILE_NAME)
2793       return std::string(BlobStart, BlobLen);
2794   }
2795 
2796   return std::string();
2797 }
2798 
2799 /// \brief Parse the record that corresponds to a LangOptions data
2800 /// structure.
2801 ///
2802 /// This routine parses the language options from the AST file and then gives
2803 /// them to the AST listener if one is set.
2804 ///
2805 /// \returns true if the listener deems the file unacceptable, false otherwise.
2806 bool ASTReader::ParseLanguageOptions(
2807                              const SmallVectorImpl<uint64_t> &Record) {
2808   if (Listener) {
2809     LangOptions LangOpts;
2810     unsigned Idx = 0;
2811 #define LANGOPT(Name, Bits, Default, Description) \
2812   LangOpts.Name = Record[Idx++];
2813 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
2814   LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
2815 #include "clang/Basic/LangOptions.def"
2816 
2817     unsigned Length = Record[Idx++];
2818     LangOpts.CurrentModule.assign(Record.begin() + Idx,
2819                                   Record.begin() + Idx + Length);
2820     Idx += Length;
2821     return Listener->ReadLanguageOptions(LangOpts);
2822   }
2823 
2824   return false;
2825 }
2826 
2827 std::pair<Module *, unsigned>
2828 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
2829   GlobalPreprocessedEntityMapType::iterator
2830   I = GlobalPreprocessedEntityMap.find(GlobalIndex);
2831   assert(I != GlobalPreprocessedEntityMap.end() &&
2832          "Corrupted global preprocessed entity map");
2833   Module *M = I->second;
2834   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
2835   return std::make_pair(M, LocalIndex);
2836 }
2837 
2838 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
2839   PreprocessedEntityID PPID = Index+1;
2840   std::pair<Module *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
2841   Module &M = *PPInfo.first;
2842   unsigned LocalIndex = PPInfo.second;
2843   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
2844 
2845   SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
2846   M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
2847 
2848   unsigned Code = M.PreprocessorDetailCursor.ReadCode();
2849   switch (Code) {
2850   case llvm::bitc::END_BLOCK:
2851     return 0;
2852 
2853   case llvm::bitc::ENTER_SUBBLOCK:
2854     Error("unexpected subblock record in preprocessor detail block");
2855     return 0;
2856 
2857   case llvm::bitc::DEFINE_ABBREV:
2858     Error("unexpected abbrevation record in preprocessor detail block");
2859     return 0;
2860 
2861   default:
2862     break;
2863   }
2864 
2865   if (!PP.getPreprocessingRecord()) {
2866     Error("no preprocessing record");
2867     return 0;
2868   }
2869 
2870   // Read the record.
2871   SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
2872                     ReadSourceLocation(M, PPOffs.End));
2873   PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
2874   const char *BlobStart = 0;
2875   unsigned BlobLen = 0;
2876   RecordData Record;
2877   PreprocessorDetailRecordTypes RecType =
2878     (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.ReadRecord(
2879                                              Code, Record, BlobStart, BlobLen);
2880   switch (RecType) {
2881   case PPD_MACRO_EXPANSION: {
2882     bool isBuiltin = Record[0];
2883     IdentifierInfo *Name = 0;
2884     MacroDefinition *Def = 0;
2885     if (isBuiltin)
2886       Name = getLocalIdentifier(M, Record[1]);
2887     else {
2888       PreprocessedEntityID
2889           GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
2890       Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
2891     }
2892 
2893     MacroExpansion *ME;
2894     if (isBuiltin)
2895       ME = new (PPRec) MacroExpansion(Name, Range);
2896     else
2897       ME = new (PPRec) MacroExpansion(Def, Range);
2898 
2899     return ME;
2900   }
2901 
2902   case PPD_MACRO_DEFINITION: {
2903     // Decode the identifier info and then check again; if the macro is
2904     // still defined and associated with the identifier,
2905     IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
2906     MacroDefinition *MD
2907       = new (PPRec) MacroDefinition(II, Range);
2908 
2909     if (DeserializationListener)
2910       DeserializationListener->MacroDefinitionRead(PPID, MD);
2911 
2912     return MD;
2913   }
2914 
2915   case PPD_INCLUSION_DIRECTIVE: {
2916     const char *FullFileNameStart = BlobStart + Record[0];
2917     const FileEntry *File
2918       = PP.getFileManager().getFile(StringRef(FullFileNameStart,
2919                                                BlobLen - Record[0]));
2920 
2921     // FIXME: Stable encoding
2922     InclusionDirective::InclusionKind Kind
2923       = static_cast<InclusionDirective::InclusionKind>(Record[2]);
2924     InclusionDirective *ID
2925       = new (PPRec) InclusionDirective(PPRec, Kind,
2926                                        StringRef(BlobStart, Record[0]),
2927                                        Record[1],
2928                                        File,
2929                                        Range);
2930     return ID;
2931   }
2932   }
2933 
2934   Error("invalid offset in preprocessor detail block");
2935   return 0;
2936 }
2937 
2938 /// \brief \arg SLocMapI points at a chunk of a module that contains no
2939 /// preprocessed entities or the entities it contains are not the ones we are
2940 /// looking for. Find the next module that contains entities and return the ID
2941 /// of the first entry.
2942 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
2943                        GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
2944   ++SLocMapI;
2945   for (GlobalSLocOffsetMapType::const_iterator
2946          EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
2947     Module &M = *SLocMapI->second;
2948     if (M.NumPreprocessedEntities)
2949       return getGlobalPreprocessedEntityID(M, M.BasePreprocessedEntityID);
2950   }
2951 
2952   return getTotalNumPreprocessedEntities();
2953 }
2954 
2955 namespace {
2956 
2957 template <unsigned PPEntityOffset::*PPLoc>
2958 struct PPEntityComp {
2959   const ASTReader &Reader;
2960   Module &M;
2961 
2962   PPEntityComp(const ASTReader &Reader, Module &M) : Reader(Reader), M(M) { }
2963 
2964   bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
2965     SourceLocation LHS = getLoc(L);
2966     SourceLocation RHS = getLoc(R);
2967     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
2968   }
2969 
2970   bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
2971     SourceLocation LHS = getLoc(L);
2972     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
2973   }
2974 
2975   bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
2976     SourceLocation RHS = getLoc(R);
2977     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
2978   }
2979 
2980   SourceLocation getLoc(const PPEntityOffset &PPE) const {
2981     return Reader.ReadSourceLocation(M, PPE.*PPLoc);
2982   }
2983 };
2984 
2985 }
2986 
2987 /// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
2988 PreprocessedEntityID
2989 ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
2990   if (SourceMgr.isLocalSourceLocation(BLoc))
2991     return getTotalNumPreprocessedEntities();
2992 
2993   GlobalSLocOffsetMapType::const_iterator
2994     SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
2995                                         BLoc.getOffset());
2996   assert(SLocMapI != GlobalSLocOffsetMap.end() &&
2997          "Corrupted global sloc offset map");
2998 
2999   if (SLocMapI->second->NumPreprocessedEntities == 0)
3000     return findNextPreprocessedEntity(SLocMapI);
3001 
3002   Module &M = *SLocMapI->second;
3003   typedef const PPEntityOffset *pp_iterator;
3004   pp_iterator pp_begin = M.PreprocessedEntityOffsets;
3005   pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
3006 
3007   size_t Count = M.NumPreprocessedEntities;
3008   size_t Half;
3009   pp_iterator First = pp_begin;
3010   pp_iterator PPI;
3011 
3012   // Do a binary search manually instead of using std::lower_bound because
3013   // The end locations of entities may be unordered (when a macro expansion
3014   // is inside another macro argument), but for this case it is not important
3015   // whether we get the first macro expansion or its containing macro.
3016   while (Count > 0) {
3017     Half = Count/2;
3018     PPI = First;
3019     std::advance(PPI, Half);
3020     if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
3021                                             BLoc)){
3022       First = PPI;
3023       ++First;
3024       Count = Count - Half - 1;
3025     } else
3026       Count = Half;
3027   }
3028 
3029   if (PPI == pp_end)
3030     return findNextPreprocessedEntity(SLocMapI);
3031 
3032   return getGlobalPreprocessedEntityID(M,
3033                                  M.BasePreprocessedEntityID + (PPI - pp_begin));
3034 }
3035 
3036 /// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
3037 PreprocessedEntityID
3038 ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
3039   if (SourceMgr.isLocalSourceLocation(ELoc))
3040     return getTotalNumPreprocessedEntities();
3041 
3042   GlobalSLocOffsetMapType::const_iterator
3043     SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
3044                                         ELoc.getOffset());
3045   assert(SLocMapI != GlobalSLocOffsetMap.end() &&
3046          "Corrupted global sloc offset map");
3047 
3048   if (SLocMapI->second->NumPreprocessedEntities == 0)
3049     return findNextPreprocessedEntity(SLocMapI);
3050 
3051   Module &M = *SLocMapI->second;
3052   typedef const PPEntityOffset *pp_iterator;
3053   pp_iterator pp_begin = M.PreprocessedEntityOffsets;
3054   pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
3055   pp_iterator PPI =
3056       std::upper_bound(pp_begin, pp_end, ELoc,
3057                        PPEntityComp<&PPEntityOffset::Begin>(*this, M));
3058 
3059   if (PPI == pp_end)
3060     return findNextPreprocessedEntity(SLocMapI);
3061 
3062   return getGlobalPreprocessedEntityID(M,
3063                                  M.BasePreprocessedEntityID + (PPI - pp_begin));
3064 }
3065 
3066 /// \brief Returns a pair of [Begin, End) indices of preallocated
3067 /// preprocessed entities that \arg Range encompasses.
3068 std::pair<unsigned, unsigned>
3069     ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
3070   if (Range.isInvalid())
3071     return std::make_pair(0,0);
3072   assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
3073 
3074   PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
3075   PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
3076   return std::make_pair(BeginID, EndID);
3077 }
3078 
3079 /// \brief Optionally returns true or false if the preallocated preprocessed
3080 /// entity with index \arg Index came from file \arg FID.
3081 llvm::Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
3082                                                              FileID FID) {
3083   if (FID.isInvalid())
3084     return false;
3085 
3086   std::pair<Module *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
3087   Module &M = *PPInfo.first;
3088   unsigned LocalIndex = PPInfo.second;
3089   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
3090 
3091   SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
3092   if (Loc.isInvalid())
3093     return false;
3094 
3095   if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
3096     return true;
3097   else
3098     return false;
3099 }
3100 
3101 namespace {
3102   /// \brief Visitor used to search for information about a header file.
3103   class HeaderFileInfoVisitor {
3104     ASTReader &Reader;
3105     const FileEntry *FE;
3106 
3107     llvm::Optional<HeaderFileInfo> HFI;
3108 
3109   public:
3110     HeaderFileInfoVisitor(ASTReader &Reader, const FileEntry *FE)
3111       : Reader(Reader), FE(FE) { }
3112 
3113     static bool visit(Module &M, void *UserData) {
3114       HeaderFileInfoVisitor *This
3115         = static_cast<HeaderFileInfoVisitor *>(UserData);
3116 
3117       HeaderFileInfoTrait Trait(This->Reader, M,
3118                                 &This->Reader.getPreprocessor().getHeaderSearchInfo(),
3119                                 M.HeaderFileFrameworkStrings,
3120                                 This->FE->getName());
3121 
3122       HeaderFileInfoLookupTable *Table
3123         = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
3124       if (!Table)
3125         return false;
3126 
3127       // Look in the on-disk hash table for an entry for this file name.
3128       HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE->getName(),
3129                                                             &Trait);
3130       if (Pos == Table->end())
3131         return false;
3132 
3133       This->HFI = *Pos;
3134       return true;
3135     }
3136 
3137     llvm::Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
3138   };
3139 }
3140 
3141 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
3142   HeaderFileInfoVisitor Visitor(*this, FE);
3143   ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
3144   if (llvm::Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) {
3145     if (Listener)
3146       Listener->ReadHeaderFileInfo(*HFI, FE->getUID());
3147     return *HFI;
3148   }
3149 
3150   return HeaderFileInfo();
3151 }
3152 
3153 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
3154   for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
3155     Module &F = *(*I);
3156     unsigned Idx = 0;
3157     while (Idx < F.PragmaDiagMappings.size()) {
3158       SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
3159       Diag.DiagStates.push_back(*Diag.GetCurDiagState());
3160       Diag.DiagStatePoints.push_back(
3161           DiagnosticsEngine::DiagStatePoint(&Diag.DiagStates.back(),
3162                                             FullSourceLoc(Loc, SourceMgr)));
3163       while (1) {
3164         assert(Idx < F.PragmaDiagMappings.size() &&
3165                "Invalid data, didn't find '-1' marking end of diag/map pairs");
3166         if (Idx >= F.PragmaDiagMappings.size()) {
3167           break; // Something is messed up but at least avoid infinite loop in
3168                  // release build.
3169         }
3170         unsigned DiagID = F.PragmaDiagMappings[Idx++];
3171         if (DiagID == (unsigned)-1) {
3172           break; // no more diag/map pairs for this location.
3173         }
3174         diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
3175         DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
3176         Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
3177       }
3178     }
3179   }
3180 }
3181 
3182 /// \brief Get the correct cursor and offset for loading a type.
3183 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
3184   GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
3185   assert(I != GlobalTypeMap.end() && "Corrupted global type map");
3186   Module *M = I->second;
3187   return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
3188 }
3189 
3190 /// \brief Read and return the type with the given index..
3191 ///
3192 /// The index is the type ID, shifted and minus the number of predefs. This
3193 /// routine actually reads the record corresponding to the type at the given
3194 /// location. It is a helper routine for GetType, which deals with reading type
3195 /// IDs.
3196 QualType ASTReader::readTypeRecord(unsigned Index) {
3197   RecordLocation Loc = TypeCursorForIndex(Index);
3198   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3199 
3200   // Keep track of where we are in the stream, then jump back there
3201   // after reading this type.
3202   SavedStreamPosition SavedPosition(DeclsCursor);
3203 
3204   ReadingKindTracker ReadingKind(Read_Type, *this);
3205 
3206   // Note that we are loading a type record.
3207   Deserializing AType(this);
3208 
3209   unsigned Idx = 0;
3210   DeclsCursor.JumpToBit(Loc.Offset);
3211   RecordData Record;
3212   unsigned Code = DeclsCursor.ReadCode();
3213   switch ((TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
3214   case TYPE_EXT_QUAL: {
3215     if (Record.size() != 2) {
3216       Error("Incorrect encoding of extended qualifier type");
3217       return QualType();
3218     }
3219     QualType Base = readType(*Loc.F, Record, Idx);
3220     Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
3221     return Context.getQualifiedType(Base, Quals);
3222   }
3223 
3224   case TYPE_COMPLEX: {
3225     if (Record.size() != 1) {
3226       Error("Incorrect encoding of complex type");
3227       return QualType();
3228     }
3229     QualType ElemType = readType(*Loc.F, Record, Idx);
3230     return Context.getComplexType(ElemType);
3231   }
3232 
3233   case TYPE_POINTER: {
3234     if (Record.size() != 1) {
3235       Error("Incorrect encoding of pointer type");
3236       return QualType();
3237     }
3238     QualType PointeeType = readType(*Loc.F, Record, Idx);
3239     return Context.getPointerType(PointeeType);
3240   }
3241 
3242   case TYPE_BLOCK_POINTER: {
3243     if (Record.size() != 1) {
3244       Error("Incorrect encoding of block pointer type");
3245       return QualType();
3246     }
3247     QualType PointeeType = readType(*Loc.F, Record, Idx);
3248     return Context.getBlockPointerType(PointeeType);
3249   }
3250 
3251   case TYPE_LVALUE_REFERENCE: {
3252     if (Record.size() != 2) {
3253       Error("Incorrect encoding of lvalue reference type");
3254       return QualType();
3255     }
3256     QualType PointeeType = readType(*Loc.F, Record, Idx);
3257     return Context.getLValueReferenceType(PointeeType, Record[1]);
3258   }
3259 
3260   case TYPE_RVALUE_REFERENCE: {
3261     if (Record.size() != 1) {
3262       Error("Incorrect encoding of rvalue reference type");
3263       return QualType();
3264     }
3265     QualType PointeeType = readType(*Loc.F, Record, Idx);
3266     return Context.getRValueReferenceType(PointeeType);
3267   }
3268 
3269   case TYPE_MEMBER_POINTER: {
3270     if (Record.size() != 2) {
3271       Error("Incorrect encoding of member pointer type");
3272       return QualType();
3273     }
3274     QualType PointeeType = readType(*Loc.F, Record, Idx);
3275     QualType ClassType = readType(*Loc.F, Record, Idx);
3276     if (PointeeType.isNull() || ClassType.isNull())
3277       return QualType();
3278 
3279     return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
3280   }
3281 
3282   case TYPE_CONSTANT_ARRAY: {
3283     QualType ElementType = readType(*Loc.F, Record, Idx);
3284     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3285     unsigned IndexTypeQuals = Record[2];
3286     unsigned Idx = 3;
3287     llvm::APInt Size = ReadAPInt(Record, Idx);
3288     return Context.getConstantArrayType(ElementType, Size,
3289                                          ASM, IndexTypeQuals);
3290   }
3291 
3292   case TYPE_INCOMPLETE_ARRAY: {
3293     QualType ElementType = readType(*Loc.F, Record, Idx);
3294     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3295     unsigned IndexTypeQuals = Record[2];
3296     return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
3297   }
3298 
3299   case TYPE_VARIABLE_ARRAY: {
3300     QualType ElementType = readType(*Loc.F, Record, Idx);
3301     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3302     unsigned IndexTypeQuals = Record[2];
3303     SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
3304     SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
3305     return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
3306                                          ASM, IndexTypeQuals,
3307                                          SourceRange(LBLoc, RBLoc));
3308   }
3309 
3310   case TYPE_VECTOR: {
3311     if (Record.size() != 3) {
3312       Error("incorrect encoding of vector type in AST file");
3313       return QualType();
3314     }
3315 
3316     QualType ElementType = readType(*Loc.F, Record, Idx);
3317     unsigned NumElements = Record[1];
3318     unsigned VecKind = Record[2];
3319     return Context.getVectorType(ElementType, NumElements,
3320                                   (VectorType::VectorKind)VecKind);
3321   }
3322 
3323   case TYPE_EXT_VECTOR: {
3324     if (Record.size() != 3) {
3325       Error("incorrect encoding of extended vector type in AST file");
3326       return QualType();
3327     }
3328 
3329     QualType ElementType = readType(*Loc.F, Record, Idx);
3330     unsigned NumElements = Record[1];
3331     return Context.getExtVectorType(ElementType, NumElements);
3332   }
3333 
3334   case TYPE_FUNCTION_NO_PROTO: {
3335     if (Record.size() != 6) {
3336       Error("incorrect encoding of no-proto function type");
3337       return QualType();
3338     }
3339     QualType ResultType = readType(*Loc.F, Record, Idx);
3340     FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
3341                                (CallingConv)Record[4], Record[5]);
3342     return Context.getFunctionNoProtoType(ResultType, Info);
3343   }
3344 
3345   case TYPE_FUNCTION_PROTO: {
3346     QualType ResultType = readType(*Loc.F, Record, Idx);
3347 
3348     FunctionProtoType::ExtProtoInfo EPI;
3349     EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
3350                                         /*hasregparm*/ Record[2],
3351                                         /*regparm*/ Record[3],
3352                                         static_cast<CallingConv>(Record[4]),
3353                                         /*produces*/ Record[5]);
3354 
3355     unsigned Idx = 6;
3356     unsigned NumParams = Record[Idx++];
3357     SmallVector<QualType, 16> ParamTypes;
3358     for (unsigned I = 0; I != NumParams; ++I)
3359       ParamTypes.push_back(readType(*Loc.F, Record, Idx));
3360 
3361     EPI.Variadic = Record[Idx++];
3362     EPI.TypeQuals = Record[Idx++];
3363     EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
3364     ExceptionSpecificationType EST =
3365         static_cast<ExceptionSpecificationType>(Record[Idx++]);
3366     EPI.ExceptionSpecType = EST;
3367     if (EST == EST_Dynamic) {
3368       EPI.NumExceptions = Record[Idx++];
3369       SmallVector<QualType, 2> Exceptions;
3370       for (unsigned I = 0; I != EPI.NumExceptions; ++I)
3371         Exceptions.push_back(readType(*Loc.F, Record, Idx));
3372       EPI.Exceptions = Exceptions.data();
3373     } else if (EST == EST_ComputedNoexcept) {
3374       EPI.NoexceptExpr = ReadExpr(*Loc.F);
3375     }
3376     return Context.getFunctionType(ResultType, ParamTypes.data(), NumParams,
3377                                     EPI);
3378   }
3379 
3380   case TYPE_UNRESOLVED_USING: {
3381     unsigned Idx = 0;
3382     return Context.getTypeDeclType(
3383                   ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
3384   }
3385 
3386   case TYPE_TYPEDEF: {
3387     if (Record.size() != 2) {
3388       Error("incorrect encoding of typedef type");
3389       return QualType();
3390     }
3391     unsigned Idx = 0;
3392     TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
3393     QualType Canonical = readType(*Loc.F, Record, Idx);
3394     if (!Canonical.isNull())
3395       Canonical = Context.getCanonicalType(Canonical);
3396     return Context.getTypedefType(Decl, Canonical);
3397   }
3398 
3399   case TYPE_TYPEOF_EXPR:
3400     return Context.getTypeOfExprType(ReadExpr(*Loc.F));
3401 
3402   case TYPE_TYPEOF: {
3403     if (Record.size() != 1) {
3404       Error("incorrect encoding of typeof(type) in AST file");
3405       return QualType();
3406     }
3407     QualType UnderlyingType = readType(*Loc.F, Record, Idx);
3408     return Context.getTypeOfType(UnderlyingType);
3409   }
3410 
3411   case TYPE_DECLTYPE:
3412     return Context.getDecltypeType(ReadExpr(*Loc.F));
3413 
3414   case TYPE_UNARY_TRANSFORM: {
3415     QualType BaseType = readType(*Loc.F, Record, Idx);
3416     QualType UnderlyingType = readType(*Loc.F, Record, Idx);
3417     UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
3418     return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
3419   }
3420 
3421   case TYPE_AUTO:
3422     return Context.getAutoType(readType(*Loc.F, Record, Idx));
3423 
3424   case TYPE_RECORD: {
3425     if (Record.size() != 2) {
3426       Error("incorrect encoding of record type");
3427       return QualType();
3428     }
3429     unsigned Idx = 0;
3430     bool IsDependent = Record[Idx++];
3431     QualType T
3432       = Context.getRecordType(ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx));
3433     const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3434     return T;
3435   }
3436 
3437   case TYPE_ENUM: {
3438     if (Record.size() != 2) {
3439       Error("incorrect encoding of enum type");
3440       return QualType();
3441     }
3442     unsigned Idx = 0;
3443     bool IsDependent = Record[Idx++];
3444     QualType T
3445       = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
3446     const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3447     return T;
3448   }
3449 
3450   case TYPE_ATTRIBUTED: {
3451     if (Record.size() != 3) {
3452       Error("incorrect encoding of attributed type");
3453       return QualType();
3454     }
3455     QualType modifiedType = readType(*Loc.F, Record, Idx);
3456     QualType equivalentType = readType(*Loc.F, Record, Idx);
3457     AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
3458     return Context.getAttributedType(kind, modifiedType, equivalentType);
3459   }
3460 
3461   case TYPE_PAREN: {
3462     if (Record.size() != 1) {
3463       Error("incorrect encoding of paren type");
3464       return QualType();
3465     }
3466     QualType InnerType = readType(*Loc.F, Record, Idx);
3467     return Context.getParenType(InnerType);
3468   }
3469 
3470   case TYPE_PACK_EXPANSION: {
3471     if (Record.size() != 2) {
3472       Error("incorrect encoding of pack expansion type");
3473       return QualType();
3474     }
3475     QualType Pattern = readType(*Loc.F, Record, Idx);
3476     if (Pattern.isNull())
3477       return QualType();
3478     llvm::Optional<unsigned> NumExpansions;
3479     if (Record[1])
3480       NumExpansions = Record[1] - 1;
3481     return Context.getPackExpansionType(Pattern, NumExpansions);
3482   }
3483 
3484   case TYPE_ELABORATED: {
3485     unsigned Idx = 0;
3486     ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3487     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
3488     QualType NamedType = readType(*Loc.F, Record, Idx);
3489     return Context.getElaboratedType(Keyword, NNS, NamedType);
3490   }
3491 
3492   case TYPE_OBJC_INTERFACE: {
3493     unsigned Idx = 0;
3494     ObjCInterfaceDecl *ItfD
3495       = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
3496     return Context.getObjCInterfaceType(ItfD);
3497   }
3498 
3499   case TYPE_OBJC_OBJECT: {
3500     unsigned Idx = 0;
3501     QualType Base = readType(*Loc.F, Record, Idx);
3502     unsigned NumProtos = Record[Idx++];
3503     SmallVector<ObjCProtocolDecl*, 4> Protos;
3504     for (unsigned I = 0; I != NumProtos; ++I)
3505       Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
3506     return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
3507   }
3508 
3509   case TYPE_OBJC_OBJECT_POINTER: {
3510     unsigned Idx = 0;
3511     QualType Pointee = readType(*Loc.F, Record, Idx);
3512     return Context.getObjCObjectPointerType(Pointee);
3513   }
3514 
3515   case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
3516     unsigned Idx = 0;
3517     QualType Parm = readType(*Loc.F, Record, Idx);
3518     QualType Replacement = readType(*Loc.F, Record, Idx);
3519     return
3520       Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
3521                                             Replacement);
3522   }
3523 
3524   case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
3525     unsigned Idx = 0;
3526     QualType Parm = readType(*Loc.F, Record, Idx);
3527     TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
3528     return Context.getSubstTemplateTypeParmPackType(
3529                                                cast<TemplateTypeParmType>(Parm),
3530                                                      ArgPack);
3531   }
3532 
3533   case TYPE_INJECTED_CLASS_NAME: {
3534     CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
3535     QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
3536     // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
3537     // for AST reading, too much interdependencies.
3538     return
3539       QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
3540   }
3541 
3542   case TYPE_TEMPLATE_TYPE_PARM: {
3543     unsigned Idx = 0;
3544     unsigned Depth = Record[Idx++];
3545     unsigned Index = Record[Idx++];
3546     bool Pack = Record[Idx++];
3547     TemplateTypeParmDecl *D
3548       = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
3549     return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
3550   }
3551 
3552   case TYPE_DEPENDENT_NAME: {
3553     unsigned Idx = 0;
3554     ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3555     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
3556     const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
3557     QualType Canon = readType(*Loc.F, Record, Idx);
3558     if (!Canon.isNull())
3559       Canon = Context.getCanonicalType(Canon);
3560     return Context.getDependentNameType(Keyword, NNS, Name, Canon);
3561   }
3562 
3563   case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
3564     unsigned Idx = 0;
3565     ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3566     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
3567     const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
3568     unsigned NumArgs = Record[Idx++];
3569     SmallVector<TemplateArgument, 8> Args;
3570     Args.reserve(NumArgs);
3571     while (NumArgs--)
3572       Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
3573     return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
3574                                                       Args.size(), Args.data());
3575   }
3576 
3577   case TYPE_DEPENDENT_SIZED_ARRAY: {
3578     unsigned Idx = 0;
3579 
3580     // ArrayType
3581     QualType ElementType = readType(*Loc.F, Record, Idx);
3582     ArrayType::ArraySizeModifier ASM
3583       = (ArrayType::ArraySizeModifier)Record[Idx++];
3584     unsigned IndexTypeQuals = Record[Idx++];
3585 
3586     // DependentSizedArrayType
3587     Expr *NumElts = ReadExpr(*Loc.F);
3588     SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
3589 
3590     return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
3591                                                IndexTypeQuals, Brackets);
3592   }
3593 
3594   case TYPE_TEMPLATE_SPECIALIZATION: {
3595     unsigned Idx = 0;
3596     bool IsDependent = Record[Idx++];
3597     TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
3598     SmallVector<TemplateArgument, 8> Args;
3599     ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
3600     QualType Underlying = readType(*Loc.F, Record, Idx);
3601     QualType T;
3602     if (Underlying.isNull())
3603       T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
3604                                                           Args.size());
3605     else
3606       T = Context.getTemplateSpecializationType(Name, Args.data(),
3607                                                  Args.size(), Underlying);
3608     const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3609     return T;
3610   }
3611 
3612   case TYPE_ATOMIC: {
3613     if (Record.size() != 1) {
3614       Error("Incorrect encoding of atomic type");
3615       return QualType();
3616     }
3617     QualType ValueType = readType(*Loc.F, Record, Idx);
3618     return Context.getAtomicType(ValueType);
3619   }
3620   }
3621   // Suppress a GCC warning
3622   return QualType();
3623 }
3624 
3625 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
3626   ASTReader &Reader;
3627   Module &F;
3628   llvm::BitstreamCursor &DeclsCursor;
3629   const ASTReader::RecordData &Record;
3630   unsigned &Idx;
3631 
3632   SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
3633                                     unsigned &I) {
3634     return Reader.ReadSourceLocation(F, R, I);
3635   }
3636 
3637   template<typename T>
3638   T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
3639     return Reader.ReadDeclAs<T>(F, Record, Idx);
3640   }
3641 
3642 public:
3643   TypeLocReader(ASTReader &Reader, Module &F,
3644                 const ASTReader::RecordData &Record, unsigned &Idx)
3645     : Reader(Reader), F(F), DeclsCursor(F.DeclsCursor), Record(Record), Idx(Idx)
3646   { }
3647 
3648   // We want compile-time assurance that we've enumerated all of
3649   // these, so unfortunately we have to declare them first, then
3650   // define them out-of-line.
3651 #define ABSTRACT_TYPELOC(CLASS, PARENT)
3652 #define TYPELOC(CLASS, PARENT) \
3653   void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
3654 #include "clang/AST/TypeLocNodes.def"
3655 
3656   void VisitFunctionTypeLoc(FunctionTypeLoc);
3657   void VisitArrayTypeLoc(ArrayTypeLoc);
3658 };
3659 
3660 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3661   // nothing to do
3662 }
3663 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3664   TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
3665   if (TL.needsExtraLocalData()) {
3666     TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
3667     TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
3668     TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
3669     TL.setModeAttr(Record[Idx++]);
3670   }
3671 }
3672 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
3673   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3674 }
3675 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
3676   TL.setStarLoc(ReadSourceLocation(Record, Idx));
3677 }
3678 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3679   TL.setCaretLoc(ReadSourceLocation(Record, Idx));
3680 }
3681 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3682   TL.setAmpLoc(ReadSourceLocation(Record, Idx));
3683 }
3684 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3685   TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
3686 }
3687 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3688   TL.setStarLoc(ReadSourceLocation(Record, Idx));
3689   TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
3690 }
3691 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
3692   TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
3693   TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
3694   if (Record[Idx++])
3695     TL.setSizeExpr(Reader.ReadExpr(F));
3696   else
3697     TL.setSizeExpr(0);
3698 }
3699 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
3700   VisitArrayTypeLoc(TL);
3701 }
3702 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
3703   VisitArrayTypeLoc(TL);
3704 }
3705 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
3706   VisitArrayTypeLoc(TL);
3707 }
3708 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
3709                                             DependentSizedArrayTypeLoc TL) {
3710   VisitArrayTypeLoc(TL);
3711 }
3712 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
3713                                         DependentSizedExtVectorTypeLoc TL) {
3714   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3715 }
3716 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
3717   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3718 }
3719 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
3720   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3721 }
3722 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3723   TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
3724   TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
3725   TL.setTrailingReturn(Record[Idx++]);
3726   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
3727     TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
3728   }
3729 }
3730 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
3731   VisitFunctionTypeLoc(TL);
3732 }
3733 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
3734   VisitFunctionTypeLoc(TL);
3735 }
3736 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
3737   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3738 }
3739 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3740   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3741 }
3742 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3743   TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
3744   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3745   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3746 }
3747 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3748   TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
3749   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3750   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3751   TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
3752 }
3753 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
3754   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3755 }
3756 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
3757   TL.setKWLoc(ReadSourceLocation(Record, Idx));
3758   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3759   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3760   TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
3761 }
3762 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
3763   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3764 }
3765 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
3766   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3767 }
3768 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
3769   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3770 }
3771 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3772   TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
3773   if (TL.hasAttrOperand()) {
3774     SourceRange range;
3775     range.setBegin(ReadSourceLocation(Record, Idx));
3776     range.setEnd(ReadSourceLocation(Record, Idx));
3777     TL.setAttrOperandParensRange(range);
3778   }
3779   if (TL.hasAttrExprOperand()) {
3780     if (Record[Idx++])
3781       TL.setAttrExprOperand(Reader.ReadExpr(F));
3782     else
3783       TL.setAttrExprOperand(0);
3784   } else if (TL.hasAttrEnumOperand())
3785     TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
3786 }
3787 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3788   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3789 }
3790 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
3791                                             SubstTemplateTypeParmTypeLoc TL) {
3792   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3793 }
3794 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
3795                                           SubstTemplateTypeParmPackTypeLoc TL) {
3796   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3797 }
3798 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
3799                                            TemplateSpecializationTypeLoc TL) {
3800   TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
3801   TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3802   TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3803   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3804     TL.setArgLocInfo(i,
3805         Reader.GetTemplateArgumentLocInfo(F,
3806                                           TL.getTypePtr()->getArg(i).getKind(),
3807                                           Record, Idx));
3808 }
3809 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
3810   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3811   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3812 }
3813 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3814   TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3815   TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
3816 }
3817 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
3818   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3819 }
3820 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
3821   TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3822   TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
3823   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3824 }
3825 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
3826        DependentTemplateSpecializationTypeLoc TL) {
3827   TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3828   TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
3829   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3830   TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3831   TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3832   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
3833     TL.setArgLocInfo(I,
3834         Reader.GetTemplateArgumentLocInfo(F,
3835                                           TL.getTypePtr()->getArg(I).getKind(),
3836                                           Record, Idx));
3837 }
3838 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
3839   TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
3840 }
3841 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3842   TL.setNameLoc(ReadSourceLocation(Record, Idx));
3843 }
3844 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3845   TL.setHasBaseTypeAsWritten(Record[Idx++]);
3846   TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3847   TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3848   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
3849     TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
3850 }
3851 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3852   TL.setStarLoc(ReadSourceLocation(Record, Idx));
3853 }
3854 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
3855   TL.setKWLoc(ReadSourceLocation(Record, Idx));
3856   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3857   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3858 }
3859 
3860 TypeSourceInfo *ASTReader::GetTypeSourceInfo(Module &F,
3861                                              const RecordData &Record,
3862                                              unsigned &Idx) {
3863   QualType InfoTy = readType(F, Record, Idx);
3864   if (InfoTy.isNull())
3865     return 0;
3866 
3867   TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
3868   TypeLocReader TLR(*this, F, Record, Idx);
3869   for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
3870     TLR.Visit(TL);
3871   return TInfo;
3872 }
3873 
3874 QualType ASTReader::GetType(TypeID ID) {
3875   unsigned FastQuals = ID & Qualifiers::FastMask;
3876   unsigned Index = ID >> Qualifiers::FastWidth;
3877 
3878   if (Index < NUM_PREDEF_TYPE_IDS) {
3879     QualType T;
3880     switch ((PredefinedTypeIDs)Index) {
3881     case PREDEF_TYPE_NULL_ID: return QualType();
3882     case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
3883     case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
3884 
3885     case PREDEF_TYPE_CHAR_U_ID:
3886     case PREDEF_TYPE_CHAR_S_ID:
3887       // FIXME: Check that the signedness of CharTy is correct!
3888       T = Context.CharTy;
3889       break;
3890 
3891     case PREDEF_TYPE_UCHAR_ID:      T = Context.UnsignedCharTy;     break;
3892     case PREDEF_TYPE_USHORT_ID:     T = Context.UnsignedShortTy;    break;
3893     case PREDEF_TYPE_UINT_ID:       T = Context.UnsignedIntTy;      break;
3894     case PREDEF_TYPE_ULONG_ID:      T = Context.UnsignedLongTy;     break;
3895     case PREDEF_TYPE_ULONGLONG_ID:  T = Context.UnsignedLongLongTy; break;
3896     case PREDEF_TYPE_UINT128_ID:    T = Context.UnsignedInt128Ty;   break;
3897     case PREDEF_TYPE_SCHAR_ID:      T = Context.SignedCharTy;       break;
3898     case PREDEF_TYPE_WCHAR_ID:      T = Context.WCharTy;            break;
3899     case PREDEF_TYPE_SHORT_ID:      T = Context.ShortTy;            break;
3900     case PREDEF_TYPE_INT_ID:        T = Context.IntTy;              break;
3901     case PREDEF_TYPE_LONG_ID:       T = Context.LongTy;             break;
3902     case PREDEF_TYPE_LONGLONG_ID:   T = Context.LongLongTy;         break;
3903     case PREDEF_TYPE_INT128_ID:     T = Context.Int128Ty;           break;
3904     case PREDEF_TYPE_HALF_ID:       T = Context.HalfTy;             break;
3905     case PREDEF_TYPE_FLOAT_ID:      T = Context.FloatTy;            break;
3906     case PREDEF_TYPE_DOUBLE_ID:     T = Context.DoubleTy;           break;
3907     case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy;       break;
3908     case PREDEF_TYPE_OVERLOAD_ID:   T = Context.OverloadTy;         break;
3909     case PREDEF_TYPE_BOUND_MEMBER:  T = Context.BoundMemberTy;      break;
3910     case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy;     break;
3911     case PREDEF_TYPE_DEPENDENT_ID:  T = Context.DependentTy;        break;
3912     case PREDEF_TYPE_UNKNOWN_ANY:   T = Context.UnknownAnyTy;       break;
3913     case PREDEF_TYPE_NULLPTR_ID:    T = Context.NullPtrTy;          break;
3914     case PREDEF_TYPE_CHAR16_ID:     T = Context.Char16Ty;           break;
3915     case PREDEF_TYPE_CHAR32_ID:     T = Context.Char32Ty;           break;
3916     case PREDEF_TYPE_OBJC_ID:       T = Context.ObjCBuiltinIdTy;    break;
3917     case PREDEF_TYPE_OBJC_CLASS:    T = Context.ObjCBuiltinClassTy; break;
3918     case PREDEF_TYPE_OBJC_SEL:      T = Context.ObjCBuiltinSelTy;   break;
3919     case PREDEF_TYPE_AUTO_DEDUCT:   T = Context.getAutoDeductType(); break;
3920 
3921     case PREDEF_TYPE_AUTO_RREF_DEDUCT:
3922       T = Context.getAutoRRefDeductType();
3923       break;
3924 
3925     case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
3926       T = Context.ARCUnbridgedCastTy;
3927       break;
3928 
3929     }
3930 
3931     assert(!T.isNull() && "Unknown predefined type");
3932     return T.withFastQualifiers(FastQuals);
3933   }
3934 
3935   Index -= NUM_PREDEF_TYPE_IDS;
3936   assert(Index < TypesLoaded.size() && "Type index out-of-range");
3937   if (TypesLoaded[Index].isNull()) {
3938     TypesLoaded[Index] = readTypeRecord(Index);
3939     if (TypesLoaded[Index].isNull())
3940       return QualType();
3941 
3942     TypesLoaded[Index]->setFromAST();
3943     if (DeserializationListener)
3944       DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
3945                                         TypesLoaded[Index]);
3946   }
3947 
3948   return TypesLoaded[Index].withFastQualifiers(FastQuals);
3949 }
3950 
3951 QualType ASTReader::getLocalType(Module &F, unsigned LocalID) {
3952   return GetType(getGlobalTypeID(F, LocalID));
3953 }
3954 
3955 serialization::TypeID
3956 ASTReader::getGlobalTypeID(Module &F, unsigned LocalID) const {
3957   unsigned FastQuals = LocalID & Qualifiers::FastMask;
3958   unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
3959 
3960   if (LocalIndex < NUM_PREDEF_TYPE_IDS)
3961     return LocalID;
3962 
3963   ContinuousRangeMap<uint32_t, int, 2>::iterator I
3964     = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
3965   assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
3966 
3967   unsigned GlobalIndex = LocalIndex + I->second;
3968   return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
3969 }
3970 
3971 TemplateArgumentLocInfo
3972 ASTReader::GetTemplateArgumentLocInfo(Module &F,
3973                                       TemplateArgument::ArgKind Kind,
3974                                       const RecordData &Record,
3975                                       unsigned &Index) {
3976   switch (Kind) {
3977   case TemplateArgument::Expression:
3978     return ReadExpr(F);
3979   case TemplateArgument::Type:
3980     return GetTypeSourceInfo(F, Record, Index);
3981   case TemplateArgument::Template: {
3982     NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
3983                                                                      Index);
3984     SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
3985     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
3986                                    SourceLocation());
3987   }
3988   case TemplateArgument::TemplateExpansion: {
3989     NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
3990                                                                      Index);
3991     SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
3992     SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
3993     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
3994                                    EllipsisLoc);
3995   }
3996   case TemplateArgument::Null:
3997   case TemplateArgument::Integral:
3998   case TemplateArgument::Declaration:
3999   case TemplateArgument::Pack:
4000     return TemplateArgumentLocInfo();
4001   }
4002   llvm_unreachable("unexpected template argument loc");
4003   return TemplateArgumentLocInfo();
4004 }
4005 
4006 TemplateArgumentLoc
4007 ASTReader::ReadTemplateArgumentLoc(Module &F,
4008                                    const RecordData &Record, unsigned &Index) {
4009   TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
4010 
4011   if (Arg.getKind() == TemplateArgument::Expression) {
4012     if (Record[Index++]) // bool InfoHasSameExpr.
4013       return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
4014   }
4015   return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
4016                                                              Record, Index));
4017 }
4018 
4019 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
4020   return GetDecl(ID);
4021 }
4022 
4023 uint64_t ASTReader::readCXXBaseSpecifiers(Module &M, const RecordData &Record,
4024                                           unsigned &Idx){
4025   if (Idx >= Record.size())
4026     return 0;
4027 
4028   unsigned LocalID = Record[Idx++];
4029   return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
4030 }
4031 
4032 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
4033   RecordLocation Loc = getLocalBitOffset(Offset);
4034   llvm::BitstreamCursor &Cursor = Loc.F->DeclsCursor;
4035   SavedStreamPosition SavedPosition(Cursor);
4036   Cursor.JumpToBit(Loc.Offset);
4037   ReadingKindTracker ReadingKind(Read_Decl, *this);
4038   RecordData Record;
4039   unsigned Code = Cursor.ReadCode();
4040   unsigned RecCode = Cursor.ReadRecord(Code, Record);
4041   if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
4042     Error("Malformed AST file: missing C++ base specifiers");
4043     return 0;
4044   }
4045 
4046   unsigned Idx = 0;
4047   unsigned NumBases = Record[Idx++];
4048   void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
4049   CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
4050   for (unsigned I = 0; I != NumBases; ++I)
4051     Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
4052   return Bases;
4053 }
4054 
4055 serialization::DeclID
4056 ASTReader::getGlobalDeclID(Module &F, unsigned LocalID) const {
4057   if (LocalID < NUM_PREDEF_DECL_IDS)
4058     return LocalID;
4059 
4060   ContinuousRangeMap<uint32_t, int, 2>::iterator I
4061     = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
4062   assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
4063 
4064   return LocalID + I->second;
4065 }
4066 
4067 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
4068                                    Module &M) const {
4069   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
4070   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
4071   return &M == I->second;
4072 }
4073 
4074 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
4075   if (ID < NUM_PREDEF_DECL_IDS)
4076     return SourceLocation();
4077 
4078   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
4079 
4080   if (Index > DeclsLoaded.size()) {
4081     Error("declaration ID out-of-range for AST file");
4082     return SourceLocation();
4083   }
4084 
4085   if (Decl *D = DeclsLoaded[Index])
4086     return D->getLocation();
4087 
4088   unsigned RawLocation = 0;
4089   RecordLocation Rec = DeclCursorForID(ID, RawLocation);
4090   return ReadSourceLocation(*Rec.F, RawLocation);
4091 }
4092 
4093 Decl *ASTReader::GetDecl(DeclID ID) {
4094   if (ID < NUM_PREDEF_DECL_IDS) {
4095     switch ((PredefinedDeclIDs)ID) {
4096     case PREDEF_DECL_NULL_ID:
4097       return 0;
4098 
4099     case PREDEF_DECL_TRANSLATION_UNIT_ID:
4100       return Context.getTranslationUnitDecl();
4101 
4102     case PREDEF_DECL_OBJC_ID_ID:
4103       return Context.getObjCIdDecl();
4104 
4105     case PREDEF_DECL_OBJC_SEL_ID:
4106       return Context.getObjCSelDecl();
4107 
4108     case PREDEF_DECL_OBJC_CLASS_ID:
4109       return Context.getObjCClassDecl();
4110 
4111     case PREDEF_DECL_INT_128_ID:
4112       return Context.getInt128Decl();
4113 
4114     case PREDEF_DECL_UNSIGNED_INT_128_ID:
4115       return Context.getUInt128Decl();
4116 
4117     case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
4118       return Context.getObjCInstanceTypeDecl();
4119     }
4120 
4121     return 0;
4122   }
4123 
4124   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
4125 
4126   if (Index > DeclsLoaded.size()) {
4127     Error("declaration ID out-of-range for AST file");
4128     return 0;
4129   }
4130 
4131 if (!DeclsLoaded[Index]) {
4132     ReadDeclRecord(ID);
4133     if (DeserializationListener)
4134       DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
4135   }
4136 
4137   return DeclsLoaded[Index];
4138 }
4139 
4140 serialization::DeclID ASTReader::ReadDeclID(Module &F,
4141                                             const RecordData &Record,
4142                                             unsigned &Idx) {
4143   if (Idx >= Record.size()) {
4144     Error("Corrupted AST file");
4145     return 0;
4146   }
4147 
4148   return getGlobalDeclID(F, Record[Idx++]);
4149 }
4150 
4151 /// \brief Resolve the offset of a statement into a statement.
4152 ///
4153 /// This operation will read a new statement from the external
4154 /// source each time it is called, and is meant to be used via a
4155 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
4156 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
4157   // Switch case IDs are per Decl.
4158   ClearSwitchCaseIDs();
4159 
4160   // Offset here is a global offset across the entire chain.
4161   RecordLocation Loc = getLocalBitOffset(Offset);
4162   Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
4163   return ReadStmtFromStream(*Loc.F);
4164 }
4165 
4166 namespace {
4167   class FindExternalLexicalDeclsVisitor {
4168     ASTReader &Reader;
4169     const DeclContext *DC;
4170     bool (*isKindWeWant)(Decl::Kind);
4171 
4172     SmallVectorImpl<Decl*> &Decls;
4173     bool PredefsVisited[NUM_PREDEF_DECL_IDS];
4174 
4175   public:
4176     FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
4177                                     bool (*isKindWeWant)(Decl::Kind),
4178                                     SmallVectorImpl<Decl*> &Decls)
4179       : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
4180     {
4181       for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
4182         PredefsVisited[I] = false;
4183     }
4184 
4185     static bool visit(Module &M, bool Preorder, void *UserData) {
4186       if (Preorder)
4187         return false;
4188 
4189       FindExternalLexicalDeclsVisitor *This
4190         = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
4191 
4192       Module::DeclContextInfosMap::iterator Info
4193         = M.DeclContextInfos.find(This->DC);
4194       if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
4195         return false;
4196 
4197       // Load all of the declaration IDs
4198       for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
4199                                *IDE = ID + Info->second.NumLexicalDecls;
4200            ID != IDE; ++ID) {
4201         if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
4202           continue;
4203 
4204         // Don't add predefined declarations to the lexical context more
4205         // than once.
4206         if (ID->second < NUM_PREDEF_DECL_IDS) {
4207           if (This->PredefsVisited[ID->second])
4208             continue;
4209 
4210           This->PredefsVisited[ID->second] = true;
4211         }
4212 
4213         if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
4214           if (!This->DC->isDeclInLexicalTraversal(D))
4215             This->Decls.push_back(D);
4216         }
4217       }
4218 
4219       return false;
4220     }
4221   };
4222 }
4223 
4224 ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
4225                                          bool (*isKindWeWant)(Decl::Kind),
4226                                          SmallVectorImpl<Decl*> &Decls) {
4227   // There might be lexical decls in multiple modules, for the TU at
4228   // least. Walk all of the modules in the order they were loaded.
4229   FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
4230   ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
4231   ++NumLexicalDeclContextsRead;
4232   return ELR_Success;
4233 }
4234 
4235 namespace {
4236 
4237 class DeclIDComp {
4238   ASTReader &Reader;
4239   Module &Mod;
4240 
4241 public:
4242   DeclIDComp(ASTReader &Reader, Module &M) : Reader(Reader), Mod(M) {}
4243 
4244   bool operator()(LocalDeclID L, LocalDeclID R) const {
4245     SourceLocation LHS = getLocation(L);
4246     SourceLocation RHS = getLocation(R);
4247     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4248   }
4249 
4250   bool operator()(SourceLocation LHS, LocalDeclID R) const {
4251     SourceLocation RHS = getLocation(R);
4252     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4253   }
4254 
4255   bool operator()(LocalDeclID L, SourceLocation RHS) const {
4256     SourceLocation LHS = getLocation(L);
4257     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4258   }
4259 
4260   SourceLocation getLocation(LocalDeclID ID) const {
4261     return Reader.getSourceManager().getFileLoc(
4262             Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
4263   }
4264 };
4265 
4266 }
4267 
4268 void ASTReader::FindFileRegionDecls(FileID File,
4269                                     unsigned Offset, unsigned Length,
4270                                     SmallVectorImpl<Decl *> &Decls) {
4271   SourceManager &SM = getSourceManager();
4272 
4273   llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
4274   if (I == FileDeclIDs.end())
4275     return;
4276 
4277   FileDeclsInfo &DInfo = I->second;
4278   if (DInfo.Decls.empty())
4279     return;
4280 
4281   SourceLocation
4282     BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
4283   SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
4284 
4285   DeclIDComp DIDComp(*this, *DInfo.Mod);
4286   ArrayRef<serialization::LocalDeclID>::iterator
4287     BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
4288                                BeginLoc, DIDComp);
4289   if (BeginIt != DInfo.Decls.begin())
4290     --BeginIt;
4291 
4292   ArrayRef<serialization::LocalDeclID>::iterator
4293     EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
4294                              EndLoc, DIDComp);
4295   if (EndIt != DInfo.Decls.end())
4296     ++EndIt;
4297 
4298   for (ArrayRef<serialization::LocalDeclID>::iterator
4299          DIt = BeginIt; DIt != EndIt; ++DIt)
4300     Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
4301 }
4302 
4303 namespace {
4304   /// \brief Module visitor used to perform name lookup into a
4305   /// declaration context.
4306   class DeclContextNameLookupVisitor {
4307     ASTReader &Reader;
4308     const DeclContext *DC;
4309     DeclarationName Name;
4310     SmallVectorImpl<NamedDecl *> &Decls;
4311 
4312   public:
4313     DeclContextNameLookupVisitor(ASTReader &Reader,
4314                                  const DeclContext *DC, DeclarationName Name,
4315                                  SmallVectorImpl<NamedDecl *> &Decls)
4316       : Reader(Reader), DC(DC), Name(Name), Decls(Decls) { }
4317 
4318     static bool visit(Module &M, void *UserData) {
4319       DeclContextNameLookupVisitor *This
4320         = static_cast<DeclContextNameLookupVisitor *>(UserData);
4321 
4322       // Check whether we have any visible declaration information for
4323       // this context in this module.
4324       Module::DeclContextInfosMap::iterator Info
4325         = M.DeclContextInfos.find(This->DC);
4326       if (Info == M.DeclContextInfos.end() || !Info->second.NameLookupTableData)
4327         return false;
4328 
4329       // Look for this name within this module.
4330       ASTDeclContextNameLookupTable *LookupTable =
4331         (ASTDeclContextNameLookupTable*)Info->second.NameLookupTableData;
4332       ASTDeclContextNameLookupTable::iterator Pos
4333         = LookupTable->find(This->Name);
4334       if (Pos == LookupTable->end())
4335         return false;
4336 
4337       bool FoundAnything = false;
4338       ASTDeclContextNameLookupTrait::data_type Data = *Pos;
4339       for (; Data.first != Data.second; ++Data.first) {
4340         NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
4341         if (!ND)
4342           continue;
4343 
4344         if (ND->getDeclName() != This->Name) {
4345           assert(!This->Name.getCXXNameType().isNull() &&
4346                  "Name mismatch without a type");
4347           continue;
4348         }
4349 
4350         // Record this declaration.
4351         FoundAnything = true;
4352         This->Decls.push_back(ND);
4353       }
4354 
4355       return FoundAnything;
4356     }
4357   };
4358 }
4359 
4360 DeclContext::lookup_result
4361 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
4362                                           DeclarationName Name) {
4363   assert(DC->hasExternalVisibleStorage() &&
4364          "DeclContext has no visible decls in storage");
4365   if (!Name)
4366     return DeclContext::lookup_result(DeclContext::lookup_iterator(0),
4367                                       DeclContext::lookup_iterator(0));
4368 
4369   SmallVector<NamedDecl *, 64> Decls;
4370   DeclContextNameLookupVisitor Visitor(*this, DC, Name, Decls);
4371   ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
4372   ++NumVisibleDeclContextsRead;
4373   SetExternalVisibleDeclsForName(DC, Name, Decls);
4374   return const_cast<DeclContext*>(DC)->lookup(Name);
4375 }
4376 
4377 /// \brief Under non-PCH compilation the consumer receives the objc methods
4378 /// before receiving the implementation, and codegen depends on this.
4379 /// We simulate this by deserializing and passing to consumer the methods of the
4380 /// implementation before passing the deserialized implementation decl.
4381 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
4382                                        ASTConsumer *Consumer) {
4383   assert(ImplD && Consumer);
4384 
4385   for (ObjCImplDecl::method_iterator
4386          I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
4387     Consumer->HandleInterestingDecl(DeclGroupRef(*I));
4388 
4389   Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
4390 }
4391 
4392 void ASTReader::PassInterestingDeclsToConsumer() {
4393   assert(Consumer);
4394   while (!InterestingDecls.empty()) {
4395     Decl *D = InterestingDecls.front();
4396     InterestingDecls.pop_front();
4397 
4398     if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
4399       PassObjCImplDeclToConsumer(ImplD, Consumer);
4400     else
4401       Consumer->HandleInterestingDecl(DeclGroupRef(D));
4402   }
4403 }
4404 
4405 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
4406   this->Consumer = Consumer;
4407 
4408   if (!Consumer)
4409     return;
4410 
4411   for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
4412     // Force deserialization of this decl, which will cause it to be queued for
4413     // passing to the consumer.
4414     GetDecl(ExternalDefinitions[I]);
4415   }
4416   ExternalDefinitions.clear();
4417 
4418   PassInterestingDeclsToConsumer();
4419 }
4420 
4421 void ASTReader::PrintStats() {
4422   std::fprintf(stderr, "*** AST File Statistics:\n");
4423 
4424   unsigned NumTypesLoaded
4425     = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
4426                                       QualType());
4427   unsigned NumDeclsLoaded
4428     = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
4429                                       (Decl *)0);
4430   unsigned NumIdentifiersLoaded
4431     = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
4432                                             IdentifiersLoaded.end(),
4433                                             (IdentifierInfo *)0);
4434   unsigned NumSelectorsLoaded
4435     = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
4436                                           SelectorsLoaded.end(),
4437                                           Selector());
4438 
4439   std::fprintf(stderr, "  %u stat cache hits\n", NumStatHits);
4440   std::fprintf(stderr, "  %u stat cache misses\n", NumStatMisses);
4441   if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
4442     std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
4443                  NumSLocEntriesRead, TotalNumSLocEntries,
4444                  ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
4445   if (!TypesLoaded.empty())
4446     std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
4447                  NumTypesLoaded, (unsigned)TypesLoaded.size(),
4448                  ((float)NumTypesLoaded/TypesLoaded.size() * 100));
4449   if (!DeclsLoaded.empty())
4450     std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
4451                  NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
4452                  ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
4453   if (!IdentifiersLoaded.empty())
4454     std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
4455                  NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
4456                  ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
4457   if (!SelectorsLoaded.empty())
4458     std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
4459                  NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
4460                  ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
4461   if (TotalNumStatements)
4462     std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
4463                  NumStatementsRead, TotalNumStatements,
4464                  ((float)NumStatementsRead/TotalNumStatements * 100));
4465   if (TotalNumMacros)
4466     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
4467                  NumMacrosRead, TotalNumMacros,
4468                  ((float)NumMacrosRead/TotalNumMacros * 100));
4469   if (TotalLexicalDeclContexts)
4470     std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
4471                  NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
4472                  ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
4473                   * 100));
4474   if (TotalVisibleDeclContexts)
4475     std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
4476                  NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
4477                  ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
4478                   * 100));
4479   if (TotalNumMethodPoolEntries) {
4480     std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
4481                  NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
4482                  ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
4483                   * 100));
4484     std::fprintf(stderr, "  %u method pool misses\n", NumMethodPoolMisses);
4485   }
4486   std::fprintf(stderr, "\n");
4487   dump();
4488   std::fprintf(stderr, "\n");
4489 }
4490 
4491 template<typename Key, typename Module, unsigned InitialCapacity>
4492 static void
4493 dumpModuleIDMap(StringRef Name,
4494                 const ContinuousRangeMap<Key, Module *,
4495                                          InitialCapacity> &Map) {
4496   if (Map.begin() == Map.end())
4497     return;
4498 
4499   typedef ContinuousRangeMap<Key, Module *, InitialCapacity> MapType;
4500   llvm::errs() << Name << ":\n";
4501   for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
4502        I != IEnd; ++I) {
4503     llvm::errs() << "  " << I->first << " -> " << I->second->FileName
4504       << "\n";
4505   }
4506 }
4507 
4508 void ASTReader::dump() {
4509   llvm::errs() << "*** PCH/Module Remappings:\n";
4510   dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
4511   dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
4512   dumpModuleIDMap("Global type map", GlobalTypeMap);
4513   dumpModuleIDMap("Global declaration map", GlobalDeclMap);
4514   dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
4515   dumpModuleIDMap("Global selector map", GlobalSelectorMap);
4516   dumpModuleIDMap("Global preprocessed entity map",
4517                   GlobalPreprocessedEntityMap);
4518 
4519   llvm::errs() << "\n*** PCH/Modules Loaded:";
4520   for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
4521                                        MEnd = ModuleMgr.end();
4522        M != MEnd; ++M)
4523     (*M)->dump();
4524 }
4525 
4526 /// Return the amount of memory used by memory buffers, breaking down
4527 /// by heap-backed versus mmap'ed memory.
4528 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
4529   for (ModuleConstIterator I = ModuleMgr.begin(),
4530       E = ModuleMgr.end(); I != E; ++I) {
4531     if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
4532       size_t bytes = buf->getBufferSize();
4533       switch (buf->getBufferKind()) {
4534         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
4535           sizes.malloc_bytes += bytes;
4536           break;
4537         case llvm::MemoryBuffer::MemoryBuffer_MMap:
4538           sizes.mmap_bytes += bytes;
4539           break;
4540       }
4541     }
4542   }
4543 }
4544 
4545 void ASTReader::InitializeSema(Sema &S) {
4546   SemaObj = &S;
4547   S.ExternalSource = this;
4548 
4549   // Makes sure any declarations that were deserialized "too early"
4550   // still get added to the identifier's declaration chains.
4551   for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
4552     SemaObj->pushExternalDeclIntoScope(PreloadedDecls[I],
4553                                        PreloadedDecls[I]->getDeclName());
4554   }
4555   PreloadedDecls.clear();
4556 
4557   // Load the offsets of the declarations that Sema references.
4558   // They will be lazily deserialized when needed.
4559   if (!SemaDeclRefs.empty()) {
4560     assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
4561     if (!SemaObj->StdNamespace)
4562       SemaObj->StdNamespace = SemaDeclRefs[0];
4563     if (!SemaObj->StdBadAlloc)
4564       SemaObj->StdBadAlloc = SemaDeclRefs[1];
4565   }
4566 
4567   if (!FPPragmaOptions.empty()) {
4568     assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
4569     SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
4570   }
4571 
4572   if (!OpenCLExtensions.empty()) {
4573     unsigned I = 0;
4574 #define OPENCLEXT(nm)  SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
4575 #include "clang/Basic/OpenCLExtensions.def"
4576 
4577     assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
4578   }
4579 }
4580 
4581 IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
4582   IdentifierLookupVisitor Visitor(StringRef(NameStart, NameEnd - NameStart));
4583   ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
4584   IdentifierInfo *II = Visitor.getIdentifierInfo();
4585   if (II)
4586     II->setOutOfDate(false);
4587   return II;
4588 }
4589 
4590 namespace clang {
4591   /// \brief An identifier-lookup iterator that enumerates all of the
4592   /// identifiers stored within a set of AST files.
4593   class ASTIdentifierIterator : public IdentifierIterator {
4594     /// \brief The AST reader whose identifiers are being enumerated.
4595     const ASTReader &Reader;
4596 
4597     /// \brief The current index into the chain of AST files stored in
4598     /// the AST reader.
4599     unsigned Index;
4600 
4601     /// \brief The current position within the identifier lookup table
4602     /// of the current AST file.
4603     ASTIdentifierLookupTable::key_iterator Current;
4604 
4605     /// \brief The end position within the identifier lookup table of
4606     /// the current AST file.
4607     ASTIdentifierLookupTable::key_iterator End;
4608 
4609   public:
4610     explicit ASTIdentifierIterator(const ASTReader &Reader);
4611 
4612     virtual StringRef Next();
4613   };
4614 }
4615 
4616 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
4617   : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
4618   ASTIdentifierLookupTable *IdTable
4619     = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
4620   Current = IdTable->key_begin();
4621   End = IdTable->key_end();
4622 }
4623 
4624 StringRef ASTIdentifierIterator::Next() {
4625   while (Current == End) {
4626     // If we have exhausted all of our AST files, we're done.
4627     if (Index == 0)
4628       return StringRef();
4629 
4630     --Index;
4631     ASTIdentifierLookupTable *IdTable
4632       = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
4633         IdentifierLookupTable;
4634     Current = IdTable->key_begin();
4635     End = IdTable->key_end();
4636   }
4637 
4638   // We have any identifiers remaining in the current AST file; return
4639   // the next one.
4640   std::pair<const char*, unsigned> Key = *Current;
4641   ++Current;
4642   return StringRef(Key.first, Key.second);
4643 }
4644 
4645 IdentifierIterator *ASTReader::getIdentifiers() const {
4646   return new ASTIdentifierIterator(*this);
4647 }
4648 
4649 namespace clang { namespace serialization {
4650   class ReadMethodPoolVisitor {
4651     ASTReader &Reader;
4652     Selector Sel;
4653     llvm::SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
4654     llvm::SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
4655 
4656     /// \brief Build an ObjCMethodList from a vector of Objective-C method
4657     /// declarations.
4658     ObjCMethodList
4659     buildObjCMethodList(const SmallVectorImpl<ObjCMethodDecl *> &Vec) const
4660     {
4661       ObjCMethodList List;
4662       ObjCMethodList *Prev = 0;
4663       for (unsigned I = 0, N = Vec.size(); I != N; ++I) {
4664         if (!List.Method) {
4665           // This is the first method, which is the easy case.
4666           List.Method = Vec[I];
4667           Prev = &List;
4668           continue;
4669         }
4670 
4671         ObjCMethodList *Mem =
4672           Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
4673         Prev->Next = new (Mem) ObjCMethodList(Vec[I], 0);
4674         Prev = Prev->Next;
4675       }
4676 
4677       return List;
4678     }
4679 
4680   public:
4681     ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel)
4682       : Reader(Reader), Sel(Sel) { }
4683 
4684     static bool visit(Module &M, void *UserData) {
4685       ReadMethodPoolVisitor *This
4686         = static_cast<ReadMethodPoolVisitor *>(UserData);
4687 
4688       if (!M.SelectorLookupTable)
4689         return false;
4690 
4691       ASTSelectorLookupTable *PoolTable
4692         = (ASTSelectorLookupTable*)M.SelectorLookupTable;
4693       ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
4694       if (Pos == PoolTable->end())
4695         return false;
4696 
4697       ++This->Reader.NumSelectorsRead;
4698       // FIXME: Not quite happy with the statistics here. We probably should
4699       // disable this tracking when called via LoadSelector.
4700       // Also, should entries without methods count as misses?
4701       ++This->Reader.NumMethodPoolEntriesRead;
4702       ASTSelectorLookupTrait::data_type Data = *Pos;
4703       if (This->Reader.DeserializationListener)
4704         This->Reader.DeserializationListener->SelectorRead(Data.ID,
4705                                                            This->Sel);
4706 
4707       This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
4708       This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
4709       return true;
4710     }
4711 
4712     /// \brief Retrieve the instance methods found by this visitor.
4713     ObjCMethodList getInstanceMethods() const {
4714       return buildObjCMethodList(InstanceMethods);
4715     }
4716 
4717     /// \brief Retrieve the instance methods found by this visitor.
4718     ObjCMethodList getFactoryMethods() const {
4719       return buildObjCMethodList(FactoryMethods);
4720     }
4721   };
4722 } } // end namespace clang::serialization
4723 
4724 std::pair<ObjCMethodList, ObjCMethodList>
4725 ASTReader::ReadMethodPool(Selector Sel) {
4726   ReadMethodPoolVisitor Visitor(*this, Sel);
4727   ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
4728   std::pair<ObjCMethodList, ObjCMethodList> Result;
4729   Result.first = Visitor.getInstanceMethods();
4730   Result.second = Visitor.getFactoryMethods();
4731 
4732   if (!Result.first.Method && !Result.second.Method)
4733     ++NumMethodPoolMisses;
4734   return Result;
4735 }
4736 
4737 void ASTReader::ReadKnownNamespaces(
4738                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
4739   Namespaces.clear();
4740 
4741   for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
4742     if (NamespaceDecl *Namespace
4743                 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
4744       Namespaces.push_back(Namespace);
4745   }
4746 }
4747 
4748 void ASTReader::ReadTentativeDefinitions(
4749                   SmallVectorImpl<VarDecl *> &TentativeDefs) {
4750   for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
4751     VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
4752     if (Var)
4753       TentativeDefs.push_back(Var);
4754   }
4755   TentativeDefinitions.clear();
4756 }
4757 
4758 void ASTReader::ReadUnusedFileScopedDecls(
4759                                SmallVectorImpl<const DeclaratorDecl *> &Decls) {
4760   for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
4761     DeclaratorDecl *D
4762       = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
4763     if (D)
4764       Decls.push_back(D);
4765   }
4766   UnusedFileScopedDecls.clear();
4767 }
4768 
4769 void ASTReader::ReadDelegatingConstructors(
4770                                  SmallVectorImpl<CXXConstructorDecl *> &Decls) {
4771   for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
4772     CXXConstructorDecl *D
4773       = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
4774     if (D)
4775       Decls.push_back(D);
4776   }
4777   DelegatingCtorDecls.clear();
4778 }
4779 
4780 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
4781   for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
4782     TypedefNameDecl *D
4783       = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
4784     if (D)
4785       Decls.push_back(D);
4786   }
4787   ExtVectorDecls.clear();
4788 }
4789 
4790 void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
4791   for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
4792     CXXRecordDecl *D
4793       = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
4794     if (D)
4795       Decls.push_back(D);
4796   }
4797   DynamicClasses.clear();
4798 }
4799 
4800 void
4801 ASTReader::ReadLocallyScopedExternalDecls(SmallVectorImpl<NamedDecl *> &Decls) {
4802   for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
4803     NamedDecl *D
4804       = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
4805     if (D)
4806       Decls.push_back(D);
4807   }
4808   LocallyScopedExternalDecls.clear();
4809 }
4810 
4811 void ASTReader::ReadReferencedSelectors(
4812        SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
4813   if (ReferencedSelectorsData.empty())
4814     return;
4815 
4816   // If there are @selector references added them to its pool. This is for
4817   // implementation of -Wselector.
4818   unsigned int DataSize = ReferencedSelectorsData.size()-1;
4819   unsigned I = 0;
4820   while (I < DataSize) {
4821     Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
4822     SourceLocation SelLoc
4823       = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
4824     Sels.push_back(std::make_pair(Sel, SelLoc));
4825   }
4826   ReferencedSelectorsData.clear();
4827 }
4828 
4829 void ASTReader::ReadWeakUndeclaredIdentifiers(
4830        SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
4831   if (WeakUndeclaredIdentifiers.empty())
4832     return;
4833 
4834   for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
4835     IdentifierInfo *WeakId
4836       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
4837     IdentifierInfo *AliasId
4838       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
4839     SourceLocation Loc
4840       = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
4841     bool Used = WeakUndeclaredIdentifiers[I++];
4842     WeakInfo WI(AliasId, Loc);
4843     WI.setUsed(Used);
4844     WeakIDs.push_back(std::make_pair(WeakId, WI));
4845   }
4846   WeakUndeclaredIdentifiers.clear();
4847 }
4848 
4849 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
4850   for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
4851     ExternalVTableUse VT;
4852     VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
4853     VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
4854     VT.DefinitionRequired = VTableUses[Idx++];
4855     VTables.push_back(VT);
4856   }
4857 
4858   VTableUses.clear();
4859 }
4860 
4861 void ASTReader::ReadPendingInstantiations(
4862        SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
4863   for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
4864     ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
4865     SourceLocation Loc
4866       = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
4867     Pending.push_back(std::make_pair(D, Loc));
4868   }
4869   PendingInstantiations.clear();
4870 }
4871 
4872 void ASTReader::LoadSelector(Selector Sel) {
4873   // It would be complicated to avoid reading the methods anyway. So don't.
4874   ReadMethodPool(Sel);
4875 }
4876 
4877 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
4878   assert(ID && "Non-zero identifier ID required");
4879   assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
4880   IdentifiersLoaded[ID - 1] = II;
4881   if (DeserializationListener)
4882     DeserializationListener->IdentifierRead(ID, II);
4883 }
4884 
4885 /// \brief Set the globally-visible declarations associated with the given
4886 /// identifier.
4887 ///
4888 /// If the AST reader is currently in a state where the given declaration IDs
4889 /// cannot safely be resolved, they are queued until it is safe to resolve
4890 /// them.
4891 ///
4892 /// \param II an IdentifierInfo that refers to one or more globally-visible
4893 /// declarations.
4894 ///
4895 /// \param DeclIDs the set of declaration IDs with the name @p II that are
4896 /// visible at global scope.
4897 ///
4898 /// \param Nonrecursive should be true to indicate that the caller knows that
4899 /// this call is non-recursive, and therefore the globally-visible declarations
4900 /// will not be placed onto the pending queue.
4901 void
4902 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
4903                               const SmallVectorImpl<uint32_t> &DeclIDs,
4904                                    bool Nonrecursive) {
4905   if (NumCurrentElementsDeserializing && !Nonrecursive) {
4906     PendingIdentifierInfos.push_back(PendingIdentifierInfo());
4907     PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
4908     PII.II = II;
4909     PII.DeclIDs.append(DeclIDs.begin(), DeclIDs.end());
4910     return;
4911   }
4912 
4913   for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
4914     NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
4915     if (SemaObj) {
4916       // Introduce this declaration into the translation-unit scope
4917       // and add it to the declaration chain for this identifier, so
4918       // that (unqualified) name lookup will find it.
4919       SemaObj->pushExternalDeclIntoScope(D, II);
4920     } else {
4921       // Queue this declaration so that it will be added to the
4922       // translation unit scope and identifier's declaration chain
4923       // once a Sema object is known.
4924       PreloadedDecls.push_back(D);
4925     }
4926   }
4927 }
4928 
4929 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
4930   if (ID == 0)
4931     return 0;
4932 
4933   if (IdentifiersLoaded.empty()) {
4934     Error("no identifier table in AST file");
4935     return 0;
4936   }
4937 
4938   ID -= 1;
4939   if (!IdentifiersLoaded[ID]) {
4940     GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
4941     assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
4942     Module *M = I->second;
4943     unsigned Index = ID - M->BaseIdentifierID;
4944     const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
4945 
4946     // All of the strings in the AST file are preceded by a 16-bit length.
4947     // Extract that 16-bit length to avoid having to execute strlen().
4948     // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
4949     //  unsigned integers.  This is important to avoid integer overflow when
4950     //  we cast them to 'unsigned'.
4951     const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
4952     unsigned StrLen = (((unsigned) StrLenPtr[0])
4953                        | (((unsigned) StrLenPtr[1]) << 8)) - 1;
4954     IdentifiersLoaded[ID]
4955       = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
4956     if (DeserializationListener)
4957       DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
4958   }
4959 
4960   return IdentifiersLoaded[ID];
4961 }
4962 
4963 IdentifierInfo *ASTReader::getLocalIdentifier(Module &M, unsigned LocalID) {
4964   return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
4965 }
4966 
4967 IdentifierID ASTReader::getGlobalIdentifierID(Module &M, unsigned LocalID) {
4968   if (LocalID < NUM_PREDEF_IDENT_IDS)
4969     return LocalID;
4970 
4971   ContinuousRangeMap<uint32_t, int, 2>::iterator I
4972     = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
4973   assert(I != M.IdentifierRemap.end()
4974          && "Invalid index into identifier index remap");
4975 
4976   return LocalID + I->second;
4977 }
4978 
4979 bool ASTReader::ReadSLocEntry(int ID) {
4980   return ReadSLocEntryRecord(ID) != Success;
4981 }
4982 
4983 Selector ASTReader::getLocalSelector(Module &M, unsigned LocalID) {
4984   return DecodeSelector(getGlobalSelectorID(M, LocalID));
4985 }
4986 
4987 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
4988   if (ID == 0)
4989     return Selector();
4990 
4991   if (ID > SelectorsLoaded.size()) {
4992     Error("selector ID out of range in AST file");
4993     return Selector();
4994   }
4995 
4996   if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
4997     // Load this selector from the selector table.
4998     GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
4999     assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
5000     Module &M = *I->second;
5001     ASTSelectorLookupTrait Trait(*this, M);
5002     unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
5003     SelectorsLoaded[ID - 1] =
5004       Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
5005     if (DeserializationListener)
5006       DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
5007   }
5008 
5009   return SelectorsLoaded[ID - 1];
5010 }
5011 
5012 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
5013   return DecodeSelector(ID);
5014 }
5015 
5016 uint32_t ASTReader::GetNumExternalSelectors() {
5017   // ID 0 (the null selector) is considered an external selector.
5018   return getTotalNumSelectors() + 1;
5019 }
5020 
5021 serialization::SelectorID
5022 ASTReader::getGlobalSelectorID(Module &M, unsigned LocalID) const {
5023   if (LocalID < NUM_PREDEF_SELECTOR_IDS)
5024     return LocalID;
5025 
5026   ContinuousRangeMap<uint32_t, int, 2>::iterator I
5027     = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
5028   assert(I != M.SelectorRemap.end()
5029          && "Invalid index into identifier index remap");
5030 
5031   return LocalID + I->second;
5032 }
5033 
5034 DeclarationName
5035 ASTReader::ReadDeclarationName(Module &F,
5036                                const RecordData &Record, unsigned &Idx) {
5037   DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
5038   switch (Kind) {
5039   case DeclarationName::Identifier:
5040     return DeclarationName(GetIdentifierInfo(F, Record, Idx));
5041 
5042   case DeclarationName::ObjCZeroArgSelector:
5043   case DeclarationName::ObjCOneArgSelector:
5044   case DeclarationName::ObjCMultiArgSelector:
5045     return DeclarationName(ReadSelector(F, Record, Idx));
5046 
5047   case DeclarationName::CXXConstructorName:
5048     return Context.DeclarationNames.getCXXConstructorName(
5049                           Context.getCanonicalType(readType(F, Record, Idx)));
5050 
5051   case DeclarationName::CXXDestructorName:
5052     return Context.DeclarationNames.getCXXDestructorName(
5053                           Context.getCanonicalType(readType(F, Record, Idx)));
5054 
5055   case DeclarationName::CXXConversionFunctionName:
5056     return Context.DeclarationNames.getCXXConversionFunctionName(
5057                           Context.getCanonicalType(readType(F, Record, Idx)));
5058 
5059   case DeclarationName::CXXOperatorName:
5060     return Context.DeclarationNames.getCXXOperatorName(
5061                                        (OverloadedOperatorKind)Record[Idx++]);
5062 
5063   case DeclarationName::CXXLiteralOperatorName:
5064     return Context.DeclarationNames.getCXXLiteralOperatorName(
5065                                        GetIdentifierInfo(F, Record, Idx));
5066 
5067   case DeclarationName::CXXUsingDirective:
5068     return DeclarationName::getUsingDirectiveName();
5069   }
5070 
5071   // Required to silence GCC warning
5072   return DeclarationName();
5073 }
5074 
5075 void ASTReader::ReadDeclarationNameLoc(Module &F,
5076                                        DeclarationNameLoc &DNLoc,
5077                                        DeclarationName Name,
5078                                       const RecordData &Record, unsigned &Idx) {
5079   switch (Name.getNameKind()) {
5080   case DeclarationName::CXXConstructorName:
5081   case DeclarationName::CXXDestructorName:
5082   case DeclarationName::CXXConversionFunctionName:
5083     DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
5084     break;
5085 
5086   case DeclarationName::CXXOperatorName:
5087     DNLoc.CXXOperatorName.BeginOpNameLoc
5088         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
5089     DNLoc.CXXOperatorName.EndOpNameLoc
5090         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
5091     break;
5092 
5093   case DeclarationName::CXXLiteralOperatorName:
5094     DNLoc.CXXLiteralOperatorName.OpNameLoc
5095         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
5096     break;
5097 
5098   case DeclarationName::Identifier:
5099   case DeclarationName::ObjCZeroArgSelector:
5100   case DeclarationName::ObjCOneArgSelector:
5101   case DeclarationName::ObjCMultiArgSelector:
5102   case DeclarationName::CXXUsingDirective:
5103     break;
5104   }
5105 }
5106 
5107 void ASTReader::ReadDeclarationNameInfo(Module &F,
5108                                         DeclarationNameInfo &NameInfo,
5109                                       const RecordData &Record, unsigned &Idx) {
5110   NameInfo.setName(ReadDeclarationName(F, Record, Idx));
5111   NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
5112   DeclarationNameLoc DNLoc;
5113   ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
5114   NameInfo.setInfo(DNLoc);
5115 }
5116 
5117 void ASTReader::ReadQualifierInfo(Module &F, QualifierInfo &Info,
5118                                   const RecordData &Record, unsigned &Idx) {
5119   Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
5120   unsigned NumTPLists = Record[Idx++];
5121   Info.NumTemplParamLists = NumTPLists;
5122   if (NumTPLists) {
5123     Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
5124     for (unsigned i=0; i != NumTPLists; ++i)
5125       Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
5126   }
5127 }
5128 
5129 TemplateName
5130 ASTReader::ReadTemplateName(Module &F, const RecordData &Record,
5131                             unsigned &Idx) {
5132   TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
5133   switch (Kind) {
5134   case TemplateName::Template:
5135       return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
5136 
5137   case TemplateName::OverloadedTemplate: {
5138     unsigned size = Record[Idx++];
5139     UnresolvedSet<8> Decls;
5140     while (size--)
5141       Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
5142 
5143     return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
5144   }
5145 
5146   case TemplateName::QualifiedTemplate: {
5147     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
5148     bool hasTemplKeyword = Record[Idx++];
5149     TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
5150     return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
5151   }
5152 
5153   case TemplateName::DependentTemplate: {
5154     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
5155     if (Record[Idx++])  // isIdentifier
5156       return Context.getDependentTemplateName(NNS,
5157                                                GetIdentifierInfo(F, Record,
5158                                                                  Idx));
5159     return Context.getDependentTemplateName(NNS,
5160                                          (OverloadedOperatorKind)Record[Idx++]);
5161   }
5162 
5163   case TemplateName::SubstTemplateTemplateParm: {
5164     TemplateTemplateParmDecl *param
5165       = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
5166     if (!param) return TemplateName();
5167     TemplateName replacement = ReadTemplateName(F, Record, Idx);
5168     return Context.getSubstTemplateTemplateParm(param, replacement);
5169   }
5170 
5171   case TemplateName::SubstTemplateTemplateParmPack: {
5172     TemplateTemplateParmDecl *Param
5173       = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
5174     if (!Param)
5175       return TemplateName();
5176 
5177     TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
5178     if (ArgPack.getKind() != TemplateArgument::Pack)
5179       return TemplateName();
5180 
5181     return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
5182   }
5183   }
5184 
5185   llvm_unreachable("Unhandled template name kind!");
5186 }
5187 
5188 TemplateArgument
5189 ASTReader::ReadTemplateArgument(Module &F,
5190                                 const RecordData &Record, unsigned &Idx) {
5191   TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
5192   switch (Kind) {
5193   case TemplateArgument::Null:
5194     return TemplateArgument();
5195   case TemplateArgument::Type:
5196     return TemplateArgument(readType(F, Record, Idx));
5197   case TemplateArgument::Declaration:
5198     return TemplateArgument(ReadDecl(F, Record, Idx));
5199   case TemplateArgument::Integral: {
5200     llvm::APSInt Value = ReadAPSInt(Record, Idx);
5201     QualType T = readType(F, Record, Idx);
5202     return TemplateArgument(Value, T);
5203   }
5204   case TemplateArgument::Template:
5205     return TemplateArgument(ReadTemplateName(F, Record, Idx));
5206   case TemplateArgument::TemplateExpansion: {
5207     TemplateName Name = ReadTemplateName(F, Record, Idx);
5208     llvm::Optional<unsigned> NumTemplateExpansions;
5209     if (unsigned NumExpansions = Record[Idx++])
5210       NumTemplateExpansions = NumExpansions - 1;
5211     return TemplateArgument(Name, NumTemplateExpansions);
5212   }
5213   case TemplateArgument::Expression:
5214     return TemplateArgument(ReadExpr(F));
5215   case TemplateArgument::Pack: {
5216     unsigned NumArgs = Record[Idx++];
5217     TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
5218     for (unsigned I = 0; I != NumArgs; ++I)
5219       Args[I] = ReadTemplateArgument(F, Record, Idx);
5220     return TemplateArgument(Args, NumArgs);
5221   }
5222   }
5223 
5224   llvm_unreachable("Unhandled template argument kind!");
5225 }
5226 
5227 TemplateParameterList *
5228 ASTReader::ReadTemplateParameterList(Module &F,
5229                                      const RecordData &Record, unsigned &Idx) {
5230   SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
5231   SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
5232   SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
5233 
5234   unsigned NumParams = Record[Idx++];
5235   SmallVector<NamedDecl *, 16> Params;
5236   Params.reserve(NumParams);
5237   while (NumParams--)
5238     Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
5239 
5240   TemplateParameterList* TemplateParams =
5241     TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
5242                                   Params.data(), Params.size(), RAngleLoc);
5243   return TemplateParams;
5244 }
5245 
5246 void
5247 ASTReader::
5248 ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
5249                          Module &F, const RecordData &Record,
5250                          unsigned &Idx) {
5251   unsigned NumTemplateArgs = Record[Idx++];
5252   TemplArgs.reserve(NumTemplateArgs);
5253   while (NumTemplateArgs--)
5254     TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
5255 }
5256 
5257 /// \brief Read a UnresolvedSet structure.
5258 void ASTReader::ReadUnresolvedSet(Module &F, UnresolvedSetImpl &Set,
5259                                   const RecordData &Record, unsigned &Idx) {
5260   unsigned NumDecls = Record[Idx++];
5261   while (NumDecls--) {
5262     NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
5263     AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
5264     Set.addDecl(D, AS);
5265   }
5266 }
5267 
5268 CXXBaseSpecifier
5269 ASTReader::ReadCXXBaseSpecifier(Module &F,
5270                                 const RecordData &Record, unsigned &Idx) {
5271   bool isVirtual = static_cast<bool>(Record[Idx++]);
5272   bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
5273   AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
5274   bool inheritConstructors = static_cast<bool>(Record[Idx++]);
5275   TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
5276   SourceRange Range = ReadSourceRange(F, Record, Idx);
5277   SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
5278   CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
5279                           EllipsisLoc);
5280   Result.setInheritConstructors(inheritConstructors);
5281   return Result;
5282 }
5283 
5284 std::pair<CXXCtorInitializer **, unsigned>
5285 ASTReader::ReadCXXCtorInitializers(Module &F, const RecordData &Record,
5286                                    unsigned &Idx) {
5287   CXXCtorInitializer **CtorInitializers = 0;
5288   unsigned NumInitializers = Record[Idx++];
5289   if (NumInitializers) {
5290     CtorInitializers
5291         = new (Context) CXXCtorInitializer*[NumInitializers];
5292     for (unsigned i=0; i != NumInitializers; ++i) {
5293       TypeSourceInfo *TInfo = 0;
5294       bool IsBaseVirtual = false;
5295       FieldDecl *Member = 0;
5296       IndirectFieldDecl *IndirectMember = 0;
5297 
5298       CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
5299       switch (Type) {
5300       case CTOR_INITIALIZER_BASE:
5301         TInfo = GetTypeSourceInfo(F, Record, Idx);
5302         IsBaseVirtual = Record[Idx++];
5303         break;
5304 
5305       case CTOR_INITIALIZER_DELEGATING:
5306         TInfo = GetTypeSourceInfo(F, Record, Idx);
5307         break;
5308 
5309        case CTOR_INITIALIZER_MEMBER:
5310         Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
5311         break;
5312 
5313        case CTOR_INITIALIZER_INDIRECT_MEMBER:
5314         IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
5315         break;
5316       }
5317 
5318       SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
5319       Expr *Init = ReadExpr(F);
5320       SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
5321       SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
5322       bool IsWritten = Record[Idx++];
5323       unsigned SourceOrderOrNumArrayIndices;
5324       SmallVector<VarDecl *, 8> Indices;
5325       if (IsWritten) {
5326         SourceOrderOrNumArrayIndices = Record[Idx++];
5327       } else {
5328         SourceOrderOrNumArrayIndices = Record[Idx++];
5329         Indices.reserve(SourceOrderOrNumArrayIndices);
5330         for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
5331           Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
5332       }
5333 
5334       CXXCtorInitializer *BOMInit;
5335       if (Type == CTOR_INITIALIZER_BASE) {
5336         BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
5337                                              LParenLoc, Init, RParenLoc,
5338                                              MemberOrEllipsisLoc);
5339       } else if (Type == CTOR_INITIALIZER_DELEGATING) {
5340         BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
5341                                                    Init, RParenLoc);
5342       } else if (IsWritten) {
5343         if (Member)
5344           BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
5345                                                LParenLoc, Init, RParenLoc);
5346         else
5347           BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
5348                                                MemberOrEllipsisLoc, LParenLoc,
5349                                                Init, RParenLoc);
5350       } else {
5351         BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
5352                                              LParenLoc, Init, RParenLoc,
5353                                              Indices.data(), Indices.size());
5354       }
5355 
5356       if (IsWritten)
5357         BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
5358       CtorInitializers[i] = BOMInit;
5359     }
5360   }
5361 
5362   return std::make_pair(CtorInitializers, NumInitializers);
5363 }
5364 
5365 NestedNameSpecifier *
5366 ASTReader::ReadNestedNameSpecifier(Module &F,
5367                                    const RecordData &Record, unsigned &Idx) {
5368   unsigned N = Record[Idx++];
5369   NestedNameSpecifier *NNS = 0, *Prev = 0;
5370   for (unsigned I = 0; I != N; ++I) {
5371     NestedNameSpecifier::SpecifierKind Kind
5372       = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
5373     switch (Kind) {
5374     case NestedNameSpecifier::Identifier: {
5375       IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
5376       NNS = NestedNameSpecifier::Create(Context, Prev, II);
5377       break;
5378     }
5379 
5380     case NestedNameSpecifier::Namespace: {
5381       NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
5382       NNS = NestedNameSpecifier::Create(Context, Prev, NS);
5383       break;
5384     }
5385 
5386     case NestedNameSpecifier::NamespaceAlias: {
5387       NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
5388       NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
5389       break;
5390     }
5391 
5392     case NestedNameSpecifier::TypeSpec:
5393     case NestedNameSpecifier::TypeSpecWithTemplate: {
5394       const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
5395       if (!T)
5396         return 0;
5397 
5398       bool Template = Record[Idx++];
5399       NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
5400       break;
5401     }
5402 
5403     case NestedNameSpecifier::Global: {
5404       NNS = NestedNameSpecifier::GlobalSpecifier(Context);
5405       // No associated value, and there can't be a prefix.
5406       break;
5407     }
5408     }
5409     Prev = NNS;
5410   }
5411   return NNS;
5412 }
5413 
5414 NestedNameSpecifierLoc
5415 ASTReader::ReadNestedNameSpecifierLoc(Module &F, const RecordData &Record,
5416                                       unsigned &Idx) {
5417   unsigned N = Record[Idx++];
5418   NestedNameSpecifierLocBuilder Builder;
5419   for (unsigned I = 0; I != N; ++I) {
5420     NestedNameSpecifier::SpecifierKind Kind
5421       = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
5422     switch (Kind) {
5423     case NestedNameSpecifier::Identifier: {
5424       IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
5425       SourceRange Range = ReadSourceRange(F, Record, Idx);
5426       Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
5427       break;
5428     }
5429 
5430     case NestedNameSpecifier::Namespace: {
5431       NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
5432       SourceRange Range = ReadSourceRange(F, Record, Idx);
5433       Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
5434       break;
5435     }
5436 
5437     case NestedNameSpecifier::NamespaceAlias: {
5438       NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
5439       SourceRange Range = ReadSourceRange(F, Record, Idx);
5440       Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
5441       break;
5442     }
5443 
5444     case NestedNameSpecifier::TypeSpec:
5445     case NestedNameSpecifier::TypeSpecWithTemplate: {
5446       bool Template = Record[Idx++];
5447       TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
5448       if (!T)
5449         return NestedNameSpecifierLoc();
5450       SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
5451 
5452       // FIXME: 'template' keyword location not saved anywhere, so we fake it.
5453       Builder.Extend(Context,
5454                      Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
5455                      T->getTypeLoc(), ColonColonLoc);
5456       break;
5457     }
5458 
5459     case NestedNameSpecifier::Global: {
5460       SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
5461       Builder.MakeGlobal(Context, ColonColonLoc);
5462       break;
5463     }
5464     }
5465   }
5466 
5467   return Builder.getWithLocInContext(Context);
5468 }
5469 
5470 SourceRange
5471 ASTReader::ReadSourceRange(Module &F, const RecordData &Record,
5472                            unsigned &Idx) {
5473   SourceLocation beg = ReadSourceLocation(F, Record, Idx);
5474   SourceLocation end = ReadSourceLocation(F, Record, Idx);
5475   return SourceRange(beg, end);
5476 }
5477 
5478 /// \brief Read an integral value
5479 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
5480   unsigned BitWidth = Record[Idx++];
5481   unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
5482   llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
5483   Idx += NumWords;
5484   return Result;
5485 }
5486 
5487 /// \brief Read a signed integral value
5488 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
5489   bool isUnsigned = Record[Idx++];
5490   return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
5491 }
5492 
5493 /// \brief Read a floating-point value
5494 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
5495   return llvm::APFloat(ReadAPInt(Record, Idx));
5496 }
5497 
5498 // \brief Read a string
5499 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
5500   unsigned Len = Record[Idx++];
5501   std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
5502   Idx += Len;
5503   return Result;
5504 }
5505 
5506 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
5507                                          unsigned &Idx) {
5508   unsigned Major = Record[Idx++];
5509   unsigned Minor = Record[Idx++];
5510   unsigned Subminor = Record[Idx++];
5511   if (Minor == 0)
5512     return VersionTuple(Major);
5513   if (Subminor == 0)
5514     return VersionTuple(Major, Minor - 1);
5515   return VersionTuple(Major, Minor - 1, Subminor - 1);
5516 }
5517 
5518 CXXTemporary *ASTReader::ReadCXXTemporary(Module &F,
5519                                           const RecordData &Record,
5520                                           unsigned &Idx) {
5521   CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
5522   return CXXTemporary::Create(Context, Decl);
5523 }
5524 
5525 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
5526   return Diag(SourceLocation(), DiagID);
5527 }
5528 
5529 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
5530   return Diags.Report(Loc, DiagID);
5531 }
5532 
5533 /// \brief Retrieve the identifier table associated with the
5534 /// preprocessor.
5535 IdentifierTable &ASTReader::getIdentifierTable() {
5536   return PP.getIdentifierTable();
5537 }
5538 
5539 /// \brief Record that the given ID maps to the given switch-case
5540 /// statement.
5541 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
5542   assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
5543   SwitchCaseStmts[ID] = SC;
5544 }
5545 
5546 /// \brief Retrieve the switch-case statement with the given ID.
5547 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
5548   assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
5549   return SwitchCaseStmts[ID];
5550 }
5551 
5552 void ASTReader::ClearSwitchCaseIDs() {
5553   SwitchCaseStmts.clear();
5554 }
5555 
5556 void ASTReader::FinishedDeserializing() {
5557   assert(NumCurrentElementsDeserializing &&
5558          "FinishedDeserializing not paired with StartedDeserializing");
5559   if (NumCurrentElementsDeserializing == 1) {
5560     // If any identifiers with corresponding top-level declarations have
5561     // been loaded, load those declarations now.
5562     while (!PendingIdentifierInfos.empty()) {
5563       SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
5564                               PendingIdentifierInfos.front().DeclIDs, true);
5565       PendingIdentifierInfos.pop_front();
5566     }
5567 
5568     // Ready to load previous declarations of Decls that were delayed.
5569     while (!PendingPreviousDecls.empty()) {
5570       loadAndAttachPreviousDecl(PendingPreviousDecls.front().first,
5571                                 PendingPreviousDecls.front().second);
5572       PendingPreviousDecls.pop_front();
5573     }
5574 
5575     for (std::vector<std::pair<ObjCInterfaceDecl *,
5576                                serialization::DeclID> >::iterator
5577            I = PendingChainedObjCCategories.begin(),
5578            E = PendingChainedObjCCategories.end(); I != E; ++I) {
5579       loadObjCChainedCategories(I->second, I->first);
5580     }
5581     PendingChainedObjCCategories.clear();
5582 
5583     // We are not in recursive loading, so it's safe to pass the "interesting"
5584     // decls to the consumer.
5585     if (Consumer)
5586       PassInterestingDeclsToConsumer();
5587 
5588     assert(PendingForwardRefs.size() == 0 &&
5589            "Some forward refs did not get linked to the definition!");
5590   }
5591   --NumCurrentElementsDeserializing;
5592 }
5593 
5594 ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
5595                      StringRef isysroot, bool DisableValidation,
5596                      bool DisableStatCache)
5597   : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
5598     SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
5599     Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
5600     Consumer(0), ModuleMgr(FileMgr.getFileSystemOptions()),
5601     RelocatablePCH(false), isysroot(isysroot),
5602     DisableValidation(DisableValidation),
5603     DisableStatCache(DisableStatCache), NumStatHits(0), NumStatMisses(0),
5604     NumSLocEntriesRead(0), TotalNumSLocEntries(0),
5605     NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
5606     TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
5607     NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
5608     NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
5609     NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
5610     TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
5611     NumCXXBaseSpecifiersLoaded(0)
5612 {
5613   SourceMgr.setExternalSLocEntrySource(this);
5614 }
5615 
5616 ASTReader::~ASTReader() {
5617   for (DeclContextVisibleUpdatesPending::iterator
5618            I = PendingVisibleUpdates.begin(),
5619            E = PendingVisibleUpdates.end();
5620        I != E; ++I) {
5621     for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
5622                                              F = I->second.end();
5623          J != F; ++J)
5624       delete static_cast<ASTDeclContextNameLookupTable*>(J->first);
5625   }
5626 }
5627