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