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