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