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