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