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