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