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