ASTReader.cpp revision a9b8da43077a78f9ab223caf4889e6c6eba2c4a3
1//===--- ASTReader.cpp - AST File Reader ------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "clang/Serialization/ASTDeserializationListener.h"
16#include "clang/Serialization/ModuleManager.h"
17#include "clang/Serialization/SerializationDiagnostic.h"
18#include "ASTCommon.h"
19#include "ASTReaderInternals.h"
20#include "clang/Sema/Sema.h"
21#include "clang/Sema/Scope.h"
22#include "clang/AST/ASTConsumer.h"
23#include "clang/AST/ASTContext.h"
24#include "clang/AST/DeclTemplate.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/NestedNameSpecifier.h"
28#include "clang/AST/Type.h"
29#include "clang/AST/TypeLocVisitor.h"
30#include "clang/Lex/MacroInfo.h"
31#include "clang/Lex/PreprocessingRecord.h"
32#include "clang/Lex/Preprocessor.h"
33#include "clang/Lex/PreprocessorOptions.h"
34#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/HeaderSearchOptions.h"
36#include "clang/Basic/OnDiskHashTable.h"
37#include "clang/Basic/SourceManager.h"
38#include "clang/Basic/SourceManagerInternals.h"
39#include "clang/Basic/FileManager.h"
40#include "clang/Basic/FileSystemStatCache.h"
41#include "clang/Basic/TargetInfo.h"
42#include "clang/Basic/TargetOptions.h"
43#include "clang/Basic/Version.h"
44#include "clang/Basic/VersionTuple.h"
45#include "llvm/ADT/StringExtras.h"
46#include "llvm/Bitcode/BitstreamReader.h"
47#include "llvm/Support/MemoryBuffer.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/FileSystem.h"
50#include "llvm/Support/Path.h"
51#include "llvm/Support/SaveAndRestore.h"
52#include "llvm/Support/system_error.h"
53#include <algorithm>
54#include <iterator>
55#include <cstdio>
56#include <sys/stat.h>
57
58using namespace clang;
59using namespace clang::serialization;
60using namespace clang::serialization::reader;
61
62//===----------------------------------------------------------------------===//
63// PCH validator implementation
64//===----------------------------------------------------------------------===//
65
66ASTReaderListener::~ASTReaderListener() {}
67
68/// \brief Compare the given set of language options against an existing set of
69/// language options.
70///
71/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
72///
73/// \returns true if the languagae options mis-match, false otherwise.
74static bool checkLanguageOptions(const LangOptions &LangOpts,
75                                 const LangOptions &ExistingLangOpts,
76                                 DiagnosticsEngine *Diags) {
77#define LANGOPT(Name, Bits, Default, Description)                 \
78  if (ExistingLangOpts.Name != LangOpts.Name) {                   \
79    if (Diags)                                                    \
80      Diags->Report(diag::err_pch_langopt_mismatch)               \
81        << Description << LangOpts.Name << ExistingLangOpts.Name; \
82    return true;                                                  \
83  }
84
85#define VALUE_LANGOPT(Name, Bits, Default, Description)   \
86  if (ExistingLangOpts.Name != LangOpts.Name) {           \
87    if (Diags)                                            \
88      Diags->Report(diag::err_pch_langopt_value_mismatch) \
89        << Description;                                   \
90    return true;                                          \
91  }
92
93#define ENUM_LANGOPT(Name, Type, Bits, Default, Description)   \
94  if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) {  \
95    if (Diags)                                                 \
96      Diags->Report(diag::err_pch_langopt_value_mismatch)      \
97        << Description;                                        \
98    return true;                                               \
99  }
100
101#define BENIGN_LANGOPT(Name, Bits, Default, Description)
102#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
103#include "clang/Basic/LangOptions.def"
104
105  if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
106    if (Diags)
107      Diags->Report(diag::err_pch_langopt_value_mismatch)
108      << "target Objective-C runtime";
109    return true;
110  }
111
112  return false;
113}
114
115/// \brief Compare the given set of target options against an existing set of
116/// target options.
117///
118/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
119///
120/// \returns true if the target options mis-match, false otherwise.
121static bool checkTargetOptions(const TargetOptions &TargetOpts,
122                               const TargetOptions &ExistingTargetOpts,
123                               DiagnosticsEngine *Diags) {
124#define CHECK_TARGET_OPT(Field, Name)                             \
125  if (TargetOpts.Field != ExistingTargetOpts.Field) {             \
126    if (Diags)                                                    \
127      Diags->Report(diag::err_pch_targetopt_mismatch)             \
128        << Name << TargetOpts.Field << ExistingTargetOpts.Field;  \
129    return true;                                                  \
130  }
131
132  CHECK_TARGET_OPT(Triple, "target");
133  CHECK_TARGET_OPT(CPU, "target CPU");
134  CHECK_TARGET_OPT(ABI, "target ABI");
135  CHECK_TARGET_OPT(CXXABI, "target C++ ABI");
136  CHECK_TARGET_OPT(LinkerVersion, "target linker version");
137#undef CHECK_TARGET_OPT
138
139  // Compare feature sets.
140  SmallVector<StringRef, 4> ExistingFeatures(
141                                             ExistingTargetOpts.FeaturesAsWritten.begin(),
142                                             ExistingTargetOpts.FeaturesAsWritten.end());
143  SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
144                                         TargetOpts.FeaturesAsWritten.end());
145  std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
146  std::sort(ReadFeatures.begin(), ReadFeatures.end());
147
148  unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
149  unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
150  while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
151    if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
152      ++ExistingIdx;
153      ++ReadIdx;
154      continue;
155    }
156
157    if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
158      if (Diags)
159        Diags->Report(diag::err_pch_targetopt_feature_mismatch)
160          << false << ReadFeatures[ReadIdx];
161      return true;
162    }
163
164    if (Diags)
165      Diags->Report(diag::err_pch_targetopt_feature_mismatch)
166        << true << ExistingFeatures[ExistingIdx];
167    return true;
168  }
169
170  if (ExistingIdx < ExistingN) {
171    if (Diags)
172      Diags->Report(diag::err_pch_targetopt_feature_mismatch)
173        << true << ExistingFeatures[ExistingIdx];
174    return true;
175  }
176
177  if (ReadIdx < ReadN) {
178    if (Diags)
179      Diags->Report(diag::err_pch_targetopt_feature_mismatch)
180        << false << ReadFeatures[ReadIdx];
181    return true;
182  }
183
184  return false;
185}
186
187bool
188PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
189                                  bool Complain) {
190  const LangOptions &ExistingLangOpts = PP.getLangOpts();
191  return checkLanguageOptions(LangOpts, ExistingLangOpts,
192                              Complain? &Reader.Diags : 0);
193}
194
195bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
196                                     bool Complain) {
197  const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
198  return checkTargetOptions(TargetOpts, ExistingTargetOpts,
199                            Complain? &Reader.Diags : 0);
200}
201
202namespace {
203  typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
204    MacroDefinitionsMap;
205}
206
207/// \brief Collect the macro definitions provided by the given preprocessor
208/// options.
209static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
210                                    MacroDefinitionsMap &Macros,
211                                    SmallVectorImpl<StringRef> *MacroNames = 0){
212  for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
213    StringRef Macro = PPOpts.Macros[I].first;
214    bool IsUndef = PPOpts.Macros[I].second;
215
216    std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
217    StringRef MacroName = MacroPair.first;
218    StringRef MacroBody = MacroPair.second;
219
220    // For an #undef'd macro, we only care about the name.
221    if (IsUndef) {
222      if (MacroNames && !Macros.count(MacroName))
223        MacroNames->push_back(MacroName);
224
225      Macros[MacroName] = std::make_pair("", true);
226      continue;
227    }
228
229    // For a #define'd macro, figure out the actual definition.
230    if (MacroName.size() == Macro.size())
231      MacroBody = "1";
232    else {
233      // Note: GCC drops anything following an end-of-line character.
234      StringRef::size_type End = MacroBody.find_first_of("\n\r");
235      MacroBody = MacroBody.substr(0, End);
236    }
237
238    if (MacroNames && !Macros.count(MacroName))
239      MacroNames->push_back(MacroName);
240    Macros[MacroName] = std::make_pair(MacroBody, false);
241  }
242}
243
244/// \brief Check the preprocessor options deserialized from the control block
245/// against the preprocessor options in an existing preprocessor.
246///
247/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
248static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
249                                     const PreprocessorOptions &ExistingPPOpts,
250                                     DiagnosticsEngine *Diags,
251                                     FileManager &FileMgr,
252                                     std::string &SuggestedPredefines) {
253  // Check macro definitions.
254  MacroDefinitionsMap ASTFileMacros;
255  collectMacroDefinitions(PPOpts, ASTFileMacros);
256  MacroDefinitionsMap ExistingMacros;
257  SmallVector<StringRef, 4> ExistingMacroNames;
258  collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
259
260  for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
261    // Dig out the macro definition in the existing preprocessor options.
262    StringRef MacroName = ExistingMacroNames[I];
263    std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
264
265    // Check whether we know anything about this macro name or not.
266    llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
267      = ASTFileMacros.find(MacroName);
268    if (Known == ASTFileMacros.end()) {
269      // FIXME: Check whether this identifier was referenced anywhere in the
270      // AST file. If so, we should reject the AST file. Unfortunately, this
271      // information isn't in the control block. What shall we do about it?
272
273      if (Existing.second) {
274        SuggestedPredefines += "#undef ";
275        SuggestedPredefines += MacroName.str();
276        SuggestedPredefines += '\n';
277      } else {
278        SuggestedPredefines += "#define ";
279        SuggestedPredefines += MacroName.str();
280        SuggestedPredefines += ' ';
281        SuggestedPredefines += Existing.first.str();
282        SuggestedPredefines += '\n';
283      }
284      continue;
285    }
286
287    // If the macro was defined in one but undef'd in the other, we have a
288    // conflict.
289    if (Existing.second != Known->second.second) {
290      if (Diags) {
291        Diags->Report(diag::err_pch_macro_def_undef)
292          << MacroName << Known->second.second;
293      }
294      return true;
295    }
296
297    // If the macro was #undef'd in both, or if the macro bodies are identical,
298    // it's fine.
299    if (Existing.second || Existing.first == Known->second.first)
300      continue;
301
302    // The macro bodies differ; complain.
303    if (Diags) {
304      Diags->Report(diag::err_pch_macro_def_conflict)
305        << MacroName << Known->second.first << Existing.first;
306    }
307    return true;
308  }
309
310  // Check whether we're using predefines.
311  if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
312    if (Diags) {
313      Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
314    }
315    return true;
316  }
317
318  // Compute the #include and #include_macros lines we need.
319  for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
320    StringRef File = ExistingPPOpts.Includes[I];
321    if (File == ExistingPPOpts.ImplicitPCHInclude)
322      continue;
323
324    if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
325          != PPOpts.Includes.end())
326      continue;
327
328    SuggestedPredefines += "#include \"";
329    SuggestedPredefines +=
330      HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
331    SuggestedPredefines += "\"\n";
332  }
333
334  for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
335    StringRef File = ExistingPPOpts.MacroIncludes[I];
336    if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
337                  File)
338        != PPOpts.MacroIncludes.end())
339      continue;
340
341    SuggestedPredefines += "#__include_macros \"";
342    SuggestedPredefines +=
343      HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
344    SuggestedPredefines += "\"\n##\n";
345  }
346
347  return false;
348}
349
350bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
351                                           bool Complain,
352                                           std::string &SuggestedPredefines) {
353  const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
354
355  return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
356                                  Complain? &Reader.Diags : 0,
357                                  PP.getFileManager(),
358                                  SuggestedPredefines);
359}
360
361namespace {
362  struct EmptyStringRef {
363    bool operator ()(StringRef r) const { return r.empty(); }
364  };
365  struct EmptyBlock {
366    bool operator ()(const PCHPredefinesBlock &r) const {return r.Data.empty();}
367  };
368}
369
370static bool EqualConcatenations(SmallVector<StringRef, 2> L,
371                                PCHPredefinesBlocks R) {
372  // First, sum up the lengths.
373  unsigned LL = 0, RL = 0;
374  for (unsigned I = 0, N = L.size(); I != N; ++I) {
375    LL += L[I].size();
376  }
377  for (unsigned I = 0, N = R.size(); I != N; ++I) {
378    RL += R[I].Data.size();
379  }
380  if (LL != RL)
381    return false;
382  if (LL == 0 && RL == 0)
383    return true;
384
385  // Kick out empty parts, they confuse the algorithm below.
386  L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
387  R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
388
389  // Do it the hard way. At this point, both vectors must be non-empty.
390  StringRef LR = L[0], RR = R[0].Data;
391  unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
392  (void) RN;
393  for (;;) {
394    // Compare the current pieces.
395    if (LR.size() == RR.size()) {
396      // If they're the same length, it's pretty easy.
397      if (LR != RR)
398        return false;
399      // Both pieces are done, advance.
400      ++LI;
401      ++RI;
402      // If either string is done, they're both done, since they're the same
403      // length.
404      if (LI == LN) {
405        assert(RI == RN && "Strings not the same length after all?");
406        return true;
407      }
408      LR = L[LI];
409      RR = R[RI].Data;
410    } else if (LR.size() < RR.size()) {
411      // Right piece is longer.
412      if (!RR.startswith(LR))
413        return false;
414      ++LI;
415      assert(LI != LN && "Strings not the same length after all?");
416      RR = RR.substr(LR.size());
417      LR = L[LI];
418    } else {
419      // Left piece is longer.
420      if (!LR.startswith(RR))
421        return false;
422      ++RI;
423      assert(RI != RN && "Strings not the same length after all?");
424      LR = LR.substr(RR.size());
425      RR = R[RI].Data;
426    }
427  }
428}
429
430static std::pair<FileID, StringRef::size_type>
431FindMacro(const PCHPredefinesBlocks &Buffers, StringRef MacroDef) {
432  std::pair<FileID, StringRef::size_type> Res;
433  for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
434    Res.second = Buffers[I].Data.find(MacroDef);
435    if (Res.second != StringRef::npos) {
436      Res.first = Buffers[I].BufferID;
437      break;
438    }
439  }
440  return Res;
441}
442
443bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
444                                        StringRef OriginalFileName,
445                                        std::string &SuggestedPredefines,
446                                        FileManager &FileMgr,
447                                        bool Complain) {
448  // We are in the context of an implicit include, so the predefines buffer will
449  // have a #include entry for the PCH file itself (as normalized by the
450  // preprocessor initialization). Find it and skip over it in the checking
451  // below.
452  SmallString<256> PCHInclude;
453  PCHInclude += "#include \"";
454  PCHInclude += HeaderSearch::NormalizeDashIncludePath(OriginalFileName,
455                                                       FileMgr);
456  PCHInclude += "\"\n";
457  std::pair<StringRef,StringRef> Split =
458    StringRef(PP.getPredefines()).split(PCHInclude.str());
459  StringRef Left =  Split.first, Right = Split.second;
460  if (Left == PP.getPredefines()) {
461    if (Complain)
462      Error("Missing PCH include entry!");
463    return true;
464  }
465
466  // If the concatenation of all the PCH buffers is equal to the adjusted
467  // command line, we're done.
468  SmallVector<StringRef, 2> CommandLine;
469  CommandLine.push_back(Left);
470  CommandLine.push_back(Right);
471  if (EqualConcatenations(CommandLine, Buffers))
472    return false;
473
474  SourceManager &SourceMgr = PP.getSourceManager();
475
476  // The predefines buffers are different. Determine what the differences are,
477  // and whether they require us to reject the PCH file.
478  SmallVector<StringRef, 8> PCHLines;
479  for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
480    Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
481
482  SmallVector<StringRef, 8> CmdLineLines;
483  Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
484
485  // Pick out implicit #includes after the PCH and don't consider them for
486  // validation; we will insert them into SuggestedPredefines so that the
487  // preprocessor includes them.
488  std::string IncludesAfterPCH;
489  SmallVector<StringRef, 8> AfterPCHLines;
490  Right.split(AfterPCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
491  for (unsigned i = 0, e = AfterPCHLines.size(); i != e; ++i) {
492    if (AfterPCHLines[i].startswith("#include ")) {
493      IncludesAfterPCH += AfterPCHLines[i];
494      IncludesAfterPCH += '\n';
495    } else {
496      CmdLineLines.push_back(AfterPCHLines[i]);
497    }
498  }
499
500  // Make sure we add the includes last into SuggestedPredefines before we
501  // exit this function.
502  struct AddIncludesRAII {
503    std::string &SuggestedPredefines;
504    std::string &IncludesAfterPCH;
505
506    AddIncludesRAII(std::string &SuggestedPredefines,
507                    std::string &IncludesAfterPCH)
508      : SuggestedPredefines(SuggestedPredefines),
509        IncludesAfterPCH(IncludesAfterPCH) { }
510    ~AddIncludesRAII() {
511      SuggestedPredefines += IncludesAfterPCH;
512    }
513  } AddIncludes(SuggestedPredefines, IncludesAfterPCH);
514
515  // Sort both sets of predefined buffer lines, since we allow some extra
516  // definitions and they may appear at any point in the output.
517  std::sort(CmdLineLines.begin(), CmdLineLines.end());
518  std::sort(PCHLines.begin(), PCHLines.end());
519
520  // Determine which predefines that were used to build the PCH file are missing
521  // from the command line.
522  std::vector<StringRef> MissingPredefines;
523  std::set_difference(PCHLines.begin(), PCHLines.end(),
524                      CmdLineLines.begin(), CmdLineLines.end(),
525                      std::back_inserter(MissingPredefines));
526
527  bool MissingDefines = false;
528  bool ConflictingDefines = false;
529  for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
530    StringRef Missing = MissingPredefines[I];
531    if (Missing.startswith("#include ")) {
532      // An -include was specified when generating the PCH; it is included in
533      // the PCH, just ignore it.
534      continue;
535    }
536    if (!Missing.startswith("#define ")) {
537      if (Complain)
538        Reader.Diag(diag::warn_pch_compiler_options_mismatch);
539      return true;
540    }
541
542    // This is a macro definition. Determine the name of the macro we're
543    // defining.
544    std::string::size_type StartOfMacroName = strlen("#define ");
545    std::string::size_type EndOfMacroName
546      = Missing.find_first_of("( \n\r", StartOfMacroName);
547    assert(EndOfMacroName != std::string::npos &&
548           "Couldn't find the end of the macro name");
549    StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
550
551    // Determine whether this macro was given a different definition on the
552    // command line.
553    std::string MacroDefStart = "#define " + MacroName.str();
554    std::string::size_type MacroDefLen = MacroDefStart.size();
555    SmallVector<StringRef, 8>::iterator ConflictPos
556      = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
557                         MacroDefStart);
558    for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
559      if (!ConflictPos->startswith(MacroDefStart)) {
560        // Different macro; we're done.
561        ConflictPos = CmdLineLines.end();
562        break;
563      }
564
565      assert(ConflictPos->size() > MacroDefLen &&
566             "Invalid #define in predefines buffer?");
567      if ((*ConflictPos)[MacroDefLen] != ' ' &&
568          (*ConflictPos)[MacroDefLen] != '(')
569        continue; // Longer macro name; keep trying.
570
571      // We found a conflicting macro definition.
572      break;
573    }
574
575    if (ConflictPos != CmdLineLines.end()) {
576      if (!Complain)
577        return true;
578
579      Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
580          << MacroName;
581
582      // Show the definition of this macro within the PCH file.
583      std::pair<FileID, StringRef::size_type> MacroLoc =
584          FindMacro(Buffers, Missing);
585      assert(MacroLoc.second!=StringRef::npos && "Unable to find macro!");
586      SourceLocation PCHMissingLoc =
587          SourceMgr.getLocForStartOfFile(MacroLoc.first)
588            .getLocWithOffset(MacroLoc.second);
589      Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
590
591      ConflictingDefines = true;
592      continue;
593    }
594
595    // If the macro doesn't conflict, then we'll just pick up the macro
596    // definition from the PCH file. Warn the user that they made a mistake.
597    if (ConflictingDefines)
598      continue; // Don't complain if there are already conflicting defs
599
600    if (!MissingDefines) {
601      if (!Complain)
602        return true;
603
604      Reader.Diag(diag::warn_cmdline_missing_macro_defs);
605      MissingDefines = true;
606    }
607
608    if (!Complain)
609      return true;
610
611    // Show the definition of this macro within the PCH file.
612    std::pair<FileID, StringRef::size_type> MacroLoc =
613        FindMacro(Buffers, Missing);
614    assert(MacroLoc.second!=StringRef::npos && "Unable to find macro!");
615    SourceLocation PCHMissingLoc =
616        SourceMgr.getLocForStartOfFile(MacroLoc.first)
617          .getLocWithOffset(MacroLoc.second);
618    Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
619  }
620
621  if (ConflictingDefines)
622    return true;
623
624  // Determine what predefines were introduced based on command-line
625  // parameters that were not present when building the PCH
626  // file. Extra #defines are okay, so long as the identifiers being
627  // defined were not used within the precompiled header.
628  std::vector<StringRef> ExtraPredefines;
629  std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
630                      PCHLines.begin(), PCHLines.end(),
631                      std::back_inserter(ExtraPredefines));
632  for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
633    StringRef &Extra = ExtraPredefines[I];
634    if (!Extra.startswith("#define ")) {
635      if (Complain)
636        Reader.Diag(diag::warn_pch_compiler_options_mismatch);
637      return true;
638    }
639
640    // This is an extra macro definition. Determine the name of the
641    // macro we're defining.
642    std::string::size_type StartOfMacroName = strlen("#define ");
643    std::string::size_type EndOfMacroName
644      = Extra.find_first_of("( \n\r", StartOfMacroName);
645    assert(EndOfMacroName != std::string::npos &&
646           "Couldn't find the end of the macro name");
647    StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
648
649    // Check whether this name was used somewhere in the PCH file. If
650    // so, defining it as a macro could change behavior, so we reject
651    // the PCH file.
652    if (IdentifierInfo *II = Reader.get(MacroName)) {
653      if (Complain)
654        Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
655      return true;
656    }
657
658    // Add this definition to the suggested predefines buffer.
659    SuggestedPredefines += Extra;
660    SuggestedPredefines += '\n';
661  }
662
663  // If we get here, it's because the predefines buffer had compatible
664  // contents. Accept the PCH file.
665  return false;
666}
667
668void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
669                                      unsigned ID) {
670  PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
671  ++NumHeaderInfos;
672}
673
674void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
675  PP.setCounterValue(Value);
676}
677
678//===----------------------------------------------------------------------===//
679// AST reader implementation
680//===----------------------------------------------------------------------===//
681
682void
683ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
684  DeserializationListener = Listener;
685}
686
687
688
689unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
690  return serialization::ComputeHash(Sel);
691}
692
693
694std::pair<unsigned, unsigned>
695ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
696  using namespace clang::io;
697  unsigned KeyLen = ReadUnalignedLE16(d);
698  unsigned DataLen = ReadUnalignedLE16(d);
699  return std::make_pair(KeyLen, DataLen);
700}
701
702ASTSelectorLookupTrait::internal_key_type
703ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
704  using namespace clang::io;
705  SelectorTable &SelTable = Reader.getContext().Selectors;
706  unsigned N = ReadUnalignedLE16(d);
707  IdentifierInfo *FirstII
708    = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
709  if (N == 0)
710    return SelTable.getNullarySelector(FirstII);
711  else if (N == 1)
712    return SelTable.getUnarySelector(FirstII);
713
714  SmallVector<IdentifierInfo *, 16> Args;
715  Args.push_back(FirstII);
716  for (unsigned I = 1; I != N; ++I)
717    Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
718
719  return SelTable.getSelector(N, Args.data());
720}
721
722ASTSelectorLookupTrait::data_type
723ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
724                                 unsigned DataLen) {
725  using namespace clang::io;
726
727  data_type Result;
728
729  Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
730  unsigned NumInstanceMethods = ReadUnalignedLE16(d);
731  unsigned NumFactoryMethods = ReadUnalignedLE16(d);
732
733  // Load instance methods
734  for (unsigned I = 0; I != NumInstanceMethods; ++I) {
735    if (ObjCMethodDecl *Method
736          = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
737      Result.Instance.push_back(Method);
738  }
739
740  // Load factory methods
741  for (unsigned I = 0; I != NumFactoryMethods; ++I) {
742    if (ObjCMethodDecl *Method
743          = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
744      Result.Factory.push_back(Method);
745  }
746
747  return Result;
748}
749
750unsigned ASTIdentifierLookupTrait::ComputeHash(const internal_key_type& a) {
751  return llvm::HashString(StringRef(a.first, a.second));
752}
753
754std::pair<unsigned, unsigned>
755ASTIdentifierLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
756  using namespace clang::io;
757  unsigned DataLen = ReadUnalignedLE16(d);
758  unsigned KeyLen = ReadUnalignedLE16(d);
759  return std::make_pair(KeyLen, DataLen);
760}
761
762std::pair<const char*, unsigned>
763ASTIdentifierLookupTrait::ReadKey(const unsigned char* d, unsigned n) {
764  assert(n >= 2 && d[n-1] == '\0');
765  return std::make_pair((const char*) d, n-1);
766}
767
768IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
769                                                   const unsigned char* d,
770                                                   unsigned DataLen) {
771  using namespace clang::io;
772  unsigned RawID = ReadUnalignedLE32(d);
773  bool IsInteresting = RawID & 0x01;
774
775  // Wipe out the "is interesting" bit.
776  RawID = RawID >> 1;
777
778  IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
779  if (!IsInteresting) {
780    // For uninteresting identifiers, just build the IdentifierInfo
781    // and associate it with the persistent ID.
782    IdentifierInfo *II = KnownII;
783    if (!II) {
784      II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
785      KnownII = II;
786    }
787    Reader.SetIdentifierInfo(ID, II);
788    II->setIsFromAST();
789    Reader.markIdentifierUpToDate(II);
790    return II;
791  }
792
793  unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
794  unsigned Bits = ReadUnalignedLE16(d);
795  bool CPlusPlusOperatorKeyword = Bits & 0x01;
796  Bits >>= 1;
797  bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
798  Bits >>= 1;
799  bool Poisoned = Bits & 0x01;
800  Bits >>= 1;
801  bool ExtensionToken = Bits & 0x01;
802  Bits >>= 1;
803  bool hadMacroDefinition = Bits & 0x01;
804  Bits >>= 1;
805
806  assert(Bits == 0 && "Extra bits in the identifier?");
807  DataLen -= 8;
808
809  // Build the IdentifierInfo itself and link the identifier ID with
810  // the new IdentifierInfo.
811  IdentifierInfo *II = KnownII;
812  if (!II) {
813    II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
814    KnownII = II;
815  }
816  Reader.markIdentifierUpToDate(II);
817  II->setIsFromAST();
818
819  // Set or check the various bits in the IdentifierInfo structure.
820  // Token IDs are read-only.
821  if (HasRevertedTokenIDToIdentifier)
822    II->RevertTokenIDToIdentifier();
823  II->setObjCOrBuiltinID(ObjCOrBuiltinID);
824  assert(II->isExtensionToken() == ExtensionToken &&
825         "Incorrect extension token flag");
826  (void)ExtensionToken;
827  if (Poisoned)
828    II->setIsPoisoned(true);
829  assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
830         "Incorrect C++ operator keyword flag");
831  (void)CPlusPlusOperatorKeyword;
832
833  // If this identifier is a macro, deserialize the macro
834  // definition.
835  if (hadMacroDefinition) {
836    SmallVector<MacroID, 4> MacroIDs;
837    while (uint32_t LocalID = ReadUnalignedLE32(d)) {
838      MacroIDs.push_back(Reader.getGlobalMacroID(F, LocalID));
839      DataLen -= 4;
840    }
841    DataLen -= 4;
842    Reader.setIdentifierIsMacro(II, MacroIDs);
843  }
844
845  Reader.SetIdentifierInfo(ID, II);
846
847  // Read all of the declarations visible at global scope with this
848  // name.
849  if (DataLen > 0) {
850    SmallVector<uint32_t, 4> DeclIDs;
851    for (; DataLen > 0; DataLen -= 4)
852      DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
853    Reader.SetGloballyVisibleDecls(II, DeclIDs);
854  }
855
856  return II;
857}
858
859unsigned
860ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
861  llvm::FoldingSetNodeID ID;
862  ID.AddInteger(Key.Kind);
863
864  switch (Key.Kind) {
865  case DeclarationName::Identifier:
866  case DeclarationName::CXXLiteralOperatorName:
867    ID.AddString(((IdentifierInfo*)Key.Data)->getName());
868    break;
869  case DeclarationName::ObjCZeroArgSelector:
870  case DeclarationName::ObjCOneArgSelector:
871  case DeclarationName::ObjCMultiArgSelector:
872    ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
873    break;
874  case DeclarationName::CXXOperatorName:
875    ID.AddInteger((OverloadedOperatorKind)Key.Data);
876    break;
877  case DeclarationName::CXXConstructorName:
878  case DeclarationName::CXXDestructorName:
879  case DeclarationName::CXXConversionFunctionName:
880  case DeclarationName::CXXUsingDirective:
881    break;
882  }
883
884  return ID.ComputeHash();
885}
886
887ASTDeclContextNameLookupTrait::internal_key_type
888ASTDeclContextNameLookupTrait::GetInternalKey(
889                                          const external_key_type& Name) const {
890  DeclNameKey Key;
891  Key.Kind = Name.getNameKind();
892  switch (Name.getNameKind()) {
893  case DeclarationName::Identifier:
894    Key.Data = (uint64_t)Name.getAsIdentifierInfo();
895    break;
896  case DeclarationName::ObjCZeroArgSelector:
897  case DeclarationName::ObjCOneArgSelector:
898  case DeclarationName::ObjCMultiArgSelector:
899    Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
900    break;
901  case DeclarationName::CXXOperatorName:
902    Key.Data = Name.getCXXOverloadedOperator();
903    break;
904  case DeclarationName::CXXLiteralOperatorName:
905    Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
906    break;
907  case DeclarationName::CXXConstructorName:
908  case DeclarationName::CXXDestructorName:
909  case DeclarationName::CXXConversionFunctionName:
910  case DeclarationName::CXXUsingDirective:
911    Key.Data = 0;
912    break;
913  }
914
915  return Key;
916}
917
918std::pair<unsigned, unsigned>
919ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
920  using namespace clang::io;
921  unsigned KeyLen = ReadUnalignedLE16(d);
922  unsigned DataLen = ReadUnalignedLE16(d);
923  return std::make_pair(KeyLen, DataLen);
924}
925
926ASTDeclContextNameLookupTrait::internal_key_type
927ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
928  using namespace clang::io;
929
930  DeclNameKey Key;
931  Key.Kind = (DeclarationName::NameKind)*d++;
932  switch (Key.Kind) {
933  case DeclarationName::Identifier:
934    Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
935    break;
936  case DeclarationName::ObjCZeroArgSelector:
937  case DeclarationName::ObjCOneArgSelector:
938  case DeclarationName::ObjCMultiArgSelector:
939    Key.Data =
940       (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
941                   .getAsOpaquePtr();
942    break;
943  case DeclarationName::CXXOperatorName:
944    Key.Data = *d++; // OverloadedOperatorKind
945    break;
946  case DeclarationName::CXXLiteralOperatorName:
947    Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
948    break;
949  case DeclarationName::CXXConstructorName:
950  case DeclarationName::CXXDestructorName:
951  case DeclarationName::CXXConversionFunctionName:
952  case DeclarationName::CXXUsingDirective:
953    Key.Data = 0;
954    break;
955  }
956
957  return Key;
958}
959
960ASTDeclContextNameLookupTrait::data_type
961ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
962                                        const unsigned char* d,
963                                        unsigned DataLen) {
964  using namespace clang::io;
965  unsigned NumDecls = ReadUnalignedLE16(d);
966  LE32DeclID *Start = (LE32DeclID *)d;
967  return std::make_pair(Start, Start + NumDecls);
968}
969
970bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
971                                       llvm::BitstreamCursor &Cursor,
972                                   const std::pair<uint64_t, uint64_t> &Offsets,
973                                       DeclContextInfo &Info) {
974  SavedStreamPosition SavedPosition(Cursor);
975  // First the lexical decls.
976  if (Offsets.first != 0) {
977    Cursor.JumpToBit(Offsets.first);
978
979    RecordData Record;
980    const char *Blob;
981    unsigned BlobLen;
982    unsigned Code = Cursor.ReadCode();
983    unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
984    if (RecCode != DECL_CONTEXT_LEXICAL) {
985      Error("Expected lexical block");
986      return true;
987    }
988
989    Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob);
990    Info.NumLexicalDecls = BlobLen / sizeof(KindDeclIDPair);
991  }
992
993  // Now the lookup table.
994  if (Offsets.second != 0) {
995    Cursor.JumpToBit(Offsets.second);
996
997    RecordData Record;
998    const char *Blob;
999    unsigned BlobLen;
1000    unsigned Code = Cursor.ReadCode();
1001    unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
1002    if (RecCode != DECL_CONTEXT_VISIBLE) {
1003      Error("Expected visible lookup table block");
1004      return true;
1005    }
1006    Info.NameLookupTableData
1007      = ASTDeclContextNameLookupTable::Create(
1008                    (const unsigned char *)Blob + Record[0],
1009                    (const unsigned char *)Blob,
1010                    ASTDeclContextNameLookupTrait(*this, M));
1011  }
1012
1013  return false;
1014}
1015
1016void ASTReader::Error(StringRef Msg) {
1017  Error(diag::err_fe_pch_malformed, Msg);
1018}
1019
1020void ASTReader::Error(unsigned DiagID,
1021                      StringRef Arg1, StringRef Arg2) {
1022  if (Diags.isDiagnosticInFlight())
1023    Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1024  else
1025    Diag(DiagID) << Arg1 << Arg2;
1026}
1027
1028/// \brief Tell the AST listener about the predefines buffers in the chain.
1029bool ASTReader::CheckPredefinesBuffers(bool Complain) {
1030  return false;
1031}
1032
1033//===----------------------------------------------------------------------===//
1034// Source Manager Deserialization
1035//===----------------------------------------------------------------------===//
1036
1037/// \brief Read the line table in the source manager block.
1038/// \returns true if there was an error.
1039bool ASTReader::ParseLineTable(ModuleFile &F,
1040                               SmallVectorImpl<uint64_t> &Record) {
1041  unsigned Idx = 0;
1042  LineTableInfo &LineTable = SourceMgr.getLineTable();
1043
1044  // Parse the file names
1045  std::map<int, int> FileIDs;
1046  for (int I = 0, N = Record[Idx++]; I != N; ++I) {
1047    // Extract the file name
1048    unsigned FilenameLen = Record[Idx++];
1049    std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
1050    Idx += FilenameLen;
1051    MaybeAddSystemRootToFilename(F, Filename);
1052    FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1053  }
1054
1055  // Parse the line entries
1056  std::vector<LineEntry> Entries;
1057  while (Idx < Record.size()) {
1058    int FID = Record[Idx++];
1059    assert(FID >= 0 && "Serialized line entries for non-local file.");
1060    // Remap FileID from 1-based old view.
1061    FID += F.SLocEntryBaseID - 1;
1062
1063    // Extract the line entries
1064    unsigned NumEntries = Record[Idx++];
1065    assert(NumEntries && "Numentries is 00000");
1066    Entries.clear();
1067    Entries.reserve(NumEntries);
1068    for (unsigned I = 0; I != NumEntries; ++I) {
1069      unsigned FileOffset = Record[Idx++];
1070      unsigned LineNo = Record[Idx++];
1071      int FilenameID = FileIDs[Record[Idx++]];
1072      SrcMgr::CharacteristicKind FileKind
1073        = (SrcMgr::CharacteristicKind)Record[Idx++];
1074      unsigned IncludeOffset = Record[Idx++];
1075      Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1076                                       FileKind, IncludeOffset));
1077    }
1078    LineTable.AddEntry(FileID::get(FID), Entries);
1079  }
1080
1081  return false;
1082}
1083
1084namespace {
1085
1086class ASTStatData {
1087public:
1088  const ino_t ino;
1089  const dev_t dev;
1090  const mode_t mode;
1091  const time_t mtime;
1092  const off_t size;
1093
1094  ASTStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
1095    : ino(i), dev(d), mode(mo), mtime(m), size(s) {}
1096};
1097
1098class ASTStatLookupTrait {
1099 public:
1100  typedef const char *external_key_type;
1101  typedef const char *internal_key_type;
1102
1103  typedef ASTStatData data_type;
1104
1105  static unsigned ComputeHash(const char *path) {
1106    return llvm::HashString(path);
1107  }
1108
1109  static internal_key_type GetInternalKey(const char *path) { return path; }
1110
1111  static bool EqualKey(internal_key_type a, internal_key_type b) {
1112    return strcmp(a, b) == 0;
1113  }
1114
1115  static std::pair<unsigned, unsigned>
1116  ReadKeyDataLength(const unsigned char*& d) {
1117    unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1118    unsigned DataLen = (unsigned) *d++;
1119    return std::make_pair(KeyLen + 1, DataLen);
1120  }
1121
1122  static internal_key_type ReadKey(const unsigned char *d, unsigned) {
1123    return (const char *)d;
1124  }
1125
1126  static data_type ReadData(const internal_key_type, const unsigned char *d,
1127                            unsigned /*DataLen*/) {
1128    using namespace clang::io;
1129
1130    ino_t ino = (ino_t) ReadUnalignedLE32(d);
1131    dev_t dev = (dev_t) ReadUnalignedLE32(d);
1132    mode_t mode = (mode_t) ReadUnalignedLE16(d);
1133    time_t mtime = (time_t) ReadUnalignedLE64(d);
1134    off_t size = (off_t) ReadUnalignedLE64(d);
1135    return data_type(ino, dev, mode, mtime, size);
1136  }
1137};
1138
1139/// \brief stat() cache for precompiled headers.
1140///
1141/// This cache is very similar to the stat cache used by pretokenized
1142/// headers.
1143class ASTStatCache : public FileSystemStatCache {
1144  typedef OnDiskChainedHashTable<ASTStatLookupTrait> CacheTy;
1145  CacheTy *Cache;
1146
1147  unsigned &NumStatHits, &NumStatMisses;
1148public:
1149  ASTStatCache(const unsigned char *Buckets, const unsigned char *Base,
1150               unsigned &NumStatHits, unsigned &NumStatMisses)
1151    : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
1152    Cache = CacheTy::Create(Buckets, Base);
1153  }
1154
1155  ~ASTStatCache() { delete Cache; }
1156
1157  LookupResult getStat(const char *Path, struct stat &StatBuf,
1158                       int *FileDescriptor) {
1159    // Do the lookup for the file's data in the AST file.
1160    CacheTy::iterator I = Cache->find(Path);
1161
1162    // If we don't get a hit in the AST file just forward to 'stat'.
1163    if (I == Cache->end()) {
1164      ++NumStatMisses;
1165      return statChained(Path, StatBuf, FileDescriptor);
1166    }
1167
1168    ++NumStatHits;
1169    ASTStatData Data = *I;
1170
1171    StatBuf.st_ino = Data.ino;
1172    StatBuf.st_dev = Data.dev;
1173    StatBuf.st_mtime = Data.mtime;
1174    StatBuf.st_mode = Data.mode;
1175    StatBuf.st_size = Data.size;
1176    return CacheExists;
1177  }
1178};
1179} // end anonymous namespace
1180
1181
1182/// \brief Read a source manager block
1183bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1184  using namespace SrcMgr;
1185
1186  llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1187
1188  // Set the source-location entry cursor to the current position in
1189  // the stream. This cursor will be used to read the contents of the
1190  // source manager block initially, and then lazily read
1191  // source-location entries as needed.
1192  SLocEntryCursor = F.Stream;
1193
1194  // The stream itself is going to skip over the source manager block.
1195  if (F.Stream.SkipBlock()) {
1196    Error("malformed block record in AST file");
1197    return true;
1198  }
1199
1200  // Enter the source manager block.
1201  if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1202    Error("malformed source manager block record in AST file");
1203    return true;
1204  }
1205
1206  RecordData Record;
1207  while (true) {
1208    unsigned Code = SLocEntryCursor.ReadCode();
1209    if (Code == llvm::bitc::END_BLOCK) {
1210      if (SLocEntryCursor.ReadBlockEnd()) {
1211        Error("error at end of Source Manager block in AST file");
1212        return true;
1213      }
1214      return false;
1215    }
1216
1217    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1218      // No known subblocks, always skip them.
1219      SLocEntryCursor.ReadSubBlockID();
1220      if (SLocEntryCursor.SkipBlock()) {
1221        Error("malformed block record in AST file");
1222        return true;
1223      }
1224      continue;
1225    }
1226
1227    if (Code == llvm::bitc::DEFINE_ABBREV) {
1228      SLocEntryCursor.ReadAbbrevRecord();
1229      continue;
1230    }
1231
1232    // Read a record.
1233    const char *BlobStart;
1234    unsigned BlobLen;
1235    Record.clear();
1236    switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1237    default:  // Default behavior: ignore.
1238      break;
1239
1240    case SM_SLOC_FILE_ENTRY:
1241    case SM_SLOC_BUFFER_ENTRY:
1242    case SM_SLOC_EXPANSION_ENTRY:
1243      // Once we hit one of the source location entries, we're done.
1244      return false;
1245    }
1246  }
1247}
1248
1249/// \brief If a header file is not found at the path that we expect it to be
1250/// and the PCH file was moved from its original location, try to resolve the
1251/// file by assuming that header+PCH were moved together and the header is in
1252/// the same place relative to the PCH.
1253static std::string
1254resolveFileRelativeToOriginalDir(const std::string &Filename,
1255                                 const std::string &OriginalDir,
1256                                 const std::string &CurrDir) {
1257  assert(OriginalDir != CurrDir &&
1258         "No point trying to resolve the file if the PCH dir didn't change");
1259  using namespace llvm::sys;
1260  SmallString<128> filePath(Filename);
1261  fs::make_absolute(filePath);
1262  assert(path::is_absolute(OriginalDir));
1263  SmallString<128> currPCHPath(CurrDir);
1264
1265  path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1266                       fileDirE = path::end(path::parent_path(filePath));
1267  path::const_iterator origDirI = path::begin(OriginalDir),
1268                       origDirE = path::end(OriginalDir);
1269  // Skip the common path components from filePath and OriginalDir.
1270  while (fileDirI != fileDirE && origDirI != origDirE &&
1271         *fileDirI == *origDirI) {
1272    ++fileDirI;
1273    ++origDirI;
1274  }
1275  for (; origDirI != origDirE; ++origDirI)
1276    path::append(currPCHPath, "..");
1277  path::append(currPCHPath, fileDirI, fileDirE);
1278  path::append(currPCHPath, path::filename(Filename));
1279  return currPCHPath.str();
1280}
1281
1282bool ASTReader::ReadSLocEntry(int ID) {
1283  if (ID == 0)
1284    return false;
1285
1286  if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1287    Error("source location entry ID out-of-range for AST file");
1288    return true;
1289  }
1290
1291  ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1292  F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
1293  llvm::BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1294  unsigned BaseOffset = F->SLocEntryBaseOffset;
1295
1296  ++NumSLocEntriesRead;
1297  unsigned Code = SLocEntryCursor.ReadCode();
1298  if (Code == llvm::bitc::END_BLOCK ||
1299      Code == llvm::bitc::ENTER_SUBBLOCK ||
1300      Code == llvm::bitc::DEFINE_ABBREV) {
1301    Error("incorrectly-formatted source location entry in AST file");
1302    return true;
1303  }
1304
1305  RecordData Record;
1306  const char *BlobStart;
1307  unsigned BlobLen;
1308  switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1309  default:
1310    Error("incorrectly-formatted source location entry in AST file");
1311    return true;
1312
1313  case SM_SLOC_FILE_ENTRY: {
1314    // We will detect whether a file changed and return 'Failure' for it, but
1315    // we will also try to fail gracefully by setting up the SLocEntry.
1316    unsigned InputID = Record[4];
1317    InputFile IF = getInputFile(*F, InputID);
1318    const FileEntry *File = IF.getPointer();
1319    bool OverriddenBuffer = IF.getInt();
1320
1321    if (!IF.getPointer())
1322      return true;
1323
1324    SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1325    if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1326      // This is the module's main file.
1327      IncludeLoc = getImportLocation(F);
1328    }
1329    SrcMgr::CharacteristicKind
1330      FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1331    FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1332                                        ID, BaseOffset + Record[0]);
1333    SrcMgr::FileInfo &FileInfo =
1334          const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1335    FileInfo.NumCreatedFIDs = Record[5];
1336    if (Record[3])
1337      FileInfo.setHasLineDirectives();
1338
1339    const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1340    unsigned NumFileDecls = Record[7];
1341    if (NumFileDecls) {
1342      assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1343      FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1344                                                             NumFileDecls));
1345    }
1346
1347    const SrcMgr::ContentCache *ContentCache
1348      = SourceMgr.getOrCreateContentCache(File,
1349                              /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1350    if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1351        ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1352      unsigned Code = SLocEntryCursor.ReadCode();
1353      Record.clear();
1354      unsigned RecCode
1355        = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
1356
1357      if (RecCode != SM_SLOC_BUFFER_BLOB) {
1358        Error("AST record has invalid code");
1359        return true;
1360      }
1361
1362      llvm::MemoryBuffer *Buffer
1363        = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
1364                                           File->getName());
1365      SourceMgr.overrideFileContents(File, Buffer);
1366    }
1367
1368    break;
1369  }
1370
1371  case SM_SLOC_BUFFER_ENTRY: {
1372    const char *Name = BlobStart;
1373    unsigned Offset = Record[0];
1374    unsigned Code = SLocEntryCursor.ReadCode();
1375    Record.clear();
1376    unsigned RecCode
1377      = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
1378
1379    if (RecCode != SM_SLOC_BUFFER_BLOB) {
1380      Error("AST record has invalid code");
1381      return true;
1382    }
1383
1384    llvm::MemoryBuffer *Buffer
1385      = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
1386                                         Name);
1387    FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID,
1388                                                         BaseOffset + Offset);
1389
1390    if (strcmp(Name, "<built-in>") == 0 && F->Kind == MK_PCH) {
1391      PCHPredefinesBlock Block = {
1392        BufferID,
1393        StringRef(BlobStart, BlobLen - 1)
1394      };
1395      PCHPredefinesBuffers.push_back(Block);
1396    }
1397
1398    break;
1399  }
1400
1401  case SM_SLOC_EXPANSION_ENTRY: {
1402    SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1403    SourceMgr.createExpansionLoc(SpellingLoc,
1404                                     ReadSourceLocation(*F, Record[2]),
1405                                     ReadSourceLocation(*F, Record[3]),
1406                                     Record[4],
1407                                     ID,
1408                                     BaseOffset + Record[0]);
1409    break;
1410  }
1411  }
1412
1413  return false;
1414}
1415
1416/// \brief Find the location where the module F is imported.
1417SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1418  if (F->ImportLoc.isValid())
1419    return F->ImportLoc;
1420
1421  // Otherwise we have a PCH. It's considered to be "imported" at the first
1422  // location of its includer.
1423  if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1424    // Main file is the importer. We assume that it is the first entry in the
1425    // entry table. We can't ask the manager, because at the time of PCH loading
1426    // the main file entry doesn't exist yet.
1427    // The very first entry is the invalid instantiation loc, which takes up
1428    // offsets 0 and 1.
1429    return SourceLocation::getFromRawEncoding(2U);
1430  }
1431  //return F->Loaders[0]->FirstLoc;
1432  return F->ImportedBy[0]->FirstLoc;
1433}
1434
1435/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1436/// specified cursor.  Read the abbreviations that are at the top of the block
1437/// and then leave the cursor pointing into the block.
1438bool ASTReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1439                                 unsigned BlockID) {
1440  if (Cursor.EnterSubBlock(BlockID)) {
1441    Error("malformed block record in AST file");
1442    return Failure;
1443  }
1444
1445  while (true) {
1446    uint64_t Offset = Cursor.GetCurrentBitNo();
1447    unsigned Code = Cursor.ReadCode();
1448
1449    // We expect all abbrevs to be at the start of the block.
1450    if (Code != llvm::bitc::DEFINE_ABBREV) {
1451      Cursor.JumpToBit(Offset);
1452      return false;
1453    }
1454    Cursor.ReadAbbrevRecord();
1455  }
1456}
1457
1458void ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset,
1459                                MacroInfo *Hint) {
1460  llvm::BitstreamCursor &Stream = F.MacroCursor;
1461
1462  // Keep track of where we are in the stream, then jump back there
1463  // after reading this macro.
1464  SavedStreamPosition SavedPosition(Stream);
1465
1466  Stream.JumpToBit(Offset);
1467  RecordData Record;
1468  SmallVector<IdentifierInfo*, 16> MacroArgs;
1469  MacroInfo *Macro = 0;
1470
1471  // RAII object to add the loaded macro information once we're done
1472  // adding tokens.
1473  struct AddLoadedMacroInfoRAII {
1474    Preprocessor &PP;
1475    MacroInfo *Hint;
1476    MacroInfo *MI;
1477    IdentifierInfo *II;
1478
1479    AddLoadedMacroInfoRAII(Preprocessor &PP, MacroInfo *Hint)
1480      : PP(PP), Hint(Hint), MI(), II() { }
1481    ~AddLoadedMacroInfoRAII( ) {
1482      if (MI) {
1483        // Finally, install the macro.
1484        PP.addLoadedMacroInfo(II, MI, Hint);
1485      }
1486    }
1487  } AddLoadedMacroInfo(PP, Hint);
1488
1489  while (true) {
1490    unsigned Code = Stream.ReadCode();
1491    switch (Code) {
1492    case llvm::bitc::END_BLOCK:
1493      return;
1494
1495    case llvm::bitc::ENTER_SUBBLOCK:
1496      // No known subblocks, always skip them.
1497      Stream.ReadSubBlockID();
1498      if (Stream.SkipBlock()) {
1499        Error("malformed block record in AST file");
1500        return;
1501      }
1502      continue;
1503
1504    case llvm::bitc::DEFINE_ABBREV:
1505      Stream.ReadAbbrevRecord();
1506      continue;
1507    default: break;
1508    }
1509
1510    // Read a record.
1511    const char *BlobStart = 0;
1512    unsigned BlobLen = 0;
1513    Record.clear();
1514    PreprocessorRecordTypes RecType =
1515      (PreprocessorRecordTypes)Stream.ReadRecord(Code, Record, BlobStart,
1516                                                 BlobLen);
1517    switch (RecType) {
1518    case PP_MACRO_OBJECT_LIKE:
1519    case PP_MACRO_FUNCTION_LIKE: {
1520      // If we already have a macro, that means that we've hit the end
1521      // of the definition of the macro we were looking for. We're
1522      // done.
1523      if (Macro)
1524        return;
1525
1526      IdentifierInfo *II = getLocalIdentifier(F, Record[0]);
1527      if (II == 0) {
1528        Error("macro must have a name in AST file");
1529        return;
1530      }
1531
1532      unsigned GlobalID = getGlobalMacroID(F, Record[1]);
1533
1534      // If this macro has already been loaded, don't do so again.
1535      if (MacrosLoaded[GlobalID - NUM_PREDEF_MACRO_IDS])
1536        return;
1537
1538      SubmoduleID GlobalSubmoduleID = getGlobalSubmoduleID(F, Record[2]);
1539      unsigned NextIndex = 3;
1540      SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1541      MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1542
1543      // Record this macro.
1544      MacrosLoaded[GlobalID - NUM_PREDEF_MACRO_IDS] = MI;
1545
1546      SourceLocation UndefLoc = ReadSourceLocation(F, Record, NextIndex);
1547      if (UndefLoc.isValid())
1548        MI->setUndefLoc(UndefLoc);
1549
1550      MI->setIsUsed(Record[NextIndex++]);
1551      MI->setIsFromAST();
1552
1553      bool IsPublic = Record[NextIndex++];
1554      MI->setVisibility(IsPublic, ReadSourceLocation(F, Record, NextIndex));
1555
1556      if (RecType == PP_MACRO_FUNCTION_LIKE) {
1557        // Decode function-like macro info.
1558        bool isC99VarArgs = Record[NextIndex++];
1559        bool isGNUVarArgs = Record[NextIndex++];
1560        MacroArgs.clear();
1561        unsigned NumArgs = Record[NextIndex++];
1562        for (unsigned i = 0; i != NumArgs; ++i)
1563          MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1564
1565        // Install function-like macro info.
1566        MI->setIsFunctionLike();
1567        if (isC99VarArgs) MI->setIsC99Varargs();
1568        if (isGNUVarArgs) MI->setIsGNUVarargs();
1569        MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1570                            PP.getPreprocessorAllocator());
1571      }
1572
1573      if (DeserializationListener)
1574        DeserializationListener->MacroRead(GlobalID, MI);
1575
1576      // If an update record marked this as undefined, do so now.
1577      // FIXME: Only if the submodule this update came from is visible?
1578      MacroUpdatesMap::iterator Update = MacroUpdates.find(GlobalID);
1579      if (Update != MacroUpdates.end()) {
1580        if (MI->getUndefLoc().isInvalid()) {
1581          for (unsigned I = 0, N = Update->second.size(); I != N; ++I) {
1582            bool Hidden = false;
1583            if (unsigned SubmoduleID = Update->second[I].first) {
1584              if (Module *Owner = getSubmodule(SubmoduleID)) {
1585                if (Owner->NameVisibility == Module::Hidden) {
1586                  // Note that this #undef is hidden.
1587                  Hidden = true;
1588
1589                  // Record this hiding for later.
1590                  HiddenNamesMap[Owner].push_back(
1591                    HiddenName(II, MI, Update->second[I].second.UndefLoc));
1592                }
1593              }
1594            }
1595
1596            if (!Hidden) {
1597              MI->setUndefLoc(Update->second[I].second.UndefLoc);
1598              if (PPMutationListener *Listener = PP.getPPMutationListener())
1599                Listener->UndefinedMacro(MI);
1600              break;
1601            }
1602          }
1603        }
1604        MacroUpdates.erase(Update);
1605      }
1606
1607      // Determine whether this macro definition is visible.
1608      bool Hidden = !MI->isPublic();
1609      if (!Hidden && GlobalSubmoduleID) {
1610        if (Module *Owner = getSubmodule(GlobalSubmoduleID)) {
1611          if (Owner->NameVisibility == Module::Hidden) {
1612            // The owning module is not visible, and this macro definition
1613            // should not be, either.
1614            Hidden = true;
1615
1616            // Note that this macro definition was hidden because its owning
1617            // module is not yet visible.
1618            HiddenNamesMap[Owner].push_back(HiddenName(II, MI));
1619          }
1620        }
1621      }
1622      MI->setHidden(Hidden);
1623
1624      // Make sure we install the macro once we're done.
1625      AddLoadedMacroInfo.MI = MI;
1626      AddLoadedMacroInfo.II = II;
1627
1628      // Remember that we saw this macro last so that we add the tokens that
1629      // form its body to it.
1630      Macro = MI;
1631
1632      if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1633          Record[NextIndex]) {
1634        // We have a macro definition. Register the association
1635        PreprocessedEntityID
1636            GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1637        PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1638        PPRec.RegisterMacroDefinition(Macro,
1639                            PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true));
1640      }
1641
1642      ++NumMacrosRead;
1643      break;
1644    }
1645
1646    case PP_TOKEN: {
1647      // If we see a TOKEN before a PP_MACRO_*, then the file is
1648      // erroneous, just pretend we didn't see this.
1649      if (Macro == 0) break;
1650
1651      Token Tok;
1652      Tok.startToken();
1653      Tok.setLocation(ReadSourceLocation(F, Record[0]));
1654      Tok.setLength(Record[1]);
1655      if (IdentifierInfo *II = getLocalIdentifier(F, Record[2]))
1656        Tok.setIdentifierInfo(II);
1657      Tok.setKind((tok::TokenKind)Record[3]);
1658      Tok.setFlag((Token::TokenFlags)Record[4]);
1659      Macro->AddTokenToBody(Tok);
1660      break;
1661    }
1662    }
1663  }
1664}
1665
1666PreprocessedEntityID
1667ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1668  ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1669    I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1670  assert(I != M.PreprocessedEntityRemap.end()
1671         && "Invalid index into preprocessed entity index remap");
1672
1673  return LocalID + I->second;
1674}
1675
1676unsigned HeaderFileInfoTrait::ComputeHash(const char *path) {
1677  return llvm::HashString(llvm::sys::path::filename(path));
1678}
1679
1680HeaderFileInfoTrait::internal_key_type
1681HeaderFileInfoTrait::GetInternalKey(const char *path) { return path; }
1682
1683bool HeaderFileInfoTrait::EqualKey(internal_key_type a, internal_key_type b) {
1684  if (strcmp(a, b) == 0)
1685    return true;
1686
1687  if (llvm::sys::path::filename(a) != llvm::sys::path::filename(b))
1688    return false;
1689
1690  // Determine whether the actual files are equivalent.
1691  bool Result = false;
1692  if (llvm::sys::fs::equivalent(a, b, Result))
1693    return false;
1694
1695  return Result;
1696}
1697
1698std::pair<unsigned, unsigned>
1699HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1700  unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1701  unsigned DataLen = (unsigned) *d++;
1702  return std::make_pair(KeyLen + 1, DataLen);
1703}
1704
1705HeaderFileInfoTrait::data_type
1706HeaderFileInfoTrait::ReadData(const internal_key_type, const unsigned char *d,
1707                              unsigned DataLen) {
1708  const unsigned char *End = d + DataLen;
1709  using namespace clang::io;
1710  HeaderFileInfo HFI;
1711  unsigned Flags = *d++;
1712  HFI.isImport = (Flags >> 5) & 0x01;
1713  HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1714  HFI.DirInfo = (Flags >> 2) & 0x03;
1715  HFI.Resolved = (Flags >> 1) & 0x01;
1716  HFI.IndexHeaderMapHeader = Flags & 0x01;
1717  HFI.NumIncludes = ReadUnalignedLE16(d);
1718  HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1719                                                        ReadUnalignedLE32(d));
1720  if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1721    // The framework offset is 1 greater than the actual offset,
1722    // since 0 is used as an indicator for "no framework name".
1723    StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1724    HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1725  }
1726
1727  assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1728  (void)End;
1729
1730  // This HeaderFileInfo was externally loaded.
1731  HFI.External = true;
1732  return HFI;
1733}
1734
1735void ASTReader::setIdentifierIsMacro(IdentifierInfo *II, ArrayRef<MacroID> IDs){
1736  II->setHadMacroDefinition(true);
1737  assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1738  PendingMacroIDs[II].append(IDs.begin(), IDs.end());
1739}
1740
1741void ASTReader::ReadDefinedMacros() {
1742  // Note that we are loading defined macros.
1743  Deserializing Macros(this);
1744
1745  for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1746      E = ModuleMgr.rend(); I != E; ++I) {
1747    llvm::BitstreamCursor &MacroCursor = (*I)->MacroCursor;
1748
1749    // If there was no preprocessor block, skip this file.
1750    if (!MacroCursor.getBitStreamReader())
1751      continue;
1752
1753    llvm::BitstreamCursor Cursor = MacroCursor;
1754    Cursor.JumpToBit((*I)->MacroStartOffset);
1755
1756    RecordData Record;
1757    while (true) {
1758      unsigned Code = Cursor.ReadCode();
1759      if (Code == llvm::bitc::END_BLOCK)
1760        break;
1761
1762      if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1763        // No known subblocks, always skip them.
1764        Cursor.ReadSubBlockID();
1765        if (Cursor.SkipBlock()) {
1766          Error("malformed block record in AST file");
1767          return;
1768        }
1769        continue;
1770      }
1771
1772      if (Code == llvm::bitc::DEFINE_ABBREV) {
1773        Cursor.ReadAbbrevRecord();
1774        continue;
1775      }
1776
1777      // Read a record.
1778      const char *BlobStart;
1779      unsigned BlobLen;
1780      Record.clear();
1781      switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1782      default:  // Default behavior: ignore.
1783        break;
1784
1785      case PP_MACRO_OBJECT_LIKE:
1786      case PP_MACRO_FUNCTION_LIKE:
1787        getLocalIdentifier(**I, Record[0]);
1788        break;
1789
1790      case PP_TOKEN:
1791        // Ignore tokens.
1792        break;
1793      }
1794    }
1795  }
1796}
1797
1798namespace {
1799  /// \brief Visitor class used to look up identifirs in an AST file.
1800  class IdentifierLookupVisitor {
1801    StringRef Name;
1802    unsigned PriorGeneration;
1803    IdentifierInfo *Found;
1804  public:
1805    IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration)
1806      : Name(Name), PriorGeneration(PriorGeneration), Found() { }
1807
1808    static bool visit(ModuleFile &M, void *UserData) {
1809      IdentifierLookupVisitor *This
1810        = static_cast<IdentifierLookupVisitor *>(UserData);
1811
1812      // If we've already searched this module file, skip it now.
1813      if (M.Generation <= This->PriorGeneration)
1814        return true;
1815
1816      ASTIdentifierLookupTable *IdTable
1817        = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1818      if (!IdTable)
1819        return false;
1820
1821      ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1822                                     M, This->Found);
1823
1824      std::pair<const char*, unsigned> Key(This->Name.begin(),
1825                                           This->Name.size());
1826      ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Trait);
1827      if (Pos == IdTable->end())
1828        return false;
1829
1830      // Dereferencing the iterator has the effect of building the
1831      // IdentifierInfo node and populating it with the various
1832      // declarations it needs.
1833      This->Found = *Pos;
1834      return true;
1835    }
1836
1837    // \brief Retrieve the identifier info found within the module
1838    // files.
1839    IdentifierInfo *getIdentifierInfo() const { return Found; }
1840  };
1841}
1842
1843void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1844  // Note that we are loading an identifier.
1845  Deserializing AnIdentifier(this);
1846
1847  unsigned PriorGeneration = 0;
1848  if (getContext().getLangOpts().Modules)
1849    PriorGeneration = IdentifierGeneration[&II];
1850
1851  IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration);
1852  ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
1853  markIdentifierUpToDate(&II);
1854}
1855
1856void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1857  if (!II)
1858    return;
1859
1860  II->setOutOfDate(false);
1861
1862  // Update the generation for this identifier.
1863  if (getContext().getLangOpts().Modules)
1864    IdentifierGeneration[II] = CurrentGeneration;
1865}
1866
1867llvm::PointerIntPair<const FileEntry *, 1, bool>
1868ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
1869  // If this ID is bogus, just return an empty input file.
1870  if (ID == 0 || ID > F.InputFilesLoaded.size())
1871    return InputFile();
1872
1873  // If we've already loaded this input file, return it.
1874  if (F.InputFilesLoaded[ID-1].getPointer())
1875    return F.InputFilesLoaded[ID-1];
1876
1877  // Go find this input file.
1878  llvm::BitstreamCursor &Cursor = F.InputFilesCursor;
1879  SavedStreamPosition SavedPosition(Cursor);
1880  Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1881
1882  unsigned Code = Cursor.ReadCode();
1883  RecordData Record;
1884  const char *BlobStart = 0;
1885  unsigned BlobLen = 0;
1886  switch ((InputFileRecordTypes)Cursor.ReadRecord(Code, Record,
1887                                                  &BlobStart, &BlobLen)) {
1888  case INPUT_FILE: {
1889    unsigned StoredID = Record[0];
1890    assert(ID == StoredID && "Bogus stored ID or offset");
1891    (void)StoredID;
1892    off_t StoredSize = (off_t)Record[1];
1893    time_t StoredTime = (time_t)Record[2];
1894    bool Overridden = (bool)Record[3];
1895
1896    // Get the file entry for this input file.
1897    StringRef OrigFilename(BlobStart, BlobLen);
1898    std::string Filename = OrigFilename;
1899    MaybeAddSystemRootToFilename(F, Filename);
1900    const FileEntry *File
1901      = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1902                  : FileMgr.getFile(Filename, /*OpenFile=*/false);
1903
1904    // If we didn't find the file, resolve it relative to the
1905    // original directory from which this AST file was created.
1906    if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1907        F.OriginalDir != CurrentDir) {
1908      std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1909                                                              F.OriginalDir,
1910                                                              CurrentDir);
1911      if (!Resolved.empty())
1912        File = FileMgr.getFile(Resolved);
1913    }
1914
1915    // For an overridden file, create a virtual file with the stored
1916    // size/timestamp.
1917    if (Overridden && File == 0) {
1918      File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1919    }
1920
1921    if (File == 0) {
1922      if (Complain) {
1923        std::string ErrorStr = "could not find file '";
1924        ErrorStr += Filename;
1925        ErrorStr += "' referenced by AST file";
1926        Error(ErrorStr.c_str());
1927      }
1928      return InputFile();
1929    }
1930
1931    // Note that we've loaded this input file.
1932    F.InputFilesLoaded[ID-1] = InputFile(File, Overridden);
1933
1934    // Check if there was a request to override the contents of the file
1935    // that was part of the precompiled header. Overridding such a file
1936    // can lead to problems when lexing using the source locations from the
1937    // PCH.
1938    SourceManager &SM = getSourceManager();
1939    if (!Overridden && SM.isFileOverridden(File)) {
1940      Error(diag::err_fe_pch_file_overridden, Filename);
1941      // After emitting the diagnostic, recover by disabling the override so
1942      // that the original file will be used.
1943      SM.disableFileContentsOverride(File);
1944      // The FileEntry is a virtual file entry with the size of the contents
1945      // that would override the original contents. Set it to the original's
1946      // size/time.
1947      FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1948                              StoredSize, StoredTime);
1949    }
1950
1951    // For an overridden file, there is nothing to validate.
1952    if (Overridden)
1953      return InputFile(File, Overridden);
1954
1955    // The stat info from the FileEntry came from the cached stat
1956    // info of the PCH, so we cannot trust it.
1957    struct stat StatBuf;
1958    if (::stat(File->getName(), &StatBuf) != 0) {
1959      StatBuf.st_size = File->getSize();
1960      StatBuf.st_mtime = File->getModificationTime();
1961    }
1962
1963    if ((StoredSize != StatBuf.st_size
1964#if !defined(LLVM_ON_WIN32)
1965         // In our regression testing, the Windows file system seems to
1966         // have inconsistent modification times that sometimes
1967         // erroneously trigger this error-handling path.
1968         || StoredTime != StatBuf.st_mtime
1969#endif
1970         )) {
1971      if (Complain)
1972        Error(diag::err_fe_pch_file_modified, Filename);
1973
1974      return InputFile();
1975    }
1976
1977    return InputFile(File, Overridden);
1978  }
1979  }
1980
1981  return InputFile();
1982}
1983
1984const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
1985  ModuleFile &M = ModuleMgr.getPrimaryModule();
1986  std::string Filename = filenameStrRef;
1987  MaybeAddSystemRootToFilename(M, Filename);
1988  const FileEntry *File = FileMgr.getFile(Filename);
1989  if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
1990      M.OriginalDir != CurrentDir) {
1991    std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1992                                                            M.OriginalDir,
1993                                                            CurrentDir);
1994    if (!resolved.empty())
1995      File = FileMgr.getFile(resolved);
1996  }
1997
1998  return File;
1999}
2000
2001/// \brief If we are loading a relocatable PCH file, and the filename is
2002/// not an absolute path, add the system root to the beginning of the file
2003/// name.
2004StringRef ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2005                                                  std::string &Filename) {
2006  // If this is not a relocatable PCH file, there's nothing to do.
2007  if (!M.RelocatablePCH)
2008    return Filename;
2009
2010  if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2011    return Filename;
2012
2013  if (isysroot.empty()) {
2014    // If no system root was given, default to '/'
2015    Filename.insert(Filename.begin(), '/');
2016    return Filename;
2017  }
2018
2019  unsigned Length = isysroot.size();
2020  if (isysroot[Length - 1] != '/')
2021    Filename.insert(Filename.begin(), '/');
2022
2023  Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2024  return Filename;
2025}
2026
2027ASTReader::ASTReadResult
2028ASTReader::ReadControlBlock(ModuleFile &F,
2029                            llvm::SmallVectorImpl<ModuleFile *> &Loaded,
2030                            unsigned ClientLoadCapabilities) {
2031  llvm::BitstreamCursor &Stream = F.Stream;
2032
2033  if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2034    Error("malformed block record in AST file");
2035    return Failure;
2036  }
2037
2038  // Read all of the records and blocks in the control block.
2039  RecordData Record;
2040  while (!Stream.AtEndOfStream()) {
2041    unsigned Code = Stream.ReadCode();
2042    if (Code == llvm::bitc::END_BLOCK) {
2043      if (Stream.ReadBlockEnd()) {
2044        Error("error at end of control block in AST file");
2045        return Failure;
2046      }
2047
2048      // Validate all of the input files.
2049      if (!DisableValidation) {
2050        bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2051        for (unsigned I = 0, N = Record[0]; I < N; ++I)
2052          if (!getInputFile(F, I+1, Complain).getPointer())
2053            return OutOfDate;
2054      }
2055
2056      return Success;
2057    }
2058
2059    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2060      switch (Stream.ReadSubBlockID()) {
2061      case INPUT_FILES_BLOCK_ID:
2062        F.InputFilesCursor = Stream;
2063        if (Stream.SkipBlock() || // Skip with the main cursor
2064            // Read the abbreviations
2065            ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2066          Error("malformed block record in AST file");
2067          return Failure;
2068        }
2069        continue;
2070
2071      default:
2072        if (!Stream.SkipBlock())
2073          continue;
2074        break;
2075      }
2076
2077      Error("malformed block record in AST file");
2078      return Failure;
2079    }
2080
2081    if (Code == llvm::bitc::DEFINE_ABBREV) {
2082      Stream.ReadAbbrevRecord();
2083      continue;
2084    }
2085
2086    // Read and process a record.
2087    Record.clear();
2088    const char *BlobStart = 0;
2089    unsigned BlobLen = 0;
2090    switch ((ControlRecordTypes)Stream.ReadRecord(Code, Record,
2091                                                  &BlobStart, &BlobLen)) {
2092    case METADATA: {
2093      if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2094        if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2095          Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
2096                                        : diag::warn_pch_version_too_new);
2097        return VersionMismatch;
2098      }
2099
2100      bool hasErrors = Record[5];
2101      if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2102        Diag(diag::err_pch_with_compiler_errors);
2103        return HadErrors;
2104      }
2105
2106      F.RelocatablePCH = Record[4];
2107
2108      const std::string &CurBranch = getClangFullRepositoryVersion();
2109      StringRef ASTBranch(BlobStart, BlobLen);
2110      if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2111        if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2112          Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
2113        return VersionMismatch;
2114      }
2115      break;
2116    }
2117
2118    case IMPORTS: {
2119      // Load each of the imported PCH files.
2120      unsigned Idx = 0, N = Record.size();
2121      while (Idx < N) {
2122        // Read information about the AST file.
2123        ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2124        unsigned Length = Record[Idx++];
2125        SmallString<128> ImportedFile(Record.begin() + Idx,
2126                                      Record.begin() + Idx + Length);
2127        Idx += Length;
2128
2129        // Load the AST file.
2130        switch(ReadASTCore(ImportedFile, ImportedKind, &F, Loaded,
2131                           ClientLoadCapabilities)) {
2132        case Failure: return Failure;
2133          // If we have to ignore the dependency, we'll have to ignore this too.
2134        case OutOfDate: return OutOfDate;
2135        case VersionMismatch: return VersionMismatch;
2136        case ConfigurationMismatch: return ConfigurationMismatch;
2137        case HadErrors: return HadErrors;
2138        case Success: break;
2139        }
2140      }
2141      break;
2142    }
2143
2144    case LANGUAGE_OPTIONS: {
2145      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2146      if (Listener && &F == *ModuleMgr.begin() &&
2147          ParseLanguageOptions(Record, Complain, *Listener) &&
2148          !DisableValidation)
2149        return ConfigurationMismatch;
2150      break;
2151    }
2152
2153    case TARGET_OPTIONS: {
2154      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2155      if (Listener && &F == *ModuleMgr.begin() &&
2156          ParseTargetOptions(Record, Complain, *Listener) &&
2157          !DisableValidation)
2158        return ConfigurationMismatch;
2159      break;
2160    }
2161
2162    case DIAGNOSTIC_OPTIONS: {
2163      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2164      if (Listener && &F == *ModuleMgr.begin() &&
2165          ParseDiagnosticOptions(Record, Complain, *Listener) &&
2166          !DisableValidation)
2167        return ConfigurationMismatch;
2168      break;
2169    }
2170
2171    case FILE_SYSTEM_OPTIONS: {
2172      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2173      if (Listener && &F == *ModuleMgr.begin() &&
2174          ParseFileSystemOptions(Record, Complain, *Listener) &&
2175          !DisableValidation)
2176        return ConfigurationMismatch;
2177      break;
2178    }
2179
2180    case HEADER_SEARCH_OPTIONS: {
2181      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2182      if (Listener && &F == *ModuleMgr.begin() &&
2183          ParseHeaderSearchOptions(Record, Complain, *Listener) &&
2184          !DisableValidation)
2185        return ConfigurationMismatch;
2186      break;
2187    }
2188
2189    case PREPROCESSOR_OPTIONS: {
2190      bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2191      if (Listener && &F == *ModuleMgr.begin() &&
2192          ParsePreprocessorOptions(Record, Complain, *Listener,
2193                                   SuggestedPredefines) &&
2194          !DisableValidation)
2195        return ConfigurationMismatch;
2196      break;
2197    }
2198
2199    case ORIGINAL_FILE:
2200      F.OriginalSourceFileID = FileID::get(Record[0]);
2201      F.ActualOriginalSourceFileName.assign(BlobStart, BlobLen);
2202      F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2203      MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2204      break;
2205
2206    case ORIGINAL_PCH_DIR:
2207      F.OriginalDir.assign(BlobStart, BlobLen);
2208      break;
2209
2210    case INPUT_FILE_OFFSETS:
2211      F.InputFileOffsets = (const uint32_t *)BlobStart;
2212      F.InputFilesLoaded.resize(Record[0]);
2213      break;
2214    }
2215  }
2216
2217  Error("premature end of bitstream in AST file");
2218  return Failure;
2219}
2220
2221bool ASTReader::ReadASTBlock(ModuleFile &F) {
2222  llvm::BitstreamCursor &Stream = F.Stream;
2223
2224  if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2225    Error("malformed block record in AST file");
2226    return true;
2227  }
2228
2229  // Read all of the records and blocks for the AST file.
2230  RecordData Record;
2231  while (!Stream.AtEndOfStream()) {
2232    unsigned Code = Stream.ReadCode();
2233    if (Code == llvm::bitc::END_BLOCK) {
2234      if (Stream.ReadBlockEnd()) {
2235        Error("error at end of module block in AST file");
2236        return true;
2237      }
2238
2239      DeclContext *DC = Context.getTranslationUnitDecl();
2240      if (!DC->hasExternalVisibleStorage() && DC->hasExternalLexicalStorage())
2241        DC->setMustBuildLookupTable();
2242
2243      return false;
2244    }
2245
2246    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2247      switch (Stream.ReadSubBlockID()) {
2248      case DECLTYPES_BLOCK_ID:
2249        // We lazily load the decls block, but we want to set up the
2250        // DeclsCursor cursor to point into it.  Clone our current bitcode
2251        // cursor to it, enter the block and read the abbrevs in that block.
2252        // With the main cursor, we just skip over it.
2253        F.DeclsCursor = Stream;
2254        if (Stream.SkipBlock() ||  // Skip with the main cursor.
2255            // Read the abbrevs.
2256            ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2257          Error("malformed block record in AST file");
2258          return true;
2259        }
2260        break;
2261
2262      case DECL_UPDATES_BLOCK_ID:
2263        if (Stream.SkipBlock()) {
2264          Error("malformed block record in AST file");
2265          return true;
2266        }
2267        break;
2268
2269      case PREPROCESSOR_BLOCK_ID:
2270        F.MacroCursor = Stream;
2271        if (!PP.getExternalSource())
2272          PP.setExternalSource(this);
2273
2274        if (Stream.SkipBlock() ||
2275            ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2276          Error("malformed block record in AST file");
2277          return true;
2278        }
2279        F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2280        break;
2281
2282      case PREPROCESSOR_DETAIL_BLOCK_ID:
2283        F.PreprocessorDetailCursor = Stream;
2284        if (Stream.SkipBlock() ||
2285            ReadBlockAbbrevs(F.PreprocessorDetailCursor,
2286                             PREPROCESSOR_DETAIL_BLOCK_ID)) {
2287          Error("malformed preprocessor detail record in AST file");
2288          return true;
2289        }
2290        F.PreprocessorDetailStartOffset
2291          = F.PreprocessorDetailCursor.GetCurrentBitNo();
2292
2293        if (!PP.getPreprocessingRecord())
2294          PP.createPreprocessingRecord(/*RecordConditionalDirectives=*/false);
2295        if (!PP.getPreprocessingRecord()->getExternalSource())
2296          PP.getPreprocessingRecord()->SetExternalSource(*this);
2297        break;
2298
2299      case SOURCE_MANAGER_BLOCK_ID:
2300        if (ReadSourceManagerBlock(F))
2301          return true;
2302        break;
2303
2304      case SUBMODULE_BLOCK_ID:
2305        if (ReadSubmoduleBlock(F))
2306          return true;
2307        break;
2308
2309      case COMMENTS_BLOCK_ID: {
2310        llvm::BitstreamCursor C = Stream;
2311        if (Stream.SkipBlock() ||
2312            ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2313          Error("malformed comments block in AST file");
2314          return true;
2315        }
2316        CommentsCursors.push_back(std::make_pair(C, &F));
2317        break;
2318      }
2319
2320      default:
2321        if (!Stream.SkipBlock())
2322          break;
2323        Error("malformed block record in AST file");
2324        return true;
2325      }
2326      continue;
2327    }
2328
2329    if (Code == llvm::bitc::DEFINE_ABBREV) {
2330      Stream.ReadAbbrevRecord();
2331      continue;
2332    }
2333
2334    // Read and process a record.
2335    Record.clear();
2336    const char *BlobStart = 0;
2337    unsigned BlobLen = 0;
2338    switch ((ASTRecordTypes)Stream.ReadRecord(Code, Record,
2339                                              &BlobStart, &BlobLen)) {
2340    default:  // Default behavior: ignore.
2341      break;
2342
2343    case TYPE_OFFSET: {
2344      if (F.LocalNumTypes != 0) {
2345        Error("duplicate TYPE_OFFSET record in AST file");
2346        return true;
2347      }
2348      F.TypeOffsets = (const uint32_t *)BlobStart;
2349      F.LocalNumTypes = Record[0];
2350      unsigned LocalBaseTypeIndex = Record[1];
2351      F.BaseTypeIndex = getTotalNumTypes();
2352
2353      if (F.LocalNumTypes > 0) {
2354        // Introduce the global -> local mapping for types within this module.
2355        GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2356
2357        // Introduce the local -> global mapping for types within this module.
2358        F.TypeRemap.insertOrReplace(
2359          std::make_pair(LocalBaseTypeIndex,
2360                         F.BaseTypeIndex - LocalBaseTypeIndex));
2361
2362        TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2363      }
2364      break;
2365    }
2366
2367    case DECL_OFFSET: {
2368      if (F.LocalNumDecls != 0) {
2369        Error("duplicate DECL_OFFSET record in AST file");
2370        return true;
2371      }
2372      F.DeclOffsets = (const DeclOffset *)BlobStart;
2373      F.LocalNumDecls = Record[0];
2374      unsigned LocalBaseDeclID = Record[1];
2375      F.BaseDeclID = getTotalNumDecls();
2376
2377      if (F.LocalNumDecls > 0) {
2378        // Introduce the global -> local mapping for declarations within this
2379        // module.
2380        GlobalDeclMap.insert(
2381          std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2382
2383        // Introduce the local -> global mapping for declarations within this
2384        // module.
2385        F.DeclRemap.insertOrReplace(
2386          std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2387
2388        // Introduce the global -> local mapping for declarations within this
2389        // module.
2390        F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2391
2392        DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2393      }
2394      break;
2395    }
2396
2397    case TU_UPDATE_LEXICAL: {
2398      DeclContext *TU = Context.getTranslationUnitDecl();
2399      DeclContextInfo &Info = F.DeclContextInfos[TU];
2400      Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(BlobStart);
2401      Info.NumLexicalDecls
2402        = static_cast<unsigned int>(BlobLen / sizeof(KindDeclIDPair));
2403      TU->setHasExternalLexicalStorage(true);
2404      break;
2405    }
2406
2407    case UPDATE_VISIBLE: {
2408      unsigned Idx = 0;
2409      serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2410      ASTDeclContextNameLookupTable *Table =
2411        ASTDeclContextNameLookupTable::Create(
2412                        (const unsigned char *)BlobStart + Record[Idx++],
2413                        (const unsigned char *)BlobStart,
2414                        ASTDeclContextNameLookupTrait(*this, F));
2415      if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2416        DeclContext *TU = Context.getTranslationUnitDecl();
2417        F.DeclContextInfos[TU].NameLookupTableData = Table;
2418        TU->setHasExternalVisibleStorage(true);
2419      } else
2420        PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2421      break;
2422    }
2423
2424    case IDENTIFIER_TABLE:
2425      F.IdentifierTableData = BlobStart;
2426      if (Record[0]) {
2427        F.IdentifierLookupTable
2428          = ASTIdentifierLookupTable::Create(
2429                       (const unsigned char *)F.IdentifierTableData + Record[0],
2430                       (const unsigned char *)F.IdentifierTableData,
2431                       ASTIdentifierLookupTrait(*this, F));
2432
2433        PP.getIdentifierTable().setExternalIdentifierLookup(this);
2434      }
2435      break;
2436
2437    case IDENTIFIER_OFFSET: {
2438      if (F.LocalNumIdentifiers != 0) {
2439        Error("duplicate IDENTIFIER_OFFSET record in AST file");
2440        return true;
2441      }
2442      F.IdentifierOffsets = (const uint32_t *)BlobStart;
2443      F.LocalNumIdentifiers = Record[0];
2444      unsigned LocalBaseIdentifierID = Record[1];
2445      F.BaseIdentifierID = getTotalNumIdentifiers();
2446
2447      if (F.LocalNumIdentifiers > 0) {
2448        // Introduce the global -> local mapping for identifiers within this
2449        // module.
2450        GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2451                                                  &F));
2452
2453        // Introduce the local -> global mapping for identifiers within this
2454        // module.
2455        F.IdentifierRemap.insertOrReplace(
2456          std::make_pair(LocalBaseIdentifierID,
2457                         F.BaseIdentifierID - LocalBaseIdentifierID));
2458
2459        IdentifiersLoaded.resize(IdentifiersLoaded.size()
2460                                 + F.LocalNumIdentifiers);
2461      }
2462      break;
2463    }
2464
2465    case EXTERNAL_DEFINITIONS:
2466      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2467        ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2468      break;
2469
2470    case SPECIAL_TYPES:
2471      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2472        SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2473      break;
2474
2475    case STATISTICS:
2476      TotalNumStatements += Record[0];
2477      TotalNumMacros += Record[1];
2478      TotalLexicalDeclContexts += Record[2];
2479      TotalVisibleDeclContexts += Record[3];
2480      break;
2481
2482    case UNUSED_FILESCOPED_DECLS:
2483      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2484        UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2485      break;
2486
2487    case DELEGATING_CTORS:
2488      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2489        DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2490      break;
2491
2492    case WEAK_UNDECLARED_IDENTIFIERS:
2493      if (Record.size() % 4 != 0) {
2494        Error("invalid weak identifiers record");
2495        return true;
2496      }
2497
2498      // FIXME: Ignore weak undeclared identifiers from non-original PCH
2499      // files. This isn't the way to do it :)
2500      WeakUndeclaredIdentifiers.clear();
2501
2502      // Translate the weak, undeclared identifiers into global IDs.
2503      for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2504        WeakUndeclaredIdentifiers.push_back(
2505          getGlobalIdentifierID(F, Record[I++]));
2506        WeakUndeclaredIdentifiers.push_back(
2507          getGlobalIdentifierID(F, Record[I++]));
2508        WeakUndeclaredIdentifiers.push_back(
2509          ReadSourceLocation(F, Record, I).getRawEncoding());
2510        WeakUndeclaredIdentifiers.push_back(Record[I++]);
2511      }
2512      break;
2513
2514    case LOCALLY_SCOPED_EXTERNAL_DECLS:
2515      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2516        LocallyScopedExternalDecls.push_back(getGlobalDeclID(F, Record[I]));
2517      break;
2518
2519    case SELECTOR_OFFSETS: {
2520      F.SelectorOffsets = (const uint32_t *)BlobStart;
2521      F.LocalNumSelectors = Record[0];
2522      unsigned LocalBaseSelectorID = Record[1];
2523      F.BaseSelectorID = getTotalNumSelectors();
2524
2525      if (F.LocalNumSelectors > 0) {
2526        // Introduce the global -> local mapping for selectors within this
2527        // module.
2528        GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2529
2530        // Introduce the local -> global mapping for selectors within this
2531        // module.
2532        F.SelectorRemap.insertOrReplace(
2533          std::make_pair(LocalBaseSelectorID,
2534                         F.BaseSelectorID - LocalBaseSelectorID));
2535
2536        SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2537      }
2538      break;
2539    }
2540
2541    case METHOD_POOL:
2542      F.SelectorLookupTableData = (const unsigned char *)BlobStart;
2543      if (Record[0])
2544        F.SelectorLookupTable
2545          = ASTSelectorLookupTable::Create(
2546                        F.SelectorLookupTableData + Record[0],
2547                        F.SelectorLookupTableData,
2548                        ASTSelectorLookupTrait(*this, F));
2549      TotalNumMethodPoolEntries += Record[1];
2550      break;
2551
2552    case REFERENCED_SELECTOR_POOL:
2553      if (!Record.empty()) {
2554        for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2555          ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2556                                                                Record[Idx++]));
2557          ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2558                                              getRawEncoding());
2559        }
2560      }
2561      break;
2562
2563    case PP_COUNTER_VALUE:
2564      if (!Record.empty() && Listener)
2565        Listener->ReadCounter(F, Record[0]);
2566      break;
2567
2568    case FILE_SORTED_DECLS:
2569      F.FileSortedDecls = (const DeclID *)BlobStart;
2570      F.NumFileSortedDecls = Record[0];
2571      break;
2572
2573    case SOURCE_LOCATION_OFFSETS: {
2574      F.SLocEntryOffsets = (const uint32_t *)BlobStart;
2575      F.LocalNumSLocEntries = Record[0];
2576      unsigned SLocSpaceSize = Record[1];
2577      llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2578          SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2579                                              SLocSpaceSize);
2580      // Make our entry in the range map. BaseID is negative and growing, so
2581      // we invert it. Because we invert it, though, we need the other end of
2582      // the range.
2583      unsigned RangeStart =
2584          unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2585      GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2586      F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2587
2588      // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2589      assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2590      GlobalSLocOffsetMap.insert(
2591          std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2592                           - SLocSpaceSize,&F));
2593
2594      // Initialize the remapping table.
2595      // Invalid stays invalid.
2596      F.SLocRemap.insert(std::make_pair(0U, 0));
2597      // This module. Base was 2 when being compiled.
2598      F.SLocRemap.insert(std::make_pair(2U,
2599                                  static_cast<int>(F.SLocEntryBaseOffset - 2)));
2600
2601      TotalNumSLocEntries += F.LocalNumSLocEntries;
2602      break;
2603    }
2604
2605    case MODULE_OFFSET_MAP: {
2606      // Additional remapping information.
2607      const unsigned char *Data = (const unsigned char*)BlobStart;
2608      const unsigned char *DataEnd = Data + BlobLen;
2609
2610      // Continuous range maps we may be updating in our module.
2611      ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2612      ContinuousRangeMap<uint32_t, int, 2>::Builder
2613        IdentifierRemap(F.IdentifierRemap);
2614      ContinuousRangeMap<uint32_t, int, 2>::Builder
2615        MacroRemap(F.MacroRemap);
2616      ContinuousRangeMap<uint32_t, int, 2>::Builder
2617        PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2618      ContinuousRangeMap<uint32_t, int, 2>::Builder
2619        SubmoduleRemap(F.SubmoduleRemap);
2620      ContinuousRangeMap<uint32_t, int, 2>::Builder
2621        SelectorRemap(F.SelectorRemap);
2622      ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2623      ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2624
2625      while(Data < DataEnd) {
2626        uint16_t Len = io::ReadUnalignedLE16(Data);
2627        StringRef Name = StringRef((const char*)Data, Len);
2628        Data += Len;
2629        ModuleFile *OM = ModuleMgr.lookup(Name);
2630        if (!OM) {
2631          Error("SourceLocation remap refers to unknown module");
2632          return true;
2633        }
2634
2635        uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2636        uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2637        uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2638        uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2639        uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2640        uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2641        uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2642        uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2643
2644        // Source location offset is mapped to OM->SLocEntryBaseOffset.
2645        SLocRemap.insert(std::make_pair(SLocOffset,
2646          static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2647        IdentifierRemap.insert(
2648          std::make_pair(IdentifierIDOffset,
2649                         OM->BaseIdentifierID - IdentifierIDOffset));
2650        MacroRemap.insert(std::make_pair(MacroIDOffset,
2651                                         OM->BaseMacroID - MacroIDOffset));
2652        PreprocessedEntityRemap.insert(
2653          std::make_pair(PreprocessedEntityIDOffset,
2654            OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2655        SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2656                                      OM->BaseSubmoduleID - SubmoduleIDOffset));
2657        SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2658                               OM->BaseSelectorID - SelectorIDOffset));
2659        DeclRemap.insert(std::make_pair(DeclIDOffset,
2660                                        OM->BaseDeclID - DeclIDOffset));
2661
2662        TypeRemap.insert(std::make_pair(TypeIndexOffset,
2663                                    OM->BaseTypeIndex - TypeIndexOffset));
2664
2665        // Global -> local mappings.
2666        F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2667      }
2668      break;
2669    }
2670
2671    case SOURCE_MANAGER_LINE_TABLE:
2672      if (ParseLineTable(F, Record))
2673        return true;
2674      break;
2675
2676    case SOURCE_LOCATION_PRELOADS: {
2677      // Need to transform from the local view (1-based IDs) to the global view,
2678      // which is based off F.SLocEntryBaseID.
2679      if (!F.PreloadSLocEntries.empty()) {
2680        Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2681        return true;
2682      }
2683
2684      F.PreloadSLocEntries.swap(Record);
2685      break;
2686    }
2687
2688    case STAT_CACHE: {
2689      if (!DisableStatCache) {
2690        ASTStatCache *MyStatCache =
2691          new ASTStatCache((const unsigned char *)BlobStart + Record[0],
2692                           (const unsigned char *)BlobStart,
2693                           NumStatHits, NumStatMisses);
2694        FileMgr.addStatCache(MyStatCache);
2695        F.StatCache = MyStatCache;
2696      }
2697      break;
2698    }
2699
2700    case EXT_VECTOR_DECLS:
2701      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2702        ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2703      break;
2704
2705    case VTABLE_USES:
2706      if (Record.size() % 3 != 0) {
2707        Error("Invalid VTABLE_USES record");
2708        return true;
2709      }
2710
2711      // Later tables overwrite earlier ones.
2712      // FIXME: Modules will have some trouble with this. This is clearly not
2713      // the right way to do this.
2714      VTableUses.clear();
2715
2716      for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2717        VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2718        VTableUses.push_back(
2719          ReadSourceLocation(F, Record, Idx).getRawEncoding());
2720        VTableUses.push_back(Record[Idx++]);
2721      }
2722      break;
2723
2724    case DYNAMIC_CLASSES:
2725      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2726        DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2727      break;
2728
2729    case PENDING_IMPLICIT_INSTANTIATIONS:
2730      if (PendingInstantiations.size() % 2 != 0) {
2731        Error("Invalid existing PendingInstantiations");
2732        return true;
2733      }
2734
2735      if (Record.size() % 2 != 0) {
2736        Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2737        return true;
2738      }
2739
2740      for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2741        PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2742        PendingInstantiations.push_back(
2743          ReadSourceLocation(F, Record, I).getRawEncoding());
2744      }
2745      break;
2746
2747    case SEMA_DECL_REFS:
2748      // Later tables overwrite earlier ones.
2749      // FIXME: Modules will have some trouble with this.
2750      SemaDeclRefs.clear();
2751      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2752        SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2753      break;
2754
2755    case PPD_ENTITIES_OFFSETS: {
2756      F.PreprocessedEntityOffsets = (const PPEntityOffset *)BlobStart;
2757      assert(BlobLen % sizeof(PPEntityOffset) == 0);
2758      F.NumPreprocessedEntities = BlobLen / sizeof(PPEntityOffset);
2759
2760      unsigned LocalBasePreprocessedEntityID = Record[0];
2761
2762      unsigned StartingID;
2763      if (!PP.getPreprocessingRecord())
2764        PP.createPreprocessingRecord(/*RecordConditionalDirectives=*/false);
2765      if (!PP.getPreprocessingRecord()->getExternalSource())
2766        PP.getPreprocessingRecord()->SetExternalSource(*this);
2767      StartingID
2768        = PP.getPreprocessingRecord()
2769            ->allocateLoadedEntities(F.NumPreprocessedEntities);
2770      F.BasePreprocessedEntityID = StartingID;
2771
2772      if (F.NumPreprocessedEntities > 0) {
2773        // Introduce the global -> local mapping for preprocessed entities in
2774        // this module.
2775        GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2776
2777        // Introduce the local -> global mapping for preprocessed entities in
2778        // this module.
2779        F.PreprocessedEntityRemap.insertOrReplace(
2780          std::make_pair(LocalBasePreprocessedEntityID,
2781            F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2782      }
2783
2784      break;
2785    }
2786
2787    case DECL_UPDATE_OFFSETS: {
2788      if (Record.size() % 2 != 0) {
2789        Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2790        return true;
2791      }
2792      for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2793        DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2794          .push_back(std::make_pair(&F, Record[I+1]));
2795      break;
2796    }
2797
2798    case DECL_REPLACEMENTS: {
2799      if (Record.size() % 3 != 0) {
2800        Error("invalid DECL_REPLACEMENTS block in AST file");
2801        return true;
2802      }
2803      for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2804        ReplacedDecls[getGlobalDeclID(F, Record[I])]
2805          = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2806      break;
2807    }
2808
2809    case OBJC_CATEGORIES_MAP: {
2810      if (F.LocalNumObjCCategoriesInMap != 0) {
2811        Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2812        return true;
2813      }
2814
2815      F.LocalNumObjCCategoriesInMap = Record[0];
2816      F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)BlobStart;
2817      break;
2818    }
2819
2820    case OBJC_CATEGORIES:
2821      F.ObjCCategories.swap(Record);
2822      break;
2823
2824    case CXX_BASE_SPECIFIER_OFFSETS: {
2825      if (F.LocalNumCXXBaseSpecifiers != 0) {
2826        Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2827        return true;
2828      }
2829
2830      F.LocalNumCXXBaseSpecifiers = Record[0];
2831      F.CXXBaseSpecifiersOffsets = (const uint32_t *)BlobStart;
2832      NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2833      break;
2834    }
2835
2836    case DIAG_PRAGMA_MAPPINGS:
2837      if (Record.size() % 2 != 0) {
2838        Error("invalid DIAG_USER_MAPPINGS block in AST file");
2839        return true;
2840      }
2841
2842      if (F.PragmaDiagMappings.empty())
2843        F.PragmaDiagMappings.swap(Record);
2844      else
2845        F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2846                                    Record.begin(), Record.end());
2847      break;
2848
2849    case CUDA_SPECIAL_DECL_REFS:
2850      // Later tables overwrite earlier ones.
2851      // FIXME: Modules will have trouble with this.
2852      CUDASpecialDeclRefs.clear();
2853      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2854        CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2855      break;
2856
2857    case HEADER_SEARCH_TABLE: {
2858      F.HeaderFileInfoTableData = BlobStart;
2859      F.LocalNumHeaderFileInfos = Record[1];
2860      F.HeaderFileFrameworkStrings = BlobStart + Record[2];
2861      if (Record[0]) {
2862        F.HeaderFileInfoTable
2863          = HeaderFileInfoLookupTable::Create(
2864                   (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2865                   (const unsigned char *)F.HeaderFileInfoTableData,
2866                   HeaderFileInfoTrait(*this, F,
2867                                       &PP.getHeaderSearchInfo(),
2868                                       BlobStart + Record[2]));
2869
2870        PP.getHeaderSearchInfo().SetExternalSource(this);
2871        if (!PP.getHeaderSearchInfo().getExternalLookup())
2872          PP.getHeaderSearchInfo().SetExternalLookup(this);
2873      }
2874      break;
2875    }
2876
2877    case FP_PRAGMA_OPTIONS:
2878      // Later tables overwrite earlier ones.
2879      FPPragmaOptions.swap(Record);
2880      break;
2881
2882    case OPENCL_EXTENSIONS:
2883      // Later tables overwrite earlier ones.
2884      OpenCLExtensions.swap(Record);
2885      break;
2886
2887    case TENTATIVE_DEFINITIONS:
2888      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2889        TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2890      break;
2891
2892    case KNOWN_NAMESPACES:
2893      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2894        KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2895      break;
2896
2897    case IMPORTED_MODULES: {
2898      if (F.Kind != MK_Module) {
2899        // If we aren't loading a module (which has its own exports), make
2900        // all of the imported modules visible.
2901        // FIXME: Deal with macros-only imports.
2902        for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2903          if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
2904            ImportedModules.push_back(GlobalID);
2905        }
2906      }
2907      break;
2908    }
2909
2910    case LOCAL_REDECLARATIONS: {
2911      F.RedeclarationChains.swap(Record);
2912      break;
2913    }
2914
2915    case LOCAL_REDECLARATIONS_MAP: {
2916      if (F.LocalNumRedeclarationsInMap != 0) {
2917        Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
2918        return true;
2919      }
2920
2921      F.LocalNumRedeclarationsInMap = Record[0];
2922      F.RedeclarationsMap = (const LocalRedeclarationsInfo *)BlobStart;
2923      break;
2924    }
2925
2926    case MERGED_DECLARATIONS: {
2927      for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
2928        GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
2929        SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
2930        for (unsigned N = Record[Idx++]; N > 0; --N)
2931          Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
2932      }
2933      break;
2934    }
2935
2936    case MACRO_OFFSET: {
2937      if (F.LocalNumMacros != 0) {
2938        Error("duplicate MACRO_OFFSET record in AST file");
2939        return true;
2940      }
2941      F.MacroOffsets = (const uint32_t *)BlobStart;
2942      F.LocalNumMacros = Record[0];
2943      unsigned LocalBaseMacroID = Record[1];
2944      F.BaseMacroID = getTotalNumMacros();
2945
2946      if (F.LocalNumMacros > 0) {
2947        // Introduce the global -> local mapping for macros within this module.
2948        GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
2949
2950        // Introduce the local -> global mapping for macros within this module.
2951        F.MacroRemap.insertOrReplace(
2952          std::make_pair(LocalBaseMacroID,
2953                         F.BaseMacroID - LocalBaseMacroID));
2954
2955        MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
2956      }
2957      break;
2958    }
2959
2960    case MACRO_UPDATES: {
2961      for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2962        MacroID ID = getGlobalMacroID(F, Record[I++]);
2963        if (I == N)
2964          break;
2965
2966        SourceLocation UndefLoc = ReadSourceLocation(F, Record, I);
2967        SubmoduleID SubmoduleID = getGlobalSubmoduleID(F, Record[I++]);;
2968        MacroUpdate Update;
2969        Update.UndefLoc = UndefLoc;
2970        MacroUpdates[ID].push_back(std::make_pair(SubmoduleID, Update));
2971      }
2972      break;
2973    }
2974    }
2975  }
2976  Error("premature end of bitstream in AST file");
2977  return true;
2978}
2979
2980void ASTReader::makeNamesVisible(const HiddenNames &Names) {
2981  for (unsigned I = 0, N = Names.size(); I != N; ++I) {
2982    switch (Names[I].getKind()) {
2983    case HiddenName::Declaration:
2984      Names[I].getDecl()->Hidden = false;
2985      break;
2986
2987    case HiddenName::MacroVisibility: {
2988      std::pair<IdentifierInfo *, MacroInfo *> Macro = Names[I].getMacro();
2989      Macro.second->setHidden(!Macro.second->isPublic());
2990      if (Macro.second->isDefined()) {
2991        PP.makeLoadedMacroInfoVisible(Macro.first, Macro.second);
2992      }
2993      break;
2994    }
2995
2996    case HiddenName::MacroUndef: {
2997      std::pair<IdentifierInfo *, MacroInfo *> Macro = Names[I].getMacro();
2998      if (Macro.second->isDefined()) {
2999        Macro.second->setUndefLoc(Names[I].getMacroUndefLoc());
3000        if (PPMutationListener *Listener = PP.getPPMutationListener())
3001          Listener->UndefinedMacro(Macro.second);
3002        PP.makeLoadedMacroInfoVisible(Macro.first, Macro.second);
3003      }
3004      break;
3005    }
3006    }
3007  }
3008}
3009
3010void ASTReader::makeModuleVisible(Module *Mod,
3011                                  Module::NameVisibilityKind NameVisibility) {
3012  llvm::SmallPtrSet<Module *, 4> Visited;
3013  llvm::SmallVector<Module *, 4> Stack;
3014  Stack.push_back(Mod);
3015  while (!Stack.empty()) {
3016    Mod = Stack.back();
3017    Stack.pop_back();
3018
3019    if (NameVisibility <= Mod->NameVisibility) {
3020      // This module already has this level of visibility (or greater), so
3021      // there is nothing more to do.
3022      continue;
3023    }
3024
3025    if (!Mod->isAvailable()) {
3026      // Modules that aren't available cannot be made visible.
3027      continue;
3028    }
3029
3030    // Update the module's name visibility.
3031    Mod->NameVisibility = NameVisibility;
3032
3033    // If we've already deserialized any names from this module,
3034    // mark them as visible.
3035    HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3036    if (Hidden != HiddenNamesMap.end()) {
3037      makeNamesVisible(Hidden->second);
3038      HiddenNamesMap.erase(Hidden);
3039    }
3040
3041    // Push any non-explicit submodules onto the stack to be marked as
3042    // visible.
3043    for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3044                                 SubEnd = Mod->submodule_end();
3045         Sub != SubEnd; ++Sub) {
3046      if (!(*Sub)->IsExplicit && Visited.insert(*Sub))
3047        Stack.push_back(*Sub);
3048    }
3049
3050    // Push any exported modules onto the stack to be marked as visible.
3051    bool AnyWildcard = false;
3052    bool UnrestrictedWildcard = false;
3053    llvm::SmallVector<Module *, 4> WildcardRestrictions;
3054    for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
3055      Module *Exported = Mod->Exports[I].getPointer();
3056      if (!Mod->Exports[I].getInt()) {
3057        // Export a named module directly; no wildcards involved.
3058        if (Visited.insert(Exported))
3059          Stack.push_back(Exported);
3060
3061        continue;
3062      }
3063
3064      // Wildcard export: export all of the imported modules that match
3065      // the given pattern.
3066      AnyWildcard = true;
3067      if (UnrestrictedWildcard)
3068        continue;
3069
3070      if (Module *Restriction = Mod->Exports[I].getPointer())
3071        WildcardRestrictions.push_back(Restriction);
3072      else {
3073        WildcardRestrictions.clear();
3074        UnrestrictedWildcard = true;
3075      }
3076    }
3077
3078    // If there were any wildcards, push any imported modules that were
3079    // re-exported by the wildcard restriction.
3080    if (!AnyWildcard)
3081      continue;
3082
3083    for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
3084      Module *Imported = Mod->Imports[I];
3085      if (!Visited.insert(Imported))
3086        continue;
3087
3088      bool Acceptable = UnrestrictedWildcard;
3089      if (!Acceptable) {
3090        // Check whether this module meets one of the restrictions.
3091        for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
3092          Module *Restriction = WildcardRestrictions[R];
3093          if (Imported == Restriction || Imported->isSubModuleOf(Restriction)) {
3094            Acceptable = true;
3095            break;
3096          }
3097        }
3098      }
3099
3100      if (!Acceptable)
3101        continue;
3102
3103      Stack.push_back(Imported);
3104    }
3105  }
3106}
3107
3108ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3109                                            ModuleKind Type,
3110                                            unsigned ClientLoadCapabilities) {
3111  // Bump the generation number.
3112  unsigned PreviousGeneration = CurrentGeneration++;
3113
3114  // Load the core of the AST files.
3115  llvm::SmallVector<ModuleFile *, 4> Loaded;
3116  switch(ReadASTCore(FileName, Type, /*ImportedBy=*/0, Loaded,
3117                     ClientLoadCapabilities)) {
3118  case Failure: return Failure;
3119  case OutOfDate: return OutOfDate;
3120  case VersionMismatch: return VersionMismatch;
3121  case ConfigurationMismatch: return ConfigurationMismatch;
3122  case HadErrors: return HadErrors;
3123  case Success: break;
3124  }
3125
3126  // Here comes stuff that we only do once the entire chain is loaded.
3127
3128  // Load the AST blocks of all of the modules that we loaded.
3129  for (llvm::SmallVectorImpl<ModuleFile *>::iterator M = Loaded.begin(),
3130                                                  MEnd = Loaded.end();
3131       M != MEnd; ++M) {
3132    ModuleFile &F = **M;
3133
3134    // Read the AST block.
3135    if (ReadASTBlock(F))
3136      return Failure;
3137
3138    // Once read, set the ModuleFile bit base offset and update the size in
3139    // bits of all files we've seen.
3140    F.GlobalBitOffset = TotalModulesSizeInBits;
3141    TotalModulesSizeInBits += F.SizeInBits;
3142    GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3143
3144    // Preload SLocEntries.
3145    for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3146      int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3147      // Load it through the SourceManager and don't call ReadSLocEntry()
3148      // directly because the entry may have already been loaded in which case
3149      // calling ReadSLocEntry() directly would trigger an assertion in
3150      // SourceManager.
3151      SourceMgr.getLoadedSLocEntryByID(Index);
3152    }
3153  }
3154
3155  // Check the predefines buffers.
3156  bool ConfigComplain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
3157  if (!DisableValidation && Type == MK_PCH &&
3158      // FIXME: CheckPredefinesBuffers also sets the SuggestedPredefines;
3159      // if DisableValidation is true, defines that were set on command-line
3160      // but not in the PCH file will not be added to SuggestedPredefines.
3161      CheckPredefinesBuffers(ConfigComplain))
3162    return ConfigurationMismatch;
3163
3164  // Mark all of the identifiers in the identifier table as being out of date,
3165  // so that various accessors know to check the loaded modules when the
3166  // identifier is used.
3167  for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3168                              IdEnd = PP.getIdentifierTable().end();
3169       Id != IdEnd; ++Id)
3170    Id->second->setOutOfDate(true);
3171
3172  // Resolve any unresolved module exports.
3173  for (unsigned I = 0, N = UnresolvedModuleImportExports.size(); I != N; ++I) {
3174    UnresolvedModuleImportExport &Unresolved = UnresolvedModuleImportExports[I];
3175    SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3176    Module *ResolvedMod = getSubmodule(GlobalID);
3177
3178    if (Unresolved.IsImport) {
3179      if (ResolvedMod)
3180        Unresolved.Mod->Imports.push_back(ResolvedMod);
3181      continue;
3182    }
3183
3184    if (ResolvedMod || Unresolved.IsWildcard)
3185      Unresolved.Mod->Exports.push_back(
3186        Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3187  }
3188  UnresolvedModuleImportExports.clear();
3189
3190  InitializeContext();
3191
3192  if (DeserializationListener)
3193    DeserializationListener->ReaderInitialized(this);
3194
3195  ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3196  if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3197    PrimaryModule.OriginalSourceFileID
3198      = FileID::get(PrimaryModule.SLocEntryBaseID
3199                    + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3200
3201    // If this AST file is a precompiled preamble, then set the
3202    // preamble file ID of the source manager to the file source file
3203    // from which the preamble was built.
3204    if (Type == MK_Preamble) {
3205      SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3206    } else if (Type == MK_MainFile) {
3207      SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3208    }
3209  }
3210
3211  // For any Objective-C class definitions we have already loaded, make sure
3212  // that we load any additional categories.
3213  for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3214    loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3215                       ObjCClassesLoaded[I],
3216                       PreviousGeneration);
3217  }
3218
3219  return Success;
3220}
3221
3222ASTReader::ASTReadResult
3223ASTReader::ReadASTCore(StringRef FileName,
3224                       ModuleKind Type,
3225                       ModuleFile *ImportedBy,
3226                       llvm::SmallVectorImpl<ModuleFile *> &Loaded,
3227                       unsigned ClientLoadCapabilities) {
3228  ModuleFile *M;
3229  bool NewModule;
3230  std::string ErrorStr;
3231  llvm::tie(M, NewModule) = ModuleMgr.addModule(FileName, Type, ImportedBy,
3232                                                CurrentGeneration, ErrorStr);
3233
3234  if (!M) {
3235    // We couldn't load the module.
3236    std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3237      + ErrorStr;
3238    Error(Msg);
3239    return Failure;
3240  }
3241
3242  if (!NewModule) {
3243    // We've already loaded this module.
3244    return Success;
3245  }
3246
3247  // FIXME: This seems rather a hack. Should CurrentDir be part of the
3248  // module?
3249  if (FileName != "-") {
3250    CurrentDir = llvm::sys::path::parent_path(FileName);
3251    if (CurrentDir.empty()) CurrentDir = ".";
3252  }
3253
3254  ModuleFile &F = *M;
3255  llvm::BitstreamCursor &Stream = F.Stream;
3256  Stream.init(F.StreamFile);
3257  F.SizeInBits = F.Buffer->getBufferSize() * 8;
3258
3259  // Sniff for the signature.
3260  if (Stream.Read(8) != 'C' ||
3261      Stream.Read(8) != 'P' ||
3262      Stream.Read(8) != 'C' ||
3263      Stream.Read(8) != 'H') {
3264    Diag(diag::err_not_a_pch_file) << FileName;
3265    return Failure;
3266  }
3267
3268  while (!Stream.AtEndOfStream()) {
3269    unsigned Code = Stream.ReadCode();
3270
3271    if (Code != llvm::bitc::ENTER_SUBBLOCK) {
3272      Error("invalid record at top-level of AST file");
3273      return Failure;
3274    }
3275
3276    unsigned BlockID = Stream.ReadSubBlockID();
3277
3278    // We only know the control subblock ID.
3279    switch (BlockID) {
3280    case llvm::bitc::BLOCKINFO_BLOCK_ID:
3281      if (Stream.ReadBlockInfoBlock()) {
3282        Error("malformed BlockInfoBlock in AST file");
3283        return Failure;
3284      }
3285      break;
3286    case CONTROL_BLOCK_ID:
3287      switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
3288      case Success:
3289        break;
3290
3291      case Failure: return Failure;
3292      case OutOfDate: return OutOfDate;
3293      case VersionMismatch: return VersionMismatch;
3294      case ConfigurationMismatch: return ConfigurationMismatch;
3295      case HadErrors: return HadErrors;
3296      }
3297      break;
3298    case AST_BLOCK_ID:
3299      // Record that we've loaded this module.
3300      Loaded.push_back(M);
3301      return Success;
3302
3303    default:
3304      if (Stream.SkipBlock()) {
3305        Error("malformed block record in AST file");
3306        return Failure;
3307      }
3308      break;
3309    }
3310  }
3311
3312  return Success;
3313}
3314
3315void ASTReader::InitializeContext() {
3316  // If there's a listener, notify them that we "read" the translation unit.
3317  if (DeserializationListener)
3318    DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3319                                      Context.getTranslationUnitDecl());
3320
3321  // Make sure we load the declaration update records for the translation unit,
3322  // if there are any.
3323  loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3324                        Context.getTranslationUnitDecl());
3325
3326  // FIXME: Find a better way to deal with collisions between these
3327  // built-in types. Right now, we just ignore the problem.
3328
3329  // Load the special types.
3330  if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3331    if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3332      if (!Context.CFConstantStringTypeDecl)
3333        Context.setCFConstantStringType(GetType(String));
3334    }
3335
3336    if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3337      QualType FileType = GetType(File);
3338      if (FileType.isNull()) {
3339        Error("FILE type is NULL");
3340        return;
3341      }
3342
3343      if (!Context.FILEDecl) {
3344        if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3345          Context.setFILEDecl(Typedef->getDecl());
3346        else {
3347          const TagType *Tag = FileType->getAs<TagType>();
3348          if (!Tag) {
3349            Error("Invalid FILE type in AST file");
3350            return;
3351          }
3352          Context.setFILEDecl(Tag->getDecl());
3353        }
3354      }
3355    }
3356
3357    if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3358      QualType Jmp_bufType = GetType(Jmp_buf);
3359      if (Jmp_bufType.isNull()) {
3360        Error("jmp_buf type is NULL");
3361        return;
3362      }
3363
3364      if (!Context.jmp_bufDecl) {
3365        if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3366          Context.setjmp_bufDecl(Typedef->getDecl());
3367        else {
3368          const TagType *Tag = Jmp_bufType->getAs<TagType>();
3369          if (!Tag) {
3370            Error("Invalid jmp_buf type in AST file");
3371            return;
3372          }
3373          Context.setjmp_bufDecl(Tag->getDecl());
3374        }
3375      }
3376    }
3377
3378    if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3379      QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3380      if (Sigjmp_bufType.isNull()) {
3381        Error("sigjmp_buf type is NULL");
3382        return;
3383      }
3384
3385      if (!Context.sigjmp_bufDecl) {
3386        if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3387          Context.setsigjmp_bufDecl(Typedef->getDecl());
3388        else {
3389          const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3390          assert(Tag && "Invalid sigjmp_buf type in AST file");
3391          Context.setsigjmp_bufDecl(Tag->getDecl());
3392        }
3393      }
3394    }
3395
3396    if (unsigned ObjCIdRedef
3397          = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3398      if (Context.ObjCIdRedefinitionType.isNull())
3399        Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3400    }
3401
3402    if (unsigned ObjCClassRedef
3403          = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3404      if (Context.ObjCClassRedefinitionType.isNull())
3405        Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3406    }
3407
3408    if (unsigned ObjCSelRedef
3409          = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3410      if (Context.ObjCSelRedefinitionType.isNull())
3411        Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3412    }
3413
3414    if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3415      QualType Ucontext_tType = GetType(Ucontext_t);
3416      if (Ucontext_tType.isNull()) {
3417        Error("ucontext_t type is NULL");
3418        return;
3419      }
3420
3421      if (!Context.ucontext_tDecl) {
3422        if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3423          Context.setucontext_tDecl(Typedef->getDecl());
3424        else {
3425          const TagType *Tag = Ucontext_tType->getAs<TagType>();
3426          assert(Tag && "Invalid ucontext_t type in AST file");
3427          Context.setucontext_tDecl(Tag->getDecl());
3428        }
3429      }
3430    }
3431  }
3432
3433  ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3434
3435  // If there were any CUDA special declarations, deserialize them.
3436  if (!CUDASpecialDeclRefs.empty()) {
3437    assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3438    Context.setcudaConfigureCallDecl(
3439                           cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3440  }
3441
3442  // Re-export any modules that were imported by a non-module AST file.
3443  for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3444    if (Module *Imported = getSubmodule(ImportedModules[I]))
3445      makeModuleVisible(Imported, Module::AllVisible);
3446  }
3447  ImportedModules.clear();
3448}
3449
3450void ASTReader::finalizeForWriting() {
3451  for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3452                                 HiddenEnd = HiddenNamesMap.end();
3453       Hidden != HiddenEnd; ++Hidden) {
3454    makeNamesVisible(Hidden->second);
3455  }
3456  HiddenNamesMap.clear();
3457}
3458
3459/// \brief Retrieve the name of the original source file name
3460/// directly from the AST file, without actually loading the AST
3461/// file.
3462std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3463                                             FileManager &FileMgr,
3464                                             DiagnosticsEngine &Diags) {
3465  // Open the AST file.
3466  std::string ErrStr;
3467  OwningPtr<llvm::MemoryBuffer> Buffer;
3468  Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3469  if (!Buffer) {
3470    Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3471    return std::string();
3472  }
3473
3474  // Initialize the stream
3475  llvm::BitstreamReader StreamFile;
3476  llvm::BitstreamCursor Stream;
3477  StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3478                  (const unsigned char *)Buffer->getBufferEnd());
3479  Stream.init(StreamFile);
3480
3481  // Sniff for the signature.
3482  if (Stream.Read(8) != 'C' ||
3483      Stream.Read(8) != 'P' ||
3484      Stream.Read(8) != 'C' ||
3485      Stream.Read(8) != 'H') {
3486    Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3487    return std::string();
3488  }
3489
3490  RecordData Record;
3491  while (!Stream.AtEndOfStream()) {
3492    unsigned Code = Stream.ReadCode();
3493
3494    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
3495      unsigned BlockID = Stream.ReadSubBlockID();
3496
3497      // We only know the AST subblock ID.
3498      switch (BlockID) {
3499      case CONTROL_BLOCK_ID:
3500        if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
3501          Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3502          return std::string();
3503        }
3504        break;
3505
3506      default:
3507        if (Stream.SkipBlock()) {
3508          Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3509          return std::string();
3510        }
3511        break;
3512      }
3513      continue;
3514    }
3515
3516    if (Code == llvm::bitc::END_BLOCK) {
3517      if (Stream.ReadBlockEnd()) {
3518        Diags.Report(diag::err_fe_pch_error_at_end_block) << ASTFileName;
3519        return std::string();
3520      }
3521      continue;
3522    }
3523
3524    if (Code == llvm::bitc::DEFINE_ABBREV) {
3525      Stream.ReadAbbrevRecord();
3526      continue;
3527    }
3528
3529    Record.clear();
3530    const char *BlobStart = 0;
3531    unsigned BlobLen = 0;
3532    if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen) == ORIGINAL_FILE)
3533      return std::string(BlobStart, BlobLen);
3534  }
3535
3536  return std::string();
3537}
3538
3539namespace {
3540  class SimplePCHValidator : public ASTReaderListener {
3541    const LangOptions &ExistingLangOpts;
3542    const TargetOptions &ExistingTargetOpts;
3543    const PreprocessorOptions &ExistingPPOpts;
3544    FileManager &FileMgr;
3545
3546  public:
3547    SimplePCHValidator(const LangOptions &ExistingLangOpts,
3548                       const TargetOptions &ExistingTargetOpts,
3549                       const PreprocessorOptions &ExistingPPOpts,
3550                       FileManager &FileMgr)
3551      : ExistingLangOpts(ExistingLangOpts),
3552        ExistingTargetOpts(ExistingTargetOpts),
3553        ExistingPPOpts(ExistingPPOpts),
3554        FileMgr(FileMgr)
3555    {
3556    }
3557
3558    virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3559                                     bool Complain) {
3560      return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3561    }
3562    virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3563                                   bool Complain) {
3564      return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3565    }
3566    virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3567                                         bool Complain,
3568                                         std::string &SuggestedPredefines) {
3569      return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
3570                                      SuggestedPredefines);
3571    }
3572  };
3573}
3574
3575bool ASTReader::isAcceptableASTFile(StringRef Filename,
3576                                    FileManager &FileMgr,
3577                                    const LangOptions &LangOpts,
3578                                    const TargetOptions &TargetOpts,
3579                                    const PreprocessorOptions &PPOpts) {
3580  // Open the AST file.
3581  std::string ErrStr;
3582  OwningPtr<llvm::MemoryBuffer> Buffer;
3583  Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3584  if (!Buffer) {
3585    return false;
3586  }
3587
3588  // Initialize the stream
3589  llvm::BitstreamReader StreamFile;
3590  llvm::BitstreamCursor Stream;
3591  StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3592                  (const unsigned char *)Buffer->getBufferEnd());
3593  Stream.init(StreamFile);
3594
3595  // Sniff for the signature.
3596  if (Stream.Read(8) != 'C' ||
3597      Stream.Read(8) != 'P' ||
3598      Stream.Read(8) != 'C' ||
3599      Stream.Read(8) != 'H') {
3600    return false;
3601  }
3602
3603  SimplePCHValidator Validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3604  RecordData Record;
3605  bool InControlBlock = false;
3606  while (!Stream.AtEndOfStream()) {
3607    unsigned Code = Stream.ReadCode();
3608
3609    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
3610      unsigned BlockID = Stream.ReadSubBlockID();
3611
3612      // We only know the control subblock ID.
3613      switch (BlockID) {
3614      case CONTROL_BLOCK_ID:
3615        if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
3616          return false;
3617        } else {
3618          InControlBlock = true;
3619        }
3620        break;
3621
3622      default:
3623        if (Stream.SkipBlock())
3624          return false;
3625        break;
3626      }
3627      continue;
3628    }
3629
3630    if (Code == llvm::bitc::END_BLOCK) {
3631      if (Stream.ReadBlockEnd()) {
3632        return false;
3633      }
3634      InControlBlock = false;
3635      continue;
3636    }
3637
3638    if (Code == llvm::bitc::DEFINE_ABBREV) {
3639      Stream.ReadAbbrevRecord();
3640      continue;
3641    }
3642
3643    Record.clear();
3644    const char *BlobStart = 0;
3645    unsigned BlobLen = 0;
3646    unsigned RecCode = Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen);
3647    if (InControlBlock) {
3648      switch ((ControlRecordTypes)RecCode) {
3649      case METADATA: {
3650        if (Record[0] != VERSION_MAJOR) {
3651          return false;
3652        }
3653
3654        const std::string &CurBranch = getClangFullRepositoryVersion();
3655        StringRef ASTBranch(BlobStart, BlobLen);
3656        if (StringRef(CurBranch) != ASTBranch)
3657          return false;
3658
3659        break;
3660      }
3661      case LANGUAGE_OPTIONS:
3662        if (ParseLanguageOptions(Record, false, Validator))
3663          return false;
3664        break;
3665
3666      case TARGET_OPTIONS:
3667        if (ParseTargetOptions(Record, false, Validator))
3668          return false;
3669        break;
3670
3671      case DIAGNOSTIC_OPTIONS:
3672        if (ParseDiagnosticOptions(Record, false, Validator))
3673          return false;
3674        break;
3675
3676      case FILE_SYSTEM_OPTIONS:
3677        if (ParseFileSystemOptions(Record, false, Validator))
3678          return false;
3679        break;
3680
3681      case HEADER_SEARCH_OPTIONS:
3682        if (ParseHeaderSearchOptions(Record, false, Validator))
3683          return false;
3684        break;
3685
3686      case PREPROCESSOR_OPTIONS: {
3687        std::string IgnoredSuggestedPredefines;
3688        if (ParsePreprocessorOptions(Record, false, Validator,
3689                                     IgnoredSuggestedPredefines))
3690          return false;
3691        break;
3692      }
3693
3694      default:
3695        // No other validation to perform.
3696        break;
3697      }
3698    }
3699  }
3700
3701  return true;
3702}
3703
3704bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3705  // Enter the submodule block.
3706  if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3707    Error("malformed submodule block record in AST file");
3708    return true;
3709  }
3710
3711  ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3712  bool First = true;
3713  Module *CurrentModule = 0;
3714  RecordData Record;
3715  while (true) {
3716    unsigned Code = F.Stream.ReadCode();
3717    if (Code == llvm::bitc::END_BLOCK) {
3718      if (F.Stream.ReadBlockEnd()) {
3719        Error("error at end of submodule block in AST file");
3720        return true;
3721      }
3722      return false;
3723    }
3724
3725    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
3726      // No known subblocks, always skip them.
3727      F.Stream.ReadSubBlockID();
3728      if (F.Stream.SkipBlock()) {
3729        Error("malformed block record in AST file");
3730        return true;
3731      }
3732      continue;
3733    }
3734
3735    if (Code == llvm::bitc::DEFINE_ABBREV) {
3736      F.Stream.ReadAbbrevRecord();
3737      continue;
3738    }
3739
3740    // Read a record.
3741    const char *BlobStart;
3742    unsigned BlobLen;
3743    Record.clear();
3744    switch (F.Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
3745    default:  // Default behavior: ignore.
3746      break;
3747
3748    case SUBMODULE_DEFINITION: {
3749      if (First) {
3750        Error("missing submodule metadata record at beginning of block");
3751        return true;
3752      }
3753
3754      if (Record.size() < 7) {
3755        Error("malformed module definition");
3756        return true;
3757      }
3758
3759      StringRef Name(BlobStart, BlobLen);
3760      SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[0]);
3761      SubmoduleID Parent = getGlobalSubmoduleID(F, Record[1]);
3762      bool IsFramework = Record[2];
3763      bool IsExplicit = Record[3];
3764      bool IsSystem = Record[4];
3765      bool InferSubmodules = Record[5];
3766      bool InferExplicitSubmodules = Record[6];
3767      bool InferExportWildcard = Record[7];
3768
3769      Module *ParentModule = 0;
3770      if (Parent)
3771        ParentModule = getSubmodule(Parent);
3772
3773      // Retrieve this (sub)module from the module map, creating it if
3774      // necessary.
3775      CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
3776                                                IsFramework,
3777                                                IsExplicit).first;
3778      SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
3779      if (GlobalIndex >= SubmodulesLoaded.size() ||
3780          SubmodulesLoaded[GlobalIndex]) {
3781        Error("too many submodules");
3782        return true;
3783      }
3784
3785      CurrentModule->setASTFile(F.File);
3786      CurrentModule->IsFromModuleFile = true;
3787      CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
3788      CurrentModule->InferSubmodules = InferSubmodules;
3789      CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
3790      CurrentModule->InferExportWildcard = InferExportWildcard;
3791      if (DeserializationListener)
3792        DeserializationListener->ModuleRead(GlobalID, CurrentModule);
3793
3794      SubmodulesLoaded[GlobalIndex] = CurrentModule;
3795      break;
3796    }
3797
3798    case SUBMODULE_UMBRELLA_HEADER: {
3799      if (First) {
3800        Error("missing submodule metadata record at beginning of block");
3801        return true;
3802      }
3803
3804      if (!CurrentModule)
3805        break;
3806
3807      StringRef FileName(BlobStart, BlobLen);
3808      if (const FileEntry *Umbrella = PP.getFileManager().getFile(FileName)) {
3809        if (!CurrentModule->getUmbrellaHeader())
3810          ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
3811        else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
3812          Error("mismatched umbrella headers in submodule");
3813          return true;
3814        }
3815      }
3816      break;
3817    }
3818
3819    case SUBMODULE_HEADER: {
3820      if (First) {
3821        Error("missing submodule metadata record at beginning of block");
3822        return true;
3823      }
3824
3825      if (!CurrentModule)
3826        break;
3827
3828      // FIXME: Be more lazy about this!
3829      StringRef FileName(BlobStart, BlobLen);
3830      if (const FileEntry *File = PP.getFileManager().getFile(FileName)) {
3831        if (std::find(CurrentModule->Headers.begin(),
3832                      CurrentModule->Headers.end(),
3833                      File) == CurrentModule->Headers.end())
3834          ModMap.addHeader(CurrentModule, File, false);
3835      }
3836      break;
3837    }
3838
3839    case SUBMODULE_EXCLUDED_HEADER: {
3840      if (First) {
3841        Error("missing submodule metadata record at beginning of block");
3842        return true;
3843      }
3844
3845      if (!CurrentModule)
3846        break;
3847
3848      // FIXME: Be more lazy about this!
3849      StringRef FileName(BlobStart, BlobLen);
3850      if (const FileEntry *File = PP.getFileManager().getFile(FileName)) {
3851        if (std::find(CurrentModule->Headers.begin(),
3852                      CurrentModule->Headers.end(),
3853                      File) == CurrentModule->Headers.end())
3854          ModMap.addHeader(CurrentModule, File, true);
3855      }
3856      break;
3857    }
3858
3859    case SUBMODULE_TOPHEADER: {
3860      if (First) {
3861        Error("missing submodule metadata record at beginning of block");
3862        return true;
3863      }
3864
3865      if (!CurrentModule)
3866        break;
3867
3868      // FIXME: Be more lazy about this!
3869      StringRef FileName(BlobStart, BlobLen);
3870      if (const FileEntry *File = PP.getFileManager().getFile(FileName))
3871        CurrentModule->TopHeaders.insert(File);
3872      break;
3873    }
3874
3875    case SUBMODULE_UMBRELLA_DIR: {
3876      if (First) {
3877        Error("missing submodule metadata record at beginning of block");
3878        return true;
3879      }
3880
3881      if (!CurrentModule)
3882        break;
3883
3884      StringRef DirName(BlobStart, BlobLen);
3885      if (const DirectoryEntry *Umbrella
3886                                  = PP.getFileManager().getDirectory(DirName)) {
3887        if (!CurrentModule->getUmbrellaDir())
3888          ModMap.setUmbrellaDir(CurrentModule, Umbrella);
3889        else if (CurrentModule->getUmbrellaDir() != Umbrella) {
3890          Error("mismatched umbrella directories in submodule");
3891          return true;
3892        }
3893      }
3894      break;
3895    }
3896
3897    case SUBMODULE_METADATA: {
3898      if (!First) {
3899        Error("submodule metadata record not at beginning of block");
3900        return true;
3901      }
3902      First = false;
3903
3904      F.BaseSubmoduleID = getTotalNumSubmodules();
3905      F.LocalNumSubmodules = Record[0];
3906      unsigned LocalBaseSubmoduleID = Record[1];
3907      if (F.LocalNumSubmodules > 0) {
3908        // Introduce the global -> local mapping for submodules within this
3909        // module.
3910        GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
3911
3912        // Introduce the local -> global mapping for submodules within this
3913        // module.
3914        F.SubmoduleRemap.insertOrReplace(
3915          std::make_pair(LocalBaseSubmoduleID,
3916                         F.BaseSubmoduleID - LocalBaseSubmoduleID));
3917
3918        SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
3919      }
3920      break;
3921    }
3922
3923    case SUBMODULE_IMPORTS: {
3924      if (First) {
3925        Error("missing submodule metadata record at beginning of block");
3926        return true;
3927      }
3928
3929      if (!CurrentModule)
3930        break;
3931
3932      for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
3933        UnresolvedModuleImportExport Unresolved;
3934        Unresolved.File = &F;
3935        Unresolved.Mod = CurrentModule;
3936        Unresolved.ID = Record[Idx];
3937        Unresolved.IsImport = true;
3938        Unresolved.IsWildcard = false;
3939        UnresolvedModuleImportExports.push_back(Unresolved);
3940      }
3941      break;
3942    }
3943
3944    case SUBMODULE_EXPORTS: {
3945      if (First) {
3946        Error("missing submodule metadata record at beginning of block");
3947        return true;
3948      }
3949
3950      if (!CurrentModule)
3951        break;
3952
3953      for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
3954        UnresolvedModuleImportExport Unresolved;
3955        Unresolved.File = &F;
3956        Unresolved.Mod = CurrentModule;
3957        Unresolved.ID = Record[Idx];
3958        Unresolved.IsImport = false;
3959        Unresolved.IsWildcard = Record[Idx + 1];
3960        UnresolvedModuleImportExports.push_back(Unresolved);
3961      }
3962
3963      // Once we've loaded the set of exports, there's no reason to keep
3964      // the parsed, unresolved exports around.
3965      CurrentModule->UnresolvedExports.clear();
3966      break;
3967    }
3968    case SUBMODULE_REQUIRES: {
3969      if (First) {
3970        Error("missing submodule metadata record at beginning of block");
3971        return true;
3972      }
3973
3974      if (!CurrentModule)
3975        break;
3976
3977      CurrentModule->addRequirement(StringRef(BlobStart, BlobLen),
3978                                    Context.getLangOpts(),
3979                                    Context.getTargetInfo());
3980      break;
3981    }
3982    }
3983  }
3984}
3985
3986/// \brief Parse the record that corresponds to a LangOptions data
3987/// structure.
3988///
3989/// This routine parses the language options from the AST file and then gives
3990/// them to the AST listener if one is set.
3991///
3992/// \returns true if the listener deems the file unacceptable, false otherwise.
3993bool ASTReader::ParseLanguageOptions(const RecordData &Record,
3994                                     bool Complain,
3995                                     ASTReaderListener &Listener) {
3996  LangOptions LangOpts;
3997  unsigned Idx = 0;
3998#define LANGOPT(Name, Bits, Default, Description) \
3999  LangOpts.Name = Record[Idx++];
4000#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4001  LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4002#include "clang/Basic/LangOptions.def"
4003
4004  ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4005  VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4006  LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4007
4008  unsigned Length = Record[Idx++];
4009  LangOpts.CurrentModule.assign(Record.begin() + Idx,
4010                                Record.begin() + Idx + Length);
4011  return Listener.ReadLanguageOptions(LangOpts, Complain);
4012}
4013
4014bool ASTReader::ParseTargetOptions(const RecordData &Record,
4015                                   bool Complain,
4016                                   ASTReaderListener &Listener) {
4017  unsigned Idx = 0;
4018  TargetOptions TargetOpts;
4019  TargetOpts.Triple = ReadString(Record, Idx);
4020  TargetOpts.CPU = ReadString(Record, Idx);
4021  TargetOpts.ABI = ReadString(Record, Idx);
4022  TargetOpts.CXXABI = ReadString(Record, Idx);
4023  TargetOpts.LinkerVersion = ReadString(Record, Idx);
4024  for (unsigned N = Record[Idx++]; N; --N) {
4025    TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4026  }
4027  for (unsigned N = Record[Idx++]; N; --N) {
4028    TargetOpts.Features.push_back(ReadString(Record, Idx));
4029  }
4030
4031  return Listener.ReadTargetOptions(TargetOpts, Complain);
4032}
4033
4034bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4035                                       ASTReaderListener &Listener) {
4036  DiagnosticOptions DiagOpts;
4037  unsigned Idx = 0;
4038#define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
4039#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4040  DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
4041#include "clang/Basic/DiagnosticOptions.def"
4042
4043  for (unsigned N = Record[Idx++]; N; --N) {
4044    DiagOpts.Warnings.push_back(ReadString(Record, Idx));
4045  }
4046
4047  return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4048}
4049
4050bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4051                                       ASTReaderListener &Listener) {
4052  FileSystemOptions FSOpts;
4053  unsigned Idx = 0;
4054  FSOpts.WorkingDir = ReadString(Record, Idx);
4055  return Listener.ReadFileSystemOptions(FSOpts, Complain);
4056}
4057
4058bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4059                                         bool Complain,
4060                                         ASTReaderListener &Listener) {
4061  HeaderSearchOptions HSOpts;
4062  unsigned Idx = 0;
4063  HSOpts.Sysroot = ReadString(Record, Idx);
4064
4065  // Include entries.
4066  for (unsigned N = Record[Idx++]; N; --N) {
4067    std::string Path = ReadString(Record, Idx);
4068    frontend::IncludeDirGroup Group
4069      = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
4070    bool IsUserSupplied = Record[Idx++];
4071    bool IsFramework = Record[Idx++];
4072    bool IgnoreSysRoot = Record[Idx++];
4073    bool IsInternal = Record[Idx++];
4074    bool ImplicitExternC = Record[Idx++];
4075    HSOpts.UserEntries.push_back(
4076      HeaderSearchOptions::Entry(Path, Group, IsUserSupplied, IsFramework,
4077                                 IgnoreSysRoot, IsInternal, ImplicitExternC));
4078  }
4079
4080  // System header prefixes.
4081  for (unsigned N = Record[Idx++]; N; --N) {
4082    std::string Prefix = ReadString(Record, Idx);
4083    bool IsSystemHeader = Record[Idx++];
4084    HSOpts.SystemHeaderPrefixes.push_back(
4085      HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4086  }
4087
4088  HSOpts.ResourceDir = ReadString(Record, Idx);
4089  HSOpts.ModuleCachePath = ReadString(Record, Idx);
4090  HSOpts.DisableModuleHash = Record[Idx++];
4091  HSOpts.UseBuiltinIncludes = Record[Idx++];
4092  HSOpts.UseStandardSystemIncludes = Record[Idx++];
4093  HSOpts.UseStandardCXXIncludes = Record[Idx++];
4094  HSOpts.UseLibcxx = Record[Idx++];
4095
4096  return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4097}
4098
4099bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4100                                         bool Complain,
4101                                         ASTReaderListener &Listener,
4102                                         std::string &SuggestedPredefines) {
4103  PreprocessorOptions PPOpts;
4104  unsigned Idx = 0;
4105
4106  // Macro definitions/undefs
4107  for (unsigned N = Record[Idx++]; N; --N) {
4108    std::string Macro = ReadString(Record, Idx);
4109    bool IsUndef = Record[Idx++];
4110    PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4111  }
4112
4113  // Includes
4114  for (unsigned N = Record[Idx++]; N; --N) {
4115    PPOpts.Includes.push_back(ReadString(Record, Idx));
4116  }
4117
4118  // Macro Includes
4119  for (unsigned N = Record[Idx++]; N; --N) {
4120    PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4121  }
4122
4123  PPOpts.UsePredefines = Record[Idx++];
4124  PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4125  PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4126  PPOpts.ObjCXXARCStandardLibrary =
4127    static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4128  SuggestedPredefines.clear();
4129  return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4130                                          SuggestedPredefines);
4131}
4132
4133std::pair<ModuleFile *, unsigned>
4134ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4135  GlobalPreprocessedEntityMapType::iterator
4136  I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4137  assert(I != GlobalPreprocessedEntityMap.end() &&
4138         "Corrupted global preprocessed entity map");
4139  ModuleFile *M = I->second;
4140  unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4141  return std::make_pair(M, LocalIndex);
4142}
4143
4144std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4145ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4146  if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4147    return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4148                                             Mod.NumPreprocessedEntities);
4149
4150  return std::make_pair(PreprocessingRecord::iterator(),
4151                        PreprocessingRecord::iterator());
4152}
4153
4154std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4155ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4156  return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4157                        ModuleDeclIterator(this, &Mod,
4158                                 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4159}
4160
4161PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4162  PreprocessedEntityID PPID = Index+1;
4163  std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4164  ModuleFile &M = *PPInfo.first;
4165  unsigned LocalIndex = PPInfo.second;
4166  const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4167
4168  SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4169  M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4170
4171  unsigned Code = M.PreprocessorDetailCursor.ReadCode();
4172  switch (Code) {
4173  case llvm::bitc::END_BLOCK:
4174    return 0;
4175
4176  case llvm::bitc::ENTER_SUBBLOCK:
4177    Error("unexpected subblock record in preprocessor detail block");
4178    return 0;
4179
4180  case llvm::bitc::DEFINE_ABBREV:
4181    Error("unexpected abbrevation record in preprocessor detail block");
4182    return 0;
4183
4184  default:
4185    break;
4186  }
4187
4188  if (!PP.getPreprocessingRecord()) {
4189    Error("no preprocessing record");
4190    return 0;
4191  }
4192
4193  // Read the record.
4194  SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4195                    ReadSourceLocation(M, PPOffs.End));
4196  PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
4197  const char *BlobStart = 0;
4198  unsigned BlobLen = 0;
4199  RecordData Record;
4200  PreprocessorDetailRecordTypes RecType =
4201    (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.ReadRecord(
4202                                             Code, Record, BlobStart, BlobLen);
4203  switch (RecType) {
4204  case PPD_MACRO_EXPANSION: {
4205    bool isBuiltin = Record[0];
4206    IdentifierInfo *Name = 0;
4207    MacroDefinition *Def = 0;
4208    if (isBuiltin)
4209      Name = getLocalIdentifier(M, Record[1]);
4210    else {
4211      PreprocessedEntityID
4212          GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4213      Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4214    }
4215
4216    MacroExpansion *ME;
4217    if (isBuiltin)
4218      ME = new (PPRec) MacroExpansion(Name, Range);
4219    else
4220      ME = new (PPRec) MacroExpansion(Def, Range);
4221
4222    return ME;
4223  }
4224
4225  case PPD_MACRO_DEFINITION: {
4226    // Decode the identifier info and then check again; if the macro is
4227    // still defined and associated with the identifier,
4228    IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4229    MacroDefinition *MD
4230      = new (PPRec) MacroDefinition(II, Range);
4231
4232    if (DeserializationListener)
4233      DeserializationListener->MacroDefinitionRead(PPID, MD);
4234
4235    return MD;
4236  }
4237
4238  case PPD_INCLUSION_DIRECTIVE: {
4239    const char *FullFileNameStart = BlobStart + Record[0];
4240    StringRef FullFileName(FullFileNameStart, BlobLen - Record[0]);
4241    const FileEntry *File = 0;
4242    if (!FullFileName.empty())
4243      File = PP.getFileManager().getFile(FullFileName);
4244
4245    // FIXME: Stable encoding
4246    InclusionDirective::InclusionKind Kind
4247      = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4248    InclusionDirective *ID
4249      = new (PPRec) InclusionDirective(PPRec, Kind,
4250                                       StringRef(BlobStart, Record[0]),
4251                                       Record[1], Record[3],
4252                                       File,
4253                                       Range);
4254    return ID;
4255  }
4256  }
4257
4258  llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4259}
4260
4261/// \brief \arg SLocMapI points at a chunk of a module that contains no
4262/// preprocessed entities or the entities it contains are not the ones we are
4263/// looking for. Find the next module that contains entities and return the ID
4264/// of the first entry.
4265PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4266                       GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4267  ++SLocMapI;
4268  for (GlobalSLocOffsetMapType::const_iterator
4269         EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4270    ModuleFile &M = *SLocMapI->second;
4271    if (M.NumPreprocessedEntities)
4272      return getGlobalPreprocessedEntityID(M, M.BasePreprocessedEntityID);
4273  }
4274
4275  return getTotalNumPreprocessedEntities();
4276}
4277
4278namespace {
4279
4280template <unsigned PPEntityOffset::*PPLoc>
4281struct PPEntityComp {
4282  const ASTReader &Reader;
4283  ModuleFile &M;
4284
4285  PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4286
4287  bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4288    SourceLocation LHS = getLoc(L);
4289    SourceLocation RHS = getLoc(R);
4290    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4291  }
4292
4293  bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4294    SourceLocation LHS = getLoc(L);
4295    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4296  }
4297
4298  bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4299    SourceLocation RHS = getLoc(R);
4300    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4301  }
4302
4303  SourceLocation getLoc(const PPEntityOffset &PPE) const {
4304    return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4305  }
4306};
4307
4308}
4309
4310/// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4311PreprocessedEntityID
4312ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4313  if (SourceMgr.isLocalSourceLocation(BLoc))
4314    return getTotalNumPreprocessedEntities();
4315
4316  GlobalSLocOffsetMapType::const_iterator
4317    SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
4318                                        BLoc.getOffset());
4319  assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4320         "Corrupted global sloc offset map");
4321
4322  if (SLocMapI->second->NumPreprocessedEntities == 0)
4323    return findNextPreprocessedEntity(SLocMapI);
4324
4325  ModuleFile &M = *SLocMapI->second;
4326  typedef const PPEntityOffset *pp_iterator;
4327  pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4328  pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4329
4330  size_t Count = M.NumPreprocessedEntities;
4331  size_t Half;
4332  pp_iterator First = pp_begin;
4333  pp_iterator PPI;
4334
4335  // Do a binary search manually instead of using std::lower_bound because
4336  // The end locations of entities may be unordered (when a macro expansion
4337  // is inside another macro argument), but for this case it is not important
4338  // whether we get the first macro expansion or its containing macro.
4339  while (Count > 0) {
4340    Half = Count/2;
4341    PPI = First;
4342    std::advance(PPI, Half);
4343    if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4344                                            BLoc)){
4345      First = PPI;
4346      ++First;
4347      Count = Count - Half - 1;
4348    } else
4349      Count = Half;
4350  }
4351
4352  if (PPI == pp_end)
4353    return findNextPreprocessedEntity(SLocMapI);
4354
4355  return getGlobalPreprocessedEntityID(M,
4356                                 M.BasePreprocessedEntityID + (PPI - pp_begin));
4357}
4358
4359/// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4360PreprocessedEntityID
4361ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4362  if (SourceMgr.isLocalSourceLocation(ELoc))
4363    return getTotalNumPreprocessedEntities();
4364
4365  GlobalSLocOffsetMapType::const_iterator
4366    SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
4367                                        ELoc.getOffset());
4368  assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4369         "Corrupted global sloc offset map");
4370
4371  if (SLocMapI->second->NumPreprocessedEntities == 0)
4372    return findNextPreprocessedEntity(SLocMapI);
4373
4374  ModuleFile &M = *SLocMapI->second;
4375  typedef const PPEntityOffset *pp_iterator;
4376  pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4377  pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4378  pp_iterator PPI =
4379      std::upper_bound(pp_begin, pp_end, ELoc,
4380                       PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4381
4382  if (PPI == pp_end)
4383    return findNextPreprocessedEntity(SLocMapI);
4384
4385  return getGlobalPreprocessedEntityID(M,
4386                                 M.BasePreprocessedEntityID + (PPI - pp_begin));
4387}
4388
4389/// \brief Returns a pair of [Begin, End) indices of preallocated
4390/// preprocessed entities that \arg Range encompasses.
4391std::pair<unsigned, unsigned>
4392    ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4393  if (Range.isInvalid())
4394    return std::make_pair(0,0);
4395  assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4396
4397  PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4398  PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4399  return std::make_pair(BeginID, EndID);
4400}
4401
4402/// \brief Optionally returns true or false if the preallocated preprocessed
4403/// entity with index \arg Index came from file \arg FID.
4404llvm::Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
4405                                                             FileID FID) {
4406  if (FID.isInvalid())
4407    return false;
4408
4409  std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4410  ModuleFile &M = *PPInfo.first;
4411  unsigned LocalIndex = PPInfo.second;
4412  const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4413
4414  SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4415  if (Loc.isInvalid())
4416    return false;
4417
4418  if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4419    return true;
4420  else
4421    return false;
4422}
4423
4424namespace {
4425  /// \brief Visitor used to search for information about a header file.
4426  class HeaderFileInfoVisitor {
4427    ASTReader &Reader;
4428    const FileEntry *FE;
4429
4430    llvm::Optional<HeaderFileInfo> HFI;
4431
4432  public:
4433    HeaderFileInfoVisitor(ASTReader &Reader, const FileEntry *FE)
4434      : Reader(Reader), FE(FE) { }
4435
4436    static bool visit(ModuleFile &M, void *UserData) {
4437      HeaderFileInfoVisitor *This
4438        = static_cast<HeaderFileInfoVisitor *>(UserData);
4439
4440      HeaderFileInfoTrait Trait(This->Reader, M,
4441                                &This->Reader.getPreprocessor().getHeaderSearchInfo(),
4442                                M.HeaderFileFrameworkStrings,
4443                                This->FE->getName());
4444
4445      HeaderFileInfoLookupTable *Table
4446        = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4447      if (!Table)
4448        return false;
4449
4450      // Look in the on-disk hash table for an entry for this file name.
4451      HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE->getName(),
4452                                                            &Trait);
4453      if (Pos == Table->end())
4454        return false;
4455
4456      This->HFI = *Pos;
4457      return true;
4458    }
4459
4460    llvm::Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
4461  };
4462}
4463
4464HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
4465  HeaderFileInfoVisitor Visitor(*this, FE);
4466  ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
4467  if (llvm::Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) {
4468    if (Listener)
4469      Listener->ReadHeaderFileInfo(*HFI, FE->getUID());
4470    return *HFI;
4471  }
4472
4473  return HeaderFileInfo();
4474}
4475
4476void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4477  for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4478    ModuleFile &F = *(*I);
4479    unsigned Idx = 0;
4480    while (Idx < F.PragmaDiagMappings.size()) {
4481      SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4482      Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4483      Diag.DiagStatePoints.push_back(
4484          DiagnosticsEngine::DiagStatePoint(&Diag.DiagStates.back(),
4485                                            FullSourceLoc(Loc, SourceMgr)));
4486      while (1) {
4487        assert(Idx < F.PragmaDiagMappings.size() &&
4488               "Invalid data, didn't find '-1' marking end of diag/map pairs");
4489        if (Idx >= F.PragmaDiagMappings.size()) {
4490          break; // Something is messed up but at least avoid infinite loop in
4491                 // release build.
4492        }
4493        unsigned DiagID = F.PragmaDiagMappings[Idx++];
4494        if (DiagID == (unsigned)-1) {
4495          break; // no more diag/map pairs for this location.
4496        }
4497        diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4498        DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4499        Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4500      }
4501    }
4502  }
4503}
4504
4505/// \brief Get the correct cursor and offset for loading a type.
4506ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4507  GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4508  assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4509  ModuleFile *M = I->second;
4510  return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4511}
4512
4513/// \brief Read and return the type with the given index..
4514///
4515/// The index is the type ID, shifted and minus the number of predefs. This
4516/// routine actually reads the record corresponding to the type at the given
4517/// location. It is a helper routine for GetType, which deals with reading type
4518/// IDs.
4519QualType ASTReader::readTypeRecord(unsigned Index) {
4520  RecordLocation Loc = TypeCursorForIndex(Index);
4521  llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
4522
4523  // Keep track of where we are in the stream, then jump back there
4524  // after reading this type.
4525  SavedStreamPosition SavedPosition(DeclsCursor);
4526
4527  ReadingKindTracker ReadingKind(Read_Type, *this);
4528
4529  // Note that we are loading a type record.
4530  Deserializing AType(this);
4531
4532  unsigned Idx = 0;
4533  DeclsCursor.JumpToBit(Loc.Offset);
4534  RecordData Record;
4535  unsigned Code = DeclsCursor.ReadCode();
4536  switch ((TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
4537  case TYPE_EXT_QUAL: {
4538    if (Record.size() != 2) {
4539      Error("Incorrect encoding of extended qualifier type");
4540      return QualType();
4541    }
4542    QualType Base = readType(*Loc.F, Record, Idx);
4543    Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4544    return Context.getQualifiedType(Base, Quals);
4545  }
4546
4547  case TYPE_COMPLEX: {
4548    if (Record.size() != 1) {
4549      Error("Incorrect encoding of complex type");
4550      return QualType();
4551    }
4552    QualType ElemType = readType(*Loc.F, Record, Idx);
4553    return Context.getComplexType(ElemType);
4554  }
4555
4556  case TYPE_POINTER: {
4557    if (Record.size() != 1) {
4558      Error("Incorrect encoding of pointer type");
4559      return QualType();
4560    }
4561    QualType PointeeType = readType(*Loc.F, Record, Idx);
4562    return Context.getPointerType(PointeeType);
4563  }
4564
4565  case TYPE_BLOCK_POINTER: {
4566    if (Record.size() != 1) {
4567      Error("Incorrect encoding of block pointer type");
4568      return QualType();
4569    }
4570    QualType PointeeType = readType(*Loc.F, Record, Idx);
4571    return Context.getBlockPointerType(PointeeType);
4572  }
4573
4574  case TYPE_LVALUE_REFERENCE: {
4575    if (Record.size() != 2) {
4576      Error("Incorrect encoding of lvalue reference type");
4577      return QualType();
4578    }
4579    QualType PointeeType = readType(*Loc.F, Record, Idx);
4580    return Context.getLValueReferenceType(PointeeType, Record[1]);
4581  }
4582
4583  case TYPE_RVALUE_REFERENCE: {
4584    if (Record.size() != 1) {
4585      Error("Incorrect encoding of rvalue reference type");
4586      return QualType();
4587    }
4588    QualType PointeeType = readType(*Loc.F, Record, Idx);
4589    return Context.getRValueReferenceType(PointeeType);
4590  }
4591
4592  case TYPE_MEMBER_POINTER: {
4593    if (Record.size() != 2) {
4594      Error("Incorrect encoding of member pointer type");
4595      return QualType();
4596    }
4597    QualType PointeeType = readType(*Loc.F, Record, Idx);
4598    QualType ClassType = readType(*Loc.F, Record, Idx);
4599    if (PointeeType.isNull() || ClassType.isNull())
4600      return QualType();
4601
4602    return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4603  }
4604
4605  case TYPE_CONSTANT_ARRAY: {
4606    QualType ElementType = readType(*Loc.F, Record, Idx);
4607    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4608    unsigned IndexTypeQuals = Record[2];
4609    unsigned Idx = 3;
4610    llvm::APInt Size = ReadAPInt(Record, Idx);
4611    return Context.getConstantArrayType(ElementType, Size,
4612                                         ASM, IndexTypeQuals);
4613  }
4614
4615  case TYPE_INCOMPLETE_ARRAY: {
4616    QualType ElementType = readType(*Loc.F, Record, Idx);
4617    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4618    unsigned IndexTypeQuals = Record[2];
4619    return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4620  }
4621
4622  case TYPE_VARIABLE_ARRAY: {
4623    QualType ElementType = readType(*Loc.F, Record, Idx);
4624    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4625    unsigned IndexTypeQuals = Record[2];
4626    SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4627    SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4628    return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4629                                         ASM, IndexTypeQuals,
4630                                         SourceRange(LBLoc, RBLoc));
4631  }
4632
4633  case TYPE_VECTOR: {
4634    if (Record.size() != 3) {
4635      Error("incorrect encoding of vector type in AST file");
4636      return QualType();
4637    }
4638
4639    QualType ElementType = readType(*Loc.F, Record, Idx);
4640    unsigned NumElements = Record[1];
4641    unsigned VecKind = Record[2];
4642    return Context.getVectorType(ElementType, NumElements,
4643                                  (VectorType::VectorKind)VecKind);
4644  }
4645
4646  case TYPE_EXT_VECTOR: {
4647    if (Record.size() != 3) {
4648      Error("incorrect encoding of extended vector type in AST file");
4649      return QualType();
4650    }
4651
4652    QualType ElementType = readType(*Loc.F, Record, Idx);
4653    unsigned NumElements = Record[1];
4654    return Context.getExtVectorType(ElementType, NumElements);
4655  }
4656
4657  case TYPE_FUNCTION_NO_PROTO: {
4658    if (Record.size() != 6) {
4659      Error("incorrect encoding of no-proto function type");
4660      return QualType();
4661    }
4662    QualType ResultType = readType(*Loc.F, Record, Idx);
4663    FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
4664                               (CallingConv)Record[4], Record[5]);
4665    return Context.getFunctionNoProtoType(ResultType, Info);
4666  }
4667
4668  case TYPE_FUNCTION_PROTO: {
4669    QualType ResultType = readType(*Loc.F, Record, Idx);
4670
4671    FunctionProtoType::ExtProtoInfo EPI;
4672    EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
4673                                        /*hasregparm*/ Record[2],
4674                                        /*regparm*/ Record[3],
4675                                        static_cast<CallingConv>(Record[4]),
4676                                        /*produces*/ Record[5]);
4677
4678    unsigned Idx = 6;
4679    unsigned NumParams = Record[Idx++];
4680    SmallVector<QualType, 16> ParamTypes;
4681    for (unsigned I = 0; I != NumParams; ++I)
4682      ParamTypes.push_back(readType(*Loc.F, Record, Idx));
4683
4684    EPI.Variadic = Record[Idx++];
4685    EPI.HasTrailingReturn = Record[Idx++];
4686    EPI.TypeQuals = Record[Idx++];
4687    EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
4688    ExceptionSpecificationType EST =
4689        static_cast<ExceptionSpecificationType>(Record[Idx++]);
4690    EPI.ExceptionSpecType = EST;
4691    SmallVector<QualType, 2> Exceptions;
4692    if (EST == EST_Dynamic) {
4693      EPI.NumExceptions = Record[Idx++];
4694      for (unsigned I = 0; I != EPI.NumExceptions; ++I)
4695        Exceptions.push_back(readType(*Loc.F, Record, Idx));
4696      EPI.Exceptions = Exceptions.data();
4697    } else if (EST == EST_ComputedNoexcept) {
4698      EPI.NoexceptExpr = ReadExpr(*Loc.F);
4699    } else if (EST == EST_Uninstantiated) {
4700      EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4701      EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4702    } else if (EST == EST_Unevaluated) {
4703      EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
4704    }
4705    return Context.getFunctionType(ResultType, ParamTypes.data(), NumParams,
4706                                    EPI);
4707  }
4708
4709  case TYPE_UNRESOLVED_USING: {
4710    unsigned Idx = 0;
4711    return Context.getTypeDeclType(
4712                  ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
4713  }
4714
4715  case TYPE_TYPEDEF: {
4716    if (Record.size() != 2) {
4717      Error("incorrect encoding of typedef type");
4718      return QualType();
4719    }
4720    unsigned Idx = 0;
4721    TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
4722    QualType Canonical = readType(*Loc.F, Record, Idx);
4723    if (!Canonical.isNull())
4724      Canonical = Context.getCanonicalType(Canonical);
4725    return Context.getTypedefType(Decl, Canonical);
4726  }
4727
4728  case TYPE_TYPEOF_EXPR:
4729    return Context.getTypeOfExprType(ReadExpr(*Loc.F));
4730
4731  case TYPE_TYPEOF: {
4732    if (Record.size() != 1) {
4733      Error("incorrect encoding of typeof(type) in AST file");
4734      return QualType();
4735    }
4736    QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4737    return Context.getTypeOfType(UnderlyingType);
4738  }
4739
4740  case TYPE_DECLTYPE: {
4741    QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4742    return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
4743  }
4744
4745  case TYPE_UNARY_TRANSFORM: {
4746    QualType BaseType = readType(*Loc.F, Record, Idx);
4747    QualType UnderlyingType = readType(*Loc.F, Record, Idx);
4748    UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
4749    return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
4750  }
4751
4752  case TYPE_AUTO:
4753    return Context.getAutoType(readType(*Loc.F, Record, Idx));
4754
4755  case TYPE_RECORD: {
4756    if (Record.size() != 2) {
4757      Error("incorrect encoding of record type");
4758      return QualType();
4759    }
4760    unsigned Idx = 0;
4761    bool IsDependent = Record[Idx++];
4762    RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
4763    RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
4764    QualType T = Context.getRecordType(RD);
4765    const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4766    return T;
4767  }
4768
4769  case TYPE_ENUM: {
4770    if (Record.size() != 2) {
4771      Error("incorrect encoding of enum type");
4772      return QualType();
4773    }
4774    unsigned Idx = 0;
4775    bool IsDependent = Record[Idx++];
4776    QualType T
4777      = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
4778    const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4779    return T;
4780  }
4781
4782  case TYPE_ATTRIBUTED: {
4783    if (Record.size() != 3) {
4784      Error("incorrect encoding of attributed type");
4785      return QualType();
4786    }
4787    QualType modifiedType = readType(*Loc.F, Record, Idx);
4788    QualType equivalentType = readType(*Loc.F, Record, Idx);
4789    AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
4790    return Context.getAttributedType(kind, modifiedType, equivalentType);
4791  }
4792
4793  case TYPE_PAREN: {
4794    if (Record.size() != 1) {
4795      Error("incorrect encoding of paren type");
4796      return QualType();
4797    }
4798    QualType InnerType = readType(*Loc.F, Record, Idx);
4799    return Context.getParenType(InnerType);
4800  }
4801
4802  case TYPE_PACK_EXPANSION: {
4803    if (Record.size() != 2) {
4804      Error("incorrect encoding of pack expansion type");
4805      return QualType();
4806    }
4807    QualType Pattern = readType(*Loc.F, Record, Idx);
4808    if (Pattern.isNull())
4809      return QualType();
4810    llvm::Optional<unsigned> NumExpansions;
4811    if (Record[1])
4812      NumExpansions = Record[1] - 1;
4813    return Context.getPackExpansionType(Pattern, NumExpansions);
4814  }
4815
4816  case TYPE_ELABORATED: {
4817    unsigned Idx = 0;
4818    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4819    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4820    QualType NamedType = readType(*Loc.F, Record, Idx);
4821    return Context.getElaboratedType(Keyword, NNS, NamedType);
4822  }
4823
4824  case TYPE_OBJC_INTERFACE: {
4825    unsigned Idx = 0;
4826    ObjCInterfaceDecl *ItfD
4827      = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
4828    return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
4829  }
4830
4831  case TYPE_OBJC_OBJECT: {
4832    unsigned Idx = 0;
4833    QualType Base = readType(*Loc.F, Record, Idx);
4834    unsigned NumProtos = Record[Idx++];
4835    SmallVector<ObjCProtocolDecl*, 4> Protos;
4836    for (unsigned I = 0; I != NumProtos; ++I)
4837      Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
4838    return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
4839  }
4840
4841  case TYPE_OBJC_OBJECT_POINTER: {
4842    unsigned Idx = 0;
4843    QualType Pointee = readType(*Loc.F, Record, Idx);
4844    return Context.getObjCObjectPointerType(Pointee);
4845  }
4846
4847  case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
4848    unsigned Idx = 0;
4849    QualType Parm = readType(*Loc.F, Record, Idx);
4850    QualType Replacement = readType(*Loc.F, Record, Idx);
4851    return
4852      Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
4853                                            Replacement);
4854  }
4855
4856  case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
4857    unsigned Idx = 0;
4858    QualType Parm = readType(*Loc.F, Record, Idx);
4859    TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
4860    return Context.getSubstTemplateTypeParmPackType(
4861                                               cast<TemplateTypeParmType>(Parm),
4862                                                     ArgPack);
4863  }
4864
4865  case TYPE_INJECTED_CLASS_NAME: {
4866    CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
4867    QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
4868    // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
4869    // for AST reading, too much interdependencies.
4870    return
4871      QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
4872  }
4873
4874  case TYPE_TEMPLATE_TYPE_PARM: {
4875    unsigned Idx = 0;
4876    unsigned Depth = Record[Idx++];
4877    unsigned Index = Record[Idx++];
4878    bool Pack = Record[Idx++];
4879    TemplateTypeParmDecl *D
4880      = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
4881    return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
4882  }
4883
4884  case TYPE_DEPENDENT_NAME: {
4885    unsigned Idx = 0;
4886    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4887    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4888    const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4889    QualType Canon = readType(*Loc.F, Record, Idx);
4890    if (!Canon.isNull())
4891      Canon = Context.getCanonicalType(Canon);
4892    return Context.getDependentNameType(Keyword, NNS, Name, Canon);
4893  }
4894
4895  case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
4896    unsigned Idx = 0;
4897    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
4898    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
4899    const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
4900    unsigned NumArgs = Record[Idx++];
4901    SmallVector<TemplateArgument, 8> Args;
4902    Args.reserve(NumArgs);
4903    while (NumArgs--)
4904      Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
4905    return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
4906                                                      Args.size(), Args.data());
4907  }
4908
4909  case TYPE_DEPENDENT_SIZED_ARRAY: {
4910    unsigned Idx = 0;
4911
4912    // ArrayType
4913    QualType ElementType = readType(*Loc.F, Record, Idx);
4914    ArrayType::ArraySizeModifier ASM
4915      = (ArrayType::ArraySizeModifier)Record[Idx++];
4916    unsigned IndexTypeQuals = Record[Idx++];
4917
4918    // DependentSizedArrayType
4919    Expr *NumElts = ReadExpr(*Loc.F);
4920    SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
4921
4922    return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
4923                                               IndexTypeQuals, Brackets);
4924  }
4925
4926  case TYPE_TEMPLATE_SPECIALIZATION: {
4927    unsigned Idx = 0;
4928    bool IsDependent = Record[Idx++];
4929    TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
4930    SmallVector<TemplateArgument, 8> Args;
4931    ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
4932    QualType Underlying = readType(*Loc.F, Record, Idx);
4933    QualType T;
4934    if (Underlying.isNull())
4935      T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
4936                                                          Args.size());
4937    else
4938      T = Context.getTemplateSpecializationType(Name, Args.data(),
4939                                                 Args.size(), Underlying);
4940    const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
4941    return T;
4942  }
4943
4944  case TYPE_ATOMIC: {
4945    if (Record.size() != 1) {
4946      Error("Incorrect encoding of atomic type");
4947      return QualType();
4948    }
4949    QualType ValueType = readType(*Loc.F, Record, Idx);
4950    return Context.getAtomicType(ValueType);
4951  }
4952  }
4953  llvm_unreachable("Invalid TypeCode!");
4954}
4955
4956class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
4957  ASTReader &Reader;
4958  ModuleFile &F;
4959  const ASTReader::RecordData &Record;
4960  unsigned &Idx;
4961
4962  SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
4963                                    unsigned &I) {
4964    return Reader.ReadSourceLocation(F, R, I);
4965  }
4966
4967  template<typename T>
4968  T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
4969    return Reader.ReadDeclAs<T>(F, Record, Idx);
4970  }
4971
4972public:
4973  TypeLocReader(ASTReader &Reader, ModuleFile &F,
4974                const ASTReader::RecordData &Record, unsigned &Idx)
4975    : Reader(Reader), F(F), Record(Record), Idx(Idx)
4976  { }
4977
4978  // We want compile-time assurance that we've enumerated all of
4979  // these, so unfortunately we have to declare them first, then
4980  // define them out-of-line.
4981#define ABSTRACT_TYPELOC(CLASS, PARENT)
4982#define TYPELOC(CLASS, PARENT) \
4983  void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
4984#include "clang/AST/TypeLocNodes.def"
4985
4986  void VisitFunctionTypeLoc(FunctionTypeLoc);
4987  void VisitArrayTypeLoc(ArrayTypeLoc);
4988};
4989
4990void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4991  // nothing to do
4992}
4993void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4994  TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
4995  if (TL.needsExtraLocalData()) {
4996    TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
4997    TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
4998    TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
4999    TL.setModeAttr(Record[Idx++]);
5000  }
5001}
5002void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5003  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5004}
5005void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5006  TL.setStarLoc(ReadSourceLocation(Record, Idx));
5007}
5008void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5009  TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5010}
5011void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5012  TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5013}
5014void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5015  TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5016}
5017void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5018  TL.setStarLoc(ReadSourceLocation(Record, Idx));
5019  TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5020}
5021void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5022  TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5023  TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5024  if (Record[Idx++])
5025    TL.setSizeExpr(Reader.ReadExpr(F));
5026  else
5027    TL.setSizeExpr(0);
5028}
5029void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5030  VisitArrayTypeLoc(TL);
5031}
5032void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5033  VisitArrayTypeLoc(TL);
5034}
5035void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5036  VisitArrayTypeLoc(TL);
5037}
5038void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5039                                            DependentSizedArrayTypeLoc TL) {
5040  VisitArrayTypeLoc(TL);
5041}
5042void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5043                                        DependentSizedExtVectorTypeLoc TL) {
5044  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5045}
5046void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5047  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5048}
5049void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5050  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5051}
5052void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5053  TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5054  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5055  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5056  TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
5057  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
5058    TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
5059  }
5060}
5061void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5062  VisitFunctionTypeLoc(TL);
5063}
5064void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5065  VisitFunctionTypeLoc(TL);
5066}
5067void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5068  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5069}
5070void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5071  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5072}
5073void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5074  TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5075  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5076  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5077}
5078void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5079  TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5080  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5081  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5082  TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5083}
5084void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5085  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5086}
5087void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5088  TL.setKWLoc(ReadSourceLocation(Record, Idx));
5089  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5090  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5091  TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5092}
5093void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5094  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5095}
5096void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5097  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5098}
5099void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5100  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5101}
5102void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5103  TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5104  if (TL.hasAttrOperand()) {
5105    SourceRange range;
5106    range.setBegin(ReadSourceLocation(Record, Idx));
5107    range.setEnd(ReadSourceLocation(Record, Idx));
5108    TL.setAttrOperandParensRange(range);
5109  }
5110  if (TL.hasAttrExprOperand()) {
5111    if (Record[Idx++])
5112      TL.setAttrExprOperand(Reader.ReadExpr(F));
5113    else
5114      TL.setAttrExprOperand(0);
5115  } else if (TL.hasAttrEnumOperand())
5116    TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5117}
5118void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5119  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5120}
5121void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5122                                            SubstTemplateTypeParmTypeLoc TL) {
5123  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5124}
5125void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5126                                          SubstTemplateTypeParmPackTypeLoc TL) {
5127  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5128}
5129void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5130                                           TemplateSpecializationTypeLoc TL) {
5131  TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5132  TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5133  TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5134  TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5135  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5136    TL.setArgLocInfo(i,
5137        Reader.GetTemplateArgumentLocInfo(F,
5138                                          TL.getTypePtr()->getArg(i).getKind(),
5139                                          Record, Idx));
5140}
5141void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5142  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5143  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5144}
5145void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5146  TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5147  TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5148}
5149void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5150  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5151}
5152void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5153  TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5154  TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5155  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5156}
5157void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5158       DependentTemplateSpecializationTypeLoc TL) {
5159  TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5160  TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5161  TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5162  TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5163  TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5164  TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5165  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5166    TL.setArgLocInfo(I,
5167        Reader.GetTemplateArgumentLocInfo(F,
5168                                          TL.getTypePtr()->getArg(I).getKind(),
5169                                          Record, Idx));
5170}
5171void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5172  TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5173}
5174void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5175  TL.setNameLoc(ReadSourceLocation(Record, Idx));
5176}
5177void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5178  TL.setHasBaseTypeAsWritten(Record[Idx++]);
5179  TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5180  TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5181  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5182    TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5183}
5184void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5185  TL.setStarLoc(ReadSourceLocation(Record, Idx));
5186}
5187void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5188  TL.setKWLoc(ReadSourceLocation(Record, Idx));
5189  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5190  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5191}
5192
5193TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5194                                             const RecordData &Record,
5195                                             unsigned &Idx) {
5196  QualType InfoTy = readType(F, Record, Idx);
5197  if (InfoTy.isNull())
5198    return 0;
5199
5200  TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5201  TypeLocReader TLR(*this, F, Record, Idx);
5202  for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5203    TLR.Visit(TL);
5204  return TInfo;
5205}
5206
5207QualType ASTReader::GetType(TypeID ID) {
5208  unsigned FastQuals = ID & Qualifiers::FastMask;
5209  unsigned Index = ID >> Qualifiers::FastWidth;
5210
5211  if (Index < NUM_PREDEF_TYPE_IDS) {
5212    QualType T;
5213    switch ((PredefinedTypeIDs)Index) {
5214    case PREDEF_TYPE_NULL_ID: return QualType();
5215    case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5216    case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5217
5218    case PREDEF_TYPE_CHAR_U_ID:
5219    case PREDEF_TYPE_CHAR_S_ID:
5220      // FIXME: Check that the signedness of CharTy is correct!
5221      T = Context.CharTy;
5222      break;
5223
5224    case PREDEF_TYPE_UCHAR_ID:      T = Context.UnsignedCharTy;     break;
5225    case PREDEF_TYPE_USHORT_ID:     T = Context.UnsignedShortTy;    break;
5226    case PREDEF_TYPE_UINT_ID:       T = Context.UnsignedIntTy;      break;
5227    case PREDEF_TYPE_ULONG_ID:      T = Context.UnsignedLongTy;     break;
5228    case PREDEF_TYPE_ULONGLONG_ID:  T = Context.UnsignedLongLongTy; break;
5229    case PREDEF_TYPE_UINT128_ID:    T = Context.UnsignedInt128Ty;   break;
5230    case PREDEF_TYPE_SCHAR_ID:      T = Context.SignedCharTy;       break;
5231    case PREDEF_TYPE_WCHAR_ID:      T = Context.WCharTy;            break;
5232    case PREDEF_TYPE_SHORT_ID:      T = Context.ShortTy;            break;
5233    case PREDEF_TYPE_INT_ID:        T = Context.IntTy;              break;
5234    case PREDEF_TYPE_LONG_ID:       T = Context.LongTy;             break;
5235    case PREDEF_TYPE_LONGLONG_ID:   T = Context.LongLongTy;         break;
5236    case PREDEF_TYPE_INT128_ID:     T = Context.Int128Ty;           break;
5237    case PREDEF_TYPE_HALF_ID:       T = Context.HalfTy;             break;
5238    case PREDEF_TYPE_FLOAT_ID:      T = Context.FloatTy;            break;
5239    case PREDEF_TYPE_DOUBLE_ID:     T = Context.DoubleTy;           break;
5240    case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy;       break;
5241    case PREDEF_TYPE_OVERLOAD_ID:   T = Context.OverloadTy;         break;
5242    case PREDEF_TYPE_BOUND_MEMBER:  T = Context.BoundMemberTy;      break;
5243    case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy;     break;
5244    case PREDEF_TYPE_DEPENDENT_ID:  T = Context.DependentTy;        break;
5245    case PREDEF_TYPE_UNKNOWN_ANY:   T = Context.UnknownAnyTy;       break;
5246    case PREDEF_TYPE_NULLPTR_ID:    T = Context.NullPtrTy;          break;
5247    case PREDEF_TYPE_CHAR16_ID:     T = Context.Char16Ty;           break;
5248    case PREDEF_TYPE_CHAR32_ID:     T = Context.Char32Ty;           break;
5249    case PREDEF_TYPE_OBJC_ID:       T = Context.ObjCBuiltinIdTy;    break;
5250    case PREDEF_TYPE_OBJC_CLASS:    T = Context.ObjCBuiltinClassTy; break;
5251    case PREDEF_TYPE_OBJC_SEL:      T = Context.ObjCBuiltinSelTy;   break;
5252    case PREDEF_TYPE_AUTO_DEDUCT:   T = Context.getAutoDeductType(); break;
5253
5254    case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5255      T = Context.getAutoRRefDeductType();
5256      break;
5257
5258    case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5259      T = Context.ARCUnbridgedCastTy;
5260      break;
5261
5262    case PREDEF_TYPE_VA_LIST_TAG:
5263      T = Context.getVaListTagType();
5264      break;
5265
5266    case PREDEF_TYPE_BUILTIN_FN:
5267      T = Context.BuiltinFnTy;
5268      break;
5269    }
5270
5271    assert(!T.isNull() && "Unknown predefined type");
5272    return T.withFastQualifiers(FastQuals);
5273  }
5274
5275  Index -= NUM_PREDEF_TYPE_IDS;
5276  assert(Index < TypesLoaded.size() && "Type index out-of-range");
5277  if (TypesLoaded[Index].isNull()) {
5278    TypesLoaded[Index] = readTypeRecord(Index);
5279    if (TypesLoaded[Index].isNull())
5280      return QualType();
5281
5282    TypesLoaded[Index]->setFromAST();
5283    if (DeserializationListener)
5284      DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5285                                        TypesLoaded[Index]);
5286  }
5287
5288  return TypesLoaded[Index].withFastQualifiers(FastQuals);
5289}
5290
5291QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5292  return GetType(getGlobalTypeID(F, LocalID));
5293}
5294
5295serialization::TypeID
5296ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5297  unsigned FastQuals = LocalID & Qualifiers::FastMask;
5298  unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5299
5300  if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5301    return LocalID;
5302
5303  ContinuousRangeMap<uint32_t, int, 2>::iterator I
5304    = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5305  assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5306
5307  unsigned GlobalIndex = LocalIndex + I->second;
5308  return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5309}
5310
5311TemplateArgumentLocInfo
5312ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5313                                      TemplateArgument::ArgKind Kind,
5314                                      const RecordData &Record,
5315                                      unsigned &Index) {
5316  switch (Kind) {
5317  case TemplateArgument::Expression:
5318    return ReadExpr(F);
5319  case TemplateArgument::Type:
5320    return GetTypeSourceInfo(F, Record, Index);
5321  case TemplateArgument::Template: {
5322    NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5323                                                                     Index);
5324    SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5325    return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5326                                   SourceLocation());
5327  }
5328  case TemplateArgument::TemplateExpansion: {
5329    NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5330                                                                     Index);
5331    SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5332    SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5333    return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5334                                   EllipsisLoc);
5335  }
5336  case TemplateArgument::Null:
5337  case TemplateArgument::Integral:
5338  case TemplateArgument::Declaration:
5339  case TemplateArgument::NullPtr:
5340  case TemplateArgument::Pack:
5341    // FIXME: Is this right?
5342    return TemplateArgumentLocInfo();
5343  }
5344  llvm_unreachable("unexpected template argument loc");
5345}
5346
5347TemplateArgumentLoc
5348ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5349                                   const RecordData &Record, unsigned &Index) {
5350  TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5351
5352  if (Arg.getKind() == TemplateArgument::Expression) {
5353    if (Record[Index++]) // bool InfoHasSameExpr.
5354      return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5355  }
5356  return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5357                                                             Record, Index));
5358}
5359
5360Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5361  return GetDecl(ID);
5362}
5363
5364uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5365                                          unsigned &Idx){
5366  if (Idx >= Record.size())
5367    return 0;
5368
5369  unsigned LocalID = Record[Idx++];
5370  return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5371}
5372
5373CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5374  RecordLocation Loc = getLocalBitOffset(Offset);
5375  llvm::BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5376  SavedStreamPosition SavedPosition(Cursor);
5377  Cursor.JumpToBit(Loc.Offset);
5378  ReadingKindTracker ReadingKind(Read_Decl, *this);
5379  RecordData Record;
5380  unsigned Code = Cursor.ReadCode();
5381  unsigned RecCode = Cursor.ReadRecord(Code, Record);
5382  if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5383    Error("Malformed AST file: missing C++ base specifiers");
5384    return 0;
5385  }
5386
5387  unsigned Idx = 0;
5388  unsigned NumBases = Record[Idx++];
5389  void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5390  CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5391  for (unsigned I = 0; I != NumBases; ++I)
5392    Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5393  return Bases;
5394}
5395
5396serialization::DeclID
5397ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5398  if (LocalID < NUM_PREDEF_DECL_IDS)
5399    return LocalID;
5400
5401  ContinuousRangeMap<uint32_t, int, 2>::iterator I
5402    = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5403  assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5404
5405  return LocalID + I->second;
5406}
5407
5408bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5409                                   ModuleFile &M) const {
5410  GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5411  assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5412  return &M == I->second;
5413}
5414
5415ModuleFile *ASTReader::getOwningModuleFile(Decl *D) {
5416  if (!D->isFromASTFile())
5417    return 0;
5418  GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5419  assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5420  return I->second;
5421}
5422
5423SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5424  if (ID < NUM_PREDEF_DECL_IDS)
5425    return SourceLocation();
5426
5427  unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5428
5429  if (Index > DeclsLoaded.size()) {
5430    Error("declaration ID out-of-range for AST file");
5431    return SourceLocation();
5432  }
5433
5434  if (Decl *D = DeclsLoaded[Index])
5435    return D->getLocation();
5436
5437  unsigned RawLocation = 0;
5438  RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5439  return ReadSourceLocation(*Rec.F, RawLocation);
5440}
5441
5442Decl *ASTReader::GetDecl(DeclID ID) {
5443  if (ID < NUM_PREDEF_DECL_IDS) {
5444    switch ((PredefinedDeclIDs)ID) {
5445    case PREDEF_DECL_NULL_ID:
5446      return 0;
5447
5448    case PREDEF_DECL_TRANSLATION_UNIT_ID:
5449      return Context.getTranslationUnitDecl();
5450
5451    case PREDEF_DECL_OBJC_ID_ID:
5452      return Context.getObjCIdDecl();
5453
5454    case PREDEF_DECL_OBJC_SEL_ID:
5455      return Context.getObjCSelDecl();
5456
5457    case PREDEF_DECL_OBJC_CLASS_ID:
5458      return Context.getObjCClassDecl();
5459
5460    case PREDEF_DECL_OBJC_PROTOCOL_ID:
5461      return Context.getObjCProtocolDecl();
5462
5463    case PREDEF_DECL_INT_128_ID:
5464      return Context.getInt128Decl();
5465
5466    case PREDEF_DECL_UNSIGNED_INT_128_ID:
5467      return Context.getUInt128Decl();
5468
5469    case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5470      return Context.getObjCInstanceTypeDecl();
5471
5472    case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5473      return Context.getBuiltinVaListDecl();
5474    }
5475  }
5476
5477  unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5478
5479  if (Index >= DeclsLoaded.size()) {
5480    assert(0 && "declaration ID out-of-range for AST file");
5481    Error("declaration ID out-of-range for AST file");
5482    return 0;
5483  }
5484
5485  if (!DeclsLoaded[Index]) {
5486    ReadDeclRecord(ID);
5487    if (DeserializationListener)
5488      DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5489  }
5490
5491  return DeclsLoaded[Index];
5492}
5493
5494DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5495                                                  DeclID GlobalID) {
5496  if (GlobalID < NUM_PREDEF_DECL_IDS)
5497    return GlobalID;
5498
5499  GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5500  assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5501  ModuleFile *Owner = I->second;
5502
5503  llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5504    = M.GlobalToLocalDeclIDs.find(Owner);
5505  if (Pos == M.GlobalToLocalDeclIDs.end())
5506    return 0;
5507
5508  return GlobalID - Owner->BaseDeclID + Pos->second;
5509}
5510
5511serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5512                                            const RecordData &Record,
5513                                            unsigned &Idx) {
5514  if (Idx >= Record.size()) {
5515    Error("Corrupted AST file");
5516    return 0;
5517  }
5518
5519  return getGlobalDeclID(F, Record[Idx++]);
5520}
5521
5522/// \brief Resolve the offset of a statement into a statement.
5523///
5524/// This operation will read a new statement from the external
5525/// source each time it is called, and is meant to be used via a
5526/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5527Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5528  // Switch case IDs are per Decl.
5529  ClearSwitchCaseIDs();
5530
5531  // Offset here is a global offset across the entire chain.
5532  RecordLocation Loc = getLocalBitOffset(Offset);
5533  Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5534  return ReadStmtFromStream(*Loc.F);
5535}
5536
5537namespace {
5538  class FindExternalLexicalDeclsVisitor {
5539    ASTReader &Reader;
5540    const DeclContext *DC;
5541    bool (*isKindWeWant)(Decl::Kind);
5542
5543    SmallVectorImpl<Decl*> &Decls;
5544    bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5545
5546  public:
5547    FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5548                                    bool (*isKindWeWant)(Decl::Kind),
5549                                    SmallVectorImpl<Decl*> &Decls)
5550      : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5551    {
5552      for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5553        PredefsVisited[I] = false;
5554    }
5555
5556    static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5557      if (Preorder)
5558        return false;
5559
5560      FindExternalLexicalDeclsVisitor *This
5561        = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5562
5563      ModuleFile::DeclContextInfosMap::iterator Info
5564        = M.DeclContextInfos.find(This->DC);
5565      if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5566        return false;
5567
5568      // Load all of the declaration IDs
5569      for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5570                               *IDE = ID + Info->second.NumLexicalDecls;
5571           ID != IDE; ++ID) {
5572        if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5573          continue;
5574
5575        // Don't add predefined declarations to the lexical context more
5576        // than once.
5577        if (ID->second < NUM_PREDEF_DECL_IDS) {
5578          if (This->PredefsVisited[ID->second])
5579            continue;
5580
5581          This->PredefsVisited[ID->second] = true;
5582        }
5583
5584        if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5585          if (!This->DC->isDeclInLexicalTraversal(D))
5586            This->Decls.push_back(D);
5587        }
5588      }
5589
5590      return false;
5591    }
5592  };
5593}
5594
5595ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5596                                         bool (*isKindWeWant)(Decl::Kind),
5597                                         SmallVectorImpl<Decl*> &Decls) {
5598  // There might be lexical decls in multiple modules, for the TU at
5599  // least. Walk all of the modules in the order they were loaded.
5600  FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5601  ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5602  ++NumLexicalDeclContextsRead;
5603  return ELR_Success;
5604}
5605
5606namespace {
5607
5608class DeclIDComp {
5609  ASTReader &Reader;
5610  ModuleFile &Mod;
5611
5612public:
5613  DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5614
5615  bool operator()(LocalDeclID L, LocalDeclID R) const {
5616    SourceLocation LHS = getLocation(L);
5617    SourceLocation RHS = getLocation(R);
5618    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5619  }
5620
5621  bool operator()(SourceLocation LHS, LocalDeclID R) const {
5622    SourceLocation RHS = getLocation(R);
5623    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5624  }
5625
5626  bool operator()(LocalDeclID L, SourceLocation RHS) const {
5627    SourceLocation LHS = getLocation(L);
5628    return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5629  }
5630
5631  SourceLocation getLocation(LocalDeclID ID) const {
5632    return Reader.getSourceManager().getFileLoc(
5633            Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
5634  }
5635};
5636
5637}
5638
5639void ASTReader::FindFileRegionDecls(FileID File,
5640                                    unsigned Offset, unsigned Length,
5641                                    SmallVectorImpl<Decl *> &Decls) {
5642  SourceManager &SM = getSourceManager();
5643
5644  llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
5645  if (I == FileDeclIDs.end())
5646    return;
5647
5648  FileDeclsInfo &DInfo = I->second;
5649  if (DInfo.Decls.empty())
5650    return;
5651
5652  SourceLocation
5653    BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
5654  SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
5655
5656  DeclIDComp DIDComp(*this, *DInfo.Mod);
5657  ArrayRef<serialization::LocalDeclID>::iterator
5658    BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5659                               BeginLoc, DIDComp);
5660  if (BeginIt != DInfo.Decls.begin())
5661    --BeginIt;
5662
5663  // If we are pointing at a top-level decl inside an objc container, we need
5664  // to backtrack until we find it otherwise we will fail to report that the
5665  // region overlaps with an objc container.
5666  while (BeginIt != DInfo.Decls.begin() &&
5667         GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
5668             ->isTopLevelDeclInObjCContainer())
5669    --BeginIt;
5670
5671  ArrayRef<serialization::LocalDeclID>::iterator
5672    EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
5673                             EndLoc, DIDComp);
5674  if (EndIt != DInfo.Decls.end())
5675    ++EndIt;
5676
5677  for (ArrayRef<serialization::LocalDeclID>::iterator
5678         DIt = BeginIt; DIt != EndIt; ++DIt)
5679    Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
5680}
5681
5682namespace {
5683  /// \brief ModuleFile visitor used to perform name lookup into a
5684  /// declaration context.
5685  class DeclContextNameLookupVisitor {
5686    ASTReader &Reader;
5687    llvm::SmallVectorImpl<const DeclContext *> &Contexts;
5688    DeclarationName Name;
5689    SmallVectorImpl<NamedDecl *> &Decls;
5690
5691  public:
5692    DeclContextNameLookupVisitor(ASTReader &Reader,
5693                                 SmallVectorImpl<const DeclContext *> &Contexts,
5694                                 DeclarationName Name,
5695                                 SmallVectorImpl<NamedDecl *> &Decls)
5696      : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
5697
5698    static bool visit(ModuleFile &M, void *UserData) {
5699      DeclContextNameLookupVisitor *This
5700        = static_cast<DeclContextNameLookupVisitor *>(UserData);
5701
5702      // Check whether we have any visible declaration information for
5703      // this context in this module.
5704      ModuleFile::DeclContextInfosMap::iterator Info;
5705      bool FoundInfo = false;
5706      for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5707        Info = M.DeclContextInfos.find(This->Contexts[I]);
5708        if (Info != M.DeclContextInfos.end() &&
5709            Info->second.NameLookupTableData) {
5710          FoundInfo = true;
5711          break;
5712        }
5713      }
5714
5715      if (!FoundInfo)
5716        return false;
5717
5718      // Look for this name within this module.
5719      ASTDeclContextNameLookupTable *LookupTable =
5720        Info->second.NameLookupTableData;
5721      ASTDeclContextNameLookupTable::iterator Pos
5722        = LookupTable->find(This->Name);
5723      if (Pos == LookupTable->end())
5724        return false;
5725
5726      bool FoundAnything = false;
5727      ASTDeclContextNameLookupTrait::data_type Data = *Pos;
5728      for (; Data.first != Data.second; ++Data.first) {
5729        NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
5730        if (!ND)
5731          continue;
5732
5733        if (ND->getDeclName() != This->Name) {
5734          // A name might be null because the decl's redeclarable part is
5735          // currently read before reading its name. The lookup is triggered by
5736          // building that decl (likely indirectly), and so it is later in the
5737          // sense of "already existing" and can be ignored here.
5738          continue;
5739        }
5740
5741        // Record this declaration.
5742        FoundAnything = true;
5743        This->Decls.push_back(ND);
5744      }
5745
5746      return FoundAnything;
5747    }
5748  };
5749}
5750
5751DeclContext::lookup_result
5752ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
5753                                          DeclarationName Name) {
5754  assert(DC->hasExternalVisibleStorage() &&
5755         "DeclContext has no visible decls in storage");
5756  if (!Name)
5757    return DeclContext::lookup_result(DeclContext::lookup_iterator(0),
5758                                      DeclContext::lookup_iterator(0));
5759
5760  SmallVector<NamedDecl *, 64> Decls;
5761
5762  // Compute the declaration contexts we need to look into. Multiple such
5763  // declaration contexts occur when two declaration contexts from disjoint
5764  // modules get merged, e.g., when two namespaces with the same name are
5765  // independently defined in separate modules.
5766  SmallVector<const DeclContext *, 2> Contexts;
5767  Contexts.push_back(DC);
5768
5769  if (DC->isNamespace()) {
5770    MergedDeclsMap::iterator Merged
5771      = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5772    if (Merged != MergedDecls.end()) {
5773      for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5774        Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5775    }
5776  }
5777
5778  DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
5779  ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
5780  ++NumVisibleDeclContextsRead;
5781  SetExternalVisibleDeclsForName(DC, Name, Decls);
5782  return const_cast<DeclContext*>(DC)->lookup(Name);
5783}
5784
5785namespace {
5786  /// \brief ModuleFile visitor used to retrieve all visible names in a
5787  /// declaration context.
5788  class DeclContextAllNamesVisitor {
5789    ASTReader &Reader;
5790    llvm::SmallVectorImpl<const DeclContext *> &Contexts;
5791    llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > &Decls;
5792
5793  public:
5794    DeclContextAllNamesVisitor(ASTReader &Reader,
5795                               SmallVectorImpl<const DeclContext *> &Contexts,
5796                               llvm::DenseMap<DeclarationName,
5797                                           SmallVector<NamedDecl *, 8> > &Decls)
5798      : Reader(Reader), Contexts(Contexts), Decls(Decls) { }
5799
5800    static bool visit(ModuleFile &M, void *UserData) {
5801      DeclContextAllNamesVisitor *This
5802        = static_cast<DeclContextAllNamesVisitor *>(UserData);
5803
5804      // Check whether we have any visible declaration information for
5805      // this context in this module.
5806      ModuleFile::DeclContextInfosMap::iterator Info;
5807      bool FoundInfo = false;
5808      for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
5809        Info = M.DeclContextInfos.find(This->Contexts[I]);
5810        if (Info != M.DeclContextInfos.end() &&
5811            Info->second.NameLookupTableData) {
5812          FoundInfo = true;
5813          break;
5814        }
5815      }
5816
5817      if (!FoundInfo)
5818        return false;
5819
5820      ASTDeclContextNameLookupTable *LookupTable =
5821        Info->second.NameLookupTableData;
5822      bool FoundAnything = false;
5823      for (ASTDeclContextNameLookupTable::data_iterator
5824	     I = LookupTable->data_begin(), E = LookupTable->data_end();
5825	   I != E; ++I) {
5826        ASTDeclContextNameLookupTrait::data_type Data = *I;
5827        for (; Data.first != Data.second; ++Data.first) {
5828          NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
5829                                                                 *Data.first);
5830          if (!ND)
5831            continue;
5832
5833          // Record this declaration.
5834          FoundAnything = true;
5835          This->Decls[ND->getDeclName()].push_back(ND);
5836        }
5837      }
5838
5839      return FoundAnything;
5840    }
5841  };
5842}
5843
5844void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
5845  if (!DC->hasExternalVisibleStorage())
5846    return;
5847  llvm::DenseMap<DeclarationName, llvm::SmallVector<NamedDecl*, 8> > Decls;
5848
5849  // Compute the declaration contexts we need to look into. Multiple such
5850  // declaration contexts occur when two declaration contexts from disjoint
5851  // modules get merged, e.g., when two namespaces with the same name are
5852  // independently defined in separate modules.
5853  SmallVector<const DeclContext *, 2> Contexts;
5854  Contexts.push_back(DC);
5855
5856  if (DC->isNamespace()) {
5857    MergedDeclsMap::iterator Merged
5858      = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
5859    if (Merged != MergedDecls.end()) {
5860      for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
5861        Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
5862    }
5863  }
5864
5865  DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls);
5866  ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
5867  ++NumVisibleDeclContextsRead;
5868
5869  for (llvm::DenseMap<DeclarationName,
5870                      llvm::SmallVector<NamedDecl*, 8> >::iterator
5871         I = Decls.begin(), E = Decls.end(); I != E; ++I) {
5872    SetExternalVisibleDeclsForName(DC, I->first, I->second);
5873  }
5874  const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
5875}
5876
5877/// \brief Under non-PCH compilation the consumer receives the objc methods
5878/// before receiving the implementation, and codegen depends on this.
5879/// We simulate this by deserializing and passing to consumer the methods of the
5880/// implementation before passing the deserialized implementation decl.
5881static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
5882                                       ASTConsumer *Consumer) {
5883  assert(ImplD && Consumer);
5884
5885  for (ObjCImplDecl::method_iterator
5886         I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
5887    Consumer->HandleInterestingDecl(DeclGroupRef(*I));
5888
5889  Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
5890}
5891
5892void ASTReader::PassInterestingDeclsToConsumer() {
5893  assert(Consumer);
5894  while (!InterestingDecls.empty()) {
5895    Decl *D = InterestingDecls.front();
5896    InterestingDecls.pop_front();
5897
5898    PassInterestingDeclToConsumer(D);
5899  }
5900}
5901
5902void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
5903  if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
5904    PassObjCImplDeclToConsumer(ImplD, Consumer);
5905  else
5906    Consumer->HandleInterestingDecl(DeclGroupRef(D));
5907}
5908
5909void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
5910  this->Consumer = Consumer;
5911
5912  if (!Consumer)
5913    return;
5914
5915  for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
5916    // Force deserialization of this decl, which will cause it to be queued for
5917    // passing to the consumer.
5918    GetDecl(ExternalDefinitions[I]);
5919  }
5920  ExternalDefinitions.clear();
5921
5922  PassInterestingDeclsToConsumer();
5923}
5924
5925void ASTReader::PrintStats() {
5926  std::fprintf(stderr, "*** AST File Statistics:\n");
5927
5928  unsigned NumTypesLoaded
5929    = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
5930                                      QualType());
5931  unsigned NumDeclsLoaded
5932    = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
5933                                      (Decl *)0);
5934  unsigned NumIdentifiersLoaded
5935    = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
5936                                            IdentifiersLoaded.end(),
5937                                            (IdentifierInfo *)0);
5938  unsigned NumMacrosLoaded
5939    = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
5940                                       MacrosLoaded.end(),
5941                                       (MacroInfo *)0);
5942  unsigned NumSelectorsLoaded
5943    = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
5944                                          SelectorsLoaded.end(),
5945                                          Selector());
5946
5947  std::fprintf(stderr, "  %u stat cache hits\n", NumStatHits);
5948  std::fprintf(stderr, "  %u stat cache misses\n", NumStatMisses);
5949  if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
5950    std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
5951                 NumSLocEntriesRead, TotalNumSLocEntries,
5952                 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
5953  if (!TypesLoaded.empty())
5954    std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
5955                 NumTypesLoaded, (unsigned)TypesLoaded.size(),
5956                 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
5957  if (!DeclsLoaded.empty())
5958    std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
5959                 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
5960                 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
5961  if (!IdentifiersLoaded.empty())
5962    std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
5963                 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
5964                 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
5965  if (!MacrosLoaded.empty())
5966    std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
5967                 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
5968                 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
5969  if (!SelectorsLoaded.empty())
5970    std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
5971                 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
5972                 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
5973  if (TotalNumStatements)
5974    std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
5975                 NumStatementsRead, TotalNumStatements,
5976                 ((float)NumStatementsRead/TotalNumStatements * 100));
5977  if (TotalNumMacros)
5978    std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
5979                 NumMacrosRead, TotalNumMacros,
5980                 ((float)NumMacrosRead/TotalNumMacros * 100));
5981  if (TotalLexicalDeclContexts)
5982    std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
5983                 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
5984                 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
5985                  * 100));
5986  if (TotalVisibleDeclContexts)
5987    std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
5988                 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
5989                 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
5990                  * 100));
5991  if (TotalNumMethodPoolEntries) {
5992    std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
5993                 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
5994                 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
5995                  * 100));
5996    std::fprintf(stderr, "  %u method pool misses\n", NumMethodPoolMisses);
5997  }
5998  std::fprintf(stderr, "\n");
5999  dump();
6000  std::fprintf(stderr, "\n");
6001}
6002
6003template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6004static void
6005dumpModuleIDMap(StringRef Name,
6006                const ContinuousRangeMap<Key, ModuleFile *,
6007                                         InitialCapacity> &Map) {
6008  if (Map.begin() == Map.end())
6009    return;
6010
6011  typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6012  llvm::errs() << Name << ":\n";
6013  for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6014       I != IEnd; ++I) {
6015    llvm::errs() << "  " << I->first << " -> " << I->second->FileName
6016      << "\n";
6017  }
6018}
6019
6020void ASTReader::dump() {
6021  llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6022  dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6023  dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6024  dumpModuleIDMap("Global type map", GlobalTypeMap);
6025  dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6026  dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6027  dumpModuleIDMap("Global macro map", GlobalMacroMap);
6028  dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6029  dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6030  dumpModuleIDMap("Global preprocessed entity map",
6031                  GlobalPreprocessedEntityMap);
6032
6033  llvm::errs() << "\n*** PCH/Modules Loaded:";
6034  for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6035                                       MEnd = ModuleMgr.end();
6036       M != MEnd; ++M)
6037    (*M)->dump();
6038}
6039
6040/// Return the amount of memory used by memory buffers, breaking down
6041/// by heap-backed versus mmap'ed memory.
6042void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6043  for (ModuleConstIterator I = ModuleMgr.begin(),
6044      E = ModuleMgr.end(); I != E; ++I) {
6045    if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6046      size_t bytes = buf->getBufferSize();
6047      switch (buf->getBufferKind()) {
6048        case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6049          sizes.malloc_bytes += bytes;
6050          break;
6051        case llvm::MemoryBuffer::MemoryBuffer_MMap:
6052          sizes.mmap_bytes += bytes;
6053          break;
6054      }
6055    }
6056  }
6057}
6058
6059void ASTReader::InitializeSema(Sema &S) {
6060  SemaObj = &S;
6061  S.addExternalSource(this);
6062
6063  // Makes sure any declarations that were deserialized "too early"
6064  // still get added to the identifier's declaration chains.
6065  for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
6066    SemaObj->pushExternalDeclIntoScope(PreloadedDecls[I],
6067                                       PreloadedDecls[I]->getDeclName());
6068  }
6069  PreloadedDecls.clear();
6070
6071  // Load the offsets of the declarations that Sema references.
6072  // They will be lazily deserialized when needed.
6073  if (!SemaDeclRefs.empty()) {
6074    assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
6075    if (!SemaObj->StdNamespace)
6076      SemaObj->StdNamespace = SemaDeclRefs[0];
6077    if (!SemaObj->StdBadAlloc)
6078      SemaObj->StdBadAlloc = SemaDeclRefs[1];
6079  }
6080
6081  if (!FPPragmaOptions.empty()) {
6082    assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6083    SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6084  }
6085
6086  if (!OpenCLExtensions.empty()) {
6087    unsigned I = 0;
6088#define OPENCLEXT(nm)  SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6089#include "clang/Basic/OpenCLExtensions.def"
6090
6091    assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6092  }
6093}
6094
6095IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6096  // Note that we are loading an identifier.
6097  Deserializing AnIdentifier(this);
6098
6099  IdentifierLookupVisitor Visitor(StringRef(NameStart, NameEnd - NameStart),
6100                                  /*PriorGeneration=*/0);
6101  ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
6102  IdentifierInfo *II = Visitor.getIdentifierInfo();
6103  markIdentifierUpToDate(II);
6104  return II;
6105}
6106
6107namespace clang {
6108  /// \brief An identifier-lookup iterator that enumerates all of the
6109  /// identifiers stored within a set of AST files.
6110  class ASTIdentifierIterator : public IdentifierIterator {
6111    /// \brief The AST reader whose identifiers are being enumerated.
6112    const ASTReader &Reader;
6113
6114    /// \brief The current index into the chain of AST files stored in
6115    /// the AST reader.
6116    unsigned Index;
6117
6118    /// \brief The current position within the identifier lookup table
6119    /// of the current AST file.
6120    ASTIdentifierLookupTable::key_iterator Current;
6121
6122    /// \brief The end position within the identifier lookup table of
6123    /// the current AST file.
6124    ASTIdentifierLookupTable::key_iterator End;
6125
6126  public:
6127    explicit ASTIdentifierIterator(const ASTReader &Reader);
6128
6129    virtual StringRef Next();
6130  };
6131}
6132
6133ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6134  : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6135  ASTIdentifierLookupTable *IdTable
6136    = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6137  Current = IdTable->key_begin();
6138  End = IdTable->key_end();
6139}
6140
6141StringRef ASTIdentifierIterator::Next() {
6142  while (Current == End) {
6143    // If we have exhausted all of our AST files, we're done.
6144    if (Index == 0)
6145      return StringRef();
6146
6147    --Index;
6148    ASTIdentifierLookupTable *IdTable
6149      = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6150        IdentifierLookupTable;
6151    Current = IdTable->key_begin();
6152    End = IdTable->key_end();
6153  }
6154
6155  // We have any identifiers remaining in the current AST file; return
6156  // the next one.
6157  std::pair<const char*, unsigned> Key = *Current;
6158  ++Current;
6159  return StringRef(Key.first, Key.second);
6160}
6161
6162IdentifierIterator *ASTReader::getIdentifiers() const {
6163  return new ASTIdentifierIterator(*this);
6164}
6165
6166namespace clang { namespace serialization {
6167  class ReadMethodPoolVisitor {
6168    ASTReader &Reader;
6169    Selector Sel;
6170    unsigned PriorGeneration;
6171    llvm::SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6172    llvm::SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
6173
6174  public:
6175    ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6176                          unsigned PriorGeneration)
6177      : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) { }
6178
6179    static bool visit(ModuleFile &M, void *UserData) {
6180      ReadMethodPoolVisitor *This
6181        = static_cast<ReadMethodPoolVisitor *>(UserData);
6182
6183      if (!M.SelectorLookupTable)
6184        return false;
6185
6186      // If we've already searched this module file, skip it now.
6187      if (M.Generation <= This->PriorGeneration)
6188        return true;
6189
6190      ASTSelectorLookupTable *PoolTable
6191        = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6192      ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6193      if (Pos == PoolTable->end())
6194        return false;
6195
6196      ++This->Reader.NumSelectorsRead;
6197      // FIXME: Not quite happy with the statistics here. We probably should
6198      // disable this tracking when called via LoadSelector.
6199      // Also, should entries without methods count as misses?
6200      ++This->Reader.NumMethodPoolEntriesRead;
6201      ASTSelectorLookupTrait::data_type Data = *Pos;
6202      if (This->Reader.DeserializationListener)
6203        This->Reader.DeserializationListener->SelectorRead(Data.ID,
6204                                                           This->Sel);
6205
6206      This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6207      This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6208      return true;
6209    }
6210
6211    /// \brief Retrieve the instance methods found by this visitor.
6212    ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6213      return InstanceMethods;
6214    }
6215
6216    /// \brief Retrieve the instance methods found by this visitor.
6217    ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6218      return FactoryMethods;
6219    }
6220  };
6221} } // end namespace clang::serialization
6222
6223/// \brief Add the given set of methods to the method list.
6224static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6225                             ObjCMethodList &List) {
6226  for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6227    S.addMethodToGlobalList(&List, Methods[I]);
6228  }
6229}
6230
6231void ASTReader::ReadMethodPool(Selector Sel) {
6232  // Get the selector generation and update it to the current generation.
6233  unsigned &Generation = SelectorGeneration[Sel];
6234  unsigned PriorGeneration = Generation;
6235  Generation = CurrentGeneration;
6236
6237  // Search for methods defined with this selector.
6238  ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6239  ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6240
6241  if (Visitor.getInstanceMethods().empty() &&
6242      Visitor.getFactoryMethods().empty()) {
6243    ++NumMethodPoolMisses;
6244    return;
6245  }
6246
6247  if (!getSema())
6248    return;
6249
6250  Sema &S = *getSema();
6251  Sema::GlobalMethodPool::iterator Pos
6252    = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6253
6254  addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6255  addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
6256}
6257
6258void ASTReader::ReadKnownNamespaces(
6259                          SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6260  Namespaces.clear();
6261
6262  for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6263    if (NamespaceDecl *Namespace
6264                = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6265      Namespaces.push_back(Namespace);
6266  }
6267}
6268
6269void ASTReader::ReadTentativeDefinitions(
6270                  SmallVectorImpl<VarDecl *> &TentativeDefs) {
6271  for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6272    VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6273    if (Var)
6274      TentativeDefs.push_back(Var);
6275  }
6276  TentativeDefinitions.clear();
6277}
6278
6279void ASTReader::ReadUnusedFileScopedDecls(
6280                               SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6281  for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6282    DeclaratorDecl *D
6283      = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6284    if (D)
6285      Decls.push_back(D);
6286  }
6287  UnusedFileScopedDecls.clear();
6288}
6289
6290void ASTReader::ReadDelegatingConstructors(
6291                                 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6292  for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6293    CXXConstructorDecl *D
6294      = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6295    if (D)
6296      Decls.push_back(D);
6297  }
6298  DelegatingCtorDecls.clear();
6299}
6300
6301void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6302  for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6303    TypedefNameDecl *D
6304      = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6305    if (D)
6306      Decls.push_back(D);
6307  }
6308  ExtVectorDecls.clear();
6309}
6310
6311void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6312  for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6313    CXXRecordDecl *D
6314      = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6315    if (D)
6316      Decls.push_back(D);
6317  }
6318  DynamicClasses.clear();
6319}
6320
6321void
6322ASTReader::ReadLocallyScopedExternalDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6323  for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
6324    NamedDecl *D
6325      = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
6326    if (D)
6327      Decls.push_back(D);
6328  }
6329  LocallyScopedExternalDecls.clear();
6330}
6331
6332void ASTReader::ReadReferencedSelectors(
6333       SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6334  if (ReferencedSelectorsData.empty())
6335    return;
6336
6337  // If there are @selector references added them to its pool. This is for
6338  // implementation of -Wselector.
6339  unsigned int DataSize = ReferencedSelectorsData.size()-1;
6340  unsigned I = 0;
6341  while (I < DataSize) {
6342    Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6343    SourceLocation SelLoc
6344      = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6345    Sels.push_back(std::make_pair(Sel, SelLoc));
6346  }
6347  ReferencedSelectorsData.clear();
6348}
6349
6350void ASTReader::ReadWeakUndeclaredIdentifiers(
6351       SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6352  if (WeakUndeclaredIdentifiers.empty())
6353    return;
6354
6355  for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6356    IdentifierInfo *WeakId
6357      = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6358    IdentifierInfo *AliasId
6359      = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6360    SourceLocation Loc
6361      = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6362    bool Used = WeakUndeclaredIdentifiers[I++];
6363    WeakInfo WI(AliasId, Loc);
6364    WI.setUsed(Used);
6365    WeakIDs.push_back(std::make_pair(WeakId, WI));
6366  }
6367  WeakUndeclaredIdentifiers.clear();
6368}
6369
6370void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6371  for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6372    ExternalVTableUse VT;
6373    VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6374    VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6375    VT.DefinitionRequired = VTableUses[Idx++];
6376    VTables.push_back(VT);
6377  }
6378
6379  VTableUses.clear();
6380}
6381
6382void ASTReader::ReadPendingInstantiations(
6383       SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6384  for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6385    ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6386    SourceLocation Loc
6387      = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6388
6389    Pending.push_back(std::make_pair(D, Loc));
6390  }
6391  PendingInstantiations.clear();
6392}
6393
6394void ASTReader::LoadSelector(Selector Sel) {
6395  // It would be complicated to avoid reading the methods anyway. So don't.
6396  ReadMethodPool(Sel);
6397}
6398
6399void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6400  assert(ID && "Non-zero identifier ID required");
6401  assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6402  IdentifiersLoaded[ID - 1] = II;
6403  if (DeserializationListener)
6404    DeserializationListener->IdentifierRead(ID, II);
6405}
6406
6407/// \brief Set the globally-visible declarations associated with the given
6408/// identifier.
6409///
6410/// If the AST reader is currently in a state where the given declaration IDs
6411/// cannot safely be resolved, they are queued until it is safe to resolve
6412/// them.
6413///
6414/// \param II an IdentifierInfo that refers to one or more globally-visible
6415/// declarations.
6416///
6417/// \param DeclIDs the set of declaration IDs with the name @p II that are
6418/// visible at global scope.
6419///
6420/// \param Nonrecursive should be true to indicate that the caller knows that
6421/// this call is non-recursive, and therefore the globally-visible declarations
6422/// will not be placed onto the pending queue.
6423void
6424ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6425                              const SmallVectorImpl<uint32_t> &DeclIDs,
6426                                   bool Nonrecursive) {
6427  if (NumCurrentElementsDeserializing && !Nonrecursive) {
6428    PendingIdentifierInfos.push_back(PendingIdentifierInfo());
6429    PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
6430    PII.II = II;
6431    PII.DeclIDs.append(DeclIDs.begin(), DeclIDs.end());
6432    return;
6433  }
6434
6435  for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6436    NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6437    if (SemaObj) {
6438      // Introduce this declaration into the translation-unit scope
6439      // and add it to the declaration chain for this identifier, so
6440      // that (unqualified) name lookup will find it.
6441      SemaObj->pushExternalDeclIntoScope(D, II);
6442    } else {
6443      // Queue this declaration so that it will be added to the
6444      // translation unit scope and identifier's declaration chain
6445      // once a Sema object is known.
6446      PreloadedDecls.push_back(D);
6447    }
6448  }
6449}
6450
6451IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
6452  if (ID == 0)
6453    return 0;
6454
6455  if (IdentifiersLoaded.empty()) {
6456    Error("no identifier table in AST file");
6457    return 0;
6458  }
6459
6460  ID -= 1;
6461  if (!IdentifiersLoaded[ID]) {
6462    GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6463    assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6464    ModuleFile *M = I->second;
6465    unsigned Index = ID - M->BaseIdentifierID;
6466    const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6467
6468    // All of the strings in the AST file are preceded by a 16-bit length.
6469    // Extract that 16-bit length to avoid having to execute strlen().
6470    // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6471    //  unsigned integers.  This is important to avoid integer overflow when
6472    //  we cast them to 'unsigned'.
6473    const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6474    unsigned StrLen = (((unsigned) StrLenPtr[0])
6475                       | (((unsigned) StrLenPtr[1]) << 8)) - 1;
6476    IdentifiersLoaded[ID]
6477      = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
6478    if (DeserializationListener)
6479      DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6480  }
6481
6482  return IdentifiersLoaded[ID];
6483}
6484
6485IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6486  return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
6487}
6488
6489IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6490  if (LocalID < NUM_PREDEF_IDENT_IDS)
6491    return LocalID;
6492
6493  ContinuousRangeMap<uint32_t, int, 2>::iterator I
6494    = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6495  assert(I != M.IdentifierRemap.end()
6496         && "Invalid index into identifier index remap");
6497
6498  return LocalID + I->second;
6499}
6500
6501MacroInfo *ASTReader::getMacro(MacroID ID, MacroInfo *Hint) {
6502  if (ID == 0)
6503    return 0;
6504
6505  if (MacrosLoaded.empty()) {
6506    Error("no macro table in AST file");
6507    return 0;
6508  }
6509
6510  ID -= NUM_PREDEF_MACRO_IDS;
6511  if (!MacrosLoaded[ID]) {
6512    GlobalMacroMapType::iterator I
6513      = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
6514    assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
6515    ModuleFile *M = I->second;
6516    unsigned Index = ID - M->BaseMacroID;
6517    ReadMacroRecord(*M, M->MacroOffsets[Index], Hint);
6518  }
6519
6520  return MacrosLoaded[ID];
6521}
6522
6523MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
6524  if (LocalID < NUM_PREDEF_MACRO_IDS)
6525    return LocalID;
6526
6527  ContinuousRangeMap<uint32_t, int, 2>::iterator I
6528    = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
6529  assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
6530
6531  return LocalID + I->second;
6532}
6533
6534serialization::SubmoduleID
6535ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
6536  if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
6537    return LocalID;
6538
6539  ContinuousRangeMap<uint32_t, int, 2>::iterator I
6540    = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
6541  assert(I != M.SubmoduleRemap.end()
6542         && "Invalid index into submodule index remap");
6543
6544  return LocalID + I->second;
6545}
6546
6547Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
6548  if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
6549    assert(GlobalID == 0 && "Unhandled global submodule ID");
6550    return 0;
6551  }
6552
6553  if (GlobalID > SubmodulesLoaded.size()) {
6554    Error("submodule ID out of range in AST file");
6555    return 0;
6556  }
6557
6558  return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
6559}
6560
6561Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
6562  return DecodeSelector(getGlobalSelectorID(M, LocalID));
6563}
6564
6565Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
6566  if (ID == 0)
6567    return Selector();
6568
6569  if (ID > SelectorsLoaded.size()) {
6570    Error("selector ID out of range in AST file");
6571    return Selector();
6572  }
6573
6574  if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
6575    // Load this selector from the selector table.
6576    GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
6577    assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
6578    ModuleFile &M = *I->second;
6579    ASTSelectorLookupTrait Trait(*this, M);
6580    unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
6581    SelectorsLoaded[ID - 1] =
6582      Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
6583    if (DeserializationListener)
6584      DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
6585  }
6586
6587  return SelectorsLoaded[ID - 1];
6588}
6589
6590Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
6591  return DecodeSelector(ID);
6592}
6593
6594uint32_t ASTReader::GetNumExternalSelectors() {
6595  // ID 0 (the null selector) is considered an external selector.
6596  return getTotalNumSelectors() + 1;
6597}
6598
6599serialization::SelectorID
6600ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
6601  if (LocalID < NUM_PREDEF_SELECTOR_IDS)
6602    return LocalID;
6603
6604  ContinuousRangeMap<uint32_t, int, 2>::iterator I
6605    = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
6606  assert(I != M.SelectorRemap.end()
6607         && "Invalid index into selector index remap");
6608
6609  return LocalID + I->second;
6610}
6611
6612DeclarationName
6613ASTReader::ReadDeclarationName(ModuleFile &F,
6614                               const RecordData &Record, unsigned &Idx) {
6615  DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
6616  switch (Kind) {
6617  case DeclarationName::Identifier:
6618    return DeclarationName(GetIdentifierInfo(F, Record, Idx));
6619
6620  case DeclarationName::ObjCZeroArgSelector:
6621  case DeclarationName::ObjCOneArgSelector:
6622  case DeclarationName::ObjCMultiArgSelector:
6623    return DeclarationName(ReadSelector(F, Record, Idx));
6624
6625  case DeclarationName::CXXConstructorName:
6626    return Context.DeclarationNames.getCXXConstructorName(
6627                          Context.getCanonicalType(readType(F, Record, Idx)));
6628
6629  case DeclarationName::CXXDestructorName:
6630    return Context.DeclarationNames.getCXXDestructorName(
6631                          Context.getCanonicalType(readType(F, Record, Idx)));
6632
6633  case DeclarationName::CXXConversionFunctionName:
6634    return Context.DeclarationNames.getCXXConversionFunctionName(
6635                          Context.getCanonicalType(readType(F, Record, Idx)));
6636
6637  case DeclarationName::CXXOperatorName:
6638    return Context.DeclarationNames.getCXXOperatorName(
6639                                       (OverloadedOperatorKind)Record[Idx++]);
6640
6641  case DeclarationName::CXXLiteralOperatorName:
6642    return Context.DeclarationNames.getCXXLiteralOperatorName(
6643                                       GetIdentifierInfo(F, Record, Idx));
6644
6645  case DeclarationName::CXXUsingDirective:
6646    return DeclarationName::getUsingDirectiveName();
6647  }
6648
6649  llvm_unreachable("Invalid NameKind!");
6650}
6651
6652void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
6653                                       DeclarationNameLoc &DNLoc,
6654                                       DeclarationName Name,
6655                                      const RecordData &Record, unsigned &Idx) {
6656  switch (Name.getNameKind()) {
6657  case DeclarationName::CXXConstructorName:
6658  case DeclarationName::CXXDestructorName:
6659  case DeclarationName::CXXConversionFunctionName:
6660    DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
6661    break;
6662
6663  case DeclarationName::CXXOperatorName:
6664    DNLoc.CXXOperatorName.BeginOpNameLoc
6665        = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6666    DNLoc.CXXOperatorName.EndOpNameLoc
6667        = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6668    break;
6669
6670  case DeclarationName::CXXLiteralOperatorName:
6671    DNLoc.CXXLiteralOperatorName.OpNameLoc
6672        = ReadSourceLocation(F, Record, Idx).getRawEncoding();
6673    break;
6674
6675  case DeclarationName::Identifier:
6676  case DeclarationName::ObjCZeroArgSelector:
6677  case DeclarationName::ObjCOneArgSelector:
6678  case DeclarationName::ObjCMultiArgSelector:
6679  case DeclarationName::CXXUsingDirective:
6680    break;
6681  }
6682}
6683
6684void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
6685                                        DeclarationNameInfo &NameInfo,
6686                                      const RecordData &Record, unsigned &Idx) {
6687  NameInfo.setName(ReadDeclarationName(F, Record, Idx));
6688  NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
6689  DeclarationNameLoc DNLoc;
6690  ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
6691  NameInfo.setInfo(DNLoc);
6692}
6693
6694void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
6695                                  const RecordData &Record, unsigned &Idx) {
6696  Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
6697  unsigned NumTPLists = Record[Idx++];
6698  Info.NumTemplParamLists = NumTPLists;
6699  if (NumTPLists) {
6700    Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
6701    for (unsigned i=0; i != NumTPLists; ++i)
6702      Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
6703  }
6704}
6705
6706TemplateName
6707ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
6708                            unsigned &Idx) {
6709  TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
6710  switch (Kind) {
6711  case TemplateName::Template:
6712      return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
6713
6714  case TemplateName::OverloadedTemplate: {
6715    unsigned size = Record[Idx++];
6716    UnresolvedSet<8> Decls;
6717    while (size--)
6718      Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
6719
6720    return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
6721  }
6722
6723  case TemplateName::QualifiedTemplate: {
6724    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6725    bool hasTemplKeyword = Record[Idx++];
6726    TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
6727    return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
6728  }
6729
6730  case TemplateName::DependentTemplate: {
6731    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
6732    if (Record[Idx++])  // isIdentifier
6733      return Context.getDependentTemplateName(NNS,
6734                                               GetIdentifierInfo(F, Record,
6735                                                                 Idx));
6736    return Context.getDependentTemplateName(NNS,
6737                                         (OverloadedOperatorKind)Record[Idx++]);
6738  }
6739
6740  case TemplateName::SubstTemplateTemplateParm: {
6741    TemplateTemplateParmDecl *param
6742      = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6743    if (!param) return TemplateName();
6744    TemplateName replacement = ReadTemplateName(F, Record, Idx);
6745    return Context.getSubstTemplateTemplateParm(param, replacement);
6746  }
6747
6748  case TemplateName::SubstTemplateTemplateParmPack: {
6749    TemplateTemplateParmDecl *Param
6750      = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
6751    if (!Param)
6752      return TemplateName();
6753
6754    TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
6755    if (ArgPack.getKind() != TemplateArgument::Pack)
6756      return TemplateName();
6757
6758    return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
6759  }
6760  }
6761
6762  llvm_unreachable("Unhandled template name kind!");
6763}
6764
6765TemplateArgument
6766ASTReader::ReadTemplateArgument(ModuleFile &F,
6767                                const RecordData &Record, unsigned &Idx) {
6768  TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
6769  switch (Kind) {
6770  case TemplateArgument::Null:
6771    return TemplateArgument();
6772  case TemplateArgument::Type:
6773    return TemplateArgument(readType(F, Record, Idx));
6774  case TemplateArgument::Declaration: {
6775    ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
6776    bool ForReferenceParam = Record[Idx++];
6777    return TemplateArgument(D, ForReferenceParam);
6778  }
6779  case TemplateArgument::NullPtr:
6780    return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
6781  case TemplateArgument::Integral: {
6782    llvm::APSInt Value = ReadAPSInt(Record, Idx);
6783    QualType T = readType(F, Record, Idx);
6784    return TemplateArgument(Context, Value, T);
6785  }
6786  case TemplateArgument::Template:
6787    return TemplateArgument(ReadTemplateName(F, Record, Idx));
6788  case TemplateArgument::TemplateExpansion: {
6789    TemplateName Name = ReadTemplateName(F, Record, Idx);
6790    llvm::Optional<unsigned> NumTemplateExpansions;
6791    if (unsigned NumExpansions = Record[Idx++])
6792      NumTemplateExpansions = NumExpansions - 1;
6793    return TemplateArgument(Name, NumTemplateExpansions);
6794  }
6795  case TemplateArgument::Expression:
6796    return TemplateArgument(ReadExpr(F));
6797  case TemplateArgument::Pack: {
6798    unsigned NumArgs = Record[Idx++];
6799    TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
6800    for (unsigned I = 0; I != NumArgs; ++I)
6801      Args[I] = ReadTemplateArgument(F, Record, Idx);
6802    return TemplateArgument(Args, NumArgs);
6803  }
6804  }
6805
6806  llvm_unreachable("Unhandled template argument kind!");
6807}
6808
6809TemplateParameterList *
6810ASTReader::ReadTemplateParameterList(ModuleFile &F,
6811                                     const RecordData &Record, unsigned &Idx) {
6812  SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
6813  SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
6814  SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
6815
6816  unsigned NumParams = Record[Idx++];
6817  SmallVector<NamedDecl *, 16> Params;
6818  Params.reserve(NumParams);
6819  while (NumParams--)
6820    Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
6821
6822  TemplateParameterList* TemplateParams =
6823    TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
6824                                  Params.data(), Params.size(), RAngleLoc);
6825  return TemplateParams;
6826}
6827
6828void
6829ASTReader::
6830ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
6831                         ModuleFile &F, const RecordData &Record,
6832                         unsigned &Idx) {
6833  unsigned NumTemplateArgs = Record[Idx++];
6834  TemplArgs.reserve(NumTemplateArgs);
6835  while (NumTemplateArgs--)
6836    TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
6837}
6838
6839/// \brief Read a UnresolvedSet structure.
6840void ASTReader::ReadUnresolvedSet(ModuleFile &F, UnresolvedSetImpl &Set,
6841                                  const RecordData &Record, unsigned &Idx) {
6842  unsigned NumDecls = Record[Idx++];
6843  while (NumDecls--) {
6844    NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
6845    AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
6846    Set.addDecl(D, AS);
6847  }
6848}
6849
6850CXXBaseSpecifier
6851ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
6852                                const RecordData &Record, unsigned &Idx) {
6853  bool isVirtual = static_cast<bool>(Record[Idx++]);
6854  bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
6855  AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
6856  bool inheritConstructors = static_cast<bool>(Record[Idx++]);
6857  TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
6858  SourceRange Range = ReadSourceRange(F, Record, Idx);
6859  SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
6860  CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
6861                          EllipsisLoc);
6862  Result.setInheritConstructors(inheritConstructors);
6863  return Result;
6864}
6865
6866std::pair<CXXCtorInitializer **, unsigned>
6867ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
6868                                   unsigned &Idx) {
6869  CXXCtorInitializer **CtorInitializers = 0;
6870  unsigned NumInitializers = Record[Idx++];
6871  if (NumInitializers) {
6872    CtorInitializers
6873        = new (Context) CXXCtorInitializer*[NumInitializers];
6874    for (unsigned i=0; i != NumInitializers; ++i) {
6875      TypeSourceInfo *TInfo = 0;
6876      bool IsBaseVirtual = false;
6877      FieldDecl *Member = 0;
6878      IndirectFieldDecl *IndirectMember = 0;
6879
6880      CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
6881      switch (Type) {
6882      case CTOR_INITIALIZER_BASE:
6883        TInfo = GetTypeSourceInfo(F, Record, Idx);
6884        IsBaseVirtual = Record[Idx++];
6885        break;
6886
6887      case CTOR_INITIALIZER_DELEGATING:
6888        TInfo = GetTypeSourceInfo(F, Record, Idx);
6889        break;
6890
6891       case CTOR_INITIALIZER_MEMBER:
6892        Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
6893        break;
6894
6895       case CTOR_INITIALIZER_INDIRECT_MEMBER:
6896        IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
6897        break;
6898      }
6899
6900      SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
6901      Expr *Init = ReadExpr(F);
6902      SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
6903      SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
6904      bool IsWritten = Record[Idx++];
6905      unsigned SourceOrderOrNumArrayIndices;
6906      SmallVector<VarDecl *, 8> Indices;
6907      if (IsWritten) {
6908        SourceOrderOrNumArrayIndices = Record[Idx++];
6909      } else {
6910        SourceOrderOrNumArrayIndices = Record[Idx++];
6911        Indices.reserve(SourceOrderOrNumArrayIndices);
6912        for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
6913          Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
6914      }
6915
6916      CXXCtorInitializer *BOMInit;
6917      if (Type == CTOR_INITIALIZER_BASE) {
6918        BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
6919                                             LParenLoc, Init, RParenLoc,
6920                                             MemberOrEllipsisLoc);
6921      } else if (Type == CTOR_INITIALIZER_DELEGATING) {
6922        BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
6923                                                   Init, RParenLoc);
6924      } else if (IsWritten) {
6925        if (Member)
6926          BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
6927                                               LParenLoc, Init, RParenLoc);
6928        else
6929          BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
6930                                               MemberOrEllipsisLoc, LParenLoc,
6931                                               Init, RParenLoc);
6932      } else {
6933        BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
6934                                             LParenLoc, Init, RParenLoc,
6935                                             Indices.data(), Indices.size());
6936      }
6937
6938      if (IsWritten)
6939        BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
6940      CtorInitializers[i] = BOMInit;
6941    }
6942  }
6943
6944  return std::make_pair(CtorInitializers, NumInitializers);
6945}
6946
6947NestedNameSpecifier *
6948ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
6949                                   const RecordData &Record, unsigned &Idx) {
6950  unsigned N = Record[Idx++];
6951  NestedNameSpecifier *NNS = 0, *Prev = 0;
6952  for (unsigned I = 0; I != N; ++I) {
6953    NestedNameSpecifier::SpecifierKind Kind
6954      = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
6955    switch (Kind) {
6956    case NestedNameSpecifier::Identifier: {
6957      IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
6958      NNS = NestedNameSpecifier::Create(Context, Prev, II);
6959      break;
6960    }
6961
6962    case NestedNameSpecifier::Namespace: {
6963      NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
6964      NNS = NestedNameSpecifier::Create(Context, Prev, NS);
6965      break;
6966    }
6967
6968    case NestedNameSpecifier::NamespaceAlias: {
6969      NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
6970      NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
6971      break;
6972    }
6973
6974    case NestedNameSpecifier::TypeSpec:
6975    case NestedNameSpecifier::TypeSpecWithTemplate: {
6976      const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
6977      if (!T)
6978        return 0;
6979
6980      bool Template = Record[Idx++];
6981      NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
6982      break;
6983    }
6984
6985    case NestedNameSpecifier::Global: {
6986      NNS = NestedNameSpecifier::GlobalSpecifier(Context);
6987      // No associated value, and there can't be a prefix.
6988      break;
6989    }
6990    }
6991    Prev = NNS;
6992  }
6993  return NNS;
6994}
6995
6996NestedNameSpecifierLoc
6997ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
6998                                      unsigned &Idx) {
6999  unsigned N = Record[Idx++];
7000  NestedNameSpecifierLocBuilder Builder;
7001  for (unsigned I = 0; I != N; ++I) {
7002    NestedNameSpecifier::SpecifierKind Kind
7003      = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7004    switch (Kind) {
7005    case NestedNameSpecifier::Identifier: {
7006      IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7007      SourceRange Range = ReadSourceRange(F, Record, Idx);
7008      Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7009      break;
7010    }
7011
7012    case NestedNameSpecifier::Namespace: {
7013      NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7014      SourceRange Range = ReadSourceRange(F, Record, Idx);
7015      Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7016      break;
7017    }
7018
7019    case NestedNameSpecifier::NamespaceAlias: {
7020      NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7021      SourceRange Range = ReadSourceRange(F, Record, Idx);
7022      Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7023      break;
7024    }
7025
7026    case NestedNameSpecifier::TypeSpec:
7027    case NestedNameSpecifier::TypeSpecWithTemplate: {
7028      bool Template = Record[Idx++];
7029      TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7030      if (!T)
7031        return NestedNameSpecifierLoc();
7032      SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7033
7034      // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7035      Builder.Extend(Context,
7036                     Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7037                     T->getTypeLoc(), ColonColonLoc);
7038      break;
7039    }
7040
7041    case NestedNameSpecifier::Global: {
7042      SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7043      Builder.MakeGlobal(Context, ColonColonLoc);
7044      break;
7045    }
7046    }
7047  }
7048
7049  return Builder.getWithLocInContext(Context);
7050}
7051
7052SourceRange
7053ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7054                           unsigned &Idx) {
7055  SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7056  SourceLocation end = ReadSourceLocation(F, Record, Idx);
7057  return SourceRange(beg, end);
7058}
7059
7060/// \brief Read an integral value
7061llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7062  unsigned BitWidth = Record[Idx++];
7063  unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7064  llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7065  Idx += NumWords;
7066  return Result;
7067}
7068
7069/// \brief Read a signed integral value
7070llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7071  bool isUnsigned = Record[Idx++];
7072  return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7073}
7074
7075/// \brief Read a floating-point value
7076llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
7077  return llvm::APFloat(ReadAPInt(Record, Idx));
7078}
7079
7080// \brief Read a string
7081std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7082  unsigned Len = Record[Idx++];
7083  std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7084  Idx += Len;
7085  return Result;
7086}
7087
7088VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7089                                         unsigned &Idx) {
7090  unsigned Major = Record[Idx++];
7091  unsigned Minor = Record[Idx++];
7092  unsigned Subminor = Record[Idx++];
7093  if (Minor == 0)
7094    return VersionTuple(Major);
7095  if (Subminor == 0)
7096    return VersionTuple(Major, Minor - 1);
7097  return VersionTuple(Major, Minor - 1, Subminor - 1);
7098}
7099
7100CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7101                                          const RecordData &Record,
7102                                          unsigned &Idx) {
7103  CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7104  return CXXTemporary::Create(Context, Decl);
7105}
7106
7107DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
7108  return Diag(SourceLocation(), DiagID);
7109}
7110
7111DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7112  return Diags.Report(Loc, DiagID);
7113}
7114
7115/// \brief Retrieve the identifier table associated with the
7116/// preprocessor.
7117IdentifierTable &ASTReader::getIdentifierTable() {
7118  return PP.getIdentifierTable();
7119}
7120
7121/// \brief Record that the given ID maps to the given switch-case
7122/// statement.
7123void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7124  assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7125         "Already have a SwitchCase with this ID");
7126  (*CurrSwitchCaseStmts)[ID] = SC;
7127}
7128
7129/// \brief Retrieve the switch-case statement with the given ID.
7130SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7131  assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7132  return (*CurrSwitchCaseStmts)[ID];
7133}
7134
7135void ASTReader::ClearSwitchCaseIDs() {
7136  CurrSwitchCaseStmts->clear();
7137}
7138
7139void ASTReader::ReadComments() {
7140  std::vector<RawComment *> Comments;
7141  for (SmallVectorImpl<std::pair<llvm::BitstreamCursor,
7142                                 serialization::ModuleFile *> >::iterator
7143       I = CommentsCursors.begin(),
7144       E = CommentsCursors.end();
7145       I != E; ++I) {
7146    llvm::BitstreamCursor &Cursor = I->first;
7147    serialization::ModuleFile &F = *I->second;
7148    SavedStreamPosition SavedPosition(Cursor);
7149
7150    RecordData Record;
7151    while (true) {
7152      unsigned Code = Cursor.ReadCode();
7153      if (Code == llvm::bitc::END_BLOCK)
7154        break;
7155
7156      if (Code == llvm::bitc::ENTER_SUBBLOCK) {
7157        // No known subblocks, always skip them.
7158        Cursor.ReadSubBlockID();
7159        if (Cursor.SkipBlock()) {
7160          Error("malformed block record in AST file");
7161          return;
7162        }
7163        continue;
7164      }
7165
7166      if (Code == llvm::bitc::DEFINE_ABBREV) {
7167        Cursor.ReadAbbrevRecord();
7168        continue;
7169      }
7170
7171      // Read a record.
7172      Record.clear();
7173      switch ((CommentRecordTypes) Cursor.ReadRecord(Code, Record)) {
7174      case COMMENTS_RAW_COMMENT: {
7175        unsigned Idx = 0;
7176        SourceRange SR = ReadSourceRange(F, Record, Idx);
7177        RawComment::CommentKind Kind =
7178            (RawComment::CommentKind) Record[Idx++];
7179        bool IsTrailingComment = Record[Idx++];
7180        bool IsAlmostTrailingComment = Record[Idx++];
7181        Comments.push_back(new (Context) RawComment(SR, Kind,
7182                                                    IsTrailingComment,
7183                                                    IsAlmostTrailingComment));
7184        break;
7185      }
7186      }
7187    }
7188  }
7189  Context.Comments.addCommentsToFront(Comments);
7190}
7191
7192void ASTReader::finishPendingActions() {
7193  while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
7194         !PendingMacroIDs.empty()) {
7195    // If any identifiers with corresponding top-level declarations have
7196    // been loaded, load those declarations now.
7197    while (!PendingIdentifierInfos.empty()) {
7198      SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
7199                              PendingIdentifierInfos.front().DeclIDs, true);
7200      PendingIdentifierInfos.pop_front();
7201    }
7202
7203    // Load pending declaration chains.
7204    for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7205      loadPendingDeclChain(PendingDeclChains[I]);
7206      PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7207    }
7208    PendingDeclChains.clear();
7209
7210    // Load any pending macro definitions.
7211    for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
7212      // FIXME: std::move here
7213      SmallVector<MacroID, 2> GlobalIDs = PendingMacroIDs.begin()[I].second;
7214      MacroInfo *Hint = 0;
7215      for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx !=  NumIDs;
7216           ++IDIdx) {
7217        Hint = getMacro(GlobalIDs[IDIdx], Hint);
7218      }
7219    }
7220    PendingMacroIDs.clear();
7221  }
7222
7223  // If we deserialized any C++ or Objective-C class definitions, any
7224  // Objective-C protocol definitions, or any redeclarable templates, make sure
7225  // that all redeclarations point to the definitions. Note that this can only
7226  // happen now, after the redeclaration chains have been fully wired.
7227  for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7228                                           DEnd = PendingDefinitions.end();
7229       D != DEnd; ++D) {
7230    if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7231      if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7232        // Make sure that the TagType points at the definition.
7233        const_cast<TagType*>(TagT)->decl = TD;
7234      }
7235
7236      if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(*D)) {
7237        for (CXXRecordDecl::redecl_iterator R = RD->redecls_begin(),
7238                                         REnd = RD->redecls_end();
7239             R != REnd; ++R)
7240          cast<CXXRecordDecl>(*R)->DefinitionData = RD->DefinitionData;
7241
7242      }
7243
7244      continue;
7245    }
7246
7247    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
7248      // Make sure that the ObjCInterfaceType points at the definition.
7249      const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7250        ->Decl = ID;
7251
7252      for (ObjCInterfaceDecl::redecl_iterator R = ID->redecls_begin(),
7253                                           REnd = ID->redecls_end();
7254           R != REnd; ++R)
7255        R->Data = ID->Data;
7256
7257      continue;
7258    }
7259
7260    if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7261      for (ObjCProtocolDecl::redecl_iterator R = PD->redecls_begin(),
7262                                          REnd = PD->redecls_end();
7263           R != REnd; ++R)
7264        R->Data = PD->Data;
7265
7266      continue;
7267    }
7268
7269    RedeclarableTemplateDecl *RTD
7270      = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7271    for (RedeclarableTemplateDecl::redecl_iterator R = RTD->redecls_begin(),
7272                                                REnd = RTD->redecls_end();
7273         R != REnd; ++R)
7274      R->Common = RTD->Common;
7275  }
7276  PendingDefinitions.clear();
7277
7278  // Load the bodies of any functions or methods we've encountered. We do
7279  // this now (delayed) so that we can be sure that the declaration chains
7280  // have been fully wired up.
7281  for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7282                               PBEnd = PendingBodies.end();
7283       PB != PBEnd; ++PB) {
7284    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7285      // FIXME: Check for =delete/=default?
7286      // FIXME: Complain about ODR violations here?
7287      if (!getContext().getLangOpts().Modules || !FD->hasBody())
7288        FD->setLazyBody(PB->second);
7289      continue;
7290    }
7291
7292    ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7293    if (!getContext().getLangOpts().Modules || !MD->hasBody())
7294      MD->setLazyBody(PB->second);
7295  }
7296  PendingBodies.clear();
7297}
7298
7299void ASTReader::FinishedDeserializing() {
7300  assert(NumCurrentElementsDeserializing &&
7301         "FinishedDeserializing not paired with StartedDeserializing");
7302  if (NumCurrentElementsDeserializing == 1) {
7303    // We decrease NumCurrentElementsDeserializing only after pending actions
7304    // are finished, to avoid recursively re-calling finishPendingActions().
7305    finishPendingActions();
7306  }
7307  --NumCurrentElementsDeserializing;
7308
7309  if (NumCurrentElementsDeserializing == 0 &&
7310      Consumer && !PassingDeclsToConsumer) {
7311    // Guard variable to avoid recursively redoing the process of passing
7312    // decls to consumer.
7313    SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7314                                                     true);
7315
7316    while (!InterestingDecls.empty()) {
7317      // We are not in recursive loading, so it's safe to pass the "interesting"
7318      // decls to the consumer.
7319      Decl *D = InterestingDecls.front();
7320      InterestingDecls.pop_front();
7321      PassInterestingDeclToConsumer(D);
7322    }
7323  }
7324}
7325
7326ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7327                     StringRef isysroot, bool DisableValidation,
7328                     bool DisableStatCache, bool AllowASTWithCompilerErrors)
7329  : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7330    SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7331    Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7332    Consumer(0), ModuleMgr(PP.getFileManager()),
7333    isysroot(isysroot), DisableValidation(DisableValidation),
7334    DisableStatCache(DisableStatCache),
7335    AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
7336    CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7337    NumStatHits(0), NumStatMisses(0),
7338    NumSLocEntriesRead(0), TotalNumSLocEntries(0),
7339    NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7340    TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
7341    NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
7342    NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
7343    NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7344    TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
7345    PassingDeclsToConsumer(false),
7346    NumCXXBaseSpecifiersLoaded(0)
7347{
7348  SourceMgr.setExternalSLocEntrySource(this);
7349}
7350
7351ASTReader::~ASTReader() {
7352  for (DeclContextVisibleUpdatesPending::iterator
7353           I = PendingVisibleUpdates.begin(),
7354           E = PendingVisibleUpdates.end();
7355       I != E; ++I) {
7356    for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7357                                             F = I->second.end();
7358         J != F; ++J)
7359      delete J->first;
7360  }
7361}
7362