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