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