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