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