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